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 int64 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 int64 1 67k ⌀ | 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 int64 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 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
470d54522a5ff339dddad5538a5beacd850ebd07 | 1,552 | cpp | C++ | graphDataStructuresAndAlgorithms/wordLatterII.cpp | archit-1997/InterviewB | 6f5655ce0c9c8dd1b2433588f47da5aa7f5860d7 | [
"MIT"
] | 1 | 2021-01-27T16:37:38.000Z | 2021-01-27T16:37:38.000Z | graphDataStructuresAndAlgorithms/wordLatterII.cpp | archit-1997/InterviewBit | 6f5655ce0c9c8dd1b2433588f47da5aa7f5860d7 | [
"MIT"
] | null | null | null | graphDataStructuresAndAlgorithms/wordLatterII.cpp | archit-1997/InterviewBit | 6f5655ce0c9c8dd1b2433588f47da5aa7f5860d7 | [
"MIT"
] | null | null | null | vector<vector<string>> res;
int nd, minL;
string en;
bool isAdj(string a, string b) {
int n = a.length();
int cnt = 0;
for (int i = 0; i < n; i++) {
if (a[i] != b[i])
cnt++;
if (cnt > 1)
return false;
}
return cnt == 1 ? true : false;
}
void dfs(vector<string> &dict, vector<string> &temp, bool vis[], int len) {
if (len > minL)
return;
if (temp[len - 1] == en) {
if (minL > len) {
minL = len;
res.clear();
}
res.push_back(temp);
return;
}
string s = temp[len - 1];
for (int i = 0; i < nd; i++) {
if (vis[i] == false && isAdj(s, dict[i])) {
vis[i] = true;
temp.push_back(dict[i]);
dfs(dict, temp, vis, len + 1);
temp.pop_back();
vis[i] = false;
}
}
}
vector<vector<string>> Solution::findLadders(string start, string end,
vector<string> &dict) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for
// more details
res.clear();
dict.push_back(end);
unordered_set<string> st;
for (auto x : dict)
st.insert(x);
dict.assign(st.begin(), st.end());
sort(dict.begin(), dict.end());
nd = dict.size();
minL = INT_MAX;
en = end;
vector<string> temp;
bool vis[nd];
memset(vis, false, sizeof(vis));
temp.push_back(start);
dfs(dict, temp, vis, 1);
return res;
}
| 20.155844 | 78 | 0.556057 | archit-1997 |
470d83ac1637399f02fd02afdf04312d546e0273 | 12,015 | cc | C++ | src/jtocconversion.cc | yamii/node-bacnet | bfe63ff626d7bb02bebfefd301307952fcbd4ee0 | [
"MIT"
] | null | null | null | src/jtocconversion.cc | yamii/node-bacnet | bfe63ff626d7bb02bebfefd301307952fcbd4ee0 | [
"MIT"
] | null | null | null | src/jtocconversion.cc | yamii/node-bacnet | bfe63ff626d7bb02bebfefd301307952fcbd4ee0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <v8.h>
#include <node.h>
#include <nan.h>
#include "address.h"
#include "datalink.h"
#include "bacapp.h"
#include "bactext.h"
using v8::Local;
using v8::Value;
using v8::Object;
using v8::Int32;
using v8::Uint32;
using v8::String;
using Nan::MaybeLocal;
using Nan::New;
uint32_t getUint32Default(Local<Object> target, std::string key, uint32_t defalt) {
Local<String> lkey = New(key).ToLocalChecked();
Local<Value> ldefault = New(defalt);
Local<Value> lvalue = Nan::Get(target, lkey).FromMaybe(ldefault);
return lvalue->ToUint32()->Value();
}
std::string extractString(Local<String> jsString) {
Nan::Utf8String lstring(jsString);
return *lstring;
}
std::string getStringOrEmpty(Local<Object> target, std::string key) {
Local<String> lkey = New(key).ToLocalChecked();
MaybeLocal<Value> mvalue = Nan::Get(target, lkey);
if (mvalue.IsEmpty() || mvalue.ToLocalChecked()->IsUndefined()) {
return "";
} else {
return extractString(mvalue.ToLocalChecked()->ToString());
}
}
// Currently converts an address string ie '123.123.123.123:456' to a bacnet address
// Non-strings create the broadcast address
// TODO : accept objects which specify the additional address properties - for which partial logic exists below
BACNET_ADDRESS bacnetAddressToC(Local<Value> addressValue) {
BACNET_ADDRESS dest = {};
if (addressValue->IsString()) { // address object parameter
BACNET_MAC_ADDRESS mac = {};
BACNET_MAC_ADDRESS adr = {};
long dnet = -1;
Nan::Utf8String address(addressValue.As<v8::String>());
address_mac_from_ascii(&mac, *address);
// if (strcmp(argv[argi], "--dnet") == 0) {
// if (++argi < argc) {
// dnet = strtol(argv[argi], NULL, 0);
// if ((dnet >= 0) && (dnet <= BACNET_BROADCAST_NETWORK)) {
// global_broadcast = false;
// }
// }
// }
// if (strcmp(argv[argi], "--dadr") == 0) {
// if (++argi < argc) {
// if (address_mac_from_ascii(&adr, argv[argi])) {
// global_broadcast = false;
// }
// }
// }
if (adr.len && mac.len) {
memcpy(&dest.mac[0], &mac.adr[0], mac.len);
dest.mac_len = mac.len;
memcpy(&dest.adr[0], &adr.adr[0], adr.len);
dest.len = adr.len;
if ((dnet >= 0) && (dnet <= BACNET_BROADCAST_NETWORK)) {
dest.net = dnet;
} else {
dest.net = BACNET_BROADCAST_NETWORK;
}
} else if (mac.len) {
memcpy(&dest.mac[0], &mac.adr[0], mac.len);
dest.mac_len = mac.len;
dest.len = 0;
if ((dnet >= 0) && (dnet <= BACNET_BROADCAST_NETWORK)) {
dest.net = dnet;
} else {
dest.net = 0;
}
} else {
if ((dnet >= 0) && (dnet <= BACNET_BROADCAST_NETWORK)) {
dest.net = dnet;
} else {
dest.net = BACNET_BROADCAST_NETWORK;
}
dest.mac_len = 0;
dest.len = 0;
}
} else {
datalink_get_broadcast_address(&dest);
}
return dest;
}
// For enums we'll need to know the context - ie properties and stuff
// This shouldn't be called for arrays as we dont know whether the return value is an array
uint8_t inferBacnetType(Local<Value> jvalue) {
if (jvalue->IsNull()) {
return BACNET_APPLICATION_TAG_NULL;
} else if (jvalue->IsBoolean()) {
return BACNET_APPLICATION_TAG_BOOLEAN;
} else if (jvalue->IsString()) {
return BACNET_APPLICATION_TAG_CHARACTER_STRING;
} else if (node::Buffer::HasInstance(jvalue)) {
return BACNET_APPLICATION_TAG_OCTET_STRING;
} else if (jvalue->IsUint32()) { // the 4 number domains have overlap, for this inference we're using unsigned int, signed int, double as the precedence
return BACNET_APPLICATION_TAG_UNSIGNED_INT;
} else if (jvalue->IsInt32()) {
return BACNET_APPLICATION_TAG_SIGNED_INT;
} else if (jvalue->IsNumber()) {
return BACNET_APPLICATION_TAG_REAL; // With my test device a double was an invalid type - it seems that real is more common
} else if (jvalue->IsObject()) {
Local<Object> jobject = jvalue->ToObject();
if (Nan::Has(jobject, Nan::New("year").ToLocalChecked()).FromMaybe(false)) {
return BACNET_APPLICATION_TAG_DATE;
} else if (Nan::Has(jobject, Nan::New("hour").ToLocalChecked()).FromMaybe(false)) {
return BACNET_APPLICATION_TAG_TIME;
} else if (Nan::Has(jobject, Nan::New("instance").ToLocalChecked()).FromMaybe(false)) {
return BACNET_APPLICATION_TAG_OBJECT_ID;
} else {
return 255; // Error : unsupported object type (array, object, ...)
}
} else {
return 255; // Error : unsupported primitive (symbol, ...)
}
}
int bacnetOctetStringToC(BACNET_OCTET_STRING * cvalue, Local<Value> jvalue) {
Local<Object> bjvalue = Nan::To<Object>(jvalue).ToLocalChecked();
size_t bufferLength = node::Buffer::Length(bjvalue);
if (bufferLength < MAX_OCTET_STRING_BYTES) {
cvalue->length = bufferLength;
memcpy(node::Buffer::Data(bjvalue), cvalue->value, bufferLength);
return 0;
} else {
return 2; // Error: Too large
}
}
int bacnetCharacterStringToC(BACNET_CHARACTER_STRING * cvalue, Local<Value> jvalue) {
Local<String> sjvalue = Nan::To<String>(jvalue).ToLocalChecked();
if (sjvalue->Utf8Length() < MAX_CHARACTER_STRING_BYTES) {
cvalue->length = sjvalue->Utf8Length();
cvalue->encoding = CHARACTER_UTF8;
sjvalue->WriteUtf8(cvalue->value);
return 0;
} else {
return 2; // Error: Too large
}
}
int bacnetBitStringToC(BACNET_BIT_STRING * cvalue, Local<Value> jvalue) {
Local<Object> bjvalue = Nan::To<Object>(jvalue).ToLocalChecked();
size_t bufferLength = node::Buffer::Length(bjvalue);
if (bufferLength < MAX_BITSTRING_BYTES) {
cvalue->bits_used = bufferLength * 8;
memcpy(node::Buffer::Data(bjvalue), cvalue->value, bufferLength);
return 0;
} else {
return 2; // Error: Too large
}
}
int bacnetDateToC(BACNET_DATE * cvalue, Local<Value> jvalue) {
Local<Object> jobject = Nan::To<Object>(jvalue).ToLocalChecked();
cvalue->year = Nan::To<uint32_t>(Nan::Get(jobject, Nan::New("year").ToLocalChecked()).ToLocalChecked()).FromJust();
cvalue->month = Nan::To<uint32_t>(Nan::Get(jobject, Nan::New("month").ToLocalChecked()).ToLocalChecked()).FromJust();
cvalue->day = Nan::To<uint32_t>(Nan::Get(jobject, Nan::New("day").ToLocalChecked()).ToLocalChecked()).FromJust();
std::string weekdaystring = getStringOrEmpty(jobject, "weekday");
unsigned int wday;
if (bactext_days_of_week_index(weekdaystring.c_str(), &wday)) {
cvalue->wday = wday + 1; // BACnet has 2 different enumeration schemes for weekdays, oe starting Monday=1 - that's the one we use
return 0;
} else {
return 3;
}
}
int bacnetTimeToC(BACNET_TIME * cvalue, Local<Value> jvalue) {
Local<Object> jobject = Nan::To<Object>(jvalue).ToLocalChecked();
cvalue->hour = Nan::To<uint32_t>(Nan::Get(jobject, Nan::New("hour").ToLocalChecked()).ToLocalChecked()).FromJust();
cvalue->min = Nan::To<uint32_t>(Nan::Get(jobject, Nan::New("min").ToLocalChecked()).ToLocalChecked()).FromJust();
cvalue->sec = Nan::To<uint32_t>(Nan::Get(jobject, Nan::New("sec").ToLocalChecked()).ToLocalChecked()).FromJust();
cvalue->hundredths = Nan::To<uint32_t>(Nan::Get(jobject, Nan::New("hundredths").ToLocalChecked()).ToLocalChecked()).FromJust();
return 0;
}
int bacnetObjectHandleToC(BACNET_OBJECT_ID * cvalue, Local<Value> jvalue) {
Local<Object> jobject = Nan::To<Object>(jvalue).ToLocalChecked();
std::string objectTypeName = getStringOrEmpty(jobject, "type");
unsigned objectTypeIndex;
if (bactext_object_type_index(objectTypeName.c_str(), &objectTypeIndex)) {
cvalue->type = objectTypeIndex;
cvalue->instance = Nan::To<uint32_t>(Nan::Get(jobject, Nan::New("instance").ToLocalChecked()).ToLocalChecked()).FromJust();
return 0;
} else {
return 3;
}
}
// For enums we'll need to know the context - ie properties and stuff
// This shouldn't be called for arrays as we dont know whether the return value is an array
// TODO check types etc
int bacnetAppValueToC(BACNET_APPLICATION_DATA_VALUE * cvalue, Local<Value> jvalue, BACNET_APPLICATION_TAG tag) {
cvalue->context_specific = false;
cvalue->context_tag = 0;
cvalue->next = 0;
cvalue->tag = tag;
switch (tag) {
case BACNET_APPLICATION_TAG_NULL:
return 0;
case BACNET_APPLICATION_TAG_BOOLEAN:
cvalue->type.Boolean = Nan::To<bool>(jvalue).FromJust();
return 0;
case BACNET_APPLICATION_TAG_UNSIGNED_INT:
cvalue->type.Unsigned_Int = Nan::To<uint32_t>(jvalue).FromJust();
return 0;
case BACNET_APPLICATION_TAG_SIGNED_INT:
cvalue->type.Signed_Int = Nan::To<int32_t>(jvalue).FromJust();
return 0;
case BACNET_APPLICATION_TAG_REAL:
cvalue->type.Real = Nan::To<double>(jvalue).FromJust();
return 0;
case BACNET_APPLICATION_TAG_DOUBLE:
cvalue->type.Double = Nan::To<double>(jvalue).FromJust();
return 0;
case BACNET_APPLICATION_TAG_OCTET_STRING:
return bacnetOctetStringToC(&cvalue->type.Octet_String, jvalue);
case BACNET_APPLICATION_TAG_CHARACTER_STRING:
return bacnetCharacterStringToC(&cvalue->type.Character_String, jvalue);
case BACNET_APPLICATION_TAG_BIT_STRING:
return bacnetBitStringToC(&cvalue->type.Bit_String, jvalue);
case BACNET_APPLICATION_TAG_ENUMERATED:
cvalue->type.Enumerated = Nan::To<uint32_t>(jvalue).FromJust(); // without the context of the property id the enumeration value is just a number
return 0;
case BACNET_APPLICATION_TAG_DATE:
return bacnetDateToC(&cvalue->type.Date, jvalue);
case BACNET_APPLICATION_TAG_TIME:
return bacnetTimeToC(&cvalue->type.Time, jvalue);
case BACNET_APPLICATION_TAG_OBJECT_ID:
return bacnetObjectHandleToC(&cvalue->type.Object_Id, jvalue);
default:
std::cout << "ERROR: value tag (" << +cvalue->tag << ") not converted to js '" << bactext_application_tag_name(cvalue->tag) << "'" << std::endl;
return 1;
}
}
// converts a value representing a bacnet object type to its enum value
const char * objectTypeToC(Local<Value> type, unsigned * index) {
if (type->IsString()) {
if (bactext_object_type_index(extractString(type.As<v8::String>()).c_str(), index)) {
return 0;
} else {
return "Object type string not valid";
}
} else if (type->IsUint32()) {
const char * name = bactext_object_type_name(type->ToUint32()->Value());
bactext_object_type_index(name, index);
return 0;
} else {
return "Object type must be either a string or unsigned int";
}
}
// TODO : provide enums
// converts a value representing a bacnet value application tag to its enum value
// returns zero on success or an error string
const char * applicationTagToC(Local<Value> type, unsigned * index) {
if (type->IsString()) {
if (bactext_application_tag_index(extractString(type.As<v8::String>()).c_str(), index)) {
return 0;
} else {
return "Application tag string not valid";
}
} else if (type->IsUint32()) {
const char * name = bactext_application_tag_name(type->ToUint32()->Value());
bactext_application_tag_index(name, index);
return 0;
} else {
return "Application tag must be either a string or unsigned int";
}
}
| 41.006826 | 163 | 0.635456 | yamii |
470ecca09a38e5e9808703253e7803ea0723bee0 | 2,424 | cpp | C++ | picam/libs/client/src/picam_client.cpp | avribacki/neato-pi | dd415f0f6ab82492468fedcafc85f18277fc7c06 | [
"MIT"
] | null | null | null | picam/libs/client/src/picam_client.cpp | avribacki/neato-pi | dd415f0f6ab82492468fedcafc85f18277fc7c06 | [
"MIT"
] | null | null | null | picam/libs/client/src/picam_client.cpp | avribacki/neato-pi | dd415f0f6ab82492468fedcafc85f18277fc7c06 | [
"MIT"
] | null | null | null | #include "picam_api.h"
#include "jaw_client.hpp"
#include "picam_protocol.hpp"
using namespace Jaw;
using namespace PiCam;
/*************************************************************************************************/
using PiCamClient = Client<Command>;
/*************************************************************************************************/
// Maybe we want different times for each operation?
static std::chrono::seconds kTimeout = std::chrono::seconds(3);
/*************************************************************************************************/
int picam_create(picam_camera_t* camera, const picam_config_t* config, const char* address)
{
if (!config) {
return static_cast<int>(std::errc::invalid_argument);
}
return PiCamClient::create(camera, Command::CREATE, kTimeout, address, std::forward_as_tuple(*config));
}
/*************************************************************************************************/
int picam_destroy(picam_camera_t camera)
{
return PiCamClient::destroy(camera, Command::DESTROY, kTimeout);
}
/*************************************************************************************************/
int picam_callback_set(picam_camera_t camera, void *user_data, picam_callback_t callback)
{
return PiCamClient::set_callback(camera, Command::CALLBACK_SET, kTimeout,
[user_data, callback](InputBuffer message) {
picam_image_t image;
read(message, image);
callback(user_data, &image);
});
}
/*************************************************************************************************/
int picam_params_get(picam_camera_t camera, picam_params_t *params)
{
if (!params) {
return static_cast<int>(std::errc::invalid_argument);
}
return PiCamClient::request(camera, Command::PARAMETERS_GET, kTimeout, *params);
}
/*************************************************************************************************/
int picam_params_set(picam_camera_t camera, picam_params_t* params)
{
if (!params) {
return static_cast<int>(std::errc::invalid_argument);
}
return PiCamClient::request(camera, Command::PARAMETERS_SET, kTimeout, std::forward_as_tuple(*params));
}
/*************************************************************************************************/
| 35.130435 | 108 | 0.458333 | avribacki |
471070a279bcb7a0d22a5220de21dd017e72f6b5 | 28,997 | cpp | C++ | assembler/tests/emitter_test.cpp | openharmony-gitee-mirror/ark_runtime_core | 2e6f195caf482dc9607efda7cfb5cc5f98da5598 | [
"Apache-2.0"
] | 1 | 2021-09-09T03:17:23.000Z | 2021-09-09T03:17:23.000Z | assembler/tests/emitter_test.cpp | openharmony-gitee-mirror/ark_runtime_core | 2e6f195caf482dc9607efda7cfb5cc5f98da5598 | [
"Apache-2.0"
] | null | null | null | assembler/tests/emitter_test.cpp | openharmony-gitee-mirror/ark_runtime_core | 2e6f195caf482dc9607efda7cfb5cc5f98da5598 | [
"Apache-2.0"
] | 1 | 2021-09-13T11:21:57.000Z | 2021-09-13T11:21:57.000Z | /*
* Copyright (c) 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 <iomanip>
#include <tuple>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "annotation_data_accessor.h"
#include "assembly-emitter.h"
#include "assembly-parser.h"
#include "class_data_accessor-inl.h"
#include "code_data_accessor-inl.h"
#include "debug_data_accessor-inl.h"
#include "field_data_accessor-inl.h"
#include "file_items.h"
#include "lexer.h"
#include "method_data_accessor-inl.h"
#include "param_annotations_data_accessor.h"
#include "proto_data_accessor-inl.h"
#include "utils/span.h"
#include "utils/leb128.h"
#include "utils/utf.h"
namespace panda::test {
using namespace panda::pandasm;
static const uint8_t *GetTypeDescriptor(const std::string &name, std::string *storage)
{
*storage = "L" + name + ";";
std::replace(storage->begin(), storage->end(), '.', '/');
return utf::CStringAsMutf8(storage->c_str());
}
TEST(emittertests, test)
{
Parser p;
auto source = R"( # 1
.record R { # 2
i32 sf <static> # 3
i8 if # 4
} # 5
# 6
.function void main() { # 7
return.void # 8
} # 9
)";
std::string source_filename = "source.pa";
auto res = p.Parse(source, source_filename);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_NE(pf, nullptr);
// Check _GLOBAL class
{
std::string descriptor;
auto class_id = pf->GetClassId(GetTypeDescriptor("_GLOBAL", &descriptor));
ASSERT_TRUE(class_id.IsValid());
ASSERT_FALSE(pf->IsExternal(class_id));
panda_file::ClassDataAccessor cda(*pf, class_id);
ASSERT_EQ(cda.GetSuperClassId().GetOffset(), 0U);
ASSERT_EQ(cda.GetAccessFlags(), ACC_PUBLIC);
ASSERT_EQ(cda.GetFieldsNumber(), 0U);
ASSERT_EQ(cda.GetMethodsNumber(), 1U);
ASSERT_EQ(cda.GetIfacesNumber(), 0U);
ASSERT_FALSE(cda.GetSourceFileId().has_value());
cda.EnumerateRuntimeAnnotations([](panda_file::File::EntityId) { ASSERT_TRUE(false); });
cda.EnumerateAnnotations([](panda_file::File::EntityId) { ASSERT_TRUE(false); });
cda.EnumerateFields([](panda_file::FieldDataAccessor &) { ASSERT_TRUE(false); });
cda.EnumerateMethods([&](panda_file::MethodDataAccessor &mda) {
ASSERT_FALSE(mda.IsExternal());
ASSERT_EQ(mda.GetClassId(), class_id);
ASSERT_EQ(utf::CompareMUtf8ToMUtf8(pf->GetStringData(mda.GetNameId()).data, utf::CStringAsMutf8("main")),
0);
panda_file::ProtoDataAccessor pda(*pf, mda.GetProtoId());
ASSERT_EQ(pda.GetNumArgs(), 0U);
ASSERT_EQ(pda.GetReturnType().GetId(), panda_file::Type::TypeId::VOID);
ASSERT_EQ(mda.GetAccessFlags(), ACC_STATIC);
ASSERT_TRUE(mda.GetCodeId().has_value());
panda_file::CodeDataAccessor cdacc(*pf, mda.GetCodeId().value());
ASSERT_EQ(cdacc.GetNumVregs(), 0U);
ASSERT_EQ(cdacc.GetNumArgs(), 0U);
ASSERT_EQ(cdacc.GetCodeSize(), 1U);
ASSERT_EQ(cdacc.GetTriesSize(), 0U);
ASSERT_FALSE(mda.GetRuntimeParamAnnotationId().has_value());
ASSERT_FALSE(mda.GetParamAnnotationId().has_value());
ASSERT_TRUE(mda.GetDebugInfoId().has_value());
panda_file::DebugInfoDataAccessor dda(*pf, mda.GetDebugInfoId().value());
ASSERT_EQ(dda.GetLineStart(), 8U);
ASSERT_EQ(dda.GetNumParams(), 0U);
mda.EnumerateRuntimeAnnotations([](panda_file::File::EntityId) { ASSERT_TRUE(false); });
mda.EnumerateAnnotations([](panda_file::File::EntityId) { ASSERT_TRUE(false); });
});
}
// Check R class
{
std::string descriptor;
auto class_id = pf->GetClassId(GetTypeDescriptor("R", &descriptor));
ASSERT_TRUE(class_id.IsValid());
ASSERT_FALSE(pf->IsExternal(class_id));
panda_file::ClassDataAccessor cda(*pf, class_id);
ASSERT_EQ(cda.GetSuperClassId().GetOffset(), 0U);
ASSERT_EQ(cda.GetAccessFlags(), 0);
ASSERT_EQ(cda.GetFieldsNumber(), 2U);
ASSERT_EQ(cda.GetMethodsNumber(), 0U);
ASSERT_EQ(cda.GetIfacesNumber(), 0U);
// We emit SET_FILE in debuginfo
ASSERT_TRUE(cda.GetSourceFileId().has_value());
EXPECT_EQ(std::string(reinterpret_cast<const char *>(pf->GetStringData(cda.GetSourceFileId().value()).data)),
source_filename);
cda.EnumerateRuntimeAnnotations([](panda_file::File::EntityId) { ASSERT_TRUE(false); });
cda.EnumerateAnnotations([](panda_file::File::EntityId) { ASSERT_TRUE(false); });
struct FieldData {
std::string name;
panda_file::Type::TypeId type_id;
uint32_t access_flags;
};
std::vector<FieldData> fields {{"sf", panda_file::Type::TypeId::I32, ACC_STATIC},
{"if", panda_file::Type::TypeId::I8, 0}};
size_t i = 0;
cda.EnumerateFields([&](panda_file::FieldDataAccessor &fda) {
ASSERT_FALSE(fda.IsExternal());
ASSERT_EQ(fda.GetClassId(), class_id);
ASSERT_EQ(utf::CompareMUtf8ToMUtf8(pf->GetStringData(fda.GetNameId()).data,
utf::CStringAsMutf8(fields[i].name.c_str())),
0);
ASSERT_EQ(fda.GetType(), panda_file::Type(fields[i].type_id).GetFieldEncoding());
ASSERT_EQ(fda.GetAccessFlags(), fields[i].access_flags);
fda.EnumerateRuntimeAnnotations([](panda_file::File::EntityId) { ASSERT_TRUE(false); });
fda.EnumerateAnnotations([](panda_file::File::EntityId) { ASSERT_TRUE(false); });
++i;
});
cda.EnumerateMethods([&](panda_file::MethodDataAccessor &) { ASSERT_TRUE(false); });
}
}
uint8_t GetSpecialOpcode(uint32_t pc_inc, int32_t line_inc)
{
return (line_inc - panda_file::LineNumberProgramItem::LINE_BASE) +
(pc_inc * panda_file::LineNumberProgramItem::LINE_RANGE) + panda_file::LineNumberProgramItem::OPCODE_BASE;
}
TEST(emittertests, debuginfo)
{
Parser p;
auto source = R"(
.function void main() {
ldai.64 0 # line 3, pc 0
# line 4
# line 5
# line 6
# line 7
# line 8
# line 9
# line 10
# line 11
# line 12
# line 13
# line 14
ldai.64 1 # line 15, pc 9
return.void # line 16, pc 18
}
)";
std::string source_filename = "source.pa";
auto res = p.Parse(source, source_filename);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_NE(pf, nullptr);
std::string descriptor;
auto class_id = pf->GetClassId(GetTypeDescriptor("_GLOBAL", &descriptor));
ASSERT_TRUE(class_id.IsValid());
panda_file::ClassDataAccessor cda(*pf, class_id);
cda.EnumerateMethods([&](panda_file::MethodDataAccessor &mda) {
panda_file::CodeDataAccessor cdacc(*pf, mda.GetCodeId().value());
ASSERT_TRUE(mda.GetDebugInfoId().has_value());
panda_file::DebugInfoDataAccessor dda(*pf, mda.GetDebugInfoId().value());
ASSERT_EQ(dda.GetLineStart(), 3U);
ASSERT_EQ(dda.GetNumParams(), 0U);
const uint8_t *program = dda.GetLineNumberProgram();
Span<const uint8_t> constant_pool = dda.GetConstantPool();
std::vector<uint8_t> opcodes {static_cast<uint8_t>(panda_file::LineNumberProgramItem::Opcode::SET_FILE),
static_cast<uint8_t>(panda_file::LineNumberProgramItem::Opcode::ADVANCE_PC),
static_cast<uint8_t>(panda_file::LineNumberProgramItem::Opcode::ADVANCE_LINE),
GetSpecialOpcode(0, 0),
GetSpecialOpcode(9, 1),
static_cast<uint8_t>(panda_file::LineNumberProgramItem::Opcode::END_SEQUENCE)};
EXPECT_THAT(opcodes, ::testing::ElementsAreArray(program, opcodes.size()));
size_t size;
bool is_full;
size_t constant_pool_offset = 0;
uint32_t offset;
std::tie(offset, size, is_full) = leb128::DecodeUnsigned<uint32_t>(&constant_pool[constant_pool_offset]);
constant_pool_offset += size;
ASSERT_TRUE(is_full);
EXPECT_EQ(
std::string(reinterpret_cast<const char *>(pf->GetStringData(panda_file::File::EntityId(offset)).data)),
source_filename);
uint32_t pc_inc;
std::tie(pc_inc, size, is_full) = leb128::DecodeUnsigned<uint32_t>(&constant_pool[constant_pool_offset]);
constant_pool_offset += size;
ASSERT_TRUE(is_full);
EXPECT_EQ(pc_inc, 9U);
int32_t line_inc;
std::tie(line_inc, size, is_full) = leb128::DecodeSigned<int32_t>(&constant_pool[constant_pool_offset]);
constant_pool_offset += size;
ASSERT_TRUE(is_full);
EXPECT_EQ(line_inc, 12);
EXPECT_EQ(constant_pool_offset, constant_pool.size());
});
}
TEST(emittertests, exceptions)
{
Parser p;
auto source = R"(
.record Exception1 {}
.record Exception2 {}
.function void main() {
ldai.64 0
try_begin:
ldai.64 1
ldai.64 2
try_end:
ldai.64 3
catch_begin1:
ldai.64 4
catch_begin2:
ldai.64 5
catchall_begin:
ldai.64 6
.catch Exception1, try_begin, try_end, catch_begin1
.catch Exception2, try_begin, try_end, catch_begin2
.catchall try_begin, try_end, catchall_begin
}
)";
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_NE(pf, nullptr);
std::string descriptor;
auto class_id = pf->GetClassId(GetTypeDescriptor("_GLOBAL", &descriptor));
ASSERT_TRUE(class_id.IsValid());
panda_file::ClassDataAccessor cda(*pf, class_id);
cda.EnumerateMethods([&](panda_file::MethodDataAccessor &mda) {
panda_file::CodeDataAccessor cdacc(*pf, mda.GetCodeId().value());
ASSERT_EQ(cdacc.GetNumVregs(), 0U);
ASSERT_EQ(cdacc.GetNumArgs(), 0U);
ASSERT_EQ(cdacc.GetTriesSize(), 1);
cdacc.EnumerateTryBlocks([&](panda_file::CodeDataAccessor::TryBlock &try_block) {
EXPECT_EQ(try_block.GetStartPc(), 9);
EXPECT_EQ(try_block.GetLength(), 18);
EXPECT_EQ(try_block.GetNumCatches(), 3);
struct CatchInfo {
panda_file::File::EntityId type_id;
uint32_t handler_pc;
};
std::vector<CatchInfo> catch_infos {{pf->GetClassId(GetTypeDescriptor("Exception1", &descriptor)), 4 * 9},
{pf->GetClassId(GetTypeDescriptor("Exception2", &descriptor)), 5 * 9},
{panda_file::File::EntityId(), 6 * 9}};
size_t i = 0;
try_block.EnumerateCatchBlocks([&](panda_file::CodeDataAccessor::CatchBlock &catch_block) {
auto idx = catch_block.GetTypeIdx();
auto id = idx != panda_file::INVALID_INDEX ? pf->ResolveClassIndex(mda.GetMethodId(), idx)
: panda_file::File::EntityId();
EXPECT_EQ(id, catch_infos[i].type_id);
EXPECT_EQ(catch_block.GetHandlerPc(), catch_infos[i].handler_pc);
++i;
return true;
});
return true;
});
});
}
TEST(emittertests, errors)
{
{
Parser p;
auto source = R"(
.record A {
B b
}
)";
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_EQ(pf, nullptr);
ASSERT_EQ(AsmEmitter::GetLastError(), "Field A.b has undefined type");
}
{
Parser p;
auto source = R"(
.function void A.b() {}
)";
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_EQ(pf, nullptr);
ASSERT_EQ(AsmEmitter::GetLastError(), "Function A.b is bound to undefined record A");
}
{
Parser p;
auto source = R"(
.function A b() {}
)";
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_EQ(pf, nullptr);
ASSERT_EQ(AsmEmitter::GetLastError(), "Function b has undefined return type");
}
{
Parser p;
auto source = R"(
.function void a(b a0) {}
)";
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_EQ(pf, nullptr);
ASSERT_EQ(AsmEmitter::GetLastError(), "Argument 0 of function a has undefined type");
}
{
Parser p;
auto source = R"(
.record A <external>
.function void A.x() {}
)";
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_EQ(pf, nullptr);
ASSERT_EQ(AsmEmitter::GetLastError(), "Non-external function A.x is bound to external record");
}
{
Ins i;
Function f("test_fuzz_imms", pandasm::extensions::Language::ECMASCRIPT);
Program prog;
i.opcode = Opcode::LDAI_64;
i.imms.clear();
f.ins.push_back(i);
prog.function_table.emplace("test_fuzz_imms", std::move(f));
auto pf = AsmEmitter::Emit(prog);
ASSERT_EQ(pf, nullptr);
ASSERT_EQ(AsmEmitter::GetLastError(), "Internal error during emitting function: test_fuzz_imms");
}
{
Ins i;
Function f("test_fuzz_regs", pandasm::extensions::Language::ECMASCRIPT);
Program prog;
i.opcode = Opcode::LDA;
i.regs.clear();
f.ins.push_back(i);
prog.function_table.emplace("test_fuzz_regs", std::move(f));
auto pf = AsmEmitter::Emit(prog);
ASSERT_EQ(pf, nullptr);
ASSERT_EQ(AsmEmitter::GetLastError(), "Internal error during emitting function: test_fuzz_regs");
}
{
Ins i;
Function f("test_fuzz_ids", pandasm::extensions::Language::ECMASCRIPT);
Program prog;
i.opcode = Opcode::LDA_STR;
i.ids.push_back("testFuzz");
f.ins.push_back(i);
prog.function_table.emplace("test_fuzz_ids", std::move(f));
prog.strings.insert("testFuz_");
auto pf = AsmEmitter::Emit(prog);
ASSERT_EQ(pf, nullptr);
ASSERT_EQ(AsmEmitter::GetLastError(), "Internal error during emitting function: test_fuzz_ids");
}
}
enum class ItemType { RECORD, FIELD, FUNCTION, PARAMETER };
std::string ItemTypeToString(ItemType item_type)
{
switch (item_type) {
case ItemType::RECORD:
return "record";
case ItemType::FIELD:
return "field";
case ItemType::FUNCTION:
return "function";
case ItemType::PARAMETER:
return "parameter";
default:
break;
}
UNREACHABLE();
return "";
}
template <Value::Type type>
auto GetAnnotationElementValue(size_t idx)
{
using T = ValueTypeHelperT<type>;
if constexpr (std::is_arithmetic_v<T>) {
if constexpr (type == Value::Type::U1) {
return static_cast<uint32_t>(idx == 0 ? 0 : 1);
}
auto res = idx == 0 ? std::numeric_limits<T>::min() : std::numeric_limits<T>::max();
if constexpr (type == Value::Type::I8) {
return static_cast<int32_t>(res);
}
if constexpr (type == Value::Type::U8) {
return static_cast<uint32_t>(res);
}
if constexpr (std::is_floating_point_v<T>) {
return res * (idx == 0 ? 10 : 0.1);
}
return res;
} else {
switch (type) {
case Value::Type::STRING:
return idx == 0 ? "123" : "456";
case Value::Type::RECORD:
return idx == 0 ? "A" : "B";
case Value::Type::ENUM:
return idx == 0 ? "E.E1" : "E.E2";
case Value::Type::ANNOTATION:
return idx == 0 ? "id_A" : "id_B";
default:
break;
}
UNREACHABLE();
return "";
}
}
TEST(emittertests, language)
{
{
Parser p;
auto source = R"(
.function void foo() {}
)";
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_NE(pf, nullptr);
std::string descriptor;
auto class_id = pf->GetClassId(GetTypeDescriptor("_GLOBAL", &descriptor));
ASSERT_TRUE(class_id.IsValid());
panda_file::ClassDataAccessor cda(*pf, class_id);
ASSERT_FALSE(cda.GetSourceLang());
cda.EnumerateMethods([&](panda_file::MethodDataAccessor &mda) { ASSERT_FALSE(mda.GetSourceLang()); });
}
}
TEST(emittertests, constructors)
{
{
Parser p;
auto source = R"(
.record R {}
.function void R.foo(R a0) <ctor> {}
)";
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_NE(pf, nullptr);
std::string descriptor;
auto class_id = pf->GetClassId(GetTypeDescriptor("R", &descriptor));
ASSERT_TRUE(class_id.IsValid());
panda_file::ClassDataAccessor cda(*pf, class_id);
cda.EnumerateMethods([&](panda_file::MethodDataAccessor &mda) {
auto *name = utf::Mutf8AsCString(pf->GetStringData(mda.GetNameId()).data);
ASSERT_STREQ(name, ".ctor");
});
}
{
Parser p;
auto source = R"(
.record R {}
.function void R.foo(R a0) <cctor> {}
)";
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_NE(pf, nullptr);
std::string descriptor;
auto class_id = pf->GetClassId(GetTypeDescriptor("R", &descriptor));
ASSERT_TRUE(class_id.IsValid());
panda_file::ClassDataAccessor cda(*pf, class_id);
cda.EnumerateMethods([&](panda_file::MethodDataAccessor &mda) {
auto *name = utf::Mutf8AsCString(pf->GetStringData(mda.GetNameId()).data);
ASSERT_STREQ(name, ".cctor");
});
}
}
TEST(emittertests, field_value)
{
Parser p;
auto source = R"(
.record panda.String <external>
.record R {
u1 f_u1 <value=1>
i8 f_i8 <value=2>
u8 f_u8 <value=128>
i16 f_i16 <value=256>
u16 f_u16 <value=32768>
i32 f_i32 <value=65536>
u32 f_u32 <value=2147483648>
i64 f_i64 <value=4294967296>
u64 f_u64 <value=9223372036854775808>
f32 f_f32 <value=1.0>
f64 f_f64 <value=2.0>
panda.String f_str <value="str">
}
)";
struct FieldData {
std::string name;
panda_file::Type::TypeId type_id;
std::variant<int32_t, uint32_t, int64_t, uint64_t, float, double, std::string> value;
};
std::vector<FieldData> data {
{"f_u1", panda_file::Type::TypeId::U1, static_cast<uint32_t>(1)},
{"f_i8", panda_file::Type::TypeId::I8, static_cast<int32_t>(2)},
{"f_u8", panda_file::Type::TypeId::U8, static_cast<uint32_t>(128)},
{"f_i16", panda_file::Type::TypeId::I16, static_cast<int32_t>(256)},
{"f_u16", panda_file::Type::TypeId::U16, static_cast<uint32_t>(32768)},
{"f_i32", panda_file::Type::TypeId::I32, static_cast<int32_t>(65536)},
{"f_u32", panda_file::Type::TypeId::U32, static_cast<uint32_t>(2147483648)},
{"f_i64", panda_file::Type::TypeId::I64, static_cast<int64_t>(4294967296)},
{"f_u64", panda_file::Type::TypeId::U64, static_cast<uint64_t>(9223372036854775808ULL)},
{"f_f32", panda_file::Type::TypeId::F32, static_cast<float>(1.0)},
{"f_f64", panda_file::Type::TypeId::F64, static_cast<double>(2.0)},
{"f_str", panda_file::Type::TypeId::REFERENCE, "str"}};
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_NE(pf, nullptr);
std::string descriptor;
auto class_id = pf->GetClassId(GetTypeDescriptor("R", &descriptor));
ASSERT_TRUE(class_id.IsValid());
ASSERT_FALSE(pf->IsExternal(class_id));
panda_file::ClassDataAccessor cda(*pf, class_id);
ASSERT_EQ(cda.GetFieldsNumber(), data.size());
auto panda_string_id = pf->GetClassId(GetTypeDescriptor("panda.String", &descriptor));
size_t idx = 0;
cda.EnumerateFields([&](panda_file::FieldDataAccessor &fda) {
const FieldData &field_data = data[idx];
ASSERT_EQ(utf::CompareMUtf8ToMUtf8(pf->GetStringData(fda.GetNameId()).data,
utf::CStringAsMutf8(field_data.name.c_str())),
0);
panda_file::Type type(field_data.type_id);
uint32_t type_value;
if (type.IsReference()) {
type_value = panda_string_id.GetOffset();
} else {
type_value = type.GetFieldEncoding();
}
ASSERT_EQ(fda.GetType(), type_value);
switch (field_data.type_id) {
case panda_file::Type::TypeId::U1: {
auto result = fda.GetValue<uint8_t>();
ASSERT_TRUE(result);
ASSERT_EQ(result.value(), std::get<uint32_t>(field_data.value));
break;
}
case panda_file::Type::TypeId::I8: {
auto result = fda.GetValue<int8_t>();
ASSERT_TRUE(result);
ASSERT_EQ(result.value(), std::get<int32_t>(field_data.value));
break;
}
case panda_file::Type::TypeId::U8: {
auto result = fda.GetValue<uint8_t>();
ASSERT_TRUE(result);
ASSERT_EQ(result.value(), std::get<uint32_t>(field_data.value));
break;
}
case panda_file::Type::TypeId::I16: {
auto result = fda.GetValue<int16_t>();
ASSERT_TRUE(result);
ASSERT_EQ(result.value(), std::get<int32_t>(field_data.value));
break;
}
case panda_file::Type::TypeId::U16: {
auto result = fda.GetValue<uint16_t>();
ASSERT_TRUE(result);
ASSERT_EQ(result.value(), std::get<uint32_t>(field_data.value));
break;
}
case panda_file::Type::TypeId::I32: {
auto result = fda.GetValue<int32_t>();
ASSERT_TRUE(result);
ASSERT_EQ(result.value(), std::get<int32_t>(field_data.value));
break;
}
case panda_file::Type::TypeId::U32: {
auto result = fda.GetValue<uint32_t>();
ASSERT_TRUE(result);
ASSERT_EQ(result.value(), std::get<uint32_t>(field_data.value));
break;
}
case panda_file::Type::TypeId::I64: {
auto result = fda.GetValue<int64_t>();
ASSERT_TRUE(result);
ASSERT_EQ(result.value(), std::get<int64_t>(field_data.value));
break;
}
case panda_file::Type::TypeId::U64: {
auto result = fda.GetValue<uint64_t>();
ASSERT_TRUE(result);
ASSERT_EQ(result.value(), std::get<uint64_t>(field_data.value));
break;
}
case panda_file::Type::TypeId::F32: {
auto result = fda.GetValue<float>();
ASSERT_TRUE(result);
ASSERT_EQ(result.value(), std::get<float>(field_data.value));
break;
}
case panda_file::Type::TypeId::F64: {
auto result = fda.GetValue<double>();
ASSERT_TRUE(result);
ASSERT_EQ(result.value(), std::get<double>(field_data.value));
break;
}
case panda_file::Type::TypeId::REFERENCE: {
auto result = fda.GetValue<uint32_t>();
ASSERT_TRUE(result);
panda_file::File::EntityId string_id(result.value());
auto val = std::get<std::string>(field_data.value);
ASSERT_EQ(utf::CompareMUtf8ToMUtf8(pf->GetStringData(string_id).data, utf::CStringAsMutf8(val.c_str())),
0);
break;
}
default: {
UNREACHABLE();
break;
}
}
++idx;
});
}
TEST(emittertests, tagged_in_func_decl)
{
Parser p;
auto source = R"(
.function any foo(any a0) <noimpl>
)";
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_NE(pf, nullptr);
std::string descriptor;
auto class_id = pf->GetClassId(GetTypeDescriptor("_GLOBAL", &descriptor));
ASSERT_TRUE(class_id.IsValid());
panda_file::ClassDataAccessor cda(*pf, class_id);
size_t num_methods = 0;
const auto tagged = panda_file::Type(panda_file::Type::TypeId::TAGGED);
cda.EnumerateMethods([&](panda_file::MethodDataAccessor &mda) {
panda_file::ProtoDataAccessor pda(*pf, mda.GetProtoId());
ASSERT_EQ(tagged, pda.GetReturnType());
ASSERT_EQ(1, pda.GetNumArgs());
ASSERT_EQ(tagged, pda.GetArgType(0));
++num_methods;
});
ASSERT_EQ(1, num_methods);
}
TEST(emittertests, tagged_in_field_decl)
{
Parser p;
auto source = R"(
.record Test {
any foo
}
)";
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_NE(pf, nullptr);
std::string descriptor;
auto class_id = pf->GetClassId(GetTypeDescriptor("Test", &descriptor));
ASSERT_TRUE(class_id.IsValid());
panda_file::ClassDataAccessor cda(*pf, class_id);
size_t num_fields = 0;
const auto tagged = panda_file::Type(panda_file::Type::TypeId::TAGGED);
cda.EnumerateFields([&](panda_file::FieldDataAccessor &fda) {
uint32_t type = fda.GetType();
ASSERT_EQ(tagged.GetFieldEncoding(), type);
++num_fields;
});
ASSERT_EQ(1, num_fields);
}
TEST(emittertests, get_GLOBAL_lang_for_JS_func)
{
Parser p;
auto source = R"(
.language ECMAScript
.function any main() {
return.dyn
}
)";
auto res = p.Parse(source);
ASSERT_EQ(p.ShowError().err, Error::ErrorType::ERR_NONE);
auto pf = AsmEmitter::Emit(res.Value());
ASSERT_NE(pf, nullptr);
std::string descriptor;
auto class_id = pf->GetClassId(GetTypeDescriptor("_GLOBAL", &descriptor));
ASSERT_TRUE(class_id.IsValid());
panda_file::ClassDataAccessor cda(*pf, class_id);
ASSERT_TRUE(cda.GetSourceLang().has_value());
ASSERT_EQ(cda.GetSourceLang(), panda_file::SourceLang::ECMASCRIPT);
}
} // namespace panda::test
| 33.25344 | 120 | 0.57637 | openharmony-gitee-mirror |
4711bc5b49380ac67c4d616b955618c7147dc312 | 14,992 | cpp | C++ | devtools/lit/lib/ProgressBar.cpp | PHP-OPEN-HUB/polarphp | 70ff4046e280fd99d718d4761686168fa8012aa5 | [
"PHP-3.01"
] | null | null | null | devtools/lit/lib/ProgressBar.cpp | PHP-OPEN-HUB/polarphp | 70ff4046e280fd99d718d4761686168fa8012aa5 | [
"PHP-3.01"
] | null | null | null | devtools/lit/lib/ProgressBar.cpp | PHP-OPEN-HUB/polarphp | 70ff4046e280fd99d718d4761686168fa8012aa5 | [
"PHP-3.01"
] | null | null | null | // This source file is part of the polarphp.org open source project
//
// Copyright (c) 2017 - 2019 polarphp software foundation
// Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://polarphp.org/LICENSE.txt for license information
// See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors
//
// Created by polarboy on 2018/09/17.
#include "ProgressBar.h"
#include "LitGlobal.h"
#include "Utils.h"
#include "CLI/CLI.hpp"
#include "polarphp/basic/adt/StringRef.h"
#include <assert.h>
#include <boost/regex.hpp>
#include <ncurses.h>
namespace polar {
namespace lit {
const std::string TerminalController::BOL{"BOL"};
const std::string TerminalController::UP{"UP"};
const std::string TerminalController::DOWN{"DOWN"};
const std::string TerminalController::LEFT{"LEFT"};
const std::string TerminalController::RIGHT{"RIGHT"};
const std::string TerminalController::CLEAR_SCREEN{"CLEAR_SCREEN"};
const std::string TerminalController::CLEAR_EOL{"CLEAR_EOL"};
const std::string TerminalController::CLEAR_BOL{"CLEAR_BOL"};
const std::string TerminalController::CLEAR_EOS{"CLEAR_EOS"};
const std::string TerminalController::BOLD{"BOLD"};
const std::string TerminalController::BLINK{"BLINK"};
const std::string TerminalController::DIM{"DIM"};
const std::string TerminalController::REVERSE{"REVERSE"};
const std::string TerminalController::NORMAL{"NORMAL"};
const std::string TerminalController::HIDE_CURSOR{"HIDE_CURSOR"};
const std::string TerminalController::SHOW_CURSOR{"SHOW_CURSOR"};
int TerminalController::COLUMNS = -1;
int TerminalController::LINE_COUNT = -1;
bool TerminalController::XN = false;
std::list<std::string> TerminalController::STRING_CAPABILITIES {
"BOL=cr",
"UP=cuu1",
"DOWN=cud1",
"LEFT=cub1",
"RIGHT=cuf1",
"CLEAR_SCREEN=clear",
"CLEAR_EOL=el",
"CLEAR_BOL=el1",
"CLEAR_EOS=ed",
"BOLD=bold",
"BLINK=blink",
"DIM=dim",
"REVERSE=rev",
"UNDERLINE=smul",
"NORMAL=sgr0",
"HIDE_CURSOR=cinvis",
"SHOW_CURSOR=cnorm"
};
std::list<std::string> TerminalController::COLOR_TYPES {
"BLACK",
"BLUE",
"GREEN",
"CYAN",
"RED",
"MAGENTA",
"YELLOW",
"WHITE"
};
std::list<std::string> TerminalController::ANSICOLORS {
"BLACK",
"RED",
"GREEN",
"YELLOW",
"BLUE",
"MAGENTA",
"CYAN",
"WHITE"
};
namespace {
class CursesWinUnlocker
{
public:
CursesWinUnlocker(bool needUnlock)
: m_needUnlock(needUnlock)
{
}
~CursesWinUnlocker()
{
if (m_needUnlock) {
::endwin();
}
}
protected:
bool m_needUnlock;
};
}
/// Create a `TerminalController` and initialize its attributes
/// with appropriate values for the current terminal.
/// `term_stream` is the stream that will be used for terminal
/// output; if this stream is not a tty, then the terminal is
/// assumed to be a dumb terminal (i.e., have no capabilities).
///
TerminalController::TerminalController(std::ostream &)
: m_initialized(false)
{
// If the stream isn't a tty, then assume it has no capabilities.
if (!stdcout_isatty()) {
throw std::runtime_error("stdcout is not a tty device");
}
initTermScreen();
CursesWinUnlocker winLocker(true);
// Check the terminal type. If we fail, then assume that the
// terminal has no capabilities.
// Look up numeric capabilities.
COLUMNS = ::tigetnum(const_cast<char *>("cols"));
LINE_COUNT = ::tigetnum(const_cast<char *>("lines"));
XN = ::tigetflag(const_cast<char *>("xenl"));
// Look up string capabilities.
for (std::string capability : STRING_CAPABILITIES) {
std::list<std::string> parts = split_string(capability, '=');
assert(parts.size() == 2);
std::list<std::string>::iterator iter = parts.begin();
std::string attribute = *iter++;
std::string capName = *iter++;
m_properties[attribute] = tigetStr(capName);
}
// init Colors
std::string setFg = tigetStr("setf");
if (!setFg.empty()) {
auto iter = COLOR_TYPES.begin();
int index = 0;
for (; iter != COLOR_TYPES.end(); ++iter, ++index) {
m_properties[*iter] = tparm(setFg, index);
}
}
std::string setAnsiFg = tigetStr("setaf");
if (!setAnsiFg.empty()) {
auto iter = ANSICOLORS.begin();
int index = 0;
for (; iter != ANSICOLORS.end(); ++iter, ++index) {
m_properties[*iter] = tparm(setAnsiFg, index);
}
}
std::string setBg = tigetStr("setb");
if (!setBg.empty()) {
auto iter = COLOR_TYPES.begin();
int index = 0;
for (; iter != COLOR_TYPES.end(); ++iter, ++index) {
m_properties[*iter] = tparm(setFg, index);
}
}
std::string setAnsiBg = tigetStr("setab");
if (!setAnsiBg.empty()) {
auto iter = ANSICOLORS.begin();
int index = 0;
for (; iter != ANSICOLORS.end(); ++iter, ++index) {
m_properties[*iter] = tparm(setAnsiFg, index);
}
}
}
TerminalController::~TerminalController()
{
}
std::string TerminalController::tigetStr(const std::string &capName)
{
// String capabilities can include "delays" of the form "$<2>".
// For any modern terminal, we should be able to just ignore
// these, so strip them out.
char *str = ::tigetstr(const_cast<char *>(capName.c_str()));
std::string cap;
if (str != nullptr && str != reinterpret_cast<char *>(-1)) {
cap = str;
}
if (!cap.empty()) {
boost::regex regex("$<\\d+>[/*]?");
cap = boost::regex_replace(cap, regex, "");
}
return cap;
}
std::string TerminalController::tparm(const std::string &arg, int index)
{
char *str = ::tparm(const_cast<char *>(arg.c_str()), index);
if (str == nullptr || str == reinterpret_cast<char *>(-1)) {
return std::string{};
}
return str;
}
void TerminalController::initTermScreen()
{
std::lock_guard locker(m_mutex);
NCURSES_CONST char *name;
if ((name = getenv("TERM")) == nullptr
|| *name == '\0')
name = const_cast<char *>("unknown");
#ifdef __CYGWIN__
/*
* 2002/9/21
* Work around a bug in Cygwin. Full-screen subprocesses run from
* bash, in turn spawned from another full-screen process, will dump
* core when attempting to write to stdout. Opening /dev/tty
* explicitly seems to fix the problem.
*/
if (isatty(fileno(stdout))) {
FILE *fp = fopen("/dev/tty", "w");
if (fp != 0 && isatty(fileno(fp))) {
fclose(stdout);
dup2(fileno(fp), STDOUT_FILENO);
stdout = fdopen(STDOUT_FILENO, "w");
}
}
#endif
if (newterm(name, stdout, stdin) == nullptr) {
throw std::runtime_error(format_string("Error opening terminal: %s.\n", name));
}
/* def_shell_mode - done in newterm/_nc_setupscreen */
def_prog_mode();
}
///
/// Replace each $-substitutions in the given template string with
/// the corresponding terminal control string (if it's defined) or
/// '' (if it's not).
///
std::string TerminalController::render(std::string tpl) const
{
boost::regex regex(R"(\$\{(\w+)\})");
boost::smatch varMatch;
while(boost::regex_search(tpl, varMatch, regex)) {
std::string varname = varMatch[1];
if (m_properties.find(varname) != m_properties.end()) {
tpl.replace(varMatch[0].first, varMatch[0].second, m_properties.at(varname));
}
}
return tpl;
}
const std::string &TerminalController::getProperty(const std::string &key) const
{
return m_properties.at(key);
}
SimpleProgressBar::SimpleProgressBar(const std::string &header)
: m_header(header),
m_atIndex(-1)
{
}
void SimpleProgressBar::update(float percent, std::string message)
{
if (m_atIndex == -1) {
std::printf("%s\n", m_header.c_str());
m_atIndex = 0;
}
int next = static_cast<int>(percent * 50);
if (next == m_atIndex) {
return;
}
for (int i = m_atIndex; i < next; ++i) {
int idx = i % 5;
if (0 == idx) {
std::printf("%-2d", i * 2);
} else if (1 == idx) {
// skip
} else if (idx < 4) {
std::printf(".");
} else {
std::printf(" ");
}
}
std::fflush(stdout);
m_atIndex = next;
}
void SimpleProgressBar::clear()
{
if (m_atIndex != -1) {
std::cout << std::endl;
std::cout.flush();
m_atIndex = -1;
}
}
const std::string ProgressBar::BAR ="%s${GREEN}[${BOLD}%s%s${NORMAL}${GREEN}]${NORMAL}%s";
const std::string ProgressBar::HEADER = "${BOLD}${CYAN}%s${NORMAL}\n\n";
ProgressBar::ProgressBar(const TerminalController &term, const std::string &header,
bool useETA)
: BOL(term.getProperty(TerminalController::BOL)),
XNL("\n"),
m_term(term),
m_header(header),
m_cleared(true),
m_useETA(useETA)
{
if (m_term.getProperty(TerminalController::CLEAR_EOL).empty() ||
m_term.getProperty(TerminalController::UP).empty() ||
m_term.getProperty(TerminalController::BOL).empty()) {
throw ValueError("Terminal isn't capable enough -- you "
"should use a simpler progress dispaly.");
}
if (m_term.COLUMNS != -1) {
m_width = static_cast<size_t>(m_term.COLUMNS);
if (!m_term.XN) {
BOL = m_term.getProperty(TerminalController::UP) + m_term.getProperty(TerminalController::BOL);
XNL = ""; // Cursor must be fed to the next line
}
} else {
m_width = 75;
}
m_bar = m_term.render(BAR);
if (m_useETA) {
m_startTime = std::chrono::system_clock::now();
}
}
void ProgressBar::update(float percent, std::string message)
{
if (m_cleared) {
std::printf("%s\n", m_header.c_str());
m_cleared = false;
}
std::string prefix = format_string("%3d%%", static_cast<int>(percent * 100));
std::string suffix = "";
if (m_useETA) {
auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - m_startTime).count();
if (percent > 0.0001f && elapsed > 1) {
int total = static_cast<int>(elapsed / percent);
int eta = int(total - elapsed);
int h = eta / 3600;
int m = (eta / 60) % 60;
int s = eta % 60;
suffix = format_string(" ETA: %02d:%02d:%02d", h, m, s);
}
}
size_t barWidth = m_width - prefix.size() - suffix.size() - 2;
size_t n = static_cast<size_t>(barWidth * percent);
if (message.size() < m_width) {
message = message + std::string(m_width - message.size(), ' ');
} else {
message = "... " + message.substr(-(m_width - 4));
}
std::string output = BOL +
m_term.getProperty(TerminalController::CLEAR_EOL);
output += format_string(m_bar, prefix.c_str(), std::string(n, '=').c_str(),
std::string(barWidth - n, '-').c_str(), suffix.c_str());
output += XNL;
output += m_term.getProperty(TerminalController::CLEAR_EOL);
output += message;
std::printf("%s\n", output.c_str());
std::fflush(stdout);
}
void ProgressBar::clear()
{
if (!m_cleared) {
std::printf("%s", (BOL + m_term.getProperty(TerminalController::CLEAR_EOL) +
m_term.getProperty(TerminalController::UP) +
m_term.getProperty(TerminalController::CLEAR_EOL)).c_str());
std::fflush(stdout);
m_cleared = true;
}
}
TestingProgressDisplay::TestingProgressDisplay(const CLI::App &opts, size_t numTests,
std::shared_ptr<AbstractProgressBar> progressBar)
: m_opts(opts),
m_numTests(numTests),
m_progressBar(progressBar),
m_completed(0)
{
m_showAllOutput = m_opts.get_option("--show-all")->count() > 0 ? true : false;
m_incremental = m_opts.get_option("--incremental")->count() > 0 ? true : false;
m_quiet = m_opts.get_option("--quiet")->count() > 0 ? true : false;
m_succinct = m_opts.get_option("--succinct")->count() > 0 ? true : false;
m_showOutput = m_opts.get_option("--verbose")->count() > 0 ? true : false;
}
void TestingProgressDisplay::finish()
{
if (m_progressBar) {
m_progressBar->clear();
} else if (m_quiet) {
// TODO
} else if (m_succinct) {
std::printf("\n");
}
}
void update_incremental_cache(TestPointer test)
{
if (!test->getResult()->getCode()->isFailure()) {
return;
}
polar::lit::modify_file_utime_and_atime(test->getFilePath());
}
void TestingProgressDisplay::update(TestPointer test)
{
m_completed += 1;
if (m_incremental) {
update_incremental_cache(test);
}
if (m_progressBar) {
m_progressBar->update(m_completed / static_cast<float>(m_numTests), test->getFullName());
}
assert(test->getResult()->getCode() && "test result code is not set");
bool shouldShow = test->getResult()->getCode()->isFailure() ||
m_showAllOutput ||
(!m_quiet && !m_succinct);
if (!shouldShow) {
return;
}
if (m_progressBar) {
m_progressBar->clear();
}
// Show the test result line.
std::string testName = test->getFullName();
ResultPointer testResult = test->getResult();
const ResultCode *resultCode = testResult->getCode();
std::printf("%s: %s (%lu of %lu)\n", resultCode->getName().c_str(),
testName.c_str(), m_completed, m_numTests);
// Show the test failure output, if requested.
if ((resultCode->isFailure() && m_showOutput) ||
m_showAllOutput) {
if (resultCode->isFailure()) {
std::printf("%s TEST '%s' FAILED %s\n", std::string(20, '*').c_str(),
test->getFullName().c_str(), std::string(20, '*').c_str());
}
std::cout << testResult->getOutput() << std::endl;
std::cout << std::string(20, '*') << std::endl;
}
// Report test metrics, if present.
if (!testResult->getMetrics().empty()) {
// @TODO sort the metrics
std::printf("%s TEST '%s' RESULTS %s\n", std::string(10, '*').c_str(),
test->getFullName().c_str(),
std::string(10, '*').c_str());
for (auto &item : testResult->getMetrics()) {
std::printf("%s: %s \n", item.first.c_str(), item.second->format().c_str());
}
std::cout << std::string(10, '*') << std::endl;
}
// Report micro-tests, if present
if (!testResult->getMicroResults().empty()) {
// @TODO sort the MicroResults
for (auto &item : testResult->getMicroResults()) {
std::printf("%s MICRO-TEST: %s\n", std::string(3, '*').c_str(), item.first.c_str());
ResultPointer microTest = item.second;
if (!microTest->getMetrics().empty()) {
// @TODO sort the metrics
for (auto µItem : microTest->getMetrics()) {
std::printf(" %s: %s \n", microItem.first.c_str(), microItem.second->format().c_str());
}
}
}
}
// Ensure the output is flushed.
std::fflush(stdout);
}
} // lit
} // polar
| 30.975207 | 126 | 0.614128 | PHP-OPEN-HUB |
471296fa4ba4364588b96efd2791ca2403d838dc | 5,179 | cpp | C++ | src/types/spatial.cpp | vi3itor/Blunted2 | 318af452e51174a3a4634f3fe19b314385838992 | [
"Unlicense"
] | 56 | 2020-07-22T22:11:06.000Z | 2022-03-09T08:11:43.000Z | GameplayFootball/src/types/spatial.cpp | ElsevierSoftwareX/SOFTX-D-20-00016 | 48c28adb72aa167a251636bc92111b3c43c0be67 | [
"MIT"
] | 9 | 2021-04-22T07:06:25.000Z | 2022-01-22T12:54:52.000Z | GameplayFootball/src/types/spatial.cpp | ElsevierSoftwareX/SOFTX-D-20-00016 | 48c28adb72aa167a251636bc92111b3c43c0be67 | [
"MIT"
] | 20 | 2017-11-07T16:52:32.000Z | 2022-01-25T02:42:48.000Z | // written by bastiaan konings schuiling 2008 - 2014
// this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important.
// i do not offer support, so don't ask. to be used for inspiration :)
#include "spatial.hpp"
namespace blunted {
Spatial::Spatial(const std::string &name) : name(name), parent(0), localMode(e_LocalMode_Relative) {
scale.Set(1, 1, 1);
Vector axis(0, 0, -1);
rotation.SetAngleAxis(0, axis);
position.Set(0, 0, 0);
aabb.data.aabb.Reset();
aabb.data.dirty = false;
InvalidateSpatialData();
}
Spatial::~Spatial() {
parent = 0;
}
Spatial::Spatial(const Spatial &src) {
name = src.GetName();
position = src.position;
rotation = src.rotation;
scale = src.scale;
localMode = src.localMode;
aabb.data.aabb = src.GetAABB();
aabb.data.dirty = false;
parent = 0;
InvalidateSpatialData();
}
void Spatial::SetLocalMode(e_LocalMode localMode) {
this->localMode = localMode;
InvalidateBoundingVolume();
}
bool Spatial::GetLocalMode() {
return localMode;
}
void Spatial::SetName(const std::string &name) {
spatialMutex.lock();
this->name = name;
spatialMutex.unlock();
}
const std::string Spatial::GetName() const {
boost::mutex::scoped_lock blah(spatialMutex);
return name.c_str();
}
void Spatial::SetParent(Spatial *parent) {
this->parent = parent;
InvalidateBoundingVolume();
}
Spatial *Spatial::GetParent() const {
return parent;
}
void Spatial::SetPosition(const Vector3 &newPosition, bool updateSpatialData) {
spatialMutex.lock();
position = newPosition;
spatialMutex.unlock();
if (updateSpatialData) RecursiveUpdateSpatialData(e_SpatialDataType_Position);
}
Vector3 Spatial::GetPosition() const {
spatialMutex.lock();
Vector3 pos = position;
spatialMutex.unlock();
return pos;
}
void Spatial::SetRotation(const Quaternion &newRotation, bool updateSpatialData) {
spatialMutex.lock();
rotation = newRotation;
spatialMutex.unlock();
if (updateSpatialData) RecursiveUpdateSpatialData(e_SpatialDataType_Both);
}
Quaternion Spatial::GetRotation() const {
spatialMutex.lock();
Quaternion rot = rotation;
spatialMutex.unlock();
return rot;
}
void Spatial::SetScale(const Vector3 &newScale) {
spatialMutex.lock();
this->scale = newScale;
spatialMutex.unlock();
RecursiveUpdateSpatialData(e_SpatialDataType_Rotation);
}
Vector3 Spatial::GetScale() const {
spatialMutex.lock();
Vector3 retScale = scale;
spatialMutex.unlock();
return retScale;
}
Vector3 Spatial::GetDerivedPosition() const {
boost::mutex::scoped_lock cachelock(cacheMutex);
if (_dirty_DerivedPosition) {
if (localMode == e_LocalMode_Relative) {
if (parent) {
const Quaternion parentDerivedRotation = parent->GetDerivedRotation();
const Vector3 parentDerivedScale = parent->GetDerivedScale();
const Vector3 parentDerivedPosition = parent->GetDerivedPosition();
_cache_DerivedPosition.Set(parentDerivedRotation * (parentDerivedScale * GetPosition()));
_cache_DerivedPosition += parentDerivedPosition;
} else {
_cache_DerivedPosition = GetPosition();
}
} else {
_cache_DerivedPosition = GetPosition();
}
_dirty_DerivedPosition = false;
}
return _cache_DerivedPosition;
}
Quaternion Spatial::GetDerivedRotation() const {
boost::mutex::scoped_lock cachelock(cacheMutex);
if (_dirty_DerivedRotation) {
if (localMode == e_LocalMode_Relative) {
if (parent) {
_cache_DerivedRotation = (parent->GetDerivedRotation() * GetRotation()).GetNormalized();
} else {
_cache_DerivedRotation = GetRotation();
}
} else {
_cache_DerivedRotation = GetRotation();
}
_dirty_DerivedRotation = false;
}
return _cache_DerivedRotation;
}
Vector3 Spatial::GetDerivedScale() const {
boost::mutex::scoped_lock cachelock(cacheMutex);
if (_dirty_DerivedScale) {
if (localMode == e_LocalMode_Relative) {
if (parent) {
_cache_DerivedScale = parent->GetDerivedScale() * GetScale();
} else {
_cache_DerivedScale = GetScale();
}
} else {
_cache_DerivedScale = GetScale();
}
_dirty_DerivedScale = false;
}
return _cache_DerivedScale;
}
void Spatial::InvalidateBoundingVolume() {
bool changed = false;
aabb.Lock();
if (aabb.data.dirty == false) {
aabb.data.dirty = true;
aabb.data.aabb.Reset();
changed = true;
}
aabb.Unlock();
if (changed) if (parent) parent->InvalidateBoundingVolume();
}
void Spatial::InvalidateSpatialData() {
cacheMutex.lock();
_dirty_DerivedPosition = true;
_dirty_DerivedRotation = true;
_dirty_DerivedScale = true;
cacheMutex.unlock();
}
AABB Spatial::GetAABB() const {
AABB tmp;
aabb.Lock();
tmp = aabb.data.aabb;
aabb.Unlock();
return tmp;
}
}
| 26.834197 | 132 | 0.659973 | vi3itor |
471442805efde85b3c383ba279797802afbda0c2 | 399 | cc | C++ | source/pkgsrc/audio/terminatorx/patches/patch-src_tX__vtt.cc | Scottx86-64/dotfiles-1 | 51004b1e2b032664cce6b553d2052757c286087d | [
"Unlicense"
] | 1 | 2021-11-20T22:46:39.000Z | 2021-11-20T22:46:39.000Z | source/pkgsrc/audio/terminatorx/patches/patch-src_tX__vtt.cc | Scottx86-64/dotfiles-1 | 51004b1e2b032664cce6b553d2052757c286087d | [
"Unlicense"
] | null | null | null | source/pkgsrc/audio/terminatorx/patches/patch-src_tX__vtt.cc | Scottx86-64/dotfiles-1 | 51004b1e2b032664cce6b553d2052757c286087d | [
"Unlicense"
] | null | null | null | $NetBSD: patch-src_tX__vtt.cc,v 1.1 2019/10/05 12:09:26 nia Exp $
Use standard stdlib.h instead of non-standard malloc.h.
--- src/tX_vtt.cc.orig 2016-07-24 14:24:08.000000000 +0000
+++ src/tX_vtt.cc
@@ -28,7 +28,7 @@
#include "tX_vtt.h"
#include "tX_global.h"
#include <stdio.h>
-#include "malloc.h"
+#include <stdlib.h>
#include <math.h>
#include "tX_mastergui.h"
#include "tX_sequencer.h"
| 24.9375 | 65 | 0.689223 | Scottx86-64 |
4716e91c2c4cc878b6c306d416b0cc1d384e498f | 17,008 | cpp | C++ | vespalib/src/tests/btree/btree-stress/btree_stress_test.cpp | alexeyche/vespa | 7585981b32937d2b13da1a8f94b42c8a0833a4c2 | [
"Apache-2.0"
] | null | null | null | vespalib/src/tests/btree/btree-stress/btree_stress_test.cpp | alexeyche/vespa | 7585981b32937d2b13da1a8f94b42c8a0833a4c2 | [
"Apache-2.0"
] | null | null | null | vespalib/src/tests/btree/btree-stress/btree_stress_test.cpp | alexeyche/vespa | 7585981b32937d2b13da1a8f94b42c8a0833a4c2 | [
"Apache-2.0"
] | null | null | null | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/btree/btree.h>
#include <vespa/vespalib/btree/btreebuilder.h>
#include <vespa/vespalib/btree/btreenodeallocator.h>
#include <vespa/vespalib/btree/btreeroot.h>
#include <vespa/vespalib/btree/btreestore.h>
#include <vespa/vespalib/gtest/gtest.h>
#include <vespa/vespalib/util/lambdatask.h>
#include <vespa/vespalib/util/rand48.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/threadstackexecutor.h>
#include <vespa/vespalib/btree/btreenodeallocator.hpp>
#include <vespa/vespalib/btree/btreenode.hpp>
#include <vespa/vespalib/btree/btreenodestore.hpp>
#include <vespa/vespalib/btree/btreeiterator.hpp>
#include <vespa/vespalib/btree/btreeroot.hpp>
#include <vespa/vespalib/btree/btreebuilder.hpp>
#include <vespa/vespalib/btree/btree.hpp>
#include <vespa/vespalib/btree/btreestore.hpp>
#include <vespa/vespalib/btree/btreeaggregator.hpp>
#include <vespa/vespalib/datastore/atomic_entry_ref.h>
#include <vespa/vespalib/datastore/buffer_type.hpp>
#include <vespa/vespalib/datastore/compaction_spec.h>
#include <vespa/vespalib/datastore/compaction_strategy.h>
#include <vespa/vespalib/datastore/entry_ref_filter.h>
#include <vespa/log/log.h>
LOG_SETUP("btree_stress_test");
using GenerationHandler = vespalib::GenerationHandler;
using RefType = vespalib::datastore::EntryRefT<22>;
using vespalib::btree::NoAggregated;
using vespalib::datastore::AtomicEntryRef;
using vespalib::datastore::CompactionSpec;
using vespalib::datastore::CompactionStrategy;
using vespalib::datastore::EntryRef;
using vespalib::datastore::EntryRefFilter;
using vespalib::makeLambdaTask;
using generation_t = GenerationHandler::generation_t;
namespace {
constexpr uint32_t value_offset = 1000000000;
bool smoke_test = false;
const vespalib::string smoke_test_option = "--smoke-test";
class RealIntStore {
using StoreType = vespalib::datastore::DataStore<uint32_t>;
using StoreRefType = StoreType::RefType;
StoreType _store;
public:
RealIntStore();
~RealIntStore();
EntryRef add(uint32_t value) { return _store.addEntry(value); }
AtomicEntryRef add_relaxed(uint32_t value) { return AtomicEntryRef(add(value)); }
void hold(const AtomicEntryRef& ref) { _store.holdElem(ref.load_relaxed(), 1); }
EntryRef move(EntryRef ref);
void transfer_hold_lists(generation_t gen) { _store.transferHoldLists(gen); }
void trim_hold_lists(generation_t gen) { _store.trimHoldLists(gen); }
uint32_t get(EntryRef ref) const { return _store.getEntry(ref); }
uint32_t get_acquire(const AtomicEntryRef& ref) const { return get(ref.load_acquire()); }
uint32_t get_relaxed(const AtomicEntryRef& ref) const { return get(ref.load_relaxed()); }
std::vector<uint32_t> start_compact();
void finish_compact(std::vector<uint32_t> to_hold);
static constexpr bool is_indirect = true;
static uint32_t get_offset_bits() { return StoreRefType::offset_bits; }
static uint32_t get_num_buffers() { return StoreRefType::numBuffers(); }
bool has_held_buffers() const noexcept { return _store.has_held_buffers(); }
};
RealIntStore::RealIntStore()
: _store()
{
}
RealIntStore::~RealIntStore() = default;
std::vector<uint32_t>
RealIntStore::start_compact()
{
// Use a compaction strategy that will compact all active buffers
CompactionStrategy compaction_strategy(0.0, 0.0, get_num_buffers(), 1.0);
CompactionSpec compaction_spec(true, false);
return _store.startCompactWorstBuffers(compaction_spec, compaction_strategy);
}
void
RealIntStore::finish_compact(std::vector<uint32_t> to_hold)
{
_store.finishCompact(to_hold);
}
EntryRef
RealIntStore::move(EntryRef ref)
{
return add(get(ref));
}
class RealIntStoreCompare
{
const RealIntStore& _store;
uint32_t _lookup_key;
public:
RealIntStoreCompare(const RealIntStore& store, uint32_t lookup_key)
: _store(store),
_lookup_key(lookup_key)
{
}
uint32_t get(EntryRef ref) const {
return (ref.valid() ? _store.get(ref) : _lookup_key);
}
bool operator()(const AtomicEntryRef& lhs, const AtomicEntryRef& rhs) const {
return get(lhs.load_acquire()) < get(rhs.load_acquire());
}
static AtomicEntryRef lookup_key() noexcept { return AtomicEntryRef(); }
const RealIntStoreCompare& get_compare() const noexcept { return *this; }
};
class NoIntStore {
public:
NoIntStore() = default;
~NoIntStore() = default;
static uint32_t add(uint32_t value) noexcept { return value; }
static uint32_t add_relaxed(uint32_t value) noexcept { return value; }
static void hold(uint32_t) noexcept { }
static void transfer_hold_lists(generation_t) noexcept { }
static void trim_hold_lists(generation_t) noexcept { }
static uint32_t get(uint32_t value) noexcept { return value; }
static uint32_t get_acquire(uint32_t value) noexcept { return value; }
static uint32_t get_relaxed(uint32_t value) noexcept { return value; }
static constexpr bool is_indirect = false;
};
class NoIntStoreCompare
{
uint32_t _lookup_key;
public:
NoIntStoreCompare(const NoIntStore&, uint32_t lookup_key)
: _lookup_key(lookup_key)
{
}
bool operator()(uint32_t lhs, uint32_t rhs) const noexcept {
return lhs < rhs;
}
uint32_t lookup_key() const noexcept { return _lookup_key; }
static std::less<uint32_t> get_compare() noexcept { return {}; }
};
}
struct IndirectKeyValueParams {
using IntStore = RealIntStore;
using MyCompare = RealIntStoreCompare;
using MyTree = vespalib::btree::BTree<AtomicEntryRef, AtomicEntryRef, NoAggregated, RealIntStoreCompare>;
};
struct DirectKeyValueParams {
using IntStore = NoIntStore;
using MyCompare = NoIntStoreCompare;
using MyTree = vespalib::btree::BTree<uint32_t, uint32_t>;
};
template <uint32_t divisor, uint32_t remainder>
class ConsiderCompact {
uint32_t _count;
bool _want_compact;
public:
ConsiderCompact()
: _count(0u),
_want_compact(false)
{
}
bool consider(uint32_t idx) {
if ((idx % divisor) == remainder) {
_want_compact = true;
}
return _want_compact;
}
void track_compacted() {
++_count;
_want_compact = false;
}
uint32_t get_count() const noexcept { return _count; }
};
template <typename Params>
class Fixture : public testing::Test
{
protected:
using IntStore = typename Params::IntStore;
using MyCompare = typename Params::MyCompare;
using MyTree = typename Params::MyTree;
using MyTreeIterator = typename MyTree::Iterator;
using MyTreeConstIterator = typename MyTree::ConstIterator;
using KeyStore = IntStore;
using ValueStore = IntStore;
GenerationHandler _generationHandler;
KeyStore _keys;
ValueStore _values;
MyTree _tree;
MyTreeIterator _writeItr;
vespalib::ThreadStackExecutor _writer; // 1 write thread
vespalib::ThreadStackExecutor _readers; // multiple reader threads
vespalib::Rand48 _rnd;
uint32_t _keyLimit;
std::atomic<long> _readSeed;
std::atomic<long> _doneWriteWork;
std::atomic<long> _doneReadWork;
std::atomic<bool> _stopRead;
bool _reportWork;
ConsiderCompact<1000, 0> _compact_tree;
ConsiderCompact<1000, 300> _compact_keys;
ConsiderCompact<1000, 600> _compact_values;
Fixture();
~Fixture() override;
void commit();
bool adjustWriteIterator(uint32_t key);
void insert(uint32_t key);
void remove(uint32_t key);
void compact_tree();
void compact_keys();
void compact_values();
void consider_compact(uint32_t idx);
void readWork(uint32_t cnt);
void readWork();
void writeWork(uint32_t cnt);
void basic_lower_bound();
void single_lower_bound_reader_without_updates();
void single_lower_bound_reader_during_updates();
void multiple_lower_bound_readers_during_updates();
};
template <typename Params>
Fixture<Params>::Fixture()
: testing::Test(),
_generationHandler(),
_tree(),
_writeItr(_tree.begin()),
_writer(1, 128_Ki),
_readers(4, 128_Ki),
_rnd(),
_keyLimit(1000000),
_readSeed(50),
_doneWriteWork(0),
_doneReadWork(0),
_stopRead(false),
_reportWork(false),
_compact_tree(),
_compact_keys(),
_compact_values()
{
_rnd.srand48(32);
}
template <typename Params>
Fixture<Params>::~Fixture()
{
_readers.sync();
_readers.shutdown();
_writer.sync();
_writer.shutdown();
commit();
if (_reportWork) {
LOG(info,
"readWork=%ld, writeWork=%ld",
_doneReadWork.load(), _doneWriteWork.load());
}
}
template <typename Params>
void
Fixture<Params>::commit()
{
auto &allocator = _tree.getAllocator();
allocator.freeze();
auto current_gen = _generationHandler.getCurrentGeneration();
allocator.transferHoldLists(current_gen);
_keys.transfer_hold_lists(current_gen);
_values.transfer_hold_lists(current_gen);
allocator.transferHoldLists(_generationHandler.getCurrentGeneration());
_generationHandler.incGeneration();
auto first_used_gen = _generationHandler.getFirstUsedGeneration();
allocator.trimHoldLists(first_used_gen);
_keys.trim_hold_lists(first_used_gen);
_values.trim_hold_lists(first_used_gen);
}
template <typename Params>
bool
Fixture<Params>::adjustWriteIterator(uint32_t key)
{
MyCompare compare(_keys, key);
if (_writeItr.valid() && _keys.get_relaxed(_writeItr.getKey()) < key) {
_writeItr.binarySeek(compare.lookup_key(), compare.get_compare());
} else {
_writeItr.lower_bound(compare.lookup_key(), compare.get_compare());
}
assert(!_writeItr.valid() || _keys.get_relaxed(_writeItr.getKey()) >= key);
return (_writeItr.valid() && _keys.get_relaxed(_writeItr.getKey()) == key);
}
template <typename Params>
void
Fixture<Params>::insert(uint32_t key)
{
if (!adjustWriteIterator(key)) {
_tree.insert(_writeItr, _keys.add_relaxed(key), _values.add_relaxed(key + value_offset));
} else {
EXPECT_EQ(key + value_offset, _values.get_relaxed(_writeItr.getData()));
}
}
template <typename Params>
void
Fixture<Params>::remove(uint32_t key)
{
if (adjustWriteIterator(key)) {
EXPECT_EQ(key + value_offset, _values.get_relaxed(_writeItr.getData()));
_keys.hold(_writeItr.getKey());
_values.hold(_writeItr.getData());
_tree.remove(_writeItr);
}
}
template <typename Params>
void
Fixture<Params>::compact_tree()
{
// Use a compaction strategy that will compact all active buffers
CompactionStrategy compaction_strategy(0.0, 0.0, RefType::numBuffers(), 1.0);
_tree.compact_worst(compaction_strategy);
_writeItr = _tree.begin();
_compact_tree.track_compacted();
}
template <typename Params>
void
Fixture<Params>::compact_keys()
{
if constexpr (KeyStore::is_indirect) {
auto to_hold = _keys.start_compact();
EntryRefFilter filter(_keys.get_num_buffers(), _keys.get_offset_bits());
filter.add_buffers(to_hold);
auto itr = _tree.begin();
while (itr.valid()) {
auto old_ref = itr.getKey().load_relaxed();
if (filter.has(old_ref)) {
auto new_ref = _keys.move(old_ref);
itr.writeKey(AtomicEntryRef(new_ref));
}
++itr;
}
_keys.finish_compact(std::move(to_hold));
}
_compact_keys.track_compacted();
}
template <typename Params>
void
Fixture<Params>::compact_values()
{
if constexpr (ValueStore::is_indirect) {
auto to_hold = _values.start_compact();
EntryRefFilter filter(_values.get_num_buffers(), _values.get_offset_bits());
filter.add_buffers(to_hold);
auto itr = _tree.begin();
while (itr.valid()) {
auto old_ref = itr.getData().load_relaxed();
if (filter.has(old_ref)) {
auto new_ref = _values.move(old_ref);
itr.getWData().store_release(new_ref);
}
++itr;
}
_values.finish_compact(std::move(to_hold));
}
_compact_values.track_compacted();
}
template <typename Params>
void
Fixture<Params>::consider_compact(uint32_t idx)
{
if (_compact_tree.consider(idx) && !_tree.getAllocator().getNodeStore().has_held_buffers()) {
compact_tree();
}
if constexpr (KeyStore::is_indirect) {
if (_compact_keys.consider(idx) && !_keys.has_held_buffers()) {
compact_keys();
}
}
if constexpr (ValueStore::is_indirect) {
if (_compact_values.consider(idx) && !_values.has_held_buffers()) {
compact_values();
}
}
}
template <typename Params>
void
Fixture<Params>::readWork(uint32_t cnt)
{
vespalib::Rand48 rnd;
rnd.srand48(++_readSeed);
uint32_t i;
uint32_t hits = 0u;
for (i = 0; i < cnt && !_stopRead.load(); ++i) {
auto guard = _generationHandler.takeGuard();
uint32_t key = rnd.lrand48() % (_keyLimit + 1);
MyCompare compare(_keys, key);
MyTreeConstIterator itr = _tree.getFrozenView().lowerBound(compare.lookup_key(), compare.get_compare());
assert(!itr.valid() || _keys.get_acquire(itr.getKey()) >= key);
if (itr.valid() && _keys.get_acquire(itr.getKey()) == key) {
EXPECT_EQ(key + value_offset, _values.get_acquire(itr.getData()));
++hits;
}
}
_doneReadWork += i;
LOG(info, "done %u read work, %u hits", i, hits);
}
template <typename Params>
void
Fixture<Params>::readWork()
{
readWork(std::numeric_limits<uint32_t>::max());
}
template <typename Params>
void
Fixture<Params>::writeWork(uint32_t cnt)
{
vespalib::Rand48 &rnd(_rnd);
for (uint32_t i = 0; i < cnt; ++i) {
consider_compact(i);
uint32_t key = rnd.lrand48() % _keyLimit;
if ((rnd.lrand48() & 1) == 0) {
insert(key);
} else {
remove(key);
}
commit();
}
_doneWriteWork += cnt;
_stopRead = true;
LOG(info, "done %u write work, %u compact tree, %u compact keys, %u compact values", cnt,
_compact_tree.get_count(),
_compact_keys.get_count(),
_compact_values.get_count());
}
template <typename Params>
void
Fixture<Params>::basic_lower_bound()
{
insert(1);
remove(2);
insert(1);
insert(5);
insert(4);
remove(3);
remove(5);
commit();
MyCompare compare(_keys, 3);
auto itr = _tree.getFrozenView().lowerBound(compare.lookup_key(), compare.get_compare());
ASSERT_TRUE(itr.valid());
EXPECT_EQ(4u, _keys.get_acquire(itr.getKey()));
}
template <typename Params>
void
Fixture<Params>::single_lower_bound_reader_without_updates()
{
_reportWork = true;
writeWork(10);
_stopRead = false;
readWork(10);
}
template <typename Params>
void
Fixture<Params>::single_lower_bound_reader_during_updates()
{
uint32_t cnt = smoke_test ? 10000 : 1000000;
_reportWork = true;
_writer.execute(makeLambdaTask([this, cnt]() { writeWork(cnt); }));
_readers.execute(makeLambdaTask([this]() { readWork(); }));
_writer.sync();
_readers.sync();
}
template <typename Params>
void
Fixture<Params>::multiple_lower_bound_readers_during_updates()
{
uint32_t cnt = smoke_test ? 10000 : 1000000;
_reportWork = true;
_writer.execute(makeLambdaTask([this, cnt]() { writeWork(cnt); }));
_readers.execute(makeLambdaTask([this]() { readWork(); }));
_readers.execute(makeLambdaTask([this]() { readWork(); }));
_readers.execute(makeLambdaTask([this]() { readWork(); }));
_readers.execute(makeLambdaTask([this]() { readWork(); }));
_writer.sync();
_readers.sync();
}
template <typename Params>
using BTreeStressTest = Fixture<Params>;
using TestTypes = testing::Types<DirectKeyValueParams, IndirectKeyValueParams>;
VESPA_GTEST_TYPED_TEST_SUITE(BTreeStressTest, TestTypes);
// Disable warnings emitted by gtest generated files when using typed tests
#pragma GCC diagnostic push
#ifndef __clang__
#pragma GCC diagnostic ignored "-Wsuggest-override"
#endif
TYPED_TEST(BTreeStressTest, basic_lower_bound)
{
this->basic_lower_bound();
}
TYPED_TEST(BTreeStressTest, single_lower_bound_reader_without_updates)
{
this->single_lower_bound_reader_without_updates();
}
TYPED_TEST(BTreeStressTest, single_lower_bound_reader_during_updates)
{
this->single_lower_bound_reader_during_updates();
}
TYPED_TEST(BTreeStressTest, multiple_lower_bound_readers_during_updates)
{
this->multiple_lower_bound_readers_during_updates();
}
#pragma GCC diagnostic pop
int main(int argc, char **argv) {
if (argc > 1 && argv[1] == smoke_test_option) {
smoke_test = true;
++argv;
--argc;
}
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 30.371429 | 112 | 0.694673 | alexeyche |
471992f04f7855bfd1d789d6a73137485c4bfa3e | 6,805 | cpp | C++ | src/docks/quadockwidgetperms.cpp | juangburgos/QUaAccessControl | 6a1af53e30fb4e75111312b9bce46b983567049e | [
"MIT"
] | null | null | null | src/docks/quadockwidgetperms.cpp | juangburgos/QUaAccessControl | 6a1af53e30fb4e75111312b9bce46b983567049e | [
"MIT"
] | null | null | null | src/docks/quadockwidgetperms.cpp | juangburgos/QUaAccessControl | 6a1af53e30fb4e75111312b9bce46b983567049e | [
"MIT"
] | 1 | 2021-11-04T21:16:21.000Z | 2021-11-04T21:16:21.000Z | #include "quadockwidgetperms.h"
#include "ui_quadockwidgetperms.h"
#include <QUaAccessControl>
#include <QUaUser>
#include <QUaRole>
#include <QUaPermissions>
#include <QUaPermissionsList>
int QUaDockWidgetPerms::PointerRole = Qt::UserRole + 1;
QUaDockWidgetPerms::QUaDockWidgetPerms(QWidget *parent) :
QWidget(parent),
ui(new Ui::QUaDockWidgetPerms)
{
ui->setupUi(this);
m_deleting = false;
// hide stuff
ui->widgetPermsView->setActionsVisible(false);
ui->widgetPermsView->setIdVisible(false);
ui->widgetPermsView->setAccessReadOnly(true);
// events
QObject::connect(ui->pushButtonShowPerms, &QPushButton::clicked, this, &QUaDockWidgetPerms::showPermsClicked);
QObject::connect(ui->comboBoxPermissions, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &QUaDockWidgetPerms::on_currentIndexChanged);
}
QUaDockWidgetPerms::~QUaDockWidgetPerms()
{
// disable old connections
while (m_connections.count() > 0)
{
QObject::disconnect(m_connections.takeFirst());
}
m_deleting = true;
delete ui;
}
void QUaDockWidgetPerms::setComboModel(QSortFilterProxyModel * proxy)
{
Q_CHECK_PTR(proxy);
// setup combo
ui->comboBoxPermissions->setModel(proxy);
ui->comboBoxPermissions->setEditable(true);
// setup completer
QCompleter *completer = new QCompleter(ui->comboBoxPermissions);
completer->setModel(proxy);
completer->setFilterMode(Qt::MatchContains);
ui->comboBoxPermissions->setCompleter(completer);
ui->comboBoxPermissions->setInsertPolicy(QComboBox::NoInsert);
}
QSortFilterProxyModel * QUaDockWidgetPerms::comboModel() const
{
return qobject_cast<QSortFilterProxyModel*>(ui->comboBoxPermissions->model());
}
QUaPermissions * QUaDockWidgetPerms::permissions() const
{
return ui->comboBoxPermissions->currentData(QUaDockWidgetPerms::PointerRole).value<QUaPermissions*>();
}
void QUaDockWidgetPerms::setPermissions(const QUaPermissions * permissions)
{
QString strId = "";
if (permissions)
{
strId = permissions->getId();
}
auto index = ui->comboBoxPermissions->findText(strId);
Q_ASSERT(index >= 0);
// NOTE : setCurrentText does not work, it does not hold the pointer (userData)
ui->comboBoxPermissions->setCurrentIndex(index);
Q_ASSERT(ui->comboBoxPermissions->currentData(QUaDockWidgetPerms::PointerRole).value<QUaPermissions*>() == permissions);
// populate ui->widgetPermsView
this->bindWidgetPermissionsEdit(permissions);
}
void QUaDockWidgetPerms::on_currentIndexChanged(int index)
{
Q_UNUSED(index);
this->bindWidgetPermissionsEdit(this->permissions());
}
void QUaDockWidgetPerms::clearWidgetPermissionsEdit()
{
ui->widgetPermsView->setId("");
ui->widgetPermsView->setRoleAccessMap(QUaRoleAccessMap());
ui->widgetPermsView->setUserAccessMap(QUaUserAccessMap());
ui->widgetPermsView->setEnabled(false);
}
void QUaDockWidgetPerms::bindWidgetPermissionsEdit(const QUaPermissions * perms)
{
if (!perms)
{
return;
}
// get access control
auto ac = perms->list()->accessControl();
Q_CHECK_PTR(ac);
// disable old connections
while (m_connections.count() > 0)
{
QObject::disconnect(m_connections.takeFirst());
}
// bind common
m_connections <<
QObject::connect(perms, &QObject::destroyed, this,
[this]() {
if (m_deleting)
{
return;
}
// clear widget
this->clearWidgetPermissionsEdit();
});
// roles (all)
QUaRoleAccessMap mapRoles;
auto roles = ac->roles()->roles();
for (auto role : roles)
{
mapRoles[role->getName()] = {
perms->canRoleRead(role),
perms->canRoleWrite(role)
};
}
ui->widgetPermsView->setRoleAccessMap(mapRoles);
// users (all)
QUaUserAccessMap mapUsers;
auto users = ac->users()->users();
for (auto user : users)
{
mapUsers[user->getName()] = {
perms->canUserReadDirectly(user),
perms->canUserWriteDirectly(user),
perms->canRoleRead(user->role()),
perms->canRoleWrite(user->role())
};
}
ui->widgetPermsView->setUserAccessMap(mapUsers);
// role updates
auto updateRole = [this, perms](QUaRole * role) {
// role table
ui->widgetPermsView->updateRoleAccess(
role->getName(),
{ perms->canRoleRead(role), perms->canRoleWrite(role) }
);
// user table
auto users = role->users();
for (auto user : users)
{
ui->widgetPermsView->updateUserAccess(
user->getName(),
{
perms->canUserReadDirectly(user),
perms->canUserWriteDirectly(user),
perms->canRoleRead(user->role()),
perms->canRoleWrite(user->role())
}
);
}
};
m_connections << QObject::connect(perms, &QUaPermissions::canReadRoleAdded , this, updateRole, Qt::QueuedConnection);
m_connections << QObject::connect(perms, &QUaPermissions::canReadRoleRemoved , this, updateRole, Qt::QueuedConnection);
m_connections << QObject::connect(perms, &QUaPermissions::canWriteRoleAdded , this, updateRole, Qt::QueuedConnection);
m_connections << QObject::connect(perms, &QUaPermissions::canWriteRoleRemoved, this, updateRole, Qt::QueuedConnection);
// user updates
auto updateUser = [this, perms](QUaUser * user) {
ui->widgetPermsView->updateUserAccess(
user->getName(),
{
perms->canUserReadDirectly (user),
perms->canUserWriteDirectly(user),
perms->canRoleRead (user->role()),
perms->canRoleWrite(user->role())
}
);
};
m_connections << QObject::connect(perms, &QUaPermissions::canReadUserAdded , this, updateUser, Qt::QueuedConnection);
m_connections << QObject::connect(perms, &QUaPermissions::canReadUserRemoved , this, updateUser, Qt::QueuedConnection);
m_connections << QObject::connect(perms, &QUaPermissions::canWriteUserAdded , this, updateUser, Qt::QueuedConnection);
m_connections << QObject::connect(perms, &QUaPermissions::canWriteUserRemoved, this, updateUser, Qt::QueuedConnection);
// user changes role
for (auto user : users)
{
m_connections << QObject::connect(user, &QUaUser::roleChanged, this,
[updateUser, user]() {
updateUser(user);
}, Qt::QueuedConnection);
}
// on user or role added/removed
auto resetPermsWidget = [this, perms]() {
this->bindWidgetPermissionsEdit(perms);
};
// NOTE : queued to wait until user/role has name or has actually been deleted
m_connections << QObject::connect(ac->roles(), &QUaRoleList::roleAdded , perms, resetPermsWidget, Qt::QueuedConnection);
m_connections << QObject::connect(ac->roles(), &QUaRoleList::roleRemoved, perms, resetPermsWidget, Qt::QueuedConnection);
m_connections << QObject::connect(ac->users(), &QUaUserList::userAdded , perms, resetPermsWidget, Qt::QueuedConnection);
m_connections << QObject::connect(ac->users(), &QUaUserList::userRemoved, perms, resetPermsWidget, Qt::QueuedConnection);
}
| 32.716346 | 148 | 0.714622 | juangburgos |
471d40609c336608934ef13cc447ef7eac67c3e5 | 987 | cpp | C++ | programs/decisions and loops/04_Quadratic_equation.cpp | MKrishan21/learn-cpp | 55f6fbccf97fc73e5d6081372a5ebda75f2a98d7 | [
"Apache-2.0"
] | null | null | null | programs/decisions and loops/04_Quadratic_equation.cpp | MKrishan21/learn-cpp | 55f6fbccf97fc73e5d6081372a5ebda75f2a98d7 | [
"Apache-2.0"
] | 1 | 2022-03-20T17:08:50.000Z | 2022-03-30T17:54:30.000Z | programs/decisions and loops/04_Quadratic_equation.cpp | MKrishan21/learn-cpp | 55f6fbccf97fc73e5d6081372a5ebda75f2a98d7 | [
"Apache-2.0"
] | null | null | null | // C++ Program to Find Quotient and Remainder
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float a, b, c, x1, x2, discriminant, x3, x4;
cout << "enter the coefficients a b & c ";
cin >> a >> b >> c;
discriminant = b * b - 4 * a * c;
if (discriminant > 0)
{
x1 = (-b + sqrt(discriminant)) / (2 * a);
x2 = (-b - sqrt(discriminant)) / (2 * a);
cout << "Roots are real and different. " << endl;
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
}
else if (discriminant == 0)
{
cout << "Roots are real & same. ";
x1 = -b / (2 * a);
cout << "x1 = x2 i.e " << x1 << endl;
}
else
{
x3 = -b / (2 * a);
x4 = sqrt(-discriminant) / (2 * a);
cout << "Roots are complex & different. ";
cout << "x1 = " << x3 << "+" << x4 << "i" << endl;
cout << "x2 = " << x3 << "-" << x4 << "i" << endl;
}
return 0;
} | 27.416667 | 58 | 0.435664 | MKrishan21 |
471dac63a76024e82d07bb1d66f3cc2550743223 | 1,646 | cpp | C++ | Graphs/01-Matrix-542.cpp | devangi2000/Data-Structures-Algorithms-Handbook | ce0f00de89af5da7f986e65089402dc6908a09b5 | [
"MIT"
] | 38 | 2021-10-14T09:36:53.000Z | 2022-01-27T02:36:19.000Z | Graphs/01-Matrix-542.cpp | devangi2000/Data-Structures-Algorithms-Handbook | ce0f00de89af5da7f986e65089402dc6908a09b5 | [
"MIT"
] | null | null | null | Graphs/01-Matrix-542.cpp | devangi2000/Data-Structures-Algorithms-Handbook | ce0f00de89af5da7f986e65089402dc6908a09b5 | [
"MIT"
] | 4 | 2021-12-06T15:47:12.000Z | 2022-02-04T04:25:00.000Z | // Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
// The distance between two adjacent cells is 1.
// Example 1:
// Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
// Output: [[0,0,0],[0,1,0],[0,0,0]]
// Example 2:
// Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
// Output: [[0,0,0],[0,1,0],[1,2,1]]
// Constraints:
// m == mat.length
// n == mat[i].length
// 1 <= m, n <= 104
// 1 <= m * n <= 104
// mat[i][j] is either 0 or 1.
// There is at least one 0 in mat.
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat){
if(mat.size() == 0) return mat;
vector<vector<int>> dirs = {{-1,0}, {1,0}, {0,1}, {0,-1}};
queue<pair<int, int>> q;
for(int i=0; i<mat.size(); ++i){
for(int j=0; j<mat[0].size(); ++j){
if(mat[i][j] == 0)
q.emplace(i, j);
else mat[i][j] = INT_MAX;
}
}
while(!q.empty()){
auto curr = q.front();
q.pop();
int x = curr.first;
int y = curr.second;
for(auto dir:dirs){
int newx = x + dir[0];
int newy = y + dir[1];
if(newx >=0 and newx < mat.size() and newy >=0 and newy < mat[0].size()){
if(mat[newx][newy] > mat[x][y] + 1){
mat[newx][newy] = mat[x][y] + 1;
q.emplace(newx, newy);
}
}
}
}
return mat;
}
};
| 29.392857 | 90 | 0.40158 | devangi2000 |
471ed406bdae8204c546e0c8b0f1151b07d33bb1 | 1,942 | hpp | C++ | libs/parse/include/fcppt/parse/make_convert_if.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/parse/include/fcppt/parse/make_convert_if.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/parse/include/fcppt/parse/make_convert_if.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_PARSE_MAKE_CONVERT_IF_HPP_INCLUDED
#define FCPPT_PARSE_MAKE_CONVERT_IF_HPP_INCLUDED
#include <fcppt/function_impl.hpp>
#include <fcppt/either/failure_type.hpp>
#include <fcppt/either/success_type.hpp>
#include <fcppt/parse/convert_if_impl.hpp>
#include <fcppt/parse/result_of.hpp>
#include <fcppt/type_traits/remove_cv_ref_t.hpp>
#include <fcppt/type_traits/value_type.hpp>
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <utility>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace parse
{
template<
typename Parser,
typename Convert
>
fcppt::parse::convert_if<
fcppt::type_traits::value_type<
fcppt::type_traits::value_type<
fcppt::either::failure_type<
std::result_of_t<
Convert(
fcppt::parse::result_of<
Parser
> &&
)
>
>
>
>,
fcppt::type_traits::remove_cv_ref_t<
Parser
>,
fcppt::either::success_type<
std::result_of_t<
Convert(
fcppt::parse::result_of<
Parser
> &&
)
>
>
>
make_convert_if(
Parser &&_parser,
Convert &&_convert
)
{
typedef
std::result_of_t<
Convert(
fcppt::parse::result_of<
Parser
> &&
)
>
result_type;
return
fcppt::parse::convert_if<
fcppt::type_traits::value_type<
fcppt::type_traits::value_type<
fcppt::either::failure_type<
result_type
>
>
>,
fcppt::type_traits::remove_cv_ref_t<
Parser
>,
fcppt::either::success_type<
result_type
>
>{
std::forward<
Parser
>(
_parser
),
fcppt::function<
result_type(
fcppt::parse::result_of<
Parser
> &&
)
>{
std::forward<
Convert
>(
_convert
)
}
};
}
}
}
#endif
| 16.886957 | 61 | 0.659114 | pmiddend |
47231b8910539119531cb2f3c6b5034866a68708 | 638 | cpp | C++ | src/executor/Executor.cpp | Charlieglider/machinery1 | 1d085634ecbb1cd69d920a92f71dd0fece659e1a | [
"Unlicense"
] | 1 | 2018-06-12T21:48:53.000Z | 2018-06-12T21:48:53.000Z | src/executor/Executor.cpp | chpap/machinery | 63130ccbe91339cadbdb0c3df3b6eea4da575403 | [
"Unlicense"
] | null | null | null | src/executor/Executor.cpp | chpap/machinery | 63130ccbe91339cadbdb0c3df3b6eea4da575403 | [
"Unlicense"
] | null | null | null | #include "Executor.h"
namespace kerberos
{
SequenceInterval::SequenceInterval(IntegerTypeArray & integers)
{
m_count = 0;
m_times = integers[0].first;
m_boundery = integers[1].first;
m_increase = m_boundery / m_times;
}
bool SequenceInterval::operator()()
{
m_count = (m_count+1) % m_boundery;
if (m_count % m_increase == 0)
{
return true;
}
return false;
}
TimeInterval::TimeInterval(IntegerTypeArray & integers)
{
}
bool TimeInterval::operator()()
{
return true;
}
} | 19.333333 | 67 | 0.540752 | Charlieglider |
472860cd6fcb7a90a6937d5c2e920d41e1edc0d6 | 719 | cpp | C++ | lucas/uri/1171.cpp | medeiroslucas/lo-and-behold-pp | d2be16f9b108b501fd9fccf173e741c93350cee4 | [
"MIT"
] | 2 | 2019-09-09T00:34:40.000Z | 2019-09-09T17:35:19.000Z | lucas/uri/1171.cpp | medeiroslucas/lo-and-behold-pp | d2be16f9b108b501fd9fccf173e741c93350cee4 | [
"MIT"
] | null | null | null | lucas/uri/1171.cpp | medeiroslucas/lo-and-behold-pp | d2be16f9b108b501fd9fccf173e741c93350cee4 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main(){
int N, i, min=2001, numanterior=0, cont=0;
int *numeros;
cin >> N;
numeros = (int *) malloc(N*sizeof(int));
for(i = 0; i<N; i++){
cin >> *(numeros+i);
}
while(1){
cont = 0;
for(i=0; i<N; i++){
if(*(numeros+i) < min && *(numeros+i) > numanterior){
min = *(numeros+i);
cont = 1;
}
else if(*(numeros+i) == min){
cont++;
}
}
if(min == 2001)return 0;
cout << min << " aparece " << cont << " vez(es)" << endl;
numanterior = min;
min = 2001;
}
return 0;
} | 15.630435 | 65 | 0.399166 | medeiroslucas |
472b5aa45fc445c60ce659738518699eb6d9bc7b | 671 | hpp | C++ | cpp/include/gecko/signals.hpp | MomsFriendlyRobotCompany/gecko | f340381113bdb423a39d47aaee61e013bb9e002a | [
"MIT"
] | 2 | 2020-03-11T03:53:19.000Z | 2020-10-06T03:18:32.000Z | cpp/include/gecko/signals.hpp | MomsFriendlyRobotCompany/gecko | f340381113bdb423a39d47aaee61e013bb9e002a | [
"MIT"
] | null | null | null | cpp/include/gecko/signals.hpp | MomsFriendlyRobotCompany/gecko | f340381113bdb423a39d47aaee61e013bb9e002a | [
"MIT"
] | null | null | null | /**************************************************\
* The MIT License (MIT)
* Copyright (c) 2014 Kevin Walchko
* see LICENSE for full details
\**************************************************/
#pragma once
/*
This class captures the SIGINT signal and sets ok to false. Since ok is
static, any class that inherits this will see the status change and
allow it close down cleanly.
*/
class SigCapture {
public:
SigCapture();
static void my_handler(int s); // signal handler function
void on(); // turn on
void shutdown(); // turn off
// protected:
static bool ok; // global status on if a SIGINT has occured
bool enabled;
};
| 27.958333 | 72 | 0.57079 | MomsFriendlyRobotCompany |
472bf849153eac1a2753ad985cc015407da3743d | 8,613 | cpp | C++ | cegui/src/RenderTarget.cpp | cbeck88/cegui-mirror | 50d3a670b22fd957eba06549a9a7e04796d0b92f | [
"MIT"
] | null | null | null | cegui/src/RenderTarget.cpp | cbeck88/cegui-mirror | 50d3a670b22fd957eba06549a9a7e04796d0b92f | [
"MIT"
] | null | null | null | cegui/src/RenderTarget.cpp | cbeck88/cegui-mirror | 50d3a670b22fd957eba06549a9a7e04796d0b92f | [
"MIT"
] | 1 | 2020-07-21T00:03:01.000Z | 2020-07-21T00:03:01.000Z | /***********************************************************************
created: Sat Feb 18 2012
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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 "CEGUI/RenderTarget.h"
#include "CEGUI/Renderer.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RenderQueue.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/glm.hpp>
#if (GLM_VERSION_MAJOR == 0 && GLM_VERSION_MINOR <= 9 && GLM_VERSION_PATCH <= 3)
#include <glm/gtx/constants.hpp>
#else
#include <glm/gtc/constants.hpp>
#endif
#include <glm/gtc/type_ptr.hpp>
namespace CEGUI
{
//----------------------------------------------------------------------------//
const String RenderTarget::EventNamespace("RenderTarget");
const String RenderTarget::EventAreaChanged("AreaChanged");
//----------------------------------------------------------------------------//
RenderTarget::RenderTarget():
d_activationCounter(0),
d_area(0, 0, 0, 0),
d_matrixValid(false),
d_matrix(1.0f),
d_viewDistance(0),
d_fovY(glm::radians(30.0f))
{
// Call the setter function to ensure that the half-angle tangens value is set correctly
setFovY(d_fovY);
}
//----------------------------------------------------------------------------//
RenderTarget::~RenderTarget()
{}
//----------------------------------------------------------------------------//
void RenderTarget::activate()
{
Renderer& owner = getOwner();
owner.setActiveRenderTarget(this);
++d_activationCounter;
if(d_activationCounter == 0)
owner.invalidateGeomBufferMatrices(this);
}
//----------------------------------------------------------------------------//
void RenderTarget::deactivate()
{
}
//----------------------------------------------------------------------------//
void RenderTarget::draw(const GeometryBuffer& buffer)
{
buffer.draw();
}
//----------------------------------------------------------------------------//
void RenderTarget::draw(const RenderQueue& queue)
{
queue.draw();
}
//----------------------------------------------------------------------------//
unsigned int RenderTarget::getActivationCounter() const
{
return d_activationCounter;
}
//----------------------------------------------------------------------------//
void RenderTarget::setArea(const Rectf& area)
{
d_area = area;
d_matrixValid = false;
RenderTargetEventArgs args(this);
fireEvent(RenderTarget::EventAreaChanged, args);
}
//----------------------------------------------------------------------------//
const Rectf& RenderTarget::getArea() const
{
return d_area;
}
//----------------------------------------------------------------------------//
glm::mat4 RenderTarget::createViewProjMatrixForOpenGL() const
{
const float w = d_area.getWidth();
const float h = d_area.getHeight();
// We need to check if width or height are zero and act accordingly to prevent running into issues
// with divisions by zero which would lead to undefined values, as well as faulty clipping planes
// This is mostly important for avoiding asserts
const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);
const float aspect = widthAndHeightNotZero ? w / h : 1.0f;
const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;
const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;
RenderTarget::d_viewDistance = midx / (aspect * RenderTarget::d_fovY_halftan);
glm::vec3 eye = glm::vec3(midx, midy, -RenderTarget::d_viewDistance);
glm::vec3 center = glm::vec3(midx, midy, 1);
glm::vec3 up = glm::vec3(0, -1, 0);
// Creating the perspective projection matrix based on an assumed vertical FOV angle
// Older glm versions use degrees (Unless radians are forced via GLM_FORCE_RADIANS). Newer versions of glm exlusively use radians.
// We need to convert the angle for older versions
#if (GLM_VERSION_MAJOR == 0 && GLM_VERSION_MINOR <= 9 && GLM_VERSION_PATCH < 6) && (!defined(GLM_FORCE_RADIANS))
glm::mat4 projectionMatrix = glm::perspective(glm::degrees(d_fovY), aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0));
#else
glm::mat4 projectionMatrix = glm::perspective(d_fovY, aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0));
#endif
// Creating the view matrix based on the eye, center and up vectors targeting the middle of the screen
glm::mat4 viewMatrix = glm::lookAt(eye, center, up);
return projectionMatrix * viewMatrix;
}
//----------------------------------------------------------------------------//
glm::mat4 RenderTarget::createViewProjMatrixForDirect3D() const
{
const float w = d_area.getWidth();
const float h = d_area.getHeight();
// We need to check if width or height are zero and act accordingly to prevent running into issues
// with divisions by zero which would lead to undefined values, as well as faulty clipping planes
// This is mostly important for avoiding asserts
const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f);
const float aspect = widthAndHeightNotZero ? w / h : 1.0f;
const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f;
const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f;
RenderTarget::d_viewDistance = midx / (aspect * RenderTarget::d_fovY_halftan);
glm::vec3 eye = glm::vec3(midx, midy, -d_viewDistance);
glm::vec3 center = glm::vec3(midx, midy, 1);
glm::vec3 up = glm::vec3(0, -1, 0);
// We need to have a projection matrix with its depth in clip space ranging from 0 to 1 for nearclip to farclip.
// The regular OpenGL projection matrix would work too, but we would lose 1 bit of depth precision, which the following
// manually filled matrix should fix:
const float fovy = 30.f;
const float zNear = RenderTarget::d_viewDistance * 0.5f;
const float zFar = RenderTarget::d_viewDistance * 2.0f;
const float f = 1.0f / std::tan(fovy * glm::pi<float>() * 0.5f / 180.0f);
const float Q = zFar / (zNear - zFar);
float projectionMatrixFloat[16] =
{
f/aspect, 0.0f, 0.0f, 0.0f,
0.0f, f, 0.0f, 0.0f,
0.0f, 0.0f, Q, -1.0f,
0.0f, 0.0f, Q * zNear, 0.0f
};
glm::mat4 projectionMatrix = glm::make_mat4(projectionMatrixFloat);
// Projection matrix abuse!
glm::mat4 viewMatrix = glm::lookAt(eye, center, up);
return projectionMatrix * viewMatrix;
}
//----------------------------------------------------------------------------//
void RenderTarget::updateMatrix(const glm::mat4& matrix) const
{
d_matrix = matrix;
d_matrixValid = true;
//! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices
d_activationCounter = -1;
}
//----------------------------------------------------------------------------//
float RenderTarget::getFovY() const
{
return d_fovY;
}
//----------------------------------------------------------------------------//
void RenderTarget::setFovY(const float fovY)
{
d_fovY = fovY;
d_fovY_halftan = std::tan(fovY * 0.5f);
}
}
| 38.450893 | 138 | 0.564728 | cbeck88 |
472ec7e2931ae78bb65dabb8973dfac45545236e | 2,242 | cpp | C++ | src/vpg/memory/pool.cpp | RiscadoA/voxel-platformer | 4e7aadad978c333a59f452a8ee9f4612ee128614 | [
"MIT"
] | 3 | 2021-03-01T16:00:04.000Z | 2022-01-07T03:45:32.000Z | src/vpg/memory/pool.cpp | RiscadoA/voxel-platformer | 4e7aadad978c333a59f452a8ee9f4612ee128614 | [
"MIT"
] | null | null | null | src/vpg/memory/pool.cpp | RiscadoA/voxel-platformer | 4e7aadad978c333a59f452a8ee9f4612ee128614 | [
"MIT"
] | 2 | 2021-03-27T03:54:24.000Z | 2021-06-22T13:53:07.000Z | #include <vpg/memory/pool.hpp>
#include <cstring>
#include <cstdlib>
using namespace vpg::memory;
Pool<void>::Pool(size_t initial_count, size_t element_sz, std::align_val_t alignment) {
this->used = 0;
this->total = initial_count;
this->element_sz = element_sz;
this->alignment = alignment;
if ((size_t)this->alignment > this->element_sz) {
this->element_sz = (size_t)this->alignment;
}
else if (this->element_sz % (size_t)this->alignment != 0) {
this->element_sz = (this->element_sz / (size_t)this->alignment + 1) * (size_t)this->alignment;
}
this->data = operator new(this->total * this->element_sz + this->total, this->alignment);
this->state = (char*)this->data + this->total * this->element_sz;
memset(this->state, 0, this->total);
}
Pool<void>::Pool(Pool&& rhs) {
this->used = rhs.used;
this->total = rhs.total;
this->element_sz = rhs.element_sz;
this->alignment = rhs.alignment;
this->data = rhs.data;
rhs.data = nullptr;
}
Pool<void>::~Pool() {
if (this->data != nullptr) {
operator delete(this->data, this->alignment);
}
}
size_t Pool<void>::alloc() {
if (this->used < this->total) {
this->used += 1;
for (size_t i = 0; i < this->total; ++i) {
if (this->state[i] == 0) {
this->state[i] = 1;
return i;
}
}
abort(); // Unreachable
}
else {
this->used += 1;
// Expand pool
auto old_total = this->total;
this->total *= 2;
void* new_data = operator new(this->total * this->element_sz + this->total, this->alignment);
this->state = (char*)this->data + this->total * this->element_sz;
memset(this->state, 1, old_total + 1);
memset(this->state + old_total + 1, 0, total - old_total - 1);
memcpy(new_data, this->data, this->total * this->element_sz);
operator delete(this->data, this->alignment);
this->data = new_data;
return old_total;
}
}
void Pool<void>::free(size_t index) {
this->state[index] = 0;
}
bool vpg::memory::Pool<void>::has_element(size_t index) {
return index < this->total && this->state[index] != 0;
}
| 28.74359 | 102 | 0.582516 | RiscadoA |
472fb0726c07927da19c9f66ab94225b1d4655c6 | 1,259 | cpp | C++ | Catch2Demo/CalculatorSumTests.cpp | Zilleplus/cppTestFrameworkDemos | ccb1cc9e8d9f7e4243b720a3f8355d258caf56c1 | [
"MIT"
] | null | null | null | Catch2Demo/CalculatorSumTests.cpp | Zilleplus/cppTestFrameworkDemos | ccb1cc9e8d9f7e4243b720a3f8355d258caf56c1 | [
"MIT"
] | null | null | null | Catch2Demo/CalculatorSumTests.cpp | Zilleplus/cppTestFrameworkDemos | ccb1cc9e8d9f7e4243b720a3f8355d258caf56c1 | [
"MIT"
] | null | null | null | #include "catch.hpp"
#include "RealCalculator.h"
TEST_CASE("Test sum of two real numbers", "[Calculator]")
{
RealCalculator calculator;
SECTION("Add 2 numbers")
{
REQUIRE(calculator.calculate(1,2,SUM)==3.0);
}
}
TEST_CASE("Generators") {
auto i = GENERATE(1, 2, 3);
auto j = GENERATE(3, 2, 1);
RealCalculator calculator;
SECTION("Sum of posssive is always possive") {
REQUIRE(0 <= calculator.calculate(i,j,SUM));
}
}
TEST_CASE("parameter based SUM test")
{
RealCalculator calculator;
for (const auto[left, right,result] : {
std::make_tuple(1, 2,3),
std::make_tuple(2, 4,6),
std::make_tuple(3, 6,9),
std::make_tuple(4, 8,12),
})
{
SECTION("SUM OF " + std::to_string(left) +"and "+ std::to_string(right))
{
CHECK(calculator.calculate(left,right,SUM)==result);
}
}
}
TEMPLATE_TEST_CASE("Generic parameter based SUM test","Calculator<T> tests",int,float)
{
RealCalculator calculator;
for (const auto[left, right, result] : {
std::make_tuple(1, 2,3),
std::make_tuple(2, 4,6),
std::make_tuple(3, 6,9),
std::make_tuple(4, 8,12),
})
{
SECTION("SUM OF " + std::to_string(left) + "and " + std::to_string(right))
{
CHECK(calculator.calculate(left, right, SUM) == result);
}
}
}
| 21.338983 | 86 | 0.641779 | Zilleplus |
47309395d715106960a581d984116c4e00f25402 | 3,485 | hpp | C++ | source/AsioExpress/EventHandling/ResourceCachePrivate/AddResourceItemsProcessor.hpp | suhao/asioexpress | 2f3453465934afdcdf4a575a2d933d86929b23c7 | [
"BSL-1.0"
] | null | null | null | source/AsioExpress/EventHandling/ResourceCachePrivate/AddResourceItemsProcessor.hpp | suhao/asioexpress | 2f3453465934afdcdf4a575a2d933d86929b23c7 | [
"BSL-1.0"
] | null | null | null | source/AsioExpress/EventHandling/ResourceCachePrivate/AddResourceItemsProcessor.hpp | suhao/asioexpress | 2f3453465934afdcdf4a575a2d933d86929b23c7 | [
"BSL-1.0"
] | null | null | null | // Copyright Ross MacGregor 2013
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <map>
#include <algorithm>
#include <boost/shared_ptr.hpp>
#include "AsioExpressError/CatchMacros.hpp"
#include "AsioExpress/UniqueId.hpp"
#include "AsioExpress/DebugTimer/DebugTimerMacros.hpp"
#include "AsioExpress/CompletionHandler.hpp"
#include "AsioExpress/Coroutine.hpp"
#include "AsioExpress/Yield.hpp"
namespace AsioExpress {
namespace ResourceCachePrivate {
template<typename ResourceItem, typename Key>
class AddResourceItemsProcessor : private AsioExpress::Coroutine
{
public:
typedef boost::shared_ptr<ResourceItem> ResourceItemPointer;
typedef boost::function<void (Key key, ResourceItemPointer item, CompletionHandler completionHandler)> AsyncRemoveFunction;
typedef ResourceCachePrivate::CacheRequest<ResourceItem, Key> Request;
typedef boost::shared_ptr<Request> RequestPointer;
typedef std::vector<Request> Requests;
typedef boost::shared_ptr<Requests> RequestsPointer;
typedef std::map<Key,int> ItemCount;
typedef boost::shared_ptr<ItemCount> ItemCountPointer;
AddResourceItemsProcessor(
Key key,
RequestsPointer requests,
ItemCountPointer itemCount,
AsyncRemoveFunction removeFunction,
CompletionHandler errorHandler) :
m_processorId("AddResourceItemsProcessor"),
m_key(key),
m_request(new Request),
m_requests(requests),
m_itemCount(itemCount),
m_removeFunction(removeFunction),
m_errorHandler(errorHandler)
{
}
void operator()(
AsioExpress::Error error = AsioExpress::Error())
{
try
{
STATEMENT_DEBUG_TIMER(m_processorId, __FILE__, this->GetCurrentLine());
REENTER(this)
{
while ((*m_itemCount)[m_key] > 0)
{
// remove request from queue if available
{
typename Requests::iterator r = std::find(
m_requests->begin(),
m_requests->end(),
m_key);
if (r == m_requests->end())
{
// no requests waiting.
break;
}
*m_request = *r;
m_requests->erase(r);
}
YIELD
{
--(*m_itemCount)[m_key];
m_removeFunction(m_key, m_request->item, *this);
}
// call completion handler
m_request->completionHandler(error);
m_request->completionHandler = 0;
}
OnExit(error);
}//REENTER
}
ASIOEXPRESS_CATCH_ERROR_AND_DO(OnExit(error))
}
private:
void OnExit(AsioExpress::Error const & error)
{
REMOVE_STATEMENT_DEBUG_TIMER(m_processorId, __FILE__, __LINE__);
if (error)
m_errorHandler(error);
}
AsioExpress::UniqueId m_processorId;
Key m_key;
RequestPointer m_request;
RequestsPointer m_requests;
ItemCountPointer m_itemCount;
AsyncRemoveFunction m_removeFunction;
CompletionHandler m_errorHandler;
};
} // namespace ResourceCachePrivate
} // namespace AsioExpress
| 30.304348 | 128 | 0.613199 | suhao |
473ddd7ed441686f935bd2f047b8e26dd205f682 | 10,542 | hpp | C++ | src/mods/FileEditor.hpp | youwereeatenbyalid/dx11_mod_base | c9c31426261c793e34a5b7ff1a15598777691ba5 | [
"MIT"
] | 2 | 2021-03-25T20:27:49.000Z | 2022-03-29T13:00:31.000Z | src/mods/FileEditor.hpp | youwereeatenbyalid/dx11_mod_base | c9c31426261c793e34a5b7ff1a15598777691ba5 | [
"MIT"
] | null | null | null | src/mods/FileEditor.hpp | youwereeatenbyalid/dx11_mod_base | c9c31426261c793e34a5b7ff1a15598777691ba5 | [
"MIT"
] | 2 | 2021-02-20T13:42:25.000Z | 2022-03-26T16:05:47.000Z | #pragma once
#include <map>
#include <filesystem>
#include <fstream>
#include <sstream>
#include "Mod.hpp"
#include "sdk/ReClass.hpp"
#include "mods/LDK.hpp"
#include "mods/SpardaWorkshop.hpp"
#include "mods/BpStageJump.hpp"
// clang-format off
namespace fs = std::filesystem;
class HotSwapCFG {
public:
HotSwapCFG(fs::path cfg_path);
HotSwapCFG(HotSwapCFG& other) = delete;
HotSwapCFG(HotSwapCFG&& other) = delete;
~HotSwapCFG() = default;
std::string get_name() const { return m_mod_name; }
std::string get_main_name() const { return m_main_name; }
std::optional<std::string> get_description() const { return m_description; }
std::optional<std::string> get_version() const { return m_version; }
std::optional<std::string> get_author() const { return m_author; }
std::optional<int> get_character() const {return m_character;}
private:
static enum class StringValue : const uint8_t {
ev_null,
ev_mod_name,
ev_description,
ev_version,
ev_author,
ev_character
};
static enum class CharacterValue : const uint8_t {
ev_null,
ev_nero,
ev_dante,
ev_v,
ev_vergil
};
std::map<std::string, StringValue> m_variable_map;
std::map<std::string, CharacterValue> m_char_name_map;
private:
void process_line(std::string variable, std::string value);
std::string str_to_lower(std::string s) {
::std::transform(s.begin(), s.end(), s.begin(), ::tolower);
return s;
}
private:
fs::path m_cfg_path;
std::string m_mod_name;
std::string m_main_name;
std::optional<std::string> m_description;
std::optional<std::string> m_version;
std::optional<std::string> m_author;
std::optional<uint8_t> m_character;
friend class FileEditor;
};
class FileEditor : public Mod {
public:
FileEditor();
~FileEditor() = default;
// mod name string for config
std::string_view get_name() const override { return "AssetSwapper"; }
std::string get_checkbox_name() override { return m_check_box_name; };
std::string get_hotkey_name() override { return m_hot_key_name; };
static bool m_is_active;
// called by m_mods->init() you'd want to override this
std::optional<std::string> on_initialize() override;
// Override this things if you want to store values in the config file
void on_config_load(const utility::Config& cfg) override;
void on_config_save(utility::Config& cfg) override;
// on_frame() is called every frame regardless whether the gui shows up.
void on_frame() override;
// on_draw_ui() is called only when the gui shows up
// you are in the imgui window here.
void on_draw_ui() override;
// on_draw_debug_ui() is called when debug window shows up
void on_draw_debug_ui() override;
private:
// Forward declration because I like to keep my structs at the end of the class
struct Costume_List_t;
struct Char_Default_Costume_Info;
// function hook instance for our detour, convinient wrapper
// around minhook
void init_check_box_info() override;
std::vector<char> m_costume_list_container;
static uint64_t m_original_costume_count;
static uint32_t get_costume_list_size(uint32_t character, uint64_t original_size);
static uintptr_t m_costume_list_size_addr;
static uintptr_t m_scroll_list_jmp_ret;
static uintptr_t m_costume_list_jmp_ret;
static uintptr_t m_costume_list_jnl_ret;
//static uintptr_t costume_select_jmp_ret;
static Costume_List_t* m_new_costume_list_p;
static std::optional<Char_Default_Costume_Info> m_selected_char_costume_info;
static uint32_t m_nero_costume_count;
static uint32_t m_nero_last_og_costume_count;
static bool m_nero_csize;
static uint32_t m_dante_costume_count;
static uint32_t m_dante_last_og_costume_count;
static bool m_dante_csize;
static uint32_t m_gilver_costume_count;
static uint32_t m_gilver_last_og_costume_count;
static bool m_gilver_csize;
static uint32_t m_vergil_costume_count;
static uint32_t m_vergil_last_og_costume_count;
static bool m_vergil_csize;
static uint32_t m_selected_character;
static bool m_is_in_select_menu;
// Showing the checkbox for the Super/EX costumes
bool m_show_costume_options;
static bool m_load_super;
static bool m_load_ex;
static naked void scroll_list_detour();
static naked void costume_list_detour();
// Saving a copy of the config data so we can use it for our own stuff after the first time the load function was called
std::optional<utility::Config> m_config;
// Actual hooks
std::unique_ptr<FunctionHook> m_file_loader_hook{};
std::unique_ptr<FunctionHook> m_costume_list_maker_hook{};
std::unique_ptr<FunctionHook> m_selected_costume_processor_hook{};
std::unique_ptr<FunctionHook> m_ui_costume_name_hook{};
// asm detours
std::unique_ptr<FunctionHook> m_scroll_list_hook{};
std::unique_ptr<FunctionHook> m_costume_list_hook{};
//Real men's hooks
static void* __fastcall file_loader_internal(uintptr_t this_p, uintptr_t RDX, const wchar_t* file_path);
void* __fastcall file_loader(uintptr_t this_p, uintptr_t RDX, const wchar_t* file_path);
static void __fastcall costume_list_maker_internal(uintptr_t RCX, uintptr_t ui2120GUI);
void __fastcall costume_list_maker(uintptr_t RCX, uintptr_t ui2120GUI);
static void __fastcall selected_costume_processor_internal(uintptr_t RCX, uintptr_t ui2120GUI);
void __fastcall selected_costume_processor(uintptr_t RCX, uintptr_t ui2120GUI);
static UI_String_t* __fastcall ui_costume_name_internal(uintptr_t RCX, uintptr_t RDX, uint32_t costume_id);
UI_String_t* __fastcall ui_costume_name(uintptr_t RCX, uintptr_t RDX, uint32_t costume_id);
void load_mods();
void load_sys_mods();
void bind_sys_mod(std::string modname, bool* on_value);
inline bool asset_check(const wchar_t* game_path, const wchar_t* mod_path) const;
private: // structs
struct Asset_Path{
/*const wchar_t* org_path;
const wchar_t* new_path;*/
std::wstring org_path;
std::wstring new_path;
};
struct Asset_Hotswap{
bool is_on;
uint64_t priority;
std::optional<uint32_t> character;
std::optional<uint32_t> slot_in_select_menu;
std::string name;
std::wstring w_name;
std::string main_name;
std::string label;
std::optional<std::string> description;
std::optional<std::string> version;
std::optional<std::string> author;
std::vector<Asset_Path> redirection_list;
std::optional<UI_String_t> costume_name;
uint32_t costume_id;
bool* on_ptr = nullptr;
};
struct Info_Back{
bool is_on;
unsigned int priority;
};
struct Costume_List_t{
// Only meant to be called when allocating memory properly
Costume_List_t(uint32_t init_size)
:ukn1{ nullptr }, ukn2{ NULL }, ukn3{ NULL },
ukn4{ nullptr }, ukn5{ NULL }, size{ init_size }
{
}
// Needs proper memory allocation
Costume_List_t(const Costume_List_t& other)
:ukn1{ other.ukn1 }, ukn2{ other.ukn2 }, ukn3{ other.ukn3 },
ukn4{ other.ukn4 }, ukn5{ other.ukn5 }, size{ other.size }
{
memcpy_s(&costumes, size*sizeof(uint32_t), &other.costumes, other.size*sizeof(uint32_t));
}
// Needs proper memory allocation
Costume_List_t(const Costume_List_t& other, uint32_t init_size)
:ukn1{ other.ukn1 }, ukn2{ other.ukn2 }, ukn3{ other.ukn3 },
ukn4{ other.ukn4 }, ukn5{ other.ukn5 }, size{ init_size }
{
memcpy_s(&costumes, size*sizeof(uint32_t), &other.costumes, other.size*sizeof(uint32_t));
}
// Needs proper memory allocation
Costume_List_t(const Costume_List_t& other, uint32_t org_size, std::vector<uint32_t> extra)
:ukn1{ other.ukn1 }, ukn2{ other.ukn2 }, ukn3{ other.ukn3 },
ukn4{ other.ukn4 }, ukn5{ other.ukn5 }, size{ org_size + extra.size() }
{
// Transfering original costume list to the new list
for (UINT i = 0; i < org_size; i++) {
costumes[i] = other.costumes[i];
}
// Putting the extra costumes into slots after the original costumes
for (UINT i = 0; i < extra.size(); i++) {
costumes[i + org_size] = extra[i];
}
}
void* ukn1;
uint32_t ukn2;
uint32_t ukn3;
void* ukn4;
uint32_t ukn5;
uint32_t size;
uint32_t costumes[];
uint32_t& operator[](uint64_t index) {
return this->costumes[index];
}
const uint32_t& operator[](uint64_t index) const {
return this->costumes[index];
}
void operator=(const Costume_List_t& other) {
ukn1 = other.ukn1;
ukn2 = other.ukn2;
ukn3 = other.ukn3;
ukn4 = other.ukn4;
ukn5 = other.ukn5;
size = other.size;
memcpy_s(costumes, size*sizeof(uint32_t), other.costumes, other.size*sizeof(uint32_t));
}
};
struct Char_Default_Costume_Info {
uint8_t org_super;
uint8_t org;
uint8_t ex;
uint8_t ex_super;
};
private:
std::optional<std::vector<fs::path>> m_mod_roots{};
std::optional<std::vector<fs::path>> m_sys_mod_roots{};
std::optional<std::vector<std::shared_ptr<Asset_Hotswap>>> m_hot_swaps{};
std::optional<std::vector<std::shared_ptr<Asset_Hotswap>>> m_sys_hot_swaps{};
std::optional<std::vector<std::shared_ptr<Asset_Hotswap>>> m_nero_swaps{};
std::optional<std::vector<std::shared_ptr<Asset_Hotswap>>> m_dante_swaps{};
std::optional<std::vector<std::shared_ptr<Asset_Hotswap>>> m_gilver_swaps{};
std::optional<std::vector<std::shared_ptr<Asset_Hotswap>>> m_vergil_swaps{};
std::vector<uint32_t> m_nero_extra_costumes;
std::vector<uint32_t> m_dante_extra_costumes;
std::vector<uint32_t> m_gilver_extra_costumes;
std::vector<uint32_t> m_vergil_extra_costumes;
void asset_swap_ui(std::optional<std::vector<std::shared_ptr<Asset_Hotswap>>>& hot_swaps);
void costume_swap_ui(std::optional<std::vector<std::shared_ptr<Asset_Hotswap>>>& costume_swaps);
};
| 34.907285 | 124 | 0.677006 | youwereeatenbyalid |
473ebb403849cafbd4d58a78c43a7d4159e2cbc3 | 1,154 | cpp | C++ | Chapter04/mmap_write.cpp | trantrongquy/C-System-Programming-Cookbook | 2df8795d8f88de10e38297606ac2fa9993d6dab4 | [
"MIT"
] | 36 | 2020-03-23T21:10:14.000Z | 2022-01-22T20:22:30.000Z | Chapter04/mmap_write.cpp | trantrongquy/C-System-Programming-Cookbook | 2df8795d8f88de10e38297606ac2fa9993d6dab4 | [
"MIT"
] | 2 | 2020-02-28T13:14:44.000Z | 2021-06-17T07:55:34.000Z | Chapter04/mmap_write.cpp | trantrongquy/C-System-Programming-Cookbook | 2df8795d8f88de10e38297606ac2fa9993d6dab4 | [
"MIT"
] | 22 | 2020-02-21T08:00:06.000Z | 2022-02-09T11:05:13.000Z | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <iostream>
#define FILEPATH "mmapped.txt"
#define NUM_OF_ITEMS_IN_FILE (1000)
#define FILESIZE (NUM_OF_ITEMS_IN_FILE * sizeof(int))
int main(int argc, char *argv[])
{
int fd = open(FILEPATH, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
if (fd == -1)
{
std::cout << "Error opening file " << FILEPATH << std::endl;
return 1;
}
int result = lseek(fd, FILESIZE-1, SEEK_SET);
if (result == -1)
{
close(fd);
std::cout << "Error calling lseek " << std::endl;
return 2;
}
result = write(fd, "", 1);
if (result != 1)
{
close(fd);
std::cout << "Error writing into the file " << std::endl;
return 3;
}
int* map = (int*) mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map == MAP_FAILED)
{
close(fd);
std::cout << "Error mapping the file " << std::endl;
return 4;
}
for (int i = 1; i <=NUM_OF_ITEMS_IN_FILE; ++i)
map[i] = 2 * i;
if (munmap(map, FILESIZE) == -1)
std::cout << "Error un-mapping" << std::endl;
close(fd);
return 0;
}
| 20.981818 | 83 | 0.584922 | trantrongquy |
474054247992303911fb385564c34230eba7d440 | 25,398 | cpp | C++ | CWE-119/source_files/CVE-2011-2377/Firefox_4.0.1_CVE_2011_2377_modules_libpr0n_decoders_nsBMPDecoder.cpp | CGCL-codes/VulDeePecker | 98610f3e116df97a1e819ffc81fbc7f6f138a8f2 | [
"Apache-2.0"
] | 185 | 2017-12-14T08:18:15.000Z | 2022-03-30T02:58:36.000Z | CWE-119/source_files/CVE-2011-2377/Firefox_4.0.1_CVE_2011_2377_modules_libpr0n_decoders_nsBMPDecoder.cpp | CGCL-codes/VulDeePecker | 98610f3e116df97a1e819ffc81fbc7f6f138a8f2 | [
"Apache-2.0"
] | 11 | 2018-01-30T23:31:20.000Z | 2022-01-17T05:03:56.000Z | CWE-119/source_files/CVE-2011-2377/Firefox_4.0.1_CVE_2011_2377_modules_libpr0n_decoders_nsBMPDecoder.cpp | CGCL-codes/VulDeePecker | 98610f3e116df97a1e819ffc81fbc7f6f138a8f2 | [
"Apache-2.0"
] | 87 | 2018-01-10T08:12:32.000Z | 2022-02-19T10:29:31.000Z | /* vim:set tw=80 expandtab softtabstop=4 ts=4 sw=4: */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Mozilla BMP Decoder.
*
* The Initial Developer of the Original Code is
* Christian Biesinger <cbiesinger@web.de>.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Neil Rashbrook <neil@parkwaycc.co.uk>
* Bobby Holley <bobbyholley@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/* I got the format description from http://www.daubnet.com/formats/BMP.html */
/* This is a Cross-Platform BMP Decoder, which should work everywhere, including
* Big-Endian machines like the PowerPC. */
#include <stdlib.h>
#include "nsBMPDecoder.h"
#include "nsIInputStream.h"
#include "RasterImage.h"
#include "imgIContainerObserver.h"
#include "prlog.h"
namespace mozilla {
namespace imagelib {
#ifdef PR_LOGGING
PRLogModuleInfo *gBMPLog = PR_NewLogModule("BMPDecoder");
#endif
// Convert from row (1..height) to absolute line (0..height-1)
#define LINE(row) ((mBIH.height < 0) ? (-mBIH.height - (row)) : ((row) - 1))
#define PIXEL_OFFSET(row, col) (LINE(row) * mBIH.width + col)
nsBMPDecoder::nsBMPDecoder()
{
mColors = nsnull;
mRow = nsnull;
mCurPos = mPos = mNumColors = mRowBytes = 0;
mOldLine = mCurLine = 1; // Otherwise decoder will never start
mState = eRLEStateInitial;
mStateData = 0;
mLOH = WIN_HEADER_LENGTH;
}
nsBMPDecoder::~nsBMPDecoder()
{
delete[] mColors;
if (mRow)
free(mRow);
}
void
nsBMPDecoder::FinishInternal()
{
// We shouldn't be called in error cases
NS_ABORT_IF_FALSE(!HasError(), "Can't call FinishInternal on error!");
// We should never make multiple frames
NS_ABORT_IF_FALSE(GetFrameCount() <= 1, "Multiple BMP frames?");
// Send notifications if appropriate
if (!IsSizeDecode() && (GetFrameCount() == 1)) {
PostFrameStop();
PostDecodeDone();
}
}
// ----------------------------------------
// Actual Data Processing
// ----------------------------------------
static void calcBitmask(PRUint32 aMask, PRUint8& aBegin, PRUint8& aLength)
{
// find the rightmost 1
PRUint8 pos;
PRBool started = PR_FALSE;
aBegin = aLength = 0;
for (pos = 0; pos <= 31; pos++) {
if (!started && (aMask & (1 << pos))) {
aBegin = pos;
started = PR_TRUE;
}
else if (started && !(aMask & (1 << pos))) {
aLength = pos - aBegin;
break;
}
}
}
NS_METHOD nsBMPDecoder::CalcBitShift()
{
PRUint8 begin, length;
// red
calcBitmask(mBitFields.red, begin, length);
mBitFields.redRightShift = begin;
mBitFields.redLeftShift = 8 - length;
// green
calcBitmask(mBitFields.green, begin, length);
mBitFields.greenRightShift = begin;
mBitFields.greenLeftShift = 8 - length;
// blue
calcBitmask(mBitFields.blue, begin, length);
mBitFields.blueRightShift = begin;
mBitFields.blueLeftShift = 8 - length;
return NS_OK;
}
void
nsBMPDecoder::WriteInternal(const char* aBuffer, PRUint32 aCount)
{
NS_ABORT_IF_FALSE(!HasError(), "Shouldn't call WriteInternal after error!");
// aCount=0 means EOF, mCurLine=0 means we're past end of image
if (!aCount || !mCurLine)
return;
nsresult rv;
if (mPos < BFH_LENGTH) { /* In BITMAPFILEHEADER */
PRUint32 toCopy = BFH_LENGTH - mPos;
if (toCopy > aCount)
toCopy = aCount;
memcpy(mRawBuf + mPos, aBuffer, toCopy);
mPos += toCopy;
aCount -= toCopy;
aBuffer += toCopy;
}
if (mPos == BFH_LENGTH) {
ProcessFileHeader();
if (mBFH.signature[0] != 'B' || mBFH.signature[1] != 'M') {
PostDataError();
return;
}
if (mBFH.bihsize == OS2_BIH_LENGTH)
mLOH = OS2_HEADER_LENGTH;
}
if (mPos >= BFH_LENGTH && mPos < mLOH) { /* In BITMAPINFOHEADER */
PRUint32 toCopy = mLOH - mPos;
if (toCopy > aCount)
toCopy = aCount;
memcpy(mRawBuf + (mPos - BFH_LENGTH), aBuffer, toCopy);
mPos += toCopy;
aCount -= toCopy;
aBuffer += toCopy;
}
if (mPos == mLOH) {
ProcessInfoHeader();
PR_LOG(gBMPLog, PR_LOG_DEBUG, ("BMP image is %lix%lix%lu. compression=%lu\n",
mBIH.width, mBIH.height, mBIH.bpp, mBIH.compression));
// Verify we support this bit depth
if (mBIH.bpp != 1 && mBIH.bpp != 4 && mBIH.bpp != 8 &&
mBIH.bpp != 16 && mBIH.bpp != 24 && mBIH.bpp != 32) {
PostDataError();
return;
}
// BMPs with negative width are invalid
// Reject extremely wide images to keep the math sane
const PRInt32 k64KWidth = 0x0000FFFF;
if (mBIH.width < 0 || mBIH.width > k64KWidth) {
PostDataError();
return;
}
PRUint32 real_height = (mBIH.height > 0) ? mBIH.height : -mBIH.height;
// Post our size to the superclass
PostSize(mBIH.width, real_height);
// We have the size. If we're doing a size decode, we got what
// we came for.
if (IsSizeDecode())
return;
// We're doing a real decode.
mOldLine = mCurLine = real_height;
if (mBIH.bpp <= 8) {
mNumColors = 1 << mBIH.bpp;
if (mBIH.colors && mBIH.colors < mNumColors)
mNumColors = mBIH.colors;
// Always allocate 256 even though mNumColors might be smaller
mColors = new colorTable[256];
memset(mColors, 0, 256 * sizeof(colorTable));
}
else if (mBIH.compression != BI_BITFIELDS && mBIH.bpp == 16) {
// Use default 5-5-5 format
mBitFields.red = 0x7C00;
mBitFields.green = 0x03E0;
mBitFields.blue = 0x001F;
CalcBitShift();
}
PRUint32 imageLength;
if ((mBIH.compression == BI_RLE8) || (mBIH.compression == BI_RLE4)) {
rv = mImage->AppendFrame(0, 0, mBIH.width, real_height, gfxASurface::ImageFormatARGB32,
(PRUint8**)&mImageData, &imageLength);
} else {
// mRow is not used for RLE encoded images
mRow = (PRUint8*)moz_malloc((mBIH.width * mBIH.bpp)/8 + 4);
// +4 because the line is padded to a 4 bit boundary, but I don't want
// to make exact calculations here, that's unnecessary.
// Also, it compensates rounding error.
if (!mRow) {
PostDecoderError(NS_ERROR_OUT_OF_MEMORY);
return;
}
rv = mImage->AppendFrame(0, 0, mBIH.width, real_height, gfxASurface::ImageFormatRGB24,
(PRUint8**)&mImageData, &imageLength);
}
if (NS_FAILED(rv) || !mImageData) {
PostDecoderError(NS_ERROR_FAILURE);
return;
}
// Prepare for transparancy
if ((mBIH.compression == BI_RLE8) || (mBIH.compression == BI_RLE4)) {
if (((mBIH.compression == BI_RLE8) && (mBIH.bpp != 8))
|| ((mBIH.compression == BI_RLE4) && (mBIH.bpp != 4) && (mBIH.bpp != 1))) {
PR_LOG(gBMPLog, PR_LOG_DEBUG, ("BMP RLE8/RLE4 compression only supports 8/4 bits per pixel\n"));
PostDataError();
return;
}
// Clear the image, as the RLE may jump over areas
memset(mImageData, 0, imageLength);
}
// Tell the superclass we're starting a frame
PostFrameStart();
}
PRUint8 bpc; // bytes per color
bpc = (mBFH.bihsize == OS2_BIH_LENGTH) ? 3 : 4; // OS/2 Bitmaps have no padding byte
if (mColors && (mPos >= mLOH && (mPos < (mLOH + mNumColors * bpc)))) {
// We will receive (mNumColors * bpc) bytes of color data
PRUint32 colorBytes = mPos - mLOH; // Number of bytes already received
PRUint8 colorNum = colorBytes / bpc; // Color which is currently received
PRUint8 at = colorBytes % bpc;
while (aCount && (mPos < (mLOH + mNumColors * bpc))) {
switch (at) {
case 0:
mColors[colorNum].blue = *aBuffer;
break;
case 1:
mColors[colorNum].green = *aBuffer;
break;
case 2:
mColors[colorNum].red = *aBuffer;
colorNum++;
break;
case 3:
// This is a padding byte
break;
}
mPos++; aBuffer++; aCount--;
at = (at + 1) % bpc;
}
}
else if (aCount && mBIH.compression == BI_BITFIELDS && mPos < (WIN_HEADER_LENGTH + BITFIELD_LENGTH)) {
// If compression is used, this is a windows bitmap, hence we can
// use WIN_HEADER_LENGTH instead of mLOH
PRUint32 toCopy = (WIN_HEADER_LENGTH + BITFIELD_LENGTH) - mPos;
if (toCopy > aCount)
toCopy = aCount;
memcpy(mRawBuf + (mPos - WIN_HEADER_LENGTH), aBuffer, toCopy);
mPos += toCopy;
aBuffer += toCopy;
aCount -= toCopy;
}
if (mBIH.compression == BI_BITFIELDS && mPos == WIN_HEADER_LENGTH + BITFIELD_LENGTH) {
mBitFields.red = LITTLE_TO_NATIVE32(*(PRUint32*)mRawBuf);
mBitFields.green = LITTLE_TO_NATIVE32(*(PRUint32*)(mRawBuf + 4));
mBitFields.blue = LITTLE_TO_NATIVE32(*(PRUint32*)(mRawBuf + 8));
CalcBitShift();
}
while (aCount && (mPos < mBFH.dataoffset)) { // Skip whatever is between header and data
mPos++; aBuffer++; aCount--;
}
if (aCount && ++mPos >= mBFH.dataoffset) {
// Need to increment mPos, else we might get to mPos==mLOH again
// From now on, mPos is irrelevant
if (!mBIH.compression || mBIH.compression == BI_BITFIELDS) {
PRUint32 rowSize = (mBIH.bpp * mBIH.width + 7) / 8; // +7 to round up
if (rowSize % 4)
rowSize += (4 - (rowSize % 4)); // Pad to DWORD Boundary
PRUint32 toCopy;
do {
toCopy = rowSize - mRowBytes;
if (toCopy) {
if (toCopy > aCount)
toCopy = aCount;
memcpy(mRow + mRowBytes, aBuffer, toCopy);
aCount -= toCopy;
aBuffer += toCopy;
mRowBytes += toCopy;
}
if (rowSize == mRowBytes) {
// Collected a whole row into mRow, process it
PRUint8* p = mRow;
PRUint32* d = mImageData + PIXEL_OFFSET(mCurLine, 0);
PRUint32 lpos = mBIH.width;
switch (mBIH.bpp) {
case 1:
while (lpos > 0) {
PRInt8 bit;
PRUint8 idx;
for (bit = 7; bit >= 0 && lpos > 0; bit--) {
idx = (*p >> bit) & 1;
SetPixel(d, idx, mColors);
--lpos;
}
++p;
}
break;
case 4:
while (lpos > 0) {
Set4BitPixel(d, *p, lpos, mColors);
++p;
}
break;
case 8:
while (lpos > 0) {
SetPixel(d, *p, mColors);
--lpos;
++p;
}
break;
case 16:
while (lpos > 0) {
PRUint16 val = LITTLE_TO_NATIVE16(*(PRUint16*)p);
SetPixel(d,
(val & mBitFields.red) >> mBitFields.redRightShift << mBitFields.redLeftShift,
(val & mBitFields.green) >> mBitFields.greenRightShift << mBitFields.greenLeftShift,
(val & mBitFields.blue) >> mBitFields.blueRightShift << mBitFields.blueLeftShift);
--lpos;
p+=2;
}
break;
case 32:
case 24:
while (lpos > 0) {
SetPixel(d, p[2], p[1], p[0]);
p += 2;
--lpos;
if (mBIH.bpp == 32)
p++; // Padding byte
++p;
}
break;
default:
NS_NOTREACHED("Unsupported color depth, but earlier check didn't catch it");
}
mCurLine --;
if (mCurLine == 0) { // Finished last line
break;
}
mRowBytes = 0;
}
} while (aCount > 0);
}
else if ((mBIH.compression == BI_RLE8) || (mBIH.compression == BI_RLE4)) {
if (((mBIH.compression == BI_RLE8) && (mBIH.bpp != 8))
|| ((mBIH.compression == BI_RLE4) && (mBIH.bpp != 4) && (mBIH.bpp != 1))) {
PR_LOG(gBMPLog, PR_LOG_DEBUG, ("BMP RLE8/RLE4 compression only supports 8/4 bits per pixel\n"));
PostDataError();
return;
}
while (aCount > 0) {
PRUint8 byte;
switch(mState) {
case eRLEStateInitial:
mStateData = (PRUint8)*aBuffer++;
aCount--;
mState = eRLEStateNeedSecondEscapeByte;
continue;
case eRLEStateNeedSecondEscapeByte:
byte = *aBuffer++;
aCount--;
if (mStateData != RLE_ESCAPE) { // encoded mode
// Encoded mode consists of two bytes:
// the first byte (mStateData) specifies the
// number of consecutive pixels to be drawn
// using the color index contained in
// the second byte
// Work around bitmaps that specify too many pixels
mState = eRLEStateInitial;
PRUint32 pixelsNeeded = PR_MIN((PRUint32)(mBIH.width - mCurPos), mStateData);
if (pixelsNeeded) {
PRUint32* d = mImageData + PIXEL_OFFSET(mCurLine, mCurPos);
mCurPos += pixelsNeeded;
if (mBIH.compression == BI_RLE8) {
do {
SetPixel(d, byte, mColors);
pixelsNeeded --;
} while (pixelsNeeded);
} else {
do {
Set4BitPixel(d, byte, pixelsNeeded, mColors);
} while (pixelsNeeded);
}
}
continue;
}
switch(byte) {
case RLE_ESCAPE_EOL:
// End of Line: Go to next row
mCurLine --;
mCurPos = 0;
mState = eRLEStateInitial;
break;
case RLE_ESCAPE_EOF: // EndOfFile
mCurPos = mCurLine = 0;
break;
case RLE_ESCAPE_DELTA:
mState = eRLEStateNeedXDelta;
continue;
default : // absolute mode
// Save the number of pixels to read
mStateData = byte;
if (mCurPos + mStateData > (PRUint32)mBIH.width) {
// We can work around bitmaps that specify one
// pixel too many, but only if their width is odd.
mStateData -= mBIH.width & 1;
if (mCurPos + mStateData > (PRUint32)mBIH.width) {
PostDataError();
return;
}
}
// See if we will need to skip a byte
// to word align the pixel data
// mStateData is a number of pixels
// so allow for the RLE compression type
// Pixels RLE8=1 RLE4=2
// 1 Pad Pad
// 2 No Pad
// 3 Pad No
// 4 No No
if (((mStateData - 1) & mBIH.compression) != 0)
mState = eRLEStateAbsoluteMode;
else
mState = eRLEStateAbsoluteModePadded;
continue;
}
break;
case eRLEStateNeedXDelta:
// Handle the XDelta and proceed to get Y Delta
byte = *aBuffer++;
aCount--;
mCurPos += byte;
if (mCurPos > mBIH.width)
mCurPos = mBIH.width;
mState = eRLEStateNeedYDelta;
continue;
case eRLEStateNeedYDelta:
// Get the Y Delta and then "handle" the move
byte = *aBuffer++;
aCount--;
mState = eRLEStateInitial;
mCurLine -= PR_MIN(byte, mCurLine);
break;
case eRLEStateAbsoluteMode: // Absolute Mode
case eRLEStateAbsoluteModePadded:
if (mStateData) {
// In absolute mode, the second byte (mStateData)
// represents the number of pixels
// that follow, each of which contains
// the color index of a single pixel.
PRUint32* d = mImageData + PIXEL_OFFSET(mCurLine, mCurPos);
PRUint32* oldPos = d;
if (mBIH.compression == BI_RLE8) {
while (aCount > 0 && mStateData > 0) {
byte = *aBuffer++;
aCount--;
SetPixel(d, byte, mColors);
mStateData--;
}
} else {
while (aCount > 0 && mStateData > 0) {
byte = *aBuffer++;
aCount--;
Set4BitPixel(d, byte, mStateData, mColors);
}
}
mCurPos += d - oldPos;
}
if (mStateData == 0) {
// In absolute mode, each run must
// be aligned on a word boundary
if (mState == eRLEStateAbsoluteMode) { // Word Aligned
mState = eRLEStateInitial;
} else if (aCount > 0) { // Not word Aligned
// "next" byte is just a padding byte
// so "move" past it and we can continue
aBuffer++;
aCount--;
mState = eRLEStateInitial;
}
}
// else state is still eRLEStateAbsoluteMode
continue;
default :
NS_ABORT_IF_FALSE(0, "BMP RLE decompression: unknown state!");
PostDecoderError(NS_ERROR_UNEXPECTED);
return;
}
// Because of the use of the continue statement
// we only get here for eol, eof or y delta
if (mCurLine == 0) { // Finished last line
break;
}
}
}
}
const PRUint32 rows = mOldLine - mCurLine;
if (rows) {
// Invalidate
nsIntRect r(0, mBIH.height < 0 ? -mBIH.height - mOldLine : mCurLine,
mBIH.width, rows);
PostInvalidation(r);
mOldLine = mCurLine;
}
return;
}
void nsBMPDecoder::ProcessFileHeader()
{
memset(&mBFH, 0, sizeof(mBFH));
memcpy(&mBFH.signature, mRawBuf, sizeof(mBFH.signature));
memcpy(&mBFH.filesize, mRawBuf + 2, sizeof(mBFH.filesize));
memcpy(&mBFH.reserved, mRawBuf + 6, sizeof(mBFH.reserved));
memcpy(&mBFH.dataoffset, mRawBuf + 10, sizeof(mBFH.dataoffset));
memcpy(&mBFH.bihsize, mRawBuf + 14, sizeof(mBFH.bihsize));
// Now correct the endianness of the header
mBFH.filesize = LITTLE_TO_NATIVE32(mBFH.filesize);
mBFH.dataoffset = LITTLE_TO_NATIVE32(mBFH.dataoffset);
mBFH.bihsize = LITTLE_TO_NATIVE32(mBFH.bihsize);
}
void nsBMPDecoder::ProcessInfoHeader()
{
memset(&mBIH, 0, sizeof(mBIH));
if (mBFH.bihsize == 12) { // OS/2 Bitmap
memcpy(&mBIH.width, mRawBuf, 2);
memcpy(&mBIH.height, mRawBuf + 2, 2);
memcpy(&mBIH.planes, mRawBuf + 4, sizeof(mBIH.planes));
memcpy(&mBIH.bpp, mRawBuf + 6, sizeof(mBIH.bpp));
}
else {
memcpy(&mBIH.width, mRawBuf, sizeof(mBIH.width));
memcpy(&mBIH.height, mRawBuf + 4, sizeof(mBIH.height));
memcpy(&mBIH.planes, mRawBuf + 8, sizeof(mBIH.planes));
memcpy(&mBIH.bpp, mRawBuf + 10, sizeof(mBIH.bpp));
memcpy(&mBIH.compression, mRawBuf + 12, sizeof(mBIH.compression));
memcpy(&mBIH.image_size, mRawBuf + 16, sizeof(mBIH.image_size));
memcpy(&mBIH.xppm, mRawBuf + 20, sizeof(mBIH.xppm));
memcpy(&mBIH.yppm, mRawBuf + 24, sizeof(mBIH.yppm));
memcpy(&mBIH.colors, mRawBuf + 28, sizeof(mBIH.colors));
memcpy(&mBIH.important_colors, mRawBuf + 32, sizeof(mBIH.important_colors));
}
// Convert endianness
mBIH.width = LITTLE_TO_NATIVE32(mBIH.width);
mBIH.height = LITTLE_TO_NATIVE32(mBIH.height);
mBIH.planes = LITTLE_TO_NATIVE16(mBIH.planes);
mBIH.bpp = LITTLE_TO_NATIVE16(mBIH.bpp);
mBIH.compression = LITTLE_TO_NATIVE32(mBIH.compression);
mBIH.image_size = LITTLE_TO_NATIVE32(mBIH.image_size);
mBIH.xppm = LITTLE_TO_NATIVE32(mBIH.xppm);
mBIH.yppm = LITTLE_TO_NATIVE32(mBIH.yppm);
mBIH.colors = LITTLE_TO_NATIVE32(mBIH.colors);
mBIH.important_colors = LITTLE_TO_NATIVE32(mBIH.important_colors);
}
} // namespace imagelib
} // namespace mozilla
| 40.378378 | 118 | 0.479802 | CGCL-codes |
47420fe837713722b30bd054801315dea2aff39d | 3,659 | cpp | C++ | source/ff.dx12/source/queue.cpp | spadapet/ff_game_library | f1bf00f90adde66c2c2aa35b109fe61b8d2c6352 | [
"MIT"
] | null | null | null | source/ff.dx12/source/queue.cpp | spadapet/ff_game_library | f1bf00f90adde66c2c2aa35b109fe61b8d2c6352 | [
"MIT"
] | null | null | null | source/ff.dx12/source/queue.cpp | spadapet/ff_game_library | f1bf00f90adde66c2c2aa35b109fe61b8d2c6352 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "access.h"
#include "device_reset_priority.h"
#include "fence.h"
#include "globals.h"
#include "queue.h"
ff::dx12::queue::queue(D3D12_COMMAND_LIST_TYPE type)
: type(type)
{
this->reset();
ff::dx12::add_device_child(this, ff::dx12::device_reset_priority::queue);
}
ff::dx12::queue::~queue()
{
ff::dx12::remove_device_child(this);
}
ff::dx12::queue::operator bool() const
{
return this->command_queue != nullptr;
}
void ff::dx12::queue::wait_for_idle()
{
ff::dx12::fence fence(this);
fence.signal(this).wait(nullptr);
}
ff::dx12::commands ff::dx12::queue::new_commands(ID3D12PipelineStateX* initial_state)
{
Microsoft::WRL::ComPtr<ID3D12GraphicsCommandListX> list;
Microsoft::WRL::ComPtr<ID3D12CommandAllocatorX> allocator;
std::unique_ptr<ff::dx12::fence> fence;
{
std::scoped_lock lock(this->mutex);
if (this->allocators.empty() || !this->allocators.front().first.complete())
{
ff::dx12::device()->CreateCommandAllocator(this->type, IID_PPV_ARGS(&allocator));
}
else
{
allocator = std::move(this->allocators.front().second);
this->allocators.pop_front();
}
if (this->lists.empty())
{
ff::dx12::device()->CreateCommandList1(0, this->type, D3D12_COMMAND_LIST_FLAG_NONE, IID_PPV_ARGS(&list));
}
else
{
list = std::move(this->lists.front());
this->lists.pop_front();
}
if (this->fences.empty())
{
fence = std::make_unique<ff::dx12::fence>(this);
}
else
{
fence = std::move(this->fences.front());
this->fences.pop_front();
}
}
allocator->Reset();
return ff::dx12::commands(*this, list.Get(), allocator.Get(), std::move(fence), initial_state);
}
void ff::dx12::queue::execute(ff::dx12::commands& commands)
{
ff::dx12::commands* p = &commands;
this->execute(&p, 1);
}
void ff::dx12::queue::execute(ff::dx12::commands** commands, size_t count)
{
ff::stack_vector<ID3D12CommandList*, 16> lists;
ff::dx12::fence_values fence_values;
ff::dx12::fence_values wait_before_execute;
if (count)
{
lists.reserve(count);
fence_values.reserve(count);
for (size_t i = 0; i < count; i++)
{
ff::dx12::commands& cur = *commands[i];
if (cur)
{
std::scoped_lock lock(this->mutex);
this->allocators.push_back(std::make_pair(cur.next_fence_value(), ff::dx12::get_command_allocator(cur)));
this->lists.push_front(ff::dx12::get_command_list(cur));
this->fences.push_front(std::move(ff::dx12::move_fence(cur)));
lists.push_back(this->lists.front().Get());
fence_values.add(this->fences.front()->next_value());
}
wait_before_execute.add(cur.wait_before_execute());
cur.close();
}
wait_before_execute.wait(this);
if (!lists.empty())
{
this->command_queue->ExecuteCommandLists(static_cast<UINT>(lists.size()), lists.data());
fence_values.signal(this);
}
}
}
void ff::dx12::queue::before_reset()
{
this->allocators.clear();
this->lists.clear();
this->fences.clear();
this->command_queue.Reset();
}
bool ff::dx12::queue::reset()
{
const D3D12_COMMAND_QUEUE_DESC command_queue_desc{ this->type };
return SUCCEEDED(ff::dx12::device()->CreateCommandQueue(&command_queue_desc, IID_PPV_ARGS(&this->command_queue)));
}
| 27.511278 | 121 | 0.596338 | spadapet |
4742997122af1c266e1b3fe2da68930984e797f9 | 18,528 | cc | C++ | content/browser/prerender/prerender_host.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | content/browser/prerender/prerender_host.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | content/browser/prerender/prerender_host.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 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 "content/browser/prerender/prerender_host.h"
#include "base/callback_forward.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_functions.h"
#include "base/run_loop.h"
#include "base/trace_event/common/trace_event_common.h"
#include "base/trace_event/trace_conversion_helper.h"
#include "content/browser/renderer_host/frame_tree.h"
#include "content/browser/renderer_host/frame_tree_node.h"
#include "content/browser/renderer_host/navigation_controller_impl.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_frame_proxy_host.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/back_forward_cache.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h"
#include "third_party/blink/public/common/features.h"
namespace content {
namespace {
void CollectAllChildren(RenderFrameHostImpl& rfh,
std::vector<RenderFrameHostImpl*>* result) {
result->push_back(&rfh);
for (size_t i = 0; i < rfh.child_count(); ++i) {
if (RenderFrameHostImpl* speculative_frame_host =
rfh.child_at(i)->render_manager()->speculative_frame_host()) {
result->push_back(speculative_frame_host);
}
CollectAllChildren(*(rfh.child_at(i)->current_frame_host()), result);
}
}
// Iterate over RenderFrameHostImpl::children_ rather than FrameTree::Nodes()
// because the |rfh| root node will not have a current_frame_host value. The
// root node is set to null in MPArch prerender activation when generating a
// BackForwardCacheImpl::Entry.
std::vector<RenderFrameHostImpl*> AllDescendantActiveRenderFrameHosts(
RenderFrameHostImpl& rfh) {
std::vector<RenderFrameHostImpl*> result;
CollectAllChildren(rfh, &result);
return result;
}
struct ActivateResult {
ActivateResult(PrerenderHost::FinalStatus status,
std::unique_ptr<BackForwardCacheImpl::Entry> entry)
: status(status), entry(std::move(entry)) {}
PrerenderHost::FinalStatus status = PrerenderHost::FinalStatus::kActivated;
std::unique_ptr<BackForwardCacheImpl::Entry> entry;
};
} // namespace
class PrerenderHost::PageHolderInterface {
public:
PageHolderInterface() = default;
virtual ~PageHolderInterface() = default;
virtual NavigationController& GetNavigationController() = 0;
virtual RenderFrameHostImpl* GetMainFrame() = 0;
virtual WebContents* GetWebContents() = 0;
virtual ActivateResult Activate(
RenderFrameHostImpl& current_render_frame_host,
NavigationRequest& navigation_request) = 0;
virtual void WaitForLoadCompletionForTesting() = 0; // IN-TEST
};
class PrerenderHost::MPArchPageHolder
: public PrerenderHost::PageHolderInterface,
public FrameTree::Delegate,
public NavigationControllerDelegate {
public:
explicit MPArchPageHolder(WebContentsImpl& web_contents)
: web_contents_(web_contents),
frame_tree_(
std::make_unique<FrameTree>(web_contents.GetBrowserContext(),
this,
this,
&web_contents,
&web_contents,
&web_contents,
&web_contents,
&web_contents)) {
DCHECK(blink::features::IsPrerenderMPArchEnabled());
frame_tree_->Init(
SiteInstance::Create(web_contents.GetBrowserContext()).get(),
/*renderer_initiated_creation=*/false,
/*main_frame_name=*/"", FrameTree::Type::kPrerender);
// TODO(https://crbug.com/1164280): This should be moved to FrameTree::Init
web_contents_.NotifySwappedFromRenderManager(
/*old_frame=*/nullptr,
frame_tree_->root()->render_manager()->current_frame_host(),
/*is_main_frame=*/true);
}
~MPArchPageHolder() override {
if (frame_tree_)
frame_tree_->Shutdown();
}
// FrameTree::Delegate
// TODO(https://crbug.com/1164280): Correctly handle load events. Ignored for
// now as it confuses WebContentsObserver instances because they can not
// distinguish between the different FrameTrees.
void DidStartLoading(FrameTreeNode* frame_tree_node,
bool to_different_document) override {}
void DidStopLoading() override {
if (on_stopped_loading_for_tests_) {
std::move(on_stopped_loading_for_tests_).Run();
}
}
void DidChangeLoadProgress() override {}
bool IsHidden() override { return true; }
// NavigationControllerDelegate
void NotifyNavigationStateChanged(InvalidateTypes changed_flags) override {}
void Stop() override { frame_tree_->StopLoading(); }
bool IsBeingDestroyed() override { return false; }
void NotifyBeforeFormRepostWarningShow() override {}
void NotifyNavigationEntryCommitted(
const LoadCommittedDetails& load_details) override {}
void NotifyNavigationEntryChanged(
const EntryChangedDetails& change_details) override {}
void NotifyNavigationListPruned(
const PrunedDetails& pruned_details) override {}
void NotifyNavigationEntriesDeleted() override {}
void ActivateAndShowRepostFormWarningDialog() override {}
bool ShouldPreserveAbortedURLs() override { return false; }
WebContents* GetWebContents() override { return &web_contents_; }
void UpdateOverridingUserAgent() override {}
// PageHolder
NavigationControllerImpl& GetNavigationController() override {
return frame_tree_->controller();
}
RenderFrameHostImpl* GetMainFrame() override {
return frame_tree_->root()->current_frame_host();
}
ActivateResult Activate(RenderFrameHostImpl& current_render_frame_host,
NavigationRequest& navigation_request) override {
if (frame_tree_->root()->HasNavigation()) {
// We do not yet support activation if there is an ongoing navigation in
// the main frame as the code assumes that NavigationRequest is associated
// with the fixed frame tree node. Ongoing navigations in frames are
// supported experimentally and require more investigation to ensure that
// these NavigationRequests can be transferred to a new
// NavigationController and that new NavigationEntries will be correctly
// created for them.
// TODO(https://crbug.com/1190644): Make sure sub-frame navigations are
// fine.
return ActivateResult(FinalStatus::kInProgressNavigation, nullptr);
}
// NOTE: TakePrerenderedPage() clears the current_frame_host value of
// frame_tree_->root(). Do not add any code between here and
// frame_tree_.reset() that calls into observer functions to minimize the
// duration of current_frame_host being null.
//
// TODO(https://crbug.com/1176148): Investigate how to combine taking the
// prerendered page and frame_tree_ destruction.
std::unique_ptr<BackForwardCacheImpl::Entry> page =
frame_tree_->root()->render_manager()->TakePrerenderedPage();
std::unique_ptr<NavigationEntryImpl> nav_entry =
GetNavigationController()
.GetEntryWithUniqueID(page->render_frame_host->nav_entry_id())
->Clone();
navigation_request.SetPrerenderNavigationEntry(std::move(nav_entry));
FrameTree* target_frame_tree = web_contents_.GetFrameTree();
DCHECK_EQ(target_frame_tree, current_render_frame_host.frame_tree());
page->render_frame_host->SetFrameTreeNode(*(target_frame_tree->root()));
// TODO(https://crbug.com/1170277): Add testing for cross-origin iframes.
for (auto& it : page->proxy_hosts) {
it.second->set_frame_tree_node(*(target_frame_tree->root()));
}
// Iterate over root RenderFrameHost and all of its descendant frames and
// updates the associated frame tree. Note that subframe proxies don't need
// their FrameTrees independently updated, since their FrameTreeNodes don't
// change, and FrameTree references in those FrameTreeNodes will be updated
// through RenderFrameHosts.
//
// TODO(https://crbug.com/1170277): Need to investigate if and how
// pending delete RenderFrameHost objects should be handled if prerendering
// runs all of the unload handlers; they are not currently handled here.
// This is because pending delete RenderFrameHosts can still receive and
// process some messages while the RenderFrameHost FrameTree and
// FrameTreeNode are stale.
for (auto* rfh : AllDescendantActiveRenderFrameHosts(
*(page->render_frame_host.get()))) {
rfh->frame_tree_node()->SetFrameTree(*target_frame_tree);
rfh->SetFrameTree(*target_frame_tree);
rfh->render_view_host()->SetFrameTree(*target_frame_tree);
if (rfh->GetRenderWidgetHost()) {
rfh->GetRenderWidgetHost()->SetFrameTree(*target_frame_tree);
}
}
frame_tree_->Shutdown();
frame_tree_.reset();
return ActivateResult(FinalStatus::kActivated, std::move(page));
}
void WaitForLoadCompletionForTesting() override {
if (!frame_tree_->IsLoading())
return;
base::RunLoop loop;
on_stopped_loading_for_tests_ = loop.QuitClosure();
loop.Run();
}
private:
// WebContents where this prerenderer is embedded.
WebContentsImpl& web_contents_;
// Frame tree created for the prerenderer to load the page and prepare it for
// a future activation. During activation, the prerendered page will be taken
// out from |frame_tree_| and moved over to |web_contents_|'s primary frame
// tree, while |frame_tree_| will be deleted.
std::unique_ptr<FrameTree> frame_tree_;
base::OnceClosure on_stopped_loading_for_tests_;
};
class PrerenderHost::WebContentsPageHolder
: public PrerenderHost::PageHolderInterface {
public:
explicit WebContentsPageHolder(BrowserContext* browser_context) {
DCHECK(blink::features::IsPrerenderWebContentsEnabled());
// Create a new WebContents for prerendering.
WebContents::CreateParams web_contents_params(browser_context);
web_contents_params.is_prerendering = true;
// TODO(https://crbug.com/1132746): Set up other fields of
// `web_contents_params` as well, and add tests for them.
web_contents_ = WebContents::Create(web_contents_params);
DCHECK(static_cast<WebContentsImpl*>(web_contents_.get())
->GetFrameTree()
->is_prerendering());
}
~WebContentsPageHolder() override = default;
// PageHolder
NavigationController& GetNavigationController() override {
return web_contents_->GetController();
}
RenderFrameHostImpl* GetMainFrame() override {
return static_cast<RenderFrameHostImpl*>(web_contents_->GetMainFrame());
}
WebContents* GetWebContents() override { return web_contents_.get(); }
ActivateResult Activate(RenderFrameHostImpl& current_render_frame_host,
NavigationRequest& navigation_request) override {
auto* current_web_contents =
WebContents::FromRenderFrameHost(¤t_render_frame_host);
DCHECK(current_web_contents);
// Merge browsing history.
GetNavigationController().CopyStateFromAndPrune(
¤t_web_contents->GetController(), /*replace_entry=*/false);
// Activate the prerendered contents.
WebContentsDelegate* delegate = current_web_contents->GetDelegate();
DCHECK(delegate);
DCHECK(GetMainFrame()->frame_tree()->is_prerendering());
GetMainFrame()->frame_tree()->ActivatePrerenderedFrameTree();
// Tentatively use Portal's activation function.
// TODO(https://crbug.com/1132746): Replace this with the MPArch.
std::unique_ptr<WebContents> predecessor_web_contents =
delegate->ActivatePortalWebContents(current_web_contents,
std::move(web_contents_));
// Stop loading on the predecessor WebContents.
predecessor_web_contents->Stop();
return ActivateResult(FinalStatus::kActivated, nullptr);
}
void WaitForLoadCompletionForTesting() override {
if (!web_contents_ || !static_cast<WebContentsImpl*>(web_contents_.get())
->GetFrameTree()
->IsLoading()) {
return;
}
base::RunLoop loop;
LoadStopObserver observer(web_contents_.get(), loop.QuitClosure());
loop.Run();
}
private:
class LoadStopObserver : public WebContentsObserver {
public:
LoadStopObserver(WebContents* web_contents,
base::OnceClosure on_stopped_loading)
: WebContentsObserver(web_contents),
on_stopped_loading_(std::move(on_stopped_loading)) {}
void DidStopLoading() override {
std::move(on_stopped_loading_).Run();
Observe(nullptr);
}
private:
base::OnceClosure on_stopped_loading_;
};
std::unique_ptr<WebContents> web_contents_;
};
PrerenderHost::PrerenderHost(blink::mojom::PrerenderAttributesPtr attributes,
RenderFrameHostImpl& initiator_render_frame_host)
: attributes_(std::move(attributes)),
initiator_origin_(initiator_render_frame_host.GetLastCommittedOrigin()),
initiator_process_id_(initiator_render_frame_host.GetProcess()->GetID()),
initiator_frame_token_(initiator_render_frame_host.GetFrameToken()) {
DCHECK(blink::features::IsPrerender2Enabled());
auto* web_contents =
WebContents::FromRenderFrameHost(&initiator_render_frame_host);
DCHECK(web_contents);
CreatePageHolder(*static_cast<WebContentsImpl*>(web_contents));
}
// TODO(https://crbug.com/1132746): Abort ongoing prerendering and notify the
// mojo capability controller in the destructor.
PrerenderHost::~PrerenderHost() {
for (auto& observer : observers_)
observer.OnHostDestroyed();
if (!final_status_)
RecordFinalStatus(FinalStatus::kDestroyed);
}
// TODO(https://crbug.com/1132746): Inspect diffs from the current
// no-state-prefetch implementation. See PrerenderContents::StartPrerendering()
// for example.
void PrerenderHost::StartPrerendering() {
TRACE_EVENT0("navigation", "PrerenderHost::StartPrerendering");
// Observe events about the prerendering contents.
Observe(page_holder_->GetWebContents());
// Start prerendering navigation.
NavigationController::LoadURLParams load_url_params(attributes_->url);
load_url_params.initiator_origin = initiator_origin_;
load_url_params.initiator_process_id = initiator_process_id_;
load_url_params.initiator_frame_token = initiator_frame_token_;
// Just use the referrer from attributes, as NoStatePrefetch does.
// TODO(crbug.com/1176054): For cross-origin prerender, follow the spec steps
// for "sufficiently-strict speculative navigation referrer policies".
if (attributes_->referrer)
load_url_params.referrer = Referrer(*attributes_->referrer);
// TODO(https://crbug.com/1132746): Set up other fields of `load_url_params`
// as well, and add tests for them.
page_holder_->GetNavigationController().LoadURLWithParams(load_url_params);
}
// TODO(https://crbug.com/1170277): Does not work with MPArch as we get
// navigation events for all FrameTrees.
void PrerenderHost::DidFinishNavigation(NavigationHandle* navigation_handle) {
// The prerendered contents are considered ready for activation when it
// reaches DidFinishNavigation.
DCHECK(!is_ready_for_activation_);
is_ready_for_activation_ = true;
// Stop observing the events about the prerendered contents.
Observe(nullptr);
}
std::unique_ptr<BackForwardCacheImpl::Entry>
PrerenderHost::ActivatePrerenderedContents(
RenderFrameHostImpl& old_render_frame_host,
NavigationRequest& navigation_request) {
TRACE_EVENT1("navigation", "PrerenderHost::ActivatePrerenderedContents",
"render_frame_host", old_render_frame_host);
DCHECK(is_ready_for_activation_);
is_ready_for_activation_ = false;
ActivateResult result =
page_holder_->Activate(old_render_frame_host, navigation_request);
if (result.status != FinalStatus::kActivated) {
RecordFinalStatus(result.status);
return nullptr;
}
for (auto& observer : observers_)
observer.OnActivated();
RecordFinalStatus(FinalStatus::kActivated);
// NOTE: for activation with multiple WebContents, `entry` is null.
return std::move(result.entry);
}
RenderFrameHostImpl* PrerenderHost::GetPrerenderedMainFrameHost() {
return page_holder_->GetMainFrame();
}
void PrerenderHost::RecordFinalStatus(base::PassKey<PrerenderHostRegistry>,
FinalStatus status) {
RecordFinalStatus(status);
}
void PrerenderHost::CreatePageHolder(WebContentsImpl& web_contents) {
switch (blink::features::kPrerender2ImplementationParam.Get()) {
case blink::features::Prerender2Implementation::kWebContents: {
page_holder_ = std::make_unique<WebContentsPageHolder>(
web_contents.GetBrowserContext());
break;
}
case blink::features::Prerender2Implementation::kMPArch: {
page_holder_ = std::make_unique<MPArchPageHolder>(web_contents);
break;
}
}
frame_tree_node_id_ = page_holder_->GetMainFrame()->GetFrameTreeNodeId();
}
void PrerenderHost::WaitForLoadStopForTesting() {
page_holder_->WaitForLoadCompletionForTesting(); // IN-TEST
}
FrameTree* PrerenderHost::GetPrerenderedFrameTree() {
DCHECK(page_holder_);
return page_holder_->GetMainFrame()->frame_tree();
}
void PrerenderHost::RecordFinalStatus(FinalStatus status) {
DCHECK(!final_status_);
final_status_ = status;
base::UmaHistogramEnumeration(
"Prerender.Experimental.PrerenderHostFinalStatus", status);
}
const GURL& PrerenderHost::GetInitialUrl() const {
return attributes_->url;
}
void PrerenderHost::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void PrerenderHost::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
bool PrerenderHost::IsAssociatedWith(const WebContentsImpl& web_contents) {
return page_holder_->GetWebContents() == &web_contents;
}
} // namespace content
| 38.519751 | 80 | 0.729167 | iridium-browser |
47477c973bc9e3b331ff840cd45038d5bfa7a81a | 1,178 | cpp | C++ | src/LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Evolution/RateDifferenceConditionPreferenceGroup.cpp | domin1101/ANNHelper | 50acb5746d6dad6777532e4c7da4983a7683efe0 | [
"Zlib"
] | 5 | 2016-02-04T06:14:42.000Z | 2017-02-06T02:21:43.000Z | src/LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Evolution/RateDifferenceConditionPreferenceGroup.cpp | domin1101/ANNHelper | 50acb5746d6dad6777532e4c7da4983a7683efe0 | [
"Zlib"
] | 41 | 2015-04-15T21:05:45.000Z | 2015-07-09T12:59:02.000Z | src/LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Evolution/RateDifferenceConditionPreferenceGroup.cpp | domin1101/LightBulb | 50acb5746d6dad6777532e4c7da4983a7683efe0 | [
"Zlib"
] | null | null | null | // Includes
#include "LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Evolution/RateDifferenceConditionPreferenceGroup.hpp"
#include "LightBulbApp/TrainingPlans/Preferences/IntegerPreference.hpp"
#include "LightBulbApp/TrainingPlans/Preferences/DoublePreference.hpp"
#include "LightBulb/Learning/Evolution/RateDifferenceCondition.hpp"
namespace LightBulb
{
#define PREFERENCE_DIFFERENCE "Difference"
#define PREFERENCE_ITERATIONS "Iterations"
RateDifferenceConditionPreferenceGroup::RateDifferenceConditionPreferenceGroup(const std::string& name)
:PreferenceGroup(name)
{
addPreference(new DoublePreference(PREFERENCE_DIFFERENCE, 0.00001, 0, 1));
addPreference(new IntegerPreference(PREFERENCE_ITERATIONS, 10, 0, 100));
}
RateDifferenceCondition* RateDifferenceConditionPreferenceGroup::create() const
{
double difference = getDoublePreference(PREFERENCE_DIFFERENCE);
int iterations = getIntegerPreference(PREFERENCE_ITERATIONS);
return new RateDifferenceCondition(difference, iterations);
}
AbstractCloneable* RateDifferenceConditionPreferenceGroup::clone() const
{
return new RateDifferenceConditionPreferenceGroup(*this);
}
}
| 36.8125 | 129 | 0.837861 | domin1101 |
474785b19cfc9676eb90451dfbd807f1f5548fe3 | 11,465 | cpp | C++ | unittests/conversation.cpp | traviscross/libzina | 6583baa68549a7d90bf6f9af5836361e41b3cef5 | [
"Apache-2.0"
] | 21 | 2016-04-03T00:05:34.000Z | 2020-05-19T23:08:37.000Z | unittests/conversation.cpp | traviscross/libzina | 6583baa68549a7d90bf6f9af5836361e41b3cef5 | [
"Apache-2.0"
] | null | null | null | unittests/conversation.cpp | traviscross/libzina | 6583baa68549a7d90bf6f9af5836361e41b3cef5 | [
"Apache-2.0"
] | 4 | 2018-01-15T07:17:27.000Z | 2021-01-10T02:01:37.000Z | /*
Copyright 2016 Silent Circle, LLC
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 <malloc.h>
#include "gtest/gtest.h"
#include "../ratchet/state/ZinaConversation.h"
#include "../storage/sqlite/SQLiteStoreConv.h"
#include "../ratchet/crypto/EcCurve.h"
#include "../logging/ZinaLogging.h"
using namespace zina;
using namespace std;
static std::string aliceName("alice@wonderland.org");
static std::string bobName("bob@milkyway.com");
static std::string aliceDev("aliceDevId");
static std::string bobDev("BobDevId");
static const uint8_t keyInData[] = {0,1,2,3,4,5,6,7,8,9,19,18,17,16,15,14,13,12,11,10,20,21,22,23,24,25,26,27,28,20,31,30};
/**
* @brief Storage test fixture class that supports memory leak checking.
*
* NOTE: when using this class as a base class for a test fixture,
* the derived class should not create any local member variables, as
* they can cause memory leaks to be improperly reported.
*/
class StoreTestFixture: public ::testing::Test {
public:
StoreTestFixture( ) {
// initialization code here
}
// code here will execute just before the test ensues
void SetUp() {
// capture the memory state at the beginning of the test
struct mallinfo minfo = mallinfo();
beginMemoryState = minfo.uordblks;
LOGGER_INSTANCE setLogLevel(WARNING);
store = SQLiteStoreConv::getStore();
store->setKey(std::string((const char*)keyInData, 32));
store->openStore(std::string());
}
void TearDown( ) {
// code here will be called just after the test completes
// ok to through exceptions from here if need be
SQLiteStoreConv::closeStore();
// only check for memory leaks if the test did not end in a failure
// NOTE: the logging via LOGGER statements may give wronge results. Thus either switch of
// logging (LOGGER_INSTANCE setLogLevel(NONE);) during tests (after debugging :-) ) or make
// sure that no errors etc are logged. The memory info may be wrong if the LOGGER really
// prints out some data.
if (!HasFailure())
{
// Gets information about the currently running test.
// Do NOT delete the returned object - it's managed by the UnitTest class.
const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info();
// if there are differences between the memory state at beginning and end, then there are memory leaks
struct mallinfo minfo = mallinfo();
if ( beginMemoryState != minfo.uordblks )
{
FAIL() << "Memory Leak(s) detected in " << test_info->name()
<< ", test case: " << test_info->test_case_name()
<< ", memory before: " << beginMemoryState << ", after: " << minfo.uordblks
<< ", difference: " << minfo.uordblks - beginMemoryState
<< endl;
}
}
}
~StoreTestFixture( ) {
// cleanup any pending stuff, but no exceptions allowed
LOGGER_INSTANCE setLogLevel(VERBOSE);
}
// put in any custom data members that you need
SQLiteStoreConv* store;
int beginMemoryState;
};
TEST_F(StoreTestFixture, BasicEmpty)
{
// localUser, remote user, remote dev id
ZinaConversation conv(aliceName, bobName, bobDev);
conv.storeConversation(*store);
ASSERT_FALSE(SQL_FAIL(store->getSqlCode())) << store->getLastError();
auto conv1 = ZinaConversation::loadConversation(aliceName, bobName, bobDev, *store);
ASSERT_TRUE(conv1 != NULL);
ASSERT_TRUE(conv1->getRK().empty());
}
TEST_F(StoreTestFixture, TestDHR)
{
// localUser, remote user, remote dev id
ZinaConversation conv(aliceName, bobName, bobDev);
conv.setRatchetFlag(true);
conv.setDHRr(PublicKeyUnique(new Ec255PublicKey(keyInData)));
PublicKeyUnique pubKey = PublicKeyUnique(new Ec255PublicKey(conv.getDHRr().getPublicKeyPointer()));
conv.setDHRs(EcCurve::generateKeyPair(EcCurveTypes::Curve25519));
KeyPairUnique keyPair(new DhKeyPair(conv.getDHRs().getPublicKey(), conv.getDHRs().getPrivateKey()));
conv.storeConversation(*store);
auto conv1 = ZinaConversation::loadConversation(aliceName, bobName, bobDev, *store);
ASSERT_TRUE(conv1 != NULL);
ASSERT_TRUE(conv1->getRatchetFlag());
const DhKeyPair& keyPair1 = conv1->getDHRs();
ASSERT_TRUE(conv1->hasDHRs());
ASSERT_TRUE(keyPair->getPublicKey() == keyPair1.getPublicKey());
const DhPublicKey& pubKey1 = conv1->getDHRr();
ASSERT_TRUE(conv1->hasDHRr());
ASSERT_TRUE(*pubKey == pubKey1);
}
TEST_F(StoreTestFixture, TestDHI)
{
// localUser, remote user, remote dev id
ZinaConversation conv(aliceName, bobName, bobDev);
conv.setRatchetFlag(true);
conv.setDHIr(PublicKeyUnique(new Ec255PublicKey(keyInData)));
PublicKeyUnique pubKey = PublicKeyUnique(new Ec255PublicKey(conv.getDHIr().getPublicKeyPointer()));
conv.setDHIs(EcCurve::generateKeyPair(EcCurveTypes::Curve25519));
KeyPairUnique keyPair(new DhKeyPair(conv.getDHIs().getPublicKey(), conv.getDHIs().getPrivateKey()));
conv.storeConversation(*store);
auto conv1 = ZinaConversation::loadConversation(aliceName, bobName, bobDev,*store);
ASSERT_TRUE(conv1 != NULL);
ASSERT_TRUE(conv1->getRatchetFlag());
const DhKeyPair& keyPair1 = conv1->getDHIs();
ASSERT_TRUE(conv1->hasDHIs());
ASSERT_TRUE(keyPair->getPublicKey() == keyPair1.getPublicKey());
const DhPublicKey& pubKey1 = conv1->getDHIr();
ASSERT_TRUE(conv1->hasDHIr());
ASSERT_TRUE(*pubKey == pubKey1);
}
TEST_F(StoreTestFixture, TestA0)
{
// localUser, remote user, remote dev id
ZinaConversation conv(aliceName, bobName, bobDev);
conv.setRatchetFlag(true);
conv.setA0(EcCurve::generateKeyPair(EcCurveTypes::Curve25519));
KeyPairUnique keyPair(new DhKeyPair(conv.getA0().getPublicKey(), conv.getA0().getPrivateKey()));
conv.storeConversation(*store);
auto conv1 = ZinaConversation::loadConversation(aliceName, bobName, bobDev, *store);
ASSERT_TRUE(conv1 != NULL);
ASSERT_TRUE(conv1->getRatchetFlag());
const DhKeyPair& keyPair1 = conv1->getA0();
ASSERT_TRUE(conv1->hasA0());
ASSERT_TRUE(keyPair->getPublicKey() == keyPair1.getPublicKey());
}
TEST_F(StoreTestFixture, SimpleFields)
{
string RK("RootKey");
string CKs("ChainKeyS 1");
string CKr("ChainKeyR 1");
// localUser, remote user, remote dev id
ZinaConversation conv(aliceName, bobName, bobDev);
conv.setRK(RK);
conv.setCKr(CKr);
conv.setCKs(CKs);
conv.setNr(3);
conv.setNs(7);
conv.setPNs(11);
conv.setPreKeyId(13);
string tst("test");
conv.setDeviceName(tst);
conv.storeConversation(*store);
auto conv1 = ZinaConversation::loadConversation(aliceName, bobName, bobDev, *store);
ASSERT_EQ(RK, conv1->getRK());
ASSERT_EQ(CKr, conv1->getCKr());
ASSERT_EQ(CKs, conv1->getCKs());
ASSERT_EQ(3, conv1->getNr());
ASSERT_EQ(7, conv1->getNs());
ASSERT_EQ(11, conv1->getPNs());
ASSERT_EQ(13, conv1->getPreKeyId());
ASSERT_TRUE(tst == conv1->getDeviceName());
}
TEST_F(StoreTestFixture, SecondaryRatchet)
{
string RK("RootKey");
string CKs("ChainKeyS 1");
string CKr("ChainKeyR 1");
// localUser, remote user, remote dev id
ZinaConversation conv(aliceName, bobName, bobDev);
conv.setRK(RK);
conv.setCKr(CKr);
conv.setCKs(CKs);
conv.saveSecondaryAddress(aliceDev, 4711);
conv.setNr(3);
conv.setNs(7);
conv.setPNs(11);
conv.setPreKeyId(13);
string tst("test");
conv.setDeviceName(tst);
conv.storeConversation(*store);
auto conv1 = ZinaConversation::loadConversation(aliceName, bobName, bobDev, *store);
string devId = conv1->lookupSecondaryDevId(4711);
ASSERT_EQ(aliceDev, devId);
ASSERT_EQ(RK, conv1->getRK());
ASSERT_EQ(CKr, conv1->getCKr());
ASSERT_EQ(CKs, conv1->getCKs());
ASSERT_EQ(3, conv1->getNr());
ASSERT_EQ(7, conv1->getNs());
ASSERT_EQ(11, conv1->getPNs());
ASSERT_EQ(13, conv1->getPreKeyId());
ASSERT_TRUE(tst == conv1->getDeviceName());
}
///**
// * A base GTest (GoogleTest) text fixture class that supports memory leak checking.
// *
// * NOTE: when using this class as a base class for a test fixture,
// * the derived class should not create any local member variables, as
// * they can cause memory leaks to be improperly reported.
// */
//
//class BaseTestFixture : public ::testing::Test
//{
//public:
// virtual void SetUp()
// {
// // capture the memory state at the beginning of the test
// struct mallinfo minfo = mallinfo();
// beginMemoryState = minfo.uordblks;
// }
//
// virtual void TearDown()
// {
// // only check for memory leaks if the test did not end in a failure
// if (!HasFailure())
// {
// // Gets information about the currently running test.
// // Do NOT delete the returned object - it's managed by the UnitTest class.
// const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info();
//
// // if there are differences between the memory state at beginning and end, then there are memory leaks
// struct mallinfo minfo = mallinfo();
// if ( beginMemoryState != minfo.uordblks )
// {
// FAIL() << "Memory Leak(s) Detected in " << test_info->name() << ", test case: " << test_info->test_case_name() << endl;
// }
// }
// }
//
//private:
// // memory state at the beginning of the test fixture set up
// int beginMemoryState;
//};
//
////----------------------------------------------------------------
//// check that allocating nothing doesn't throw a false positive
////----------------------------------------------------------------
//TEST_F(BaseTestFixture, BaseTestFixtureTest)
//{
// // should always pass an empty test
//}
//
////----------------------------------------------------------------
//// check that malloc()ing something is detected
////----------------------------------------------------------------
//TEST_F(BaseTestFixture, BaseTestFixtureMallocTest)
//{
// // should always fail
// void* p = malloc(10);
//}
//
////----------------------------------------------------------------
//// check that new()ing something is detected
////----------------------------------------------------------------
//TEST_F(BaseTestFixture, BaseTestFixtureNewFailTest)
//{
// // should always fail
// int* array = new int[10];
//}
//
////----------------------------------------------------------------
////
////----------------------------------------------------------------
//TEST_F(BaseTestFixture, BaseTestFixtureNewTest)
//{
// void* p = malloc(10);
// free( p );
//}
| 34.637462 | 137 | 0.632883 | traviscross |
47485c6e3aeca10613b76c90156abf333b5ac49a | 2,178 | cpp | C++ | src/kinematics.cpp | Valts-M/ros2_com | 647bfb815595309ef469cbf81a1f7f1b9bb1fc3c | [
"Apache-2.0"
] | null | null | null | src/kinematics.cpp | Valts-M/ros2_com | 647bfb815595309ef469cbf81a1f7f1b9bb1fc3c | [
"Apache-2.0"
] | null | null | null | src/kinematics.cpp | Valts-M/ros2_com | 647bfb815595309ef469cbf81a1f7f1b9bb1fc3c | [
"Apache-2.0"
] | null | null | null | #include "kinematics.hpp"
#include "tf2_geometry_msgs/tf2_geometry_msgs.h"
#include "tf2/LinearMath/Quaternion.h"
namespace ros2_com
{
Kinematics::Kinematics() : Kinematics::Kinematics(RobotConfig()){}
Kinematics::Kinematics(const RobotConfig& config) :
m_leftEncScale(config.leftEncScale),
m_rightEncScale(config.rightEncScale),
m_leftGyroScale(config.leftGyroScale),
m_rightGyroScale(config.RightGyroScale){}
void Kinematics::calcPosAndVelocity(const zbot::MsgRawStatus& input, nav_msgs::msg::Odometry& output)
{
const double leftDistance{input.encoders[0] * m_leftEncScale};
const double rightDistance{input.encoders[1] * m_rightEncScale};
const double distanceTraveled{(leftDistance + rightDistance) / 2};
//const double deltaAngle{(rightDistance - leftDistance) / m_wheelDistance};
const double trueGyroZ = input.gyroDelta - m_gyroBias;
const double deltaAngle{ trueGyroZ < 0 ? trueGyroZ * m_leftGyroScale : trueGyroZ * m_rightGyroScale};
//if moving update message
if(std::fabs(input.encoders[0]) > 10 || std::fabs(input.encoders[1]) > 10)
{
m_yaw += deltaAngle;
output.pose.pose.position.x += distanceTraveled * cos(m_yaw);
output.pose.pose.position.y += distanceTraveled * sin(m_yaw);
//calibration
leftEncTicCount += input.encoders[0];
rightEncTicCount += input.encoders[1];
gyroTicCount += trueGyroZ;
//check if orientation is within bounds
if( m_yaw >= M_PI)
m_yaw -= 2 * M_PI;
else if( m_yaw <= -M_PI)
m_yaw += 2 * M_PI;
tf2::Quaternion temp;
temp.setRPY(0, 0, m_yaw);
tf2::convert(temp, output.pose.pose.orientation);
output.twist.twist.linear.x = distanceTraveled / input.time;
output.twist.twist.angular.z = deltaAngle / input.time;
}
else //if not moving recalculate gyro bias
{
gyroBuf.push_back(input.gyroDelta);
m_gyroTicSum += input.gyroDelta;
if(gyroBuf.full())
{
m_gyroTicSum -= gyroBuf.front();
}
else
{
++m_noMovementCount;
}
m_gyroBias = m_gyroTicSum / m_noMovementCount;
}
}
} | 33 | 105 | 0.671258 | Valts-M |
4748e87d994c95ffb85a21593ef1eca52c2bc317 | 835 | cpp | C++ | utility.cpp | leannejdong/INSEL_PARSER | 8bc1462cea56741b26adcbf7531819d051e3b6bd | [
"MIT"
] | 1 | 2020-12-25T13:57:47.000Z | 2020-12-25T13:57:47.000Z | utility.cpp | leannejdong/Insel_parser | 8bc1462cea56741b26adcbf7531819d051e3b6bd | [
"MIT"
] | null | null | null | utility.cpp | leannejdong/Insel_parser | 8bc1462cea56741b26adcbf7531819d051e3b6bd | [
"MIT"
] | null | null | null | //
// Created by leanne on 1/6/21.
//
#include "utility.h"
#include<algorithm>
#include<sstream>
#include<fstream>
using std::string;
using std::vector;
using std::istringstream;
vector<int> strToVecInts(const string &graph_string)
{
vector<int> vecInts;
istringstream input_stream(graph_string);
int number;
while(input_stream >> number) {
vecInts.push_back(number);
}
return vecInts;
}
Edges parseGraph(const string &graph_string)
{
std::ifstream split(graph_string);
string each;
Edges V;
while (std::getline(split, each)) {
vector<int> vec1 = strToVecInts(each);
std::getline(split, each);
vector<int> vec2 = strToVecInts(each);
for (int x : vec2) {
V.push_back(std::make_pair(vec1[0] - 1, x - 1));
}
}
return V;
}
| 18.977273 | 60 | 0.627545 | leannejdong |
474930886378e71436fb9e874ec1996d99a8cec5 | 1,849 | cpp | C++ | test/unit/math/rev/core/grad_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/rev/core/grad_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/rev/core/grad_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | #include <gtest/gtest.h>
#include <test/unit/math/rev/fun/util.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/sin.hpp>
#include <vector>
TEST(AgradRev, multiple_grads) {
for (int i = 0; i < 100; ++i) {
stan::math::var a = 2.0;
stan::math::var b = 3.0 * a;
stan::math::var c = sin(a) * b;
// fixes warning regarding unused variable
c = c;
stan::math::var nothing;
}
stan::math::var d = 2.0;
stan::math::var e = 3.0;
stan::math::var f = d * e;
std::vector<stan::math::var> x{d, e};
std::vector<double> grad_f;
f.grad(x, grad_f);
EXPECT_FLOAT_EQ(3.0, d.adj());
EXPECT_FLOAT_EQ(2.0, e.adj());
EXPECT_FLOAT_EQ(3.0, grad_f[0]);
EXPECT_FLOAT_EQ(2.0, grad_f[1]);
}
TEST(AgradRev, ensure_first_vari_chained) {
using stan::math::var;
// Make sure there aren't any varis on stack
stan::math::recover_memory();
int N = 10;
std::vector<var> vars;
var total = 0.0;
for (int i = 0; i < N; ++i) {
vars.push_back(0.0);
total += vars.back();
}
total.grad();
EXPECT_FLOAT_EQ(0.0, total.val());
for (int i = 0; i < N; ++i) {
EXPECT_FLOAT_EQ(1.0, vars[i].adj());
}
}
namespace stan {
namespace math {
class test_vari : public vari {
public:
test_vari() : vari(0.0) {}
virtual void chain() {
stan::math::nested_rev_autodiff nested;
// Add enough vars to make the the var_stack_ vector reallocate
int N_new_vars = ChainableStack::instance_->var_stack_.capacity() + 1;
var total = 0.0;
for (int i = 0; i < N_new_vars; ++i) {
total += i;
}
total.grad();
}
};
} // namespace math
} // namespace stan
TEST(AgradRev, nested_grad_during_chain) {
using stan::math::var;
var total = 0.0;
for (int i = 0; i < 2; ++i) {
total += i;
}
var test_var(new stan::math::test_vari());
test_var.grad();
}
| 19.88172 | 74 | 0.600865 | LaudateCorpus1 |
474f455e0b90a74010298dbffc9363c798ebd1cd | 17,913 | cpp | C++ | shaderapivulkan/src/TF2Vulkan/meshes/VulkanMesh.cpp | melvyn2/TF2Vulkan | a8cd1c49ecfe9d4dc31af0a50ba7690c61c255c4 | [
"MIT"
] | null | null | null | shaderapivulkan/src/TF2Vulkan/meshes/VulkanMesh.cpp | melvyn2/TF2Vulkan | a8cd1c49ecfe9d4dc31af0a50ba7690c61c255c4 | [
"MIT"
] | null | null | null | shaderapivulkan/src/TF2Vulkan/meshes/VulkanMesh.cpp | melvyn2/TF2Vulkan | a8cd1c49ecfe9d4dc31af0a50ba7690c61c255c4 | [
"MIT"
] | null | null | null | #include "TF2Vulkan/IShaderAPI/IShaderAPI_StateManagerDynamic.h"
#include "interface/IMaterialInternal.h"
#include "interface/internal/IBufferPoolInternal.h"
#include "interface/internal/IShaderDeviceInternal.h"
#include "interface/internal/IStateManagerStatic.h"
#include "TF2Vulkan/VulkanFactories.h"
#include "VulkanMesh.h"
#include <TF2Vulkan/Util/FourCC.h>
#include "TF2Vulkan/Util/Misc.h"
#include <TF2Vulkan/Util/std_variant.h>
using namespace TF2Vulkan;
static std::atomic<uint32_t> s_VulkanGPUBufferIndex = 0;
void VulkanGPUBuffer::AssertCheckHeap()
{
ENSURE(_CrtCheckMemory());
}
static void ValidateVertexFormat(VertexFormat meshFormat, VertexFormat materialFormat)
{
if (!materialFormat.IsCompressed())
assert(!meshFormat.IsCompressed());
const auto CheckFlag = [&](VertexFormatFlags flag)
{
if (meshFormat.m_Flags & flag)
{
assert(materialFormat.m_Flags & flag);
}
};
CheckFlag(VertexFormatFlags::Position);
CheckFlag(VertexFormatFlags::Normal);
CheckFlag(VertexFormatFlags::Color);
CheckFlag(VertexFormatFlags::Specular);
CheckFlag(VertexFormatFlags::TangentS);
CheckFlag(VertexFormatFlags::TangentT);
CheckFlag(VertexFormatFlags::Wrinkle);
// Questionable checks
#if false
CheckFlag(VertexFormatFlags::BoneIndex);
#endif
}
int VulkanMesh::GetRoomRemaining() const
{
auto lock = ScopeThreadLock();
LOG_FUNC_ANYTHREAD();
const auto vtxRoom = m_VertexBuffer->GetRoomRemaining();
const auto idxRoom = m_IndexBuffer->GetRoomRemaining();
assert(vtxRoom == idxRoom);
return Util::algorithm::min(vtxRoom, idxRoom);
}
VertexFormat VulkanMesh::GetColorMeshFormat() const
{
LOG_FUNC_ANYTHREAD();
return m_ColorMesh ? VertexFormat(m_ColorMesh->GetVertexFormat()) : VertexFormat{};
}
void VulkanMesh::OverrideVertexBuffer(IMesh* src)
{
auto lock = ScopeThreadLock();
LOG_FUNC_ANYTHREAD();
if (src)
{
if (!m_OriginalVertexBuffer)
m_OriginalVertexBuffer = m_VertexBuffer;
m_VertexBuffer = assert_cast<VulkanMesh*>(src)->m_VertexBuffer;
}
else
{
if (m_OriginalVertexBuffer)
m_VertexBuffer = std::move(m_OriginalVertexBuffer);
}
}
void VulkanMesh::OverrideIndexBuffer(IMesh* src)
{
auto lock = ScopeThreadLock();
LOG_FUNC_ANYTHREAD();
if (src)
{
if (!m_OriginalIndexBuffer)
m_OriginalIndexBuffer = m_IndexBuffer;
m_IndexBuffer = assert_cast<VulkanMesh*>(src)->m_IndexBuffer;
}
else
{
if (m_OriginalIndexBuffer)
m_IndexBuffer = std::move(m_OriginalIndexBuffer);
}
}
void VulkanGPUBuffer::UpdateDynamicBuffer()
{
auto lock = ScopeThreadLock();
LOG_FUNC_ANYTHREAD();
if (IsDynamic())
{
if (Util::IsMainThread())
{
TF2VULKAN_PIX_MARKER("UpdateDynamicBuffer %s [dynamic]: %zu bytes",
vk::to_string(m_Usage).c_str(),
m_CPUBuffer.size());
}
// Just memcpy into the dynamic buffer
//if (updateSize > 0 || !std::holds_alternative<BufferPoolEntry>(m_Buffer))
m_Buffer = g_ShaderDevice.GetBufferPool(m_Usage).Create(m_CPUBuffer.size(), m_CPUBuffer.data());
}
}
void* VulkanGPUBuffer::GetBuffer(size_t size, bool truncate)
{
AssertHasLock();
LOG_FUNC_ANYTHREAD();
if (Util::IsMainThread())
{
TF2VULKAN_PIX_MARKER("GetBuffer(size = %zu, truncate = %s) %s [%s]",
m_CPUBuffer.size(), truncate ? "true" : "false",
vk::to_string(m_Usage).c_str(),
IsDynamic() ? "dynamic" : "static");
}
if (truncate || m_CPUBuffer.size() < size)
m_CPUBuffer.resize(size);
return m_CPUBuffer.data();
}
void VulkanGPUBuffer::CommitModifications(size_t updateBegin, size_t updateSize)
{
AssertHasLock();
LOG_FUNC_ANYTHREAD();
if (!IsDynamic())
{
if (Util::IsMainThread())
{
TF2VULKAN_PIX_MARKER("CommitModifications %s [static]: %zu bytes @ offset %zu",
vk::to_string(m_Usage).c_str(),
updateBegin, updateSize);
}
assert(std::holds_alternative<std::monostate>(m_Buffer) || std::holds_alternative<vma::AllocatedBuffer>(m_Buffer));
auto entry = g_ShaderDevice
.GetBufferPool(vk::BufferUsageFlagBits::eTransferSrc)
.Create(updateSize, Util::OffsetPtr(m_CPUBuffer.data(), updateBegin));
const auto& realPool = static_cast<const IBufferPoolInternal&>(entry.GetPool());
const auto entryInfo = realPool.GetBufferInfo(entry);
auto& cmdBuf = g_ShaderDevice.GetPrimaryCmdBuf();
auto& dstBuf = Util::get_or_emplace<vma::AllocatedBuffer>(m_Buffer);
if (!dstBuf || dstBuf.size() < m_CPUBuffer.size())
{
if (dstBuf)
cmdBuf.AddResource(std::move(dstBuf));
char dbgName[128];
sprintf_s(dbgName, "VulkanGPUBuffer #%u [static] [%zu, %zu)", ++s_VulkanGPUBufferIndex,
updateBegin, updateBegin + updateSize);
dstBuf = Factories::BufferFactory{}
.SetSize(m_CPUBuffer.size())
.SetUsage(m_Usage | vk::BufferUsageFlagBits::eTransferDst)
.SetMemoryType(vma::MemoryType::eGpuOnly)
.SetDebugName(dbgName)
.Create();
}
const auto region = vk::BufferCopy{}
.setSize(updateSize)
.setSrcOffset(entry.GetOffset())
.setDstOffset(updateBegin);
if (auto [transfer, lock] = g_ShaderDevice.GetTransferQueue().locked(); transfer)
{
auto transferCmdBuf = transfer->CreateCmdBufferAndBegin();
transferCmdBuf->copyBuffer(entryInfo.m_Buffer, dstBuf.GetBuffer(), region);
transferCmdBuf->Submit();
}
else
{
cmdBuf.TryEndRenderPass();
cmdBuf.copyBuffer(entryInfo.m_Buffer, dstBuf.GetBuffer(), region);
}
}
}
VulkanMesh::VulkanMesh(const VertexFormat& fmt, bool isDynamic) :
m_VertexBuffer(std::make_shared<VulkanVertexBuffer>(fmt, isDynamic)),
m_IndexBuffer(std::make_shared<VulkanIndexBuffer>(isDynamic))
{
}
VulkanMesh::VulkanMesh(const VertexFormat& fmt) :
VulkanMesh(fmt, false)
{
}
void VulkanMesh::Draw(int firstIndex, int indexCount)
{
auto lock = ScopeThreadLock();
LOG_FUNC();
if (!g_ShaderDevice.IsPrimaryCmdBufReady())
{
Warning(TF2VULKAN_PREFIX "Skipping mesh draw, shader device not ready yet\n");
return;
}
if (firstIndex == -1)
{
// "Start at true zero"?
firstIndex = 0;
}
assert(firstIndex >= 0); // Catch other weird values
assert(indexCount >= 0);
if (indexCount == 0)
{
// Apparently, 0 means "draw everything"
indexCount = IndexCount();
if (indexCount <= 0)
return; // Nothing to draw
}
assert((firstIndex + indexCount) <= IndexCount());
ActiveMeshScope meshScope(ActiveMeshData{ this, firstIndex, indexCount });
auto& dynState = g_StateManagerDynamic.GetDynamicState();
auto internalMaterial = assert_cast<IMaterialInternal*>(dynState.m_BoundMaterial);
#ifdef _DEBUG
[[maybe_unused]] auto matName = internalMaterial->GetName();
[[maybe_unused]] auto shader = internalMaterial->GetShader();
[[maybe_unused]] auto shaderName = internalMaterial->GetShaderName();
#endif
internalMaterial->DrawMesh(VertexFormat(GetVertexFormat()).GetCompressionType());
}
void VulkanMesh::DrawInternal(IVulkanCommandBuffer& cmdBuf, int firstIndex, int indexCount)
{
auto lock = ScopeThreadLock();
LOG_FUNC();
if (!VertexCount())
{
assert(!indexCount == !VertexCount());
Warning(TF2VULKAN_PREFIX "No vertices\n");
TF2VULKAN_PIX_MARKER("No vertices");
return;
}
vk::Buffer indexBuffer, vertexBuffer, vertexBufferColor;
size_t indexBufferOffset, vertexBufferOffset, vertexBufferColorOffset = 0; // intentionally only last one assigned
m_IndexBuffer->GetGPUBuffer(indexBuffer, indexBufferOffset);
cmdBuf.bindIndexBuffer(indexBuffer, indexBufferOffset, vk::IndexType::eUint16);
m_VertexBuffer->GetGPUBuffer(vertexBuffer, vertexBufferOffset);
if (m_ColorMesh)
{
auto colorMeshInternal = assert_cast<IMeshInternal*>(m_ColorMesh);
auto& colorVB = colorMeshInternal->GetVertexBuffer();
colorVB.GetGPUBuffer(vertexBufferColor, vertexBufferColorOffset);
vertexBufferColorOffset += m_ColorMeshVertexOffset;
}
// Bind vertex buffers
{
const vk::Buffer vtxBufs[] =
{
g_ShaderDevice.GetDummyVertexBuffer(),
vertexBuffer,
vertexBufferColor,
};
const vk::DeviceSize offsets[] =
{
0,
vertexBufferOffset,
Util::SafeConvert<vk::DeviceSize>(vertexBufferColorOffset)
};
const uint32_t vbCount = m_ColorMesh ? 3 : 2;
static_assert(std::size(vtxBufs) == std::size(offsets));
cmdBuf.bindVertexBuffers(0, vk::ArrayProxy(vbCount, vtxBufs), vk::ArrayProxy(vbCount, offsets));
}
cmdBuf.drawIndexed(Util::SafeConvert<uint32_t>(indexCount), 1, Util::SafeConvert<uint32_t>(firstIndex));
MarkAsDrawn();
}
void VulkanMesh::SetColorMesh(IMesh* colorMesh, int vertexOffset)
{
auto lock = ScopeThreadLock();
LOG_FUNC_ANYTHREAD();
m_ColorMesh = colorMesh;
m_ColorMeshVertexOffset = vertexOffset;
}
void VulkanMesh::Draw(CPrimList* lists, int listCount)
{
auto lock = ScopeThreadLock();
LOG_FUNC();
// TODO: Indirect rendering?
//assert(listCount == 1);
for (int i = 0; i < listCount; i++)
Draw(lists[i].m_FirstIndex, lists[i].m_NumIndices);
}
void VulkanMesh::CopyToMeshBuilder(int startVert, int vertCount, int startIndex, int indexCount, int indexOffset, CMeshBuilder& builder)
{
NOT_IMPLEMENTED_FUNC();
}
void VulkanMesh::SetFlexMesh(IMesh* mesh, int vertexOffset)
{
LOG_FUNC();
if (mesh || vertexOffset)
NOT_IMPLEMENTED_FUNC_NOBREAK(); // TODO: This goes into vPosFlex and vNormalFlex
}
VulkanIndexBuffer::VulkanIndexBuffer(bool isDynamic) :
VulkanGPUBuffer(isDynamic, vk::BufferUsageFlagBits::eIndexBuffer)
{
}
void VulkanIndexBuffer::ModifyBegin(uint32_t firstIndex, uint32_t indexCount, IndexDesc_t& desc,
bool read, bool write, bool truncate)
{
LOG_FUNC_ANYTHREAD();
desc = {};
desc.m_nIndexSize = sizeof(IndexFormatType) >> 1; // Why?
desc.m_nFirstIndex = 0;
desc.m_nOffset = 0;
if (indexCount <= 0)
{
// Not thread safe at this point, but we don't want to unnecessarily
// lock if indexCount is zero and we're just returning a pointer to
// dummy data.
assert(!m_ModifyIndexData);
desc.m_pIndices = reinterpret_cast<IndexFormatType*>(&IShaderAPI_MeshManager::s_FallbackMeshData);
return;
}
BeginThreadLock();
assert(!m_ModifyIndexData); // Once more after the lock, just to be sure
const auto indexDataSize = indexCount * IndexElementSize();
const auto& modifyData = m_ModifyIndexData.emplace<ModifyData>({ firstIndex, indexCount });
desc.m_pIndices = reinterpret_cast<IndexFormatType*>(Util::OffsetPtr(GetBuffer(indexDataSize, truncate), firstIndex * IndexElementSize()));
assert(desc.m_pIndices);
}
void VulkanIndexBuffer::ModifyBegin(bool readOnly, int firstIndex, int indexCount, IndexDesc_t& desc)
{
LOG_FUNC_ANYTHREAD();
const bool shouldAllowRead = true;
const bool shouldAllowWrite = !readOnly;
return ModifyBegin(firstIndex, indexCount, desc, shouldAllowRead, shouldAllowWrite, false);
}
void VulkanIndexBuffer::ModifyEnd(IndexDesc_t& desc)
{
LOG_FUNC_ANYTHREAD();
AssertCheckHeap();
if (!m_ModifyIndexData)
return;
const auto& modify = m_ModifyIndexData.value();
assert(IsDynamic() || modify.m_Count > 0);
CommitModifications(modify.m_Offset * IndexElementSize(), modify.m_Count * IndexElementSize());
ValidateData(m_IndexCount, 0, desc);
m_ModifyIndexData.reset();
EndThreadLock();
}
void VulkanIndexBuffer::ValidateData(int indexCount, const IndexDesc_t& desc)
{
LOG_FUNC_ANYTHREAD();
return ValidateData(Util::SafeConvert<uint32_t>(indexCount), 0, desc);
}
void VulkanIndexBuffer::ValidateData(uint32_t indexCount, uint32_t firstIndex, const IndexDesc_t& desc)
{
LOG_FUNC_ANYTHREAD();
// TODO
}
VulkanGPUBuffer::VulkanGPUBuffer(bool isDynamic, vk::BufferUsageFlags usage) :
m_IsDynamic(isDynamic),
m_Usage(usage)
{
}
void VulkanGPUBuffer::GetGPUBuffer(vk::Buffer& buffer, size_t& offset)
{
auto lock = ScopeThreadLock();
if (IsDynamic())
UpdateDynamicBuffer();
if (auto foundBuf = std::get_if<vma::AllocatedBuffer>(&m_Buffer))
{
buffer = foundBuf->GetBuffer();
offset = 0;
}
else if (auto foundBuf = std::get_if<BufferPoolEntry>(&m_Buffer))
{
offset = foundBuf->GetOffset();
buffer = static_cast<const IBufferPoolInternal&>(foundBuf->GetPool()).GetBuffer(offset);
}
else
{
const auto& realPool = static_cast<const IBufferPoolInternal&>(g_ShaderDevice.GetBufferPool(m_Usage));
buffer = realPool.GetBufferInfo(0).m_Buffer;
offset = 0;
}
}
VulkanVertexBuffer::VulkanVertexBuffer(const VertexFormat& format, bool isDynamic) :
VulkanGPUBuffer(isDynamic, vk::BufferUsageFlagBits::eVertexBuffer),
m_Format(format)
{
}
void VulkanVertexBuffer::Unlock(int vertexCount, VertexDesc_t& desc)
{
LOG_FUNC_ANYTHREAD();
if (!m_ModifyVertexData)
return;
auto& modify = m_ModifyVertexData.value();
[[maybe_unused]] const auto oldModifySize = modify.m_Size;
[[maybe_unused]] const auto oldVertexCount = m_VertexCount;
Util::SafeConvert(vertexCount, m_VertexCount);
modify.m_Size = m_VertexCount * Util::SafeConvert<uint32_t>(desc.m_ActualVertexSize);
ModifyEnd(desc);
}
void VulkanIndexBuffer::Unlock(int indexCount, IndexDesc_t& desc)
{
LOG_FUNC_ANYTHREAD();
AssertCheckHeap();
if (!m_ModifyIndexData)
return;
auto& modify = m_ModifyIndexData.value();
[[maybe_unused]] const auto oldModifyCount = modify.m_Count;
[[maybe_unused]] const auto oldIndexCount = m_IndexCount;
Util::SafeConvert(indexCount, m_IndexCount);
Util::SafeConvert(m_IndexCount, modify.m_Count);
ModifyEnd(desc);
}
void VulkanVertexBuffer::ModifyEnd(VertexDesc_t& desc)
{
LOG_FUNC_ANYTHREAD();
if (!m_ModifyVertexData)
return;
const auto& modify = m_ModifyVertexData.value();
CommitModifications(modify.m_Offset, modify.m_Size);
m_VertexCount = Util::algorithm::max(m_VertexCount, (modify.m_Size + modify.m_Offset) / desc.m_ActualVertexSize);
ValidateData(modify.m_Size / desc.m_ActualVertexSize, desc);
m_ModifyVertexData.reset();
EndThreadLock();
}
void VulkanVertexBuffer::ModifyBegin(uint32_t firstVertex, uint32_t vertexCount, VertexDesc_t& desc,
bool read, bool write, bool truncate)
{
LOG_FUNC_ANYTHREAD();
desc = {};
if (vertexCount <= 0)
{
// Not thread safe yet, but avoid unnecessary locks if just returning dummy data.
assert(!m_ModifyVertexData);
g_MeshManager.SetDummyDataPointers(desc);
return;
}
BeginThreadLock();
assert(!m_ModifyVertexData); // Once more, after the lock
AssertCheckHeap();
assert(!m_Format.IsUnknownFormat());
VertexFormat::Element vtxElems[VERTEX_ELEMENT_NUMELEMENTS];
size_t totalVtxSize;
desc.m_NumBoneWeights = m_Format.m_BoneWeightCount;
const auto vtxElemsCount = m_Format.GetVertexElements(vtxElems, std::size(vtxElems), &totalVtxSize);
assert(!m_ModifyVertexData);
const auto& modify = m_ModifyVertexData.emplace<ModifyData>({ firstVertex * totalVtxSize, vertexCount * totalVtxSize });
assert(modify.m_Size > 0);
g_MeshManager.ComputeVertexDescription(GetBuffer(modify.m_Offset + modify.m_Size, truncate), m_Format, desc);
//ValidateData(vertexCount, firstVertex, desc);
}
template<typename T, size_t count, size_t alignment, typename = std::enable_if_t<std::is_floating_point_v<T>>>
static void ValidateType(const Shaders::vector<T, count, alignment>& v)
{
for (size_t i = 0; i < count; i++)
{
if (!std::isfinite(v[i]))
DebuggerBreakIfDebugging();
}
}
template<typename T>
static void ValidateType(const void* base, int elementIndex, int elementSize)
{
if (elementSize <= 0)
return;
const T& typed = *reinterpret_cast<const T*>(reinterpret_cast<const std::byte*>(base) + elementSize * elementIndex);
ValidateType(typed);
}
void VulkanVertexBuffer::ValidateData(uint32_t vertexCount, uint32_t firstVertex, const VertexDesc_t& desc)
{
LOG_FUNC_ANYTHREAD();
const uint32_t endVertex = firstVertex + vertexCount;
for (uint32_t i = firstVertex; i < endVertex; i++)
{
ValidateType<Shaders::float3>(desc.m_pPosition, i, desc.m_VertexSize_Position);
if (desc.m_CompressionType == VERTEX_COMPRESSION_NONE)
ValidateType<Shaders::float3>(desc.m_pNormal, i, desc.m_VertexSize_Normal);
}
}
VulkanDynamicMesh::VulkanDynamicMesh(const VertexFormat& fmt) :
VulkanMesh(fmt, true)
{
}
void VulkanDynamicMesh::LockMesh(int vertexCount, int indexCount, MeshDesc_t& desc)
{
LOG_FUNC_ANYTHREAD();
if (m_HasDrawn)
{
m_FirstUndrawnIndex = 0;
m_FirstUndrawnVertex = 0;
m_TotalIndices = 0;
m_TotalVertices = 0;
m_HasDrawn = false;
}
return VulkanMesh::LockMesh(vertexCount, indexCount, desc);
}
void VulkanDynamicMesh::UnlockMesh(int vertexCount, int indexCount, MeshDesc_t& desc)
{
LOG_FUNC_ANYTHREAD();
m_TotalVertices += Util::SafeConvert<uint32_t>(vertexCount);
m_TotalIndices += Util::SafeConvert<uint32_t>(indexCount);
return BaseClass::UnlockMesh(vertexCount, indexCount, desc);
}
void VulkanDynamicMesh::Draw(int firstIndex, int indexCount)
{
LOG_FUNC_ANYTHREAD();
MarkAsDrawn();
const bool isPointsOrInstQuads = GetPrimitiveType() == MATERIAL_POINTS || GetPrimitiveType() == MATERIAL_INSTANCED_QUADS;
const bool ibOverride = HasIndexBufferOverride();
const bool vbOverride = HasVertexBufferOverride();
if (ibOverride || vbOverride || (m_TotalVertices > 0 && (m_TotalIndices > 0 || isPointsOrInstQuads)))
{
const uint32_t firstVertex = vbOverride ? 0 : m_FirstUndrawnVertex;
//const uint32_t firstIndex = m_IndexOverride ? 0 : m_FirstUndrawnIndex;
const uint32_t realIndexCount = ibOverride ? firstVertex : 0;
const uint32_t baseIndex = ibOverride ? 0 : m_FirstUndrawnIndex;
if (firstIndex == -1 && indexCount == 0)
{
// Draw the entire mesh
if (ibOverride)
{
indexCount = IndexCount();
}
else
{
if (isPointsOrInstQuads)
Util::SafeConvert(m_TotalVertices, indexCount);
else
Util::SafeConvert(m_TotalIndices, indexCount);
}
assert(indexCount > 0);
}
else
{
assert(firstIndex >= 0);
firstIndex += baseIndex;
}
BaseClass::Draw(firstIndex, indexCount);
}
else
{
const auto idxCount = IndexCount();
const auto vtxCount = VertexCount();
if (idxCount > 0 && vtxCount > 0)
Warning(TF2VULKAN_PREFIX "Skipping draw (%i indices and %i vertices)\n", idxCount, vtxCount);
}
}
void VulkanDynamicMesh::MarkAsDrawn()
{
LOG_FUNC_ANYTHREAD();
m_HasDrawn = true;
}
| 26.498521 | 140 | 0.74566 | melvyn2 |
47535de4a05f42be5091ec3b3c518135ce8e4508 | 2,109 | cpp | C++ | shared/Heap/Heap.cpp | alicialink/system-squeeze | f0a82546389d5feae48668352e0b1dcd83100674 | [
"MIT"
] | null | null | null | shared/Heap/Heap.cpp | alicialink/system-squeeze | f0a82546389d5feae48668352e0b1dcd83100674 | [
"MIT"
] | null | null | null | shared/Heap/Heap.cpp | alicialink/system-squeeze | f0a82546389d5feae48668352e0b1dcd83100674 | [
"MIT"
] | null | null | null | #include "Heap.h"
#include <stdlib.h>
int h_parent(int i)
{
return (int)((i - 1) / 2);
}
int h_child_left(int i)
{
return (2 * i) + 1;
}
int h_child_right(int i)
{
return (2 * i) + 2;
}
bool h_create(Heap **h)
{
Heap *newHeap = (Heap *)malloc(sizeof(Heap));
if (newHeap == NULL) {
return false;
}
else {
newHeap->tree = NULL;
newHeap->size = 0;
*h = newHeap;
return true;
}
}
bool h_insert(Heap *h, int data)
{
int *temp = (int *)realloc(h->tree, sizeof(int) * (h->size + 1));
if (temp == NULL) {
return false;
}
h->tree = temp;
h->size++;
h->tree[h->size - 1] = data;
int child = h->size - 1;
int parent = h_parent(child);
while (child > 0 && h->tree[child] > h->tree[parent]) {
int swap = h->tree[parent];
h->tree[parent] = h->tree[child];
h->tree[child] = swap;
child = parent;
parent = h_parent(child);
}
return true;
}
bool h_remove(Heap *h, int *data)
{
if (h->tree == NULL) {
return false;
}
if (h->size == 1) {
*data = h->tree[0];
free(h->tree);
h->tree = NULL;
}
else {
*data = h->tree[0];
int oldEnd = h->tree[h->size - 1];
int *temp = (int *)realloc(h->tree, sizeof(int) * (h->size - 1));
if (temp == NULL) {
return false;
}
h->size--;
h->tree[0] = oldEnd;
int parent = 0;
int left = 0;
int right = 0;
int maximum = 0;
while (true) {
left = h_child_left(parent);
right = h_child_right(parent);
if (left < h->size && (h->tree[left] > h->tree[parent])) {
maximum = left;
}
else {
maximum = parent;
}
if (right < h->size && (h->tree[right] > h->tree[maximum])) {
maximum = right;
}
if (maximum == parent) {
break;
}
else {
int swap = h->tree[maximum];
h->tree[maximum] = h->tree[parent];
h->tree[parent] = swap;
parent = maximum;
}
}
}
return true;
}
void h_erase(Heap *h)
{
if (h != NULL) {
if (h->tree != NULL) {
free(h->tree);
}
free(h);
}
}
| 15.857143 | 69 | 0.495021 | alicialink |
4755c138300bb384230b1feed1c8d051175c5b97 | 5,366 | cpp | C++ | libcaf_core/src/response_promise.cpp | Hamdor/actor-framework | ce63edffa2b7acb698cfaea571142029d38e9ef0 | [
"BSD-3-Clause"
] | 2,517 | 2015-01-04T22:19:43.000Z | 2022-03-31T12:20:48.000Z | libcaf_core/src/response_promise.cpp | Hamdor/actor-framework | ce63edffa2b7acb698cfaea571142029d38e9ef0 | [
"BSD-3-Clause"
] | 894 | 2015-01-07T14:21:21.000Z | 2022-03-30T06:37:18.000Z | libcaf_core/src/response_promise.cpp | Hamdor/actor-framework | ce63edffa2b7acb698cfaea571142029d38e9ef0 | [
"BSD-3-Clause"
] | 570 | 2015-01-21T18:59:33.000Z | 2022-03-31T19:00:02.000Z | // This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#include <algorithm>
#include <utility>
#include "caf/response_promise.hpp"
#include "caf/detail/profiled_send.hpp"
#include "caf/local_actor.hpp"
#include "caf/logger.hpp"
#include "caf/no_stages.hpp"
namespace caf {
namespace {
bool requires_response(message_id mid) {
return !mid.is_response() && !mid.is_answered();
}
bool requires_response(const mailbox_element& src) {
return requires_response(src.mid);
}
bool has_response_receiver(const mailbox_element& src) {
return src.sender || !src.stages.empty();
}
} // namespace
// -- constructors, destructors, and assignment operators ----------------------
response_promise::response_promise(local_actor* self, strong_actor_ptr source,
forwarding_stack stages, message_id mid) {
CAF_ASSERT(self != nullptr);
// Form an invalid request promise when initialized from a response ID, since
// we always drop messages in this case. Also don't create promises for
// anonymous messages since there's nowhere to send the message to anyway.
if (requires_response(mid)) {
state_ = make_counted<state>();
state_->self = self;
state_->source.swap(source);
state_->stages.swap(stages);
state_->id = mid;
}
}
response_promise::response_promise(local_actor* self, mailbox_element& src)
: response_promise(self, std::move(src.sender), std::move(src.stages),
src.mid) {
// nop
}
// -- properties ---------------------------------------------------------------
bool response_promise::async() const noexcept {
return id().is_async();
}
bool response_promise::pending() const noexcept {
return state_ != nullptr && state_->self != nullptr;
}
strong_actor_ptr response_promise::source() const noexcept {
if (state_)
return state_->source;
else
return nullptr;
}
response_promise::forwarding_stack response_promise::stages() const {
if (state_)
return state_->stages;
else
return {};
}
strong_actor_ptr response_promise::next() const noexcept {
if (state_)
return state_->stages.empty() ? state_->source : state_->stages[0];
else
return nullptr;
}
message_id response_promise::id() const noexcept {
if (state_)
return state_->id;
else
return make_message_id();
}
// -- delivery -----------------------------------------------------------------
void response_promise::deliver(message msg) {
CAF_LOG_TRACE(CAF_ARG(msg));
if (pending()) {
state_->deliver_impl(std::move(msg));
state_.reset();
}
}
void response_promise::deliver(error x) {
CAF_LOG_TRACE(CAF_ARG(x));
if (pending()) {
state_->deliver_impl(make_message(std::move(x)));
state_.reset();
}
}
void response_promise::deliver() {
CAF_LOG_TRACE(CAF_ARG(""));
if (pending()) {
state_->deliver_impl(make_message());
state_.reset();
}
}
void response_promise::respond_to(local_actor* self, mailbox_element* request,
message& response) {
if (request && requires_response(*request)
&& has_response_receiver(*request)) {
state tmp;
tmp.self = self;
tmp.source.swap(request->sender);
tmp.stages.swap(request->stages);
tmp.id = request->mid;
tmp.deliver_impl(std::move(response));
request->mid.mark_as_answered();
}
}
void response_promise::respond_to(local_actor* self, mailbox_element* request,
error& response) {
if (request && requires_response(*request)
&& has_response_receiver(*request)) {
state tmp;
tmp.self = self;
tmp.source.swap(request->sender);
tmp.stages.swap(request->stages);
tmp.id = request->mid;
tmp.deliver_impl(make_message(std::move(response)));
request->mid.mark_as_answered();
}
}
// -- state --------------------------------------------------------------------
response_promise::state::~state() {
if (self) {
CAF_LOG_DEBUG("broken promise!");
deliver_impl(make_message(make_error(sec::broken_promise)));
}
}
void response_promise::state::cancel() {
self = nullptr;
}
void response_promise::state::deliver_impl(message msg) {
CAF_LOG_TRACE(CAF_ARG(msg));
if (msg.empty() && id.is_async()) {
CAF_LOG_DEBUG("drop response: empty response to asynchronous input");
} else if (!stages.empty()) {
auto next = std::move(stages.back());
stages.pop_back();
detail::profiled_send(self, std::move(source), next, id, std::move(stages),
self->context(), std::move(msg));
} else if (source != nullptr) {
detail::profiled_send(self, self->ctrl(), source, id.response_id(),
forwarding_stack{}, self->context(), std::move(msg));
}
cancel();
}
void response_promise::state::delegate_impl(abstract_actor* receiver,
message msg) {
CAF_LOG_TRACE(CAF_ARG(msg));
if (receiver != nullptr) {
detail::profiled_send(self, std::move(source), receiver, id,
std::move(stages), self->context(), std::move(msg));
} else {
CAF_LOG_DEBUG("drop response: invalid delegation target");
}
cancel();
}
} // namespace caf
| 28.242105 | 80 | 0.636974 | Hamdor |
4755cc6261ec0a76d98fa0fc10100bb7156beec2 | 3,766 | cpp | C++ | VrpnNet/AnalogOutputRemote.cpp | vrpn/VrpnNet | b75e5dd846f11b564f6e5ae06317b8781c40142f | [
"MIT"
] | 11 | 2015-04-13T17:53:29.000Z | 2021-06-01T17:33:49.000Z | VrpnNet/AnalogOutputRemote.cpp | vrpn/VrpnNet | b75e5dd846f11b564f6e5ae06317b8781c40142f | [
"MIT"
] | 7 | 2015-04-13T17:45:44.000Z | 2016-09-18T23:42:52.000Z | VrpnNet/AnalogOutputRemote.cpp | vancegroup/VrpnNet | 9767f94c573529f2b4859df1cebb96381b7750a9 | [
"MIT"
] | 4 | 2015-05-20T19:20:29.000Z | 2016-03-20T13:57:28.000Z | // AnalogOutputRemote.cpp: Implementation for Vrpn.AnalogOutputRemote
//
// Copyright (c) 2008-2009 Chris VanderKnyff
//
// 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 "AnalogOutputRemote.h"
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace Vrpn;
AnalogOutputRemote::AnalogOutputRemote(String ^name)
{
Initialize(name, 0);
}
AnalogOutputRemote::AnalogOutputRemote(String ^name, Connection ^c)
{
Initialize(name, c->ToPointer());
}
AnalogOutputRemote::~AnalogOutputRemote()
{
this->!AnalogOutputRemote();
}
AnalogOutputRemote::!AnalogOutputRemote()
{
delete m_analogOut;
m_disposed = true;
}
void AnalogOutputRemote::Initialize(String ^name, vrpn_Connection *lpConn)
{
IntPtr hAnsiName = Marshal::StringToHGlobalAnsi(name);
const char *ansiName = static_cast<const char *>(hAnsiName.ToPointer());
m_analogOut = new ::vrpn_Analog_Output_Remote(ansiName, lpConn);
Marshal::FreeHGlobal(hAnsiName);
m_disposed = false;
}
void AnalogOutputRemote::Update()
{
CHECK_DISPOSAL_STATUS();
m_analogOut->mainloop();
}
void AnalogOutputRemote::MuteWarnings::set(Boolean shutUp)
{
CHECK_DISPOSAL_STATUS();
m_analogOut->shutup = shutUp;
}
Boolean AnalogOutputRemote::MuteWarnings::get()
{
CHECK_DISPOSAL_STATUS();
return m_analogOut->shutup;
}
Connection^ AnalogOutputRemote::GetConnection()
{
CHECK_DISPOSAL_STATUS();
return Connection::FromPointer(m_analogOut->connectionPtr());
}
Boolean AnalogOutputRemote::RequestChannelChange(Int64 channel, Double value)
{
CHECK_DISPOSAL_STATUS();
return RequestChannelChange(channel, value, ServiceClass::Reliable);
}
Boolean AnalogOutputRemote::RequestChannelChange(Int64 channel, Double value, ServiceClass sc)
{
CHECK_DISPOSAL_STATUS();
if (channel > 0xFFFFFFFFUL)
throw gcnew ArgumentOutOfRangeException("channel", "Value must fit in a vrpn_uint32 type");
return m_analogOut->request_change_channel_value(
static_cast<unsigned int>(channel),
value, static_cast<unsigned int>(sc));
}
Boolean AnalogOutputRemote::RequestChannelChange(array<Double> ^channels)
{
CHECK_DISPOSAL_STATUS();
return RequestChannelChange(channels, ServiceClass::Reliable);
}
Boolean AnalogOutputRemote::RequestChannelChange(array<Double> ^channels, ServiceClass sc)
{
CHECK_DISPOSAL_STATUS();
if (channels->LongLength > 0xFFFFFFFFUL)
throw gcnew ArgumentException(
"VRPN AnalogOutput class supports only 2^32-1 channels", "channels");
pin_ptr<Double> pChannels = &channels[0];
return m_analogOut->request_change_channels(channels->Length, pChannels,
static_cast<unsigned int>(sc));
} | 31.123967 | 95 | 0.754116 | vrpn |
47587fb719b576a9f4a953f4233de13d93ae190f | 21,327 | cpp | C++ | Modules/PhotoacousticsAlgorithms/Algorithms/mitkPhotoacousticBeamformingFilter.cpp | ZP-Hust/MITK | ca11353183c5ed4bc30f938eae8bde43a0689bf6 | [
"BSD-3-Clause"
] | null | null | null | Modules/PhotoacousticsAlgorithms/Algorithms/mitkPhotoacousticBeamformingFilter.cpp | ZP-Hust/MITK | ca11353183c5ed4bc30f938eae8bde43a0689bf6 | [
"BSD-3-Clause"
] | null | null | null | Modules/PhotoacousticsAlgorithms/Algorithms/mitkPhotoacousticBeamformingFilter.cpp | ZP-Hust/MITK | ca11353183c5ed4bc30f938eae8bde43a0689bf6 | [
"BSD-3-Clause"
] | 1 | 2019-01-09T08:20:18.000Z | 2019-01-09T08:20:18.000Z | /*===================================================================
mitkPhotoacousticBeamformingFilter
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#define _USE_MATH_DEFINES
#include "mitkPhotoacousticBeamformingFilter.h"
#include "mitkProperties.h"
#include "mitkImageReadAccessor.h"
#include <algorithm>
#include <itkImageIOBase.h>
#include <chrono>
#include <cmath>
#include <thread>
#include <itkImageIOBase.h>
#include "mitkImageCast.h"
#include <mitkPhotoacousticOCLBeamformer.h>
mitk::BeamformingFilter::BeamformingFilter() : m_OutputData(nullptr), m_InputData(nullptr)
{
this->SetNumberOfIndexedInputs(1);
this->SetNumberOfRequiredInputs(1);
m_ProgressHandle = [](int, std::string) {};
}
void mitk::BeamformingFilter::SetProgressHandle(std::function<void(int, std::string)> progressHandle)
{
m_ProgressHandle = progressHandle;
}
mitk::BeamformingFilter::~BeamformingFilter()
{
}
void mitk::BeamformingFilter::GenerateInputRequestedRegion()
{
Superclass::GenerateInputRequestedRegion();
mitk::Image* output = this->GetOutput();
mitk::Image* input = const_cast<mitk::Image *> (this->GetInput());
if (!output->IsInitialized())
{
return;
}
input->SetRequestedRegionToLargestPossibleRegion();
//GenerateTimeInInputRegion(output, input);
}
void mitk::BeamformingFilter::GenerateOutputInformation()
{
mitk::Image::ConstPointer input = this->GetInput();
mitk::Image::Pointer output = this->GetOutput();
if ((output->IsInitialized()) && (this->GetMTime() <= m_TimeOfHeaderInitialization.GetMTime()))
return;
itkDebugMacro(<< "GenerateOutputInformation()");
unsigned int dim[] = { m_Conf.ReconstructionLines, m_Conf.SamplesPerLine, input->GetDimension(2) };
output->Initialize(mitk::MakeScalarPixelType<float>(), 3, dim);
mitk::Vector3D spacing;
spacing[0] = m_Conf.Pitch * m_Conf.TransducerElements * 1000 / m_Conf.ReconstructionLines;
spacing[1] = m_Conf.RecordTime / 2 * m_Conf.SpeedOfSound * 1000 / m_Conf.SamplesPerLine;
spacing[2] = 1;
output->GetGeometry()->SetSpacing(spacing);
output->GetGeometry()->Modified();
output->SetPropertyList(input->GetPropertyList()->Clone());
m_TimeOfHeaderInitialization.Modified();
}
void mitk::BeamformingFilter::GenerateData()
{
GenerateOutputInformation();
mitk::Image::Pointer input = this->GetInput();
mitk::Image::Pointer output = this->GetOutput();
if (!output->IsInitialized())
return;
float inputDim[2] = { (float)input->GetDimension(0), (float)input->GetDimension(1) };
float outputDim[2] = { (float)output->GetDimension(0), (float)output->GetDimension(1) };
unsigned short chunkSize = 2; // TODO: make this slightly less arbitrary
unsigned int oclOutputDim[3] = { output->GetDimension(0), output->GetDimension(1), output->GetDimension(2) };
unsigned int oclOutputDimChunk[3] = { output->GetDimension(0), output->GetDimension(1), chunkSize};
unsigned int oclInputDimChunk[3] = { input->GetDimension(0), input->GetDimension(1), chunkSize};
unsigned int oclOutputDimLastChunk[3] = { output->GetDimension(0), output->GetDimension(1), input->GetDimension(2) % chunkSize };
unsigned int oclInputDimLastChunk[3] = { input->GetDimension(0), input->GetDimension(1), input->GetDimension(2) % chunkSize };
const int apodArraySize = m_Conf.TransducerElements * 4; // set the resolution of the apodization array
float* ApodWindow;
// calculate the appropiate apodization window
switch (m_Conf.Apod)
{
case beamformingSettings::Apodization::Hann:
ApodWindow = VonHannFunction(apodArraySize);
break;
case beamformingSettings::Apodization::Hamm:
ApodWindow = HammFunction(apodArraySize);
break;
case beamformingSettings::Apodization::Box:
ApodWindow = BoxFunction(apodArraySize);
break;
default:
ApodWindow = BoxFunction(apodArraySize);
break;
}
int progInterval = output->GetDimension(2) / 20 > 1 ? output->GetDimension(2) / 20 : 1;
// the interval at which we update the gui progress bar
auto begin = std::chrono::high_resolution_clock::now(); // debbuging the performance...
if (!m_Conf.UseGPU)
{
for (unsigned int i = 0; i < output->GetDimension(2); ++i) // seperate Slices should get Beamforming seperately applied
{
mitk::ImageReadAccessor inputReadAccessor(input, input->GetSliceData(i));
m_OutputData = new float[m_Conf.ReconstructionLines*m_Conf.SamplesPerLine];
m_InputDataPuffer = new float[input->GetDimension(0)*input->GetDimension(1)];
// first, we convert any data to float, which we use by default
if (input->GetPixelType().GetTypeAsString() == "scalar (float)" || input->GetPixelType().GetTypeAsString() == " (float)")
{
m_InputData = (float*)inputReadAccessor.GetData();
}
else
{
MITK_INFO << "Pixel type is not float, abort";
return;
}
// fill the image with zeros
for (int l = 0; l < outputDim[0]; ++l)
{
for (int s = 0; s < outputDim[1]; ++s)
{
m_OutputData[l*(short)outputDim[1] + s] = 0;
}
}
std::thread *threads = new std::thread[(short)outputDim[0]];
// every line will be beamformed in a seperate thread
if (m_Conf.Algorithm == beamformingSettings::BeamformingAlgorithm::DAS)
{
if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::QuadApprox)
{
for (short line = 0; line < outputDim[0]; ++line)
{
threads[line] = std::thread(&BeamformingFilter::DASQuadraticLine, this, m_InputData, m_OutputData, inputDim, outputDim, line, ApodWindow, apodArraySize);
}
}
else if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::Spherical)
{
for (short line = 0; line < outputDim[0]; ++line)
{
threads[line] = std::thread(&BeamformingFilter::DASSphericalLine, this, m_InputData, m_OutputData, inputDim, outputDim, line, ApodWindow, apodArraySize);
}
}
}
else if (m_Conf.Algorithm == beamformingSettings::BeamformingAlgorithm::DMAS)
{
if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::QuadApprox)
{
for (short line = 0; line < outputDim[0]; ++line)
{
threads[line] = std::thread(&BeamformingFilter::DMASQuadraticLine, this, m_InputData, m_OutputData, inputDim, outputDim, line, ApodWindow, apodArraySize);
}
}
else if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::Spherical)
{
for (short line = 0; line < outputDim[0]; ++line)
{
threads[line] = std::thread(&BeamformingFilter::DMASSphericalLine, this, m_InputData, m_OutputData, inputDim, outputDim, line, ApodWindow, apodArraySize);
}
}
}
// wait for all lines to finish
for (short line = 0; line < outputDim[0]; ++line)
{
threads[line].join();
}
output->SetSlice(m_OutputData, i);
if (i % progInterval == 0)
m_ProgressHandle((int)((i + 1) / (float)output->GetDimension(2) * 100), "performing reconstruction");
delete[] m_OutputData;
delete[] m_InputDataPuffer;
m_OutputData = nullptr;
m_InputData = nullptr;
}
}
else
{
mitk::PhotoacousticOCLBeamformer::Pointer m_oclFilter = mitk::PhotoacousticOCLBeamformer::New();
try
{
if (m_Conf.Algorithm == beamformingSettings::BeamformingAlgorithm::DAS)
{
if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::QuadApprox)
m_oclFilter->SetAlgorithm(PhotoacousticOCLBeamformer::BeamformingAlgorithm::DASQuad, true);
else if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::Spherical)
m_oclFilter->SetAlgorithm(PhotoacousticOCLBeamformer::BeamformingAlgorithm::DASSphe, true);
}
else if (m_Conf.Algorithm == beamformingSettings::BeamformingAlgorithm::DMAS)
{
if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::QuadApprox)
m_oclFilter->SetAlgorithm(PhotoacousticOCLBeamformer::BeamformingAlgorithm::DMASQuad, true);
else if (m_Conf.DelayCalculationMethod == beamformingSettings::DelayCalc::Spherical)
m_oclFilter->SetAlgorithm(PhotoacousticOCLBeamformer::BeamformingAlgorithm::DMASSphe, true);
}
m_oclFilter->SetApodisation(ApodWindow, apodArraySize);
m_oclFilter->SetOutputDim(oclOutputDimChunk);
m_oclFilter->SetBeamformingParameters(m_Conf.SpeedOfSound, m_Conf.TimeSpacing, m_Conf.Pitch, m_Conf.Angle, m_Conf.Photoacoustic, m_Conf.TransducerElements);
if (chunkSize < oclOutputDim[2])
{
bool skip = false;
for (unsigned int i = 0; !skip && i < ceil((float)oclOutputDim[2] / (float)chunkSize); ++i)
{
m_ProgressHandle(100 * ((float)(i * chunkSize) / (float)oclOutputDim[2]), "performing reconstruction");
mitk::Image::Pointer chunk = mitk::Image::New();
if ((int)((oclOutputDim[2]) - (i * chunkSize)) == (int)(1 + chunkSize))
{
// A 3d image of 3rd dimension == 1 can not be processed by openCL, make sure that this case never arises
oclInputDimLastChunk[2] = input->GetDimension(2) % chunkSize + chunkSize;
oclOutputDimLastChunk[2] = input->GetDimension(2) % chunkSize + chunkSize;
chunk->Initialize(input->GetPixelType(), 3, oclInputDimLastChunk);
m_oclFilter->SetOutputDim(oclOutputDimLastChunk);
skip = true; //skip the last chunk
}
else if ((oclOutputDim[2]) - (i * chunkSize) >= chunkSize)
chunk->Initialize(input->GetPixelType(), 3, oclInputDimChunk);
else
{
chunk->Initialize(input->GetPixelType(), 3, oclInputDimLastChunk);
m_oclFilter->SetOutputDim(oclOutputDimLastChunk);
}
chunk->SetSpacing(input->GetGeometry()->GetSpacing());
mitk::ImageReadAccessor ChunkMove(input);
chunk->SetImportVolume((void*)&(((float*)const_cast<void*>(ChunkMove.GetData()))[i * chunkSize * input->GetDimension(0) * input->GetDimension(1)]), 0, 0, mitk::Image::ReferenceMemory);
m_oclFilter->SetInput(chunk);
m_oclFilter->Update();
auto out = m_oclFilter->GetOutput();
for (unsigned int s = i * chunkSize; s < oclOutputDim[2]; ++s) // TODO: make the bounds here smaller...
{
mitk::ImageReadAccessor copy(out, out->GetSliceData(s - i * chunkSize));
output->SetImportSlice(const_cast<void*>(copy.GetData()), s, 0, 0, mitk::Image::ReferenceMemory);
}
}
}
else
{
m_ProgressHandle(50, "performing reconstruction");
m_oclFilter->SetOutputDim(oclOutputDim);
m_oclFilter->SetInput(input);
m_oclFilter->Update();
auto out = m_oclFilter->GetOutput();
mitk::ImageReadAccessor copy(out);
output->SetImportVolume(const_cast<void*>(copy.GetData()), 0, 0, mitk::Image::ReferenceMemory);
}
}
catch (mitk::Exception &e)
{
std::string errorMessage = "Caught unexpected exception ";
errorMessage.append(e.what());
MITK_ERROR << errorMessage;
}
}
m_TimeOfHeaderInitialization.Modified();
auto end = std::chrono::high_resolution_clock::now();
MITK_INFO << "Beamforming of " << output->GetDimension(2) << " Images completed in " << ((float)std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count()) / 1000000 << "ms" << std::endl;
}
void mitk::BeamformingFilter::Configure(beamformingSettings settings)
{
m_Conf = settings;
}
float* mitk::BeamformingFilter::VonHannFunction(int samples)
{
float* ApodWindow = new float[samples];
for (int n = 0; n < samples; ++n)
{
ApodWindow[n] = (1 - cos(2 * M_PI * n / (samples - 1))) / 2;
}
return ApodWindow;
}
float* mitk::BeamformingFilter::HammFunction(int samples)
{
float* ApodWindow = new float[samples];
for (int n = 0; n < samples; ++n)
{
ApodWindow[n] = 0.54 - 0.46*cos(2 * M_PI*n / (samples - 1));
}
return ApodWindow;
}
float* mitk::BeamformingFilter::BoxFunction(int samples)
{
float* ApodWindow = new float[samples];
for (int n = 0; n < samples; ++n)
{
ApodWindow[n] = 1;
}
return ApodWindow;
}
void mitk::BeamformingFilter::DASQuadraticLine(float* input, float* output, float inputDim[2], float outputDim[2], const short& line, float* apodisation, const short& apodArraySize)
{
float& inputS = inputDim[1];
float& inputL = inputDim[0];
float& outputS = outputDim[1];
float& outputL = outputDim[0];
short AddSample = 0;
short maxLine = 0;
short minLine = 0;
float delayMultiplicator = 0;
float l_i = 0;
float s_i = 0;
float part = 0.07 * inputL;
float tan_phi = std::tan(m_Conf.Angle / 360 * 2 * M_PI);
float part_multiplicator = tan_phi * m_Conf.TimeSpacing * m_Conf.SpeedOfSound / m_Conf.Pitch * m_Conf.ReconstructionLines / m_Conf.TransducerElements;
float apod_mult = 1;
short usedLines = (maxLine - minLine);
//quadratic delay
l_i = line / outputL * inputL;
for (short sample = 0; sample < outputS; ++sample)
{
s_i = (float)sample / outputS * inputS / 2;
part = part_multiplicator*s_i;
if (part < 1)
part = 1;
maxLine = (short)std::min((l_i + part) + 1, inputL);
minLine = (short)std::max((l_i - part), 0.0f);
usedLines = (maxLine - minLine);
apod_mult = apodArraySize / (maxLine - minLine);
delayMultiplicator = pow((1 / (m_Conf.TimeSpacing*m_Conf.SpeedOfSound) * (m_Conf.Pitch*m_Conf.TransducerElements) / inputL), 2) / s_i / 2;
for (short l_s = minLine; l_s < maxLine; ++l_s)
{
AddSample = delayMultiplicator * pow((l_s - l_i), 2) + s_i + (1 - m_Conf.Photoacoustic)*s_i;
if (AddSample < inputS && AddSample >= 0)
output[sample*(short)outputL + line] += input[l_s + AddSample*(short)inputL] * apodisation[(short)((l_s - minLine)*apod_mult)];
else
--usedLines;
}
output[sample*(short)outputL + line] = output[sample*(short)outputL + line] / usedLines;
}
}
void mitk::BeamformingFilter::DASSphericalLine(float* input, float* output, float inputDim[2], float outputDim[2], const short& line, float* apodisation, const short& apodArraySize)
{
float& inputS = inputDim[1];
float& inputL = inputDim[0];
float& outputS = outputDim[1];
float& outputL = outputDim[0];
short AddSample = 0;
short maxLine = 0;
short minLine = 0;
float l_i = 0;
float s_i = 0;
float part = 0.07 * inputL;
float tan_phi = std::tan(m_Conf.Angle / 360 * 2 * M_PI);
float part_multiplicator = tan_phi * m_Conf.TimeSpacing * m_Conf.SpeedOfSound / m_Conf.Pitch * m_Conf.ReconstructionLines / m_Conf.TransducerElements;
float apod_mult = 1;
short usedLines = (maxLine - minLine);
//exact delay
l_i = (float)line / outputL * inputL;
for (short sample = 0; sample < outputS; ++sample)
{
s_i = (float)sample / outputS * inputS / 2;
part = part_multiplicator*s_i;
if (part < 1)
part = 1;
maxLine = (short)std::min((l_i + part) + 1, inputL);
minLine = (short)std::max((l_i - part), 0.0f);
usedLines = (maxLine - minLine);
apod_mult = apodArraySize / (maxLine - minLine);
for (short l_s = minLine; l_s < maxLine; ++l_s)
{
AddSample = (int)sqrt(
pow(s_i, 2)
+
pow((1 / (m_Conf.TimeSpacing*m_Conf.SpeedOfSound) * ((l_s - l_i)*m_Conf.Pitch*m_Conf.TransducerElements) / inputL), 2)
) + (1 - m_Conf.Photoacoustic)*s_i;
if (AddSample < inputS && AddSample >= 0)
output[sample*(short)outputL + line] += input[l_s + AddSample*(short)inputL] * apodisation[(short)((l_s - minLine)*apod_mult)];
else
--usedLines;
}
output[sample*(short)outputL + line] = output[sample*(short)outputL + line] / usedLines;
}
}
void mitk::BeamformingFilter::DMASQuadraticLine(float* input, float* output, float inputDim[2], float outputDim[2], const short& line, float* apodisation, const short& apodArraySize)
{
float& inputS = inputDim[1];
float& inputL = inputDim[0];
float& outputS = outputDim[1];
float& outputL = outputDim[0];
short maxLine = 0;
short minLine = 0;
float delayMultiplicator = 0;
float l_i = 0;
float s_i = 0;
float part = 0.07 * inputL;
float tan_phi = std::tan(m_Conf.Angle / 360 * 2 * M_PI);
float part_multiplicator = tan_phi * m_Conf.TimeSpacing * m_Conf.SpeedOfSound / m_Conf.Pitch * m_Conf.ReconstructionLines / m_Conf.TransducerElements;
float apod_mult = 1;
float mult = 0;
short usedLines = (maxLine - minLine);
//quadratic delay
l_i = line / outputL * inputL;
for (short sample = 0; sample < outputS; ++sample)
{
s_i = sample / outputS * inputS / 2;
part = part_multiplicator*s_i;
if (part < 1)
part = 1;
maxLine = (short)std::min((l_i + part) + 1, inputL);
minLine = (short)std::max((l_i - part), 0.0f);
usedLines = (maxLine - minLine);
apod_mult = apodArraySize / (maxLine - minLine);
delayMultiplicator = pow((1 / (m_Conf.TimeSpacing*m_Conf.SpeedOfSound) * (m_Conf.Pitch*m_Conf.TransducerElements) / inputL), 2) / s_i / 2;
//calculate the AddSamples beforehand to save some time
short* AddSample = new short[maxLine - minLine];
for (short l_s = 0; l_s < maxLine - minLine; ++l_s)
{
AddSample[l_s] = (short)(delayMultiplicator * pow((minLine + l_s - l_i), 2) + s_i) + (1 - m_Conf.Photoacoustic)*s_i;
}
for (short l_s1 = minLine; l_s1 < maxLine - 1; ++l_s1)
{
if (AddSample[l_s1 - minLine] < (short)inputS && AddSample[l_s1 - minLine] >= 0)
{
for (short l_s2 = l_s1 + 1; l_s2 < maxLine; ++l_s2)
{
if (AddSample[l_s2 - minLine] < inputS && AddSample[l_s2 - minLine] >= 0)
{
mult = input[l_s2 + AddSample[l_s2 - minLine] * (short)inputL] * apodisation[(short)((l_s2 - minLine)*apod_mult)] * input[l_s1 + AddSample[l_s1 - minLine] * (short)inputL] * apodisation[(short)((l_s1 - minLine)*apod_mult)];
output[sample*(short)outputL + line] += sqrt(abs(mult)) * ((mult > 0) - (mult < 0));
}
}
}
else
--usedLines;
}
output[sample*(short)outputL + line] = 10 * output[sample*(short)outputL + line] / (pow(usedLines, 2) - (usedLines - 1));
delete[] AddSample;
}
}
void mitk::BeamformingFilter::DMASSphericalLine(float* input, float* output, float inputDim[2], float outputDim[2], const short& line, float* apodisation, const short& apodArraySize)
{
float& inputS = inputDim[1];
float& inputL = inputDim[0];
float& outputS = outputDim[1];
float& outputL = outputDim[0];
short maxLine = 0;
short minLine = 0;
float l_i = 0;
float s_i = 0;
float part = 0.07 * inputL;
float tan_phi = std::tan(m_Conf.Angle / 360 * 2 * M_PI);
float part_multiplicator = tan_phi * m_Conf.TimeSpacing * m_Conf.SpeedOfSound / m_Conf.Pitch * m_Conf.ReconstructionLines / m_Conf.TransducerElements;
float apod_mult = 1;
float mult = 0;
short usedLines = (maxLine - minLine);
//exact delay
l_i = line / outputL * inputL;
for (short sample = 0; sample < outputS; ++sample)
{
s_i = sample / outputS * inputS / 2;
part = part_multiplicator*s_i;
if (part < 1)
part = 1;
maxLine = (short)std::min((l_i + part) + 1, inputL);
minLine = (short)std::max((l_i - part), 0.0f);
usedLines = (maxLine - minLine);
apod_mult = apodArraySize / (maxLine - minLine);
//calculate the AddSamples beforehand to save some time
short* AddSample = new short[maxLine - minLine];
for (short l_s = 0; l_s < maxLine - minLine; ++l_s)
{
AddSample[l_s] = (short)sqrt(
pow(s_i, 2)
+
pow((1 / (m_Conf.TimeSpacing*m_Conf.SpeedOfSound) * ((minLine + l_s - l_i)*m_Conf.Pitch*m_Conf.TransducerElements) / inputL), 2)
) + (1 - m_Conf.Photoacoustic)*s_i;
}
for (short l_s1 = minLine; l_s1 < maxLine - 1; ++l_s1)
{
if (AddSample[l_s1 - minLine] < inputS && AddSample[l_s1 - minLine] >= 0)
{
for (short l_s2 = l_s1 + 1; l_s2 < maxLine; ++l_s2)
{
if (AddSample[l_s2 - minLine] < inputS && AddSample[l_s2 - minLine] >= 0)
{
mult = input[l_s2 + AddSample[l_s2 - minLine] * (short)inputL] * apodisation[(int)((l_s2 - minLine)*apod_mult)] * input[l_s1 + AddSample[l_s1 - minLine] * (short)inputL] * apodisation[(int)((l_s1 - minLine)*apod_mult)];
output[sample*(short)outputL + line] += sqrt(abs(mult)) * ((mult > 0) - (mult < 0));
}
}
}
else
--usedLines;
}
output[sample*(short)outputL + line] = 10 * output[sample*(short)outputL + line] / (pow(usedLines, 2) - (usedLines - 1));
delete[] AddSample;
}
}
| 35.077303 | 235 | 0.648099 | ZP-Hust |
4758a5d70b1bf5667b99161e9cefcf234ba15c33 | 3,732 | cpp | C++ | firmware-latest/communication/src/events.cpp | adeeshag/particle_project | 0c2ab278cf902f97d2422c44c008978be58fe6b7 | [
"Unlicense"
] | null | null | null | firmware-latest/communication/src/events.cpp | adeeshag/particle_project | 0c2ab278cf902f97d2422c44c008978be58fe6b7 | [
"Unlicense"
] | null | null | null | firmware-latest/communication/src/events.cpp | adeeshag/particle_project | 0c2ab278cf902f97d2422c44c008978be58fe6b7 | [
"Unlicense"
] | null | null | null | /**
******************************************************************************
* @file events.cpp
* @authors Zachary Crockett
* @version V1.0.0
* @date 26-Feb-2014
* @brief Internal CoAP event message creation
******************************************************************************
Copyright (c) 2014-2015 Particle Industries, Inc. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see <http://www.gnu.org/licenses/>.
******************************************************************************
*/
#include "events.h"
#include <string.h>
size_t event(uint8_t buf[], uint16_t message_id, const char *event_name,
const char *data, int ttl, EventType::Enum event_type)
{
uint8_t *p = buf;
*p++ = 0x50; // non-confirmable, no token
*p++ = 0x02; // code 0.02 POST request
*p++ = message_id >> 8;
*p++ = message_id & 0xff;
*p++ = 0xb1; // one-byte Uri-Path option
*p++ = event_type;
size_t name_data_len = strnlen(event_name, 63);
p += event_name_uri_path(p, event_name, name_data_len);
if (60 != ttl)
{
*p++ = 0x33;
*p++ = (ttl >> 16) & 0xff;
*p++ = (ttl >> 8) & 0xff;
*p++ = ttl & 0xff;
}
if (NULL != data)
{
name_data_len = strnlen(data, 255);
*p++ = 0xff;
memcpy(p, data, name_data_len);
p += name_data_len;
}
return p - buf;
}
// Private, used by two subscription variants below
uint8_t *subscription_prelude(uint8_t buf[], uint16_t message_id,
const char *event_name)
{
uint8_t *p = buf;
*p++ = 0x40; // confirmable, no token
*p++ = 0x01; // code 0.01 GET request
*p++ = message_id >> 8;
*p++ = message_id & 0xff;
*p++ = 0xb1; // one-byte Uri-Path option
*p++ = 'e';
if (NULL != event_name)
{
size_t len = strnlen(event_name, 63);
p += event_name_uri_path(p, event_name, len);
}
return p;
}
size_t subscription(uint8_t buf[], uint16_t message_id,
const char *event_name, const char *device_id)
{
uint8_t *p = subscription_prelude(buf, message_id, event_name);
if (NULL != device_id)
{
size_t len = strnlen(device_id, 63);
*p++ = 0xff;
memcpy(p, device_id, len);
p += len;
}
return p - buf;
}
size_t subscription(uint8_t buf[], uint16_t message_id,
const char *event_name, SubscriptionScope::Enum scope)
{
uint8_t *p = subscription_prelude(buf, message_id, event_name);
switch (scope)
{
case SubscriptionScope::MY_DEVICES:
*p++ = 0x41; // one-byte Uri-Query option
*p++ = 'u';
break;
case SubscriptionScope::FIREHOSE:
default:
// unfiltered firehose is not allowed
if (NULL == event_name || 0 == *event_name)
{
return -1;
}
}
return p - buf;
}
size_t event_name_uri_path(uint8_t buf[], const char *name, size_t name_len)
{
if (0 == name_len)
{
return 0;
}
else if (name_len < 13)
{
buf[0] = name_len;
memcpy(buf + 1, name, name_len);
return name_len + 1;
}
else
{
buf[0] = 0x0d;
buf[1] = name_len - 13;
memcpy(buf + 2, name, name_len);
return name_len + 2;
}
}
| 26.097902 | 80 | 0.583333 | adeeshag |
e6e25d79f05ac2a41eafd537cd3cb1dd8988c65c | 4,198 | cpp | C++ | serial_device.cpp | AlexX333BY/dds-fpga-ticker-client | 836df9e5353b0e96987951fa81e9a37f1002a6d1 | [
"MIT"
] | 1 | 2019-12-18T16:40:51.000Z | 2019-12-18T16:40:51.000Z | serial_device.cpp | AlexX333BY/dds-fpga-ticker-client | 836df9e5353b0e96987951fa81e9a37f1002a6d1 | [
"MIT"
] | null | null | null | serial_device.cpp | AlexX333BY/dds-fpga-ticker-client | 836df9e5353b0e96987951fa81e9a37f1002a6d1 | [
"MIT"
] | null | null | null | #include "serial_device.h"
#include <stdexcept>
using namespace fpga_ticker_client;
#ifdef __unix__
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <unordered_map>
serial_device::serial_device(const std::string &path, const uint32_t speed) : device(-1)
{
const std::unordered_map<uint32_t, speed_t> serial_speeds = {
{ 0, B0 },
{ 50, B50 },
{ 75, B75 },
{ 110, B110 },
{ 134, B134 },
{ 150, B150 },
{ 200, B200 },
{ 300, B300 },
{ 600, B600 },
{ 1200, B1200 },
{ 1800, B1800 },
{ 2400, B2400 },
{ 4800, B4800 },
{ 9600, B9600 },
{ 19200, B19200 },
{ 38400, B38400 },
{ 57600, B57600 },
{ 115200, B115200 },
{ 230400, B230400 }
};
try {
const speed_t port_speed = serial_speeds.at(speed);
device = open(path.c_str(), O_RDWR | O_NOCTTY);
if (device != -1) {
if(isatty(device)) {
struct termios config = {};
if (tcgetattr(device, &config) != -1) {
config.c_oflag = 0;
config.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN | ISIG);
config.c_cflag &= ~(CSIZE | PARENB);
config.c_cflag |= CS8;
config.c_cc[VTIME] = 0;
if ((cfsetospeed(&config, port_speed == -1))
|| (tcsetattr(device, TCSANOW, &config) == -1)) {
close(device);
device = -1;
}
} else {
close(device);
device = -1;
}
} else {
close(device);
device = -1;
}
}
} catch (const std::out_of_range&) {
if (device != -1) {
close(device);
device = -1;
}
}
}
serial_device::~serial_device()
{
if (device != -1) {
close(device);
}
}
bool serial_device::is_opened() const
{
return device != -1;
}
void serial_device::write_byte(const uint8_t byte) const
{
if (!is_opened()) {
throw std::logic_error("Device is not opened");
}
ssize_t write_result;
do {
write_result = write(device, &byte, sizeof(byte));
} while ((write_result != -1) && (write_result != sizeof(byte)));
if (write_result == sizeof(byte)) {
tcflush(device, TCOFLUSH);
} else {
throw std::runtime_error("Error writing data to device: " + std::to_string(errno));
}
}
#elif defined (_WIN32) || defined(_WIN64)
serial_device::serial_device(const std::string& path, const uint32_t speed) : device(INVALID_HANDLE_VALUE)
{
device = CreateFileA(path.c_str(), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (device != INVALID_HANDLE_VALUE) {
DCB comm_state;
if (GetCommState(device, &comm_state) == TRUE) {
comm_state.BaudRate = speed;
comm_state.ByteSize = sizeof(uint8_t) * 8;
comm_state.DCBlength = sizeof(comm_state);
comm_state.fBinary = TRUE;
if (SetCommState(device, &comm_state) == FALSE) {
CloseHandle(device);
device = INVALID_HANDLE_VALUE;
}
} else {
CloseHandle(device);
device = INVALID_HANDLE_VALUE;
}
}
}
serial_device::~serial_device()
{
if (device != INVALID_HANDLE_VALUE) {
CloseHandle(device);
}
}
bool serial_device::is_opened() const
{
return device != INVALID_HANDLE_VALUE;
}
void serial_device::write_byte(const uint8_t byte) const
{
if (!is_opened()) {
throw std::logic_error("Device is not opened");
}
BOOL write_result;
DWORD write_count;
do {
write_result = WriteFile(device, &byte, sizeof(byte), &write_count, NULL);
} while ((write_result == TRUE) && (write_count != sizeof(byte)));
if (write_result == TRUE) {
FlushFileBuffers(device);
} else {
throw std::runtime_error("Error writing data to device: " + std::to_string(GetLastError()));
}
}
#endif
| 26.56962 | 106 | 0.526679 | AlexX333BY |
e6e577deb83d81b726fe574676492d8bb7430f7a | 2,263 | cpp | C++ | code/87.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 23 | 2020-03-30T05:44:56.000Z | 2021-09-04T16:00:57.000Z | code/87.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 1 | 2020-05-10T15:04:05.000Z | 2020-06-14T01:21:44.000Z | code/87.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 6 | 2020-03-30T05:45:04.000Z | 2020-08-13T10:01:39.000Z | #include <bits/stdc++.h>
#define INF 2000000000
using namespace std;
typedef long long ll;
int read(){
int f = 1, x = 0;
char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();}
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return f * x;
}
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isLeaf(TreeNode* root) {
return root->left == NULL && root->right == NULL;
}
class Solution {
public:
bool dfs(string& s1, string& s2, int l1, int r1, int l2, int r2, bool flag){
if (r1 - l1 == 1)
return s1[l1] == s2[l2];
int vec[26] = {0}, cnt = 0;
for (int i = 1; i < r1 - l1; ++i){
if (vec[s1[l1 + i - 1]] == 0) ++cnt;
else if (vec[s1[l1 + i - 1]] == -1) --cnt;
++vec[s1[l1 + i - 1]];
if (flag) {
if (vec[s2[l2 + i - 1]] == 1) --cnt;
else if (vec[s2[l2 + i - 1]] == 0) ++cnt;
--vec[s2[l2 + i - 1]];
if (cnt == 0 && (dfs(s1, s2, l1, l1 + i, l2, l2 + i, true) || dfs(s1, s2, l1, l1 + i, l2, l2 + i, false)) &&
(dfs(s1, s2, l1 + i, r1, l2 + i, r2, true) || dfs(s1, s2, l1 + i, r1, l2 + i, r2, false)))
return true;
}else {
if (vec[s2[r2 - i]] == 1) --cnt;
else if (vec[s2[r2 - i]] == 0) ++cnt;
--vec[s2[r2 - i]];
if (cnt == 0 && (dfs(s1, s2, l1, l1 + i, r2 - i, r2, true) || dfs(s1, s2, l1, l1 + i, r2 - i, r2, false)) &&
(dfs(s1, s2, l1 + i, r1, l2, r2 - i, true) || dfs(s1, s2, l1 + i, r1, l2, r2 - i, false)))
return true;
}
}
return false;
}
bool isScramble(string s1, string s2) {
for (int i = 0; i < s1.length(); ++i)
s1[i] -= 'a';
for (int i = 0; i < s2.length(); ++i)
s2[i] -= 'a';
return dfs(s1, s2, 0, s1.length(), 0, s2.length(), true) ||
dfs(s1, s2, 0, s1.length(), 0, s2.length(), false);
}
};
Solution sol;
void init(){
}
void solve(){
// sol.convert();
}
int main(){
init();
solve();
return 0;
}
| 31 | 124 | 0.418913 | Nightwish-cn |
e6e57bcd14af72348eff2906ff5bf63c3d98edf0 | 7,833 | cc | C++ | proxy/http/HttpProxyServerMain.cc | allandproust/TrafficServer-1 | 7d517c7ab3f21b812bc0969244386480a94df467 | [
"Apache-2.0"
] | 83 | 2015-01-13T14:44:55.000Z | 2021-10-30T07:57:03.000Z | proxy/http/HttpProxyServerMain.cc | flashbuckets/trafficserver | 236fab894c0909913580f7a75a307ab393b3986c | [
"Apache-2.0"
] | 9 | 2015-03-13T15:17:28.000Z | 2017-04-19T08:53:24.000Z | proxy/http/HttpProxyServerMain.cc | flashbuckets/trafficserver | 236fab894c0909913580f7a75a307ab393b3986c | [
"Apache-2.0"
] | 50 | 2015-01-29T14:51:38.000Z | 2021-11-10T02:03:35.000Z | /** @file
A brief file description
@section license License
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 "ink_config.h"
#include "P_Net.h"
#include "Main.h"
#include "Error.h"
#include "HttpConfig.h"
#include "HttpAcceptCont.h"
#include "ReverseProxy.h"
#include "HttpSessionManager.h"
#include "HttpUpdateSM.h"
#include "HttpClientSession.h"
#include "HttpPages.h"
#include "HttpTunnel.h"
#include "Tokenizer.h"
#include "P_SSLNextProtocolAccept.h"
#include "P_ProtocolAcceptCont.h"
#ifdef DEBUG
extern "C"
{
void http_dump();
}
///////////////////////////////////////////////////////////
//
// http_dump()
//
///////////////////////////////////////////////////////////
void
http_dump()
{
// if (diags->on("http_dump"))
{
// httpNetProcessor.dump();
// HttpStateMachine::dump_state_machines();
}
return;
}
#endif
struct DumpStats: public Continuation
{
int mainEvent(int event, void *e)
{
(void) event;
(void) e;
/* http_dump() */
// dump_stats();
return EVENT_CONT;
}
DumpStats():Continuation(NULL)
{
SET_HANDLER(&DumpStats::mainEvent);
}
};
HttpAcceptCont *plugin_http_accept = NULL;
HttpAcceptCont *plugin_http_transparent_accept = 0;
#if !defined(TS_NO_API)
static SLL<SSLNextProtocolAccept> ssl_plugin_acceptors;
static ProcessMutex ssl_plugin_mutex = PTHREAD_MUTEX_INITIALIZER;
bool
ssl_register_protocol(const char * protocol, Continuation * contp)
{
ink_scoped_mutex lock(ssl_plugin_mutex);
for (SSLNextProtocolAccept * ssl = ssl_plugin_acceptors.head;
ssl; ssl = ssl_plugin_acceptors.next(ssl)) {
if (!ssl->registerEndpoint(protocol, contp)) {
return false;
}
}
return true;
}
bool
ssl_unregister_protocol(const char * protocol, Continuation * contp)
{
ink_scoped_mutex lock(ssl_plugin_mutex);
for (SSLNextProtocolAccept * ssl = ssl_plugin_acceptors.head;
ssl; ssl = ssl_plugin_acceptors.next(ssl)) {
// Ignore possible failure because we want to try to unregister
// from all SSL ports.
ssl->unregisterEndpoint(protocol, contp);
}
return true;
}
#endif /* !defined(TS_NO_API) */
/////////////////////////////////////////////////////////////////
//
// main()
//
/////////////////////////////////////////////////////////////////
void
init_HttpProxyServer(void)
{
#ifndef INK_NO_REVERSE
init_reverse_proxy();
#endif
// HttpConfig::startup();
httpSessionManager.init();
http_pages_init();
ink_mutex_init(&debug_sm_list_mutex, "HttpSM Debug List");
ink_mutex_init(&debug_cs_list_mutex, "HttpCS Debug List");
// DI's request to disable/reenable ICP on the fly
icp_dynamic_enabled = 1;
// INKqa11918
init_max_chunk_buf();
#ifndef TS_NO_API
// Used to give plugins the ability to create http requests
// The equivalent of the connecting to localhost on the proxy
// port but without going through the operating system
//
if (plugin_http_accept == NULL) {
plugin_http_accept = NEW(new HttpAcceptCont);
plugin_http_accept->mutex = new_ProxyMutex();
}
// Same as plugin_http_accept except outbound transparent.
if (! plugin_http_transparent_accept) {
HttpAcceptCont::Options ha_opt;
ha_opt.setOutboundTransparent(true);
plugin_http_transparent_accept = NEW(new HttpAcceptCont(ha_opt));
plugin_http_transparent_accept->mutex = new_ProxyMutex();
}
ink_mutex_init(&ssl_plugin_mutex, "SSL Acceptor List");
#endif
}
void
start_HttpProxyServer(int accept_threads)
{
char *dump_every_str = 0;
static bool called_once = false;
NetProcessor::AcceptOptions opt;
if ((dump_every_str = getenv("PROXY_DUMP_STATS")) != 0) {
int dump_every_sec = atoi(dump_every_str);
eventProcessor.schedule_every(NEW(new DumpStats), HRTIME_SECONDS(dump_every_sec), ET_CALL);
}
///////////////////////////////////
// start accepting connections //
///////////////////////////////////
ink_assert(!called_once);
opt.accept_threads = accept_threads;
REC_ReadConfigInteger(opt.recv_bufsize, "proxy.config.net.sock_recv_buffer_size_in");
REC_ReadConfigInteger(opt.send_bufsize, "proxy.config.net.sock_send_buffer_size_in");
REC_ReadConfigInteger(opt.packet_mark, "proxy.config.net.sock_packet_mark_in");
REC_ReadConfigInteger(opt.packet_tos, "proxy.config.net.sock_packet_tos_in");
SSLConfig::scoped_config sslParam;
for ( int i = 0 , n = HttpProxyPort::global().length() ; i < n ; ++i ) {
HttpProxyPort& p = HttpProxyPort::global()[i];
HttpAcceptCont::Options ha_opt;
opt.f_inbound_transparent = p.m_inbound_transparent_p;
opt.ip_family = p.m_family;
opt.local_port = p.m_port;
opt.create_default_NetAccept = false;
ha_opt.f_outbound_transparent = p.m_outbound_transparent_p;
ha_opt.transport_type = p.m_type;
if (p.m_inbound_ip.isValid())
opt.local_ip = p.m_inbound_ip;
else if (AF_INET6 == p.m_family && HttpConfig::m_master.inbound_ip6.isIp6())
opt.local_ip = HttpConfig::m_master.inbound_ip6;
else if (AF_INET == p.m_family && HttpConfig::m_master.inbound_ip4.isIp4())
opt.local_ip = HttpConfig::m_master.inbound_ip4;
if (p.m_outbound_ip4.isValid())
ha_opt.outbound_ip4 = p.m_outbound_ip4;
else if (HttpConfig::m_master.outbound_ip4.isValid())
ha_opt.outbound_ip4 = HttpConfig::m_master.outbound_ip4;
if (p.m_outbound_ip6.isValid())
ha_opt.outbound_ip6 = p.m_outbound_ip6;
else if (HttpConfig::m_master.outbound_ip6.isValid())
ha_opt.outbound_ip6 = HttpConfig::m_master.outbound_ip6;
HttpAcceptCont *http = NEW(new HttpAcceptCont(ha_opt));
SpdyAcceptCont *spdy = NEW(new SpdyAcceptCont(http));
SSLNextProtocolAccept *ssl = NEW(new SSLNextProtocolAccept(http));
ProtocolAcceptCont *proto = NEW(new ProtocolAcceptCont());
proto->registerEndpoint(NET_PROTO_HTTP, http);
proto->registerEndpoint(NET_PROTO_HTTP_SSL, ssl);
proto->registerEndpoint(NET_PROTO_HTTP_SPDY, spdy);
if (p.isSSL()) {
// HTTP
ssl->registerEndpoint(TS_NPN_PROTOCOL_HTTP_1_0, http);
ssl->registerEndpoint(TS_NPN_PROTOCOL_HTTP_1_1, http);
#if TS_HAS_SPDY
// SPDY
ssl->registerEndpoint(TS_NPN_PROTOCOL_SPDY_3, spdy);
#endif
#ifndef TS_NO_API
ink_scoped_mutex lock(ssl_plugin_mutex);
ssl_plugin_acceptors.push(ssl);
#endif
sslNetProcessor.main_accept(proto, p.m_fd, opt);
} else {
netProcessor.main_accept(proto, p.m_fd, opt);
}
}
SSLConfig::release(sslParam);
#ifdef DEBUG
if (diags->on("http_dump")) {
// HttpStateMachine::dump_state_machines();
}
#endif
#if TS_HAS_TESTS
if (is_action_tag_set("http_update_test")) {
init_http_update_test();
}
#endif
}
void
start_HttpProxyServerBackDoor(int port, int accept_threads)
{
NetProcessor::AcceptOptions opt;
HttpAcceptCont::Options ha_opt;
opt.local_port = port;
opt.accept_threads = accept_threads;
opt.localhost_only = true;
ha_opt.backdoor = true;
opt.backdoor = true;
// The backdoor only binds the loopback interface
netProcessor.main_accept(NEW(new HttpAcceptCont(ha_opt)), NO_FD, opt);
}
| 28.904059 | 95 | 0.699349 | allandproust |
e6e6e861d6ae33a6ed1e82d6202e984019b0062d | 3,033 | cpp | C++ | test/module/shared_model/builders/common_objects/signature_builder_test.cpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | test/module/shared_model/builders/common_objects/signature_builder_test.cpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | test/module/shared_model/builders/common_objects/signature_builder_test.cpp | coderintherye/iroha | 68509282851130c9818f21acef1ef28e53622315 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. 2018 All Rights Reserved.
* http://soramitsu.co.jp
*
* 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 <gtest/gtest.h>
#include "builders_test_fixture.hpp"
#include "module/shared_model/builders/common_objects/signature_builder.hpp"
#include "module/shared_model/builders/protobuf/common_objects/proto_signature_builder.hpp"
#include "validators/field_validator.hpp"
// TODO: 14.02.2018 nickaleks mock builder implementation IR-970
// TODO: 14.02.2018 nickaleks mock field validator IR-971
/**
* @given field values which pass stateless validation
* @when PeerBuilder is invoked
* @then Peer object is successfully constructed and has valid fields
*/
TEST(PeerBuilderTest, StatelessValidAddressCreation) {
shared_model::builder::SignatureBuilder<
shared_model::proto::SignatureBuilder,
shared_model::validation::FieldValidator>
builder;
shared_model::interface::types::PubkeyType expected_key(std::string(32, '1'));
shared_model::interface::Signature::SignedType expected_signed(
"signed object");
auto signature =
builder.publicKey(expected_key).signedData(expected_signed).build();
signature.match(
[&](shared_model::builder::BuilderResult<
shared_model::interface::Signature>::ValueType &v) {
EXPECT_EQ(v.value->publicKey(), expected_key);
EXPECT_EQ(v.value->signedData(), expected_signed);
},
[](shared_model::builder::BuilderResult<
shared_model::interface::Signature>::ErrorType &e) {
FAIL() << *e.error;
});
}
/**
* @given field values which pass stateless validation
* @when SignatureBuilder is invoked twice
* @then Two identical (==) Signature objects are constructed
*/
TEST(SignatureBuilderTest, SeveralObjectsFromOneBuilder) {
shared_model::builder::SignatureBuilder<
shared_model::proto::SignatureBuilder,
shared_model::validation::FieldValidator>
builder;
shared_model::interface::types::PubkeyType expected_key(std::string(32, '1'));
shared_model::interface::Signature::SignedType expected_signed(
"signed object");
auto state = builder.publicKey(expected_key).signedData(expected_signed);
auto signature = state.build();
auto signature2 = state.build();
testResultObjects(signature, signature2, [](auto &a, auto &b) {
// pointer points to different objects
ASSERT_TRUE(a != b);
EXPECT_EQ(a->publicKey(), b->publicKey());
EXPECT_EQ(a->signedData(), b->signedData());
});
}
| 35.682353 | 91 | 0.726014 | coderintherye |
e6eda95147638c5a9ab2e6f5107109c2dc181850 | 16,857 | cpp | C++ | src/modrin_motor_plugins/epos2.cpp | ein57ein/modrin | 7ec843439ffb19fb9fb68ca416f78770b5c72228 | [
"BSD-3-Clause"
] | null | null | null | src/modrin_motor_plugins/epos2.cpp | ein57ein/modrin | 7ec843439ffb19fb9fb68ca416f78770b5c72228 | [
"BSD-3-Clause"
] | null | null | null | src/modrin_motor_plugins/epos2.cpp | ein57ein/modrin | 7ec843439ffb19fb9fb68ca416f78770b5c72228 | [
"BSD-3-Clause"
] | null | null | null | #include <pluginlib/class_list_macros.h>
#include <modrin_motor_plugins/epos2.hpp>
PLUGINLIB_EXPORT_CLASS(modrin_motor_plugins::Epos2, modrin::Motor)
namespace modrin_motor_plugins
{
Epos2::Epos2():devhandle(0), lastEpos2ErrorCode(0)
{
ROS_DEBUG("created an instance of epos2-plugin for modrin");
}
Epos2::~Epos2()
{
if ( devhandle != 0 ) closeEpos2();
}
bool Epos2::onInit()
{
if ( ros::param::has(full_namespace + "/node_nr") )
{
int temp;
ros::param::get(full_namespace + "/node_nr", temp);
epos_node_nr.push_back(temp);
} else {
ROS_ERROR("[%s] couldn't read an Epos2 node_nr from the parameter-server at \"%s\"", name.c_str(), (full_namespace + "/node_nr").c_str() );
return false;
}
eposCanClient = ros::param::has(full_namespace + "/can_connected_with");
if ( eposCanClient )
{
std::string can_connected_with;
ros::param::get(full_namespace + "/can_connected_with", can_connected_with);
//size_t x = srv_name.find_last_of("/");
//srv_name = srv_name.substr(0, x+1) + can_connected_with;
srv_name = ros::this_node::getName() + "/" + can_connected_with;
epos2_can = roshandle.serviceClient<modrin::epos2_can>( srv_name );
} else {
//establishCommmunication();
srv_name = full_namespace;
epos2_can_srv = roshandle.advertiseService(srv_name.c_str(), &Epos2::canSrv, this);
ROS_DEBUG("[%s] create srv: %s", name.c_str(), srv_name.c_str());
}
controllTimer = roshandle.createTimer(ros::Rate(0.2), &Epos2::periopdicControllCallback, this);
return initEpos2(1000);
}
void Epos2::periopdicControllCallback(const ros::TimerEvent& event) {
switch ( getState() ) {
case not_init: initEpos2();
break;
case fault: if (!eposCanClient) resetAndClearFaultOnAllDevices();
break;
}
}
bool Epos2::initEpos2(int timeout)
{
if (eposCanClient) {
modrin::epos2_can temp;
temp.request.node_nr = epos_node_nr[0];
ros::service::waitForService(srv_name, timeout);
ROS_DEBUG("call srv: %s", srv_name.c_str() );
if (epos2_can.call(temp))
{
devhandle = (void*) temp.response.devhandle;
ROS_INFO("[%s] receive an epos2 device-handle: %#lx", name.c_str(), (unsigned long int) devhandle);
} else {
devhandle = 0;
}
} else {
establishCommmunication();
}
if (devhandle == 0)
{
if (eposCanClient) {
ROS_WARN("[%s] couldn't receive an epos2 device-handle", name.c_str());
} else {
ROS_ERROR("[%s] couldn't receive an epos2 device-handle", name.c_str());
}
return false;
} else {
//set parameter
if (eposCanClient) {setParameter();}
ROS_INFO("[%s] Epos2 with node_nr %i successfully started in ns \"%s\"", name.c_str(), epos_node_nr[0], full_namespace.c_str() );
return true;
}
}
bool Epos2::establishCommmunication()
{
std::string port;
char *protocol, *port_type;
int baudrate, timeout;
ros::param::get(full_namespace + "/port", port);
ros::param::param<int>(full_namespace + "/timeout", timeout, 750);
if ( port.substr(0,3).compare("USB") == 0 ) {
ros::param::param<int>(full_namespace + "/baudrate", baudrate, 1000000);
protocol = (char*)"MAXON SERIAL V2";
port_type = (char*)"USB";
} else if ( port.substr(0,8).compare("/dev/tty") == 0 ) {
ros::param::param<int>(full_namespace + "/baudrate", baudrate, 115200);
protocol = (char*)"MAXON_RS232";
port_type = (char*)"RS232";
} else {
ROS_ERROR("[%s] \"%s\" isn't a valid portname for the Epos2. Allowed are USB* or /dev/tty*", name.c_str(), port.c_str());
return false;
}
unsigned int errorCode=0;
devhandle = VCS_OpenDevice((char*)"EPOS2", protocol, port_type, (char*) port.c_str(), &lastEpos2ErrorCode);
if (devhandle == 0) {
printEpos2Error();
return false;
} else {
if ( VCS_SetProtocolStackSettings(devhandle, baudrate, timeout, &lastEpos2ErrorCode) ) {
ROS_INFO("[%s] open EPOS2-Device on port %s (baudrate: %i; timeout: %i). device-handle: %#lx", name.c_str(), port.c_str(), baudrate, timeout, (unsigned long int) devhandle);
return true;
} else {
printEpos2Error();
return false;
}
}
}
bool Epos2::canSrv(modrin::epos2_can::Request &req, modrin::epos2_can::Response &res)
{
ROS_INFO("[%s] Epos2 with node_nr %i call the canSrv", name.c_str(), req.node_nr);
res.devhandle = (unsigned long int) devhandle;
if (devhandle == 0)
{
return false;
} else {
epos_node_nr.push_back(req.node_nr);
resetAndClearFaultOnAllDevices();
setParameter();
return true;
}
}
bool Epos2::setEnable()
{
state temp = getState();
if ( temp == enabled ) return true;
if ( temp != disabled ) return false;
if ( VCS_SetEnableState(devhandle, epos_node_nr[0], &lastEpos2ErrorCode) ) {
return true;
} else {
printEpos2Error();
return false;
}
}
bool Epos2::setDisable()
{
state temp = getState();
if ( temp == disabled ) return true;
if ( temp == not_init ) return false;
if ( VCS_SetDisableState(devhandle, epos_node_nr[0], &lastEpos2ErrorCode) ) {
return true;
} else {
printEpos2Error();
return false;
}
}
bool Epos2::setQuickStop()
{
if ( VCS_SetQuickStopState(devhandle, epos_node_nr[0], &lastEpos2ErrorCode) ) {
return true;
} else {
printEpos2Error();
return false;
}
}
modrin::Motor::state Epos2::getState()
{
unsigned short tempState=0;
if ( VCS_GetState(devhandle, epos_node_nr[0], &tempState, &lastEpos2ErrorCode) ) {
switch (tempState) {
case ST_ENABLED: return enabled;
break;
case ST_DISABLED: return disabled;
break;
case ST_QUICKSTOP: return disabled;
break;
case ST_FAULT:
default: return fault;
break;
}
} else {
if ( devhandle != 0 ) {
printEpos2Error();
closeEpos2();
}
return not_init;
}
}
void Epos2::closeEpos2()
{
setDisable();
if ( !VCS_CloseDevice(devhandle, &lastEpos2ErrorCode) ) printEpos2Error();
devhandle = 0;
}
//set parameters first (notation and dimension)
bool Epos2::setRPM(double rpm) {return false;}
double Epos2::getMaxRPM() { return 0.0; }
void Epos2::resetAndClearFaultOnAllDevices()
{
std::vector<int>::iterator it;
for (it = epos_node_nr.begin(); it < epos_node_nr.end(); it++) {
if ( !VCS_SetDisableState(devhandle, *it, &lastEpos2ErrorCode) ) printEpos2Error();
}
for (it = epos_node_nr.begin(); it < epos_node_nr.end(); it++) {
if ( !VCS_ResetDevice(devhandle, *it, &lastEpos2ErrorCode) ) printEpos2Error();
}
for (it = epos_node_nr.begin(); it < epos_node_nr.end(); it++) {
if ( !VCS_ClearFault(devhandle, *it, &lastEpos2ErrorCode) ) printEpos2Error();
}
for (it = epos_node_nr.begin(); it < epos_node_nr.end(); it++) {
if ( !VCS_SetEnableState(devhandle, *it, &lastEpos2ErrorCode) ) printEpos2Error();
}
}
void Epos2::printEpos2Error()
{
unsigned short maxStr=255; //max stringsize
char errorText[maxStr]; //errorstring
if ( VCS_GetErrorInfo(lastEpos2ErrorCode, errorText, maxStr) )
{
ROS_ERROR("[%s] %s (errorCode: %#x)", name.c_str(), errorText, lastEpos2ErrorCode);
} else {
ROS_FATAL("[%s] Unable to resolve an errorText for the Epos2-ErrorCode %#x", name.c_str(), lastEpos2ErrorCode);
}
}
bool Epos2::setParameter()
{
if ( !setDisable() ) return false;
if ( !setDimensionAndNotation() ) return false;
if ( !checkSpin() ) return false;
if ( !checkMotorParameter() ) return false;
if ( !VCS_Store(devhandle, epos_node_nr[0], &lastEpos2ErrorCode) ) {
printEpos2Error();
}
if ( !setEnable() ) return false;
return true;
}
bool Epos2::checkMotorParameter()
{
short unsigned motor_type;
if ( !VCS_GetMotorType(devhandle, epos_node_nr[0], &motor_type, &lastEpos2ErrorCode) ) {
printEpos2Error();
}
//ros::param::has(full_namespace + "/motor_type")
if ( ros::param::get(full_namespace + "/motor_type", (int&) motor_type) ) {
if ( !VCS_SetMotorType(devhandle, epos_node_nr[0], motor_type, &lastEpos2ErrorCode) ) {
printEpos2Error();
}
}
short unsigned nominal_current = 0, max_current = 0, thermal_time_constant = 0;
unsigned char number_of_pole_pairs = 1;
std::string motor_str;
if ( motor_type == MT_DC_MOTOR ) {
motor_str = "brushed DC motor";
if ( !VCS_GetDcMotorParameter(devhandle, epos_node_nr[0], &nominal_current, &max_current, &thermal_time_constant, &lastEpos2ErrorCode) ) {
printEpos2Error();
}
} else {
motor_str = (motor_type == MT_EC_SINUS_COMMUTATED_MOTOR) ? "EC motor sinus commutated" : "EC motor block commutated";
if ( !VCS_GetEcMotorParameter(devhandle, epos_node_nr[0], &nominal_current, &max_current, &thermal_time_constant, &number_of_pole_pairs, &lastEpos2ErrorCode) ) {
printEpos2Error();
}
}
thermal_time_constant = 100 * thermal_time_constant;
bool something_changed = false, successfully_set = true;
if ( ros::param::get(full_namespace + "/motor_nominal_current", (int&) nominal_current) ) { something_changed = true; }
if ( ros::param::get(full_namespace + "/motor_max_output_current", (int&) max_current) ) { something_changed = true; }
if ( ros::param::get(full_namespace + "/motor_thermal_time_constant", (int&) thermal_time_constant) ) { something_changed = true; }
std::ostringstream pole_pair_str;
pole_pair_str.str("");
if ( motor_type == MT_DC_MOTOR ) {
if (something_changed) {
if ( !VCS_SetDcMotorParameter(devhandle, epos_node_nr[0], nominal_current, max_current, (short unsigned) (thermal_time_constant / 100.0), &lastEpos2ErrorCode) ) {
printEpos2Error();
successfully_set = false;
}
}
} else {
if ( ros::param::get(full_namespace + "/motor_pole_pair_number", (int&) number_of_pole_pairs) ) { something_changed = true; }
pole_pair_str << number_of_pole_pairs << " pole pairs, ";
if (something_changed) {
if ( !VCS_SetEcMotorParameter(devhandle, epos_node_nr[0], nominal_current, max_current, (short unsigned) (thermal_time_constant / 100.0), number_of_pole_pairs, &lastEpos2ErrorCode) ) {
printEpos2Error();
successfully_set = false;
}
}
}
unsigned int bytes = 0;
int max_rpm;
if ( !VCS_GetObject(devhandle, epos_node_nr[0], 0x6410, 0x04, &max_rpm, 4, &bytes, &lastEpos2ErrorCode) ) {
printEpos2Error();
}
if ( ros::param::get(full_namespace + "/motor_max_rpm", max_rpm) ) {
if ( !VCS_SetObject(devhandle, epos_node_nr[0], 0x6410, 0x04, &max_rpm, 4, &bytes, &lastEpos2ErrorCode) ) {
printEpos2Error();
}
}
if (successfully_set) {
ROS_INFO("[%s] current motor parameter: %s, %.3fA nominal current, %.3fA peak current, max %i rpm, %sthermal time constant winding = %.1fs", name.c_str(), motor_str.c_str(), nominal_current/1000.0, max_current/1000.0, max_rpm, pole_pair_str.str().c_str(), thermal_time_constant/1000.0);
return true;
} else {
return false;
}
}
bool Epos2::setDimensionAndNotation() {
object_data data_temp[]={
//{VN_STANDARD, int8, 0x6089, 0}, {0xac, uint8, 0x608a, 0}, //Position [steps]
{VN_MILLI, int8, 0x608b, 0}, //{VD_RPM, uint8, 0x608c, 0}, //Velocity [1e-3 rev/min]
//{VN_STANDARD, int8, 0x608d, 0}, {VD_RPM, uint8, 0x608e, 0} //Acceleration [rev/(min * s)]
};
std::vector<object_data> data;
for (int i=0; i < sizeof(data_temp) / sizeof(object_data); i ++) {
data.push_back(data_temp[i]);
}
return setObject(&data);
}
bool Epos2::checkSpin() {
object_data data_temp = {0, uint16, 0x2008, 0};
std::vector<object_data> data;
data.push_back(data_temp);
if ( !getObject(&data) ) { return false; }
bool temp; //true = 1; false = 0
if ( ros::param::get(full_namespace + "/motor_reverse", temp) ) {
if ( temp xor (data[0].value >> 8) & 1 ) {
data[0].value = (data[0].value & 0xfeff) + temp * 0x100;
setObject(&data);
}
}
ROS_INFO("[%s] Miscellaneous Configuration Word: %#x", name.c_str(), data[0].value );
return true;
}
bool Epos2::checkGearParameter() {
object_data data_temp[]={
{1, uint32, 0x2230, 0x01}, //Gear Ratio Numerator
{1, uint16, 0x2230, 0x02}, //Gear Ratio Denominator
{1000, uint32, 0x2230, 0x03} //Gear Maximal Speed
};
std::vector<object_data> data;
for (int i=0; i < sizeof(data_temp) / sizeof(object_data); i ++) {
data.push_back(data_temp[i]);
}
if ( !getObject(&data) ) { return false; }
}
bool Epos2::getObject(std::vector<object_data> *data) {
bool no_error = true;
uint32_t bytes;
for (std::vector<object_data>::iterator it=data->begin(); it < data->end(); it++) {
if ( it->type == int8 ) {
int8_t value;
if ( !VCS_GetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 1, &bytes, &lastEpos2ErrorCode) ) {
printEpos2Error();
no_error = false;
} else {
it->value = value;
}
} else if ( it->type == uint8 ) {
uint8_t value;
if ( !VCS_GetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 1, &bytes, &lastEpos2ErrorCode) ) {
printEpos2Error();
no_error = false;
} else {
it->value = value;
}
} else if ( it->type == uint16 ) {
uint16_t value;
if ( !VCS_GetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 2, &bytes, &lastEpos2ErrorCode) ) {
printEpos2Error();
no_error = false;
} else {
it->value = value;
}
} else if ( it->type == uint32 ) {
uint32_t value;
if ( !VCS_GetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 4, &bytes, &lastEpos2ErrorCode) ) {
printEpos2Error();
no_error = false;
} else {
it->value = value;
}
}
}
return no_error;
}
bool Epos2::setObject(std::vector<object_data> *data) {
bool no_error = true;
uint32_t bytes;
for (std::vector<object_data>::iterator it=data->begin(); it < data->end(); it++) {
if ( it->type == int8 ) {
int8_t value = it->value;
if ( !VCS_SetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 1, &bytes, &lastEpos2ErrorCode) ) {
printEpos2Error();
no_error = false;
}
} else if ( it->type == uint8 ) {
uint8_t value = it->value;
if ( !VCS_SetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 1, &bytes, &lastEpos2ErrorCode) ) {
printEpos2Error();
no_error = false;
}
} else if ( it->type == uint16 ) {
uint16_t value = it->value;
if ( !VCS_SetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 2, &bytes, &lastEpos2ErrorCode) ) {
printEpos2Error();
no_error = false;
}
} else if ( it->type == uint32 ) {
uint32_t value = it->value;
if ( !VCS_SetObject(devhandle, epos_node_nr[0], it->index, it->sub_index, &value, 4, &bytes, &lastEpos2ErrorCode) ) {
printEpos2Error();
no_error = false;
}
}
}
return no_error;
}
}
| 34.543033 | 295 | 0.576556 | ein57ein |
e6ee1ddca6363514ed132fdf189b08050cd5b256 | 1,794 | cpp | C++ | src/nw4r/snd/snd_TaskThread.cpp | kiwi515/ogws-1 | b08dab7b988befb03f0efe03305f38c8ab8bad1e | [
"MIT"
] | 47 | 2020-08-27T00:27:31.000Z | 2022-03-14T13:40:08.000Z | src/nw4r/snd/snd_TaskThread.cpp | kiwi515/OGWS | 5903be49e333a6c871b6d28f15338839802ad853 | [
"MIT"
] | 1 | 2020-09-22T11:13:28.000Z | 2020-09-22T11:13:32.000Z | src/nw4r/snd/snd_TaskThread.cpp | kiwi515/OGWS | 5903be49e333a6c871b6d28f15338839802ad853 | [
"MIT"
] | 6 | 2020-08-27T20:06:25.000Z | 2022-01-16T08:57:28.000Z | #pragma ipa file
#include "snd_TaskThread.h"
#include "snd_TaskManager.h"
namespace nw4r
{
namespace snd
{
namespace detail
{
TaskThread::TaskThread()
{
mStackEnd = NULL;
mIsExiting = false;
mIsAlive = false;
}
TaskThread::~TaskThread()
{
if (mIsAlive) Destroy();
}
bool TaskThread::Create(s32 r4, void *stack, u32 r6)
{
if (mIsAlive) Destroy();
if (!OSCreateThread(&mThread, ThreadFunc, &mThread, (void *)((u32)stack + r6), r6, r4, 0))
return false;
mStackEnd = stack;
mIsExiting = false;
mIsAlive = true;
OSResumeThread(&mThread);
return true;
}
void TaskThread::Destroy()
{
if (mIsAlive)
{
mIsExiting = true;
TaskManager *pInstance = TaskManager::GetInstance();
pInstance->CancelWaitTask();
OSJoinThread(&mThread, 0);
mIsAlive = false;
}
}
int TaskThread::ThreadFunc(void *p)
{
TaskThread *pThread = (TaskThread *)p;
while (!pThread->mIsExiting)
{
TaskManager *pInstance = TaskManager::GetInstance();
pInstance->WaitTask();
if (pThread->mIsExiting) break;
pInstance = TaskManager::GetInstance();
pInstance->ExecuteTask();
}
return 0;
}
}
}
} | 26.776119 | 106 | 0.421405 | kiwi515 |
e6f237ff9f91f4470cdb7e401b1e5960c0564716 | 2,454 | hh | C++ | nipXray/include/NXChamberParameterisation.hh | maxwell-herrmann/geant4-simple-examples | 0052d40fdc05baef05b4a6873c03d0d54885ad40 | [
"BSD-2-Clause"
] | 9 | 2015-04-27T11:54:19.000Z | 2022-01-30T23:42:00.000Z | nipXray/include/NXChamberParameterisation.hh | maxwell-herrmann/geant4-simple-examples | 0052d40fdc05baef05b4a6873c03d0d54885ad40 | [
"BSD-2-Clause"
] | null | null | null | nipXray/include/NXChamberParameterisation.hh | maxwell-herrmann/geant4-simple-examples | 0052d40fdc05baef05b4a6873c03d0d54885ad40 | [
"BSD-2-Clause"
] | 3 | 2019-12-18T21:11:57.000Z | 2020-05-28T17:30:03.000Z | //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#ifndef NXChamberParameterisation_H
#define NXChamberParameterisation_H 1
#include "globals.hh"
#include "G4VPVParameterisation.hh"
#include "G4NistManager.hh"
class G4VPhysicalVolume;
class G4Box;
// Dummy declarations to get rid of warnings ...
class G4Trd;
class G4Trap;
class G4Cons;
class G4Orb;
class G4Sphere;
class G4Torus;
class G4Para;
class G4Hype;
class G4Tubs;
class G4Polycone;
class G4Polyhedra;
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
class NXChamberParameterisation : public G4VPVParameterisation
{
public:
NXChamberParameterisation( G4double startZ );
virtual
~NXChamberParameterisation();
void ComputeTransformation (const G4int copyNo,
G4VPhysicalVolume* physVol) const;
void ComputeDimensions (G4Box & trackerLayer, const G4int copyNo,
const G4VPhysicalVolume* physVol) const;
G4Material* ComputeMaterial(const G4int repNo,G4VPhysicalVolume *currentVol,
const G4VTouchable *parentTouch=0);
private: // Dummy declarations to get rid of warnings ...
void ComputeDimensions (G4Trd&,const G4int,const G4VPhysicalVolume*) const {}
void ComputeDimensions (G4Trap&,const G4int,const G4VPhysicalVolume*) const {}
void ComputeDimensions (G4Cons&,const G4int,const G4VPhysicalVolume*) const {}
void ComputeDimensions (G4Sphere&,const G4int,const G4VPhysicalVolume*) const {}
void ComputeDimensions (G4Orb&,const G4int,const G4VPhysicalVolume*) const {}
void ComputeDimensions (G4Torus&,const G4int,const G4VPhysicalVolume*) const {}
void ComputeDimensions (G4Para&,const G4int,const G4VPhysicalVolume*) const {}
void ComputeDimensions (G4Hype&,const G4int,const G4VPhysicalVolume*) const {}
void ComputeDimensions (G4Tubs&,const G4int,const G4VPhysicalVolume*) const {}
void ComputeDimensions (G4Polycone&,const G4int,const G4VPhysicalVolume*) const {}
void ComputeDimensions (G4Polyhedra&,const G4int,const G4VPhysicalVolume*) const {}
private:
G4double fStartZ;
G4Material* Fe;
G4Material* Vacuum;
};
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#endif
| 34.083333 | 91 | 0.696007 | maxwell-herrmann |
e6f5d5e5ce376f277c99c3f9d56ee7f31d62a478 | 33,983 | hpp | C++ | src/lang/dzm_prc.hpp | arogan-group/DZMLang | 4ef827de34a07fb4f2dde817c297841c25382231 | [
"Apache-2.0"
] | 1 | 2016-09-23T14:29:44.000Z | 2016-09-23T14:29:44.000Z | src/lang/dzm_prc.hpp | arogan-group/DZMLang | 4ef827de34a07fb4f2dde817c297841c25382231 | [
"Apache-2.0"
] | null | null | null | src/lang/dzm_prc.hpp | arogan-group/DZMLang | 4ef827de34a07fb4f2dde817c297841c25382231 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2016 Dominik Madarasz
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.
*/
#if !defined(DZM_PRC_H)
#include <ctime>
#include <cmath>
#ifndef WIN32
#include <pthread.h>
#endif
#define def_proc(Name) static inline OBJECT * Name##_proc(OBJECT *Args)
#define add_procedure(Name, Call) \
define_variable(make_symbol((u8 *)Name), \
make_procedure(Call), \
Env);
#define check_args(o) \
if(is_nil(pair_get_a(Args))) \
LOG(LOG_WARN, o " " "is missing required arguments")
#include "prc/prc_net.hpp"
#include "prc/prc_thd.hpp"
def_proc(inc)
{
OBJECT *Arg0 = pair_get_a(Args);
OBJECT *Obj = Arg0;
if(is_realnum(Arg0))
{
Obj = make_realnum(Arg0->uData.MDL_REALNUM.Value + 1.0);
}
else if(is_fixnum(Arg0))
{
Obj = make_fixnum(Arg0->uData.MDL_FIXNUM.Value + 1);
}
else if(is_character(Arg0))
{
Obj = make_character(Arg0->uData.MDL_CHARACTER.Value + 1);
}
else if(is_string(Arg0))
{
Obj = make_string(Arg0->uData.MDL_STRING.Value + 1);
}
return(Obj);
}
def_proc(dec)
{
OBJECT *Arg0 = pair_get_a(Args);
OBJECT *Obj = Arg0;
if(is_realnum(Arg0))
{
Obj = make_realnum(Arg0->uData.MDL_REALNUM.Value - 1.0);
}
else if(is_fixnum(Arg0))
{
Obj = make_fixnum(Arg0->uData.MDL_FIXNUM.Value - 1);
}
else if(is_character(Arg0))
{
Obj = make_character(Arg0->uData.MDL_CHARACTER.Value - 1);
}
else if(is_string(Arg0))
{
Obj = make_string(Arg0->uData.MDL_STRING.Value - 1);
}
return(Obj);
}
// NOTE(zaklaus): Arithmetic operators
static inline OBJECT *
add_proc(OBJECT *Args)
{
real64 Result = 0;
b32 Real = 0;
while(!is_nil(Args))
{
if(is_fixnum(pair_get_a(Args)))
Result += (pair_get_a(Args))->uData.MDL_FIXNUM.Value;
else
{
Real = 1;
Result += (pair_get_a(Args))->uData.MDL_REALNUM.Value;
}
Args = pair_get_b(Args);
}
if(!Real)
return(make_fixnum((s64)Result));
else
return(make_realnum(Result));
}
static inline OBJECT *
sub_proc(OBJECT *Args)
{
r64 Result = 0;
b32 Real = 0;
if(!is_nil(Args))
{
if(is_fixnum(pair_get_a(Args)))
Result = (r64)(pair_get_a(Args))->uData.MDL_FIXNUM.Value;
else
{
Real = 1;
Result = (pair_get_a(Args))->uData.MDL_REALNUM.Value;
}
Args = pair_get_b(Args);
}
b32 IsAlone = 1;
while(!is_nil(Args))
{
Result -= (pair_get_a(Args))->uData.MDL_FIXNUM.Value;
Args = pair_get_b(Args);
IsAlone = 0;
}
if(IsAlone)
{
Result = -Result;
}
if(!Real)
return(make_fixnum((s64)Result));
else
return(make_realnum(Result));
}
static inline OBJECT *
div_proc(OBJECT *Args)
{
r64 Result = 0;
b32 Real = 1;
if(!is_nil(Args))
{
if(is_fixnum(pair_get_a(Args)))
Result = (r64)(pair_get_a(Args))->uData.MDL_FIXNUM.Value;
else
{
Result = (r64)(pair_get_a(Args))->uData.MDL_REALNUM.Value;
}
Args = pair_get_b(Args);
}
while(!is_nil(Args))
{
if((pair_get_a(Args))->uData.MDL_FIXNUM.Value == 0)
{
LOG(ERR_WARN, "Division by zero");
return(Nil);
InvalidCodePath;
}
if(is_fixnum(pair_get_a(Args)))
Result = (r64)Result / (r64)(pair_get_a(Args))->uData.MDL_FIXNUM.Value;
else
{
Result /= (r64)(pair_get_a(Args))->uData.MDL_REALNUM.Value;
}
Args = pair_get_b(Args);
}
if(!Real)
return(make_fixnum((s64)Result));
else
return(make_realnum(Result));
}
static inline OBJECT *
div_full_proc(OBJECT *Args)
{
r64 Result = 0;
b32 Real = 0;
if (!is_nil(Args))
{
if (is_fixnum(pair_get_a(Args)))
Result = (r64)(pair_get_a(Args))->uData.MDL_FIXNUM.Value;
else
{
Result = (r64)(pair_get_a(Args))->uData.MDL_REALNUM.Value;
}
Args = pair_get_b(Args);
}
while (!is_nil(Args))
{
if ((pair_get_a(Args))->uData.MDL_FIXNUM.Value == 0)
{
LOG(ERR_WARN, "Division by zero");
return(Nil);
InvalidCodePath;
}
if (is_fixnum(pair_get_a(Args)))
Result = (r64)Result / (r64)(pair_get_a(Args))->uData.MDL_FIXNUM.Value;
else
{
Result /= (r64)(pair_get_a(Args))->uData.MDL_REALNUM.Value;
}
Args = pair_get_b(Args);
}
if (!Real)
return(make_fixnum((s64)Result));
else
return(make_realnum(Result));
}
static inline OBJECT *
mod_proc(OBJECT *Args)
{
s64 Result = 0;
if(is_realnum(pair_get_a(Args)))
{
r64 Value = pair_get_a(Args)->uData.MDL_REALNUM.Value;
if(trunc(Value) != Value) Value = -1;
pair_set_a(Args, make_fixnum(Value));
}
if(!is_nil(Args))
{
Result = (pair_get_a(Args))->uData.MDL_FIXNUM.Value;
Args = pair_get_b(Args);
}
while(!is_nil(Args))
{
if((pair_get_a(Args))->uData.MDL_FIXNUM.Value == 0)
{
LOG(ERR_WARN, "Division by zero");
return(Nil);
InvalidCodePath;
}
Result %= (pair_get_a(Args))->uData.MDL_FIXNUM.Value;
Args = pair_get_b(Args);
}
return(make_fixnum(Result));
}
static inline OBJECT *
mul_proc(OBJECT *Args)
{
r64 Result = 1;
b32 Real = 0;
while(!is_nil(Args))
{
if(is_fixnum(pair_get_a(Args)))
Result *= (pair_get_a(Args))->uData.MDL_FIXNUM.Value;
else
{
Real = 1;
Result *= (pair_get_a(Args))->uData.MDL_REALNUM.Value;
}
Args = pair_get_b(Args);
}
if(!Real)
return(make_fixnum((s64)Result));
else
return(make_realnum(Result));
}
// NOTE(zaklaus): Existence checks
def_proc(is_nil)
{
return(is_nil(pair_get_a(Args)) ? True : False);
}
def_proc(is_boolean)
{
return(is_boolean(pair_get_a(Args)) ? True : False);
}
def_proc(is_symbol)
{
return(is_symbol(pair_get_a(Args)) ? True : False);
}
def_proc(is_integer)
{
return(is_fixnum(pair_get_a(Args)) ? True : False);
}
def_proc(is_real)
{
return(is_realnum(pair_get_a(Args)) ? True : False);
}
def_proc(is_char)
{
return(is_character(pair_get_a(Args)) ? True : False);
}
def_proc(is_string)
{
return(is_string(pair_get_a(Args)) ? True : False);
}
def_proc(is_pair)
{
return(is_pair(pair_get_a(Args)) ? True : False);
}
def_proc(is_compound)
{
return(is_compound(pair_get_a(Args)) ? True : False);
}
def_proc(is_procedure)
{
return((is_procedure(pair_get_a(Args))) ? True : False);
}
// NOTE(zaklaus): Type conversions
def_proc(char_to_integer)
{
return(make_fixnum((pair_get_a(Args))->uData.MDL_CHARACTER.Value));
}
def_proc(integer_to_char)
{
return(make_character((u8)(pair_get_a(Args))->uData.MDL_FIXNUM.Value));
}
def_proc(string_to_char)
{
return(make_character(*((pair_get_a(Args))->uData.MDL_STRING.Value)));
}
def_proc(char_to_symbol)
{
TEMP_MEMORY Mem = begin_temp(&StringArena);
char *Buffer = (char *)push_size(&StringArena, 2, default_arena_params());
sprintf(Buffer, "%c", pair_get_a(Args)->uData.MDL_CHARACTER.Value);
end_temp(Mem);
return(make_symbol((u8 *)Buffer));
}
def_proc(char_to_string)
{
TEMP_MEMORY Mem = begin_temp(&StringArena);
char *Buffer = (char *)push_size(&StringArena, 2, default_arena_params());
sprintf(Buffer, "%c", pair_get_a(Args)->uData.MDL_CHARACTER.Value);
end_temp(Mem);
return(make_string((u8 *)Buffer));
}
def_proc(number_to_string)
{
TEMP_MEMORY Mem = begin_temp(&StringArena);
char *Buffer = (char *)push_size(&StringArena, 66, default_arena_params());
if(is_fixnum(pair_get_a(Args))) sprintf(Buffer, "%" PRId64, (pair_get_a(Args))->uData.MDL_FIXNUM.Value);
else sprintf(Buffer, "%lf", (double)((pair_get_a(Args))->uData.MDL_REALNUM.Value));
end_temp(Mem);
return(make_string((u8 *)Buffer));
}
def_proc(string_to_number)
{
char * String = (char *)((pair_get_a(Args))->uData.MDL_STRING.Value);
char * EndPtr = 0;
s64 Number = strtoull(String, &EndPtr, 10);
return(make_fixnum(Number));
}
def_proc(symbol_to_string)
{
return(make_string((pair_get_a(Args))->uData.MDL_SYMBOL.Value));
}
def_proc(string_to_symbol)
{
return(make_symbol((pair_get_a(Args))->uData.MDL_STRING.Value));
}
def_proc(is_number_equal)
{
OBJECT *R = False;
if(pair_get_a(Args)->Type == MDL_FIXNUM)
{
s64 Value = (pair_get_a(Args))->uData.MDL_FIXNUM.Value;
while(!is_nil(Args = pair_get_b(Args)))
{
if(is_fixnum(pair_get_a(Args)))
{
R = (Value == pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False;
}
if(is_realnum(pair_get_a(Args)))
{
R = ((r64)Value == pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False;
}
}
}
else if(pair_get_a(Args)->Type == MDL_REALNUM)
{
r64 Value = (pair_get_a(Args))->uData.MDL_REALNUM.Value;
while(!is_nil(Args = pair_get_b(Args)))
{
if(is_fixnum(pair_get_a(Args)))
{
R = (Value == (r64)pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False;
}
if(is_realnum(pair_get_a(Args)))
{
R = (Value == pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False;
}
if(R == False) return(R);
}
}
return(R);
}
def_proc(is_greater_than_or_equal)
{
OBJECT* R = 0;
if(pair_get_a(Args)->Type == MDL_FIXNUM)
{
s64 Value = (pair_get_a(Args))->uData.MDL_FIXNUM.Value;
while(!is_nil(Args = pair_get_b(Args)))
{
if(is_fixnum(pair_get_a(Args)))
{
R = (Value >= pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False;
}
if(is_realnum(pair_get_a(Args)))
{
R = ((r64)Value >= pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False;
}
if(R == False) return(R);
}
}
else if(pair_get_a(Args)->Type == MDL_REALNUM)
{
r64 Value = (pair_get_a(Args))->uData.MDL_REALNUM.Value;
while(!is_nil(Args = pair_get_b(Args)))
{
if(is_fixnum(pair_get_a(Args)))
{
R = (Value >= (r64)pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False;
}
if(is_realnum(pair_get_a(Args)))
{
R = (Value >= pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False;
}
if(R == False) return(R);
}
}
return(R);
}
def_proc(is_greater_than)
{
OBJECT* R = 0;
if(pair_get_a(Args)->Type == MDL_FIXNUM)
{
s64 Value = (pair_get_a(Args))->uData.MDL_FIXNUM.Value;
while(!is_nil(Args = pair_get_b(Args)))
{
if(is_fixnum(pair_get_a(Args)))
{
R = (Value > pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False;
}
if(is_realnum(pair_get_a(Args)))
{
R = ((r64)Value > pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False;
}
if(R == False) return(R);
}
}
else if(pair_get_a(Args)->Type == MDL_REALNUM)
{
r64 Value = (pair_get_a(Args))->uData.MDL_REALNUM.Value;
while(!is_nil(Args = pair_get_b(Args)))
{
if(is_fixnum(pair_get_a(Args)))
{
R = (Value > (r64)pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False;
}
if(is_realnum(pair_get_a(Args)))
{
R = (Value > pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False;
}
if(R == False) return(R);
}
}
return(R);
}
def_proc(is_less_than)
{
OBJECT* R = 0;
if(pair_get_a(Args)->Type == MDL_FIXNUM)
{
s64 Value = (pair_get_a(Args))->uData.MDL_FIXNUM.Value;
while(!is_nil(Args = pair_get_b(Args)))
{
if(is_fixnum(pair_get_a(Args)))
{
R = (Value < pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False;
}
if(is_realnum(pair_get_a(Args)))
{
R = ((r64)Value < pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False;
}
if(R == False) return(R);
}
}
else if(pair_get_a(Args)->Type == MDL_REALNUM)
{
r64 Value = (pair_get_a(Args))->uData.MDL_REALNUM.Value;
while(!is_nil(Args = pair_get_b(Args)))
{
if(is_fixnum(pair_get_a(Args)))
{
R = (Value < (r64)pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False;
}
if(is_realnum(pair_get_a(Args)))
{
R = (Value < pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False;
}
if(R == False) return(R);
}
}
return(R);
}
def_proc(is_less_than_or_equal)
{
OBJECT* R = 0;
if(pair_get_a(Args)->Type == MDL_FIXNUM)
{
s64 Value = (pair_get_a(Args))->uData.MDL_FIXNUM.Value;
while(!is_nil(Args = pair_get_b(Args)))
{
if(is_fixnum(pair_get_a(Args)))
{
R = (Value <= pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False;
}
if(is_realnum(pair_get_a(Args)))
{
R = ((r64)Value <= pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False;
}
if(R == False) return(R);
}
}
else if(pair_get_a(Args)->Type == MDL_REALNUM)
{
r64 Value = (pair_get_a(Args))->uData.MDL_REALNUM.Value;
while(!is_nil(Args = pair_get_b(Args)))
{
if(is_fixnum(pair_get_a(Args)))
{
R = (Value <= (r64)pair_get_a(Args)->uData.MDL_FIXNUM.Value) ? True : False;
}
if(is_realnum(pair_get_a(Args)))
{
R = (Value <= pair_get_a(Args)->uData.MDL_REALNUM.Value) ? True : False;
}
if(R == False) return(R);
}
}
return(R);
}
def_proc(concat)
{
TEMP_MEMORY StringTemp = begin_temp(&StringArena);
char *Result = 0;
OBJECT *Text = pair_get_a(Args);
concat_tailcall:
if(is_string(Text))
{
Result = (char *)push_size(&StringArena, strlen((char *)Text->uData.MDL_STRING.Value)+1, default_arena_params());
strcpy(Result, (char *)Text->uData.MDL_STRING.Value);
}
else if(is_pair(Text))
{
Text = concat_proc(Text);
goto concat_tailcall;
}
else
{
Result = (char *)push_size(&StringArena,2,default_arena_params());
Result[0] = (char)Text->uData.MDL_CHARACTER.Value;
Result[1] = 0;
}
while(!is_nil(Args = pair_get_b(Args)))
{
Text = pair_get_a(Args);
concat_tailcall2:
if(is_string(Text))
{
Result = (char *)push_copy(&StringArena, strlen(Result) + strlen((char *)Text->uData.MDL_STRING.Value)+1, Result, default_arena_params());
strcat(Result, (char *)Text->uData.MDL_STRING.Value);
}
else if(is_nil(Text))
{
break;
}
else if(is_pair(Text))
{
Text = concat_proc(Text);
goto concat_tailcall2;
}
else
{
mi ResultEnd = strlen(Result);
Result = (char *)push_copy(&StringArena, strlen(Result) + 2, Result, default_arena_params());
Result[ResultEnd] = (char)Text->uData.MDL_CHARACTER.Value;
Result[ResultEnd+1] = 0;
}
}
end_temp(StringTemp);
return(make_string((u8 *)Result));
}
def_proc(cons)
{
pair_set_b(Args, pair_get_a(pair_get_b(Args)));
return(Args);
}
def_proc(car)
{
if(is_string(pair_get_a(Args)))
return(make_character(pair_get_a(Args)->uData.MDL_STRING.Value[0]));
else
return(pair_get_a(pair_get_a(Args)));
}
def_proc(cdr)
{
if(is_string(pair_get_a(Args)) &&
(strlen((char *)pair_get_a(Args)->uData.MDL_STRING.Value) > 1))
return(make_string(pair_get_a(Args)->uData.MDL_STRING.Value+1));
else if(is_pair(pair_get_a(Args)))
return(pair_get_b(pair_get_a(Args)));
else
return(Nil);
}
def_proc(set_car)
{
pair_set_a(pair_get_a(Args), pair_get_a(pair_get_b(Args)));
return OKSymbol;
}
def_proc(set_cdr)
{
pair_set_b(pair_get_a(Args), pair_get_a(pair_get_b(Args)));
return OKSymbol;
}
def_proc(list)
{
return(Args);
}
def_proc(is_eq)
{
OBJECT *Obj1 = pair_get_a(Args);
OBJECT *Obj2 = pair_get_a(pair_get_b(Args));
if(Obj1->Type != Obj2->Type)
{
return(False);
}
switch(Obj1->Type)
{
case MDL_REALNUM:
case MDL_FIXNUM:
{
return((Obj1->uData.MDL_FIXNUM.Value ==
Obj2->uData.MDL_FIXNUM.Value) ?
True : False);
}break;
case MDL_CHARACTER:
{
return((Obj1->uData.MDL_CHARACTER.Value ==
Obj2->uData.MDL_CHARACTER.Value) ?
True : False);
}break;
case MDL_STRING:
{
return((!strcmp((char *)Obj1->uData.MDL_STRING.Value,
(char *)Obj2->uData.MDL_STRING.Value)) ?
True : False);
}break;
default:
{
return((Obj1 == Obj2) ? True : False);
}break;
}
}
def_proc(apply)
{
LOG(ERR_WARN, "illegal state: The body of the apply should not execute");
InvalidCodePath;
Unreachable(Args);
}
def_proc(eval)
{
LOG(ERR_WARN, "illegal state: The body of the eval should not execute");
InvalidCodePath;
Unreachable(Args);
}
def_proc(interaction_env)
{
return(GlobalEnv);
Unreachable(Args);
}
def_proc(nil_env)
{
return(setup_env());
Unreachable(Args);
}
def_proc(env)
{
return(make_env());
Unreachable(Args);
}
def_proc(load)
{
b32 OldOk = PrintOk;
PrintOk = 0;
u8 *Filename;
FILE *In;
OBJECT *Exp;
OBJECT *Result = 0;
OBJECT *Env = GlobalEnv;
Filename = (pair_get_a(Args))->uData.MDL_STRING.Value;
In = fopen((char *)Filename, "r");
if(In == 0)
{
LOG(ERR_WARN, "Could not load file \"%s\"\n", Filename);
PrintOk = OldOk;
return(Nil);
InvalidCodePath;
}
if(!is_nil(pair_get_b(Args)))
{
Env = pair_get_b(pair_get_a(Args));
}
while((Exp = read(In)) != 0)
{
Result = eval(Exp, Env);
}
fclose(In);
PrintOk = OldOk;
return(Result);
}
def_proc(read)
{
FILE *In;
OBJECT *Result;
In = is_nil(Args) ? read_input(stdin) : (pair_get_a(Args))->uData.MDL_INPUT.Stream;
Result = read(In);
return((Result == 0) ? EOF_Obj : Result);
}
def_proc(write)
{
OBJECT *Exp;
FILE *Out;
Exp = pair_get_a(Args);
Args = pair_get_b(Args);
Out = is_nil(Args) ? stdout : (pair_get_a(Args))->uData.MDL_OUTPUT.Stream;
b32 StripQuotes = is_nil(Args) ? 1 : is_nil(pair_get_b(Args)) ? 1 : (pair_get_a(pair_get_b(Args)))->uData.MDL_BOOLEAN.Value;
write(Out, Exp, StripQuotes);
fflush(Out);
return(OKSymbol);
}
def_proc(peek_char)
{
FILE *In;
s32 Result;
In = is_nil(Args) ? read_input(stdin) : (pair_get_a(Args))->uData.MDL_INPUT.Stream;
Result = peek(In);
return((Result == EOF) ? EOF_Obj : make_character(Result));
}
def_proc(open_input)
{
u8 *Filename;
FILE *In;
Filename = (pair_get_a(Args))->uData.MDL_STRING.Value;
In = fopen((char *)Filename, "r");
if(In == 0)
{
LOG(ERR_WARN, "Could not load file \"%s\"\n", Filename);
InvalidCodePath;
}
return(make_input(In));
}
def_proc(close_input)
{
s32 Result;
Result = fclose((pair_get_a(Args))->uData.MDL_INPUT.Stream);
if(Result == EOF)
{
LOG(ERR_WARN, "Could not close input");
InvalidCodePath;
}
return(OKSymbol);
}
def_proc(is_input)
{
return(is_input(pair_get_a(Args)) ? True : False);
}
def_proc(open_output)
{
u8 *Filename;
FILE *In;
Filename = (pair_get_a(Args))->uData.MDL_STRING.Value;
In = fopen((char *)Filename, "w");
if(In == 0)
{
LOG(ERR_WARN, "Could not load file \"%s\"\n", Filename);
InvalidCodePath;
}
return(make_output(In));
}
def_proc(close_output)
{
s32 Result;
Result = fclose((pair_get_a(Args))->uData.MDL_INPUT.Stream);
if(Result == EOF)
{
LOG(ERR_WARN, "Could not close output");
InvalidCodePath;
}
return(OKSymbol);
}
def_proc(is_output)
{
return(is_output(pair_get_a(Args)) ? True : False);
}
def_proc(is_eof_obj)
{
return(is_eof_obj(pair_get_a(Args)) ? True : False);
}
def_proc(write_char)
{
OBJECT *Char;
FILE *Out;
Char = pair_get_a(Args);
Args = pair_get_b(Args);
Out = is_nil(Args) ? stdout : (pair_get_a(Args))->uData.MDL_OUTPUT.Stream;
putc(Char->uData.MDL_CHARACTER.Value, Out);
fflush(Out);
return(OKSymbol);
}
def_proc(write_string)
{
OBJECT *String;
FILE *Out;
String = pair_get_a(Args);
if(!is_string(String) && (is_realnum(String) || is_fixnum(String)))
{
TEMP_MEMORY Temp = begin_temp(&StringArena);
char *Buffer = (char *)push_size(&StringArena, 66, default_arena_params());
if(is_realnum(String))
{
sprintf(Buffer, "%.17Lg", String->uData.MDL_REALNUM.Value);
}
else sprintf(Buffer, "%" PRId64, String->uData.MDL_FIXNUM.Value);
String = make_string((u8 *)Buffer);
end_temp(Temp);
}
else if(!is_string(String))
{
LOG(ERR_WARN, "write-string expects 1 parameter to be: <MDL_STRING|MDL_REALNUM|MDL_FIXNUM>.");
return(Nil);
}
Args = pair_get_b(Args);
Out = is_nil(Args) ? stdout : (pair_get_a(Args))->uData.MDL_OUTPUT.Stream;
fprintf(Out, "%s", (char *)String->uData.MDL_STRING.Value);
fflush(Out);
return(OKSymbol);
}
def_proc(read_string)
{
FILE *In;
OBJECT *Result;
In = (is_nil(pair_get_a(Args))) ? stdin : (pair_get_a(Args))->uData.MDL_INPUT.Stream;
char *String = (char *)StringArena.Base;
fgets(String, (int)StringArena.Size, In);
Result = make_string((u8 *)String);
StringArena.Used = 0;
return((Result == 0) ? EOF_Obj : Result);
}
static inline u8 *
trim_string(u8 *String);
def_proc(trim)
{
if(!is_string(pair_get_a(Args))) return(pair_get_a(Args));
return(make_string(trim_string(pair_get_a(Args)->uData.MDL_STRING.Value)));
}
def_proc(read_char)
{
s32 Result;
FILE *In;
if(is_string(pair_get_a(Args)))
{
Result = *(pair_get_a(Args)->uData.MDL_STRING.Value);
return(make_character(Result));
}
In = is_nil(Args) ? stdin : (pair_get_a(Args))->uData.MDL_INPUT.Stream;
Result = getc(In);
#if _WIN32_
getc(In); // Consume '\r'
#endif
getc(In); // Consume '\n'
return((Result == EOF) ? EOF_Obj : make_character(Result));
}
def_proc(system)
{
#if _ELEVATED == 1
if(!is_string(pair_get_a(Args)))
{
return(Nil);
}
FILE *Out = stdout;
if(!is_nil(pair_get_a(pair_get_b(Args))))
{
Out = (pair_get_a(pair_get_b(Args)))->uData.MDL_OUTPUT.Stream;
}
#ifdef WIN32
FILE *Sys = _popen((char *)(pair_get_a(Args)->uData.MDL_STRING.Value), "r");
#else
FILE *Sys = popen((char *)(pair_get_a(Args)->uData.MDL_STRING.Value), "r");
#endif
if(!Sys)
{
goto system_end;
}
s32 C;
while((C = getc(Sys)) != EOF)
{
putc((char)C, Out);
}
#ifdef WIN32
_pclose(Sys);
#else
pclose(Sys);
#endif
system_end:
if(is_nil(pair_get_a(pair_get_b(Args))))
return(OKSymbol);
else
return(pair_get_a(pair_get_b(Args)));
#else
LOG(ERR_WARN, "Procedure requires elevation!");
return(OKSymbol);
Unreachable(Args);
#endif
}
def_proc(arena_mem)
{
return(make_fixnum(0));
/*make_pair(make_fixnum(
get_arena_size_remaining(GlobalArena, default_arena_params())),
make_fixnum(GlobalArena->Size)));*/
Unreachable(Args);
}
def_proc(log_mem)
{
PrintMemUsage = !PrintMemUsage;
return(Args);
}
def_proc(error_reporting)
{
if(is_nil(pair_get_a(Args)))
{
LOG(ERR_WARN, "error-reporting is missing: <error-level>");
return(OKSymbol);
}
u8 Result = (u8)(pair_get_a(Args)->uData.MDL_FIXNUM.Value);
error_reporting(Result);
return(OKSymbol);
}
def_proc(random)
{
srand((unsigned int)time(0));
s64 RandomValue = (s64)rand();
if(!is_nil(pair_get_a(Args)))
{
RandomValue %= (pair_get_a(Args))->uData.MDL_FIXNUM.Value;
}
return(make_fixnum(RandomValue));
}
def_proc(error)
{
if(is_nil(pair_get_a(Args)))
{
LOG(ERR_WARN, "error is missing: <message>");
return(OKSymbol);
}
LOG(ERR_WARN, "Exception -> %s", (char *)pair_get_a(Args)->uData.MDL_STRING.Value);
return(OKSymbol);
}
def_proc(log)
{
return(make_realnum(log(pair_get_a(Args)->uData.MDL_REALNUM.Value)));
}
def_proc(log2)
{
r64 A = pair_get_a(Args)->uData.MDL_REALNUM.Value;
return(make_realnum(log2(A)));
}
def_proc(sin)
{
if(pair_get_a(Args)->Type == MDL_REALNUM)
{
return(make_realnum(sin((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value))));
}
return(make_realnum(sin((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value))));
}
def_proc(cos)
{
if(pair_get_a(Args)->Type == MDL_REALNUM)
{
return(make_realnum(cos((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value))));
}
return(make_realnum(cos((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value))));
}
def_proc(tan)
{
if(pair_get_a(Args)->Type == MDL_REALNUM)
{
return(make_realnum(tan((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value))));
}
return(make_realnum(tan((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value))));
}
def_proc(asin)
{
if(pair_get_a(Args)->Type == MDL_REALNUM)
{
return(make_realnum(asin((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value))));
}
return(make_realnum(asin((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value))));
}
def_proc(acos)
{
if(pair_get_a(Args)->Type == MDL_REALNUM)
{
return(make_realnum(acos((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value))));
}
return(make_realnum(acos((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value))));
}
def_proc(atan)
{
if(pair_get_a(Args)->Type == MDL_REALNUM)
{
return(make_realnum(atan((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value))));
}
return(make_realnum(atan((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value))));
}
def_proc(sqrt)
{
if(pair_get_a(Args)->Type == MDL_REALNUM)
{
return(make_realnum(sqrt((double)(pair_get_a(Args)->uData.MDL_REALNUM.Value))));
}
return(make_realnum(sqrt((double)(pair_get_a(Args)->uData.MDL_FIXNUM.Value))));
}
def_proc(exit)
{
s64 ErrorCode = 0;
if(!is_nil(pair_get_a(Args)))
{
ErrorCode = pair_get_a(Args)->uData.MDL_FIXNUM.Value;
}
exit((int)ErrorCode);
}
def_proc(log_verbose)
{
if(!is_nil(pair_get_a(Args)) && !is_boolean(pair_get_a(Args)))
{
LOG(ERR_WARN, "log-verbose is missing: <MDL_BOOLEAN>");
return(OKSymbol);
}
b32 Result = 0;
if(!is_nil(pair_get_a(Args)))
{
Result = (is_true(pair_get_a(Args))) ? 1 : 0;
}
else
{
Result = !IsVerbose;
}
set_log_verbose(Result);
return(OKSymbol);
}
def_proc(sleep)
{
if(!is_nil(pair_get_a(Args)))
{
sleepcp((int)pair_get_a(Args)->uData.MDL_FIXNUM.Value);
}
return(OKSymbol);
Unreachable(Args);
}
static inline void
init_builtins(OBJECT *Env)
{
add_procedure("inc", inc_proc);
add_procedure("dec", dec_proc);
add_procedure("+" , add_proc);
add_procedure("-" , sub_proc);
add_procedure("*" , mul_proc);
add_procedure("/" , div_proc);
add_procedure("//", div_full_proc);
add_procedure("%" , mod_proc);
add_procedure("nil?" , is_nil_proc);
add_procedure("null?" , is_nil_proc);
add_procedure("boolean?" , is_boolean_proc);
add_procedure("symbol?" , is_symbol_proc);
add_procedure("integer?" , is_integer_proc);
add_procedure("char?" , is_char_proc);
add_procedure("string?" , is_string_proc);
add_procedure("pair?" , is_pair_proc);
add_procedure("procedure?", is_procedure_proc);
add_procedure("char->integer" , char_to_integer_proc);
add_procedure("char->string" , char_to_string_proc);
add_procedure("char->symbol" , char_to_symbol_proc);
add_procedure("integer->char" , integer_to_char_proc);
add_procedure("string->char" , string_to_char_proc);
add_procedure("number->string", number_to_string_proc);
add_procedure("string->number", string_to_number_proc);
add_procedure("symbol->string", symbol_to_string_proc);
add_procedure("string->symbol", string_to_symbol_proc);
add_procedure("trim-string", trim_proc);
add_procedure("=" , is_number_equal_proc);
add_procedure("<" , is_less_than_proc);
add_procedure(">" , is_greater_than_proc);
add_procedure(">=" , is_greater_than_or_equal_proc);
add_procedure("<=" , is_less_than_or_equal_proc);
add_procedure("log" , log_proc);
add_procedure("log2" , log2_proc);
add_procedure("sin" , sin_proc);
add_procedure("cos" , cos_proc);
add_procedure("tan" , tan_proc);
add_procedure("asin" , asin_proc);
add_procedure("acos" , acos_proc);
add_procedure("atan" , atan_proc);
add_procedure("sqrt" , sqrt_proc);
add_procedure("exit" , exit_proc);
add_procedure("sleep", sleep_proc);
add_procedure("cons" , cons_proc);
add_procedure("car" , car_proc);
add_procedure("cdr" , cdr_proc);
add_procedure("set-car!", set_car_proc);
add_procedure("set-cdr!", set_cdr_proc);
add_procedure("list" , list_proc);
add_procedure("apply" , apply_proc);
add_procedure("eval" , eval_proc);
add_procedure("eq?", is_eq_proc);
add_procedure("env" , env_proc);
add_procedure("i-env" , interaction_env_proc);
add_procedure("nil-env" , nil_env_proc);
add_procedure("load" , load_proc);
add_procedure("open-input" , open_input_proc);
add_procedure("close-input" , close_input_proc);
add_procedure("input?" , is_input_proc);
add_procedure("read" , read_proc);
add_procedure("read-char" , read_char_proc);
add_procedure("read-string" , read_string_proc);
add_procedure("peek-char" , peek_char_proc);
add_procedure("eof?" , is_eof_obj_proc);
add_procedure("open-output" , open_output_proc);
add_procedure("close-output", close_output_proc);
add_procedure("output?" , is_output_proc);
add_procedure("write-char" , write_char_proc);
add_procedure("write-string" , write_string_proc);
add_procedure("write" , write_proc);
add_procedure("error" , error_proc);
add_procedure("concat" , concat_proc);
add_procedure("system" , system_proc);
add_procedure("arena-mem" , arena_mem_proc);
add_procedure("log-mem" , log_mem_proc);
add_procedure("error-reporting", error_reporting_proc);
add_procedure("log-verbose" , log_verbose_proc);
add_procedure("random" , random_proc);
install_thd_module(Env);
install_net_module(Env);
}
#define DZM_PRC_H
#endif
| 25.941221 | 153 | 0.568549 | arogan-group |
e6f69861901ec37b5cad0bb497aa89182bac1d70 | 290 | cpp | C++ | src/16000/16917.cpp17.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | 8 | 2018-04-12T15:54:09.000Z | 2020-06-05T07:41:15.000Z | src/16000/16917.cpp17.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | null | null | null | src/16000/16917.cpp17.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
const int INF=1e9;
using namespace std;
int main()
{
int a, b, c, x, y;
cin >> a >> b >> c >> x >> y;
int r1, r2, r3;
r1 = min(x, y) * 2 * c + abs(x - y)*(x > y ? a : b);
r2 = x*a + y*b;
r3 = max(x, y) * 2 * c;
cout << min({ r1, r2, r3 });
} | 19.333333 | 53 | 0.482759 | upple |
e6fcff938d84109a6d190404bd506133a607e31f | 3,685 | cpp | C++ | src/service_discovery.cpp | maxcong001/empty009 | 5fd7a4f2ef3f459ff869ffbd6fb6ac8e97725f64 | [
"MIT"
] | null | null | null | src/service_discovery.cpp | maxcong001/empty009 | 5fd7a4f2ef3f459ff869ffbd6fb6ac8e97725f64 | [
"MIT"
] | null | null | null | src/service_discovery.cpp | maxcong001/empty009 | 5fd7a4f2ef3f459ff869ffbd6fb6ac8e97725f64 | [
"MIT"
] | null | null | null | #include "service_discovery.hpp"
/*********************** Common ***********************/
/**
* @brief Compare functions used for "sort" and "difference"
* @param lhs: pointer reference to common data
* @param rhs: pointer reference to common data
* @return true if lhs < rhs, otherwise return false
*/
bool compareDiscoveryData(const service_discovery_interface::ptr_t &lhs, const service_discovery_interface::ptr_t &rhs)
{
return lhs->less(lhs, rhs);
}
/*********************** Service Discovery Base Data ***********************/
/**
* @brief get host and port
* @param type: address type
* @return host and port
*/
HostAndPort service_discovery_interface::getHostAndPort(DwAddrType::type type, HostType::type hostType)
{
// error log
return HostAndPort(); // return empty data
}
/**
* @brief set host and port
* @param data: host and port
* @param type: address type
* @return void
*/
void service_discovery_interface::setHostAndPort(HostAndPort &data, DwAddrType::type type)
{
// error log
return;
}
/**
* @brief get host type
* @param type: address type
* @return host type
*/
HostType::type service_discovery_interface::getHostType(DwAddrType::type type, HostType::type hostType)
{
// error log
return HostType::DBW_MAX; // return an invalid value
}
/**
* @brief set host type
* @param type: host type
* @param addrType: address type
* @return host type
*/
void service_discovery_interface::setHostType(HostType::type type, DwAddrType::type addrType)
{
// error log
return;
}
/**
* @brief check host type exists or not
* @param addrType: address type
* @param type: host type
* @return true/false
*/
bool service_discovery_interface::hasHostType(DwAddrType::type addrType, HostType::type type)
{
return (getHostType(addrType) == type);
}
/**
* @brief operator == for service_discovery_interface
* @param data: reference for common data
* @return true if equal, otherwise return false
*/
bool service_discovery_interface::operator==(service_discovery_interface &data)
{
bool flag = ((this->svcLabel == data.svcLabel) &&
(this->dataType == data.dataType));
return flag;
}
/**
* @brief operator < for service_discovery_interface
* @param data: reference for common data
* @return true if *this < data, otherwise return false
*/
bool service_discovery_interface::operator<(service_discovery_interface &data)
{
// compare based on priority: dataType > svcLabel
if (this->dataType < data.dataType)
{
return true;
}
else if (this->dataType > data.dataType)
{
return false;
}
if (this->svcLabel < data.svcLabel)
{
return true;
}
else if (this->svcLabel > data.svcLabel)
{
return false;
}
return false;
}
/**
* @brief Compare service_discovery_interface
* @param lhs: pointer to common data
* @param rhs: pointer to common data
* @return true if *lhs < *rhs, otherwise return false
*/
bool service_discovery_interface::less(service_discovery_interface::ptr_t lhs, service_discovery_interface::ptr_t rhs)
{
if (!lhs || !rhs)
{
return false;
}
return (*lhs < *rhs);
}
/**
* @brief Dump service_discovery_interface
* @param prefix: prefix used when dumping data
* @param onScreen: indicating whether dump log on stdout
* @return void
*/
void service_discovery_interface::dump(std::string prefix, bool onScreen)
{
std::ostringstream os;
os << prefix << "Dump service_discovery_interface(" << std::hex << this << ") ..." << std::endl;
prefix += "\t";
os << prefix << "dataType: " << dataType << ", svcLabel: " << svcLabel << std::endl;
if (onScreen)
{
printf("%s\n", os.str().c_str());
}
else
{
}
return;
} | 23.621795 | 119 | 0.674084 | maxcong001 |
fc026dc716d1e177c74155115630b2ef0af242cf | 1,403 | tpp | C++ | uppsrc/Core/src.tpp/Exc$en-us.tpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | uppsrc/Core/src.tpp/Exc$en-us.tpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 1 | 2021-04-06T21:57:39.000Z | 2021-04-06T21:57:39.000Z | uppsrc/Core/src.tpp/Exc$en-us.tpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 3 | 2017-08-26T12:06:05.000Z | 2019-11-22T16:57:47.000Z | topic "Miscellaneous";
[2 $$0,0#00000000000000000000000000000000:Default]
[i448;a25;kKO9;2 $$1,0#37138531426314131252341829483380:class]
[l288;2 $$2,0#27521748481378242620020725143825:desc]
[0 $$3,0#96390100711032703541132217272105:end]
[H6;0 $$4,0#05600065144404261032431302351956:begin]
[i448;a25;kKO9;2 $$5,0#37138531426314131252341829483370:item]
[l288;a4;*@5;1 $$6,6#70004532496200323422659154056402:requirement]
[l288;i1121;b17;O9;~~~.1408;2 $$7,0#10431211400427159095818037425705:param]
[i448;b42;O9;2 $$8,8#61672508125594000341940100500538:tparam]
[b42;2 $$9,9#13035079074754324216151401829390:normal]
[{_}
[ {{10000@(113.42.0) [s0;%% [*@7;4 Exc]]}}&]
[s3;%% &]
[s1;:Exc`:`:class: [@(0.0.255)3 class][3 _][*3 Exc][3 _:_][@(0.0.255)3 public][3 _][*@3;3 String]&]
[s9;%% This is the preferred root class of U`+`+ exception. It is
basically a String. The idea is that all kinds of exception can
be either managed by specific handlers, or simple Exc handler
can be used, displaying textual information to the user.&]
[s3;%% &]
[s0;%% &]
[ {{10000F(128)G(128)@1 [s0;%% [* Constructor Detail]]}}&]
[s0; &]
[s5;:Exc`:`:Exc`(`): [* Exc]()&]
[s2;%% Default constructor.&]
[s3; &]
[s4; &]
[s5;:Exc`:`:Exc`(const String`&`): [* Exc]([@(0.0.255) const]_[_^String^ String][@(0.0.255) `&
]_[*@3 desc])&]
[s2;%% Constructor, error described as [%-*C@3 desc].&]
[s3; &]
[s0; ] | 43.84375 | 100 | 0.659301 | dreamsxin |
fc02c2816238aa40862f33daeab3d42036d3192e | 1,966 | hpp | C++ | src/src/lib/geneial/core/population/builder/PermutationChromosomeFactory.hpp | geneial/geneial | 5e525c32b7c1e1e88788644e448e9234c93b55e2 | [
"MIT"
] | 5 | 2015-08-25T15:40:09.000Z | 2020-03-15T19:33:22.000Z | src/src/lib/geneial/core/population/builder/PermutationChromosomeFactory.hpp | geneial/geneial | 5e525c32b7c1e1e88788644e448e9234c93b55e2 | [
"MIT"
] | null | null | null | src/src/lib/geneial/core/population/builder/PermutationChromosomeFactory.hpp | geneial/geneial | 5e525c32b7c1e1e88788644e448e9234c93b55e2 | [
"MIT"
] | 3 | 2019-01-24T13:14:51.000Z | 2022-01-03T07:30:20.000Z | #pragma once
#include <geneial/core/population/builder/PermutationChromosomeFactory.h>
#include <geneial/utility/Random.h>
#include <algorithm>
#include <cassert>
geneial_private_namespace(geneial)
{
geneial_private_namespace(population)
{
geneial_private_namespace(chromosome)
{
using ::geneial::population::chromosome::PermutationBuilderSettings;
using ::geneial::population::chromosome::PermutationChromosomeFactory;
geneial_export_namespace
{
template<typename VALUE_TYPE, typename FITNESS_TYPE>
typename BaseChromosome<FITNESS_TYPE>::ptr PermutationChromosomeFactory<VALUE_TYPE, FITNESS_TYPE>::doCreateChromosome(
typename BaseChromosomeFactory<FITNESS_TYPE>::PopulateBehavior populateValues)
{
using namespace geneial::utility;
auto new_chromosome = this->allocateNewChromsome();
if (populateValues == BaseChromosomeFactory<FITNESS_TYPE>::CREATE_VALUES)
{
assert(_settings.getNum() > 1);
const unsigned int amount = _settings.getNum();
for(unsigned int i = 0; i < amount; i++)
{
const VALUE_TYPE val = i;
new_chromosome->getContainer()[i] = val;
}
const unsigned rounds = Random::generate<unsigned int>(_settings.getPermutationRoundsMin(),_settings.getPermutationRoundsMax());
for(unsigned int i = 0; i<rounds;i++)
{
unsigned int swapA = Random::generate<unsigned int>(0,_settings.getNum()-1);
unsigned int swapB;
do{
swapB = Random::generate<unsigned int>(0,_settings.getNum()-1);
}while(swapA == swapB);
auto iterBegin = new_chromosome->getContainer().begin();
iter_swap(iterBegin + swapA, iterBegin + swapB);
}
assert(new_chromosome->getSize() == _settings.getNum());
}
return std::move(new_chromosome);
}
} /* geneial_export_namespace */
} /* private namespace chromosome */
} /* private namespace population */
} /* private namespace geneial */
| 31.206349 | 136 | 0.702442 | geneial |
fc058332b8302cf04188b381800a978a276c22d1 | 1,589 | cpp | C++ | algorithms/cpp/source/candy.cpp | straywarrior/leetcode-solutions | d94749daf7da895b83c6834cb3b1e2a0b8a52ccc | [
"MIT"
] | null | null | null | algorithms/cpp/source/candy.cpp | straywarrior/leetcode-solutions | d94749daf7da895b83c6834cb3b1e2a0b8a52ccc | [
"MIT"
] | null | null | null | algorithms/cpp/source/candy.cpp | straywarrior/leetcode-solutions | d94749daf7da895b83c6834cb3b1e2a0b8a52ccc | [
"MIT"
] | null | null | null | /*
* candy.cpp
* Copyright (C) 2018 StrayWarrior <i@straywarrior.com>
*
* Distributed under terms of the MIT license.
*/
#include "common.hpp"
#define CATCH_CONFIG_MAIN
#include "catch/catch.hpp"
using namespace std;
class Candy {
public:
int candy(vector<int> & ratings) {
return this->solve_trivial(ratings);
}
int solve_trivial(vector<int> & ratings) {
int m = ratings.size();
vector<int> candies(m, 1);
for (int i = 0; i < m - 1; ++i) {
if (ratings[i + 1] > ratings[i])
candies[i + 1] = candies[i] + 1;
}
// Here I use max operation to make sure the left neighbor get enough
// candies. After the first pass, children with higher scores than
// their right neighbors should have at least same number of candies as
// their neighbors. It's obvious, so why do I type so many words here?
for (int i = m - 1; i > 0; --i) {
if (ratings[i - 1] > ratings[i])
candies[i - 1] = std::max(candies[i - 1], candies[i] + 1);
}
int sum = 0;
for (auto c : candies)
sum += c;
return sum;
}
};
TEST_CASE( "test corectness", "leetcode.cpp.candy" ) {
Candy sol;
using TestCase = std::tuple< vector<int>, int >;
std::vector<TestCase> test_cases {
TestCase{ {1, 2}, 3 },
TestCase{ {1, 2, 3}, 6 },
TestCase{ {1, 4, 2, 3}, 6 },
TestCase{ {}, 0 },
};
for (auto & t : test_cases) {
CHECK(sol.candy(std::get<0>(t)) == std::get<1>(t));
}
}
| 27.877193 | 79 | 0.539962 | straywarrior |
fc07d725ea4a87c2f9c89ccb953edf35a0374002 | 5,676 | cpp | C++ | SalesforceSDK/src/core/SFGenericTask.cpp | blackberry/BlackBerry10SDK-for-SalesforceMobile | 6d925c7efbd731e098d23deb05c1699b9fae5e9b | [
"CC-BY-3.0"
] | null | null | null | SalesforceSDK/src/core/SFGenericTask.cpp | blackberry/BlackBerry10SDK-for-SalesforceMobile | 6d925c7efbd731e098d23deb05c1699b9fae5e9b | [
"CC-BY-3.0"
] | null | null | null | SalesforceSDK/src/core/SFGenericTask.cpp | blackberry/BlackBerry10SDK-for-SalesforceMobile | 6d925c7efbd731e098d23deb05c1699b9fae5e9b | [
"CC-BY-3.0"
] | 2 | 2015-03-19T10:51:48.000Z | 2019-02-15T19:12:06.000Z | /*
* Copyright 2013 BlackBerry Limited.
*
* 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.
*
* SFGenericTask.cpp
*
* Created on: Mar 6, 2013
* Author: Livan Yi Du
*/
#include "SFGenericTask.h"
#include <QEventLoop>
#include <QThreadPool>
#include <QMutexLocker>
#include <QMetaObject>
#include <QEventLoop>
#include <QThread>
#include <QMutex>
#include "SFResult.h"
namespace sf {
SFGenericTask::SFGenericTask(const bool & cancellable) : QObject(), QRunnable() {
mStatus = TaskStatusNotStarted;
mResult = NULL;
mEventLoop = NULL;
mExecutionThread = NULL;
mMutex = cancellable ? this->mutex() : NULL;
mCancellable = cancellable;
mCancelled = false;
mAutoRetry = false;
mRetryCount = 0; //no retry
this->setAutoDelete(false);
}
SFGenericTask::~SFGenericTask() {
delete mEventLoop;
delete mMutex;
}
/*
* Public
*/
void SFGenericTask::startTaskAsync(QObject* receiver, const char * slot) {
this->prepareToStart(receiver, slot);
QThreadPool::globalInstance()->start(this);
}
void SFGenericTask::setCancellable(const bool & cancellable) {
if (cancellable) {
//prepare mutex lock
this->mutex();
}
this->mCancellable = cancellable;
}
void SFGenericTask::run() {
mStatus = TaskStatusRunning;
mExecutionThread = QThread::currentThread();
this->prepare();
try {
mStatus = this->execute();
} catch(std::exception &e) {
mStatus = TaskStatusError;
sfWarning() << "[SFGenericTask] Exception:" << e.what();
this->prepareQObjectForDisposal(mResult);
mResult = SFResult::create();
mResult->mStatus = SFResult::TaskResultError;
mResult->mCode = -1;
mResult->mMessage = QString(e.what());
} catch (...) {
mStatus = TaskStatusError;
sfWarning() << "[SFGenericTask] Unknown Error";
this->prepareQObjectForDisposal(mResult);
mResult = SFResult::create();
mResult->mStatus = SFResult::TaskResultError;
mResult->mCode = -1;
mResult->mMessage = QString("Fatal Error");
}
this->cleanup();
}
void SFGenericTask::cancel() {
//garuantee cancel is called from owner thread
if (QThread::currentThread() != this->thread()) {
QMetaObject::invokeMethod(this, "cancel");
return;
}
//this one is typically called from thread other than the one this runnable belongs to (through meta obj invokation or signal)
if (!mCancellable) {
return;
}
sfWarning() << "Canceling task:"<< this;
//set flag, cleanup() will check for it
this->setCancelled(true);
}
/*
* Protected
*/
void SFGenericTask::prepareToStart(QObject* receiver, const char * slot) {
// we clear the parent because we want to keep the option to move the task to another thread
// we shouldn't set parent anyway if the runnable have "auto delete" on
this->setParent(0);
this->setAutoDelete(false);
if (this->mResult) {
this->mResult->deleteLater();
this->mResult = NULL;
}
if (receiver && slot) {
connect(this, SIGNAL(taskResultReady(sf::SFResult*)), receiver, slot);
}
}
QEventLoop* SFGenericTask::eventLoop() {
if (!mEventLoop) {
//we cannot assign "this" as parent because runnable is not created in same thread
//so, remember to delete it!
mEventLoop = new QEventLoop(0);
}
return mEventLoop;
}
QMutex* SFGenericTask::mutex() {
if (!mMutex) {
mMutex = new QMutex();
}
return mMutex;
}
void SFGenericTask::setCancelled(const bool &cancelled) {
if (!mCancellable) {
return;
}
QMutexLocker locker(mutex());
mCancelled = cancelled;
}
bool SFGenericTask::isCancelled() {
if (!mCancellable) {
return false;
}
QMutexLocker locker(mutex());
return mCancelled;
}
void SFGenericTask::prepare() {
emit taskPreExecution(this);
}
void SFGenericTask::cleanup() {
this->prepareQObjectForDisposal(mResult);
if (this->isCancelled()) {
mResult = SFResult::createCancelResult();
mStatus = TaskStatusCancelled;
} else if (!mResult) {
mResult = SFResult::createErrorResult(SFResultCode::SFErrorGeneric, "No result.");
mStatus = TaskStatusError;
}
mResult->mTags = mTags;
if (mStatus != TaskStatusWillRetry || !this->retry()) {
//no need to retry or can't retry, finish up
emit taskResultReady(mResult);
emit taskFinished(this);
this->deleteLater();
}
}
bool SFGenericTask::retry() {
if (mRetryCount-- <= 0) {
mStatus = TaskStatusError;
return false;
}
emit taskShouldRetry(this, mResult);
if (!mAutoRetry) {
//we've done everything we could, now it's up to "taskShouldRetry" handlers to manually restart the task
return true;
}
//up to this point, we assume the task has prepared itself for re-execution
QMetaObject::invokeMethod(this, "startTaskAsync", Qt::QueuedConnection);
emit taskDidAutoRetry(this);
return true;
}
void SFGenericTask::prepareQObjectForDisposal(QObject* object) {
if (!object) {
return;
}
if (object->thread() != QThread::currentThread()) {
sfWarning() << "[SFGenericTask] Failed to dispose object:" << object << ". Potential memory issue. Deleting now...";
object->deleteLater();
return;
}
QThread *creatorThread = this->thread();
//try to push result to creators thread
if (object->thread() != creatorThread) {
object->moveToThread(creatorThread);
}
if (object->thread() == creatorThread) {
object->setParent(this);
}
}
}/* namespace */
| 24.571429 | 127 | 0.708245 | blackberry |
fc093012ab6bb16f57f98c62993fecf93857f662 | 3,664 | hxx | C++ | src/private/httpparser.hxx | Targoman/qhttp | 2351076d2e23c8820e6e94d064de689d99edb22f | [
"MIT"
] | 2 | 2020-07-03T06:34:15.000Z | 2020-07-03T19:19:09.000Z | src/private/httpparser.hxx | Targoman/QHttp | 55df46aab918a1f923e8b1b79674cf9f82490bc5 | [
"MIT"
] | null | null | null | src/private/httpparser.hxx | Targoman/QHttp | 55df46aab918a1f923e8b1b79674cf9f82490bc5 | [
"MIT"
] | null | null | null | /** @file httpparser.hxx
*
* @copyright (C) 2016
* @date 2016.05.26
* @version 1.0.0
* @author amir zamani <azadkuh@live.com>
*
*/
#ifndef QHTTP_HTTPPARSER_HXX
#define QHTTP_HTTPPARSER_HXX
#include "qhttpbase.hpp"
///////////////////////////////////////////////////////////////////////////////
namespace qhttp {
namespace details {
///////////////////////////////////////////////////////////////////////////////
/// base HttpParser based on joyent http_parser
template<class TImpl>
class HttpParser
{
public:
explicit HttpParser(http_parser_type type) {
// create http_parser object
iparser.data = static_cast<TImpl*>(this);
http_parser_init(&iparser, type);
memset(&iparserSettings, 0, sizeof(http_parser_settings));
iparserSettings.on_message_begin = onMessageBegin;
iparserSettings.on_url = onUrl;
iparserSettings.on_status = onStatus;
iparserSettings.on_header_field = onHeaderField;
iparserSettings.on_header_value = onHeaderValue;
iparserSettings.on_headers_complete = onHeadersComplete;
iparserSettings.on_body = onBody;
iparserSettings.on_message_complete = onMessageComplete;
}
size_t parse(const char* data, size_t length) {
return http_parser_execute(&iparser,
&iparserSettings,
data,
length);
}
public: // callback functions for http_parser_settings
static int onMessageBegin(http_parser* p) {
return me(p)->messageBegin(p);
}
static int onUrl(http_parser* p, const char* at, size_t length) {
return me(p)->url(p, at, length);
}
static int onStatus(http_parser* p, const char* at, size_t length) {
return me(p)->status(p, at, length);
}
static int onHeaderField(http_parser* p, const char* at, size_t length) {
return me(p)->headerField(p, at, length);
}
static int onHeaderValue(http_parser* p, const char* at, size_t length) {
return me(p)->headerValue(p, at, length);
}
static int onHeadersComplete(http_parser* p) {
return me(p)->headersComplete(p);
}
static int onBody(http_parser* p, const char* at, size_t length) {
return me(p)->body(p, at, length);
}
static int onMessageComplete(http_parser* p) {
return me(p)->messageComplete(p);
}
protected:
// The ones we are reading in from the parser
QByteArray itempHeaderField;
QByteArray itempHeaderValue;
// if connection has a timeout, these fields will be used
quint32 itimeOut = 0;
QBasicTimer itimer;
// uniform socket object
QScopedPointer<QHttpAbstractSocket> isocket;
// if connection should persist
bool ikeepAlive = false;
// joyent http_parser
http_parser iparser;
http_parser_settings iparserSettings;
static auto me(http_parser* p) {
return static_cast<TImpl*>(p->data);
}
}; //
/// basic request parser (server)
template<class TImpl>
struct HttpRequestParser : public HttpParser<TImpl> {
HttpRequestParser() : HttpParser<TImpl>(HTTP_REQUEST) {}
};
/// basic response parser (clinet)
template<class TImpl>
struct HttpResponseParser : public HttpParser<TImpl> {
HttpResponseParser() : HttpParser<TImpl>(HTTP_RESPONSE) {}
};
///////////////////////////////////////////////////////////////////////////////
} // namespace details
} // namespace qhttp
///////////////////////////////////////////////////////////////////////////////
#endif // QHTTP_HTTPPARSER_HXX
| 30.533333 | 79 | 0.593341 | Targoman |
fc0b34e792d9a186d4cb20c5baf0ed4ef3de16f7 | 7,955 | hh | C++ | src/include/SchemaItem.hh | websurfer5/json-schema-enforcer | 99211a602b1c8177d9f9e67cd7773015f74a4080 | [
"Apache-2.0"
] | null | null | null | src/include/SchemaItem.hh | websurfer5/json-schema-enforcer | 99211a602b1c8177d9f9e67cd7773015f74a4080 | [
"Apache-2.0"
] | null | null | null | src/include/SchemaItem.hh | websurfer5/json-schema-enforcer | 99211a602b1c8177d9f9e67cd7773015f74a4080 | [
"Apache-2.0"
] | null | null | null | // SchemaItem.hh
//
// Copyright 2018 Jeffrey Kintscher <websurfer@surf2c.net>
//
// 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 __JSONSCHEMAENFORCER_SCHEMA_ITEM_HH
#define __JSONSCHEMAENFORCER_SCHEMA_ITEM_HH
namespace jsonschemaenforcer
{
class ParsedItemData;
}
#include "config.h"
#include "FormatType.hh"
#include "ItemType.hh"
#include "JsonItem.hh"
#include "stddefs.hh"
#include <iostream>
#include <list>
#include <string>
namespace jsonschemaenforcer
{
class SchemaData;
class SchemaItem;
typedef std::list<SchemaItem> SchemaItemList;
class SchemaItem
{
public:
SchemaItem();
SchemaItem(const SchemaItem& sitem);
~SchemaItem();
SchemaItem& operator =(const SchemaItem& sitem);
bool operator ==(const SchemaItem& sitem) const;
inline bool operator !=(const SchemaItem& sitem) const { return !(this->operator ==(sitem)); };
inline void add_item_type(const ItemType& _type) { type_set.insert(_type); };
void clear();
bool define_item(const std::string& _key, const ParsedItemData& idata);
bool define_dependency_array(const std::string& _key, const StdStringList& s_list);
bool empty() const;
inline std::string emit_parser(SchemaData& sd,
const std::string& start_state) const
{
return emit_parser(sd, start_state, "");
};
std::string emit_integer_parser_rules(SchemaData& sd,
const std::string& start_state,
const std::string& key_validation_state) const;
std::string emit_number_parser_rules(SchemaData& sd,
const std::string& start_state,
const std::string& key_validation_state) const;
std::string emit_string_parser_rules(SchemaData& sd,
const std::string& start_state,
const std::string& key_validation_state) const;
std::string emit_object_parser_rules(SchemaData& sd,
const std::string& start_state,
const std::string& key_validation_state) const;
std::string emit_array_parser_rules(SchemaData& sd,
const std::string& start_state,
const std::string& key_validation_state) const;
// std::string emit_boolean_parser_rules(SchemaData& sd, const std::string& start_state) const;
// std::string emit_null_parser_rules(SchemaData& sd, const std::string& start_state) const;
# define DEF_VAR(vtype, vname, value, test_value, flag_name, flag_value, func_set, func_get) \
void func_set(vtype _##vname); \
inline vtype func_get() const { return vname; }; \
inline bool has_##vname() const { return flag_name; };
# define DEF_OBJ(objtype, vname, initfunc, emptyfunc, test_value, flag_name, flag_value, func_set, func_get) \
void func_set(const objtype& _##vname); \
inline const objtype& func_get() const { return vname; }; \
inline bool has_##vname() const { return flag_name; };
# define DEF_OBJ_PTR(objtype, vname, initfunc, emptyfunc, test_value, flag_name, flag_value, func_set, func_get) \
void func_set(const objtype& obj); \
const objtype& func_get() const; \
inline bool has_##vname() const { return flag_name; };
# define DEF_FLAG(fname, value, func_set, func_clear) \
inline void func_set() { fname = true; }; \
inline void func_set(bool b) { fname = b; }; \
inline void func_clear() { fname = false; }; \
inline bool is_##fname() const { return fname; };
# include "SchemaItem-vars.hh"
# undef DEF_VAR
# undef DEF_OBJ
# undef DEF_OBJ_PTR
# undef DEF_FLAG
//
// has item type functions
//
# define DEF_FLAG(fname, str_name) \
inline bool has_##fname##_type() const { return (type_set.find(ItemType::type_##fname) != type_set.end()); };
# include "ItemType-vars.hh"
# undef DEF_FLAG
protected:
//
// The set_data templated function ensures that a real
// only gets assigned to an integer variable if the real
// value is an integer.
//
template <class T, class U>
bool set_data(bool& b_var1, bool b_var2, T& var1, const U& var2,
const std::string& prop_type, const std::string& var_name)
{
bool error = false;
if (b_var2)
{
if (var2 != (T) var2)
{
b_var1 = false;
error = true;
std::cerr << __FUNCTION__ << "(): \"" << var_name << "\" property value is not "
<< prop_type << ": " << var2 << std::endl;
}
else
{
b_var1 = true;
var1 = (T) var2;
}
}
else
b_var1 = false;
return !error;
}
std::string emit_parser(SchemaData& sd,
const std::string& start_state,
const std::string& key_validation_state) const;
void emit_array_rule(SchemaData& sd,
std::string& rule_str,
bool& first,
const SchemaItem& item,
const std::string& array_state,
const std::string& item_tag) const;
void emit_default_rules(SchemaData& sd) const;
void emit_object_rule(SchemaData& sd,
std::string& rule_str,
bool& first,
const SchemaItem& item,
const std::string& object_state,
const std::string& prop_names_state) const;
bool is_vanilla() const;
bool set_array_data(const ParsedItemData& idata);
bool set_integer_data(const ParsedItemData& idata);
bool set_number_data(const ParsedItemData& idata);
bool set_object_data(const ParsedItemData& idata);
bool set_string_data(const ParsedItemData& idata);
public:
# define DEF_VAR(vtype, vname, value, test_value, flag_name, flag_value, func_set, func_get) \
vtype vname; \
bool flag_name;
# define DEF_OBJ(objtype, vname, initfunc, emptyfunc, test_value, flag_name, flag_value, func_set, func_get) \
objtype vname; \
bool flag_name;
# define DEF_OBJ_PTR(objtype, vname, initfunc, emptyfunc, test_value, flag_name, flag_value, func_set, func_get) \
objtype *vname; \
bool flag_name;
# define DEF_FLAG(fname, value, func_set, func_clear) \
bool fname;
# include "SchemaItem-vars.hh"
# undef DEF_VAR
# undef DEF_OBJ
# undef DEF_OBJ_PTR
# undef DEF_FLAG
};
}
#endif // __JSONSCHEMAENFORCER_SCHEMA_ITEM_HH
| 39.974874 | 120 | 0.565933 | websurfer5 |
fc0d67ff3f419586734faf3876b2aa69795dcd28 | 567 | cpp | C++ | assignments/a1/archive/t.cpp | suryaavala/advancedcpp | 84c1847bf42ff744f99b4c0f94b77cfa71ca00d8 | [
"MIT"
] | null | null | null | assignments/a1/archive/t.cpp | suryaavala/advancedcpp | 84c1847bf42ff744f99b4c0f94b77cfa71ca00d8 | [
"MIT"
] | null | null | null | assignments/a1/archive/t.cpp | suryaavala/advancedcpp | 84c1847bf42ff744f99b4c0f94b77cfa71ca00d8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <iomanip>
#include <string>
#include <sstream>
int main(int argc, char const *argv[]) {
std::string c = "1.1";
int a = std::stoi(c);
double b = std::stod(c);
std::cout << "a = " << a <<", b = " << b << ", c = " << c << " a/b = " <<a/b<<'\n';
std::stringstream stream;
//stream << std::fixed << std::setprecision(3) << a;
//std::string x = stream.str();
stream << std::fixed << std::setprecision(3) << b;
std::string y = stream.str();
std::cout << "x = " << " y = " << y << '\n';
return 0;
}
| 21.807692 | 85 | 0.514991 | suryaavala |
fc12f1bb40762427e02bff17cf8ae9659a485933 | 4,207 | cc | C++ | src/api/render/texture.cc | izzyaxel/Loft | 809b4e3df2c2b08092c6b3a94073f4509240b4f2 | [
"BSD-3-Clause"
] | null | null | null | src/api/render/texture.cc | izzyaxel/Loft | 809b4e3df2c2b08092c6b3a94073f4509240b4f2 | [
"BSD-3-Clause"
] | null | null | null | src/api/render/texture.cc | izzyaxel/Loft | 809b4e3df2c2b08092c6b3a94073f4509240b4f2 | [
"BSD-3-Clause"
] | null | null | null | #include "texture.hh"
#include <glad/glad.h>
Texture::Texture(uint32_t width, uint32_t height, ColorFormat colorFormat, InterpMode mode, bool sRGB)
{
this->fmt = colorFormat;
this->width = width;
this->height = height;
glCreateTextures(GL_TEXTURE_2D, 1, &this->handle);
int32_t f = 0;
if(colorFormat == ColorFormat::RGB) //It's more efficient to use an extra 8 bits of VRAM per pixel
{
if(sRGB) f = GL_SRGB8;
else f = GL_RGB8;
}
else if(colorFormat == ColorFormat::RGBA)
{
if(sRGB) f = GL_SRGB8_ALPHA8;
else f = GL_RGBA8;
}
else if(colorFormat == ColorFormat::GREY)
{
f = GL_R8;
}
glTextureStorage2D(this->handle, 1, f, width, height);
this->clear();
this->setInterpolation(mode, mode);
this->setAnisotropyLevel(1);
}
Texture::Texture(uint8_t *data, uint32_t width, uint32_t height, ColorFormat colorFormat, InterpMode mode, bool sRGB)
{
this->fmt = colorFormat;
this->width = width;
this->height = height;
int32_t f = 0, cf = 0;
if(colorFormat == ColorFormat::RGB) //TODO It's more efficient to use an extra 8 bits of VRAM per pixel
{
if(sRGB) f = GL_SRGB8;
else f = GL_RGB8;
cf = GL_RGB;
}
else if(colorFormat == ColorFormat::RGBA)
{
if(sRGB) f = GL_SRGB8_ALPHA8;
else f = GL_RGBA8;
cf = GL_RGBA;
}
else if(colorFormat == ColorFormat::GREY)
{
f = GL_R8;
cf = GL_RED;
}
glCreateTextures(GL_TEXTURE_2D, 1, &this->handle);
glTextureStorage2D(this->handle, 1, f, width, height);
glTextureSubImage2D(this->handle, 0, 0, 0, this->width, this->height, cf, GL_UNSIGNED_BYTE, data);
this->setInterpolation(mode, mode);
this->setAnisotropyLevel(1);
}
Texture::Texture(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha, bool sRGB)
{
this->fmt = ColorFormat::RGBA;
this->width = 1;
this->height = 1;
uint8_t **data = new uint8_t *;
data[0] = new uint8_t[4];
data[0][0] = red;
data[0][1] = green;
data[0][2] = blue;
data[0][3] = alpha;
glCreateTextures(GL_TEXTURE_2D, 1, &this->handle);
glTextureStorage2D(this->handle, 1, sRGB ? GL_SRGB8_ALPHA8 : GL_RGBA8, this->width, this->height);
glTextureSubImage2D(this->handle, 0, 0, 0, this->width, 1, GL_RGBA, GL_UNSIGNED_BYTE, data[0]);
this->setInterpolation(InterpMode::Linear, InterpMode::Linear);
this->setAnisotropyLevel(1);
}
Texture::~Texture()
{
glDeleteTextures(1, &this->handle);
}
Texture::Texture(Texture &other)
{
this->handle = other.handle;
other.handle = 0;
}
Texture& Texture::operator=(Texture other)
{
this->handle = other.handle;
other.handle = 0;
return *this;
}
Texture::Texture(Texture &&other)
{
this->handle = other.handle;
other.handle = 0;
}
Texture& Texture::operator=(Texture &&other)
{
this->handle = other.handle;
other.handle = 0;
return *this;
}
void Texture::use(uint32_t target)
{
int32_t curTex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &curTex);
glBindTextureUnit(target, this->handle);
}
void Texture::setInterpolation(InterpMode min, InterpMode mag)
{
GLenum glMin = GL_NEAREST, glMag = GL_NEAREST;
switch(min)
{
case InterpMode::Nearest: glMin = GL_NEAREST; break;
case InterpMode::Linear: glMin = GL_LINEAR; break;
default: break;
}
switch(mag)
{
case InterpMode::Nearest: glMag = GL_NEAREST; break;
case InterpMode::Linear: glMag = GL_LINEAR; break;
default: break;
}
glTextureParameteri(this->handle, GL_TEXTURE_MIN_FILTER, glMin);
glTextureParameteri(this->handle, GL_TEXTURE_MAG_FILTER, glMag);
}
void Texture::setAnisotropyLevel(uint32_t level)
{
glTextureParameterf(this->handle, GL_TEXTURE_MAX_ANISOTROPY, level);
}
void Texture::subImage(uint8_t *data, uint32_t w, uint32_t h, uint32_t xPos, uint32_t yPos, ColorFormat format)
{
int32_t f = 0;
switch(format)
{
case ColorFormat::RGB:
f = GL_RGB;
break;
case ColorFormat::RGBA:
f = GL_RGBA;
break;
case ColorFormat::GREY:
f = GL_RED;
break;
}
glTextureSubImage2D(this->handle, 0, xPos, yPos, w, h, f, GL_UNSIGNED_BYTE, data);
}
void Texture::clear()
{
int32_t f = 0;
switch(this->fmt)
{
case ColorFormat::RGB:
f = GL_RGB;
break;
case ColorFormat::RGBA:
f = GL_RGBA;
break;
case ColorFormat::GREY:
f = GL_RED;
break;
}
glClearTexImage(this->handle, 0, f, GL_UNSIGNED_BYTE, "\0\0\0\0");
}
| 23.634831 | 117 | 0.697884 | izzyaxel |
fc18060403c801ab5107db674f98a7d6ab7442d9 | 2,450 | hh | C++ | src/gui_component.hh | lighttransport/nnview | 4cba0957a5e9354c792dac12196cc64b0f750c43 | [
"MIT"
] | 74 | 2019-07-11T17:15:40.000Z | 2022-02-20T18:02:17.000Z | src/gui_component.hh | lighttransport/nnview | 4cba0957a5e9354c792dac12196cc64b0f750c43 | [
"MIT"
] | 2 | 2019-07-24T11:55:52.000Z | 2019-07-24T11:59:23.000Z | src/gui_component.hh | lighttransport/nnview | 4cba0957a5e9354c792dac12196cc64b0f750c43 | [
"MIT"
] | 10 | 2019-07-27T23:34:24.000Z | 2021-12-29T05:45:43.000Z | #ifndef NNVIEW_GUI_COMPONENT_HH_
#define NNVIEW_GUI_COMPONENT_HH_
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#endif
#include "imgui_node_editor.h"
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#include "datatypes.h"
#include <string>
#include <vector>
#include <map>
namespace ed = ax::NodeEditor;
namespace nnview {
struct ImNode;
enum class PinType {
Flow,
Bool,
Int,
Float,
String,
Object,
Function,
Delegate,
};
enum class PinKind { Output, Input };
struct Link {
ed::LinkId ID;
ed::PinId StartPinID;
ed::PinId EndPinID;
ImColor Color;
Link(ed::LinkId id, ed::PinId startPinId, ed::PinId endPinId)
: ID(id),
StartPinID(startPinId),
EndPinID(endPinId),
Color(255, 255, 255) {}
};
struct Pin {
ed::PinId ID;
ImNode *ImNode;
std::string Name;
PinType Type;
PinKind Kind;
Pin(ed::PinId id, const std::string name, PinType type)
: ID(id), ImNode(nullptr), Name(name), Type(type), Kind(PinKind::Input) {}
};
struct ImNode {
// For imgui-node-editor
ed::NodeId id;
std::string name;
std::vector<Pin> inputs;
std::vector<Pin> outputs;
ImColor color;
ImVec2 size;
int tensor_id = -1; // Index to nnview::Graph::tensors
ImNode(ed::NodeId _id, const std::string _name,
ImColor _color = ImColor(255, 255, 255))
: id(_id), name(_name), color(_color), size(0, 0) {}
};
class GUIContext {
public:
int _active_tensor_idx = -1; // index to nnview::Graph::tensors
nnview::Graph _graph;
// Node and Link(connection) information using imgui-node-editor
std::vector<ImNode> _imnodes;
std::vector<Link> _links;
std::map<int, int> _node_id_to_imnode_idx_map; // <NodeId, index to _imnodes>
// OpenGL texture id for displaying Tensor as Texture(Image)
std::vector<GLuint> _tensor_texture_ids;
GLuint _background_texture_id = 0;
ed::EditorContext *_editor_context = nullptr;
// Call `init` before calling any methods defined in `GUIContext`.
// `graph` variable must be set before calling `init`.
void init();
// Initialize and layout ImNodes from Graph.
// This function should be called after `init` and before calling ImNode
// drawing methods.
void init_imnode_graph();
void draw_imnodes();
// Draw Tensor in active section.
void draw_tensor();
void finalize();
};
} // namespace nnview
#endif // NNVIEW_GUI_COMPONENT_HH_
| 20.247934 | 80 | 0.68898 | lighttransport |
fc189b0e59158000429902dc22d56f8eff5d771f | 2,647 | hh | C++ | kernel/host/host-common/util/FDReceiver.hh | ManyThreads/mythos | 723a4b11e454a0c28e096755140c5e0eecf6a211 | [
"MIT"
] | 12 | 2016-10-06T14:02:17.000Z | 2021-09-12T06:14:30.000Z | kernel/host/host-common/util/FDReceiver.hh | ManyThreads/mythos | 723a4b11e454a0c28e096755140c5e0eecf6a211 | [
"MIT"
] | 110 | 2017-06-22T20:10:17.000Z | 2022-01-18T12:58:40.000Z | kernel/host/host-common/util/FDReceiver.hh | ManyThreads/mythos | 723a4b11e454a0c28e096755140c5e0eecf6a211 | [
"MIT"
] | 6 | 2016-12-09T08:30:08.000Z | 2021-12-10T19:05:04.000Z | /* -*- mode:C++; indent-tabs-mode:nil; -*- */
/* MIT License -- MyThOS: The Many-Threads Operating System
*
* 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.
*
* Copyright 2016 Randolf Rotta, Robert Kuban, and contributors, BTU Cottbus-Senftenberg
*/
#pragma once
#include <sys/socket.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/un.h>
class FDReceiver{
int sock;
struct sockaddr_un addr;
public:
FDReceiver()
: sock(-1)
{
}
~FDReceiver(){
disconnect();
}
bool disconnect(){
if(sock >= 0)
close(sock);
}
bool connectToSocket(const char *sockPath){
disconnect();
sock = socket(PF_LOCAL, SOCK_STREAM, 0);
if (sock == -1){
std::cerr << "error: unable to open socket" << std::endl;
return false;
}
addr.sun_family = AF_LOCAL;
strcpy(addr.sun_path, sockPath);
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1){
std::cerr << "error: connecting to domain socket failed" << std::endl;
disconnect();
return false;
}
return true;
}
int recvFD(){
if(sock < 0)
return (-1);
struct msghdr msg = {0};
char m_buffer[256];
struct iovec io = { .iov_base = m_buffer, .iov_len = sizeof(m_buffer) };
msg.msg_iov = &io;
msg.msg_iovlen = 1;
char c_buffer[256];
msg.msg_control = c_buffer;
msg.msg_controllen = sizeof(c_buffer);
int recvBytes = 0;
do{
recvBytes = recvmsg(sock, &msg, 0);
}while(recvBytes == 0);
if (recvBytes < 0)
return (-1);
struct cmsghdr * cmsg = CMSG_FIRSTHDR(&msg);
unsigned char * data = CMSG_DATA(cmsg);
int fd = *((int*) data);
return fd;
}
};
| 24.284404 | 88 | 0.68606 | ManyThreads |
fc1e1dedb28f9af089ad41fe9aa441064b3847a0 | 390 | cpp | C++ | src/top.chenqwwq/acwing/content/_52/_1.cpp | chenqwwq/_leetcode | a8055c53c9a68cedb1b57a56f98e83709448e4cb | [
"Apache-2.0"
] | null | null | null | src/top.chenqwwq/acwing/content/_52/_1.cpp | chenqwwq/_leetcode | a8055c53c9a68cedb1b57a56f98e83709448e4cb | [
"Apache-2.0"
] | null | null | null | src/top.chenqwwq/acwing/content/_52/_1.cpp | chenqwwq/_leetcode | a8055c53c9a68cedb1b57a56f98e83709448e4cb | [
"Apache-2.0"
] | null | null | null | //
// Created by chenqwwq on 2022/5/21.
//
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int num;
cin >> num;
int ans = 0, i = 1;
while (num) {
int cost = (i * (i + 1)) / 2;
if (num < cost) break;
num -= cost;
ans++;
i++;
}
printf("%d\n",ans);
return 0;
} | 15.6 | 37 | 0.471795 | chenqwwq |
fc2206d293c8a442af3c660c9af9e2f2af7492de | 282 | cpp | C++ | src/construction/Constraints.cpp | ShnitzelKiller/Reverse-Engineering-Carpentry | 585b5ff053c7e3bf286b663a584bc83687691bd6 | [
"MIT"
] | 3 | 2021-09-08T07:28:13.000Z | 2022-03-02T21:12:40.000Z | src/construction/Constraints.cpp | ShnitzelKiller/Reverse-Engineering-Carpentry | 585b5ff053c7e3bf286b663a584bc83687691bd6 | [
"MIT"
] | 1 | 2021-09-21T14:40:55.000Z | 2021-09-26T01:19:38.000Z | src/construction/Constraints.cpp | ShnitzelKiller/Reverse-Engineering-Carpentry | 585b5ff053c7e3bf286b663a584bc83687691bd6 | [
"MIT"
] | null | null | null | //
// Created by James Noeckel on 1/16/21.
//
#include "Constraints.h"
Edge2d ConnectionConstraint::getGuide() const {
Eigen::Vector2d dir = (edge.second - edge.first).normalized();
return {edge.first - dir * startGuideExtention, edge.second + dir * endGuideExtension};
}
| 25.636364 | 91 | 0.702128 | ShnitzelKiller |
fc23b7dac87be87ec34d96a2f549355e6b66018c | 3,965 | hpp | C++ | src/network.hpp | packetgenie/PacketGenie | cf09d39f53b9e6119c0ebe77134a032a082c81fd | [
"Apache-2.0"
] | 1 | 2015-08-20T12:31:02.000Z | 2015-08-20T12:31:02.000Z | src/network.hpp | packetgenie/PacketGenie | cf09d39f53b9e6119c0ebe77134a032a082c81fd | [
"Apache-2.0"
] | null | null | null | src/network.hpp | packetgenie/PacketGenie | cf09d39f53b9e6119c0ebe77134a032a082c81fd | [
"Apache-2.0"
] | 2 | 2015-08-19T14:47:32.000Z | 2019-08-30T15:58:07.000Z | // FILE: src/network.hpp Date Modified: March 17, 2015
// PacketGenie
// Copyright 2014 The Regents of the University of Michigan
// Dong-Hyeon Park, Ritesh Parikh, Valeria Bertacco
//
// PacketGenie is 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 _NETWORK_HPP_
#define _NETWORK_HPP_
#include <string>
#include <map>
#include <vector>
#include <fstream>
#include <list>
#include "node.hpp"
#include "node_configs.hpp"
#include "node_group.hpp"
#include "globals.hpp"
#include "misc.cpp"
#include "injection_process.hpp"
#include "traffic_pattern.hpp"
#include "packet_handler.hpp"
#include "packet.hpp"
#include "reply_job.hpp"
namespace tf_gen
{
enum NetworkType
{
NETWORK_MESH = 0,
//NETWORK_CROSSBAR,
};
enum NetworkStatus
{
NETWORK_STATUS_READY = 0,
NETWORK_STATUS_DONE,
NETWORK_STATUS_ACTIVE,
NETWORK_STATUS_WRAPPING_UP,
NETWORK_STATUS_PRE_INIT,
NETWORK_STATUS_ERROR,
};
class Network
{
public:
Network(NetworkType ntwk_type,
size_t dim_x, size_t dim_y);
virtual ~Network();
int set_inj_process(vector<string> *str_params);
int set_sender_nodes(vector<string> *idx_list);
int set_receiver_nodes(vector<string> *idx_list);
int set_traffic_pattern(vector<string> *str_params);
int set_packet_type_reply(vector<string> *str_params);
int set_packet_type(vector<string> *str_params);
int set_node_group(vector<string> *str_params);
int config_nodes(vector<string> *str_params);
#if _BOOKSIM
int config_BookSim(const char* const config_file);
#endif
int init_sim(size_t sim_end);
int step();
int get_traffic_records(string & printout);
int print_traffic_records();
NetworkStatus get_status();
int set_dram_bank_config(vector<string> *str_params);
int set_dram_timing_config(vector<string> *str_params);
bool no_outstanding_reply();
private:
int process_all_packet_queues();
void update_all_clocks();
int config_nodes_buffer(vector<string> *str_params,
list<Node *> &nodes);
int config_nodes_dram(vector<string> *str_params,
list<Node*> &nodes);
int config_nodes_clock(vector<string> *str_params,
list<Node*> &nodes);
#if _BOOKSIM
int config_nodes_default_port();
// int config_nodes_port(vector<string> *str_params,
// list<Node*> &nodes);
#endif
vector<Node> *node_list;
size_t m_ntwk_size;
NetworkType m_ntwk_type;
NetworkStatus m_status;
double base_inj_per_step; // Base injection rate, normalized
// by step size
size_t sim_end;
long next_event_time;
list<NodeGroup*> *group_list;
list<NodeGroup*> *active_groups;
list<NodeGroup*> *waiting_groups;
list<NodeGroup*> *finished_groups;
map<string, senders_t> *sender_map;
map<string, receivers_t> *receiver_map;
map<string, InjectionProcess *> *inj_proc_map;
map<string, TrafficPattern *> *traf_pattern_map;
map<string, Packet*> *packet_map;
map<string, ReplyPacketHandler *> *reply_handler_map;
map<string, Dram> *dram_map;
// Packet pool of all existing packets.
packet_pool_t global_packet_pool;
};
}
#endif
| 26.790541 | 76 | 0.669357 | packetgenie |
fc27a28e41f64ee3f80965bb901ed85a1e9059ce | 3,560 | cpp | C++ | src/Models/NeuronNetwork.cpp | SpiritSeeker/SpikeSim | c0ce896df15ed4bd46deb1aa61a3df637c0b6078 | [
"Apache-2.0"
] | null | null | null | src/Models/NeuronNetwork.cpp | SpiritSeeker/SpikeSim | c0ce896df15ed4bd46deb1aa61a3df637c0b6078 | [
"Apache-2.0"
] | null | null | null | src/Models/NeuronNetwork.cpp | SpiritSeeker/SpikeSim | c0ce896df15ed4bd46deb1aa61a3df637c0b6078 | [
"Apache-2.0"
] | null | null | null | #include "sspch.h"
#include "NeuronNetwork.h"
namespace SpikeSim {
NeuronNetwork::NeuronNetwork()
{}
void NeuronNetwork::OnUpdate(const std::vector<std::vector<double>>& inputCurrents, uint32_t nIter)
{
uint32_t inputCounter = 0;
for (int i = 0; i < m_Neurons.size(); i++)
{
if (m_InputNeuron[i])
m_Neurons[i]->OnUpdate(inputCurrents[inputCounter++]);
else
{
std::vector<double> inputCurrent(m_Neurons[i]->GetDendriteCount(), 0);
for (int j = 0; j < m_Connections.size(); j++)
{
if (m_Connections[j].PostNeuron == i)
inputCurrent[m_Connections[j].Dendrite] = m_Synapses[m_Connections[j].SynapseID]->GetOutputCurrent();
}
}
}
for (int i = 0; i < m_Synapses.size(); i++)
{
double inputVoltage = m_Neurons[m_Connections[i].PreNeuron]->GetTerminalVoltages()[m_Connections[i].Axon];
double outputVoltage = m_Neurons[m_Connections[i].PostNeuron]->GetInputVoltages()[m_Connections[i].Dendrite];
m_Synapses[i]->OnUpdate(inputVoltage, outputVoltage);
}
for (int i = 0; i < m_PlotInfo.size(); i++)
{
m_PlotData[i].X.push_back(nIter * m_Timestep);
if (m_PlotInfo[i].Type == 0)
{
switch (m_PlotInfo[i].Component)
{
case 0:
{
m_PlotData[i].Y.push_back(m_Neurons[m_PlotInfo[i].ID]->GetDendriteCurrent());
break;
}
case 1:
{
m_PlotData[i].Y.push_back(m_Neurons[m_PlotInfo[i].ID]->GetMembranePotential());
break;
}
case 2:
{
m_PlotData[i].Y.push_back(m_Neurons[m_PlotInfo[i].ID]->GetTerminalVoltages()[m_PlotInfo[i].Index]);
break;
}
}
}
else
m_PlotData[i].Y.push_back(m_Synapses[m_PlotInfo[i].ID]->GetOutputCurrent());
}
}
void NeuronNetwork::AddNeuron(uint32_t dendrites, uint32_t axons, bool input)
{
struct NeuronProps props;
props.n_Dendrites = dendrites;
props.n_Axons = axons;
auto neuron = Neuron::Create(props);
neuron->SetTimestep(m_Timestep);
m_Neurons.push_back(neuron);
m_InputNeuron.push_back(input);
}
void NeuronNetwork::AddSynapse(uint32_t fromNeuronID, uint32_t fromAxonID, uint32_t toNeuronID, uint32_t toDendriteID)
{
auto synapse = Synapse::Create(SynapseType::FixedResistor);
synapse->SetTimestep(m_Timestep);
m_Synapses.push_back(synapse);
m_Connections.push_back({ (uint32_t)m_Connections.size(), fromNeuronID, fromAxonID, toNeuronID, toDendriteID });
}
void NeuronNetwork::TracePlot(PlotType type, uint32_t id)
{
switch (type)
{
case PlotType::MembranePotential:
{
m_PlotInfo.push_back({ 0, id, 1, 0 });
m_PlotData.push_back({ {0}, {-70} });
}
case PlotType::SynapticCurrent:
{
m_PlotInfo.push_back({ 1, id, 0, 0 });
m_PlotData.push_back({ {0}, {0} });
}
case PlotType::DendriteCurrent:
{
m_PlotInfo.push_back({ 0, id, 0, 0 });
m_PlotData.push_back({ {0}, {0} });
}
}
}
void NeuronNetwork::TracePlot(PlotType type, uint32_t neuronID, uint32_t id)
{
m_PlotInfo.push_back({ 0, neuronID, 2, id });
m_PlotData.push_back({ {0}, {-70} });
}
void NeuronNetwork::SetTimestep(double timestep)
{
m_Timestep = timestep;
for (auto neuron : m_Neurons)
neuron->SetTimestep(m_Timestep);
for (auto synapse : m_Synapses)
synapse->SetTimestep(m_Timestep);
}
}
| 29.666667 | 120 | 0.613764 | SpiritSeeker |
fc2be6da9d115404b750a37739abeeefef952fa1 | 1,658 | hh | C++ | src/thirdparty/acg_localizer/src/math/SFMT_src/SFMT-params607.hh | rajvishah/ms-sfm | 0de1553c471c416ce5ca3d19c65abe36d8e17a07 | [
"MIT"
] | 1,102 | 2017-02-02T15:39:57.000Z | 2022-03-23T09:43:29.000Z | src/thirdparty/acg_localizer/src/math/SFMT_src/SFMT-params607.hh | rajvishah/ms-sfm | 0de1553c471c416ce5ca3d19c65abe36d8e17a07 | [
"MIT"
] | 339 | 2017-02-17T09:55:38.000Z | 2022-03-29T11:44:01.000Z | src/thirdparty/acg_localizer/src/math/SFMT_src/SFMT-params607.hh | rajvishah/ms-sfm | 0de1553c471c416ce5ca3d19c65abe36d8e17a07 | [
"MIT"
] | 331 | 2017-02-02T15:34:42.000Z | 2022-03-23T02:42:24.000Z | #ifndef SFMT_PARAMS607_H
#define SFMT_PARAMS607_H
#define POS1 2
#define SL1 15
#define SL2 3
#define SR1 13
#define SR2 3
#define MSK1 0xfdff37ffU
#define MSK2 0xef7f3f7dU
#define MSK3 0xff777b7dU
#define MSK4 0x7ff7fb2fU
#define PARITY1 0x00000001U
#define PARITY2 0x00000000U
#define PARITY3 0x00000000U
#define PARITY4 0x5986f054U
/* PARAMETERS FOR ALTIVEC */
#if defined(__APPLE__) /* For OSX */
#define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1)
#define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1)
#define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4)
#define ALTI_MSK64 \
(vector unsigned int)(MSK2, MSK1, MSK4, MSK3)
#define ALTI_SL2_PERM \
(vector unsigned char)(3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10)
#define ALTI_SL2_PERM64 \
(vector unsigned char)(3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2)
#define ALTI_SR2_PERM \
(vector unsigned char)(5,6,7,0,9,10,11,4,13,14,15,8,19,19,19,12)
#define ALTI_SR2_PERM64 \
(vector unsigned char)(13,14,15,0,1,2,3,4,19,19,19,8,9,10,11,12)
#else /* For OTHER OSs(Linux?) */
#define ALTI_SL1 {SL1, SL1, SL1, SL1}
#define ALTI_SR1 {SR1, SR1, SR1, SR1}
#define ALTI_MSK {MSK1, MSK2, MSK3, MSK4}
#define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3}
#define ALTI_SL2_PERM {3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10}
#define ALTI_SL2_PERM64 {3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2}
#define ALTI_SR2_PERM {5,6,7,0,9,10,11,4,13,14,15,8,19,19,19,12}
#define ALTI_SR2_PERM64 {13,14,15,0,1,2,3,4,19,19,19,8,9,10,11,12}
#endif /* For OSX */
#define IDSTR "SFMT-607:2-15-3-13-3:fdff37ff-ef7f3f7d-ff777b7d-7ff7fb2f"
#endif /* SFMT_PARAMS607_H */
| 35.276596 | 72 | 0.693607 | rajvishah |
fc2c0bb1e0cfe66fdcd966503a6044455b2f8b70 | 368 | cpp | C++ | ch03/081.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | null | null | null | ch03/081.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | null | null | null | ch03/081.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | 1 | 2022-01-25T15:51:34.000Z | 2022-01-25T15:51:34.000Z | #include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
using std::cin;
int main(void)
{
string word;
vector<string> text;
int i = 0;
while(cin >> word)
{
text.push_back(word);
if(++i > 2)
break;
}
for(vector<string>::size_type ix = 0; ix != text.size(); ++ix)
std::cout << text[ix] << std::endl;
return 0;
}
| 14.72 | 63 | 0.61413 | mallius |
fc2fb291cd91df0b25212bfff4d27b4db24e9531 | 2,639 | cpp | C++ | HaloTAS/MCCTAS/speedometer.cpp | s3anyboy/HaloTAS | 9584786f19e1475399298fda2d5783d47623cccd | [
"MIT"
] | 6 | 2019-09-10T19:47:04.000Z | 2020-11-26T08:32:36.000Z | HaloTAS/MCCTAS/speedometer.cpp | s3anyboy/HaloTAS | 9584786f19e1475399298fda2d5783d47623cccd | [
"MIT"
] | 13 | 2018-11-24T09:37:49.000Z | 2021-10-22T02:29:11.000Z | HaloTAS/MCCTAS/speedometer.cpp | s3anyboy/HaloTAS | 9584786f19e1475399298fda2d5783d47623cccd | [
"MIT"
] | 3 | 2020-07-28T09:19:14.000Z | 2020-09-02T04:48:49.000Z | #include "pch.h"
#include "speedometer.h"
void speedometer::clear()
{
mDataPoints.clear();
mSumTotalDistanceXYTravelled = 0.0f;
mSumTotalDistanceXYZTravelled = 0.0f;
mSumTotalDistanceCount = 0;
}
float vec3_xy_distance(glm::vec3 a, glm::vec3 b) {
return glm::distance(
glm::vec2(a.x, a.y),
glm::vec2(b.x, b.y)
);
}
double speedometer::average_speed_per_second(axis a)
{
// Doesn't make sense to have a speed if we don't have at least 2 data points
if (mDataPoints.size() < 2)
return 0.0f;
// Get the sum of distances between all data points
double totalDistance = 0.0f;
glm::vec3 lastPosition = mDataPoints.front();
for (auto& currentPosition : mDataPoints) {
switch (a)
{
case speedometer::axis::X:
totalDistance += glm::distance(lastPosition.x, currentPosition.x);
break;
case speedometer::axis::Y:
totalDistance += glm::distance(lastPosition.y, currentPosition.y);
break;
case speedometer::axis::Z:
totalDistance += glm::distance(lastPosition.z, currentPosition.z);
break;
case speedometer::axis::XY:
totalDistance += vec3_xy_distance(lastPosition, currentPosition);
break;
case speedometer::axis::XYZ:
totalDistance += glm::distance(lastPosition, currentPosition);
break;
}
lastPosition = currentPosition;
}
auto speedCount = mDataPoints.size() - 1; // 2 data points = 1 speed value, etc
return (totalDistance / speedCount) * mDataTickRate;
}
void speedometer::push_back(const glm::vec3& newPosition)
{
if (mDataPoints.size() > 0) {
auto back = mDataPoints.back();
mSumTotalDistanceXYTravelled += vec3_xy_distance(back, newPosition);
mSumTotalDistanceXYZTravelled += glm::distance(back, newPosition);
mSumTotalDistanceCount++;
}
mDataPoints.push_back(newPosition);
}
std::vector<float> speedometer::display_data(axis axis)
{
std::vector<float> data;
glm::vec3 lastPosition = mDataPoints.front();
bool skipFirst = false;
for (auto& currentPosition : mDataPoints) {
if (!skipFirst) {
skipFirst = true;
continue;
}
switch (axis)
{
case speedometer::axis::X:
data.push_back(glm::distance(lastPosition.x, currentPosition.x));
break;
case speedometer::axis::Y:
data.push_back(glm::distance(lastPosition.y, currentPosition.y));
break;
case speedometer::axis::Z:
data.push_back(glm::distance(lastPosition.z, currentPosition.z));
break;
case speedometer::axis::XY:
data.push_back(vec3_xy_distance(lastPosition, currentPosition));
break;
case speedometer::axis::XYZ:
data.push_back(glm::distance(lastPosition, currentPosition));
break;
}
lastPosition = currentPosition;
}
return data;
}
| 25.872549 | 80 | 0.71618 | s3anyboy |
fc3195ad06f02ab26d0c17c74229563b76f76652 | 2,208 | cpp | C++ | typo-poi/source/UTF8.cpp | mogemimi/daily-snippets | d9da3db8c62538e4a37f0f6b69c5d46d55c4225f | [
"MIT"
] | 14 | 2017-06-16T22:52:38.000Z | 2022-02-14T04:11:06.000Z | typo-poi/source/UTF8.cpp | mogemimi/daily-snippets | d9da3db8c62538e4a37f0f6b69c5d46d55c4225f | [
"MIT"
] | 2 | 2016-03-13T14:50:04.000Z | 2019-04-01T09:53:17.000Z | typo-poi/source/UTF8.cpp | mogemimi/daily-snippets | d9da3db8c62538e4a37f0f6b69c5d46d55c4225f | [
"MIT"
] | 2 | 2016-03-13T14:05:17.000Z | 2018-09-18T01:28:42.000Z | // Copyright (c) 2015 mogemimi. Distributed under the MIT license.
#include "utf8.h"
#include <cassert>
#include <utility>
#define USE_LLVM_CONVERTUTF 1
#if defined(USE_LLVM_CONVERTUTF)
#include "thirdparty/ConvertUTF.h"
#include <vector>
#else
#include <codecvt>
#include <locale>
#endif
namespace somera {
std::u32string toUtf32(const std::string& utf8)
{
if (utf8.empty()) {
return {};
}
#if defined(USE_LLVM_CONVERTUTF)
auto src = reinterpret_cast<const UTF8*>(utf8.data());
auto srcEnd = reinterpret_cast<const UTF8*>(utf8.data() + utf8.size());
std::u32string result;
result.resize(utf8.length() + 1);
auto dest = reinterpret_cast<UTF32*>(&result[0]);
auto destEnd = dest + result.size();
ConversionResult CR =
::ConvertUTF8toUTF32(&src, srcEnd, &dest, destEnd, strictConversion);
assert(CR != targetExhausted);
if (CR != conversionOK) {
// error
result.clear();
return result;
}
result.resize(reinterpret_cast<const char32_t*>(dest) - result.data());
result.shrink_to_fit();
return result;
#else
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert;
return convert.from_bytes(utf8);
#endif
}
std::string toUtf8(const std::u32string& utf32)
{
if (utf32.empty()) {
return {};
}
#if defined(USE_LLVM_CONVERTUTF)
auto src = reinterpret_cast<const UTF32*>(utf32.data());
auto srcEnd = reinterpret_cast<const UTF32*>(utf32.data() + utf32.size());
std::string result;
result.resize(utf32.length() * UNI_MAX_UTF8_BYTES_PER_CODE_POINT + 1);
auto dest = reinterpret_cast<UTF8*>(&result[0]);
auto destEnd = dest + result.size();
ConversionResult CR =
::ConvertUTF32toUTF8(&src, srcEnd, &dest, destEnd, strictConversion);
assert(CR != targetExhausted);
if (CR != conversionOK) {
// error
result.clear();
return result;
}
result.resize(reinterpret_cast<const char*>(dest) - result.data());
result.shrink_to_fit();
return result;
#else
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert;
return convert.to_bytes(utf32);
#endif
}
} // namespace somera
| 25.37931 | 78 | 0.664402 | mogemimi |
fc32a97b374aebf8f4b5f922eb78cb6b7e4e0e15 | 1,913 | cpp | C++ | Source/DScene_Main2.cpp | XDApp/DawnFramework | 4963be2c4ead995a3b02fb0c683c3f77662b9916 | [
"MIT"
] | 1 | 2015-06-21T08:04:36.000Z | 2015-06-21T08:04:36.000Z | Source/DScene_Main2.cpp | XDApp/DawnFramework | 4963be2c4ead995a3b02fb0c683c3f77662b9916 | [
"MIT"
] | null | null | null | Source/DScene_Main2.cpp | XDApp/DawnFramework | 4963be2c4ead995a3b02fb0c683c3f77662b9916 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "DScene_Main2.h"
DScene_Main2::DScene_Main2()
{
}
DScene_Main2::~DScene_Main2()
{
}
void DScene_Main2::Update()
{
DScene::Update();
}
void DScene_Main2::Render()
{
DScene::Render();
glUseProgram(Program->GetProgram());
glEnableVertexAttribArray(vertexPosition_modelspaceID);
glBindVertexArray(VertexArrayID);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(vertexPosition_modelspaceID, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(vertexPosition_modelspaceID);
}
void DScene_Main2::Start()
{
VLoader = new DTextFileResourceLoader(DF->Config->ResourcePath() + "V2.vert.glsl");
FLoader = new DTextFileResourceLoader(DF->Config->ResourcePath() + "F2.frag.glsl");
VShader = new DGLVertexShader(VLoader);
FShader = new DGLFragmentShader(FLoader);
VLoader->Open();
VShader->Load();
VLoader->Close();
FLoader->Open();
FShader->Load();
FLoader->Close();
Program = new DGLProgram();
Program->AttachShader(VShader);
Program->AttachShader(FShader);
Program->Load();
delete VLoader;
delete FLoader;
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
static const GLfloat g_vertex_buffer_data2[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
};
VertexArrayID = 0;
vertexPosition_modelspaceID = glGetAttribLocation(Program->GetProgram(), "vertexPosition_modelspace");
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
}
void DScene_Main2::End()
{
glDeleteBuffers(1, &vertexbuffer);
glDeleteVertexArrays(1, &VertexArrayID);
Program->Destroy();
VShader->Destroy();
FShader->Destroy();
}
| 22.505882 | 103 | 0.736017 | XDApp |
fc38e91cc3f25ea8e1d3687593f3481e149c433c | 1,507 | cxx | C++ | src/lib/SceMi/BlueNoC/Link.cxx | GaloisInc/BESSPIN-BSC | 21a0a8cba9e643ef5afcb87eac164cc33ea83e94 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 1 | 2022-02-11T01:52:42.000Z | 2022-02-11T01:52:42.000Z | src/lib/SceMi/BlueNoC/Link.cxx | GaloisInc/BESSPIN-BSC | 21a0a8cba9e643ef5afcb87eac164cc33ea83e94 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | src/lib/SceMi/BlueNoC/Link.cxx | GaloisInc/BESSPIN-BSC | 21a0a8cba9e643ef5afcb87eac164cc33ea83e94 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2009 Bluespec, Inc. All rights reserved. */
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/mman.h>
#include "sized_types.h"
#include "Link.h"
Link::Link(const char *logEnvir)
: _logTraffic(false)
, _logFile(0)
{
// Open trace file for logging all pci traffic. based on environment variable
char * outfile = getenv (logEnvir);
if (outfile) {
_logFile = fopen (outfile, "w");
if (_logFile == NULL) {
fprintf(stderr, "Could not open LINK trace file %s\n", outfile);
}
else {
fprintf(stderr, "Opened LINK trace file %s\n", outfile);
_logTraffic = true;
fprintf (_logFile, "Opened LINK trace file %s\n", outfile);
fflush(_logFile);
}
}
}
Link::~Link() {
if (_logTraffic) {
fprintf (_logFile, "Closing LINK trace file\n");
fclose (_logFile);
_logTraffic = false;
}
}
void Link::report (const Packet *pkt)
{
fprintf (_logFile,"I%d", pkt->channel);
for (unsigned int i=bits_to_words(pkt->num_bits); i != 0 ; --i) {
fprintf (_logFile, " %08x", pkt->data[i-1]);
}
fprintf (_logFile, "\n");
fflush(_logFile);
}
void Link::report (const SceMiU64& ts, const Packet *pkt)
{
fprintf (_logFile,"O%d %llu", pkt->channel, ts);
for (unsigned int i=bits_to_words(pkt->num_bits); i != 0 ; --i) {
fprintf (_logFile, " %08x", pkt->data[i-1]);
}
fprintf (_logFile, "\n");
fflush(_logFile);
}
| 24.306452 | 81 | 0.627074 | GaloisInc |
fc39f7906ddf2b699917a2e9bc4cf8b85e38beab | 7,098 | hpp | C++ | vendor/bela/include/bela/__format/args.hpp | dandycheung/baulk | f0ea046bf19e494510ae61cc4633fc38877c53e4 | [
"MIT"
] | null | null | null | vendor/bela/include/bela/__format/args.hpp | dandycheung/baulk | f0ea046bf19e494510ae61cc4633fc38877c53e4 | [
"MIT"
] | 1 | 2022-01-09T13:54:11.000Z | 2022-01-09T13:54:11.000Z | vendor/bela/include/bela/__format/args.hpp | dandycheung/baulk | f0ea046bf19e494510ae61cc4633fc38877c53e4 | [
"MIT"
] | null | null | null | ///
#ifndef BELA__FORMAT_ARGS_HPP
#define BELA__FORMAT_ARGS_HPP
#pragma once
#include <cstdint>
#include <cstdlib>
#include <cstddef>
#include <cstring>
#include <string>
#include <string_view>
#include <bela/types.hpp>
namespace bela::format_internal {
enum class __types : wchar_t {
__boolean,
__character,
__float,
__signed_integral, // short,int,
__unsigned_integral,
__u8strings,
__u16strings,
__u32strings,
__pointer,
};
// has_native support
// bela::error_code
// std::filesystem::path
template <typename T>
concept has_native = requires(const T &a) {
{ a.native() } -> std::convertible_to<const std::wstring &>;
};
template <typename T>
concept has_string_view = requires(const T &a) {
{ a.string_view() } -> std::convertible_to<std::wstring_view>;
};
struct FormatArg {
union {
struct {
uint64_t i;
size_t width;
} unsigned_integral;
struct {
int64_t i;
size_t width;
} signed_integral;
struct {
char32_t c;
size_t width;
} character;
struct {
double d;
size_t width;
} floating;
struct {
const char8_t *data;
size_t len;
} u8_strings;
struct {
const wchar_t *data;
size_t len;
} u16_strings;
struct {
const char32_t *data;
size_t len;
} u32_strings;
const uintptr_t value;
};
const __types type;
void u16strings_store(std::wstring_view sv) {
u16_strings.data = sv.data();
u16_strings.len = sv.size();
}
FormatArg(bool b) : type(__types::__boolean) {
character.c = b ? 1 : 0;
character.width = sizeof(bool);
}
// character
template <typename C>
requires bela::character<C> FormatArg(C c) : type(__types::__character) {
character.c = c;
character.width = sizeof(C);
}
// signed integral
template <typename I>
requires bela::strict_signed_integral<I> FormatArg(I i) : type(__types::__signed_integral) {
signed_integral.i = i;
signed_integral.width = sizeof(I);
}
// unsigned integral
template <typename U>
requires bela::strict_unsigned_integral<U> FormatArg(U u) : type(__types::__unsigned_integral) {
unsigned_integral.i = u;
unsigned_integral.width = sizeof(U);
}
// float double
template <typename F>
requires std::floating_point<F> FormatArg(F f) : type(__types::__float) {
floating.d = f;
floating.width = sizeof(F);
}
// UTF-8
template <typename C>
requires bela::u8_character<C> FormatArg(const C *str) : type(__types::__u8strings) {
u8_strings.data = (str == nullptr) ? u8"(NULL)" : reinterpret_cast<const char8_t *>(str);
u8_strings.len = (str == nullptr) ? sizeof("(NULL)") - 1 : std::char_traits<C>::length(str);
}
template <typename C>
requires bela::u8_character<C> FormatArg(C *str) : type(__types::__u8strings) {
u8_strings.data = (str == nullptr) ? u8"(NULL)" : reinterpret_cast<const char8_t *>(str);
u8_strings.len = (str == nullptr) ? sizeof("(NULL)") - 1 : std::char_traits<C>::length(str);
}
// NOLINT(runtime/explicit)
template <typename C, typename Allocator>
requires bela::u8_character<C> FormatArg(const std::basic_string<C, std::char_traits<C>, Allocator> &str)
: type(__types::__u8strings) {
u8_strings.data = reinterpret_cast<const char8_t *>(str.data());
u8_strings.len = str.size();
}
template <typename C>
requires bela::u8_character<C> FormatArg(std::basic_string_view<C> sv) : type(__types::__u8strings) {
u8_strings.data = reinterpret_cast<const char8_t *>(sv.data());
u8_strings.len = sv.size();
}
// UTF-16
template <typename C>
requires bela::u16_character<C> FormatArg(const C *str) : type(__types::__u16strings) {
u16_strings.data = (str == nullptr) ? L"(NULL)" : reinterpret_cast<const wchar_t *>(str);
u16_strings.len = (str == nullptr) ? sizeof("(NULL)") - 1 : std::char_traits<C>::length(str);
}
template <typename C>
requires bela::u16_character<C> FormatArg(C *str) : type(__types::__u16strings) {
u16_strings.data = (str == nullptr) ? L"(NULL)" : reinterpret_cast<const wchar_t *>(str);
u16_strings.len = (str == nullptr) ? sizeof("(NULL)") - 1 : std::char_traits<C>::length(str);
}
// NOLINT(runtime/explicit)
template <typename C, typename Allocator>
requires bela::u16_character<C> FormatArg(const std::basic_string<C, std::char_traits<C>, Allocator> &str)
: type(__types::__u16strings) {
u16_strings.data = reinterpret_cast<const wchar_t *>(str.data());
u16_strings.len = str.size();
}
template <typename C>
requires bela::u16_character<C> FormatArg(std::basic_string_view<C> sv) : type(__types::__u16strings) {
u16_strings.data = reinterpret_cast<const wchar_t *>(sv.data());
u16_strings.len = sv.size();
}
// UTF-32
FormatArg(const char32_t *str) : type(__types::__u32strings) {
u32_strings.data = (str == nullptr) ? U"(NULL)" : str;
u32_strings.len = (str == nullptr) ? sizeof("(NULL)") - 1 : std::char_traits<char32_t>::length(str);
}
FormatArg(char32_t *str) : type(__types::__u32strings) {
u32_strings.data = (str == nullptr) ? U"(NULL)" : str;
u32_strings.len = (str == nullptr) ? sizeof("(NULL)") - 1 : std::char_traits<char32_t>::length(str);
}
template <typename Allocator>
FormatArg(const std::basic_string<char32_t, std::char_traits<char32_t>, Allocator> &str)
: type(__types::__u32strings) {
u32_strings.data = str.data();
u32_strings.len = str.size();
}
FormatArg(std::u32string_view sv) : type(__types::__u32strings) {
u32_strings.data = sv.data();
u32_strings.len = sv.size();
}
// Extended type support
template <typename T>
requires has_native<T> FormatArg(const T &t) : type(__types::__u16strings) {
u16strings_store(t.native()); // store native (const std::wstring &)
}
template <typename T>
requires has_string_view<T> FormatArg(const T &t) : type(__types::__u16strings) {
u16strings_store(t.string_view()); // store native (const std::wstring &)
}
// Any pointer value that can be cast to a "void*".
template <class T>
requires bela::not_character<T> FormatArg(T *p) : value(reinterpret_cast<intptr_t>(p)), type(__types::__pointer) {}
bool is_integral_superset() const {
return type != __types::__u8strings && type != __types::__u16strings && type != __types::__u32strings;
}
auto make_unicode() const noexcept { return character.c; }
auto make_u8string_view() const noexcept { return std::u8string_view{u8_strings.data, u8_strings.len}; }
auto make_u16string_view() const noexcept { return std::wstring_view{u16_strings.data, u16_strings.len}; }
auto make_u32string_view() const noexcept { return std::u32string_view{u32_strings.data, u32_strings.len}; }
auto make_unsigned_unchecked() const noexcept { return unsigned_integral.i; }
auto make_unsigned_unchecked(bool &sign) const noexcept {
if (sign = signed_integral.i < 0; sign) {
return static_cast<uint64_t>(-signed_integral.i);
}
return static_cast<uint64_t>(signed_integral.i);
}
};
} // namespace bela::format_internal
#endif | 34.456311 | 117 | 0.67681 | dandycheung |
fc3dbcd1b30877ed8bea9d755e097cc036f440b9 | 1,103 | hpp | C++ | src/prsClass.hpp | GeoKon/GKE-L1 | 1ae69b3fdcdf0bb20df1a5afc011ad2d682e29d2 | [
"MIT"
] | 3 | 2019-01-09T04:30:41.000Z | 2019-08-17T03:08:48.000Z | src/prsClass.hpp | GeoKon/GKE-L1 | 1ae69b3fdcdf0bb20df1a5afc011ad2d682e29d2 | [
"MIT"
] | null | null | null | src/prsClass.hpp | GeoKon/GKE-L1 | 1ae69b3fdcdf0bb20df1a5afc011ad2d682e29d2 | [
"MIT"
] | null | null | null | #pragma once
#define DQUOTE '"'
#define LCURL pr.moveAfter( '{' )
#define RCURL pr.moveAfter( '}' )
#define COLON pr.moveAfter( ':' )
#define COMMA pr.moveAfter( ',' )
#define COPYS pr.copyString()
#define COPYD pr.copyDigits()
#define EXPECT(A) pr.expect(A)
#define FIND(A) pr.find(A)
#define INIT(A) pr.init(A)
#define ERROR pr.error()
class PRS
{
private:
void nospace(); // advances pointer to next non-space
char *buffer;
int maxsiz; // max size of the buffer
int nextbf; // next available byte into buffer
char *p; // walking pointer into buffer
char *porg; // original p-pointer
int errcode; // error Code
int errfunc; // where the error occured
public:
PRS( int size );
~PRS();
void init( char *text );
int error();
void moveAfter( int c );
void expect( char *t );
void find( char *t );
char *copyString(); // expects a string in quotes
char *copyDigits(); // expects a string in quotes
};
| 23.978261 | 78 | 0.563917 | GeoKon |
fc3e0e20de7584ae0fc60495db6d357ca298add9 | 39,391 | cpp | C++ | nfc/src/DOOM/doomclassic/doom/p_enemy.cpp | 1337programming/leviathan | ca9a31b45c25fd23f361d67136ae5ac6b98d2628 | [
"Apache-2.0"
] | 1 | 2018-11-07T22:44:23.000Z | 2018-11-07T22:44:23.000Z | ekronclassic/ekron/p_enemy.cpp | vic3t3chn0/OpenKrown | 201c8fb6895cb0439e39c984d2fbc2c2eaf185b4 | [
"MIT"
] | null | null | null | ekronclassic/ekron/p_enemy.cpp | vic3t3chn0/OpenKrown | 201c8fb6895cb0439e39c984d2fbc2c2eaf185b4 | [
"MIT"
] | null | null | null | /*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code 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.
Doom 3 BFG Edition Source Code 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 Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "Precompiled.h"
#include "globaldata.h"
#include <stdlib.h>
#include "m_random.h"
#include "i_system.h"
#include "doomdef.h"
#include "p_local.h"
#include "s_sound.h"
#include "g_game.h"
// State.
#include "doomstat.h"
#include "r_state.h"
// Data.
#include "sounds.h"
extern bool globalNetworking;
//
// P_NewChaseDir related LUT.
//
const dirtype_t opposite[] =
{
DI_WEST, DI_SOUTHWEST, DI_SOUTH, DI_SOUTHEAST,
DI_EAST, DI_NORTHEAST, DI_NORTH, DI_NORTHWEST, DI_NODIR
};
const dirtype_t diags[] =
{
DI_NORTHWEST, DI_NORTHEAST, DI_SOUTHWEST, DI_SOUTHEAST
};
extern "C" void A_Fall (mobj_t *actor, void *);
//
// ENEMY THINKING
// Enemies are allways spawned
// with targetplayer = -1, threshold = 0
// Most monsters are spawned unaware of all ::g->players,
// but some can be made preaware
//
//
// Called by P_NoiseAlert.
// Recursively traverse adjacent ::g->sectors,
// sound blocking ::g->lines cut off traversal.
//
void
P_RecursiveSound
( sector_t* sec,
int soundblocks )
{
int i;
line_t* check;
sector_t* other;
// wake up all monsters in this sector
if (sec->validcount == ::g->validcount
&& sec->soundtraversed <= soundblocks+1)
{
return; // already flooded
}
sec->validcount = ::g->validcount;
sec->soundtraversed = soundblocks+1;
sec->soundtarget = ::g->soundtarget;
for (i=0 ;i<sec->linecount ; i++)
{
check = sec->lines[i];
if (! (check->flags & ML_TWOSIDED) )
continue;
P_LineOpening (check);
if (::g->openrange <= 0)
continue; // closed door
if ( ::g->sides[ check->sidenum[0] ].sector == sec)
other = ::g->sides[ check->sidenum[1] ] .sector;
else
other = ::g->sides[ check->sidenum[0] ].sector;
if (check->flags & ML_SOUNDBLOCK)
{
if (!soundblocks)
P_RecursiveSound (other, 1);
}
else
P_RecursiveSound (other, soundblocks);
}
}
//
// P_NoiseAlert
// If a monster yells at a player,
// it will alert other monsters to the player.
//
void
P_NoiseAlert
( mobj_t* target,
mobj_t* emmiter )
{
::g->soundtarget = target;
::g->validcount++;
P_RecursiveSound (emmiter->subsector->sector, 0);
}
//
// P_CheckMeleeRange
//
qboolean P_CheckMeleeRange (mobj_t* actor)
{
mobj_t* pl;
fixed_t dist;
if (!actor->target)
return false;
pl = actor->target;
dist = P_AproxDistance (pl->x-actor->x, pl->y-actor->y);
if (dist >= MELEERANGE-20*FRACUNIT+pl->info->radius)
return false;
if (! P_CheckSight (actor, actor->target) )
return false;
return true;
}
//
// P_CheckMissileRange
//
qboolean P_CheckMissileRange (mobj_t* actor)
{
fixed_t dist;
if (! P_CheckSight (actor, actor->target) )
return false;
if ( actor->flags & MF_JUSTHIT )
{
// the target just hit the enemy,
// so fight back!
actor->flags &= ~MF_JUSTHIT;
return true;
}
if (actor->reactiontime)
return false; // do not attack yet
// OPTIMIZE: get this from a global checksight
dist = P_AproxDistance ( actor->x-actor->target->x,
actor->y-actor->target->y) - 64*FRACUNIT;
if (!actor->info->meleestate)
dist -= 128*FRACUNIT; // no melee attack, so fire more
dist >>= 16;
if (actor->type == MT_VILE)
{
if (dist > 14*64)
return false; // too far away
}
if (actor->type == MT_UNDEAD)
{
if (dist < 196)
return false; // close for fist attack
dist >>= 1;
}
if (actor->type == MT_CYBORG
|| actor->type == MT_SPIDER
|| actor->type == MT_SKULL)
{
dist >>= 1;
}
if (dist > 200)
dist = 200;
if (actor->type == MT_CYBORG && dist > 160)
dist = 160;
if (P_Random () < dist)
return false;
return true;
}
//
// P_Move
// Move in the current direction,
// returns false if the move is blocked.
//
const fixed_t xspeed[8] = {FRACUNIT,47000,0,-47000,-FRACUNIT,-47000,0,47000};
const fixed_t yspeed[8] = {0,47000,FRACUNIT,47000,0,-47000,-FRACUNIT,-47000};
qboolean P_Move (mobj_t* actor)
{
fixed_t tryx;
fixed_t tryy;
line_t* ld;
// warning: 'catch', 'throw', and 'try'
// are all C++ reserved words
qboolean try_ok;
qboolean good;
if (actor->movedir == DI_NODIR)
return false;
if ((unsigned)actor->movedir >= 8)
I_Error ("Weird actor->movedir!");
tryx = actor->x + actor->info->speed*xspeed[actor->movedir];
tryy = actor->y + actor->info->speed*yspeed[actor->movedir];
try_ok = P_TryMove (actor, tryx, tryy);
if (!try_ok)
{
// open any specials
if (actor->flags & MF_FLOAT && ::g->floatok)
{
// must adjust height
if (actor->z < ::g->tmfloorz)
actor->z += FLOATSPEED;
else
actor->z -= FLOATSPEED;
actor->flags |= MF_INFLOAT;
return true;
}
if (!::g->numspechit)
return false;
actor->movedir = DI_NODIR;
good = false;
while (::g->numspechit--)
{
ld = ::g->spechit[::g->numspechit];
// if the special is not a door
// that can be opened,
// return false
if (P_UseSpecialLine (actor, ld,0))
good = true;
}
return good;
}
else
{
actor->flags &= ~MF_INFLOAT;
}
if (! (actor->flags & MF_FLOAT) )
actor->z = actor->floorz;
return true;
}
//
// TryWalk
// Attempts to move actor on
// in its current (ob->moveangle) direction.
// If blocked by either a wall or an actor
// returns FALSE
// If move is either clear or blocked only by a door,
// returns TRUE and sets...
// If a door is in the way,
// an OpenDoor call is made to start it opening.
//
qboolean P_TryWalk (mobj_t* actor)
{
if (!P_Move (actor))
{
return false;
}
actor->movecount = P_Random()&15;
return true;
}
void P_NewChaseDir (mobj_t* actor)
{
fixed_t deltax;
fixed_t deltay;
dirtype_t d[3];
int tdir;
dirtype_t olddir;
dirtype_t turnaround;
if (!actor->target)
I_Error ("P_NewChaseDir: called with no target");
olddir = (dirtype_t)actor->movedir;
turnaround=opposite[olddir];
deltax = actor->target->x - actor->x;
deltay = actor->target->y - actor->y;
if (deltax>10*FRACUNIT)
d[1]= DI_EAST;
else if (deltax<-10*FRACUNIT)
d[1]= DI_WEST;
else
d[1]=DI_NODIR;
if (deltay<-10*FRACUNIT)
d[2]= DI_SOUTH;
else if (deltay>10*FRACUNIT)
d[2]= DI_NORTH;
else
d[2]=DI_NODIR;
// try direct route
if (d[1] != DI_NODIR
&& d[2] != DI_NODIR)
{
actor->movedir = diags[((deltay<0)<<1)+(deltax>0)];
if (actor->movedir != turnaround && P_TryWalk(actor))
return;
}
// try other directions
if (P_Random() > 200
|| abs(deltay)>abs(deltax))
{
tdir=d[1];
d[1]=d[2];
d[2]=(dirtype_t)tdir;
}
if (d[1]==turnaround)
d[1]=DI_NODIR;
if (d[2]==turnaround)
d[2]=DI_NODIR;
if (d[1]!=DI_NODIR)
{
actor->movedir = d[1];
if (P_TryWalk(actor))
{
// either moved forward or attacked
return;
}
}
if (d[2]!=DI_NODIR)
{
actor->movedir =d[2];
if (P_TryWalk(actor))
return;
}
// there is no direct path to the player,
// so pick another direction.
if (olddir!=DI_NODIR)
{
actor->movedir =olddir;
if (P_TryWalk(actor))
return;
}
// randomly determine direction of search
if (P_Random()&1)
{
for ( tdir=DI_EAST;
tdir<=DI_SOUTHEAST;
tdir++ )
{
if (tdir!=turnaround)
{
actor->movedir =tdir;
if ( P_TryWalk(actor) )
return;
}
}
}
else
{
for ( tdir=DI_SOUTHEAST;
tdir != (DI_EAST-1);
tdir-- )
{
if (tdir!=turnaround)
{
actor->movedir =tdir;
if ( P_TryWalk(actor) )
return;
}
}
}
if (turnaround != DI_NODIR)
{
actor->movedir =turnaround;
if ( P_TryWalk(actor) )
return;
}
actor->movedir = DI_NODIR; // can not move
}
//
// P_LookForPlayers
// If allaround is false, only look 180 degrees in front.
// Returns true if a player is targeted.
//
qboolean
P_LookForPlayers
( mobj_t* actor,
qboolean allaround )
{
int c;
int stop;
player_t* player;
sector_t* sector;
angle_t an;
fixed_t dist;
sector = actor->subsector->sector;
c = 0;
stop = (actor->lastlook-1)&3;
for ( ; ; actor->lastlook = (actor->lastlook+1)&3 )
{
if (!::g->playeringame[actor->lastlook])
continue;
if (c++ == 2
|| actor->lastlook == stop)
{
// done looking
return false;
}
player = &::g->players[actor->lastlook];
if (player->health <= 0)
continue; // dead
if (!P_CheckSight (actor, player->mo))
continue; // out of sight
if (!allaround)
{
an = R_PointToAngle2 (actor->x,
actor->y,
player->mo->x,
player->mo->y)
- actor->angle;
if (an > ANG90 && an < ANG270)
{
dist = P_AproxDistance (player->mo->x - actor->x,
player->mo->y - actor->y);
// if real close, react anyway
if (dist > MELEERANGE)
continue; // behind back
}
}
actor->target = player->mo;
return true;
}
return false;
}
extern "C" {
//
// A_KeenDie
// DOOM II special, map 32.
// Uses special tag 666.
//
void A_KeenDie (mobj_t* mo, void * )
{
thinker_t* th;
mobj_t* mo2;
line_t junk;
A_Fall (mo, 0);
// scan the remaining thinkers
// to see if all Keens are dead
for (th = ::g->thinkercap.next ; th != &::g->thinkercap ; th=th->next)
{
if (th->function.acp1 != (actionf_p1)P_MobjThinker)
continue;
mo2 = (mobj_t *)th;
if (mo2 != mo
&& mo2->type == mo->type
&& mo2->health > 0)
{
// other Keen not dead
return;
}
}
junk.tag = 666;
EV_DoDoor(&junk,opened);
}
//
// ACTION ROUTINES
//
//
// A_Look
// Stay in state until a player is sighted.
//
void A_Look (mobj_t* actor, void * )
{
mobj_t* targ;
actor->threshold = 0; // any shot will wake up
targ = actor->subsector->sector->soundtarget;
if (targ
&& (targ->flags & MF_SHOOTABLE) )
{
actor->target = targ;
if ( actor->flags & MF_AMBUSH )
{
if (P_CheckSight (actor, actor->target))
goto seeyou;
}
else
goto seeyou;
}
if (!P_LookForPlayers (actor, false) )
return;
// go into chase state
seeyou:
if (actor->info->seesound)
{
int sound;
switch (actor->info->seesound)
{
case sfx_posit1:
case sfx_posit2:
case sfx_posit3:
sound = sfx_posit1+P_Random()%3;
break;
case sfx_bgsit1:
case sfx_bgsit2:
sound = sfx_bgsit1+P_Random()%2;
break;
default:
sound = actor->info->seesound;
break;
}
if (actor->type==MT_SPIDER
|| actor->type == MT_CYBORG)
{
// full volume
S_StartSound (NULL, sound);
}
else
S_StartSound (actor, sound);
}
P_SetMobjState (actor, (statenum_t)actor->info->seestate);
}
//
// A_Chase
// Actor has a melee attack,
// so it tries to close as fast as possible
//
void A_Chase (mobj_t* actor, void * )
{
int delta;
if (actor->reactiontime)
actor->reactiontime--;
// modify target threshold
if (actor->threshold)
{
if (!actor->target
|| actor->target->health <= 0)
{
actor->threshold = 0;
}
else
actor->threshold--;
}
// turn towards movement direction if not there yet
if (actor->movedir < 8)
{
actor->angle &= (7<<29);
delta = actor->angle - (actor->movedir << 29);
if (delta > 0)
actor->angle -= ANG90/2;
else if (delta < 0)
actor->angle += ANG90/2;
}
if (!actor->target
|| !(actor->target->flags&MF_SHOOTABLE))
{
// look for a new target
if (P_LookForPlayers(actor,true))
return; // got a new target
P_SetMobjState (actor, (statenum_t)actor->info->spawnstate);
return;
}
// do not attack twice in a row
if (actor->flags & MF_JUSTATTACKED)
{
actor->flags &= ~MF_JUSTATTACKED;
if (::g->gameskill != sk_nightmare && !::g->fastparm)
P_NewChaseDir (actor);
return;
}
// check for melee attack
if (actor->info->meleestate && P_CheckMeleeRange (actor))
{
if (actor->info->attacksound)
S_StartSound (actor, actor->info->attacksound);
P_SetMobjState (actor, (statenum_t)actor->info->meleestate);
return;
}
// check for missile attack
if (actor->info->missilestate)
{
if (::g->gameskill < sk_nightmare
&& !::g->fastparm && actor->movecount)
{
goto nomissile;
}
if (!P_CheckMissileRange (actor))
goto nomissile;
P_SetMobjState (actor, (statenum_t)actor->info->missilestate);
actor->flags |= MF_JUSTATTACKED;
return;
}
// ?
nomissile:
// possibly choose another target
if (::g->netgame
&& !actor->threshold
&& !P_CheckSight (actor, actor->target) )
{
if (P_LookForPlayers(actor,true))
return; // got a new target
}
// chase towards player
if (--actor->movecount<0
|| !P_Move (actor))
{
P_NewChaseDir (actor);
}
// make active sound
if (actor->info->activesound && P_Random () < 3)
{
S_StartSound (actor, actor->info->activesound);
}
}
//
// A_FaceTarget
//
void A_FaceTarget (mobj_t* actor, void * )
{
if (!actor->target)
return;
actor->flags &= ~MF_AMBUSH;
actor->angle = R_PointToAngle2 (actor->x,
actor->y,
actor->target->x,
actor->target->y);
if (actor->target->flags & MF_SHADOW)
actor->angle += (P_Random()-P_Random())<<21;
}
//
// A_PosAttack
//
void A_PosAttack (mobj_t* actor, void * )
{
int angle;
int damage;
int slope;
if (!actor->target)
return;
A_FaceTarget (actor, 0);
angle = actor->angle;
slope = P_AimLineAttack (actor, angle, MISSILERANGE);
S_StartSound (actor, sfx_pistol);
angle += (P_Random()-P_Random())<<20;
damage = ((P_Random()%5)+1)*3;
P_LineAttack (actor, angle, MISSILERANGE, slope, damage);
}
void A_SPosAttack (mobj_t* actor, void * )
{
int i;
int angle;
int bangle;
int damage;
int slope;
if (!actor->target)
return;
S_StartSound (actor, sfx_shotgn);
A_FaceTarget (actor, 0);
bangle = actor->angle;
slope = P_AimLineAttack (actor, bangle, MISSILERANGE);
for (i=0 ; i<3 ; i++)
{
angle = bangle + ((P_Random()-P_Random())<<20);
damage = ((P_Random()%5)+1)*3;
P_LineAttack (actor, angle, MISSILERANGE, slope, damage);
}
}
void A_CPosAttack (mobj_t* actor, void * )
{
int angle;
int bangle;
int damage;
int slope;
if (!actor->target)
return;
S_StartSound (actor, sfx_shotgn);
A_FaceTarget (actor, 0);
bangle = actor->angle;
slope = P_AimLineAttack (actor, bangle, MISSILERANGE);
angle = bangle + ((P_Random()-P_Random())<<20);
damage = ((P_Random()%5)+1)*3;
P_LineAttack (actor, angle, MISSILERANGE, slope, damage);
}
void A_CPosRefire (mobj_t* actor, void * )
{
// keep firing unless target got out of sight
A_FaceTarget (actor, 0);
if (P_Random () < 40)
return;
if (!actor->target
|| actor->target->health <= 0
|| !P_CheckSight (actor, actor->target) )
{
P_SetMobjState (actor, (statenum_t)actor->info->seestate);
}
}
void A_SpidRefire (mobj_t* actor, void * )
{
// keep firing unless target got out of sight
A_FaceTarget (actor, 0);
if (P_Random () < 10)
return;
if (!actor->target
|| actor->target->health <= 0
|| !P_CheckSight (actor, actor->target) )
{
P_SetMobjState (actor, (statenum_t)actor->info->seestate);
}
}
void A_BspiAttack (mobj_t *actor, void * )
{
if (!actor->target)
return;
A_FaceTarget (actor, 0);
// launch a missile
P_SpawnMissile (actor, actor->target, MT_ARACHPLAZ);
}
//
// A_TroopAttack
//
void A_TroopAttack (mobj_t* actor, void * )
{
int damage;
if (!actor->target)
return;
A_FaceTarget (actor, 0);
if (P_CheckMeleeRange (actor))
{
S_StartSound (actor, sfx_claw);
damage = (P_Random()%8+1)*3;
P_DamageMobj (actor->target, actor, actor, damage);
return;
}
// launch a missile
P_SpawnMissile (actor, actor->target, MT_TROOPSHOT);
}
void A_SargAttack (mobj_t* actor, void * )
{
int damage;
if (!actor->target)
return;
A_FaceTarget (actor, 0);
if (P_CheckMeleeRange (actor))
{
damage = ((P_Random()%10)+1)*4;
P_DamageMobj (actor->target, actor, actor, damage);
}
}
void A_HeadAttack (mobj_t* actor, void * )
{
int damage;
if (!actor->target)
return;
A_FaceTarget (actor, 0);
if (P_CheckMeleeRange (actor))
{
damage = (P_Random()%6+1)*10;
P_DamageMobj (actor->target, actor, actor, damage);
return;
}
// launch a missile
P_SpawnMissile (actor, actor->target, MT_HEADSHOT);
}
void A_CyberAttack (mobj_t* actor, void * )
{
if (!actor->target)
return;
A_FaceTarget (actor, 0);
P_SpawnMissile (actor, actor->target, MT_ROCKET);
}
void A_BruisAttack (mobj_t* actor, void * )
{
int damage;
if (!actor->target)
return;
if (P_CheckMeleeRange (actor))
{
S_StartSound (actor, sfx_claw);
damage = (P_Random()%8+1)*10;
P_DamageMobj (actor->target, actor, actor, damage);
return;
}
// launch a missile
P_SpawnMissile (actor, actor->target, MT_BRUISERSHOT);
}
//
// A_SkelMissile
//
void A_SkelMissile (mobj_t* actor, void * )
{
mobj_t* mo;
if (!actor->target)
return;
A_FaceTarget (actor, 0);
actor->z += 16*FRACUNIT; // so missile spawns higher
mo = P_SpawnMissile (actor, actor->target, MT_TRACER);
actor->z -= 16*FRACUNIT; // back to normal
mo->x += mo->momx;
mo->y += mo->momy;
mo->tracer = actor->target;
}
void A_Tracer (mobj_t* actor, void * )
{
angle_t exact;
fixed_t dist;
fixed_t slope;
mobj_t* dest;
mobj_t* th;
//if (::g->gametic & 3)
//return;
// DHM - Nerve :: Demo fix - Keep the game state deterministic!!!
if ( ::g->leveltime & 3 ) {
return;
}
// spawn a puff of smoke behind the rocket
P_SpawnPuff (actor->x, actor->y, actor->z);
th = P_SpawnMobj (actor->x-actor->momx,
actor->y-actor->momy,
actor->z, MT_SMOKE);
th->momz = FRACUNIT;
th->tics -= P_Random()&3;
if (th->tics < 1)
th->tics = 1;
// adjust direction
dest = actor->tracer;
if (!dest || dest->health <= 0)
return;
// change angle
exact = R_PointToAngle2 (actor->x,
actor->y,
dest->x,
dest->y);
if (exact != actor->angle)
{
if (exact - actor->angle > 0x80000000)
{
actor->angle -= ::g->TRACEANGLE;
if (exact - actor->angle < 0x80000000)
actor->angle = exact;
}
else
{
actor->angle += ::g->TRACEANGLE;
if (exact - actor->angle > 0x80000000)
actor->angle = exact;
}
}
exact = actor->angle>>ANGLETOFINESHIFT;
actor->momx = FixedMul (actor->info->speed, finecosine[exact]);
actor->momy = FixedMul (actor->info->speed, finesine[exact]);
// change slope
dist = P_AproxDistance (dest->x - actor->x,
dest->y - actor->y);
dist = dist / actor->info->speed;
if (dist < 1)
dist = 1;
slope = (dest->z+40*FRACUNIT - actor->z) / dist;
if (slope < actor->momz)
actor->momz -= FRACUNIT/8;
else
actor->momz += FRACUNIT/8;
}
void A_SkelWhoosh (mobj_t* actor, void * )
{
if (!actor->target)
return;
A_FaceTarget (actor, 0);
S_StartSound (actor,sfx_skeswg);
}
void A_SkelFist (mobj_t* actor, void * )
{
int damage;
if (!actor->target)
return;
A_FaceTarget (actor, 0);
if (P_CheckMeleeRange (actor))
{
damage = ((P_Random()%10)+1)*6;
S_StartSound (actor, sfx_skepch);
P_DamageMobj (actor->target, actor, actor, damage);
}
}
//
// PIT_VileCheck
// Detect a corpse that could be raised.
//
qboolean PIT_VileCheck (mobj_t* thing )
{
int maxdist;
qboolean check;
if (!(thing->flags & MF_CORPSE) )
return true; // not a monster
if (thing->tics != -1)
return true; // not lying still yet
if (thing->info->raisestate == S_NULL)
return true; // monster doesn't have a raise state
maxdist = thing->info->radius + mobjinfo[MT_VILE].radius;
if ( abs(thing->x - ::g->viletryx) > maxdist
|| abs(thing->y - ::g->viletryy) > maxdist )
return true; // not actually touching
::g->corpsehit = thing;
::g->corpsehit->momx = ::g->corpsehit->momy = 0;
::g->corpsehit->height <<= 2;
check = P_CheckPosition (::g->corpsehit, ::g->corpsehit->x, ::g->corpsehit->y);
::g->corpsehit->height >>= 2;
if (!check)
return true; // doesn't fit here
return false; // got one, so stop checking
}
//
// A_VileChase
// Check for ressurecting a body
//
void A_VileChase (mobj_t* actor, void * )
{
int xl;
int xh;
int yl;
int yh;
int bx;
int by;
const mobjinfo_t* info;
mobj_t* temp;
if (actor->movedir != DI_NODIR)
{
// check for corpses to raise
::g->viletryx =
actor->x + actor->info->speed*xspeed[actor->movedir];
::g->viletryy =
actor->y + actor->info->speed*yspeed[actor->movedir];
xl = (::g->viletryx - ::g->bmaporgx - MAXRADIUS*2)>>MAPBLOCKSHIFT;
xh = (::g->viletryx - ::g->bmaporgx + MAXRADIUS*2)>>MAPBLOCKSHIFT;
yl = (::g->viletryy - ::g->bmaporgy - MAXRADIUS*2)>>MAPBLOCKSHIFT;
yh = (::g->viletryy - ::g->bmaporgy + MAXRADIUS*2)>>MAPBLOCKSHIFT;
::g->vileobj = actor;
for (bx=xl ; bx<=xh ; bx++)
{
for (by=yl ; by<=yh ; by++)
{
// Call PIT_VileCheck to check
// whether object is a corpse
// that canbe raised.
if (!P_BlockThingsIterator(bx,by,PIT_VileCheck))
{
// got one!
temp = actor->target;
actor->target = ::g->corpsehit;
A_FaceTarget (actor, 0);
actor->target = temp;
P_SetMobjState (actor, S_VILE_HEAL1);
S_StartSound (::g->corpsehit, sfx_slop);
info = ::g->corpsehit->info;
P_SetMobjState (::g->corpsehit,(statenum_t)info->raisestate);
::g->corpsehit->height <<= 2;
::g->corpsehit->flags = info->flags;
::g->corpsehit->health = info->spawnhealth;
::g->corpsehit->target = NULL;
return;
}
}
}
}
// Return to normal attack.
A_Chase (actor, 0);
}
//
// A_VileStart
//
void A_VileStart (mobj_t* actor, void * )
{
S_StartSound (actor, sfx_vilatk);
}
//
// A_Fire
// Keep fire in front of player unless out of sight
//
void A_Fire (mobj_t* actor, void * );
void A_StartFire (mobj_t* actor, void * )
{
S_StartSound(actor,sfx_flamst);
A_Fire(actor, 0 );
}
void A_FireCrackle (mobj_t* actor, void * )
{
S_StartSound(actor,sfx_flame);
A_Fire(actor, 0);
}
void A_Fire (mobj_t* actor, void * )
{
mobj_t* dest;
unsigned an;
dest = actor->tracer;
if (!dest)
return;
// don't move it if the vile lost sight
if (!P_CheckSight (actor->target, dest) )
return;
an = dest->angle >> ANGLETOFINESHIFT;
P_UnsetThingPosition (actor);
actor->x = dest->x + FixedMul (24*FRACUNIT, finecosine[an]);
actor->y = dest->y + FixedMul (24*FRACUNIT, finesine[an]);
actor->z = dest->z;
P_SetThingPosition (actor);
}
//
// A_VileTarget
// Spawn the hellfire
//
void A_VileTarget (mobj_t* actor, void * )
{
mobj_t* fog;
if (!actor->target)
return;
A_FaceTarget (actor, 0);
fog = P_SpawnMobj (actor->target->x,
actor->target->x,
actor->target->z, MT_FIRE);
actor->tracer = fog;
fog->target = actor;
fog->tracer = actor->target;
A_Fire (fog, 0);
}
//
// A_VileAttack
//
void A_VileAttack (mobj_t* actor, void * )
{
mobj_t* fire;
int an;
if (!actor->target)
return;
A_FaceTarget (actor, 0);
if (!P_CheckSight (actor, actor->target) )
return;
S_StartSound (actor, sfx_barexp);
P_DamageMobj (actor->target, actor, actor, 20);
actor->target->momz = 1000*FRACUNIT/actor->target->info->mass;
an = actor->angle >> ANGLETOFINESHIFT;
fire = actor->tracer;
if (!fire)
return;
// move the fire between the vile and the player
fire->x = actor->target->x - FixedMul (24*FRACUNIT, finecosine[an]);
fire->y = actor->target->y - FixedMul (24*FRACUNIT, finesine[an]);
P_RadiusAttack (fire, actor, 70 );
}
//
// Mancubus attack,
// firing three missiles (bruisers)
// in three different directions?
// Doesn't look like it.
//
void A_FatRaise (mobj_t *actor, void * )
{
A_FaceTarget (actor, 0);
S_StartSound (actor, sfx_manatk);
}
void A_FatAttack1 (mobj_t* actor, void * )
{
mobj_t* mo;
int an;
A_FaceTarget (actor, 0);
// Change direction to ...
actor->angle += FATSPREAD;
P_SpawnMissile (actor, actor->target, MT_FATSHOT);
mo = P_SpawnMissile (actor, actor->target, MT_FATSHOT);
mo->angle += FATSPREAD;
an = mo->angle >> ANGLETOFINESHIFT;
mo->momx = FixedMul (mo->info->speed, finecosine[an]);
mo->momy = FixedMul (mo->info->speed, finesine[an]);
}
void A_FatAttack2 (mobj_t* actor, void * )
{
mobj_t* mo;
int an;
A_FaceTarget (actor, 0);
// Now here choose opposite deviation.
actor->angle -= FATSPREAD;
P_SpawnMissile (actor, actor->target, MT_FATSHOT);
mo = P_SpawnMissile (actor, actor->target, MT_FATSHOT);
mo->angle -= FATSPREAD*2;
an = mo->angle >> ANGLETOFINESHIFT;
mo->momx = FixedMul (mo->info->speed, finecosine[an]);
mo->momy = FixedMul (mo->info->speed, finesine[an]);
}
void A_FatAttack3 (mobj_t* actor, void * )
{
mobj_t* mo;
int an;
A_FaceTarget (actor, 0);
mo = P_SpawnMissile (actor, actor->target, MT_FATSHOT);
mo->angle -= FATSPREAD/2;
an = mo->angle >> ANGLETOFINESHIFT;
mo->momx = FixedMul (mo->info->speed, finecosine[an]);
mo->momy = FixedMul (mo->info->speed, finesine[an]);
mo = P_SpawnMissile (actor, actor->target, MT_FATSHOT);
mo->angle += FATSPREAD/2;
an = mo->angle >> ANGLETOFINESHIFT;
mo->momx = FixedMul (mo->info->speed, finecosine[an]);
mo->momy = FixedMul (mo->info->speed, finesine[an]);
}
//
// SkullAttack
// Fly at the player like a missile.
//
void A_SkullAttack (mobj_t* actor, void * )
{
mobj_t* dest;
angle_t an;
int dist;
if (!actor->target)
return;
dest = actor->target;
actor->flags |= MF_SKULLFLY;
S_StartSound (actor, actor->info->attacksound);
A_FaceTarget (actor, 0);
an = actor->angle >> ANGLETOFINESHIFT;
actor->momx = FixedMul (SKULLSPEED, finecosine[an]);
actor->momy = FixedMul (SKULLSPEED, finesine[an]);
dist = P_AproxDistance (dest->x - actor->x, dest->y - actor->y);
dist = dist / SKULLSPEED;
if (dist < 1)
dist = 1;
actor->momz = (dest->z+(dest->height>>1) - actor->z) / dist;
}
//
// A_PainShootSkull
// Spawn a lost soul and launch it at the target
//
void
A_PainShootSkull
( mobj_t* actor,
angle_t angle )
{
fixed_t x;
fixed_t y;
fixed_t z;
mobj_t* newmobj;
angle_t an;
int prestep;
int count;
thinker_t* currentthinker;
// count total number of skull currently on the level
count = 0;
currentthinker = ::g->thinkercap.next;
while (currentthinker != &::g->thinkercap)
{
if ( (currentthinker->function.acp1 == (actionf_p1)P_MobjThinker)
&& ((mobj_t *)currentthinker)->type == MT_SKULL)
count++;
currentthinker = currentthinker->next;
}
// if there are allready 20 skulls on the level,
// don't spit another one
if (count > 20)
return;
// okay, there's playe for another one
an = angle >> ANGLETOFINESHIFT;
prestep =
4*FRACUNIT
+ 3*(actor->info->radius + mobjinfo[MT_SKULL].radius)/2;
x = actor->x + FixedMul (prestep, finecosine[an]);
y = actor->y + FixedMul (prestep, finesine[an]);
z = actor->z + 8*FRACUNIT;
newmobj = P_SpawnMobj (x , y, z, MT_SKULL);
// Check for movements.
if (!P_TryMove (newmobj, newmobj->x, newmobj->y))
{
// kill it immediately
P_DamageMobj (newmobj,actor,actor,10000);
return;
}
newmobj->target = actor->target;
A_SkullAttack (newmobj, 0);
}
//
// A_PainAttack
// Spawn a lost soul and launch it at the target
//
void A_PainAttack (mobj_t* actor, void * )
{
if (!actor->target)
return;
A_FaceTarget (actor, 0);
A_PainShootSkull (actor, actor->angle);
}
void A_PainDie (mobj_t* actor, void * )
{
A_Fall (actor, 0);
A_PainShootSkull (actor, actor->angle+ANG90);
A_PainShootSkull (actor, actor->angle+ANG180);
A_PainShootSkull (actor, actor->angle+ANG270);
}
void A_Scream (mobj_t* actor, void * )
{
int sound;
switch (actor->info->deathsound)
{
case 0:
return;
case sfx_podth1:
case sfx_podth2:
case sfx_podth3:
sound = sfx_podth1 + P_Random ()%3;
break;
case sfx_bgdth1:
case sfx_bgdth2:
sound = sfx_bgdth1 + P_Random ()%2;
break;
default:
sound = actor->info->deathsound;
break;
}
// Check for bosses.
if (actor->type==MT_SPIDER
|| actor->type == MT_CYBORG)
{
// full volume
S_StartSound (NULL, sound);
}
else
S_StartSound (actor, sound);
}
void A_XScream (mobj_t* actor, void * )
{
S_StartSound (actor, sfx_slop);
}
void A_Pain (mobj_t* actor, void * )
{
if (actor->info->painsound )
S_StartSound (actor, actor->info->painsound);
}
void A_Fall (mobj_t *actor, void * )
{
// actor is on ground, it can be walked over
actor->flags &= ~MF_SOLID;
// So change this if corpse objects
// are meant to be obstacles.
}
//
// A_Explode
//
void A_Explode (mobj_t* thingy, void * )
{
P_RadiusAttack ( thingy, thingy->target, 128 );
}
//
// A_BossDeath
// Possibly trigger special effects
// if on first boss level
//
void A_BossDeath (mobj_t* mo, void * )
{
thinker_t* th;
mobj_t* mo2;
line_t junk;
int i;
if ( ::g->gamemode == commercial)
{
if (::g->gamemap != 7)
return;
if ((mo->type != MT_FATSO)
&& (mo->type != MT_BABY))
return;
}
else
{
switch(::g->gameepisode)
{
case 1:
if (::g->gamemap != 8)
return;
if (mo->type != MT_BRUISER)
return;
break;
case 2:
if (::g->gamemap != 8)
return;
if (mo->type != MT_CYBORG)
return;
break;
case 3:
if (::g->gamemap != 8)
return;
if (mo->type != MT_SPIDER)
return;
break;
case 4:
switch(::g->gamemap)
{
case 6:
if (mo->type != MT_CYBORG)
return;
break;
case 8:
if (mo->type != MT_SPIDER)
return;
break;
default:
return;
break;
}
break;
default:
if (::g->gamemap != 8)
return;
break;
}
}
// make sure there is a player alive for victory
for (i=0 ; i<MAXPLAYERS ; i++)
if (::g->playeringame[i] && ::g->players[i].health > 0)
break;
if (i==MAXPLAYERS)
return; // no one left alive, so do not end game
// scan the remaining thinkers to see
// if all bosses are dead
for (th = ::g->thinkercap.next ; th != &::g->thinkercap ; th=th->next)
{
if (th->function.acp1 != (actionf_p1)P_MobjThinker)
continue;
mo2 = (mobj_t *)th;
if (mo2 != mo
&& mo2->type == mo->type
&& mo2->health > 0)
{
// other boss not dead
return;
}
}
// victory!
if ( ::g->gamemode == commercial)
{
if (::g->gamemap == 7)
{
if (mo->type == MT_FATSO)
{
junk.tag = 666;
EV_DoFloor(&junk,lowerFloorToLowest);
return;
}
if (mo->type == MT_BABY)
{
junk.tag = 667;
EV_DoFloor(&junk,raiseToTexture);
return;
}
}
}
else
{
switch(::g->gameepisode)
{
case 1:
junk.tag = 666;
EV_DoFloor (&junk, lowerFloorToLowest);
return;
break;
case 4:
switch(::g->gamemap)
{
case 6:
junk.tag = 666;
EV_DoDoor (&junk, blazeOpen);
return;
break;
case 8:
junk.tag = 666;
EV_DoFloor (&junk, lowerFloorToLowest);
return;
break;
}
}
}
G_ExitLevel ();
}
void A_Hoof (mobj_t* mo, void * )
{
S_StartSound (mo, sfx_hoof);
A_Chase (mo, 0);
}
void A_Metal (mobj_t* mo, void * )
{
S_StartSound (mo, sfx_metal);
A_Chase (mo, 0);
}
void A_BabyMetal (mobj_t* mo, void * )
{
S_StartSound (mo, sfx_bspwlk);
A_Chase (mo, 0);
}
void
A_OpenShotgun2
( player_t* player,
pspdef_t* psp )
{
if (globalNetworking || (player == &::g->players[::g->consoleplayer]))
S_StartSound (player->mo, sfx_dbopn);
}
void
A_LoadShotgun2
( player_t* player,
pspdef_t* psp )
{
if (globalNetworking || (player == &::g->players[::g->consoleplayer]))
S_StartSound (player->mo, sfx_dbload);
}
void
A_ReFire
( player_t* player,
pspdef_t* psp );
void
A_CloseShotgun2
( player_t* player,
pspdef_t* psp )
{
if (globalNetworking || (player == &::g->players[::g->consoleplayer]))
S_StartSound (player->mo, sfx_dbcls);
A_ReFire(player,psp);
}
void A_BrainAwake (mobj_t* mo, void * )
{
thinker_t* thinker;
mobj_t* m;
// find all the target spots
::g->easy = 0;
::g->numbraintargets = 0;
::g->braintargeton = 0;
thinker = ::g->thinkercap.next;
for (thinker = ::g->thinkercap.next ;
thinker != &::g->thinkercap ;
thinker = thinker->next)
{
if (thinker->function.acp1 != (actionf_p1)P_MobjThinker)
continue; // not a mobj
m = (mobj_t *)thinker;
if (m->type == MT_BOSSTARGET )
{
::g->braintargets[::g->numbraintargets] = m;
::g->numbraintargets++;
}
}
S_StartSound (NULL,sfx_bossit);
}
void A_BrainPain (mobj_t* mo, void * )
{
S_StartSound (NULL,sfx_bospn);
}
void A_BrainScream (mobj_t* mo, void * )
{
int x;
int y;
int z;
mobj_t* th;
for (x=mo->x - 196*FRACUNIT ; x< mo->x + 320*FRACUNIT ; x+= FRACUNIT*8)
{
y = mo->y - 320*FRACUNIT;
z = 128 + P_Random()*2*FRACUNIT;
th = P_SpawnMobj (x,y,z, MT_ROCKET);
th->momz = P_Random()*512;
P_SetMobjState (th, S_BRAINEXPLODE1);
th->tics -= P_Random()&7;
if (th->tics < 1)
th->tics = 1;
}
S_StartSound (NULL,sfx_bosdth);
}
void A_BrainExplode (mobj_t* mo, void * )
{
int x;
int y;
int z;
mobj_t* th;
x = mo->x + (P_Random () - P_Random ())*2048;
y = mo->y;
z = 128 + P_Random()*2*FRACUNIT;
th = P_SpawnMobj (x,y,z, MT_ROCKET);
th->momz = P_Random()*512;
P_SetMobjState (th, S_BRAINEXPLODE1);
th->tics -= P_Random()&7;
if (th->tics < 1)
th->tics = 1;
}
void A_BrainDie (mobj_t* mo, void * )
{
G_ExitLevel ();
}
void A_BrainSpit (mobj_t* mo, void * )
{
mobj_t* targ;
mobj_t* newmobj;
::g->easy ^= 1;
if (::g->gameskill <= sk_easy && (!::g->easy))
return;
if ( 1 ) {
// count number of thinkers
int numCorpse = 0;
int numEnemies = 0;
for ( thinker_t* th = ::g->thinkercap.next; th != &::g->thinkercap; th = th->next ) {
if ( th->function.acp1 == (actionf_p1)P_MobjThinker ) {
mobj_t* obj = (mobj_t*)th;
if ( obj->flags & MF_CORPSE ) {
numCorpse++;
}
else if ( obj->type > MT_PLAYER && obj->type < MT_KEEN ) {
numEnemies++;
}
}
}
if ( numCorpse > 48 ) {
for ( int i = 0; i < 12; i++ ) {
for ( thinker_t* th = ::g->thinkercap.next; th != &::g->thinkercap; th = th->next ) {
if ( th->function.acp1 == (actionf_p1)P_MobjThinker ) {
mobj_t* obj = (mobj_t*)th;
if ( obj->flags & MF_CORPSE ) {
P_RemoveMobj( obj );
break;
}
}
}
}
}
if ( numEnemies > 32 ) {
return;
}
}
// shoot a cube at current target
targ = ::g->braintargets[::g->braintargeton];
::g->braintargeton = (::g->braintargeton+1) % ::g->numbraintargets;
// spawn brain missile
newmobj = P_SpawnMissile (mo, targ, MT_SPAWNSHOT);
newmobj->target = targ;
newmobj->reactiontime =
((targ->y - mo->y)/newmobj->momy) / newmobj->state->tics;
S_StartSound(NULL, sfx_bospit);
}
void A_SpawnFly (mobj_t* mo, void * );
// travelling cube sound
void A_SpawnSound (mobj_t* mo, void * )
{
S_StartSound (mo,sfx_boscub);
A_SpawnFly(mo, 0);
}
void A_SpawnFly (mobj_t* mo, void * )
{
mobj_t* newmobj;
mobj_t* fog;
mobj_t* targ;
int r;
mobjtype_t type;
if (--mo->reactiontime)
return; // still flying
targ = mo->target;
// First spawn teleport fog.
fog = P_SpawnMobj (targ->x, targ->y, targ->z, MT_SPAWNFIRE);
S_StartSound (fog, sfx_telept);
// Randomly select monster to spawn.
r = P_Random ();
// Probability distribution (kind of :),
// decreasing likelihood.
if ( r<50 )
type = MT_TROOP;
else if (r<90)
type = MT_SERGEANT;
else if (r<120)
type = MT_SHADOWS;
else if (r<130)
type = MT_PAIN;
else if (r<160)
type = MT_HEAD;
else if (r<162)
type = MT_VILE;
else if (r<172)
type = MT_UNDEAD;
else if (r<192)
type = MT_BABY;
else if (r<222)
type = MT_FATSO;
else if (r<246)
type = MT_KNIGHT;
else
type = MT_BRUISER;
newmobj = P_SpawnMobj (targ->x, targ->y, targ->z, type);
if (P_LookForPlayers (newmobj, true) )
P_SetMobjState (newmobj, (statenum_t)newmobj->info->seestate);
// telefrag anything in this spot
P_TeleportMove (newmobj, newmobj->x, newmobj->y);
// remove self (i.e., cube).
P_RemoveMobj (mo);
}
void A_PlayerScream (mobj_t* mo, void * )
{
// Default death sound.
int sound = sfx_pldeth;
if ( (::g->gamemode == commercial)
&& (mo->health < -50))
{
// IF THE PLAYER DIES
// LESS THAN -50% WITHOUT GIBBING
sound = sfx_pdiehi;
}
if ( ::g->demoplayback || globalNetworking || (mo == ::g->players[::g->consoleplayer].mo))
S_StartSound (mo, sound);
}
}; // extern "C"
| 19.413997 | 366 | 0.595796 | 1337programming |
fc43ea46a0892b483d460302adfe7819245a1228 | 8,623 | cc | C++ | ui/ozone/platform/wayland/wayland_pointer_unittest.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2017-02-01T08:49:08.000Z | 2018-02-03T06:14:48.000Z | ui/ozone/platform/wayland/wayland_pointer_unittest.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 1 | 2016-07-11T15:19:20.000Z | 2017-04-02T20:38:55.000Z | ui/ozone/platform/wayland/wayland_pointer_unittest.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.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 <linux/input.h>
#include <wayland-server.h>
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/event.h"
#include "ui/ozone/platform/wayland/fake_server.h"
#include "ui/ozone/platform/wayland/mock_platform_window_delegate.h"
#include "ui/ozone/platform/wayland/wayland_test.h"
#include "ui/ozone/platform/wayland/wayland_window.h"
using ::testing::SaveArg;
using ::testing::_;
namespace ui {
class WaylandPointerTest : public WaylandTest {
public:
WaylandPointerTest() {}
void SetUp() override {
WaylandTest::SetUp();
wl_seat_send_capabilities(server.seat()->resource(),
WL_SEAT_CAPABILITY_POINTER);
Sync();
pointer = server.seat()->pointer.get();
ASSERT_TRUE(pointer);
}
protected:
wl::MockPointer* pointer;
private:
DISALLOW_COPY_AND_ASSIGN(WaylandPointerTest);
};
TEST_F(WaylandPointerTest, Leave) {
MockPlatformWindowDelegate other_delegate;
WaylandWindow other_window(&other_delegate, &display,
gfx::Rect(0, 0, 10, 10));
gfx::AcceleratedWidget other_widget = gfx::kNullAcceleratedWidget;
EXPECT_CALL(other_delegate, OnAcceleratedWidgetAvailable(_, _))
.WillOnce(SaveArg<0>(&other_widget));
ASSERT_TRUE(other_window.Initialize());
ASSERT_NE(other_widget, gfx::kNullAcceleratedWidget);
Sync();
wl::MockSurface* other_surface =
server.GetObject<wl::MockSurface>(other_widget);
ASSERT_TRUE(other_surface);
wl_pointer_send_enter(pointer->resource(), 1, surface->resource(), 0, 0);
wl_pointer_send_leave(pointer->resource(), 2, surface->resource());
wl_pointer_send_enter(pointer->resource(), 3, other_surface->resource(), 0,
0);
wl_pointer_send_button(pointer->resource(), 4, 1004, BTN_LEFT,
WL_POINTER_BUTTON_STATE_PRESSED);
EXPECT_CALL(delegate, DispatchEvent(_)).Times(0);
// Do an extra Sync() here so that we process the second enter event before we
// destroy |other_window|.
Sync();
}
ACTION_P(CloneEvent, ptr) {
*ptr = Event::Clone(*arg0);
}
TEST_F(WaylandPointerTest, Motion) {
wl_pointer_send_enter(pointer->resource(), 1, surface->resource(), 0, 0);
wl_pointer_send_motion(pointer->resource(), 1002, wl_fixed_from_double(10.75),
wl_fixed_from_double(20.375));
std::unique_ptr<Event> event;
EXPECT_CALL(delegate, DispatchEvent(_)).WillOnce(CloneEvent(&event));
Sync();
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
auto mouse_event = static_cast<MouseEvent*>(event.get());
EXPECT_EQ(ET_MOUSE_MOVED, mouse_event->type());
EXPECT_EQ(0, mouse_event->button_flags());
EXPECT_EQ(0, mouse_event->changed_button_flags());
// TODO(forney): Once crbug.com/337827 is solved, compare with the fractional
// coordinates sent above.
EXPECT_EQ(gfx::PointF(10, 20), mouse_event->location_f());
EXPECT_EQ(gfx::PointF(10, 20), mouse_event->root_location_f());
}
TEST_F(WaylandPointerTest, MotionDragged) {
wl_pointer_send_enter(pointer->resource(), 1, surface->resource(), 0, 0);
wl_pointer_send_button(pointer->resource(), 2, 1002, BTN_MIDDLE,
WL_POINTER_BUTTON_STATE_PRESSED);
Sync();
std::unique_ptr<Event> event;
EXPECT_CALL(delegate, DispatchEvent(_)).WillOnce(CloneEvent(&event));
wl_pointer_send_motion(pointer->resource(), 1003, wl_fixed_from_int(400),
wl_fixed_from_int(500));
Sync();
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
auto mouse_event = static_cast<MouseEvent*>(event.get());
EXPECT_EQ(ET_MOUSE_DRAGGED, mouse_event->type());
EXPECT_EQ(EF_MIDDLE_MOUSE_BUTTON, mouse_event->button_flags());
EXPECT_EQ(0, mouse_event->changed_button_flags());
EXPECT_EQ(gfx::PointF(400, 500), mouse_event->location_f());
EXPECT_EQ(gfx::PointF(400, 500), mouse_event->root_location_f());
}
TEST_F(WaylandPointerTest, ButtonPress) {
wl_pointer_send_enter(pointer->resource(), 1, surface->resource(),
wl_fixed_from_int(200), wl_fixed_from_int(150));
wl_pointer_send_button(pointer->resource(), 2, 1002, BTN_RIGHT,
WL_POINTER_BUTTON_STATE_PRESSED);
Sync();
std::unique_ptr<Event> event;
EXPECT_CALL(delegate, DispatchEvent(_)).WillOnce(CloneEvent(&event));
wl_pointer_send_button(pointer->resource(), 3, 1003, BTN_LEFT,
WL_POINTER_BUTTON_STATE_PRESSED);
Sync();
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
auto mouse_event = static_cast<MouseEvent*>(event.get());
EXPECT_EQ(ET_MOUSE_PRESSED, mouse_event->type());
EXPECT_EQ(EF_LEFT_MOUSE_BUTTON | EF_RIGHT_MOUSE_BUTTON,
mouse_event->button_flags());
EXPECT_EQ(EF_LEFT_MOUSE_BUTTON, mouse_event->changed_button_flags());
EXPECT_EQ(gfx::PointF(200, 150), mouse_event->location_f());
EXPECT_EQ(gfx::PointF(200, 150), mouse_event->root_location_f());
}
TEST_F(WaylandPointerTest, ButtonRelease) {
wl_pointer_send_enter(pointer->resource(), 1, surface->resource(),
wl_fixed_from_int(50), wl_fixed_from_int(50));
wl_pointer_send_button(pointer->resource(), 2, 1002, BTN_BACK,
WL_POINTER_BUTTON_STATE_PRESSED);
wl_pointer_send_button(pointer->resource(), 3, 1003, BTN_LEFT,
WL_POINTER_BUTTON_STATE_PRESSED);
Sync();
std::unique_ptr<Event> event;
EXPECT_CALL(delegate, DispatchEvent(_)).WillOnce(CloneEvent(&event));
wl_pointer_send_button(pointer->resource(), 4, 1004, BTN_LEFT,
WL_POINTER_BUTTON_STATE_RELEASED);
Sync();
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseEvent());
auto mouse_event = static_cast<MouseEvent*>(event.get());
EXPECT_EQ(ET_MOUSE_RELEASED, mouse_event->type());
EXPECT_EQ(EF_LEFT_MOUSE_BUTTON | EF_BACK_MOUSE_BUTTON,
mouse_event->button_flags());
EXPECT_EQ(EF_LEFT_MOUSE_BUTTON, mouse_event->changed_button_flags());
EXPECT_EQ(gfx::PointF(50, 50), mouse_event->location_f());
EXPECT_EQ(gfx::PointF(50, 50), mouse_event->root_location_f());
}
TEST_F(WaylandPointerTest, AxisVertical) {
wl_pointer_send_enter(pointer->resource(), 1, surface->resource(),
wl_fixed_from_int(0), wl_fixed_from_int(0));
wl_pointer_send_button(pointer->resource(), 2, 1002, BTN_RIGHT,
WL_POINTER_BUTTON_STATE_PRESSED);
Sync();
std::unique_ptr<Event> event;
EXPECT_CALL(delegate, DispatchEvent(_)).WillOnce(CloneEvent(&event));
// Wayland servers typically send a value of 10 per mouse wheel click.
wl_pointer_send_axis(pointer->resource(), 1003,
WL_POINTER_AXIS_VERTICAL_SCROLL, wl_fixed_from_int(20));
Sync();
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseWheelEvent());
auto mouse_wheel_event = static_cast<MouseWheelEvent*>(event.get());
EXPECT_EQ(gfx::Vector2d(0, -2 * MouseWheelEvent::kWheelDelta),
mouse_wheel_event->offset());
EXPECT_EQ(EF_RIGHT_MOUSE_BUTTON, mouse_wheel_event->button_flags());
EXPECT_EQ(0, mouse_wheel_event->changed_button_flags());
EXPECT_EQ(gfx::PointF(), mouse_wheel_event->location_f());
EXPECT_EQ(gfx::PointF(), mouse_wheel_event->root_location_f());
}
TEST_F(WaylandPointerTest, AxisHorizontal) {
wl_pointer_send_enter(pointer->resource(), 1, surface->resource(),
wl_fixed_from_int(50), wl_fixed_from_int(75));
wl_pointer_send_button(pointer->resource(), 2, 1002, BTN_LEFT,
WL_POINTER_BUTTON_STATE_PRESSED);
Sync();
std::unique_ptr<Event> event;
EXPECT_CALL(delegate, DispatchEvent(_)).WillOnce(CloneEvent(&event));
// Wayland servers typically send a value of 10 per mouse wheel click.
wl_pointer_send_axis(pointer->resource(), 1003,
WL_POINTER_AXIS_HORIZONTAL_SCROLL,
wl_fixed_from_int(10));
Sync();
ASSERT_TRUE(event);
ASSERT_TRUE(event->IsMouseWheelEvent());
auto mouse_wheel_event = static_cast<MouseWheelEvent*>(event.get());
EXPECT_EQ(gfx::Vector2d(MouseWheelEvent::kWheelDelta, 0),
mouse_wheel_event->offset());
EXPECT_EQ(EF_LEFT_MOUSE_BUTTON, mouse_wheel_event->button_flags());
EXPECT_EQ(0, mouse_wheel_event->changed_button_flags());
EXPECT_EQ(gfx::PointF(50, 75), mouse_wheel_event->location_f());
EXPECT_EQ(gfx::PointF(50, 75), mouse_wheel_event->root_location_f());
}
} // namespace ui
| 37.008584 | 80 | 0.708222 | Wzzzx |
fc46f81abc7ae8be166f4cabead98178c3e38f0a | 7,157 | cpp | C++ | source/NanairoCore/Color/spectral_transport.cpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 30 | 2015-09-06T03:14:29.000Z | 2021-06-18T11:00:19.000Z | source/NanairoCore/Color/spectral_transport.cpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 31 | 2016-01-14T14:50:34.000Z | 2018-06-25T13:21:48.000Z | source/NanairoCore/Color/spectral_transport.cpp | byzin/Nanairo | 23fb6deeec73509c538a9c21009e12be63e8d0e4 | [
"MIT"
] | 6 | 2017-04-09T13:07:47.000Z | 2021-05-29T21:17:34.000Z | /*!
\file spectral_transport.cpp
\author Sho Ikeda
Copyright (c) 2015-2018 Sho Ikeda
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
#include "spectral_transport.hpp"
// Standard C++ library
#include <cmath>
#include <vector>
// Zisc
#include "zisc/arith_array.hpp"
#include "zisc/error.hpp"
#include "zisc/matrix.hpp"
#include "zisc/memory_resource.hpp"
#include "zisc/utility.hpp"
// Nanairo
#include "color.hpp"
#include "color_conversion.hpp"
#include "xyz_color.hpp"
#include "xyz_color_matching_function.hpp"
#include "yxy_color.hpp"
#include "NanairoCore/nanairo_core_config.hpp"
#include "NanairoCore/Color/SpectralTransportParameter/spectral_transport_parameters.hpp"
#include "SpectralDistribution/spectral_distribution.hpp"
namespace nanairo {
/*!
*/
constexpr std::array<int, 2> SpectralTransport::gridResolution() noexcept
{
using zisc::cast;
return std::array<int, 2>{{cast<int>(spectral_transport::kGridResolution[0]),
cast<int>(spectral_transport::kGridResolution[1])}};
}
/*!
*/
constexpr int SpectralTransport::gridSize() noexcept
{
using zisc::cast;
return cast<int>(spectral_transport::kGridResolution[0] *
spectral_transport::kGridResolution[1]);
}
/*!
*/
void SpectralTransport::toSpectra(
const XyzColor& xyz,
SpectralDistribution* spectra,
zisc::pmr::memory_resource* work_resource) noexcept
{
using zisc::cast;
const auto yxy = ColorConversion::toYxy(xyz);
const auto uv = toUv(yxy); // Rotate to align with grid
constexpr auto grid_res = gridResolution();
if (zisc::isInBounds(uv[0], 0.0, cast<Float>(grid_res[0])) &&
zisc::isInBounds(uv[1], 0.0, cast<Float>(grid_res[1]))) {
std::array<int, 2> uvi{{cast<int>(uv[0]), cast<int>(uv[1])}};
const int cell_index = uvi[0] + grid_res[0] * uvi[1];
ZISC_ASSERT(zisc::isInBounds(cell_index, 0, gridSize()),
"The cell index is out of range.");
for (uint i = 0; i < spectra->size(); ++i) {
const uint16 lambda = spectra->getWavelength(i);
Float spectrum = toSpectrum(lambda, cell_index, uv, work_resource);
// Now we have a spectrum which corresponds to the xy chromaticities of the input.
// Need to scale according to the input brightness X+Y+Z now
spectrum = spectrum * (xyz.x() + xyz.y() + xyz.z());
// The division by equal energy reflectance is here to make sure
// that xyz = (1, 1, 1) maps to a spectrum that is constant 1.
spectrum = spectrum * spectral_transport::kInvEqualEnergyReflectance;
spectra->set(i, spectrum);
}
}
}
/*!
*/
inline
zisc::ArithArray<Float, 3> SpectralTransport::hom(
const zisc::ArithArray<Float, 2>& x) noexcept
{
return zisc::ArithArray<Float, 3>{x[0], x[1], 1.0};
}
/*!
*/
inline
zisc::ArithArray<Float, 2> SpectralTransport::dehom(
const zisc::ArithArray<Float, 3>& x) noexcept
{
return zisc::ArithArray<Float, 2>{x[0] / x[2], x[1] / x[2]};
}
/*!
*/
Float SpectralTransport::toSpectrum(
const uint16 lambda,
const int cell_index,
const UvColor& uv,
zisc::pmr::memory_resource* work_resource) noexcept
{
using zisc::cast;
const auto& cell = spectral_transport::kGrid[cell_index];
// Get Linearly interpolated spectral power for the corner vertices.
zisc::pmr::vector<Float> p{work_resource};
p.resize(cell.num_points_, 0.0);
// This clamping is only necessary if lambda is not sure to be [min, max].
constexpr int spectra_size = cast<int>(CoreConfig::spectraSize());
const Float sb =
cast<Float>(lambda - CoreConfig::shortestWavelength()) /
cast<Float>(CoreConfig::longestWavelength()-CoreConfig::shortestWavelength()) *
cast<Float>(spectra_size - 1);
const int sb0 = cast<int>(sb);
const int sb1 = (sb0 + 1 < spectra_size) ? sb0 + 1 : sb0;
ZISC_ASSERT(zisc::isInBounds(sb0, 0, spectra_size), "The sb0 is out of range.");
ZISC_ASSERT(zisc::isInBounds(sb1, 0, spectra_size), "The sb1 is out of range.");
const Float sbf = sb - cast<Float>(sb0);
for (int i = 0; i < cast<int>(p.size()); ++i) {
ZISC_ASSERT(0 <= cell.indices_[i], "The index is minus.");
const auto& point = spectral_transport::kDataPoints[cell.indices_[i]];
p[i] = (1.0 - sbf) * point.spectra_[sb0] + sbf * point.spectra_[sb1];
}
Float interpolated_p = 0.0;
if (cell.inside_) {
// fast path for normal inner quads
const UvColor uvf{uv[0] - std::floor(uv[0]), uv[1] - std::floor(uv[1])};
ZISC_ASSERT(zisc::isInBounds(uvf[0], 0.0, 1.0), "The uvf[0] is out of range.");
ZISC_ASSERT(zisc::isInBounds(uvf[1], 0.0, 1.0), "The uvf[1] is out of range.");
// The layout of the vertices in the quad is:
// 2 3
// 0 1
interpolated_p =
p[0] * (1.0 - uvf[0]) * (1.0 - uvf[1]) +
p[2] * (1.0 - uvf[0]) * uvf[1] +
p[3] * uvf[0] * uvf[1] +
p[1] * uvf[0] * (1.0 - uvf[1]);
}
else {
// Need to go through triangulation
// We get the indices in such an order that they form a triangle fan around idx[0]
// Compute barycentric coordinates of our xy* point for all triangles in the fan:
const auto& point0 = spectral_transport::kDataPoints[cell.indices_[0]];
const auto& point1 = spectral_transport::kDataPoints[cell.indices_[1]];
const auto e = uv.data() - point0.uv_.data();
auto e0 = point1.uv_.data() - point0.uv_.data();
Float uu = e0[0] * e[1] - e[0] * e0[1];
for (int i = 0; i < cast<int>(cell.num_points_ - 1); ++i) {
zisc::ArithArray<Float, 2> e1{0.0, 0.0};
if (i == cast<int>(cell.num_points_ - 2)) // Close the circle
e1 = point1.uv_.data() - point0.uv_.data();
else
e1 = spectral_transport::kDataPoints[cell.indices_[i + 2]].uv_.data() - point0.uv_.data();
const Float vv = e[0] * e1[1] - e1[0] * e[1];
//! \todo with some sign magic, this division could be deferred to the last iteration!
const Float area = e0[0] * e1[1] - e1[0] * e0[1];
// normalize
const Float u = uu / area;
const Float v = vv / area;
const Float w = 1.0 - (u + v);
if ((u < 0.0) || (v < 0.0) || (w < 0.0)) {
uu = -vv;
e0 = e1;
continue;
}
// This seems to be triangle we've been looking for .
interpolated_p = p[0] * w +
p[i + 1] * v +
p[(i == cast<int>(cell.num_points_ - 2)) ? 1 : (i+2)] * u;
break;
}
}
return interpolated_p;
}
/*!
*/
inline
auto SpectralTransport::toUv(const YxyColor& yxy) noexcept -> UvColor
{
zisc::Matrix<Float, 3, 1> v3{yxy.x(),
yxy.y(),
1.0};
const auto v2 = spectral_transport::kToUvFromXy * v3;
return UvColor{v2(0, 0), v2(1, 0)};
}
/*!
*/
inline
auto SpectralTransport::toXystar(const YxyColor& yxy) noexcept -> XystarColor
{
zisc::Matrix<Float, 3, 1> v3{yxy.x(),
yxy.y(),
1.0};
const auto v2 = spectral_transport::kToXystarFromXy * v3;
return XystarColor{v2(0, 0), v2(1, 0)};
}
} // namespace nanairo
| 34.244019 | 98 | 0.623585 | byzin |
fc491731ed86969ef7c98516499272f89a2775e6 | 751 | cpp | C++ | LeetCode/Check If It Is a Straight Line.cpp | Rupali409/CPP-Questions-and-Solutions | a42664302f18b7d99aac2501bcf956950e3cc61a | [
"MIT"
] | 42 | 2021-09-26T18:02:52.000Z | 2022-03-15T01:52:15.000Z | LeetCode/Check If It Is a Straight Line.cpp | Rupali409/CPP-Questions-and-Solutions | a42664302f18b7d99aac2501bcf956950e3cc61a | [
"MIT"
] | 404 | 2021-09-24T19:55:10.000Z | 2021-11-03T05:47:47.000Z | LeetCode/Check If It Is a Straight Line.cpp | Rupali409/CPP-Questions-and-Solutions | a42664302f18b7d99aac2501bcf956950e3cc61a | [
"MIT"
] | 140 | 2021-09-22T20:50:04.000Z | 2022-01-22T16:59:09.000Z | //1232. Check If It Is a Straight Line
//https://leetcode.com/problems/check-if-it-is-a-straight-line/
class Solution {
public:
bool checkStraightLine(vector<vector<int>>& coordinates) {
//if points are two then return true
if(coordinates.size()==2)
return true;
else{
int x1=coordinates[0][0],x2=coordinates[1][0],y1=coordinates[0] [1],y2=coordinates[1][1];
for(int i=2;i<coordinates.size();i++){
int x= coordinates[i][0];
int y= coordinates[i][1];
//this is equation of line every points should satisfies this
if((y-y1)*(x2-x1)!=(y2-y1)*(x-x1))
return false;
}
}
return true;
}
}; | 34.136364 | 107 | 0.54727 | Rupali409 |
fc4fac1d8251d9a89d4ddce893b2d888961c4137 | 3,256 | hh | C++ | extras/android/cpp/jni/type_info.hh | mzdun/dashcam-gps | 7611a08792cac98c4fd1260111e3fc0e632e982b | [
"MIT"
] | 6 | 2020-02-14T00:46:16.000Z | 2021-04-07T09:29:06.000Z | extras/android/cpp/jni/type_info.hh | mzdun/dashcam-gps | 7611a08792cac98c4fd1260111e3fc0e632e982b | [
"MIT"
] | 1 | 2020-06-09T10:55:43.000Z | 2020-06-18T11:39:59.000Z | extras/android/cpp/jni/type_info.hh | mzdun/dashcam-gps | 7611a08792cac98c4fd1260111e3fc0e632e982b | [
"MIT"
] | 2 | 2020-06-17T13:20:22.000Z | 2021-04-11T10:18:03.000Z | #pragma once
#include <jni/fixed_string.hh>
#include <jni/primitive.hh>
#define DEFINE_PACKAGE(NAME) \
struct PACKAGE { \
static constexpr auto package_name() noexcept { \
return jni::fixed_string{NAME}; \
} \
}
#define DEFINE_NAME(CLS, NAME) \
struct CLS { \
static constexpr auto get_name() noexcept { \
return jni::fixed_string{NAME}; \
} \
}
namespace jni {
template <typename Type, typename = void>
struct type;
template <typename Type, typename = void>
struct conv;
#define SIMPLE_TYPE(TYPE, JNI_TYPE, CODE) \
template <> \
struct type<TYPE> { \
static constexpr auto name() noexcept { \
return jni::fixed_string{CODE}; \
} \
}; \
\
template <> \
struct conv<TYPE> { \
static JNI_TYPE unpack(TYPE const& wrapped) { \
return static_cast<JNI_TYPE>(wrapped); \
} \
static TYPE pack(JNI_TYPE jvm) { return TYPE{jvm}; } \
}
#define OBJECT_TYPE(TYPE, CODE) SIMPLE_TYPE(TYPE, jobject, CODE)
#define PRIMITIVE_TYPE(JNI_TYPE, CODE) \
template <> \
struct type<JNI_TYPE> { \
static constexpr auto name() noexcept { \
return jni::fixed_string{CODE}; \
} \
}; \
\
template <> \
struct conv<JNI_TYPE> { \
static JNI_TYPE unpack(JNI_TYPE jvm) { return jvm; } \
static JNI_TYPE pack(JNI_TYPE jvm) { return jvm; } \
}
#define JNI_PRIMITIVE_TYPE(JNI_TYPE, UNUSED, CODE) \
PRIMITIVE_TYPE(JNI_TYPE, CODE);
JNI_PRIMITIVES(JNI_PRIMITIVE_TYPE)
#undef JNI_PRIMITIVE_TYPE
template <>
struct type<void> {
static constexpr auto name() noexcept { return fixed_string{"V"}; }
};
PRIMITIVE_TYPE(jobject, "Ljava/lang/Object;");
PRIMITIVE_TYPE(jstring, "Ljava/lang/String;");
template <typename Type>
struct type<Type const> : type<Type> {};
template <typename Type>
struct type<Type&> : type<Type> {};
template <typename Element>
struct array;
template <typename Element>
struct type<array<Element>> {
static constexpr auto name() noexcept {
return "[" + type<Element>::name();
}
};
template <typename Return, typename... Args>
struct type<Return(Args...)> {
static constexpr auto name() noexcept {
return fixed_string{"("} + (type<Args>::name() + ... + "") + ")" +
type<Return>::name();
}
};
} // namespace jni
| 35.391304 | 69 | 0.454853 | mzdun |
fc50a55cc736c6648c2783e8986f3273f30d7e85 | 1,658 | cpp | C++ | third_party/WebKit/Source/modules/battery/BatteryDispatcher.cpp | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 1 | 2020-09-15T08:43:34.000Z | 2020-09-15T08:43:34.000Z | third_party/WebKit/Source/modules/battery/BatteryDispatcher.cpp | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/modules/battery/BatteryDispatcher.cpp | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 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 "modules/battery/BatteryDispatcher.h"
#include "platform/mojo/MojoHelper.h"
#include "public/platform/Platform.h"
#include "public/platform/ServiceRegistry.h"
#include "wtf/Assertions.h"
#include "wtf/PassOwnPtr.h"
namespace blink {
BatteryDispatcher& BatteryDispatcher::instance()
{
DEFINE_STATIC_LOCAL(BatteryDispatcher, batteryDispatcher, (new BatteryDispatcher));
return batteryDispatcher;
}
BatteryDispatcher::BatteryDispatcher()
: m_hasLatestData(false)
{
}
void BatteryDispatcher::queryNextStatus()
{
m_monitor->QueryNextStatus(createBaseCallback(bind<device::blink::BatteryStatusPtr>(&BatteryDispatcher::onDidChange, this)));
}
void BatteryDispatcher::onDidChange(device::blink::BatteryStatusPtr batteryStatus)
{
queryNextStatus();
ASSERT(batteryStatus);
updateBatteryStatus(BatteryStatus(
batteryStatus->charging,
batteryStatus->charging_time,
batteryStatus->discharging_time,
batteryStatus->level));
}
void BatteryDispatcher::updateBatteryStatus(const BatteryStatus& batteryStatus)
{
m_batteryStatus = batteryStatus;
m_hasLatestData = true;
notifyControllers();
}
void BatteryDispatcher::startListening()
{
ASSERT(!m_monitor.is_bound());
Platform::current()->serviceRegistry()->connectToRemoteService(
mojo::GetProxy(&m_monitor));
queryNextStatus();
}
void BatteryDispatcher::stopListening()
{
m_monitor.reset();
m_hasLatestData = false;
}
} // namespace blink
| 25.121212 | 129 | 0.750905 | maidiHaitai |
fc5331a99186004a962c248eca1c15102f755776 | 1,230 | cpp | C++ | tests/djvGLTest/OffscreenBufferFuncTest.cpp | pafri/DJV | 9db15673b6b03ad3743f57119118261b1fbe8810 | [
"BSD-3-Clause"
] | null | null | null | tests/djvGLTest/OffscreenBufferFuncTest.cpp | pafri/DJV | 9db15673b6b03ad3743f57119118261b1fbe8810 | [
"BSD-3-Clause"
] | null | null | null | tests/djvGLTest/OffscreenBufferFuncTest.cpp | pafri/DJV | 9db15673b6b03ad3743f57119118261b1fbe8810 | [
"BSD-3-Clause"
] | null | null | null | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2020 Darby Johnston
// All rights reserved.
#include <djvGLTest/OffscreenBufferFuncTest.h>
#include <djvGL/OffscreenBufferFunc.h>
#include <sstream>
using namespace djv::Core;
using namespace djv::GL;
namespace djv
{
namespace GLTest
{
OffscreenBufferFuncTest::OffscreenBufferFuncTest(
const System::File::Path& tempPath,
const std::shared_ptr<System::Context>& context) :
ITest("djv::GLTest::OffscreenBufferFuncTest", tempPath, context)
{}
void OffscreenBufferFuncTest::run()
{
_enum();
}
void OffscreenBufferFuncTest::_enum()
{
for (const auto& i : getOffscreenDepthTypeEnums())
{
std::stringstream ss;
ss << i;
_print("Depth type: " + _getText(ss.str()));
}
for (const auto& i : getOffscreenSamplingEnums())
{
std::stringstream ss;
ss << i;
_print("Offscreen sampling: " + _getText(ss.str()));
}
}
} // namespace GLTest
} // namespace djv
| 25.102041 | 76 | 0.541463 | pafri |
fc54d632396443718dd3c4719540b37c041fe3b3 | 80,648 | cpp | C++ | unit_tests/undirected/unit_tests_gmw_skeleton_generator.cpp | ShoYamanishi/wailea | e6263ed238ae32233a58d169868a4a94bf03a30b | [
"MIT"
] | 4 | 2019-05-15T10:07:47.000Z | 2021-09-02T18:38:35.000Z | unit_tests/undirected/unit_tests_gmw_skeleton_generator.cpp | ShoYamanishi/wailea | e6263ed238ae32233a58d169868a4a94bf03a30b | [
"MIT"
] | 1 | 2021-06-18T17:31:13.000Z | 2021-06-18T17:31:13.000Z | unit_tests/undirected/unit_tests_gmw_skeleton_generator.cpp | ShoYamanishi/wailea | e6263ed238ae32233a58d169868a4a94bf03a30b | [
"MIT"
] | 1 | 2021-08-10T21:13:51.000Z | 2021-08-10T21:13:51.000Z | #include "gtest/gtest.h"
#include "undirected/gmw_skeleton_generator.hpp"
#include "undirected/tree_path_finder.hpp"
#include "undirected/tree_splitter.hpp"
namespace Wailea {
namespace Undirected {
class GMWSkeletonTests : public ::testing::Test {
protected:
GMWSkeletonTests(){;};
virtual ~GMWSkeletonTests(){;};
virtual void SetUp() {;};
virtual void TearDown() {;};
void setComponentEdgeType(
SPQRComponentEdge& e, enum SPQRComponentEdge::type t){e.mType = t;};
void setSPQRTreeEdgeParams(
SPQRComponentEdge& te,
edge_list_it_t e1,
edge_list_it_t e2,
node_list_it_t n1
) {
te.mTreeEdge = e1;
te.mVirtualPairEdge = e2;
te.mVirtualPairTreeNode = n1;
}
void setType(GMWSkeleton& skel, GMWSkeleton::type t){ skel.mType = t;}
void setTreeNodeType(SPQRTreeNode& tn, enum SPQRTreeNode::type t)
{tn.mType = t;}
void setBlockNodes(GMWSkeleton& skel, vector<node_list_it_t>& ns){
for (auto it : ns) { skel.mBlockNodes.push_back(it); }
}
void setBlockNit11(GMWSkeleton& skel, node_list_it_t nit){
skel.mBlockNit11 = nit;
}
void setBlockNit12(GMWSkeleton& skel, node_list_it_t nit){
skel.mBlockNit12 = nit;
}
void setBlockNit21(GMWSkeleton& skel, node_list_it_t nit){
skel.mBlockNit21 = nit;
}
void setBlockNit22(GMWSkeleton& skel, node_list_it_t nit){
skel.mBlockNit22 = nit;
}
void generateSkeleton(GMWSkeleton& skel){
skel.generateSkeleton();
}
bool checkSkelEdges(
Graph& g,
vector<edge_list_it_t>&edges,
size_t numVirtualEdges,
vector<edge_list_it_t>&virtualEdges
) {
if (g.numEdges() != edges.size() + numVirtualEdges){
return false;
}
vector<int> counters;
for (int i = 0; i < g.numEdges(); i++) {counters.push_back(0);}
int index = 0;
for (auto eit = g.edges().first; eit != g.edges().second; eit++) {
auto& SE = dynamic_cast<GMWSkeletonEdge&>(*(*eit));
for (auto e : edges) {
if (SE.IGBackwardLink() == e && SE.mVirtual == false) {
counters[index] = counters[index] + 1;
}
}
index++;
}
size_t ve = 0;
index = 0;
for (auto eit = g.edges().first; eit != g.edges().second; eit++) {
auto& SE = dynamic_cast<GMWSkeletonEdge&>(*(*eit));
if (counters[index] != 1) {
if (counters[index] == 0&& SE.mVirtual == true) {
virtualEdges.push_back(eit);
ve++;
}
else {
return false;
}
}
index++;
}
if (ve != numVirtualEdges) {
return false;
}
return true;
}
};
/** @brief Tests GMWSkeleton::generateSkeleton()
*/
TEST_F(GMWSkeletonTests, Test1) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeleton skel;
// END1_NODE_END2_NODE
setType(skel, GMWSkeleton::END1_NODE_END2_NODE);
vector<node_list_it_t> blockNodes;
blockNodes.push_back(bn_01.backIt());
blockNodes.push_back(bn_02.backIt());
blockNodes.push_back(bn_03.backIt());
blockNodes.push_back(bn_04.backIt());
blockNodes.push_back(bn_05.backIt());
blockNodes.push_back(bn_06.backIt());
blockNodes.push_back(bn_07.backIt());
blockNodes.push_back(bn_08.backIt());
setBlockNodes(skel, blockNodes);
setBlockNit11(skel, bn_01.backIt());
setBlockNit21(skel, bn_02.backIt());
generateSkeleton(skel);
Graph& sk = skel.graph();
EXPECT_EQ(sk.numNodes(), 8);
auto sknit = sk.nodes().first;
auto& sn_01 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_01.IGBackwardLink(), bn_01.backIt());
sknit++;
auto& sn_02 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_02.IGBackwardLink(), bn_02.backIt());
sknit++;
auto& sn_03 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_03.IGBackwardLink(), bn_03.backIt());
sknit++;
auto& sn_04 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_04.IGBackwardLink(), bn_04.backIt());
sknit++;
auto& sn_05 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_05.IGBackwardLink(), bn_05.backIt());
sknit++;
auto& sn_06 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_06.IGBackwardLink(), bn_06.backIt());
sknit++;
auto& sn_07 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_07.IGBackwardLink(), bn_07.backIt());
sknit++;
auto& sn_08 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_08.IGBackwardLink(), bn_08.backIt());
EXPECT_EQ(sk.numEdges(), 11);
vector<edge_list_it_t> skelEdgesTested;
vector<edge_list_it_t> virtualEdges;
skelEdgesTested.push_back(be_01_02.backIt());
skelEdgesTested.push_back(be_01_03.backIt());
skelEdgesTested.push_back(be_01_07.backIt());
skelEdgesTested.push_back(be_02_04.backIt());
skelEdgesTested.push_back(be_02_08.backIt());
skelEdgesTested.push_back(be_03_04.backIt());
skelEdgesTested.push_back(be_03_05.backIt());
skelEdgesTested.push_back(be_04_06.backIt());
skelEdgesTested.push_back(be_05_06.backIt());
skelEdgesTested.push_back(be_05_07.backIt());
skelEdgesTested.push_back(be_06_08.backIt());
EXPECT_EQ(checkSkelEdges(sk, skelEdgesTested, 0, virtualEdges), true);
EXPECT_EQ(skel.mSkelNit1, sn_01.backIt());
EXPECT_EQ(skel.mSkelNit2, sn_02.backIt());
EXPECT_EQ(skel.mSkelEit1, sk.edges().second);
EXPECT_EQ(skel.mSkelEit2, sk.edges().second);
}
/** @brief Tests GMWSkeleton::generateSkeleton()
*/
TEST_F(GMWSkeletonTests, Test2) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeleton skel;
// END1_NODE_END2_NODE
setType(skel, GMWSkeleton::END1_NODE_END2_EDGE);
vector<node_list_it_t> blockNodes;
blockNodes.push_back(bn_01.backIt());
blockNodes.push_back(bn_02.backIt());
blockNodes.push_back(bn_03.backIt());
blockNodes.push_back(bn_04.backIt());
blockNodes.push_back(bn_05.backIt());
blockNodes.push_back(bn_06.backIt());
blockNodes.push_back(bn_07.backIt());
blockNodes.push_back(bn_08.backIt());
setBlockNodes(skel, blockNodes);
setBlockNit11(skel, bn_01.backIt());
setBlockNit21(skel, bn_07.backIt());
setBlockNit22(skel, bn_08.backIt());
generateSkeleton(skel);
Graph& sk = skel.graph();
EXPECT_EQ(sk.numNodes(), 8);
auto sknit = sk.nodes().first;
auto& sn_01 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_01.IGBackwardLink(), bn_01.backIt());
sknit++;
auto& sn_02 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_02.IGBackwardLink(), bn_02.backIt());
sknit++;
auto& sn_03 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_03.IGBackwardLink(), bn_03.backIt());
sknit++;
auto& sn_04 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_04.IGBackwardLink(), bn_04.backIt());
sknit++;
auto& sn_05 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_05.IGBackwardLink(), bn_05.backIt());
sknit++;
auto& sn_06 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_06.IGBackwardLink(), bn_06.backIt());
sknit++;
auto& sn_07 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_07.IGBackwardLink(), bn_07.backIt());
sknit++;
auto& sn_08 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_08.IGBackwardLink(), bn_08.backIt());
EXPECT_EQ(sk.numEdges(), 12);
vector<edge_list_it_t> skelEdgesTested;
vector<edge_list_it_t> virtualEdges;
skelEdgesTested.push_back(be_01_02.backIt());
skelEdgesTested.push_back(be_01_03.backIt());
skelEdgesTested.push_back(be_01_07.backIt());
skelEdgesTested.push_back(be_02_04.backIt());
skelEdgesTested.push_back(be_02_08.backIt());
skelEdgesTested.push_back(be_03_04.backIt());
skelEdgesTested.push_back(be_03_05.backIt());
skelEdgesTested.push_back(be_04_06.backIt());
skelEdgesTested.push_back(be_05_06.backIt());
skelEdgesTested.push_back(be_05_07.backIt());
skelEdgesTested.push_back(be_06_08.backIt());
EXPECT_EQ(checkSkelEdges(sk, skelEdgesTested, 1, virtualEdges), true);
EXPECT_EQ(skel.mSkelNit1, sn_01.backIt());
EXPECT_EQ(skel.mSkelNit2, sk.nodes().second);
EXPECT_EQ(skel.mSkelEit1, sk.edges().second);
EXPECT_EQ(skel.mSkelEit2, *(virtualEdges.begin()));
auto& VE2 = dynamic_cast<GMWSkeletonEdge&>(*(*skel.mSkelEit2));
EXPECT_EQ((&(VE2.incidentNode1()) == &sn_07 &&
&(VE2.incidentNode2()) == &sn_08)||
(&(VE2.incidentNode1()) == &sn_08 &&
&(VE2.incidentNode2()) == &sn_07) , true);
}
/** @brief Tests GMWSkeleton::generateSkeleton()
*/
TEST_F(GMWSkeletonTests, Test3) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeleton skel;
setType(skel, GMWSkeleton::END1_EDGE_END2_NODE);
vector<node_list_it_t> blockNodes;
blockNodes.push_back(bn_10.backIt());
blockNodes.push_back(bn_12.backIt());
blockNodes.push_back(bn_17.backIt());
blockNodes.push_back(bn_18.backIt());
blockNodes.push_back(bn_19.backIt());
blockNodes.push_back(bn_20.backIt());
blockNodes.push_back(bn_21.backIt());
blockNodes.push_back(bn_22.backIt());
setBlockNodes(skel, blockNodes);
setBlockNit11(skel, bn_10.backIt());
setBlockNit12(skel, bn_12.backIt());
setBlockNit21(skel, bn_19.backIt());
generateSkeleton(skel);
Graph& sk = skel.graph();
EXPECT_EQ(sk.numNodes(), 8);
auto sknit = sk.nodes().first;
auto& sn_01 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_01.IGBackwardLink(), bn_10.backIt());
sknit++;
auto& sn_02 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_02.IGBackwardLink(), bn_12.backIt());
sknit++;
auto& sn_03 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_03.IGBackwardLink(), bn_17.backIt());
sknit++;
auto& sn_04 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_04.IGBackwardLink(), bn_18.backIt());
sknit++;
auto& sn_05 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_05.IGBackwardLink(), bn_19.backIt());
sknit++;
auto& sn_06 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_06.IGBackwardLink(), bn_20.backIt());
sknit++;
auto& sn_07 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_07.IGBackwardLink(), bn_21.backIt());
sknit++;
auto& sn_08 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_08.IGBackwardLink(), bn_22.backIt());
EXPECT_EQ(sk.numEdges(), 14);
vector<edge_list_it_t> skelEdgesTested;
vector<edge_list_it_t> virtualEdges;
skelEdgesTested.push_back(be_10_17.backIt());
skelEdgesTested.push_back(be_12_17.backIt());
skelEdgesTested.push_back(be_10_18.backIt());
skelEdgesTested.push_back(be_12_18.backIt());
skelEdgesTested.push_back(be_17_18.backIt());
skelEdgesTested.push_back(be_12_21.backIt());
skelEdgesTested.push_back(be_12_19.backIt());
skelEdgesTested.push_back(be_18_20.backIt());
skelEdgesTested.push_back(be_18_22.backIt());
skelEdgesTested.push_back(be_19_20.backIt());
skelEdgesTested.push_back(be_19_21.backIt());
skelEdgesTested.push_back(be_20_22.backIt());
skelEdgesTested.push_back(be_21_22.backIt());
EXPECT_EQ(checkSkelEdges(sk, skelEdgesTested, 1, virtualEdges), true);
EXPECT_EQ(skel.mSkelNit1, sk.nodes().second);
EXPECT_EQ(skel.mSkelNit2, sn_05.backIt());
EXPECT_EQ(skel.mSkelEit1, *(virtualEdges.begin()));
EXPECT_EQ(skel.mSkelEit2, sk.edges().second);
auto& VE1 = dynamic_cast<GMWSkeletonEdge&>(*(*skel.mSkelEit1));
EXPECT_EQ((&(VE1.incidentNode1()) == &sn_01 &&
&(VE1.incidentNode2()) == &sn_02)||
(&(VE1.incidentNode1()) == &sn_02 &&
&(VE1.incidentNode2()) == &sn_01) , true);
}
/** @brief Tests GMWSkeleton::generateSkeleton()
*/
TEST_F(GMWSkeletonTests, Test4) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeleton skel;
setType(skel, GMWSkeleton::END1_EDGE_END2_EDGE);
vector<node_list_it_t> blockNodes;
blockNodes.push_back(bn_07.backIt());
blockNodes.push_back(bn_08.backIt());
blockNodes.push_back(bn_09.backIt());
blockNodes.push_back(bn_10.backIt());
blockNodes.push_back(bn_13.backIt());
blockNodes.push_back(bn_14.backIt());
blockNodes.push_back(bn_15.backIt());
blockNodes.push_back(bn_16.backIt());
setBlockNodes(skel, blockNodes);
setBlockNit11(skel, bn_07.backIt());
setBlockNit12(skel, bn_08.backIt());
setBlockNit21(skel, bn_09.backIt());
setBlockNit22(skel, bn_10.backIt());
generateSkeleton(skel);
Graph& sk = skel.graph();
EXPECT_EQ(sk.numNodes(), 8);
auto sknit = sk.nodes().first;
auto& sn_01 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_01.IGBackwardLink(), bn_07.backIt());
sknit++;
auto& sn_02 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_02.IGBackwardLink(), bn_08.backIt());
sknit++;
auto& sn_03 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_03.IGBackwardLink(), bn_09.backIt());
sknit++;
auto& sn_04 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_04.IGBackwardLink(), bn_10.backIt());
sknit++;
auto& sn_05 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_05.IGBackwardLink(), bn_13.backIt());
sknit++;
auto& sn_06 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_06.IGBackwardLink(), bn_14.backIt());
sknit++;
auto& sn_07 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_07.IGBackwardLink(), bn_15.backIt());
sknit++;
auto& sn_08 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_08.IGBackwardLink(), bn_16.backIt());
EXPECT_EQ(sk.numEdges(), 11);
vector<edge_list_it_t> skelEdgesTested;
vector<edge_list_it_t> virtualEdges;
skelEdgesTested.push_back(be_07_09.backIt());
skelEdgesTested.push_back(be_08_15.backIt());
skelEdgesTested.push_back(be_08_13.backIt());
skelEdgesTested.push_back(be_13_15.backIt());
skelEdgesTested.push_back(be_13_14.backIt());
skelEdgesTested.push_back(be_14_10.backIt());
skelEdgesTested.push_back(be_10_16.backIt());
skelEdgesTested.push_back(be_14_16.backIt());
skelEdgesTested.push_back(be_15_16.backIt());
EXPECT_EQ(checkSkelEdges(sk, skelEdgesTested, 2, virtualEdges), true);
EXPECT_EQ(skel.mSkelNit1, sk.nodes().second);
EXPECT_EQ(skel.mSkelNit2, sk.nodes().second);
EXPECT_EQ( (skel.mSkelEit1==*(virtualEdges.begin()) &&
skel.mSkelEit2==*(virtualEdges.rbegin()) )||
(skel.mSkelEit1==*(virtualEdges.begin()) &&
skel.mSkelEit2==*(virtualEdges.rbegin()) ), true);
auto& VE1 = dynamic_cast<GMWSkeletonEdge&>(*(*skel.mSkelEit1));
EXPECT_EQ((&(VE1.incidentNode1()) == &sn_01 &&
&(VE1.incidentNode2()) == &sn_02)||
(&(VE1.incidentNode1()) == &sn_02 &&
&(VE1.incidentNode2()) == &sn_01) , true);
auto& VE2 = dynamic_cast<GMWSkeletonEdge&>(*(*skel.mSkelEit2));
EXPECT_EQ((&(VE2.incidentNode1()) == &sn_03 &&
&(VE2.incidentNode2()) == &sn_04)||
(&(VE2.incidentNode1()) == &sn_04 &&
&(VE2.incidentNode2()) == &sn_03) , true);
}
class GMWSkeletonGeneratorTests : public ::testing::Test {
protected:
GMWSkeletonGeneratorTests(){;};
virtual ~GMWSkeletonGeneratorTests(){;};
virtual void SetUp() {;};
virtual void TearDown() {;};
void setComponentEdgeType(
SPQRComponentEdge& e, enum SPQRComponentEdge::type t){e.mType = t;};
void setSPQRTreeEdgeParams(
SPQRComponentEdge& te,
edge_list_it_t e1,
edge_list_it_t e2,
node_list_it_t n1
) {
te.mTreeEdge = e1;
te.mVirtualPairEdge = e2;
te.mVirtualPairTreeNode = n1;
}
void findTreeNodesFromBlockNodes(
GMWSkeletonGenerator& skel,
SPQRTree& T,
node_list_it_t bnit1,
node_list_it_t bnit2,
node_list_it_t& tnit1,
node_list_it_t& tnit2
){ skel.findTreeNodesFromBlockNodes(T, bnit1, bnit2, tnit1, tnit2); }
void findMinimalTreePath(
GMWSkeletonGenerator& skel,
list<node_list_it_t>& treePathNodes,
list<edge_list_it_t>& treePathEdges,
node_list_it_t bnit1,
node_list_it_t bnit2
){ skel.findMinimalTreePath(treePathNodes, treePathEdges, bnit1, bnit2); }
vector<node_list_it_t> fromTreeNodesToSkeletonNodes(
GMWSkeletonGenerator& skel,
list<node_list_it_t> treeNodes
){ return skel.fromTreeNodesToSkeletonNodes(treeNodes); }
bool checkNodes(
vector<node_list_it_t>& nodes1, vector<node_list_it_t>& nodes2) {
if (nodes1.size() != nodes2.size()){
return false;
}
vector<int> counters;
for (int i = 0; i < nodes1.size(); i++) {counters.push_back(0);}
int index = 0;
for (auto n1 : nodes1) {
for (auto n2 : nodes2) {
if (n1 == n2) {
counters[index] = counters[index] + 1;
}
}
index++;
}
for (auto c1 : counters) {
if (c1 != 1) {
return false;
}
}
return true;
}
bool isVirtualEdge(
GMWSkeletonGenerator& skelGen,
node_list_it_t tnit,
node_list_it_t bnit1,
node_list_it_t bnit2
) {
return skelGen.isVirtualEdge(tnit, bnit1, bnit2);
}
void generateSkeleton(GMWSkeleton& skel){
skel.generateSkeleton();
}
void setType(GMWSkeleton& skel, GMWSkeleton::type t){ skel.mType = t;}
void setBlockNodes(GMWSkeleton& skel, vector<node_list_it_t>& ns){
for (auto it : ns) { skel.mBlockNodes.push_back(it); }
}
void setBlockNit11(GMWSkeleton& skel, node_list_it_t nit){
skel.mBlockNit11 = nit;
}
void setBlockNit12(GMWSkeleton& skel, node_list_it_t nit){
skel.mBlockNit12 = nit;
}
void setBlockNit21(GMWSkeleton& skel, node_list_it_t nit){
skel.mBlockNit21 = nit;
}
void setBlockNit22(GMWSkeleton& skel, node_list_it_t nit){
skel.mBlockNit22 = nit;
}
void setTreeNodeType(SPQRTreeNode& tn, enum SPQRTreeNode::type t)
{tn.mType = t;}
bool checkSkelEdges(
Graph& g,
vector<edge_list_it_t>&edges,
size_t numVirtualEdges,
vector<edge_list_it_t>&virtualEdges
) {
if (g.numEdges() != edges.size() + numVirtualEdges){
return false;
}
vector<int> counters;
for (int i = 0; i < g.numEdges(); i++) {counters.push_back(0);}
int index = 0;
for (auto eit = g.edges().first; eit != g.edges().second; eit++) {
auto& SE = dynamic_cast<GMWSkeletonEdge&>(*(*eit));
for (auto e : edges) {
if (SE.IGBackwardLink() == e && SE.mVirtual == false) {
counters[index] = counters[index] + 1;
}
}
index++;
}
size_t ve = 0;
index = 0;
for (auto eit = g.edges().first; eit != g.edges().second; eit++) {
auto& SE = dynamic_cast<GMWSkeletonEdge&>(*(*eit));
if (counters[index] != 1) {
if (counters[index] == 0&& SE.mVirtual == true) {
virtualEdges.push_back(eit);
ve++;
}
else {
return false;
}
}
index++;
}
if (ve != numVirtualEdges) {
return false;
}
return true;
}
bool checkSkelNodes(
Graph& skel,
vector<node_list_it_t>& blockNodes,
vector<node_list_it_t>& skelNodes
) {
if (skel.numNodes() != blockNodes.size()){
return false;
}
skelNodes.clear();
vector<size_t> counters;
for (int i = 0; i < blockNodes.size(); i++) {
skelNodes.push_back(*blockNodes.end());
counters.push_back(0);
}
int index = 0;
for (auto n2 : blockNodes) {
for (auto n1=skel.nodes().first; n1!=skel.nodes().second; n1++) {
auto& SK = dynamic_cast<GMWSkeletonNode&>(*(*n1));
if (SK.IGBackwardLink() == n2) {
counters[index] = counters[index] + 1;
skelNodes[index] = n1;
}
}
index++;
}
for (auto c1 : counters) {
if (c1 != 1) {
return false;
}
}
return true;
}
};
/** @brief Tests GMWSkeletonGenerator::findTreeNodesFromBlockNodes().
*/
TEST_F(GMWSkeletonGeneratorTests, Test1) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeletonGenerator skel;
node_list_it_t tnit1;
node_list_it_t tnit2;
findTreeNodesFromBlockNodes(
skel, spqrTree, bn_01.backIt(), bn_02.backIt(), tnit1, tnit2);
EXPECT_EQ(tnit1, tn_01.backIt());
EXPECT_EQ(tnit2, tn_01.backIt());
findTreeNodesFromBlockNodes(
skel, spqrTree, bn_03.backIt(), bn_04.backIt(), tnit1, tnit2);
EXPECT_EQ(tnit1, tn_01.backIt());
EXPECT_EQ(tnit2, tn_01.backIt());
findTreeNodesFromBlockNodes(
skel, spqrTree, bn_05.backIt(), bn_06.backIt(), tnit1, tnit2);
EXPECT_EQ(tnit1, tn_01.backIt());
EXPECT_EQ(tnit2, tn_01.backIt());
findTreeNodesFromBlockNodes(
skel, spqrTree, bn_07.backIt(), bn_08.backIt(), tnit1, tnit2);
EXPECT_EQ(tnit1==tn_01.backIt()||tnit1==tn_02.backIt(), true);
EXPECT_EQ(tnit2==tn_01.backIt()||tnit2==tn_02.backIt()||
tnit2==tn_03.backIt(), true);
findTreeNodesFromBlockNodes(
skel, spqrTree, bn_09.backIt(), bn_10.backIt(), tnit1, tnit2);
EXPECT_EQ(tnit1==tn_02.backIt()||tnit1==tn_04.backIt()||
tnit1==tn_05.backIt(), true);
EXPECT_EQ(tnit2==tn_02.backIt()||tnit2==tn_03.backIt()||
tnit2==tn_04.backIt()||tnit2==tn_05.backIt()||
tnit2==tn_06.backIt()||tnit2==tn_07.backIt(), true);
findTreeNodesFromBlockNodes(
skel, spqrTree, bn_11.backIt(), bn_12.backIt(), tnit1, tnit2);
EXPECT_EQ(tnit1==tn_05.backIt(), true);
EXPECT_EQ(tnit2==tn_05.backIt()||tnit2==tn_06.backIt()||
tnit2==tn_07.backIt()||tnit2==tn_08.backIt()||
tnit2==tn_09.backIt(), true);
findTreeNodesFromBlockNodes(
skel, spqrTree, bn_13.backIt(), bn_14.backIt(), tnit1, tnit2);
EXPECT_EQ(tnit1==tn_03.backIt(), true);
EXPECT_EQ(tnit2==tn_03.backIt(), true);
findTreeNodesFromBlockNodes(
skel, spqrTree, bn_15.backIt(), bn_16.backIt(), tnit1, tnit2);
EXPECT_EQ(tnit1==tn_03.backIt(), true);
EXPECT_EQ(tnit2==tn_03.backIt(), true);
findTreeNodesFromBlockNodes(
skel, spqrTree, bn_17.backIt(), bn_18.backIt(), tnit1, tnit2);
EXPECT_EQ(tnit1==tn_07.backIt(), true);
EXPECT_EQ(tnit2==tn_07.backIt()||tnit2==tn_08.backIt()||
tnit2==tn_09.backIt(), true);
findTreeNodesFromBlockNodes(
skel, spqrTree, bn_19.backIt(), bn_20.backIt(), tnit1, tnit2);
EXPECT_EQ(tnit1==tn_09.backIt(), true);
EXPECT_EQ(tnit2==tn_09.backIt(), true);
findTreeNodesFromBlockNodes(
skel, spqrTree, bn_21.backIt(), bn_22.backIt(), tnit1, tnit2);
EXPECT_EQ(tnit1==tn_09.backIt(), true);
EXPECT_EQ(tnit2==tn_09.backIt(), true);
}
/** @brief Tests GMWSkeletonGenerator::findMinimalTreePath().
*/
TEST_F(GMWSkeletonGeneratorTests, Test2) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeletonGenerator skel;
list<node_list_it_t> nodes_01;
list<edge_list_it_t> edges_01;
nodes_01.push_back(tn_01.backIt());
nodes_01.push_back(tn_02.backIt());
nodes_01.push_back(tn_03.backIt());
edges_01.push_back(te_01_02.backIt());
edges_01.push_back(te_02_03.backIt());
findMinimalTreePath(
skel, nodes_01, edges_01, bn_07.backIt(), bn_08.backIt());
EXPECT_EQ(nodes_01.size(), 1);
EXPECT_EQ(edges_01.size(), 0);
EXPECT_EQ(*(nodes_01.begin())==tn_01.backIt()||
*(nodes_01.begin())==tn_02.backIt(), true);
list<node_list_it_t> nodes_02;
list<edge_list_it_t> edges_02;
nodes_02.push_back(tn_01.backIt());
nodes_02.push_back(tn_02.backIt());
nodes_02.push_back(tn_04.backIt());
nodes_02.push_back(tn_05.backIt());
nodes_02.push_back(tn_06.backIt());
nodes_02.push_back(tn_07.backIt());
edges_02.push_back(te_01_02.backIt());
edges_02.push_back(te_02_04.backIt());
edges_02.push_back(te_04_05.backIt());
edges_02.push_back(te_05_06.backIt());
edges_02.push_back(te_06_07.backIt());
findMinimalTreePath(
skel, nodes_02, edges_02, bn_08.backIt(), bn_12.backIt());
EXPECT_EQ(nodes_02.size(), 3);
EXPECT_EQ(edges_02.size(), 2);
auto neit = nodes_02.begin();
EXPECT_EQ(*neit, tn_02.backIt());
neit++;
EXPECT_EQ(*neit, tn_04.backIt());
neit++;
EXPECT_EQ(*neit, tn_05.backIt());
auto eeit = edges_02.begin();
EXPECT_EQ(*eeit, te_02_04.backIt());
eeit++;
EXPECT_EQ(*eeit, te_04_05.backIt());
list<node_list_it_t> nodes_03;
list<edge_list_it_t> edges_03;
nodes_03.push_back(tn_03.backIt());
nodes_03.push_back(tn_02.backIt());
nodes_03.push_back(tn_04.backIt());
nodes_03.push_back(tn_05.backIt());
nodes_03.push_back(tn_06.backIt());
nodes_03.push_back(tn_07.backIt());
nodes_03.push_back(tn_08.backIt());
nodes_03.push_back(tn_09.backIt());
edges_03.push_back(te_02_03.backIt());
edges_03.push_back(te_02_04.backIt());
edges_03.push_back(te_04_05.backIt());
edges_03.push_back(te_05_06.backIt());
edges_03.push_back(te_06_07.backIt());
edges_03.push_back(te_07_08.backIt());
edges_03.push_back(te_08_09.backIt());
findMinimalTreePath(
skel, nodes_03, edges_03, bn_13.backIt(), bn_22.backIt());
EXPECT_EQ(nodes_03.size(), 8);
EXPECT_EQ(edges_03.size(), 7);
}
/** @brief Tests GMWSkeletonGenerator::fromTreeNodesToSkeletonNodes().
*/
TEST_F(GMWSkeletonGeneratorTests, Test3) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeletonGenerator skel;
list<node_list_it_t> treeNodes_01;
treeNodes_01.push_back(tn_04.backIt());
vector<node_list_it_t> blockNodes_01 =
fromTreeNodesToSkeletonNodes(skel, treeNodes_01);
vector<node_list_it_t> blockNodesExpected_01;
blockNodesExpected_01.push_back(bn_09.backIt());
blockNodesExpected_01.push_back(bn_10.backIt());
EXPECT_EQ(checkNodes(blockNodes_01, blockNodesExpected_01), true);
list<node_list_it_t> treeNodes_02;
treeNodes_02.push_back(tn_01.backIt());
treeNodes_02.push_back(tn_02.backIt());
treeNodes_02.push_back(tn_03.backIt());
vector<node_list_it_t> blockNodes_02 =
fromTreeNodesToSkeletonNodes(skel, treeNodes_02);
vector<node_list_it_t> blockNodesExpected_02;
blockNodesExpected_02.push_back(bn_01.backIt());
blockNodesExpected_02.push_back(bn_02.backIt());
blockNodesExpected_02.push_back(bn_03.backIt());
blockNodesExpected_02.push_back(bn_04.backIt());
blockNodesExpected_02.push_back(bn_05.backIt());
blockNodesExpected_02.push_back(bn_06.backIt());
blockNodesExpected_02.push_back(bn_07.backIt());
blockNodesExpected_02.push_back(bn_08.backIt());
blockNodesExpected_02.push_back(bn_09.backIt());
blockNodesExpected_02.push_back(bn_10.backIt());
blockNodesExpected_02.push_back(bn_13.backIt());
blockNodesExpected_02.push_back(bn_14.backIt());
blockNodesExpected_02.push_back(bn_15.backIt());
blockNodesExpected_02.push_back(bn_16.backIt());
EXPECT_EQ(checkNodes(blockNodes_02, blockNodesExpected_02), true);
list<node_list_it_t> treeNodes_03;
treeNodes_03.push_back(tn_05.backIt());
treeNodes_03.push_back(tn_06.backIt());
treeNodes_03.push_back(tn_07.backIt());
vector<node_list_it_t> blockNodes_03 =
fromTreeNodesToSkeletonNodes(skel, treeNodes_03);
vector<node_list_it_t> blockNodesExpected_03;
blockNodesExpected_03.push_back(bn_09.backIt());
blockNodesExpected_03.push_back(bn_10.backIt());
blockNodesExpected_03.push_back(bn_11.backIt());
blockNodesExpected_03.push_back(bn_12.backIt());
blockNodesExpected_03.push_back(bn_17.backIt());
blockNodesExpected_03.push_back(bn_18.backIt());
EXPECT_EQ(checkNodes(blockNodes_03, blockNodesExpected_03), true);
}
/** @brief Tests GMWSkeletonGenerator::processBlock() in steps.
*/
TEST_F(GMWSkeletonGeneratorTests, Test4) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeletonGenerator skelGen;
// Find the tree nodes for N1 and N2.
bool res1 =
isVirtualEdge(skelGen, tn_01.backIt(), bn_07.backIt(), bn_08.backIt());
EXPECT_EQ(res1, true);
bool res2 =
isVirtualEdge(skelGen, tn_01.backIt(), bn_07.backIt(), bn_01.backIt());
EXPECT_EQ(res2, false);
bool res3 =
isVirtualEdge(skelGen, tn_02.backIt(), bn_07.backIt(), bn_08.backIt());
EXPECT_EQ(res3, true);
bool res4 =
isVirtualEdge(skelGen, tn_03.backIt(), bn_13.backIt(), bn_14.backIt());
EXPECT_EQ(res4, false);
}
/** @brief Tests GMWSkeletonGenerator::processBlock() in steps.
* same block, virtual edge
*/
TEST_F(GMWSkeletonGeneratorTests, Test5) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeletonGenerator skelGen;
// Find the tree nodes for N1 and N2.
node_list_it_t bnit1 = bn_07.backIt();
node_list_it_t bnit2 = bn_08.backIt();
node_list_it_t tnit1;
node_list_it_t tnit2;
findTreeNodesFromBlockNodes(skelGen, spqrTree, bnit1, bnit2, tnit1, tnit2);
auto& TN1 = dynamic_cast<SPQRTreeNode&>(*(*tnit1));
auto& TN2 = dynamic_cast<SPQRTreeNode&>(*(*tnit2));
// Find a path from N1 to N2 on the tree.
TreePathFinder finder;
list<node_list_it_t> spqrPathNodes;
list<edge_list_it_t> spqrPathEdges;
finder.findPath(spqrTree, TN1, TN2, spqrPathNodes, spqrPathEdges);
// Find the minimal path from N1 to N2 on the tree.
findMinimalTreePath(skelGen, spqrPathNodes, spqrPathEdges, bnit1, bnit2);
// Find the component nodes for each representative node along the path.
EXPECT_EQ(spqrPathNodes.size(),1);
EXPECT_EQ(
isVirtualEdge(skelGen, *(spqrPathNodes.begin()), bnit1, bnit2), true);
}
/** @brief Tests GMWSkeletonGenerator::processBlock() in steps.
* same block, not virtual edge
*/
TEST_F(GMWSkeletonGeneratorTests, Test6) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeletonGenerator skelGen;
// Find the tree nodes for N1 and N2.
node_list_it_t bnit1 = bn_01.backIt();
node_list_it_t bnit2 = bn_08.backIt();
node_list_it_t tnit1;
node_list_it_t tnit2;
findTreeNodesFromBlockNodes(skelGen, spqrTree, bnit1, bnit2, tnit1, tnit2);
auto& TN1 = dynamic_cast<SPQRTreeNode&>(*(*tnit1));
auto& TN2 = dynamic_cast<SPQRTreeNode&>(*(*tnit2));
// Find a path from N1 to N2 on the tree.
TreePathFinder finder;
list<node_list_it_t> spqrPathNodes;
list<edge_list_it_t> spqrPathEdges;
finder.findPath(spqrTree, TN1, TN2, spqrPathNodes, spqrPathEdges);
// Find the minimal path from N1 to N2 on the tree.
findMinimalTreePath(skelGen, spqrPathNodes, spqrPathEdges, bnit1, bnit2);
// Find the component nodes for each representative node along the path.
EXPECT_EQ(spqrPathNodes.size(),1);
EXPECT_EQ(*(spqrPathNodes.begin()),tn_01.backIt());
EXPECT_EQ(
isVirtualEdge(skelGen, *(spqrPathNodes.begin()), bnit1, bnit2), false);
GMWSkeleton skel;
setType(skel, GMWSkeleton::END1_NODE_END2_NODE);
setBlockNit11(skel, bnit1);
setBlockNit21(skel, bnit2);
vector<node_list_it_t> blockNodes;
for (auto bnit=B01.nodes().first; bnit!=B01.nodes().second; bnit++) {
blockNodes.push_back(bnit);
}
setBlockNodes(skel, blockNodes);
generateSkeleton(skel);
// Check the skeleton
Graph& sk = skel.graph();
EXPECT_EQ(sk.numNodes(), 22);
auto sknit = sk.nodes().first;
auto& sn_01 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_01.IGBackwardLink(), bn_01.backIt());
sknit++;
auto& sn_02 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_02.IGBackwardLink(), bn_02.backIt());
sknit++;
auto& sn_03 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_03.IGBackwardLink(), bn_03.backIt());
sknit++;
auto& sn_04 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_04.IGBackwardLink(), bn_04.backIt());
sknit++;
auto& sn_05 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_05.IGBackwardLink(), bn_05.backIt());
sknit++;
auto& sn_06 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_06.IGBackwardLink(), bn_06.backIt());
sknit++;
auto& sn_07 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_07.IGBackwardLink(), bn_07.backIt());
sknit++;
auto& sn_08 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_08.IGBackwardLink(), bn_08.backIt());
sknit++;
auto& sn_09 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_09.IGBackwardLink(), bn_09.backIt());
sknit++;
auto& sn_10 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_10.IGBackwardLink(), bn_10.backIt());
sknit++;
auto& sn_11 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_11.IGBackwardLink(), bn_11.backIt());
sknit++;
auto& sn_12 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_12.IGBackwardLink(), bn_12.backIt());
sknit++;
auto& sn_13 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_13.IGBackwardLink(), bn_13.backIt());
sknit++;
auto& sn_14 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_14.IGBackwardLink(), bn_14.backIt());
sknit++;
auto& sn_15 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_15.IGBackwardLink(), bn_15.backIt());
sknit++;
auto& sn_16 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_16.IGBackwardLink(), bn_16.backIt());
sknit++;
auto& sn_17 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_17.IGBackwardLink(), bn_17.backIt());
sknit++;
auto& sn_18 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_18.IGBackwardLink(), bn_18.backIt());
sknit++;
auto& sn_19 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_19.IGBackwardLink(), bn_19.backIt());
sknit++;
auto& sn_20 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_20.IGBackwardLink(), bn_20.backIt());
sknit++;
auto& sn_21 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_21.IGBackwardLink(), bn_21.backIt());
sknit++;
auto& sn_22 = dynamic_cast<GMWSkeletonNode&>(*(*sknit));
EXPECT_EQ(sn_22.IGBackwardLink(), bn_22.backIt());
EXPECT_EQ(sk.numEdges(), 39);
vector<edge_list_it_t> skelEdgesTested;
vector<edge_list_it_t> virtualEdges;
skelEdgesTested.push_back(be_01_02.backIt());
skelEdgesTested.push_back(be_01_03.backIt());
skelEdgesTested.push_back(be_01_07.backIt());
skelEdgesTested.push_back(be_02_04.backIt());
skelEdgesTested.push_back(be_02_08.backIt());
skelEdgesTested.push_back(be_03_04.backIt());
skelEdgesTested.push_back(be_03_05.backIt());
skelEdgesTested.push_back(be_04_06.backIt());
skelEdgesTested.push_back(be_05_06.backIt());
skelEdgesTested.push_back(be_05_07.backIt());
skelEdgesTested.push_back(be_06_08.backIt());
skelEdgesTested.push_back(be_07_09.backIt());
skelEdgesTested.push_back(be_08_15.backIt());
skelEdgesTested.push_back(be_08_13.backIt());
skelEdgesTested.push_back(be_13_14.backIt());
skelEdgesTested.push_back(be_13_15.backIt());
skelEdgesTested.push_back(be_15_16.backIt());
skelEdgesTested.push_back(be_14_10.backIt());
skelEdgesTested.push_back(be_14_16.backIt());
skelEdgesTested.push_back(be_10_16.backIt());
skelEdgesTested.push_back(be_09_10.backIt());
skelEdgesTested.push_back(be_09_11.backIt());
skelEdgesTested.push_back(be_10_11.backIt());
skelEdgesTested.push_back(be_09_12.backIt());
skelEdgesTested.push_back(be_11_12.backIt());
skelEdgesTested.push_back(be_10_12.backIt());
skelEdgesTested.push_back(be_10_17.backIt());
skelEdgesTested.push_back(be_10_18.backIt());
skelEdgesTested.push_back(be_12_17.backIt());
skelEdgesTested.push_back(be_17_18.backIt());
skelEdgesTested.push_back(be_12_18.backIt());
skelEdgesTested.push_back(be_12_21.backIt());
skelEdgesTested.push_back(be_12_19.backIt());
skelEdgesTested.push_back(be_19_20.backIt());
skelEdgesTested.push_back(be_19_21.backIt());
skelEdgesTested.push_back(be_18_20.backIt());
skelEdgesTested.push_back(be_18_22.backIt());
skelEdgesTested.push_back(be_20_22.backIt());
skelEdgesTested.push_back(be_21_22.backIt());
EXPECT_EQ(checkSkelEdges(sk, skelEdgesTested, 0, virtualEdges), true);
EXPECT_EQ(skel.mSkelNit1, sn_01.backIt());
EXPECT_EQ(skel.mSkelNit2, sn_08.backIt());
EXPECT_EQ(skel.mSkelEit1, sk.edges().second);
EXPECT_EQ(skel.mSkelEit2, sk.edges().second);
}
/** @brief Tests GMWSkeletonGenerator::processBlock() in steps.
* realistic.
*/
TEST_F(GMWSkeletonGeneratorTests, Test7) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeletonGenerator skelGen;
// Find the tree nodes for N1 and N2.
node_list_it_t bnit1 = bn_03.backIt();
node_list_it_t bnit2 = bn_19.backIt();
node_list_it_t tnit1;
node_list_it_t tnit2;
findTreeNodesFromBlockNodes(skelGen, spqrTree, bnit1, bnit2, tnit1, tnit2);
EXPECT_EQ(tnit1, tn_01.backIt());
EXPECT_EQ(tnit2, tn_09.backIt());
auto& TN1 = dynamic_cast<SPQRTreeNode&>(*(*tnit1));
auto& TN2 = dynamic_cast<SPQRTreeNode&>(*(*tnit2));
// Find a path from N1 to N2 on the tree.
TreePathFinder finder;
list<node_list_it_t> spqrPathNodes;
list<edge_list_it_t> spqrPathEdges;
finder.findPath(spqrTree, TN1, TN2, spqrPathNodes, spqrPathEdges);
// Find the minimal path from N1 to N2 on the tree.
findMinimalTreePath(skelGen, spqrPathNodes, spqrPathEdges, bnit1, bnit2);
// Find the component nodes for each representative node along the path.
EXPECT_EQ(spqrPathNodes.size(),8);
EXPECT_EQ(spqrPathEdges.size(),7);
// Prepare the tree edges for expansion.
TreeSplitter splitter(spqrTree);
splitter.prepareTree(spqrPathEdges);
size_t index = 0;
list<edge_list_it_t>::iterator eItIt = spqrPathEdges.begin();
list<node_list_it_t>::iterator nItIt = spqrPathNodes.begin();
// Tree Component 0
auto& TN_0 = dynamic_cast<SPQRTreeNode&>(*(*(*nItIt)));
EXPECT_EQ(TN_0.type(),SPQRTreeNode::RType);
GMWSkeleton skel_0;
setType(skel_0,GMWSkeleton::END1_NODE_END2_EDGE);
setBlockNit11(skel_0,bnit1);
auto& TE2_0 = dynamic_cast<SPQRTreeEdge&>(*(*(*eItIt)));
edge_list_it_t ve2It;
if (TE2_0.incidentNode1().backIt()== *nItIt) {
ve2It = TE2_0.virtualEdge1();
}
else {
ve2It = TE2_0.virtualEdge2();
}
EXPECT_EQ(ve2It,ce_01_07_08.backIt());
auto& VE2_0 = dynamic_cast<Edge&>(*(*ve2It));
auto& CN1_0 = dynamic_cast<SPQRComponentNode&>(VE2_0.incidentNode1());
auto& CN2_0 = dynamic_cast<SPQRComponentNode&>(VE2_0.incidentNode2());
setBlockNit21(skel_0, CN1_0.IGBackwardLink());
setBlockNit22(skel_0, CN2_0.IGBackwardLink());
list<node_list_it_t> treeNodes_0 = splitter.findComponent(*nItIt);
EXPECT_EQ(treeNodes_0.size(), 1);
vector<node_list_it_t> blockNodes_0 =
fromTreeNodesToSkeletonNodes(skelGen, treeNodes_0);
vector<node_list_it_t> blockNodesExpected_0;
blockNodesExpected_0.push_back(bn_01.backIt());
blockNodesExpected_0.push_back(bn_02.backIt());
blockNodesExpected_0.push_back(bn_03.backIt());
blockNodesExpected_0.push_back(bn_04.backIt());
blockNodesExpected_0.push_back(bn_05.backIt());
blockNodesExpected_0.push_back(bn_06.backIt());
blockNodesExpected_0.push_back(bn_07.backIt());
blockNodesExpected_0.push_back(bn_08.backIt());
EXPECT_EQ(checkNodes(blockNodes_0, blockNodesExpected_0), true);
setBlockNodes(skel_0, blockNodes_0);
generateSkeleton(skel_0);
EXPECT_EQ(skel_0.graph().numNodes(), 8);
EXPECT_EQ(skel_0.graph().numEdges(), 12);
vector<node_list_it_t> skelNodes_0;
EXPECT_EQ(
checkSkelNodes(skel_0.graph(),blockNodesExpected_0,skelNodes_0),true);
vector<edge_list_it_t> skelEdgesTested_0;
vector<edge_list_it_t> virtualEdges_0;
skelEdgesTested_0.push_back(be_01_02.backIt());
skelEdgesTested_0.push_back(be_01_03.backIt());
skelEdgesTested_0.push_back(be_01_07.backIt());
skelEdgesTested_0.push_back(be_02_04.backIt());
skelEdgesTested_0.push_back(be_02_08.backIt());
skelEdgesTested_0.push_back(be_03_04.backIt());
skelEdgesTested_0.push_back(be_03_05.backIt());
skelEdgesTested_0.push_back(be_04_06.backIt());
skelEdgesTested_0.push_back(be_05_06.backIt());
skelEdgesTested_0.push_back(be_05_07.backIt());
skelEdgesTested_0.push_back(be_06_08.backIt());
EXPECT_EQ(checkSkelEdges(
skel_0.graph(), skelEdgesTested_0, 1, virtualEdges_0), true);
EXPECT_EQ(skel_0.mSkelNit1, skelNodes_0[2]);
EXPECT_EQ(skel_0.mSkelNit2, skel_0.graph().nodes().second);
EXPECT_EQ(skel_0.mSkelEit1, skel_0.graph().edges().second);
EXPECT_EQ(skel_0.mSkelEit2, *(virtualEdges_0.begin()));
auto& SVE2_0 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_0.mSkelEit2));
EXPECT_EQ((SVE2_0.incidentNode1().backIt() == skelNodes_0[6] &&
SVE2_0.incidentNode2().backIt() == skelNodes_0[7] )||
(SVE2_0.incidentNode1().backIt() == skelNodes_0[7] &&
SVE2_0.incidentNode2().backIt() == skelNodes_0[6] ) , true);
index++;
nItIt++;
// Tree Component 1
auto& TN_1 = dynamic_cast<SPQRTreeNode&>(*(*(*nItIt)));
EXPECT_EQ(TN_1.type(),SPQRTreeNode::SType);
// Intermediate component on the path.
GMWSkeleton skel_1;
setType(skel_1, GMWSkeleton::END1_EDGE_END2_EDGE);
auto& TE1_1 = dynamic_cast<SPQRTreeEdge&>(*(*(*eItIt)));
edge_list_it_t ve1It;
if (TE1_1.incidentNode1().backIt()== *nItIt) {
ve1It = TE1_1.virtualEdge1();
}
else {
ve1It = TE1_1.virtualEdge2();
}
EXPECT_EQ(ve1It,ce_02_07_08.backIt());
auto& VE1_1 = dynamic_cast<Edge&>(*(*ve1It));
auto& CN1_1_1 = dynamic_cast<SPQRComponentNode&>(VE1_1.incidentNode1());
auto& CN1_2_1 = dynamic_cast<SPQRComponentNode&>(VE1_1.incidentNode2());
setBlockNit11(skel_1, CN1_1_1.IGBackwardLink());
setBlockNit12(skel_1, CN1_2_1.IGBackwardLink());
eItIt++;
auto& TE2_1 = dynamic_cast<SPQRTreeEdge&>(*(*(*eItIt)));
if (TE2_1.incidentNode1().backIt()== *nItIt) {
ve2It = TE2_1.virtualEdge1();
}
else {
ve2It = TE2_1.virtualEdge2();
}
EXPECT_EQ(ve2It,ce_02_09_10.backIt());
auto& VE2_1 = dynamic_cast<Edge&>(*(*ve2It));
auto& CN2_1_1 = dynamic_cast<SPQRComponentNode&>(VE2_1.incidentNode1());
auto& CN2_2_1 = dynamic_cast<SPQRComponentNode&>(VE2_1.incidentNode2());
setBlockNit21(skel_1, CN2_1_1.IGBackwardLink());
setBlockNit22(skel_1, CN2_2_1.IGBackwardLink());
list<node_list_it_t> treeNodes_1 = splitter.findComponent(*nItIt);
EXPECT_EQ(treeNodes_1.size(), 2);
vector<node_list_it_t> blockNodes_1
= fromTreeNodesToSkeletonNodes(skelGen, treeNodes_1);
vector<node_list_it_t> blockNodesExpected_1;
blockNodesExpected_1.push_back(bn_07.backIt());
blockNodesExpected_1.push_back(bn_08.backIt());
blockNodesExpected_1.push_back(bn_09.backIt());
blockNodesExpected_1.push_back(bn_10.backIt());
blockNodesExpected_1.push_back(bn_13.backIt());
blockNodesExpected_1.push_back(bn_14.backIt());
blockNodesExpected_1.push_back(bn_15.backIt());
blockNodesExpected_1.push_back(bn_16.backIt());
EXPECT_EQ(checkNodes(blockNodes_1, blockNodesExpected_1), true);
setBlockNodes(skel_1, blockNodes_1);
generateSkeleton(skel_1);
EXPECT_EQ(skel_1.graph().numNodes(), 8);
EXPECT_EQ(skel_1.graph().numEdges(), 11);
vector<node_list_it_t> skelNodes_1;
EXPECT_EQ(
checkSkelNodes(skel_1.graph(),blockNodesExpected_1,skelNodes_1),true);
vector<edge_list_it_t> skelEdgesTested_1;
vector<edge_list_it_t> virtualEdges_1;
skelEdgesTested_1.push_back(be_07_09.backIt());
skelEdgesTested_1.push_back(be_08_15.backIt());
skelEdgesTested_1.push_back(be_08_13.backIt());
skelEdgesTested_1.push_back(be_13_15.backIt());
skelEdgesTested_1.push_back(be_13_14.backIt());
skelEdgesTested_1.push_back(be_15_16.backIt());
skelEdgesTested_1.push_back(be_14_10.backIt());
skelEdgesTested_1.push_back(be_14_16.backIt());
skelEdgesTested_1.push_back(be_10_16.backIt());
EXPECT_EQ(checkSkelEdges(
skel_1.graph(), skelEdgesTested_1, 2, virtualEdges_1), true);
EXPECT_EQ(skel_1.mSkelNit1, skel_1.graph().nodes().second);
EXPECT_EQ(skel_1.mSkelNit2, skel_1.graph().nodes().second);
EXPECT_EQ(skel_1.mSkelEit1, *(virtualEdges_1.begin()));
EXPECT_EQ(skel_1.mSkelEit2, *(virtualEdges_1.rbegin()));
auto& SVE1_1 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_1.mSkelEit1));
EXPECT_EQ((SVE1_1.incidentNode1().backIt() == skelNodes_1[0] &&
SVE1_1.incidentNode2().backIt() == skelNodes_1[1] )||
(SVE1_1.incidentNode1().backIt() == skelNodes_1[1] &&
SVE1_1.incidentNode2().backIt() == skelNodes_1[0] ) , true);
auto& SVE2_1 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_1.mSkelEit2));
EXPECT_EQ((SVE2_1.incidentNode1().backIt() == skelNodes_1[2] &&
SVE2_1.incidentNode2().backIt() == skelNodes_1[3] )||
(SVE2_1.incidentNode1().backIt() == skelNodes_1[3] &&
SVE2_1.incidentNode2().backIt() == skelNodes_1[2] ) , true);
index++;
nItIt++;
// Tree Component 2
auto& TN_2 = dynamic_cast<SPQRTreeNode&>(*(*(*nItIt)));
EXPECT_EQ(TN_2.type(),SPQRTreeNode::PType);
eItIt++;
index++;
nItIt++;
// Tree Component 3
auto& TN_3 = dynamic_cast<SPQRTreeNode&>(*(*(*nItIt)));
EXPECT_EQ(TN_3.type(),SPQRTreeNode::RType);
// Intermediate component on the path.
GMWSkeleton skel_3;
setType(skel_3, GMWSkeleton::END1_EDGE_END2_EDGE);
auto& TE1_3 = dynamic_cast<SPQRTreeEdge&>(*(*(*eItIt)));
if (TE1_3.incidentNode1().backIt()== *nItIt) {
ve1It = TE1_3.virtualEdge1();
}
else {
ve1It = TE1_3.virtualEdge2();
}
EXPECT_EQ(ve1It,ce_05_09_10.backIt());
auto& VE1_3 = dynamic_cast<Edge&>(*(*ve1It));
auto& CN1_1_3 = dynamic_cast<SPQRComponentNode&>(VE1_3.incidentNode1());
auto& CN1_2_3 = dynamic_cast<SPQRComponentNode&>(VE1_3.incidentNode2());
setBlockNit11(skel_3, CN1_1_3.IGBackwardLink());
setBlockNit12(skel_3, CN1_2_3.IGBackwardLink());
eItIt++;
auto& TE2_3 = dynamic_cast<SPQRTreeEdge&>(*(*(*eItIt)));
if (TE2_3.incidentNode1().backIt()== *nItIt) {
ve2It = TE2_3.virtualEdge1();
}
else {
ve2It = TE2_3.virtualEdge2();
}
EXPECT_EQ(ve2It,ce_05_10_12.backIt());
auto& VE2_3 = dynamic_cast<Edge&>(*(*ve2It));
auto& CN2_1_3 = dynamic_cast<SPQRComponentNode&>(VE2_3.incidentNode1());
auto& CN2_2_3 = dynamic_cast<SPQRComponentNode&>(VE2_3.incidentNode2());
setBlockNit21(skel_3, CN2_1_3.IGBackwardLink());
setBlockNit22(skel_3, CN2_2_3.IGBackwardLink());
list<node_list_it_t> treeNodes_3 = splitter.findComponent(*nItIt);
EXPECT_EQ(treeNodes_3.size(), 1);
vector<node_list_it_t> blockNodes_3
= fromTreeNodesToSkeletonNodes(skelGen, treeNodes_3);
vector<node_list_it_t> blockNodesExpected_3;
blockNodesExpected_3.push_back(bn_09.backIt());
blockNodesExpected_3.push_back(bn_10.backIt());
blockNodesExpected_3.push_back(bn_11.backIt());
blockNodesExpected_3.push_back(bn_12.backIt());
EXPECT_EQ(checkNodes(blockNodes_3, blockNodesExpected_3), true);
setBlockNodes(skel_3, blockNodes_3);
generateSkeleton(skel_3);
EXPECT_EQ(skel_3.graph().numNodes(), 4);
EXPECT_EQ(skel_3.graph().numEdges(), 6);
vector<node_list_it_t> skelNodes_3;
EXPECT_EQ(
checkSkelNodes(skel_3.graph(),blockNodesExpected_3,skelNodes_3),true);
vector<edge_list_it_t> skelEdgesTested_3;
vector<edge_list_it_t> virtualEdges_3;
skelEdgesTested_3.push_back(be_09_11.backIt());
skelEdgesTested_3.push_back(be_10_11.backIt());
skelEdgesTested_3.push_back(be_09_12.backIt());
skelEdgesTested_3.push_back(be_11_12.backIt());
EXPECT_EQ(checkSkelEdges(
skel_3.graph(), skelEdgesTested_3, 2, virtualEdges_3), true);
EXPECT_EQ(skel_3.mSkelNit1, skel_3.graph().nodes().second);
EXPECT_EQ(skel_3.mSkelNit2, skel_3.graph().nodes().second);
EXPECT_EQ(skel_3.mSkelEit1, *(virtualEdges_3.begin()));
EXPECT_EQ(skel_3.mSkelEit2, *(virtualEdges_3.rbegin()));
auto& SVE1_3 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_3.mSkelEit1));
EXPECT_EQ((SVE1_3.incidentNode1().backIt() == skelNodes_3[0] &&
SVE1_3.incidentNode2().backIt() == skelNodes_3[1] )||
(SVE1_3.incidentNode1().backIt() == skelNodes_3[1] &&
SVE1_3.incidentNode2().backIt() == skelNodes_3[0] ) , true);
auto& SVE2_3 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_3.mSkelEit2));
EXPECT_EQ((SVE2_3.incidentNode1().backIt() == skelNodes_3[1] &&
SVE2_3.incidentNode2().backIt() == skelNodes_3[3] )||
(SVE2_3.incidentNode1().backIt() == skelNodes_3[3] &&
SVE2_3.incidentNode2().backIt() == skelNodes_3[1] ) , true);
index++;
nItIt++;
// Tree Component 4
auto& TN_4 = dynamic_cast<SPQRTreeNode&>(*(*(*nItIt)));
EXPECT_EQ(TN_4.type(),SPQRTreeNode::PType);
eItIt++;
index++;
nItIt++;
// Tree Component 5
auto& TN_5 = dynamic_cast<SPQRTreeNode&>(*(*(*nItIt)));
EXPECT_EQ(TN_5.type(),SPQRTreeNode::RType);
// Intermediate component on the path.
GMWSkeleton skel_5;
setType(skel_5, GMWSkeleton::END1_EDGE_END2_EDGE);
auto& TE1_5 = dynamic_cast<SPQRTreeEdge&>(*(*(*eItIt)));
if (TE1_5.incidentNode1().backIt()== *nItIt) {
ve1It = TE1_5.virtualEdge1();
}
else {
ve1It = TE1_5.virtualEdge2();
}
EXPECT_EQ(ve1It,ce_07_10_12.backIt());
auto& VE1_5 = dynamic_cast<Edge&>(*(*ve1It));
auto& CN1_1_5 = dynamic_cast<SPQRComponentNode&>(VE1_5.incidentNode1());
auto& CN1_2_5 = dynamic_cast<SPQRComponentNode&>(VE1_5.incidentNode2());
setBlockNit11(skel_5, CN1_1_5.IGBackwardLink());
setBlockNit12(skel_5, CN1_2_5.IGBackwardLink());
eItIt++;
auto& TE2_5 = dynamic_cast<SPQRTreeEdge&>(*(*(*eItIt)));
if (TE2_5.incidentNode1().backIt()== *nItIt) {
ve2It = TE2_5.virtualEdge1();
}
else {
ve2It = TE2_5.virtualEdge2();
}
EXPECT_EQ(ve2It,ce_07_12_18.backIt());
auto& VE2_5 = dynamic_cast<Edge&>(*(*ve2It));
auto& CN2_1_5 = dynamic_cast<SPQRComponentNode&>(VE2_5.incidentNode1());
auto& CN2_2_5 = dynamic_cast<SPQRComponentNode&>(VE2_5.incidentNode2());
setBlockNit21(skel_5, CN2_1_5.IGBackwardLink());
setBlockNit22(skel_5, CN2_2_5.IGBackwardLink());
list<node_list_it_t> treeNodes_5 = splitter.findComponent(*nItIt);
EXPECT_EQ(treeNodes_5.size(), 1);
vector<node_list_it_t> blockNodes_5
= fromTreeNodesToSkeletonNodes(skelGen, treeNodes_5);
vector<node_list_it_t> blockNodesExpected_5;
blockNodesExpected_5.push_back(bn_10.backIt());
blockNodesExpected_5.push_back(bn_12.backIt());
blockNodesExpected_5.push_back(bn_17.backIt());
blockNodesExpected_5.push_back(bn_18.backIt());
EXPECT_EQ(checkNodes(blockNodes_5, blockNodesExpected_5), true);
setBlockNodes(skel_5, blockNodes_5);
generateSkeleton(skel_5);
EXPECT_EQ(skel_5.graph().numNodes(), 4);
EXPECT_EQ(skel_5.graph().numEdges(), 6);
vector<node_list_it_t> skelNodes_5;
EXPECT_EQ(
checkSkelNodes(skel_5.graph(),blockNodesExpected_5,skelNodes_5),true);
vector<edge_list_it_t> skelEdgesTested_5;
vector<edge_list_it_t> virtualEdges_5;
skelEdgesTested_5.push_back(be_10_17.backIt());
skelEdgesTested_5.push_back(be_10_18.backIt());
skelEdgesTested_5.push_back(be_12_17.backIt());
skelEdgesTested_5.push_back(be_17_18.backIt());
EXPECT_EQ(checkSkelEdges(
skel_5.graph(), skelEdgesTested_5, 2, virtualEdges_5), true);
EXPECT_EQ(skel_5.mSkelNit1, skel_5.graph().nodes().second);
EXPECT_EQ(skel_5.mSkelNit2, skel_5.graph().nodes().second);
EXPECT_EQ(skel_5.mSkelEit1, *(virtualEdges_5.begin()));
EXPECT_EQ(skel_5.mSkelEit2, *(virtualEdges_5.rbegin()));
auto& SVE1_5 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_5.mSkelEit1));
EXPECT_EQ((SVE1_5.incidentNode1().backIt() == skelNodes_5[0] &&
SVE1_5.incidentNode2().backIt() == skelNodes_5[1] )||
(SVE1_5.incidentNode1().backIt() == skelNodes_5[1] &&
SVE1_5.incidentNode2().backIt() == skelNodes_5[0] ) , true);
auto& SVE2_5 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_5.mSkelEit2));
EXPECT_EQ((SVE2_5.incidentNode1().backIt() == skelNodes_5[1] &&
SVE2_5.incidentNode2().backIt() == skelNodes_5[3] )||
(SVE2_5.incidentNode1().backIt() == skelNodes_5[3] &&
SVE2_5.incidentNode2().backIt() == skelNodes_5[1] ) , true);
index++;
nItIt++;
// Tree Component 6
auto& TN_6 = dynamic_cast<SPQRTreeNode&>(*(*(*nItIt)));
EXPECT_EQ(TN_6.type(),SPQRTreeNode::PType);
eItIt++;
index++;
nItIt++;
// Tree Component 7
auto& TN_7 = dynamic_cast<SPQRTreeNode&>(*(*(*nItIt)));
EXPECT_EQ(TN_7.type(),SPQRTreeNode::RType);
GMWSkeleton skel_7;
setType(skel_7, GMWSkeleton::END1_EDGE_END2_NODE);
auto& TE1_7 = dynamic_cast<SPQRTreeEdge&>(*(*(*eItIt)));
if (TE1_7.incidentNode1().backIt()== *nItIt) {
ve1It = TE1_7.virtualEdge1();
}
else {
ve1It = TE1_7.virtualEdge2();
}
EXPECT_EQ(ve1It,ce_09_12_18.backIt());
auto& VE1_7 = dynamic_cast<Edge&>(*(*ve1It));
auto& CN1_1_7 = dynamic_cast<SPQRComponentNode&>(VE1_7.incidentNode1());
auto& CN1_2_7 = dynamic_cast<SPQRComponentNode&>(VE1_7.incidentNode2());
setBlockNit11(skel_7, CN1_1_7.IGBackwardLink());
setBlockNit12(skel_7, CN1_2_7.IGBackwardLink());
setBlockNit21(skel_7, bnit2);
list<node_list_it_t> treeNodes_7 = splitter.findComponent(*nItIt);
EXPECT_EQ(treeNodes_7.size(), 1);
vector<node_list_it_t> blockNodes_7
= fromTreeNodesToSkeletonNodes(skelGen, treeNodes_7);
setBlockNodes(skel_7, blockNodes_7);
generateSkeleton(skel_7);
vector<node_list_it_t> blockNodesExpected_7;
blockNodesExpected_7.push_back(bn_12.backIt());
blockNodesExpected_7.push_back(bn_18.backIt());
blockNodesExpected_7.push_back(bn_19.backIt());
blockNodesExpected_7.push_back(bn_20.backIt());
blockNodesExpected_7.push_back(bn_21.backIt());
blockNodesExpected_7.push_back(bn_22.backIt());
EXPECT_EQ(checkNodes(blockNodes_7, blockNodesExpected_7), true);
EXPECT_EQ(skel_7.graph().numNodes(), 6);
EXPECT_EQ(skel_7.graph().numEdges(), 9);
vector<node_list_it_t> skelNodes_7;
EXPECT_EQ(
checkSkelNodes(skel_7.graph(),blockNodesExpected_7,skelNodes_7),true);
vector<edge_list_it_t> skelEdgesTested_7;
vector<edge_list_it_t> virtualEdges_7;
skelEdgesTested_7.push_back(be_12_21.backIt());
skelEdgesTested_7.push_back(be_12_19.backIt());
skelEdgesTested_7.push_back(be_19_21.backIt());
skelEdgesTested_7.push_back(be_19_20.backIt());
skelEdgesTested_7.push_back(be_18_20.backIt());
skelEdgesTested_7.push_back(be_18_22.backIt());
skelEdgesTested_7.push_back(be_20_22.backIt());
skelEdgesTested_7.push_back(be_21_22.backIt());
EXPECT_EQ(checkSkelEdges(
skel_7.graph(), skelEdgesTested_7, 1, virtualEdges_7), true);
EXPECT_EQ(skel_7.mSkelNit1, skel_7.graph().nodes().second);
EXPECT_EQ(skel_7.mSkelNit2, skelNodes_7[2]);
EXPECT_EQ(skel_7.mSkelEit1, *(virtualEdges_7.begin()));
EXPECT_EQ(skel_7.mSkelEit2, skel_7.graph().edges().second);
auto& SVE1_7 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_7.mSkelEit1));
EXPECT_EQ((SVE1_7.incidentNode1().backIt() == skelNodes_7[0] &&
SVE1_7.incidentNode2().backIt() == skelNodes_7[1] )||
(SVE1_7.incidentNode1().backIt() == skelNodes_7[1] &&
SVE1_7.incidentNode2().backIt() == skelNodes_7[0] ) , true);
index++;
nItIt++;
}
/** @brief Tests GMWSkeletonGenerator::processBlock() in steps.
* realistic 2.
*/
TEST_F(GMWSkeletonGeneratorTests, Test8) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeletonGenerator skelGen;
// Find the tree nodes for N1 and N2.
node_list_it_t bnit1 = bn_11.backIt();
node_list_it_t bnit2 = bn_13.backIt();
node_list_it_t tnit1;
node_list_it_t tnit2;
findTreeNodesFromBlockNodes(skelGen, spqrTree, bnit1, bnit2, tnit1, tnit2);
EXPECT_EQ(tnit1, tn_05.backIt());
EXPECT_EQ(tnit2, tn_03.backIt());
auto& TN1 = dynamic_cast<SPQRTreeNode&>(*(*tnit1));
auto& TN2 = dynamic_cast<SPQRTreeNode&>(*(*tnit2));
// Find a path from N1 to N2 on the tree.
TreePathFinder finder;
list<node_list_it_t> spqrPathNodes;
list<edge_list_it_t> spqrPathEdges;
finder.findPath(spqrTree, TN1, TN2, spqrPathNodes, spqrPathEdges);
// Find the minimal path from N1 to N2 on the tree.
findMinimalTreePath(skelGen, spqrPathNodes, spqrPathEdges, bnit1, bnit2);
// Find the component nodes for each representative node along the path.
EXPECT_EQ(spqrPathNodes.size(),4);
EXPECT_EQ(spqrPathEdges.size(),3);
// Prepare the tree edges for expansion.
TreeSplitter splitter(spqrTree);
splitter.prepareTree(spqrPathEdges);
size_t index = 0;
list<edge_list_it_t>::iterator eItIt = spqrPathEdges.begin();
list<node_list_it_t>::iterator nItIt = spqrPathNodes.begin();
// Tree Component 0
auto& TN_0 = dynamic_cast<SPQRTreeNode&>(*(*(*nItIt)));
EXPECT_EQ(TN_0.type(),SPQRTreeNode::RType);
GMWSkeleton skel_0;
setType(skel_0,GMWSkeleton::END1_NODE_END2_EDGE);
setBlockNit11(skel_0,bnit1);
auto& TE2_0 = dynamic_cast<SPQRTreeEdge&>(*(*(*eItIt)));
edge_list_it_t ve2It;
if (TE2_0.incidentNode1().backIt()== *nItIt) {
ve2It = TE2_0.virtualEdge1();
}
else {
ve2It = TE2_0.virtualEdge2();
}
EXPECT_EQ(ve2It,ce_05_09_10.backIt());
auto& VE2_0 = dynamic_cast<Edge&>(*(*ve2It));
auto& CN1_0 = dynamic_cast<SPQRComponentNode&>(VE2_0.incidentNode1());
auto& CN2_0 = dynamic_cast<SPQRComponentNode&>(VE2_0.incidentNode2());
setBlockNit21(skel_0, CN1_0.IGBackwardLink());
setBlockNit22(skel_0, CN2_0.IGBackwardLink());
list<node_list_it_t> treeNodes_0 = splitter.findComponent(*nItIt);
EXPECT_EQ(treeNodes_0.size(), 5);
vector<node_list_it_t> blockNodes_0 =
fromTreeNodesToSkeletonNodes(skelGen, treeNodes_0);
vector<node_list_it_t> blockNodesExpected_0;
blockNodesExpected_0.push_back(bn_09.backIt());
blockNodesExpected_0.push_back(bn_10.backIt());
blockNodesExpected_0.push_back(bn_11.backIt());
blockNodesExpected_0.push_back(bn_12.backIt());
blockNodesExpected_0.push_back(bn_17.backIt());
blockNodesExpected_0.push_back(bn_18.backIt());
blockNodesExpected_0.push_back(bn_19.backIt());
blockNodesExpected_0.push_back(bn_20.backIt());
blockNodesExpected_0.push_back(bn_21.backIt());
blockNodesExpected_0.push_back(bn_22.backIt());
EXPECT_EQ(checkNodes(blockNodes_0, blockNodesExpected_0), true);
setBlockNodes(skel_0, blockNodes_0);
generateSkeleton(skel_0);
EXPECT_EQ(skel_0.graph().numNodes(), 10);
EXPECT_EQ(skel_0.graph().numEdges(), 19);
vector<node_list_it_t> skelNodes_0;
EXPECT_EQ(
checkSkelNodes(skel_0.graph(), blockNodesExpected_0, skelNodes_0), true);
vector<edge_list_it_t> skelEdgesTested_0;
vector<edge_list_it_t> virtualEdges_0;
skelEdgesTested_0.push_back(be_09_11.backIt());
skelEdgesTested_0.push_back(be_10_11.backIt());
skelEdgesTested_0.push_back(be_09_12.backIt());
skelEdgesTested_0.push_back(be_10_12.backIt());
skelEdgesTested_0.push_back(be_11_12.backIt());
skelEdgesTested_0.push_back(be_10_18.backIt());
skelEdgesTested_0.push_back(be_10_17.backIt());
skelEdgesTested_0.push_back(be_12_17.backIt());
skelEdgesTested_0.push_back(be_12_18.backIt());
skelEdgesTested_0.push_back(be_17_18.backIt());
skelEdgesTested_0.push_back(be_12_21.backIt());
skelEdgesTested_0.push_back(be_12_19.backIt());
skelEdgesTested_0.push_back(be_18_22.backIt());
skelEdgesTested_0.push_back(be_18_20.backIt());
skelEdgesTested_0.push_back(be_19_20.backIt());
skelEdgesTested_0.push_back(be_19_21.backIt());
skelEdgesTested_0.push_back(be_20_22.backIt());
skelEdgesTested_0.push_back(be_21_22.backIt());
EXPECT_EQ(checkSkelEdges(
skel_0.graph(), skelEdgesTested_0, 1, virtualEdges_0), true);
EXPECT_EQ(skel_0.mSkelNit1, skelNodes_0[2]);
EXPECT_EQ(skel_0.mSkelNit2, skel_0.graph().nodes().second);
EXPECT_EQ(skel_0.mSkelEit1, skel_0.graph().edges().second);
EXPECT_EQ(skel_0.mSkelEit2, *(virtualEdges_0.begin()));
auto& SVE2_0 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_0.mSkelEit2));
EXPECT_EQ((SVE2_0.incidentNode1().backIt() == skelNodes_0[0] &&
SVE2_0.incidentNode2().backIt() == skelNodes_0[1] )||
(SVE2_0.incidentNode1().backIt() == skelNodes_0[1] &&
SVE2_0.incidentNode2().backIt() == skelNodes_0[0] ) , true);
index++;
nItIt++;
// Tree Component 1
auto& TN_1 = dynamic_cast<SPQRTreeNode&>(*(*(*nItIt)));
EXPECT_EQ(TN_1.type(),SPQRTreeNode::PType);
eItIt++;
index++;
nItIt++;
// Tree Component 2
auto& TN_2 = dynamic_cast<SPQRTreeNode&>(*(*(*nItIt)));
EXPECT_EQ(TN_2.type(),SPQRTreeNode::SType);
eItIt++;
index++;
nItIt++;
// Tree Component 3
auto& TN_3 = dynamic_cast<SPQRTreeNode&>(*(*(*nItIt)));
EXPECT_EQ(TN_3.type(),SPQRTreeNode::RType);
GMWSkeleton skel_3;
setType(skel_3, GMWSkeleton::END1_EDGE_END2_NODE);
auto& TE1_3 = dynamic_cast<SPQRTreeEdge&>(*(*(*eItIt)));
edge_list_it_t ve1It;
if (TE1_3.incidentNode1().backIt()== *nItIt) {
ve1It = TE1_3.virtualEdge1();
}
else {
ve1It = TE1_3.virtualEdge2();
}
EXPECT_EQ(ve1It,ce_03_08_10.backIt());
auto& VE1_3 = dynamic_cast<Edge&>(*(*ve1It));
auto& CN1_1_3 = dynamic_cast<SPQRComponentNode&>(VE1_3.incidentNode1());
auto& CN1_2_3 = dynamic_cast<SPQRComponentNode&>(VE1_3.incidentNode2());
setBlockNit11(skel_3, CN1_1_3.IGBackwardLink());
setBlockNit12(skel_3, CN1_2_3.IGBackwardLink());
setBlockNit21(skel_3, bnit2);
list<node_list_it_t> treeNodes_3 = splitter.findComponent(*nItIt);
EXPECT_EQ(treeNodes_3.size(), 1);
vector<node_list_it_t> blockNodes_3
= fromTreeNodesToSkeletonNodes(skelGen, treeNodes_3);
setBlockNodes(skel_3, blockNodes_3);
generateSkeleton(skel_3);
vector<node_list_it_t> blockNodesExpected_3;
blockNodesExpected_3.push_back(bn_08.backIt());
blockNodesExpected_3.push_back(bn_10.backIt());
blockNodesExpected_3.push_back(bn_13.backIt());
blockNodesExpected_3.push_back(bn_14.backIt());
blockNodesExpected_3.push_back(bn_15.backIt());
blockNodesExpected_3.push_back(bn_16.backIt());
EXPECT_EQ(checkNodes(blockNodes_3, blockNodesExpected_3), true);
EXPECT_EQ(skel_3.graph().numNodes(), 6);
EXPECT_EQ(skel_3.graph().numEdges(), 9);
vector<node_list_it_t> skelNodes_3;
EXPECT_EQ(
checkSkelNodes(skel_3.graph(),blockNodesExpected_3,skelNodes_3),true);
vector<edge_list_it_t> skelEdgesTested_3;
vector<edge_list_it_t> virtualEdges_3;
skelEdgesTested_3.push_back(be_08_15.backIt());
skelEdgesTested_3.push_back(be_08_13.backIt());
skelEdgesTested_3.push_back(be_13_15.backIt());
skelEdgesTested_3.push_back(be_13_14.backIt());
skelEdgesTested_3.push_back(be_14_10.backIt());
skelEdgesTested_3.push_back(be_14_16.backIt());
skelEdgesTested_3.push_back(be_15_16.backIt());
skelEdgesTested_3.push_back(be_10_16.backIt());
EXPECT_EQ(checkSkelEdges(
skel_3.graph(), skelEdgesTested_3, 1, virtualEdges_3), true);
EXPECT_EQ(skel_3.mSkelNit1, skel_3.graph().nodes().second);
EXPECT_EQ(skel_3.mSkelNit2, skelNodes_3[2]);
EXPECT_EQ(skel_3.mSkelEit1, *(virtualEdges_3.begin()));
EXPECT_EQ(skel_3.mSkelEit2, skel_3.graph().edges().second);
auto& SVE1_3 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_3.mSkelEit1));
EXPECT_EQ((SVE1_3.incidentNode1().backIt() == skelNodes_3[0] &&
SVE1_3.incidentNode2().backIt() == skelNodes_3[1] )||
(SVE1_3.incidentNode1().backIt() == skelNodes_3[1] &&
SVE1_3.incidentNode2().backIt() == skelNodes_3[0] ) , true);
index++;
nItIt++;
}
/** @brief Tests GMWSkeletonGenerator::processBlock()
* realistic.
*/
TEST_F(GMWSkeletonGeneratorTests, Test9) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeletonGenerator skelGen;
node_list_it_t bnit1 = bn_03.backIt();
node_list_it_t bnit2 = bn_19.backIt();
skelGen.processBlock(B01, bnit1, bnit2);
EXPECT_EQ(skelGen.numSkeletons(), 4);
auto& skel_0 = skelGen.skeleton(0);
vector<node_list_it_t> blockNodesExpected_0;
blockNodesExpected_0.push_back(bn_01.backIt());
blockNodesExpected_0.push_back(bn_02.backIt());
blockNodesExpected_0.push_back(bn_03.backIt());
blockNodesExpected_0.push_back(bn_04.backIt());
blockNodesExpected_0.push_back(bn_05.backIt());
blockNodesExpected_0.push_back(bn_06.backIt());
blockNodesExpected_0.push_back(bn_07.backIt());
blockNodesExpected_0.push_back(bn_08.backIt());
EXPECT_EQ(skel_0.graph().numNodes(), 8);
EXPECT_EQ(skel_0.graph().numEdges(), 12);
vector<node_list_it_t> skelNodes_0;
EXPECT_EQ(
checkSkelNodes(skel_0.graph(), blockNodesExpected_0, skelNodes_0), true);
vector<edge_list_it_t> skelEdgesTested_0;
vector<edge_list_it_t> virtualEdges_0;
skelEdgesTested_0.push_back(be_01_02.backIt());
skelEdgesTested_0.push_back(be_01_03.backIt());
skelEdgesTested_0.push_back(be_01_07.backIt());
skelEdgesTested_0.push_back(be_02_04.backIt());
skelEdgesTested_0.push_back(be_02_08.backIt());
skelEdgesTested_0.push_back(be_03_04.backIt());
skelEdgesTested_0.push_back(be_03_05.backIt());
skelEdgesTested_0.push_back(be_04_06.backIt());
skelEdgesTested_0.push_back(be_05_06.backIt());
skelEdgesTested_0.push_back(be_05_07.backIt());
skelEdgesTested_0.push_back(be_06_08.backIt());
EXPECT_EQ(checkSkelEdges(
skel_0.graph(), skelEdgesTested_0, 1, virtualEdges_0), true);
EXPECT_EQ(skelNodes_0.size(),8);
EXPECT_EQ(skel_0.mSkelNit1, skelNodes_0[2]);
EXPECT_EQ(skel_0.mSkelNit2, skel_0.graph().nodes().second);
EXPECT_EQ(skel_0.mSkelEit1, skel_0.graph().edges().second);
EXPECT_EQ(skel_0.mSkelEit2, *(virtualEdges_0.begin()));
auto& SVE2_0 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_0.mSkelEit2));
EXPECT_EQ((SVE2_0.incidentNode1().backIt() == skelNodes_0[6] &&
SVE2_0.incidentNode2().backIt() == skelNodes_0[7] )||
(SVE2_0.incidentNode1().backIt() == skelNodes_0[7] &&
SVE2_0.incidentNode2().backIt() == skelNodes_0[6] ) , true);
auto& skel_1 = skelGen.skeleton(1);
vector<node_list_it_t> blockNodesExpected_1;
blockNodesExpected_1.push_back(bn_09.backIt());
blockNodesExpected_1.push_back(bn_10.backIt());
blockNodesExpected_1.push_back(bn_11.backIt());
blockNodesExpected_1.push_back(bn_12.backIt());
EXPECT_EQ(skel_1.graph().numNodes(), 4);
EXPECT_EQ(skel_1.graph().numEdges(), 6);
vector<node_list_it_t> skelNodes_1;
EXPECT_EQ(
checkSkelNodes(skel_1.graph(), blockNodesExpected_1, skelNodes_1), true);
vector<edge_list_it_t> skelEdgesTested_1;
vector<edge_list_it_t> virtualEdges_1;
skelEdgesTested_1.push_back(be_09_11.backIt());
skelEdgesTested_1.push_back(be_09_12.backIt());
skelEdgesTested_1.push_back(be_10_11.backIt());
skelEdgesTested_1.push_back(be_11_12.backIt());
EXPECT_EQ(checkSkelEdges(
skel_1.graph(), skelEdgesTested_1, 2, virtualEdges_1), true);
EXPECT_EQ(skelNodes_1.size(),4);
EXPECT_EQ(skel_1.mSkelNit1, skel_1.graph().nodes().second);
EXPECT_EQ(skel_1.mSkelNit2, skel_1.graph().nodes().second);
EXPECT_EQ(skel_1.mSkelEit1, *(virtualEdges_1.begin()));
EXPECT_EQ(skel_1.mSkelEit2, *(virtualEdges_1.rbegin()));
auto& SVE1_1 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_1.mSkelEit1));
EXPECT_EQ((SVE1_1.incidentNode1().backIt() == skelNodes_1[0] &&
SVE1_1.incidentNode2().backIt() == skelNodes_1[1] )||
(SVE1_1.incidentNode1().backIt() == skelNodes_1[1] &&
SVE1_1.incidentNode2().backIt() == skelNodes_1[0] ) , true);
auto& SVE2_1 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_1.mSkelEit2));
EXPECT_EQ((SVE2_1.incidentNode1().backIt() == skelNodes_1[1] &&
SVE2_1.incidentNode2().backIt() == skelNodes_1[3] )||
(SVE2_1.incidentNode1().backIt() == skelNodes_1[3] &&
SVE2_1.incidentNode2().backIt() == skelNodes_1[1] ) , true);
auto& skel_2 = skelGen.skeleton(2);
vector<node_list_it_t> blockNodesExpected_2;
blockNodesExpected_2.push_back(bn_10.backIt());
blockNodesExpected_2.push_back(bn_12.backIt());
blockNodesExpected_2.push_back(bn_17.backIt());
blockNodesExpected_2.push_back(bn_18.backIt());
EXPECT_EQ(skel_2.graph().numNodes(), 4);
EXPECT_EQ(skel_2.graph().numEdges(), 6);
vector<node_list_it_t> skelNodes_2;
EXPECT_EQ(
checkSkelNodes(skel_2.graph(), blockNodesExpected_2, skelNodes_2), true);
vector<edge_list_it_t> skelEdgesTested_2;
vector<edge_list_it_t> virtualEdges_2;
skelEdgesTested_2.push_back(be_10_17.backIt());
skelEdgesTested_2.push_back(be_12_17.backIt());
skelEdgesTested_2.push_back(be_10_18.backIt());
skelEdgesTested_2.push_back(be_17_18.backIt());
EXPECT_EQ(checkSkelEdges(
skel_2.graph(), skelEdgesTested_2, 2, virtualEdges_2), true);
EXPECT_EQ(skelNodes_2.size(),4);
EXPECT_EQ(skel_2.mSkelNit1, skel_2.graph().nodes().second);
EXPECT_EQ(skel_2.mSkelNit2, skel_2.graph().nodes().second);
EXPECT_EQ(skel_2.mSkelEit1, *(virtualEdges_2.begin()));
EXPECT_EQ(skel_2.mSkelEit2, *(virtualEdges_2.rbegin()));
auto& SVE1_2 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_2.mSkelEit1));
EXPECT_EQ((SVE1_2.incidentNode1().backIt() == skelNodes_2[0] &&
SVE1_2.incidentNode2().backIt() == skelNodes_2[1] )||
(SVE1_2.incidentNode1().backIt() == skelNodes_2[1] &&
SVE1_2.incidentNode2().backIt() == skelNodes_2[0] ) , true);
auto& SVE2_2 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_2.mSkelEit2));
EXPECT_EQ((SVE2_2.incidentNode1().backIt() == skelNodes_2[1] &&
SVE2_2.incidentNode2().backIt() == skelNodes_2[3] )||
(SVE2_2.incidentNode1().backIt() == skelNodes_2[3] &&
SVE2_2.incidentNode2().backIt() == skelNodes_2[1] ) , true);
auto& skel_3 = skelGen.skeleton(3);
vector<node_list_it_t> blockNodesExpected_3;
blockNodesExpected_3.push_back(bn_12.backIt());
blockNodesExpected_3.push_back(bn_18.backIt());
blockNodesExpected_3.push_back(bn_19.backIt());
blockNodesExpected_3.push_back(bn_20.backIt());
blockNodesExpected_3.push_back(bn_21.backIt());
blockNodesExpected_3.push_back(bn_22.backIt());
EXPECT_EQ(skel_3.graph().numNodes(), 6);
EXPECT_EQ(skel_3.graph().numEdges(), 9);
vector<node_list_it_t> skelNodes_3;
EXPECT_EQ(
checkSkelNodes(skel_3.graph(), blockNodesExpected_3, skelNodes_3), true);
vector<edge_list_it_t> skelEdgesTested_3;
vector<edge_list_it_t> virtualEdges_3;
skelEdgesTested_3.push_back(be_12_21.backIt());
skelEdgesTested_3.push_back(be_12_19.backIt());
skelEdgesTested_3.push_back(be_19_21.backIt());
skelEdgesTested_3.push_back(be_19_20.backIt());
skelEdgesTested_3.push_back(be_21_22.backIt());
skelEdgesTested_3.push_back(be_18_20.backIt());
skelEdgesTested_3.push_back(be_18_22.backIt());
skelEdgesTested_3.push_back(be_20_22.backIt());
EXPECT_EQ(checkSkelEdges(
skel_3.graph(), skelEdgesTested_3, 1, virtualEdges_3), true);
EXPECT_EQ(skelNodes_3.size(),6);
EXPECT_EQ(skel_3.mSkelNit1, skel_3.graph().nodes().second);
EXPECT_EQ(skel_3.mSkelNit2, skelNodes_3[2]);
EXPECT_EQ(skel_3.mSkelEit1, *(virtualEdges_3.rbegin()));
EXPECT_EQ(skel_3.mSkelEit2, skel_3.graph().edges().second);
auto& SVE1_3 = dynamic_cast<GMWSkeletonEdge&>(*(*skel_3.mSkelEit1));
EXPECT_EQ((SVE1_3.incidentNode1().backIt() == skelNodes_3[0] &&
SVE1_3.incidentNode2().backIt() == skelNodes_3[1] )||
(SVE1_3.incidentNode1().backIt() == skelNodes_3[1] &&
SVE1_3.incidentNode2().backIt() == skelNodes_3[0] ) , true);
}
/** @brief Tests GMWSkeletonGenerator::processBlock()
* one node
*/
TEST_F(GMWSkeletonGeneratorTests, Test10) {
#include "unit_tests/undirected/unit_tests_gmw_skeleton_generator_gen_tree_inc.inc"
GMWSkeletonGenerator skelGen;
node_list_it_t bnit1 = bn_13.backIt();
node_list_it_t bnit2 = bn_14.backIt();
skelGen.processBlock(B01, bnit1, bnit2);
EXPECT_EQ(skelGen.numSkeletons(), 1);
auto& skel_0 = skelGen.skeleton(0);
vector<node_list_it_t> blockNodesExpected_0;
blockNodesExpected_0.push_back(bn_01.backIt());
blockNodesExpected_0.push_back(bn_02.backIt());
blockNodesExpected_0.push_back(bn_03.backIt());
blockNodesExpected_0.push_back(bn_04.backIt());
blockNodesExpected_0.push_back(bn_05.backIt());
blockNodesExpected_0.push_back(bn_06.backIt());
blockNodesExpected_0.push_back(bn_07.backIt());
blockNodesExpected_0.push_back(bn_08.backIt());
blockNodesExpected_0.push_back(bn_09.backIt());
blockNodesExpected_0.push_back(bn_10.backIt());
blockNodesExpected_0.push_back(bn_11.backIt());
blockNodesExpected_0.push_back(bn_12.backIt());
blockNodesExpected_0.push_back(bn_13.backIt());
blockNodesExpected_0.push_back(bn_14.backIt());
blockNodesExpected_0.push_back(bn_15.backIt());
blockNodesExpected_0.push_back(bn_16.backIt());
blockNodesExpected_0.push_back(bn_17.backIt());
blockNodesExpected_0.push_back(bn_18.backIt());
blockNodesExpected_0.push_back(bn_19.backIt());
blockNodesExpected_0.push_back(bn_20.backIt());
blockNodesExpected_0.push_back(bn_21.backIt());
blockNodesExpected_0.push_back(bn_22.backIt());
EXPECT_EQ(skel_0.graph().numNodes(), 22);
EXPECT_EQ(skel_0.graph().numEdges(), 39);
vector<node_list_it_t> skelNodes_0;
EXPECT_EQ(
checkSkelNodes(skel_0.graph(), blockNodesExpected_0, skelNodes_0), true);
vector<edge_list_it_t> skelEdgesTested_0;
vector<edge_list_it_t> virtualEdges_0;
skelEdgesTested_0.push_back(be_01_02.backIt());
skelEdgesTested_0.push_back(be_01_03.backIt());
skelEdgesTested_0.push_back(be_01_07.backIt());
skelEdgesTested_0.push_back(be_02_04.backIt());
skelEdgesTested_0.push_back(be_02_08.backIt());
skelEdgesTested_0.push_back(be_03_04.backIt());
skelEdgesTested_0.push_back(be_03_05.backIt());
skelEdgesTested_0.push_back(be_04_06.backIt());
skelEdgesTested_0.push_back(be_05_06.backIt());
skelEdgesTested_0.push_back(be_05_07.backIt());
skelEdgesTested_0.push_back(be_06_08.backIt());
skelEdgesTested_0.push_back(be_07_09.backIt());
skelEdgesTested_0.push_back(be_08_15.backIt());
skelEdgesTested_0.push_back(be_08_13.backIt());
skelEdgesTested_0.push_back(be_13_15.backIt());
skelEdgesTested_0.push_back(be_13_14.backIt());
skelEdgesTested_0.push_back(be_15_16.backIt());
skelEdgesTested_0.push_back(be_14_10.backIt());
skelEdgesTested_0.push_back(be_14_16.backIt());
skelEdgesTested_0.push_back(be_10_16.backIt());
skelEdgesTested_0.push_back(be_09_10.backIt());
skelEdgesTested_0.push_back(be_09_11.backIt());
skelEdgesTested_0.push_back(be_10_11.backIt());
skelEdgesTested_0.push_back(be_09_12.backIt());
skelEdgesTested_0.push_back(be_11_12.backIt());
skelEdgesTested_0.push_back(be_10_12.backIt());
skelEdgesTested_0.push_back(be_10_17.backIt());
skelEdgesTested_0.push_back(be_10_18.backIt());
skelEdgesTested_0.push_back(be_12_17.backIt());
skelEdgesTested_0.push_back(be_17_18.backIt());
skelEdgesTested_0.push_back(be_12_18.backIt());
skelEdgesTested_0.push_back(be_12_21.backIt());
skelEdgesTested_0.push_back(be_12_19.backIt());
skelEdgesTested_0.push_back(be_19_20.backIt());
skelEdgesTested_0.push_back(be_18_20.backIt());
skelEdgesTested_0.push_back(be_18_22.backIt());
skelEdgesTested_0.push_back(be_20_22.backIt());
skelEdgesTested_0.push_back(be_19_21.backIt());
skelEdgesTested_0.push_back(be_21_22.backIt());
EXPECT_EQ(checkSkelEdges(
skel_0.graph(), skelEdgesTested_0, 0, virtualEdges_0), true);
EXPECT_EQ(skelNodes_0.size(),22);
EXPECT_EQ(skel_0.mSkelNit1, skelNodes_0[12]);
EXPECT_EQ(skel_0.mSkelNit2, skelNodes_0[13]);
EXPECT_EQ(skel_0.mSkelEit1, skel_0.graph().edges().second);
EXPECT_EQ(skel_0.mSkelEit2, skel_0.graph().edges().second);
}
} // namespace Undirected
} // namespace Wailea
| 35.748227 | 87 | 0.669924 | ShoYamanishi |
fc54ebae2d6bc709d29b0f08c882c3a4bb9d7360 | 9,852 | cxx | C++ | bpkg/manifest-utility.cxx | build2/bpkg | bd939839b44d90d027517e447537dd52539269ff | [
"MIT"
] | 19 | 2018-05-30T12:01:25.000Z | 2022-01-29T21:37:23.000Z | bpkg/manifest-utility.cxx | build2/bpkg | bd939839b44d90d027517e447537dd52539269ff | [
"MIT"
] | 2 | 2019-03-18T22:31:45.000Z | 2020-07-28T06:44:03.000Z | bpkg/manifest-utility.cxx | build2/bpkg | bd939839b44d90d027517e447537dd52539269ff | [
"MIT"
] | 1 | 2019-02-04T02:58:14.000Z | 2019-02-04T02:58:14.000Z | // file : bpkg/manifest-utility.cxx -*- C++ -*-
// license : MIT; see accompanying LICENSE file
#include <bpkg/manifest-utility.hxx>
#include <cstring> // strcspn()
#include <libbutl/b.hxx>
#include <libbutl/sha256.hxx>
#include <bpkg/package.hxx> // wildcard_version
#include <bpkg/diagnostics.hxx>
#include <bpkg/common-options.hxx>
using namespace std;
using namespace butl;
namespace bpkg
{
const path repositories_file ("repositories.manifest");
const path packages_file ("packages.manifest");
const path signature_file ("signature.manifest");
const path manifest_file ("manifest");
vector<package_info>
package_b_info (const common_options& o, const dir_paths& ds, bool ext_mods)
{
path b (name_b (o));
vector<package_info> r;
try
{
b_info (r,
ds,
ext_mods,
verb,
[] (const char* const args[], size_t n)
{
if (verb >= 2)
print_process (args, n);
},
b,
exec_dir,
o.build_option ());
return r;
}
catch (const b_error& e)
{
if (e.normal ())
throw failed (); // Assume the build2 process issued diagnostics.
diag_record dr (fail);
dr << "unable to parse project ";
if (r.size () < ds.size ()) dr << ds[r.size ()] << ' ';
dr << "info: " << e <<
info << "produced by '" << b << "'; use --build to override" << endf;
}
}
package_scheme
parse_package_scheme (const char*& s)
{
// Ignore the character case for consistency with a case insensitivity of
// URI schemes some of which we may support in the future.
//
if (icasecmp (s, "sys:", 4) == 0)
{
s += 4;
return package_scheme::sys;
}
return package_scheme::none;
}
package_name
parse_package_name (const char* s, bool allow_version)
{
try
{
return extract_package_name (s, allow_version);
}
catch (const invalid_argument& e)
{
fail << "invalid package name " << (allow_version ? "in " : "")
<< "'" << s << "': " << e << endf;
}
}
version
parse_package_version (const char* s,
bool allow_wildcard,
version::flags fl)
{
using traits = string::traits_type;
if (const char* p = traits::find (s, traits::length (s), '/'))
{
if (*++p == '\0')
fail << "empty package version in '" << s << "'";
if (allow_wildcard && strcmp (p, "*") == 0)
return wildcard_version;
try
{
return extract_package_version (s, fl);
}
catch (const invalid_argument& e)
{
fail << "invalid package version '" << p << "' in '" << s << "': "
<< e;
}
}
return version ();
}
optional<version_constraint>
parse_package_version_constraint (const char* s,
bool allow_wildcard,
version::flags fl,
bool version_only)
{
// Calculate the version specification position as a length of the prefix
// that doesn't contain slashes and the version constraint starting
// characters.
//
size_t n (strcspn (s, "/=<>([~^"));
if (s[n] == '\0') // No version (constraint) is specified?
return nullopt;
const char* v (s + n); // Constraint or version including '/'.
// If only the version is allowed or the package name is followed by '/'
// then fallback to the version parsing.
//
if (version_only || v[0] == '/')
try
{
return version_constraint (
parse_package_version (s, allow_wildcard, fl));
}
catch (const invalid_argument& e)
{
fail << "invalid package version '" << v + 1 << "' in '" << s << "': "
<< e;
}
try
{
version_constraint r (v);
if (!r.complete ())
throw invalid_argument ("incomplete");
// There doesn't seem to be any good reason to allow specifying a stub
// version in the version constraint. Note that the constraint having
// both endpoints set to the wildcard version (which is a stub) denotes
// the system package wildcard version and may result only from the '/*'
// string representation.
//
auto stub = [] (const optional<version>& v)
{
return v && v->compare (wildcard_version, true) == 0;
};
if (stub (r.min_version) || stub (r.max_version))
throw invalid_argument ("endpoint is a stub");
return r;
}
catch (const invalid_argument& e)
{
fail << "invalid package version constraint '" << v << "' in '" << s
<< "': " << e << endf;
}
}
repository_location
parse_location (const string& s, optional<repository_type> ot)
try
{
typed_repository_url tu (s);
repository_url& u (tu.url);
assert (u.path);
// Make the relative path absolute using the current directory.
//
if (u.scheme == repository_protocol::file && u.path->relative ())
u.path->complete ().normalize ();
// Guess the repository type to construct the repository location:
//
// 1. If the type is specified in the URL scheme, then use that (but
// validate that it matches the --type option, if present).
//
// 2. If the type is specified as an option, then use that.
//
// Validate the protocol/type compatibility (e.g. git:// vs pkg) for both
// cases.
//
// 3. See the guess_type() function description in <libbpkg/manifest.hxx>
// for the algorithm details.
//
if (tu.type && ot && tu.type != ot)
fail << to_string (*ot) << " repository type mismatch for location '"
<< s << "'";
repository_type t (tu.type ? *tu.type :
ot ? *ot :
guess_type (tu.url, true /* local */));
try
{
// Don't move the URL since it may still be needed for diagnostics.
//
return repository_location (u, t);
}
catch (const invalid_argument& e)
{
diag_record dr;
dr << fail << "invalid " << t << " repository location '" << u << "': "
<< e;
// If the pkg repository type was guessed, then suggest the user to
// specify the type explicitly.
//
if (!tu.type && !ot && t == repository_type::pkg)
dr << info << "consider using --type to specify repository type";
dr << endf;
}
}
catch (const invalid_path& e)
{
fail << "invalid repository path '" << s << "': " << e << endf;
}
catch (const invalid_argument& e)
{
fail << "invalid repository location '" << s << "': " << e << endf;
}
catch (const system_error& e)
{
fail << "failed to guess repository type for '" << s << "': " << e << endf;
}
dir_path
repository_state (const repository_location& rl)
{
switch (rl.type ())
{
case repository_type::pkg:
case repository_type::dir: return dir_path (); // No state.
case repository_type::git:
{
// Strip the fragment, so all the repository fragments of the same
// git repository can reuse the state. So, for example, the state is
// shared for the fragments fetched from the following git repository
// locations:
//
// https://www.example.com/foo.git#master
// git://example.com/foo#stable
//
repository_url u (rl.url ());
u.fragment = nullopt;
repository_location l (u, rl.type ());
return dir_path (sha256 (l.canonical_name ()).abbreviated_string (12));
}
}
assert (false); // Can't be here.
return dir_path ();
}
bool
repository_name (const string& s)
{
size_t p (s.find (':'));
// If it has no scheme, then this is not a canonical name.
//
if (p == string::npos)
return false;
// This is a canonical name if the scheme is convertible to the repository
// type and is followed by the colon and no more than one slash.
//
// Note that the approach is valid unless we invent the file scheme for the
// canonical name.
//
try
{
string scheme (s, 0, p);
to_repository_type (scheme);
bool r (!(p + 2 < s.size () && s[p + 1] == '/' && s[p + 2] == '/'));
assert (!r || scheme != "file");
return r;
}
catch (const invalid_argument&)
{
return false;
}
}
package_version_infos
package_versions (const common_options& o, const dir_paths& ds)
{
vector<b_project_info> pis (package_b_info (o, ds, false /* ext_mods */));
package_version_infos r;
r.reserve (pis.size ());
for (const b_project_info& pi: pis)
{
// An empty version indicates that the version module is not enabled for
// the project.
//
optional<version> v (!pi.version.empty ()
? version (pi.version.string ())
: optional<version> ());
r.push_back (package_version_info {move (v), move (pi)});
}
return r;
}
string
package_checksum (const common_options& o,
const dir_path& d,
const package_info* pi)
{
path f (d / manifest_file);
try
{
ifdstream is (f, fdopen_mode::binary);
sha256 cs (is);
const vector<package_info::subproject>& sps (
pi != nullptr
? pi->subprojects
: package_b_info (o, d, false /* ext_mods */).subprojects);
for (const package_info::subproject& sp: sps)
cs.append (sp.path.string ());
return cs.string ();
}
catch (const io_error& e)
{
fail << "unable to read from " << f << ": " << e << endf;
}
}
}
| 27.290859 | 79 | 0.554101 | build2 |
fc5808b152bd73ca1016d2c5a73d94e35028f83f | 1,657 | cpp | C++ | compiler/locomotiv/src/Node/Push.cpp | bogus-sudo/ONE-1 | 7052a817eff661ec2854ed2e7ee0de5e8ba82b55 | [
"Apache-2.0"
] | 1 | 2020-05-22T13:53:40.000Z | 2020-05-22T13:53:40.000Z | compiler/locomotiv/src/Node/Push.cpp | bogus-sudo/ONE-1 | 7052a817eff661ec2854ed2e7ee0de5e8ba82b55 | [
"Apache-2.0"
] | null | null | null | compiler/locomotiv/src/Node/Push.cpp | bogus-sudo/ONE-1 | 7052a817eff661ec2854ed2e7ee0de5e8ba82b55 | [
"Apache-2.0"
] | 1 | 2021-07-22T11:02:43.000Z | 2021-07-22T11:02:43.000Z | /*
* Copyright (c) 2019 Samsung Electronics Co., Ltd. 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 "NodeExecution.h"
#include "NodeDataImpl.h"
#include "NodeDomain.h"
#include "Validation.h"
#include <stdexcept>
#include <cassert>
namespace locomotiv
{
void NodeExecution::execute(loco::Push *push)
{
auto from_data = annot_data(push->from());
validate(from_data, "Ingredient not ready");
validate(annot_domain(push->from()) == loco::Domain::Tensor, "Ingredient of Push is not tensor");
std::unique_ptr<NodeData> push_data = nullptr;
switch (from_data->dtype())
{
case loco::DataType::S32:
{
auto from_bufptr = from_data->as_s32_bufptr();
push_data = make_data(*from_bufptr);
break;
}
case loco::DataType::FLOAT32:
{
auto from_bufptr = from_data->as_f32_bufptr();
push_data = make_data(*from_bufptr);
break;
}
default:
throw std::runtime_error("NYI for this DataType");
}
assert(push_data != nullptr);
annot_data(push, std::move(push_data));
annot_domain(push, loco::Domain::Tensor);
}
} // namespace locomotiv
| 26.725806 | 99 | 0.69825 | bogus-sudo |
fc5c99772fa986d19ee6333bab7a0bebb40884cd | 208 | cpp | C++ | questions/47971176/main.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 302 | 2017-03-04T00:05:23.000Z | 2022-03-28T22:51:29.000Z | questions/47971176/main.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 30 | 2017-12-02T19:26:43.000Z | 2022-03-28T07:40:36.000Z | questions/47971176/main.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 388 | 2017-07-04T16:53:12.000Z | 2022-03-18T22:20:19.000Z | #include "widget.h"
#include "worker.h"
#include <QApplication>
#include <QPushButton>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Widget widget;
widget.show();
return a.exec();
}
| 17.333333 | 34 | 0.677885 | sesu089 |
fc5f2b37a9c3575f80b8eacb5f133a2c5277dccc | 2,040 | cpp | C++ | engine/Engine.UI/src/ui/adapter/RecyclerView.cpp | ZieIony/Ghurund | be84166ef0aba5556910685b7a3b754b823da556 | [
"MIT"
] | 66 | 2018-12-16T21:03:36.000Z | 2022-03-26T12:23:57.000Z | engine/Engine.UI/src/ui/adapter/RecyclerView.cpp | ZieIony/Ghurund | be84166ef0aba5556910685b7a3b754b823da556 | [
"MIT"
] | 57 | 2018-04-24T20:53:01.000Z | 2021-02-21T12:14:20.000Z | engine/Engine.UI/src/ui/adapter/RecyclerView.cpp | ZieIony/Ghurund | be84166ef0aba5556910685b7a3b754b823da556 | [
"MIT"
] | 7 | 2019-07-16T08:25:25.000Z | 2022-03-21T08:29:46.000Z | #include "ghuipch.h"
#include "RecyclerView.h"
#include "core/reflection/TypeBuilder.h"
#include "ui/Canvas.h"
namespace Ghurund::UI {
const Ghurund::Core::Type& RecyclerView::GET_TYPE() {
static const auto CONSTRUCTOR = Constructor<RecyclerView>();
static const Ghurund::Core::Type TYPE = TypeBuilder<RecyclerView>(NAMESPACE_NAME, GH_STRINGIFY(RecyclerView))
.withConstructor(CONSTRUCTOR)
.withSupertype(__super::GET_TYPE());
return TYPE;
}
void RecyclerView::onDraw(Canvas& canvas) {
if (!layoutManager)
return;
canvas.save();
canvas.clipRect(0, 0, Size.width, Size.height);
auto& scroll = layoutManager->Scroll;
canvas.translate(scroll.x, scroll.y);
for (Control* c : Children)
c->draw(canvas);
canvas.restoreClipRect();
canvas.restore();
}
bool RecyclerView::dispatchMouseButtonEvent(const MouseButtonEventArgs& event) {
if (!layoutManager)
return false;
const FloatPoint& scroll = layoutManager->Scroll;
return __super::dispatchMouseButtonEvent(event.translate(-scroll.x, -scroll.y, event.Inside));
}
bool RecyclerView::dispatchMouseMotionEvent(const MouseMotionEventArgs& event) {
if (!layoutManager)
return false;
const FloatPoint& scroll = layoutManager->Scroll;
return __super::dispatchMouseMotionEvent(event.translate(-scroll.x, -scroll.y, event.Inside));
}
bool RecyclerView::dispatchMouseWheelEvent(const MouseWheelEventArgs& args) {
if (layoutManager && childrenProvider) {
if (args.Wheel == MouseWheel::VERTICAL) {
layoutManager->scrollBy(0, (float)args.Delta);
onScrolled();
repaint();
} else {
layoutManager->scrollBy((float)args.Delta, 0);
onScrolled();
repaint();
}
}
return OnMouseWheel(args);
}
}
| 32.380952 | 117 | 0.613235 | ZieIony |
fc61559c4a4edb821cb64c7d5840c59af574094c | 940 | cpp | C++ | Stp/Base/Thread/ThreadChecker.cpp | markazmierczak/Polonite | 240f099cafc5c38dc1ae1cc6fc5773e13f65e9de | [
"MIT"
] | 1 | 2019-07-11T12:47:52.000Z | 2019-07-11T12:47:52.000Z | Stp/Base/Thread/ThreadChecker.cpp | Polonite/Polonite | 240f099cafc5c38dc1ae1cc6fc5773e13f65e9de | [
"MIT"
] | null | null | null | Stp/Base/Thread/ThreadChecker.cpp | Polonite/Polonite | 240f099cafc5c38dc1ae1cc6fc5773e13f65e9de | [
"MIT"
] | 1 | 2019-07-11T12:47:53.000Z | 2019-07-11T12:47:53.000Z | // Copyright 2017 Polonite Authors. All rights reserved.
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "Base/Thread/ThreadChecker.h"
#if ASSERT_IS_ON
namespace stp {
ThreadChecker::ThreadChecker() {
EnsureThreadIdAssigned();
}
ThreadChecker::~ThreadChecker() {}
bool ThreadChecker::calledOnValidThread() const {
EnsureThreadIdAssigned();
AutoLock auto_lock(borrow(lock_));
return valid_thread_ == NativeThread::currentHandle();
}
void ThreadChecker::DetachFromThread() {
AutoLock auto_lock(borrow(lock_));
valid_thread_ = InvalidNativeThreadHandle;
}
void ThreadChecker::EnsureThreadIdAssigned() const {
AutoLock auto_lock(borrow(lock_));
if (valid_thread_ == InvalidNativeThreadHandle)
valid_thread_ = NativeThread::currentHandle();
}
} // namespace stp
#endif // ASSERT_IS_ON
| 24.736842 | 73 | 0.760638 | markazmierczak |
fc63b4bb05645fc32710d3a6a4180d059611c680 | 174 | cxx | C++ | StRoot/RTS/src/DAQ_SSD/ssdReader.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/RTS/src/DAQ_SSD/ssdReader.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/RTS/src/DAQ_SSD/ssdReader.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | #include <sys/types.h>
#include "RTS/src/DAQ_READER/daqReader.h"
#include <DAQ_READER/daq_dta.h>
#include <DAQ_READER/daq_det.h>
#include "ssdReader.h"
DAQ_LEGACY_DEF(ssd);
| 21.75 | 41 | 0.764368 | xiaohaijin |
fc6a4314f477dffa086ae1c52382c4b19b12fe46 | 1,774 | cpp | C++ | applications/about/main.cpp | innerout/skift | e44a77adafa99676fa1a011d94b7a44eefbce18c | [
"MIT"
] | 2 | 2021-08-14T16:03:48.000Z | 2021-11-09T10:29:36.000Z | applications/about/main.cpp | optimisticside/skift | 3d59b222d686c83e370e8075506d129f8ff1fdac | [
"MIT"
] | null | null | null | applications/about/main.cpp | optimisticside/skift | 3d59b222d686c83e370e8075506d129f8ff1fdac | [
"MIT"
] | 2 | 2020-10-13T14:25:30.000Z | 2020-10-13T14:39:40.000Z | #include <libsystem/BuildInfo.h>
#include <libwidget/Application.h>
#include <libwidget/Markup.h>
#include <libwidget/Widgets.h>
#include <libwidget/widgets/TextField.h>
static auto logo_based_on_color_scheme()
{
auto path = theme_is_dark() ? "/Applications/about/logo-white.png"
: "/Applications/about/logo-black.png";
return Bitmap::load_from_or_placeholder(path);
}
int main(int argc, char **argv)
{
application_initialize(argc, argv);
Window *window = window_create_from_file("/Applications/about/about.markup");
window->with_widget<Image>("system-image", [&](auto image) {
image->change_bitmap(logo_based_on_color_scheme());
});
window->with_widget<Label>("version-label", [&](auto label) {
label->text(__BUILD_VERSION__);
});
window->with_widget<Label>("commit-label", [&](auto label) {
label->text(__BUILD_GITREF__ "/" __BUILD_CONFIG__);
});
window->with_widget<Button>("license-button", [&](auto button) {
button->on(Event::ACTION, [window](auto) {
auto license_window = new Window(WINDOW_NONE);
license_window->title("License");
license_window->size({556, 416});
auto field = new TextField(license_window->root(), TextModel::from_file("/Files/license.md"));
field->attributes(LAYOUT_FILL);
field->readonly(true);
field->font(Font::create("mono").take_value());
field->focus();
license_window->show();
});
});
window->with_widget<Button>("ok-button", [&](auto button) {
button->on(Event::ACTION, [window](auto) {
window->hide();
});
});
window->show();
return application_run();
}
| 30.067797 | 106 | 0.614994 | innerout |
fc6ff2dbce458572e2e499af449318b67ccb40a3 | 2,115 | cpp | C++ | modules/libavparser/libavparser.cpp | Colinwang531/av_converged_communication_system_architecture | d8d8a2ff72b5342fd0c3426978884c0e9c43dde8 | [
"MIT"
] | 2 | 2021-12-10T07:45:30.000Z | 2021-12-17T01:42:36.000Z | modules/libavparser/libavparser.cpp | Colinwang531/av_converged_communication_system_architecture | d8d8a2ff72b5342fd0c3426978884c0e9c43dde8 | [
"MIT"
] | null | null | null | modules/libavparser/libavparser.cpp | Colinwang531/av_converged_communication_system_architecture | d8d8a2ff72b5342fd0c3426978884c0e9c43dde8 | [
"MIT"
] | null | null | null | #include "boost/bind/bind.hpp"
using namespace boost::placeholders;
#include "boost/make_shared.hpp"
#include "error_code.h"
#include "map/unordered_map.h"
#include "buffer/buffer_parser.h"
#include "ps/ps_parser.h"
#include "rtp/rtp_es_parser.h"
#include "libavparser.h"
using namespace module::av::stream;
using AVParserNodePtr = boost::shared_ptr<AVParserNode>;
using AVParserNodePtrs = UnorderedMap<const uint32_t, AVParserNodePtr>;
static AVParserNodePtrs nodes;
Libavparser::Libavparser()
{}
Libavparser::~Libavparser()
{}
int Libavparser::addConf(const AVParserModeConf& conf)
{
int ret{
0 < conf.id ? Error_Code_Success : Error_Code_Invalid_Param};
if (Error_Code_Success == ret)
{
AVParserNodePtr node;
if (AVParserType::AV_PARSER_TYPE_BUFFER_PARSER == conf.type)
{
node = boost::make_shared<BufferParser>(
boost::bind(&Libavparser::afterParsedDataNotification, this, _1, _2),
conf.id,
conf.cache);
}
else if (AVParserType::AV_PARSER_TYPE_PS_PARSER == conf.type)
{
node = boost::make_shared<PSParser>(
boost::bind(&Libavparser::afterParsedDataNotification, this, _1, _2),
conf.id);
}
else if (AVParserType::AV_PARSER_TYPE_RTP_ES_PARSER == conf.type)
{
node = boost::make_shared<RTPESParser>(
boost::bind(&Libavparser::afterParsedDataNotification, this, _1, _2),
conf.id);
}
else
{
ret = Error_Code_Operate_Not_Support;
}
if (node)
{
nodes.add(conf.id, node);
}
}
return ret;
}
int Libavparser::removeConf(const uint32_t id/* = 0*/)
{
int ret{0 < id ? Error_Code_Success : Error_Code_Invalid_Param};
if (Error_Code_Success == ret)
{
AVParserNodePtr node{nodes.at(id)};
if (node)
{
nodes.remove(id);
}
else
{
ret = Error_Code_Object_Not_Exist;
}
}
return ret;
}
int Libavparser::input(
const uint32_t id/* = 0*/,
const void* avpkt/* = nullptr*/)
{
int ret{0 < id && avpkt ? Error_Code_Success : Error_Code_Invalid_Param};
if(Error_Code_Success == ret)
{
AVParserNodePtr node{nodes.at(id)};
ret = node ? node->input(avpkt) : Error_Code_Object_Not_Exist;
}
return ret;
}
| 21.15 | 74 | 0.705437 | Colinwang531 |
fc713583a57526add1657960aa4e6191346c46ac | 753 | hpp | C++ | cpp_kernels/global/mean_std_dev_u8.hpp | HipaccVX/HipaccVX | 0d469748df11c95f916b5a70f0006878f8550e3c | [
"MIT"
] | 1 | 2021-06-08T08:58:54.000Z | 2021-06-08T08:58:54.000Z | cpp_kernels/global/mean_std_dev_u8.hpp | HipaccVX/HipaccVX | 0d469748df11c95f916b5a70f0006878f8550e3c | [
"MIT"
] | 1 | 2021-11-13T14:55:55.000Z | 2021-11-13T14:55:55.000Z | cpp_kernels/global/mean_std_dev_u8.hpp | HipaccVX/HipaccVX | 0d469748df11c95f916b5a70f0006878f8550e3c | [
"MIT"
] | null | null | null | void Mean_Std_Dev_u8(float *out_mean, float *out_stddev,
unsigned char *in_data, const unsigned int in_width, const unsigned int in_height)
{
float fmean = 0.0f, fstddev = 0.0f;
double sum = 0.0, sum_diff_sqrs = 0.0;
for (long long y = 0; y < in_height; y++)
{
for (long long x = 0; x < in_width; x++)
{
sum += in_data[y * in_width + x];
}
}
fmean = (float)(sum / (in_width * in_height));
for (long long y = 0; y < in_height; y++)
{
for (long long x = 0; x < in_width; x++)
{
double value = in_data[y * in_width + x] - fmean;
sum_diff_sqrs += value * value;
}
}
fstddev = (float)sqrt(sum_diff_sqrs / (in_width * in_height));
*out_mean = fmean;
if (out_stddev != nullptr)
*out_stddev = fstddev;
}
| 26.892857 | 103 | 0.609562 | HipaccVX |
fc720d7eca2c7568df0133c28d7a5ef10fff7931 | 3,317 | cpp | C++ | Code/GeometryCommand/GeoCommandCreateFace.cpp | baojunli/FastCAE | a3f99f6402da564df87fcef30674ce5f44379962 | [
"BSD-3-Clause"
] | 2 | 2020-02-21T01:04:35.000Z | 2020-02-21T03:35:37.000Z | Code/GeometryCommand/GeoCommandCreateFace.cpp | Sunqia/FastCAE | cbc023fe07b6e306ceefae8b8bd7c12bc1562acb | [
"BSD-3-Clause"
] | 1 | 2020-03-06T04:49:42.000Z | 2020-03-06T04:49:42.000Z | Code/GeometryCommand/GeoCommandCreateFace.cpp | Sunqia/FastCAE | cbc023fe07b6e306ceefae8b8bd7c12bc1562acb | [
"BSD-3-Clause"
] | null | null | null | #include "GeoCommandCreateFace.h"
#include "geometry/geometrySet.h"
#include "geometry/geometryData.h"
#include <BRepFilletAPI_MakeChamfer.hxx>
#include <TopExp.hxx>
#include <TopoDS.hxx>
#include <TopoDS_TShape.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Wire.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Face.hxx>
#include <TopExp_Explorer.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <QDebug>
#include "GeoCommandCommon.h"
#include <list>
#include "geometry/geometryParaFace.h"
namespace Command
{
CommandCreateFace::CommandCreateFace(GUI::MainWindow* m, MainWidget::PreWindow* p)
:GeoCommandBase(m,p)
{
}
bool CommandCreateFace::execute()
{
if (_shapeHash.size() < 1) return false;
QList<Geometry::GeometrySet*> setList = _shapeHash.uniqueKeys();
std::list<TopoDS_Edge> edgeList;
for (int i = 0; i < setList.size(); ++i)
{
Geometry::GeometrySet* set = setList.at(i);
TopoDS_Shape* parent = set->getShape();
QList<int> shapes = _shapeHash.values(set);
const int count = shapes.size();
for (int j=0; j < count; ++j)
{
const int index = shapes.at(j);
TopExp_Explorer edgeExp(*parent, TopAbs_EDGE);
for (int k = 0; k < index; ++k) edgeExp.Next();
const TopoDS_Shape& shape = edgeExp.Current();
const TopoDS_Edge& E = TopoDS::Edge(shape);
edgeList.push_back(E);
}
}
std::vector<TopoDS_Wire> wireList = GeoCommandCommon::bulidWire(edgeList);
TopoDS_Shape resShape = GeoCommandCommon::makeFace(wireList);
if (resShape.IsNull()) return false;
TopoDS_Shape* successShape = new TopoDS_Shape;
*successShape = resShape;
Geometry::GeometrySet* newset = new Geometry::GeometrySet(Geometry::STEP);
newset->setName(_name);
newset->setShape(successShape);
//_geoData->appendGeometrySet(newset);
_result = newset;
if (_isEdit)
{
newset->setName(_editSet->getName());
_geoData->replaceSet(newset, _editSet);
emit removeDisplayActor(_editSet);
}
else
{
newset->setName(_name);
_geoData->appendGeometrySet(newset);
}
Geometry::GeometryParaFace* para = new Geometry::GeometryParaFace;
para->setName(_name);
para->setShapeHash(_shapeHash);
_result->setParameter(para);
GeoCommandBase::execute();
emit showSet(newset);
emit updateGeoTree();
return true;
}
void CommandCreateFace::undo()
{
emit removeDisplayActor(_result);
if (_isEdit)
{
_geoData->replaceSet(_editSet, _result);
emit showSet(_editSet);
}
else
{
_geoData->removeTopGeometrySet(_result);
}
emit updateGeoTree();
}
void CommandCreateFace::redo()
{
if (_isEdit)
{
_geoData->replaceSet(_result, _editSet);
emit removeDisplayActor(_editSet);
}
else
_geoData->appendGeometrySet(_result);
emit updateGeoTree();
emit showSet(_result);
}
void CommandCreateFace::releaseResult()
{
if (_result != nullptr) delete _result;
}
void CommandCreateFace::setShapeList(QMultiHash<Geometry::GeometrySet*, int> s)
{
_shapeHash = s;
}
void CommandCreateFace::setActor(QList<vtkActor*> ac)
{
_actor = ac;
}
void CommandCreateFace::setName(QString name)
{
_name = name;
}
}
| 23.863309 | 84 | 0.678324 | baojunli |
fc736d998561fbbaa43c300e8dea6813dda2f2c2 | 2,812 | cpp | C++ | SOLVER/src/preloop/utilities/PreloopFFTW.cpp | kuangdai/AxiSEM3D | fd9da14e9107783e3b07b936c67af2412146e099 | [
"MIT"
] | 17 | 2016-12-16T03:13:57.000Z | 2021-12-15T01:56:45.000Z | SOLVER/src/preloop/utilities/PreloopFFTW.cpp | syzeng-duduxi/AxiSEM3D | fd9da14e9107783e3b07b936c67af2412146e099 | [
"MIT"
] | 6 | 2018-01-15T17:17:20.000Z | 2020-03-18T09:53:58.000Z | SOLVER/src/preloop/utilities/PreloopFFTW.cpp | syzeng-duduxi/AxiSEM3D | fd9da14e9107783e3b07b936c67af2412146e099 | [
"MIT"
] | 19 | 2016-12-28T16:55:00.000Z | 2021-06-23T01:02:16.000Z | // PreloopFFTW.cpp
// created by Kuangdai on 21-Sep-2016
// perform FFT using fftw
#include "PreloopFFTW.h"
int PreloopFFTW::sNmax = 0;
std::vector<fftw_plan> PreloopFFTW::sR2CPlans;
std::vector<fftw_plan> PreloopFFTW::sC2RPlans;
std::vector<RDColX> PreloopFFTW::sR2C_RMats;
std::vector<CDColX> PreloopFFTW::sR2C_CMats;
std::vector<RDColX> PreloopFFTW::sC2R_RMats;
std::vector<CDColX> PreloopFFTW::sC2R_CMats;
void PreloopFFTW::checkAndInit(int nr) {
if (nr <= sNmax) {
return;
}
int xx = 1;
for (int NR = sNmax + 1; NR <= nr; NR++) {
int NC = NR / 2 + 1;
int n[] = {NR};
sR2C_RMats.push_back(RDColX(NR, 1));
sR2C_CMats.push_back(CDColX(NC, 1));
sC2R_RMats.push_back(RDColX(NR, 1));
sC2R_CMats.push_back(CDColX(NC, 1));
double *r2c_r = &(sR2C_RMats[NR - 1](0, 0));
ComplexD *r2c_c = &(sR2C_CMats[NR - 1](0, 0));
sR2CPlans.push_back(fftw_plan_many_dft_r2c(
1, n, xx, r2c_r, n, 1, NR, reinterpret_cast<fftw_complex*>(r2c_c), n, 1, NC, FFTW_ESTIMATE));
double *c2r_r = &(sC2R_RMats[NR - 1](0, 0));
ComplexD *c2r_c = &(sC2R_CMats[NR - 1](0, 0));
sC2RPlans.push_back(fftw_plan_many_dft_c2r(
1, n, xx, reinterpret_cast<fftw_complex*>(c2r_c), n, 1, NC, c2r_r, n, 1, NR, FFTW_ESTIMATE));
}
sNmax = nr;
}
void PreloopFFTW::finalize() {
for (int i = 0; i < sNmax; i++) {
fftw_destroy_plan(sR2CPlans[i]);
fftw_destroy_plan(sC2RPlans[i]);
}
sNmax = 0;
}
void PreloopFFTW::computeR2C(int nr) {
checkAndInit(nr);
fftw_execute(sR2CPlans[nr - 1]);
double inv_nr = one / (double)nr;
sR2C_CMats[nr - 1] *= inv_nr;
}
void PreloopFFTW::computeC2R(int nr) {
checkAndInit(nr);
fftw_execute(sC2RPlans[nr - 1]);
}
bool PreloopFFTW::isLuckyNumber(int n, bool forceOdd)
{
int num = n;
// We always hope to use even numbers that are generally faster,
// but the Nyquist frequency sometimes causes trouble.
// force odd
if (forceOdd && num % 2 == 0) {
return false;
}
// use even when n > 10
if (!forceOdd && num % 2 != 0 && num > 10) {
return false;
}
for (int i = 2; i <= num; i++) {
while(num % i == 0) {
num /= i;
if (i > 13) {
return false;
}
}
}
num = n;
int e = 0;
while(num % 11 == 0) {
num /= 11;
e++;
}
num = n;
int f = 0;
while(num % 13 == 0) {
num /= 13;
f++;
}
if (e + f > 1) {
return false;
}
return true;
}
int PreloopFFTW::nextLuckyNumber(int n, bool forceOdd)
{
while(true) {
if (isLuckyNumber(n, forceOdd)) {
return n;
}
n++;
}
}
| 25.563636 | 108 | 0.550498 | kuangdai |
fc74bb7873f7a111ff7dc13f49fcb913a6a953cd | 564 | cpp | C++ | BFEngine/src/core/window.cpp | YnopTafGib/BigFatEngine | 267758779747adfd9e1d0eb6c7674158ecbe15c6 | [
"MIT"
] | null | null | null | BFEngine/src/core/window.cpp | YnopTafGib/BigFatEngine | 267758779747adfd9e1d0eb6c7674158ecbe15c6 | [
"MIT"
] | null | null | null | BFEngine/src/core/window.cpp | YnopTafGib/BigFatEngine | 267758779747adfd9e1d0eb6c7674158ecbe15c6 | [
"MIT"
] | null | null | null | #include "bfepch.hpp"
#include "window.hpp"
namespace BFE
{
Window::Window( const std::string& p_title, const ivec2& p_size ) : m_title( p_title ), m_size( p_size )
{
glfwInit();
glfwWindowHint( GLFW_CLIENT_API, GLFW_NO_API );
glfwWindowHint( GLFW_RESIZABLE, GLFW_FALSE );
m_window = glfwCreateWindow( m_size.x, m_size.y, m_title.c_str(), nullptr, nullptr );
LOG_INFO( "Created GLFW window." );
}
Window::~Window()
{
glfwDestroyWindow( m_window );
glfwTerminate();
}
void Window::update() { glfwPollEvents(); }
} // namespace BFE
| 21.692308 | 104 | 0.684397 | YnopTafGib |
fc778e36a0b8f448698928817006dc79942c08d6 | 5,032 | hxx | C++ | OCC/opencascade-7.2.0/x64/debug/inc/BRepOffsetAPI_MakeEvolved.hxx | jiaguobing/FastCAE | 2348ab87e83fe5c704e4c998cf391229c25ac5d5 | [
"BSD-3-Clause"
] | 2 | 2020-02-21T01:04:35.000Z | 2020-02-21T03:35:37.000Z | OCC/opencascade-7.2.0/x64/debug/inc/BRepOffsetAPI_MakeEvolved.hxx | Sunqia/FastCAE | cbc023fe07b6e306ceefae8b8bd7c12bc1562acb | [
"BSD-3-Clause"
] | 1 | 2020-03-06T04:49:42.000Z | 2020-03-06T04:49:42.000Z | OCC/opencascade-7.2.0/x64/debug/inc/BRepOffsetAPI_MakeEvolved.hxx | Sunqia/FastCAE | cbc023fe07b6e306ceefae8b8bd7c12bc1562acb | [
"BSD-3-Clause"
] | 1 | 2021-11-21T13:03:26.000Z | 2021-11-21T13:03:26.000Z | // Created on: 1995-09-18
// Created by: Bruno DUMORTIER
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepOffsetAPI_MakeEvolved_HeaderFile
#define _BRepOffsetAPI_MakeEvolved_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <BRepFill_Evolved.hxx>
#include <BRepBuilderAPI_MakeShape.hxx>
#include <GeomAbs_JoinType.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Real.hxx>
#include <TopTools_ListOfShape.hxx>
class TopoDS_Wire;
class TopoDS_Face;
class BRepFill_Evolved;
class TopoDS_Shape;
//! Describes functions to build evolved shapes.
//! An evolved shape is built from a planar spine (face or
//! wire) and a profile (wire). The evolved shape is the
//! unlooped sweep (pipe) of the profile along the spine.
//! Self-intersections are removed.
//! A MakeEvolved object provides a framework for:
//! - defining the construction of an evolved shape,
//! - implementing the construction algorithm, and
//! - consulting the result.
//! Computes an Evolved by
//! 1 - sweeping a profil along a spine.
//! 2 - removing the self-intersections.
//!
//! The profile is defined in a Referential R. The position of
//! the profile at the current point of the spine is given by
//! confusing R and the local referential given by ( D0, D1
//! and the normal of the Spine)
//!
//! If the Boolean <AxeProf> is true, R is O,X,Y,Z
//! else R is defined as the local refential at the nearest
//! point of the profil to the spine.
//!
//! if <Solid> is TRUE the Shape result is completed to be a
//! solid or a compound of solids.
class BRepOffsetAPI_MakeEvolved : public BRepBuilderAPI_MakeShape
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT BRepOffsetAPI_MakeEvolved();
Standard_EXPORT BRepOffsetAPI_MakeEvolved(const TopoDS_Wire& Spine, const TopoDS_Wire& Profil, const GeomAbs_JoinType Join = GeomAbs_Arc, const Standard_Boolean AxeProf = Standard_True, const Standard_Boolean Solid = Standard_False, const Standard_Boolean ProfOnSpine = Standard_False, const Standard_Real Tol = 0.0000001);
//! These constructors construct an evolved shape by sweeping the profile
//! Profile along the spine Spine.
//! The profile is defined in a coordinate system R.
//! The coordinate system is determined by AxeProf:
//! - if AxeProf is true, R is the global coordinate system,
//! - if AxeProf is false, R is computed so that:
//! - its origin is given by the point on the spine which is
//! closest to the profile,
//! - its "X Axis" is given by the tangent to the spine at this point, and
//! - its "Z Axis" is the normal to the plane which contains the spine.
//! The position of the profile at the current point of the
//! spine is given by making R coincident with the local
//! coordinate system given by the current point, the
//! tangent vector and the normal to the spine.
//! Join defines the type of pipe generated by the salient
//! vertices of the spine. The default type is GeomAbs_Arc
//! where the vertices generate revolved pipes about the
//! axis passing along the vertex and the normal to the
//! plane of the spine. At present, this is the only
//! construction type implemented.
Standard_EXPORT BRepOffsetAPI_MakeEvolved(const TopoDS_Face& Spine, const TopoDS_Wire& Profil, const GeomAbs_JoinType Join = GeomAbs_Arc, const Standard_Boolean AxeProf = Standard_True, const Standard_Boolean Solid = Standard_False, const Standard_Boolean ProfOnSpine = Standard_False, const Standard_Real Tol = 0.0000001);
Standard_EXPORT const BRepFill_Evolved& Evolved() const;
//! Builds the resulting shape (redefined from MakeShape).
Standard_EXPORT virtual void Build() Standard_OVERRIDE;
//! Returns the shapes created from a subshape
//! <SpineShape> of the spine and a subshape
//! <ProfShape> on the profile.
Standard_EXPORT const TopTools_ListOfShape& GeneratedShapes (const TopoDS_Shape& SpineShape, const TopoDS_Shape& ProfShape) const;
//! Return the face Top if <Solid> is True in the constructor.
Standard_EXPORT const TopoDS_Shape& Top() const;
//! Return the face Bottom if <Solid> is True in the constructor.
Standard_EXPORT const TopoDS_Shape& Bottom() const;
protected:
private:
BRepFill_Evolved myEvolved;
};
#endif // _BRepOffsetAPI_MakeEvolved_HeaderFile
| 37.552239 | 325 | 0.75159 | jiaguobing |
fc77e164cdb591239d9a443b9f3675442011aae5 | 2,690 | cc | C++ | control/vanes_generated.cc | sentree/hover-jet | 7c0f03e57ecfd07a7a167b3ae509700fb48b8764 | [
"MIT"
] | 10 | 2018-12-26T23:08:40.000Z | 2021-02-04T23:22:01.000Z | control/vanes_generated.cc | sentree/hover-jet | 7c0f03e57ecfd07a7a167b3ae509700fb48b8764 | [
"MIT"
] | 40 | 2018-12-15T21:10:04.000Z | 2021-07-29T06:21:22.000Z | control/vanes_generated.cc | sentree/hover-jet | 7c0f03e57ecfd07a7a167b3ae509700fb48b8764 | [
"MIT"
] | 6 | 2018-12-15T20:46:19.000Z | 2020-11-27T09:39:34.000Z | /* Don't edit this; this code was generated by op_graph */
#include "control/vanes_generated.hh"
namespace jet {
namespace control {
VecNd<4>
QuadraframeStatusDelta::to_vector(const QuadraframeStatusDelta &in_grp) {
const VecNd<4> out =
(VecNd<4>() << (in_grp.servo_0_angle_rad_error),
(in_grp.servo_1_angle_rad_error), (in_grp.servo_2_angle_rad_error),
(in_grp.servo_3_angle_rad_error))
.finished();
return out;
}
QuadraframeStatusDelta
QuadraframeStatusDelta::from_vector(const VecNd<4> &in_vec) {
const QuadraframeStatusDelta out = QuadraframeStatusDelta{
(in_vec[0]), (in_vec[1]), (in_vec[2]), (in_vec[3])};
return out;
}
QuadraframeStatus operator-(const QuadraframeStatus &a,
const QuadraframeStatus &b) {
const QuadraframeStatus difference =
QuadraframeStatus{((a.servo_0_angle_rad) - (b.servo_0_angle_rad)),
((a.servo_1_angle_rad) - (b.servo_1_angle_rad)),
((a.servo_2_angle_rad) - (b.servo_2_angle_rad)),
((a.servo_3_angle_rad) - (b.servo_3_angle_rad))};
return difference;
}
QuadraframeStatus operator+(const QuadraframeStatus &a,
const QuadraframeStatusDelta &grp_b) {
const QuadraframeStatus out = QuadraframeStatus{
((a.servo_0_angle_rad) + (grp_b.servo_0_angle_rad_error)),
((a.servo_1_angle_rad) + (grp_b.servo_1_angle_rad_error)),
((a.servo_2_angle_rad) + (grp_b.servo_2_angle_rad_error)),
((a.servo_3_angle_rad) + (grp_b.servo_3_angle_rad_error))};
return out;
}
VecNd<4> QuadraframeStatus::compute_delta(const QuadraframeStatus &a,
const QuadraframeStatus &b) {
const QuadraframeStatus difference = a - b;
const double servo_3_angle_rad_error = difference.servo_3_angle_rad;
const double servo_2_angle_rad_error = difference.servo_2_angle_rad;
const double servo_0_angle_rad_error = difference.servo_0_angle_rad;
const double servo_1_angle_rad_error = difference.servo_1_angle_rad;
const QuadraframeStatusDelta delta =
QuadraframeStatusDelta{servo_0_angle_rad_error, servo_1_angle_rad_error,
servo_2_angle_rad_error, servo_3_angle_rad_error};
const VecNd<4> out_vec = QuadraframeStatusDelta::to_vector(delta);
return out_vec;
}
QuadraframeStatus QuadraframeStatus::apply_delta(const QuadraframeStatus &a,
const VecNd<4> &delta) {
const QuadraframeStatusDelta grp_b =
QuadraframeStatusDelta::from_vector(delta);
const QuadraframeStatus out = a + grp_b;
return out;
}
} // namespace control
} // namespace jet | 44.833333 | 79 | 0.697026 | sentree |
fc79a4d089f7c42a53a09a502b9c66313b473aa1 | 660 | cpp | C++ | leetcode/852_easy_peak-index-in-a-mountain-array.cpp | shoryaconsul/code_practice | f04eeff266beffbba6d9f22e6f8c5861f0dbf998 | [
"MIT"
] | null | null | null | leetcode/852_easy_peak-index-in-a-mountain-array.cpp | shoryaconsul/code_practice | f04eeff266beffbba6d9f22e6f8c5861f0dbf998 | [
"MIT"
] | null | null | null | leetcode/852_easy_peak-index-in-a-mountain-array.cpp | shoryaconsul/code_practice | f04eeff266beffbba6d9f22e6f8c5861f0dbf998 | [
"MIT"
] | null | null | null | class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int start = 0;
int end = arr.size()-1;
int mid;
while(start+2 <= end){
mid = start + (end-start)/2;
if(arr[mid] > arr[mid-1] && arr[mid] > arr[mid+1]) return mid;
if(arr[mid] > arr[mid-1]){ // peak lies to the right of mid
start = mid + 1;
}
else{ // peak lies to the left of mid
end = mid - 1;
}
}
if(start == end) return start;
if(arr[start] > arr[end]) return start;
return end;
}
}; | 28.695652 | 74 | 0.442424 | shoryaconsul |
fc79af0f5598d3a659a11f37aa347ffabfa0e670 | 9,022 | cpp | C++ | source/xbox360/brfilenamexbox360.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 115 | 2015-01-18T17:29:30.000Z | 2022-01-30T04:31:48.000Z | source/xbox360/brfilenamexbox360.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-22T04:53:38.000Z | 2015-01-31T13:52:40.000Z | source/xbox360/brfilenamexbox360.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-23T20:06:46.000Z | 2020-05-20T16:06:00.000Z | /***************************************
Filename Class
Xbox 360 specific code
Copyright (c) 1995-2017 by Rebecca Ann Heineman <becky@burgerbecky.com>
It is released under an MIT Open Source license. Please see LICENSE for
license details. Yes, you can use it in a commercial title without paying
anything, just give me a credit.
Please? It's not like I'm asking you for money!
***************************************/
#include "brfilename.h"
#if defined(BURGER_XBOX360)
#include "brfilemanager.h"
#include "brmemoryfunctions.h"
#define NOD3D
#define NONET
#include <xtl.h>
/*! ************************************
\brief Expand a filename into XBox 360 format.
Using the rules for a Burgerlib type pathname, expand a path
into a FULL pathname native to the Xbox 360 file system.
Directory delimiters are colons only.
If the path starts with a colon, then it is a full pathname starting with a
volume name. If the path starts with ".D2:" then it is a full pathname starting
with a drive number. If the path starts with a "$:","*:" or "@:" then use
special prefix numbers 32-34 If the path starts with 0: through 31: then use
prefix 0-31. Otherwise prepend the pathname with the contents of prefix 8
("Default")
If the path after the prefix is removed is a period then POP the number of
directories from the pathname for each period present after the first.
Example "..:PrevDir:File:" will go down one directory and up the directory
PrevDir
All returned pathnames will NOT have a trailing "\", they will
take the form of c:\\foo\\bar\\file.txt or similar
Examples:<br>
If drive C: is named "boot" then ":boot:foo:bar.txt" = "c:\foo\bar.txt"<br>
If there is no drive named "boot" then ":boot:foo:bar.txt" =
"\\boot\foo\bar.txt"<br>
".D2:foo:bar.txt" = "c:\foo\bar.txt"<br>
".D4:foo:bar.txt" = "e:\foo\bar.txt"<br>
"@:game:data.dat" = "c:\users\<Current user>\appdata\roaming\game\data.dat"
\param pInput Pointer to a pathname string
\sa Burger::Filename::Set(const char *)
***************************************/
const char* Burger::Filename::GetNative(void) BURGER_NOEXCEPT
{
// First step, expand myself to a fully qualified pathname
Expand();
/***************************************
DOS version and Win 95 version
I prefer for all paths intended for DOS use
a generic drive specifier before the working directory.
The problem is that Volume LABEL are very difficult to parse
and slow to access.
***************************************/
// First parse either the volume name of a .DXX device number
// I hopefully will get a volume number since DOS prefers it
const uint8_t* pPath =
reinterpret_cast<uint8_t*>(m_pFilename); // Copy to running pointer
// Now that I have the drive number, determine the length
// of the output buffer and start the conversion
uintptr_t uPathLength = StringLength(reinterpret_cast<const char*>(pPath));
// Reserve 6 extra bytes for the prefix and/or the trailing / and null
char* pOutput = m_NativeFilename;
if (uPathLength >= (sizeof(m_NativeFilename) - 6)) {
pOutput = static_cast<char*>(Alloc(uPathLength + 6));
if (!pOutput) {
pOutput = m_NativeFilename;
uPathLength = 0; // I'm so boned
} else {
m_pNativeFilename = pOutput; // This is my buffer
}
}
// Ignore the first colon, it's to the device name
if (pPath[0] == ':') {
++pPath;
--uPathLength;
}
if (uPathLength) {
uint_t uTemp;
uint_t uFirst = TRUE;
do {
uTemp = pPath[0];
++pPath;
if (uTemp == ':') {
if (uFirst) {
pOutput[0] = ':';
++pOutput;
uFirst = FALSE;
}
uTemp = '\\';
}
pOutput[0] = static_cast<char>(uTemp);
++pOutput;
} while (--uPathLength);
// Remove trailing slash
if (uTemp == '\\') {
--pOutput;
}
}
pOutput[0] = 0; // Terminate the "C" string
return m_pNativeFilename;
}
/***************************************
\brief Set the filename to the current working directory
Query the operating system for the current working directory and set the
filename to that directory. The path is converted into UTF8 character
encoding and stored in Burgerlib filename format
On platforms where a current working directory doesn't make sense, like an
ROM based system, the filename is cleared out.
***************************************/
Burger::eError BURGER_API Burger::Filename::SetSystemWorkingDirectory(
void) BURGER_NOEXCEPT
{
Set(":GAME:");
return kErrorNone;
}
/***************************************
\brief Set the filename to the application's directory
Determine the directory where the application resides and set the filename
to that directory. The path is converted into UTF8 character encoding and
stored in Burgerlib filename format.
On platforms where a current working directory doesn't make sense, like an
ROM based system, the filename is cleared out.
***************************************/
Burger::eError BURGER_API Burger::Filename::SetApplicationDirectory(
void) BURGER_NOEXCEPT
{
Set(":GAME:");
return kErrorNone;
}
/***************************************
\brief Set the filename to the boot volume directory
Determine the directory of the drive volume that the operating system was
loaded from. The path is converted into UTF8 character encoding and stored
in Burgerlib filename format.
On platforms where a current working directory doesn't make sense, like a
ROM based system, the filename is cleared out.
***************************************/
Burger::eError BURGER_API Burger::Filename::SetBootVolumeDirectory(
void) BURGER_NOEXCEPT
{
Set(":GAME:");
return kErrorNone;
}
/***************************************
\brief Set the filename to the local machine preferences directory
Determine the directory where the user's preferences that are
local to the machine is located. The path is converted
into UTF8 character encoding and stored in Burgerlib
filename format.
On platforms where a current working directory doesn't make sense,
like an ROM based system, the filename is cleared out.
***************************************/
Burger::eError BURGER_API Burger::Filename::SetMachinePrefsDirectory(
void) BURGER_NOEXCEPT
{
Set(":GAME:");
return kErrorNone;
}
/***************************************
\brief Set the filename to the user's preferences directory
Determine the directory where the user's preferences that
could be shared among all machines the user has an account
with is located. The path is converted
into UTF8 character encoding and stored in Burgerlib
filename format.
On platforms where a current working directory doesn't make sense,
like an ROM based system, the filename is cleared out.
***************************************/
Burger::eError BURGER_API Burger::Filename::SetUserPrefsDirectory(
void) BURGER_NOEXCEPT
{
Set(":GAME:");
return kErrorNone;
}
/***************************************
Convert a Windows path to a Burgerlib path
Paths without a leading '\' are prefixed with
the current working directory
Paths with a drive letter but no leading \ will use
the drive's current working directory
If it's a network path "\\" then use that as the volume name.
The Windows version converts these types of paths:
"C:\foo\bar2" = ".D2:foo:bar2:"<br>
"foo" = "(working directory from 8):foo:"<br>
"foo\bar2" = "(working directory from 8):foo:bar2:"<br>
"\foo" = ".D(Mounted drive number):foo:"<br>
"\\foo\bar\file.txt" = ":foo:bar:file.txt:"
***************************************/
Burger::eError BURGER_API Burger::Filename::SetFromNative(
const char* pInput) BURGER_NOEXCEPT
{
Clear();
if (!pInput || !pInput[0]) { // No directory at all?
pInput = "D:\\"; // Just get the current directory
}
// How long would the string be if it was UTF8?
uintptr_t uExpandedLength = StringLength(pInput);
uintptr_t uOutputLength = uExpandedLength + 6;
char* pOutput = m_Filename;
if (uOutputLength >= sizeof(m_Filename)) {
pOutput = static_cast<char*>(Alloc(uOutputLength));
if (!pOutput) {
return kErrorOutOfMemory;
}
}
m_pFilename = pOutput;
const char* pSrc = pInput;
pOutput[0] = ':';
++pOutput;
// Turn the drive name into the root segment
const char* pColon = StringCharacter(pSrc, ':');
if (pColon) {
uintptr_t uVolumeNameSize = pColon - pInput;
MemoryCopy(pOutput, pSrc, uVolumeNameSize);
pOutput += uVolumeNameSize;
pSrc = pColon + 1;
}
// Append the rest of the path, and change slashes to colons
uint_t uTemp2 = reinterpret_cast<const uint8_t*>(pSrc)[0];
++pSrc;
if (uTemp2) {
do {
if (uTemp2 == '\\') { // Convert directory holders
uTemp2 = ':'; // To generic paths
}
pOutput[0] = static_cast<char>(uTemp2); // Save char
++pOutput;
uTemp2 = pSrc[0]; // Next char
++pSrc;
} while (uTemp2); // Still more?
}
// The wrap up...
// Make sure it's appended with a colon
if (pOutput[-1] != ':') { // Last char a colon?
pOutput[0] = ':'; // End with a colon!
pOutput[1] = 0;
}
return kErrorNone;
}
#endif
| 28.282132 | 79 | 0.656728 | Olde-Skuul |
fc7a43dfdbd487c63d5f1d0358a2ae1a2aa9fb56 | 967 | hpp | C++ | src/vgl/file/file.hpp | alexsr/vgl | 51fe9d990de4049bf3219b21a9ca930738a5c638 | [
"MIT"
] | 1 | 2019-05-18T18:27:19.000Z | 2019-05-18T18:27:19.000Z | src/vgl/file/file.hpp | alexsr/vgl | 51fe9d990de4049bf3219b21a9ca930738a5c638 | [
"MIT"
] | null | null | null | src/vgl/file/file.hpp | alexsr/vgl | 51fe9d990de4049bf3219b21a9ca930738a5c638 | [
"MIT"
] | null | null | null | #pragma once
#include <optional>
#include "file_paths.hpp"
#include <future>
namespace vgl::file
{
bool is_file(const std::filesystem::path& path);
bool is_file(const char* path);
std::optional<std::filesystem::path> save_file_dialog(const std::filesystem::path& default_path, const std::string& filter = "");
std::optional<std::filesystem::path> open_file_dialog(const std::filesystem::path& default_path, const std::string& filter = "");
std::optional<std::vector<std::filesystem::path>> open_multiple_files_dialog(const std::filesystem::path& default_path,
const std::string& filter = "");
std::string load_string_file(const std::filesystem::path& file_path);
std::future<std::string> load_string_file_async(std::filesystem::path file_path);
std::vector<std::byte> load_binary_file(const std::filesystem::path& file_path);
std::future<std::vector<std::byte>> load_binary_file_async(std::filesystem::path file_path);
}
| 48.35 | 133 | 0.730093 | alexsr |
fc7a782404104b734aeed5340f4ffac654e5771c | 2,315 | cc | C++ | solutions/kattis/wettiles/main.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 4 | 2020-11-07T14:38:02.000Z | 2022-01-03T19:02:36.000Z | solutions/kattis/wettiles/main.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 1 | 2019-04-17T06:55:14.000Z | 2019-04-17T06:55:14.000Z | solutions/kattis/wettiles/main.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <climits>
#include <cmath>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
using ll = long long;
using ld = long double;
using vi = vector<int>;
using ii = pair<int, int>;
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
int x;
while (cin >> x && x != -1) {
int y, t, l, w;
cin >> y >> t >> l >> w;
// Multi-source shortest paths (MSSP) on an unweighted graph.
// This is made slightly more difficult by the limitation of path lengths,
// and the parsing of obstacles.
vector<vi> dist(x, vi(y, 1e9));
queue<ii> q;
vector<ii> sources;
for (int i = 0; i < l; ++i) {
int r, c;
cin >> r >> c;
--r, --c;
q.emplace(r, c);
dist[r][c] = 1;
}
vector<vector<bool>> grid(x, vector<bool>(y, 1));
for (int i = 0; i < w; ++i) {
int x1, x2, y1, y2;
cin >> x1 >> y1 >> x2 >> y2;
--x1, --x2, --y1, --y2;
if (x1 > x2) {
swap(x1, x2);
swap(y1, y2);
}
if (x1 == x2) {
if (y2 < y1) {
swap(y1, y2);
}
for (int c = y1; c <= y2; ++c) {
grid[x1][c] = 0;
}
} else {
int grad = (y2 - y1) / (x2 - x1);
for (int r = x1, c = y1; r <= x2; ++r, c += grad) {
grid[r][c] = 0;
}
}
}
const vector<ii> edges = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (q.size()) {
auto [r, c] = q.front();
q.pop();
for (auto [dr, dc] : edges) {
int nr = dr + r;
int nc = dc + c;
if (nc < 0 || nr < 0 || nr >= x || nc >= y) continue;
if (!grid[nr][nc]) continue;
int ndist = dist[r][c] + 1;
if (ndist >= dist[nr][nc] || ndist > t) continue;
dist[nr][nc] = ndist;
q.emplace(nr, nc);
}
}
int count = 0;
for (int i = 0; i < x; ++i) {
for (int j = 0; j < y; ++j) {
if (dist[i][j] < 1e9) {
++count;
}
}
}
cout << count << '\n';
}
}
| 22.047619 | 78 | 0.465659 | zwliew |
fc7ccba1782e66d1548b7b59f5d0d6b5c99c72a7 | 5,097 | cpp | C++ | clib_build/src/Intersection.cpp | pemryan/XCIST | 044930e58880ac29208c62434c275a8724c67ef5 | [
"BSD-3-Clause"
] | 9 | 2020-09-04T01:52:41.000Z | 2021-09-20T16:05:28.000Z | clib_build/src/Intersection.cpp | pemryan/XCIST | 044930e58880ac29208c62434c275a8724c67ef5 | [
"BSD-3-Clause"
] | 1 | 2021-09-15T13:59:57.000Z | 2021-09-17T21:33:53.000Z | clib_build/src/Intersection.cpp | pemryan/XCIST | 044930e58880ac29208c62434c275a8724c67ef5 | [
"BSD-3-Clause"
] | 5 | 2020-09-05T08:17:18.000Z | 2021-03-09T02:49:58.000Z | // Copyright 2020, General Electric Company. All rights reserved. See https://github.com/xcist/code/blob/master/LICENSE
#include "Intersection.h"
#include <vector>
#include <algorithm>
#include "MatVec.h"
#include <math.h>
Intersection::Intersection() {
}
Intersection::~Intersection() {
}
Intersection::Intersection(int id, double a_time, bool a_enterSense,
double a_rho, int a_priority, int a_material) {
time = a_time;
enterSense = a_enterSense;
rho = a_rho;
priority = a_priority;
material = a_material;
ID = id;
}
void Intersection::PrintMe(std::ostream& c) const {
c << "Intersection time " << time << "\r\n";
c << "Entry time (vs. exit time) " << enterSense << "\r\n";
c << "priority = " << priority << ", ";
c << "rho = " << rho << ", ";
c << "matl = " << material << "\r\n";
c << "object ID = " << ID << "\r\n";
}
std::ostream& operator<<(std::ostream& c, Intersection& p) {
p.PrintMe(c);
return c;
}
std::ostream& operator<<(std::ostream& c, IntersectionSet& p) {
IntersectionSet::iterator i;
for (i=p.begin();i!=p.end();i++) {
i->PrintMe(c);
c << "\r\n";
}
return c;
}
bool Icmp(const Intersection& a, const Intersection& b) {
return (a.time < b.time) || ((a.time == b.time) && a.enterSense);
}
//typedef std::vector<Intersection> hitStackType;
typedef IntersectionSet hitStackType;
void IntersectionSet::GetHitList(double *ptable) {
if (empty()) return;
std::sort(begin(),end(),Icmp);
hitStackType hitStack;
//
// Calculate pathlength
//
double previousposition=0.;
int currentpriority = 0;
double currentrho = 0;
int currentmaterial = 0;
for (IntersectionSet::iterator nr=begin();nr!=end();nr++) {
//
// get new data
//
double position=nr->time;
int priority=nr->priority;
bool sense=nr->enterSense;
if (hitStack.empty()) {
currentpriority=0;
currentrho=0;
currentmaterial=0;
} else {
currentpriority=hitStack.back().priority;
currentrho=hitStack.back().rho;
currentmaterial=hitStack.back().material;
ptable[currentmaterial-1] += (position-previousposition)*currentrho;
}
previousposition=position;
if (priority > currentpriority) {
// PUSH
hitStack.push_back(*nr);
} else if (priority == currentpriority) {
if (hitStack.empty())
throw "Error: stack underflow in GetHitList.\r\n";
hitStack.pop_back();
}
else {
if (sense) {
hitStackType::iterator cp = hitStack.begin();
while ((cp != hitStack.end()) && cp->priority < priority)
cp++;
// INSERT IN STACK
hitStack.insert(cp,*nr);
} else {
// GET OUT STACK
hitStackType::iterator cp = hitStack.begin();
while ((cp != hitStack.end()) && cp->priority != priority)
cp++;
hitStack.erase(cp);
}
}
}
if (!hitStack.empty()) {
printf("ERROR\r\n");
std::cout << (*this);
printf("hitstack...\r\n");
std::cout << hitStack;
throw "Error: stack not empty on exit of GetHitList.\r\n";
}
}
void IntersectionSet::RenderIntersections(int N, float dX, float* IDmap, int targID) {
if (empty()) return;
std::sort(begin(),end(),Icmp);
hitStackType hitStack;
//
// Calculate pathlength
//
double previousposition=0.;
int currentpriority = 0;
double currentrho = 0;
int currentmaterial = 0;
int currentID = 0;
for (IntersectionSet::iterator nr=begin();nr!=end();nr++) {
//
// get new data
//
double position=nr->time;
int priority=nr->priority;
bool sense=nr->enterSense;
if (hitStack.empty()) {
currentpriority=0;
currentrho=0;
currentmaterial=0;
currentID = 0;
} else {
currentpriority=hitStack.back().priority;
currentrho=hitStack.back().rho;
currentmaterial=hitStack.back().material;
currentID = hitStack.back().ID;
if (currentmaterial == targID) {
float startndx, stopndx;
startndx = previousposition/dX;
stopndx = position/dX;
int firstwhole, lastwhole, firstfrac, lastfrac;
firstwhole = (int) ceil(startndx+0.5);
lastwhole = (int) floor(stopndx-0.5);
firstfrac = (int) ceil(startndx-0.5);
lastfrac = (int) floor(stopndx+0.5);
IDmap[firstfrac] += currentrho*(firstfrac+0.5-startndx);
IDmap[lastfrac] += currentrho*(stopndx-lastfrac+0.5);
if (firstfrac == lastfrac)
IDmap[lastfrac] -= currentrho*(1.0);
for (int p=firstwhole;p<=lastwhole;p++)
IDmap[p] += currentrho*1.0;
}
}
previousposition=position;
if (priority > currentpriority) {
// PUSH
hitStack.push_back(*nr);
} else if (priority == currentpriority) {
if (hitStack.empty())
throw "Error: stack underflow in RenderIntersections.\n";
hitStack.pop_back();
}
else {
if (sense) {
hitStackType::iterator cp = hitStack.begin();
while ((cp != hitStack.end()) && cp->priority < priority)
cp++;
// INSERT IN STACK
hitStack.insert(cp,*nr);
} else {
// GET OUT STACK
hitStackType::iterator cp = hitStack.begin();
while ((cp != hitStack.end()) && cp->priority != priority)
cp++;
hitStack.erase(cp);
}
}
}
}
| 25.613065 | 119 | 0.628016 | pemryan |
fc7e58b4c347acde1e49ff082be26e051fff46f3 | 958 | cpp | C++ | source/ashespp/Buffer/VertexBuffer.cpp | DragonJoker/Ashes | a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e | [
"MIT"
] | 227 | 2018-09-17T16:03:35.000Z | 2022-03-19T02:02:45.000Z | source/ashespp/Buffer/VertexBuffer.cpp | DragonJoker/RendererLib | 0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a | [
"MIT"
] | 39 | 2018-02-06T22:22:24.000Z | 2018-08-29T07:11:06.000Z | source/ashespp/Buffer/VertexBuffer.cpp | DragonJoker/Ashes | a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e | [
"MIT"
] | 8 | 2019-05-04T10:33:32.000Z | 2021-04-05T13:19:27.000Z | /*
This file belongs to Ashes.
See LICENSE file in root folder.
*/
#include "ashespp/Buffer/VertexBuffer.hpp"
namespace ashes
{
VertexBufferBase::VertexBufferBase( Device const & device
, VkDeviceSize size
, VkBufferUsageFlags usage
, QueueShare sharingMode )
: VertexBufferBase{ device, "VertexBuffer", size, usage, std::move( sharingMode ) }
{
}
VertexBufferBase::VertexBufferBase( Device const & device
, std::string const & debugName
, VkDeviceSize size
, VkBufferUsageFlags usage
, QueueShare sharingMode )
: m_device{ device }
, m_size{ size }
, m_buffer{ m_device.createBuffer( debugName
, size
, usage | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT
, std::move( sharingMode ) ) }
{
}
void VertexBufferBase::bindMemory( DeviceMemoryPtr memory )
{
m_buffer->bindMemory( std::move( memory ) );
}
VkMemoryRequirements VertexBufferBase::getMemoryRequirements()const
{
return m_buffer->getMemoryRequirements();
}
}
| 23.365854 | 85 | 0.729645 | DragonJoker |
fc80825aaf884bc20ed05f783d3a24522b35a745 | 937 | cpp | C++ | reports/DA1/Q1.cpp | PaletiKrishnasai/High-Performance-Computing | 269dcac49be9671cff5fb02bbea9a49124e1ec3a | [
"MIT"
] | null | null | null | reports/DA1/Q1.cpp | PaletiKrishnasai/High-Performance-Computing | 269dcac49be9671cff5fb02bbea9a49124e1ec3a | [
"MIT"
] | null | null | null | reports/DA1/Q1.cpp | PaletiKrishnasai/High-Performance-Computing | 269dcac49be9671cff5fb02bbea9a49124e1ec3a | [
"MIT"
] | null | null | null | /*
Author : Paleti Krishnasai CED18I039
Parallelize the following sequence and write openMP and estimate parallelization fraction for
the sequence’s larger number 100000. Write your comments on each problem.
1. Sequence 5, 8, 11, 14, 17, 20, 23..
*/
// g++ -O0 -fopenmp Q1.cpp -o Q1
#include <bits/stdc++.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <math.h>
#include <time.h>
#include <omp.h>
using namespace std;
#define n 1000001
double sequence[n];
int main()
{
float startTime, endTime,execTime;
int i;
srand(time(0));
startTime = omp_get_wtime();
#pragma omp parallel private (i)
{
#pragma omp for
for(i=0;i<100000;i++)
{
sequence[i] = 5 + (i) + (i) + (i);
}
}
endTime = omp_get_wtime();
execTime = endTime - startTime;
for(i=0;i<100000;i++)
cout<<sequence[i]<<endl;
cout<<"time "<<execTime<<endl;
return(0);
} | 21.295455 | 93 | 0.626467 | PaletiKrishnasai |
fc8093dd6f33bc5e48bbc5b987201084ac954fd8 | 594 | cc | C++ | bindings.cc | jwerle/repo | 15d07ce6d039766e7c3f4bda6652430eb7686d7b | [
"MIT"
] | 1 | 2022-02-27T20:41:57.000Z | 2022-02-27T20:41:57.000Z | bindings.cc | jwerle/repo | 15d07ce6d039766e7c3f4bda6652430eb7686d7b | [
"MIT"
] | null | null | null | bindings.cc | jwerle/repo | 15d07ce6d039766e7c3f4bda6652430eb7686d7b | [
"MIT"
] | null | null | null |
#include <v8.h>
#include <node.h>
#include "repo.h"
#define str(s) v8::String::New(s)
class User {
// repo_user_t *ref_;
v8::Persistent<v8::Object> obj_;
public:
User () {
// ref_ = repo_user_new();
obj_->SetPointerInInternalField(0, this);
}
v8::Handle<v8::Object>
ToObject () {
return obj_;
}
};
v8::Handle<v8::Value>
NewUser (const v8::Arguments &args) {
v8::HandleScope scope;
User *user = new User();
return scope.Close(user->ToObject());
}
void
Init (v8::Handle<v8::Object> exports) {
NODE_SET_METHOD(exports, "User", NewUser);
}
NODE_MODULE(repo, Init); | 16.5 | 44 | 0.648148 | jwerle |
fc8ac01aa8ee29821a616a46a192c8b5dacf67df | 1,223 | cpp | C++ | searching-algorithms/binarySearch.cpp | Divyansh1315/data-structures-and-algorithms-code | 46b0bec41f022b60be4798227a5f5fc86dccee1a | [
"MIT"
] | 1 | 2022-02-09T14:28:28.000Z | 2022-02-09T14:28:28.000Z | searching-algorithms/binarySearch.cpp | Divyansh1315/data-structures-and-algorithms-code | 46b0bec41f022b60be4798227a5f5fc86dccee1a | [
"MIT"
] | 1 | 2022-02-02T04:58:10.000Z | 2022-02-02T04:58:10.000Z | searching-algorithms/binarySearch.cpp | Divyansh1315/data-structures-and-algorithms-code | 46b0bec41f022b60be4798227a5f5fc86dccee1a | [
"MIT"
] | 1 | 2022-02-02T00:23:59.000Z | 2022-02-02T00:23:59.000Z | #include <bits/stdc++.h>
using namespace std;
// iterative approach
/*
int binarySearch(int arr[],int element, int low, int high) {
while(low <= high) {
int mid = low + (high - low)/2;
if(arr[mid] == element)
return mid;
else if(arr[mid] < element)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
*/
// recursive approach
int binarySearch(int arr[], int element, int low, int high) {
if(low <= high) {
int mid = low + (high - low)/2;
return arr[mid] == element
? mid
: (arr[mid] < element
? binarySearch(arr, element, mid + 1, high)
: binarySearch(arr, element, low, mid - 1));
// if(arr[mid] == element)
// return mid;
// else if (arr[mid] < element)
// return binarySearch(arr, element, mid + 1, high);
// else
// return binarySearch(arr, element, low, mid - 1);
}
return -1;
}
int main() {
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int element = 1;
int size = sizeof(arr)/sizeof(arr[0]);
int result = binarySearch(arr, element, 0, size - 1);
if (result == -1)
cout << "Element is not found" << endl;
else
cout << "Element is found at " << result << " index" << endl;
return 0;
} | 23.075472 | 65 | 0.553557 | Divyansh1315 |
fc8c396a25870fcdf1cf16138b72464a1dfeab9a | 7,917 | cc | C++ | nox/src/nox/netapps/hoststate/hosttracker.cc | ayjazz/OESS | deadc504d287febc7cbd7251ddb102bb5c8b1f04 | [
"Apache-2.0"
] | 28 | 2015-02-04T13:59:25.000Z | 2021-12-29T03:44:47.000Z | nox/src/nox/netapps/hoststate/hosttracker.cc | ayjazz/OESS | deadc504d287febc7cbd7251ddb102bb5c8b1f04 | [
"Apache-2.0"
] | 552 | 2015-01-05T18:25:54.000Z | 2022-03-16T18:51:13.000Z | nox/src/nox/netapps/hoststate/hosttracker.cc | ayjazz/OESS | deadc504d287febc7cbd7251ddb102bb5c8b1f04 | [
"Apache-2.0"
] | 25 | 2015-02-04T18:48:20.000Z | 2020-06-18T15:51:05.000Z | #include "hosttracker.hh"
#include <boost/bind.hpp>
namespace vigil
{
static Vlog_module lg("hosttracker");
Host_location_event::Host_location_event(const ethernetaddr host_,
const list<hosttracker::location> loc_,
enum type type_):
Event(static_get_name()), host(host_), eventType(type_)
{
for (list<hosttracker::location>::const_iterator i = loc_.begin();
i != loc_.end(); i++)
loc.push_back(*(new hosttracker::location(i->dpid,
i->port,
i->lastTime)));
}
hosttracker::location::location(datapathid dpid_, uint16_t port_, time_t tv):
dpid(dpid_), port(port_), lastTime(tv)
{ }
void hosttracker::location::set(const hosttracker::location& loc)
{
dpid = loc.dpid;
port = loc.port;
lastTime = loc.lastTime;
}
void hosttracker::configure(const Configuration* c)
{
defaultnBindings = DEFAULT_HOST_N_BINDINGS;
hostTimeout = DEFAULT_HOST_TIMEOUT;
register_event(Host_location_event::static_get_name());
}
void hosttracker::install()
{
}
void hosttracker::check_timeout()
{
if (hostlocation.size() == 0)
return;
time_t timenow;
time(&timenow);
hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
hostlocation.find(oldest_host());
if (i == hostlocation.end())
return;
list<hosttracker::location>::iterator j = get_oldest(i->second);
while (j->lastTime+hostTimeout < timenow)
{
//Remove old entry
i->second.erase(j);
if (i->second.size() == 0)
hostlocation.erase(i);
//Get next oldest
i = hostlocation.find(oldest_host());
if (i == hostlocation.end())
return;
j = get_oldest(i->second);
}
//Post next one
timeval tv = {get_oldest(i->second)->lastTime+hostTimeout-timenow, 0};
post(boost::bind(&hosttracker::check_timeout, this), tv);
}
const ethernetaddr hosttracker::oldest_host()
{
ethernetaddr oldest((uint64_t) 0);
time_t oldest_time = 0;
hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
hostlocation.begin();
while (i != hostlocation.end())
{
if (oldest_time == 0 ||
get_oldest(i->second)->lastTime < oldest_time)
{
oldest_time = get_oldest(i->second)->lastTime;
oldest = i->first;
}
i++;
}
return oldest;
}
void hosttracker::add_location(ethernetaddr host, datapathid dpid,
uint16_t port, time_t tv, bool postEvent)
{
//Set default time as now
if (tv == 0)
time(&tv);
add_location(host, hosttracker::location(dpid,port,tv), postEvent);
}
void hosttracker::add_location(ethernetaddr host, hosttracker::location loc,
bool postEvent)
{
hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
hostlocation.find(host);
if (i == hostlocation.end())
{
//New host
list<location> j = list<location>();
j.push_front(loc);
hostlocation.insert(make_pair(host,j));
if (postEvent)
post(new Host_location_event(host,j,Host_location_event::ADD));
VLOG_DBG(lg, "New host %"PRIx64" at %"PRIx64":%"PRIx16"",
host.hb_long(), loc.dpid.as_host(), loc.port);
}
else
{
//Existing host
list<location>::iterator k = i->second.begin();
while (k->dpid != loc.dpid || k->port != loc.port)
{
k++;
if (k == i->second.end())
break;
}
if (k == i->second.end())
{
//New location
while (i->second.size() >= getBindingNumber(host))
i->second.erase(get_oldest(i->second));
i->second.push_front(loc);
VLOG_DBG(lg, "Host %"PRIx64" at new location %"PRIx64":%"PRIx16"",
i->first.hb_long(), loc.dpid.as_host(), loc.port);
if (postEvent)
post(new Host_location_event(host,i->second,
Host_location_event::MODIFY));
}
else
{
//Update timeout
k->lastTime = loc.lastTime;
VLOG_DBG(lg, "Host %"PRIx64" at old location %"PRIx64":%"PRIx16"",
i->first.hb_long(), loc.dpid.as_host(), loc.port);
}
}
VLOG_DBG(lg, "Added host %"PRIx64" to location %"PRIx64":%"PRIx16"",
host.hb_long(), loc.dpid.as_host(), loc.port);
//Schedule timeout if first entry
if (hostlocation.size() == 0)
{
timeval tv= {hostTimeout,0};
post(boost::bind(&hosttracker::check_timeout, this), tv);
}
}
void hosttracker::remove_location(ethernetaddr host, datapathid dpid,
uint16_t port, bool postEvent)
{
remove_location(host, hosttracker::location(dpid,port,0), postEvent);
}
void hosttracker::remove_location(ethernetaddr host,
hosttracker::location loc,
bool postEvent)
{
hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
hostlocation.find(host);
if (i != hostlocation.end())
{
bool changed = false;
list<location>::iterator k = i->second.begin();
while (k != i->second.end())
{
if (k->dpid == loc.dpid || k->port == loc.port)
{
k = i->second.erase(k);
changed = true;
}
else
k++;
}
if (postEvent && changed)
post(new Host_location_event(host,i->second,
(i->second.size() == 0)?
Host_location_event::REMOVE:
Host_location_event::MODIFY));
if (i->second.size() == 0)
hostlocation.erase(i);
}
else
VLOG_DBG(lg, "Host %"PRIx64" has no location, cannot unset.",
host.hb_long());
}
const hosttracker::location hosttracker::get_latest_location(ethernetaddr host)
{
list<hosttracker::location> locs = \
(list<hosttracker::location>) get_locations(host);
if (locs.size() == 0)
return hosttracker::location(datapathid(), 0, 0);
else
return *(get_newest(locs));
}
const list<ethernetaddr> hosttracker::get_hosts()
{
list<ethernetaddr> hostlist;
hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
hostlocation.begin();
while (i != hostlocation.end())
{
hostlist.push_back(i->first);
i++;
}
return hostlist;
}
const list<hosttracker::location> hosttracker::get_locations(ethernetaddr host)
{
hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
hostlocation.find(host);
if (i == hostlocation.end())
return list<hosttracker::location>();
else
return i->second;
}
list<hosttracker::location>::iterator
hosttracker::get_newest(list<hosttracker::location>& loclist)
{
list<location>::iterator newest = loclist.begin();
list<location>::iterator j = loclist.begin();
while (j != loclist.end())
{
if (j->lastTime > newest->lastTime)
newest = j;
j++;
}
return newest;
}
list<hosttracker::location>::iterator
hosttracker::get_oldest(list<hosttracker::location>& loclist)
{
list<location>::iterator oldest = loclist.begin();
list<location>::iterator j = loclist.begin();
while (j != loclist.end())
{
if (j->lastTime < oldest->lastTime)
oldest = j;
j++;
}
return oldest;
}
uint8_t hosttracker::getBindingNumber(ethernetaddr host)
{
hash_map<ethernetaddr,uint8_t>::iterator i = nBindings.find(host);
if (i != nBindings.end())
return i->second;
return defaultnBindings;
}
const list<hosttracker::location> hosttracker::getLocations(ethernetaddr host)
{
hash_map<ethernetaddr,list<hosttracker::location> >::iterator i = \
hostlocation.find(host);
if (i == hostlocation.end())
return list<hosttracker::location>();
return i->second;
}
void hosttracker::getInstance(const Context* c,
hosttracker*& component)
{
component = dynamic_cast<hosttracker*>
(c->get_by_interface(container::Interface_description
(typeid(hosttracker).name())));
}
REGISTER_COMPONENT(Simple_component_factory<hosttracker>,
hosttracker);
} // vigil namespace
| 26.215232 | 81 | 0.629784 | ayjazz |
475a97cea4e88778d2ac52bde43e9b9eaa66071d | 5,745 | cc | C++ | source/breakpoint.cc | finixbit/ftrace | 1bc5099864c7eadc5846a14e0027ab07daca6549 | [
"MIT"
] | 71 | 2018-02-19T04:46:43.000Z | 2021-12-21T21:12:14.000Z | source/breakpoint.cc | finixbit/ftrace | 1bc5099864c7eadc5846a14e0027ab07daca6549 | [
"MIT"
] | 1 | 2018-04-15T18:38:32.000Z | 2018-04-26T13:53:54.000Z | source/breakpoint.cc | finixbit/ftrace | 1bc5099864c7eadc5846a14e0027ab07daca6549 | [
"MIT"
] | 13 | 2018-02-19T12:51:20.000Z | 2022-03-31T06:59:15.000Z | #include <iostream>
#include <sys/ptrace.h> /* ptrace */
#include <sys/wait.h> /* wait */
#include <inttypes.h> /* PRIx64 */
#include "breakpoint.h"
#include "callsite.h"
#include "symbol.h"
void Breakpoint::set_symbol_breakpoint(
pid_t &child_pid, std::intptr_t &sym_address) {
if(m_breakpoints_map.count(sym_address)) {
auto &bp = m_breakpoints_map[sym_address];
bp.m_is_symbol_address = true;
} else {
breakpoint_t bp;
bp.m_bp_address = sym_address;
bp.m_is_symbol_address = true;
enable_breakpoint(child_pid, bp);
m_breakpoints_map[sym_address] = bp;
}
}
void Breakpoint::set_callsite_breakpoint(
pid_t &child_pid, std::intptr_t &cs_address, std::intptr_t &cs_return_address) {
if(m_breakpoints_map.count(cs_address)) {
auto &bp = m_breakpoints_map[cs_address];
bp.m_is_cs_caller_address = true;
bp.m_cs_caller_address = cs_address;
} else {
breakpoint_t bp;
bp.m_bp_address = cs_address;
bp.m_is_cs_caller_address = true;
bp.m_cs_caller_address = cs_address;
enable_breakpoint(child_pid, bp);
m_breakpoints_map[cs_address] = bp;
}
if(cs_return_address == 0)
return;
if(m_breakpoints_map.count(cs_return_address)) {
auto &bp = m_breakpoints_map[cs_return_address];
bp.m_is_cs_return_address = true;
bp.m_cs_return_caller_address = cs_address;
} else {
breakpoint_t bp;
bp.m_bp_address = cs_return_address;
bp.m_is_cs_return_address = true;
bp.m_cs_return_caller_address = cs_address;
enable_breakpoint(child_pid, bp);
m_breakpoints_map[cs_return_address] = bp;
}
}
void Breakpoint::continue_execution(pid_t &child_pid) {
while(1) {
ptrace(PTRACE_CONT, child_pid, nullptr, nullptr);
wait_for_signal(child_pid);
step_over_breakpoint(child_pid);
}
}
void Breakpoint::wait_for_signal(pid_t &child_pid) {
int wait_status = 0;
auto options = 0;
auto i = waitpid(child_pid, &wait_status, options);
if(WIFEXITED(wait_status) || (WIFSIGNALED(wait_status) && WTERMSIG(wait_status) == SIGKILL)) {
std::cout << "[+] process " << child_pid << " terminated" << std::endl;
return;
}
}
void Breakpoint::step_over_breakpoint(pid_t &child_pid) {
// - 1 because execution will go past the breakpoint
auto possible_breakpoint_location = get_program_counter(child_pid) - 1;
if (m_breakpoints_map.count(possible_breakpoint_location)) {
auto& bp = m_breakpoints_map[possible_breakpoint_location];
if (bp.m_enabled) {
printf("breakpoint[0x%" PRIx64 "] ", bp.m_bp_address);
if(bp.m_is_cs_return_address) {
auto &cs = Callsite::m_callsites_map[bp.m_cs_return_caller_address];
std::cout << "return: " << cs.m_cs_name << " ";
}
if(bp.m_is_cs_caller_address) {
auto &cs = Callsite::m_callsites_map[bp.m_cs_caller_address];
std::cout << " call: " << cs.m_cs_name << " ";
}
if(bp.m_is_symbol_address) {
auto &sym = Symbol::m_symbols_map[bp.m_bp_address];
std::cout << " call: " << sym.m_sym_name << " ";
}
printf("\n");
auto previous_instruction_address = possible_breakpoint_location;
set_program_counter(child_pid, previous_instruction_address);
disable_breakpoint(child_pid, bp);
ptrace(PTRACE_SINGLESTEP, child_pid, nullptr, nullptr);
wait_for_signal(child_pid);
enable_breakpoint(child_pid, bp);
}
}
}
uint64_t Breakpoint::get_program_counter(pid_t &child_pid) {
user_regs_struct regs = get_registers(child_pid);
return (uint64_t)regs.rip;
}
void Breakpoint::set_program_counter(pid_t &child_pid, uint64_t &pc) {
user_regs_struct regs = get_registers(child_pid);
#ifdef __x86_64__
regs.rip = pc;
#else
regs.eip = pc;
#endif
ptrace(PTRACE_SETREGS, child_pid, nullptr, ®s);
}
user_regs_struct Breakpoint::get_registers(pid_t &child_pid) {
struct user_regs_struct regs;
long esp, eax, ebx, edx, ecx, esi, edi, eip;
#ifdef __x86_64__
esp = regs.rsp;
eip = regs.rip;
eax = regs.rax;
ebx = regs.rbx;
ecx = regs.rcx;
edx = regs.rdx;
esi = regs.rsi;
edi = regs.rdi;
#else
esp = regs.esp;
eip = regs.eip;
eax = regs.eax;
ebx = regs.ebx;
ecx = regs.ecx;
edx = regs.edx;
esi = regs.esi;
edi = regs.edi;
#endif
if(ptrace(PTRACE_GETREGS, child_pid, nullptr, ®s) == -1) {
std::cout << "Error: PTRACE_GETREGS" << std::endl;
exit(1);
};
return regs;
}
void Breakpoint::enable_breakpoint(pid_t &child_pid, breakpoint_t &bp) {
auto data = ptrace(PTRACE_PEEKDATA, child_pid, bp.m_bp_address, nullptr);
bp.m_original_data = static_cast<uint8_t>(data & 0xff); //save bottom byte
//set bottom byte to 0xcc
uint64_t int3 = 0xcc;
uint64_t data_with_int3 = ((data & ~0xff) | int3);
ptrace(PTRACE_POKEDATA, child_pid, bp.m_bp_address, data_with_int3);
bp.m_enabled = true;
}
void Breakpoint::disable_breakpoint(pid_t &child_pid, breakpoint_t &bp) {
auto data = ptrace(PTRACE_PEEKDATA, child_pid, bp.m_bp_address, nullptr);
//overwrite the low byte with the original data and write it back to memory.
auto restored_data = ((data & ~0xff) | bp.m_original_data);
ptrace(PTRACE_POKEDATA, child_pid, bp.m_bp_address, restored_data);
bp.m_enabled = false;
}
| 30.721925 | 98 | 0.636554 | finixbit |