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 109 | 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 48.5k ⌀ | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9c99294d15a63bd543ecbd828b2ddfab607b8451 | 1,158 | cpp | C++ | 2019Homeworks/20191026_Mock_MidTerm/4.BacteriaMulti.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | 8 | 2019-10-09T14:33:42.000Z | 2020-12-03T00:49:29.000Z | 2019Homeworks/20191026_Mock_MidTerm/4.BacteriaMulti.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | null | null | null | 2019Homeworks/20191026_Mock_MidTerm/4.BacteriaMulti.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | null | null | null | #include<iostream>
#include<cstring>
using namespace std;
int tie_n[10][10];
int tie[10][10];
int tie_o[10][10];
void gen(int x,int y){
int b=tie[x][y];
if(x!=1){
if(y!=1)tie_n[x-1][y-1]+=b;
tie_n[x-1][y]+=b;
if(y!=9)tie_n[x-1][y+1]+=b;
}
if(y!=1)tie_n[x][y-1]+=b;
tie_n[x][y]+=2*b;
if(y!=9)tie_n[x][y+1]+=b;
if(x!=9){
if(y!=1)tie_n[x+1][y-1]+=b;
tie_n[x+1][y]+=b;
if(y!=9)tie_n[x+1][y+1]+=b;
}
}
int main(){
int n;
memset(tie,0,sizeof(tie));
memset(tie_n,0,sizeof(tie_n));
memset(tie_o,0,sizeof(tie));
cin>>tie[5][5]>>n;
while(n--){
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++){
gen(i,j);
}
}
//for(int i=1;i<=9;i++){
// for(int j=1;j<=9;j++){
// tie_n[i][j]-=tie_o[i][j];
// }
//}
//memcpy(tie_o,tie,sizeof(tie));
memcpy(tie,tie_n,sizeof(tie_n));
memset(tie_n,0,sizeof(tie_n));
}
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++){
cout<<tie[i][j]<<(j==9?"\n":" ");
}
}
return 0;
} | 23.16 | 45 | 0.418826 | Guyutongxue |
9c9cc61371f6bd8d0ec219d8e5f48f6c7baca41d | 3,098 | cpp | C++ | libs/ml/tests/unit/ops/top_k.cpp | kitounliu/ledger | 3fed5269efbdd68b059648678af01a02e90b41bd | [
"Apache-2.0"
] | null | null | null | libs/ml/tests/unit/ops/top_k.cpp | kitounliu/ledger | 3fed5269efbdd68b059648678af01a02e90b41bd | [
"Apache-2.0"
] | null | null | null | libs/ml/tests/unit/ops/top_k.cpp | kitounliu/ledger | 3fed5269efbdd68b059648678af01a02e90b41bd | [
"Apache-2.0"
] | null | null | null | //------------------------------------------------------------------------------
//
// Copyright 2018-2020 Fetch.AI 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.
//
//------------------------------------------------------------------------------
#include "test_types.hpp"
#include "math/base_types.hpp"
#include "ml/ops/top_k.hpp"
#include "gtest/gtest.h"
#include <memory>
#include <vector>
namespace {
using namespace fetch::ml;
template <typename T>
class TopKOpTest : public ::testing::Test
{
};
TYPED_TEST_SUITE(TopKOpTest, fetch::math::test::TensorFloatingTypes, );
TYPED_TEST(TopKOpTest, forward_test)
{
using SizeType = typename TypeParam::SizeType;
using TensorType = TypeParam;
TensorType data = TypeParam::FromString("9,4,3,2;5,6,7,8;1,10,11,12;13,14,15,16");
data.Reshape({4, 4});
TensorType gt = TypeParam::FromString("13,14,15,16;9,10,11,12");
gt.Reshape({2, 4});
SizeType k = 2;
bool sorted = true;
fetch::ml::ops::TopK<TypeParam> op(k, sorted);
TypeParam prediction(op.ComputeOutputShape({std::make_shared<TypeParam>(data)}));
op.Forward({std::make_shared<TypeParam>(data)}, prediction);
// test correct values
ASSERT_EQ(prediction.shape(), gt.shape());
ASSERT_TRUE(prediction.AllClose(gt));
}
TYPED_TEST(TopKOpTest, backward_2D_test)
{
using TensorType = TypeParam;
using SizeType = typename TypeParam::SizeType;
using DataType = typename TypeParam::Type;
TensorType data = TypeParam::FromString("9,4,3,2;5,6,7,8;1,10,11,12;13,14,15,16");
data.Reshape({4, 4});
TensorType error = TypeParam::FromString("20,-21,22,-23;24,-25,26,-27");
error.Reshape({2, 4});
TensorType gt_error = TypeParam::FromString("24,0,0,0;0,0,0,0;0,-25,26,-27;20,-21,22,-23");
gt_error.Reshape({4, 4});
SizeType k = 2;
bool sorted = true;
auto shape = error.shape();
fetch::ml::ops::TopK<TypeParam> op(k, sorted);
TypeParam prediction(op.ComputeOutputShape({std::make_shared<TypeParam>(data)}));
op.Forward({std::make_shared<TypeParam>(data)}, prediction);
std::vector<TensorType> error_signal =
op.Backward({std::make_shared<const TensorType>(data)}, error);
ASSERT_EQ(error_signal.at(0).shape().size(), 2);
ASSERT_EQ(error_signal.at(0).shape().at(0), 4);
ASSERT_EQ(error_signal.at(0).shape().at(1), 4);
ASSERT_TRUE(error_signal.at(0).AllClose(gt_error, fetch::math::function_tolerance<DataType>(),
fetch::math::function_tolerance<DataType>()));
fetch::math::state_clear<DataType>();
}
} // namespace
| 31.292929 | 96 | 0.651065 | kitounliu |
9ca3cdfa145eb8887328576ef4d6d8be7b59b415 | 242 | cpp | C++ | practice/srv.cpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | 47 | 2016-05-20T08:49:47.000Z | 2022-01-03T01:17:07.000Z | practice/srv.cpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | null | null | null | practice/srv.cpp | MaxHonggg/professional_boost | 6fff73d3b9832644068dc8fe0443be813c7237b4 | [
"BSD-2-Clause"
] | 37 | 2016-07-25T04:52:08.000Z | 2022-02-14T03:55:08.000Z | // Copyright (c) 2016
// Author: Chrono Law
#include <std.hpp>
//using namespace std;
using std::cout;
using std::endl;
#include "tcp_server.hpp"
int main()
{
cout << "server start" << endl;
tcp_server svr(6677);
svr.run();
}
| 13.444444 | 35 | 0.628099 | MaxHonggg |
9ca93a8a09b901e9302a14bf9b106b560974b736 | 6,208 | cpp | C++ | LiquidCore/src/ios/V82JSC/BigInt.cpp | vivocha/LiquidCore | 8fdc3abc4a7a4601ae9049f163b6b9debd2eb9a4 | [
"MIT"
] | null | null | null | LiquidCore/src/ios/V82JSC/BigInt.cpp | vivocha/LiquidCore | 8fdc3abc4a7a4601ae9049f163b6b9debd2eb9a4 | [
"MIT"
] | null | null | null | LiquidCore/src/ios/V82JSC/BigInt.cpp | vivocha/LiquidCore | 8fdc3abc4a7a4601ae9049f163b6b9debd2eb9a4 | [
"MIT"
] | 1 | 2020-05-04T22:27:52.000Z | 2020-05-04T22:27:52.000Z | /*
* Copyright (c) 2018 Eric Lange
*
* Distributed under the MIT License. See LICENSE.md at
* https://github.com/LiquidPlayer/LiquidCore for terms and conditions.
*/
#include "V82JSC.h"
#include <iomanip>
using namespace V82JSC;
using namespace v8;
Local<BigInt> BigInt::New(Isolate* isolate, int64_t value)
{
EscapableHandleScope scope(isolate);
auto context = OperatingContext(isolate);
auto ctx = ToContextRef(context);
std::stringstream stream;
stream << value;
std::string strValue(stream.str());
auto arg_local = v8::String::NewFromUtf8(isolate, strValue.c_str(), v8::String::NewStringType::kNormalString);
auto arg = ToJSValueRef(arg_local, context);
auto bigint = exec(ctx, "return BigInt(_1)", 1, &arg);
return scope.Escape(V82JSC::Value::New(ToContextImpl(context), bigint).As<BigInt>());
}
Local<BigInt> BigInt::NewFromUnsigned(Isolate* isolate, uint64_t value)
{
EscapableHandleScope scope(isolate);
auto context = OperatingContext(isolate);
auto ctx = ToContextRef(context);
std::stringstream stream;
stream << value;
std::string strValue(stream.str());
auto arg_local = v8::String::NewFromUtf8(isolate, strValue.c_str(), v8::String::NewStringType::kNormalString);
auto arg = ToJSValueRef(arg_local, context);
auto bigint = exec(ctx, "return BigInt(_1)", 1, &arg);
return scope.Escape(V82JSC::Value::New(ToContextImpl(context), bigint).As<BigInt>());
}
/**
* Creates a new BigInt object using a specified sign bit and a
* specified list of digits/words.
* The resulting number is calculated as:
*
* (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...)
*/
MaybeLocal<BigInt> BigInt::NewFromWords(Local<v8::Context> context, int sign_bit,
int word_count, const uint64_t* words)
{
auto isolate = ToIsolate(ToContextImpl(context)->GetIsolate());
EscapableHandleScope scope(isolate);
auto ctx = ToContextRef(context);
std::stringstream stream;
if (sign_bit) stream << "-";
stream << "0x";
for (int i=word_count; i>0; --i) {
stream << std::setfill('0') << std::setw(16) << std::hex << words[i-1];
}
std::string strValue(stream.str());
auto arg_local = v8::String::NewFromUtf8(isolate, strValue.c_str(), v8::String::NewStringType::kNormalString);
auto arg = ToJSValueRef(arg_local, context);
auto bigint = exec(ctx, "return BigInt(_1)", 1, &arg);
return scope.Escape(V82JSC::Value::New(ToContextImpl(context), bigint).As<BigInt>());
}
/**
* Returns the value of this BigInt as an unsigned 64-bit integer.
* If `lossless` is provided, it will reflect whether the return value was
* truncated or wrapped around. In particular, it is set to `false` if this
* BigInt is negative.
*/
uint64_t BigInt::Uint64Value(bool* lossless) const
{
auto context = ToCurrentContext(this);
auto ctx = ToContextRef(context);
auto value = ToJSValueRef(this, context);
auto int64 = exec(ctx, "let v = BigInt.asUIntN(64,_1); return BigInt.EQ === undefined ? [v, _1==v] : [v, BigInt.EQ(_1, v)]", 1, &value);
auto int64_v = JSObjectGetPropertyAtIndex(ctx, (JSObjectRef)int64, 0, nullptr);
auto int64_lossless = JSObjectGetPropertyAtIndex(ctx, (JSObjectRef)int64, 1, nullptr);
if (lossless) {
*lossless = JSValueToBoolean(ctx, int64_lossless);
}
return JSValueToNumber(ctx, int64_v, nullptr);
}
/**
* Returns the value of this BigInt as a signed 64-bit integer.
* If `lossless` is provided, it will reflect whether this BigInt was
* truncated or not.
*/
int64_t BigInt::Int64Value(bool* lossless) const
{
auto context = ToCurrentContext(this);
auto ctx = ToContextRef(context);
auto value = ToJSValueRef(this, context);
auto int64 = exec(ctx, "let v = BigInt.asIntN(64,_1); return BigInt.EQ === undefined ? [v, _1==v] : [v, BigInt.EQ(_1, v)]", 1, &value);
auto int64_v = JSObjectGetPropertyAtIndex(ctx, (JSObjectRef)int64, 0, nullptr);
auto int64_lossless = JSObjectGetPropertyAtIndex(ctx, (JSObjectRef)int64, 1, nullptr);
if (lossless) {
*lossless = JSValueToBoolean(ctx, int64_lossless);
}
return JSValueToNumber(ctx, int64_v, nullptr);
}
/**
* Returns the number of 64-bit words needed to store the result of
* ToWordsArray().
*/
int BigInt::WordCount() const
{
auto context = ToCurrentContext(this);
auto ctx = ToContextRef(context);
auto value = ToJSValueRef(this, context);
auto words = exec(ctx, "let s = _1.toString(16); let l = s.length - (s[0]==='-')?1:0; return (l/16) + 1", 1, &value);
return JSValueToNumber(ctx, words, nullptr);
}
/**
* Writes the contents of this BigInt to a specified memory location.
* `sign_bit` must be provided and will be set to 1 if this BigInt is
* negative.
* `*word_count` has to be initialized to the length of the `words` array.
* Upon return, it will be set to the actual number of words that would
* be needed to store this BigInt (i.e. the return value of `WordCount()`).
*/
void BigInt::ToWordsArray(int* sign_bit, int* word_count, uint64_t* words) const
{
auto context = ToCurrentContext(this);
auto ctx = ToContextRef(context);
auto value = ToJSValueRef(this, context);
const auto code =
"let s = _1.toString(16); "
"let sign_bit = s[0] === '-'; "
"if (sign_bit) s = s.substr(1); "
"let padn = s.length % 16; "
"for (let i=0; i < padn; i++) s = '0'.concat(s); "
"let words = [];"
"while (s.length > 0) {"
" let w = s.substr(0,16); s = substr(16);"
" words.push(parseInt(w,16));"
"}"
"return [sign_bit, words.length, words];";
auto ret = exec(ctx, code, 1, &value);
*sign_bit = JSValueToNumber(ctx, JSObjectGetPropertyAtIndex(ctx, (JSObjectRef)ret, 0, nullptr), nullptr);
int wc = JSValueToNumber(ctx, JSObjectGetPropertyAtIndex(ctx, (JSObjectRef)ret, 1, nullptr), nullptr);
auto arr = JSValueToObject(ctx, JSObjectGetPropertyAtIndex(ctx, (JSObjectRef)ret, 2, nullptr), nullptr);
for (int i=0; i<wc && i<*word_count; i++) {
words[i] = JSValueToNumber(ctx, JSObjectGetPropertyAtIndex(ctx, arr, i, nullptr), nullptr);
}
*word_count = wc;
}
| 37.853659 | 140 | 0.67107 | vivocha |
9caadc813a6ed2aeed32189d8e0520ce2feb1ba9 | 1,075 | cpp | C++ | net/ip_tools.cpp | AlexRuzin/CPP_API | 404e2c298244e0e29cf06b8e1def4ed59a149cb2 | [
"MIT"
] | 14 | 2018-01-04T18:30:59.000Z | 2021-07-07T15:15:15.000Z | net/ip_tools.cpp | AlexRuzin/CPP_API | 404e2c298244e0e29cf06b8e1def4ed59a149cb2 | [
"MIT"
] | null | null | null | net/ip_tools.cpp | AlexRuzin/CPP_API | 404e2c298244e0e29cf06b8e1def4ed59a149cb2 | [
"MIT"
] | 6 | 2018-08-31T03:45:43.000Z | 2019-06-05T02:55:46.000Z | #include <Windows.h>
#include "ip_tools.h"
#include "../../_api/common/mem.h"
#include "../../_api/common/str.h"
using namespace ip_tools;
bool ip_tools::is_ip(__in LPCSTR name)
{
IP_ADDR_A address;
mem::zeromem(&address, sizeof(IP_ADDR_A));
PCHAR ptr = (PCHAR)name;
for (UINT i = 0; i <= 3; i++) {
PCHAR end = ptr;
while (*end != '.') {
if (*end == '\0') {
if (i == 3) {
break;
}
i = 0;
while (address.octets[i] != NULL) {
mem::free(address.octets[i]);
i++;
}
return false;
}
end++;
}
address.octets[i] = (PCHAR)mem::malloc((DWORD_PTR)end - (DWORD_PTR)ptr + str::ASCII_CHAR);
mem::copy(address.octets[i], ptr, (DWORD_PTR)((DWORD_PTR)end - (DWORD_PTR)ptr));
if (*end == '\0') break;
ptr = &end[str::ASCII_CHAR];
}
for (UINT i = 0; i < 4; i++) {
if (str::is_digitA(address.octets[i], str::lenA(address.octets[i])) == false) {
for (i = 0; i < 4; i++) {
mem::free(address.octets[i]);
}
return false;
}
}
for (UINT i = 0; i < 4; i++) {
mem::free(address.octets[i]);
}
return true;
} | 21.5 | 92 | 0.557209 | AlexRuzin |
9cab2dd20c51fd6ea54b1e86cf525e159c69134a | 1,347 | cpp | C++ | model_qtlog4/main.cpp | snailone008/Gameinterface-Doudizhu | 8f7f9e3a4e73651ec9aa7eecb2f57a82ea6879ba | [
"Apache-2.0"
] | null | null | null | model_qtlog4/main.cpp | snailone008/Gameinterface-Doudizhu | 8f7f9e3a4e73651ec9aa7eecb2f57a82ea6879ba | [
"Apache-2.0"
] | null | null | null | model_qtlog4/main.cpp | snailone008/Gameinterface-Doudizhu | 8f7f9e3a4e73651ec9aa7eecb2f57a82ea6879ba | [
"Apache-2.0"
] | null | null | null | #include <QApplication>
#include <qblog4qt.h>
#include<QDebug>
#include "qsampledata.h"
#include <QJsonDocument>
#include <QJsonObject>
#include "reflectionobject.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Log4Info("hello world log4info4!", "abcdefg");
Log4Warn("Log4Warn", "234");
Log4Debug("Log4Debug", "234");
Log4Fatal("Log4Fatal", "234");
// Log4Error("snailone --fin not found");
// return a.exec();
QSampleData data;
data.m_nType = 12;
data.m_strName = "vic.MINg";
QJsonObject json ;
json.insert("m_nType", data.m_nType);
json.insert("Time", data.m_strName );
json.insert("Qing", true);
QJsonDocument document;
document.setObject(json);
QByteArray byteArray = document.toJson(QJsonDocument::Compact);
QString str(byteArray);
Log4Info(str);
int propertyIndex;
// ReflectionObject theObject;
// const QMetaObject* theMetaObject = theObject.metaObject();
// int propertyCount = theMetaObject->propertyCount();
// for(propertyIndex = 0; propertyIndex < propertyCount; ++propertyIndex)
// {
// QMetaProperty oneProperty = theMetaObject->property(propertyIndex);
// qDebug() << "name: " << oneProperty.name();
// qDebug() << "type: " << oneProperty.type() << "\n";
// }
return 0;
}
| 23.224138 | 77 | 0.64588 | snailone008 |
9cac069f3770e1db1fd827f37c8d5c80ec8968f1 | 2,172 | cpp | C++ | src/engine/sound/openal/OpenALSound.cpp | zapolnov/TankHero | a907417dc171cb0d4ea04539ae09ba37ee7782ab | [
"MIT"
] | null | null | null | src/engine/sound/openal/OpenALSound.cpp | zapolnov/TankHero | a907417dc171cb0d4ea04539ae09ba37ee7782ab | [
"MIT"
] | null | null | null | src/engine/sound/openal/OpenALSound.cpp | zapolnov/TankHero | a907417dc171cb0d4ea04539ae09ba37ee7782ab | [
"MIT"
] | null | null | null | #include "OpenALSound.h"
#include "src/engine/utility/StbVorbis.h"
#include <cassert>
#include <cstdlib>
OpenALSound::OpenALSound(ALCcontext* context)
: mContext(context)
, mBuffer(0)
{
if (mContext) {
alcMakeContextCurrent(mContext);
alGenBuffers(1, &mBuffer);
}
}
OpenALSound::~OpenALSound()
{
if (mContext) {
alcMakeContextCurrent(mContext);
alDeleteBuffers(1, &mBuffer);
}
}
void OpenALSound::load(const std::string& file)
{
if (!mContext)
return;
short* buffer = nullptr;
int channels = 0;
int sampleRate = 0;
int nSamples = stb_vorbis_decode_filename(file.c_str(), &channels, &sampleRate, &buffer);
assert(nSamples > 0);
if (nSamples <= 0) {
if (buffer)
std::free(buffer);
return;
}
assert(channels == 1 || channels == 2);
if (channels != 1 && channels != 2) {
std::free(buffer);
return;
}
ALenum format = (channels == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16);
size_t bufferSize = size_t(nSamples) * size_t(channels) * sizeof(short);
alcMakeContextCurrent(mContext);
alBufferData(mBuffer, format, buffer, ALsizei(bufferSize), sampleRate);
std::free(buffer);
}
void OpenALSound::play(ALuint source, bool looping)
{
if (!mContext)
return;
alcMakeContextCurrent(mContext);
alSource3f(source, AL_POSITION, 0.0f, 0.0f, 0.0f);
alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE);
alSourcef(source, AL_PITCH, 1.0f);
alSourcef(source, AL_GAIN, 1.0f);
alSourcei(source, AL_BUFFER, mBuffer);
alSourcei(source, AL_LOOPING, (looping ? AL_TRUE : AL_FALSE));
alSourcePlay(source);
}
void OpenALSound::play(ALuint source, const glm::vec3& position, bool looping)
{
if (!mContext)
return;
alcMakeContextCurrent(mContext);
alSourcefv(source, AL_POSITION, &position[0]);
alSourcei(source, AL_SOURCE_RELATIVE, AL_FALSE);
alSourcef(source, AL_PITCH, 1.0f);
alSourcef(source, AL_GAIN, 1.0f);
alSourcei(source, AL_BUFFER, mBuffer);
alSourcei(source, AL_LOOPING, (looping ? AL_TRUE : AL_FALSE));
alSourcePlay(source);
}
| 25.857143 | 93 | 0.653315 | zapolnov |
66d771cd17310ce13c1ca32d1ed1d8c8f4ac995a | 1,250 | hpp | C++ | lib/ArduinoJson/src/ArduinoJson/Object/ObjectFunctions.hpp | shybzzz/ESP-1ch-Gateway | 25cac33837e06b11439193a3a0a2dc81b35bf686 | [
"MIT"
] | 274 | 2016-04-13T11:34:42.000Z | 2022-03-22T08:29:30.000Z | lib/ArduinoJson/src/ArduinoJson/Object/ObjectFunctions.hpp | shybzzz/ESP-1ch-Gateway | 25cac33837e06b11439193a3a0a2dc81b35bf686 | [
"MIT"
] | 99 | 2016-04-15T09:58:24.000Z | 2022-03-23T16:05:28.000Z | lib/ArduinoJson/src/ArduinoJson/Object/ObjectFunctions.hpp | shybzzz/ESP-1ch-Gateway | 25cac33837e06b11439193a3a0a2dc81b35bf686 | [
"MIT"
] | 134 | 2016-05-19T02:40:20.000Z | 2022-03-18T11:32:32.000Z | // ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2020
// MIT License
#pragma once
#include <ArduinoJson/Collection/CollectionData.hpp>
namespace ARDUINOJSON_NAMESPACE {
template <typename Visitor>
void objectAccept(const CollectionData *obj, Visitor &visitor) {
if (obj)
visitor.visitObject(*obj);
else
visitor.visitNull();
}
inline bool objectEquals(const CollectionData *lhs, const CollectionData *rhs) {
if (lhs == rhs) return true;
if (!lhs || !rhs) return false;
return lhs->equalsObject(*rhs);
}
template <typename TAdaptedString>
inline VariantData *objectGet(const CollectionData *obj, TAdaptedString key) {
if (!obj) return 0;
return obj->get(key);
}
template <typename TAdaptedString>
void objectRemove(CollectionData *obj, TAdaptedString key) {
if (!obj) return;
obj->remove(key);
}
template <typename TAdaptedString>
inline VariantData *objectGetOrCreate(CollectionData *obj, TAdaptedString key,
MemoryPool *pool) {
if (!obj) return 0;
// ignore null key
if (key.isNull()) return 0;
// search a matching key
VariantData *var = obj->get(key);
if (var) return var;
return obj->add(key, pool);
}
} // namespace ARDUINOJSON_NAMESPACE
| 24.038462 | 80 | 0.7064 | shybzzz |
66dca17d5f818dd022cb1ee1a201aba82c08af48 | 1,848 | cpp | C++ | src/src/NodeValue/Type.cpp | Scorbutics/skalang | c8d1869a2f0c7857ee05ef45bd3aa4e537d39558 | [
"MIT"
] | 3 | 2019-04-08T17:34:19.000Z | 2020-01-03T04:47:06.000Z | src/src/NodeValue/Type.cpp | Scorbutics/skalang | c8d1869a2f0c7857ee05ef45bd3aa4e537d39558 | [
"MIT"
] | 4 | 2020-04-19T22:09:06.000Z | 2020-11-06T15:47:08.000Z | src/src/NodeValue/Type.cpp | Scorbutics/skalang | c8d1869a2f0c7857ee05ef45bd3aa4e537d39558 | [
"MIT"
] | null | null | null | #include "Config/LoggerConfigLang.h"
#include "Symbol.h"
#include "Type.h"
#include "Service/SymbolTable.h"
#include "Service/TypeCrosser/TypeCrossExpression.h"
#include "Runtime/Service/ScriptTypeSerializer.h"
SKA_LOGC_CONFIG(ska::LogLevel::Disabled, ska::Type)
ska::Type ska::Type::crossTypes(const TypeCrosser& crosser, std::string op, const Type& type2) const {
return crosser.cross(op, *this, type2);
}
ska::Type::Type(const Symbol* symbol, ExpressionType t) :
m_type(t),
m_symbol(symbol) {
}
bool ska::Type::operator==(const Type& t) const {
if (m_symbol != nullptr && t.m_symbol != nullptr) {
return *m_symbol == *t.m_symbol;
}
return structuralEquality(t);
}
std::string ska::Type::name() const {
return m_symbol == nullptr ? "" : m_symbol->name();
}
bool ska::Type::structuralEquality(const Type& t) const {
return m_type == t.m_type && m_compound == t.m_compound;
}
bool ska::Type::tryChangeSymbol(const Type& type) {
if (type.m_symbol != nullptr && m_symbol != type.m_symbol) {
m_symbol = type.m_symbol;
return true;
}
return false;
}
std::ostream& ska::operator<<(std::ostream& stream, const ska::Type& type) {
const auto mainType = ExpressionTypeSTR[static_cast<std::size_t>(type.m_type)];
auto addedSymbolPart = (type.m_symbol == nullptr ? "" : (" " + type.m_symbol->name()));
if (type.m_compound.empty()) {
stream << mainType << addedSymbolPart;
} else {
stream << mainType << addedSymbolPart << " (";
std::size_t rindex = type.m_compound.size() - 1;
for (const auto& childType : type.m_compound) {
stream << childType << (rindex == 0 ? "" : " - ");
rindex--;
}
stream << ")";
}
return stream;
}
void ska::Type::serialize(SerializerOutput& output, ScriptTypeSerializer& serializer, bool writeSymbol) const {
serializer.write(output, writeSymbol ? m_symbol : nullptr, *this);
}
| 28 | 111 | 0.687229 | Scorbutics |
66dffa219e24da14812ed15dee516e225071835e | 222 | cpp | C++ | src/Modules/MainAppModule/MainAppModule.cpp | Di-Strix/MaterializeLayout | 4cf1b4c696c961b4909cb1e149e3bef44310a145 | [
"MIT"
] | 1 | 2021-07-25T08:35:08.000Z | 2021-07-25T08:35:08.000Z | src/Modules/MainAppModule/MainAppModule.cpp | Di-Strix/MaterializeLayout | 4cf1b4c696c961b4909cb1e149e3bef44310a145 | [
"MIT"
] | null | null | null | src/Modules/MainAppModule/MainAppModule.cpp | Di-Strix/MaterializeLayout | 4cf1b4c696c961b4909cb1e149e3bef44310a145 | [
"MIT"
] | null | null | null | #include "MainAppModule.h"
MaterializeLayoutModule getMainAppModule()
{
return {
{ "",
0,
0 },
{ "f6cc125703de810dcfc41a47649d9dbe",
APPLICATION_JS,
APPLICATION_JS_LENGTH }
};
} | 17.076923 | 42 | 0.608108 | Di-Strix |
66e1dd2914210b3df93e7f9f168b7eace86e22d7 | 6,257 | cpp | C++ | src/oxtra/dispatcher/dispatcher.cpp | oxtra/oxtra | cd538062869bfe68fc8552604c22334589d7380c | [
"BSD-3-Clause"
] | 9 | 2019-10-22T19:44:25.000Z | 2021-05-02T17:47:14.000Z | src/oxtra/dispatcher/dispatcher.cpp | oxtra/oxtra | cd538062869bfe68fc8552604c22334589d7380c | [
"BSD-3-Clause"
] | 1 | 2020-11-16T20:06:14.000Z | 2020-11-16T20:06:14.000Z | src/oxtra/dispatcher/dispatcher.cpp | oxtra/oxtra | cd538062869bfe68fc8552604c22334589d7380c | [
"BSD-3-Clause"
] | 2 | 2020-11-16T17:05:47.000Z | 2021-05-02T17:47:16.000Z | #include "oxtra/dispatcher/dispatcher.h"
#include "oxtra/dispatcher/syscalls.h"
#include "execution_context.h"
#include "oxtra/debugger/debugger.h"
#include "oxtra/logger/logger.h"
#include "elf.h"
#include <cstring>
using namespace dispatcher;
using namespace codegen;
using namespace utils;
Dispatcher::Dispatcher(const elf::Elf& elf, const arguments::Arguments& args, char** envp)
: _elf(elf), _args(args), _envp(envp), _codegen(args, elf) {}
long Dispatcher::run() {
const auto[guest_stack, return_stack, tlb_address] = init_guest_context();
// initialize the debugger if necessary
std::unique_ptr<debugger::Debugger> debugger = nullptr;
if (_args.get_debugging() > 0) {
debugger = std::make_unique<debugger::Debugger>(_elf, &_context, _args.get_debugging() == 2,
_context.guest.map.rsp - _args.get_stack_size(),
_args.get_stack_size());
_context.debugger = debugger.get();
}
// set the flags indirectly
_context.flag_info.overflow_operation = static_cast<uint16_t>(jump_table::Entry::overflow_clear) * 4;
_context.flag_info.carry_operation = static_cast<uint16_t>(jump_table::Entry::carry_clear) * 4;
_context.flag_info.zero_value = 1;
_context.flag_info.sign_size = 0;
_context.flag_info.parity_value = 1;
_context.flag_info.carry_pointer = 0;
_context.flag_info.overflow_pointer = 0;
// switch the context and begin translation
const char* error_string = nullptr;
const auto exit_code = guest_enter(&_context, _elf.get_entry_point(), &error_string);
munmap(reinterpret_cast<void*>(return_stack), 0x1000);
munmap(reinterpret_cast<void*>(tlb_address), Dispatcher::tlb_size * sizeof(uintptr_t) * 2);
// check if the guest has ended with and error
if (error_string != nullptr) {
std::string error{error_string};
munmap(reinterpret_cast<void*>(guest_stack), _args.get_stack_size());
throw std::runtime_error(error);
}
munmap(reinterpret_cast<void*>(guest_stack), _args.get_stack_size());
return exit_code;
}
ExecutionContext* Dispatcher::execution_context() {
register ExecutionContext* ctx asm("s11");
return ctx;
}
std::tuple<uintptr_t, uintptr_t, uintptr_t> Dispatcher::init_guest_context() {
// https://software.intel.com/sites/default/files/article/402129/mpx-linux64-abi.pdf
_context.guest.map.rdx = 0; // function-pointer to on-exit
_context.guest.map.call_table = reinterpret_cast<uintptr_t>(_codegen.get_call_table());
_context.guest.map.return_stack = reinterpret_cast<uintptr_t>(mmap(nullptr, 0x1000, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
_context.guest.map.jump_table = reinterpret_cast<uintptr_t>(jump_table::table_address);
_context.guest.map.tlb = reinterpret_cast<uintptr_t>(mmap(nullptr, Dispatcher::tlb_size * sizeof(uintptr_t) * 2,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
_context.guest.map.context = reinterpret_cast<uintptr_t>(&_context);
_context.codegen = &_codegen;
_context.program_break = _context.initial_break = _context.last_break_page = _elf.get_base_vaddr() + _elf.get_image_size();
_context.syscall_map = reinterpret_cast<const uintptr_t*>(syscalls::syscall_map.data());
auto envp = _envp;
// count environment pointers and search for aux vectors
while (*envp++ != nullptr); // find the first entry after the null entry
const size_t env_count = envp - _envp; // size includes nullptr
// aux vectors begin after the envp (null separated)
const auto auxvs = reinterpret_cast<Elf64_auxv_t*>(envp);
// count aux vectors
auto auxv = auxvs;
while ((auxv++)->a_type != AT_NULL);
const size_t
auxv_count = auxv - auxvs, // size includes null entry
auxv_size = auxv_count * sizeof(Elf64_auxv_t) - 8; // last entry is 8 bytes
// the count of the necessary arguments with zero entries in between (in bytes). Zero paddings are included in size
const auto min_stack_size = utils::page_align(auxv_size + // auxv
env_count * sizeof(char*) + // envp
sizeof(char*) + _args.get_guest_arguments().size() * sizeof(char*) + // argv
sizeof(size_t)); // argc
// initialize the stack (assume a page for the arg, env pointers and aux vectors)
const auto stack_size = utils::page_align(_args.get_stack_size());
const auto stack_memory = reinterpret_cast<uintptr_t>(mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
// page aligned by only using page-aligned values
_context.guest.map.rsp = stack_memory + stack_size - min_stack_size;
_context.guest.map.rbp = 0; // unspecified
auto rsp = reinterpret_cast<size_t*>(_context.guest.map.rsp);
// put argc and argv on stack
*rsp++ = _args.get_guest_arguments().size() + 1;
*rsp++ = reinterpret_cast<size_t>(_args.get_guest_path());
for (const auto& arg : _args.get_guest_arguments()) {
*rsp++ = reinterpret_cast<size_t>(arg.c_str());
}
*rsp++ = 0;
// put environment strings on the stack
std::memcpy(rsp, _envp, env_count * sizeof(char*));
rsp += env_count;
// put aux vectors on the stack
std::memcpy(rsp, auxvs, auxv_size);
const auto guest_auxv = reinterpret_cast<Elf64_auxv_t*>(rsp);
for (auto entry = guest_auxv; entry->a_type != AT_NULL; ++entry) {
if (entry->a_type == AT_PHDR) {
const auto elf_hdr = reinterpret_cast<const Elf64_Ehdr*>(_elf.get_base_vaddr());
entry->a_un.a_val = _elf.get_base_vaddr() + elf_hdr->e_phoff;
} else if (entry->a_type == AT_ENTRY) {
entry->a_un.a_val = _elf.get_entry_point();
}
}
return {stack_memory, _context.guest.map.return_stack, _context.guest.map.tlb};
}
void Dispatcher::emulate_syscall(ExecutionContext* context) {
using namespace syscalls;
// the x86 syscall index
const auto guest_index = context->guest.map.rax;
// is this an invalid index?
if (guest_index < syscall_map.size()) {
// get the entry from the syscall map
const auto entry = syscall_map[guest_index];
if (entry.is_valid()) {
entry.emulation_fn(context);
return;
}
}
// we will only reach this if the system call is not supported
char fault_message[256];
snprintf(fault_message, sizeof(fault_message), "Guest tried to call an unsupported syscall (%li).", guest_index);
dispatcher::Dispatcher::fault_exit(fault_message);
} | 38.863354 | 124 | 0.728464 | oxtra |
66e46613f997a1dfa1e0a4714876a343eb4317d9 | 4,066 | hpp | C++ | src/Evolution/Systems/CurvedScalarWave/TimeDerivative.hpp | kidder/spectre | 97ae95f72320f9f67895d3303824e64de6fd9077 | [
"MIT"
] | 117 | 2017-04-08T22:52:48.000Z | 2022-03-25T07:23:36.000Z | src/Evolution/Systems/CurvedScalarWave/TimeDerivative.hpp | GitHimanshuc/spectre | 4de4033ba36547113293fe4dbdd77591485a4aee | [
"MIT"
] | 3,177 | 2017-04-07T21:10:18.000Z | 2022-03-31T23:55:59.000Z | src/Evolution/Systems/CurvedScalarWave/TimeDerivative.hpp | geoffrey4444/spectre | 9350d61830b360e2d5b273fdd176dcc841dbefb0 | [
"MIT"
] | 85 | 2017-04-07T19:36:13.000Z | 2022-03-01T10:21:00.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <cstddef>
#include "DataStructures/Tensor/TypeAliases.hpp"
#include "Evolution/Systems/CurvedScalarWave/Characteristics.hpp"
#include "Evolution/Systems/CurvedScalarWave/Tags.hpp"
#include "NumericalAlgorithms/LinearOperators/PartialDerivatives.hpp"
#include "PointwiseFunctions/GeneralRelativity/Tags.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/TMPL.hpp"
/// \cond
class DataVector;
template <typename X, typename Symm, typename IndexList>
class Tensor;
/// \endcond
namespace CurvedScalarWave {
/*!
* \brief Compute the time derivative of the evolved variables of the
* first-order scalar wave system on a curved background.
*
* The evolution equations for the first-order scalar wave system are given by
* \cite Holst2004wt :
*
* \f{align}
* \partial_t\Psi = & (1 + \gamma_1) \beta^k \partial_k \Psi - \alpha \Pi -
* \gamma_1 \beta^k \Phi_k \\
*
* \partial_t\Pi = & - \alpha \gamma^{ij}\partial_i\Phi_j + \beta^k \partial_k
* \Pi + \gamma_1 \gamma_2 \beta^k \partial_k \Psi + \alpha \Gamma^i -
* \gamma^{ij} \Phi_i \partial_j \alpha
* + \alpha K \Pi - \gamma_1 \gamma_2 \beta^k \Phi_k\\
*
* \partial_t\Phi_i = & - \alpha \partial_i \Pi + \beta^k \partial_k \Phi +
* \gamma_2 \alpha \partial_i \Psi - \Pi
* \partial_i \alpha + \Phi_k \partial_i \beta^j - \gamma_2 \alpha \Phi_i\\
* \f}
*
* where \f$\Psi\f$ is the scalar field, \f$\Pi\f$ is the
* conjugate momentum to \f$\Psi\f$, \f$\Phi_i=\partial_i\Psi\f$ is an
* auxiliary variable, \f$\alpha\f$ is the lapse, \f$\beta^k\f$ is the shift,
* \f$ \gamma_{ij} \f$ is the spatial metric, \f$ K \f$ is the trace of the
* extrinsic curvature, and \f$ \Gamma^i \f$ is the trace of the Christoffel
* symbol of the second kind. \f$\gamma_1, \gamma_2\f$ are constraint damping
* parameters.
*/
template <size_t Dim>
struct TimeDerivative {
public:
using temporary_tags = tmpl::list<
gr::Tags::Lapse<DataVector>,
gr::Tags::Shift<Dim, Frame::Inertial, DataVector>,
gr::Tags::InverseSpatialMetric<Dim, Frame::Inertial, DataVector>,
Tags::ConstraintGamma1, Tags::ConstraintGamma2>;
using argument_tags = tmpl::list<
Pi, Phi<Dim>, gr::Tags::Lapse<DataVector>,
gr::Tags::Shift<Dim, Frame::Inertial, DataVector>,
::Tags::deriv<gr::Tags::Lapse<DataVector>, tmpl::size_t<Dim>,
Frame::Inertial>,
::Tags::deriv<gr::Tags::Shift<Dim, Frame::Inertial, DataVector>,
tmpl::size_t<Dim>, Frame::Inertial>,
gr::Tags::InverseSpatialMetric<Dim, Frame::Inertial, DataVector>,
gr::Tags::TraceSpatialChristoffelSecondKind<Dim, Frame::Inertial,
DataVector>,
gr::Tags::TraceExtrinsicCurvature<DataVector>, Tags::ConstraintGamma1,
Tags::ConstraintGamma2>;
static void apply(
gsl::not_null<Scalar<DataVector>*> dt_pi,
gsl::not_null<tnsr::i<DataVector, Dim, Frame::Inertial>*> dt_phi,
gsl::not_null<Scalar<DataVector>*> dt_psi,
gsl::not_null<Scalar<DataVector>*> result_lapse,
gsl::not_null<tnsr::I<DataVector, Dim>*> result_shift,
gsl::not_null<tnsr::II<DataVector, Dim>*> result_inverse_spatial_metric,
gsl::not_null<Scalar<DataVector>*> result_gamma1,
gsl::not_null<Scalar<DataVector>*> result_gamma2,
const tnsr::i<DataVector, Dim>& d_pi,
const tnsr::ij<DataVector, Dim>& d_phi,
const tnsr::i<DataVector, Dim>& d_psi, const Scalar<DataVector>& pi,
const tnsr::i<DataVector, Dim>& phi, const Scalar<DataVector>& lapse,
const tnsr::I<DataVector, Dim>& shift,
const tnsr::i<DataVector, Dim>& deriv_lapse,
const tnsr::iJ<DataVector, Dim>& deriv_shift,
const tnsr::II<DataVector, Dim>& upper_spatial_metric,
const tnsr::I<DataVector, Dim>& trace_spatial_christoffel,
const Scalar<DataVector>& trace_extrinsic_curvature,
const Scalar<DataVector>& gamma1, const Scalar<DataVector>& gamma2);
};
} // namespace CurvedScalarWave
| 41.489796 | 78 | 0.679538 | kidder |
66e5f1e085c8cfe167976c28e1c9c9a6b36b919d | 6,484 | hpp | C++ | include/sharpen/ByteBuffer.hpp | KnownSpace/Sharpen | 28c6a7c430b6eeb37eb8d554859321a2bee43776 | [
"MIT"
] | 13 | 2020-10-25T04:02:07.000Z | 2022-03-29T13:21:30.000Z | include/sharpen/ByteBuffer.hpp | KnownSpace/Sharpen | 28c6a7c430b6eeb37eb8d554859321a2bee43776 | [
"MIT"
] | 18 | 2020-10-09T04:51:03.000Z | 2022-03-01T06:24:23.000Z | include/sharpen/ByteBuffer.hpp | KnownSpace/Sharpen | 28c6a7c430b6eeb37eb8d554859321a2bee43776 | [
"MIT"
] | 7 | 2020-10-23T04:25:28.000Z | 2022-03-23T06:52:39.000Z | #pragma once
#ifndef _SHARPEN_BYTEBUFFER_HPP
#define _SHARPEN_BYTEBUFFER_HPP
#include <vector>
#include <algorithm>
#include <type_traits>
#include "Noncopyable.hpp"
#include "TypeDef.hpp"
#include "BufferOps.hpp"
namespace sharpen
{
class ByteBuffer
{
using Vector = std::vector<sharpen::Char>;
using Self = ByteBuffer;
protected:
Vector vector_;
sharpen::Size mark_;
private:
void CheckAndMoveMark();
public:
using Iterator = typename Vector::iterator;
using ConstIterator = typename Vector::const_iterator;
using ReverseIterator = typename Vector::reverse_iterator;
using ConstReverseIterator = typename Vector::const_reverse_iterator;
ByteBuffer();
explicit ByteBuffer(sharpen::Size size);
explicit ByteBuffer(Vector &&vector) noexcept;
ByteBuffer(const sharpen::Char *p,sharpen::Size size);
ByteBuffer(const Self &other);
ByteBuffer(Self &&other) noexcept;
virtual ~ByteBuffer() noexcept = default;
Self &operator=(const Self &other);
Self &operator=(Self &&other) noexcept;
//use by stl
void swap(Self &other) noexcept;
inline void Swap(Self &other) noexcept
{
this->swap(other);
}
void PushBack(sharpen::Char val);
sharpen::Size GetSize() const;
void PopBack();
sharpen::Char Front() const;
sharpen::Char &Front();
sharpen::Char Back() const;
sharpen::Char &Back();
sharpen::Char &Get(sharpen::Size index);
sharpen::Char Get(sharpen::Size index) const;
sharpen::Char GetOrDefault(sharpen::Size index,sharpen::Char defaultVal) const noexcept;
sharpen::Char *Data();
const sharpen::Char* Data() const;
inline sharpen::Char &operator[](sharpen::Size index)
{
return this->Get(index);
}
inline sharpen::Char operator[](sharpen::Size index) const
{
return this->Get(index);
}
void Reserve(sharpen::Size size);
void Reset();
void Extend(sharpen::Size size);
void Extend(sharpen::Size size,sharpen::Char defaultValue);
void ExtendTo(sharpen::Size size);
void ExtendTo(sharpen::Size size,sharpen::Char defaultValue);
void Shrink();
void Append(const sharpen::Char *p,sharpen::Size size);
void Append(const Self &other);
template<typename _Iterator,typename _Checker = decltype(std::declval<Self>().PushBack(*std::declval<_Iterator>()))>
void Append(_Iterator begin,_Iterator end)
{
while (begin != end)
{
this->vector_.push_back(*begin);
++begin;
}
}
void Erase(sharpen::Size pos);
void Erase(sharpen::Size begin,sharpen::Size end);
void Erase(ConstIterator where);
void Erase(ConstIterator begin,ConstIterator end);
void Mark(sharpen::Size pos);
sharpen::Size Remaining() const;
sharpen::Size GetMark() const;
inline Iterator Begin()
{
return this->vector_.begin();
}
inline ConstIterator Begin() const
{
return this->vector_.cbegin();
}
inline ReverseIterator ReverseBegin()
{
return this->vector_.rbegin();
}
inline ConstReverseIterator ReverseBegin() const
{
return this->vector_.crbegin();
}
inline Iterator End()
{
return this->vector_.end();
}
inline ConstIterator End() const
{
return this->vector_.cend();
}
inline ReverseIterator ReverseEnd()
{
return this->vector_.rend();
}
inline ConstReverseIterator ReverseEnd() const
{
return this->vector_.crend();
}
ConstIterator Find(sharpen::Char e) const;
Iterator Find(sharpen::Char e);
ReverseIterator ReverseFind(sharpen::Char e);
ConstReverseIterator ReverseFind(sharpen::Char e) const;
template<typename _Iterator,typename _Check = decltype(std::declval<Self>().Get(0) == *std::declval<_Iterator>())>
Iterator Search(const _Iterator begin,const _Iterator end)
{
return std::search(this->Begin(),this->End(),begin,end);
}
template<typename _Iterator,typename _Check = decltype(std::declval<Self>().Get(0) == *std::declval<_Iterator>())>
ConstIterator Search(const _Iterator begin,const _Iterator end) const
{
return std::search(this->Begin(),this->End(),begin,end);
}
inline void Clear()
{
this->vector_.clear();
}
inline sharpen::Uint32 Adler32() const noexcept
{
return sharpen::Adler32(this->Data(),this->GetSize());
}
inline sharpen::Uint16 Crc16() const noexcept
{
return sharpen::Crc16(this->Data(),this->GetSize());
}
inline sharpen::ByteBuffer Base64Encode() const
{
sharpen::ByteBuffer buf{sharpen::ComputeBase64EncodeSize(this->GetSize())};
bool success = sharpen::Base64Encode(buf.Data(),buf.GetSize(),this->Data(),this->GetSize());
static_cast<void>(success);
return buf;
}
inline sharpen::ByteBuffer Base64Decode() const
{
sharpen::ByteBuffer buf{sharpen::ComputeBase64DecodeSize(this->GetSize())};
bool success = sharpen::Base64Decode(buf.Data(),buf.GetSize(),this->Data(),this->GetSize());
static_cast<void>(success);
return buf;
}
sharpen::Int32 CompareWith(const Self &other) const noexcept;
inline bool operator>(const Self &other) const noexcept
{
return this->CompareWith(other) > 0;
}
inline bool operator<(const Self &other) const noexcept
{
return this->CompareWith(other) < 0;
}
inline bool operator>=(const Self &other) const noexcept
{
return this->CompareWith(other) >= 0;
}
inline bool operator<=(const Self &other) const noexcept
{
return this->CompareWith(other) <= 0;
}
};
}
#endif | 25.427451 | 124 | 0.579426 | KnownSpace |
66e6a627ad1f5c25ab6c3bdf4b5e5549dc65a566 | 582 | cpp | C++ | CCC/16_S2.cpp | juneharold/USACO | a96b54f68e7247c61044f3c0d9e7260952c508e2 | [
"MIT"
] | null | null | null | CCC/16_S2.cpp | juneharold/USACO | a96b54f68e7247c61044f3c0d9e7260952c508e2 | [
"MIT"
] | null | null | null | CCC/16_S2.cpp | juneharold/USACO | a96b54f68e7247c61044f3c0d9e7260952c508e2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
using namespace std;
int Q, N, A[105], B[105];
void find_max() {
int ret=0;
for (int i=0; i<N; i++) {
int speed=max(A[i], B[N-1-i]);
ret+=speed;
}
cout << ret;
}
void find_min() {
int ret=0;
for (int i=0; i<N; i++) {
int speed=max(A[i], B[i]);
ret+=speed;
}
cout << ret;
}
int main()
{
cin >> Q >> N;
for (int i=0; i<N; i++) cin >> A[i];
for (int i=0; i<N; i++) cin >> B[i];
sort(A, A+N);
sort(B, B+N);
if (Q==1) find_min();
else find_max();
}
| 16.166667 | 40 | 0.455326 | juneharold |
66e7501d1dc224968c7ff05df35a26b7bd63769f | 787 | cpp | C++ | lw/net/router_test.cpp | LifeWanted/liblw | af8e08c47cb8aa7542eb2bef9fe09b7a0b44fed8 | [
"MIT"
] | 36 | 2015-10-04T15:05:21.000Z | 2022-01-30T07:18:36.000Z | lw/net/router_test.cpp | LifeWanted/liblw | af8e08c47cb8aa7542eb2bef9fe09b7a0b44fed8 | [
"MIT"
] | 8 | 2017-03-20T12:28:15.000Z | 2021-02-24T20:40:45.000Z | lw/net/router_test.cpp | LifeWanted/liblw | af8e08c47cb8aa7542eb2bef9fe09b7a0b44fed8 | [
"MIT"
] | 6 | 2017-09-25T13:50:03.000Z | 2021-01-16T00:01:44.000Z | #include "lw/net/router.h"
#include <memory>
#include "gtest/gtest.h"
#include "lw/co/task.h"
#include "lw/io/co/co.h"
namespace lw::net {
namespace {
class TestRouter: public Router {
public:
void attach_routes() override {};
co::Task run(std::unique_ptr<io::CoStream> conn) override {
co_return;
};
std::size_t connection_count() const override { return 0; }
const std::unordered_set<RouteBase*>& test_get_registered_routes() {
return get_registered_routes();
}
};
class TestRoute: public RouteBase {};
TEST(Router, RoutesAreRegisterable) {
TestRoute route;
register_route<TestRouter>(&route);
TestRouter router;
const auto& routes = router.test_get_registered_routes();
ASSERT_EQ(routes.size(), 1);
EXPECT_TRUE(routes.contains(&route));
}
}
}
| 20.179487 | 70 | 0.711563 | LifeWanted |
66e8d236cea32fd16ecaaab843b4b44f5376d3b3 | 5,137 | cpp | C++ | bootstrap/frontend/src/ILemitter.cpp | rdrpenguin04/Community-Compiler | 3e1909555930aa6e91916a3b186f17a88dbe5aae | [
"MIT"
] | 18 | 2018-04-30T01:42:34.000Z | 2019-07-26T08:17:22.000Z | bootstrap/frontend/src/ILemitter.cpp | thebennybox-Community-Compiler-Project/Community-Compiler | 08c92b91ae33667b5fa7a6c47db0aa5dc6b0c59c | [
"MIT"
] | 52 | 2018-04-27T19:00:09.000Z | 2018-08-20T08:37:04.000Z | bootstrap/frontend/src/ILemitter.cpp | thebennybox-Community-Compiler-Project/Community-Compiler | 08c92b91ae33667b5fa7a6c47db0aa5dc6b0c59c | [
"MIT"
] | 11 | 2018-04-28T10:50:18.000Z | 2020-08-28T05:35:53.000Z | #include "ILemitter.h"
void ILemitter::remove_last()
{
stream.pop_back();
}
void ILemitter::no_operation() {
w(NOOP);
}
void ILemitter::push_u8(uint8_t x) {
w(PU08);
w(x);
}
void ILemitter::push_u16(uint16_t x) {
w(PU16);
w(x);
}
void ILemitter::push_u32(uint32_t x) {
w(PU32);
w(x);
}
void ILemitter::push_u64(uint64_t x) {
w(PU64);
w(x);
}
void ILemitter::push_i8(int8_t x) {
w(PI08);
w(x);
}
void ILemitter::push_i16(int16_t x) {
w(PI16);
w(x);
}
void ILemitter::push_i32(int32_t x) {
w(PI32);
w(x);
}
void ILemitter::push_i64(int64_t x) {
w(PI64);
w(x);
}
void ILemitter::push_f32(float f) {
w(PF32);
w(f);
}
void ILemitter::push_f64(double d) {
w(PF64);
w(d);
}
void ILemitter::push_true() {
w(PTRU);
}
void ILemitter::push_false() {
w(PFLS);
}
void ILemitter::push_str(const char *str) {
w(PSTR);
w(str);
}
void ILemitter::push_function(const char *lbl) {
w(PFUN);
w(lbl);
}
void ILemitter::push_label(const char *lbl) {
w(PLBL);
w(lbl);
}
void ILemitter::cast(uint8_t type) {
w(CAST);
w(type);
}
void ILemitter::_delete() {
w(DELE);
}
void ILemitter::swap() {
w(SWAP);
}
void ILemitter::duplicate() {
w(DUPE);
}
void ILemitter::compare_equal() {
w(CMPE);
}
void ILemitter::compare_greater_than() {
w(CMPG);
}
void ILemitter::compare_greateror_equal() {
w(CPGE);
}
void ILemitter::compare_less_than() {
w(CMPL);
}
void ILemitter::compare_lessor_equal() {
w(CPGE);
}
void ILemitter::function(const char *lbl) {
w(FUNC);
w(lbl);
}
void ILemitter::_return() {
w(RETN);
}
void ILemitter::call(const char *lbl) {
w(CALL);
w(lbl);
}
void ILemitter::call_stack(
uint8_t return_type, uint32_t *args, uint32_t arg_count) {
w(CALS);
w(return_type);
w(arg_count);
for(uint32_t i = 0; i < arg_count; i++) {
w(args[i]);
}
}
void ILemitter::label(const char *lbl) {
w(LABL);
w(lbl);
}
void ILemitter::jump(const char *lbl) {
w(JUMP);
w(lbl);
}
void ILemitter::jump_equal_zero(const char *lbl) {
w(JEQZ);
w(lbl);
}
void ILemitter::jump_not_equal_zero(const char *lbl) {
w(JNEZ);
w(lbl);
}
void ILemitter::jump_greater_than_zero(const char *lbl) {
w(JGTZ);
w(lbl);
}
void ILemitter::jump_greater_equal_zero(const char *lbl) {
w(JGEZ);
w(lbl);
}
void ILemitter::jump_less_than_zero(const char *lbl) {
w(JLTZ);
w(lbl);
}
void ILemitter::jump_less_equal_zero(const char *lbl) {
w(JLEZ);
w(lbl);
}
void ILemitter::load_local(const char *lbl) {
w(LLOC);
w(lbl);
}
void ILemitter::store_local(const char *lbl) {
w(SLOC);
w(lbl);
}
void ILemitter::address_local(const char *lbl) {
w(ADRL);
w(lbl);
}
void ILemitter::address_stack() {
w(ADRS);
}
void ILemitter::load_argument(const char *lbl) {
w(LARG);
w(lbl);
}
void ILemitter::store_argument(const char *lbl) {
w(SARG);
w(lbl);
}
void ILemitter::address_argument(const char *lbl) {
w(ADRA);
w(lbl);
}
void ILemitter::load_global(const char *lbl) {
w(LGLO);
w(lbl);
}
void ILemitter::store_global(const char *lbl) {
w(SGLO);
w(lbl);
}
void ILemitter::address_global(const char *lbl) {
w(ADRG);
w(lbl);
}
void ILemitter::read() {
w(READ);
}
void ILemitter::write() {
w(WRIT);
}
void ILemitter::integer_add() {
w(IADD);
}
void ILemitter::integer_subtract() {
w(ISUB);
}
void ILemitter::integer_multiply() {
w(IMUL);
}
void ILemitter::integer_divide() {
w(IDIV);
}
void ILemitter::integer_remainder() {
w(IMOD);
}
void ILemitter::integer_negate() {
w(INEG);
}
void ILemitter::float_add() {
w(FADD);
}
void ILemitter::float_subtract() {
w(FSUB);
}
void ILemitter::float_multiply() {
w(FMUL);
}
void ILemitter::float_divide() {
w(FDIV);
}
void ILemitter::float_remainder() {
w(FMOD);
}
void ILemitter::float_negate() {
w(FNEG);
}
void ILemitter::bitwise_left_shift() {
w(BSHL);
}
void ILemitter::bitwise_right_shift() {
w(BSHR);
}
void ILemitter::bitwise_and() {
w(BAND);
}
void ILemitter::bitwise_or() {
w(BWOR);
}
void ILemitter::bitwise_xor() {
w(BXOR);
}
void ILemitter::external_function(
const char *name,
uint8_t type,
uint32_t arg_count,
uint8_t *args) {
w(EXFN);
w(name);
w(type);
w(arg_count);
for(uint32_t i = 0; i < arg_count; i++) {
w(args[i]);
}
}
void ILemitter::internal_function(const char *name, uint8_t type) {
w(INFN);
w(name);
w(type);
}
void ILemitter::function_parameter(
const char *func, const char *name, uint8_t type) {
w(FPRM);
w(func);
w(name);
w(type);
}
void ILemitter::function_local(
const char *func, const char *name, uint8_t type) {
w(FLOC);
w(func);
w(name);
w(type);
}
void ILemitter::global(const char *name, uint8_t type) {
w(GLOB);
w(name);
w(type);
}
void ILemitter::data(const char *name, const char *data) {
w(DATA);
w(name);
w(data);
}
| 14.269444 | 67 | 0.600545 | rdrpenguin04 |
66ee8f7dd3d4f519d3c0b19f5b02ed1bda03b25a | 616 | cpp | C++ | malloc.cpp | rsds8540/cpp-solved-problems | cbd63e0743d7653d8e06401026c16aa1dd5f775b | [
"Apache-2.0"
] | 1 | 2021-04-27T18:23:05.000Z | 2021-04-27T18:23:05.000Z | malloc.cpp | rsds8540/cpp-solved-problems | cbd63e0743d7653d8e06401026c16aa1dd5f775b | [
"Apache-2.0"
] | null | null | null | malloc.cpp | rsds8540/cpp-solved-problems | cbd63e0743d7653d8e06401026c16aa1dd5f775b | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
int* ptr;
int n;
cout<<"Enter the size: ";
cin>>n;
ptr = (int*) malloc(n*sizeof(int));//syntax of malloc
// for (int i = 0; i < n; i++)
// {
// cout<<"Enter the value no. "<<i<<" of this dynamic array: ";
// // cin>>(&ptr[i]);
// scanf("%d",&ptr[i]); //why not working in cin?
// }
for (int i = 0; i < n; i++)
{
cout<<"The value no. "<<i<<" of this dynamic array is :"<<ptr[i]<<endl; // initially allocated with garbage value
}
// cout<<sizeof(int);
return 0;
} | 22.814815 | 121 | 0.483766 | rsds8540 |
66eed6d1e3535e2e46d15d0b372e704d4dff0b51 | 1,006 | hpp | C++ | include/metal/number/less.hpp | brunocodutra/MPL2 | 9db9b403e58e0be0bbd295ff64f01e700965f25d | [
"MIT"
] | 320 | 2015-09-28T19:55:56.000Z | 2022-03-09T03:00:23.000Z | include/metal/number/less.hpp | brunocodutra/MPL2 | 9db9b403e58e0be0bbd295ff64f01e700965f25d | [
"MIT"
] | 80 | 2015-09-09T16:45:55.000Z | 2021-08-08T21:06:00.000Z | include/metal/number/less.hpp | brunocodutra/MPL2 | 9db9b403e58e0be0bbd295ff64f01e700965f25d | [
"MIT"
] | 26 | 2016-02-29T16:16:37.000Z | 2020-12-14T05:49:24.000Z | #ifndef METAL_NUMBER_LESS_HPP
#define METAL_NUMBER_LESS_HPP
#include "../config.hpp"
namespace metal {
/// \cond
namespace detail {
template <class x, class y>
struct _less;
}
/// \endcond
/// \ingroup number
///
/// ### Description
/// Checks whether a \number is less than another.
///
/// ### Usage
/// For any \numbers `x` and `y`
/// \code
/// using result = metal::less<x, y>;
/// \endcode
///
/// \returns: \number
/// \semantics:
/// Equivalent to
/// \code
/// using result = metal::number<(x{} < y{})>;
/// \endcode
///
/// ### Example
/// \snippet number.cpp less
///
/// ### See Also
/// \see number, greater, max, min
template <class x, class y>
using less = typename detail::_less<x, y>::type;
}
#include "../number/number.hpp"
namespace metal {
/// \cond
namespace detail {
template <class x, class y>
struct _less {
};
template <int_ x, int_ y>
struct _less<number<x>, number<y>> : number<(x < y)> {
};
}
/// \endcond
}
#endif
| 17.344828 | 58 | 0.582505 | brunocodutra |
66efb614ed9846e819bad47581d810cca7177af3 | 1,914 | cpp | C++ | src/core/binary_reader.cpp | hermet/rive-cpp | d69378d97e7d987930c3764655153bf8ddc65966 | [
"MIT"
] | null | null | null | src/core/binary_reader.cpp | hermet/rive-cpp | d69378d97e7d987930c3764655153bf8ddc65966 | [
"MIT"
] | null | null | null | src/core/binary_reader.cpp | hermet/rive-cpp | d69378d97e7d987930c3764655153bf8ddc65966 | [
"MIT"
] | null | null | null | #include "core/binary_reader.hpp"
#include "core/reader.h"
#include <vector>
using namespace rive;
BinaryReader::BinaryReader(uint8_t* bytes, size_t length) :
m_Position(bytes),
m_End(bytes + length),
m_Overflowed(false),
m_Length(length)
{
}
bool BinaryReader::reachedEnd() const
{
return m_Position == m_End || didOverflow();
}
size_t BinaryReader::lengthInBytes() const { return m_Length; }
bool BinaryReader::didOverflow() const { return m_Overflowed; }
void BinaryReader::overflow()
{
m_Overflowed = true;
m_Position = m_End;
}
uint64_t BinaryReader::readVarUint()
{
uint64_t value;
auto readBytes = decode_uint_leb(m_Position, m_End, &value);
if (readBytes == 0)
{
overflow();
return 0;
}
m_Position += readBytes;
return value;
}
std::string BinaryReader::readString()
{
uint64_t length = readVarUint();
if (didOverflow())
{
return std::string();
}
std::vector<char> rawValue(length + 1);
auto readBytes = decode_string(length, m_Position, m_End, &rawValue[0]);
if (readBytes != length)
{
overflow();
return std::string();
}
m_Position += readBytes;
return std::string(rawValue.data(), length);
}
double BinaryReader::readFloat64()
{
double value;
auto readBytes = decode_double(m_Position, m_End, &value);
if (readBytes == 0)
{
overflow();
return 0.0;
}
m_Position += readBytes;
return value;
}
float BinaryReader::readFloat32()
{
float value;
auto readBytes = decode_float(m_Position, m_End, &value);
if (readBytes == 0)
{
overflow();
return 0.0f;
}
m_Position += readBytes;
return value;
}
uint8_t BinaryReader::readByte()
{
if (m_End - m_Position < 1)
{
overflow();
return 0;
}
return *m_Position++;
}
uint32_t BinaryReader::readUint32()
{
uint32_t value;
auto readBytes = decode_uint_32(m_Position, m_End, &value);
if (readBytes == 0)
{
overflow();
return 0;
}
m_Position += readBytes;
return value;
}
| 17.4 | 73 | 0.6907 | hermet |
66f0a1b629c786aecc7384f340daf9fd20d1b6fb | 2,492 | inl | C++ | Misc/UnusedCode/RSLibAndTests/RSLib/Code/Math/Types/Polynomial.inl | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 34 | 2017-04-19T18:26:02.000Z | 2022-02-15T17:47:26.000Z | Misc/UnusedCode/RSLibAndTests/RSLib/Code/Math/Types/Polynomial.inl | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 307 | 2017-05-04T21:45:01.000Z | 2022-02-03T00:59:01.000Z | Misc/UnusedCode/RSLibAndTests/RSLib/Code/Math/Types/Polynomial.inl | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 4 | 2017-09-05T17:04:31.000Z | 2021-12-15T21:24:28.000Z | #ifndef RS_POLYNOMIAL_INL
#define RS_POLYNOMIAL_INL
using namespace RSLib;
// construction/destruction:
template<class T>
rsPolynomial<T>::rsPolynomial(T *coeffs, int order)
{
N = order;
a = new T[N+1];
for(int n = 0; n <= N; n++)
a[n] = coeffs[n];
}
template<class T>
rsPolynomial<T>::rsPolynomial(const rsPolynomial<T>& other)
{
N = other.N;
a = new T[N+1];
for(int n = 0; n <= N; n++)
a[n] = other.a[n];
}
template<class T>
rsPolynomial<T>::~rsPolynomial()
{
delete[] a;
}
/*
// operators:
template<class T>
rsPolynomial<T> rsPolynomial<T>::operator-() const
{
if( value == 0 )
return *this;
else
return rsPolynomial<T>(modulus-value, modulus);
}
template<class T>
bool rsPolynomial<T>::operator==(const rsPolynomial<T>& other) const
{
return value == other.value && modulus == other.modulus;
}
template<class T>
bool rsPolynomial<T>::operator!=(const rsPolynomial<T>& other) const
{
return !(*this == other);
}
template<class T>
rsPolynomial<T> rsPolynomial<T>::operator+(const rsPolynomial<T> &other)
{
rsAssert( modulus == other.modulus );
T r = this->value + other.value;
if( r >= modulus )
r -= modulus;
return rsPolynomial<T>(r, modulus);
}
template<class T>
rsPolynomial<T> rsPolynomial<T>::operator-(const rsPolynomial<T> &other)
{
rsAssert( modulus == other.modulus );
T r;
if( other.value > this->value )
r = modulus + this->value - other.value;
else
r = this->value - other.value;
return rsPolynomial<T>(r, modulus);
}
template<class T>
rsPolynomial<T> rsPolynomial<T>::operator*(const rsPolynomial<T> &other)
{
rsAssert( modulus == other.modulus );
T r = (this->value * other.value) % modulus;
return rsPolynomial<T>(r, modulus);
}
template<class T>
rsPolynomial<T> rsPolynomial<T>::operator/(const rsPolynomial<T> &other)
{
rsAssert( modulus == other.modulus );
return *this * rsModularInverse(other.value, modulus);
}
template<class T>
rsPolynomial<T>& rsPolynomial<T>::operator+=(const rsPolynomial<T> &other)
{
*this = *this + other;
return *this;
}
template<class T>
rsPolynomial<T>& rsPolynomial<T>::operator-=(const rsPolynomial<T> &other)
{
*this = *this - other;
return *this;
}
template<class T>
rsPolynomial<T>& rsPolynomial<T>::operator*=(const rsPolynomial<T> &other)
{
*this = *this * other;
return *this;
}
template<class T>
rsPolynomial<T>& rsPolynomial<T>::operator/=(const rsPolynomial<T> &other)
{
*this = *this / other;
return *this;
}
*/
#endif
| 20.42623 | 74 | 0.668539 | RobinSchmidt |
66f297c502b00dc6faacbfe094c9821721caf43f | 4,992 | cpp | C++ | tests/MobileNetDatabase.cpp | Air000/armnn_s32v | ec3ee60825d6b7642a70987c4911944cef7a3ee6 | [
"MIT"
] | 1 | 2019-03-19T08:44:28.000Z | 2019-03-19T08:44:28.000Z | tests/MobileNetDatabase.cpp | Air000/armnn_s32v | ec3ee60825d6b7642a70987c4911944cef7a3ee6 | [
"MIT"
] | null | null | null | tests/MobileNetDatabase.cpp | Air000/armnn_s32v | ec3ee60825d6b7642a70987c4911944cef7a3ee6 | [
"MIT"
] | 1 | 2019-10-11T05:58:56.000Z | 2019-10-11T05:58:56.000Z | //
// Copyright © 2017 Arm Ltd. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "InferenceTestImage.hpp"
#include "MobileNetDatabase.hpp"
#include <boost/numeric/conversion/cast.hpp>
#include <boost/assert.hpp>
#include <boost/format.hpp>
#include <iostream>
#include <fcntl.h>
#include <array>
namespace
{
inline float Lerp(float a, float b, float w)
{
return w * b + (1.f - w) * a;
}
inline void PutData(std::vector<float> & data,
const unsigned int width,
const unsigned int x,
const unsigned int y,
const unsigned int c,
float value)
{
data[(3*((y*width)+x)) + c] = value;
}
std::vector<float>
ResizeBilinearAndNormalize(const InferenceTestImage & image,
const unsigned int outputWidth,
const unsigned int outputHeight)
{
std::vector<float> out;
out.resize(outputWidth * outputHeight * 3);
// We follow the definition of TensorFlow and AndroidNN: The top-left corner of a texel in the output
// image is projected into the input image to figure out the interpolants and weights. Note that this
// will yield different results than if projecting the centre of output texels.
const unsigned int inputWidth = image.GetWidth();
const unsigned int inputHeight = image.GetHeight();
// How much to scale pixel coordinates in the output image to get the corresponding pixel coordinates
// in the input image
const float scaleY = boost::numeric_cast<float>(inputHeight) / boost::numeric_cast<float>(outputHeight);
const float scaleX = boost::numeric_cast<float>(inputWidth) / boost::numeric_cast<float>(outputWidth);
uint8_t rgb_x0y0[3];
uint8_t rgb_x1y0[3];
uint8_t rgb_x0y1[3];
uint8_t rgb_x1y1[3];
for (unsigned int y = 0; y < outputHeight; ++y)
{
// Corresponding real-valued height coordinate in input image
const float iy = boost::numeric_cast<float>(y) * scaleY;
// Discrete height coordinate of top-left texel (in the 2x2 texel area used for interpolation)
const float fiy = floorf(iy);
const unsigned int y0 = boost::numeric_cast<unsigned int>(fiy);
// Interpolation weight (range [0,1])
const float yw = iy - fiy;
for (unsigned int x = 0; x < outputWidth; ++x)
{
// Real-valued and discrete width coordinates in input image
const float ix = boost::numeric_cast<float>(x) * scaleX;
const float fix = floorf(ix);
const unsigned int x0 = boost::numeric_cast<unsigned int>(fix);
// Interpolation weight (range [0,1])
const float xw = ix - fix;
// Discrete width/height coordinates of texels below and to the right of (x0, y0)
const unsigned int x1 = std::min(x0 + 1, inputWidth - 1u);
const unsigned int y1 = std::min(y0 + 1, inputHeight - 1u);
std::tie(rgb_x0y0[0], rgb_x0y0[1], rgb_x0y0[2]) = image.GetPixelAs3Channels(x0, y0);
std::tie(rgb_x1y0[0], rgb_x1y0[1], rgb_x1y0[2]) = image.GetPixelAs3Channels(x1, y0);
std::tie(rgb_x0y1[0], rgb_x0y1[1], rgb_x0y1[2]) = image.GetPixelAs3Channels(x0, y1);
std::tie(rgb_x1y1[0], rgb_x1y1[1], rgb_x1y1[2]) = image.GetPixelAs3Channels(x1, y1);
for (unsigned c=0; c<3; ++c)
{
const float ly0 = Lerp(float(rgb_x0y0[c]), float(rgb_x1y0[c]), xw);
const float ly1 = Lerp(float(rgb_x0y1[c]), float(rgb_x1y1[c]), xw);
const float l = Lerp(ly0, ly1, yw);
PutData(out, outputWidth, x, y, c, l/255.0f);
}
}
}
return out;
}
} // end of anonymous namespace
MobileNetDatabase::MobileNetDatabase(const std::string& binaryFileDirectory,
unsigned int width,
unsigned int height,
const std::vector<ImageSet>& imageSet)
: m_BinaryDirectory(binaryFileDirectory)
, m_Height(height)
, m_Width(width)
, m_ImageSet(imageSet)
{
}
std::unique_ptr<MobileNetDatabase::TTestCaseData>
MobileNetDatabase::GetTestCaseData(unsigned int testCaseId)
{
testCaseId = testCaseId % boost::numeric_cast<unsigned int>(m_ImageSet.size());
const ImageSet& imageSet = m_ImageSet[testCaseId];
const std::string fullPath = m_BinaryDirectory + imageSet.first;
InferenceTestImage image(fullPath.c_str());
// this ResizeBilinear result is closer to the tensorflow one than STB.
// there is still some difference though, but the inference results are
// similar to tensorflow for MobileNet
std::vector<float> resized(ResizeBilinearAndNormalize(image, m_Width, m_Height));
const unsigned int label = imageSet.second;
return std::make_unique<TTestCaseData>(label, std::move(resized));
}
| 37.253731 | 108 | 0.636018 | Air000 |
66f38e2a9da92b3deea2630f2b1a182d24c482fb | 1,501 | cpp | C++ | src/GraphicsInstance.cpp | LuisHsu/Assignment_4 | 1735738d3d523d9c3a007d9fb471f121071e75fe | [
"BSD-3-Clause"
] | null | null | null | src/GraphicsInstance.cpp | LuisHsu/Assignment_4 | 1735738d3d523d9c3a007d9fb471f121071e75fe | [
"BSD-3-Clause"
] | null | null | null | src/GraphicsInstance.cpp | LuisHsu/Assignment_4 | 1735738d3d523d9c3a007d9fb471f121071e75fe | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright 2020 Luis Hsu. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
#include <GraphicsInstance.hpp>
#include <iostream>
#include <stdexcept>
#include <vector>
GraphicsInstance::GraphicsInstance(){
// Create instance
VkApplicationInfo appInfo = {
.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
.pApplicationName = "Assignment 4",
.applicationVersion = VK_MAKE_VERSION(1, 0, 0),
.pEngineName = "No Engine",
.engineVersion = VK_MAKE_VERSION(1, 0, 0),
.apiVersion = VK_API_VERSION_1_0,
};
std::vector<const char*> extensionNames({
"VK_KHR_surface",
"VK_KHR_xcb_surface"
});
std::vector<const char*> validationLayers({
"VK_LAYER_KHRONOS_validation"
});
VkInstanceCreateInfo instanceCreateInfo = {
.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
.pApplicationInfo = &appInfo,
.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()),
.ppEnabledLayerNames = validationLayers.data(),
.enabledExtensionCount = static_cast<uint32_t>(extensionNames.size()),
.ppEnabledExtensionNames = extensionNames.data(),
};
if(vkCreateInstance(&instanceCreateInfo, nullptr, &instance) != VK_SUCCESS){
throw std::runtime_error("Cannot create Vulkan instance");
}
}
GraphicsInstance::~GraphicsInstance(){
vkDestroyInstance(instance, nullptr);
} | 33.355556 | 80 | 0.685543 | LuisHsu |
66f8f3213d7ef68a96ba325935b779269ba119d4 | 122 | cc | C++ | src/game/Utils/Text.cc | FluffyQuack/ja2-stracciatella | 59781890986dc5360ed4b148b83836c029121d5f | [
"BSD-Source-Code"
] | 346 | 2016-02-16T11:17:25.000Z | 2022-03-28T18:18:14.000Z | src/game/Utils/Text.cc | FluffyQuack/ja2-stracciatella | 59781890986dc5360ed4b148b83836c029121d5f | [
"BSD-Source-Code"
] | 1,119 | 2016-02-14T23:19:56.000Z | 2022-03-31T21:57:58.000Z | src/game/Utils/Text.cc | FluffyQuack/ja2-stracciatella | 59781890986dc5360ed4b148b83836c029121d5f | [
"BSD-Source-Code"
] | 90 | 2016-02-17T22:17:11.000Z | 2022-03-12T11:59:56.000Z | #include "Text.h"
#include <string_theory/string>
ST::string ItemNames[MAXITEMS];
ST::string ShortItemNames[MAXITEMS];
| 15.25 | 36 | 0.762295 | FluffyQuack |
66f9a3a8b94e46f562cc37170cf59e1ba5393349 | 7,077 | cpp | C++ | ql/math/matrix.cpp | haozhangphd/QuantLib-noBoost | ddded069868161099843c04840454f00816113ad | [
"BSD-3-Clause"
] | 76 | 2017-06-28T21:24:38.000Z | 2021-12-19T18:07:37.000Z | ql/math/matrix.cpp | haozhangphd/QuantLib-noBoost | ddded069868161099843c04840454f00816113ad | [
"BSD-3-Clause"
] | 2 | 2017-07-05T09:20:13.000Z | 2019-10-31T12:06:51.000Z | ql/math/matrix.cpp | haozhangphd/QuantLib-noBoost | ddded069868161099843c04840454f00816113ad | [
"BSD-3-Clause"
] | 34 | 2017-07-02T14:49:21.000Z | 2021-11-26T15:32:04.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2017 Hao Zhang
Copyright (C) 2007, 2008 Klaus Spanderen
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file matrix.hpp
\brief matrix used in linear algebra.
*/
#include <ql/math/matrix.hpp>
#ifdef QL_USE_MKL
#include <mkl.h>
#endif
#ifndef QL_USE_MKL
namespace {
using QuantLib::Matrix;
using QuantLib::Real;
// inspired by Numerical Recipes 3rd edition by Press et al.
std::tuple<Matrix, std::vector<int>, Real> luDecomposition(const Matrix &m) {
Matrix ret(m);
int size = ret.row_size();
std::vector<Real> vv(size, 1);
std::vector<int> index(size);
Real perm = 1;
for (int i = 0; i < size; ++i) {
Real largest_element = *std::max_element(ret.row_begin(i), ret.row_end(i),
[](Real x, Real y) { return std::abs(x) < std::abs(y); });
if (largest_element == 0.0)
return std::make_tuple(Matrix(size, size), std::vector<int>(size), 0);
vv[i] /= largest_element;
}
for (int k = 0; k < size; ++k) {
std::vector<Real> temp(size-k);
std::transform(vv.begin()+k, vv.end(), ret.column_begin(k)+k,temp.begin(),[](Real x, Real y){return x * std::abs(y);});
int largest_element_index = std::distance(temp.begin(), std::max_element(temp.begin(), temp.end())) + k;
if (largest_element_index != k) {
std::swap_ranges(ret.row_begin(largest_element_index), ret.row_end(largest_element_index), ret.row_begin(k));
perm = -perm;
vv[largest_element_index] = vv[k];
}
index[k] = largest_element_index;
temp.pop_back();
std::for_each(ret.column_begin(k) + k + 1, ret.column_end(k), [&ret, &k](Real& x){x/=ret.diagonal()[k];});
std::copy(ret.column_begin(k)+k + 1, ret.column_end(k), temp.begin());
for (int i = k + 1; i < size; i++) {
for (int j = k + 1; j < size; j++)
ret[i][j] -= temp[i-k-1] * ret[k][j];
}
}
return std::make_tuple(ret, index, perm);
}
}
#endif
namespace QuantLib {
Matrix inverse(const Matrix &m) {
const size_t size = m.rows();
QL_REQUIRE(size == m.columns(), "matrix is not square");
#ifdef QL_USE_MKL
std::vector<Real> lu(size * size);
std::copy(m.begin(), m.end(), lu.begin());
std::vector<int> ipiv(size);
int info;
info = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, size, size, lu.data(), size, ipiv.data());
QL_REQUIRE(info == 0, "Failed to obtain LU decomposition of the matrix.");
LAPACKE_dgetri(LAPACK_ROW_MAJOR, size, lu.data(), size, ipiv.data());
QL_REQUIRE(info == 0, "Could not invert the matrix.");
Matrix retVal(size, size);
std::copy(lu.begin(), lu.end(), retVal.begin());
return retVal;
#else
//There is a bug in GCC7's handling of structured binding
//https://infektor.net/posts/2017-02-17-maybe-bindings-are-unused.html
//fixed in GCC8
#if defined(__GNUG__) && (__GNUG__ == 7)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif
//TODO-HAO: remove this check once Visual Studio 2017.3 is released
//because structured binding is supported in Visual Studio 2017.3
#ifndef _MSC_VER
auto [lu, index, _] = luDecomposition(m);
#else
Matrix lu;
std::vector<int> index;
std::tie(lu, index, std::ignore) = luDecomposition(m);
#endif
Matrix ret(size, size);
for (size_t k = 0; k < size; ++k) {
std::vector<Real> ret_column(size, 0);
ret_column[k] = 1;
int ii=0;
Real sum;
for (size_t i = 0; i < size; ++i) {
sum = ret_column[index[i]];
ret_column[index[i]] = ret_column[i];
if (ii != 0)
for (size_t j = ii - 1; j < i; ++j)
sum -= lu[i][j] * ret_column[j];
else if (sum != 0.0)
ii = i + 1;
ret_column[i] = sum;
}
for (size_t i = size; i > 0; --i) {
sum = ret_column[i-1];
for (size_t j = i; j < size; j++)
sum -= lu[i - 1][j] * ret_column[j];
ret_column[i - 1] = sum / lu[i - 1][i - 1];
}
std::copy(ret_column.begin(), ret_column.end(), ret.column_begin(k));
}
return ret;
#if defined(__GNUG__) && (__GNUG__ == 7)
#pragma GCC diagnostic pop
#endif
#endif
}
Real determinant(const Matrix &m) {
#ifdef QL_USE_MKL
const int size = m.rows();
QL_REQUIRE(size == static_cast<int>(m.columns()), "matrix is not square");
std::vector<Real> lu(size * size);
std::copy(m.begin(), m.end(), lu.begin());
std::vector<int> ipiv(size);
int info;
info = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, size, size, lu.data(), size, ipiv.data());
if (info < 0)
QL_FAIL("Failed to obtain LU decomposition of the matrix.");
else if (info > 0)
return 0;
Real retVal = 1.0;
for (int i = 0; i < size; ++i) {
if (ipiv[i] != i + 1)
retVal *= -lu[i * (size + 1)];
else
retVal *= lu[i * (size + 1)];
}
return retVal;
#else
const size_t size = m.rows();
QL_REQUIRE(size == m.columns(), "matrix is not square");
//There is a bug in GCC7's handling of structured binding
//https://infektor.net/posts/2017-02-17-maybe-bindings-are-unused.html
//fixed in GCC8
#if defined(__GNUG__) && (__GNUG__ == 7)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif
//TODO-HAO: remove this check once Visual Studio 2017.3 is released
//because structured binding is supported in Visual Studio 2017.3
#ifndef _MSC_VER
auto [lu, _, ret] = luDecomposition(m);
#else
Matrix lu;
Real ret;
std::tie(lu, std::ignore, ret) = luDecomposition(m);
#endif
Array diag = lu.diagonal();
return std::accumulate(diag.begin(), diag.end(), ret, std::multiplies<Real>());
#if defined(__GNUG__) && (__GNUG__ == 7)
#pragma GCC diagnostic pop
#endif
#endif
}
}
| 34.691176 | 131 | 0.57157 | haozhangphd |
0f084c3f8b0fb7b5eecdbb81413c12e677fcf17e | 551 | hpp | C++ | libcaf_io/caf/io/connection_helper.hpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | 2,517 | 2015-01-04T22:19:43.000Z | 2022-03-31T12:20:48.000Z | libcaf_io/caf/io/connection_helper.hpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | 894 | 2015-01-07T14:21:21.000Z | 2022-03-30T06:37:18.000Z | libcaf_io/caf/io/connection_helper.hpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"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.
#pragma once
#include "caf/detail/io_export.hpp"
#include "caf/fwd.hpp"
namespace caf::io {
struct connection_helper_state {
static inline const char* name = "caf.system.connection-helper";
};
CAF_IO_EXPORT behavior
connection_helper(stateful_actor<connection_helper_state>* self, actor b);
} // namespace caf::io
| 27.55 | 77 | 0.767695 | seewpx |
0f0b93b7d2e0d6d94de1ad4a464e7691c84d46f4 | 5,799 | cpp | C++ | FragExt.Lib/SpinLock.cpp | jeremy-boschen/FragExt | c340eecf7cd5992001db1b4a404bcaec09523ba4 | [
"Zlib"
] | null | null | null | FragExt.Lib/SpinLock.cpp | jeremy-boschen/FragExt | c340eecf7cd5992001db1b4a404bcaec09523ba4 | [
"Zlib"
] | null | null | null | FragExt.Lib/SpinLock.cpp | jeremy-boschen/FragExt | c340eecf7cd5992001db1b4a404bcaec09523ba4 | [
"Zlib"
] | 2 | 2020-03-03T12:55:17.000Z | 2022-03-07T15:37:33.000Z | /* FragExt - Shell extension for providing file fragmentation
* information.
*
* Copyright (C) 2004-2009 Jeremy Boschen. All rights reserved.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in
* a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
/* SpinLock.cpp
* Spin lock implementation
*
* Copyright (C) 2004-2009 Jeremy Boschen
*/
#include "Stdafx.h"
#include "SpinLock.h"
/*++
Private Declarations
--*/
DWORD_PTR
GetProcessProcessorCount(
);
BOOLEAN
TryAcquireSpinLock(
__deref_inout volatile SPINLOCK* SLock,
__in DWORD dwThreadID
);
void
SpinWait(
__in USHORT SpinCount
);
/*++
Private Data
--*/
const BOOLEAN gIsSingleProcessorProcess = (GetProcessProcessorCount() > 0 ? FALSE : TRUE);
/*++
Implementation
--*/
void
APIENTRY
AcquireSpinLock(
__deref_inout volatile SPINLOCK* SLock
)
{
DWORD dwThreadID;
USHORT SpinCount;
USHORT CurrentSpin;
int BackoffThreshold;
dwThreadID = GetCurrentThreadId();
/*
* Cache the spin count as we don't support it changing
* while we're spinning
*/
SpinCount = SLock->SpinCount;
CurrentSpin = 0;
BackoffThreshold = 10;
for ( ;; )
{
/*
* Try to acquire the lock
*/
if ( TryAcquireSpinLock(SLock,
dwThreadID) )
{
/*
* We acquired the lock, so bail
*/
return;
}
if ( gIsSingleProcessorProcess )
{
/*
* There is only 1 processor assigned to this process, so there's
* no point doing a spin wait
*/
Sleep(1);
}
else
{
YieldProcessor();
if ( ++CurrentSpin < SpinCount )
{
if ( BackoffThreshold > 0 )
{
--BackoffThreshold;
Sleep(0);
}
else
{
Sleep(1);
}
CurrentSpin = 0;
}
}
}
}
void
APIENTRY
ReleaseSpinLock(
__deref_inout volatile SPINLOCK* SLock
)
{
#ifdef _DEBUG
if ( SLock->ThreadID != GetCurrentThreadId() )
{
/*
* Some thread other than the one that originally acquired the spinlock
* is attempting to release it
*/
DebugBreak();
}
#endif /* DBG */
SLock->Depth -= 1;
/*
* Force the write to complete before anything else occurs and prevent
* the CPU from reordering anything
*/
_ForceMemoryWriteCompletion();
if ( 0 == SLock->Depth )
{
_ForceMemoryReadCompletion();
/*
* The owning thread has released the lock as many times as it
* acquired it, so give it up to another thread now
*/
SLock->ThreadID = 0;
}
}
BOOLEAN
TryAcquireSpinLock(
__deref_inout volatile SPINLOCK* SLock,
__in DWORD dwThreadID
)
{
volatile DWORD dwOwnerID;
/*
* We acquire the lock by assigning the thread ID to the lock. The same thread can
* acquire the lock multiple times
*/
dwOwnerID = static_cast<DWORD>(InterlockedCompareExchange(reinterpret_cast<volatile LONG*>(&(SLock->ThreadID)),
static_cast<LONG>(dwThreadID),
0));
/*
* We acquired the lock if it was previously zero, or if the current value is the
* same thread ID, which indicates recursive acquisition
*/
if ( (0 != dwOwnerID) && (dwOwnerID != dwThreadID) )
{
/*
* Another thread beat this one to acquire the lock
*/
return ( FALSE );
}
/*
* Prevent the CPU from reordering the update to Depth below. The compiler won't because Depth
* is declared volatile
*/
_ForceMemoryReadCompletion();
/*
* The thread either already owns the lock or it has acquired it. We don't need to
* do this with an interlock because only the owning thread ever reaches this point
*/
SLock->Depth += 1;
/*
* If this fires then Depth has overflowed because the thread has acquired this lock
* recursively, too many times
*/
_ASSERTE(SLock->Depth > 0);
/* Success */
return ( TRUE );
}
DWORD_PTR
GetProcessProcessorCount(
)
{
SYSTEM_INFO SysInfo;
DWORD_PTR cProcessProcessorCount;
DWORD_PTR ProcessAffinity;
DWORD_PTR SystemAffinity;
if ( GetProcessAffinityMask(GetCurrentProcess(),
&ProcessAffinity,
&SystemAffinity) )
{
cProcessProcessorCount = 0;
/*
* Count the number of bits set in the process affinity
*/
while ( ProcessAffinity )
{
cProcessProcessorCount += (ProcessAffinity & static_cast<DWORD_PTR>(1U));
ProcessAffinity >>= 1;
}
}
else
{
GetSystemInfo(&SysInfo);
cProcessProcessorCount = static_cast<DWORD_PTR>(SysInfo.dwNumberOfProcessors);
}
return ( cProcessProcessorCount );
}
| 23.196 | 114 | 0.60407 | jeremy-boschen |
0f0ce9451345fc882729fe2630d581d3433607e5 | 4,271 | cpp | C++ | server.cpp | NewtonVan/SuperDuperDnsServer | 0c52094d85b6a7c380e3667dd89b4b6ba999d8b1 | [
"MIT"
] | 1 | 2020-07-03T07:29:25.000Z | 2020-07-03T07:29:25.000Z | server.cpp | NewtonVan/SuperDuperDnsServer | 0c52094d85b6a7c380e3667dd89b4b6ba999d8b1 | [
"MIT"
] | null | null | null | server.cpp | NewtonVan/SuperDuperDnsServer | 0c52094d85b6a7c380e3667dd89b4b6ba999d8b1 | [
"MIT"
] | null | null | null | //
// Created by Newton on 2020/6/6.
//
#include "SuperDuperLib.h"
#include "server.h"
using namespace dns;
Server::Server()
{
#ifdef _WIN32
m_resolver.init(".\\server.cache");
m_resolver.configure(".\\upperproxy.confg");
#else
m_resolver.init("./server.cache");
m_resolver.configure("./upperproxy.confg");
#endif
}
/*
* init the server
* create socket used for dns proxy server
* set it to listening mode
*/
void Server::init(int &port)
{
int status;
struct addrinfo hints;
struct addrinfo *servInfo;
char str_port[1<<5];
unsigned value= 1;
sprintf(str_port, "%d", port);
memset(&hints, 0, sizeof(hints));
hints.ai_family= AF_INET;
hints.ai_socktype= SOCK_DGRAM;
hints.ai_flags= AI_PASSIVE;
if (0!= (status= getaddrinfo(NULL, str_port, &hints, &servInfo))){
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
if (-1== (m_socketfd= socket(servInfo->ai_family, servInfo->ai_socktype, servInfo->ai_protocol))){
printf("create socket error: %s(errno: %d)\n",strerror(errno),errno);
exit(1);
}
#ifdef _WIN32
setsockopt(m_socketfd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char *>(&value), sizeof(value));
#else
setsockopt(m_socketfd, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(value));
#endif
if (bind(m_socketfd, servInfo->ai_addr, servInfo->ai_addrlen)){
printf("bind socket error: %s(errno: %d)\n",strerror(errno),errno);
exit(1);
}
if (port == 0) {
socklen_t namelen = servInfo->ai_addrlen;
if (getsockname(m_socketfd, servInfo->ai_addr, &namelen) == -1) {
printf("getsockname error: %s(errno: %d)\n",strerror(errno),errno);
return;
}
struct sockaddr_in *servAddr= (struct sockaddr_in*)(servInfo->ai_addr);
port = ntohs(servAddr->sin_port);
}
std::cout<<"server running on port:"<<port<<std::endl;
}
/*
* wait for the query datagram
* process the datagram
* solve the datagram
*/
void Server::run(const std::string logNm)
{
char rbuf[MAX_UDP_LTH], sbuf[MAX_UDP_LTH];
struct sockaddr clientAddr;
char p_clientAddr[INET6_ADDRSTRLEN];
socklen_t len= sizeof(struct sockaddr_in);
m_resolver.getLog(logNm);
while (true){
int lth= (int)recvfrom(m_socketfd, rbuf, sizeof(rbuf), 0, (struct sockaddr*)&clientAddr, &len);
if (lth <= 0){
continue;
}
logFile.open(logNm.c_str(), std::ios::app);
std::cout<<"******************************************"<<std::endl;
logFile<<"******************************************"<<std::endl;
if (AF_INET== clientAddr.sa_family){
struct sockaddr_in *v4CltAddr= (struct sockaddr_in*)&clientAddr;
inet_ntop(AF_INET, &(v4CltAddr->sin_addr), p_clientAddr, INET_ADDRSTRLEN);
std::cout<<"Received from: "<<p_clientAddr<<std::endl;
logFile<<"Received form: "<<p_clientAddr<<std::endl;
}
else{
struct sockaddr_in6 *v6CltAddr= (struct sockaddr_in6*)&clientAddr;
inet_ntop(AF_INET6, &(v6CltAddr->sin6_addr), p_clientAddr, INET6_ADDRSTRLEN);
std::cout<<"Received from: "<<p_clientAddr<<std::endl;
logFile<<"Received form: "<<p_clientAddr<<std::endl;
}
m_query.decode(rbuf, lth);
logData= m_query.to_string();
std::cout<<logData;
logFile<<logData;
logFile.close();
if(m_resolver.process(m_query, m_response, rbuf, lth, sbuf)){ // cache hit
memset(sbuf, 0, sizeof(sbuf));
lth= m_response.encode(sbuf);
logData= m_response.to_string();
logFile.open(logNm.c_str(), std::ios::app);
std::cout<<logData;
logFile<<logData;
std::cout<<"Cache was hit"<<std::endl;
std::cout<<"******************************************\n\n"<<std::endl;
logFile<<"Cache was hit"<<std::endl;
logFile<<"******************************************\n\n"<<std::endl;
logFile.close();
}
sendto(m_socketfd, sbuf, lth, 0, (struct sockaddr*)&clientAddr, len);
std::cout<<std::endl;
}
} | 29.455172 | 108 | 0.579958 | NewtonVan |
0f0e12858f753e8e7f78cd8acbf11efe56757a71 | 7,491 | cpp | C++ | implementation/cpl_guicommon/cpl_frameobject/cpl_dynamicloader.cpp | cayprogram/cpl_main | 9cc8f4c8cf33465506bdb18ddc84340992b16494 | [
"MIT"
] | null | null | null | implementation/cpl_guicommon/cpl_frameobject/cpl_dynamicloader.cpp | cayprogram/cpl_main | 9cc8f4c8cf33465506bdb18ddc84340992b16494 | [
"MIT"
] | null | null | null | implementation/cpl_guicommon/cpl_frameobject/cpl_dynamicloader.cpp | cayprogram/cpl_main | 9cc8f4c8cf33465506bdb18ddc84340992b16494 | [
"MIT"
] | null | null | null | #include "cpl_frameobjectincludes.h"
//-----------------------------------------------------------------------------
// class cpl_DynamicLoader
//-----------------------------------------------------------------------------
//
cpl_DynamicLoader* cpl_DynamicLoader::New() {
return new cpl_DynamicLoader;
}
//-----------------------------------------------------------------------------
// 1. Implementation for HPUX machines
#ifdef __hpux
#define VTKDYNAMICLOADER_DEFINED 1
#include <dl.h>
//-----------------------------------------------------------------------------
cpl_LibHandle cpl_DynamicLoader::OpenLibrary(const char* libname ) {
return shl_load(libname, BIND_DEFERRED | DYNAMIC_PATH, 0L);
}
//-----------------------------------------------------------------------------
int cpl_DynamicLoader::CloseLibrary(cpl_LibHandle lib) {
return 0;
}
//-----------------------------------------------------------------------------
void* cpl_DynamicLoader::GetSymbolAddress(cpl_LibHandle lib, const char* sym) {
void* addr;
int status;
status = shl_findsym (&lib, sym, TYPE_PROCEDURE, &addr);
return (status < 0) ? (void*)0 : addr;
}
//-----------------------------------------------------------------------------
const char* cpl_DynamicLoader::LibPrefix() {
return "lib";
}
//-----------------------------------------------------------------------------
const char* cpl_DynamicLoader::LibExtension() {
return ".sl";
}
//-----------------------------------------------------------------------------
const char* cpl_DynamicLoader::LastError() {
return 0;
}
#endif
// ---------------------------------------------------------------
// 2. Implementation for Darwin (including OSX) Machines
#ifdef __APPLE__
#define VTKDYNAMICLOADER_DEFINED
// Visual Age Compiler for Mac OSX does not understand this extension.
#if defined(__IBMCPP__) && !defined(__private_extern__)
# define __private_extern__
#endif
#include <mach-o/dyld.h>
//-----------------------------------------------------------------------------
cpl_LibHandle cpl_DynamicLoader::OpenLibrary(const char* libname ) {
NSObjectFileImageReturnCode rc;
NSObjectFileImage image;
rc = NSCreateObjectFileImageFromFile(libname, &image);
return NSLinkModule(image, libname, TRUE);
}
//-----------------------------------------------------------------------------
int cpl_DynamicLoader::CloseLibrary(cpl_LibHandle) {
return 0;
}
//-----------------------------------------------------------------------------
void* cpl_DynamicLoader::GetSymbolAddress(cpl_LibHandle, const char* sym) {
void *result = 0;
// global 'C' symbols names are preceded with an underscore '_'
char *_sym = new char[ strlen(sym) + 2 ];
strcpy( _sym + 1, sym );
_sym[0] = '_';
if (NSIsSymbolNameDefined(_sym)) {
NSSymbol symbol = NSLookupAndBindSymbol(_sym);
if (symbol) {
result = NSAddressOfSymbol(symbol);
}
}
else {
}
delete[] _sym;
return result;
}
//-----------------------------------------------------------------------------
const char* cpl_DynamicLoader::LibPrefix() {
return "lib";
}
//-----------------------------------------------------------------------------
const char* cpl_DynamicLoader::LibExtension() {
return ".so";
}
//-----------------------------------------------------------------------------
const char* cpl_DynamicLoader::LastError() {
return 0;
}
#endif
// ---------------------------------------------------------------
// 3. Implementation for Windows win32 code
#ifdef _WIN32
# include "windows.h"
#define VTKDYNAMICLOADER_DEFINED 1
//-----------------------------------------------------------------------------
cpl_LibHandle cpl_DynamicLoader::OpenLibrary(const char* libname ) {
#ifdef UNICODE
wchar_t *libn = new wchar_t [mbstowcs(NULL, libname, 32000)+1];
mbstowcs(libn, libname, 32000);
cpl_LibHandle ret = LoadLibrary(libn);
delete [] libn;
return ret;
#else
return LoadLibrary(libname);
#endif
}
//-----------------------------------------------------------------------------
int cpl_DynamicLoader::CloseLibrary(cpl_LibHandle lib) {
return (int)FreeLibrary(static_cast<HMODULE>(lib));
}
//-----------------------------------------------------------------------------
void* cpl_DynamicLoader::GetSymbolAddress(cpl_LibHandle lib, const char* sym) {
#if defined (UNICODE) && !defined(_MSC_VER)
wchar_t *wsym = new wchar_t [mbstowcs(NULL, sym, 32000)+1];
mbstowcs(wsym, sym, 32000);
// Force GetProcAddress to return void* with a c style cast
// This is because you can not cast a function to a void* without
// an error on gcc 3.2 and ANSI C++,
void *ret = (void*)GetProcAddress(lib, wsym);
delete [] wsym;
return ret;
#else
return (void*)GetProcAddress(static_cast<HMODULE>(lib), sym);
#endif
}
//-----------------------------------------------------------------------------
const char* cpl_DynamicLoader::LibPrefix() {
return "";
}
//-----------------------------------------------------------------------------
const char* cpl_DynamicLoader::LibExtension() {
return ".dll";
}
//-----------------------------------------------------------------------------
const char* cpl_DynamicLoader::LastError() {
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
// Free the buffer.
static char* str = 0;
delete [] str;
if (lpMsgBuf) {
str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);
LocalFree( lpMsgBuf );
}
return str;
}
#endif
// ---------------------------------------------------------------
// 4. Implementation for default UNIX machines.
// if nothing has been defined then use this
#ifndef VTKDYNAMICLOADER_DEFINED
#define VTKDYNAMICLOADER_DEFINED
// Setup for most unix machines
#include <dlfcn.h>
//-----------------------------------------------------------------------------
cpl_LibHandle cpl_DynamicLoader::OpenLibrary(const char* libname ) {
return dlopen(libname, RTLD_LAZY);
}
//-----------------------------------------------------------------------------
int cpl_DynamicLoader::CloseLibrary(cpl_LibHandle lib) {
// dlclose returns 0 on success, and non-cpl_ on error.
return !((int)dlclose(lib));
}
//-----------------------------------------------------------------------------
void* cpl_DynamicLoader::GetSymbolAddress(cpl_LibHandle lib, const char* sym) {
return dlsym(lib, sym);
}
//-----------------------------------------------------------------------------
const char* cpl_DynamicLoader::LibPrefix() {
return "lib";
}
//-----------------------------------------------------------------------------
const char* cpl_DynamicLoader::LibExtension() {
return ".so";
}
//-----------------------------------------------------------------------------
const char* cpl_DynamicLoader::LastError() {
return dlerror();
}
#endif
//-----------------------------------------------------------------------------
cpl_DynamicLoader::cpl_DynamicLoader() {
}
//-----------------------------------------------------------------------------
cpl_DynamicLoader::~cpl_DynamicLoader() {
}
| 31.343096 | 80 | 0.453878 | cayprogram |
0f0e3919b000882168093bcbdb3155247df62e2d | 9,835 | cpp | C++ | src/server/scripts/Kalimdor/HallsOfOrigination/boss_isiset.cpp | Arkania/ArkCORE | 2484554a7b54be0b652f9dc3c5a8beba79df9fbf | [
"OpenSSL"
] | 42 | 2015-01-05T10:00:07.000Z | 2022-02-18T14:51:33.000Z | src/server/scripts/Kalimdor/HallsOfOrigination/boss_isiset.cpp | superllout/WOW | 3d0eeb940cccf8ab7854259172c6d75a85ee4f7d | [
"OpenSSL"
] | null | null | null | src/server/scripts/Kalimdor/HallsOfOrigination/boss_isiset.cpp | superllout/WOW | 3d0eeb940cccf8ab7854259172c6d75a85ee4f7d | [
"OpenSSL"
] | 31 | 2015-01-09T02:04:29.000Z | 2021-09-01T13:20:20.000Z | /*
* Copyright (C) 2011 True Blood <http://www.trueblood-servers.com/>
* By Asardial
*
* Copyright (C) 2011 - 2013 ArkCORE <http://www.arkania.net/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ScriptPCH.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellScript.h"
#include "SpellAuraEffects.h"
class OrientationCheck : public std::unary_function<Unit*, bool>
{
public:
explicit OrientationCheck(Unit* _caster) : caster(_caster) { }
bool operator() (Unit* unit)
{
return !unit->isInFront(caster, 40.0f, 2.5f);
}
private:
Unit* caster;
};
enum Texts
{
SAY_AGGRO = 0,
SAY_SUPERNOVA = 1,
SAY_KILL_1 = 2,
SAY_KILL_2 = 2,
SAY_DEATH_1 = 3,
SAY_DEATH_2 = 3,
};
enum Spells
{
SPELL_SUPERNOVA = 74136,
SPELL_ASTRAL_RAIN = 74370,
SPELL_CELESTIAL_CALL_P1 = 74362,
SPELL_CELESTIAL_CALL_P2 = 74355,
SPELL_CELESTIAL_CALL_P3 = 74364,
SPELL_VEIL_OF_SKY_P1 = 74133,
SPELL_VEIL_OF_SKY_P2 = 74372,
SPELL_VEIL_OF_SKY_P3 = 74373,
};
class boss_isiset : public CreatureScript
{
public:
boss_isiset() : CreatureScript("boss_isiset") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_isisetAI(pCreature);
}
struct boss_isisetAI : public ScriptedAI
{
boss_isisetAI(Creature* pCreature) : ScriptedAI(pCreature)
{
pInstance = pCreature->GetInstanceScript();
SetCombatMovement(true);
}
std::list<uint64> SummonList;
InstanceScript *pInstance;
uint32 SupernovaTimer;
uint32 AstralRainTimer;
uint32 CelestialCallPhase3Timer;
uint32 CelestialCallPhase2Timer;
uint32 CelestialCallPhase1Timer;
uint32 VeilOfSkyPhase3Timer;
uint32 VeilOfSkyPhase2Timer;
uint32 VeilOfSkyPhase1Timer;
uint32 Phase;
bool Phased;
bool AstralRain, VeilOfSky, CelestialCall;
void EnterCombat(Unit *who)
{
Talk(SAY_AGGRO);
}
void KilledUnit(Unit* victim)
{
Talk(RAND(SAY_KILL_1, SAY_KILL_2));
}
void JustDied(Unit* Killer)
{
Talk(RAND(SAY_DEATH_1, SAY_DEATH_2));
}
void Reset()
{
RemoveSummons();
SupernovaTimer = 15000+rand()%5000;
AstralRainTimer = 10000;
CelestialCallPhase3Timer = 25000;
CelestialCallPhase2Timer = 25000;
CelestialCallPhase1Timer = 25000;
VeilOfSkyPhase3Timer = 20000;
VeilOfSkyPhase2Timer = 20000;
VeilOfSkyPhase1Timer = 20000;
Phased = false;
AstralRain = true;
VeilOfSky = true;
CelestialCall = true;
Phase = 0;
}
void SummonedCreatureDespawn(Creature* summon)
{
switch(summon->GetEntry())
{
case 39720: // Astral Rain
AstralRain = false;
break;
case 39721: // Celestial Call
CelestialCall = false;
break;
case 39722: // Veil of Sky
VeilOfSky = false;
break;
}
RemoveSummons();
}
void RemoveSummons()
{
if (SummonList.empty())
return;
for (std::list<uint64>::const_iterator itr = SummonList.begin(); itr != SummonList.end(); ++itr)
{
if (Creature* pTemp = Unit::GetCreature(*me, *itr))
if (pTemp)
pTemp->DisappearAndDie();
}
SummonList.clear();
}
void JustSummoned(Creature* pSummon)
{
SummonList.push_back(pSummon->GetGUID());
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (!HealthAbovePct(66) && Phase == 0)
{
Phase = 1;
Phased = true;
Position pos;
me->GetPosition(&pos);
me->SummonCreature(39720, pos, TEMPSUMMON_CORPSE_DESPAWN, 1000);
me->SummonCreature(39721, pos, TEMPSUMMON_CORPSE_DESPAWN, 1000);
me->SummonCreature(39722, pos, TEMPSUMMON_CORPSE_DESPAWN, 1000);
}
if (!HealthAbovePct(33) && Phase == 1)
{
Phase = 2;
Phased = true;
Position pos;
me->GetPosition(&pos);
if (AstralRain == true)
me->SummonCreature(39720, pos, TEMPSUMMON_CORPSE_DESPAWN, 1000);
if (CelestialCall == true)
me->SummonCreature(39721, pos, TEMPSUMMON_CORPSE_DESPAWN, 1000);
if (VeilOfSky == true)
me->SummonCreature(39722, pos, TEMPSUMMON_CORPSE_DESPAWN, 1000);
}
if (Phase == 0)
{
if (CelestialCallPhase1Timer <= diff && Phased == false && CelestialCall == true)
{
DoCast(me, SPELL_CELESTIAL_CALL_P1);
CelestialCallPhase1Timer = 45000;
} else CelestialCallPhase1Timer -= diff;
if (VeilOfSkyPhase1Timer <= diff && Phased == false && VeilOfSky == true)
{
DoCast(me, SPELL_VEIL_OF_SKY_P1);
VeilOfSkyPhase1Timer = 45000;
} else VeilOfSkyPhase1Timer -= diff;
}
if (Phase == 1)
{
if (CelestialCallPhase2Timer <= diff && Phased == false && CelestialCall == true)
{
DoCast(me, SPELL_CELESTIAL_CALL_P2);
CelestialCallPhase2Timer = 45000;
} else CelestialCallPhase2Timer -= diff;
if (VeilOfSkyPhase2Timer <= diff && Phased == false && VeilOfSky == true)
{
DoCast(me, SPELL_VEIL_OF_SKY_P2);
VeilOfSkyPhase2Timer = 45000;
} else VeilOfSkyPhase2Timer -= diff;
}
if (Phase == 2)
{
if (CelestialCallPhase3Timer <= diff && Phased == false && CelestialCall == true)
{
DoCast(me, SPELL_CELESTIAL_CALL_P3);
CelestialCallPhase3Timer = 45000;
} else CelestialCallPhase3Timer -= diff;
if (VeilOfSkyPhase3Timer <= diff && Phased == false && VeilOfSky == true)
{
DoCast(me, SPELL_VEIL_OF_SKY_P3);
VeilOfSkyPhase3Timer = 45000;
} else VeilOfSkyPhase3Timer -= diff;
}
if (SupernovaTimer <= diff && Phased == false)
{
Talk(SAY_SUPERNOVA);
DoCast(me->getVictim(), SPELL_SUPERNOVA);
SupernovaTimer = 15000+rand()%5000;
} else SupernovaTimer -= diff;
if (AstralRainTimer <= diff && Phased == false && CelestialCall == true)
{
DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0, 0, true), SPELL_ASTRAL_RAIN);
AstralRainTimer = 10000;
} else AstralRainTimer -= diff;
DoMeleeAttackIfReady();
}
};
};
class spell_isiset_supernova : public SpellScriptLoader
{
public:
spell_isiset_supernova() : SpellScriptLoader("spell_isiset_supernova") { }
class spell_isiset_supernova_SpellScript : public SpellScript
{
PrepareSpellScript(spell_isiset_supernova_SpellScript);
void FilterTargets(std::list<Unit*>& unitList)
{
unitList.remove_if(OrientationCheck(GetCaster()));
}
void Register()
{
OnUnitTargetSelect += SpellUnitTargetFn(spell_isiset_supernova_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_AREA_ENEMY_SRC);
OnUnitTargetSelect += SpellUnitTargetFn(spell_isiset_supernova_SpellScript::FilterTargets, EFFECT_1, TARGET_UNIT_AREA_ENEMY_SRC);
}
};
SpellScript *GetSpellScript() const
{
return new spell_isiset_supernova_SpellScript();
}
};
void AddSC_boss_isiset()
{
new boss_isiset();
new spell_isiset_supernova();
} | 34.031142 | 145 | 0.516014 | Arkania |
0f14be28932ba2c02a33791d56c2bda7265f7f96 | 1,037 | cpp | C++ | solutions/1032.stream-of-characters.251031467.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/1032.stream-of-characters.251031467.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/1032.stream-of-characters.251031467.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | struct Node {
bool isWord;
vector<Node *> edges;
Node() : isWord(false), edges(26, NULL) {}
};
void addWord(string &s, Node *root) {
reverse(s.begin(), s.end());
for (char c : s) {
if (!root->edges[c - 'a'])
root->edges[c - 'a'] = new Node();
root = root->edges[c - 'a'];
}
root->isWord = true;
}
bool search(string &s, Node *root) {
int n = s.size();
for (int i = n - 1; i >= 0; i--) {
int c = s[i] - 'a';
if (!root->edges[c])
return false;
root = root->edges[c];
if (root->isWord)
return true;
}
return false;
}
class StreamChecker {
vector<Node *> current;
Node *root;
string s;
public:
StreamChecker(vector<string> &words) {
root = new Node();
for (string &w : words)
addWord(w, root);
}
bool query(char letter) {
s += letter;
return search(s, root);
}
};
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker* obj = new StreamChecker(words);
* bool param_1 = obj->query(letter);
*/
| 17.87931 | 69 | 0.56027 | satu0king |
0f16d9d46f35b4f29cb686ca5646be2f26945c8d | 3,788 | cpp | C++ | src/rollinghashcpp/example5.cpp | zhaoxiaofei/binhash | 78e0d465757b93f02cd2d6545717be9e78f93f95 | [
"Apache-2.0"
] | 35 | 2018-07-24T13:59:24.000Z | 2022-03-15T15:06:40.000Z | src/rollinghashcpp/example5.cpp | zhaoxiaofei/binhash | 78e0d465757b93f02cd2d6545717be9e78f93f95 | [
"Apache-2.0"
] | 6 | 2018-11-09T20:15:28.000Z | 2021-03-04T14:38:01.000Z | src/rollinghashcpp/example5.cpp | zhaoxiaofei/binhash | 78e0d465757b93f02cd2d6545717be9e78f93f95 | [
"Apache-2.0"
] | 6 | 2018-07-24T15:08:33.000Z | 2019-07-05T11:52:05.000Z | #include <string>
#include <memory>
#include <cassert>
#include <iostream>
#include "cyclichash.h"
/*
An issue is application-specific and has to do with the nature of DNA. Even
though we usually represent DNA as a string of characters (such as `GATTACA`),
this is really only half the story. DNA is double stranded with `A` pairing
to `T` and `C` pairing to `G`, so the string `GATTACA` really represents the
following molecule.
```
gattaca
|||||||
ɔʇɐɐʇƃʇ
```
In most contexts, we have no way of knowing whether the original piece of DNA
sampled was from the top strand or the bottom strand, and so when we hash DNA
sequences we typically want the two complementary sequences to hash to the
same value.
I used two cyclic hashes: one for the "top" strand of DNA (observed from the
provided string, updated using forward updates) and one for the "bottom" strand
(inferred from the provided string, updated using reverse updates). Then to get
the hash for a particular k-mer (n-gram) in the DNA, I just XOR the current
forward and reverse hashes.
*/
// Define DNA's complementary nucleotides
//
// Daniel: This is probably inefficient. Needlessly so.
// if efficiency matters, you want to define the character hash so that it takes the
// key 'A' to the hash value of 'T' and so forth.
//
# define nucleotide_complement(ch) ( \
(toupper(ch)) == 'A' ? 'T' : \
(toupper(ch)) == 'T' ? 'A' : \
(toupper(ch)) == 'C' ? 'G' : 'C' \
)
// A sequence and its reverse complement (such as "GATTACA" and "TGTAATC") are
// biologically identical and should hash to the same value. A sequence that is
// equal to its reverse complement is a special case and should be handled
// accordingly.
//
#define canonical_hash(fwd, rev) ( \
fwd == rev ? rev : fwd ^ rev \
)
#define WORDSIZE 5
#define SEED1 42
#define SEED2 1985
#define HASHBITS 64
// full string hash from scratch (for comparison)
uint64_t fullhash(const string & input) {
assert(input.size() == WORDSIZE);
CyclicHash<uint64_t> forward(input.size(), SEED1, SEED2, HASHBITS);
CyclicHash<uint64_t> reverse(input.size(), SEED1, SEED2, HASHBITS);
for (int j = 0; j < input.size(); j++) {
forward.eat(input[j]);
reverse.eat(nucleotide_complement(input[input.size() - 1 - j]));
}
return canonical_hash(forward.hashvalue, reverse.hashvalue);
}
// check the rolling hash
// k is the k-gram size, input is any string
void demo(int k, string input) {
// Initialize the hash function to compute the hash of the first k-mer.
CyclicHash<uint64_t> forward(k, SEED1, SEED2, HASHBITS);
CyclicHash<uint64_t> reverse(k, SEED1, SEED2, HASHBITS);
for (int j = 0; j < k; j++) {
forward.eat(input[j]);
// going backward
reverse.eat(nucleotide_complement(input[k - 1 - j]));
}
// rolling has
uint64_t hashval = canonical_hash(forward.hashvalue, reverse.hashvalue);
assert(fullhash(input.substr(0,k)) == hashval);
std::cout << input.substr(0,k) << " " << hashval << std::endl;
for(int j = k ; j < input.size(); j++) {
forward.update(input[j-k], input[j]);
// note: you to flip the parameters of reverse_update
reverse.reverse_update(nucleotide_complement(input[j]), nucleotide_complement(input[j-k]));
// compute the rolling has
hashval = canonical_hash(forward.hashvalue, reverse.hashvalue);
// compare with full string hash
assert(fullhash(input.substr(j-k+1,k)) == hashval);
std::cout << input.substr(j-k+1,k) << " " << hashval << std::endl;
}
}
int main(int argc, char * argv[])
{
demo(5,"GATTACACAATAGCAAATT");
std::cout << " code looks good " << std::endl;
return 0;
}
| 35.735849 | 98 | 0.661035 | zhaoxiaofei |
0f17e95f2e07ba885e2293338bac7d09e6861d87 | 4,781 | hpp | C++ | libraries/chain/include/deip/chain/services/dbs_research_token_sale.hpp | DEIPworld/deip-chain | d3fdcfdde179f700156156ea87522a807ec52532 | [
"MIT"
] | 1 | 2021-08-16T12:44:43.000Z | 2021-08-16T12:44:43.000Z | libraries/chain/include/deip/chain/services/dbs_research_token_sale.hpp | DEIPworld/deip-chain | d3fdcfdde179f700156156ea87522a807ec52532 | [
"MIT"
] | null | null | null | libraries/chain/include/deip/chain/services/dbs_research_token_sale.hpp | DEIPworld/deip-chain | d3fdcfdde179f700156156ea87522a807ec52532 | [
"MIT"
] | 2 | 2021-08-16T12:44:46.000Z | 2021-12-31T17:09:45.000Z | #pragma once
#include "dbs_base_impl.hpp"
#include <vector>
#include <set>
#include <functional>
#include <deip/chain/schema/deip_object_types.hpp>
#include <deip/chain/schema/research_token_sale_object.hpp>
#include <deip/chain/schema/research_object.hpp>
namespace deip {
namespace chain {
class dbs_research_token_sale : public dbs_base
{
friend class dbservice_dbs_factory;
dbs_research_token_sale() = delete;
protected:
explicit dbs_research_token_sale(database& db);
public:
using research_token_sale_refs_type = std::vector<std::reference_wrapper<const research_token_sale_object>>;
using research_token_sale_optional_ref_type = fc::optional<std::reference_wrapper<const research_token_sale_object>>;
const research_token_sale_object& create_research_token_sale(const external_id_type& external_id,
const research_object& research,
const flat_set<asset>& security_tokens_on_sale,
const fc::time_point_sec& start_time,
const fc::time_point_sec& end_time,
const asset& soft_cap,
const asset& hard_cap);
const research_token_sale_object& get_research_token_sale_by_id(const research_token_sale_id_type& id) const;
const research_token_sale_object& get_research_token_sale(const external_id_type& external_id) const;
const research_token_sale_refs_type get_research_token_sales_by_research(const external_id_type& research_external_id) const;
const research_token_sale_optional_ref_type get_research_token_sale_if_exists(const external_id_type& external_id) const;
const research_token_sale_optional_ref_type get_research_token_sale_if_exists(const research_token_sale_id_type& id) const;
const research_token_sale_refs_type get_by_research_id(const research_id_type &research_id) const;
const research_token_sale_object& collect_funds(const research_token_sale_id_type& id, const asset& amount);
const research_token_sale_object& update_status(const research_token_sale_id_type &id,
const research_token_sale_status& status);
research_token_sale_refs_type get_by_research_id_and_status(const research_id_type& research_id,
const research_token_sale_status& status) const;
using research_token_sale_contribution_refs_type = std::vector<std::reference_wrapper<const research_token_sale_contribution_object>>;
using research_token_sale_contribution_optional_ref_type = fc::optional<std::reference_wrapper<const research_token_sale_contribution_object>>;
const research_token_sale_contribution_object& contribute(const research_token_sale_id_type& research_token_sale_id,
const account_name_type& owner,
const fc::time_point_sec& contribution_time,
const asset& amount);
const research_token_sale_contribution_optional_ref_type get_research_token_sale_contribution_if_exists(const research_token_sale_contribution_id_type& id) const;
const research_token_sale_contribution_refs_type get_research_token_sale_contributions_by_research_token_sale(const external_id_type& token_sale_external_id) const;
const research_token_sale_contribution_refs_type get_research_token_sale_contributions_by_research_token_sale_id(const research_token_sale_id_type& research_token_sale_id) const;
const research_token_sale_contribution_object& get_research_token_sale_contribution_by_contributor_and_research_token_sale_id(const account_name_type& owner, const research_token_sale_id_type& research_token_sale_id) const;
const research_token_sale_contribution_optional_ref_type get_research_token_sale_contribution_by_contributor_and_research_token_sale_id_if_exists(const account_name_type& owner, const research_token_sale_id_type& research_token_sale_id) const;
const research_token_sale_contribution_refs_type get_research_token_sale_contributions_by_contributor(const account_name_type& owner) const;
void finish_research_token_sale(const research_token_sale_id_type& research_token_sale_id);
void refund_research_token_sale(const research_token_sale_id_type research_token_sale_id);
void process_research_token_sales();
};
} // namespace chain
} // namespace deip
| 55.593023 | 247 | 0.735202 | DEIPworld |
0f1a7f63d3e2f2791457235cf1403d182871fbc0 | 7,950 | cpp | C++ | ngraph/core/src/op/avg_pool.cpp | uikilin100/openvino | afc5191b8c75b1de4adc8cb07c6269b52882ddfe | [
"Apache-2.0"
] | 1 | 2021-03-16T17:40:26.000Z | 2021-03-16T17:40:26.000Z | ngraph/core/src/op/avg_pool.cpp | uikilin100/openvino | afc5191b8c75b1de4adc8cb07c6269b52882ddfe | [
"Apache-2.0"
] | 42 | 2020-11-23T08:09:57.000Z | 2022-02-21T13:03:34.000Z | ngraph/core/src/op/avg_pool.cpp | tsocha/openvino | 3081fac7581933568b496a3c4e744d1cee481619 | [
"Apache-2.0"
] | 4 | 2021-04-02T08:48:38.000Z | 2021-07-01T06:59:02.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "ngraph/op/avg_pool.hpp"
#include "itt.hpp"
#include "ngraph/attribute_visitor.hpp"
#include "ngraph/graph_util.hpp"
#include "ngraph/validation_util.hpp"
using namespace std;
using namespace ngraph;
// *** AvgPool OP SET 1 ***
NGRAPH_RTTI_DEFINITION(op::v1::AvgPool, "AvgPool", 1);
op::v1::AvgPool::AvgPool(const Output<Node>& arg,
const Strides& strides,
const Shape& pads_begin,
const Shape& pads_end,
const Shape& kernel,
bool exclude_pad,
op::RoundingType rounding_type,
const PadType& auto_pad)
: Op({arg}),
m_kernel(kernel),
m_strides(strides),
m_pads_begin(pads_begin),
m_pads_end(pads_end),
m_exclude_pad(exclude_pad),
m_auto_pad(auto_pad),
m_rounding_type(rounding_type) {
constructor_validate_and_infer_types();
}
bool op::v1::AvgPool::visit_attributes(AttributeVisitor& visitor) {
NGRAPH_OP_SCOPE(v1_AvgPool_visit_attributes);
visitor.on_attribute("kernel", m_kernel);
visitor.on_attribute("strides", m_strides);
visitor.on_attribute("pads_begin", m_pads_begin);
visitor.on_attribute("pads_end", m_pads_end);
visitor.on_attribute("exclude-pad", m_exclude_pad);
visitor.on_attribute("auto_pad", m_auto_pad);
visitor.on_attribute("rounding_type", m_rounding_type);
return true;
}
void op::v1::AvgPool::validate_and_infer_types() {
NGRAPH_OP_SCOPE(v1_AvgPool_validate_and_infer_types);
if (0 == m_strides.size()) {
m_strides = Strides(m_kernel.size(), 1);
}
if (0 == m_pads_begin.size()) {
m_pads_begin = Shape(m_kernel.size(), 0);
}
if (0 == m_pads_end.size()) {
m_pads_end = Shape(m_kernel.size(), 0);
}
const PartialShape& arg_shape = get_input_partial_shape(0);
NODE_VALIDATION_CHECK(
this,
arg_shape.rank().compatible(3) || arg_shape.rank().compatible(4) || arg_shape.rank().compatible(5),
"Expected a 3D, 4D or 5D tensor for the input. Got: ",
arg_shape);
if (arg_shape.rank().is_static()) {
NODE_VALIDATION_CHECK(this,
static_cast<int64_t>(m_pads_end.size()) == arg_shape.rank().get_max_length() - 2,
"Expected pads_end size to be equal to input size - 2. Got: ",
m_pads_end.size());
NODE_VALIDATION_CHECK(this,
static_cast<int64_t>(m_pads_begin.size()) == arg_shape.rank().get_max_length() - 2,
"Expected pads_begin size to be equal to input size - 2. Got: ",
m_pads_begin.size());
NODE_VALIDATION_CHECK(this,
static_cast<int64_t>(m_kernel.size()) == arg_shape.rank().get_max_length() - 2,
"Expected kernel size to be equal to input size - 2. Got: ",
m_kernel.size());
NODE_VALIDATION_CHECK(this,
static_cast<int64_t>(m_strides.size()) == arg_shape.rank().get_max_length() - 2,
"Expected strides size to be equal to input size - 2. Got: ",
m_kernel.size());
}
auto output_shape = PartialShape::dynamic();
if (arg_shape.rank().is_static()) {
output_shape = std::vector<Dimension>(arg_shape.rank().get_max_length(), Dimension::dynamic());
if (arg_shape[0].is_static()) {
output_shape[0] = arg_shape[0]; // batch size
}
if (arg_shape[1].is_static()) {
output_shape[1] = arg_shape[1]; // channel size
}
}
bool update_auto_padding_succeed = true;
if (m_auto_pad == PadType::SAME_UPPER || m_auto_pad == PadType::SAME_LOWER) {
CoordinateDiff pads_end;
CoordinateDiff pads_begin;
update_auto_padding_succeed = try_apply_auto_padding(arg_shape,
m_kernel,
m_strides,
Strides(m_kernel.size(), 1), // No dilation
m_auto_pad,
pads_end,
pads_begin);
m_pads_end = Shape(pads_end.begin(), pads_end.end());
m_pads_begin = Shape(pads_begin.begin(), pads_begin.end());
}
if (m_auto_pad == PadType::VALID) {
m_pads_end = Shape(m_pads_end.size(), 0);
m_pads_begin = Shape(m_pads_begin.size(), 0);
}
// infer_batched_forward_pooling wants CoordinateDiffs for these, while the pooling ops for
// now still take Shape (no negative padding).
CoordinateDiff pads_begin(m_pads_begin.begin(), m_pads_begin.end());
CoordinateDiff pads_end(m_pads_end.begin(), m_pads_end.end());
set_output_type(0,
get_input_element_type(0),
update_auto_padding_succeed
? infer_batched_pooling_forward(this,
arg_shape,
pads_begin,
pads_end,
m_kernel,
m_strides,
!m_exclude_pad,
m_rounding_type == op::RoundingType::CEIL,
Strides{}) // no dilation of the window
: output_shape);
}
const Shape& op::v1::AvgPool::get_kernel() const {
return m_kernel;
}
void op::v1::AvgPool::set_kernel(const Shape& kernel) {
m_kernel = kernel;
}
const Strides& op::v1::AvgPool::get_strides() const {
return m_strides;
}
void op::v1::AvgPool::set_strides(const Strides& strides) {
m_strides = strides;
}
const Shape& op::v1::AvgPool::get_pads_begin() const {
return m_pads_begin;
}
void op::v1::AvgPool::set_pads_begin(const Shape& pads_begin) {
m_pads_begin = pads_begin;
}
const Shape& op::v1::AvgPool::get_pads_end() const {
return m_pads_end;
}
void op::v1::AvgPool::set_pads_end(const Shape& pads_end) {
m_pads_end = pads_end;
}
bool op::v1::AvgPool::get_exclude_pad() const {
return m_exclude_pad;
}
void op::v1::AvgPool::set_exclude_pad(bool exclude_pad) {
m_exclude_pad = exclude_pad;
}
const op::PadType& op::v1::AvgPool::get_auto_pad() const {
return m_auto_pad;
}
void op::v1::AvgPool::set_auto_pad(const op::PadType& auto_pad) {
m_auto_pad = auto_pad;
}
op::RoundingType op::v1::AvgPool::get_rounding_type() const {
return m_rounding_type;
}
void op::v1::AvgPool::set_rounding_type(op::RoundingType rounding_type) {
m_rounding_type = rounding_type;
}
shared_ptr<Node> op::v1::AvgPool::clone_with_new_inputs(const OutputVector& new_args) const {
NGRAPH_OP_SCOPE(v1_AvgPool_clone_with_new_inputs);
check_new_args_count(this, new_args);
return make_shared<v1::AvgPool>(new_args.at(0),
m_strides,
m_pads_begin,
m_pads_end,
m_kernel,
m_exclude_pad,
m_rounding_type,
m_auto_pad);
}
shared_ptr<Node> op::v1::AvgPool::get_default_value() const {
return op::Constant::create(get_element_type(), get_shape(), {0});
}
| 37.857143 | 113 | 0.55195 | uikilin100 |
0f1df7e865699da4e50389ddce8587348b1afa92 | 65 | cpp | C++ | core/GUI/Selector.cpp | ferluht/pocketdaw | 0e40b32191e431cde54cd5944611c4b5b293ea68 | [
"BSD-2-Clause"
] | null | null | null | core/GUI/Selector.cpp | ferluht/pocketdaw | 0e40b32191e431cde54cd5944611c4b5b293ea68 | [
"BSD-2-Clause"
] | null | null | null | core/GUI/Selector.cpp | ferluht/pocketdaw | 0e40b32191e431cde54cd5944611c4b5b293ea68 | [
"BSD-2-Clause"
] | 1 | 2022-03-29T19:45:51.000Z | 2022-03-29T19:45:51.000Z | //
// Created by ibelikov on 24.12.19.
//
#include "Selector.h"
| 10.833333 | 35 | 0.630769 | ferluht |
0f21beff2666f406d346e39a820ebfd924317262 | 5,808 | hpp | C++ | include/Mono/Math/Prime/PrimalityTest_.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/Mono/Math/Prime/PrimalityTest_.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/Mono/Math/Prime/PrimalityTest_.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.MulticastDelegate
#include "System/MulticastDelegate.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Mono::Math
namespace Mono::Math {
// Forward declaring type: BigInteger
class BigInteger_;
}
// Forward declaring namespace: Mono::Math::Prime
namespace Mono::Math::Prime {
// Forward declaring type: ConfidenceFactor
struct ConfidenceFactor_;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: IAsyncResult
class IAsyncResult;
// Forward declaring type: AsyncCallback
class AsyncCallback;
}
// Completed forward declares
// Type namespace: Mono.Math.Prime
namespace Mono::Math::Prime {
// Forward declaring type: PrimalityTest
class PrimalityTest_;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::Mono::Math::Prime::PrimalityTest_);
DEFINE_IL2CPP_ARG_TYPE(::Mono::Math::Prime::PrimalityTest_*, "Mono.Math.Prime", "PrimalityTest");
// Type namespace: Mono.Math.Prime
namespace Mono::Math::Prime {
// Size: 0x70
#pragma pack(push, 1)
// Autogenerated type: Mono.Math.Prime.PrimalityTest
// [TokenAttribute] Offset: FFFFFFFF
class PrimalityTest_ : public ::System::MulticastDelegate {
public:
// public System.Void .ctor(System.Object object, System.IntPtr method)
// Offset: 0x14D0314
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static PrimalityTest_* New_ctor(::Il2CppObject* object, ::System::IntPtr method) {
static auto ___internal__logger = ::Logger::get().WithContext("::Mono::Math::Prime::PrimalityTest_::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<PrimalityTest_*, creationType>(object, method)));
}
// public System.Boolean Invoke(Mono.Math.BigInteger bi, Mono.Math.Prime.ConfidenceFactor confidence)
// Offset: 0x14D0324
bool Invoke(::Mono::Math::BigInteger_* bi, ::Mono::Math::Prime::ConfidenceFactor_ confidence);
// public System.IAsyncResult BeginInvoke(Mono.Math.BigInteger bi, Mono.Math.Prime.ConfidenceFactor confidence, System.AsyncCallback callback, System.Object object)
// Offset: 0x14D06C0
::System::IAsyncResult* BeginInvoke(::Mono::Math::BigInteger_* bi, ::Mono::Math::Prime::ConfidenceFactor_ confidence, ::System::AsyncCallback* callback, ::Il2CppObject* object);
// public System.Boolean EndInvoke(System.IAsyncResult result)
// Offset: 0x14D0758
bool EndInvoke(::System::IAsyncResult* result);
}; // Mono.Math.Prime.PrimalityTest
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Mono::Math::Prime::PrimalityTest_::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: Mono::Math::Prime::PrimalityTest_::Invoke
// Il2CppName: Invoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Mono::Math::Prime::PrimalityTest_::*)(::Mono::Math::BigInteger_*, ::Mono::Math::Prime::ConfidenceFactor_)>(&Mono::Math::Prime::PrimalityTest_::Invoke)> {
static const MethodInfo* get() {
static auto* bi = &::il2cpp_utils::GetClassFromName("Mono.Math", "BigInteger")->byval_arg;
static auto* confidence = &::il2cpp_utils::GetClassFromName("Mono.Math.Prime", "ConfidenceFactor")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Mono::Math::Prime::PrimalityTest_*), "Invoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{bi, confidence});
}
};
// Writing MetadataGetter for method: Mono::Math::Prime::PrimalityTest_::BeginInvoke
// Il2CppName: BeginInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::IAsyncResult* (Mono::Math::Prime::PrimalityTest_::*)(::Mono::Math::BigInteger_*, ::Mono::Math::Prime::ConfidenceFactor_, ::System::AsyncCallback*, ::Il2CppObject*)>(&Mono::Math::Prime::PrimalityTest_::BeginInvoke)> {
static const MethodInfo* get() {
static auto* bi = &::il2cpp_utils::GetClassFromName("Mono.Math", "BigInteger")->byval_arg;
static auto* confidence = &::il2cpp_utils::GetClassFromName("Mono.Math.Prime", "ConfidenceFactor")->byval_arg;
static auto* callback = &::il2cpp_utils::GetClassFromName("System", "AsyncCallback")->byval_arg;
static auto* object = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Mono::Math::Prime::PrimalityTest_*), "BeginInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{bi, confidence, callback, object});
}
};
// Writing MetadataGetter for method: Mono::Math::Prime::PrimalityTest_::EndInvoke
// Il2CppName: EndInvoke
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Mono::Math::Prime::PrimalityTest_::*)(::System::IAsyncResult*)>(&Mono::Math::Prime::PrimalityTest_::EndInvoke)> {
static const MethodInfo* get() {
static auto* result = &::il2cpp_utils::GetClassFromName("System", "IAsyncResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Mono::Math::Prime::PrimalityTest_*), "EndInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{result});
}
};
| 55.314286 | 295 | 0.737259 | v0idp |
0f22e82b232259f8c25d76261756ada321235c48 | 1,054 | cpp | C++ | ch04/e4-11.cpp | nanonashy/PPPUCpp2ndJP | b829867e9e21bf59d9c5ea6c2fbe96bb03597301 | [
"MIT"
] | 3 | 2021-12-17T17:25:18.000Z | 2022-03-02T15:52:23.000Z | ch04/e4-11.cpp | nashinium/PPPUCpp2ndJP | b829867e9e21bf59d9c5ea6c2fbe96bb03597301 | [
"MIT"
] | 1 | 2020-04-22T07:16:34.000Z | 2020-04-22T10:04:04.000Z | ch04/e4-11.cpp | nashinium/PPPUCpp2ndJP | b829867e9e21bf59d9c5ea6c2fbe96bb03597301 | [
"MIT"
] | 1 | 2020-04-22T08:13:51.000Z | 2020-04-22T08:13:51.000Z | // 問題文:
// 1~100の素数をすべて見つけ出すプログラムを作成する。そのための方法の1つは、素数が順番
// に配置された vector
// を使用して、数字が素数かどうかをチェックする関数を記述することだ。
// つまり、この vector が primes
// という名前であるとすれば、primes[0]==2、primes[1]==3、 primes[2]==5
// などを使用して、数字がそれよりも小さい素数で割り切れるかどうかをチェックする。
// 次に、1~100の各数字が素数かどうかをチェックし、検出された素数を vector
// に格納する
// グループを記述する。また、検出された素数を一覧表示するぺ部のループも記述する。素数の
// vector を primes
// と比較することで、結果をチェックするとよいだろう。最初の素数は2である。
#include "../include/std_lib_facilities.h"
bool check_primes(vector<int> primes, int number) {
bool is_prime{true};
unsigned int i{0};
while (is_prime && i < primes.size()) {
if (number % primes[i] == 0)
is_prime = false;
++i;
}
return is_prime;
}
int main() {
vector<int> primes;
primes.push_back(2);
int limit{100};
for (int i = 3; i <= limit; ++i) {
if (check_primes(primes, i))
primes.push_back(i);
}
std::cout << "1~100の素数リスト\n";
for (int p : primes)
std::cout << p << '\n';
return 0;
} | 24.511628 | 57 | 0.59203 | nanonashy |
0f23f885a5b4a6b8e03fe9db68619288ce98e85f | 574 | cpp | C++ | ch06/ex6_21.cpp | jl1987/Cpp-Primer | 028dcb44318667bb8713c82ce0c86676a3dcda27 | [
"CC0-1.0"
] | 1 | 2019-05-02T19:19:11.000Z | 2019-05-02T19:19:11.000Z | ch06/ex6_21.cpp | jl1987/Cpp-Primer | 028dcb44318667bb8713c82ce0c86676a3dcda27 | [
"CC0-1.0"
] | null | null | null | ch06/ex6_21.cpp | jl1987/Cpp-Primer | 028dcb44318667bb8713c82ce0c86676a3dcda27 | [
"CC0-1.0"
] | null | null | null | //! @Alan
//!
//! Exercise 6.21:
//! Write a function that takes an int and a pointer to an int and
//! returns the larger of the int value or the value to which the
//! pointer points. What type should you use for the pointer?
//!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int LargerOne(const int _i,const int* _ip);
int main()
{
int c=6;
cout<<LargerOne(7,&c);
return 0;
}
int LargerOne(const int _i, const int *_ip)
{
if( _i > *_ip )
{
return _i;
}
else
{
return *_ip;
}
}
| 14 | 66 | 0.601045 | jl1987 |
0f24ea4784fa4696146c038cb3f5eaa6dca973f7 | 21,864 | cpp | C++ | utils/vpc/vpc/solutiongenerator_win32.cpp | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 252 | 2020-12-16T15:34:43.000Z | 2022-03-31T23:21:37.000Z | cstrike15_src/utils/vpc/vpc/solutiongenerator_win32.cpp | bahadiraraz/Counter-Strike-Global-Offensive | 9a0534100cb98ffa1cf0c32e138f0e7971e910d3 | [
"MIT"
] | 23 | 2020-12-20T18:02:54.000Z | 2022-03-28T16:58:32.000Z | cstrike15_src/utils/vpc/vpc/solutiongenerator_win32.cpp | bahadiraraz/Counter-Strike-Global-Offensive | 9a0534100cb98ffa1cf0c32e138f0e7971e910d3 | [
"MIT"
] | 42 | 2020-12-19T04:32:33.000Z | 2022-03-30T06:00:28.000Z | //===================== Copyright (c) Valve Corporation. All Rights Reserved. ======================
//
// Purpose:
//
//==================================================================================================
#include "vpc.h"
#include "dependencies.h"
#include "tier1/checksum_md5.h"
struct SolutionFolderData_t
{
CUtlString strAbsPath;
CUtlString strFolderName;
CUtlString strGUID;
CUtlString strParentGUID;
CUtlString strSearchPattern;
CUtlVector< CUtlString > files;
};
class CSolutionGenerator_Win32 : public IBaseSolutionGenerator
{
public:
void GetVCPROJSolutionGUID( const char *szProjectExtension, char (&szSolutionGUID)[256] )
{
#if defined( PLATFORM_WINDOWS )
HKEY hKey;
int firstVer = 8;
const int lastVer = 14; // Handle up to VS 14, AKA VS 2015
if ( g_pVPC->Is2010() )
{
firstVer = 10;
}
// Handle both VisualStudio and VCExpress (used by some SourceSDK customers)
const char* productName[] =
{
"VisualStudio",
"VCExpress",
};
for ( int nLocationIter = 0; nLocationIter < 2; ++nLocationIter ) //for some reason I don't care to investigate there are more keys available at HKEY_CURRENT_USER\\Software\\Microsoft\\%s\\%d.0_Config\\Projects (androidproj support)
{
for ( int vsVer = firstVer; vsVer <= lastVer; ++vsVer )
{
for ( int productNumber = 0; productNumber < ARRAYSIZE(productName); ++productNumber )
{
LONG ret;
if ( nLocationIter == 0 )
{
#if defined( _WIN64 )
#define WOW6432NODESTR "Software\\Wow6432Node"
#else
#define WOW6432NODESTR "Software"
#endif
ret = RegOpenKeyEx( HKEY_LOCAL_MACHINE, CFmtStrN<1024>( WOW6432NODESTR "\\Microsoft\\%s\\%d.0\\Projects", productName[ productNumber ], vsVer ).Get(), 0, KEY_READ, &hKey );
}
else if ( nLocationIter == 1 )
{
ret = RegOpenKeyEx( HKEY_CURRENT_USER, CFmtStrN<1024>( "Software\\Microsoft\\%s\\%d.0_Config\\Projects", productName[ productNumber ], vsVer ).Get(), 0, KEY_READ, &hKey );
}
else
{
UNREACHABLE();
}
if ( ret != ERROR_SUCCESS )
continue;
int nEnumKey = 0;
do
{
char szKeyName[MAX_FIXED_PATH];
DWORD dwKeyNameSize = sizeof( szKeyName );
ret = RegEnumKeyEx( hKey, nEnumKey++, szKeyName, &dwKeyNameSize, NULL, NULL, NULL, NULL );
if ( ret == ERROR_NO_MORE_ITEMS )
break;
HKEY hSubKey;
ret = RegOpenKeyEx( hKey, szKeyName, 0, KEY_READ, &hSubKey );
if ( ret == ERROR_SUCCESS )
{
DWORD dwType;
char ext[MAX_BASE_FILENAME];
DWORD dwExtLen = sizeof( ext );
ret = RegQueryValueEx( hSubKey, "DefaultProjectExtension", NULL, &dwType, (BYTE*)ext, &dwExtLen );
RegCloseKey( hSubKey );
// VS 2012 and beyond has the DefaultProjectExtension as vcxproj instead of vcproj
if ( (ret == ERROR_SUCCESS) && (dwType == REG_SZ) && V_stricmp_fast( ext, szProjectExtension ) == 0 )
{
V_strncpy( szSolutionGUID, szKeyName, ARRAYSIZE(szSolutionGUID) );
RegCloseKey( hKey );
return;
}
}
}
while( true );
RegCloseKey( hKey );
}
}
}
#endif
g_pVPC->VPCError( "Unable to find RegKey for .%s files in solutions.", szProjectExtension );
}
const char *UpdateProjectFilename( const char *pProjectFilename, CUtlPathStringHolder *pUpdateBuffer )
{
const char *pExt = V_GetFileExtension( pProjectFilename );
// We may be generating a makefile wrapper solution,
// in which case we need to look at the wrapper
// project instead of the base project.
const char *pProjectExt = "vcproj";
if ( g_pVPC->Is2010() )
{
pProjectExt = "vcxproj";
}
if ( pExt == NULL ||
V_stricmp_fast( pExt, "mak" ) == 0 )
{
pUpdateBuffer->Set( pProjectFilename, ".", pProjectExt );
return pUpdateBuffer->Get();
}
return pProjectFilename;
}
virtual void GenerateSolutionFile( const char *pSolutionFilename, CUtlVector<CDependency_Project*> &projects )
{
// Default extension.
CUtlPathStringHolder tmpSolutionFilename;
if ( !V_GetFileExtension( pSolutionFilename ) )
{
tmpSolutionFilename.Set( pSolutionFilename, ".sln" );
pSolutionFilename = tmpSolutionFilename.Get();
}
CUtlVector<CUtlString> allProjectPlatforms;
{
CUtlVector<CUtlString> platformCollect;
for ( int i = 0; i < projects.Count(); i++ )
{
//collect all the platforms supported by this project
platformCollect.RemoveAll();
projects[i]->m_pProjectGenerator->EnumerateSupportedVPCTargetPlatforms( platformCollect );
//add each supported platform to the final list if it's not already in there
for ( int j = 0; j < platformCollect.Count(); ++j )
{
if ( !allProjectPlatforms.IsValidIndex( allProjectPlatforms.Find( platformCollect[j] ) ) )
{
allProjectPlatforms.AddToTail( platformCollect[j] );
}
}
}
}
g_pVPC->VPCStatus( true, "\nWriting solution file %s.", pSolutionFilename );
// Write the file.
FILE *fp = fopen( pSolutionFilename, "wt" );
if ( !fp )
g_pVPC->VPCError( "Can't open %s for writing.", pSolutionFilename );
if ( g_pVPC->Is2015() )
{
fprintf( fp, "\xef\xbb\xbf\nMicrosoft Visual Studio Solution File, Format Version 14.00\n" );
fprintf( fp, "# Visual Studio 2015\n" );
}
else if ( g_pVPC->Is2013() )
{
fprintf( fp, "\xef\xbb\xbf\nMicrosoft Visual Studio Solution File, Format Version 12.00\n" ); // Format didn't change from VS 2012 to VS 2013
fprintf( fp, "# Visual Studio 2013\n" );
}
else if ( g_pVPC->Is2012() )
{
fprintf( fp, "\xef\xbb\xbf\nMicrosoft Visual Studio Solution File, Format Version 12.00\n" );
fprintf( fp, "# Visual Studio 2012\n" );
}
else if ( g_pVPC->Is2010() )
{
fprintf( fp, "\xef\xbb\xbf\nMicrosoft Visual Studio Solution File, Format Version 11.00\n" );
fprintf( fp, "# Visual Studio 2010\n" );
}
else
{
fprintf( fp, "\xef\xbb\xbf\nMicrosoft Visual Studio Solution File, Format Version 9.00\n" );
fprintf( fp, "# Visual Studio 2005\n" );
}
fprintf( fp, "#\n" );
fprintf( fp, "# Automatically generated solution:\n" );
fprintf( fp, "# devtools\\bin\\vpc " );
#if defined( PLATFORM_WINDOWS )
for ( int k = 1; k < __argc; ++ k )
fprintf( fp, "%s ", __argv[k] );
#endif
fprintf( fp, "\n" );
fprintf( fp, "#\n" );
fprintf( fp, "#\n" );
if ( !g_pVPC->Is2010() )
{
// if /slnItems <filename> is passed on the command line, build a Solution Items project
const char *pSolutionItemsFilename = g_pVPC->GetSolutionItemsFilename();
if ( pSolutionItemsFilename[0] != '\0' )
{
fprintf( fp, "Project(\"{2150E333-8FDC-42A3-9474-1A3956D46DE8}\") = \"Solution Items\", \"Solution Items\", \"{AAAAAAAA-8B4A-11D0-8D11-90A07D6D6F7D}\"\n" );
fprintf( fp, "\tProjectSection(SolutionItems) = preProject\n" );
WriteSolutionItems( fp );
fprintf( fp, "\tEndProjectSection\n" );
fprintf( fp, "EndProject\n" );
}
}
//Write the data for all the solution folders
CUtlVector< SolutionFolderData_t > solutionFolderData;
WriteSolutionFolders( fp, solutionFolderData );
for ( int i=0; i < projects.Count(); i++ )
{
CDependency_Project *pCurProject = projects[i];
char szBasePath[MAX_PATH];
V_strncpy( szBasePath, pCurProject->m_Filename, ARRAYSIZE( szBasePath ) );
V_StripFilename( szBasePath );
char szOutputFilePath[MAX_PATH];
V_ComposeFileName( szBasePath, pCurProject->GetProjectFileName(), szOutputFilePath, ARRAYSIZE( szOutputFilePath ) );
// Get a relative filename for the vcproj file.
CUtlPathStringHolder updatedFilename;
const char *pFullProjectFilename = UpdateProjectFilename( szOutputFilePath,
&updatedFilename );
char szRelativeFilename[MAX_FIXED_PATH];
if ( !V_MakeRelativePath( pFullProjectFilename, g_pVPC->GetSourcePath(), szRelativeFilename, sizeof( szRelativeFilename ) ) )
g_pVPC->VPCError( "Can't make a relative path (to the base source directory) for %s.", pFullProjectFilename );
char szSolutionGUID[256];
GetVCPROJSolutionGUID( V_GetFileExtension( szRelativeFilename ), szSolutionGUID );
if ( g_pVPC->Is2010() )
{
char *pLastDot;
char pProjectName[MAX_BASE_FILENAME];
// It looks like Incredibuild 3.6 looks to build projects using the full project name
// with _x360 or _win64 attached to the end. Basically, the full project filename with
// the path and .vcxproj extension removed.
Sys_StripPath( pFullProjectFilename, pProjectName, sizeof( pProjectName ) );
pLastDot = V_strrchr( pProjectName, '.' );
if (pLastDot)
{
*pLastDot = 0;
}
fprintf( fp, "Project(\"%s\") = \"%s\", \"%s\", \"{%s}\"\n", szSolutionGUID, pProjectName, szRelativeFilename, pCurProject->GetProjectGUIDString() );
}
else
{
fprintf( fp, "Project(\"%s\") = \"%s\", \"%s\", \"{%s}\"\n", szSolutionGUID, pCurProject->GetName(), szRelativeFilename, pCurProject->GetProjectGUIDString() );
}
bool bHasDependencies = false;
for ( int iTestProject=0; iTestProject < projects.Count(); iTestProject++ )
{
if ( i == iTestProject )
continue;
CDependency_Project *pTestProject = projects[iTestProject];
if ( pCurProject->DependsOn( pTestProject, k_EDependsOnFlagCheckNormalDependencies | k_EDependsOnFlagTraversePastLibs | k_EDependsOnFlagRecurse ) ||
pCurProject->DependsOn( pTestProject, k_EDependsOnFlagCheckAdditionalDependencies | k_EDependsOnFlagTraversePastLibs ) )
{
if ( !bHasDependencies )
{
fprintf( fp, "\tProjectSection(ProjectDependencies) = postProject\n" );
bHasDependencies = true;
}
fprintf( fp, "\t\t{%s} = {%s}\n", projects[iTestProject]->GetProjectGUIDString(), projects[iTestProject]->GetProjectGUIDString() );
}
}
if ( bHasDependencies )
fprintf( fp, "\tEndProjectSection\n" );
fprintf( fp, "EndProject\n" );
}
if ( g_pVPC->Is2010() )
{
fprintf( fp, "Global\n" );
fprintf( fp, " GlobalSection(SolutionConfigurationPlatforms) = preSolution\n" );
for ( int nPlatformIter = 0; nPlatformIter < allProjectPlatforms.Count(); ++nPlatformIter )
{
const char *szVPCPlatformName = allProjectPlatforms[nPlatformIter].Get();
fprintf( fp, " Debug|%s = Debug|%s\n", szVPCPlatformName, szVPCPlatformName );
fprintf( fp, " Release|%s = Release|%s\n", szVPCPlatformName, szVPCPlatformName );
}
fprintf( fp, " EndGlobalSection\n" );
fprintf( fp, " GlobalSection(ProjectConfigurationPlatforms) = postSolution\n" );
for ( int nPlatformIter = 0; nPlatformIter < allProjectPlatforms.Count(); ++nPlatformIter )
{
const char *szVPCPlatformName = allProjectPlatforms[nPlatformIter].Get();
for ( int i=0; i < projects.Count(); i++ )
{
const char *ProjectGUID = projects[i]->GetProjectGUIDString();
IBaseProjectGenerator *pProjectGenerator = projects[i]->m_pProjectGenerator;
bool bBuilds = pProjectGenerator->BuildsForTargetPlatform( szVPCPlatformName );
bool bDeploys = pProjectGenerator->DeploysForVPCTargetPlatform( szVPCPlatformName );
if ( bBuilds || bDeploys )
{
CUtlString sPlatformAlias = pProjectGenerator->GetSolutionPlatformAlias( szVPCPlatformName, this );
const char *szVisualStudioPlatformName = sPlatformAlias.Get();
fprintf( fp, " {%s}.Debug|%s.ActiveCfg = Debug|%s\n", ProjectGUID, szVPCPlatformName, szVisualStudioPlatformName );
if ( bBuilds )
{
fprintf( fp, " {%s}.Debug|%s.Build.0 = Debug|%s\n", ProjectGUID, szVPCPlatformName, szVisualStudioPlatformName );
}
if ( bDeploys )
{
fprintf( fp, " {%s}.Debug|%s.Deploy.0 = Debug|%s\n", ProjectGUID, szVPCPlatformName, szVisualStudioPlatformName );
}
fprintf( fp, " {%s}.Release|%s.ActiveCfg = Release|%s\n", ProjectGUID, szVPCPlatformName, szVisualStudioPlatformName );
if ( bBuilds )
{
fprintf( fp, " {%s}.Release|%s.Build.0 = Release|%s\n", ProjectGUID, szVPCPlatformName, szVisualStudioPlatformName );
}
if ( bDeploys )
{
fprintf( fp, " {%s}.Release|%s.Deploy.0 = Release|%s\n", ProjectGUID, szVPCPlatformName, szVisualStudioPlatformName );
}
}
}
}
fprintf( fp, " EndGlobalSection\n" );
fprintf( fp, " GlobalSection(SolutionProperties) = preSolution\n" );
fprintf( fp, " HideSolutionNode = FALSE\n" );
fprintf( fp, " EndGlobalSection\n" );
if ( solutionFolderData.Count() > 0 )
{
//Add the nested solution folders
fprintf( fp, " GlobalSection(NestedProjects) = preSolution\n" );
FOR_EACH_VEC( solutionFolderData, i )
{
if ( !solutionFolderData[i].strParentGUID.IsEmpty() && ShouldWriteSolutionFolder( solutionFolderData[i], solutionFolderData ) )
{
fprintf( fp, "\t\t%s = %s\n", solutionFolderData[i].strGUID.Get(), solutionFolderData[i].strParentGUID.Get() );
}
}
fprintf( fp, " EndGlobalSection\n" );
}
fprintf( fp, "EndGlobal\n" );
}
fclose( fp );
Sys_CopyToMirror( pSolutionFilename );
}
virtual const char *GetSolutionFileExtension() { return "sln"; }
virtual SolutionType_t GetSolutionType( void ) OVERRIDE { return ST_VISUALSTUDIO; }
const char* FindInFile( const char *pFilename, const char *pFileData, const char *pSearchFor )
{
const char *pPos = V_stristr( pFileData, pSearchFor );
if ( !pPos )
{
g_pVPC->VPCError( "Can't find %s in %s.", pSearchFor, pFilename );
}
return pPos + V_strlen( pSearchFor );
}
// Parse g_SolutionItemsFilename, reading in filenames (including wildcards),
// and add them to the Solution Items project we're already writing.
void WriteSolutionItems( FILE *fp )
{
#if defined( PLATFORM_WINDOWS )
CUtlPathStringHolder fullSolutionItemsPath;
if ( V_IsAbsolutePath( g_pVPC->GetSolutionItemsFilename() ) )
fullSolutionItemsPath.Set( g_pVPC->GetSolutionItemsFilename() );
else
fullSolutionItemsPath.ComposeFileName( g_pVPC->GetStartDirectory(), g_pVPC->GetSolutionItemsFilename() );
g_pVPC->GetScript().PushScript( fullSolutionItemsPath );
int numSolutionItems = 0;
while ( g_pVPC->GetScript().GetData() )
{
// read a line
const char *pToken = g_pVPC->GetScript().GetToken( false );
// strip out \r\n chars
char *end = V_strstr( pToken, "\n" );
if ( end )
{
*end = '\0';
}
end = V_strstr( pToken, "\r" );
if ( end )
{
*end = '\0';
}
// bail on strings too small to be paths
if ( V_strlen( pToken ) < 3 )
continue;
// compose an absolute path w/o any ../
CUtlPathStringHolder fullPath;
if ( V_IsAbsolutePath( pToken ) )
fullPath.Set( pToken );
else
fullPath.ComposeFileName( g_pVPC->GetStartDirectory(), pToken );
fullPath.FixSlashesAndDotSlashes();
if ( V_strstr( fullPath, "*" ) != NULL )
{
// wildcard!
CUtlPathStringHolder wildcardPath( fullPath );
wildcardPath.StripFilename();
struct _finddata32_t data;
intptr_t handle = _findfirst32( fullPath, &data );
if ( handle != -1L )
{
do
{
if ( ( data.attrib & _A_SUBDIR ) == 0 )
{
// not a dir, just a filename - add it
fullPath.ComposeFileName( wildcardPath, data.name );
fullPath.FixSlashesAndDotSlashes();
fprintf( fp, "\t\t%s = %s\n", fullPath.Get(), fullPath.Get() );
++numSolutionItems;
}
} while ( _findnext32( handle, &data ) == 0 );
_findclose( handle );
}
}
else
{
// just a file - add it
fprintf( fp, "\t\t%s = %s\n", fullPath.Get(), fullPath.Get() );
++numSolutionItems;
}
}
g_pVPC->GetScript().PopScript();
Msg( "Found %d solution files in %s\n", numSolutionItems, g_pVPC->GetSolutionItemsFilename() );
#endif
}
void AddSolutionFolder( CUtlString strAbsPath, CUtlString strSearchPattern, CUtlVector< SolutionFolderData_t > &solutionFolders )
{
solutionFolders.AddToTail();
SolutionFolderData_t &folder = solutionFolders.Tail();
folder.strAbsPath = strAbsPath;
folder.strAbsPath.StripTrailingSlash();
folder.strSearchPattern = strSearchPattern;
//Get the name of the folder that will be added to the solution
int nPathLength = folder.strAbsPath.Length();
while ( nPathLength > 0 )
{
//Find the last path separator in the path
if ( PATHSEPARATOR( folder.strAbsPath[nPathLength-1] ) )
{
break;
}
nPathLength--;
}
folder.strFolderName = folder.strAbsPath.Slice( nPathLength );
folder.strFolderName.ToLower();
//Get the GUID of the folder
MD5Context_t ctx;
unsigned char digest[MD5_DIGEST_LENGTH];
V_memset( &ctx, 0, sizeof( ctx ) );
V_memset( digest, 0, sizeof( digest ) );
MD5Init( &ctx );
MD5Update( &ctx, (unsigned char *)folder.strAbsPath.Get(), folder.strAbsPath.Length() );
MD5Final( digest, &ctx );
char szMD5[64];
V_binarytohex( digest, MD5_DIGEST_LENGTH, szMD5, sizeof( szMD5 ) );
V_strupper_fast( szMD5 );
char szGUID[100];
V_snprintf( szGUID, sizeof( szGUID ), "{%8.8s-%4.4s-%4.4s-%4.4s-%12.12s}", szMD5, &szMD5[8], &szMD5[12], &szMD5[16], &szMD5[20] );
folder.strGUID = szGUID;
}
void AddFilesToSolutionFolder( CUtlVector< SolutionFolderData_t > &folders, int nIndex )
{
#if defined( PLATFORM_WINDOWS )
CUtlString strSearchPattern = folders[nIndex].strSearchPattern;
bool bAllFiles = strSearchPattern == "*.*";
const char *pszSearchExtension = V_GetFileExtensionSafe( strSearchPattern );
CUtlString strSearchPath = CUtlString::PathJoin( folders[nIndex].strAbsPath, "*.*" );
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile( strSearchPath, &findFileData );
if ( hFind != INVALID_HANDLE_VALUE )
{
do
{
//FindFirstFile and FindNextFile find "." and ".." as files when searched using "*.*"
//we don't want these to be added to our lists
if ( findFileData.cFileName[0] != '.' )
{
//If the found file is actually a directory
if ( findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
//Found a sub-dir, add it to the list of folders and add all the files in the sub-dir
CUtlString strSubDirPath = CUtlString::PathJoin( folders[nIndex].strAbsPath, findFileData.cFileName );
AddSolutionFolder( strSubDirPath, folders[nIndex].strSearchPattern, folders );
//Set the parent GUID for the sub-directory
int nSubDirIndex = folders.Count() - 1;
folders[nSubDirIndex].strParentGUID = folders[nIndex].strGUID;
//Recursively add the files from the sub-dir
AddFilesToSolutionFolder( folders, nSubDirIndex );
}
else
{
//Add this file to the list if we are adding all files or if this files extension matches the search pattern
const char *pszExtension = V_GetFileExtensionSafe( findFileData.cFileName );
if ( bAllFiles || !V_stricmp_fast( pszExtension, pszSearchExtension ) )
{
folders[nIndex].files.AddToTail( CUtlString::PathJoin( folders[nIndex].strAbsPath, findFileData.cFileName ) );
}
}
}
} while ( FindNextFile( hFind, &findFileData ) != 0 );
FindClose( hFind );
}
#endif
}
bool ShouldWriteSolutionFolder( SolutionFolderData_t &folder, CUtlVector< SolutionFolderData_t > &solutionFolderData )
{
if ( folder.files.Count() > 0 )
{
//Write the folder if it has files
return true;
}
else
{
//Only write empty folders if they are the parent of another folder that has files or children that have files
FOR_EACH_VEC( solutionFolderData, i )
{
if ( folder.strGUID == solutionFolderData[i].strParentGUID && ShouldWriteSolutionFolder( solutionFolderData[i], solutionFolderData ) )
{
return true;
}
}
}
return false;
}
void WriteSolutionFolders( FILE *fp, CUtlVector< SolutionFolderData_t > &solutionFolderData )
{
const CUtlVector< CUtlString > &solutionFolderNames = g_pVPC->GetSolutionFolderNames();
char szOldPath[MAX_FIXED_PATH];
V_GetCurrentDirectory( szOldPath, ARRAYSIZE( szOldPath ) );
V_SetCurrentDirectory( g_pVPC->GetSourcePath() );
FOR_EACH_VEC( solutionFolderNames, x )
{
//Get the path and search pattern for the folder
CUtlString strAbsPath, strSearchPattern;
if ( solutionFolderNames[x].GetExtension().IsEmpty() )
{
//No search pattern provided, assume "*.*" (all files)
strAbsPath = solutionFolderNames[x].AbsPath( NULL, k_bVPCForceLowerCase );
strSearchPattern = "*.*";
}
else
{
//Separate the path and search pattern
strAbsPath = solutionFolderNames[x].StripFilename().AbsPath( NULL, k_bVPCForceLowerCase );
strSearchPattern = solutionFolderNames[x].UnqualifiedFilename();
}
AddSolutionFolder( strAbsPath, strSearchPattern, solutionFolderData );
AddFilesToSolutionFolder( solutionFolderData, solutionFolderData.Count() - 1 );
}
V_SetCurrentDirectory( szOldPath );
//Write out each solution folder
FOR_EACH_VEC( solutionFolderData, i )
{
if ( ShouldWriteSolutionFolder( solutionFolderData[i], solutionFolderData ) )
{
fprintf( fp, "Project(\"{2150E333-8FDC-42A3-9474-1A3956D46DE8}\") = \"%s\", \"%s\", \"%s\"\n", solutionFolderData[i].strFolderName.Get(), solutionFolderData[i].strFolderName.Get(), solutionFolderData[i].strGUID.Get() );
if ( solutionFolderData[i].files.Count() > 0 )
{
fprintf( fp, "\tProjectSection(SolutionItems) = preProject\n" );
FOR_EACH_VEC( solutionFolderData[i].files, j )
{
fprintf( fp, "\t\t%s = %s\n", solutionFolderData[i].files[j].Get(), solutionFolderData[i].files[j].Get() );
}
fprintf( fp, "\tEndProjectSection\n" );
}
fprintf( fp, "EndProject\n" );
}
}
}
};
static CSolutionGenerator_Win32 g_SolutionGenerator_Win32;
IBaseSolutionGenerator* GetSolutionGenerator_Win32()
{
return &g_SolutionGenerator_Win32;
}
| 34.00311 | 234 | 0.665935 | DannyParker0001 |
0f256d75fd48b5724c37e77dbc2d6a4dac175b90 | 29,478 | cpp | C++ | src/game/client/tf/vgui/tf_deathmatchscoreboard.cpp | Menoly12/Yet-Another-Deathmatch-Mod | 8f532c8ba9cacdeedc2407b67926a63d19465603 | [
"Unlicense"
] | 127 | 2015-01-07T02:28:55.000Z | 2022-03-29T21:30:32.000Z | src/game/client/tf/vgui/tf_deathmatchscoreboard.cpp | Snow150/TF2Classic | d070129a436a8a070659f0267f6e63564a519a47 | [
"Unlicense"
] | 155 | 2015-01-09T12:54:20.000Z | 2022-03-14T21:11:11.000Z | src/game/client/tf/vgui/tf_deathmatchscoreboard.cpp | Snow150/TF2Classic | d070129a436a8a070659f0267f6e63564a519a47 | [
"Unlicense"
] | 106 | 2015-01-07T03:38:13.000Z | 2022-03-19T22:42:19.000Z | //========= Copyright © 1996-2006, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include <tier1/fmtstr.h>
#include <vgui_controls/Label.h>
#include <vgui_controls/Button.h>
#include <vgui_controls/ImagePanel.h>
#include <vgui_controls/RichText.h>
#include <vgui_controls/Frame.h>
#include <vgui/IScheme.h>
#include <vgui/ILocalize.h>
#include <vgui/ISurface.h>
#include <vgui/IVGui.h>
#include <vgui_controls/SectionedListPanel.h>
#include <vgui_controls/ImageList.h>
#include <vgui_controls/Menu.h>
#include <vgui_controls/MenuItem.h>
#include <game/client/iviewport.h>
#include <KeyValues.h>
#include <filesystem.h>
#include "IGameUIFuncs.h" // for key bindings
#include "tf_controls.h"
#include "tf_shareddefs.h"
#include "tf_deathmatchscoreboard.h"
#include "tf_gamestats_shared.h"
#include "tf_hud_statpanel.h"
#include "c_playerresource.h"
#include "c_tf_playerresource.h"
#include "c_tf_team.h"
#include "c_tf_player.h"
#include "vgui_avatarimage.h"
#include "tf_gamerules.h"
#include "inputsystem/iinputsystem.h"
#include "basemodelpanel.h"
#include "engine/IEngineSound.h"
#include "in_buttons.h"
#include "voice_status.h"
#include "tf_music_manager.h"
#if defined ( _X360 )
#include "engine/imatchmaking.h"
#endif
using namespace vgui;
#define SCOREBOARD_MAX_LIST_ENTRIES 12
extern bool IsInCommentaryMode( void );
extern const char *GetMapDisplayName( const char *mapName );
vgui::IImage* GetDefaultAvatarImage( C_BasePlayer *pPlayer );
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CTFDeathMatchScoreBoardDialog::CTFDeathMatchScoreBoardDialog( IViewPort *pViewPort ) : CClientScoreBoardDialog( pViewPort )
{
SetProportional( true );
SetKeyBoardInputEnabled( false );
SetMouseInputEnabled( false );
MakePopup( true );
SetScheme( "ClientScheme" );
m_pPlayerListRed = new SectionedListPanel( this, "RedPlayerList" );
m_pRedScoreBG = new ImagePanel( this, "RedScoreBG" );
m_iImageDead = 0;
m_iImageDominated = 0;
m_iImageNemesis = 0;
bLockInput = false;
m_pWinPanel = new EditablePanel( this, "WinPanel" );
m_flTimeUpdateTeamScore = 0;
iSelectedPlayerIndex = 0;
ListenForGameEvent( "server_spawn" );
ListenForGameEvent( "teamplay_win_panel" );
ListenForGameEvent( "teamplay_round_start" );
ListenForGameEvent( "teamplay_game_over" );
ListenForGameEvent( "tf_game_over" );
SetDialogVariable( "server", "" );
m_pContextMenu = new Menu( this, "contextmenu" );
m_pContextMenu->AddMenuItem( "Mute", new KeyValues( "Command", "command", "mute" ), this );
m_pContextMenu->AddMenuItem( "Vote kick...", new KeyValues( "Command", "command", "kick" ), this );
m_pContextMenu->AddMenuItem( "Show Steam profile", new KeyValues( "Command", "command", "showprofile" ), this );
SetVisible( false );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CTFDeathMatchScoreBoardDialog::~CTFDeathMatchScoreBoardDialog()
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::PerformLayout()
{
BaseClass::PerformLayout();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
LoadControlSettings( "Resource/UI/DeathMatchScoreBoard.res" );
if ( m_pImageList )
{
m_iImageDead = m_pImageList->AddImage( scheme()->GetImage( "../hud/leaderboard_dead", true ) );
m_iImageDominated = m_pImageList->AddImage( scheme()->GetImage( "../hud/leaderboard_dominated", true ) );
m_iImageNemesis = m_pImageList->AddImage( scheme()->GetImage( "../hud/leaderboard_nemesis", true ) );
// We're skipping the mercenary, as he shouldn't have a visible class emblem during regular gameplay
for ( int i = TF_CLASS_SCOUT; i < TF_CLASS_MERCENARY; i++ )
{
m_iClassEmblem[i] = m_pImageList->AddImage( scheme()->GetImage( g_aPlayerClassEmblems[i - 1], true ) );
m_iClassEmblemDead[i] = m_pImageList->AddImage( scheme()->GetImage( g_aPlayerClassEmblemsDead[i - 1], true ) );
}
// resize the images to our resolution
for ( int i = 1; i < m_pImageList->GetImageCount(); i++ )
{
int wide = 13, tall = 13;
m_pImageList->GetImage( i )->SetSize( scheme()->GetProportionalScaledValueEx( GetScheme(), wide ), scheme()->GetProportionalScaledValueEx( GetScheme(), tall ) );
}
}
if ( m_pWinPanel )
{
m_pWinPanel->SetVisible( false );
}
SetPlayerListImages( m_pPlayerListRed );
m_pPlayerListRed->SetVerticalScrollbar( true );
iDefaultTall = m_pPlayerListRed->GetTall();
SetVisible( false );
Reset();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::ShowContextMenu( KeyValues* data )
{
Panel *pItem = (Panel*)data->GetPtr( "SubPanel" );
int iItem = data->GetInt( "itemID" );
if ( pItem )
{
KeyValues *pData = m_pPlayerListRed->GetItemData( iItem );
iSelectedPlayerIndex = pData->GetInt( "playerIndex", 0 );
bool bMuted = GetClientVoiceMgr()->IsPlayerBlocked( iSelectedPlayerIndex );
vgui::MenuItem *pMenuMute = m_pContextMenu->GetMenuItem( 0 );
pMenuMute->SetText( !bMuted ? "Mute" : "Unmute" );
if ( !( g_PR->GetPing( iSelectedPlayerIndex ) < 1 && g_PR->IsFakePlayer( iSelectedPlayerIndex ) ) )
{
Menu::PlaceContextMenu( this, m_pContextMenu );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::OnCommand( const char* command )
{
if ( !Q_strcmp( command, "mute" ) )
{
bool bMuted = GetClientVoiceMgr()->IsPlayerBlocked( iSelectedPlayerIndex );
GetClientVoiceMgr()->SetPlayerBlockedState( iSelectedPlayerIndex, !bMuted );
}
else if ( !Q_strcmp( command, "kick" ) )
{
//add proper votekicking after callvotes support
engine->ExecuteClientCmd( "callvote" );
}
else if ( !Q_strcmp( command, "showprofile" ) )
{
C_BasePlayer *pPlayerOther = UTIL_PlayerByIndex( iSelectedPlayerIndex );
if ( pPlayerOther )
{
CSteamID pPlayerSteamID;
pPlayerOther->GetSteamID( &pPlayerSteamID );
steamapicontext->SteamFriends()->ActivateGameOverlayToUser( "steamid", pPlayerSteamID );
}
}
else
{
BaseClass::OnCommand( command );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::ShowPanel( bool bShow )
{
// Catch the case where we call ShowPanel before ApplySchemeSettings, eg when
// going from windowed <-> fullscreen
if ( m_pImageList == NULL )
{
InvalidateLayout( true, true );
}
if ( !bShow && bLockInput )
{
return;
}
// Don't show in commentary mode
if ( IsInCommentaryMode() )
{
bShow = false;
}
if ( IsVisible() == bShow )
{
return;
}
int iRenderGroup = gHUD.LookupRenderGroupIndexByName( "global" );
if ( bShow )
{
SetVisible( true );
SetKeyBoardInputEnabled( false );
gHUD.LockRenderGroup( iRenderGroup );
// Clear the selected item, this forces the default to the local player
SectionedListPanel *pList = GetSelectedPlayerList();
if ( pList )
{
pList->ClearSelection();
}
}
else
{
SetVisible( false );
m_pContextMenu->SetVisible( false );
SetMouseInputEnabled( false );
SetKeyBoardInputEnabled( false );
bLockInput = false;
gHUD.UnlockRenderGroup( iRenderGroup );
}
}
//-----------------------------------------------------------------------------
// Purpose: Resets the scoreboard panel
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::Reset()
{
InitPlayerList( m_pPlayerListRed );
}
//-----------------------------------------------------------------------------
// Purpose: Inits the player list in a list panel
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::InitPlayerList( SectionedListPanel *pPlayerList )
{
//pPlayerList->SetVerticalScrollbar( true );
pPlayerList->RemoveAll();
pPlayerList->RemoveAllSections();
pPlayerList->AddSection( 0, "Players", TFPlayerSortFunc );
pPlayerList->SetSectionAlwaysVisible( 0, true );
pPlayerList->SetSectionFgColor( 0, Color( 255, 255, 255, 255 ) );
pPlayerList->SetBgColor( Color( 0, 0, 0, 0 ) );
pPlayerList->SetBorder( NULL );
// Avatars are always displayed at 32x32 regardless of resolution
if ( ShowAvatars() )
{
pPlayerList->AddColumnToSection( 0, "avatar", "", SectionedListPanel::COLUMN_IMAGE/* | SectionedListPanel::COLUMN_CENTER*/, m_iAvatarWidth );
}
pPlayerList->AddColumnToSection( 0, "name", "#TF_Scoreboard_Name", 0, m_iNameWidth );
pPlayerList->AddColumnToSection( 0, "status", "", SectionedListPanel::COLUMN_IMAGE, m_iStatusWidth );
pPlayerList->AddColumnToSection( 0, "nemesis", "", SectionedListPanel::COLUMN_IMAGE, m_iNemesisWidth );
pPlayerList->AddColumnToSection( 0, "kills", "#TF_ScoreBoard_KillsLabel", 0, m_iKillsWidth );
pPlayerList->AddColumnToSection( 0, "deaths", "#TF_ScoreBoard_DeathsLabel", 0, m_iDeathsWidth );
pPlayerList->AddColumnToSection( 0, "streak", "#TF_ScoreBoard_KillStreak", 0, m_iKillstreakWidth );
pPlayerList->AddColumnToSection( 0, "score", "#TF_Scoreboard_Score", 0, m_iScoreWidth );
pPlayerList->AddColumnToSection( 0, "ping", "#TF_Scoreboard_Ping", 0, m_iPingWidth );
}
//-----------------------------------------------------------------------------
// Purpose: Builds the image list to use in the player list
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::SetPlayerListImages( vgui::SectionedListPanel *pPlayerList )
{
pPlayerList->SetImageList( m_pImageList, false );
pPlayerList->SetVisible( true );
}
//-----------------------------------------------------------------------------
// Purpose: Updates the dialog
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::Update()
{
UpdateTeamInfo();
UpdatePlayerList();
UpdateSpectatorList();
UpdatePlayerDetails();
MoveToCenterOfScreen();
// update every second
m_fNextUpdateTime = gpGlobals->curtime + 1.0f;
}
//-----------------------------------------------------------------------------
// Purpose: Updates information about teams
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::UpdateTeamInfo()
{
// update the team sections in the scoreboard
int teamIndex = TF_TEAM_RED;
wchar_t *teamName = NULL;
C_Team *team = GetGlobalTeam( teamIndex );
if ( team )
{
// choose dialog variables to set depending on team
const char *pDialogVarTeamScore = NULL;
const char *pDialogVarTeamPlayerCount = NULL;
const char *pDialogVarTeamName = NULL;
switch ( teamIndex )
{
case TF_TEAM_RED:
pDialogVarTeamScore = "redteamscore";
pDialogVarTeamPlayerCount = "redteamplayercount";
pDialogVarTeamName = "redteamname";
break;
default:
Assert( false );
break;
}
// update # of players on each team
wchar_t name[64];
wchar_t string1[1024];
wchar_t wNumPlayers[6];
_snwprintf( wNumPlayers, ARRAYSIZE( wNumPlayers ), L"%i", team->Get_Number_Players() );
if ( !teamName && team )
{
g_pVGuiLocalize->ConvertANSIToUnicode( team->Get_Name(), name, sizeof( name ) );
teamName = name;
}
if ( team->Get_Number_Players() == 1 )
{
g_pVGuiLocalize->ConstructString( string1, sizeof( string1 ), g_pVGuiLocalize->Find( "#TF_ScoreBoard_Player" ), 1, wNumPlayers );
}
else
{
g_pVGuiLocalize->ConstructString( string1, sizeof( string1 ), g_pVGuiLocalize->Find( "#TF_ScoreBoard_Players" ), 1, wNumPlayers );
}
// set # of players for team in dialog
SetDialogVariable( pDialogVarTeamPlayerCount, string1 );
// set team score in dialog
SetDialogVariable( pDialogVarTeamScore, team->Get_Score() );
// set team name
SetDialogVariable( pDialogVarTeamName, team->Get_Name() );
}
}
//-----------------------------------------------------------------------------
// Purpose: Updates the player list
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::UpdatePlayerList()
{
int iSelectedPlayerIndex = GetLocalPlayerIndex();
// Save off which player we had selected
SectionedListPanel *pList = GetSelectedPlayerList();
if ( pList )
{
int itemID = pList->GetSelectedItem();
if ( itemID >= 0 )
{
KeyValues *pInfo = pList->GetItemData( itemID );
if ( pInfo )
{
iSelectedPlayerIndex = pInfo->GetInt( "playerIndex" );
}
}
}
m_pPlayerListRed->RemoveAll();
C_TF_PlayerResource *tf_PR = dynamic_cast<C_TF_PlayerResource *>( g_PR );
if ( !tf_PR )
return;
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( !pLocalPlayer )
return;
int localteam = pLocalPlayer->GetTeamNumber();
bool bMadeSelection = false;
for ( int playerIndex = 1; playerIndex <= MAX_PLAYERS; playerIndex++ )
{
if ( g_PR->IsConnected( playerIndex ) )
{
SectionedListPanel *pPlayerList = NULL;
switch ( g_PR->GetTeam( playerIndex ) )
{
case TF_TEAM_RED:
pPlayerList = m_pPlayerListRed;
break;
}
if ( null == pPlayerList )
continue;
const char *szName = tf_PR->GetPlayerName( playerIndex );
int score = tf_PR->GetTotalScore( playerIndex );
int kills = tf_PR->GetPlayerScore( playerIndex );
int deaths = tf_PR->GetDeaths( playerIndex );
int streak = tf_PR->GetKillstreak( playerIndex );
KeyValues *pKeyValues = new KeyValues( "data" );
pKeyValues->SetInt( "playerIndex", playerIndex );
pKeyValues->SetString( "name", szName );
pKeyValues->SetInt( "score", score );
pKeyValues->SetInt( "kills", kills );
pKeyValues->SetInt( "deaths", deaths );
pKeyValues->SetInt( "streak", streak );
// can only see class information if we're on the same team
if ( !AreEnemyTeams( g_PR->GetTeam( playerIndex ), localteam ) && !( localteam == TEAM_UNASSIGNED ) )
{
// class name
if ( g_PR->IsConnected( playerIndex ) )
{
int iClass = tf_PR->GetPlayerClass( playerIndex );
if ( GetLocalPlayerIndex() == playerIndex && !tf_PR->IsAlive( playerIndex ) )
{
// If this is local player and he is dead, show desired class (which he will spawn as) rather than current class.
C_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer();
int iDesiredClass = pPlayer->m_Shared.GetDesiredPlayerClassIndex();
// use desired class unless it's random -- if random, his future class is not decided until moment of spawn
if ( TF_CLASS_RANDOM != iDesiredClass )
{
iClass = iDesiredClass;
}
}
else
{
// for non-local players, show the current class
iClass = tf_PR->GetPlayerClass( playerIndex );
}
}
}
else
{
C_TFPlayer *pPlayerOther = ToTFPlayer( UTIL_PlayerByIndex( playerIndex ) );
if ( pPlayerOther && pPlayerOther->m_Shared.IsPlayerDominated( pLocalPlayer->entindex() ) )
{
// if local player is dominated by this player, show a nemesis icon
pKeyValues->SetInt( "nemesis", m_iImageNemesis );
}
else if ( pLocalPlayer->m_Shared.IsPlayerDominated( playerIndex ) )
{
// if this player is dominated by the local player, show the domination icon
pKeyValues->SetInt( "nemesis", m_iImageDominated );
}
}
// display whether player is alive or dead (all players see this for all other players on both teams)
pKeyValues->SetInt( "status", tf_PR->IsAlive( playerIndex ) ? 0 : m_iImageDead );
if ( g_PR->GetPing( playerIndex ) < 1 )
{
if ( g_PR->IsFakePlayer( playerIndex ) )
{
pKeyValues->SetString( "ping", "#TF_Scoreboard_Bot" );
}
else
{
pKeyValues->SetString( "ping", "" );
}
}
else
{
pKeyValues->SetInt( "ping", g_PR->GetPing( playerIndex ) );
}
UpdatePlayerAvatar( playerIndex, pKeyValues );
int itemID = pPlayerList->AddItem( 0, pKeyValues );
Color clr = tf_PR->GetPlayerColor( playerIndex );
pPlayerList->SetItemFgColor( itemID, clr );
if ( iSelectedPlayerIndex == playerIndex )
{
bMadeSelection = true;
pPlayerList->SetSelectedItem( itemID );
}
pKeyValues->deleteThis();
}
}
// If we're on spectator, find a default selection
if ( !bMadeSelection )
{
if ( m_pPlayerListRed->GetItemCount() > 0 )
{
m_pPlayerListRed->SetSelectedItem( 0 );
}
}
ResizeScoreboard();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::ResizeScoreboard()
{
int _wide, _tall;
int wide, tall;
int x, y;
surface()->GetScreenSize( _wide, _tall );
m_pPlayerListRed->GetContentSize( wide, tall );
m_pPlayerListRed->GetPos( x, y );
int yshift = y + scheme()->GetProportionalScaledValue( 10 );
if ( tall > iDefaultTall && tall + yshift < _tall )
{
m_pPlayerListRed->SetSize( wide, tall );
tall += yshift;
wide = GetWide();
SetSize( wide, tall );
}
}
//-----------------------------------------------------------------------------
// Purpose: Updates the spectator list
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::UpdateSpectatorList()
{
char szSpectatorList[512] = "";
int nSpectators = 0;
for ( int playerIndex = 1; playerIndex <= MAX_PLAYERS; playerIndex++ )
{
if ( ShouldShowAsSpectator( playerIndex ) )
{
if ( nSpectators > 0 )
{
Q_strncat( szSpectatorList, ", ", ARRAYSIZE( szSpectatorList ) );
}
Q_strncat( szSpectatorList, g_PR->GetPlayerName( playerIndex ), ARRAYSIZE( szSpectatorList ) );
nSpectators++;
}
}
wchar_t wzSpectators[512] = L"";
if ( nSpectators > 0 )
{
const char *pchFormat = ( 1 == nSpectators ? "#ScoreBoard_Spectator" : "#ScoreBoard_Spectators" );
wchar_t wzSpectatorCount[16];
wchar_t wzSpectatorList[1024];
_snwprintf( wzSpectatorCount, ARRAYSIZE( wzSpectatorCount ), L"%i", nSpectators );
g_pVGuiLocalize->ConvertANSIToUnicode( szSpectatorList, wzSpectatorList, sizeof( wzSpectatorList ) );
g_pVGuiLocalize->ConstructString( wzSpectators, sizeof( wzSpectators ), g_pVGuiLocalize->Find( pchFormat ), 2, wzSpectatorCount, wzSpectatorList );
}
SetDialogVariable( "spectators", wzSpectators );
}
//-----------------------------------------------------------------------------
// Purpose: Updates details about a player
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::UpdatePlayerDetails()
{
ClearPlayerDetails();
C_TF_PlayerResource *tf_PR = dynamic_cast<C_TF_PlayerResource *>( g_PR );
if ( !tf_PR )
return;
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( !pLocalPlayer )
return;
int playerIndex = pLocalPlayer->entindex();
// Make sure the selected player is still connected.
if ( !tf_PR->IsConnected( playerIndex ) )
return;
if ( engine->IsHLTV() )
{
SetDialogVariable( "playername", tf_PR->GetPlayerName( playerIndex ) );
return;
}
RoundStats_t &roundStats = GetStatPanel()->GetRoundStatsCurrentGame();
SetDialogVariable( "kills", tf_PR->GetPlayerScore( playerIndex ) );
SetDialogVariable( "deaths", tf_PR->GetDeaths( playerIndex ) );
SetDialogVariable( "assists", roundStats.m_iStat[TFSTAT_KILLASSISTS] );
SetDialogVariable( "dominations", roundStats.m_iStat[TFSTAT_DOMINATIONS] );
SetDialogVariable( "revenge", roundStats.m_iStat[TFSTAT_REVENGE] );
SetDialogVariable( "playername", tf_PR->GetPlayerName( playerIndex ) );
SetDialogVariable( "playerscore", GetPointsString( tf_PR->GetTotalScore( playerIndex ) ) );
Color clr = tf_PR->GetPlayerColor( playerIndex );
m_pRedScoreBG->SetFillColor( clr );
}
//-----------------------------------------------------------------------------
// Purpose: Clears score details
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::ClearPlayerDetails()
{
// HLTV has no game stats
bool bVisible = !engine->IsHLTV();
SetDialogVariable( "kills", "" );
SetControlVisible( "KillsLabel", bVisible );
SetDialogVariable( "deaths", "" );
SetControlVisible( "DeathsLabel", bVisible );
SetDialogVariable( "dominations", "" );
SetControlVisible( "DominationLabel", bVisible );
SetDialogVariable( "revenge", "" );
SetControlVisible( "RevengeLabel", bVisible );
SetDialogVariable( "assists", "" );
SetControlVisible( "AssistsLabel", bVisible );
SetDialogVariable( "playername", "" );
SetDialogVariable( "playerscore", "" );
}
//-----------------------------------------------------------------------------
// Purpose: Used for sorting players
//-----------------------------------------------------------------------------
bool CTFDeathMatchScoreBoardDialog::TFPlayerSortFunc( vgui::SectionedListPanel *list, int itemID1, int itemID2 )
{
KeyValues *it1 = list->GetItemData( itemID1 );
KeyValues *it2 = list->GetItemData( itemID2 );
Assert( it1 && it2 );
// first compare score
int v1 = it1->GetInt( "score" );
int v2 = it2->GetInt( "score" );
if ( v1 > v2 )
return true;
else if ( v1 < v2 )
return false;
// if score is the same, use player index to get deterministic sort
int iPlayerIndex1 = it1->GetInt( "playerIndex" );
int iPlayerIndex2 = it2->GetInt( "playerIndex" );
return ( iPlayerIndex1 > iPlayerIndex2 );
}
//-----------------------------------------------------------------------------
// Purpose: Returns whether the specified player index is a spectator
//-----------------------------------------------------------------------------
bool CTFDeathMatchScoreBoardDialog::ShouldShowAsSpectator( int iPlayerIndex )
{
C_TF_PlayerResource *tf_PR = dynamic_cast<C_TF_PlayerResource *>( g_PR );
if ( !tf_PR )
return false;
// see if player is connected
if ( tf_PR->IsConnected( iPlayerIndex ) )
{
// either spectating or unassigned team should show in spectator list
int iTeam = tf_PR->GetTeam( iPlayerIndex );
if ( TEAM_SPECTATOR == iTeam || TEAM_UNASSIGNED == iTeam )
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Event handler
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::FireGameEvent( IGameEvent *event )
{
const char *type = event->GetName();
if ( 0 == Q_strcmp( type, "server_spawn" ) )
{
// set server name in scoreboard
const char *hostname = event->GetString( "hostname" );
wchar_t wzHostName[256];
wchar_t wzServerLabel[256];
g_pVGuiLocalize->ConvertANSIToUnicode( hostname, wzHostName, sizeof( wzHostName ) );
g_pVGuiLocalize->ConstructString( wzServerLabel, sizeof( wzServerLabel ), g_pVGuiLocalize->Find( "#Scoreboard_Server" ), 1, wzHostName );
SetDialogVariable( "server", wzServerLabel );
// Set the level name after the server spawn
char szMapName[MAX_MAP_NAME];
Q_FileBase( engine->GetLevelName(), szMapName, sizeof( szMapName ) );
Q_strlower( szMapName );
SetDialogVariable( "mapname", GetMapDisplayName( szMapName ) );
m_pWinPanel->SetVisible( false );
bLockInput = false;
ShowPanel( false );
}
else if ( Q_strcmp( "teamplay_win_panel", type ) == 0 )
{
if ( !TFGameRules() || !TFGameRules()->IsDeathmatch() )
return;
m_fNextUpdateTime = gpGlobals->curtime + 0.1;
m_flTimeUpdateTeamScore = gpGlobals->curtime + 4.5f;
bLockInput = true;
bool bPlayerFirst = false;
C_TF_PlayerResource *tf_PR = dynamic_cast<C_TF_PlayerResource *>( g_PR );
if ( !tf_PR )
return;
// look for the top 3 players sent in the event
for ( int i = 1; i <= 3; i++ )
{
bool bShow = false;
char szPlayerIndexVal[64] = "", szPlayerScoreVal[64] = "", szPlayerKillsVal[64] = "", szPlayerDeathsVal[64] = "";
// get player index and round points from the event
Q_snprintf( szPlayerIndexVal, ARRAYSIZE( szPlayerIndexVal ), "player_%d", i );
Q_snprintf( szPlayerScoreVal, ARRAYSIZE( szPlayerScoreVal ), "player_%d_points", i );
Q_snprintf( szPlayerKillsVal, ARRAYSIZE( szPlayerKillsVal ), "player_%d_kills", i );
Q_snprintf( szPlayerDeathsVal, ARRAYSIZE( szPlayerDeathsVal ), "player_%d_deaths", i );
int iPlayerIndex = event->GetInt( szPlayerIndexVal, 0 );
int iRoundScore = event->GetInt( szPlayerScoreVal, 0 );
int iPlayerKills = event->GetInt( szPlayerKillsVal, 0 );
int iPlayerDeaths = event->GetInt( szPlayerDeathsVal, 0 );
// round score of 0 means no player to show for that position (not enough players, or didn't score any points that round)
if ( iRoundScore > 0 )
bShow = true;
CAvatarImagePanel *pPlayerAvatar = dynamic_cast<CAvatarImagePanel *>( m_pWinPanel->FindChildByName( CFmtStr( "Player%dAvatar", i ) ) );
if ( pPlayerAvatar )
{
pPlayerAvatar->ClearAvatar();
if ( bShow )
{
pPlayerAvatar->SetPlayer( GetSteamIDForPlayerIndex( iPlayerIndex ), k_EAvatarSize32x32 );
pPlayerAvatar->SetAvatarSize( 32, 32 );
}
pPlayerAvatar->SetVisible( bShow );
}
vgui::Label *pPlayerName = dynamic_cast<Label *>( m_pWinPanel->FindChildByName( CFmtStr( "Player%dName", i ) ) );
vgui::Label *pPlayerKills = dynamic_cast<Label *>( m_pWinPanel->FindChildByName( CFmtStr( "Player%dKills", i ) ) );
vgui::Label *pPlayerDeaths = dynamic_cast<Label *>( m_pWinPanel->FindChildByName( CFmtStr( "Player%dDeaths", i ) ) );
CModelPanel *pPlayerModel = dynamic_cast<CModelPanel *>( m_pWinPanel->FindChildByName( CFmtStr( "Player%dModel", i ) ) );
if ( !pPlayerName || !pPlayerKills || !pPlayerDeaths )
return;
if ( bShow )
{
// set the player labels to team color
Color clr = tf_PR->GetPlayerColor( iPlayerIndex );
pPlayerName->SetFgColor( clr );
pPlayerKills->SetFgColor( clr );
pPlayerDeaths->SetFgColor( clr );
// set label contents
pPlayerName->SetText( g_PR->GetPlayerName( iPlayerIndex ) );
pPlayerKills->SetText( CFmtStr( "Kills: %d", iPlayerKills ) );
pPlayerDeaths->SetText( CFmtStr( "Deaths: %d", iPlayerDeaths ) );
if ( i == 1 && iPlayerIndex == GetLocalPlayerIndex() )
bPlayerFirst = true;
// store the colors for model coloring
m_vecWinningPlayerColor.AddToTail( Vector( clr.r() / 255.0f, clr.g() / 255.0f, clr.b() / 255.0f ) );
}
// show or hide labels for this player position
pPlayerName->SetVisible( bShow );
pPlayerKills->SetVisible( bShow );
pPlayerDeaths->SetVisible( bShow );
pPlayerModel->SetVisible( bShow );
}
ShowPanel( true );
if ( !GetTFMusicManager()->IsPlayingMusic() )
{
CLocalPlayerFilter filter;
C_BaseEntity::EmitSound( filter, SOUND_FROM_LOCAL_PLAYER, ( bPlayerFirst ? "music.dm_winpanel_first" : "music.dm_winpanel" ) );
}
}
else if ( Q_strcmp( "teamplay_round_start", type ) == 0 )
{
m_flTimeUpdateTeamScore = 0.0f;
m_pWinPanel->SetVisible( false );
bLockInput = false;
ShowPanel( false );
}
if ( IsVisible() )
{
Update();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
SectionedListPanel *CTFDeathMatchScoreBoardDialog::GetSelectedPlayerList( void )
{
SectionedListPanel *pList = NULL;
// navigation
if ( m_pPlayerListRed->GetSelectedItem() >= 0 )
{
pList = m_pPlayerListRed;
}
return pList;
}
//-----------------------------------------------------------------------------
// Purpose: panel think method
//-----------------------------------------------------------------------------
void CTFDeathMatchScoreBoardDialog::OnThink()
{
BaseClass::OnThink();
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( IsVisible() && pLocalPlayer && pLocalPlayer->m_nButtons & IN_ATTACK2 )
{
SetMouseInputEnabled( true );
}
// if we've scheduled ourselves to update the team scores, handle it now
if ( m_flTimeUpdateTeamScore > 0 && ( gpGlobals->curtime > m_flTimeUpdateTeamScore ) && m_pWinPanel )
{
m_pWinPanel->SetVisible( true );
m_flTimeUpdateTeamScore = 0;
}
if ( m_pWinPanel && m_pWinPanel->IsVisible() && !m_vecWinningPlayerColor.IsEmpty() )
{
for ( int i = 1; i <= 3; i++ )
{
CModelPanel *pPlayerModelPanel = dynamic_cast<CModelPanel *>( m_pWinPanel->FindChildByName( CFmtStr( "Player%dModel", i ) ) );
if ( pPlayerModelPanel )
{
CModelPanelModel *pPanelModel = pPlayerModelPanel->m_hModel.Get();
if ( pPanelModel )
{
pPanelModel->m_nSkin = 8;
pPanelModel->SetModelColor( m_vecWinningPlayerColor.Head() );
m_vecWinningPlayerColor.Remove( 0 );
}
}
}
}
}
| 33.121348 | 164 | 0.621582 | Menoly12 |
0f265f6779c0fa8f54fe1197709f8ef4f11d5a61 | 82,955 | cc | C++ | zircon/system/utest/fidl/decoding_tests.cc | sunshinewithmoonlight/fuchsia-2003 | 02b23026dc7fecbad063210d5d45fa1b17feeb8b | [
"BSD-3-Clause"
] | null | null | null | zircon/system/utest/fidl/decoding_tests.cc | sunshinewithmoonlight/fuchsia-2003 | 02b23026dc7fecbad063210d5d45fa1b17feeb8b | [
"BSD-3-Clause"
] | null | null | null | zircon/system/utest/fidl/decoding_tests.cc | sunshinewithmoonlight/fuchsia-2003 | 02b23026dc7fecbad063210d5d45fa1b17feeb8b | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/fidl/coding.h>
#include <lib/zx/eventpair.h>
#include <stddef.h>
#include <zircon/syscalls.h>
#include <memory>
#include <unittest/unittest.h>
#include "fidl_coded_types.h"
#include "fidl_structs.h"
namespace fidl {
namespace {
// Some notes:
//
// - All tests of out-of-line bounded allocation overruns need to have
// another big out-of-line allocation following it. This
// distinguishes "the buffer is too small" from "the bits on the
// wire asked for more than the type allowed".
// TODO(kulakowski) Change the tests to check for more specific error
// values, once those are settled.
constexpr zx_handle_t dummy_handle_0 = static_cast<zx_handle_t>(23);
constexpr zx_handle_t dummy_handle_1 = static_cast<zx_handle_t>(24);
constexpr zx_handle_t dummy_handle_2 = static_cast<zx_handle_t>(25);
constexpr zx_handle_t dummy_handle_3 = static_cast<zx_handle_t>(26);
constexpr zx_handle_t dummy_handle_4 = static_cast<zx_handle_t>(27);
constexpr zx_handle_t dummy_handle_5 = static_cast<zx_handle_t>(28);
constexpr zx_handle_t dummy_handle_6 = static_cast<zx_handle_t>(29);
constexpr zx_handle_t dummy_handle_7 = static_cast<zx_handle_t>(30);
constexpr zx_handle_t dummy_handle_8 = static_cast<zx_handle_t>(31);
constexpr zx_handle_t dummy_handle_9 = static_cast<zx_handle_t>(32);
constexpr zx_handle_t dummy_handle_10 = static_cast<zx_handle_t>(33);
constexpr zx_handle_t dummy_handle_11 = static_cast<zx_handle_t>(34);
constexpr zx_handle_t dummy_handle_12 = static_cast<zx_handle_t>(35);
constexpr zx_handle_t dummy_handle_13 = static_cast<zx_handle_t>(36);
constexpr zx_handle_t dummy_handle_14 = static_cast<zx_handle_t>(37);
constexpr zx_handle_t dummy_handle_15 = static_cast<zx_handle_t>(38);
constexpr zx_handle_t dummy_handle_16 = static_cast<zx_handle_t>(39);
constexpr zx_handle_t dummy_handle_17 = static_cast<zx_handle_t>(40);
constexpr zx_handle_t dummy_handle_18 = static_cast<zx_handle_t>(41);
constexpr zx_handle_t dummy_handle_19 = static_cast<zx_handle_t>(42);
constexpr zx_handle_t dummy_handle_20 = static_cast<zx_handle_t>(43);
constexpr zx_handle_t dummy_handle_21 = static_cast<zx_handle_t>(44);
constexpr zx_handle_t dummy_handle_22 = static_cast<zx_handle_t>(45);
constexpr zx_handle_t dummy_handle_23 = static_cast<zx_handle_t>(46);
constexpr zx_handle_t dummy_handle_24 = static_cast<zx_handle_t>(47);
constexpr zx_handle_t dummy_handle_25 = static_cast<zx_handle_t>(48);
constexpr zx_handle_t dummy_handle_26 = static_cast<zx_handle_t>(49);
constexpr zx_handle_t dummy_handle_27 = static_cast<zx_handle_t>(50);
constexpr zx_handle_t dummy_handle_28 = static_cast<zx_handle_t>(51);
constexpr zx_handle_t dummy_handle_29 = static_cast<zx_handle_t>(52);
// All sizes in fidl encoding tables are 32 bits. The fidl compiler
// normally enforces this. Check manually in manual tests.
template <typename T, size_t N>
uint32_t ArrayCount(T const (&array)[N]) {
static_assert(N < UINT32_MAX, "Array is too large!");
return N;
}
template <typename T, size_t N>
uint32_t ArraySize(T const (&array)[N]) {
static_assert(sizeof(array) < UINT32_MAX, "Array is too large!");
return sizeof(array);
}
// Check if the other end of the eventpair is valid
bool IsPeerValid(const zx::unowned_eventpair handle) {
zx_signals_t observed_signals = {};
switch (handle->wait_one(ZX_EVENTPAIR_PEER_CLOSED, zx::deadline_after(zx::msec(1)),
&observed_signals)) {
case ZX_ERR_TIMED_OUT:
// timeout implies peer-closed was not observed
return true;
case ZX_OK:
return (observed_signals & ZX_EVENTPAIR_PEER_CLOSED) == 0;
default:
return false;
}
}
bool decode_null_decode_parameters() {
BEGIN_TEST;
zx_handle_t handles[] = {static_cast<zx_handle_t>(23)};
// Null message type.
{
nonnullable_handle_message_layout message = {};
message.inline_struct.handle = FIDL_HANDLE_PRESENT;
const char* error = nullptr;
auto status = fidl_decode(nullptr, &message, sizeof(nonnullable_handle_message_layout), handles,
ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
}
// Null message.
{
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_message_type, nullptr,
sizeof(nonnullable_handle_message_layout), handles,
ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
}
// Null handles, for a message that has a handle.
{
nonnullable_handle_message_layout message = {};
message.inline_struct.handle = FIDL_HANDLE_PRESENT;
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_message_type, &message,
sizeof(nonnullable_handle_message_layout), nullptr, 0, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
}
// Null handles but positive handle count.
{
nonnullable_handle_message_layout message = {};
message.inline_struct.handle = FIDL_HANDLE_PRESENT;
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_message_type, &message,
sizeof(nonnullable_handle_message_layout), nullptr, 1, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
}
// A null error string pointer is ok, though.
{
auto status = fidl_decode(nullptr, nullptr, 0u, nullptr, 0u, nullptr);
EXPECT_NE(status, ZX_OK);
}
// A null error is also ok in success cases.
{
nonnullable_handle_message_layout message = {};
message.inline_struct.handle = FIDL_HANDLE_PRESENT;
auto status = fidl_decode(&nonnullable_handle_message_type, &message,
sizeof(nonnullable_handle_message_layout), handles,
ArrayCount(handles), nullptr);
EXPECT_EQ(status, ZX_OK);
}
END_TEST;
}
bool decode_single_present_handle_unaligned_error() {
BEGIN_TEST;
// Test a short, unaligned version of nonnullable message
// handle. All fidl message objects should be 8 byte aligned.
//
// We use a byte array rather than fidl_message_header_t to avoid
// aligning to 8 bytes.
struct unaligned_nonnullable_handle_inline_data {
uint8_t header[sizeof(fidl_message_header_t)];
zx_handle_t handle;
};
struct unaligned_nonnullable_handle_message_layout {
unaligned_nonnullable_handle_inline_data inline_struct;
};
unaligned_nonnullable_handle_message_layout message = {};
message.inline_struct.handle = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
};
// Decoding the unaligned version of the struct should fail.
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_message_type, &message, sizeof(message), handles,
ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_present_nonnullable_string_unaligned_error() {
BEGIN_TEST;
unbounded_nonnullable_string_message_layout message = {};
message.inline_struct.string = fidl_string_t{6, reinterpret_cast<char*>(FIDL_ALLOC_PRESENT)};
memcpy(message.data, "hello!", 6);
// Copy the message to unaligned storage one byte off from true alignment
unbounded_nonnullable_string_message_layout message_storage[2];
uint8_t* unaligned_ptr = reinterpret_cast<uint8_t*>(&message_storage[0]) + 1;
memcpy(unaligned_ptr, &message, sizeof(message));
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nonnullable_string_message_type, unaligned_ptr,
sizeof(message), nullptr, 0, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
ASSERT_STR_STR(error, "must be aligned to FIDL_ALIGNMENT");
END_TEST;
}
bool decode_single_present_handle() {
BEGIN_TEST;
nonnullable_handle_message_layout message = {};
message.inline_struct.handle = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
};
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_message_type, &message, sizeof(message), handles,
ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.handle, dummy_handle_0);
END_TEST;
}
bool decode_single_present_handle_check_trailing_padding() {
BEGIN_TEST;
// There are four padding bytes; any of them not being zero should lead to an error.
for (size_t i = 0; i < 4; i++) {
constexpr size_t kBufferSize = sizeof(nonnullable_handle_message_layout);
nonnullable_handle_message_layout message;
uint8_t* buffer = reinterpret_cast<uint8_t*>(&message);
memset(buffer, 0, kBufferSize);
message.inline_struct.handle = FIDL_HANDLE_PRESENT;
buffer[kBufferSize - 4 + i] = 0xAA;
zx_handle_t handles[] = {
dummy_handle_0,
};
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_message_type, &message, kBufferSize, handles,
ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_STR_EQ(error, "non-zero padding bytes detected during decoding");
}
END_TEST;
}
bool decode_too_many_handles_specified_error() {
BEGIN_TEST;
nonnullable_handle_message_layout message = {};
message.inline_struct.handle = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
ZX_HANDLE_INVALID,
};
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_message_type, &message, sizeof(message), handles,
ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
EXPECT_EQ(message.inline_struct.handle, dummy_handle_0);
END_TEST;
}
bool decode_too_many_handles_specified_should_close_handles() {
BEGIN_TEST;
nonnullable_handle_message_layout message = {};
message.inline_struct.handle = FIDL_HANDLE_PRESENT;
zx::eventpair ep0, ep1;
ASSERT_EQ(zx::eventpair::create(0, &ep0, &ep1), ZX_OK);
zx_handle_t handles[] = {
ep0.get(),
ZX_HANDLE_INVALID,
};
ASSERT_TRUE(IsPeerValid(zx::unowned_eventpair(ep1)));
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_message_type, &message, sizeof(message), handles,
ArrayCount(handles), &error);
ASSERT_EQ(status, ZX_ERR_INVALID_ARGS);
ASSERT_NONNULL(error);
ASSERT_EQ(message.inline_struct.handle, ep0.get());
ASSERT_FALSE(IsPeerValid(zx::unowned_eventpair(ep1)));
// When the test succeeds, |ep0| is closed by the decoder.
zx_handle_t unused = ep0.release();
(void)unused;
END_TEST;
}
bool decode_too_many_bytes_specified_should_close_handles() {
BEGIN_TEST;
constexpr size_t kSizeTooBig = sizeof(nonnullable_handle_message_layout) * 2;
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(kSizeTooBig);
nonnullable_handle_message_layout& message =
*reinterpret_cast<nonnullable_handle_message_layout*>(buffer.get());
message.inline_struct.handle = FIDL_HANDLE_PRESENT;
zx::eventpair ep0, ep1;
ASSERT_EQ(zx::eventpair::create(0, &ep0, &ep1), ZX_OK);
zx_handle_t handles[] = {
ep0.get(),
};
ASSERT_TRUE(IsPeerValid(zx::unowned_eventpair(ep1)));
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_message_type, &message, kSizeTooBig, handles,
ArrayCount(handles), &error);
ASSERT_EQ(status, ZX_ERR_INVALID_ARGS);
ASSERT_NONNULL(error);
ASSERT_EQ(message.inline_struct.handle, ep0.get());
ASSERT_FALSE(IsPeerValid(zx::unowned_eventpair(ep1)));
// When the test succeeds, |ep0| is closed by the decoder.
zx_handle_t unused = ep0.release();
(void)unused;
END_TEST;
}
bool decode_multiple_present_handles() {
BEGIN_TEST;
multiple_nonnullable_handles_message_layout message = {};
message.inline_struct.handle_0 = FIDL_HANDLE_PRESENT;
message.inline_struct.handle_1 = FIDL_HANDLE_PRESENT;
message.inline_struct.handle_2 = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
};
const char* error = nullptr;
auto status = fidl_decode(&multiple_nonnullable_handles_message_type, &message, sizeof(message),
handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.data_0, 0u);
EXPECT_EQ(message.inline_struct.handle_0, dummy_handle_0);
EXPECT_EQ(message.inline_struct.data_1, 0u);
EXPECT_EQ(message.inline_struct.handle_1, dummy_handle_1);
EXPECT_EQ(message.inline_struct.handle_2, dummy_handle_2);
EXPECT_EQ(message.inline_struct.data_2, 0u);
END_TEST;
}
bool decode_single_absent_handle() {
BEGIN_TEST;
nullable_handle_message_layout message = {};
message.inline_struct.handle = FIDL_HANDLE_ABSENT;
const char* error = nullptr;
auto status =
fidl_decode(&nullable_handle_message_type, &message, sizeof(message), nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.handle, ZX_HANDLE_INVALID);
END_TEST;
}
bool decode_multiple_absent_handles() {
BEGIN_TEST;
multiple_nullable_handles_message_layout message = {};
message.inline_struct.handle_0 = FIDL_HANDLE_ABSENT;
message.inline_struct.handle_1 = FIDL_HANDLE_ABSENT;
message.inline_struct.handle_2 = FIDL_HANDLE_ABSENT;
const char* error = nullptr;
auto status = fidl_decode(&multiple_nullable_handles_message_type, &message, sizeof(message),
nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.data_0, 0u);
EXPECT_EQ(message.inline_struct.handle_0, ZX_HANDLE_INVALID);
EXPECT_EQ(message.inline_struct.data_1, 0u);
EXPECT_EQ(message.inline_struct.handle_1, ZX_HANDLE_INVALID);
EXPECT_EQ(message.inline_struct.handle_2, ZX_HANDLE_INVALID);
EXPECT_EQ(message.inline_struct.data_2, 0u);
END_TEST;
}
bool decode_array_of_present_handles() {
BEGIN_TEST;
array_of_nonnullable_handles_message_layout message = {};
message.inline_struct.handles[0] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[1] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[2] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[3] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
dummy_handle_3,
};
const char* error = nullptr;
auto status = fidl_decode(&array_of_nonnullable_handles_message_type, &message, sizeof(message),
handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.handles[0], dummy_handle_0);
EXPECT_EQ(message.inline_struct.handles[1], dummy_handle_1);
EXPECT_EQ(message.inline_struct.handles[2], dummy_handle_2);
EXPECT_EQ(message.inline_struct.handles[3], dummy_handle_3);
END_TEST;
}
bool decode_array_of_present_handles_error_closes_handles() {
BEGIN_TEST;
array_of_nonnullable_handles_message_layout message = {};
zx_handle_t handle_pairs[4][2];
// Use eventpairs so that we can know for sure that handles were closed by fidl_decode.
for (uint32_t i = 0; i < ArrayCount(handle_pairs); ++i) {
ASSERT_EQ(zx_eventpair_create(0u, &handle_pairs[i][0], &handle_pairs[i][1]), ZX_OK);
}
message.inline_struct.handles[0] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[1] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[2] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[3] = FIDL_HANDLE_PRESENT;
zx_handle_t out_of_line_handles[4] = {
handle_pairs[0][0],
handle_pairs[1][0],
handle_pairs[2][0],
handle_pairs[3][0],
};
const char* error = nullptr;
auto status = fidl_decode(&array_of_nonnullable_handles_message_type, &message, sizeof(message),
out_of_line_handles,
// -2 makes this invalid.
ArrayCount(out_of_line_handles) - 2, &error);
// Should fail because we we pass in a max_handles < the actual number of handles.
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
// All the handles that we told fidl_decode about should be closed.
uint32_t i;
for (i = 0; i < ArrayCount(handle_pairs) - 2; ++i) {
zx_signals_t observed_signals;
EXPECT_EQ(zx_object_wait_one(handle_pairs[i][1], ZX_EVENTPAIR_PEER_CLOSED,
1, // deadline shouldn't matter, should return immediately.
&observed_signals),
ZX_OK);
EXPECT_EQ(observed_signals & ZX_EVENTPAIR_PEER_CLOSED, ZX_EVENTPAIR_PEER_CLOSED);
EXPECT_EQ(zx_handle_close(handle_pairs[i][1]), ZX_OK); // [i][0] was closed by fidl_encode.
}
// But the other ones should not be.
for (; i < ArrayCount(handle_pairs); ++i) {
zx_signals_t observed_signals;
EXPECT_EQ(zx_object_wait_one(handle_pairs[i][1], ZX_EVENTPAIR_PEER_CLOSED,
zx_clock_get_monotonic() + 1, &observed_signals),
ZX_ERR_TIMED_OUT);
EXPECT_EQ(observed_signals & ZX_EVENTPAIR_PEER_CLOSED, 0);
EXPECT_EQ(zx_handle_close(handle_pairs[i][0]), ZX_OK);
EXPECT_EQ(zx_handle_close(handle_pairs[i][1]), ZX_OK);
}
END_TEST;
}
bool decode_array_of_nonnullable_handles_some_absent_error() {
BEGIN_TEST;
array_of_nonnullable_handles_message_layout message = {};
message.inline_struct.handles[0] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[1] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[2] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[3] = FIDL_HANDLE_ABSENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
dummy_handle_3,
};
const char* error = nullptr;
auto status = fidl_decode(&array_of_nonnullable_handles_message_type, &message, sizeof(message),
handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_array_of_nullable_handles() {
BEGIN_TEST;
array_of_nullable_handles_message_layout message = {};
message.inline_struct.handles[0] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[1] = FIDL_HANDLE_ABSENT;
message.inline_struct.handles[2] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[3] = FIDL_HANDLE_ABSENT;
message.inline_struct.handles[4] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
};
const char* error = nullptr;
auto status = fidl_decode(&array_of_nullable_handles_message_type, &message, sizeof(message),
handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.handles[0], dummy_handle_0);
EXPECT_EQ(message.inline_struct.handles[1], ZX_HANDLE_INVALID);
EXPECT_EQ(message.inline_struct.handles[2], dummy_handle_1);
EXPECT_EQ(message.inline_struct.handles[3], ZX_HANDLE_INVALID);
EXPECT_EQ(message.inline_struct.handles[4], dummy_handle_2);
END_TEST;
}
bool decode_array_of_nullable_handles_with_insufficient_handles_error() {
BEGIN_TEST;
array_of_nullable_handles_message_layout message = {};
message.inline_struct.handles[0] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[1] = FIDL_HANDLE_ABSENT;
message.inline_struct.handles[2] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[3] = FIDL_HANDLE_ABSENT;
message.inline_struct.handles[4] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
};
const char* error = nullptr;
auto status = fidl_decode(&array_of_nullable_handles_message_type, &message, sizeof(message),
handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_array_of_array_of_present_handles() {
BEGIN_TEST;
array_of_array_of_nonnullable_handles_message_layout message = {};
message.inline_struct.handles[0][0] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[0][1] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[0][2] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[0][3] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[1][0] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[1][1] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[1][2] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[1][3] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[2][0] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[2][1] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[2][2] = FIDL_HANDLE_PRESENT;
message.inline_struct.handles[2][3] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0, dummy_handle_1, dummy_handle_2, dummy_handle_3,
dummy_handle_4, dummy_handle_5, dummy_handle_6, dummy_handle_7,
dummy_handle_8, dummy_handle_9, dummy_handle_10, dummy_handle_11,
};
const char* error = nullptr;
auto status = fidl_decode(&array_of_array_of_nonnullable_handles_message_type, &message,
sizeof(message), handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.handles[0][0], dummy_handle_0);
EXPECT_EQ(message.inline_struct.handles[0][1], dummy_handle_1);
EXPECT_EQ(message.inline_struct.handles[0][2], dummy_handle_2);
EXPECT_EQ(message.inline_struct.handles[0][3], dummy_handle_3);
EXPECT_EQ(message.inline_struct.handles[1][0], dummy_handle_4);
EXPECT_EQ(message.inline_struct.handles[1][1], dummy_handle_5);
EXPECT_EQ(message.inline_struct.handles[1][2], dummy_handle_6);
EXPECT_EQ(message.inline_struct.handles[1][3], dummy_handle_7);
EXPECT_EQ(message.inline_struct.handles[2][0], dummy_handle_8);
EXPECT_EQ(message.inline_struct.handles[2][1], dummy_handle_9);
EXPECT_EQ(message.inline_struct.handles[2][2], dummy_handle_10);
EXPECT_EQ(message.inline_struct.handles[2][3], dummy_handle_11);
END_TEST;
}
bool decode_out_of_line_array() {
BEGIN_TEST;
out_of_line_array_of_nonnullable_handles_message_layout message = {};
message.inline_struct.maybe_array =
reinterpret_cast<array_of_nonnullable_handles*>(FIDL_ALLOC_PRESENT);
message.data.handles[0] = FIDL_HANDLE_PRESENT;
message.data.handles[1] = FIDL_HANDLE_PRESENT;
message.data.handles[2] = FIDL_HANDLE_PRESENT;
message.data.handles[3] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
dummy_handle_3,
};
const char* error = nullptr;
auto status = fidl_decode(&out_of_line_array_of_nonnullable_handles_message_type, &message,
sizeof(message), handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto array_ptr = message.inline_struct.maybe_array;
EXPECT_NONNULL(array_ptr);
EXPECT_EQ(array_ptr->handles[0], dummy_handle_0);
EXPECT_EQ(array_ptr->handles[1], dummy_handle_1);
EXPECT_EQ(array_ptr->handles[2], dummy_handle_2);
EXPECT_EQ(array_ptr->handles[3], dummy_handle_3);
END_TEST;
}
bool decode_present_nonnullable_string() {
BEGIN_TEST;
unbounded_nonnullable_string_message_layout message = {};
message.inline_struct.string = fidl_string_t{6, reinterpret_cast<char*>(FIDL_ALLOC_PRESENT)};
memcpy(message.data, "hello!", 6);
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nonnullable_string_message_type, &message, sizeof(message),
nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.string.size, 6);
EXPECT_EQ(message.inline_struct.string.data[0], 'h');
EXPECT_EQ(message.inline_struct.string.data[1], 'e');
EXPECT_EQ(message.inline_struct.string.data[2], 'l');
EXPECT_EQ(message.inline_struct.string.data[3], 'l');
EXPECT_EQ(message.inline_struct.string.data[4], 'o');
EXPECT_EQ(message.inline_struct.string.data[5], '!');
END_TEST;
}
bool decode_present_nullable_string() {
BEGIN_TEST;
unbounded_nullable_string_message_layout message = {};
message.inline_struct.string = fidl_string_t{6, reinterpret_cast<char*>(FIDL_ALLOC_PRESENT)};
memcpy(message.data, "hello!", 6);
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nullable_string_message_type, &message, sizeof(message),
nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.string.size, 6);
EXPECT_EQ(message.inline_struct.string.data[0], 'h');
EXPECT_EQ(message.inline_struct.string.data[1], 'e');
EXPECT_EQ(message.inline_struct.string.data[2], 'l');
EXPECT_EQ(message.inline_struct.string.data[3], 'l');
EXPECT_EQ(message.inline_struct.string.data[4], 'o');
EXPECT_EQ(message.inline_struct.string.data[5], '!');
END_TEST;
}
bool decode_multiple_present_nullable_string() {
BEGIN_TEST;
// Among other things, this test ensures we handle out-of-line
// alignment to FIDL_ALIGNMENT (i.e., 8) bytes correctly.
multiple_nullable_strings_message_layout message;
memset(&message, 0, sizeof(message));
message.inline_struct.string = fidl_string_t{6, reinterpret_cast<char*>(FIDL_ALLOC_PRESENT)};
message.inline_struct.string2 = fidl_string_t{8, reinterpret_cast<char*>(FIDL_ALLOC_PRESENT)};
memcpy(message.data, "hello ", 6);
memcpy(message.data2, "world!!! ", 8);
const char* error = nullptr;
auto status = fidl_decode(&multiple_nullable_strings_message_type, &message, sizeof(message),
nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.string.size, 6);
EXPECT_EQ(message.inline_struct.string.data[0], 'h');
EXPECT_EQ(message.inline_struct.string.data[1], 'e');
EXPECT_EQ(message.inline_struct.string.data[2], 'l');
EXPECT_EQ(message.inline_struct.string.data[3], 'l');
EXPECT_EQ(message.inline_struct.string.data[4], 'o');
EXPECT_EQ(message.inline_struct.string.data[5], ' ');
EXPECT_EQ(message.inline_struct.string2.size, 8);
EXPECT_EQ(message.inline_struct.string2.data[0], 'w');
EXPECT_EQ(message.inline_struct.string2.data[1], 'o');
EXPECT_EQ(message.inline_struct.string2.data[2], 'r');
EXPECT_EQ(message.inline_struct.string2.data[3], 'l');
EXPECT_EQ(message.inline_struct.string2.data[4], 'd');
EXPECT_EQ(message.inline_struct.string2.data[5], '!');
EXPECT_EQ(message.inline_struct.string2.data[6], '!');
EXPECT_EQ(message.inline_struct.string2.data[7], '!');
EXPECT_EQ(message.inline_struct.string2.data[7], '!');
END_TEST;
}
bool decode_absent_nonnullable_string_error() {
BEGIN_TEST;
unbounded_nonnullable_string_message_layout message = {};
message.inline_struct.string = fidl_string_t{6, reinterpret_cast<char*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nonnullable_string_message_type, &message, sizeof(message),
nullptr, 0, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_absent_nullable_string() {
BEGIN_TEST;
unbounded_nullable_string_message_layout message = {};
message.inline_struct.string = fidl_string_t{0, reinterpret_cast<char*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nullable_string_message_type, &message,
sizeof(message.inline_struct), nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
END_TEST;
}
bool decode_present_nonnullable_bounded_string() {
BEGIN_TEST;
bounded_32_nonnullable_string_message_layout message = {};
message.inline_struct.string = fidl_string_t{6, reinterpret_cast<char*>(FIDL_ALLOC_PRESENT)};
memcpy(message.data, "hello!", 6);
const char* error = nullptr;
auto status = fidl_decode(&bounded_32_nonnullable_string_message_type, &message, sizeof(message),
nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.string.size, 6);
EXPECT_EQ(message.inline_struct.string.data[0], 'h');
EXPECT_EQ(message.inline_struct.string.data[1], 'e');
EXPECT_EQ(message.inline_struct.string.data[2], 'l');
EXPECT_EQ(message.inline_struct.string.data[3], 'l');
EXPECT_EQ(message.inline_struct.string.data[4], 'o');
EXPECT_EQ(message.inline_struct.string.data[5], '!');
END_TEST;
}
bool decode_present_nullable_bounded_string() {
BEGIN_TEST;
bounded_32_nullable_string_message_layout message = {};
message.inline_struct.string = fidl_string_t{6, reinterpret_cast<char*>(FIDL_ALLOC_PRESENT)};
memcpy(message.data, "hello!", 6);
const char* error = nullptr;
auto status = fidl_decode(&bounded_32_nullable_string_message_type, &message, sizeof(message),
nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.string.size, 6);
EXPECT_EQ(message.inline_struct.string.data[0], 'h');
EXPECT_EQ(message.inline_struct.string.data[1], 'e');
EXPECT_EQ(message.inline_struct.string.data[2], 'l');
EXPECT_EQ(message.inline_struct.string.data[3], 'l');
EXPECT_EQ(message.inline_struct.string.data[4], 'o');
EXPECT_EQ(message.inline_struct.string.data[5], '!');
END_TEST;
}
bool decode_absent_nonnullable_bounded_string_error() {
BEGIN_TEST;
bounded_32_nonnullable_string_message_layout message = {};
message.inline_struct.string = fidl_string_t{6, reinterpret_cast<char*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&bounded_32_nonnullable_string_message_type, &message, sizeof(message),
nullptr, 0, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_absent_nullable_bounded_string() {
BEGIN_TEST;
bounded_32_nullable_string_message_layout message = {};
message.inline_struct.string = fidl_string_t{0, reinterpret_cast<char*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&bounded_32_nullable_string_message_type, &message,
sizeof(message.inline_struct), nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
END_TEST;
}
bool decode_present_nonnullable_bounded_string_short_error() {
BEGIN_TEST;
multiple_short_nonnullable_strings_message_layout message = {};
message.inline_struct.string = fidl_string_t{6, reinterpret_cast<char*>(FIDL_ALLOC_PRESENT)};
message.inline_struct.string2 = fidl_string_t{8, reinterpret_cast<char*>(FIDL_ALLOC_PRESENT)};
memcpy(message.data, "hello ", 6);
memcpy(message.data2, "world! ", 6);
const char* error = nullptr;
auto status = fidl_decode(&multiple_short_nonnullable_strings_message_type, &message,
sizeof(message), nullptr, 0, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_present_nullable_bounded_string_short_error() {
BEGIN_TEST;
multiple_short_nullable_strings_message_layout message = {};
message.inline_struct.string = fidl_string_t{6, reinterpret_cast<char*>(FIDL_ALLOC_PRESENT)};
message.inline_struct.string2 = fidl_string_t{8, reinterpret_cast<char*>(FIDL_ALLOC_PRESENT)};
memcpy(message.data, "hello ", 6);
memcpy(message.data2, "world! ", 6);
const char* error = nullptr;
auto status = fidl_decode(&multiple_short_nullable_strings_message_type, &message,
sizeof(message), nullptr, 0, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_vector_with_huge_count() {
BEGIN_TEST;
unbounded_nonnullable_vector_of_uint32_message_layout message = {};
// (2^30 + 4) * 4 (4 == sizeof(uint32_t)) overflows to 16 when stored as uint32_t.
// We want 16 because it happens to be the actual size of the vector data in the message,
// so we can trigger the overflow without triggering the "tried to claim too many bytes" or
// "didn't use all the bytes in the message" errors.
message.inline_struct.vector =
fidl_vector_t{(1ull << 30) + 4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nonnullable_vector_of_uint32_message_type, &message,
sizeof(message), nullptr, 0, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
const char expected_error_msg[] = "integer overflow calculating vector size";
EXPECT_STR_EQ(expected_error_msg, error, "wrong error msg");
auto message_uint32 = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_NONNULL(message_uint32);
END_TEST;
}
bool decode_present_nonnullable_vector_of_handles() {
BEGIN_TEST;
unbounded_nonnullable_vector_of_handles_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
message.handles[0] = FIDL_HANDLE_PRESENT;
message.handles[1] = FIDL_HANDLE_PRESENT;
message.handles[2] = FIDL_HANDLE_PRESENT;
message.handles[3] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
dummy_handle_3,
};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nonnullable_vector_of_handles_message_type, &message,
sizeof(message), handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto message_handles = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_EQ(message_handles[0], dummy_handle_0);
EXPECT_EQ(message_handles[1], dummy_handle_1);
EXPECT_EQ(message_handles[2], dummy_handle_2);
EXPECT_EQ(message_handles[3], dummy_handle_3);
END_TEST;
}
bool decode_present_nullable_vector_of_handles() {
BEGIN_TEST;
unbounded_nullable_vector_of_handles_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
message.handles[0] = FIDL_HANDLE_PRESENT;
message.handles[1] = FIDL_HANDLE_PRESENT;
message.handles[2] = FIDL_HANDLE_PRESENT;
message.handles[3] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
dummy_handle_3,
};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nullable_vector_of_handles_message_type, &message,
sizeof(message), handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto message_handles = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_EQ(message_handles[0], dummy_handle_0);
EXPECT_EQ(message_handles[1], dummy_handle_1);
EXPECT_EQ(message_handles[2], dummy_handle_2);
EXPECT_EQ(message_handles[3], dummy_handle_3);
END_TEST;
}
bool decode_absent_nonnullable_vector_of_handles_error() {
BEGIN_TEST;
unbounded_nonnullable_vector_of_handles_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_ABSENT)};
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
dummy_handle_3,
};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nonnullable_vector_of_handles_message_type, &message,
sizeof(message), handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_absent_nullable_vector_of_handles() {
BEGIN_TEST;
unbounded_nullable_vector_of_handles_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{0, reinterpret_cast<void*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nullable_vector_of_handles_message_type, &message,
sizeof(message.inline_struct), nullptr, 0u, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto message_handles = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_NULL(message_handles);
END_TEST;
}
bool decode_present_nonnullable_bounded_vector_of_handles() {
BEGIN_TEST;
bounded_32_nonnullable_vector_of_handles_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
message.handles[0] = FIDL_HANDLE_PRESENT;
message.handles[1] = FIDL_HANDLE_PRESENT;
message.handles[2] = FIDL_HANDLE_PRESENT;
message.handles[3] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
dummy_handle_3,
};
const char* error = nullptr;
auto status = fidl_decode(&bounded_32_nonnullable_vector_of_handles_message_type, &message,
sizeof(message), handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto message_handles = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_EQ(message_handles[0], dummy_handle_0);
EXPECT_EQ(message_handles[1], dummy_handle_1);
EXPECT_EQ(message_handles[2], dummy_handle_2);
EXPECT_EQ(message_handles[3], dummy_handle_3);
END_TEST;
}
bool decode_present_nullable_bounded_vector_of_handles() {
BEGIN_TEST;
bounded_32_nullable_vector_of_handles_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
message.handles[0] = FIDL_HANDLE_PRESENT;
message.handles[1] = FIDL_HANDLE_PRESENT;
message.handles[2] = FIDL_HANDLE_PRESENT;
message.handles[3] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
dummy_handle_3,
};
const char* error = nullptr;
auto status = fidl_decode(&bounded_32_nullable_vector_of_handles_message_type, &message,
sizeof(message), handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto message_handles = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_EQ(message_handles[0], dummy_handle_0);
EXPECT_EQ(message_handles[1], dummy_handle_1);
EXPECT_EQ(message_handles[2], dummy_handle_2);
EXPECT_EQ(message_handles[3], dummy_handle_3);
END_TEST;
}
bool decode_absent_nonnullable_bounded_vector_of_handles() {
BEGIN_TEST;
bounded_32_nonnullable_vector_of_handles_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&bounded_32_nonnullable_vector_of_handles_message_type, &message,
sizeof(message.inline_struct), nullptr, 0u, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
auto message_handles = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_NULL(message_handles);
END_TEST;
}
bool decode_absent_nullable_bounded_vector_of_handles() {
BEGIN_TEST;
bounded_32_nullable_vector_of_handles_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{0, reinterpret_cast<void*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&bounded_32_nullable_vector_of_handles_message_type, &message,
sizeof(message.inline_struct), nullptr, 0u, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto message_handles = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_NULL(message_handles);
END_TEST;
}
bool decode_present_nonnullable_bounded_vector_of_handles_short_error() {
BEGIN_TEST;
multiple_nonnullable_vectors_of_handles_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
message.inline_struct.vector2 = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
message.handles[0] = FIDL_HANDLE_PRESENT;
message.handles[1] = FIDL_HANDLE_PRESENT;
message.handles[2] = FIDL_HANDLE_PRESENT;
message.handles[3] = FIDL_HANDLE_PRESENT;
message.handles2[0] = FIDL_HANDLE_PRESENT;
message.handles2[1] = FIDL_HANDLE_PRESENT;
message.handles2[2] = FIDL_HANDLE_PRESENT;
message.handles2[3] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0, dummy_handle_1, dummy_handle_2, dummy_handle_3,
dummy_handle_4, dummy_handle_5, dummy_handle_6, dummy_handle_7,
};
const char* error = nullptr;
auto status = fidl_decode(&multiple_nonnullable_vectors_of_handles_message_type, &message,
sizeof(message), handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_present_nullable_bounded_vector_of_handles_short_error() {
BEGIN_TEST;
multiple_nullable_vectors_of_handles_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
message.inline_struct.vector2 = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
message.handles[0] = FIDL_HANDLE_PRESENT;
message.handles[1] = FIDL_HANDLE_PRESENT;
message.handles[2] = FIDL_HANDLE_PRESENT;
message.handles[3] = FIDL_HANDLE_PRESENT;
message.handles2[0] = FIDL_HANDLE_PRESENT;
message.handles2[1] = FIDL_HANDLE_PRESENT;
message.handles2[2] = FIDL_HANDLE_PRESENT;
message.handles2[3] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0, dummy_handle_1, dummy_handle_2, dummy_handle_3,
dummy_handle_4, dummy_handle_5, dummy_handle_6, dummy_handle_7,
};
const char* error = nullptr;
auto status = fidl_decode(&multiple_nullable_vectors_of_handles_message_type, &message,
sizeof(message), handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_present_nonnullable_vector_of_uint32() {
BEGIN_TEST;
unbounded_nonnullable_vector_of_uint32_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nonnullable_vector_of_uint32_message_type, &message,
sizeof(message), nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto message_uint32 = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_NONNULL(message_uint32);
END_TEST;
}
bool decode_present_nullable_vector_of_uint32() {
BEGIN_TEST;
unbounded_nullable_vector_of_uint32_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nullable_vector_of_uint32_message_type, &message,
sizeof(message), nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto message_uint32 = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_NONNULL(message_uint32);
END_TEST;
}
bool decode_absent_nonnullable_vector_of_uint32_error() {
BEGIN_TEST;
unbounded_nonnullable_vector_of_uint32_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nonnullable_vector_of_uint32_message_type, &message,
sizeof(message.inline_struct), nullptr, 0, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_absent_and_empty_nonnullable_vector_of_uint32_error() {
BEGIN_TEST;
unbounded_nonnullable_vector_of_uint32_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{0, reinterpret_cast<void*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nonnullable_vector_of_uint32_message_type, &message,
sizeof(message.inline_struct), nullptr, 0, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_absent_nullable_vector_of_uint32() {
BEGIN_TEST;
unbounded_nullable_vector_of_uint32_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{0, reinterpret_cast<void*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nullable_vector_of_uint32_message_type, &message,
sizeof(message.inline_struct), nullptr, 0u, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto message_uint32 = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_NULL(message_uint32);
END_TEST;
}
bool decode_absent_nullable_vector_of_uint32_non_zero_length_error() {
BEGIN_TEST;
unbounded_nullable_vector_of_uint32_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&unbounded_nullable_vector_of_uint32_message_type, &message,
sizeof(message.inline_struct), nullptr, 0u, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_present_nonnullable_bounded_vector_of_uint32() {
BEGIN_TEST;
bounded_32_nonnullable_vector_of_uint32_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
const char* error = nullptr;
auto status = fidl_decode(&bounded_32_nonnullable_vector_of_uint32_message_type, &message,
sizeof(message), nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto message_uint32 = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_NONNULL(message_uint32);
END_TEST;
}
bool decode_present_nullable_bounded_vector_of_uint32() {
BEGIN_TEST;
bounded_32_nullable_vector_of_uint32_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
const char* error = nullptr;
auto status = fidl_decode(&bounded_32_nullable_vector_of_uint32_message_type, &message,
sizeof(message), nullptr, 0, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto message_uint32 = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_NONNULL(message_uint32);
END_TEST;
}
bool decode_absent_nonnullable_bounded_vector_of_uint32() {
BEGIN_TEST;
bounded_32_nonnullable_vector_of_uint32_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&bounded_32_nonnullable_vector_of_uint32_message_type, &message,
sizeof(message.inline_struct), nullptr, 0u, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
auto message_uint32 = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_NULL(message_uint32);
END_TEST;
}
bool decode_absent_nullable_bounded_vector_of_uint32() {
BEGIN_TEST;
bounded_32_nullable_vector_of_uint32_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{0, reinterpret_cast<void*>(FIDL_ALLOC_ABSENT)};
const char* error = nullptr;
auto status = fidl_decode(&bounded_32_nullable_vector_of_uint32_message_type, &message,
sizeof(message.inline_struct), nullptr, 0u, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
auto message_uint32 = reinterpret_cast<zx_handle_t*>(message.inline_struct.vector.data);
EXPECT_NULL(message_uint32);
END_TEST;
}
bool decode_present_nonnullable_bounded_vector_of_uint32_short_error() {
BEGIN_TEST;
multiple_nonnullable_vectors_of_uint32_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
message.inline_struct.vector2 = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
const char* error = nullptr;
auto status = fidl_decode(&multiple_nonnullable_vectors_of_uint32_message_type, &message,
sizeof(message), nullptr, 0, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_present_nullable_bounded_vector_of_uint32_short_error() {
BEGIN_TEST;
multiple_nullable_vectors_of_uint32_message_layout message = {};
message.inline_struct.vector = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
message.inline_struct.vector2 = fidl_vector_t{4, reinterpret_cast<void*>(FIDL_ALLOC_PRESENT)};
const char* error = nullptr;
auto status = fidl_decode(&multiple_nullable_vectors_of_uint32_message_type, &message,
sizeof(message), nullptr, 0, &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_bad_tagged_union_error() {
BEGIN_TEST;
nonnullable_handle_union_message_layout message = {};
message.inline_struct.data.tag = 43u;
message.inline_struct.data.handle = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
};
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_union_message_type, &message, sizeof(message),
handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
END_TEST;
}
bool decode_single_membered_present_nonnullable_union() {
BEGIN_TEST;
nonnullable_handle_union_message_layout message = {};
message.inline_struct.data.tag = nonnullable_handle_union_kHandle;
message.inline_struct.data.handle = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
};
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_union_message_type, &message, sizeof(message),
handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.data.tag, nonnullable_handle_union_kHandle);
EXPECT_EQ(message.inline_struct.data.handle, dummy_handle_0);
END_TEST;
}
bool decode_many_membered_present_nonnullable_union() {
BEGIN_TEST;
array_of_nonnullable_handles_union_message_layout message;
memset(&message, 0, sizeof(message));
message.inline_struct.data.tag = array_of_nonnullable_handles_union_kArrayOfArrayOfHandles;
message.inline_struct.data.array_of_array_of_handles[0][0] = FIDL_HANDLE_PRESENT;
message.inline_struct.data.array_of_array_of_handles[0][1] = FIDL_HANDLE_PRESENT;
message.inline_struct.data.array_of_array_of_handles[1][0] = FIDL_HANDLE_PRESENT;
message.inline_struct.data.array_of_array_of_handles[1][1] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
dummy_handle_3,
};
const char* error = nullptr;
auto status = fidl_decode(&array_of_nonnullable_handles_union_message_type, &message,
sizeof(message), handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.data.tag,
array_of_nonnullable_handles_union_kArrayOfArrayOfHandles);
EXPECT_EQ(message.inline_struct.data.array_of_array_of_handles[0][0], dummy_handle_0);
EXPECT_EQ(message.inline_struct.data.array_of_array_of_handles[0][1], dummy_handle_1);
EXPECT_EQ(message.inline_struct.data.array_of_array_of_handles[1][0], dummy_handle_2);
EXPECT_EQ(message.inline_struct.data.array_of_array_of_handles[1][1], dummy_handle_3);
END_TEST;
}
bool decode_many_membered_present_nonnullable_union_check_padding() {
BEGIN_TEST;
// 4 bytes tag + 16 bytes largest variant + 4 bytes padding = 24
constexpr size_t kUnionSize = 24;
static_assert(sizeof(array_of_nonnullable_handles_union_message_layout::inline_struct.data) ==
kUnionSize);
// The union comes after the 16 byte message header.
constexpr size_t kUnionOffset = 16;
// 4 bytes tag
constexpr size_t kHandleOffset = 4;
// Any single padding byte being non-zero should result in an error.
for (size_t i = kHandleOffset + sizeof(zx_handle_t); i < kUnionSize; i++) {
constexpr size_t kBufferSize = sizeof(array_of_nonnullable_handles_union_message_layout);
array_of_nonnullable_handles_union_message_layout message;
uint8_t* buffer = reinterpret_cast<uint8_t*>(&message);
memset(buffer, 0, kBufferSize);
ASSERT_EQ(reinterpret_cast<uint8_t*>(&message.inline_struct.data) -
reinterpret_cast<uint8_t*>(&message),
kUnionOffset);
ASSERT_EQ(reinterpret_cast<uint8_t*>(&message.inline_struct.data.handle) -
reinterpret_cast<uint8_t*>(&message.inline_struct.data),
kHandleOffset);
message.inline_struct.data.tag = array_of_nonnullable_handles_union_kHandle;
message.inline_struct.data.handle = FIDL_HANDLE_PRESENT;
buffer[kUnionOffset + i] = 0xAA;
zx_handle_t handles[] = {
dummy_handle_0,
};
const char* error = nullptr;
auto status = fidl_decode(&array_of_nonnullable_handles_union_message_type, &message,
kBufferSize, handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_STR_EQ(error, "non-zero padding bytes detected during decoding");
}
END_TEST;
}
bool decode_single_membered_present_nullable_union() {
BEGIN_TEST;
nonnullable_handle_union_ptr_message_layout message = {};
message.inline_struct.data = reinterpret_cast<nonnullable_handle_union*>(FIDL_ALLOC_PRESENT);
message.data.tag = nonnullable_handle_union_kHandle;
message.data.handle = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
};
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_union_ptr_message_type, &message, sizeof(message),
handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.data, &message.data);
EXPECT_EQ(message.inline_struct.data->tag, nonnullable_handle_union_kHandle);
EXPECT_EQ(message.inline_struct.data->handle, dummy_handle_0);
END_TEST;
}
bool decode_many_membered_present_nullable_union() {
BEGIN_TEST;
array_of_nonnullable_handles_union_ptr_message_layout message;
memset(&message, 0, sizeof(message));
message.inline_struct.data =
reinterpret_cast<array_of_nonnullable_handles_union*>(FIDL_ALLOC_PRESENT);
message.data.tag = array_of_nonnullable_handles_union_kArrayOfArrayOfHandles;
message.data.array_of_array_of_handles[0][0] = FIDL_HANDLE_PRESENT;
message.data.array_of_array_of_handles[0][1] = FIDL_HANDLE_PRESENT;
message.data.array_of_array_of_handles[1][0] = FIDL_HANDLE_PRESENT;
message.data.array_of_array_of_handles[1][1] = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
dummy_handle_3,
};
const char* error = nullptr;
auto status = fidl_decode(&array_of_nonnullable_handles_union_ptr_message_type, &message,
sizeof(message), handles, ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_EQ(message.inline_struct.data, &message.data);
EXPECT_EQ(message.inline_struct.data->tag,
array_of_nonnullable_handles_union_kArrayOfArrayOfHandles);
EXPECT_EQ(message.inline_struct.data->array_of_array_of_handles[0][0], dummy_handle_0);
EXPECT_EQ(message.inline_struct.data->array_of_array_of_handles[0][1], dummy_handle_1);
EXPECT_EQ(message.inline_struct.data->array_of_array_of_handles[1][0], dummy_handle_2);
EXPECT_EQ(message.inline_struct.data->array_of_array_of_handles[1][1], dummy_handle_3);
END_TEST;
}
bool decode_single_membered_absent_nullable_union() {
BEGIN_TEST;
nonnullable_handle_union_ptr_message_layout message = {};
message.inline_struct.data = reinterpret_cast<nonnullable_handle_union*>(FIDL_ALLOC_ABSENT);
const char* error = nullptr;
auto status = fidl_decode(&nonnullable_handle_union_ptr_message_type, &message,
sizeof(message.inline_struct), nullptr, 0u, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_NULL(message.inline_struct.data);
END_TEST;
}
bool decode_many_membered_absent_nullable_union() {
BEGIN_TEST;
array_of_nonnullable_handles_union_ptr_message_layout message = {};
message.inline_struct.data =
reinterpret_cast<array_of_nonnullable_handles_union*>(FIDL_ALLOC_ABSENT);
const char* error = nullptr;
auto status = fidl_decode(&array_of_nonnullable_handles_union_ptr_message_type, &message,
sizeof(message.inline_struct), nullptr, 0u, &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
EXPECT_NULL(message.inline_struct.data);
END_TEST;
}
bool decode_nested_nonnullable_structs() {
BEGIN_TEST;
nested_structs_message_layout message = {};
message.inline_struct.l0.handle_0 = FIDL_HANDLE_PRESENT;
message.inline_struct.l0.l1.handle_1 = FIDL_HANDLE_PRESENT;
message.inline_struct.l0.l1.l2.handle_2 = FIDL_HANDLE_PRESENT;
message.inline_struct.l0.l1.l2.l3.handle_3 = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
dummy_handle_3,
};
const char* error = nullptr;
auto status = fidl_decode(&nested_structs_message_type, &message, sizeof(message), handles,
ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
// Note the traversal order! l1 -> l3 -> l2 -> l0
EXPECT_EQ(message.inline_struct.l0.l1.handle_1, dummy_handle_0);
EXPECT_EQ(message.inline_struct.l0.l1.l2.l3.handle_3, dummy_handle_1);
EXPECT_EQ(message.inline_struct.l0.l1.l2.handle_2, dummy_handle_2);
EXPECT_EQ(message.inline_struct.l0.handle_0, dummy_handle_3);
END_TEST;
}
bool decode_nested_nonnullable_structs_check_padding() {
BEGIN_TEST;
// Wire-format:
// message
// - 16 bytes header
// + struct_level_0 ------------- offset 16 = 4 * 4
// - uint64_t
// + struct_level_1 ----------- offset 24 = 4 * 6
// - zx_handle_t
// - (4 bytes padding) ------ offset 28 = 4 * 7
// + struct_level_2 --------- offset 32 = 4 * 8
// - uint64_t
// + struct_level_3 ------- offset 40 = 4 * 10
// - uint32_t
// - zx_handle_t
// - zx_handle_t
// - (4 bytes padding) ---- offset 52 = 4 * 13
// - uint64_t
// - zx_handle_t
// - (4 bytes padding) -------- offset 68 = 4 * 17
static_assert(sizeof(nested_structs_message_layout) == 68 + 4);
// Hence the padding bytes are located at:
size_t padding_offsets[] = {
28, 29, 30, 31, 52, 53, 54, 55, 68, 69, 70, 71,
};
for (const auto padding_offset : padding_offsets) {
constexpr size_t kBufferSize = sizeof(nested_structs_message_layout);
nested_structs_message_layout message;
uint8_t* buffer = reinterpret_cast<uint8_t*>(&message);
memset(buffer, 0, kBufferSize);
message.inline_struct.l0.handle_0 = FIDL_HANDLE_PRESENT;
message.inline_struct.l0.l1.handle_1 = FIDL_HANDLE_PRESENT;
message.inline_struct.l0.l1.l2.handle_2 = FIDL_HANDLE_PRESENT;
message.inline_struct.l0.l1.l2.l3.handle_3 = FIDL_HANDLE_PRESENT;
buffer[padding_offset] = 0xAA;
zx_handle_t handles[] = {
dummy_handle_0,
dummy_handle_1,
dummy_handle_2,
dummy_handle_3,
};
const char* error = nullptr;
auto status = fidl_decode(&nested_structs_message_type, &message, kBufferSize, handles,
ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_STR_EQ(error, "non-zero padding bytes detected during decoding");
}
END_TEST;
}
bool decode_nested_nullable_structs() {
BEGIN_TEST;
// See below for the handle traversal order.
nested_struct_ptrs_message_layout message = {};
message.inline_struct.l0_present = reinterpret_cast<struct_ptr_level_0*>(FIDL_ALLOC_PRESENT);
message.inline_struct.l0_inline.l1_present =
reinterpret_cast<struct_ptr_level_1*>(FIDL_ALLOC_PRESENT);
message.inline_struct.l0_inline.l1_inline.l2_present =
reinterpret_cast<struct_ptr_level_2*>(FIDL_ALLOC_PRESENT);
message.inline_struct.l0_inline.l1_inline.l2_inline.l3_present =
reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_PRESENT);
message.in_in_out_2.l3_present = reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_PRESENT);
message.in_out_1.l2_present = reinterpret_cast<struct_ptr_level_2*>(FIDL_ALLOC_PRESENT);
message.in_out_1.l2_inline.l3_present = reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_PRESENT);
message.in_out_out_2.l3_present = reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_PRESENT);
message.out_0.l1_present = reinterpret_cast<struct_ptr_level_1*>(FIDL_ALLOC_PRESENT);
message.out_0.l1_inline.l2_present = reinterpret_cast<struct_ptr_level_2*>(FIDL_ALLOC_PRESENT);
message.out_0.l1_inline.l2_inline.l3_present =
reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_PRESENT);
message.out_in_out_2.l3_present = reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_PRESENT);
message.out_out_1.l2_present = reinterpret_cast<struct_ptr_level_2*>(FIDL_ALLOC_PRESENT);
message.out_out_1.l2_inline.l3_present =
reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_PRESENT);
message.out_out_out_2.l3_present = reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_PRESENT);
message.inline_struct.l0_absent = reinterpret_cast<struct_ptr_level_0*>(FIDL_ALLOC_ABSENT);
message.inline_struct.l0_inline.l1_absent =
reinterpret_cast<struct_ptr_level_1*>(FIDL_ALLOC_ABSENT);
message.inline_struct.l0_inline.l1_inline.l2_absent =
reinterpret_cast<struct_ptr_level_2*>(FIDL_ALLOC_ABSENT);
message.inline_struct.l0_inline.l1_inline.l2_inline.l3_absent =
reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_ABSENT);
message.in_in_out_2.l3_absent = reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_ABSENT);
message.in_out_1.l2_absent = reinterpret_cast<struct_ptr_level_2*>(FIDL_ALLOC_ABSENT);
message.in_out_1.l2_inline.l3_absent = reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_ABSENT);
message.in_out_out_2.l3_absent = reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_ABSENT);
message.out_0.l1_absent = reinterpret_cast<struct_ptr_level_1*>(FIDL_ALLOC_ABSENT);
message.out_0.l1_inline.l2_absent = reinterpret_cast<struct_ptr_level_2*>(FIDL_ALLOC_ABSENT);
message.out_0.l1_inline.l2_inline.l3_absent =
reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_ABSENT);
message.out_in_out_2.l3_absent = reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_ABSENT);
message.out_out_1.l2_absent = reinterpret_cast<struct_ptr_level_2*>(FIDL_ALLOC_ABSENT);
message.out_out_1.l2_inline.l3_absent = reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_ABSENT);
message.out_out_out_2.l3_absent = reinterpret_cast<struct_ptr_level_3*>(FIDL_ALLOC_ABSENT);
message.inline_struct.l0_inline.l1_inline.handle_1 = FIDL_HANDLE_PRESENT;
message.in_in_out_out_3.handle_3 = FIDL_HANDLE_PRESENT;
message.in_in_out_2.l3_inline.handle_3 = FIDL_HANDLE_PRESENT;
message.in_in_out_2.handle_2 = FIDL_HANDLE_PRESENT;
message.in_in_in_out_3.handle_3 = FIDL_HANDLE_PRESENT;
message.inline_struct.l0_inline.l1_inline.l2_inline.l3_inline.handle_3 = FIDL_HANDLE_PRESENT;
message.inline_struct.l0_inline.l1_inline.l2_inline.handle_2 = FIDL_HANDLE_PRESENT;
message.inline_struct.l0_inline.handle_0 = FIDL_HANDLE_PRESENT;
message.in_out_1.handle_1 = FIDL_HANDLE_PRESENT;
message.in_out_out_out_3.handle_3 = FIDL_HANDLE_PRESENT;
message.in_out_out_2.l3_inline.handle_3 = FIDL_HANDLE_PRESENT;
message.in_out_out_2.handle_2 = FIDL_HANDLE_PRESENT;
message.in_out_in_out_3.handle_3 = FIDL_HANDLE_PRESENT;
message.in_out_1.l2_inline.l3_inline.handle_3 = FIDL_HANDLE_PRESENT;
message.in_out_1.l2_inline.handle_2 = FIDL_HANDLE_PRESENT;
message.out_0.l1_inline.handle_1 = FIDL_HANDLE_PRESENT;
message.out_in_out_out_3.handle_3 = FIDL_HANDLE_PRESENT;
message.out_in_out_2.l3_inline.handle_3 = FIDL_HANDLE_PRESENT;
message.out_in_out_2.handle_2 = FIDL_HANDLE_PRESENT;
message.out_in_in_out_3.handle_3 = FIDL_HANDLE_PRESENT;
message.out_0.l1_inline.l2_inline.l3_inline.handle_3 = FIDL_HANDLE_PRESENT;
message.out_0.l1_inline.l2_inline.handle_2 = FIDL_HANDLE_PRESENT;
message.out_0.handle_0 = FIDL_HANDLE_PRESENT;
message.out_out_1.handle_1 = FIDL_HANDLE_PRESENT;
message.out_out_out_out_3.handle_3 = FIDL_HANDLE_PRESENT;
message.out_out_out_2.l3_inline.handle_3 = FIDL_HANDLE_PRESENT;
message.out_out_out_2.handle_2 = FIDL_HANDLE_PRESENT;
message.out_out_in_out_3.handle_3 = FIDL_HANDLE_PRESENT;
message.out_out_1.l2_inline.l3_inline.handle_3 = FIDL_HANDLE_PRESENT;
message.out_out_1.l2_inline.handle_2 = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0, dummy_handle_1, dummy_handle_2, dummy_handle_3, dummy_handle_4,
dummy_handle_5, dummy_handle_6, dummy_handle_7, dummy_handle_8, dummy_handle_9,
dummy_handle_10, dummy_handle_11, dummy_handle_12, dummy_handle_13, dummy_handle_14,
dummy_handle_15, dummy_handle_16, dummy_handle_17, dummy_handle_18, dummy_handle_19,
dummy_handle_20, dummy_handle_21, dummy_handle_22, dummy_handle_23, dummy_handle_24,
dummy_handle_25, dummy_handle_26, dummy_handle_27, dummy_handle_28, dummy_handle_29,
};
const char* error = nullptr;
auto status = fidl_decode(&nested_struct_ptrs_message_type, &message, sizeof(message), handles,
ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
// Note the traversal order!
// 0 inline
// 1 inline
// handle
EXPECT_EQ(message.inline_struct.l0_inline.l1_inline.handle_1, dummy_handle_0);
// 2 out of line
// 3 out of line
EXPECT_EQ(message.inline_struct.l0_inline.l1_inline.l2_present->l3_present->handle_3,
dummy_handle_1);
// 3 inline
EXPECT_EQ(message.inline_struct.l0_inline.l1_inline.l2_present->l3_inline.handle_3,
dummy_handle_2);
// handle
EXPECT_EQ(message.inline_struct.l0_inline.l1_inline.l2_present->handle_2, dummy_handle_3);
// 2 inline
// 3 out of line
EXPECT_EQ(message.inline_struct.l0_inline.l1_inline.l2_inline.l3_present->handle_3,
dummy_handle_4);
// 3 inline
EXPECT_EQ(message.inline_struct.l0_inline.l1_inline.l2_inline.l3_inline.handle_3, dummy_handle_5);
// handle
EXPECT_EQ(message.inline_struct.l0_inline.l1_inline.l2_inline.handle_2, dummy_handle_6);
// handle
EXPECT_EQ(message.inline_struct.l0_inline.handle_0, dummy_handle_7);
// 1 out of line
// handle
EXPECT_EQ(message.inline_struct.l0_inline.l1_present->handle_1, dummy_handle_8);
// 2 out of line
// 3 out of line
EXPECT_EQ(message.inline_struct.l0_inline.l1_present->l2_present->l3_present->handle_3,
dummy_handle_9);
// 3 inline
EXPECT_EQ(message.inline_struct.l0_inline.l1_present->l2_present->l3_inline.handle_3,
dummy_handle_10);
// handle
EXPECT_EQ(message.inline_struct.l0_inline.l1_present->l2_present->handle_2, dummy_handle_11);
// 2 inline
// 3 out of line
EXPECT_EQ(message.inline_struct.l0_inline.l1_present->l2_inline.l3_present->handle_3,
dummy_handle_12);
// 3 inline
EXPECT_EQ(message.inline_struct.l0_inline.l1_present->l2_inline.l3_inline.handle_3,
dummy_handle_13);
// handle
EXPECT_EQ(message.inline_struct.l0_inline.l1_present->l2_inline.handle_2, dummy_handle_14);
// 0 out of line
// 1 inline
// handle
EXPECT_EQ(message.inline_struct.l0_present->l1_inline.handle_1, dummy_handle_15);
// 2 out of line
// 3 out of line
EXPECT_EQ(message.inline_struct.l0_present->l1_inline.l2_present->l3_present->handle_3,
dummy_handle_16);
// 3 inline
EXPECT_EQ(message.inline_struct.l0_present->l1_inline.l2_present->l3_inline.handle_3,
dummy_handle_17);
// handle
EXPECT_EQ(message.inline_struct.l0_present->l1_inline.l2_present->handle_2, dummy_handle_18);
// 2 inline
// 3 out of line
EXPECT_EQ(message.inline_struct.l0_present->l1_inline.l2_inline.l3_present->handle_3,
dummy_handle_19);
// 3 inline
EXPECT_EQ(message.inline_struct.l0_present->l1_inline.l2_inline.l3_inline.handle_3,
dummy_handle_20);
// handle
EXPECT_EQ(message.inline_struct.l0_present->l1_inline.l2_inline.handle_2, dummy_handle_21);
// handle
EXPECT_EQ(message.inline_struct.l0_present->handle_0, dummy_handle_22);
// 1 out of line
// handle
EXPECT_EQ(message.inline_struct.l0_present->l1_present->handle_1, dummy_handle_23);
// 2 out of line
// 3 out of line
EXPECT_EQ(message.inline_struct.l0_present->l1_present->l2_present->l3_present->handle_3,
dummy_handle_24);
// 3 inline
EXPECT_EQ(message.inline_struct.l0_present->l1_present->l2_present->l3_inline.handle_3,
dummy_handle_25);
// handle
EXPECT_EQ(message.inline_struct.l0_present->l1_present->l2_present->handle_2, dummy_handle_26);
// 2 inline
// 3 out of line
EXPECT_EQ(message.inline_struct.l0_present->l1_present->l2_inline.l3_present->handle_3,
dummy_handle_27);
// 3 inline
EXPECT_EQ(message.inline_struct.l0_present->l1_present->l2_inline.l3_inline.handle_3,
dummy_handle_28);
// handle
EXPECT_EQ(message.inline_struct.l0_present->l1_present->l2_inline.handle_2, dummy_handle_29);
// Finally, check that all absent members are nullptr.
EXPECT_NULL(message.inline_struct.l0_absent);
EXPECT_NULL(message.inline_struct.l0_inline.l1_absent);
EXPECT_NULL(message.inline_struct.l0_inline.l1_inline.l2_absent);
EXPECT_NULL(message.inline_struct.l0_inline.l1_inline.l2_inline.l3_absent);
EXPECT_NULL(message.inline_struct.l0_inline.l1_inline.l2_present->l3_absent);
EXPECT_NULL(message.inline_struct.l0_inline.l1_present->l2_absent);
EXPECT_NULL(message.inline_struct.l0_inline.l1_present->l2_inline.l3_absent);
EXPECT_NULL(message.inline_struct.l0_inline.l1_present->l2_present->l3_absent);
EXPECT_NULL(message.inline_struct.l0_present->l1_absent);
EXPECT_NULL(message.inline_struct.l0_present->l1_inline.l2_absent);
EXPECT_NULL(message.inline_struct.l0_present->l1_inline.l2_inline.l3_absent);
EXPECT_NULL(message.inline_struct.l0_present->l1_inline.l2_present->l3_absent);
EXPECT_NULL(message.inline_struct.l0_present->l1_present->l2_absent);
EXPECT_NULL(message.inline_struct.l0_present->l1_present->l2_inline.l3_absent);
EXPECT_NULL(message.inline_struct.l0_present->l1_present->l2_present->l3_absent);
END_TEST;
}
void SetUpRecursionMessage(recursion_message_layout* message) {
message->inline_struct.inline_union.tag = maybe_recurse_union_kMore;
message->inline_struct.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_0.inline_union.tag = maybe_recurse_union_kMore;
message->depth_0.inline_union.more = reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_1.inline_union.tag = maybe_recurse_union_kMore;
message->depth_1.inline_union.more = reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_2.inline_union.tag = maybe_recurse_union_kMore;
message->depth_2.inline_union.more = reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_3.inline_union.tag = maybe_recurse_union_kMore;
message->depth_3.inline_union.more = reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_4.inline_union.tag = maybe_recurse_union_kMore;
message->depth_4.inline_union.more = reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_5.inline_union.tag = maybe_recurse_union_kMore;
message->depth_5.inline_union.more = reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_6.inline_union.tag = maybe_recurse_union_kMore;
message->depth_6.inline_union.more = reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_7.inline_union.tag = maybe_recurse_union_kMore;
message->depth_7.inline_union.more = reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_8.inline_union.tag = maybe_recurse_union_kMore;
message->depth_8.inline_union.more = reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_9.inline_union.tag = maybe_recurse_union_kMore;
message->depth_9.inline_union.more = reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_10.inline_union.tag = maybe_recurse_union_kMore;
message->depth_10.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_11.inline_union.tag = maybe_recurse_union_kMore;
message->depth_11.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_12.inline_union.tag = maybe_recurse_union_kMore;
message->depth_12.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_13.inline_union.tag = maybe_recurse_union_kMore;
message->depth_13.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_14.inline_union.tag = maybe_recurse_union_kMore;
message->depth_14.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_15.inline_union.tag = maybe_recurse_union_kMore;
message->depth_15.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_16.inline_union.tag = maybe_recurse_union_kMore;
message->depth_16.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_17.inline_union.tag = maybe_recurse_union_kMore;
message->depth_17.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_18.inline_union.tag = maybe_recurse_union_kMore;
message->depth_18.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_19.inline_union.tag = maybe_recurse_union_kMore;
message->depth_19.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_20.inline_union.tag = maybe_recurse_union_kMore;
message->depth_20.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_21.inline_union.tag = maybe_recurse_union_kMore;
message->depth_21.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_22.inline_union.tag = maybe_recurse_union_kMore;
message->depth_22.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_23.inline_union.tag = maybe_recurse_union_kMore;
message->depth_23.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_24.inline_union.tag = maybe_recurse_union_kMore;
message->depth_24.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_25.inline_union.tag = maybe_recurse_union_kMore;
message->depth_25.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_26.inline_union.tag = maybe_recurse_union_kMore;
message->depth_26.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message->depth_27.inline_union.tag = maybe_recurse_union_kMore;
message->depth_27.inline_union.more =
reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
}
bool decode_nested_struct_recursion_too_deep_error() {
BEGIN_TEST;
recursion_message_layout message;
memset(&message, 0, sizeof(message));
// First we check that FIDL_RECURSION_DEPTH - 1 levels of recursion is OK.
SetUpRecursionMessage(&message);
message.depth_28.inline_union.tag = maybe_recurse_union_kDone;
message.depth_28.inline_union.handle = FIDL_HANDLE_PRESENT;
zx_handle_t handles[] = {
dummy_handle_0,
};
const char* error = nullptr;
auto status = fidl_decode(&recursion_message_type, &message,
// Tell it to ignore everything after we stop recursion.
offsetof(recursion_message_layout, depth_29), handles,
ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_OK);
EXPECT_NULL(error, error);
// Now add another level of recursion.
SetUpRecursionMessage(&message);
message.depth_28.inline_union.tag = maybe_recurse_union_kMore;
message.depth_28.inline_union.more = reinterpret_cast<recursion_inline_data*>(FIDL_ALLOC_PRESENT);
message.depth_29.inline_union.tag = maybe_recurse_union_kDone;
message.depth_29.inline_union.handle = FIDL_HANDLE_PRESENT;
error = nullptr;
status = fidl_decode(&recursion_message_type, &message, sizeof(message), handles,
ArrayCount(handles), &error);
EXPECT_EQ(status, ZX_ERR_INVALID_ARGS);
EXPECT_NONNULL(error);
const char expected_error_msg[] = "recursion depth exceeded processing struct";
EXPECT_STR_EQ(expected_error_msg, error, "wrong error msg");
END_TEST;
}
BEGIN_TEST_CASE(null_parameters)
RUN_TEST(decode_null_decode_parameters)
END_TEST_CASE(null_parameters)
BEGIN_TEST_CASE(unaligned)
RUN_TEST(decode_single_present_handle_unaligned_error)
RUN_TEST(decode_present_nonnullable_string_unaligned_error)
END_TEST_CASE(unaligned)
BEGIN_TEST_CASE(handles)
RUN_TEST(decode_single_present_handle)
RUN_TEST(decode_single_present_handle_check_trailing_padding)
RUN_TEST(decode_too_many_handles_specified_error)
RUN_TEST(decode_too_many_handles_specified_should_close_handles)
RUN_TEST(decode_too_many_bytes_specified_should_close_handles)
RUN_TEST(decode_multiple_present_handles)
RUN_TEST(decode_single_absent_handle)
RUN_TEST(decode_multiple_absent_handles)
END_TEST_CASE(handles)
BEGIN_TEST_CASE(arrays)
RUN_TEST(decode_array_of_present_handles)
RUN_TEST(decode_array_of_present_handles_error_closes_handles)
RUN_TEST(decode_array_of_nonnullable_handles_some_absent_error)
RUN_TEST(decode_array_of_nullable_handles)
RUN_TEST(decode_array_of_nullable_handles_with_insufficient_handles_error)
RUN_TEST(decode_array_of_array_of_present_handles)
RUN_TEST(decode_out_of_line_array)
END_TEST_CASE(arrays)
BEGIN_TEST_CASE(strings)
RUN_TEST(decode_present_nonnullable_string)
RUN_TEST(decode_multiple_present_nullable_string)
RUN_TEST(decode_present_nullable_string)
RUN_TEST(decode_absent_nonnullable_string_error)
RUN_TEST(decode_absent_nullable_string)
RUN_TEST(decode_present_nonnullable_bounded_string)
RUN_TEST(decode_present_nullable_bounded_string)
RUN_TEST(decode_absent_nonnullable_bounded_string_error)
RUN_TEST(decode_absent_nullable_bounded_string)
RUN_TEST(decode_present_nonnullable_bounded_string_short_error)
RUN_TEST(decode_present_nullable_bounded_string_short_error)
END_TEST_CASE(strings)
BEGIN_TEST_CASE(vectors)
RUN_TEST(decode_vector_with_huge_count)
RUN_TEST(decode_present_nonnullable_vector_of_handles)
RUN_TEST(decode_present_nullable_vector_of_handles)
RUN_TEST(decode_absent_nonnullable_vector_of_handles_error)
RUN_TEST(decode_absent_nullable_vector_of_handles)
RUN_TEST(decode_present_nonnullable_bounded_vector_of_handles)
RUN_TEST(decode_present_nullable_bounded_vector_of_handles)
RUN_TEST(decode_absent_nonnullable_bounded_vector_of_handles)
RUN_TEST(decode_absent_nullable_bounded_vector_of_handles)
RUN_TEST(decode_present_nonnullable_bounded_vector_of_handles_short_error)
RUN_TEST(decode_present_nullable_bounded_vector_of_handles_short_error)
RUN_TEST(decode_present_nonnullable_vector_of_uint32)
RUN_TEST(decode_present_nullable_vector_of_uint32)
RUN_TEST(decode_absent_nonnullable_vector_of_uint32_error)
RUN_TEST(decode_absent_and_empty_nonnullable_vector_of_uint32_error)
RUN_TEST(decode_absent_nullable_vector_of_uint32)
RUN_TEST(decode_absent_nullable_vector_of_uint32_non_zero_length_error)
RUN_TEST(decode_present_nonnullable_bounded_vector_of_uint32)
RUN_TEST(decode_present_nullable_bounded_vector_of_uint32)
RUN_TEST(decode_absent_nonnullable_bounded_vector_of_uint32)
RUN_TEST(decode_absent_nullable_bounded_vector_of_uint32)
RUN_TEST(decode_present_nonnullable_bounded_vector_of_uint32_short_error)
RUN_TEST(decode_present_nullable_bounded_vector_of_uint32_short_error)
END_TEST_CASE(vectors)
BEGIN_TEST_CASE(unions)
RUN_TEST(decode_bad_tagged_union_error)
RUN_TEST(decode_single_membered_present_nonnullable_union)
RUN_TEST(decode_many_membered_present_nonnullable_union)
RUN_TEST(decode_many_membered_present_nonnullable_union_check_padding)
RUN_TEST(decode_single_membered_present_nullable_union)
RUN_TEST(decode_many_membered_present_nullable_union)
RUN_TEST(decode_single_membered_absent_nullable_union)
RUN_TEST(decode_many_membered_absent_nullable_union)
END_TEST_CASE(unions)
BEGIN_TEST_CASE(structs)
RUN_TEST(decode_nested_nonnullable_structs)
RUN_TEST(decode_nested_nonnullable_structs_check_padding)
RUN_TEST(decode_nested_nullable_structs)
RUN_TEST(decode_nested_struct_recursion_too_deep_error)
END_TEST_CASE(structs)
} // namespace
} // namespace fidl
| 38.637634 | 100 | 0.75858 | sunshinewithmoonlight |
0f2c28c2da293c95335ad244c303c823214bf393 | 10,657 | cpp | C++ | examples/Cpp/MultiContext/Example.cpp | beldenfox/LLGL | 3a54125ebfa79bb06fccf8c413d308ff22186b52 | [
"BSD-3-Clause"
] | null | null | null | examples/Cpp/MultiContext/Example.cpp | beldenfox/LLGL | 3a54125ebfa79bb06fccf8c413d308ff22186b52 | [
"BSD-3-Clause"
] | null | null | null | examples/Cpp/MultiContext/Example.cpp | beldenfox/LLGL | 3a54125ebfa79bb06fccf8c413d308ff22186b52 | [
"BSD-3-Clause"
] | null | null | null | /*
* Example.cpp (Example_MultiContext)
*
* This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include <ExampleBase.h>
#include <LLGL/Application.h>
int main(int argc, char* argv[])
{
try
{
ExampleBase::Initialize();
// Load render system module
LLGL::RenderingDebugger debugger;
auto renderer = LLGL::RenderSystem::Load(GetSelectedRendererModule(argc, argv), nullptr, &debugger);
std::cout << "LLGL Renderer: " << renderer->GetName() << std::endl;
LLGL::Extent2D windowSize = { 640, 480 };
std::shared_ptr<LLGL::Window> window1 = ExampleBase::CreateWindow(windowSize);
std::shared_ptr<LLGL::Window> window2 = ExampleBase::CreateWindow(windowSize);
LLGL::RenderContextDescriptor contextDesc;
{
contextDesc.videoMode.resolution = window1->GetPreferredResolution();
contextDesc.vsync.enabled = true;
contextDesc.samples = 8;
}
auto context1 = renderer->CreateRenderContext(contextDesc, window1);
auto context2 = renderer->CreateRenderContext(contextDesc, window2);
// Get command queue and create command buffer
auto commandQueue = renderer->GetCommandQueue();
auto commands = renderer->CreateCommandBuffer();
// Create input handler
auto input = std::make_shared<LLGL::Input>();
window1->AddEventListener(input);
window2->AddEventListener(input);
// Set window titles
window1->SetTitle(L"LLGL Example: Multi Context (1)");
window2->SetTitle(L"LLGL Example: Multi Context (2)");
// Set window positions
LLGL::Extent2D desktopResolution;
if (auto display = LLGL::Display::InstantiatePrimary())
desktopResolution = display->GetDisplayMode().resolution;
const LLGL::Offset2D desktopCenter
{
static_cast<int>(desktopResolution.width)/2,
static_cast<int>(desktopResolution.height)/2
};
window1->SetPosition({ desktopCenter.x - 700, desktopCenter.y - 480/2 });
window2->SetPosition({ desktopCenter.x + 700 - 640, desktopCenter.y - 480/2 });
// Show windows
window1->Show();
window2->Show();
// Vertex data structure
struct Vertex
{
Gs::Vector2f position;
LLGL::ColorRGBf color;
};
// Vertex data
float objSize = 0.5f;
Vertex vertices[] =
{
// Triangle
{ { 0, objSize }, { 1, 0, 0 } },
{ { objSize, -objSize }, { 0, 1, 0 } },
{ { -objSize, -objSize }, { 0, 0, 1 } },
// Quad
{ { -objSize, -objSize }, { 1, 0, 0 } },
{ { -objSize, objSize }, { 1, 0, 0 } },
{ { objSize, -objSize }, { 1, 1, 0 } },
{ { objSize, objSize }, { 1, 1, 0 } },
};
// Vertex format
LLGL::VertexFormat vertexFormat;
vertexFormat.AppendAttribute({ "position", LLGL::Format::RG32Float }); // position has 2 float components
vertexFormat.AppendAttribute({ "color", LLGL::Format::RGB32Float }); // color has 3 float components
// Create vertex buffer
LLGL::BufferDescriptor vertexBufferDesc;
{
vertexBufferDesc.size = sizeof(vertices); // Size (in bytes) of the vertex buffer
vertexBufferDesc.bindFlags = LLGL::BindFlags::VertexBuffer;
vertexBufferDesc.vertexAttribs = vertexFormat.attributes; // Vertex format layout
}
auto vertexBuffer = renderer->CreateBuffer(vertexBufferDesc, vertices);
// Create shaders
LLGL::Shader* vertShader = nullptr;
LLGL::Shader* geomShader = nullptr;
LLGL::Shader* fragShader = nullptr;
// Load vertex, geometry, and fragment shaders from file
auto HasLanguage = [&](const LLGL::ShadingLanguage lang)
{
const auto& languages = renderer->GetRenderingCaps().shadingLanguages;
return (std::find(languages.begin(), languages.end(), lang) != languages.end());
};
LLGL::ShaderDescriptor vertShaderDesc, geomShaderDesc, fragShaderDesc;
if (HasLanguage(LLGL::ShadingLanguage::GLSL))
{
vertShaderDesc = { LLGL::ShaderType::Vertex, "Example.vert" };
geomShaderDesc = { LLGL::ShaderType::Geometry, "Example.geom" };
fragShaderDesc = { LLGL::ShaderType::Fragment, "Example.frag" };
}
else if (HasLanguage(LLGL::ShadingLanguage::SPIRV))
{
vertShaderDesc = LLGL::ShaderDescFromFile(LLGL::ShaderType::Vertex, "Example.450core.vert.spv");
geomShaderDesc = LLGL::ShaderDescFromFile(LLGL::ShaderType::Geometry, "Example.450core.geom.spv");
fragShaderDesc = LLGL::ShaderDescFromFile(LLGL::ShaderType::Fragment, "Example.450core.frag.spv");
}
else if (HasLanguage(LLGL::ShadingLanguage::HLSL))
{
vertShaderDesc = { LLGL::ShaderType::Vertex, "Example.hlsl", "VS", "vs_4_0" };
geomShaderDesc = { LLGL::ShaderType::Geometry, "Example.hlsl", "GS", "gs_4_0" };
fragShaderDesc = { LLGL::ShaderType::Fragment, "Example.hlsl", "PS", "ps_4_0" };
}
else if (HasLanguage(LLGL::ShadingLanguage::Metal))
{
vertShaderDesc = { LLGL::ShaderType::Vertex, "Example.metal", "VS", "2.0" };
//geomShaderDesc = N/A
fragShaderDesc = { LLGL::ShaderType::Fragment, "Example.metal", "PS", "2.0" };
}
// Set vertex input attributes and create vertex shader
vertShaderDesc.vertex.inputAttribs = vertexFormat.attributes;
vertShader = renderer->CreateShader(vertShaderDesc);
// Create geometry shader (if supported)
if (geomShaderDesc.source != nullptr)
geomShader = renderer->CreateShader(geomShaderDesc);
// Create fragment shader
fragShader = renderer->CreateShader(fragShaderDesc);
// Print info log (warnings and errors)
for (auto shader : { vertShader, geomShader, fragShader })
{
if (shader)
{
std::string log = shader->GetReport();
if (!log.empty())
std::cerr << log << std::endl;
}
}
// Create shader program which is used as composite
LLGL::ShaderProgramDescriptor shaderProgramDesc;
{
shaderProgramDesc.vertexShader = vertShader;
shaderProgramDesc.geometryShader = geomShader;
shaderProgramDesc.fragmentShader = fragShader;
}
auto shaderProgram = renderer->CreateShaderProgram(shaderProgramDesc);
if (shaderProgram->HasErrors())
throw std::runtime_error(shaderProgram->GetReport());
// Create graphics pipeline
LLGL::PipelineState* pipeline[2] = {};
const bool logicOpSupported = renderer->GetRenderingCaps().features.hasLogicOp;
LLGL::GraphicsPipelineDescriptor pipelineDesc;
{
pipelineDesc.shaderProgram = shaderProgram;
pipelineDesc.renderPass = context1->GetRenderPass();
pipelineDesc.primitiveTopology = LLGL::PrimitiveTopology::TriangleStrip;
pipelineDesc.rasterizer.multiSampleEnabled = (contextDesc.samples > 1);
}
pipeline[0] = renderer->CreatePipelineState(pipelineDesc);
{
pipelineDesc.renderPass = context2->GetRenderPass();
// Only enable logic operations if it's supported, otherwise an exception is thrown
if (logicOpSupported)
pipelineDesc.blend.logicOp = LLGL::LogicOp::CopyInverted;
}
pipeline[1] = renderer->CreatePipelineState(pipelineDesc);
// Initialize viewport array
LLGL::Viewport viewports[2] =
{
LLGL::Viewport { 0.0f, 0.0f, 320.0f, 480.0f },
LLGL::Viewport { 320.0f, 0.0f, 320.0f, 480.0f },
};
bool enableLogicOp = false;
if (logicOpSupported)
std::cout << "Press SPACE to enabled/disable logic fragment operations" << std::endl;
// Generate multiple-instances via geometry shader.
// Otherwise, use instanced rendering if geometry shaders are not supported (for Metal shading language).
std::uint32_t numInstances = (geomShader != nullptr ? 1 : 2);
// Enter main loop
while ( LLGL::Application::ProcessEvents() && !input->KeyPressed(LLGL::Key::Escape) )
{
// Switch between pipeline states
if (input->KeyDown(LLGL::Key::Space))
{
if (logicOpSupported)
{
enableLogicOp = !enableLogicOp;
if (enableLogicOp)
std::cout << "Logic Fragment Operation Enabled" << std::endl;
else
std::cout << "Logic Fragment Operation Disabled" << std::endl;
}
else
std::cout << "Logic Fragment Operation Not Supported" << std::endl;
}
// Start encoding commands
commands->Begin();
{
// Set global render states: viewports, vertex buffer, and graphics pipeline
commands->SetViewports(2, viewports);
commands->SetVertexBuffer(*vertexBuffer);
commands->SetPipelineState(*pipeline[enableLogicOp ? 1 : 0]);
// Draw triangle with 3 vertices in 1st render context
commands->BeginRenderPass(*context1);
{
commands->DrawInstanced(3, 0, numInstances);
}
commands->EndRenderPass();
// Draw quad with 4 vertices in 2nd render context
commands->BeginRenderPass(*context2);
{
commands->DrawInstanced(4, 3, numInstances);
}
commands->EndRenderPass();
}
commands->End();
commandQueue->Submit(*commands);
// Present the results on the screen
context1->Present();
context2->Present();
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
| 39.6171 | 115 | 0.573426 | beldenfox |
0f2da6cae69cb90e5807084f33aa3711fd13245c | 30,781 | cpp | C++ | examples/osg/osgAtlasPuppet.cpp | axeisghost/DART6motionBlur | 23387b0422bf95b75a113dbf5facc5f10d4a3305 | [
"BSD-2-Clause"
] | 4 | 2021-02-20T15:59:42.000Z | 2022-03-25T04:04:21.000Z | examples/osg/osgAtlasPuppet.cpp | axeisghost/DART6motionBlur | 23387b0422bf95b75a113dbf5facc5f10d4a3305 | [
"BSD-2-Clause"
] | 1 | 2021-04-14T04:12:48.000Z | 2021-04-14T04:12:48.000Z | examples/osg/osgAtlasPuppet.cpp | axeisghost/DART6motionBlur | 23387b0422bf95b75a113dbf5facc5f10d4a3305 | [
"BSD-2-Clause"
] | 2 | 2019-10-29T12:41:16.000Z | 2021-03-22T16:38:27.000Z | /*
* Copyright (c) 2015-2016, Humanoid Lab, Georgia Tech Research Corporation
* Copyright (c) 2015-2017, Graphics Lab, Georgia Tech Research Corporation
* Copyright (c) 2016-2017, Personal Robotics Lab, Carnegie Mellon University
* All rights reserved.
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <dart/dart.hpp>
#include <dart/gui/osg/osg.hpp>
#include <dart/utils/utils.hpp>
using namespace dart::common;
using namespace dart::dynamics;
using namespace dart::simulation;
using namespace dart::utils;
using namespace dart::math;
const double display_elevation = 0.05;
class RelaxedPosture : public dart::optimizer::Function
{
public:
RelaxedPosture(const Eigen::VectorXd& idealPosture,
const Eigen::VectorXd& lower, const Eigen::VectorXd& upper,
const Eigen::VectorXd& weights, bool enforceIdeal = false)
: enforceIdealPosture(enforceIdeal),
mIdeal(idealPosture),
mLower(lower),
mUpper(upper),
mWeights(weights)
{
int dofs = mIdeal.size();
if(mLower.size() != dofs || mWeights.size() != dofs || mUpper.size() != dofs)
{
dterr << "[RelaxedPose::RelaxedPose] Dimension mismatch:\n"
<< " ideal: " << mIdeal.size() << "\n"
<< " lower: " << mLower.size() << "\n"
<< " upper: " << mUpper.size() << "\n"
<< " weights: " << mWeights.size() << "\n";
}
mResultVector.setZero(dofs);
}
double eval(const Eigen::VectorXd& _x) override
{
computeResultVector(_x);
return 0.5 * mResultVector.dot(mResultVector);
}
void evalGradient(const Eigen::VectorXd& _x,
Eigen::Map<Eigen::VectorXd> _grad) override
{
computeResultVector(_x);
_grad.setZero();
int smaller = std::min(mResultVector.size(), _grad.size());
for(int i=0; i < smaller; ++i)
_grad[i] = mResultVector[i];
}
void computeResultVector(const Eigen::VectorXd& _x)
{
mResultVector.setZero();
if(enforceIdealPosture)
{
// Try to get the robot into the best possible posture
for(int i=0; i < _x.size(); ++i)
{
if(mIdeal.size() <= i)
break;
mResultVector[i] = mWeights[i]*(_x[i] - mIdeal[i]);
}
}
else
{
// Only adjust the posture if it is really bad
for(int i=0; i < _x.size(); ++i)
{
if(mIdeal.size() <= i)
break;
if(_x[i] < mLower[i])
mResultVector[i] = mWeights[i]*(_x[i] - mLower[i]);
else if(mUpper[i] < _x[i])
mResultVector[i] = mWeights[i]*(_x[i] - mUpper[i]);
}
}
}
bool enforceIdealPosture;
protected:
Eigen::VectorXd mResultVector;
Eigen::VectorXd mIdeal;
Eigen::VectorXd mLower;
Eigen::VectorXd mUpper;
Eigen::VectorXd mWeights;
};
class TeleoperationWorld : public dart::gui::osg::WorldNode
{
public:
enum MoveEnum_t
{
MOVE_Q = 0,
MOVE_W,
MOVE_E,
MOVE_A,
MOVE_S,
MOVE_D,
MOVE_F,
MOVE_Z,
NUM_MOVE
};
TeleoperationWorld(WorldPtr _world, SkeletonPtr _robot)
: dart::gui::osg::WorldNode(_world),
mAtlas(_robot),
iter(0),
l_foot(_robot->getEndEffector("l_foot")),
r_foot(_robot->getEndEffector("r_foot"))
{
mMoveComponents.resize(NUM_MOVE, false);
mAnyMovement = false;
}
void setMovement(const std::vector<bool>& moveComponents)
{
mMoveComponents = moveComponents;
mAnyMovement = false;
for(bool move : mMoveComponents)
{
if(move)
{
mAnyMovement = true;
break;
}
}
}
void customPreRefresh() override
{
if(mAnyMovement)
{
Eigen::Isometry3d old_tf = mAtlas->getBodyNode(0)->getWorldTransform();
Eigen::Isometry3d new_tf = Eigen::Isometry3d::Identity();
Eigen::Vector3d forward = old_tf.linear().col(0);
forward[2] = 0.0;
if(forward.norm() > 1e-10)
forward.normalize();
else
forward.setZero();
Eigen::Vector3d left = old_tf.linear().col(1);
left[2] = 0.0;
if(left.norm() > 1e-10)
left.normalize();
else
left.setZero();
const Eigen::Vector3d& up = Eigen::Vector3d::UnitZ();
const double linearStep = 0.01;
const double elevationStep = 0.2*linearStep;
const double rotationalStep = 2.0*M_PI/180.0;
if(mMoveComponents[MOVE_W])
new_tf.translate( linearStep*forward);
if(mMoveComponents[MOVE_S])
new_tf.translate(-linearStep*forward);
if(mMoveComponents[MOVE_A])
new_tf.translate( linearStep*left);
if(mMoveComponents[MOVE_D])
new_tf.translate(-linearStep*left);
if(mMoveComponents[MOVE_F])
new_tf.translate( elevationStep*up);
if(mMoveComponents[MOVE_Z])
new_tf.translate(-elevationStep*up);
if(mMoveComponents[MOVE_Q])
new_tf.rotate(Eigen::AngleAxisd( rotationalStep, up));
if(mMoveComponents[MOVE_E])
new_tf.rotate(Eigen::AngleAxisd(-rotationalStep, up));
new_tf.pretranslate(old_tf.translation());
new_tf.rotate(old_tf.rotation());
mAtlas->getJoint(0)->setPositions(FreeJoint::convertToPositions(new_tf));
}
bool solved = mAtlas->getIK(true)->solve();
if(!solved)
++iter;
else
iter = 0;
if(iter == 1000)
{
std::cout << "Failing!" << std::endl;
}
}
protected:
SkeletonPtr mAtlas;
std::size_t iter;
EndEffectorPtr l_foot;
EndEffectorPtr r_foot;
Eigen::VectorXd grad;
std::vector<bool> mMoveComponents;
bool mAnyMovement;
};
class InputHandler : public ::osgGA::GUIEventHandler
{
public:
InputHandler(dart::gui::osg::Viewer* viewer, TeleoperationWorld* teleop,
const SkeletonPtr& atlas, const WorldPtr& world)
: mViewer(viewer),
mTeleop(teleop),
mAtlas(atlas),
mWorld(world)
{
initialize();
}
void initialize()
{
mRestConfig = mAtlas->getPositions();
mLegs.reserve(12);
for(std::size_t i=0; i<mAtlas->getNumDofs(); ++i)
{
if(mAtlas->getDof(i)->getName().substr(1, 5) == "_leg_")
mLegs.push_back(mAtlas->getDof(i)->getIndexInSkeleton());
}
// We should also adjust the pelvis when detangling the legs
mLegs.push_back(mAtlas->getDof("rootJoint_rot_x")->getIndexInSkeleton());
mLegs.push_back(mAtlas->getDof("rootJoint_rot_y")->getIndexInSkeleton());
mLegs.push_back(mAtlas->getDof("rootJoint_pos_z")->getIndexInSkeleton());
for(std::size_t i=0; i < mAtlas->getNumEndEffectors(); ++i)
{
const InverseKinematicsPtr ik = mAtlas->getEndEffector(i)->getIK();
if(ik)
{
mDefaultBounds.push_back(ik->getErrorMethod().getBounds());
mDefaultTargetTf.push_back(ik->getTarget()->getRelativeTransform());
mConstraintActive.push_back(false);
mEndEffectorIndex.push_back(i);
}
}
mPosture = std::dynamic_pointer_cast<RelaxedPosture>(
mAtlas->getIK(true)->getObjective());
mBalance = std::dynamic_pointer_cast<dart::constraint::BalanceConstraint>(
mAtlas->getIK(true)->getProblem()->getEqConstraint(1));
mOptimizationKey = 'r';
mMoveComponents.resize(TeleoperationWorld::NUM_MOVE, false);
}
virtual bool handle(const ::osgGA::GUIEventAdapter& ea,
::osgGA::GUIActionAdapter&) override
{
if(nullptr == mAtlas)
{
return false;
}
if( ::osgGA::GUIEventAdapter::KEYDOWN == ea.getEventType() )
{
if( ea.getKey() == 'p' )
{
for(std::size_t i=0; i < mAtlas->getNumDofs(); ++i)
std::cout << mAtlas->getDof(i)->getName() << ": "
<< mAtlas->getDof(i)->getPosition() << std::endl;
std::cout << " -- -- -- -- -- " << std::endl;
return true;
}
if( ea.getKey() == 't' )
{
// Reset all the positions except for x, y, and yaw
for(std::size_t i=0; i < mAtlas->getNumDofs(); ++i)
{
if( i < 2 || 4 < i )
mAtlas->getDof(i)->setPosition(mRestConfig[i]);
}
return true;
}
if( '1' <= ea.getKey() && ea.getKey() <= '9' )
{
std::size_t index = ea.getKey() - '1';
if(index < mConstraintActive.size())
{
EndEffector* ee = mAtlas->getEndEffector(mEndEffectorIndex[index]);
const InverseKinematicsPtr& ik = ee->getIK();
if(ik && mConstraintActive[index])
{
mConstraintActive[index] = false;
ik->getErrorMethod().setBounds(mDefaultBounds[index]);
ik->getTarget()->setRelativeTransform(mDefaultTargetTf[index]);
mWorld->removeSimpleFrame(ik->getTarget());
}
else if(ik)
{
mConstraintActive[index] = true;
// Use the standard default bounds instead of our custom default
// bounds
ik->getErrorMethod().setBounds();
ik->getTarget()->setTransform(ee->getTransform());
mWorld->addSimpleFrame(ik->getTarget());
}
}
return true;
}
if( 'x' == ea.getKey() )
{
EndEffector* ee = mAtlas->getEndEffector("l_foot");
ee->getSupport()->setActive(!ee->getSupport()->isActive());
return true;
}
if( 'c' == ea.getKey() )
{
EndEffector* ee = mAtlas->getEndEffector("r_foot");
ee->getSupport()->setActive(!ee->getSupport()->isActive());
return true;
}
switch(ea.getKey())
{
case 'w': mMoveComponents[TeleoperationWorld::MOVE_W] = true; break;
case 'a': mMoveComponents[TeleoperationWorld::MOVE_A] = true; break;
case 's': mMoveComponents[TeleoperationWorld::MOVE_S] = true; break;
case 'd': mMoveComponents[TeleoperationWorld::MOVE_D] = true; break;
case 'q': mMoveComponents[TeleoperationWorld::MOVE_Q] = true; break;
case 'e': mMoveComponents[TeleoperationWorld::MOVE_E] = true; break;
case 'f': mMoveComponents[TeleoperationWorld::MOVE_F] = true; break;
case 'z': mMoveComponents[TeleoperationWorld::MOVE_Z] = true; break;
}
switch(ea.getKey())
{
case 'w': case 'a': case 's': case 'd': case 'q': case'e': case 'f': case 'z':
{
mTeleop->setMovement(mMoveComponents);
return true;
}
}
if(mOptimizationKey == ea.getKey())
{
if(mPosture)
mPosture->enforceIdealPosture = true;
if(mBalance)
mBalance->setErrorMethod(dart::constraint::BalanceConstraint::OPTIMIZE_BALANCE);
return true;
}
}
if( ::osgGA::GUIEventAdapter::KEYUP == ea.getEventType() )
{
if(ea.getKey() == mOptimizationKey)
{
if(mPosture)
mPosture->enforceIdealPosture = false;
if(mBalance)
mBalance->setErrorMethod(dart::constraint::BalanceConstraint::FROM_CENTROID);
return true;
}
switch(ea.getKey())
{
case 'w': mMoveComponents[TeleoperationWorld::MOVE_W] = false; break;
case 'a': mMoveComponents[TeleoperationWorld::MOVE_A] = false; break;
case 's': mMoveComponents[TeleoperationWorld::MOVE_S] = false; break;
case 'd': mMoveComponents[TeleoperationWorld::MOVE_D] = false; break;
case 'q': mMoveComponents[TeleoperationWorld::MOVE_Q] = false; break;
case 'e': mMoveComponents[TeleoperationWorld::MOVE_E] = false; break;
case 'f': mMoveComponents[TeleoperationWorld::MOVE_F] = false; break;
case 'z': mMoveComponents[TeleoperationWorld::MOVE_Z] = false; break;
}
switch(ea.getKey())
{
case 'w': case 'a': case 's': case 'd': case 'q': case'e': case 'f': case 'z':
{
mTeleop->setMovement(mMoveComponents);
return true;
}
}
}
return false;
}
protected:
dart::gui::osg::Viewer* mViewer;
TeleoperationWorld* mTeleop;
SkeletonPtr mAtlas;
WorldPtr mWorld;
Eigen::VectorXd mRestConfig;
std::vector<std::size_t> mLegs;
std::vector<bool> mConstraintActive;
std::vector<std::size_t> mEndEffectorIndex;
std::vector< std::pair<Eigen::Vector6d, Eigen::Vector6d> > mDefaultBounds;
Eigen::aligned_vector<Eigen::Isometry3d> mDefaultTargetTf;
std::shared_ptr<RelaxedPosture> mPosture;
std::shared_ptr<dart::constraint::BalanceConstraint> mBalance;
char mOptimizationKey;
std::vector<bool> mMoveComponents;
};
SkeletonPtr createGround()
{
// Create a Skeleton to represent the ground
SkeletonPtr ground = Skeleton::create("ground");
Eigen::Isometry3d tf(Eigen::Isometry3d::Identity());
double thickness = 0.01;
tf.translation() = Eigen::Vector3d(0,0,-thickness/2.0);
WeldJoint::Properties joint;
joint.mT_ParentBodyToJoint = tf;
ground->createJointAndBodyNodePair<WeldJoint>(nullptr, joint);
ShapePtr groundShape =
std::make_shared<BoxShape>(Eigen::Vector3d(10,10,thickness));
auto shapeNode = ground->getBodyNode(0)->createShapeNodeWith<
VisualAspect, CollisionAspect, DynamicsAspect>(groundShape);
shapeNode->getVisualAspect()->setColor(dart::Color::Blue(0.2));
return ground;
}
SkeletonPtr createAtlas()
{
// Parse in the atlas model
DartLoader urdf;
SkeletonPtr atlas =
urdf.parseSkeleton(DART_DATA_PATH"sdf/atlas/atlas_v3_no_head.urdf");
// Add a box to the root node to make it easier to click and drag
double scale = 0.25;
ShapePtr boxShape =
std::make_shared<BoxShape>(scale*Eigen::Vector3d(1.0, 1.0, 0.5));
Eigen::Isometry3d tf(Eigen::Isometry3d::Identity());
tf.translation() = Eigen::Vector3d(0.1*Eigen::Vector3d(0.0, 0.0, 1.0));
auto shapeNode =
atlas->getBodyNode(0)->createShapeNodeWith<VisualAspect>(boxShape);
shapeNode->getVisualAspect()->setColor(dart::Color::Black());
shapeNode->setRelativeTransform(tf);
return atlas;
}
void setupStartConfiguration(const SkeletonPtr& atlas)
{
// Squat with the right leg
atlas->getDof("r_leg_hpy")->setPosition(-45.0*M_PI/180.0);
atlas->getDof("r_leg_kny")->setPosition( 90.0*M_PI/180.0);
atlas->getDof("r_leg_aky")->setPosition(-45.0*M_PI/180.0);
// Squat with the left left
atlas->getDof("l_leg_hpy")->setPosition(-45.0*M_PI/180.0);
atlas->getDof("l_leg_kny")->setPosition( 90.0*M_PI/180.0);
atlas->getDof("l_leg_aky")->setPosition(-45.0*M_PI/180.0);
// Get the right arm into a comfortable position
atlas->getDof("r_arm_shx")->setPosition( 65.0*M_PI/180.0);
atlas->getDof("r_arm_ely")->setPosition( 90.0*M_PI/180.0);
atlas->getDof("r_arm_elx")->setPosition(-90.0*M_PI/180.0);
atlas->getDof("r_arm_wry")->setPosition( 65.0*M_PI/180.0);
// Get the left arm into a comfortable position
atlas->getDof("l_arm_shx")->setPosition(-65.0*M_PI/180.0);
atlas->getDof("l_arm_ely")->setPosition( 90.0*M_PI/180.0);
atlas->getDof("l_arm_elx")->setPosition( 90.0*M_PI/180.0);
atlas->getDof("l_arm_wry")->setPosition( 65.0*M_PI/180.0);
// Prevent the knees from bending backwards
atlas->getDof("r_leg_kny")->setPositionLowerLimit( 10*M_PI/180.0);
atlas->getDof("l_leg_kny")->setPositionLowerLimit( 10*M_PI/180.0);
}
void setupEndEffectors(const SkeletonPtr& atlas)
{
// Apply very small weights to the gradient of the root joint in order to
// encourage the arms to use arm joints instead of only moving around the root
// joint
Eigen::VectorXd rootjoint_weights = Eigen::VectorXd::Ones(6);
rootjoint_weights = 0.01*rootjoint_weights;
// Setting the bounds to be infinite allows the end effector to be implicitly
// unconstrained
Eigen::Vector3d linearBounds =
Eigen::Vector3d::Constant(std::numeric_limits<double>::infinity());
Eigen::Vector3d angularBounds =
Eigen::Vector3d::Constant(std::numeric_limits<double>::infinity());
// -- Set up the left hand --
// Create a relative transform for the EndEffector frame. This is the
// transform that the left hand will have relative to the BodyNode that it is
// attached to
Eigen::Isometry3d tf_hand(Eigen::Isometry3d::Identity());
tf_hand.translation() = Eigen::Vector3d(0.0009, 0.1254, 0.012);
tf_hand.rotate(Eigen::AngleAxisd(90.0*M_PI/180.0, Eigen::Vector3d::UnitZ()));
// Create the left hand's end effector and set its relative transform
EndEffector* l_hand = atlas->getBodyNode("l_hand")->createEndEffector("l_hand");
l_hand->setDefaultRelativeTransform(tf_hand, true);
// Create an interactive frame to use as the target for the left hand
dart::gui::osg::InteractiveFramePtr lh_target(new dart::gui::osg::InteractiveFrame(
Frame::World(), "lh_target"));
// Set the target of the left hand to the interactive frame. We pass true into
// the function to tell it that it should create the IK module if it does not
// already exist. If we don't do that, then calling getIK() could return a
// nullptr if the IK module was never created.
l_hand->getIK(true)->setTarget(lh_target);
// Tell the left hand to use the whole body for its IK
l_hand->getIK()->useWholeBody();
// Set the weights for the gradient
l_hand->getIK()->getGradientMethod().setComponentWeights(rootjoint_weights);
// Set the bounds for the IK to be infinite so that the hands start out
// unconstrained
l_hand->getIK()->getErrorMethod().setLinearBounds(
-linearBounds, linearBounds);
l_hand->getIK()->getErrorMethod().setAngularBounds(
-angularBounds, angularBounds);
// -- Set up the right hand --
// The orientation of the right hand frame is different than the left, so we
// need to adjust the signs of the relative transform
tf_hand.translation()[0] = -tf_hand.translation()[0];
tf_hand.translation()[1] = -tf_hand.translation()[1];
tf_hand.linear() = tf_hand.linear().inverse();
// Create the right hand's end effector and set its relative transform
EndEffector* r_hand = atlas->getBodyNode("r_hand")->createEndEffector("r_hand");
r_hand->setDefaultRelativeTransform(tf_hand, true);
// Create an interactive frame to use as the target for the right hand
dart::gui::osg::InteractiveFramePtr rh_target(new dart::gui::osg::InteractiveFrame(
Frame::World(), "rh_target"));
// Create the right hand's IK and set its target
r_hand->getIK(true)->setTarget(rh_target);
// Tell the right hand to use the whole body for its IK
r_hand->getIK()->useWholeBody();
// Set the weights for the gradient
r_hand->getIK()->getGradientMethod().setComponentWeights(rootjoint_weights);
// Set the bounds for the IK to be infinite so that the hands start out
// unconstrained
r_hand->getIK()->getErrorMethod().setLinearBounds(
-linearBounds, linearBounds);
r_hand->getIK()->getErrorMethod().setAngularBounds(
-angularBounds, angularBounds);
// Define the support geometry for the feet. These points will be used to
// compute the convex hull of the robot's support polygon
dart::math::SupportGeometry support;
const double sup_pos_x = 0.10-0.186;
const double sup_neg_x = -0.03-0.186;
const double sup_pos_y = 0.03;
const double sup_neg_y = -0.03;
support.push_back(Eigen::Vector3d(sup_neg_x, sup_neg_y, 0.0));
support.push_back(Eigen::Vector3d(sup_pos_x, sup_neg_y, 0.0));
support.push_back(Eigen::Vector3d(sup_pos_x, sup_pos_y, 0.0));
support.push_back(Eigen::Vector3d(sup_neg_x, sup_pos_y, 0.0));
// Create a relative transform that goes from the center of the feet to the
// bottom of the feet
Eigen::Isometry3d tf_foot(Eigen::Isometry3d::Identity());
tf_foot.translation() = Eigen::Vector3d(0.186, 0.0, -0.08);
// Constrain the feet to snap to the ground
linearBounds[2] = 1e-8;
// Constrain the feet to lie flat on the ground
angularBounds[0] = 1e-8;
angularBounds[1] = 1e-8;
// Create an end effector for the left foot and set its relative transform
EndEffector* l_foot = atlas->getBodyNode("l_foot")->createEndEffector("l_foot");
l_foot->setRelativeTransform(tf_foot);
// Create an interactive frame to use as the target for the left foot
dart::gui::osg::InteractiveFramePtr lf_target(new dart::gui::osg::InteractiveFrame(
Frame::World(), "lf_target"));
// Create the left foot's IK and set its target
l_foot->getIK(true)->setTarget(lf_target);
// Set the left foot's IK hierarchy level to 1. This will project its IK goals
// through the null space of any IK modules that are on level 0. This means
// that it will try to accomplish its goals while also accommodating the goals
// of other modules.
l_foot->getIK()->setHierarchyLevel(1);
// Use the bounds defined above
l_foot->getIK()->getErrorMethod().setLinearBounds(
-linearBounds, linearBounds);
l_foot->getIK()->getErrorMethod().setAngularBounds(
-angularBounds, angularBounds);
// Create Support for the foot and give it geometry
l_foot->getSupport(true)->setGeometry(support);
// Turn on support mode so that it can be used as a foot
l_foot->getSupport()->setActive();
// Create an end effector for the right foot and set its relative transform
EndEffector* r_foot = atlas->getBodyNode("r_foot")->createEndEffector("r_foot");
r_foot->setRelativeTransform(tf_foot);
// Create an interactive frame to use as the target for the right foot
dart::gui::osg::InteractiveFramePtr rf_target(new dart::gui::osg::InteractiveFrame(
Frame::World(), "rf_target"));
// Create the right foot's IK module and set its target
r_foot->getIK(true)->setTarget(rf_target);
// Set the right foot's IK hierarchy level to 1
r_foot->getIK()->setHierarchyLevel(1);
// Use the bounds defined above
r_foot->getIK()->getErrorMethod().setLinearBounds(
-linearBounds, linearBounds);
r_foot->getIK()->getErrorMethod().setAngularBounds(
-angularBounds, angularBounds);
// Create Support for the foot and give it geometry
r_foot->getSupport(true)->setGeometry(support);
// Turn on support mode so that it can be used as a foot
r_foot->getSupport()->setActive();
// Move atlas to the ground so that it starts out squatting with its feet on
// the ground
double heightChange = -r_foot->getWorldTransform().translation()[2];
atlas->getDof(5)->setPosition(heightChange);
// Now that the feet are on the ground, we should set their target transforms
l_foot->getIK()->getTarget()->setTransform(l_foot->getTransform());
r_foot->getIK()->getTarget()->setTransform(r_foot->getTransform());
}
void setupWholeBodySolver(const SkeletonPtr& atlas)
{
// The default
std::shared_ptr<dart::optimizer::GradientDescentSolver> solver =
std::dynamic_pointer_cast<dart::optimizer::GradientDescentSolver>(
atlas->getIK(true)->getSolver());
solver->setNumMaxIterations(10);
std::size_t nDofs = atlas->getNumDofs();
double default_weight = 0.01;
Eigen::VectorXd weights = default_weight * Eigen::VectorXd::Ones(nDofs);
weights[2] = 0.0;
weights[3] = 0.0;
weights[4] = 0.0;
weights[6] *= 0.2;
weights[7] *= 0.2;
weights[8] *= 0.2;
Eigen::VectorXd lower_posture = Eigen::VectorXd::Constant(
nDofs, -std::numeric_limits<double>::infinity());
lower_posture[0] = -0.35;
lower_posture[1] = -0.35;
lower_posture[5] = 0.600;
lower_posture[6] = -0.1;
lower_posture[7] = -0.1;
lower_posture[8] = -0.1;
Eigen::VectorXd upper_posture = Eigen::VectorXd::Constant(
nDofs, std::numeric_limits<double>::infinity());
upper_posture[0] = 0.35;
upper_posture[1] = 0.35;
upper_posture[5] = 0.885;
upper_posture[6] = 0.1;
upper_posture[7] = 0.1;
upper_posture[8] = 0.1;
std::shared_ptr<RelaxedPosture> objective = std::make_shared<RelaxedPosture>(
atlas->getPositions(), lower_posture, upper_posture, weights);
atlas->getIK()->setObjective(objective);
std::shared_ptr<dart::constraint::BalanceConstraint> balance =
std::make_shared<dart::constraint::BalanceConstraint>(atlas->getIK());
atlas->getIK()->getProblem()->addEqConstraint(balance);
// // Shift the center of mass towards the support polygon center while trying
// // to keep the support polygon where it is
// balance->setErrorMethod(dart::constraint::BalanceConstraint::FROM_CENTROID);
// balance->setBalanceMethod(dart::constraint::BalanceConstraint::SHIFT_COM);
// // Keep shifting the center of mass towards the center of the support
// // polygon, even if it is already inside. This is useful for trying to
// // optimize a stance
// balance->setErrorMethod(dart::constraint::BalanceConstraint::OPTIMIZE_BALANCE);
// balance->setBalanceMethod(dart::constraint::BalanceConstraint::SHIFT_COM);
// // Try to leave the center of mass where it is while moving the support
// // polygon to be under the current center of mass location
balance->setErrorMethod(dart::constraint::BalanceConstraint::FROM_CENTROID);
balance->setBalanceMethod(dart::constraint::BalanceConstraint::SHIFT_SUPPORT);
// // Try to leave the center of mass where it is while moving the support
// // point that is closest to the center of mass
// balance->setErrorMethod(dart::constraint::BalanceConstraint::FROM_EDGE);
// balance->setBalanceMethod(dart::constraint::BalanceConstraint::SHIFT_SUPPORT);
// Note that using the FROM_EDGE error method is liable to leave the center of
// mass visualization red even when the constraint was successfully solved.
// This is because the constraint solver has a tiny bit of tolerance that
// allows the Problem to be considered solved when the center of mass is
// microscopically outside of the support polygon. This is an inherent risk of
// using FROM_EDGE instead of FROM_CENTROID.
// Feel free to experiment with the different balancing methods. You will find
// that some work much better for user interaction than others.
}
void enableDragAndDrops(dart::gui::osg::Viewer& viewer, const SkeletonPtr& atlas)
{
// Turn on drag-and-drop for the whole Skeleton
for(std::size_t i=0; i < atlas->getNumBodyNodes(); ++i)
viewer.enableDragAndDrop(atlas->getBodyNode(i), false, false);
for(std::size_t i=0; i < atlas->getNumEndEffectors(); ++i)
{
EndEffector* ee = atlas->getEndEffector(i);
if(!ee->getIK())
continue;
// Check whether the target is an interactive frame, and add it if it is
if(const auto& frame = std::dynamic_pointer_cast<dart::gui::osg::InteractiveFrame>(
ee->getIK()->getTarget()))
viewer.enableDragAndDrop(frame.get());
}
}
int main()
{
WorldPtr world(new World);
SkeletonPtr atlas = createAtlas();
world->addSkeleton(atlas);
SkeletonPtr ground = createGround();
world->addSkeleton(ground);
setupStartConfiguration(atlas);
setupEndEffectors(atlas);
setupWholeBodySolver(atlas);
::osg::ref_ptr<TeleoperationWorld> node = new TeleoperationWorld(world, atlas);
dart::gui::osg::Viewer viewer;
// Prevent this World from simulating
viewer.allowSimulation(false);
viewer.addWorldNode(node);
// Add our custom input handler to the Viewer
viewer.addEventHandler(new InputHandler(&viewer, node, atlas, world));
enableDragAndDrops(viewer, atlas);
// Attach a support polygon visualizer
viewer.addAttachment(new dart::gui::osg::SupportPolygonVisual(
atlas, display_elevation));
// Print out instructions for the viewer
std::cout << viewer.getInstructions() << std::endl;
std::cout << "Alt + Click: Try to translate a body without changing its orientation\n"
<< "Ctrl + Click: Try to rotate a body without changing its translation\n"
<< "Shift + Click: Move a body using only its parent joint\n"
<< "1 -> 4: Toggle the interactive target of an EndEffector\n"
<< "W A S D: Move the robot around the scene\n"
<< "Q E: Rotate the robot counter-clockwise and clockwise\n"
<< "F Z: Shift the robot's elevation up and down\n"
<< "X C: Toggle support on the left and right foot\n"
<< "R: Optimize the robot's posture\n"
<< "T: Reset the robot to its relaxed posture\n\n"
<< " Because this uses iterative Jacobian methods, the solver can get finicky,\n"
<< " and the robot can get tangled up. Use 'R' and 'T' keys when the robot is\n"
<< " in a messy configuration\n\n"
<< " The green polygon is the support polygon of the robot, and the blue/red ball is\n"
<< " the robot's center of mass. The green ball is the centroid of the polygon.\n\n"
<< "Note that this is purely kinematic. Physical simulation is not allowed in this app.\n"
<< std::endl;
// Set up the window
viewer.setUpViewInWindow(0, 0, 1280, 960);
// Set up the default viewing position
viewer.getCameraManipulator()->setHomePosition(::osg::Vec3( 5.34, 3.00, 2.41),
::osg::Vec3( 0.00, 0.00, 1.00),
::osg::Vec3(-0.20, -0.08, 0.98));
// Reset the camera manipulator so that it starts in the new viewing position
viewer.setCameraManipulator(viewer.getCameraManipulator());
// Run the Viewer
viewer.run();
}
| 34.012155 | 102 | 0.659758 | axeisghost |
0f2e7a17e83c1ea4333eb74dbf13ebec95ac4634 | 14,359 | cpp | C++ | header_files/parameters.cpp | shahaneshantanu/memphys | 1b95afa505808f302d2dd4689faa45bb6480e8d8 | [
"MIT"
] | null | null | null | header_files/parameters.cpp | shahaneshantanu/memphys | 1b95afa505808f302d2dd4689faa45bb6480e8d8 | [
"MIT"
] | null | null | null | header_files/parameters.cpp | shahaneshantanu/memphys | 1b95afa505808f302d2dd4689faa45bb6480e8d8 | [
"MIT"
] | 1 | 2022-03-07T00:32:37.000Z | 2022-03-07T00:32:37.000Z | //Author: Dr. Shantanu Shahane
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <float.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include "class.hpp"
#include <unistd.h>
#include <limits.h>
#include <Eigen/Dense>
#include <unsupported/Eigen/SparseExtra>
#include <Eigen/SparseLU>
#include <Eigen/OrderingMethods>
#include <Eigen/Eigenvalues>
#include <Eigen/Core>
#include <Eigen/SparseCore>
#include <Spectra/GenEigsSolver.h>
#include <Spectra/MatOp/SparseGenMatProd.h>
#include <Spectra/GenEigsRealShiftSolver.h>
#include <Spectra/MatOp/SparseGenRealShiftSolve.h>
using namespace std;
PARAMETERS::PARAMETERS(string parameter_file, string gmsh_file)
{
cout << "\n";
check_mpi();
meshfile = gmsh_file;
cout << "PARAMETERS::PARAMETERS gmsh_file: " << meshfile << endl;
does_file_exist(meshfile.c_str(), "Called from PARAMETERS::read_calc_parameters");
read_calc_parameters(parameter_file);
verify_parameters();
get_problem_dimension_msh();
calc_cloud_num_points();
calc_polynomial_term_exponents();
cout << "\n";
}
void PARAMETERS::read_calc_parameters(string parameter_file)
{
does_file_exist(parameter_file.c_str(), "Called from PARAMETERS::read_calc_parameters");
char ctemp[5000], ctemp_2[100];
string stemp;
int itemp;
double dtemp;
FILE *file;
file = fopen(parameter_file.c_str(), "r");
cout << endl;
fscanf(file, "%[^,],%i\n", ctemp, &poly_deg);
printf("PARAMETERS::read_calc_parameters Read %s = %i\n", ctemp, poly_deg);
fscanf(file, "%[^,],%i\n", ctemp, &phs_deg);
printf("PARAMETERS::read_calc_parameters Read %s = %i\n", ctemp, phs_deg);
fscanf(file, "%[^,],%lf\n", ctemp, &cloud_size_multiplier);
printf("PARAMETERS::read_calc_parameters Read %s = %g\n", ctemp, cloud_size_multiplier);
fscanf(file, "%[^,],%i\n", ctemp, &nt);
printf("PARAMETERS::read_calc_parameters Read %s = %i\n", ctemp, nt);
fscanf(file, "%[^,],%lf\n", ctemp, &Courant);
printf("PARAMETERS::read_calc_parameters Read %s = %g\n", ctemp, Courant);
fscanf(file, "%[^,],%s\n", ctemp, ctemp_2);
solver_type = ctemp_2;
printf("PARAMETERS::read_calc_parameters Read %s = %s\n", ctemp, solver_type.c_str());
fscanf(file, "%[^,],%lf\n", ctemp, &steady_tolerance);
printf("PARAMETERS::read_calc_parameters Read %s = %g\n", ctemp, steady_tolerance);
fscanf(file, "%[^,],%lf\n", ctemp, &solver_tolerance);
printf("PARAMETERS::read_calc_parameters Read %s = %g\n", ctemp, solver_tolerance);
fscanf(file, "%[^,],%i\n", ctemp, &euclid_precond_level_hypre);
printf("PARAMETERS::read_calc_parameters Read %s = %i\n", ctemp, euclid_precond_level_hypre);
fscanf(file, "%[^,],%i\n", ctemp, &gmres_kdim);
printf("PARAMETERS::read_calc_parameters Read %s = %i\n", ctemp, gmres_kdim);
fscanf(file, "%[^,],%lf\n", ctemp, &precond_droptol);
printf("PARAMETERS::read_calc_parameters Read %s = %g\n", ctemp, precond_droptol);
fscanf(file, "%[^,],%i\n", ctemp, &n_iter);
printf("PARAMETERS::read_calc_parameters Read %s = %i\n", ctemp, n_iter);
cout << endl;
}
void PARAMETERS::verify_parameters()
{
if (poly_deg < 2 || poly_deg > 15)
{
printf("\n\nERROR from PARAMETERS::verify_parameters poly_deg should be in range [2, 15]; current value: %i\n\n", poly_deg);
throw bad_exception();
}
if (phs_deg != 3 && phs_deg != 5 && phs_deg != 7 && phs_deg != 9 && phs_deg != 11)
{
printf("\n\nERROR from PARAMETERS::verify_parameters phs_deg should be 3, 5, 7, 9, or 11; current value: %i\n\n", phs_deg);
throw bad_exception();
}
if (strcmp(solver_type.c_str(), "hypre_ilu_gmres") != 0 && strcmp(solver_type.c_str(), "eigen_direct") != 0 && strcmp(solver_type.c_str(), "eigen_ilu_bicgstab") != 0)
{
cout << "\n\nERROR from PARAMETERS::verify_parameters solver_type should be either hypre_ilu_gmres, eigen_ilu_bicgstab or eigen_direct; current value: " << solver_type << "\n\n";
throw bad_exception();
}
if (meshfile.find_last_of(".") + 1 == meshfile.size())
{
cout << "\n\nERROR from PARAMETERS::verify_parameters extension of meshfile should be msh; \nUnable to find extension in the meshfile: " << meshfile << "\n\n";
throw bad_exception();
}
string extension = meshfile.substr(meshfile.find_last_of(".") + 1, meshfile.size());
if (extension != "msh")
{
cout << "\n\nERROR from PARAMETERS::verify_parameters extension of meshfile should be msh; \nCurrent extension: " << extension << " of the meshfile: " << meshfile << "\n\n";
throw bad_exception();
}
output_file_prefix = meshfile;
if (output_file_prefix.find_last_of("/") < output_file_prefix.size()) //remove location details from mesh file name if required
output_file_prefix = output_file_prefix.substr(output_file_prefix.find_last_of("/") + 1, output_file_prefix.size());
if (output_file_prefix.find_last_of(".") < output_file_prefix.size()) //remove extension from mesh file name if required
output_file_prefix.replace(output_file_prefix.begin() + output_file_prefix.find_last_of("."), output_file_prefix.end(), "");
output_file_prefix += "_polydeg_" + to_string(poly_deg);
cout << "PARAMETERS::verify_parameters output_file_prefix: " << output_file_prefix << endl;
}
void PARAMETERS::calc_cloud_num_points()
{
if (dimension == 2)
num_poly_terms = ((int)(0.5 * (poly_deg + 1) * (poly_deg + 2)));
else
num_poly_terms = ((int)((poly_deg + 1) * (poly_deg + 2) * (poly_deg + 3) / 6)); //sum(0.5*(1:poly_deg+1).*(2:poly_deg+2)) = (poly_deg + 1) * (poly_deg + 2) * (poly_deg + 3) / 6
cloud_size = (int)(ceil(cloud_size_multiplier * num_poly_terms));
cout << "PARAMETERS::calc_cloud_num_points num_poly_terms: " << num_poly_terms << ", cloud_size: " << cloud_size << endl;
}
void PARAMETERS::get_problem_dimension_msh()
{ //identify whether its a 2D or 3D gmsh grid
clock_t start = clock();
int dim = 2;
FILE *file;
int itemp, ncv, cv_type, eof_flag = 0;
double dtemp;
char temp[50];
file = fopen(meshfile.c_str(), "r");
while (true)
{
eof_flag = fscanf(file, "%s ", temp);
if (strcmp(temp, "$MeshFormat") == 0)
break;
if (eof_flag < 0)
{
printf("\n\nERROR from PARAMETERS::get_problem_dimension_msh $MeshFormat not found in %s file\n\n", meshfile.c_str());
throw bad_exception();
}
}
// fscanf(file, "%s", temp);
fgets(temp, 50, file);
if (strcmp(temp, "2.2 0 8\n") != 0)
{
printf("\n\nERROR from PARAMETERS::get_problem_dimension_msh MeshFormat should be 2.2 0 8; but %s file has %s format instead\n\n", meshfile.c_str(), temp);
throw bad_exception();
}
eof_flag = 0;
while (true)
{
eof_flag = fscanf(file, "%s ", temp);
if (strcmp(temp, "$Nodes") == 0)
break;
if (eof_flag < 0)
{
printf("\n\nERROR from PARAMETERS::get_problem_dimension_msh $Nodes not found in %s file\n\n", meshfile.c_str());
throw bad_exception();
}
}
eof_flag = 0;
while (true)
{
eof_flag = fscanf(file, "%s ", temp);
if (strcmp(temp, "$Elements") == 0)
break;
if (eof_flag < 0)
{
printf("\n\nERROR from PARAMETERS::get_problem_dimension_msh $Elements not found in %s file\n\n", meshfile.c_str());
throw bad_exception();
}
}
fscanf(file, "%i ", &ncv);
// cout << "get_problem_dimension_msh ncv = " << ncv << endl;
//reference: http://www.manpagez.com/info/gmsh/gmsh-2.2.6/gmsh_63.php
for (int icv = 0; icv < ncv; icv++)
{
fscanf(file, "%i ", &itemp); //cv number
fscanf(file, "%i ", &cv_type); //cv type
if (cv_type == 4 || cv_type == 5 || cv_type == 6 || cv_type == 7)
{ //4-node tetrahedron || 8-node hexahedron || 6-node prism || 5-node pyramid
dim = 3;
break; //3D element found
}
else if (cv_type == 11 || cv_type == 12 || cv_type == 13 || cv_type == 14)
{ //10-node tetrahedron || 27-node hexahedron || 18-node prism || 14-node pyramid
dim = 3;
break; //3D element found
}
else if (cv_type == 17 || cv_type == 18 || cv_type == 19)
{ //20-node hexahedron || 15-node prism || 13-node pyramid
dim = 3;
break; //3D element found
}
else if (cv_type == 29 || cv_type == 30 || cv_type == 31)
{ //20-node tetrahedron || 35-node tetrahedron || 56-node tetrahedron
dim = 3;
break; //3D element found
}
fscanf(file, "%*[^\n]\n"); //skip reading remaining row
}
dimension = dim;
cout << "PARAMETERS::get_problem_dimension_msh problem dimension: " << dimension << endl;
}
void PARAMETERS::calc_polynomial_term_exponents()
{
polynomial_term_exponents.resize(num_poly_terms, dimension);
Eigen::MatrixXi deg_temp;
if (dimension == 2)
{
polynomial_term_exponents.row(0) = Eigen::MatrixXi::Zero(1, dimension); //constant term
polynomial_term_exponents.block(1, 0, dimension, dimension) = Eigen::MatrixXi::Identity(dimension, dimension); //two linear terms
int previous_index = 1;
for (int deg = 2; deg <= poly_deg; deg++)
{ //quadratic onwards terms
deg_temp.resize(deg + 1, dimension);
for (int i = previous_index; i < previous_index + deg; i++)
{
deg_temp(i - previous_index, 0) = 1 + polynomial_term_exponents(i, 0); //exponents of 'x'
deg_temp(i - previous_index, 1) = polynomial_term_exponents(i, 1); //exponents of 'y'
}
deg_temp(deg, 0) = 0;
deg_temp(deg, 1) = deg;
previous_index = previous_index + deg;
polynomial_term_exponents.block(previous_index, 0, deg + 1, dimension) = deg_temp;
}
}
else
{
polynomial_term_exponents.row(0) = Eigen::MatrixXi::Zero(1, dimension); //constant term
polynomial_term_exponents.block(1, 0, dimension, dimension) = Eigen::MatrixXi::Identity(dimension, dimension); //three linear terms
int previous_index = 1;
for (int deg = 2; deg <= poly_deg; deg++)
{ //quadratic onwards terms
deg_temp.resize(0.5 * (deg + 1) * (deg + 2), dimension);
for (int i = previous_index; i < previous_index + (deg * (deg + 1) / 2); i++)
{
deg_temp(i - previous_index, 0) = 1 + polynomial_term_exponents(i, 0); //exponents of 'x'
deg_temp(i - previous_index, 1) = polynomial_term_exponents(i, 1); //exponents of 'y'
deg_temp(i - previous_index, 2) = polynomial_term_exponents(i, 2); //exponents of 'z'
}
for (int i = previous_index + (0.5 * deg * (deg - 1)); i < previous_index + (0.5 * deg * (deg + 1)); i++)
{
deg_temp(i - previous_index + deg, 0) = polynomial_term_exponents(i, 0); //exponents of 'x'
deg_temp(i - previous_index + deg, 1) = 1 + polynomial_term_exponents(i, 1); //exponents of 'y'
deg_temp(i - previous_index + deg, 2) = polynomial_term_exponents(i, 2); //exponents of 'z'
}
deg_temp((0.5 * (deg + 1) * (deg + 2)) - 1, 0) = 0;
deg_temp((0.5 * (deg + 1) * (deg + 2)) - 1, 1) = 0;
deg_temp((0.5 * (deg + 1) * (deg + 2)) - 1, 2) = deg;
previous_index = previous_index + (0.5 * deg * (deg + 1));
polynomial_term_exponents.block(previous_index, 0, 0.5 * (deg + 1) * (deg + 2), dimension) = deg_temp;
}
}
}
void PARAMETERS::calc_dt(Eigen::SparseMatrix<double, Eigen::RowMajor> &grad_x, Eigen::SparseMatrix<double, Eigen::RowMajor> &grad_y, Eigen::SparseMatrix<double, Eigen::RowMajor> &grad_z, Eigen::SparseMatrix<double, Eigen::RowMajor> &laplacian, double u0, double v0, double w0, double alpha)
{
Eigen::VectorXcd eigval_grad_x, eigval_grad_y, eigval_grad_z, eigval_laplacian;
eigval_grad_x = calc_largest_magnitude_eigenvalue(grad_x);
eigval_grad_y = calc_largest_magnitude_eigenvalue(grad_y);
if (dimension == 3)
eigval_grad_z = calc_largest_magnitude_eigenvalue(grad_z);
eigval_laplacian = calc_largest_magnitude_eigenvalue(laplacian);
grad_x_eigval_real = eigval_grad_x[0].real(), grad_x_eigval_imag = eigval_grad_x[0].imag();
grad_y_eigval_real = eigval_grad_y[0].real(), grad_y_eigval_imag = eigval_grad_y[0].imag();
if (dimension == 3)
grad_z_eigval_real = eigval_grad_z[0].real(), grad_z_eigval_imag = eigval_grad_z[0].imag();
laplace_eigval_real = eigval_laplacian[0].real(), laplace_eigval_imag = eigval_laplacian[0].imag();
printf("\nPARAMETERS::calc_dt Eigenvalue with largest magnitude: grad_x: (%g, %g)\n", eigval_grad_x[0].real(), eigval_grad_x[0].imag());
printf("PARAMETERS::calc_dt Eigenvalue with largest magnitude: grad_y: (%g, %g)\n", eigval_grad_y[0].real(), eigval_grad_y[0].imag());
if (dimension == 3)
printf("PARAMETERS::calc_dt Eigenvalue with largest magnitude: grad_z: (%g, %g)\n", eigval_grad_z[0].real(), eigval_grad_z[0].imag());
printf("PARAMETERS::calc_dt Eigenvalue with largest magnitude: laplacian: (%g, %g)\n", eigval_laplacian[0].real(), eigval_laplacian[0].imag());
double evalues = u0 * sqrt((eigval_grad_x[0].real() * eigval_grad_x[0].real()) + (eigval_grad_x[0].imag() * eigval_grad_x[0].imag()));
evalues += v0 * sqrt((eigval_grad_y[0].real() * eigval_grad_y[0].real()) + (eigval_grad_y[0].imag() * eigval_grad_y[0].imag()));
if (dimension == 3)
evalues += w0 * sqrt((eigval_grad_z[0].real() * eigval_grad_z[0].real()) + (eigval_grad_z[0].imag() * eigval_grad_z[0].imag()));
evalues += alpha * sqrt((eigval_laplacian[0].real() * eigval_laplacian[0].real()) + (eigval_laplacian[0].imag() * eigval_laplacian[0].imag()));
dt = 2.0 / evalues; //forward Euler
dt = dt * Courant;
printf("PARAMETERS::calc_dt Courant: %g, dt: %g seconds\n\n", Courant, dt);
} | 48.674576 | 290 | 0.622954 | shahaneshantanu |
0f2fdea1345bc464c9bdb2b115885013fafec6fc | 623 | hpp | C++ | include/react/detail/either.hpp | ldionne/react | 57b51d179661a9c21bc1f987d124722ac36399ac | [
"BSL-1.0"
] | 6 | 2015-06-05T17:48:12.000Z | 2020-10-04T03:45:18.000Z | include/react/detail/either.hpp | ldionne/react | 57b51d179661a9c21bc1f987d124722ac36399ac | [
"BSL-1.0"
] | 1 | 2021-06-23T05:51:46.000Z | 2021-06-23T05:51:46.000Z | include/react/detail/either.hpp | ldionne/react | 57b51d179661a9c21bc1f987d124722ac36399ac | [
"BSL-1.0"
] | 2 | 2016-05-06T06:55:40.000Z | 2020-03-25T19:19:14.000Z | /*!
* @file
* Defines `react::detail::either`.
*/
#ifndef REACT_DETAIL_EITHER_HPP
#define REACT_DETAIL_EITHER_HPP
namespace react {
namespace either_detail {
template <typename Left, typename Right>
auto either_impl(typename Left::type*) -> Left;
template <typename Left, typename Right>
auto either_impl(...) -> Right;
} // end namespace either_detail
namespace detail {
template <typename Left, typename Right>
struct either
: decltype(either_detail::either_impl<Left, Right>(nullptr))
{ };
} // end namespace detail
} // end namespace react
#endif // !REACT_DETAIL_EITHER_HPP
| 23.074074 | 68 | 0.704655 | ldionne |
0f309eef930ac51ebd33a7739e312482a967d776 | 4,567 | cc | C++ | test/tcp_client_test.cc | chengchenwish/evpp | 750f87eb7c0f0313c85e280f41ba0f424ad455ce | [
"BSD-3-Clause"
] | 3,189 | 2017-03-04T02:56:39.000Z | 2022-03-31T16:06:08.000Z | test/tcp_client_test.cc | chengchenwish/evpp | 750f87eb7c0f0313c85e280f41ba0f424ad455ce | [
"BSD-3-Clause"
] | 259 | 2017-03-07T02:01:25.000Z | 2022-03-27T09:16:19.000Z | test/tcp_client_test.cc | chengchenwish/evpp | 750f87eb7c0f0313c85e280f41ba0f424ad455ce | [
"BSD-3-Clause"
] | 990 | 2017-03-06T03:55:43.000Z | 2022-03-24T10:50:18.000Z | #include "test_common.h"
#include <evpp/libevent.h>
#include <evpp/event_watcher.h>
#include <evpp/event_loop.h>
#include <evpp/event_loop_thread.h>
#include <evpp/tcp_server.h>
#include <evpp/buffer.h>
#include <evpp/tcp_conn.h>
#include <evpp/tcp_client.h>
TEST_UNIT(testTCPClientConnectFailed) {
std::shared_ptr<evpp::EventLoop> loop(new evpp::EventLoop);
std::shared_ptr<evpp::TCPClient> client(new evpp::TCPClient(loop.get(), "127.0.0.1:39723", "TCPPingPongClient"));
client->SetConnectionCallback([&loop, &client](const evpp::TCPConnPtr& conn) {
H_TEST_ASSERT(!conn->IsConnected());
client->Disconnect();
loop->Stop();
});
client->set_auto_reconnect(false);
client->Connect();
loop->Run();
client.reset();
loop.reset();
H_TEST_ASSERT(evpp::GetActiveEventCount() == 0);
}
TEST_UNIT(testTCPClientDisconnectImmediately) {
std::shared_ptr<evpp::EventLoop> loop(new evpp::EventLoop);
std::shared_ptr<evpp::TCPClient> client(new evpp::TCPClient(loop.get(), "cmake.org:80", "TCPPingPongClient"));
client->SetConnectionCallback([loop, client](const evpp::TCPConnPtr& conn) {
H_TEST_ASSERT(!conn->IsConnected());
auto f = [loop]() { loop->Stop(); };
loop->RunAfter(1.0, f);
});
client->set_auto_reconnect(false);
client->Connect();
client->Disconnect();
loop->Run();
client.reset();
loop.reset();
H_TEST_ASSERT(evpp::GetActiveEventCount() == 0);
}
TEST_UNIT(testTCPClientConnectionTimeout) {
std::shared_ptr<evpp::EventLoop> loop(new evpp::EventLoop);
std::shared_ptr<evpp::TCPClient> client(new evpp::TCPClient(loop.get(), "cmake.org:80", "TCPPingPongClient"));
client->SetConnectionCallback([loop, client](const evpp::TCPConnPtr& conn) {
loop->Stop();
});
client->set_auto_reconnect(false);
client->set_connecting_timeout(evpp::Duration(0.0001));
client->Connect();
loop->Run();
client.reset();
loop.reset();
H_TEST_ASSERT(evpp::GetActiveEventCount() == 0);
}
namespace {
struct NSQConn {
NSQConn(evpp::EventLoop* loop) : loop_(loop) {
client_ = std::make_shared<evpp::TCPClient>(loop, "www.so.com:80", "TCPPingPongClient");
client_->SetConnectionCallback([this](const evpp::TCPConnPtr& conn) {
H_TEST_ASSERT(conn->IsConnected());
H_TEST_ASSERT(this->loop_->IsRunning());
this->connected_ = true;
client_->SetConnectionCallback(evpp::ConnectionCallback());
});
client_->Connect();
}
void Disconnect() {
if (!connected_) {
loop_->RunAfter(100.0, [this]() {this->Disconnect(); });
return;
}
// We call TCPClient::Disconnect and then delete the hold object of TCPClient immediately
client_->Disconnect();
client_.reset();
connected_ = false;
loop_->RunAfter(100.0, [this]() {this->loop_->Stop(); });
}
std::shared_ptr<evpp::TCPClient> client_;
bool connected_ = false;
evpp::EventLoop* loop_;
};
}
TEST_UNIT(testTCPClientDisconnectAndDestruct) {
std::shared_ptr<evpp::EventLoop> loop(new evpp::EventLoop);
NSQConn nc(loop.get());
loop->RunAfter(100.0, [&nc]() {nc.Disconnect(); });
loop->Run();
loop.reset();
H_TEST_ASSERT(evpp::GetActiveEventCount() == 0);
}
TEST_UNIT(testTCPClientConnectLocalhost) {
evpp::EventLoop loop;
evpp::TCPClient client(&loop, "localhost:39099", "TestClient");
client.SetConnectionCallback([&loop, &client](const evpp::TCPConnPtr& conn) {
H_TEST_ASSERT(!conn->IsConnected());
client.Disconnect();
loop.Stop();
});
client.SetMessageCallback([](const evpp::TCPConnPtr& conn, evpp::Buffer* buf) {});
client.Connect();
loop.Run();
H_TEST_ASSERT(evpp::GetActiveEventCount() == 0);
}
TEST_UNIT(TestTCPClientDisconnectImmediatelyIssue172) {
const std::string strAddr = "qup.f.360.cn:80";
evpp::EventLoop loop;
evpp::TCPClient client(&loop, strAddr, "TestClient");
client.SetConnectionCallback([&loop, &client](const evpp::TCPConnPtr& conn) {
if (conn->IsConnected()) {
auto f = [&]() {
client.Disconnect();
loop.Stop();
};
loop.RunAfter(evpp::Duration(1.0), f);
}
}
);
client.SetMessageCallback([](const evpp::TCPConnPtr& conn, evpp::Buffer* buf) {
std::string strMsg = buf->NextAllString();
});
client.Connect();
loop.Run();
} | 33.580882 | 117 | 0.631706 | chengchenwish |
0f3542ebd5f79b9e21004f8d57726f8f5d30619a | 369 | hpp | C++ | gearoenix/render/buffer/gx-rnd-buf-dynamic.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 35 | 2018-01-07T02:34:38.000Z | 2022-02-09T05:19:03.000Z | gearoenix/render/buffer/gx-rnd-buf-dynamic.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 111 | 2017-09-20T09:12:36.000Z | 2020-12-27T12:52:03.000Z | gearoenix/render/buffer/gx-rnd-buf-dynamic.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 5 | 2020-02-11T11:17:37.000Z | 2021-01-08T17:55:43.000Z | #ifndef GEAROENIX_RENDER_BUFFER_DYNAMIC_HPP
#define GEAROENIX_RENDER_BUFFER_DYNAMIC_HPP
#include "gx-rnd-buf-buffer.hpp"
namespace gearoenix::render::buffer {
class Dynamic : public Buffer {
protected:
Dynamic(const unsigned int s, engine::Engine* const e) noexcept
: Buffer(s, e)
{
}
public:
virtual ~Dynamic() noexcept = default;
};
}
#endif
| 21.705882 | 67 | 0.723577 | Hossein-Noroozpour |
0f38b2c5e0a7119a8cd7e2acf0fd6b9ad7c81e9a | 2,482 | cpp | C++ | Error.cpp | dascenzo/MyDictionary | f258f987f05d58be0c0df6eec58eec6be0b441dc | [
"MIT"
] | 1 | 2021-01-28T14:29:01.000Z | 2021-01-28T14:29:01.000Z | Error.cpp | dascenzo/MyDictionary | f258f987f05d58be0c0df6eec58eec6be0b441dc | [
"MIT"
] | null | null | null | Error.cpp | dascenzo/MyDictionary | f258f987f05d58be0c0df6eec58eec6be0b441dc | [
"MIT"
] | null | null | null | #include "Error.h"
#include <cstdio>
MissingArgument::MissingArgument(Variant action, std::string_view option) noexcept
: ActionMisuseNoShorthand(std::move(action)), m_option(option) {
}
const char* MissingArgument::option() const noexcept {
return m_option;
}
InvalidArgument::InvalidArgument(Variant action, std::string_view option, std::string_view argument) noexcept
: ActionMisuseNoShorthand(std::move(action)), m_option(option), m_argument(argument) {
}
const char* InvalidArgument::option() const noexcept {
return m_option;
}
const char* InvalidArgument::argument() const noexcept {
return m_argument;
}
UsageError::UsageError(Variant variant) noexcept
: m_variant(std::move(variant)) {
}
const char* UsageError::what() const noexcept {
return "invalid usage";
}
const UsageError::Variant& UsageError::variant() const noexcept {
return m_variant;
}
BadEnvVar::BadEnvVar(std::string_view badVariable) noexcept
: m_badVariable(badVariable) {
}
const char* BadEnvVar::variable() const noexcept {
return m_badVariable;
}
SetEnvFailed::SetEnvFailed(int errNo) noexcept
: m_errNo(errNo) {
}
int SetEnvFailed::errNo() const noexcept {
return m_errNo;
}
EnvironmentSetupError::EnvironmentSetupError(Variant variant) noexcept
: m_variant(std::move(variant)) {
}
const EnvironmentSetupError::Variant& EnvironmentSetupError::variant() const noexcept {
return m_variant;
}
const char* EnvironmentSetupError::what() const noexcept {
return "environment setup error";
};
DataStateError::DataStateError(DataVariant data, ErrorType errorType) noexcept
: m_data(std::move(data)), m_errorType(errorType) {
}
const DataStateError::DataVariant& DataStateError::data() const noexcept {
return m_data;
}
DataStateError::ErrorType DataStateError::type() const noexcept {
return m_errorType;
}
const char* DataStateError::what() const noexcept {
return "data state error";
}
UpdateSpecificationError::UpdateSpecificationError(std::string_view word) noexcept
: m_word(word) {
}
const char* UpdateSpecificationError::word() const noexcept {
return m_word;
}
const char* UpdateSpecificationError::what() const noexcept {
static_assert(std::is_same_v<decltype(m_word), SafeString>, "buffer size determination not valid");
static std::array<char, SafeString::maxStringLength + 100 /* for context text */> buf;
std::sprintf(buf.data(), "nothing specified to be updated for entry (word=%s)",
static_cast<const char*>(m_word));
return buf.data();
}
| 33.540541 | 109 | 0.763497 | dascenzo |
0f394b0de39f090d8d7e6278831746d78210eb93 | 168 | cpp | C++ | AdaLovelace2020/kipr/audio.cpp | AdaLovelace-Botball/Botball2020 | c2cecbd40218e4434ceaf45a50651b35c575eb10 | [
"MIT"
] | null | null | null | AdaLovelace2020/kipr/audio.cpp | AdaLovelace-Botball/Botball2020 | c2cecbd40218e4434ceaf45a50651b35c575eb10 | [
"MIT"
] | null | null | null | AdaLovelace2020/kipr/audio.cpp | AdaLovelace-Botball/Botball2020 | c2cecbd40218e4434ceaf45a50651b35c575eb10 | [
"MIT"
] | null | null | null | /*
* audio.cpp
*
* Created on: Nov 13, 2015
* Author: Joshua Southerland
*/
#include "wallaby/audio.h"
#include <cstdio>
void beep()
{
printf("\a");
}
| 9.882353 | 34 | 0.577381 | AdaLovelace-Botball |
0f3ce89ccc8f77617da456671d594cd839868d8b | 1,102 | cpp | C++ | EU4toV3/Source/Mappers/Titles/TitleMapping.cpp | Idhrendur/EU4toVic3 | b29ba8e59a3bd14af11fb6b30f4626cde7264a4f | [
"MIT"
] | 3 | 2018-12-23T17:04:15.000Z | 2021-05-06T14:12:28.000Z | EU4toV2/Source/Mappers/Titles/TitleMapping.cpp | IhateTrains/EU4toVic2 | 061f5e1a0bc1a1f3b54bdfe471b501260149b56b | [
"MIT"
] | null | null | null | EU4toV2/Source/Mappers/Titles/TitleMapping.cpp | IhateTrains/EU4toVic2 | 061f5e1a0bc1a1f3b54bdfe471b501260149b56b | [
"MIT"
] | null | null | null | #include "TitleMapping.h"
#include "ParserHelpers.h"
#include "CommonRegexes.h"
mappers::TitleMapping::TitleMapping(std::istream& theStream)
{
registerKeys();
parseStream(theStream);
clearRegisteredKeywords();
}
void mappers::TitleMapping::registerKeys()
{
registerKeyword("name", [this](const std::string& unused, std::istream& theStream) {
name = commonItems::singleString(theStream).getString();
transform(name.begin(), name.end(), name.begin(), ::tolower);
});
registerKeyword("title", [this](const std::string& unused, std::istream& theStream) {
title = commonItems::singleString(theStream).getString();
});
registerKeyword("region", [this](const std::string& unused, std::istream& theStream) {
region = commonItems::singleString(theStream).getString();
});
registerRegex(commonItems::catchallRegex, commonItems::ignoreItem);
}
bool mappers::TitleMapping::hasIslamicRegion() const
{
return region == "e_persia" || region == "e_arabia";
}
bool mappers::TitleMapping::hasIndianRegion() const
{
return region == "e_rajastan" || region == "e_bengal" || region == "e_deccan";
}
| 30.611111 | 87 | 0.725045 | Idhrendur |
0f4023e200b5020fec5f29bb12ee6013d768d349 | 219 | hpp | C++ | Libraries/Graphics/Precompiled.hpp | jodavis42/ZilchShadersSamples | 3c94d295b68ae2e81ece3b12f3a17fe7d59566de | [
"MIT"
] | 1 | 2019-08-31T00:45:44.000Z | 2019-08-31T00:45:44.000Z | Libraries/Graphics/Precompiled.hpp | jodavis42/ZilchShadersSamples | 3c94d295b68ae2e81ece3b12f3a17fe7d59566de | [
"MIT"
] | 2 | 2019-09-08T16:06:05.000Z | 2019-09-08T16:06:58.000Z | Libraries/Graphics/Precompiled.hpp | jodavis42/ZilchShadersSamples | 3c94d295b68ae2e81ece3b12f3a17fe7d59566de | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
/// Authors: Joshua Davis
///////////////////////////////////////////////////////////////////////////////
#include "GraphicsStandard.hpp"
| 36.5 | 79 | 0.200913 | jodavis42 |
0f436bec11e66a3506319833a0729ba0c27a96e9 | 1,262 | cpp | C++ | ch03/stringtest.cpp | dingqunfei/CppPrimerPamphlet | fee63cd05d0e3c6c01c42c08376797c993ffafde | [
"Apache-2.0"
] | null | null | null | ch03/stringtest.cpp | dingqunfei/CppPrimerPamphlet | fee63cd05d0e3c6c01c42c08376797c993ffafde | [
"Apache-2.0"
] | null | null | null | ch03/stringtest.cpp | dingqunfei/CppPrimerPamphlet | fee63cd05d0e3c6c01c42c08376797c993ffafde | [
"Apache-2.0"
] | null | null | null | /**
* @file test.cpp
* @brief
* @author dqflying (dqflying@gmail.com)
* @version 1.0
* @date 2020-06-03
*
* @copyright Copyright (c) 2020 DQFLYING.INC
*
* @par 新增文件:
*
*
* Date Version Author LISENCE
* 2020-06-03 1.0 dqflying XXXXXXX
* Description:
*
*
*/
#include <string>
#include <iostream>
#include <cstring>
#include <iterator>
#include <vector>
using namespace std;
int main(int argc, char **argv)
{
char cstr[] = {'a', 'b', 'c', 'd', '\0'};
std::cout << strlen(cstr) << std::endl;
std::vector<char> chVec(std::begin(cstr), std::end(cstr));
std::string forstr("Hello world!!!");
for(auto &letter: forstr)
{
letter = toupper(letter);
}
std::cout << forstr << std::endl;
//初始化
string s1 = "abcdefg";
string s2 = s1;
string s3("hijklmn");
string s4(s3);
string s5(10, 'j');
string s6 = string("abc");
string s7 = string(10, 'k');
//getline 函数
string input;
while(getline(cin, input))
{
if(input.size())
{
cout << input << endl;
}
}
//io
string s8, s9;
cin >> s8 >> s9;
cout << s8 << s9 << endl;
return 0;
} | 18.028571 | 62 | 0.504754 | dingqunfei |
0f4528e7c75a7b5e9c084d1c2ee63de397ef07e7 | 3,006 | cpp | C++ | libs/graph/example/cycle_ratio_example.cpp | zyiacas/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | libs/graph/example/cycle_ratio_example.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | libs/graph/example/cycle_ratio_example.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | // Copyright (C) 2006-2009 Dmitry Bufistov and Andrey Parfenov
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <cassert>
#include <ctime>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/random.hpp>
#include <boost/graph/howard_cycle_ratio.hpp>
/**
* @author Dmitry Bufistov
* @author Andrey Parfenov
*/
using namespace boost;
typedef adjacency_list<
listS, listS, directedS,
property<vertex_index_t, int>,
property<
edge_weight_t, double, property<edge_weight2_t, double>
>
> grap_real_t;
template <typename TG>
void gen_rand_graph(TG &g, size_t nV, size_t nE)
{
g.clear();
mt19937 rng;
rng.seed(uint32_t(time(0)));
boost::generate_random_graph(g, nV, nE, rng, true, true);
boost::uniform_real<> ur(-1,10);
boost::variate_generator<boost::mt19937&, boost::uniform_real<> > ew1rg(rng, ur);
randomize_property<edge_weight_t>(g, ew1rg);
boost::uniform_int<size_t> uint(1,5);
boost::variate_generator<boost::mt19937&, boost::uniform_int<size_t> > ew2rg(rng, uint);
randomize_property<edge_weight2_t>(g, ew2rg);
}
int main(int argc, char* argv[])
{
using std::cout;
using std::endl;
const double epsilon = 0.0000001;
double min_cr, max_cr; ///Minimum and maximum cycle ratio
typedef std::vector<graph_traits<grap_real_t>::edge_descriptor> ccReal_t;
ccReal_t cc; ///critical cycle
grap_real_t tgr;
property_map<grap_real_t, vertex_index_t>::type vim = get(vertex_index, tgr);
property_map<grap_real_t, edge_weight_t>::type ew1 = get(edge_weight, tgr);
property_map<grap_real_t, edge_weight2_t>::type ew2 = get(edge_weight2, tgr);
gen_rand_graph(tgr, 1000, 30000);
cout << "Vertices number: " << num_vertices(tgr) << endl;
cout << "Edges number: " << num_edges(tgr) << endl;
int i = 0;
graph_traits<grap_real_t>::vertex_iterator vi, vi_end;
for (boost::tie(vi, vi_end) = vertices(tgr); vi != vi_end; vi++) {
vim[*vi] = i++; ///Initialize vertex index property
}
max_cr = maximum_cycle_ratio(tgr, vim, ew1, ew2);
cout << "Maximum cycle ratio is " << max_cr << endl;
min_cr = minimum_cycle_ratio(tgr, vim, ew1, ew2, &cc);
cout << "Minimum cycle ratio is " << min_cr << endl;
std::pair<double, double> cr(.0,.0);
cout << "Critical cycle:\n";
for (ccReal_t::iterator itr = cc.begin(); itr != cc.end(); ++itr)
{
cr.first += ew1[*itr];
cr.second += ew2[*itr];
std::cout << "(" << vim[source(*itr, tgr)] << "," <<
vim[target(*itr, tgr)] << ") ";
}
cout << endl;
assert(std::abs(cr.first / cr.second - min_cr) < epsilon);
return EXIT_SUCCESS;
}
| 35.785714 | 98 | 0.644045 | zyiacas |
0f4ae352650e1fa61883ecfca758ad4a99c6ef95 | 1,567 | cpp | C++ | android-31/java/time/format/SignStyle.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/time/format/SignStyle.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/time/format/SignStyle.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../../JArray.hpp"
#include "../../../JString.hpp"
#include "./SignStyle.hpp"
namespace java::time::format
{
// Fields
java::time::format::SignStyle SignStyle::ALWAYS()
{
return getStaticObjectField(
"java.time.format.SignStyle",
"ALWAYS",
"Ljava/time/format/SignStyle;"
);
}
java::time::format::SignStyle SignStyle::EXCEEDS_PAD()
{
return getStaticObjectField(
"java.time.format.SignStyle",
"EXCEEDS_PAD",
"Ljava/time/format/SignStyle;"
);
}
java::time::format::SignStyle SignStyle::NEVER()
{
return getStaticObjectField(
"java.time.format.SignStyle",
"NEVER",
"Ljava/time/format/SignStyle;"
);
}
java::time::format::SignStyle SignStyle::NORMAL()
{
return getStaticObjectField(
"java.time.format.SignStyle",
"NORMAL",
"Ljava/time/format/SignStyle;"
);
}
java::time::format::SignStyle SignStyle::NOT_NEGATIVE()
{
return getStaticObjectField(
"java.time.format.SignStyle",
"NOT_NEGATIVE",
"Ljava/time/format/SignStyle;"
);
}
// QJniObject forward
SignStyle::SignStyle(QJniObject obj) : java::lang::Enum(obj) {}
// Constructors
// Methods
java::time::format::SignStyle SignStyle::valueOf(JString arg0)
{
return callStaticObjectMethod(
"java.time.format.SignStyle",
"valueOf",
"(Ljava/lang/String;)Ljava/time/format/SignStyle;",
arg0.object<jstring>()
);
}
JArray SignStyle::values()
{
return callStaticObjectMethod(
"java.time.format.SignStyle",
"values",
"()[Ljava/time/format/SignStyle;"
);
}
} // namespace java::time::format
| 21.175676 | 64 | 0.674537 | YJBeetle |
0f51b824b220cbc7eec4093f0be20bbfce17125b | 8,423 | cpp | C++ | libtsuba/src/RDGCore.cpp | bozhiyou/katana | 74aef79010f6db444b19e94bac28e8f7c8856338 | [
"BSD-3-Clause"
] | null | null | null | libtsuba/src/RDGCore.cpp | bozhiyou/katana | 74aef79010f6db444b19e94bac28e8f7c8856338 | [
"BSD-3-Clause"
] | null | null | null | libtsuba/src/RDGCore.cpp | bozhiyou/katana | 74aef79010f6db444b19e94bac28e8f7c8856338 | [
"BSD-3-Clause"
] | null | null | null | #include "RDGCore.h"
#include "RDGPartHeader.h"
#include "katana/ArrowInterchange.h"
#include "katana/Result.h"
#include "tsuba/Errors.h"
#include "tsuba/ParquetReader.h"
namespace {
katana::Result<void>
UpsertProperties(
const std::shared_ptr<arrow::Table>& props,
std::shared_ptr<arrow::Table>* to_update,
std::vector<tsuba::PropStorageInfo>* prop_state) {
if (!props->schema()->HasDistinctFieldNames()) {
return KATANA_ERROR(
tsuba::ErrorCode::Exists, "column names must be distinct: {}",
fmt::join(props->schema()->field_names(), ", "));
}
if (prop_state->empty()) {
KATANA_LOG_ASSERT((*to_update)->num_columns() == 0);
for (const auto& field : props->fields()) {
prop_state->emplace_back(field->name(), field->type());
}
*to_update = props;
return katana::ResultSuccess();
}
std::shared_ptr<arrow::Table> next = *to_update;
if (next->num_columns() > 0 && next->num_rows() != props->num_rows()) {
return KATANA_ERROR(
tsuba::ErrorCode::InvalidArgument, "expected {} rows found {} instead",
next->num_rows(), props->num_rows());
}
int last = next->num_columns();
for (int i = 0, n = props->num_columns(); i < n; i++) {
std::shared_ptr<arrow::Field> field = props->field(i);
int current_col = -1;
auto prop_info_it = std::find_if(
prop_state->begin(), prop_state->end(),
[&](const tsuba::PropStorageInfo& psi) {
return field->name() == psi.name();
});
if (prop_info_it == prop_state->end()) {
prop_info_it = prop_state->insert(
prop_info_it, tsuba::PropStorageInfo(field->name(), field->type()));
} else if (!prop_info_it->IsAbsent()) {
current_col = next->schema()->GetFieldIndex(field->name());
}
if (current_col < 0) {
if (next->num_columns() == 0) {
next = arrow::Table::Make(arrow::schema({field}), {props->column(i)});
} else {
next = KATANA_CHECKED_CONTEXT(
next->AddColumn(last++, field, props->column(i)), "insert");
}
} else {
next = KATANA_CHECKED_CONTEXT(
next->SetColumn(current_col, field, props->column(i)), "update");
}
prop_info_it->WasModified(field->type());
}
if (!next->schema()->HasDistinctFieldNames()) {
return KATANA_ERROR(
tsuba::ErrorCode::Exists, "column names are not distinct: {}",
fmt::join(next->schema()->field_names(), ", "));
}
*to_update = next;
return katana::ResultSuccess();
}
katana::Result<void>
AddProperties(
const std::shared_ptr<arrow::Table>& props,
std::shared_ptr<arrow::Table>* to_update,
std::vector<tsuba::PropStorageInfo>* prop_state) {
for (const auto& field : props->fields()) {
// Column names are not sorted, but assumed to be less than 100s
auto prop_info_it = std::find_if(
prop_state->begin(), prop_state->end(),
[&](const tsuba::PropStorageInfo& psi) {
return field->name() == psi.name();
});
if (prop_info_it != prop_state->end()) {
return KATANA_ERROR(
tsuba::ErrorCode::Exists, "column names are not distinct");
}
}
return UpsertProperties(props, to_update, prop_state);
}
katana::Result<void>
EnsureTypeLoaded(const katana::Uri& rdg_dir, tsuba::PropStorageInfo* psi) {
if (!psi->type()) {
auto reader = KATANA_CHECKED(tsuba::ParquetReader::Make());
KATANA_LOG_ASSERT(psi->IsAbsent());
std::shared_ptr<arrow::Schema> schema =
KATANA_CHECKED(reader->GetSchema(rdg_dir.Join(psi->path())));
psi->set_type(schema->field(0)->type());
}
return katana::ResultSuccess();
}
} // namespace
namespace tsuba {
katana::Result<void>
RDGCore::AddPartitionMetadataArray(const std::shared_ptr<arrow::Table>& props) {
auto field = props->schema()->field(0);
const std::string& name = field->name();
std::shared_ptr<arrow::ChunkedArray> col = props->column(0);
if (name.find(kMirrorNodesPropName) == 0) {
AddMirrorNodes(std::move(col));
} else if (name.find(kMasterNodesPropName) == 0) {
AddMasterNodes(std::move(col));
} else if (name == kHostToOwnedGlobalNodeIDsPropName) {
set_host_to_owned_global_node_ids(std::move(col));
} else if (name == kHostToOwnedGlobalEdgeIDsPropName) {
set_host_to_owned_global_edge_ids(std::move(col));
} else if (name == kLocalToUserIDPropName) {
set_local_to_user_id(std::move(col));
} else if (name == kLocalToGlobalIDPropName) {
set_local_to_global_id(std::move(col));
} else if (name == kDeprecatedLocalToGlobalIDPropName) {
KATANA_LOG_WARN(
"deprecated graph format; replace the existing graph by storing the "
"current graph");
set_local_to_global_id(std::move(col));
} else if (name == kDeprecatedHostToOwnedGlobalNodeIDsPropName) {
KATANA_LOG_WARN(
"deprecated graph format; replace the existing graph by storing the "
"current graph");
set_host_to_owned_global_node_ids(std::move(col));
} else {
return KATANA_ERROR(ErrorCode::InvalidArgument, "checking metadata name");
}
return katana::ResultSuccess();
}
katana::Result<void>
RDGCore::AddNodeProperties(const std::shared_ptr<arrow::Table>& props) {
return AddProperties(
props, &node_properties_, &part_header_.node_prop_info_list());
}
katana::Result<void>
RDGCore::AddEdgeProperties(const std::shared_ptr<arrow::Table>& props) {
return AddProperties(
props, &edge_properties_, &part_header_.edge_prop_info_list());
}
katana::Result<void>
RDGCore::UpsertNodeProperties(const std::shared_ptr<arrow::Table>& props) {
return UpsertProperties(
props, &node_properties_, &part_header_.node_prop_info_list());
}
katana::Result<void>
RDGCore::UpsertEdgeProperties(const std::shared_ptr<arrow::Table>& props) {
return UpsertProperties(
props, &edge_properties_, &part_header_.edge_prop_info_list());
}
katana::Result<void>
RDGCore::EnsureNodeTypesLoaded() {
if (rdg_dir_.empty()) {
return KATANA_ERROR(
tsuba::ErrorCode::InvalidArgument,
"no rdg_dir set, cannot ensure node types are loaded");
}
for (auto& prop : part_header_.node_prop_info_list()) {
KATANA_CHECKED_CONTEXT(
EnsureTypeLoaded(rdg_dir_, &prop), "property {}",
std::quoted(prop.name()));
}
return katana::ResultSuccess();
}
katana::Result<void>
RDGCore::EnsureEdgeTypesLoaded() {
if (rdg_dir_.empty()) {
return KATANA_ERROR(
tsuba::ErrorCode::InvalidArgument,
"no rdg_dir set, cannot ensure edge types are loaded");
}
for (auto& prop : part_header_.edge_prop_info_list()) {
KATANA_CHECKED_CONTEXT(
EnsureTypeLoaded(rdg_dir_, &prop), "property {}",
std::quoted(prop.name()));
}
return katana::ResultSuccess();
}
void
tsuba::RDGCore::InitArrowVectors() {
// Create an empty array, accessed by Distribution during loading
host_to_owned_global_node_ids_ = katana::NullChunkedArray(arrow::uint64(), 0);
host_to_owned_global_edge_ids_ = katana::NullChunkedArray(arrow::uint64(), 0);
local_to_user_id_ = katana::NullChunkedArray(arrow::uint64(), 0);
local_to_global_id_ = katana::NullChunkedArray(arrow::uint64(), 0);
}
void
RDGCore::InitEmptyProperties() {
std::vector<std::shared_ptr<arrow::Array>> empty;
node_properties_ = arrow::Table::Make(arrow::schema({}), empty, 0);
edge_properties_ = arrow::Table::Make(arrow::schema({}), empty, 0);
}
bool
RDGCore::Equals(const RDGCore& other) const {
// Assumption: t_f_s and other.t_f_s are both fully loaded into memory
return topology_file_storage_.size() == other.topology_file_storage_.size() &&
!memcmp(
topology_file_storage_.ptr<uint8_t>(),
other.topology_file_storage_.ptr<uint8_t>(),
topology_file_storage_.size()) &&
node_properties_->Equals(*other.node_properties_, true) &&
edge_properties_->Equals(*other.edge_properties_, true);
}
katana::Result<void>
RDGCore::RemoveNodeProperty(int i) {
auto field = node_properties_->field(i);
node_properties_ = KATANA_CHECKED(node_properties_->RemoveColumn(i));
return part_header_.RemoveNodeProperty(field->name());
}
katana::Result<void>
RDGCore::RemoveEdgeProperty(int i) {
auto field = edge_properties_->field(i);
edge_properties_ = KATANA_CHECKED(edge_properties_->RemoveColumn(i));
return part_header_.RemoveEdgeProperty(field->name());
}
} // namespace tsuba
| 33.424603 | 80 | 0.676244 | bozhiyou |
0f55ab3f42af11d94aaf4943bfce2266aeee7cde | 708 | cc | C++ | tests/test_challenge.cc | thomasmarsh/monkey | de79536cad78371cf25ea0c26a492f700e2c92f8 | [
"MIT"
] | 6 | 2016-08-31T06:26:32.000Z | 2022-02-10T23:28:29.000Z | tests/test_challenge.cc | thomasmarsh/monkey | de79536cad78371cf25ea0c26a492f700e2c92f8 | [
"MIT"
] | 1 | 2017-04-26T16:37:35.000Z | 2017-04-26T16:37:35.000Z | tests/test_challenge.cc | thomasmarsh/monkey | de79536cad78371cf25ea0c26a492f700e2c92f8 | [
"MIT"
] | null | null | null | #include "challenge.h"
#include "log.h"
#include "support/catch.hpp"
TEST_CASE("initial challenge state good", "[challenge]") {
Challenge c(4);
REQUIRE(!c.finished());
}
TEST_CASE("detect end of challenge", "[challenge]") {
Challenge c(4);
for (int i=0; i < 4; ++i) {
c.round.pass();
c.step();
}
REQUIRE(c.finished());
}
TEST_CASE("reset after end of challenge", "[challenge]") {
Challenge c(4);
for (int i=0; i < 3; ++i) {
c.round.concede();
c.step();
}
REQUIRE(c.finished());
c.reset();
REQUIRE(!c.finished());
for (int i=0; i < 4; ++i) {
c.round.pass();
c.step();
}
REQUIRE(c.finished());
}
| 19.135135 | 58 | 0.526836 | thomasmarsh |
0f59b28fe549e8636334aa952a1738f96f72200d | 16,807 | cpp | C++ | WDL/plush2/pl_make.cpp | badi91/iPlug2 | e508e85060871cef4ff16c9bc80c503c375e0a14 | [
"Zlib"
] | 1,305 | 2018-07-28T08:48:47.000Z | 2022-03-31T23:06:59.000Z | WDL/plush2/pl_make.cpp | badi91/iPlug2 | e508e85060871cef4ff16c9bc80c503c375e0a14 | [
"Zlib"
] | 582 | 2019-01-01T15:37:55.000Z | 2022-03-30T22:57:16.000Z | WDL/plush2/pl_make.cpp | badi91/iPlug2 | e508e85060871cef4ff16c9bc80c503c375e0a14 | [
"Zlib"
] | 284 | 2018-10-17T22:16:26.000Z | 2022-03-30T15:38:19.000Z | /******************************************************************************
Plush Version 1.2
make.c
Object Primitives
Copyright (c) 1996-2000, Justin Frankel
*******************************************************************************
Notes:
Most of these routines are highly unoptimized.
They could all use some work, such as more capable divisions (Box is
most notable), etc... The mapping coordinates are all set up nicely,
though.
******************************************************************************/
#include "plush.h"
pl_Obj *plMakeTorus(pl_Float r1, pl_Float r2, pl_uInt divrot, pl_uInt divrad,
pl_Mat *m) {
pl_Obj *o;
pl_Vertex *v;
pl_Face *f;
pl_uInt x, y;
double ravg, rt, a, da, al, dal;
pl_Float U,V,dU,dV;
if (divrot < 3) divrot = 3;
if (divrad < 3) divrad = 3;
ravg = (r1+r2)*0.5;
rt = (r2-r1)*0.5;
o = new pl_Obj(divrad*divrot,divrad*divrot*2);
if (!o) return 0;
v = o->Vertices.Get();
a = 0.0;
da = 2*PL_PI/divrot;
for (y = 0; y < divrot; y ++) {
al = 0.0;
dal = 2*PL_PI/divrad;
for (x = 0; x < divrad; x ++) {
v->x = (pl_Float) (cos((double) a)*(ravg + cos((double) al)*rt));
v->z = (pl_Float) (sin((double) a)*(ravg + cos((double) al)*rt));
v->y = (pl_Float) (sin((double) al)*rt);
v++;
al += dal;
}
a += da;
}
v = o->Vertices.Get();
f = o->Faces.Get();
dV = 1.0/divrad;
dU = 1.0/divrot;
U = 0;
for (y = 0; y < divrot; y ++) {
V = -0.5;
for (x = 0; x < divrad; x ++) {
f->VertexIndices[0] = v+x+y*divrad - o->Vertices.Get();
f->MappingU[0][0] = U;
f->MappingV[0][0] = V;
f->VertexIndices[1] = v+(x+1==divrad?0:x+1)+y*divrad - o->Vertices.Get();
f->MappingU[0][1] = U;
f->MappingV[0][1] = V+dV;
f->VertexIndices[2] = v+x+(y+1==divrot?0:(y+1)*divrad) - o->Vertices.Get();
f->MappingU[0][2] = U+dU;
f->MappingV[0][2] = V;
f->Material = m;
f++;
f->VertexIndices[0] = v+x+(y+1==divrot?0:(y+1)*divrad) - o->Vertices.Get();
f->MappingU[0][0] = U+dU;
f->MappingV[0][0] = V;
f->VertexIndices[1] = v+(x+1==divrad?0:x+1)+y*divrad - o->Vertices.Get();
f->MappingU[0][1] = U;
f->MappingV[0][1] = V+dV;
f->VertexIndices[2] = v+(x+1==divrad?0:x+1)+(y+1==divrot?0:(y+1)*divrad) - o->Vertices.Get();
f->MappingU[0][2] = U+dU;
f->MappingV[0][2] = V+dV;
f->Material = m;
f++;
V += dV;
}
U += dU;
}
o->CalculateNormals();
return (o);
}
pl_Obj *plMakeSphere(pl_Float r, pl_uInt divr, pl_uInt divh, pl_Mat *m) {
pl_Obj *o;
pl_Vertex *v;
pl_Face *f;
pl_uInt x, y;
double a, da, yp, ya, yda, yf;
pl_Float U,V,dU,dV;
if (divh < 3) divh = 3;
if (divr < 3) divr = 3;
o = new pl_Obj(2+(divh-2)*(divr),2*divr+(divh-3)*divr*2);
if (!o) return 0;
v = o->Vertices.Get();
v->x = v->z = 0.0; v->y = r; v++;
v->x = v->z = 0.0; v->y = -r; v++;
ya = 0.0;
yda = PL_PI/(divh-1);
da = (PL_PI*2.0)/divr;
for (y = 0; y < divh - 2; y ++) {
ya += yda;
yp = cos((double) ya)*r;
yf = sin((double) ya)*r;
a = 0.0;
for (x = 0; x < divr; x ++) {
v->y = (pl_Float) yp;
v->x = (pl_Float) (cos((double) a)*yf);
v->z = (pl_Float) (sin((double) a)*yf);
v++;
a += da;
}
}
f = o->Faces.Get();
v = o->Vertices.Get() + 2;
a = 0.0;
U = 0;
dU = 1.0/divr;
dV = V = 1.0/divh;
for (x = 0; x < divr; x ++) {
f->VertexIndices[0] = 0;
f->VertexIndices[1] = v + (x+1==divr ? 0 : x+1) - o->Vertices.Get();
f->VertexIndices[2] = v + x - o->Vertices.Get();
f->MappingU[0][0] = U;
f->MappingV[0][0] = 0;
f->MappingU[0][1] = U+dU;
f->MappingV[0][1] = V;
f->MappingU[0][2] = U;
f->MappingV[0][2] = V;
f->Material = m;
f++;
U += dU;
}
da = 1.0/(divr+1);
v = o->Vertices.Get() + 2;
for (x = 0; x < (divh-3); x ++) {
U = 0;
for (y = 0; y < divr; y ++) {
f->VertexIndices[0] = v+y - o->Vertices.Get();
f->VertexIndices[1] = v+divr+(y+1==divr?0:y+1) - o->Vertices.Get();
f->VertexIndices[2] = v+y+divr - o->Vertices.Get();
f->MappingU[0][0] = U;
f->MappingV[0][0] = V;
f->MappingU[0][1] = U+dU;
f->MappingV[0][1] = V+dV;
f->MappingU[0][2] = U;
f->MappingV[0][2] = V+dV;
f->Material = m; f++;
f->VertexIndices[0] = v+y - o->Vertices.Get();
f->VertexIndices[1] = v+(y+1==divr?0:y+1) - o->Vertices.Get();
f->VertexIndices[2] = v+(y+1==divr?0:y+1)+divr - o->Vertices.Get();
f->MappingU[0][0] = U;
f->MappingV[0][0] = V;
f->MappingU[0][1] = U+dU;
f->MappingV[0][1] = V;
f->MappingU[0][2] = U+dU;
f->MappingV[0][2] = V+dV;
f->Material = m; f++;
U += dU;
}
V += dV;
v += divr;
}
v = o->Vertices.Get() + o->Vertices.GetSize() - divr;
U = 0;
for (x = 0; x < divr; x ++) {
f->VertexIndices[0] = 1;
f->VertexIndices[1] = v + x - o->Vertices.Get();
f->VertexIndices[2] = v + (x+1==divr ? 0 : x+1) - o->Vertices.Get();
f->MappingU[0][0] = U;
f->MappingV[0][0] = 1.0;
f->MappingU[0][1] = U;
f->MappingV[0][1] = V;
f->MappingU[0][2] = U+dU;
f->MappingV[0][2] = V;
f->Material = m;
f++;
U += dU;
}
o->CalculateNormals();
return (o);
}
pl_Obj *plMakeDisc(pl_Float r, pl_uInt divr, pl_Mat *m)
{
pl_Obj *o;
pl_Vertex *v;
pl_Face *f;
pl_uInt32 i;
double a, da;
o=new pl_Obj(divr, divr);
if (!o) return NULL;
a = 0.0;
da = (2.0*PL_PI)/divr;
v = o->Vertices.Get();
for (i = 0; i < divr; i ++)
{
v->y = 0.0;
v->x = (pl_Float) (r*cos((double) a));
v->z = (pl_Float)(r*sin(a));
v->xformedx = (0.5 + (0.5*cos((double) a))); // temp
v->xformedy = (0.5 + (0.5*sin((double) a))); // use xf
v++;
a += da;
}
v = o->Vertices.Get();
f = o->Faces.Get();
for (i = 0; i < divr; i ++)
{
f->VertexIndices[0] = i == divr-1 ? 0 : i + 1;
f->VertexIndices[1] = i;
f->VertexIndices[2] = 0;
f->MappingU[0][0] = v[(i==divr-1?0:i+1)].xformedx;
f->MappingV[0][0] = v[(i==divr-1?0:i+1)].xformedy;
f->MappingU[0][1] = v[i].xformedx;
f->MappingV[0][1] = v[i].xformedy;
f->MappingU[0][2] = f->MappingV[0][2] = 0.5;
f->Material = m;
f++;
}
f->VertexIndices[0] = 0;
f->VertexIndices[1] = 2;
f->VertexIndices[2] = 1;
f->MappingU[0][0] = v[0].xformedx;
f->MappingV[0][0] = v[0].xformedy;
f->MappingU[0][1] = v[1].xformedx;
f->MappingV[0][1] = v[1].xformedy;
f->MappingU[0][2] = v[2].xformedx;
f->MappingV[0][2] = v[2].xformedy;
f->Material = m;
o->CalculateNormals();
return o;
}
pl_Obj *plMakeCylinder(pl_Float r, pl_Float h, pl_uInt divr, pl_Bool captop,
pl_Bool capbottom, pl_Mat *m) {
pl_Obj *o;
pl_Vertex *v, *topverts, *bottomverts, *topcapvert=0, *bottomcapvert=0;
pl_Face *f;
pl_uInt32 i;
double a, da;
if (divr < 3) divr = 3;
o = new pl_Obj(divr*2+((divr==3)?0:(captop?1:0)+(capbottom?1:0)),
divr*2+(divr==3 ? (captop ? 1 : 0) + (capbottom ? 1 : 0) :
(captop ? divr : 0) + (capbottom ? divr : 0)));
if (!o) return 0;
a = 0.0;
da = (2.0*PL_PI)/divr;
v = o->Vertices.Get();
topverts = v;
for (i = 0; i < divr; i ++) {
v->y = h/2.0f;
v->x = (pl_Float) (r*cos((double) a));
v->z = (pl_Float)(r*sin(a));
v->xformedx = (0.5 + (0.5*cos((double) a))); // temp
v->xformedy = (0.5 + (0.5*sin((double) a))); // use xf
v++;
a += da;
}
bottomverts = v;
a = 0.0;
for (i = 0; i < divr; i ++) {
v->y = -h/2.0f;
v->x = (pl_Float) (r*cos((double) a));
v->z = (pl_Float) (r*sin(a));
v->xformedx = (0.5 + (0.5*cos((double) a)));
v->xformedy = (0.5 + (0.5*sin((double) a)));
v++; a += da;
}
if (captop && divr != 3) {
topcapvert = v;
v->y = h / 2.0f;
v->x = v->z = 0.0f;
v++;
}
if (capbottom && divr != 3) {
bottomcapvert = v;
v->y = -h / 2.0f;
v->x = v->z = 0.0f;
v++;
}
f = o->Faces.Get();
for (i = 0; i < divr; i ++) {
f->VertexIndices[0] = bottomverts + i - o->Vertices.Get();
f->VertexIndices[1] = topverts + i - o->Vertices.Get();
f->VertexIndices[2] = bottomverts + (i == divr-1 ? 0 : i+1) - o->Vertices.Get();
f->MappingV[0][0] = f->MappingV[0][2] = 1.0; f->MappingV[0][1] = 0;
f->MappingU[0][0] = f->MappingU[0][1] = i/(double)divr;
f->MappingU[0][2] = ((i+1))/(double)divr;
f->Material = m; f++;
f->VertexIndices[0] = bottomverts + (i == divr-1 ? 0 : i+1) - o->Vertices.Get();
f->VertexIndices[1] = topverts + i - o->Vertices.Get();
f->VertexIndices[2] = topverts + (i == divr-1 ? 0 : i+1) - o->Vertices.Get();
f->MappingV[0][1] = f->MappingV[0][2] = 0; f->MappingV[0][0] = 1.0;
f->MappingU[0][0] = f->MappingU[0][2] = ((i+1))/(double)divr;
f->MappingU[0][1] = (i)/(double)divr;
f->Material = m; f++;
}
if (captop) {
if (divr == 3) {
f->VertexIndices[0] = topverts + 0 - o->Vertices.Get();
f->VertexIndices[1] = topverts + 2 - o->Vertices.Get();
f->VertexIndices[2] = topverts + 1 - o->Vertices.Get();
f->MappingU[0][0] = topverts[0].xformedx;
f->MappingV[0][0] = topverts[0].xformedy;
f->MappingU[0][1] = topverts[1].xformedx;
f->MappingV[0][1] = topverts[1].xformedy;
f->MappingU[0][2] = topverts[2].xformedx;
f->MappingV[0][2] = topverts[2].xformedy;
f->Material = m; f++;
} else {
for (i = 0; i < divr; i ++) {
f->VertexIndices[0] = topverts + (i == divr-1 ? 0 : i + 1) - o->Vertices.Get();
f->VertexIndices[1] = topverts + i - o->Vertices.Get();
f->VertexIndices[2] = topcapvert - o->Vertices.Get();
f->MappingU[0][0] = topverts[(i==divr-1?0:i+1)].xformedx;
f->MappingV[0][0] = topverts[(i==divr-1?0:i+1)].xformedy;
f->MappingU[0][1] = topverts[i].xformedx;
f->MappingV[0][1] = topverts[i].xformedy;
f->MappingU[0][2] = f->MappingV[0][2] = 0.5;
f->Material = m; f++;
}
}
}
if (capbottom) {
if (divr == 3) {
f->VertexIndices[0] = bottomverts + 0 - o->Vertices.Get();
f->VertexIndices[1] = bottomverts + 1 - o->Vertices.Get();
f->VertexIndices[2] = bottomverts + 2 - o->Vertices.Get();
f->MappingU[0][0] = bottomverts[0].xformedx;
f->MappingV[0][0] = bottomverts[0].xformedy;
f->MappingU[0][1] = bottomverts[1].xformedx;
f->MappingV[0][1] = bottomverts[1].xformedy;
f->MappingU[0][2] = bottomverts[2].xformedx;
f->MappingV[0][2] = bottomverts[2].xformedy;
f->Material = m; f++;
} else {
for (i = 0; i < divr; i ++) {
f->VertexIndices[0] = bottomverts + i - o->Vertices.Get();
f->VertexIndices[1] = bottomverts + (i == divr-1 ? 0 : i + 1) - o->Vertices.Get();
f->VertexIndices[2] = bottomcapvert - o->Vertices.Get();
f->MappingU[0][0] = bottomverts[i].xformedx;
f->MappingV[0][0] = bottomverts[i].xformedy;
f->MappingU[0][1] = bottomverts[(i==divr-1?0:i+1)].xformedx;
f->MappingV[0][1] = bottomverts[(i==divr-1?0:i+1)].xformedy;
f->MappingU[0][2] = f->MappingV[0][2] = 0.5;
f->Material = m; f++;
}
}
}
o->CalculateNormals();
return (o);
}
pl_Obj *plMakeCone(pl_Float r, pl_Float h, pl_uInt div,
pl_Bool cap, pl_Mat *m) {
pl_Obj *o;
pl_Vertex *v;
pl_Face *f;
pl_uInt32 i;
double a, da;
if (div < 3) div = 3;
o = new pl_Obj(div + (div == 3 ? 1 : (cap ? 2 : 1)),
div + (div == 3 ? 1 : (cap ? div : 0)));
if (!o) return 0;
v = o->Vertices.Get();
v->x = v->z = 0; v->y = h/2;
v->xformedx = 0.5;
v->xformedy = 0.5;
v++;
a = 0.0;
da = (2.0*PL_PI)/div;
for (i = 1; i <= div; i ++) {
v->y = h/-2.0f;
v->x = (pl_Float) (r*cos((double) a));
v->z = (pl_Float) (r*sin((double) a));
v->xformedx = (0.5 + (cos((double) a)*0.5));
v->xformedy = (0.5 + (sin((double) a)*0.5));
a += da;
v++;
}
if (cap && div != 3) {
v->y = h / -2.0f;
v->x = v->z = 0.0f;
v->xformedx = 0.5;
v->xformedy = 0.5;
v++;
}
f = o->Faces.Get();
for (i = 1; i <= div; i ++) {
f->VertexIndices[0] = 0;
f->VertexIndices[1] = o->Vertices.Get() + (i == div ? 1 : i + 1) - o->Vertices.Get();
f->VertexIndices[2] = o->Vertices.Get() + i - o->Vertices.Get();
f->MappingU[0][0] = o->Vertices.Get()[0].xformedx;
f->MappingV[0][0] = o->Vertices.Get()[0].xformedy;
f->MappingU[0][1] = o->Vertices.Get()[(i==div?1:i+1)].xformedx;
f->MappingV[0][1] = o->Vertices.Get()[(i==div?1:i+1)].xformedy;
f->MappingU[0][2] = o->Vertices.Get()[i].xformedx;
f->MappingV[0][2] = o->Vertices.Get()[i].xformedy;
f->Material = m;
f++;
}
if (cap) {
if (div == 3) {
f->VertexIndices[0] = 1;
f->VertexIndices[1] = 2;
f->VertexIndices[2] = 3;
f->MappingU[0][0] = o->Vertices.Get()[1].xformedx;
f->MappingV[0][0] = o->Vertices.Get()[1].xformedy;
f->MappingU[0][1] = o->Vertices.Get()[2].xformedx;
f->MappingV[0][1] = o->Vertices.Get()[2].xformedy;
f->MappingU[0][2] = o->Vertices.Get()[3].xformedx;
f->MappingV[0][2] = o->Vertices.Get()[3].xformedy;
f->Material = m;
f++;
} else {
for (i = 1; i <= div; i ++) {
f->VertexIndices[0] = div + 1;
f->VertexIndices[1] = i;
f->VertexIndices[2] = (i==div ? 1 : i+1);
f->MappingU[0][0] = o->Vertices.Get()[div+1].xformedx;
f->MappingV[0][0] = o->Vertices.Get()[div+1].xformedy;
f->MappingU[0][1] = o->Vertices.Get()[i].xformedx;
f->MappingV[0][1] = o->Vertices.Get()[i].xformedy;
f->MappingU[0][2] = o->Vertices.Get()[i==div?1:i+1].xformedx;
f->MappingV[0][2] = o->Vertices.Get()[i==div?1:i+1].xformedy;
f->Material = m;
f++;
}
}
}
o->CalculateNormals();
return (o);
}
static pl_uChar verts[6*6] = {
0,4,1, 1,4,5, 0,1,2, 3,2,1, 2,3,6, 3,7,6,
6,7,4, 4,7,5, 1,7,3, 7,1,5, 2,6,0, 4,0,6
};
static pl_uChar map[24*2*3] = {
1,0, 1,1, 0,0, 0,0, 1,1, 0,1,
0,0, 1,0, 0,1, 1,1, 0,1, 1,0,
0,0, 1,0, 0,1, 1,0, 1,1, 0,1,
0,0, 1,0, 0,1, 0,1, 1,0, 1,1,
1,0, 0,1, 0,0, 0,1, 1,0, 1,1,
1,0, 1,1, 0,0, 0,1, 0,0, 1,1
};
pl_Obj *plMakeBox(pl_Float w, pl_Float d, pl_Float h, pl_Mat *m) {
pl_uChar *mm = map;
pl_uChar *vv = verts;
pl_Obj *o;
pl_Vertex *v;
pl_Face *f;
pl_uInt x;
o = new pl_Obj(8,12);
if (!o) return 0;
v = o->Vertices.Get();
v->x = -w/2; v->y = h/2; v->z = d/2; v++;
v->x = w/2; v->y = h/2; v->z = d/2; v++;
v->x = -w/2; v->y = h/2; v->z = -d/2; v++;
v->x = w/2; v->y = h/2; v->z = -d/2; v++;
v->x = -w/2; v->y = -h/2; v->z = d/2; v++;
v->x = w/2; v->y = -h/2; v->z = d/2; v++;
v->x = -w/2; v->y = -h/2; v->z = -d/2; v++;
v->x = w/2; v->y = -h/2; v->z = -d/2; v++;
f = o->Faces.Get();
for (x = 0; x < 12; x ++) {
f->VertexIndices[0] = *vv++;
f->VertexIndices[1] = *vv++;
f->VertexIndices[2] = *vv++;
f->MappingU[0][0] = (pl_Float) *mm++;
f->MappingV[0][0] = (pl_Float) *mm++;
f->MappingU[0][1] = (pl_Float) *mm++;
f->MappingV[0][1] = (pl_Float) *mm++;
f->MappingU[0][2] = (pl_Float) *mm++;
f->MappingV[0][2] = (pl_Float) *mm++;
f->Material = m;
f++;
}
o->CalculateNormals();
return (o);
}
pl_Obj *plMakePlane(pl_Float w, pl_Float d, pl_uInt res, pl_Mat *m) {
pl_Obj *o;
pl_Vertex *v;
pl_Face *f;
pl_uInt x, y;
o = new pl_Obj((res+1)*(res+1),res*res*2);
if (!o) return 0;
v = o->Vertices.Get();
for (y = 0; y <= res; y ++) {
for (x = 0; x <= res; x ++) {
v->y = 0;
v->x = ((x*w)/res) - w/2;
v->z = ((y*d)/res) - d/2;
v++;
}
}
f = o->Faces.Get();
for (y = 0; y < res; y ++) {
for (x = 0; x < res; x ++) {
f->VertexIndices[0] = x+(y*(res+1));
f->MappingU[0][0] = (x)/(double)res;
f->MappingV[0][0] = (y)/(double)res;
f->VertexIndices[2] = x+1+(y*(res+1));
f->MappingU[0][2] = ((x+1))/(double)res;
f->MappingV[0][2] = (y)/(double)res;
f->VertexIndices[1] = x+((y+1)*(res+1));
f->MappingU[0][1] = (x)/(double)res;
f->MappingV[0][1] = ((y+1))/(double)res;
f->Material = m;
f++;
f->VertexIndices[0] = x+((y+1)*(res+1));
f->MappingU[0][0] = (x)/(double)res;
f->MappingV[0][0] = ((y+1))/(double)res;
f->VertexIndices[2] = x+1+(y*(res+1));
f->MappingU[0][2] = ((x+1))/(double)res;
f->MappingV[0][2] = (y)/(double)res;
f->VertexIndices[1] = x+1+((y+1)*(res+1));
f->MappingU[0][1] = ((x+1))/(double)res;
f->MappingV[0][1] = ((y+1))/(double)res;
f->Material = m;
f++;
}
}
o->CalculateNormals();
return (o);
}
| 31.239777 | 99 | 0.483906 | badi91 |
0f5a9701adff5b6a3dee6e54845012ec6f29a095 | 12,202 | hpp | C++ | include/System/Xml/XmlProcessingInstruction.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Xml/XmlProcessingInstruction.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/Xml/XmlProcessingInstruction.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Xml.XmlLinkedNode
#include "System/Xml/XmlLinkedNode.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Xml
namespace System::Xml {
// Forward declaring type: XmlDocument
class XmlDocument;
// Forward declaring type: XmlNodeType
struct XmlNodeType;
// Forward declaring type: XmlWriter
class XmlWriter;
}
// Completed forward declares
// Type namespace: System.Xml
namespace System::Xml {
// Forward declaring type: XmlProcessingInstruction
class XmlProcessingInstruction;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Xml::XmlProcessingInstruction);
DEFINE_IL2CPP_ARG_TYPE(::System::Xml::XmlProcessingInstruction*, "System.Xml", "XmlProcessingInstruction");
// Type namespace: System.Xml
namespace System::Xml {
// Size: 0x30
#pragma pack(push, 1)
// Autogenerated type: System.Xml.XmlProcessingInstruction
// [TokenAttribute] Offset: FFFFFFFF
class XmlProcessingInstruction : public ::System::Xml::XmlLinkedNode {
public:
public:
// private System.String target
// Size: 0x8
// Offset: 0x20
::StringW target;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
// private System.String data
// Size: 0x8
// Offset: 0x28
::StringW data;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
public:
// Get instance field reference: private System.String target
[[deprecated("Use field access instead!")]] ::StringW& dyn_target();
// Get instance field reference: private System.String data
[[deprecated("Use field access instead!")]] ::StringW& dyn_data();
// public System.Void set_Data(System.String value)
// Offset: 0x1024260
void set_Data(::StringW value);
// protected internal System.Void .ctor(System.String target, System.String data, System.Xml.XmlDocument doc)
// Offset: 0x10241B4
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static XmlProcessingInstruction* New_ctor(::StringW target, ::StringW data, ::System::Xml::XmlDocument* doc) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::XmlProcessingInstruction::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<XmlProcessingInstruction*, creationType>(target, data, doc)));
}
// public override System.String get_Name()
// Offset: 0x10241F0
// Implemented from: System.Xml.XmlNode
// Base method: System.String XmlNode::get_Name()
::StringW get_Name();
// public override System.String get_LocalName()
// Offset: 0x1024248
// Implemented from: System.Xml.XmlNode
// Base method: System.String XmlNode::get_LocalName()
::StringW get_LocalName();
// public override System.String get_Value()
// Offset: 0x1024254
// Implemented from: System.Xml.XmlNode
// Base method: System.String XmlNode::get_Value()
::StringW get_Value();
// public override System.Void set_Value(System.String value)
// Offset: 0x102425C
// Implemented from: System.Xml.XmlNode
// Base method: System.Void XmlNode::set_Value(System.String value)
void set_Value(::StringW value);
// public override System.String get_InnerText()
// Offset: 0x1024310
// Implemented from: System.Xml.XmlNode
// Base method: System.String XmlNode::get_InnerText()
::StringW get_InnerText();
// public override System.Void set_InnerText(System.String value)
// Offset: 0x1024318
// Implemented from: System.Xml.XmlNode
// Base method: System.Void XmlNode::set_InnerText(System.String value)
void set_InnerText(::StringW value);
// public override System.Xml.XmlNodeType get_NodeType()
// Offset: 0x102431C
// Implemented from: System.Xml.XmlNode
// Base method: System.Xml.XmlNodeType XmlNode::get_NodeType()
::System::Xml::XmlNodeType get_NodeType();
// public override System.Xml.XmlNode CloneNode(System.Boolean deep)
// Offset: 0x1024324
// Implemented from: System.Xml.XmlNode
// Base method: System.Xml.XmlNode XmlNode::CloneNode(System.Boolean deep)
::System::Xml::XmlNode* CloneNode(bool deep);
// public override System.Void WriteTo(System.Xml.XmlWriter w)
// Offset: 0x1024368
// Implemented from: System.Xml.XmlNode
// Base method: System.Void XmlNode::WriteTo(System.Xml.XmlWriter w)
void WriteTo(::System::Xml::XmlWriter* w);
// public override System.Void WriteContentTo(System.Xml.XmlWriter w)
// Offset: 0x1024394
// Implemented from: System.Xml.XmlNode
// Base method: System.Void XmlNode::WriteContentTo(System.Xml.XmlWriter w)
void WriteContentTo(::System::Xml::XmlWriter* w);
}; // System.Xml.XmlProcessingInstruction
#pragma pack(pop)
static check_size<sizeof(XmlProcessingInstruction), 40 + sizeof(::StringW)> __System_Xml_XmlProcessingInstructionSizeCheck;
static_assert(sizeof(XmlProcessingInstruction) == 0x30);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Xml::XmlProcessingInstruction::set_Data
// Il2CppName: set_Data
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::XmlProcessingInstruction::*)(::StringW)>(&System::Xml::XmlProcessingInstruction::set_Data)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlProcessingInstruction*), "set_Data", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Xml::XmlProcessingInstruction::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Xml::XmlProcessingInstruction::get_Name
// Il2CppName: get_Name
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Xml::XmlProcessingInstruction::*)()>(&System::Xml::XmlProcessingInstruction::get_Name)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlProcessingInstruction*), "get_Name", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlProcessingInstruction::get_LocalName
// Il2CppName: get_LocalName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Xml::XmlProcessingInstruction::*)()>(&System::Xml::XmlProcessingInstruction::get_LocalName)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlProcessingInstruction*), "get_LocalName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlProcessingInstruction::get_Value
// Il2CppName: get_Value
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Xml::XmlProcessingInstruction::*)()>(&System::Xml::XmlProcessingInstruction::get_Value)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlProcessingInstruction*), "get_Value", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlProcessingInstruction::set_Value
// Il2CppName: set_Value
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::XmlProcessingInstruction::*)(::StringW)>(&System::Xml::XmlProcessingInstruction::set_Value)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlProcessingInstruction*), "set_Value", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Xml::XmlProcessingInstruction::get_InnerText
// Il2CppName: get_InnerText
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Xml::XmlProcessingInstruction::*)()>(&System::Xml::XmlProcessingInstruction::get_InnerText)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlProcessingInstruction*), "get_InnerText", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlProcessingInstruction::set_InnerText
// Il2CppName: set_InnerText
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::XmlProcessingInstruction::*)(::StringW)>(&System::Xml::XmlProcessingInstruction::set_InnerText)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlProcessingInstruction*), "set_InnerText", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: System::Xml::XmlProcessingInstruction::get_NodeType
// Il2CppName: get_NodeType
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Xml::XmlNodeType (System::Xml::XmlProcessingInstruction::*)()>(&System::Xml::XmlProcessingInstruction::get_NodeType)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlProcessingInstruction*), "get_NodeType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::XmlProcessingInstruction::CloneNode
// Il2CppName: CloneNode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Xml::XmlNode* (System::Xml::XmlProcessingInstruction::*)(bool)>(&System::Xml::XmlProcessingInstruction::CloneNode)> {
static const MethodInfo* get() {
static auto* deep = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlProcessingInstruction*), "CloneNode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{deep});
}
};
// Writing MetadataGetter for method: System::Xml::XmlProcessingInstruction::WriteTo
// Il2CppName: WriteTo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::XmlProcessingInstruction::*)(::System::Xml::XmlWriter*)>(&System::Xml::XmlProcessingInstruction::WriteTo)> {
static const MethodInfo* get() {
static auto* w = &::il2cpp_utils::GetClassFromName("System.Xml", "XmlWriter")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlProcessingInstruction*), "WriteTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{w});
}
};
// Writing MetadataGetter for method: System::Xml::XmlProcessingInstruction::WriteContentTo
// Il2CppName: WriteContentTo
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::XmlProcessingInstruction::*)(::System::Xml::XmlWriter*)>(&System::Xml::XmlProcessingInstruction::WriteContentTo)> {
static const MethodInfo* get() {
static auto* w = &::il2cpp_utils::GetClassFromName("System.Xml", "XmlWriter")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::XmlProcessingInstruction*), "WriteContentTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{w});
}
};
| 54.231111 | 203 | 0.738158 | v0idp |
0f647838e6c007f41414050dcf4b34ee1314d066 | 3,035 | cpp | C++ | Source/AllProjects/AIUtils/CIDAI/CIDAI_BTNodeFactory.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 216 | 2019-03-09T06:41:28.000Z | 2022-02-25T16:27:19.000Z | Source/AllProjects/AIUtils/CIDAI/CIDAI_BTNodeFactory.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 9 | 2020-09-27T08:00:52.000Z | 2021-07-02T14:27:31.000Z | Source/AllProjects/AIUtils/CIDAI/CIDAI_BTNodeFactory.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 29 | 2019-03-09T10:12:24.000Z | 2021-03-03T22:25:29.000Z | //
// FILE NAME: CIDAI_BTNodeFactory.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 12/07/2016
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the abstract base class from which all BT node factories are
// derived.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CIDAI_.hpp"
// ---------------------------------------------------------------------------
// Magic macros
// ---------------------------------------------------------------------------
RTTIDecls(TAIBTNodeFact, TObject)
// ---------------------------------------------------------------------------
// CLASS: TAIBTNodeFact
// PREFIX: nfact
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TAIBTNodeFact: Public, static methods
// ---------------------------------------------------------------------------
// For keyed collection supports
const TString& TAIBTNodeFact::strKey(const TAIBTNodeFact& nfactSrc)
{
return nfactSrc.m_strFactKey;
}
// ---------------------------------------------------------------------------
// TAIBTNodeFact: Constructors and Destructor
// ---------------------------------------------------------------------------
// Nothing to do at this level
TAIBTNodeFact::~TAIBTNodeFact()
{
}
// ---------------------------------------------------------------------------
// TAIBTNodeFact: Public, non-virtual methods
// ---------------------------------------------------------------------------
//
// We make this non-virtual and call a virtual protected on the derived class. This
// way we can intercept all newly created nodes and do whatever we need.
//
TAIBTNode*
TAIBTNodeFact::pbtnodeMakeNew( const TString& strPath
, const TString& strName
, const TString& strType
, const tCIDLib::TBoolean bFlag)
{
TAIBTNode* pbtnodeRet = pbtnodeNew(strPath, strName, strType);
// Store the flag on the node if we created it
if (pbtnodeRet)
pbtnodeRet->bFlag(bFlag);
return pbtnodeRet;
}
// Provide access to the factory key for this factory
const TString& TAIBTNodeFact::strFactKey() const
{
return m_strFactKey;
}
// ---------------------------------------------------------------------------
// TAIBTNodeFact: Hidden constructors
// ---------------------------------------------------------------------------
TAIBTNodeFact::TAIBTNodeFact(const TString& strFactKey) :
m_strFactKey(strFactKey)
{
}
| 28.101852 | 85 | 0.421417 | MarkStega |
0f65afef2866e9ba1e4dbcc08eac8a63ada40c4a | 50,070 | cc | C++ | src/writer/spirv/builder_constructor_expression_test.cc | sunnyps/tint | 22daca166bbc412345fc60d4f60646d6d2f3ada0 | [
"Apache-2.0"
] | null | null | null | src/writer/spirv/builder_constructor_expression_test.cc | sunnyps/tint | 22daca166bbc412345fc60d4f60646d6d2f3ada0 | [
"Apache-2.0"
] | null | null | null | src/writer/spirv/builder_constructor_expression_test.cc | sunnyps/tint | 22daca166bbc412345fc60d4f60646d6d2f3ada0 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The Tint Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/writer/spirv/spv_dump.h"
#include "src/writer/spirv/test_helper.h"
namespace tint {
namespace writer {
namespace spirv {
namespace {
using SpvBuilderConstructorTest = TestHelper;
TEST_F(SpvBuilderConstructorTest, Const) {
auto* c = Expr(42.2f);
WrapInFunction(c);
spirv::Builder& b = Build();
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, c, true), 2u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%1 = OpTypeFloat 32
%2 = OpConstant %1 42.2000008
)");
}
TEST_F(SpvBuilderConstructorTest, Type_WithCasts_OutsideFunction_IsError) {
auto* t = Construct<f32>(Construct<u32>(1));
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_EQ(b.GenerateExpression(t), 0u);
EXPECT_TRUE(b.has_error()) << b.error();
EXPECT_EQ(b.error(),
"Internal error: trying to add SPIR-V instruction 124 outside a "
"function");
}
TEST_F(SpvBuilderConstructorTest, Type) {
auto* t = vec3<f32>(1.0f, 1.0f, 3.0f);
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, t, true), 5u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 3
%3 = OpConstant %2 1
%4 = OpConstant %2 3
%5 = OpConstantComposite %1 %3 %3 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_WithCasts) {
auto* t = vec2<f32>(Construct<f32>(1), Construct<f32>(1));
WrapInFunction(t);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(t), 7u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 2
%4 = OpTypeInt 32 1
%5 = OpConstant %4 1
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%3 = OpConvertSToF %2 %5
%6 = OpConvertSToF %2 %5
%7 = OpCompositeConstruct %1 %3 %6
)");
}
TEST_F(SpvBuilderConstructorTest, Type_WithAlias) {
// type Int = i32
// cast<Int>(2.3f)
auto* alias = Alias("Int", ty.i32());
auto* cast = Construct(ty.Of(alias), 2.3f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 1u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeInt 32 1
%3 = OpTypeFloat 32
%4 = OpConstant %3 2.29999995
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%1 = OpConvertFToS %2 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_IdentifierExpression_Param) {
auto* var = Var("ident", ty.f32());
auto* t = vec2<f32>(1.0f, "ident");
WrapInFunction(var, t);
spirv::Builder& b = Build();
b.push_function(Function{});
ASSERT_TRUE(b.GenerateFunctionVariable(var)) << b.error();
EXPECT_EQ(b.GenerateExpression(t), 8u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypePointer Function %3
%4 = OpConstantNull %3
%5 = OpTypeVector %3 2
%6 = OpConstant %3 1
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].variables()),
R"(%1 = OpVariable %2 Function %4
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%7 = OpLoad %3 %1
%8 = OpCompositeConstruct %5 %6 %7
)");
}
TEST_F(SpvBuilderConstructorTest, Vector_Bitcast_Params) {
auto* t = vec2<u32>(Construct<u32>(1), Construct<u32>(1));
WrapInFunction(t);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(t), 7u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeInt 32 0
%1 = OpTypeVector %2 2
%4 = OpTypeInt 32 1
%5 = OpConstant %4 1
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%3 = OpBitcast %2 %5
%6 = OpBitcast %2 %5
%7 = OpCompositeConstruct %1 %3 %6
)");
}
TEST_F(SpvBuilderConstructorTest, Type_NonConst_Value_Fails) {
auto* rel = create<ast::BinaryExpression>(ast::BinaryOp::kAdd, Expr(3.0f),
Expr(3.0f));
auto* t = vec2<f32>(1.0f, rel);
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, t, true), 0u);
EXPECT_TRUE(b.has_error());
EXPECT_EQ(b.error(), R"(constructor must be a constant expression)");
}
TEST_F(SpvBuilderConstructorTest, Type_Bool_With_Bool) {
auto* cast = Construct<bool>(true);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 3u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeBool
%3 = OpConstantTrue %2
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()), R"()");
}
TEST_F(SpvBuilderConstructorTest, Type_I32_With_I32) {
auto* cast = Construct<i32>(2);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 3u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeInt 32 1
%3 = OpConstant %2 2
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()), R"()");
}
TEST_F(SpvBuilderConstructorTest, Type_U32_With_U32) {
auto* cast = Construct<u32>(2u);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 3u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeInt 32 0
%3 = OpConstant %2 2
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()), R"()");
}
TEST_F(SpvBuilderConstructorTest, Type_F32_With_F32) {
auto* cast = Construct<f32>(2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 3u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%3 = OpConstant %2 2
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()), R"()");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec2_With_Bool_Literal) {
auto* cast = vec2<bool>(true);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeBool
%1 = OpTypeVector %2 2
%3 = OpConstantTrue %2
%4 = OpConstantComposite %1 %3 %3
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()), R"()");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec2_With_Bool_Var) {
auto* var = Var("v", nullptr, Expr(true));
auto* cast = vec2<bool>(var);
WrapInFunction(var, cast);
spirv::Builder& b = Build();
b.push_function(Function{});
ASSERT_TRUE(b.GenerateFunctionVariable(var)) << b.error();
ASSERT_EQ(b.GenerateExpression(cast), 8u) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%1 = OpTypeBool
%2 = OpConstantTrue %1
%4 = OpTypePointer Function %1
%5 = OpConstantNull %1
%6 = OpTypeVector %1 2
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(OpStore %3 %2
%7 = OpLoad %1 %3
%8 = OpCompositeConstruct %6 %7 %7
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec2_With_F32_Literal) {
auto* cast = vec2<f32>(2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 2
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()), R"()");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec2_With_F32_Var) {
auto* var = Var("v", nullptr, Expr(2.0f));
auto* cast = vec2<f32>(var);
WrapInFunction(var, cast);
spirv::Builder& b = Build();
b.push_function(Function{});
ASSERT_TRUE(b.GenerateFunctionVariable(var)) << b.error();
ASSERT_EQ(b.GenerateExpression(cast), 8u) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%1 = OpTypeFloat 32
%2 = OpConstant %1 2
%4 = OpTypePointer Function %1
%5 = OpConstantNull %1
%6 = OpTypeVector %1 2
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()), R"(OpStore %3 %2
%7 = OpLoad %1 %3
%8 = OpCompositeConstruct %6 %7 %7
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec2_With_F32_F32) {
auto* cast = vec2<f32>(2.0f, 2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 2
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec2_With_Vec2) {
auto* value = vec2<f32>(2.0f, 2.0f);
auto* cast = vec2<f32>(value);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 5u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 2
%4 = OpConstant %3 2
%5 = OpConstantComposite %2 %4 %4
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()), R"()");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec3_With_F32) {
auto* cast = vec3<f32>(2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 3
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3 %3
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec3_With_Bool) {
auto* cast = vec3<bool>(true);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeBool
%1 = OpTypeVector %2 3
%3 = OpConstantTrue %2
%4 = OpConstantComposite %1 %3 %3 %3
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec3_With_F32_F32_F32) {
auto* cast = vec3<f32>(2.0f, 2.0f, 2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 3
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3 %3
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec3_With_F32_Vec2) {
auto* cast = vec3<f32>(2.0f, vec2<f32>(2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 8u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 3
%3 = OpConstant %2 2
%4 = OpTypeVector %2 2
%5 = OpConstantComposite %4 %3 %3
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%6 = OpCompositeExtract %2 %5 0
%7 = OpCompositeExtract %2 %5 1
%8 = OpCompositeConstruct %1 %3 %6 %7
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec3_With_Vec2_F32) {
auto* cast = vec3<f32>(vec2<f32>(2.0f, 2.0f), 2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 8u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 3
%3 = OpTypeVector %2 2
%4 = OpConstant %2 2
%5 = OpConstantComposite %3 %4 %4
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%6 = OpCompositeExtract %2 %5 0
%7 = OpCompositeExtract %2 %5 1
%8 = OpCompositeConstruct %1 %6 %7 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec3_With_Vec3) {
auto* value = vec3<f32>(2.0f, 2.0f, 2.0f);
auto* cast = vec3<f32>(value);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 5u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 3
%4 = OpConstant %3 2
%5 = OpConstantComposite %2 %4 %4 %4
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()), R"()");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec4_With_Bool) {
auto* cast = vec4<bool>(true);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeBool
%1 = OpTypeVector %2 4
%3 = OpConstantTrue %2
%4 = OpConstantComposite %1 %3 %3 %3 %3
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec4_With_F32) {
auto* cast = vec4<f32>(2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3 %3 %3
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec4_With_F32_F32_F32_F32) {
auto* cast = vec4<f32>(2.0f, 2.0f, 2.0f, 2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3 %3 %3
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec4_With_F32_F32_Vec2) {
auto* cast = vec4<f32>(2.0f, 2.0f, vec2<f32>(2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 8u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpConstant %2 2
%4 = OpTypeVector %2 2
%5 = OpConstantComposite %4 %3 %3
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%6 = OpCompositeExtract %2 %5 0
%7 = OpCompositeExtract %2 %5 1
%8 = OpCompositeConstruct %1 %3 %3 %6 %7
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec4_With_F32_Vec2_F32) {
auto* cast = vec4<f32>(2.0f, vec2<f32>(2.0f, 2.0f), 2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 8u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpConstant %2 2
%4 = OpTypeVector %2 2
%5 = OpConstantComposite %4 %3 %3
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%6 = OpCompositeExtract %2 %5 0
%7 = OpCompositeExtract %2 %5 1
%8 = OpCompositeConstruct %1 %3 %6 %7 %3
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec4_With_Vec2_F32_F32) {
auto* cast = vec4<f32>(vec2<f32>(2.0f, 2.0f), 2.0f, 2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 8u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpTypeVector %2 2
%4 = OpConstant %2 2
%5 = OpConstantComposite %3 %4 %4
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%6 = OpCompositeExtract %2 %5 0
%7 = OpCompositeExtract %2 %5 1
%8 = OpCompositeConstruct %1 %6 %7 %4 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec4_With_Vec2_Vec2) {
auto* cast = vec4<f32>(vec2<f32>(2.0f, 2.0f), vec2<f32>(2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 10u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpTypeVector %2 2
%4 = OpConstant %2 2
%5 = OpConstantComposite %3 %4 %4
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%6 = OpCompositeExtract %2 %5 0
%7 = OpCompositeExtract %2 %5 1
%8 = OpCompositeExtract %2 %5 0
%9 = OpCompositeExtract %2 %5 1
%10 = OpCompositeConstruct %1 %6 %7 %8 %9
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec4_With_F32_Vec3) {
auto* cast = vec4<f32>(2.0f, vec3<f32>(2.0f, 2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 9u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpConstant %2 2
%4 = OpTypeVector %2 3
%5 = OpConstantComposite %4 %3 %3 %3
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%6 = OpCompositeExtract %2 %5 0
%7 = OpCompositeExtract %2 %5 1
%8 = OpCompositeExtract %2 %5 2
%9 = OpCompositeConstruct %1 %3 %6 %7 %8
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec4_With_Vec3_F32) {
auto* cast = vec4<f32>(vec3<f32>(2.0f, 2.0f, 2.0f), 2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 9u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpTypeVector %2 3
%4 = OpConstant %2 2
%5 = OpConstantComposite %3 %4 %4 %4
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%6 = OpCompositeExtract %2 %5 0
%7 = OpCompositeExtract %2 %5 1
%8 = OpCompositeExtract %2 %5 2
%9 = OpCompositeConstruct %1 %6 %7 %8 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Vec4_With_Vec4) {
auto* value = vec4<f32>(2.0f, 2.0f, 2.0f, 2.0f);
auto* cast = vec4<f32>(value);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 5u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 4
%4 = OpConstant %3 2
%5 = OpConstantComposite %2 %4 %4 %4 %4
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()), R"()");
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec2_With_F32) {
auto* cast = vec2<f32>(2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, cast, true), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 2
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec2_With_Vec2) {
auto* cast = vec2<f32>(vec2<f32>(2.0f, 2.0f));
GlobalConst("a", ty.vec2<f32>(), cast);
spirv::Builder& b = SanitizeAndBuild();
ASSERT_TRUE(b.Build());
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 2
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3
%6 = OpTypeVoid
%5 = OpTypeFunction %6
)");
Validate(b);
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec3_With_Vec3) {
auto* cast = vec3<f32>(vec3<f32>(2.0f, 2.0f, 2.0f));
GlobalConst("a", ty.vec3<f32>(), cast);
spirv::Builder& b = SanitizeAndBuild();
ASSERT_TRUE(b.Build());
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 3
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3 %3
%6 = OpTypeVoid
%5 = OpTypeFunction %6
)");
Validate(b);
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec4_With_Vec4) {
auto* cast = vec4<f32>(vec4<f32>(2.0f, 2.0f, 2.0f, 2.0f));
GlobalConst("a", ty.vec4<f32>(), cast);
spirv::Builder& b = SanitizeAndBuild();
ASSERT_TRUE(b.Build());
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3 %3 %3
%6 = OpTypeVoid
%5 = OpTypeFunction %6
)");
Validate(b);
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec3_With_F32) {
auto* cast = vec3<f32>(2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, cast, true), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 3
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3 %3
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec3_With_F32_Vec2) {
auto* cast = vec3<f32>(2.0f, vec2<f32>(2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, cast, true), 11u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 3
%3 = OpConstant %2 2
%4 = OpTypeVector %2 2
%5 = OpConstantComposite %4 %3 %3
%7 = OpTypeInt 32 0
%8 = OpConstant %7 0
%6 = OpSpecConstantOp %2 CompositeExtract %5 8
%10 = OpConstant %7 1
%9 = OpSpecConstantOp %2 CompositeExtract %5 10
%11 = OpSpecConstantComposite %1 %3 %6 %9
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec3_With_Vec2_F32) {
auto* cast = vec3<f32>(vec2<f32>(2.0f, 2.0f), 2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, cast, true), 11u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 3
%3 = OpTypeVector %2 2
%4 = OpConstant %2 2
%5 = OpConstantComposite %3 %4 %4
%7 = OpTypeInt 32 0
%8 = OpConstant %7 0
%6 = OpSpecConstantOp %2 CompositeExtract %5 8
%10 = OpConstant %7 1
%9 = OpSpecConstantOp %2 CompositeExtract %5 10
%11 = OpSpecConstantComposite %1 %6 %9 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec4_With_F32) {
auto* cast = vec4<f32>(2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, cast, true), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3 %3 %3
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec4_With_F32_F32_Vec2) {
auto* cast = vec4<f32>(2.0f, 2.0f, vec2<f32>(2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, cast, true), 11u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpConstant %2 2
%4 = OpTypeVector %2 2
%5 = OpConstantComposite %4 %3 %3
%7 = OpTypeInt 32 0
%8 = OpConstant %7 0
%6 = OpSpecConstantOp %2 CompositeExtract %5 8
%10 = OpConstant %7 1
%9 = OpSpecConstantOp %2 CompositeExtract %5 10
%11 = OpSpecConstantComposite %1 %3 %3 %6 %9
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec4_With_F32_Vec2_F32) {
auto* cast = vec4<f32>(2.0f, vec2<f32>(2.0f, 2.0f), 2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, cast, true), 11u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpConstant %2 2
%4 = OpTypeVector %2 2
%5 = OpConstantComposite %4 %3 %3
%7 = OpTypeInt 32 0
%8 = OpConstant %7 0
%6 = OpSpecConstantOp %2 CompositeExtract %5 8
%10 = OpConstant %7 1
%9 = OpSpecConstantOp %2 CompositeExtract %5 10
%11 = OpSpecConstantComposite %1 %3 %6 %9 %3
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec4_With_Vec2_F32_F32) {
auto* cast = vec4<f32>(vec2<f32>(2.0f, 2.0f), 2.0f, 2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, cast, true), 11u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpTypeVector %2 2
%4 = OpConstant %2 2
%5 = OpConstantComposite %3 %4 %4
%7 = OpTypeInt 32 0
%8 = OpConstant %7 0
%6 = OpSpecConstantOp %2 CompositeExtract %5 8
%10 = OpConstant %7 1
%9 = OpSpecConstantOp %2 CompositeExtract %5 10
%11 = OpSpecConstantComposite %1 %6 %9 %4 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec4_With_Vec2_Vec2) {
auto* cast = vec4<f32>(vec2<f32>(2.0f, 2.0f), vec2<f32>(2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, cast, true), 13u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpTypeVector %2 2
%4 = OpConstant %2 2
%5 = OpConstantComposite %3 %4 %4
%7 = OpTypeInt 32 0
%8 = OpConstant %7 0
%6 = OpSpecConstantOp %2 CompositeExtract %5 8
%10 = OpConstant %7 1
%9 = OpSpecConstantOp %2 CompositeExtract %5 10
%11 = OpSpecConstantOp %2 CompositeExtract %5 8
%12 = OpSpecConstantOp %2 CompositeExtract %5 10
%13 = OpSpecConstantComposite %1 %6 %9 %11 %12
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec4_With_F32_Vec3) {
auto* cast = vec4<f32>(2.0f, vec3<f32>(2.0f, 2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, cast, true), 13u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpConstant %2 2
%4 = OpTypeVector %2 3
%5 = OpConstantComposite %4 %3 %3 %3
%7 = OpTypeInt 32 0
%8 = OpConstant %7 0
%6 = OpSpecConstantOp %2 CompositeExtract %5 8
%10 = OpConstant %7 1
%9 = OpSpecConstantOp %2 CompositeExtract %5 10
%12 = OpConstant %7 2
%11 = OpSpecConstantOp %2 CompositeExtract %5 12
%13 = OpSpecConstantComposite %1 %3 %6 %9 %11
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ModuleScope_Vec4_With_Vec3_F32) {
auto* cast = vec4<f32>(vec3<f32>(2.0f, 2.0f, 2.0f), 2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateConstructorExpression(nullptr, cast, true), 13u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 4
%3 = OpTypeVector %2 3
%4 = OpConstant %2 2
%5 = OpConstantComposite %3 %4 %4 %4
%7 = OpTypeInt 32 0
%8 = OpConstant %7 0
%6 = OpSpecConstantOp %2 CompositeExtract %5 8
%10 = OpConstant %7 1
%9 = OpSpecConstantOp %2 CompositeExtract %5 10
%12 = OpConstant %7 2
%11 = OpSpecConstantOp %2 CompositeExtract %5 12
%13 = OpSpecConstantComposite %1 %6 %9 %11 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Mat2x2_With_Vec2_Vec2) {
auto* cast = mat2x2<f32>(vec2<f32>(2.0f, 2.0f), vec2<f32>(2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 6u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 2
%1 = OpTypeMatrix %2 2
%4 = OpConstant %3 2
%5 = OpConstantComposite %2 %4 %4
%6 = OpConstantComposite %1 %5 %5
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Mat3x2_With_Vec2_Vec2_Vec2) {
auto* cast = mat3x2<f32>(vec2<f32>(2.0f, 2.0f), vec2<f32>(2.0f, 2.0f),
vec2<f32>(2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 6u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 2
%1 = OpTypeMatrix %2 3
%4 = OpConstant %3 2
%5 = OpConstantComposite %2 %4 %4
%6 = OpConstantComposite %1 %5 %5 %5
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Mat4x2_With_Vec2_Vec2_Vec2_Vec2) {
auto* cast = mat4x2<f32>(vec2<f32>(2.0f, 2.0f), vec2<f32>(2.0f, 2.0f),
vec2<f32>(2.0f, 2.0f), vec2<f32>(2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 6u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 2
%1 = OpTypeMatrix %2 4
%4 = OpConstant %3 2
%5 = OpConstantComposite %2 %4 %4
%6 = OpConstantComposite %1 %5 %5 %5 %5
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Mat2x3_With_Vec3_Vec3) {
auto* cast =
mat2x3<f32>(vec3<f32>(2.0f, 2.0f, 2.0f), vec3<f32>(2.0f, 2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 6u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 3
%1 = OpTypeMatrix %2 2
%4 = OpConstant %3 2
%5 = OpConstantComposite %2 %4 %4 %4
%6 = OpConstantComposite %1 %5 %5
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Mat3x3_With_Vec3_Vec3_Vec3) {
auto* cast =
mat3x3<f32>(vec3<f32>(2.0f, 2.0f, 2.0f), vec3<f32>(2.0f, 2.0f, 2.0f),
vec3<f32>(2.0f, 2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 6u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 3
%1 = OpTypeMatrix %2 3
%4 = OpConstant %3 2
%5 = OpConstantComposite %2 %4 %4 %4
%6 = OpConstantComposite %1 %5 %5 %5
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Mat4x3_With_Vec3_Vec3_Vec3_Vec3) {
auto* cast =
mat4x3<f32>(vec3<f32>(2.0f, 2.0f, 2.0f), vec3<f32>(2.0f, 2.0f, 2.0f),
vec3<f32>(2.0f, 2.0f, 2.0f), vec3<f32>(2.0f, 2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 6u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 3
%1 = OpTypeMatrix %2 4
%4 = OpConstant %3 2
%5 = OpConstantComposite %2 %4 %4 %4
%6 = OpConstantComposite %1 %5 %5 %5 %5
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Mat2x4_With_Vec4_Vec4) {
auto* cast = mat2x4<f32>(vec4<f32>(2.0f, 2.0f, 2.0f, 2.0f),
vec4<f32>(2.0f, 2.0f, 2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 6u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 4
%1 = OpTypeMatrix %2 2
%4 = OpConstant %3 2
%5 = OpConstantComposite %2 %4 %4 %4 %4
%6 = OpConstantComposite %1 %5 %5
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Mat3x4_With_Vec4_Vec4_Vec4) {
auto* cast = mat3x4<f32>(vec4<f32>(2.0f, 2.0f, 2.0f, 2.0f),
vec4<f32>(2.0f, 2.0f, 2.0f, 2.0f),
vec4<f32>(2.0f, 2.0f, 2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 6u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 4
%1 = OpTypeMatrix %2 3
%4 = OpConstant %3 2
%5 = OpConstantComposite %2 %4 %4 %4 %4
%6 = OpConstantComposite %1 %5 %5 %5
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Mat4x4_With_Vec4_Vec4_Vec4_Vec4) {
auto* cast = mat4x4<f32>(
vec4<f32>(2.0f, 2.0f, 2.0f, 2.0f), vec4<f32>(2.0f, 2.0f, 2.0f, 2.0f),
vec4<f32>(2.0f, 2.0f, 2.0f, 2.0f), vec4<f32>(2.0f, 2.0f, 2.0f, 2.0f));
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 6u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 4
%1 = OpTypeMatrix %2 4
%4 = OpConstant %3 2
%5 = OpConstantComposite %2 %4 %4 %4 %4
%6 = OpConstantComposite %1 %5 %5 %5 %5
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Array_5_F32) {
auto* cast = array<f32, 5>(2.0f, 2.0f, 2.0f, 2.0f, 2.0f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 6u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%3 = OpTypeInt 32 0
%4 = OpConstant %3 5
%1 = OpTypeArray %2 %4
%5 = OpConstant %2 2
%6 = OpConstantComposite %1 %5 %5 %5 %5 %5
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Array_2_Vec3) {
auto* first = vec3<f32>(1.f, 2.f, 3.f);
auto* second = vec3<f32>(1.f, 2.f, 3.f);
auto* t = Construct(ty.array(ty.vec3<f32>(), 2), first, second);
WrapInFunction(t);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(t), 10u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 3
%4 = OpTypeInt 32 0
%5 = OpConstant %4 2
%1 = OpTypeArray %2 %5
%6 = OpConstant %3 1
%7 = OpConstant %3 2
%8 = OpConstant %3 3
%9 = OpConstantComposite %2 %6 %7 %8
%10 = OpConstantComposite %1 %9 %9
)");
}
TEST_F(SpvBuilderConstructorTest, CommonInitializer_TwoVectors) {
auto* v1 = vec3<f32>(2.0f, 2.0f, 2.0f);
auto* v2 = vec3<f32>(2.0f, 2.0f, 2.0f);
ast::StatementList stmts = {
WrapInStatement(v1),
WrapInStatement(v2),
};
WrapInFunction(stmts);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(v1), 4u);
EXPECT_EQ(b.GenerateExpression(v2), 4u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeVector %2 3
%3 = OpConstant %2 2
%4 = OpConstantComposite %1 %3 %3 %3
)");
}
TEST_F(SpvBuilderConstructorTest, CommonInitializer_TwoArrays) {
auto* a1 = array<f32, 3>(2.0f, 2.0f, 2.0f);
auto* a2 = array<f32, 3>(2.0f, 2.0f, 2.0f);
ast::StatementList stmts = {
WrapInStatement(a1),
WrapInStatement(a2),
};
WrapInFunction(stmts);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(a1), 6u);
EXPECT_EQ(b.GenerateExpression(a2), 6u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%3 = OpTypeInt 32 0
%4 = OpConstant %3 3
%1 = OpTypeArray %2 %4
%5 = OpConstant %2 2
%6 = OpConstantComposite %1 %5 %5 %5
)");
}
TEST_F(SpvBuilderConstructorTest, CommonInitializer_Array_VecArray) {
// Test that initializers of different types with the same values produce
// different OpConstantComposite instructions.
// crbug.com/tint/777
auto* a1 = array<f32, 2>(1.0f, 2.0f);
auto* a2 = vec2<f32>(1.0f, 2.0f);
ast::StatementList stmts = {
WrapInStatement(a1),
WrapInStatement(a2),
};
WrapInFunction(stmts);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(a1), 7u);
EXPECT_EQ(b.GenerateExpression(a2), 9u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%3 = OpTypeInt 32 0
%4 = OpConstant %3 2
%1 = OpTypeArray %2 %4
%5 = OpConstant %2 1
%6 = OpConstant %2 2
%7 = OpConstantComposite %1 %5 %6
%8 = OpTypeVector %2 2
%9 = OpConstantComposite %8 %5 %6
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Struct) {
auto* s = Structure("my_struct", {
Member("a", ty.f32()),
Member("b", ty.vec3<f32>()),
});
auto* t = Construct(ty.Of(s), 2.0f, vec3<f32>(2.0f, 2.0f, 2.0f));
WrapInFunction(t);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(t), 6u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%3 = OpTypeVector %2 3
%1 = OpTypeStruct %2 %3
%4 = OpConstant %2 2
%5 = OpConstantComposite %3 %4 %4 %4
%6 = OpConstantComposite %1 %4 %5
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ZeroInit_F32) {
auto* t = Construct(ty.f32());
WrapInFunction(t);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(t), 2u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%1 = OpTypeFloat 32
%2 = OpConstantNull %1
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ZeroInit_I32) {
auto* t = Construct<i32>();
WrapInFunction(t);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(t), 2u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%1 = OpTypeInt 32 1
%2 = OpConstantNull %1
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ZeroInit_U32) {
auto* t = Construct<u32>();
WrapInFunction(t);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(t), 2u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%1 = OpTypeInt 32 0
%2 = OpConstantNull %1
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ZeroInit_Bool) {
auto* t = Construct(ty.bool_());
WrapInFunction(t);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(t), 2u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%1 = OpTypeBool
%2 = OpConstantNull %1
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ZeroInit_Vector) {
auto* t = vec2<i32>();
WrapInFunction(t);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(t), 3u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeInt 32 1
%1 = OpTypeVector %2 2
%3 = OpConstantNull %1
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ZeroInit_Matrix) {
auto* t = mat4x2<f32>();
WrapInFunction(t);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(t), 4u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeFloat 32
%2 = OpTypeVector %3 2
%1 = OpTypeMatrix %2 4
%4 = OpConstantNull %1
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ZeroInit_Array) {
auto* t = array<i32, 2>();
WrapInFunction(t);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(t), 5u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeInt 32 1
%3 = OpTypeInt 32 0
%4 = OpConstant %3 2
%1 = OpTypeArray %2 %4
%5 = OpConstantNull %1
)");
}
TEST_F(SpvBuilderConstructorTest, Type_ZeroInit_Struct) {
auto* s = Structure("my_struct", {Member("a", ty.f32())});
auto* t = Construct(ty.Of(s));
WrapInFunction(t);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(t), 3u);
ASSERT_FALSE(b.has_error()) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%1 = OpTypeStruct %2
%3 = OpConstantNull %1
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Convert_U32_To_I32) {
auto* cast = Construct<i32>(2u);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 1u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeInt 32 1
%3 = OpTypeInt 32 0
%4 = OpConstant %3 2
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%1 = OpBitcast %2 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Convert_I32_To_U32) {
auto* cast = Construct<u32>(2);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 1u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeInt 32 0
%3 = OpTypeInt 32 1
%4 = OpConstant %3 2
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%1 = OpBitcast %2 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Convert_F32_To_I32) {
auto* cast = Construct<i32>(2.4f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 1u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeInt 32 1
%3 = OpTypeFloat 32
%4 = OpConstant %3 2.4000001
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%1 = OpConvertFToS %2 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Convert_F32_To_U32) {
auto* cast = Construct<u32>(2.4f);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 1u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeInt 32 0
%3 = OpTypeFloat 32
%4 = OpConstant %3 2.4000001
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%1 = OpConvertFToU %2 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Convert_I32_To_F32) {
auto* cast = Construct<f32>(2);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 1u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%3 = OpTypeInt 32 1
%4 = OpConstant %3 2
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%1 = OpConvertSToF %2 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Convert_U32_To_F32) {
auto* cast = Construct<f32>(2u);
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
EXPECT_EQ(b.GenerateExpression(cast), 1u);
EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
%3 = OpTypeInt 32 0
%4 = OpConstant %3 2
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%1 = OpConvertUToF %2 %4
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Convert_Vectors_U32_to_I32) {
auto* var = Global("i", ty.vec3<u32>(), ast::StorageClass::kPrivate);
auto* cast = vec3<i32>("i");
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
ASSERT_TRUE(b.GenerateGlobalVariable(var)) << b.error();
EXPECT_EQ(b.GenerateExpression(cast), 6u) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%4 = OpTypeInt 32 0
%3 = OpTypeVector %4 3
%2 = OpTypePointer Private %3
%5 = OpConstantNull %3
%1 = OpVariable %2 Private %5
%8 = OpTypeInt 32 1
%7 = OpTypeVector %8 3
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%9 = OpLoad %3 %1
%6 = OpBitcast %7 %9
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Convert_Vectors_F32_to_I32) {
auto* var = Global("i", ty.vec3<f32>(), ast::StorageClass::kPrivate);
auto* cast = vec3<i32>("i");
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
ASSERT_TRUE(b.GenerateGlobalVariable(var)) << b.error();
EXPECT_EQ(b.GenerateExpression(cast), 6u) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%4 = OpTypeFloat 32
%3 = OpTypeVector %4 3
%2 = OpTypePointer Private %3
%5 = OpConstantNull %3
%1 = OpVariable %2 Private %5
%8 = OpTypeInt 32 1
%7 = OpTypeVector %8 3
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%9 = OpLoad %3 %1
%6 = OpConvertFToS %7 %9
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Convert_Vectors_I32_to_U32) {
auto* var = Global("i", ty.vec3<i32>(), ast::StorageClass::kPrivate);
auto* cast = vec3<u32>("i");
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
ASSERT_TRUE(b.GenerateGlobalVariable(var)) << b.error();
EXPECT_EQ(b.GenerateExpression(cast), 6u) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%4 = OpTypeInt 32 1
%3 = OpTypeVector %4 3
%2 = OpTypePointer Private %3
%5 = OpConstantNull %3
%1 = OpVariable %2 Private %5
%8 = OpTypeInt 32 0
%7 = OpTypeVector %8 3
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%9 = OpLoad %3 %1
%6 = OpBitcast %7 %9
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Convert_Vectors_F32_to_U32) {
auto* var = Global("i", ty.vec3<f32>(), ast::StorageClass::kPrivate);
auto* cast = vec3<u32>("i");
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
ASSERT_TRUE(b.GenerateGlobalVariable(var)) << b.error();
EXPECT_EQ(b.GenerateExpression(cast), 6u) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%4 = OpTypeFloat 32
%3 = OpTypeVector %4 3
%2 = OpTypePointer Private %3
%5 = OpConstantNull %3
%1 = OpVariable %2 Private %5
%8 = OpTypeInt 32 0
%7 = OpTypeVector %8 3
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%9 = OpLoad %3 %1
%6 = OpConvertFToU %7 %9
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Convert_Vectors_I32_to_F32) {
auto* var = Global("i", ty.vec3<i32>(), ast::StorageClass::kPrivate);
auto* cast = vec3<f32>("i");
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
ASSERT_TRUE(b.GenerateGlobalVariable(var)) << b.error();
EXPECT_EQ(b.GenerateExpression(cast), 6u) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%4 = OpTypeInt 32 1
%3 = OpTypeVector %4 3
%2 = OpTypePointer Private %3
%5 = OpConstantNull %3
%1 = OpVariable %2 Private %5
%8 = OpTypeFloat 32
%7 = OpTypeVector %8 3
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%9 = OpLoad %3 %1
%6 = OpConvertSToF %7 %9
)");
}
TEST_F(SpvBuilderConstructorTest, Type_Convert_Vectors_U32_to_F32) {
auto* var = Global("i", ty.vec3<u32>(), ast::StorageClass::kPrivate);
auto* cast = vec3<f32>("i");
WrapInFunction(cast);
spirv::Builder& b = Build();
b.push_function(Function{});
ASSERT_TRUE(b.GenerateGlobalVariable(var)) << b.error();
EXPECT_EQ(b.GenerateExpression(cast), 6u) << b.error();
EXPECT_EQ(DumpInstructions(b.types()), R"(%4 = OpTypeInt 32 0
%3 = OpTypeVector %4 3
%2 = OpTypePointer Private %3
%5 = OpConstantNull %3
%1 = OpVariable %2 Private %5
%8 = OpTypeFloat 32
%7 = OpTypeVector %8 3
)");
EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
R"(%9 = OpLoad %3 %1
%6 = OpConvertUToF %7 %9
)");
}
TEST_F(SpvBuilderConstructorTest,
IsConstructorConst_GlobalVectorWithAllConstConstructors) {
// vec3<f32>(1.0, 2.0, 3.0) -> true
auto* t = vec3<f32>(1.f, 2.f, 3.f);
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_TRUE(b.is_constructor_const(t, true));
EXPECT_FALSE(b.has_error());
}
TEST_F(SpvBuilderConstructorTest, IsConstructorConst_GlobalVector_WithIdent) {
// vec3<f32>(a, b, c) -> false -- ERROR
Global("a", ty.f32(), ast::StorageClass::kPrivate);
Global("b", ty.f32(), ast::StorageClass::kPrivate);
Global("c", ty.f32(), ast::StorageClass::kPrivate);
auto* t = vec3<f32>("a", "b", "c");
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_FALSE(b.is_constructor_const(t, true));
EXPECT_TRUE(b.has_error());
EXPECT_EQ(b.error(), "constructor must be a constant expression");
}
TEST_F(SpvBuilderConstructorTest,
IsConstructorConst_GlobalArrayWithAllConstConstructors) {
// array<vec3<f32>, 2>(vec3<f32>(1.0, 2.0, 3.0), vec3<f32>(1.0, 2.0, 3.0))
// -> true
auto* t = Construct(ty.array(ty.vec3<f32>(), 2), vec3<f32>(1.f, 2.f, 3.f),
vec3<f32>(1.f, 2.f, 3.f));
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_TRUE(b.is_constructor_const(t, true));
EXPECT_FALSE(b.has_error());
}
TEST_F(SpvBuilderConstructorTest,
IsConstructorConst_GlobalVectorWithMatchingTypeConstructors) {
// vec2<f32>(f32(1.0), f32(2.0)) -> false
auto* t = vec2<f32>(Construct<f32>(1.f), Construct<f32>(2.f));
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_FALSE(b.is_constructor_const(t, true));
EXPECT_FALSE(b.has_error());
}
TEST_F(SpvBuilderConstructorTest,
IsConstructorConst_GlobalWithTypeCastConstructor) {
// vec2<f32>(f32(1), f32(2)) -> false
auto* t = vec2<f32>(Construct<f32>(1), Construct<f32>(2));
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_FALSE(b.is_constructor_const(t, true));
EXPECT_FALSE(b.has_error());
}
TEST_F(SpvBuilderConstructorTest,
IsConstructorConst_VectorWithAllConstConstructors) {
// vec3<f32>(1.0, 2.0, 3.0) -> true
auto* t = vec3<f32>(1.f, 2.f, 3.f);
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_TRUE(b.is_constructor_const(t, false));
EXPECT_FALSE(b.has_error());
}
TEST_F(SpvBuilderConstructorTest, IsConstructorConst_Vector_WithIdent) {
// vec3<f32>(a, b, c) -> false
Global("a", ty.f32(), ast::StorageClass::kPrivate);
Global("b", ty.f32(), ast::StorageClass::kPrivate);
Global("c", ty.f32(), ast::StorageClass::kPrivate);
auto* t = vec3<f32>("a", "b", "c");
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_FALSE(b.is_constructor_const(t, false));
EXPECT_FALSE(b.has_error());
}
TEST_F(SpvBuilderConstructorTest,
IsConstructorConst_ArrayWithAllConstConstructors) {
// array<vec3<f32>, 2>(vec3<f32>(1.0, 2.0, 3.0), vec3<f32>(1.0, 2.0, 3.0))
// -> true
auto* first = vec3<f32>(1.f, 2.f, 3.f);
auto* second = vec3<f32>(1.f, 2.f, 3.f);
auto* t = Construct(ty.array(ty.vec3<f32>(), 2), first, second);
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_TRUE(b.is_constructor_const(t, false));
EXPECT_FALSE(b.has_error());
}
TEST_F(SpvBuilderConstructorTest,
IsConstructorConst_VectorWithTypeCastConstConstructors) {
// vec2<f32>(f32(1), f32(2)) -> false
auto* t = vec2<f32>(Construct<f32>(1), Construct<f32>(2));
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_FALSE(b.is_constructor_const(t, false));
EXPECT_FALSE(b.has_error());
}
TEST_F(SpvBuilderConstructorTest, IsConstructorConst_BitCastScalars) {
auto* t = vec2<u32>(Construct<u32>(1), Construct<u32>(1));
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_FALSE(b.is_constructor_const(t, false));
EXPECT_FALSE(b.has_error());
}
TEST_F(SpvBuilderConstructorTest, IsConstructorConst_Struct) {
auto* s = Structure("my_struct", {
Member("a", ty.f32()),
Member("b", ty.vec3<f32>()),
});
auto* t = Construct(ty.Of(s), 2.f, vec3<f32>(2.f, 2.f, 2.f));
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_TRUE(b.is_constructor_const(t, false));
EXPECT_FALSE(b.has_error());
}
TEST_F(SpvBuilderConstructorTest,
IsConstructorConst_Struct_WithIdentSubExpression) {
auto* s = Structure("my_struct", {
Member("a", ty.f32()),
Member("b", ty.vec3<f32>()),
});
Global("a", ty.f32(), ast::StorageClass::kPrivate);
Global("b", ty.vec3<f32>(), ast::StorageClass::kPrivate);
auto* t = Construct(ty.Of(s), "a", "b");
WrapInFunction(t);
spirv::Builder& b = Build();
EXPECT_FALSE(b.is_constructor_const(t, false));
EXPECT_FALSE(b.has_error());
}
} // namespace
} // namespace spirv
} // namespace writer
} // namespace tint
| 26.919355 | 79 | 0.669762 | sunnyps |
0f6738ad200f86863aeebb2794c76ac05e98a1fa | 1,877 | cpp | C++ | programs_v2/chapter_10/example_10_4/modules/motion_sensor/motion_sensor.cpp | epernia/arm_book | ffdd17618c2c7372cef338fc743f517bf6f0f42b | [
"BSD-3-Clause"
] | 2 | 2021-05-03T17:21:37.000Z | 2021-06-08T08:32:07.000Z | programs_v2/chapter_10/example_10_4/modules/motion_sensor/motion_sensor.cpp | epernia/arm_book | ffdd17618c2c7372cef338fc743f517bf6f0f42b | [
"BSD-3-Clause"
] | null | null | null | programs_v2/chapter_10/example_10_4/modules/motion_sensor/motion_sensor.cpp | epernia/arm_book | ffdd17618c2c7372cef338fc743f517bf6f0f42b | [
"BSD-3-Clause"
] | 2 | 2020-10-14T19:06:24.000Z | 2021-06-08T08:32:09.000Z | //=====[Libraries]=============================================================
#include "arm_book_lib.h"
#include "motion_sensor.h"
#include "pc_serial_com.h"
//=====[Declaration of private defines]========================================
//=====[Declaration of private data types]=====================================
//=====[Declaration and initialization of public global objects]===============
InterruptIn pirOutputSignal(PG_0);
//=====[Declaration of external public global variables]=======================
//=====[Declaration and initialization of public global variables]=============
//=====[Declaration and initialization of private global variables]============
static bool pirState;
static bool motionSensorActivated;
//=====[Declarations (prototypes) of private functions]========================
static void motionDetected();
static void motionCeased();
//=====[Implementations of public functions]===================================
void motionSensorInit()
{
pirOutputSignal.rise(&motionDetected);
pirState = OFF;
motionSensorActivated = true;
}
bool motionSensorRead()
{
return pirState;
}
void motionSensorActivate()
{
motionSensorActivated = true;
if ( !pirState ) {
pirOutputSignal.rise(&motionDetected);
}
pcSerialComStringWrite("The motion sensor has been activated\r\n");
}
void motionSensorDeactivate()
{
motionSensorActivated = false;
pcSerialComStringWrite("The motion sensor has been deactivated\r\n");
}
//=====[Implementations of private functions]==================================
static void motionDetected()
{
pirState = ON;
pirOutputSignal.rise(NULL);
pirOutputSignal.fall(&motionCeased);
}
static void motionCeased()
{
pirState = OFF;
pirOutputSignal.fall(NULL);
if ( motionSensorActivated ) {
pirOutputSignal.rise(&motionDetected);
}
}
| 24.697368 | 79 | 0.602025 | epernia |
0f6b911cc3b29677a043042e76d2fa1857e8af88 | 6,756 | cpp | C++ | bolt/server/src/url_utils.cpp | gamunu/bolt | c1a2956f02656f3ec2c244486a816337126905ae | [
"Apache-2.0"
] | 1 | 2022-03-06T09:23:56.000Z | 2022-03-06T09:23:56.000Z | bolt/server/src/url_utils.cpp | gamunu/bolt | c1a2956f02656f3ec2c244486a816337126905ae | [
"Apache-2.0"
] | 3 | 2021-04-23T18:12:20.000Z | 2021-04-23T18:12:47.000Z | bolt/server/src/url_utils.cpp | gamunu/bolt | c1a2956f02656f3ec2c244486a816337126905ae | [
"Apache-2.0"
] | null | null | null | #include <url_utils.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <regex>
#include <message_types.hpp>
vector<string_t> UrlUtils::splitUri(const http_request& message)
{
return uri::split_path(uri::decode(message.relative_uri().path()));
}
/// <summary>
/// Gets the name of the table.
/// Validates the table name using regular expression
/// Returns true if maches otherwise returns false
/// </summary>
/// <param name="paths">vector of paths.</param>
/// <param name="table">referece to table name.</param>
/// <returns></returns>
bool UrlUtils::getTableName(const vector<string_t> paths, string_t &table)
{
//Expression will check for Table('name')
//Table name must be 2 to 62 long and can have alphanumaric characters
const wregex expression(U("^(?:Tables\\(')([A-Za-z][A-Za-z0-9]{2,62})(?:'\\))$"));
wsmatch what;
//Path[1] is the Table('name')
if (regex_match(paths[0], what, expression))
{
table = what[1]; //There are three sets in the expression, 2nd is the table name
return true;
}
return false;
}
bool UrlUtils::getTableNamespace(const vector<string_t> paths, string_t &tablenamespace)
{
if (paths.size() > 0)
{
tablenamespace = paths[0];
return true;
}
return false;
}
map<string_t, string_t> UrlUtils::splitQueryString(const http_request& message)
{
return uri::split_query(uri::decode(message.relative_uri().query()));
}
vector<string_t> UrlUtils::getColumnNames(string_t str)
{
vector<string_t> columns;
boost::split(columns, str, boost::is_any_of(","));
return columns;
}
bool UrlUtils::hasTables(vector<string_t> const paths)
{
if (paths.size() >= 0 && paths[0] == U("Tables"))
{
return true;
}
return false;
}
bool UrlUtils::hasQuery(vector<string_t> const paths)
{
if (paths.size() >= 0 && paths[0] == U("Query"))
{
return true;
}
return false;
}
bool UrlUtils::hasAdministration(vector<string_t> const paths)
{
if (paths.size() >= 0 && paths[0] == U("Administration"))
{
return true;
}
return false;
}
bool UrlUtils::getTableNameWithKeys(vector<string_t> const paths, string_t& table, string_t& rowkey, string_t& paritionkey)
{
//Expression will check for tablename(RowKey='<rowkey>',PartitionKey='<partitionkey>')
//Table name must be 2 to 62 long and can have alphanumaric characters
const wregex expression(U("^([A-Za-z][A-Za-z0-9]{2,62})(?:\\()(?:(?:PartitionKey=')(\\w+)(?:',RowKey=')(\\w+)(?:'))?(?:\\))$"));
wsmatch what;
//Path[1] is the Table('name')
if (regex_match(paths[0], what, expression))
{
table = what[1]; //There are three sets in the expression, 2nd is the table name
paritionkey = what[2];
rowkey = what[3];
return true;
}
return false;
}
bool UrlUtils::getTableNameWithoutKeys(vector<string_t> const paths, string_t& table)
{
//Expression will check for tablename(RowKey='<rowkey>',PartitionKey='<partitionkey>')
//Table name must be 2 to 62 long and can have alphanumaric characters
const wregex expression(U("^([A-Za-z][A-Za-z0-9]{2,62})(?:\\()?(?:\\))?$"));
wsmatch what;
//Path[1] is the Table('name')
if (regex_match(paths[0], what, expression))
{
table = what[1]; //There are three sets in the expression, 2nd is the table name
return true;
}
return false;
}
bool UrlUtils::getAnalyze(vector<string_t> const paths, string_t& tablename)
{
if (paths.size() >= 2 && paths[1] == U("Analyze") && !paths[2].empty())
{
tablename = paths[2];
return true;
}
return false;
}
bool UrlUtils::getCheck(vector<string_t> const paths, string_t& tablename)
{
if (paths.size() >= 2 && paths[1] == U("Check") && !paths[2].empty())
{
tablename = paths[2];
return true;
}
return false;
}
bool UrlUtils::getRepair(vector<string_t> const paths, string_t& tablename)
{
if (paths.size() >= 2 && paths[1] == U("Repair") && !paths[2].empty())
{
tablename = paths[2];
return true;
}
return false;
}
bool UrlUtils::getIndexes(vector<string_t> const paths, string_t& tablename)
{
if (paths.size() >= 2 && paths[1] == U("Indexes") && !paths[2].empty())
{
tablename = paths[2];
return true;
}
return false;
}
bool UrlUtils::getKeys(vector<string_t> const paths, string_t& tablename)
{
if (paths.size() >= 2 && paths[1] == U("Keys") && !paths[2].empty())
{
tablename = paths[2];
return true;
}
return false;
}
bool UrlUtils::getOptimize(vector<string_t> const paths, string_t& tablename)
{
if (paths.size() >= 2 && paths[1] == U("Optimize") && !paths[2].empty())
{
tablename = paths[2];
return true;
}
return false;
}
bool UrlUtils::hasEngines(vector<string_t> const paths)
{
if (paths.size() >= 2 && paths[1] == U("Engines"))
{
return true;
}
return false;
}
bool UrlUtils::hasStatus(vector<string_t> const paths)
{
if (paths.size() >= 2 && paths[1] == U("Status"))
{
return true;
}
return false;
}
bool UrlUtils::hasPlugins(vector<string_t> const paths)
{
if (paths.size() >= 2 && paths[1] == U("Plugins"))
{
return true;
}
return false;
}
bool UrlUtils::hasOpenTables(vector<string_t> const paths)
{
if (paths.size() >= 2 && paths[1] == U("OpenTables"))
{
return true;
}
return false;
}
bool UrlUtils::getFilter(map<string_t, string_t> const query, map<string_t, string_t> &filter)
{
map<string_t, string_t> parsed_query;
//Expression will check for tablename(RowKey='<rowkey>',PartitionKey='<partitionkey>')
//Table name must be 2 to 62 long and can have alphanumaric characters
string_t expression_string = U("^(?:(?:\\()(\\w+)(?:\\s)(le|lt|ge|gt|ne|eq)(?:\\s)(\\w+)(?:\\)))(?:(?:\\s)(and|or)(?:\\s)(?:(?:\\()(\\w+)(?:\\s)(le|lt|ge|gt|ne|eq)(?:\\s)(\\w+)(?:\\))))?$");
auto lfilter = query.find(FILTER);
if (lfilter != query.end())
{
const wregex expression(expression_string);
wsmatch what;
//Path[1] is the Table('name')
string_t filter_value = lfilter->second;
if (regex_match(filter_value, what, expression))
{
if (what.size() >= 3)
{
parsed_query.insert(make_pair(U("first_attr"), what[1]));
parsed_query.insert(make_pair(U("first_con"), what[2]));
parsed_query.insert(make_pair(U("first_val"), what[3]));
if (what.size() == 8)
{
parsed_query.insert(make_pair(U("join"), what[4]));
parsed_query.insert(make_pair(U("second_attr"), what[5]));
parsed_query.insert(make_pair(U("second_con"), what[6]));
parsed_query.insert(make_pair(U("second_val"), what[7]));
}
filter = parsed_query;
return true;
}
}
}
return false;
}
bool UrlUtils::getSelect(map<string_t, string_t> const query, vector<string_t>& select)
{
if (query.find(SELECT) != query.cend())
{
auto lselect = getColumnNames(query.find(SELECT)->second);
if (lselect.size() > 0)
{
select = lselect;
return true;
}
}
return false;
} | 25.688213 | 191 | 0.658526 | gamunu |
0f71a13fe7bbca1b1dd842c861f5fe5fa5be9332 | 1,477 | cpp | C++ | Classes/Scenes/SplashScene.cpp | datakop/shipio | d24826d5477830a5563700574fafdf0ab686f47e | [
"MIT"
] | null | null | null | Classes/Scenes/SplashScene.cpp | datakop/shipio | d24826d5477830a5563700574fafdf0ab686f47e | [
"MIT"
] | null | null | null | Classes/Scenes/SplashScene.cpp | datakop/shipio | d24826d5477830a5563700574fafdf0ab686f47e | [
"MIT"
] | null | null | null | #include "SplashScene.h"
#include "MainMenuScene.h"
#include "Definitions.h"
USING_NS_CC;
Scene* SplashScene::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = SplashScene::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool SplashScene::init()
{
//////////////////////////////
// 1. super init first
if (!Layer::init()) {
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
this->scheduleOnce(schedule_selector(SplashScene::GoToMainMenuScene), DISPLAY_TIME_SPLASH_SCENE);
auto backgroundSprite = Sprite::create("splash.jpg");
backgroundSprite->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
this->addChild(backgroundSprite);
auto label = Label::createWithTTF("The Shipio game", "fonts/Marker Felt.ttf", 70);
label->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
this->addChild(label);
return true;
}
void SplashScene::GoToMainMenuScene(float dt)
{
auto scene = MainMenuScene::createScene();
Director::getInstance()->replaceScene(TransitionFade::create(TRANSITION_TIME, scene));
}
| 26.375 | 110 | 0.665538 | datakop |
0f71a986d711e6e9509b65d72c3031303a12e523 | 7,256 | hpp | C++ | ReactNativeFrontend/ios/Pods/boost/boost/gil/extension/numeric/sampler.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 153 | 2015-02-03T06:03:54.000Z | 2022-03-20T15:06:34.000Z | ReactNativeFrontend/ios/Pods/boost/boost/gil/extension/numeric/sampler.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 429 | 2015-03-22T09:49:04.000Z | 2022-03-28T08:32:08.000Z | ReactNativeFrontend/ios/Pods/boost/boost/gil/extension/numeric/sampler.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 215 | 2015-03-15T09:20:51.000Z | 2022-03-30T12:40:07.000Z | //
// Copyright 2005-2007 Adobe Systems Incorporated
//
// 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 BOOST_GIL_EXTENSION_NUMERIC_SAMPLER_HPP
#define BOOST_GIL_EXTENSION_NUMERIC_SAMPLER_HPP
#include <boost/gil/extension/numeric/pixel_numeric_operations.hpp>
#include <boost/gil/extension/dynamic_image/dynamic_image_all.hpp>
namespace boost { namespace gil {
// Nearest-neighbor and bilinear image samplers.
// NOTE: The code is for example use only. It is not optimized for performance
///////////////////////////////////////////////////////////////////////////
////
//// resample_pixels: set each pixel in the destination view as the result of a sampling function over the transformed coordinates of the source view
////
///////////////////////////////////////////////////////////////////////////
/*
template <typename Sampler>
concept SamplerConcept {
template <typename DstP, // Models PixelConcept
typename SrcView, // Models RandomAccessNDImageViewConcept
typename S_COORDS> // Models PointNDConcept, where S_COORDS::num_dimensions == SrcView::num_dimensions
bool sample(const Sampler& s, const SrcView& src, const S_COORDS& p, DstP result);
};
*/
/// \brief A sampler that sets the destination pixel to the closest one in the source. If outside the bounds, it doesn't change the destination
/// \ingroup ImageAlgorithms
struct nearest_neighbor_sampler {};
template <typename DstP, typename SrcView, typename F>
bool sample(nearest_neighbor_sampler, SrcView const& src, point<F> const& p, DstP& result)
{
typename SrcView::point_t center(iround(p));
if (center.x >= 0 && center.y >= 0 && center.x < src.width() && center.y < src.height())
{
result=src(center.x,center.y);
return true;
}
return false;
}
struct cast_channel_fn {
template <typename SrcChannel, typename DstChannel>
void operator()(const SrcChannel& src, DstChannel& dst) {
using dst_value_t = typename channel_traits<DstChannel>::value_type;
dst = dst_value_t(src);
}
};
template <typename SrcPixel, typename DstPixel>
void cast_pixel(const SrcPixel& src, DstPixel& dst) {
static_for_each(src,dst,cast_channel_fn());
}
namespace detail {
template <typename Weight>
struct add_dst_mul_src_channel {
Weight _w;
add_dst_mul_src_channel(Weight w) : _w(w) {}
template <typename SrcChannel, typename DstChannel>
void operator()(const SrcChannel& src, DstChannel& dst) const {
dst += DstChannel(src*_w);
}
};
// dst += DST_TYPE(src * w)
template <typename SrcP,typename Weight,typename DstP>
struct add_dst_mul_src {
void operator()(const SrcP& src, Weight weight, DstP& dst) const {
static_for_each(src,dst, add_dst_mul_src_channel<Weight>(weight));
// pixel_assigns_t<DstP,DstP&>()(
// pixel_plus_t<DstP,DstP,DstP>()(
// pixel_multiplies_scalar_t<SrcP,Weight,DstP>()(src,weight),
// dst),
// dst);
}
};
} // namespace detail
/// \brief A sampler that sets the destination pixel as the bilinear interpolation of the four closest pixels from the source.
/// If outside the bounds, it doesn't change the destination
/// \ingroup ImageAlgorithms
struct bilinear_sampler {};
template <typename DstP, typename SrcView, typename F>
bool sample(bilinear_sampler, SrcView const& src, point<F> const& p, DstP& result)
{
using SrcP = typename SrcView::value_type;
point_t p0(ifloor(p.x), ifloor(p.y)); // the closest integer coordinate top left from p
point<F> frac(p.x-p0.x, p.y-p0.y);
if (p0.x < -1 || p0.y < -1 || p0.x>=src.width() || p0.y>=src.height())
{
return false;
}
pixel<F,devicen_layout_t<num_channels<SrcView>::value> > mp(0); // suboptimal
typename SrcView::xy_locator loc=src.xy_at(p0.x,p0.y);
if (p0.x == -1)
{
if (p0.y == -1)
{
// the top-left corner pixel
++loc.y();
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(loc.x()[1], 1 ,mp);
}
else if (p0.y+1<src.height())
{
// on the first column, but not the top-left nor bottom-left corner pixel
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(loc.x()[1], (1-frac.y),mp);
++loc.y();
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(loc.x()[1], frac.y ,mp);
}
else
{
// the bottom-left corner pixel
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(loc.x()[1], 1 ,mp);
}
}
else if (p0.x+1<src.width())
{
if (p0.y == -1)
{
// on the first row, but not the top-left nor top-right corner pixel
++loc.y();
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, (1-frac.x) ,mp);
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(loc.x()[1], frac.x ,mp);
}
else if (p0.y+1<src.height())
{
// most common case - inside the image, not on the frist nor last row/column
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, (1-frac.x)*(1-frac.y),mp);
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(loc.x()[1], frac.x *(1-frac.y),mp);
++loc.y();
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, (1-frac.x)* frac.y ,mp);
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(loc.x()[1], frac.x * frac.y ,mp);
}
else
{
// on the last row, but not the bottom-left nor bottom-right corner pixel
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, (1-frac.x) ,mp);
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(loc.x()[1], frac.x ,mp);
}
}
else
{
if (p0.y == -1)
{
// the top-right corner pixel
++loc.y();
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, 1 ,mp);
}
else if (p0.y+1<src.height())
{
// on the last column, but not the top-right nor bottom-right corner pixel
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, (1-frac.y),mp);
++loc.y();
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, frac.y ,mp);
}
else
{
// the bottom-right corner pixel
detail::add_dst_mul_src<SrcP,F,pixel<F,devicen_layout_t<num_channels<SrcView>::value> > >()(*loc, 1 ,mp);
}
}
// Convert from floating point average value to the source type
SrcP src_result;
cast_pixel(mp,src_result);
color_convert(src_result, result);
return true;
}
}} // namespace boost::gil
#endif
| 38.391534 | 153 | 0.643881 | Harshitha91 |
0f72fe0fafe806b12360e88900c0d937b34f04ca | 1,567 | cpp | C++ | Sparky-core/src/sp/graphics/shaders/ShaderFactory.cpp | LifeOrGame/Sparky | 2ebcba2613b47011a224ddce5bc9267b46ba0119 | [
"Apache-2.0"
] | 1,303 | 2015-02-15T05:12:55.000Z | 2022-03-18T18:23:28.000Z | Sparky-core/src/sp/graphics/shaders/ShaderFactory.cpp | WildFire212/Sparky | a679d0834e37eb3570dff18b01550210734cb97e | [
"Apache-2.0"
] | 124 | 2015-04-02T14:15:05.000Z | 2021-05-05T12:47:16.000Z | Sparky-core/src/sp/graphics/shaders/ShaderFactory.cpp | WildFire212/Sparky | a679d0834e37eb3570dff18b01550210734cb97e | [
"Apache-2.0"
] | 538 | 2015-02-19T21:53:15.000Z | 2022-03-11T06:18:05.000Z | #include "sp/sp.h"
#include "ShaderFactory.h"
#include "sp/graphics/API/Context.h"
namespace sp { namespace graphics { namespace ShaderFactory {
#if defined(SP_PLATFORM_WINDOWS)
static const char* s_BatchRendererShaderGL =
#include "sp/platform/opengl/shaders/BatchRenderer.shader"
;
static const char* s_BatchRendererShaderD3D =
#include "sp/platform/directx/shaders/BatchRenderer.hlsl"
;
static const char* s_SimpleShader =
#include "default/Simple.shader"
;
static const char* s_BasicLightShader =
#include "default/BasicLight.shader"
;
static const char* s_GeometryPassShader =
#include "default/GeometryPass.shader"
;
static const char* s_DebugShader =
#include "default/Debug.shader"
;
#else
#error TODO: GLES shaders!
#endif
API::Shader* BatchRendererShader()
{
switch (API::Context::GetRenderAPI())
{
case API::RenderAPI::OPENGL: return API::Shader::CreateFromSource("BatchRenderer", s_BatchRendererShaderGL);
case API::RenderAPI::DIRECT3D: return API::Shader::CreateFromSource("BatchRenderer", s_BatchRendererShaderD3D);
}
return nullptr;
}
API::Shader* SimpleShader()
{
return API::Shader::CreateFromSource("Simple Shader", s_SimpleShader);
}
API::Shader* BasicLightShader()
{
return API::Shader::CreateFromSource("Basic Light Shader", s_BasicLightShader);
}
API::Shader* GeometryPassShader()
{
return API::Shader::CreateFromSource("Geometry Pass Shader", s_GeometryPassShader);
}
API::Shader* DebugShader()
{
return API::Shader::CreateFromSource("Debug Shader", s_DebugShader);
}
} } } | 23.38806 | 114 | 0.746011 | LifeOrGame |
0f73f2833c8edee55a017101a079d075b1ebd422 | 3,869 | cpp | C++ | src/WMAnalysis.cpp | UK-MAC/WMTools | 308b46dda235de0f57ddcfaf8780d6015443805a | [
"MIT"
] | 9 | 2015-03-27T05:03:22.000Z | 2021-12-11T16:52:13.000Z | src/WMAnalysis.cpp | UK-MAC/WMTools | 308b46dda235de0f57ddcfaf8780d6015443805a | [
"MIT"
] | null | null | null | src/WMAnalysis.cpp | UK-MAC/WMTools | 308b46dda235de0f57ddcfaf8780d6015443805a | [
"MIT"
] | null | null | null | #include "../include/WMAnalysis.h"
WMAnalysis::WMAnalysis(string tracefile, bool graph, bool functions,
bool allocations, bool time_search, double time_val) {
/* Generate a tracefile name (from rank id) if not provided with one */
if (tracefile.empty())
tracefile = WMUtils::makeFileName();
trace_file_name = tracefile;
/* Set the flags */
allocation_graph = graph;
hwm_profile = functions;
hwm_allocations = allocations;
/* First check if we are doing a time search */
if(time_search){
trace_reader = new TraceReader(tracefile, false, true,
allocations, false, -1, time_val);
generateFunctionBreakdown(trace_reader);
return;
}
/* Make a new trace reader with the flags + perform first iteration */
trace_reader = new TraceReader(tracefile, allocation_graph);
/* If needed perform a second iteration */
if (hwm_profile || hwm_allocations) {
/* Extract the HWMID from first pass */
long hwmID = trace_reader->getHWMID();
TraceReader *secondPass = new TraceReader(tracefile, false, functions,
allocations, false, hwmID);
/* If required dump the graph */
if (hwm_profile)
generateFunctionBreakdown(secondPass);
delete secondPass;
}
}
void WMAnalysis::generateFunctionBreakdown(TraceReader * tr) {
/* Extract call site allocation data */
set<FunctionSiteAllocation *, FunctionSiteAllocation::comparator> call_sites =
tr->getFunctionBreakdown();
set<FunctionSiteAllocation *, FunctionSiteAllocation::comparatorMem> call_sites_mem(
call_sites.begin(), call_sites.end());
/* Get High Water Mark */
long HWM = tr->getCurrMemory();
/* Make a temp string buffer for writing to */
stringstream temp_stream (stringstream::in | stringstream::out);
/* Establish Iterator */
set<FunctionSiteAllocation *, FunctionSiteAllocation::comparatorMem>::reverse_iterator it =
call_sites_mem.rbegin();
/* Track MPI Memory function consumption */
long mpi_memory = 0;
bool mpi_found = false;
string mpi_function_name("libmpi");
double mpi_memory_percentage = 0;
/* Reverse iterate over call sites > orderd by size, dumping to file */
while (it != call_sites_mem.rend()) {
/* Reset MPI lib found status */
mpi_found = false;
FunctionSiteAllocation * fsa = *it;
int stackID = fsa->getStackId();
double percentage = ((double) fsa->getMemory()) / HWM;
percentage *= 100;
/* Output stack ID + data */
temp_stream << "Call Stack: " << stackID << " Allocated "
<< fsa->getMemory() << "(B) (" << percentage << "(%) ) from "
<< fsa->getCount() << " allocations\n";
vector <string> functions = tr->getCallStack(stackID);
int i;
for (i = 0; i < functions.size(); i++) {
/* Make indentation */
int j;
for (j = 0; j < i; j++)
temp_stream << "-";
temp_stream << functions[i] << "\n";
if(!mpi_found && functions[i].find(mpi_function_name)!=string::npos){
mpi_memory += fsa->getMemory();
mpi_found = true;
}
}
temp_stream << "\n\n";
/* Move to next allocation site */
it++;
}
/* Generate filename */
string hwm_filename = WMUtils::makeFunctionsFilename(trace_file_name);
/* Make file object */
ofstream hwm_file(hwm_filename.c_str());
hwm_file << "# HWM Functions file from WMTools - " << hwm_filename
<< " HWM of " << HWM << "(B)\n";
hwm_file << "# Time: " << tr->getCurrTime() << " (s)\n";
/* Dump MPI Memory to file */
mpi_memory_percentage = (((double) mpi_memory) / HWM)*100;
hwm_file << "# MPI Memory summary: " << mpi_memory << "(B) (" << mpi_memory_percentage << "%) of memory attributed to MPI (" << mpi_function_name << ")\n";
hwm_file << "#\n";
hwm_file << "# High Water Mark Function Breakdown\n";
hwm_file << "\n";
/* Copy contents of temp stream buffer to final file */
hwm_file<< temp_stream.str();
/* Close the files */
hwm_file.close();
}
| 26.868056 | 156 | 0.666839 | UK-MAC |
0f77710680f101585b0991b336c361d628845c0f | 21,288 | cc | C++ | verilog/CST/declaration_test.cc | ColtonProvias/verible | ded8ad5e03d0eca2125d9ae3ba6c4f07919b4565 | [
"Apache-2.0"
] | null | null | null | verilog/CST/declaration_test.cc | ColtonProvias/verible | ded8ad5e03d0eca2125d9ae3ba6c4f07919b4565 | [
"Apache-2.0"
] | null | null | null | verilog/CST/declaration_test.cc | ColtonProvias/verible | ded8ad5e03d0eca2125d9ae3ba6c4f07919b4565 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "verilog/CST/declaration.h"
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "common/analysis/syntax_tree_search.h"
#include "common/analysis/syntax_tree_search_test_utils.h"
#include "common/text/text_structure.h"
#include "common/text/tree_utils.h"
#include "verilog/CST/match_test_utils.h"
#undef ASSERT_OK
#define ASSERT_OK(value) ASSERT_TRUE((value).ok())
namespace verilog {
namespace {
using verible::SyntaxTreeSearchTestCase;
using verible::TextStructureView;
using verible::TreeSearchMatch;
TEST(FindAllDataDeclarations, CountMatches) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
{""},
{"module m;\nendmodule\n"},
{"class c;\nendclass\n"},
{"function f;\nendfunction\n"},
{"package p;\nendpackage\n"},
{"task t;\nendtask\n"},
{{kTag, "foo bar;"}, "\n"},
{{kTag, "foo bar, baz;"}, "\n"},
{{kTag, "foo bar;"}, "\n", {kTag, "foo baz;"}, "\n"},
{"module m;\n"
" ",
{kTag, "foo bar, baz;"},
"\n"
"endmodule\n"},
{"module m;\n",
{kTag, "foo bar;"},
"\n",
{kTag, "foo baz;"},
"\n"
"endmodule\n"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
return FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root));
});
}
}
TEST(FindAllNetVariablesTest, Various) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
// bar is inside kVariableDeclarationAssignment
// {"foo ", {kTag, "bar"}, ";\n"},
{""},
{"module m; endmodule\n"},
{"module m;\nwire ", {kTag, "bar"}, ";\nendmodule\n"},
{"module m;\nwire ", {kTag, "w"}, ", ", {kTag, "x"}, ";\nendmodule\n"},
{"module m;\nwire ", {kTag, "bar[N]"}, ";\nendmodule\n"},
{"module m;\nwire ", {kTag, "bar[N-1:0]"}, ";\nendmodule\n"},
{"module m;\nwire [M]", {kTag, "bar"}, ";\nendmodule\n"},
{"module m;\nwire [M]", {kTag, "bar[N]"}, ";\nendmodule\n"},
{"module m;\nwire [M][B]", {kTag, "bar[N][C]"}, ";\nendmodule\n"},
{"module m;\nwire ",
{kTag, "w[2]"},
", ",
{kTag, "x[4]"},
";\nendmodule\n"},
{"module m1;\nwire ",
{kTag, "baz"},
";\nendmodule\n"
"module m2;\nwire ",
{kTag, "bar"},
";\nendmodule\n"},
{"module m;\nlogic bar;\nendmodule\n"},
{"module m;\nreg bar;\nendmodule\n"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
return FindAllNetVariables(*ABSL_DIE_IF_NULL(root));
});
}
}
TEST(FindAllRegisterVariablesTest, Various) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
// bar is inside kVariableDeclarationAssignment
// {"foo ", {kTag, "bar"}, ";\n"},
{"module m;\nlogic ", {kTag, "bar"}, ";\nendmodule\n"},
{"module m;\nlogic ", {kTag, "bar[8]"}, ";\nendmodule\n"},
{"module m;\nlogic [4]", {kTag, "bar"}, ";\nendmodule\n"},
{"module m;\nreg ", {kTag, "bar"}, ";\nendmodule\n"},
{"module m;\nfoo ", {kTag, "bar"}, ";\nendmodule\n"},
{"module m;\nfoo ", {kTag, "bar"}, ", ", {kTag, "baz"}, ";\nendmodule\n"},
{"module m;\nlogic ",
{kTag, "bar"},
";\nlogic ",
{kTag, "baz"},
";\nendmodule\n"},
{"module m;\nwire bar;\nendmodule\n"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
return FindAllRegisterVariables(*ABSL_DIE_IF_NULL(root));
});
}
}
TEST(FindAllGateInstancesTest, Various) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
// bar is inside kVariableDeclarationAssignment
// {"foo ", {kTag, "bar"}, ";\n"},
{"module m;\nlogic bar;\nendmodule\n"},
{"module m;\nreg bar;\nendmodule\n"},
{"module m;\nfoo bar;\nendmodule\n"},
{"module m;\nfoo ", {kTag, "bar()"}, ";\nendmodule\n"},
{"module m;\nfoo ",
{kTag, "bar()"},
", ",
{kTag, "baz()"},
";\nendmodule\n"},
{"module m;\nfoo ",
{kTag, "bar()"},
";\ngoo ",
{kTag, "baz()"},
";\nendmodule\n"},
{"module m;\nfoo ", {kTag, "bar(baz)"}, ";\nendmodule\n"},
{"module m;\nfoo ", {kTag, "bar(baz, blah)"}, ";\nendmodule\n"},
{"module m;\nfoo ", {kTag, "bar(.baz)"}, ";\nendmodule\n"},
{"module m;\nfoo ", {kTag, "bar(.baz(baz))"}, ";\nendmodule\n"},
{"module m;\nfoo ", {kTag, "bar(.baz(baz), .c(c))"}, ";\nendmodule\n"},
{"module m;\nfoo #() ", {kTag, "bar()"}, ";\nendmodule\n"},
{"module m;\nfoo #(N) ", {kTag, "bar()"}, ";\nendmodule\n"},
{"module m;\nfoo #(.N(N)) ", {kTag, "bar()"}, ";\nendmodule\n"},
{"module m;\nfoo #(M, N) ", {kTag, "bar()"}, ";\nendmodule\n"},
{"module m;\nfoo #(.N(N), .M(M)) ", {kTag, "bar()"}, ";\nendmodule\n"},
{"module m;\nfoo #(.N(N), .M(M)) ",
{kTag, "bar()"},
",",
{kTag, "blah()"},
";\nendmodule\n"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
return FindAllGateInstances(*ABSL_DIE_IF_NULL(root));
});
}
}
TEST(FindAllGateInstancesTest, FindArgumentListOfGateInstance) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
// bar is inside kVariableDeclarationAssignment
// {"foo ", {kTag, "bar"}, ";\n"},
{"module m;\nlogic bar;\nendmodule\n"},
{"module m;\nreg bar;\nendmodule\n"},
{"module m;\nfoo bar;\nendmodule\n"},
{"module m;\nfoo bar", {kTag, "()"}, ";\nendmodule\n"},
{"module m;\nfoo bar",
{kTag, "()"},
", baz",
{kTag, "()"},
";\nendmodule\n"},
{"module m;\nfoo bar",
{kTag, "()"},
";\ngoo baz",
{kTag, "()"},
";\nendmodule\n"},
{"module m;\nfoo bar", {kTag, "(baz)"}, ";\nendmodule\n"},
{"module m;\nfoo bar", {kTag, "(baz, blah)"}, ";\nendmodule\n"},
{"module m;\nfoo bar", {kTag, "(.baz)"}, ";\nendmodule\n"},
{"module m;\nfoo bar", {kTag, "(.baz(baz))"}, ";\nendmodule\n"},
{"module m;\nfoo bar", {kTag, "(.baz(baz), .c(c))"}, ";\nendmodule\n"},
{"module m;\nfoo #() bar", {kTag, "()"}, ";\nendmodule\n"},
{"module m;\nfoo #(N) bar", {kTag, "()"}, ";\nendmodule\n"},
{"module m;\nfoo #(.N(N)) bar", {kTag, "()"}, ";\nendmodule\n"},
{"module m;\nfoo #(M, N) bar", {kTag, "()"}, ";\nendmodule\n"},
{"module m;\nfoo #(.N(N), .M(M)) bar", {kTag, "()"}, ";\nendmodule\n"},
{"module m;\nfoo #(.N(N), .M(M)) bar",
{kTag, "()"},
",blah",
{kTag, "()"},
";\nendmodule\n"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto& instances = FindAllGateInstances(*ABSL_DIE_IF_NULL(root));
std::vector<TreeSearchMatch> paren_groups;
for (const auto& decl : instances) {
const auto& paren_group =
GetParenGroupFromModuleInstantiation(*decl.match);
paren_groups.emplace_back(
TreeSearchMatch{&paren_group, {/* ignored context */}});
}
return paren_groups;
});
}
}
TEST(GetQualifiersOfDataDeclarationTest, NoQualifiers) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
// each of these test cases should match exactly one data declaration
// and have no qualifiers
{{kTag, "foo bar;"}, "\n"},
{"module m;\n",
{kTag, "foo bar;"},
"\n"
"endmodule\n"},
{"class c;\n",
{kTag, "int foo;"},
"\n"
"endclass\n"},
{"package p;\n",
{kTag, "int foo;"},
"\n"
"endpackage\n"},
{"function f;\n",
{kTag, "logic bar;"},
"\n"
"endfunction\n"},
{"task t;\n",
{kTag, "logic bar;"},
"\n"
"endtask\n"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto decls = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root));
// Verify that quals is either nullptr or empty or contains only
// nullptrs.
for (const auto& decl : decls) {
const auto* quals = GetQualifiersOfDataDeclaration(*decl.match);
if (quals != nullptr) {
for (const auto& child : quals->children()) {
EXPECT_EQ(child, nullptr)
<< "unexpected qualifiers:\n"
<< verible::RawTreePrinter(*child) << "\nfailed on:\n"
<< text_structure.Contents();
}
}
}
return decls;
});
}
}
TEST(GetTypeOfDataDeclarationTest, ExplicitTypes) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
// each of these test cases should match exactly one data declaration
// and have no qualifiers
{{kTag, "foo"}, " bar;\n"},
{{kTag, "foo"}, " bar, baz;\n"},
{"const ", {kTag, "foo"}, " bar;\n"},
{"const ", {kTag, "foo#(1)"}, " bar;\n"},
{"const ", {kTag, "foo#(.N(1))"}, " bar;\n"},
{"const ", {kTag, "foo#(1, 2, 3)"}, " bar;\n"},
{"static ", {kTag, "foo"}, " bar;\n"},
{"var static ", {kTag, "foo"}, " bar;\n"},
{"automatic ", {kTag, "foo"}, " bar;\n"},
{"class c;\n",
{kTag, "int"},
" foo;\n"
"endclass\n"},
{"class c;\n"
"const static ",
{kTag, "int"},
" foo;\n"
"endclass\n"},
{"class c;\n"
"function f;\n"
"const ",
{kTag, "int"},
" foo;\n"
"endfunction\n"
"endclass\n"},
{"class c;\n"
"function f;\n"
"const ",
{kTag, "int"},
" foo;\n",
{kTag, "bit"},
" bar;\n"
"endfunction\n"
"endclass\n"},
{"class c;\n"
"function f;\n"
"const ",
{kTag, "int"},
" foo;\n",
"endfunction\n"
"endclass\n"
"class d;\n"
"function g;\n",
{kTag, "bit"},
" bar;\n"
"endfunction\n"
"endclass\n"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto decls = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root));
std::vector<TreeSearchMatch> types;
for (const auto& decl : decls) {
const auto& type = GetTypeOfDataDeclaration(*decl.match);
types.emplace_back(TreeSearchMatch{&type, {/* ignored context */}});
}
return types;
});
}
}
TEST(GetQualifiersOfDataDeclarationTest, SomeQualifiers) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
// each of these test cases should match exactly one data declaration
// and have no qualifiers
{{kTag, "const"}, " foo bar;\n"},
{{kTag, "const"}, " foo#(1) bar;\n"},
{{kTag, "const"}, " foo bar, baz;\n"},
{{kTag, "static"}, " foo bar;\n"},
{{kTag, "automatic"}, " foo bar;\n"},
{{kTag, "var"}, " foo bar;\n"},
{{kTag, "var static"}, " foo bar;\n"},
{{kTag, "const static"}, " foo bar;\n"},
{"class c;\n",
{kTag, "const static"},
" int foo;\n"
"endclass\n"},
{"class c;\n",
{kTag, "const"},
" int foo;\n"
"endclass\n"},
{"class c;\n"
"function f;\n",
{kTag, "const"},
" int foo;\n"
"endfunction\n"
"endclass\n"},
{"class c;\n"
"function f;\n",
{kTag, "const"},
" int foo;\n",
{kTag, "const"},
" bit bar;\n"
"endfunction\n"
"endclass\n"},
{"class c;\n"
"function f;\n",
{kTag, "const"},
" int foo;\n",
"endfunction\n"
"endclass\n"
"class d;\n"
"function g;\n",
{kTag, "const"},
" bit bar;\n"
"endfunction\n"
"endclass\n"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto decls = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root));
std::vector<TreeSearchMatch> quals;
for (const auto& decl : decls) {
const auto* qual = GetQualifiersOfDataDeclaration(*decl.match);
if (qual != nullptr) {
quals.push_back(TreeSearchMatch{qual, {/* ignored context */}});
} else {
EXPECT_NE(qual, nullptr) << "decl:\n"
<< verible::RawTreePrinter(*decl.match);
}
}
return quals;
});
}
}
TEST(GetInstanceListFromDataDeclarationTest, InstanceLists) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
// each of these test cases should match exactly one data declaration
// and have no qualifiers
{"foo ", {kTag, "bar"}, ";\n"},
{"foo ", {kTag, "bar = 0"}, ";\n"},
{"foo ", {kTag, "bar, baz"}, ";\n"},
{"foo ", {kTag, "bar = 1, baz = 2"}, ";\n"},
{"foo#(1) ", {kTag, "bar"}, ";\n"},
{"foo#(1,2) ", {kTag, "bar,baz,bam"}, ";\n"},
{"const foo ", {kTag, "bar = 0"}, ";\n"},
{"static foo ", {kTag, "bar = 0"}, ";\n"},
{"class c;\n"
" foo ",
{kTag, "bar"},
";\n"
"endclass\n"},
{"class c;\n"
" foo ",
{kTag, "barr, bazz"},
";\n"
"endclass\n"},
{"class c;\n"
" const int ",
{kTag, "barr, bazz"},
";\n"
"endclass\n"},
{"class c;\n"
" const int ",
{kTag, "barr=3, bazz=4"},
";\n"
"endclass\n"},
{"function f;\n"
" foo ",
{kTag, "bar"},
";\n"
"endfunction\n"},
{"function f;\n"
" foo ",
{kTag, "bar, baz"},
";\n"
"endfunction\n"},
{"task t;\n"
" foo ",
{kTag, "bar"},
";\n"
"endtask\n"},
{"task t;\n"
" foo ",
{kTag, "bar, baz"},
";\n"
"endtask\n"},
{"package p;\n"
" foo ",
{kTag, "bar"},
";\n"
"endpackage\n"},
{"package p;\n"
" foo ",
{kTag, "bar, baz"},
";\n"
"endpackage\n"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto decls = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root));
std::vector<TreeSearchMatch> inst_lists;
for (const auto& decl : decls) {
const auto& insts = GetInstanceListFromDataDeclaration(*decl.match);
inst_lists.push_back(
TreeSearchMatch{&insts, {/* ignored context */}});
}
return inst_lists;
});
}
}
TEST(GetVariableDeclarationAssign, VariableName) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
{""},
{"module m;\nendmodule\n"},
{"class class_c;\nendclass\nmodule m;\nclass_c c = new();\nendmodule"},
{"package pkg;\nint ",
{kTag, "x"},
", ",
{kTag, "y"},
";\nbit ",
{kTag, "b1"},
", ",
{kTag, "b2"},
";\nlogic ",
{kTag, "l1"},
", ",
{kTag, "l2"},
";\nstring ",
{kTag, "s1"},
", ",
{kTag, "s2"},
";\nendpackage"},
{"class class_c;\nint ",
{kTag, "x"},
", ",
{kTag, "y"},
";\nbit ",
{kTag, "b1"},
", ",
{kTag, "b2"},
";\nlogic ",
{kTag, "l1"},
", ",
{kTag, "l2"},
";\nstring ",
{kTag, "s1"},
", ",
{kTag, "s2"},
";\nendclass"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto decls =
FindAllVariableDeclarationAssignment(*ABSL_DIE_IF_NULL(root));
std::vector<TreeSearchMatch> names;
for (const auto& decl : decls) {
const auto& name =
GetUnqualifiedIdFromVariableDeclarationAssignment(*decl.match);
names.emplace_back(TreeSearchMatch{&name, {/* ignored context */}});
}
return names;
});
}
}
TEST(GetVariableDeclarationAssign,
FindTrailingAssignOfVariableDeclarationAssign) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
{""},
{"module m;\nendmodule\n"},
{"class class_c;\nendclass\nmodule m;\nclass_c c = new();\nendmodule"},
{"package pkg;\n int x ",
{kTag, "= 4"},
", y ",
{kTag, "= 4"},
";\nlogic k ",
{kTag, "= fun_call()"},
";\nendpackage"},
{"class cls;\n int x ",
{kTag, "= 4"},
", y ",
{kTag, "= 4"},
";\nlogic k ",
{kTag, "= fun_call()"},
";\nendclass"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto& instances =
FindAllVariableDeclarationAssignment(*ABSL_DIE_IF_NULL(root));
std::vector<TreeSearchMatch> paren_groups;
for (const auto& decl : instances) {
const auto* paren_group =
GetTrailingExpressionFromVariableDeclarationAssign(*decl.match);
paren_groups.emplace_back(
TreeSearchMatch{paren_group, {/* ignored context */}});
}
return paren_groups;
});
}
}
TEST(FindAllRegisterVariablesTest, FindTrailingAssignOfRegisterVariable) {
constexpr int kTag = 1; // value doesn't matter
const SyntaxTreeSearchTestCase kTestCases[] = {
{""},
{"module m;\nendmodule\n"},
{"class class_c;\nendclass\nmodule m;\nclass_c c ",
{kTag, "= new()"},
";\nendmodule"},
{"module module_m();\n int x ",
{kTag, "= 4"},
", y ",
{kTag, "= 4"},
";\nlogic k ",
{kTag, "= fun_call()"},
";\nendmodule"},
{"task tsk();\n int x ",
{kTag, "= 4"},
", y ",
{kTag, "= 4"},
";\nlogic k ",
{kTag, "= fun_call()"},
";\nendtask"},
{"function int fun();\n int x ",
{kTag, "= 4"},
", y ",
{kTag, "= 4"},
";\nlogic k ",
{kTag, "= fun_call()"},
";\nreturn 1;\nendfunction"},
};
for (const auto& test : kTestCases) {
TestVerilogSyntaxRangeMatches(
__FUNCTION__, test, [](const TextStructureView& text_structure) {
const auto& root = text_structure.SyntaxTree();
const auto& instances =
FindAllRegisterVariables(*ABSL_DIE_IF_NULL(root));
std::vector<TreeSearchMatch> paren_groups;
for (const auto& decl : instances) {
const auto* paren_group =
GetTrailingExpressionFromRegisterVariable(*decl.match);
paren_groups.emplace_back(
TreeSearchMatch{paren_group, {/* ignored context */}});
}
return paren_groups;
});
}
}
} // namespace
} // namespace verilog
| 32.600306 | 80 | 0.521233 | ColtonProvias |
0f7cd5ea5b7ba5628d5a7f9f10c53f28617f977c | 3,091 | cpp | C++ | OrbitLinuxTracing/PerfEventProcessor2.cpp | MagicPoncho/orbit | c92d2f64ad3caeef0e41ee04719d84217820b9f8 | [
"BSD-2-Clause"
] | null | null | null | OrbitLinuxTracing/PerfEventProcessor2.cpp | MagicPoncho/orbit | c92d2f64ad3caeef0e41ee04719d84217820b9f8 | [
"BSD-2-Clause"
] | null | null | null | OrbitLinuxTracing/PerfEventProcessor2.cpp | MagicPoncho/orbit | c92d2f64ad3caeef0e41ee04719d84217820b9f8 | [
"BSD-2-Clause"
] | 1 | 2020-05-20T04:32:01.000Z | 2020-05-20T04:32:01.000Z | #include "PerfEventProcessor2.h"
#include <OrbitBase/Logging.h>
#include <memory>
#include <queue>
#include "PerfEvent.h"
#include "Utils.h"
namespace LinuxTracing {
void PerfEventQueue::PushEvent(int origin_fd,
std::unique_ptr<PerfEvent> event) {
if (fd_event_queues_.count(origin_fd) > 0) {
std::shared_ptr<std::queue<std::unique_ptr<PerfEvent>>> event_queue =
fd_event_queues_.at(origin_fd);
CHECK(!event_queue->empty());
// Fundamental assumption: events from the same file descriptor come already
// in order.
CHECK(event->GetTimestamp() >= event_queue->front()->GetTimestamp());
event_queue->push(std::move(event));
} else {
auto event_queue =
std::make_shared<std::queue<std::unique_ptr<PerfEvent>>>();
fd_event_queues_.insert(std::make_pair(origin_fd, event_queue));
event_queue->push(std::move(event));
event_queues_queue_.push(std::make_pair(origin_fd, event_queue));
}
}
bool PerfEventQueue::HasEvent() { return !event_queues_queue_.empty(); }
PerfEvent* PerfEventQueue::TopEvent() {
return event_queues_queue_.top().second->front().get();
}
std::unique_ptr<PerfEvent> PerfEventQueue::PopEvent() {
std::pair<int, std::shared_ptr<std::queue<std::unique_ptr<PerfEvent>>>>
top_fd_queue = event_queues_queue_.top();
event_queues_queue_.pop();
const int& top_fd = top_fd_queue.first;
std::shared_ptr<std::queue<std::unique_ptr<PerfEvent>>>& top_queue =
top_fd_queue.second;
std::unique_ptr<PerfEvent> top_event = std::move(top_queue->front());
top_queue->pop();
if (top_queue->empty()) {
fd_event_queues_.erase(top_fd);
} else {
// Remove and re-insert so that the queue is in the right position in the
// heap after the front of the queue has been removed.
event_queues_queue_.push(top_fd_queue);
}
return top_event;
}
void PerfEventProcessor2::AddEvent(int origin_fd,
std::unique_ptr<PerfEvent> event) {
#ifndef NDEBUG
if (last_processed_timestamp_ > 0 &&
event->GetTimestamp() <
last_processed_timestamp_ - PROCESSING_DELAY_MS * 1'000'000) {
ERROR("Processed an event out of order");
}
#endif
event_queue_.PushEvent(origin_fd, std::move(event));
}
void PerfEventProcessor2::ProcessAllEvents() {
while (event_queue_.HasEvent()) {
std::unique_ptr<PerfEvent> event = event_queue_.PopEvent();
#ifndef NDEBUG
last_processed_timestamp_ = event->GetTimestamp();
#endif
event->Accept(visitor_.get());
}
}
void PerfEventProcessor2::ProcessOldEvents() {
uint64_t max_timestamp = MonotonicTimestampNs();
while (event_queue_.HasEvent()) {
PerfEvent* event = event_queue_.TopEvent();
// Do not read the most recent events as out-of-order events could arrive.
if (event->GetTimestamp() + PROCESSING_DELAY_MS * 1'000'000 >=
max_timestamp) {
break;
}
#ifndef NDEBUG
last_processed_timestamp_ = event->GetTimestamp();
#endif
event->Accept(visitor_.get());
event_queue_.PopEvent();
}
}
} // namespace LinuxTracing
| 30.303922 | 80 | 0.693627 | MagicPoncho |
0f7f06817ead0a7bc722e41881d61d57aee8ea7b | 5,662 | hpp | C++ | src/axom/inlet/LuaReader.hpp | bmhan12/axom | fbee125aec6357340f35b6fd5d0d4a62a3c80733 | [
"BSD-3-Clause"
] | 86 | 2019-04-12T20:39:37.000Z | 2022-01-28T17:06:08.000Z | src/axom/inlet/LuaReader.hpp | bmhan12/axom | fbee125aec6357340f35b6fd5d0d4a62a3c80733 | [
"BSD-3-Clause"
] | 597 | 2019-04-25T22:36:16.000Z | 2022-03-31T20:21:54.000Z | src/axom/inlet/LuaReader.hpp | bmhan12/axom | fbee125aec6357340f35b6fd5d0d4a62a3c80733 | [
"BSD-3-Clause"
] | 21 | 2019-06-27T15:53:08.000Z | 2021-09-30T20:17:41.000Z | // Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and
// other Axom Project Developers. See the top-level LICENSE file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
/*!
*******************************************************************************
* \file LuaReader.hpp
*
* \brief This file contains the class definition of the LuaReader.
*******************************************************************************
*/
#ifndef INLET_LUAMAP_HPP
#define INLET_LUAMAP_HPP
#include "axom/inlet/Reader.hpp"
#include "axom/sol.hpp"
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
namespace axom
{
namespace inlet
{
/*!
*******************************************************************************
* \class LuaReader
*
* \brief A Reader that is able to read variables from a Lua file.
*
* \see Reader
*******************************************************************************
*/
class LuaReader : public Reader
{
public:
LuaReader();
bool parseFile(const std::string& filePath) override;
bool parseString(const std::string& luaString) override;
ReaderResult getBool(const std::string& id, bool& value) override;
ReaderResult getDouble(const std::string& id, double& value) override;
ReaderResult getInt(const std::string& id, int& value) override;
ReaderResult getString(const std::string& id, std::string& value) override;
ReaderResult getIntMap(const std::string& id,
std::unordered_map<int, int>& values) override;
ReaderResult getIntMap(const std::string& id,
std::unordered_map<VariantKey, int>& values) override;
ReaderResult getDoubleMap(const std::string& id,
std::unordered_map<int, double>& values) override;
ReaderResult getDoubleMap(const std::string& id,
std::unordered_map<VariantKey, double>& values) override;
ReaderResult getBoolMap(const std::string& id,
std::unordered_map<int, bool>& values) override;
ReaderResult getBoolMap(const std::string& id,
std::unordered_map<VariantKey, bool>& values) override;
ReaderResult getStringMap(const std::string& id,
std::unordered_map<int, std::string>& values) override;
ReaderResult getStringMap(
const std::string& id,
std::unordered_map<VariantKey, std::string>& values) override;
ReaderResult getIndices(const std::string& id,
std::vector<int>& indices) override;
ReaderResult getIndices(const std::string& id,
std::vector<VariantKey>& indices) override;
FunctionVariant getFunction(const std::string& id,
const FunctionTag ret_type,
const std::vector<FunctionTag>& arg_types) override;
std::vector<std::string> getAllNames() override;
/*!
*****************************************************************************
* \brief The base index for arrays in Lua
*****************************************************************************
*/
static const int baseIndex = 1;
/*!
*****************************************************************************
* \brief Returns the Sol Lua state
*
* This allows the user to access functionality that was not provided by Inlet.
*
* \return Reference to the Sol Lua state
*****************************************************************************
*/
axom::sol::state& solState() { return m_lua; }
private:
// Expect this to be called for only Inlet-supported types.
template <typename T>
ReaderResult getValue(const std::string& id, T& value);
// Expect this to be called for only Inlet-supported types.
template <typename Key, typename Val>
ReaderResult getMap(const std::string& id,
std::unordered_map<Key, Val>& values,
axom::sol::type type);
template <typename T>
ReaderResult getIndicesInternal(const std::string& id, std::vector<T>& indices);
/*!
*****************************************************************************
* \brief Obtains the Lua table reached by successive indexing through the
* range of keys described by a pair of iterators
*
* \note For a set of keys {key1, key2, key3, ...}, this function
* is equivalent to
* \code{.cpp}
* table = m_lua[key1][key2][key3][...];
* \endcode
*
* \param [in] begin Iterator to the beginning of the range of keys
* \param [in] end Iterator to one-past-the-end of the range
* \param [out] t The table to traverse
*
* \return Whether the traversal was successful
*****************************************************************************
*/
template <typename Iter>
bool traverseToTable(Iter begin, Iter end, axom::sol::table& table);
/*!
*****************************************************************************
* \brief Traverses the Lua state to retrieve a sol function object
*
* \param [in] id The identifier to the function that will be retrieved
*
* \return The function, compares false if not found
*****************************************************************************
*/
axom::sol::protected_function getFunctionInternal(const std::string& id);
axom::sol::state m_lua;
// The elements in the global table preloaded by Sol/Lua, these are ignored
// to ensure that name retrieval only includes user-provided paths
std::vector<std::string> m_preloaded_globals;
};
} // end namespace inlet
} // end namespace axom
#endif
| 34.950617 | 85 | 0.548746 | bmhan12 |
0f7faf87e8f4b7f13e893b0f02c9fbc2789a103f | 1,058 | cpp | C++ | test/verify/aoj-0275.test.cpp | jupiro/library | f3e0a2f35aefab49ff8960c17a264118e97b3378 | [
"Unlicense"
] | null | null | null | test/verify/aoj-0275.test.cpp | jupiro/library | f3e0a2f35aefab49ff8960c17a264118e97b3378 | [
"Unlicense"
] | null | null | null | test/verify/aoj-0275.test.cpp | jupiro/library | f3e0a2f35aefab49ff8960c17a264118e97b3378 | [
"Unlicense"
] | null | null | null | #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0275"
#include "../../template/template.cpp"
#include "../../graph/shortest-path/dijkstra.hpp"
#include "../../graph/others/topological-sort.hpp"
#include "../../graph/others/offline-dag-reachability.hpp"
int main() {
int S, R, A, B, Q;
cin >> S >> R;
Graph< int > g(S);
vector< int > U(R), V(R), C(R);
for(int i = 0; i < R; i++) {
cin >> U[i] >> V[i] >> C[i];
--U[i], --V[i];
g.add_edge(U[i], V[i], C[i]);
}
cin >> A >> B >> Q;
--A, --B;
auto pre = dijkstra(g, A).dist;
auto suf = dijkstra(g, B).dist;
Graph< int > dag(S);
for(int i = 0; i < R; i++) {
if(pre[U[i]] + C[i] + suf[V[i]] == pre[B]) dag.add_directed_edge(U[i], V[i]);
if(pre[V[i]] + C[i] + suf[U[i]] == pre[B]) dag.add_directed_edge(V[i], U[i]);
}
vector< pair< int, int > > qs(Q);
for(auto &p : qs) {
cin >> p.first >> p.second;
--p.first, --p.second;
}
auto ans = offline_dag_reachability(dag, qs);
for(auto &p : ans) cout << (p ? "Yes\n" : "No\n");
}
| 29.388889 | 81 | 0.529301 | jupiro |
0f80e25f175fd2b8630264be60481c4c4b2ff7ff | 1,031 | cpp | C++ | code/985.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 23 | 2020-03-30T05:44:56.000Z | 2021-09-04T16:00:57.000Z | code/985.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 1 | 2020-05-10T15:04:05.000Z | 2020-06-14T01:21:44.000Z | code/985.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;
}
class Solution {
public:
vector<int> sumEvenAfterQueries(vector<int>& A, vector<vector<int>>& queries) {
vector<int> ans;
int cur = 0, n = queries.size();
for (int i: A)
if(!(i & 1)) cur += i;
for (int i = 0; i < n; ++i){
int id = queries[i][1], v = queries[i][0];
if(A[id] & 1){
if(v & 1) cur += A[id] + v;
A[id] += v;
}else{
if(v & 1) cur -= A[id];
else cur += v;
A[id] += v;
}
ans.push_back(cur);
}
return ans;
}
};
Solution sol;
void init(){
}
void solve(){
// sol.convert();
}
int main(){
init();
solve();
return 0;
}
| 22.413043 | 83 | 0.42774 | Nightwish-cn |
0f82335da3f3edac0c35a3ee4244178c6e777529 | 8,696 | cpp | C++ | mcrouter/test/cpp_unit_tests/mcrouter_cpp_tests.cpp | wicky-info/mcrouter | bc8bbbcc3e9a6ef79146d4096f3e39af942ada09 | [
"BSD-3-Clause"
] | 1 | 2015-11-08T10:09:45.000Z | 2015-11-08T10:09:45.000Z | mcrouter/test/cpp_unit_tests/mcrouter_cpp_tests.cpp | wicky-info/mcrouter | bc8bbbcc3e9a6ef79146d4096f3e39af942ada09 | [
"BSD-3-Clause"
] | null | null | null | mcrouter/test/cpp_unit_tests/mcrouter_cpp_tests.cpp | wicky-info/mcrouter | bc8bbbcc3e9a6ef79146d4096f3e39af942ada09 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <semaphore.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <algorithm>
#include <string>
#include <vector>
#include <boost/filesystem.hpp>
#include <gtest/gtest.h>
#include <folly/experimental/TestUtil.h>
#include <folly/FileUtil.h>
#include <folly/io/async/EventBase.h>
#include "mcrouter/config.h"
#include "mcrouter/options.h"
#include "mcrouter/router.h"
using namespace boost::filesystem;
using namespace facebook::memcache::mcrouter;
using namespace std;
using facebook::memcache::createMcMsgRef;
using facebook::memcache::McMsgRef;
using facebook::memcache::McReply;
using facebook::memcache::McrouterOptions;
const std::string kAlreadyRepliedConfig =
"mcrouter/test/cpp_unit_tests/files/already_replied.json";
#define MEMCACHE_CONFIG "mcrouter/test/test_ascii.json"
#define MEMCACHE_ROUTE "/././"
McMsgRef new_get_req(const char *key) {
auto msg = createMcMsgRef(key);
msg->op = mc_op_get;
return std::move(msg);
}
McMsgRef new_del_req(const char *key) {
auto msg = createMcMsgRef(key);
msg->op = mc_op_delete;
return std::move(msg);
}
void on_reply(mcrouter_client_t *client,
mcrouter_msg_t *router_req,
void* context) {
mcrouter_msg_t *r_msg = static_cast<mcrouter_msg_t*>(router_req->context);
r_msg->reply = std::move(router_req->reply);
}
void mcrouter_send_helper(mcrouter_client_t *client,
const vector<McMsgRef>& reqs,
vector<McReply> &replies) {
vector<mc_msg_t*> ret;
int n = reqs.size();
replies.clear();
mcrouter_msg_t *r_msgs = new mcrouter_msg_t[n];
for (int i = 0; i < n; i++) {
r_msgs[i].req = const_cast<mc_msg_t*>(reqs[i].get());
r_msgs[i].reply = McReply(mc_res_unknown);
r_msgs[i].context = &r_msgs[i];
}
mcrouter_send(client, r_msgs, n);
int i = 0;
folly::EventBase* eventBase = mcrouter_client_get_base(client);
while (i < n) {
mcrouterLoopOnce(eventBase);
while (i < n) {
if (r_msgs[i].reply.result() != mc_res_unknown) {
replies.push_back(std::move(r_msgs[i].reply));
i++;
} else break;
}
}
delete [] r_msgs;
}
TEST(mcrouter, start_and_stop) {
for (int i = 0; i < 2; i++) {
auto opts = defaultTestOptions();
opts.config_file = MEMCACHE_CONFIG;
opts.default_route = MEMCACHE_ROUTE;
mcrouter_t *router = mcrouter_new(opts);
EXPECT_FALSE(router == nullptr);
folly::EventBase eventBase;
mcrouter_client_t *client = mcrouter_client_new(
router,
&eventBase,
(mcrouter_client_callbacks_t){nullptr, nullptr},
nullptr,
0, false);
EXPECT_FALSE(client == nullptr);
mcrouter_client_disconnect(client);
mcrouter_free(router);
}
}
void on_disconnect(void* context) {
sem_post((sem_t*)context);
}
void test_disconnect_callback(bool thread_safe_callbacks) {
sem_t sem_disconnect;
sem_init(&sem_disconnect, 0, 0);
auto opts = defaultTestOptions();
opts.config_file = MEMCACHE_CONFIG;
opts.default_route = MEMCACHE_ROUTE;
mcrouter_t *router = mcrouter_new(opts);
EXPECT_FALSE(router == nullptr);
folly::EventBase eventBase;
mcrouter_client_t *client = mcrouter_client_new(
router,
thread_safe_callbacks ? nullptr : &eventBase,
(mcrouter_client_callbacks_t){nullptr, on_disconnect},
&sem_disconnect,
0, false);
EXPECT_FALSE(client == nullptr);
const char test_key[] = "test_key_disconnect";
vector<mcrouter_msg_t> reqs(1);
auto msg = new_get_req(test_key);
reqs.back().req = const_cast<mc_msg_t*>(msg.get());
reqs.back().reply = McReply(mc_res_unknown);
mcrouter_send(client, reqs.data(), reqs.size());
EXPECT_NE(0, sem_trywait(&sem_disconnect));
mcrouter_client_disconnect(client);
EXPECT_EQ(0, sem_wait(&sem_disconnect));
mcrouter_free(router);
}
TEST(mcrouter, test_zeroreqs_mcroutersend) {
sem_t sem_disconnect;
sem_init(&sem_disconnect, 0, 0);
auto opts = defaultTestOptions();
opts.config_file = MEMCACHE_CONFIG;
opts.default_route = MEMCACHE_ROUTE;
mcrouter_t *router = mcrouter_new(opts);
mcrouter_client_t *client = mcrouter_client_new(
router,
nullptr,
(mcrouter_client_callbacks_t){nullptr, on_disconnect},
&sem_disconnect,
0, false);
vector<mcrouter_msg_t> reqs(0);
mcrouter_send(client, reqs.data(), reqs.size());
mcrouter_send(client, nullptr, 0);
mcrouter_client_disconnect(client);
mcrouter_free(router);
}
TEST(mcrouter, disconnect_callback) {
test_disconnect_callback(false);
}
TEST(mcrouter, disconnect_callback_ts_callbacks) {
test_disconnect_callback(true);
}
TEST(mcrouter, fork) {
const char persistence_id[] = "fork";
auto opts = defaultTestOptions();
opts.config_file = MEMCACHE_CONFIG;
opts.default_route = MEMCACHE_ROUTE;
mcrouter_t *router = mcrouter_init(persistence_id, opts);
EXPECT_NE(static_cast<mcrouter_t*>(nullptr), router);
auto eventBase = std::make_shared<folly::EventBase>();
mcrouter_client_t *client = mcrouter_client_new(
router,
eventBase.get(),
(mcrouter_client_callbacks_t){on_reply, nullptr},
nullptr,
0, false);
EXPECT_NE(static_cast<mcrouter_client_t*>(nullptr), client);
const char parent_key[] = "libmcrouter_test:fork:parent";
const char child_key[] = "libmcrouter_test:fork:child";
vector<McMsgRef> preqs;
vector<McReply> preplies;
preqs.push_back(new_get_req(parent_key));
mcrouter_send_helper(client, preqs, preplies);
mcrouter_client_disconnect(client);
free_all_libmcrouters();
int fds[2];
pipe(fds);
pid_t pid = fork();
router = mcrouter_init(persistence_id, opts);
EXPECT_NE(static_cast<mcrouter_t*>(nullptr), router);
eventBase = std::make_shared<folly::EventBase>();
client = mcrouter_client_new(
router,
eventBase.get(),
(mcrouter_client_callbacks_t){on_reply, nullptr},
nullptr,
0, false);
EXPECT_NE(static_cast<mcrouter_client_t*>(nullptr), client);
vector<McMsgRef> reqs;
vector<McReply> replies;
if (pid) { // parent
close(fds[1]);
reqs.push_back(new_get_req(parent_key));
mcrouter_send_helper(client, reqs, replies);
} else {
router = mcrouter_get(persistence_id);
reqs.push_back(new_get_req(child_key));
mcrouter_send_helper(client, reqs, replies);
}
mcrouter_client_disconnect(client);
mcrouter_free(router);
if (pid) { // parent
char buf[100];
read(fds[0], buf, sizeof(buf));
close(fds[0]);
waitpid(pid, nullptr, 0);
} else {
write(fds[1], "done", 4);
close(fds[1]);
exit(0);
}
}
TEST(mcrouter, already_replied_failed_delete) {
folly::test::TemporaryDirectory tmpdir("already_replied_failed_delete");
mcrouter_client_callbacks_t cb = {
.on_reply = &on_reply,
.on_disconnect = nullptr
};
auto opts = defaultTestOptions();
std::string configStr;
EXPECT_TRUE(folly::readFile(kAlreadyRepliedConfig.data(), configStr));
opts.config_str = configStr;
opts.async_spool = tmpdir.path().string();
mcrouter_t *router = mcrouter_new(opts);
EXPECT_TRUE(router != nullptr);
folly::EventBase eventBase;
mcrouter_client_t *client = mcrouter_client_new(router, &eventBase, cb,
nullptr, 0, false);
EXPECT_TRUE(client != nullptr);
vector<McMsgRef> reqs;
vector<McReply> replies;
reqs.push_back(new_del_req("abc"));
mcrouter_send_helper(client, reqs, replies);
// Give mcrouter a chance to write the log -- we don't really know when
// the write completes because we receive the response right away.
sleep(1);
mcrouter_client_disconnect(client);
mcrouter_free(router);
// Verify the existance and contents of the file.
vector<string> files;
string contents;
string prefix(R"!(["AS1.0",)!");
string suffix(R"!(,"C",["127.0.0.1",4242,"delete abc\r\n"]])!" "\n");
for (recursive_directory_iterator it(tmpdir.path());
it != recursive_directory_iterator();
++it) {
if (!is_directory(it->symlink_status())) {
files.push_back(it->path().string());
}
}
EXPECT_EQ(files.size(), 1);
folly::readFile(files[0].data(), contents);
EXPECT_GT(contents.size(), prefix.size());
EXPECT_GT(contents.size(), suffix.size());
auto p = mismatch(prefix.begin(), prefix.end(), contents.begin());
EXPECT_TRUE(p.first == prefix.end());
auto s = mismatch(suffix.rbegin(), suffix.rend(), contents.rbegin());
EXPECT_TRUE(s.first == suffix.rend());
}
| 27.961415 | 79 | 0.701472 | wicky-info |
0f82b4e511ccf0386914803cb9bc9594387be4bb | 1,339 | cpp | C++ | labs/lab02/test-stack.cpp | josdyr/set10108 | fea3ef54745b40fe8da018563e107623d619713a | [
"MIT"
] | null | null | null | labs/lab02/test-stack.cpp | josdyr/set10108 | fea3ef54745b40fe8da018563e107623d619713a | [
"MIT"
] | null | null | null | labs/lab02/test-stack.cpp | josdyr/set10108 | fea3ef54745b40fe8da018563e107623d619713a | [
"MIT"
] | null | null | null | #include <iostream>
#include <memory>
#include <thread>
#include "threadsafe_stack.h"
using namespace std;
void pusher(shared_ptr<threadsafe_stack<unsigned int>> stack)
{
// Pusher will push 1 million values onto the stack
for (unsigned int i = 0; i < 100000; ++i)
{
stack->push(i);
// Make the pusher yield. Will give priority to another thread
this_thread::yield();
}
}
void popper(shared_ptr<threadsafe_stack<unsigned int>> stack)
{
// Popper will pop 1 million values from the stack.
// We do this using a counter and a while loop
unsigned int count = 0;
while (count < 100000)
{
// Try and pop a value
try
{
auto val = stack->pop();
// Item popped. Increment count
++count;
}
catch (exception e)
{
// Item not popped. Display message
// cout << e.what() << endl;
}
}
}
int main(int argc, char **argv)
{
// Create a threadsafe_stack
auto stack = make_shared<threadsafe_stack<unsigned int>>();
// Create two threads
thread t1(popper, stack);
thread t2(pusher, stack);
// Join two threads
t1.join();
t2.join();
// Check if stack is empty
cout << "Stack empty = " << stack->empty() << endl;
return 0;
}
| 22.694915 | 71 | 0.578043 | josdyr |
abf373a2383872ee47c042dbc21e1c84a184d854 | 467 | cpp | C++ | Stats/RunningMean.cpp | 3nprob/clboss | 0435b6c074347ce82e490a5988534054e9d7348d | [
"MIT"
] | 108 | 2020-10-01T17:12:40.000Z | 2022-03-30T09:18:03.000Z | Stats/RunningMean.cpp | 3nprob/clboss | 0435b6c074347ce82e490a5988534054e9d7348d | [
"MIT"
] | 94 | 2020-10-03T13:40:30.000Z | 2022-03-30T09:18:00.000Z | Stats/RunningMean.cpp | 3nprob/clboss | 0435b6c074347ce82e490a5988534054e9d7348d | [
"MIT"
] | 17 | 2020-10-29T13:27:59.000Z | 2022-03-18T13:05:03.000Z | #include"Stats/RunningMean.hpp"
#include"Util/Str.hpp"
#include<cstdlib>
namespace {
union UD {
std::uint64_t u;
double d;
};
}
namespace Stats {
std::ostream& operator<<(std::ostream& os, RunningMean& m) {
union UD dat;
dat.d = m.mean;
os << std::hex << dat.u << " " << m.samples << " ";
return os;
}
std::istream& operator>>(std::istream& is, RunningMean& m) {
union UD dat;
is >> std::hex >> dat.u >> m.samples;
m.mean = dat.d;
return is;
}
}
| 13.342857 | 60 | 0.608137 | 3nprob |
abf3dae1543514dff36e509af6cc8a749b0e8cbe | 7,778 | cc | C++ | modules/planning/scenarios/side_pass/stage_approach_obstacle.cc | aurora12344/project | f904643843c7c41d422b92fb53279475b4b0b1bd | [
"Apache-2.0"
] | 2 | 2019-01-15T08:34:59.000Z | 2019-01-15T08:35:00.000Z | modules/planning/scenarios/side_pass/stage_approach_obstacle.cc | aurora12344/project | f904643843c7c41d422b92fb53279475b4b0b1bd | [
"Apache-2.0"
] | null | null | null | modules/planning/scenarios/side_pass/stage_approach_obstacle.cc | aurora12344/project | f904643843c7c41d422b92fb53279475b4b0b1bd | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright 2018 The Apollo Authors. 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.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/scenarios/side_pass/stage_approach_obstacle.h"
#include <algorithm>
#include <string>
#include <vector>
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/obstacle_blocking_analyzer.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/speed_profile_generator.h"
namespace apollo {
namespace planning {
namespace scenario {
namespace side_pass {
using apollo::common::TrajectoryPoint;
using apollo::common::VehicleConfigHelper;
/*
* @brief: STAGE ApproachObstacle in side_pass scenario
*/
Stage::StageStatus StageApproachObstacle::Process(
const TrajectoryPoint& planning_start_point, Frame* frame) {
ADEBUG << "SIDEPASS: Approaching obstacle.";
std::string blocking_obstacle_id = GetContext()->front_blocking_obstacle_id_;
const SLBoundary& adc_sl_boundary =
frame->reference_line_info().front().AdcSlBoundary();
const PathDecision& path_decision =
frame->reference_line_info().front().path_decision();
double obstacle_start_s = -1.0;
for (const auto* obstacle : path_decision.obstacles().Items()) {
if (obstacle->Id() == blocking_obstacle_id) {
obstacle_start_s = obstacle->PerceptionSLBoundary().start_s();
break;
}
}
if (obstacle_start_s < 0.0) {
AWARN << "front blocking obstacle: " << blocking_obstacle_id
<< " is not found";
next_stage_ = ScenarioConfig::NO_STAGE;
return Stage::FINISHED;
}
if ((obstacle_start_s - adc_sl_boundary.end_s()) <
GetContext()->scenario_config_.min_front_obstacle_distance()) {
next_stage_ = ScenarioConfig::NO_STAGE;
return Stage::FINISHED;
}
double kBlockingObstacleDistance = 5.0;
double stop_fence_s = obstacle_start_s - kBlockingObstacleDistance;
stop_fence_s = std::max(stop_fence_s, adc_sl_boundary.end_s() + 0.2);
std::string virtual_obstacle_id = blocking_obstacle_id + "_virtual_stop";
for (auto& reference_line_info : *frame->mutable_reference_line_info()) {
auto* obstacle = frame->CreateStopObstacle(
&reference_line_info, virtual_obstacle_id, stop_fence_s);
if (!obstacle) {
AERROR << "Failed to create virtual stop obstacle["
<< blocking_obstacle_id << "]";
next_stage_ = ScenarioConfig::NO_STAGE;
return Stage::FINISHED;
}
Obstacle* stop_wall = reference_line_info.AddObstacle(obstacle);
if (!stop_wall) {
AERROR << "Failed to create stop obstacle for: " << blocking_obstacle_id;
next_stage_ = ScenarioConfig::NO_STAGE;
return Stage::FINISHED;
}
const double stop_distance = 0.2;
const double stop_s = stop_fence_s - stop_distance;
const auto& reference_line = reference_line_info.reference_line();
auto stop_point = reference_line.GetReferencePoint(stop_s);
double stop_heading = reference_line.GetReferencePoint(stop_s).heading();
ObjectDecisionType stop;
auto stop_decision = stop.mutable_stop();
stop_decision->set_reason_code(StopReasonCode::STOP_REASON_OBSTACLE);
stop_decision->set_distance_s(-stop_distance);
stop_decision->set_stop_heading(stop_heading);
stop_decision->mutable_stop_point()->set_x(stop_point.x());
stop_decision->mutable_stop_point()->set_y(stop_point.y());
stop_decision->mutable_stop_point()->set_z(0.0);
auto* path_decision = reference_line_info.path_decision();
path_decision->AddLongitudinalDecision("SidePass", stop_wall->Id(), stop);
break;
}
// check the status of side pass scenario
bool has_blocking_obstacle = false;
for (const auto* obstacle : path_decision.obstacles().Items()) {
if (obstacle->IsVirtual() || !obstacle->IsStatic()) {
continue;
}
CHECK(obstacle->IsStatic());
if (obstacle->speed() >
GetContext()->scenario_config_.block_obstacle_min_speed()) {
continue;
}
if (obstacle->PerceptionSLBoundary().start_s() <=
adc_sl_boundary.end_s()) { // such vehicles are behind the ego car.
continue;
}
if (obstacle->PerceptionSLBoundary().start_s() >
adc_sl_boundary.end_s() +
GetContext()->scenario_config_.max_front_obstacle_distance()) {
// vehicles are far away
continue;
}
// check driving_width
const auto& reference_line =
frame->reference_line_info().front().reference_line();
const double driving_width =
reference_line.GetDrivingWidth(obstacle->PerceptionSLBoundary());
const double adc_width =
VehicleConfigHelper::GetConfig().vehicle_param().width();
if (driving_width - adc_width - FLAGS_static_decision_nudge_l_buffer >
GetContext()->scenario_config_.min_l_nudge_buffer()) {
continue;
}
has_blocking_obstacle = true;
break;
}
if (!has_blocking_obstacle) {
next_stage_ = ScenarioConfig::NO_STAGE;
ADEBUG << "There is no blocking obstacle.";
return Stage::FINISHED;
}
// do path planning
bool plan_ok = ExecuteTaskOnReferenceLine(planning_start_point, frame);
if (!plan_ok) {
AERROR << "Stage " << Name() << " error: "
<< "planning on reference line failed.";
return Stage::ERROR;
}
const ReferenceLineInfo& reference_line_info =
frame->reference_line_info().front();
double adc_velocity = frame->vehicle_state().linear_velocity();
double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();
double front_obstacle_distance = 1000;
for (const auto* obstacle : path_decision.obstacles().Items()) {
if (obstacle->IsVirtual()) {
continue;
}
bool is_on_road = reference_line_info.reference_line().HasOverlap(
obstacle->PerceptionBoundingBox());
if (!is_on_road) {
continue;
}
const auto& obstacle_sl = obstacle->PerceptionSLBoundary();
if (obstacle_sl.end_s() <= reference_line_info.AdcSlBoundary().start_s()) {
continue;
}
double distance = obstacle_sl.start_s() - adc_front_edge_s;
if (distance < front_obstacle_distance) {
front_obstacle_distance = distance;
}
}
if ((front_obstacle_distance) < 0) {
AERROR << "Stage " << Name() << " error: "
<< "front obstacle has wrong position.";
return Stage::ERROR;
}
double max_stop_velocity =
GetContext()->scenario_config_.approach_obstacle_max_stop_speed();
double min_stop_obstacle_distance =
GetContext()->scenario_config_.approach_obstacle_min_stop_distance();
ADEBUG << "front_obstacle_distance = " << front_obstacle_distance;
ADEBUG << "adc_velocity = " << adc_velocity;
if (adc_velocity < max_stop_velocity &&
front_obstacle_distance > min_stop_obstacle_distance) {
next_stage_ = ScenarioConfig::SIDE_PASS_GENERATE_PATH;
return Stage::FINISHED;
}
return Stage::RUNNING;
}
} // namespace side_pass
} // namespace scenario
} // namespace planning
} // namespace apollo
| 35.354545 | 79 | 0.696194 | aurora12344 |
abf58024ccaa48643c7b50910dd9f429f65d70b8 | 38,933 | cpp | C++ | source/parser/parser.cpp | ThatGuyMike7/masonc | 43a3a69cd64f52fda8a629360c52a222549d6368 | [
"BSL-1.0"
] | 3 | 2020-08-10T13:37:48.000Z | 2021-07-06T10:14:39.000Z | source/parser/parser.cpp | ThatGuyMike7/masonc | 43a3a69cd64f52fda8a629360c52a222549d6368 | [
"BSL-1.0"
] | null | null | null | source/parser/parser.cpp | ThatGuyMike7/masonc | 43a3a69cd64f52fda8a629360c52a222549d6368 | [
"BSL-1.0"
] | null | null | null | #include <parser.hpp>
#include <common.hpp>
#include <mod.hpp>
#include <mod_handle.hpp>
#include <type.hpp>
#include <logger.hpp>
#include <timer.hpp>
#include <lexer.hpp>
#include <build_stage.hpp>
#include <iostream>
#include <optional>
#include <limits>
#include <cstring>
namespace masonc::parser
{
void parser_instance_output::free()
{
for (u64 i = 0; i < delete_list_expressions.size(); i += 1) {
delete delete_list_expressions[i];
}
}
void parser_instance_output::print_expressions()
{
for (u64 i = 0; i < AST.size(); i += 1) {
std::cout << format_expression(AST[i]) << std::endl;
}
}
std::string parser_instance_output::format_expression(const expression& expr, u64 level)
{
std::string message;
for (u64 i = 0; i < level; i += 1) {
message += " ";
}
// This is safe because no matter the current variant,
// it is guaranteed to be at the same address
// (and type is the first member in tagged expression struct).
switch (expr.value.empty.type) {
default:
message += "Unknown Expression";
break;
case EXPR_EMPTY:
message += "Empty Expression";
break;
case EXPR_UNARY:
message += "Unary Expression: Op_Code='"
+ std::to_string(expr.value.unary.value.op_code) + "'"
+ "\n" + format_expression(*expr.value.unary.value.expr, level + 1);
break;
case EXPR_BINARY:
message += "Binary Expression: Op_Code='"
+ std::to_string(expr.value.binary.value.op->op_code) + "'"
+ "\n" + format_expression(*expr.value.binary.value.left, level + 1)
+ "\n" + format_expression(*expr.value.binary.value.right, level + 1);
break;
case EXPR_PARENTHESES:
message += "Parentheses Expression: Op_Code='"
+ std::to_string(expr.value.parentheses.value.expr.op->op_code) + "'"
+ "\n" + format_expression(*expr.value.parentheses.value.expr.left, level + 1)
+ "\n" + format_expression(*expr.value.parentheses.value.expr.right, level + 1);
break;
case EXPR_NUMBER_LITERAL:
message += "Number Literal: Value='";
message += expr.value.number.value.value;
message += "'";
break;
case EXPR_STRING_LITERAL:
message += "String Literal: Value='";
message += expr.value.str.value.value;
message += "'";
break;
case EXPR_REFERENCE:
message += "Reference: Name='";
//message += expr.value.reference.value.name;
message += "'";
break;
case EXPR_VAR_DECLARATION:
message += "Variable Declaration: Name='";
//message += expr.value.variable_declaration.value.name;
message += "' Type='";
if(expr.value.variable_declaration.value.is_pointer)
message += "^";
//message += expr.value.variable_declaration.value.type_name;
message += "'";
if(expr.value.variable_declaration.value.specifiers != SPECIFIER_NONE) {
message += " Specifiers='";
if(expr.value.variable_declaration.value.specifiers & SPECIFIER_CONST)
message += "const ";
if(expr.value.variable_declaration.value.specifiers & SPECIFIER_MUT)
message += "mut ";
message += "'";
}
break;
case EXPR_PROC_PROTOTYPE:
message += "Procedure Prototype Expression: Name='";
//message += expr.value.procedure_prototype.value.name;
message += "' Return Type='";
//message += expr.value.procedure_prototype.value.return_type_name;
message += "'";
if (expr.value.procedure_prototype.value.argument_list.size() > 0)
message += "\nArgument List: ";
for (u64 i = 0; i < expr.value.procedure_prototype.value.argument_list.size(); i += 1) {
message += "\n" + format_expression(
expr.value.procedure_prototype.value.argument_list[i], level + 1
);
}
break;
case EXPR_PROC_DEFINITION:
message += format_expression(
expression{ expr.value.procedure_definition.value.prototype }, level
);
if (expr.value.procedure_definition.value.body.size() > 0)
message += "\nBody: ";
for (u64 i = 0; i < expr.value.procedure_definition.value.body.size(); i += 1) {
message += "\n" + format_expression(
expr.value.procedure_definition.value.body[i], level + 1);
}
break;
case EXPR_PROC_CALL:
message += "Procedure Call Expression: Name='";
//message += expr.value.procedure_call.value.name;
message += "'";
for (u64 i = 0; i < expr.value.procedure_call.value.argument_list.size(); i += 1) {
message += "\n" + format_expression(
expr.value.procedure_call.value.argument_list[i], level + 1
);
}
break;
case EXPR_MODULE_DECLARATION:
message += "Module Declaration: Name='";
message += expr.value.module_declaration.value.name;
message += "'";
break;
case EXPR_MODULE_IMPORT:
message += "Module Import: Name='";
message += file_module.module_import_names.at(
expr.value.module_import.value.import_index);
message += "'";
break;
}
return message;
}
parser_instance::parser_instance(masonc::parser::parser_instance_output* parser_output)
{
this->parser_output = parser_output;
//this->token_index = 0;
//this->done = false;
// The first statement must be a module declaration.
auto module_identifier_result = expect("module");
if (!module_identifier_result) {
return;
}
auto module_declaration_result = parse_module_declaration();
if (!module_declaration_result) {
report_parse_error("Missing module declaration.");
return;
}
parser_output->AST.push_back(module_declaration_result.value());
// Drive the parser.
drive();
}
void parser_instance::drive()
{
while(true) {
auto top_level_expression = parse_top_level();
if (top_level_expression)
parser_output->AST.push_back(top_level_expression.value());
// Reached the end of the token stream.
if (done)
break;
}
}
masonc::lexer::lexer_instance_output* parser_instance::lexer_output()
{
return &parser_output->lexer_output;
}
scope* parser_instance::current_scope()
{
return parser_output->file_module.module_scope.get_child(current_scope_index);
}
bool parser_instance::module_declaration_exists()
{
return !parser_output->module_name.empty();
}
void parser_instance::set_module(const char* module_name, u16 module_name_length)
{
parser_output->module_name = std::string{ module_name };
// Tell the module scope of the module.
parser_output->file_module.module_scope.m_module = &parser_output->file_module;
//u16 module_name_length = parser_output->module_names.length_at(current_handle);
//const char* module_name = parser_output->module_names.at(current_handle);
// Give the module scope the module name.
parser_output->file_module.module_scope.set_name(module_name, module_name_length);
try {
// Guess how many tokens will end up being 1 expression on average to
// avoid reallocations.
parser_output->AST.reserve(lexer_output()->tokens.size() / 10 + 32);
}
catch (...) {
global_logger.log_error("Could not reserve space for AST container.");
}
current_scope_index = parser_output->file_module.module_scope.index();
}
void parser_instance::set_module(const std::string& module_name)
{
assume(module_name.length() <= std::numeric_limits<u16>::max(),
"\"module_name\" length exceeds size of \"u16\"");
set_module(module_name.c_str(), static_cast<u16>(module_name.length()));
}
void parser_instance::eat(u64 count)
{
token_index += count;
}
std::optional<masonc::lexer::token*> parser_instance::peek_token()
{
if(token_index < lexer_output()->tokens.size()) {
std::optional<masonc::lexer::token*> result{ &lexer_output()->tokens[token_index] };
return result;
}
return std::nullopt;
}
std::optional<masonc::lexer::token*> parser_instance::expect_any()
{
auto token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::nullopt;
}
eat();
return token_result.value();
}
std::optional<masonc::lexer::token*> parser_instance::expect_identifier()
{
auto token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::nullopt;
}
if (token_result.value()->type != masonc::lexer::TOKEN_IDENTIFIER) {
report_parse_error("Expected an identifier.");
return std::nullopt;
}
eat();
return token_result.value();
}
std::optional<masonc::lexer::token*> parser_instance::expect(char c)
{
auto token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::nullopt;
}
// Assumes that type "char" is signed
if (token_result.value()->type != c) {
report_parse_error("Expected \"" + std::string{ c } + "\".");
return std::nullopt;
}
eat();
return token_result.value();
}
std::optional<masonc::lexer::token*> parser_instance::expect(const std::string& identifier)
{
auto token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::nullopt;
}
if (token_result.value()->type != masonc::lexer::TOKEN_IDENTIFIER ||
identifier_at(*token_result.value()) != identifier)
{
report_parse_error("Expected \"" + identifier + "\".");
return std::nullopt;
}
eat();
return token_result.value();
}
const char* parser_instance::identifier_at(const masonc::lexer::token& identifier_token)
{
assume(lexer_output()->identifiers.size() > identifier_token.value_index, "value_index is out of range");
return lexer_output()->identifiers.at(identifier_token.value_index);
}
const char* parser_instance::integer_at(const masonc::lexer::token& integer_token)
{
assume(lexer_output()->integers.size() > integer_token.value_index, "value_index is out of range");
return lexer_output()->integers.at(integer_token.value_index);
}
const char* parser_instance::decimal_at(const masonc::lexer::token& decimal_token)
{
assume(lexer_output()->decimals.size() > decimal_token.value_index, "value_index is out of range");
return lexer_output()->decimals.at(decimal_token.value_index);
}
const char* parser_instance::string_at(const masonc::lexer::token& string_token)
{
assume(lexer_output()->strings.size() > string_token.value_index, "value_index is out of range");
return lexer_output()->strings.at(string_token.value_index);
}
masonc::lexer::token_location* parser_instance::get_token_location(u64 token_index)
{
return &lexer_output()->locations[token_index];
}
void parser_instance::report_parse_error(const std::string& msg)
{
// TODO: Mark as unlikely.
if (this->token_index == 0)
report_parse_error_at(msg, this->token_index);
else
report_parse_error_at(msg, this->token_index - 1);
}
void parser_instance::report_parse_error_at(const std::string& msg, u64 token_index)
{
masonc::lexer::token_location* location = get_token_location(token_index);
parser_output->messages.report_error(msg, build_stage::PARSER, *location);
}
void parser_instance::recover()
{
while (true) {
std::optional<masonc::lexer::token*> token_result = peek_token();
if (!token_result)
return;
eat();
if (token_result.value()->type == ';' ||
token_result.value()->type == '}')
{
return;
}
}
}
std::optional<u8> parser_instance::parse_specifiers()
{
u8 specifiers = SPECIFIER_NONE;
while (true) {
auto token_result = peek_token();
if (!token_result) {
done = true;
return std::nullopt;
}
if (token_result.value()->type != masonc::lexer::TOKEN_IDENTIFIER) {
report_parse_error("Expected an identifier.");
recover();
return std::nullopt;
}
const char* identifier = identifier_at(*token_result.value());
if (std::strcmp(identifier, "mut") == 0) {
eat();
if (specifiers & SPECIFIER_MUT) {
report_parse_error("Specifier is already defined.");
continue;
}
specifiers |= SPECIFIER_MUT;
}
else if (std::strcmp(identifier, "const") == 0) {
eat();
if (specifiers & SPECIFIER_CONST) {
report_parse_error("Specifier is already defined.");
continue;
}
specifiers |= SPECIFIER_CONST;
}
else {
return specifiers;
}
}
}
std::optional<expression> parser_instance::parse_top_level()
{
std::optional<u8> specifiers_result = parse_specifiers();
if (!specifiers_result)
return std::nullopt;
// Next token is guaranteed to exist and be an identifier.
auto token_result = peek_token();
const char* identifier = identifier_at(*token_result.value());
symbol_handle identifier_handle = token_result.value()->value_index;
eat();
if (specifiers_result.value() == SPECIFIER_NONE) {
if (std::strcmp(identifier, "proc") == 0)
return parse_procedure();
if (std::strcmp(identifier, "module") == 0)
report_parse_error("Module declaration must be the first statement in the source file, and there must only be one module declaration.");
// return parse_module_declaration();
if (std::strcmp(identifier, "import") == 0)
return parse_module_import();
}
// Specifiers are declared and parsed.
token_result = expect(':');
if (!token_result) {
recover();
return std::nullopt;
}
return parse_variable_declaration(CONTEXT_STATEMENT,
identifier_handle, specifiers_result.value());
}
std::optional<expression> parser_instance::parse_statement()
{
std::optional<u8> specifiers_result = parse_specifiers();
if(!specifiers_result)
return std::nullopt;
// Next token is guaranteed to exist and be an identifier.
auto token_result = peek_token();
const char* identifier = identifier_at(*token_result.value());
symbol_handle identifier_handle = token_result.value()->value_index;
eat();
if (std::strcmp(identifier, "return") == 0) {
// Parse return statement.
return parse_expression(CONTEXT_STATEMENT);
}
token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::nullopt;
}
if (specifiers_result.value() == SPECIFIER_NONE &&
token_result.value()->type == '(')
{
eat();
return parse_call(CONTEXT_STATEMENT, identifier_handle);
}
// Specifiers are declared or next token is not "(".
if (token_result.value()->type == ':') {
eat();
return parse_variable_declaration(CONTEXT_STATEMENT,
identifier_handle, specifiers_result.value());
}
report_parse_error("Unexpected token.");
recover();
return std::nullopt;
}
std::optional<expression> parser_instance::parse_expression(parse_context context)
{
auto primary_result = parse_primary(CONTEXT_NONE);
if (!primary_result)
return std::nullopt;
auto token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::nullopt;
}
auto op_result = get_op(token_result.value()->type);
if (op_result) {
// Eat the binary operator.
eat();
}
else {
// Next token is not a binary operator.
if (context == CONTEXT_STATEMENT) {
if (token_result.value()->type == ';') {
// Eat the ";".
eat();
}
else {
recover();
return std::nullopt;
}
}
return primary_result;
}
// Parse right-hand side of binary expression.
return parse_binary(context, primary_result.value(), op_result.value());
}
std::optional<expression> parser_instance::parse_primary(parse_context context)
{
auto token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::nullopt;
}
switch (token_result.value()->type) {
default: {
report_parse_error("Unexpected token.");
recover();
return std::nullopt;
}
case '^':
case '&': {
eat();
auto primary_result = parse_primary(context);
if (!primary_result)
return std::nullopt;
expression* expr = new expression{ primary_result.value() };
parser_output->delete_list_expressions.push_back(expr);
return expression{ expression_unary{ expr, token_result.value()->type } };
}
case masonc::lexer::TOKEN_IDENTIFIER: {
eat();
const char* identifier = identifier_at(*token_result.value());
symbol_handle identifier_handle = token_result.value()->value_index;
if (std::strcmp(identifier, "proc") == 0) {
report_parse_error("Procedure must be top-level expression.");
// TODO: Jump to end of procedure and not next ";" or "}".
recover();
return std::nullopt;
}
// Look ahead after the identifier.
token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::nullopt;
}
switch (token_result.value()->type) {
default:
return parse_reference(context, identifier_handle);
case '(':
eat();
return parse_call(context, identifier_handle);
}
}
case masonc::lexer::TOKEN_INTEGER: {
eat();
return parse_number_literal(context, integer_at(*token_result.value()), NUMBER_INTEGER);
}
case masonc::lexer::TOKEN_DECIMAL: {
eat();
return parse_number_literal(context, decimal_at(*token_result.value()), NUMBER_DECIMAL);
}
case masonc::lexer::TOKEN_STRING: {
eat();
return parse_string_literal(context, string_at(*token_result.value()));
}
case '(': {
eat();
return parse_parentheses(context);
}
}
}
std::optional<expression> parser_instance::parse_binary(parse_context context,
const expression& left, const binary_operator* op)
{
auto right_result = parse_expression(context);
if (!right_result)
return std::nullopt;
expression* expr_left = new expression{ left };
expression* expr_right = new expression{ right_result.value() };
parser_output->delete_list_expressions.push_back(expr_left);
parser_output->delete_list_expressions.push_back(expr_right);
return expression{ expression_binary{ expr_left, expr_right, op } };
}
std::optional<expression> parser_instance::parse_parentheses(parse_context context)
{
// Parse what is inside the parentheses.
auto expr_result = parse_expression(CONTEXT_NONE);
if (!expr_result)
return std::nullopt;
// Eat the ")".
if (!expect(')')) {
recover();
return std::nullopt;
}
if(context == CONTEXT_STATEMENT) {
if (!expect(';')) {
recover();
return std::nullopt;
}
}
// If a binary expression is encased in the parentheses,
// return a "expression_parentheses" containing the binary expression
// so that operator precedence can be correctly applied later.
//
// Otherwise just return the expression.
if(expr_result.value().value.empty.type == EXPR_BINARY)
return expression{ expression_parentheses{ expr_result.value().value.binary.value } };
else
return expr_result;
}
std::optional<expression> parser_instance::parse_number_literal(parse_context context,
const char* number, number_type type)
{
if (context == CONTEXT_STATEMENT) {
if (!expect(';')) {
recover();
return std::nullopt;
}
}
return expression{ expression_number_literal{ number, type } };
}
std::optional<expression> parser_instance::parse_string_literal(parse_context context, const char* str)
{
if (context == CONTEXT_STATEMENT) {
if (!expect(';')) {
recover();
return std::nullopt;
}
}
return expression{ expression_string_literal{ str } };
}
std::optional<expression> parser_instance::parse_reference(parse_context context,
symbol_handle identifier_handle)
{
if (context == CONTEXT_STATEMENT) {
if (!expect(';')) {
recover();
return std::nullopt;
}
}
return expression{ expression_reference{ identifier_handle } };
}
std::optional<expression> parser_instance::parse_variable_declaration(parse_context context,
symbol_handle name_handle, u8 specifiers)
{
const char* name = lexer_output()->identifiers.at(name_handle);
bool is_pointer;
auto token_result = expect_any();
if (!token_result)
return std::nullopt;
if (token_result.value()->type == '^') {
is_pointer = true;
token_result = expect_identifier();
if (!token_result) {
recover();
return std::nullopt;
}
}
else {
is_pointer = false;
if (token_result.value()->type != masonc::lexer::TOKEN_IDENTIFIER) {
report_parse_error("Expected an identifier.");
recover();
return std::nullopt;
}
}
// The token is an identifier.
const char* type = identifier_at(*token_result.value());
type_handle type_handle = token_result.value()->value_index;
// Add variable to symbol table of current scope.
bool add_symbol_result = current_scope()->add_symbol(name);
if (!add_symbol_result) {
report_parse_error("Symbol is already defined.");
recover();
return std::nullopt;
}
if (context == CONTEXT_STATEMENT) {
token_result = expect_any();
if (!token_result) {
recover();
return std::nullopt;
}
// Variable declaration statements can optionally assign a value.
if (token_result.value()->type == OP_EQUALS.op_code) {
// Parse the right-hand side.
return parse_binary(
CONTEXT_STATEMENT,
expression{
expression_variable_declaration{
name_handle,
type_handle,
specifiers,
is_pointer
}
},
&OP_EQUALS
);
}
// No value is assigned to the variable, handle end of statement here.
if (token_result.value()->type != ';') {
report_parse_error("Expected \";\".");
recover();
return std::nullopt;
}
}
return expression{
expression_variable_declaration{
name_handle,
type_handle,
specifiers,
is_pointer
}
};
}
std::optional<expression> parser_instance::parse_call(parse_context context, symbol_handle name_handle)
{
expression_procedure_call call_expr{ name_handle };
auto token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::nullopt;
}
if (token_result.value()->type != ')') {
// Parse argument(s).
while (true) {
auto argument = parse_expression(CONTEXT_NONE);
if (!argument)
return std::nullopt;
call_expr.argument_list.push_back(argument.value());
token_result = expect_any();
if (!token_result)
return std::nullopt;
switch (token_result.value()->type) {
default:
report_parse_error("Unexpected token.");
recover();
return std::nullopt;
case ',':
continue;
case ')':
goto END_LOOP;
};
}
}
END_LOOP:
if (context == CONTEXT_STATEMENT) {
if (!expect(';')) {
recover();
return std::nullopt;
}
}
return expression{ call_expr };
}
std::vector<expression> parser_instance::parse_argument_list()
{
std::vector<expression> argument_list;
// Get the first token after "(".
// No need to check if it's valid because that was done before in 'parse_procedure()'.
//std::optional<token*> token_result = eat();
while (true)
{
auto specifiers_result = parse_specifiers();
if (!specifiers_result)
return std::vector<expression>{};
// Next token is guaranteed to exist and be an identifier.
auto token_result = peek_token();
//const char* identifier = identifier_at(*token_result.value());
symbol_handle identifier_handle = token_result.value()->value_index;
eat();
if (!expect(':')) {
// TODO: Recover from this by going to the next argument, instead of ";" or "}".
recover();
return std::vector<expression>{};
}
// Parse the argument
auto variable_declaration = parse_variable_declaration(CONTEXT_NONE,
identifier_handle, specifiers_result.value());
if (!variable_declaration)
return std::vector<expression>{};
argument_list.push_back(variable_declaration.value());
token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::vector<expression>{};
}
switch (token_result.value()->type) {
default:
report_parse_error("Unexpected token.");
recover();
return std::vector<expression>{};
case ',':
eat();
continue;
case ')':
eat();
return argument_list;
}
}
}
std::optional<expression> parser_instance::parse_procedure()
{
auto token_result = expect_identifier();
if (!token_result) {
// TODO: Recover by going to the end of the procedure.
recover();
return std::nullopt;
}
const char* name = identifier_at(*token_result.value());
symbol_handle name_handle = token_result.value()->value_index;
// Add procedure to symbol table of current scope.
bool add_symbol_result = current_scope()->add_symbol(name);
if (!add_symbol_result) {
report_parse_error("Symbol is already defined.");
return std::nullopt;
}
token_result = expect('(');
if (!token_result) {
recover();
return std::nullopt;
}
token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::nullopt;
}
// Any arguments are stashed here, otherwise it's empty.
std::vector<expression> argument_list;
// Procedure has no arguments.
if (token_result.value()->type == ')') {
// Eat the ")".
eat();
}
// Procedure has arguments.
else {
// Parse argument list.
argument_list = parse_argument_list();
}
token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::nullopt;
}
// Contains return type handle if one is specified, otherwise empty.
std::optional<type_handle> return_type_handle;
// Return type specified.
if (token_result.value()->type == masonc::lexer::TOKEN_RIGHT_POINTER)
{
// Eat the "->".
eat();
token_result = expect_identifier();
if (!token_result) {
// TODO: Recover by jumping to the end of the procedure.
recover();
return std::nullopt;
}
//return_type_identifier = identifier_at(*token_result.value());
return_type_handle = token_result.value()->value_index;
// Peek the token after the return type.
token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token");
done = true;
return std::nullopt;
}
}
switch (token_result.value()->type) {
default:
report_parse_error("Unexpected token.");
recover();
return std::nullopt;
// Procedure has a body.
case '{':
// Parse procedure body.
eat();
return parse_procedure_body(
expression_procedure_prototype{
name_handle,
return_type_handle,
argument_list
}
);
// Procedure has no body and is a prototype.
case ';':
// Done parsing procedure prototype.
eat();
return expression{
expression_procedure_prototype {
name_handle,
return_type_handle,
argument_list
}
};
}
}
std::optional<expression> parser_instance::parse_procedure_body(const expression_procedure_prototype& prototype)
{
auto token_result = peek_token();
if (!token_result) {
report_parse_error("Expected a token.");
done = true;
return std::nullopt;
}
if (token_result.value()->type == '}') {
// Procedure body is empty.
eat();
return expression{ expression_procedure_definition{ prototype } };
}
// Procedure body is not empty.
scope_index parent_scope_index = current_scope_index;
u16 procedure_name_length = lexer_output()->identifiers.length_at(prototype.name_handle);
const char* procedure_name = lexer_output()->identifiers.at(prototype.name_handle);
// Create new scope for the procedure and make it current.
current_scope_index = current_scope()->add_child(scope{});
scope* procedure_scope = current_scope();
procedure_scope->set_name(procedure_name, procedure_name_length);
std::vector<expression> body;
while (true) {
auto statement_result = parse_statement();
if (!statement_result)
return std::nullopt;
body.push_back(statement_result.value());
token_result = peek_token();
if (!token_result) {
current_scope_index = parent_scope_index;
report_parse_error("Expected a token");
done = true;
return std::nullopt;
}
// Check if the token after the last parsed expression is '}',
// which would be the end of the body.
if (token_result.value()->type == '}') {
// Eat the "}".
eat();
break;
}
}
current_scope_index = parent_scope_index;
return expression{ expression_procedure_definition{ prototype, body } };
}
std::optional<expression> parser_instance::parse_module_declaration()
{
std::string temp_module_name;
while(true)
{
auto token_result = expect_identifier();
if (!token_result) {
recover();
return std::nullopt;
}
temp_module_name += identifier_at(*token_result.value());
token_result = expect_any();
if (!token_result)
return std::nullopt;
if (token_result.value()->type == lexer::TOKEN_DOUBLECOLON) {
temp_module_name += "::";
continue;
}
else if(token_result.value()->type == ';') {
set_module(temp_module_name);
// Done parsing module declaration statement.
return expression{ expression_module_declaration{ parser_output->module_name.c_str() } };
}
else {
report_parse_error("Unexpected token.");
recover();
return std::nullopt;
}
}
}
std::optional<expression> parser_instance::parse_module_import()
{
std::string temp_module_name;
while(true)
{
auto token_result = expect_identifier();
if (!token_result) {
recover();
return std::nullopt;
}
temp_module_name += identifier_at(*token_result.value());
token_result = expect_any();
if (!token_result)
return std::nullopt;
// TODO: Check for "as" token.
if (token_result.value()->type == lexer::TOKEN_DOUBLECOLON) {
temp_module_name += "::";
continue;
}
else if (token_result.value()->type == ';') {
// TODO: Check if imported more than once.
u64 import_index = parser_output->file_module.module_import_names.copy_back(temp_module_name);
// Done parsing module import statement.
return expression{
expression_module_import{ import_index, get_token_location(this->token_index) }
};
}
else {
report_parse_error("Unexpected token.");
recover();
return std::nullopt;
}
}
}
expression_binary* get_binary_expression(expression* expr)
{
if (expr->value.empty.type == EXPR_BINARY)
return &expr->value.binary.value;
else if (expr->value.empty.type == EXPR_PARENTHESES)
return &expr->value.parentheses.value.expr;
return nullptr;
}
} | 32.910397 | 152 | 0.532325 | ThatGuyMike7 |
abf879b6c13c89fd9480e7aa7d32fa6d3ed98c98 | 3,169 | cpp | C++ | src/advent5.cpp | arkadye/advent_of_code_2020 | 6652f6e0ab8c09312fbfbb5934c553c264c467cc | [
"CC0-1.0"
] | 2 | 2020-12-30T07:12:09.000Z | 2021-11-21T18:37:10.000Z | src/advent5.cpp | arkadye/advent_of_code_2020 | 6652f6e0ab8c09312fbfbb5934c553c264c467cc | [
"CC0-1.0"
] | null | null | null | src/advent5.cpp | arkadye/advent_of_code_2020 | 6652f6e0ab8c09312fbfbb5934c553c264c467cc | [
"CC0-1.0"
] | null | null | null | #include "../advent/advent5.h"
#include "../utils/advent_utils.h"
#include "../utils/sorted_vector.h"
#include <string>
#include <numeric>
#include <cassert>
namespace
{
using FileIt = std::istream_iterator<std::string>;
using utils::open_puzzle_input;
using utils::sorted_vector;
constexpr char FORWARD = 'F';
constexpr char BACKWARD = 'B';
constexpr char LEFT = 'L';
constexpr char RIGHT = 'R';
template <typename InputIt>
int partition(InputIt pass_start, InputIt pass_finish, int low_end, int top_end, char go_low, char go_high)
{
if (pass_start == pass_finish)
{
assert(low_end == top_end || low_end == (top_end -1));
return low_end;
}
const char section = *pass_start;
assert(section == go_low || section == go_high);
auto recurse = [&](int new_lower, int new_upper)
{
return partition(pass_start + 1, pass_finish, new_lower, new_upper, go_low, go_high);
};
const int midpoint = low_end + ((top_end - low_end) / 2);
if (section == go_low)
{
return recurse(low_end, midpoint);
}
else if (section == go_high)
{
return recurse(midpoint, top_end);
}
assert(false);
return -1;
}
template <typename InputIt>
int partition(InputIt start, InputIt finish, int max_val, char go_low, char go_high)
{
return partition(start, finish, 0, max_val, go_low, go_high);
}
int get_seat_number_generic(const std::string& id, int row_digits, int col_digits)
{
assert(static_cast<int>(id.size()) == (row_digits + col_digits));
const int num_rows = 1 << row_digits;
const int num_cols = 1 << col_digits;
const auto split_point = begin(id) + row_digits;
const int row_number = partition(begin(id), split_point, num_rows, FORWARD, BACKWARD);
const int col_number = partition(split_point, end(id), num_cols, LEFT, RIGHT);
return row_number * num_cols + col_number;
}
int get_seat_number_p1(const std::string& id)
{
return get_seat_number_generic(id, 7, 3);
}
}
ResultType day_five_testcase_a()
{
return get_seat_number_p1("FBFBBFFRLR");
}
ResultType day_five_testcase_b()
{
return get_seat_number_p1("BFFFBBFRRR");
}
ResultType day_five_testcase_c()
{
return get_seat_number_p1("FFFBBBFRRR");
}
ResultType day_five_testcase_d()
{
return get_seat_number_p1("BBFFBBFRLL");
}
ResultType advent_five_p1()
{
std::ifstream input = open_puzzle_input(5);
return std::transform_reduce(FileIt{ input }, FileIt{},
-1, [](int l, int r) {return std::max(l, r); }, get_seat_number_p1);
}
ResultType advent_five_p2()
{
const sorted_vector<int> ids = []()
{
sorted_vector<int> result;
std::ifstream input = open_puzzle_input(5);
std::for_each(FileIt{ input }, FileIt{}, [&result](const std::string& s) {result.insert(get_seat_number_p1(s)); });
return result;
}();
for (std::size_t i = 0; i < (ids.size() - 1); ++i)
{
const auto this_one = ids[i];
const auto next_one = ids[i + 1];
const auto difference = next_one - this_one;
if (difference == 2)
{
return this_one + 1;
}
assert(difference == 1);
}
assert(false);
return "!ERROR!";
}
| 25.352 | 118 | 0.667403 | arkadye |
abfb64d2d20d1f6e622671c9d362c5378aeda2c4 | 171 | cpp | C++ | FerrousEngine/stream_writer.cpp | Syncaidius/FerrousEngine | a53d439dbdb153422f1007f69dce89c330231999 | [
"MIT"
] | 3 | 2019-06-04T23:56:29.000Z | 2019-11-29T23:45:59.000Z | FerrousEngine/stream_writer.cpp | Syncaidius/FerrousEngine | a53d439dbdb153422f1007f69dce89c330231999 | [
"MIT"
] | null | null | null | FerrousEngine/stream_writer.cpp | Syncaidius/FerrousEngine | a53d439dbdb153422f1007f69dce89c330231999 | [
"MIT"
] | null | null | null | #include "stream_writer.h"
namespace fe {
StreamWriter::StreamWriter(Stream* stream) {
_stream = stream;
}
StreamWriter::~StreamWriter() {
_stream = nullptr;
}
} | 15.545455 | 45 | 0.695906 | Syncaidius |
abfc0d16224addb8eb26c927bc505e792146898a | 1,357 | cpp | C++ | src/Evolution/Systems/ScalarWave/Equations.cpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | 2 | 2021-04-11T04:07:42.000Z | 2021-04-11T05:07:54.000Z | src/Evolution/Systems/ScalarWave/Equations.cpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | 4 | 2018-06-04T20:26:40.000Z | 2018-07-27T14:54:55.000Z | src/Evolution/Systems/ScalarWave/Equations.cpp | macedo22/spectre | 97b2b7ae356cf86830258cb5f689f1191fdb6ddd | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Evolution/Systems/ScalarWave/Equations.hpp"
#include <cstddef>
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "Utilities/ContainerHelpers.hpp"
#include "Utilities/GenerateInstantiations.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/TMPL.hpp"
namespace ScalarWave {
template <size_t Dim>
void ComputeNormalDotFluxes<Dim>::apply(
const gsl::not_null<Scalar<DataVector>*> pi_normal_dot_flux,
const gsl::not_null<tnsr::i<DataVector, Dim, Frame::Inertial>*>
phi_normal_dot_flux,
const gsl::not_null<Scalar<DataVector>*> psi_normal_dot_flux,
const Scalar<DataVector>& pi) noexcept {
destructive_resize_components(pi_normal_dot_flux, get(pi).size());
destructive_resize_components(phi_normal_dot_flux, get(pi).size());
destructive_resize_components(psi_normal_dot_flux, get(pi).size());
get(*pi_normal_dot_flux) = 0.0;
get(*psi_normal_dot_flux) = 0.0;
for (size_t i = 0; i < Dim; ++i) {
phi_normal_dot_flux->get(i) = 0.0;
}
}
} // namespace ScalarWave
#define DIM(data) BOOST_PP_TUPLE_ELEM(0, data)
#define INSTANTIATION(_, data) \
template class ScalarWave::ComputeNormalDotFluxes<DIM(data)>;
GENERATE_INSTANTIATIONS(INSTANTIATION, (1, 2, 3))
#undef INSTANTIATION
#undef DIM
| 31.55814 | 69 | 0.755343 | macedo22 |
abfc6acb696f70a8a35483228319ab9068bf3fcf | 4,626 | cpp | C++ | src/conjuntos.cpp | NaturalFlow/ConjuntosTP1 | fccc0aa4b48ffa7a71138a46bce35c2c94ffdd13 | [
"MIT"
] | null | null | null | src/conjuntos.cpp | NaturalFlow/ConjuntosTP1 | fccc0aa4b48ffa7a71138a46bce35c2c94ffdd13 | [
"MIT"
] | null | null | null | src/conjuntos.cpp | NaturalFlow/ConjuntosTP1 | fccc0aa4b48ffa7a71138a46bce35c2c94ffdd13 | [
"MIT"
] | null | null | null | #include "conjuntos.h"
void lerConjunto(int* conjunto, int qtdElementos) {
for(unsigned int i = 0; i < qtdElementos; i++) {
std::cin >> conjunto[i];
}
}
void imprimirConjunto(int* conjunto, int qtdElementos, std::string nome) {
std::cout << nome << '{';
for(unsigned int i = 0; i < qtdElementos; i++) {
std::cout << conjunto[i] << (i == qtdElementos-1 ? "}\n" : ", ");
}
}
void uniao(int* A, int qtdA, int* B, int qtdB, int* AUB, int* qtdAUB) {
*qtdAUB = qtdA;
for(unsigned int i = 0; i < qtdA; i++) {
AUB[i] = A[i];
}
for(unsigned int i = 0; i < qtdB; i++) {
bool encontrado = false;
for(unsigned int j = 0; j < *qtdAUB; j++) {
if(B[i] == AUB[j]) {
encontrado = true;
}
}
if(encontrado == false) {
int index = *qtdAUB;
AUB[index] = B[i];
*qtdAUB += 1;
}
}
}
void inter(int* A, int qtdA, int* B, int qtdB, int* AinterB, int* qtdAinterB) {
int index = 0;
for(unsigned int i = 0; i < qtdA; i++) {
for(unsigned int j = 0; j < qtdB; j++) {
if(A[i] == B[j]) {
AinterB[index] = A[i];
*qtdAinterB += 1;
index++;
}
}
}
}
void dif(int* A, int qtdA, int* B, int qtdB, int* AdifB, int* qtdAdifB) {
for(unsigned int i = 0; i < qtdA; i++) {
bool encontrado = false;
for(unsigned int j = 0; j < qtdB; j++) {
if(A[i] == B[j]) {
encontrado = true;
}
}
if(!encontrado) {
int index = *qtdAdifB;
AdifB[index] = A[i];
*qtdAdifB += 1;
}
}
}
bool subconjunto(int* A, int qtdA, int* B, int qtdB) {
int index = 0;
unsigned int k = 0;
for(unsigned int i = 0; (i < qtdA && k != qtdB) ; i++) {
for(unsigned int j = 0; j < qtdB; j++) {
if(A[i] == B[j]) {
k++;
}
}
}
return k == qtdB;
}
bool identicos(int* A, int qtdA, int* B, int qtdB) {
if(qtdA != qtdB) {
return false;
}
unsigned int k = 0;
for(unsigned int i = 0; i < qtdA; i++) {
for(unsigned int j = 0; j < qtdB; j++) {
if(A[i] == B[j]) {
k++;
}
}
}
return k == qtdA;
}
int amplitude(int* conjunto,int tamanhoConjunto) {
int maior,menor;
maior = menor = conjunto[0];
for(unsigned int i = 0; i < tamanhoConjunto; i++) {
if(conjunto[i] > maior) {
maior = conjunto[i];
}else if(conjunto[i] < menor) {
menor = conjunto[i];
}
}
return maior-menor;
}
void subcadeia(int* conjunto, int tamanhoConj, int* subconj, int* tamanhoSub,char regra) {
unsigned int indexMaiorSeq = 0,maiorSeq =0,indexSeqAtual = 0,SeqAtual = 0;
if(regra == '>') {
for(unsigned int i = 0; i < tamanhoConj-1; i++) {
if(conjunto[i] > conjunto[i+1]) {
indexSeqAtual = conjunto[i+1];
SeqAtual++;
if(SeqAtual > maiorSeq) {
maiorSeq = SeqAtual;
indexMaiorSeq = indexSeqAtual;
}
}
}
}
else {
for(unsigned int i = 0; i < tamanhoConj-1; i++) {
if(conjunto[i] < conjunto[i+1]) {
indexSeqAtual = conjunto[i+1];
SeqAtual++;
if(SeqAtual > maiorSeq) {
maiorSeq = SeqAtual;
indexMaiorSeq = indexSeqAtual;
}
}
}
}
for(unsigned int k = 0,i = indexMaiorSeq - maiorSeq;k < maiorSeq; i++,k++) {
subconj[k] = conjunto[i];
*tamanhoSub += 1;
}
}
void intercalando(int* A, int qtdA, int* B, int qtdB, int* conjunto, int* tamanho) {
unsigned int maiorTamanho = qtdA > qtdB ? qtdA : qtdB;
unsigned int menorTamanho = qtdA > qtdB ? qtdB : qtdA;
int* maiorConjunto= qtdA > qtdB ? A : B;
for(unsigned int i = 0; i < menorTamanho; i++) {
if(A[i] < B[i]) {
*tamanho += 2;
conjunto[i] = A[i];
conjunto[i+1] = B[i];
}else {
*tamanho += 2;
conjunto[i] = B[i];
conjunto[i+1] = A[i];
}
}
for(unsigned int k = *tamanho,i = 0; i < maiorTamanho - menorTamanho; k++, i++) {
conjunto[k] = maiorConjunto[menorTamanho+i];
}
}
| 31.04698 | 91 | 0.447255 | NaturalFlow |
280c4d24b44603cb17eba0f6208d5876b0d49d1f | 3,001 | hpp | C++ | silkrpc/json/types.hpp | gelfand/silkrpc | ecbfb0bb31c4d9ca8bd37bd193ae922fb4bbfbb3 | [
"Apache-2.0"
] | null | null | null | silkrpc/json/types.hpp | gelfand/silkrpc | ecbfb0bb31c4d9ca8bd37bd193ae922fb4bbfbb3 | [
"Apache-2.0"
] | null | null | null | silkrpc/json/types.hpp | gelfand/silkrpc | ecbfb0bb31c4d9ca8bd37bd193ae922fb4bbfbb3 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 The Silkrpc Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef SILKRPC_JSON_TYPES_HPP_
#define SILKRPC_JSON_TYPES_HPP_
#include <optional>
#include <string>
#include <vector>
#include <intx/intx.hpp>
#include <evmc/evmc.hpp>
#include <nlohmann/json.hpp>
#include <silkrpc/types/block.hpp>
#include <silkrpc/types/call.hpp>
#include <silkrpc/types/chain_config.hpp>
#include <silkrpc/types/error.hpp>
#include <silkrpc/types/filter.hpp>
#include <silkrpc/types/issuance.hpp>
#include <silkrpc/types/log.hpp>
#include <silkrpc/types/transaction.hpp>
#include <silkrpc/types/receipt.hpp>
#include <silkworm/types/block.hpp>
#include <silkworm/types/transaction.hpp>
namespace evmc {
void to_json(nlohmann::json& json, const address& addr);
void from_json(const nlohmann::json& json, address& addr);
void to_json(nlohmann::json& json, const bytes32& b32);
void from_json(const nlohmann::json& json, bytes32& b32);
} // namespace evmc
namespace silkworm {
void to_json(nlohmann::json& json, const BlockHeader& ommer);
void to_json(nlohmann::json& json, const Transaction& transaction);
} // namespace silkworm
namespace silkrpc {
void to_json(nlohmann::json& json, const Block& b);
void to_json(nlohmann::json& json, const Transaction& transaction);
void from_json(const nlohmann::json& json, Call& call);
void to_json(nlohmann::json& json, const Log& log);
void from_json(const nlohmann::json& json, Log& log);
void to_json(nlohmann::json& json, const Receipt& receipt);
void from_json(const nlohmann::json& json, Receipt& receipt);
void to_json(nlohmann::json& json, const Filter& filter);
void from_json(const nlohmann::json& json, Filter& filter);
void to_json(nlohmann::json& json, const Forks& forks);
void to_json(nlohmann::json& json, const Issuance& issuance);
void to_json(nlohmann::json& json, const Error& error);
void to_json(nlohmann::json& json, const RevertError& error);
std::string to_hex_no_leading_zeros(uint64_t number);
std::string to_hex_no_leading_zeros(silkworm::ByteView bytes);
std::string to_quantity(uint64_t number);
std::string to_quantity(intx::uint256 number);
std::string to_quantity(silkworm::ByteView bytes);
nlohmann::json make_json_content(uint32_t id, const nlohmann::json& result);
nlohmann::json make_json_error(uint32_t id, int32_t code, const std::string& message);
nlohmann::json make_json_error(uint32_t id, const RevertError& error);
} // namespace silkrpc
#endif // SILKRPC_JSON_TYPES_HPP_
| 31.260417 | 86 | 0.765078 | gelfand |
28123cf935482d836abfe70489e67c1b4f776444 | 7,440 | cc | C++ | src/DesktopApp/main.cc | lurume84/blink-desktop | d6d01f8dc461edd22192a521fbd49669bfa8f684 | [
"MIT"
] | 75 | 2019-03-08T14:15:49.000Z | 2022-01-05T17:30:43.000Z | src/DesktopApp/main.cc | lurume84/blink-desktop | d6d01f8dc461edd22192a521fbd49669bfa8f684 | [
"MIT"
] | 55 | 2019-02-17T01:34:12.000Z | 2022-02-26T21:07:33.000Z | src/DesktopApp/main.cc | lurume84/blink-desktop | d6d01f8dc461edd22192a521fbd49669bfa8f684 | [
"MIT"
] | 20 | 2019-05-21T19:02:31.000Z | 2022-03-28T07:29:28.000Z | // Copyright (c) 2015 The Chromium Embedded Framework 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 <windows.h>
#include "include/base/cef_scoped_ptr.h"
#include "include/cef_command_line.h"
#include "include/cef_sandbox_win.h"
#include "browser/main_context_impl.h"
#include "browser/main_message_loop_multithreaded_win.h"
#include "browser/root_window_manager.h"
#include "browser/test_runner.h"
#include "browser/client_app_browser.h"
#include "browser/main_message_loop_external_pump.h"
#include "browser/main_message_loop_std.h"
#include "common/client_app_other.h"
#include "common/client_switches.h"
#include "renderer/client_app_renderer.h"
#include "DesktopCore\DesktopCore.h"
#include "Events.h"
#include "DesktopCore\Utils\Patterns\PublisherSubscriber\Subscriber.h"
#include "DesktopCore\System\Services\CrashReportService.h"
#include "DesktopCore\Upgrade\Agents\UpgradeViewerAgent.h"
#include "DesktopCore\Upgrade\Agents\UpgradeDesktopAgent.h"
#include "DesktopCore\Upgrade\Events.h"
#include "DesktopCore\Network\Agents\FileServerAgent.h"
#include "DesktopCore\Blink\Agents\SyncVideoAgent.h"
#include "DesktopCore\Blink\Agents\SyncThumbnailAgent.h"
#include "DesktopCore\Blink\Agents\LiveViewAgent.h"
#include "DesktopCore\Blink\Agents\ActivityAgent.h"
#include "DesktopCore\System\Agents\LogAgent.h"
#include "DesktopCore\System\Services\LogService.h"
#include "Services\DownloadViewerService.h"
#include "Services\DownloadDesktopService.h"
// When generating projects with CMake the CEF_USE_SANDBOX value will be defined
// automatically if using the required compiler version. Pass -DUSE_SANDBOX=OFF
// to the CMake command-line to disable use of the sandbox.
// Uncomment this line to manually enable sandbox support.
// #define CEF_USE_SANDBOX 1
#if defined(CEF_USE_SANDBOX)
// The cef_sandbox.lib static library may not link successfully with all VS
// versions.
#pragma comment(lib, "cef_sandbox.lib")
#endif
namespace client {
namespace {
int RunMain(HINSTANCE hInstance, int nCmdShow)
{
desktop::core::service::CrashReportService service;
service.initialize({});
// Enable High-DPI support on Windows 7 or newer.
CefEnableHighDPISupport();
CefMainArgs main_args(hInstance);
void* sandbox_info = NULL;
#if defined(CEF_USE_SANDBOX)
// Manage the life span of the sandbox information object. This is necessary
// for sandbox support on Windows. See cef_sandbox_win.h for complete details.
CefScopedSandboxInfo scoped_sandbox;
sandbox_info = scoped_sandbox.sandbox_info();
#endif
// Parse command-line arguments.
CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine();
command_line->InitFromString(::GetCommandLineW());
command_line->AppendSwitch(switches::kUseViews);
command_line->AppendSwitch(switches::kHideFrame);
command_line->AppendSwitch(switches::kHideControls);
command_line->AppendSwitch(switches::kExternalMessagePump);
command_line->AppendSwitchWithValue("disable-web-security", "true");
// Create a ClientApp of the correct type.
CefRefPtr<CefApp> app;
ClientApp::ProcessType process_type = ClientApp::GetProcessType(command_line);
if (process_type == ClientApp::BrowserProcess)
app = new ClientAppBrowser();
else if (process_type == ClientApp::RendererProcess)
app = new ClientAppRenderer();
else if (process_type == ClientApp::OtherProcess)
app = new ClientAppOther();
// Execute the secondary process, if any.
int exit_code = CefExecuteProcess(main_args, app, sandbox_info);
if (exit_code >= 0)
return exit_code;
// Create the main context object.
scoped_ptr<MainContextImpl> context(new MainContextImpl(command_line, true));
CefSettings settings;
settings.remote_debugging_port = 8088;
//CefString(&settings.user_agent).FromString("BlingBrowser");
settings.external_message_pump = true;
#if !defined(CEF_USE_SANDBOX)
settings.no_sandbox = true;
#endif
// Populate the settings based on command line arguments.
context->PopulateSettings(&settings);
// Create the main message loop object.
scoped_ptr<MainMessageLoop> message_loop;
if (settings.multi_threaded_message_loop)
message_loop.reset(new MainMessageLoopMultithreadedWin);
else if (settings.external_message_pump)
message_loop = MainMessageLoopExternalPump::Create();
else
message_loop.reset(new MainMessageLoopStd);
// Initialize CEF.
context->Initialize(main_args, settings, app, sandbox_info);
// Register scheme handlers.
test_runner::RegisterSchemeHandlers();
RootWindowConfig window_config;
window_config.always_on_top = command_line->HasSwitch(switches::kAlwaysOnTop);
window_config.with_controls =
!command_line->HasSwitch(switches::kHideControls);
window_config.with_osr = settings.windowless_rendering_enabled ? true : false;
{
desktop::core::service::ApplicationDataService applicationService;
if (boost::filesystem::exists(applicationService.getViewerFolder() + "/index.html"))
{
desktop::core::service::IniFileService iniFileService;
window_config.url = iniFileService.get<std::string>(applicationService.getMyDocuments() + "Bling.ini", "FileServer", "Endpoint", "http://127.0.0.1:9191/");
}
else
{
window_config.url = boost::filesystem::canonical("Html/loading/index.html").string();
}
}
desktop::core::DesktopCore core;
core.initialize();
core.addAgent(std::make_unique<desktop::core::agent::LogAgent>());
core.addAgent(std::make_unique<desktop::core::agent::SyncVideoAgent>());
core.addAgent(std::make_unique<desktop::core::agent::SyncThumbnailAgent>());
core.addAgent(std::make_unique<desktop::core::agent::LiveViewAgent>());
core.addAgent(std::make_unique<desktop::core::agent::FileServerAgent>());
desktop::core::utils::patterns::Subscriber subscriber;
subscriber.subscribe([&core, &subscriber](const desktop::core::utils::patterns::Event& rawEvt)
{
const auto& evt = static_cast<const desktop::ui::events::BrowserCreatedEvent&>(rawEvt);
auto &browser = evt.m_browser;
desktop::core::service::LogService::info("Browser instance created");
core.addAgent(std::make_unique<desktop::core::agent::UpgradeViewerAgent>(std::make_unique<desktop::ui::service::DownloadViewerService>(browser)));
core.addAgent(std::make_unique<desktop::core::agent::UpgradeDesktopAgent>(std::make_unique<desktop::ui::service::DownloadDesktopService>(browser)));
subscriber.unsubscribe(desktop::ui::events::BROWSER_CREATED_EVENT);
}, desktop::ui::events::BROWSER_CREATED_EVENT);
// Create the first window.
context->GetRootWindowManager()->CreateRootWindow(window_config);
// Run the message loop. This will block until Quit() is called by the
// RootWindowManager after all windows have been destroyed.
int result = message_loop->Run();
// Shut down CEF.
context->Shutdown();
// Release objects in reverse order of creation.
message_loop.reset();
context.reset();
return result;
}
} // namespace
} // namespace client
// Program entry point function.
int APIENTRY wWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow) {
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
return client::RunMain(hInstance, nCmdShow);
}
| 36.470588 | 159 | 0.761694 | lurume84 |
281480c8e5b26bc76ccc8896f98222fc7ea382b3 | 2,361 | cc | C++ | atom/renderer/api/atom_api_renderer_ipc.cc | joaomoreno/electron | 9547ff135f3f14d4bad31ae446b0a2e7a0f0ea3d | [
"MIT"
] | 3 | 2019-03-20T10:57:42.000Z | 2020-11-02T07:02:40.000Z | atom/renderer/api/atom_api_renderer_ipc.cc | joaomoreno/electron | 9547ff135f3f14d4bad31ae446b0a2e7a0f0ea3d | [
"MIT"
] | 5 | 2016-06-10T16:57:36.000Z | 2019-03-30T18:51:36.000Z | atom/renderer/api/atom_api_renderer_ipc.cc | joaomoreno/electron | 9547ff135f3f14d4bad31ae446b0a2e7a0f0ea3d | [
"MIT"
] | 3 | 2016-07-22T16:53:13.000Z | 2020-12-18T18:11:36.000Z | // Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/api/atom_api_renderer_ipc.h"
#include "atom/common/api/api_messages.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "content/public/renderer/render_view.h"
#include "native_mate/dictionary.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebView.h"
using content::RenderView;
using blink::WebLocalFrame;
using blink::WebView;
namespace atom {
namespace api {
RenderView* GetCurrentRenderView() {
WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext();
if (!frame)
return nullptr;
WebView* view = frame->view();
if (!view)
return nullptr; // can happen during closing.
return RenderView::FromWebView(view);
}
void Send(mate::Arguments* args,
const base::string16& channel,
const base::ListValue& arguments) {
RenderView* render_view = GetCurrentRenderView();
if (render_view == nullptr)
return;
bool success = render_view->Send(new AtomViewHostMsg_Message(
render_view->GetRoutingID(), channel, arguments));
if (!success)
args->ThrowError("Unable to send AtomViewHostMsg_Message");
}
base::string16 SendSync(mate::Arguments* args,
const base::string16& channel,
const base::ListValue& arguments) {
base::string16 json;
RenderView* render_view = GetCurrentRenderView();
if (render_view == nullptr)
return json;
IPC::SyncMessage* message = new AtomViewHostMsg_Message_Sync(
render_view->GetRoutingID(), channel, arguments, &json);
bool success = render_view->Send(message);
if (!success)
args->ThrowError("Unable to send AtomViewHostMsg_Message_Sync");
return json;
}
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
mate::Dictionary dict(context->GetIsolate(), exports);
dict.SetMethod("send", &Send);
dict.SetMethod("sendSync", &SendSync);
}
} // namespace api
} // namespace atom
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_renderer_ipc, atom::api::Initialize)
| 29.5125 | 75 | 0.71834 | joaomoreno |
281889d0a0d5786e1b45594677b7a487ddb21204 | 5,112 | cc | C++ | zbluenet/zbluenet/src/zbluenet/logger_mgr.cc | zhengjinwei123/zbluenet | 2d3c26f587de34ca7924176487b92e0700756792 | [
"Apache-2.0"
] | 3 | 2021-09-08T02:36:08.000Z | 2022-01-02T20:18:44.000Z | zbluenet/zbluenet/src/zbluenet/logger_mgr.cc | zhengjinwei123/zbluenet | 2d3c26f587de34ca7924176487b92e0700756792 | [
"Apache-2.0"
] | null | null | null | zbluenet/zbluenet/src/zbluenet/logger_mgr.cc | zhengjinwei123/zbluenet | 2d3c26f587de34ca7924176487b92e0700756792 | [
"Apache-2.0"
] | null | null | null | #include <zbluenet/logger_mgr.h>
#include <zbluenet/logger_sink.h>
#include <vector>
namespace zbluenet {
class LoggerMgr::Impl {
public:
using LogFormatter = LoggerMgr::LogFormatter;
using LoggerVec = std::vector<Logger *>;
Impl();
~Impl();
void setMaxLoggerCount(int count);
void setMaxLogSize(int size /* = 4096 */);
bool registerLogger(int logger_id, LogFormatter formatter /* = nullptr */, int level /* = -1 */);
void removeLogger(int logger_id);
bool addSink(int logger_id, LoggerSink *sink, LogFormatter formatter /* = nullptr */, int level /* = -1 */);
void log(int logger_id, int level, const char *filename, int line, const char *function, const char *fmt, va_list args);
void plainLog(int logger_id, int level, const char *format, va_list args);
void setLevelFilter(int logger_id, int level);
private:
LoggerVec loggers_;
int max_log_size_;
};
//////////////////////////////////////////////////////////////////////////
ZBLUENET_PRECREATED_SINGLETON_IMPL(LoggerMgr)
LoggerMgr::Impl::Impl():
max_log_size_(0)
{
}
LoggerMgr::Impl::~Impl()
{
for (size_t i = 0, size = loggers_.size(); i < size; ++i) {
delete loggers_[i];
}
}
void LoggerMgr::Impl::setMaxLoggerCount(int count)
{
if (count < 0) {
return;
}
if (count < (int)loggers_.size()) {
for (size_t i = count, size = loggers_.size(); i < size; ++i) {
delete loggers_[i];
}
}
loggers_.resize(count, nullptr);
}
void LoggerMgr::Impl::setMaxLogSize(int size /* = 4096 */)
{
if (size <= 0) {
return;
}
max_log_size_ = size;
}
bool LoggerMgr::Impl::registerLogger(int logger_id, LogFormatter formatter /* = nullptr */, int level /* = -1 */)
{
if (logger_id < 0 || logger_id >= (int)loggers_.size()) {
return false;
}
if (loggers_[logger_id] != nullptr) {
return false;
}
loggers_[logger_id] = new Logger(formatter, level, max_log_size_);
return true;
}
void LoggerMgr::Impl::removeLogger(int logger_id)
{
if (logger_id < 0 || logger_id >= (int)loggers_.size()) {
return;
}
if (nullptr == loggers_[logger_id]) {
return;
}
delete loggers_[logger_id];
loggers_[logger_id] = nullptr;
}
bool LoggerMgr::Impl::addSink(int logger_id, LoggerSink *sink, LogFormatter formatter /* = nullptr */, int level /* = -1 */)
{
if (logger_id < 0 || logger_id >= (int)loggers_.size()) {
return false;
}
if (nullptr == loggers_[logger_id]) {
return false;
}
return loggers_[logger_id]->addSink(sink, formatter, level);
}
void LoggerMgr::Impl::log(int logger_id, int level, const char *filename, int line, const char *function, const char *fmt, va_list args)
{
if (logger_id < 0 || logger_id >= (int)loggers_.size()) {
return;
}
if (nullptr == loggers_[logger_id]) {
return;
}
loggers_[logger_id]->log(level, filename, line, function, fmt, args);
}
void LoggerMgr::Impl::plainLog(int logger_id, int level, const char *format, va_list args)
{
if (logger_id < 0 || logger_id >= (int)loggers_.size()) {
return;
}
if (nullptr == loggers_[logger_id]) {
return;
}
loggers_[logger_id]->plainLog(level, format, args);
}
void LoggerMgr::Impl::setLevelFilter(int logger_id, int level)
{
if (logger_id < 0 || logger_id >= (int)loggers_.size()) {
return;
}
if (nullptr == loggers_[logger_id]) {
return;
}
loggers_[logger_id]->setLevelFilter(level);
}
//////////////////////////////////////////////////////////////////////////
LoggerMgr::LoggerMgr() :
pimpl_(new Impl())
{
setMaxLoggerCount();
setMaxLogSize();
}
LoggerMgr::~LoggerMgr()
{
}
void LoggerMgr::setMaxLoggerCount(int count)
{
pimpl_->setMaxLoggerCount(count);
}
void LoggerMgr::setMaxLogSize(int size)
{
pimpl_->setMaxLogSize(size);
}
bool LoggerMgr::registerLogger(int logger_id, LogFormatter formatter, int level)
{
return pimpl_->registerLogger(logger_id, formatter, level);
}
void LoggerMgr::removeLogger(int logger_id)
{
pimpl_->removeLogger(logger_id);
}
bool LoggerMgr::addSink(int logger_id, LoggerSink *sink, LogFormatter formatter, int level)
{
return pimpl_->addSink(logger_id, sink, formatter, level);
}
void LoggerMgr::log(int logger_id, int level, const char *filename, int line, const char *function, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
pimpl_->log(logger_id, level, filename, line, function, fmt, args);
va_end(args);
}
void LoggerMgr::log(int logger_id, int level, const char *filename, int line, const char *function, const char *fmt, va_list args)
{
pimpl_->log(logger_id, level, filename, line, function, fmt, args);
}
void LoggerMgr::plainLog(int logger_id, int level, const char *format, ...)
{
va_list args;
va_start(args, format);
pimpl_->plainLog(logger_id, level, format, args);
va_end(args);
}
void LoggerMgr::plainLog(int logger_id, int level, const char *format, va_list args)
{
pimpl_->plainLog(logger_id, level, format, args);
}
void LoggerMgr::setLevelFilter(int logger_id, int level)
{
pimpl_->setLevelFilter(logger_id, level);
}
} // namespace zbluenet
| 24.227488 | 137 | 0.655125 | zhengjinwei123 |
2819917cd0acc64cac0ec556690c06ba125529ba | 524 | hpp | C++ | pythran/pythonic/time/time.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 1 | 2018-03-24T00:33:03.000Z | 2018-03-24T00:33:03.000Z | pythran/pythonic/time/time.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/time/time.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | null | null | null | #ifndef PYTHONIC_TIME_TIME_HPP
#define PYTHONIC_TIME_TIME_HPP
#include "pythonic/include/time/time.hpp"
#include "pythonic/utils/functor.hpp"
#include <chrono>
PYTHONIC_NS_BEGIN
namespace time
{
double time()
{
std::chrono::time_point<std::chrono::steady_clock> tp =
std::chrono::steady_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(
tp.time_since_epoch()).count() /
1000.;
}
DEFINE_FUNCTOR(pythonic::time, time)
}
PYTHONIC_NS_END
#endif
| 18.714286 | 65 | 0.694656 | SylvainCorlay |
281bf7ef8deb624403c334298e80baddf9b26944 | 7,025 | cpp | C++ | wxWidgets-2.9.1/src/generic/propdlg.cpp | gamekit-developers/gamekit | 74c896af5826ebe8fb72f2911015738f38ab7bb2 | [
"Zlib",
"MIT"
] | 241 | 2015-01-04T00:36:58.000Z | 2022-01-06T19:19:23.000Z | wxWidgets-2.9.1/src/generic/propdlg.cpp | gamekit-developers/gamekit | 74c896af5826ebe8fb72f2911015738f38ab7bb2 | [
"Zlib",
"MIT"
] | 10 | 2015-07-10T18:27:17.000Z | 2019-06-26T20:59:59.000Z | wxWidgets-2.9.1/src/generic/propdlg.cpp | gamekit-developers/gamekit | 74c896af5826ebe8fb72f2911015738f38ab7bb2 | [
"Zlib",
"MIT"
] | 82 | 2015-01-25T18:02:35.000Z | 2022-03-05T12:28:17.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: src/generic/propdlg.cpp
// Purpose: wxPropertySheetDialog
// Author: Julian Smart
// Modified by:
// Created: 2005-03-12
// RCS-ID: $Id$
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_BOOKCTRL
#ifndef WX_PRECOMP
#include "wx/button.h"
#include "wx/sizer.h"
#include "wx/intl.h"
#include "wx/log.h"
#include "wx/msgdlg.h"
#endif
#include "wx/bookctrl.h"
#if wxUSE_NOTEBOOK
#include "wx/notebook.h"
#endif
#if wxUSE_CHOICEBOOK
#include "wx/choicebk.h"
#endif
#if wxUSE_TOOLBOOK
#include "wx/toolbook.h"
#endif
#if wxUSE_LISTBOOK
#include "wx/listbook.h"
#endif
#if wxUSE_TREEBOOK
#include "wx/treebook.h"
#endif
#include "wx/generic/propdlg.h"
#include "wx/sysopt.h"
//-----------------------------------------------------------------------------
// wxPropertySheetDialog
//-----------------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxPropertySheetDialog, wxDialog)
BEGIN_EVENT_TABLE(wxPropertySheetDialog, wxDialog)
EVT_ACTIVATE(wxPropertySheetDialog::OnActivate)
EVT_IDLE(wxPropertySheetDialog::OnIdle)
END_EVENT_TABLE()
bool wxPropertySheetDialog::Create(wxWindow* parent, wxWindowID id, const wxString& title,
const wxPoint& pos, const wxSize& sz, long style,
const wxString& name)
{
parent = GetParentForModalDialog(parent, style);
if (!wxDialog::Create(parent, id, title, pos, sz, style|wxCLIP_CHILDREN, name))
return false;
wxBoxSizer *topSizer = new wxBoxSizer( wxVERTICAL );
SetSizer(topSizer);
// This gives more space around the edges
m_innerSizer = new wxBoxSizer( wxVERTICAL );
#if defined(__SMARTPHONE__) || defined(__POCKETPC__)
m_sheetOuterBorder = 0;
#endif
topSizer->Add(m_innerSizer, 1, wxGROW|wxALL, m_sheetOuterBorder);
m_bookCtrl = CreateBookCtrl();
AddBookCtrl(m_innerSizer);
return true;
}
void wxPropertySheetDialog::Init()
{
m_sheetStyle = wxPROPSHEET_DEFAULT;
m_innerSizer = NULL;
m_bookCtrl = NULL;
m_sheetOuterBorder = 2;
m_sheetInnerBorder = 5;
}
// Layout the dialog, to be called after pages have been created
void wxPropertySheetDialog::LayoutDialog(int centreFlags)
{
#if !defined(__SMARTPHONE__) && !defined(__POCKETPC__)
GetSizer()->Fit(this);
GetSizer()->SetSizeHints(this);
if (centreFlags)
Centre(centreFlags);
#else
wxUnusedVar(centreFlags);
#endif
#if defined(__SMARTPHONE__)
if (m_bookCtrl)
m_bookCtrl->SetFocus();
#endif
}
// Creates the buttons, if any
void wxPropertySheetDialog::CreateButtons(int flags)
{
#ifdef __POCKETPC__
// keep system option status
const wxChar *optionName = wxT("wince.dialog.real-ok-cancel");
const int status = wxSystemOptions::GetOptionInt(optionName);
wxSystemOptions::SetOption(optionName,0);
#endif
wxSizer *buttonSizer = CreateButtonSizer(flags);
if( buttonSizer )
{
m_innerSizer->Add( buttonSizer, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT|wxRIGHT, 2);
m_innerSizer->AddSpacer(2);
}
#ifdef __POCKETPC__
// restore system option
wxSystemOptions::SetOption(optionName,status);
#endif
}
// Creates the book control
wxBookCtrlBase* wxPropertySheetDialog::CreateBookCtrl()
{
int style = wxCLIP_CHILDREN | wxBK_DEFAULT;
wxBookCtrlBase* bookCtrl = NULL;
#if wxUSE_NOTEBOOK
if (GetSheetStyle() & wxPROPSHEET_NOTEBOOK)
bookCtrl = new wxNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, style );
#endif
#if wxUSE_CHOICEBOOK
if (GetSheetStyle() & wxPROPSHEET_CHOICEBOOK)
bookCtrl = new wxChoicebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, style );
#endif
#if wxUSE_TOOLBOOK
#if defined(__WXMAC__) && wxUSE_TOOLBAR && wxUSE_BMPBUTTON
if (GetSheetStyle() & wxPROPSHEET_BUTTONTOOLBOOK)
bookCtrl = new wxToolbook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, style|wxTBK_BUTTONBAR );
else
#endif
if ((GetSheetStyle() & wxPROPSHEET_TOOLBOOK) || (GetSheetStyle() & wxPROPSHEET_BUTTONTOOLBOOK))
bookCtrl = new wxToolbook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, style );
#endif
#if wxUSE_LISTBOOK
if (GetSheetStyle() & wxPROPSHEET_LISTBOOK)
bookCtrl = new wxListbook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, style );
#endif
#if wxUSE_TREEBOOK
if (GetSheetStyle() & wxPROPSHEET_TREEBOOK)
bookCtrl = new wxTreebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, style );
#endif
if (!bookCtrl)
bookCtrl = new wxBookCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, style );
if (GetSheetStyle() & wxPROPSHEET_SHRINKTOFIT)
bookCtrl->SetFitToCurrentPage(true);
return bookCtrl;
}
// Adds the book control to the inner sizer.
void wxPropertySheetDialog::AddBookCtrl(wxSizer* sizer)
{
#if defined(__POCKETPC__) && wxUSE_NOTEBOOK
// The book control has to be sized larger than the dialog because of a border bug
// in WinCE
int borderSize = -2;
sizer->Add( m_bookCtrl, 1, wxGROW|wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxRIGHT, borderSize );
#else
sizer->Add( m_bookCtrl, 1, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, m_sheetInnerBorder );
#endif
}
void wxPropertySheetDialog::OnActivate(wxActivateEvent& event)
{
#if defined(__SMARTPHONE__)
// Attempt to focus the choice control: not yet working, but might
// be a step in the right direction. OnActivate overrides the default
// handler in toplevel.cpp that sets the focus for the first child of
// of the dialog (the choicebook).
if (event.GetActive())
{
wxChoicebook* choiceBook = wxDynamicCast(GetBookCtrl(), wxChoicebook);
if (choiceBook)
choiceBook->SetFocus();
}
else
#endif
event.Skip();
}
// Resize dialog if necessary
void wxPropertySheetDialog::OnIdle(wxIdleEvent& event)
{
event.Skip();
if ((GetSheetStyle() & wxPROPSHEET_SHRINKTOFIT) && GetBookCtrl())
{
int sel = GetBookCtrl()->GetSelection();
if (sel != -1 && sel != m_selectedPage)
{
GetBookCtrl()->InvalidateBestSize();
InvalidateBestSize();
SetSizeHints(-1, -1, -1, -1);
m_selectedPage = sel;
LayoutDialog(0);
}
}
}
// Override function in base
wxWindow* wxPropertySheetDialog::GetContentWindow() const
{
return GetBookCtrl();
}
#endif // wxUSE_BOOKCTRL
| 29.893617 | 109 | 0.644982 | gamekit-developers |
281f018a81b8c3bf1ac15a9d5b1d3c9ce5cb084f | 13,938 | cpp | C++ | swage/refine_high_order_mesh.cpp | CollinsEM/ELEMENTS | cdce322459d74b0723878e650360f135f71dd1d8 | [
"BSD-3-Clause"
] | 14 | 2020-07-21T21:54:41.000Z | 2022-01-04T15:44:02.000Z | swage/refine_high_order_mesh.cpp | CollinsEM/ELEMENTS | cdce322459d74b0723878e650360f135f71dd1d8 | [
"BSD-3-Clause"
] | 2 | 2021-05-05T14:34:21.000Z | 2021-12-01T01:53:32.000Z | swage/refine_high_order_mesh.cpp | CollinsEM/ELEMENTS | cdce322459d74b0723878e650360f135f71dd1d8 | [
"BSD-3-Clause"
] | 8 | 2020-11-25T21:37:06.000Z | 2022-02-01T22:02:18.000Z | #include "lagrange_polynomials.h"
#include "swage.h"
#include "lagrange_element.h"
#include "point_distributions.h"
namespace swage {
void refine_high_order_mesh(mesh_t &input_mesh, mesh_t &mesh) {
// High order mesh parameters
const int dim = 3;
int elem_order = input_mesh.elem_order();
int num_elems = input_mesh.num_elems();
int num_verts_1d = elem_order + 1;
int num_verts = pow(num_verts_1d, dim);
int num_sub_1d = elem_order*2;
int num_subcells_per_elem = pow((num_sub_1d), dim);
int num_g_pts_1d = 2*elem_order + 1;
int num_g_pts = pow(num_g_pts_1d, dim);
// ------------------------------------------------------------------------
// Initialize Element and cell information in on high order mesh
// ------------------------------------------------------------------------
mesh.init_element(elem_order, dim, num_elems);
mesh.init_cells(num_elems*num_subcells_per_elem);
mesh.init_gauss_pts();
// ------------------------------------------------------------------------
// Interpolate quadrature points in each element of input mesh
// ------------------------------------------------------------------------
// Initialize temporary array to store node coordinates
auto g_points_in_mesh = CArray<Real>(num_elems*num_g_pts, dim);
// Assume vertices in reference element of input mesh are equispaced
CArray<Real> vert_coords_1d(num_verts_1d);
Real lower_bound = -1.0, upper_bound = 1.0;
equispaced_points(num_verts_1d, lower_bound, upper_bound,
vert_coords_1d.pointer());
// Create reference element
LagrangeElement<Real> elem(SizeType(elem_order),
vert_coords_1d.pointer());
// Assume Lobatto nodes for quadrature
CArray<Real> lobatto_nodes(num_g_pts_1d);
lobatto_nodes_1D_tmp(lobatto_nodes, num_g_pts_1d);
// Loop over elements and...
CArray<Real> vert_x_coords(num_verts);
CArray<Real> vert_y_coords(num_verts);
CArray<Real> vert_z_coords(num_verts);
int g_point_count = 0;
for (int elem_gid = 0; elem_gid < num_elems; elem_gid++) {
// ...get spatial coordinates of vertices from input mesh
for (int vert_lid = 0; vert_lid < num_verts; vert_lid++) {
vert_x_coords(vert_lid) = input_mesh.node_coords(
input_mesh.nodes_in_elem(elem_gid, vert_lid), 0);
vert_y_coords(vert_lid) = input_mesh.node_coords(
input_mesh.nodes_in_elem(elem_gid, vert_lid), 1);
vert_z_coords(vert_lid) = input_mesh.node_coords(
input_mesh.nodes_in_elem(elem_gid, vert_lid), 2);
}
// Loop over quadrature points and ...
for (int node_lid = 0; node_lid < num_g_pts; node_lid++) {
// ...interpolate each quadrature point
// Get IJK coordinates of quadrature point
const SizeType num_rad = 3;
SizeType radices[num_rad] = {SizeType(num_g_pts_1d),
SizeType(num_g_pts_1d), SizeType(num_g_pts_1d)};
SizeType ijk[num_rad];
common::base_10_to_mixed_radix(num_rad, radices, node_lid, ijk);
// Get reference coordinates of quadrature point
Real X[3];
X[0] = lobatto_nodes(ijk[0]);
X[1] = lobatto_nodes(ijk[1]);
X[2] = lobatto_nodes(ijk[2]);
// Interpolate
g_points_in_mesh(g_point_count, 0) = elem.eval_approx(
vert_x_coords.pointer(), X);
g_points_in_mesh(g_point_count, 1) = elem.eval_approx(
vert_y_coords.pointer(), X);
g_points_in_mesh(g_point_count, 2) = elem.eval_approx(
vert_z_coords.pointer(), X);
g_point_count++;
}
}
// ------------------------------------------------------------------------
// Hash x, y, and x coordinates to eliminate double counted points for
// node index.
// ------------------------------------------------------------------------
Real pos_max[dim];
Real pos_min[dim];
for (int i = 0; i < dim; i++) {
pos_max[i] = NUM_MIN;
pos_min[i] = NUM_MAX;
}
// Find the minimum and maximum vertex coordinates
for (int vert_id = 0; vert_id < input_mesh.num_nodes(); vert_id++) {
Real position[3];
for(int i = 0; i < dim; i++){
position[i] = input_mesh.node_coords(vert_id, i);
pos_max[i] = fmax(pos_max[i], position[i]);
pos_min[i] = fmin(pos_min[i], position[i]);
}
}
// Get minimum/maximum distance between any two vertices in the mesh
Real min_dist_elem = NUM_MAX;
Real max_dist_elem = 0.0;
for (int elem_id = 0; elem_id < input_mesh.num_elems(); elem_id++) {
// Loop over combinations of two vertices in element
for (int j = 0; j < num_verts_1d; j++) { // index of first vertex
for (int i = j + 1; i < num_verts_1d; i++) { // index of second vertex
// Get coordinates of vertices
Real x1 = input_mesh.node_coords(input_mesh.nodes_in_elem(elem_id, j), 0);
Real y1 = input_mesh.node_coords(input_mesh.nodes_in_elem(elem_id, j), 1);
Real z1 = input_mesh.node_coords(input_mesh.nodes_in_elem(elem_id, j), 2);
Real x2 = input_mesh.node_coords(input_mesh.nodes_in_elem(elem_id, i), 0);
Real y2 = input_mesh.node_coords(input_mesh.nodes_in_elem(elem_id, i), 1);
Real z2 = input_mesh.node_coords(input_mesh.nodes_in_elem(elem_id, i), 2);
// Compute distance between vertices
Real dist = std::sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)
+ (z2 - z1)*(z1 - z1));
// Compare distance to current minimum/maximum
min_dist_elem = std::min(min_dist_elem, dist);
max_dist_elem = std::max(max_dist_elem, dist);
}
}
}
Real min_dist = min_dist_elem;
Real max_dist = max_dist_elem;
std::cout << "minimum distance between vertices: " << min_dist << std::endl;
// Define hashing distance (size of bins)
Real num_inter = elem_order; // intervals between vertices in 1D
Real h = min_dist/(7.0*(num_inter)); // subdivisions between any two points
std::cout << "hashing distance: " << h << std::endl;
// Calculate number of bins in each dimension
Real float_bins[3];
for (int i = 0; i < dim; i++) {
// TODO ask Jacob about reasoning here
float_bins[i] = fmax(1e-16, (pos_max[i] - pos_min[i] + 1.0 + 1e-14)/h); //1e-14
}
// Convert # of bins to ints
int int_bins[3];
for(int i = 0; i < dim; i++){
// TODO ask Jacob about why typecast instead of round
int_bins[i] = (int)float_bins[i];
}
Real float_idx[3]; // float values for index
int int_idx[3]; // int values for index
int key; // hash key
int max_key = 0; // larges hash key value
// Getting hash keys from x,y,z positions and largest key value
int h_keys[num_g_pts*num_elems];
for (int g_pt = 0; g_pt < num_g_pts*num_elems; g_pt++) {
Real coords[3];
for (int i = 0; i < dim; i++) {
coords[i] = g_points_in_mesh(g_pt, i);
float_idx[i] = fmax(1e-16, (coords[i] - pos_min[i] + 1e-14)/(h));
int_idx[i] = (int)float_idx[i];
}
// i + j*num_x + k*num_x*num_y
if (dim == 2) {
key = int_idx[0] + int_idx[1]*int_bins[0];
} else {
key = int_idx[0]
+ int_idx[1]*int_bins[0]
+ int_idx[2]*int_bins[0]*int_bins[1];
}
h_keys[g_pt] = key;
max_key = std::max(max_key, key);
}
// Allocating array for hash table
// TODO Ask Jacob why max_key plus 10?
// TODO Ask Jacob if he's ever checked how much memory this takes up
CArray<int> hash(max_key+10);
// Initializing values at key positions to zero
for (int g_pt = 0; g_pt < num_g_pts*num_elems; g_pt++) {
hash(h_keys[g_pt]) = 0;
}
// Temporary array for gauss->node map and node->gauss map
CArray <int> node_to_gauss_map;
node_to_gauss_map = CArray <int> (num_g_pts*num_elems);
// counters
int num_nodes = 0;
int node_gid = 0;
// walk over all gauss points
for (int g_pt = 0; g_pt < num_g_pts*num_elems; g_pt++) {
// Subtract 1 every time the index is touched
if (hash(h_keys[g_pt]) <= 0) {
hash(h_keys[g_pt]) += -1;
}
// If this is the first time the index is touched add to
// node_to_gauss_map (WARNING: ONLY THE FIRST TIME IS COUNTED)
// and index the number of nodes
if (hash(h_keys[g_pt]) == -1) {
node_to_gauss_map(num_nodes) = g_pt;
num_nodes++;
}
// If this index has been touched before, replace hash value with
// node id
if (hash(h_keys[g_pt]) <= -1) {
hash(h_keys[g_pt]) = node_gid;
// gauss_node_map[g_pt] = node_gid;
mesh.node_in_gauss(g_pt) = node_gid;
node_gid++;
// If hash value is positive, then the value is the index
// for the single node associated with this g_point
} else {
// gauss_node_map[g_pt] = hash[h_keys[g_pt]];
mesh.node_in_gauss(g_pt) = hash(h_keys[g_pt]);
}
}
// Initialize nodes on sub_mesh
mesh.init_nodes(num_nodes);
// ---------------------------------------------------------------------------
// Write position to nodes
// ---------------------------------------------------------------------------
for (int node_gid = 0; node_gid < num_nodes; node_gid++) {
for (int i = 0; i < dim; i++) {
mesh.node_coords(node_gid, i) = g_points_in_mesh(node_to_gauss_map(node_gid), i);
}
}
// ---------------------------------------------------------------------------
// Get gauss points and nodes associated with each cell,
// as well as the cells associated with each element
// ---------------------------------------------------------------------------
// auto gauss_id_in_cell = CArray<int> (sub_mesh.num_cells(), num_sub_1d*num_sub_1d*num_sub_1d, 8);
int sub_in_elem = num_sub_1d*num_sub_1d*num_sub_1d;
// gauss_in_cell
int p0, p1, p2, p3, p4, p5, p6, p7;
p0 = p1 = p2 = p3 = p4 = p5 = p6 = p7 = 0;
int num_1d = num_g_pts_1d;
for(int elem_gid = 0; elem_gid < num_elems; elem_gid++){
for(int k = 0; k < num_sub_1d; k++){
for(int j = 0; j < num_sub_1d; j++){
for(int i = 0; i < num_sub_1d; i++){
// The p# point to a global gauss point index before double counting
p0 = (i) + (j)*num_1d + (k)*num_1d*num_1d;
p1 = (i+1) + (j)*num_1d + (k)*num_1d*num_1d;
p2 = (i) + (j+1)*num_1d + (k)*num_1d*num_1d;
p3 = (i+1) + (j+1)*num_1d + (k)*num_1d*num_1d;
p4 = (i) + (j)*num_1d + (k+1)*num_1d*num_1d;
p5 = (i+1) + (j)*num_1d + (k+1)*num_1d*num_1d;
p6 = (i) + (j+1)*num_1d + (k+1)*num_1d*num_1d;
p7 = (i+1) + (j+1)*num_1d + (k+1)*num_1d*num_1d;
p0 += num_1d*num_1d*num_1d*(elem_gid);
p1 += num_1d*num_1d*num_1d*(elem_gid);
p2 += num_1d*num_1d*num_1d*(elem_gid);
p3 += num_1d*num_1d*num_1d*(elem_gid);
p4 += num_1d*num_1d*num_1d*(elem_gid);
p5 += num_1d*num_1d*num_1d*(elem_gid);
p6 += num_1d*num_1d*num_1d*(elem_gid);
p7 += num_1d*num_1d*num_1d*(elem_gid);
int cell_lid = i + j*num_sub_1d + k*num_sub_1d*num_sub_1d;
int cell_gid = cell_lid + num_sub_1d*num_sub_1d*num_sub_1d*(elem_gid);
mesh.gauss_in_cell(cell_gid, 0) = p0;
mesh.gauss_in_cell(cell_gid, 1) = p1;
mesh.gauss_in_cell(cell_gid, 2) = p2;
mesh.gauss_in_cell(cell_gid, 3) = p3;
mesh.gauss_in_cell(cell_gid, 4) = p4;
mesh.gauss_in_cell(cell_gid, 5) = p5;
mesh.gauss_in_cell(cell_gid, 6) = p6;
mesh.gauss_in_cell(cell_gid, 7) = p7;
mesh.cells_in_elem(elem_gid, cell_lid) = cell_gid;
mesh.elems_in_cell(cell_gid) = elem_gid;
}
}
}
}
int cell_gid = 0;
int p[8];
// for each cell read the list of associated nodes
for(int elem = 0; elem < num_elems; elem++){
for(int k = 0; k < num_sub_1d; k++){
for(int j = 0; j < num_sub_1d; j++){
for(int i = 0; i < num_sub_1d; i++){
// The p# point to a global gauss point index before double counting
p[0] = (i) + (j)*num_1d + (k)*num_1d*num_1d;
p[1] = (i+1) + (j)*num_1d + (k)*num_1d*num_1d;
p[2] = (i) + (j+1)*num_1d + (k)*num_1d*num_1d;
p[3] = (i+1) + (j+1)*num_1d + (k)*num_1d*num_1d;
p[4] = (i) + (j)*num_1d + (k+1)*num_1d*num_1d;
p[5] = (i+1) + (j)*num_1d + (k+1)*num_1d*num_1d;
p[6] = (i) + (j+1)*num_1d + (k+1)*num_1d*num_1d;
p[7] = (i+1) + (j+1)*num_1d + (k+1)*num_1d*num_1d;
for (int idx = 0; idx < 8; idx++){
p[idx] += num_1d*num_1d*num_1d*(elem);
}
for (int node_lid = 0; node_lid < 8; node_lid++){
mesh.nodes_in_cell(cell_gid, node_lid) = mesh.node_in_gauss(p[node_lid]);
}
// incriment global index for cell
cell_gid++;
}
}
}
}
mesh.build_connectivity();
}
}
| 37.67027 | 103 | 0.531784 | CollinsEM |
2820c3abc86d471553bdf32f5da651987802a270 | 1,090 | cpp | C++ | competitive programming/leetcode/222. Count Complete Tree Nodes.cpp | kashyap99saksham/Code | 96658d0920eb79c007701d2a3cc9dbf453d78f96 | [
"MIT"
] | 16 | 2020-06-02T19:22:45.000Z | 2022-02-05T10:35:28.000Z | competitive programming/leetcode/222. Count Complete Tree Nodes.cpp | codezoned/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | null | null | null | competitive programming/leetcode/222. Count Complete Tree Nodes.cpp | codezoned/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | 2 | 2020-08-27T17:40:06.000Z | 2022-02-05T10:33:52.000Z | Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example:
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void countNodesUtil(TreeNode* root, int &cnt){
if(!root) return;
countNodesUtil(root->left, cnt);
cnt++;
countNodesUtil(root->right, cnt);
}
int countNodes(TreeNode* root) {
int cnt=0;
countNodesUtil(root, cnt);
return cnt;
}
};
| 20.566038 | 213 | 0.619266 | kashyap99saksham |
2821754670cab7193162fc5bb1e60143b4757972 | 433 | cpp | C++ | Asked questions/tempCodeRunnerFile.cpp | SeekerNik/code | e36105361daffac2b6e48ab63f3b9d79120f6310 | [
"MIT"
] | null | null | null | Asked questions/tempCodeRunnerFile.cpp | SeekerNik/code | e36105361daffac2b6e48ab63f3b9d79120f6310 | [
"MIT"
] | null | null | null | Asked questions/tempCodeRunnerFile.cpp | SeekerNik/code | e36105361daffac2b6e48ab63f3b9d79120f6310 | [
"MIT"
] | null | null | null | void checkMagazine(vector<string> magazine, vector<string> note)
{
int count = 0;
for (int i = 0; i < magazine.size(); i++)
{
for (int j = 0; j < note.size(); j++)
{
if (magazine[i] == note[i])
{
count++;
}
}
}
if (count == note.size())
{
cout << "Yes";
}
else
{
cout << "No";
}
} | 19.681818 | 65 | 0.357968 | SeekerNik |
2821a82c8df46da9444d8a8b697bf8eb7dbd57cd | 1,470 | cpp | C++ | src/gui/css-parser/driver.cpp | lii-enac/djnn-cpp | f27c5ba3186186ee22c93ae91c16063556e929b6 | [
"BSD-2-Clause"
] | 4 | 2018-09-11T14:27:57.000Z | 2019-12-16T21:06:26.000Z | src/gui/css-parser/driver.cpp | lii-enac/djnn-cpp | f27c5ba3186186ee22c93ae91c16063556e929b6 | [
"BSD-2-Clause"
] | null | null | null | src/gui/css-parser/driver.cpp | lii-enac/djnn-cpp | f27c5ba3186186ee22c93ae91c16063556e929b6 | [
"BSD-2-Clause"
] | 2 | 2018-06-11T14:15:30.000Z | 2019-01-09T12:23:35.000Z | /*
* djnn v2
*
* The copyright holders for the contents of this file are:
* Ecole Nationale de l'Aviation Civile, France (2020)
* See file "license.terms" for the rights and conditions
* defined by copyright holders.
*
*
* Contributors:
* Mathieu Magnaudet <mathieu.magnaudet@enac.fr>
*
*/
#include "core/utils/iostream.h"
#include <fstream>
#include <sstream>
#include "driver.h"
#include "scanner.h"
namespace css
{
using namespace djnn;
Driver::Driver () :
_lexer (nullptr), _root (nullptr)
{
}
bool
Driver::parse_stream (std::istream& in, const string& name, FatProcess *p)
{
_root = p;
stream = name.c_str();
Scanner scanner (&in);
this->_lexer = &scanner;
Parser parser (*this);
return (parser.parse () == 0);
}
bool
Driver::parse_file (const string& filename, FatProcess *p)
{
std::ifstream in (filename.c_str ());
if (!in.good ())
return false;
return parse_stream (in, filename, p);
}
bool
Driver::parse_string (const string& input, const string& sname, FatProcess *p)
{
std::istringstream iss (input.c_str());
return parse_stream (iss, sname, p);
}
FatProcess*
Driver::get_parent ()
{
return _root;
}
void
Driver::error (const class location& l, const djnn::string& m)
{
std::cerr << l << ": " << m << std::endl;
}
void
Driver::error (const djnn::string& m)
{
std::cerr << m << std::endl;
}
}
| 17.926829 | 80 | 0.614286 | lii-enac |
2821ae11d5924bc784e86b6221c14f4a445c5367 | 356 | hpp | C++ | src/util/unicode/case.hpp | lu-plus-plus/ama | 18c9623c0f6d5d0cb26bd0717b40ea3b5f1ce5e8 | [
"BSD-2-Clause"
] | 24 | 2022-01-06T20:26:42.000Z | 2022-02-18T07:56:44.000Z | src/util/unicode/case.hpp | lu-plus-plus/ama | 18c9623c0f6d5d0cb26bd0717b40ea3b5f1ce5e8 | [
"BSD-2-Clause"
] | null | null | null | src/util/unicode/case.hpp | lu-plus-plus/ama | 18c9623c0f6d5d0cb26bd0717b40ea3b5f1ce5e8 | [
"BSD-2-Clause"
] | 4 | 2022-01-06T20:26:44.000Z | 2022-01-14T06:59:48.000Z | #ifndef _CASE_JCH_HPP
#define _CASE_JCH_HPP
#include <string>
#include "../jc_array.h"
#include <functional>
/*#pragma add("jc_files", "./case.jc");*/
namespace unicode {
std::string toUpper(std::span<char> s);
std::string toLower(std::span<char> s);
std::string toUpperASCII(std::span<char> s);
std::string toLowerASCII(std::span<char> s);
};
#endif
| 23.733333 | 45 | 0.702247 | lu-plus-plus |
28230aadfa00778f8a72451c887bc5bc1ebc4ee5 | 319 | cpp | C++ | CSES/Generate.cpp | pratik8696/DSA | 049a76b6e2445bb5de2e87f3755038609006c06a | [
"MIT"
] | 2 | 2021-09-27T14:12:28.000Z | 2021-09-28T03:35:46.000Z | CSES/Generate.cpp | pratik8696/DSA | 049a76b6e2445bb5de2e87f3755038609006c06a | [
"MIT"
] | 2 | 2021-09-30T09:07:11.000Z | 2021-10-17T18:42:34.000Z | CSES/Generate.cpp | pratik8696/DSA | 049a76b6e2445bb5de2e87f3755038609006c06a | [
"MIT"
] | null | null | null | #include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
char s[1000];
scanf("%s", &s);
switch (s[n - 1])
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("Vowel Found");
break;
default:
printf("Consonants Found");
}
return 0;
} | 13.869565 | 35 | 0.429467 | pratik8696 |
28292efcdb7fb42a13e4a61b49c387009c8bf158 | 2,404 | cpp | C++ | tests/Unit/PointwiseFunctions/Hydro/Test_SpecificEnthalpy.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 117 | 2017-04-08T22:52:48.000Z | 2022-03-25T07:23:36.000Z | tests/Unit/PointwiseFunctions/Hydro/Test_SpecificEnthalpy.cpp | GitHimanshuc/spectre | 4de4033ba36547113293fe4dbdd77591485a4aee | [
"MIT"
] | 3,177 | 2017-04-07T21:10:18.000Z | 2022-03-31T23:55:59.000Z | tests/Unit/PointwiseFunctions/Hydro/Test_SpecificEnthalpy.cpp | geoffrey4444/spectre | 9350d61830b360e2d5b273fdd176dcc841dbefb0 | [
"MIT"
] | 85 | 2017-04-07T19:36:13.000Z | 2022-03-01T10:21:00.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Framework/TestingFramework.hpp"
#include <limits>
#include <string>
#include "DataStructures/DataBox/DataBox.hpp"
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "Framework/CheckWithRandomValues.hpp"
#include "Framework/SetupLocalPythonEnvironment.hpp"
#include "Helpers/DataStructures/DataBox/TestHelpers.hpp"
#include "PointwiseFunctions/Hydro/SpecificEnthalpy.hpp"
#include "PointwiseFunctions/Hydro/Tags.hpp"
#include "Utilities/TMPL.hpp"
namespace {
template <typename DataType>
void test_relativistic_specific_enthalpy(const DataType& used_for_size) {
pypp::check_with_random_values<1>(
static_cast<Scalar<DataType> (*)(const Scalar<DataType>&,
const Scalar<DataType>&,
const Scalar<DataType>&)>(
&hydro::relativistic_specific_enthalpy<DataType>),
"TestFunctions", "relativistic_specific_enthalpy", {{{0.01, 1.0}}},
used_for_size);
}
} // namespace
namespace hydro {
SPECTRE_TEST_CASE("Unit.PointwiseFunctions.Hydro.SpecificEnthalpy",
"[Unit][Hydro]") {
pypp::SetupLocalPythonEnvironment local_python_env{
"PointwiseFunctions/Hydro"};
test_relativistic_specific_enthalpy(
std::numeric_limits<double>::signaling_NaN());
test_relativistic_specific_enthalpy(DataVector(5));
// Check compute item works correctly in DataBox
TestHelpers::db::test_compute_tag<Tags::SpecificEnthalpyCompute<DataVector>>(
"SpecificEnthalpy");
Scalar<DataVector> rest_mass_density{{{DataVector{5, 0.2}}}};
Scalar<DataVector> specific_internal_energy{{{DataVector{5, 0.23}}}};
Scalar<DataVector> pressure{{{DataVector{5, 0.234}}}};
const auto box =
db::create<db::AddSimpleTags<Tags::RestMassDensity<DataVector>,
Tags::SpecificInternalEnergy<DataVector>,
Tags::Pressure<DataVector>>,
db::AddComputeTags<Tags::SpecificEnthalpyCompute<DataVector>>>(
rest_mass_density, specific_internal_energy, pressure);
CHECK(db::get<Tags::SpecificEnthalpy<DataVector>>(box) ==
relativistic_specific_enthalpy(rest_mass_density,
specific_internal_energy, pressure));
}
} // namespace hydro
| 39.409836 | 80 | 0.697587 | nilsvu |
2829428881fb2d79e868bfd52c804134db20e9d8 | 4,923 | cpp | C++ | Source/Plugins/bsfVulkanRenderAPI/Managers/BsVulkanTextureManager.cpp | pgruenbacher/bsf | 9bbac75ca4cc445cd26b435f74465ad91d3e528e | [
"MIT"
] | 2 | 2019-07-08T17:26:25.000Z | 2019-10-13T19:15:28.000Z | Source/Plugins/bsfVulkanRenderAPI/Managers/BsVulkanTextureManager.cpp | REGoth-project/bsf | e176800d1cb9e71b7be8a28bdae935ed9ddd1de4 | [
"MIT"
] | null | null | null | Source/Plugins/bsfVulkanRenderAPI/Managers/BsVulkanTextureManager.cpp | REGoth-project/bsf | e176800d1cb9e71b7be8a28bdae935ed9ddd1de4 | [
"MIT"
] | 4 | 2019-06-23T09:55:47.000Z | 2019-07-08T17:23:05.000Z | //************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#include "Managers/BsVulkanTextureManager.h"
#include "BsVulkanTexture.h"
#include "BsVulkanRenderTexture.h"
#include "BsVulkanResource.h"
#include "BsVulkanUtility.h"
namespace bs
{
struct DummyTexFormat
{
TextureType type;
int arraySize;
int width;
int height;
int depth;
};
const static DummyTexFormat DummyTexTypes[] =
{
{ TEX_TYPE_1D, 1, 2, 1, 1 },
{ TEX_TYPE_1D, 2, 2, 1, 1 },
{ TEX_TYPE_2D, 1, 2, 2, 1 },
{ TEX_TYPE_2D, 2, 2, 2, 1 },
{ TEX_TYPE_3D, 1, 2, 2, 2 },
{ TEX_TYPE_CUBE_MAP, 1, 2, 2, 1 },
{ TEX_TYPE_CUBE_MAP, 2, 2, 2, 1 }
};
SPtr<RenderTexture> VulkanTextureManager::createRenderTextureImpl(const RENDER_TEXTURE_DESC& desc)
{
VulkanRenderTexture* tex = new (bs_alloc<VulkanRenderTexture>()) VulkanRenderTexture(desc);
return bs_core_ptr<VulkanRenderTexture>(tex);
}
PixelFormat VulkanTextureManager::getNativeFormat(TextureType ttype, PixelFormat format, int usage, bool hwGamma)
{
PixelUtil::checkFormat(format, ttype, usage);
if (ct::VulkanUtility::getPixelFormat(format, hwGamma) == VK_FORMAT_UNDEFINED)
return PF_RGBA8;
return format;
}
namespace ct
{
void VulkanTextureManager::onStartUp()
{
TextureManager::onStartUp();
int idx = 0;
for(auto& entry : DummyTexTypes)
{
SPtr<PixelData> pixelData = PixelData::create(entry.width, entry.height, entry.depth, PF_RGBA8);
for(int depth = 0; depth < entry.depth; depth++)
for(int height = 0; height < entry.height; height++)
for(int width = 0; width < entry.width; width++)
pixelData->setColorAt(Color::White, width, height, depth);
TEXTURE_DESC desc;
desc.type = entry.type;
desc.width = entry.width;
desc.height = entry.height;
desc.depth = entry.depth;
desc.numArraySlices = entry.arraySize;
desc.format = PF_RGBA8;
desc.usage = TU_STATIC | TU_MUTABLEFORMAT;
mDummyReadTextures[idx] = std::static_pointer_cast<VulkanTexture>(createTexture(desc));
mDummyReadTextures[idx]->writeData(*pixelData);
desc.usage = TU_LOADSTORE;
mDummyStorageTextures[idx] = std::static_pointer_cast<VulkanTexture>(createTexture(desc));
idx++;
}
}
VulkanTexture* VulkanTextureManager::getDummyTexture(GpuParamObjectType type) const
{
switch(type)
{
case GPOT_TEXTURE2DMS:
case GPOT_TEXTURE2D:
return mDummyReadTextures[2].get();
case GPOT_RWTEXTURE2D:
case GPOT_RWTEXTURE2DMS:
return mDummyStorageTextures[2].get();
case GPOT_TEXTURECUBE:
return mDummyReadTextures[5].get();
case GPOT_TEXTURECUBEARRAY:
return mDummyReadTextures[6].get();
case GPOT_TEXTURE2DARRAY:
case GPOT_TEXTURE2DMSARRAY:
return mDummyReadTextures[3].get();
case GPOT_RWTEXTURE2DARRAY:
case GPOT_RWTEXTURE2DMSARRAY:
return mDummyStorageTextures[3].get();
case GPOT_TEXTURE3D:
return mDummyReadTextures[4].get();
case GPOT_RWTEXTURE3D:
return mDummyStorageTextures[4].get();
case GPOT_TEXTURE1D:
return mDummyReadTextures[0].get();
case GPOT_TEXTURE1DARRAY:
return mDummyReadTextures[1].get();
case GPOT_RWTEXTURE1D:
return mDummyStorageTextures[0].get();
case GPOT_RWTEXTURE1DARRAY:
return mDummyStorageTextures[1].get();
default:
return nullptr;
}
}
VkFormat VulkanTextureManager::getDummyViewFormat(GpuBufferFormat format)
{
switch(format)
{
case BF_16X1F:
case BF_32X1F:
return VK_FORMAT_R32_SFLOAT;
case BF_16X2F:
case BF_32X2F:
return VK_FORMAT_R16G16_UNORM;
case BF_32X3F:
case BF_32X4F:
case BF_16X4F:
return VK_FORMAT_R8G8B8A8_UNORM;
case BF_16X1U:
case BF_32X1U:
return VK_FORMAT_R32_UINT;
case BF_16X2U:
case BF_32X2U:
return VK_FORMAT_R16G16_UINT;
case BF_32X3U:
case BF_32X4U:
case BF_16X4U:
return VK_FORMAT_R8G8B8A8_UINT;
case BF_16X1S:
case BF_32X1S:
return VK_FORMAT_R32_SINT;
case BF_16X2S:
case BF_32X2S:
return VK_FORMAT_R16G16_SINT;
case BF_32X3S:
case BF_32X4S:
case BF_16X4S:
return VK_FORMAT_R8G8B8A8_SINT;
default:
return VK_FORMAT_UNDEFINED;
}
}
SPtr<Texture> VulkanTextureManager::createTextureInternal(const TEXTURE_DESC& desc,
const SPtr<PixelData>& initialData, GpuDeviceFlags deviceMask)
{
VulkanTexture* tex = new (bs_alloc<VulkanTexture>()) VulkanTexture(desc, initialData, deviceMask);
SPtr<VulkanTexture> texPtr = bs_shared_ptr<VulkanTexture>(tex);
texPtr->_setThisPtr(texPtr);
return texPtr;
}
SPtr<RenderTexture> VulkanTextureManager::createRenderTextureInternal(const RENDER_TEXTURE_DESC& desc,
UINT32 deviceIdx)
{
SPtr<VulkanRenderTexture> texPtr = bs_shared_ptr_new<VulkanRenderTexture>(desc, deviceIdx);
texPtr->_setThisPtr(texPtr);
return texPtr;
}
}
} | 27.502793 | 124 | 0.719683 | pgruenbacher |
282a78990fe955fe99e900487d29333fcf725d06 | 7,963 | cpp | C++ | src/lib/OpenEXR/ImfStdIO.cpp | msercheli/openexr | 9912f6b3886f6c695547747d70e19b98c0e38d59 | [
"BSD-3-Clause"
] | 517 | 2018-08-11T02:18:47.000Z | 2022-03-27T05:31:40.000Z | src/lib/OpenEXR/ImfStdIO.cpp | msercheli/openexr | 9912f6b3886f6c695547747d70e19b98c0e38d59 | [
"BSD-3-Clause"
] | 391 | 2018-07-31T21:28:52.000Z | 2022-03-28T16:51:18.000Z | src/lib/OpenEXR/ImfStdIO.cpp | msercheli/openexr | 9912f6b3886f6c695547747d70e19b98c0e38d59 | [
"BSD-3-Clause"
] | 189 | 2018-12-22T15:39:26.000Z | 2022-03-16T17:03:20.000Z | //
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) Contributors to the OpenEXR Project.
//
//-----------------------------------------------------------------------------
//
// Low-level file input and output for OpenEXR
// based on C++ standard iostreams.
//
//-----------------------------------------------------------------------------
#include <ImfStdIO.h>
#include "Iex.h"
#include <errno.h>
#ifdef _WIN32
# define VC_EXTRALEAN
# include <windows.h>
# include <string.h>
# include <io.h>
# include <fcntl.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <share.h>
# include <string>
# include <iostream>
#endif
using namespace std;
#include "ImfNamespace.h"
OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER
namespace {
#ifdef _WIN32
wstring WidenFilename (const char *filename)
{
wstring ret;
int fnlen = static_cast<int>( strlen(filename) );
int len = MultiByteToWideChar(CP_UTF8, 0, filename, fnlen, NULL, 0 );
if (len > 0)
{
ret.resize(len);
MultiByteToWideChar(CP_UTF8, 0, filename, fnlen, &ret[0], len);
}
return ret;
}
# if defined(__GLIBCXX__) && !(defined(_GLIBCXX_HAVE_WFOPEN) && defined(_GLIBCXX_USE_WCHAR_T))
# define USE_CUSTOM_WIDE_OPEN 1
# endif
# ifdef USE_CUSTOM_WIDE_OPEN
template <typename CharT, typename TraitsT>
class InjectFilebuf : public basic_filebuf<CharT, TraitsT>
{
public:
using base_filebuf = basic_filebuf<CharT, TraitsT>;
inline base_filebuf* wide_open (int fd, ios_base::openmode m)
{
// sys_open will do an fdopen internally which will then clean up the fd upon close
this->_M_file.sys_open (fd, m);
if (this->is_open ())
{
// reset the internal state, these members are consistent between gcc versions 4.3 - 9
// but at 9, the wfopen stuff should become available, such that this will no longer be
// active
this->_M_allocate_internal_buffer ();
this->_M_mode = m;
this->_M_reading = false;
this->_M_writing = false;
this->_M_set_buffer (-1);
this->_M_state_last = this->_M_state_cur = this->_M_state_beg;
// we don't ever seek to end or anything, so should be done at this point...
return this;
}
return nullptr;
}
};
# endif // USE_CUSTOM_WIDE_OPEN
ifstream*
make_ifstream (const char *filename)
{
wstring wfn = WidenFilename (filename);
# ifdef USE_CUSTOM_WIDE_OPEN
int fd;
errno_t e = _wsopen_s (
&fd, wfn.c_str (), _O_RDONLY|_O_BINARY, _SH_DENYNO, _S_IREAD | _S_IWRITE);
if (e != 0)
{
char errbuf[4096];
strerror_s (errbuf, 4096, e);
errno = e;
throw IEX_NAMESPACE::ErrnoExc (
"Unable to open input filestream: " + std::string (errbuf));
}
ifstream* ret = new ifstream;
using CharT = ifstream::char_type;
using TraitsT = ifstream::traits_type;
if (static_cast<InjectFilebuf<CharT, TraitsT>*> (ret->rdbuf ())
->wide_open (fd, ios_base::in | ios_base::binary))
{
ret->clear();
ret->setstate(ios_base::goodbit);
}
# else
ifstream* ret = new ifstream(wfn.c_str (), ios_base::in | ios_base::binary);
# endif
return ret;
}
ofstream*
make_ofstream (const char* filename)
{
wstring wfn = WidenFilename (filename);
# ifdef USE_CUSTOM_WIDE_OPEN
int fd;
errno_t e = _wsopen_s (
&fd,
wfn.c_str (),
_O_WRONLY | _O_CREAT | _O_BINARY,
_SH_DENYNO,
_S_IREAD | _S_IWRITE);
if (e != 0)
{
char errbuf[4096];
strerror_s (errbuf, 4096, e);
errno = e;
throw IEX_NAMESPACE::ErrnoExc (
"Unable to open output filestream: " + std::string(errbuf));
}
ofstream* ret = new ofstream;
using CharT = ifstream::char_type;
using TraitsT = ifstream::traits_type;
if (static_cast<InjectFilebuf<CharT, TraitsT>*> (ret->rdbuf ())
->wide_open (fd, ios_base::out | ios_base::binary))
{
ret->clear ();
ret->setstate (ios_base::goodbit);
}
# else
ofstream *ret = new ofstream (wfn.c_str (), ios_base::binary);
# endif
return ret;
}
#else
ifstream*
make_ifstream (const char* filename)
{
return new ifstream (filename, ios_base::binary);
}
inline ofstream*
make_ofstream (const char* filename)
{
return new ofstream (filename, ios_base::binary);
}
#endif
void
clearError ()
{
errno = 0;
}
bool
checkError (istream &is, streamsize expected = 0)
{
if (!is)
{
if (errno)
IEX_NAMESPACE::throwErrnoExc();
if (is.gcount() < expected)
{
THROW (IEX_NAMESPACE::InputExc, "Early end of file: read " << is.gcount()
<< " out of " << expected << " requested bytes.");
}
return false;
}
return true;
}
void
checkError (ostream &os)
{
if (!os)
{
if (errno)
IEX_NAMESPACE::throwErrnoExc();
throw IEX_NAMESPACE::ErrnoExc ("File output failed.");
}
}
} // namespace
StdIFStream::StdIFStream (const char fileName[]):
OPENEXR_IMF_INTERNAL_NAMESPACE::IStream (fileName),
_is (make_ifstream (fileName)),
_deleteStream (true)
{
if (!*_is)
{
delete _is;
IEX_NAMESPACE::throwErrnoExc();
}
}
StdIFStream::StdIFStream (ifstream &is, const char fileName[]):
OPENEXR_IMF_INTERNAL_NAMESPACE::IStream (fileName),
_is (&is),
_deleteStream (false)
{
// empty
}
StdIFStream::~StdIFStream ()
{
if (_deleteStream)
delete _is;
}
bool
StdIFStream::read (char c[/*n*/], int n)
{
if (!*_is)
throw IEX_NAMESPACE::InputExc ("Unexpected end of file.");
clearError();
_is->read (c, n);
return checkError (*_is, n);
}
uint64_t
StdIFStream::tellg ()
{
return std::streamoff (_is->tellg());
}
void
StdIFStream::seekg (uint64_t pos)
{
_is->seekg (pos);
checkError (*_is);
}
void
StdIFStream::clear ()
{
_is->clear();
}
StdISStream::StdISStream (): OPENEXR_IMF_INTERNAL_NAMESPACE::IStream ("(string)")
{
// empty
}
StdISStream::~StdISStream ()
{
}
bool
StdISStream::read (char c[/*n*/], int n)
{
if (!_is)
throw IEX_NAMESPACE::InputExc ("Unexpected end of file.");
clearError();
_is.read (c, n);
return checkError (_is, n);
}
uint64_t
StdISStream::tellg ()
{
return std::streamoff (_is.tellg());
}
void
StdISStream::seekg (uint64_t pos)
{
_is.seekg (pos);
checkError (_is);
}
void
StdISStream::clear ()
{
_is.clear();
}
std::string
StdISStream::str () const
{
return _is.str ();
}
void
StdISStream::str (const std::string &s)
{
_is.str(s);
}
StdOFStream::StdOFStream (const char fileName[])
: OPENEXR_IMF_INTERNAL_NAMESPACE::OStream (fileName)
, _os (make_ofstream (fileName))
, _deleteStream (true)
{
if (!*_os)
{
delete _os;
IEX_NAMESPACE::throwErrnoExc();
}
}
StdOFStream::StdOFStream (ofstream &os, const char fileName[]):
OPENEXR_IMF_INTERNAL_NAMESPACE::OStream (fileName),
_os (&os),
_deleteStream (false)
{
// empty
}
StdOFStream::~StdOFStream ()
{
if (_deleteStream)
delete _os;
}
void
StdOFStream::write (const char c[/*n*/], int n)
{
clearError();
_os->write (c, n);
checkError (*_os);
}
uint64_t
StdOFStream::tellp ()
{
return std::streamoff (_os->tellp());
}
void
StdOFStream::seekp (uint64_t pos)
{
_os->seekp (pos);
checkError (*_os);
}
StdOSStream::StdOSStream (): OPENEXR_IMF_INTERNAL_NAMESPACE::OStream ("(string)")
{
// empty
}
StdOSStream::~StdOSStream ()
{
}
void
StdOSStream::write (const char c[/*n*/], int n)
{
clearError();
_os.write (c, n);
checkError (_os);
}
uint64_t
StdOSStream::tellp ()
{
return std::streamoff (_os.tellp());
}
void
StdOSStream::seekp (uint64_t pos)
{
_os.seekp (pos);
checkError (_os);
}
std::string
StdOSStream::str () const
{
return _os.str ();
}
OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
| 19.095923 | 99 | 0.615597 | msercheli |
282b04bff1262494d8f9d85462248e917e26df68 | 20,160 | cc | C++ | tests/libtests/faults/TestAdjustTopology_quad.cc | cehanagan/pylith | cf5c1c34040460a82f79b6eb54df894ed1b1ee93 | [
"MIT"
] | 93 | 2015-01-08T16:41:22.000Z | 2022-02-25T13:40:02.000Z | tests/libtests/faults/TestAdjustTopology_quad.cc | sloppyjuicy/pylith | ac2c1587f87e45c948638b19560813d4d5b6a9e3 | [
"MIT"
] | 277 | 2015-02-20T16:27:35.000Z | 2022-03-30T21:13:09.000Z | tests/libtests/faults/TestAdjustTopology_quad.cc | sloppyjuicy/pylith | ac2c1587f87e45c948638b19560813d4d5b6a9e3 | [
"MIT"
] | 71 | 2015-03-24T12:11:08.000Z | 2022-03-03T04:26:02.000Z | // -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University at Buffalo
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2021 University of California, Davis
//
// See LICENSE.md for license information.
//
// ----------------------------------------------------------------------
//
#include <portinfo>
#include "TestAdjustTopology.hh" // Implementation of class methods
// ------------------------------------------------------------------------------------------------
namespace pylith {
namespace faults {
// ----------------------------------------------------------------------------------------
class TestAdjustTopology_QuadA : public TestAdjustTopology {
CPPUNIT_TEST_SUB_SUITE(TestAdjustTopology_QuadA, TestAdjustTopology);
CPPUNIT_TEST_SUITE_END();
void setUp(void) {
TestAdjustTopology::setUp();
_data->filename = "data/quad_a.mesh";
_data->numFaults = 1;
static const char* const faultSurfaceLabels[1] = { "fault" };
_data->faultSurfaceLabels = const_cast<const char**>(faultSurfaceLabels);
static const char* const faultEdgeLabels[1] = { NULL };
_data->faultEdgeLabels = const_cast<const char**>(faultEdgeLabels);
static const int interfaceIds[1] = { 100 };
_data->interfaceIds = const_cast<const int*>(interfaceIds);
_data->cellDim = 2;
_data->spaceDim = 2;
_data->numVertices = 8;
static const size_t numCells = 3;
_data->numCells = numCells;
static const int numCorners[numCells] = { 4, 4, 4 };
_data->numCorners = const_cast<int*>(numCorners);
static const int materialIds[numCells] = { 0, 0, 100 };
_data->materialIds = const_cast<int*>(materialIds);
static const size_t numGroups = 2;
_data->numGroups = numGroups;
static const int groupSizes[numGroups] = { 4+2, 4+2 }; // vertices + edges
_data->groupSizes = const_cast<int*>(groupSizes);
static const char* groupNames[numGroups] = { "output", "fault" };
_data->groupNames = const_cast<char**>(groupNames);
static const char* groupTypes[numGroups] = { "vertex", "vertex" };
_data->groupTypes = const_cast<char**>(groupTypes);
} // setUp
}; // TestAdjustTopology_QuadA
CPPUNIT_TEST_SUITE_REGISTRATION(TestAdjustTopology_QuadA);
// ----------------------------------------------------------------------------------------
class TestAdjustTopology_QuadB : public TestAdjustTopology {
CPPUNIT_TEST_SUB_SUITE(TestAdjustTopology_QuadB, TestAdjustTopology);
CPPUNIT_TEST_SUITE_END();
void setUp(void) {
TestAdjustTopology::setUp();
_data->filename = "data/quad_b.mesh";
_data->numFaults = 1;
static const char* const faultSurfaceLabels[1] = { "fault" };
_data->faultSurfaceLabels = const_cast<const char**>(faultSurfaceLabels);
static const char* const faultEdgeLabels[1] = { NULL };
_data->faultEdgeLabels = const_cast<const char**>(faultEdgeLabels);
static const int interfaceIds[1] = { 100 };
_data->interfaceIds = const_cast<const int*>(interfaceIds);
_data->cellDim = 2;
_data->spaceDim = 2;
_data->numVertices = 8;
static const size_t numCells = 3;
_data->numCells = numCells;
static const int numCorners[numCells] = { 4, 4, 4 };
_data->numCorners = const_cast<int*>(numCorners);
static const int materialIds[numCells] = { 0, 0, 100 };
_data->materialIds = const_cast<int*>(materialIds);
static const size_t numGroups = 2;
_data->numGroups = numGroups;
static const int groupSizes[numGroups] = { 4+2, 4+2 }; // vertices + edges
_data->groupSizes = const_cast<int*>(groupSizes);
static const char* groupNames[numGroups] = { "output", "fault" };
_data->groupNames = const_cast<char**>(groupNames);
static const char* groupTypes[numGroups] = { "vertex", "vertex" };
_data->groupTypes = const_cast<char**>(groupTypes);
} // setUp
}; // TestAdjustTopology_QuadB
CPPUNIT_TEST_SUITE_REGISTRATION(TestAdjustTopology_QuadB);
// ----------------------------------------------------------------------------------------
class TestAdjustTopology_QuadC : public TestAdjustTopology {
CPPUNIT_TEST_SUB_SUITE(TestAdjustTopology_QuadC, TestAdjustTopology);
CPPUNIT_TEST_SUITE_END();
void setUp(void) {
TestAdjustTopology::setUp();
_data->filename = "data/quad_c.mesh";
_data->numFaults = 1;
static const char* const faultSurfaceLabels[1] = { "fault" };
_data->faultSurfaceLabels = const_cast<const char**>(faultSurfaceLabels);
static const char* const faultEdgeLabels[1] = { NULL };
_data->faultEdgeLabels = const_cast<const char**>(faultEdgeLabels);
static const int interfaceIds[1] = { 100 };
_data->interfaceIds = const_cast<const int*>(interfaceIds);
_data->cellDim = 2;
_data->spaceDim = 2;
_data->numVertices = 8;
static const size_t numCells = 3;
_data->numCells = numCells;
static const int numCorners[numCells] = { 4, 4, 4 };
_data->numCorners = const_cast<int*>(numCorners);
static const int materialIds[numCells] = { 0, 0, 100 };
_data->materialIds = const_cast<int*>(materialIds);
static const size_t numGroups = 2;
_data->numGroups = numGroups;
static const int groupSizes[numGroups] = { 4+2, 4+2 }; // vertices + edges
_data->groupSizes = const_cast<int*>(groupSizes);
static const char* groupNames[numGroups] = { "output", "fault" };
_data->groupNames = const_cast<char**>(groupNames);
static const char* groupTypes[numGroups] = { "vertex", "vertex" };
_data->groupTypes = const_cast<char**>(groupTypes);
} // setUp
}; // TestAdjustTopology_QuadC
CPPUNIT_TEST_SUITE_REGISTRATION(TestAdjustTopology_QuadC);
// ----------------------------------------------------------------------------------------
class TestAdjustTopology_QuadD : public TestAdjustTopology {
CPPUNIT_TEST_SUB_SUITE(TestAdjustTopology_QuadD, TestAdjustTopology);
CPPUNIT_TEST_SUITE_END();
void setUp(void) {
TestAdjustTopology::setUp();
_data->filename = "data/quad_d.mesh";
_data->numFaults = 1;
static const char* const faultSurfaceLabels[1] = { "fault" };
_data->faultSurfaceLabels = const_cast<const char**>(faultSurfaceLabels);
static const char* const faultEdgeLabels[1] = { NULL };
_data->faultEdgeLabels = const_cast<const char**>(faultEdgeLabels);
static const int interfaceIds[1] = { 100 };
_data->interfaceIds = const_cast<const int*>(interfaceIds);
_data->cellDim = 2;
_data->spaceDim = 2;
_data->numVertices = 8;
static const size_t numCells = 3;
_data->numCells = numCells;
static const int numCorners[numCells] = { 4, 4, 4 };
_data->numCorners = const_cast<int*>(numCorners);
static const int materialIds[numCells] = { 0, 0, 100 };
_data->materialIds = const_cast<int*>(materialIds);
static const size_t numGroups = 2;
_data->numGroups = numGroups;
static const int groupSizes[numGroups] = { 4+2, 4+2 }; // vertices + edges
_data->groupSizes = const_cast<int*>(groupSizes);
static const char* groupNames[numGroups] = { "output", "fault" };
_data->groupNames = const_cast<char**>(groupNames);
static const char* groupTypes[numGroups] = { "vertex", "vertex" };
_data->groupTypes = const_cast<char**>(groupTypes);
} // setUp
}; // TestAdjustTopology_QuadD
CPPUNIT_TEST_SUITE_REGISTRATION(TestAdjustTopology_QuadD);
// ----------------------------------------------------------------------------------------
class TestAdjustTopology_QuadE : public TestAdjustTopology {
CPPUNIT_TEST_SUB_SUITE(TestAdjustTopology_QuadE, TestAdjustTopology);
CPPUNIT_TEST_SUITE_END();
void setUp(void) {
TestAdjustTopology::setUp();
_data->filename = "data/quad_e.mesh";
_data->numFaults = 1;
static const char* const faultSurfaceLabels[1] = { "fault" };
_data->faultSurfaceLabels = const_cast<const char**>(faultSurfaceLabels);
static const char* const faultEdgeLabels[1] = { NULL };
_data->faultEdgeLabels = const_cast<const char**>(faultEdgeLabels);
static const int interfaceIds[1] = { 100 };
_data->interfaceIds = const_cast<const int*>(interfaceIds);
_data->cellDim = 2;
_data->spaceDim = 2;
_data->numVertices = 12;
static const size_t numCells = 6;
_data->numCells = numCells;
static const int numCorners[numCells] = { 4, 4, 4, 4, 4, 4 };
_data->numCorners = const_cast<int*>(numCorners);
static const int materialIds[numCells] = { 0, 0, 0, 0, 100, 100 };
_data->materialIds = const_cast<int*>(materialIds);
static const size_t numGroups = 2;
_data->numGroups = numGroups;
static const int groupSizes[numGroups] = { 4+2, 6+4 }; // vertices + edges
_data->groupSizes = const_cast<int*>(groupSizes);
static const char* groupNames[numGroups] = { "output", "fault" };
_data->groupNames = const_cast<char**>(groupNames);
static const char* groupTypes[numGroups] = { "vertex", "vertex" };
_data->groupTypes = const_cast<char**>(groupTypes);
} // setUp
}; // TestAdjustTopology_QuadE
CPPUNIT_TEST_SUITE_REGISTRATION(TestAdjustTopology_QuadE);
// ----------------------------------------------------------------------------------------
class TestAdjustTopology_QuadF : public TestAdjustTopology {
CPPUNIT_TEST_SUB_SUITE(TestAdjustTopology_QuadF, TestAdjustTopology);
CPPUNIT_TEST_SUITE_END();
void setUp(void) {
TestAdjustTopology::setUp();
_data->filename = "data/quad_f.mesh";
_data->numFaults = 1;
static const char* const faultSurfaceLabels[1] = { "fault" };
_data->faultSurfaceLabels = const_cast<const char**>(faultSurfaceLabels);
static const char* const faultEdgeLabels[1] = { NULL };
_data->faultEdgeLabels = const_cast<const char**>(faultEdgeLabels);
static const int interfaceIds[1] = { 100 };
_data->interfaceIds = const_cast<const int*>(interfaceIds);
_data->cellDim = 2;
_data->spaceDim = 2;
_data->numVertices = 12;
static const size_t numCells = 6;
_data->numCells = numCells;
static const int numCorners[numCells] = { 4, 4, 4, 4, 4, 4 };
_data->numCorners = const_cast<int*>(numCorners);
static const int materialIds[numCells] = { 0, 0, 0, 0, 100, 100 };
_data->materialIds = const_cast<int*>(materialIds);
static const size_t numGroups = 2;
_data->numGroups = numGroups;
static const int groupSizes[numGroups] = { 4+2, 6+4 }; // vertices + edges
_data->groupSizes = const_cast<int*>(groupSizes);
static const char* groupNames[numGroups] = { "output", "fault" };
_data->groupNames = const_cast<char**>(groupNames);
static const char* groupTypes[numGroups] = { "vertex", "vertex" };
_data->groupTypes = const_cast<char**>(groupTypes);
} // setUp
}; // TestAdjustTopology_QuadF
CPPUNIT_TEST_SUITE_REGISTRATION(TestAdjustTopology_QuadF);
// ----------------------------------------------------------------------------------------
class TestAdjustTopology_QuadG : public TestAdjustTopology {
CPPUNIT_TEST_SUB_SUITE(TestAdjustTopology_QuadG, TestAdjustTopology);
CPPUNIT_TEST_SUITE_END();
void setUp(void) {
TestAdjustTopology::setUp();
_data->filename = "data/quad_g.mesh";
_data->numFaults = 1;
static const char* const faultSurfaceLabels[1] = { "fault" };
_data->faultSurfaceLabels = const_cast<const char**>(faultSurfaceLabels);
static const char* const faultEdgeLabels[1] = { NULL };
_data->faultEdgeLabels = const_cast<const char**>(faultEdgeLabels);
static const int interfaceIds[1] = { 100 };
_data->interfaceIds = const_cast<const int*>(interfaceIds);
_data->cellDim = 2;
_data->spaceDim = 2;
_data->numVertices = 14;
static const size_t numCells = 7;
_data->numCells = numCells;
static const int numCorners[numCells] = { 4, 4, 4, 4, 4, 4, 4 };
_data->numCorners = const_cast<int*>(numCorners);
static const int materialIds[numCells] = { 0, 0, 0, 2, 2, 100, 100 };
_data->materialIds = const_cast<int*>(materialIds);
static const size_t numGroups = 2;
_data->numGroups = numGroups;
static const int groupSizes[numGroups] = { 3+2, 6+4 }; // vertices + edges
_data->groupSizes = const_cast<int*>(groupSizes);
static const char* groupNames[numGroups] = { "output", "fault" };
_data->groupNames = const_cast<char**>(groupNames);
static const char* groupTypes[numGroups] = { "vertex", "vertex" };
_data->groupTypes = const_cast<char**>(groupTypes);
} // setUp
}; // TestAdjustTopology_QuadG
CPPUNIT_TEST_SUITE_REGISTRATION(TestAdjustTopology_QuadG);
// ----------------------------------------------------------------------------------------
class TestAdjustTopology_QuadH : public TestAdjustTopology {
CPPUNIT_TEST_SUB_SUITE(TestAdjustTopology_QuadH, TestAdjustTopology);
CPPUNIT_TEST_SUITE_END();
void setUp(void) {
TestAdjustTopology::setUp();
_data->filename = "data/quad_h.mesh";
_data->numFaults = 2;
static const char* const faultSurfaceLabels[2] = { "faultA", "faultB" };
_data->faultSurfaceLabels = const_cast<const char**>(faultSurfaceLabels);
static const char* const faultEdgeLabels[2] = { NULL, "faultB-edge" };
_data->faultEdgeLabels = const_cast<const char**>(faultEdgeLabels);
static const int interfaceIds[2] = { 101, 100 };
_data->interfaceIds = const_cast<const int*>(interfaceIds);
_data->cellDim = 2;
_data->spaceDim = 2;
_data->numVertices = 22;
static const size_t numCells = 14;
_data->numCells = numCells;
static const int numCorners[numCells] = {
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, };
_data->numCorners = const_cast<int*>(numCorners);
static const int materialIds[numCells] = {
10, 10, 11, 10, 10, 11, 12, 12, 11,
100, 100, 101, 101, 101 };
_data->materialIds = const_cast<int*>(materialIds);
static const size_t numGroups = 3;
_data->numGroups = numGroups;
static const int groupSizes[numGroups] = { 6+4, 8+6, 1 }; // vertices + edges
_data->groupSizes = const_cast<int*>(groupSizes);
static const char* groupNames[numGroups] = { "faultB", "faultA", "faultB-edge" };
_data->groupNames = const_cast<char**>(groupNames);
static const char* groupTypes[numGroups] = { "vertex", "vertex", "vertex" };
_data->groupTypes = const_cast<char**>(groupTypes);
} // setUp
}; // TestAdjustTopology_QuadH
CPPUNIT_TEST_SUITE_REGISTRATION(TestAdjustTopology_QuadH);
// ----------------------------------------------------------------------------------------
class TestAdjustTopology_QuadI : public TestAdjustTopology {
CPPUNIT_TEST_SUB_SUITE(TestAdjustTopology_QuadI, TestAdjustTopology);
CPPUNIT_TEST_SUITE_END();
void setUp(void) {
TestAdjustTopology::setUp();
_data->filename = "data/quad_i.mesh";
static const size_t numFaults = 1;
_data->numFaults = numFaults;
static const char* const faultSurfaceLabels[numFaults] = { "fault", };
_data->faultSurfaceLabels = const_cast<const char**>(faultSurfaceLabels);
static const char* const faultEdgeLabels[numFaults] = { "edge" };
_data->faultEdgeLabels = const_cast<const char**>(faultEdgeLabels);
static const int interfaceIds[numFaults] = { 100 };
_data->interfaceIds = const_cast<const int*>(interfaceIds);
_data->cellDim = 2;
_data->spaceDim = 2;
_data->numVertices = 14;
static const size_t numCells = 8;
_data->numCells = numCells;
static const int numCorners[numCells] = {
4, 4, 4, 4, 4, 4,
4, 4, };
_data->numCorners = const_cast<int*>(numCorners);
static const int materialIds[numCells] = {
10, 10, 10, 11, 10, 11,
100, 100, };
_data->materialIds = const_cast<int*>(materialIds);
static const size_t numGroups = 4;
_data->numGroups = numGroups;
static const int groupSizes[numGroups] = { 3+2, 4+2, 1, 5+4 }; // vertices + edges
_data->groupSizes = const_cast<int*>(groupSizes);
static const char* groupNames[numGroups] = { "output2", "output1", "edge", "fault"};
_data->groupNames = const_cast<char**>(groupNames);
static const char* groupTypes[numGroups] = { "vertex", "vertex", "vertex", "vertex" };
_data->groupTypes = const_cast<char**>(groupTypes);
} // setUp
}; // TestAdjustTopology_QuadI
CPPUNIT_TEST_SUITE_REGISTRATION(TestAdjustTopology_QuadI);
} // faults
} // pylith
// End of file
| 47.435294 | 102 | 0.531647 | cehanagan |
282f3fac6957fc271b07c96a4ea6c62f395dd1ee | 7,649 | cpp | C++ | src/components/transmission/miprtpcomponent.cpp | xchbx/fox | 12787683ba10db8f5eedf21e2d0e7a63bebc1664 | [
"Apache-2.0"
] | 2 | 2019-04-12T10:26:43.000Z | 2019-06-21T15:20:11.000Z | src/components/transmission/miprtpcomponent.cpp | xchbx/NetCamera | 12787683ba10db8f5eedf21e2d0e7a63bebc1664 | [
"Apache-2.0"
] | 1 | 2019-08-06T16:57:49.000Z | 2019-08-06T16:57:49.000Z | src/components/transmission/miprtpcomponent.cpp | xchbx/NetCamera | 12787683ba10db8f5eedf21e2d0e7a63bebc1664 | [
"Apache-2.0"
] | 1 | 2020-12-31T08:52:03.000Z | 2020-12-31T08:52:03.000Z | /*
This file is a part of EMIPLIB, the EDM Media over IP Library.
Copyright (C) 2006-2016 Hasselt University - Expertise Centre for
Digital Media (EDM) (http://www.edm.uhasselt.be)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include "mipconfig.h"
#include "miprtpcomponent.h"
#include "miprtpmessage.h"
#include "mipsystemmessage.h"
#include <jrtplib3/rtpsession.h>
#include <jrtplib3/rtpsourcedata.h>
#include "mipdebug.h"
using namespace jrtplib;
#define MIPRTPCOMPONENT_ERRSTR_NOTINIT "Component was not initialized"
#define MIPRTPCOMPONENT_ERRSTR_ALREADYINIT "Component is already initialized"
#define MIPRTPCOMPONENT_ERRSTR_BADSESSIONPARAM "The RTP session parameter cannot be NULL"
#define MIPRTPCOMPONENT_ERRSTR_BADMESSAGE "Not a valid message"
#define MIPRTPCOMPONENT_ERRSTR_NORTPSESSION "The RTP session is not created yet"
#define MIPRTPCOMPONENT_ERRSTR_RTPERROR "Detected JRTPLIB error: "
MIPRTPComponent::MIPRTPComponent() : MIPComponent("MIPRTPComponent")
{
m_pRTPSession = 0;
m_msgIt = m_messages.begin();
}
MIPRTPComponent::~MIPRTPComponent()
{
destroy();
}
bool MIPRTPComponent::init(RTPSession *pSess, uint32_t silentTimestampIncrement)
{
if (pSess == 0)
{
setErrorString(MIPRTPCOMPONENT_ERRSTR_BADSESSIONPARAM);
return false;
}
if (m_pRTPSession != 0)
{
setErrorString(MIPRTPCOMPONENT_ERRSTR_ALREADYINIT);
return false;
}
m_pRTPSession = pSess;
m_prevIteration = -1;
m_prevSendIteration = -1;
m_silentTimestampIncrease = silentTimestampIncrement;
m_enableSending = true;
m_msgIt = m_messages.begin();
return true;
}
bool MIPRTPComponent::destroy()
{
if (m_pRTPSession == 0)
{
setErrorString(MIPRTPCOMPONENT_ERRSTR_NOTINIT);
return false;
}
m_pRTPSession = 0;
clearMessages();
return true;
}
bool MIPRTPComponent::push(const MIPComponentChain &chain, int64_t iteration, MIPMessage *pMsg)
{
if (m_pRTPSession == 0)
{
setErrorString(MIPRTPCOMPONENT_ERRSTR_NOTINIT);
return false;
}
if (!m_pRTPSession->IsActive())
{
setErrorString(MIPRTPCOMPONENT_ERRSTR_NORTPSESSION);
return false;
}
if (pMsg->getMessageType() == MIPMESSAGE_TYPE_RTP && pMsg->getMessageSubtype() == MIPRTPMESSAGE_TYPE_SEND)
{
// Check if the timestamp needs to be increased first
if (m_silentTimestampIncrease != 0)
{
if (m_prevSendIteration != -1)
{
int64_t intervals = iteration - m_prevSendIteration - 1;
if (intervals > 0)
{
uint32_t factor = (uint32_t)intervals;
uint32_t tsInc = factor * m_silentTimestampIncrease;
m_pRTPSession->IncrementTimestamp(tsInc);
}
}
}
m_prevSendIteration = iteration;
// Send message
MIPRTPSendMessage *pRTPMsg = (MIPRTPSendMessage *)pMsg;
int status;
MIPTime sampInst = pRTPMsg->getSamplingInstant();
MIPTime delay = MIPTime::getCurrentTime();
delay -= sampInst;
if (delay.getValue() > 0 && delay.getValue() < 10.0) // ok, we can assume the time was indeed the sampling instant
m_pRTPSession->SetPreTransmissionDelay(RTPTime((uint32_t)delay.getSeconds(),(uint32_t)delay.getMicroSeconds()));
if (m_enableSending)
{
status = m_pRTPSession->SendPacket(pRTPMsg->getPayload(),pRTPMsg->getPayloadLength(),
pRTPMsg->getPayloadType(),pRTPMsg->getMarker(),
pRTPMsg->getTimestampIncrement());
}
else
{
// If we're not actually sending the packet, we still need to increment the timestamp
// to keep the timing correct
status = m_pRTPSession->IncrementTimestamp(pRTPMsg->getTimestampIncrement());
}
if (status < 0)
{
setErrorString(std::string(MIPRTPCOMPONENT_ERRSTR_RTPERROR) + RTPGetErrorString(status));
return false;
}
}
else if (pMsg->getMessageType() == MIPMESSAGE_TYPE_SYSTEM && pMsg->getMessageSubtype() == MIPSYSTEMMESSAGE_TYPE_ISTIME)
{
return true;
}
else
{
setErrorString(MIPRTPCOMPONENT_ERRSTR_BADMESSAGE);
return false;
}
return true;
}
bool MIPRTPComponent::pull(const MIPComponentChain &chain, int64_t iteration, MIPMessage **pMsg)
{
if (m_pRTPSession == 0)
{
setErrorString(MIPRTPCOMPONENT_ERRSTR_NOTINIT);
return false;
}
if (!m_pRTPSession->IsActive())
{
setErrorString(MIPRTPCOMPONENT_ERRSTR_NORTPSESSION);
return false;
}
if (!processNewPackets(iteration))
return false;
if (m_msgIt == m_messages.end())
{
m_msgIt = m_messages.begin();
*pMsg = 0;
}
else
{
*pMsg = *m_msgIt;
m_msgIt++;
}
return true;
}
bool MIPRTPComponent::processNewPackets(int64_t iteration)
{
if (iteration != m_prevIteration)
{
m_prevIteration = iteration;
clearMessages();
m_pRTPSession->Poll(); // This is a dummy function if the RTPSession background thread is used.
m_pRTPSession->BeginDataAccess();
if (m_pRTPSession->GotoFirstSourceWithData())
{
do
{
RTPSourceData *srcData = m_pRTPSession->GetCurrentSourceInfo();
size_t cnameLength;
const uint8_t *pCName = srcData->SDES_GetCNAME(&cnameLength);
uint32_t jitterSamples = srcData->INF_GetJitter();
real_t jitterSeconds = 0;
real_t tsUnit;
real_t tsUnitEstimation;
bool setTimingInfo = false;
uint32_t timingInfTimestamp = 0;
MIPTime timingInfWallclock(0);
tsUnitEstimation = (real_t)srcData->INF_GetEstimatedTimestampUnit();
if ((tsUnit = (real_t)srcData->GetTimestampUnit()) > 0)
jitterSeconds = (real_t)jitterSamples*tsUnit;
else
{
if (tsUnitEstimation > 0)
jitterSeconds = (real_t)jitterSamples*tsUnitEstimation;
}
if (srcData->SR_HasInfo())
{
RTPNTPTime ntpTime = srcData->SR_GetNTPTimestamp();
if (!(ntpTime.GetMSW() == 0 && ntpTime.GetLSW() == 0))
{
setTimingInfo = true;
RTPTime rtpTime(ntpTime);
timingInfWallclock = MIPTime(rtpTime.GetSeconds(),rtpTime.GetMicroSeconds());
timingInfTimestamp = srcData->SR_GetRTPTimestamp();
}
}
RTPPacket *pPack;
while ((pPack = m_pRTPSession->GetNextPacket()) != 0)
{
MIPRTPReceiveMessage *pRTPMsg = new MIPRTPReceiveMessage(pPack,pCName,cnameLength,true,m_pRTPSession);
pRTPMsg->setJitter(MIPTime(jitterSeconds));
if (tsUnit > 0)
pRTPMsg->setTimestampUnit(tsUnit);
if (tsUnitEstimation > 0)
pRTPMsg->setTimestampUnitEstimate(tsUnitEstimation);
if (setTimingInfo)
pRTPMsg->setTimingInfo(timingInfWallclock, timingInfTimestamp);
pRTPMsg->setSourceID(getSourceID(pPack, srcData));
m_messages.push_back(pRTPMsg);
}
} while (m_pRTPSession->GotoNextSourceWithData());
}
m_pRTPSession->EndDataAccess();
m_msgIt = m_messages.begin();
}
return true;
}
void MIPRTPComponent::clearMessages()
{
std::list<MIPRTPReceiveMessage *>::iterator it;
for (it = m_messages.begin() ; it != m_messages.end() ; it++)
delete (*it);
m_messages.clear();
m_msgIt = m_messages.begin();
}
uint64_t MIPRTPComponent::getSourceID(const RTPPacket *pPack, const RTPSourceData *pSourceData) const
{
return (uint64_t)(pPack->GetSSRC());
}
| 27.028269 | 120 | 0.722709 | xchbx |
2833bb09ad4fcc31f15e4d9e37fe9dc795de0eef | 4,184 | cpp | C++ | test/control/PathPlannerConstAcc.cpp | ClaudiaVisentin/eeros-framework | 63739a2e33b0c5e9e573748fef675131c35181a6 | [
"Apache-2.0"
] | 10 | 2015-02-17T15:27:50.000Z | 2021-12-10T08:34:13.000Z | test/control/PathPlannerConstAcc.cpp | ClaudiaVisentin/eeros-framework | 63739a2e33b0c5e9e573748fef675131c35181a6 | [
"Apache-2.0"
] | 6 | 2016-05-10T17:11:09.000Z | 2022-03-31T07:52:11.000Z | test/control/PathPlannerConstAcc.cpp | ClaudiaVisentin/eeros-framework | 63739a2e33b0c5e9e573748fef675131c35181a6 | [
"Apache-2.0"
] | 13 | 2016-05-01T09:56:51.000Z | 2022-03-28T09:27:49.000Z | #include <eeros/control/PathPlannerConstAcc.hpp>
#include <eeros/core/Fault.hpp>
#include <eeros/math/Matrix.hpp>
#include <gtest/gtest.h>
#include <Utils.hpp>
using namespace eeros;
using namespace eeros::control;
using namespace eeros::math;
// Test name
TEST(controlPathPlannerConstAcc, name) {
PathPlannerConstAcc<Matrix<1,1,double>> planner(1, 1, 1, 0.1);
EXPECT_EQ(planner.getName(), std::string(""));
planner.setName("path planner");
EXPECT_EQ(planner.getName(), std::string("path planner"));
}
// Test initial values for NaN
TEST(controlPathPlannerConstAcc, nan) {
PathPlannerConstAcc<Matrix<2,1,double>> planner({1,1}, {1,1}, {1,1}, 0.1);
EXPECT_TRUE(std::isnan(planner.getAccOut().getSignal().getValue()[0]));
EXPECT_TRUE(std::isnan(planner.getAccOut().getSignal().getValue()[1]));
EXPECT_TRUE(std::isnan(planner.getVelOut().getSignal().getValue()[0]));
EXPECT_TRUE(std::isnan(planner.getVelOut().getSignal().getValue()[1]));
EXPECT_TRUE(std::isnan(planner.getPosOut().getSignal().getValue()[0]));
EXPECT_TRUE(std::isnan(planner.getPosOut().getSignal().getValue()[1]));
}
// Test initial and end positions
TEST(controlPathPlannerConstAcc, init1) {
PathPlannerConstAcc<Matrix<2,1,double>> planner({1,1}, {1,1}, {1,1}, 0.1);
Matrix<2,1,double> start{10, 5}, end{20, 15};
planner.move(start, end);
planner.run();
EXPECT_TRUE(Utils::compareApprox(planner.getAccOut().getSignal().getValue()[0], 1, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getAccOut().getSignal().getValue()[1], 1, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getVelOut().getSignal().getValue()[0], 0.1, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getVelOut().getSignal().getValue()[1], 0.1, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getPosOut().getSignal().getValue()[0], 10.005, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getPosOut().getSignal().getValue()[1], 5.005, 1e-10));
for (int i = 0; i < 150; i++) planner.run();
EXPECT_TRUE(Utils::compareApprox(planner.getAccOut().getSignal().getValue()[0], 0, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getAccOut().getSignal().getValue()[1], 0, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getVelOut().getSignal().getValue()[0], 0, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getVelOut().getSignal().getValue()[1], 0, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getPosOut().getSignal().getValue()[0], 20, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getPosOut().getSignal().getValue()[1], 15, 1e-10));
}
// Test initial and end positions
TEST(controlPathPlannerConstAcc, init2) {
PathPlannerConstAcc<Matrix<2,1,double>> planner({1,1}, {1,1}, {1,1}, 0.1);
Matrix<2,1,double> start{10, 5}, end{10, 15};
planner.move(start, end);
planner.run();
EXPECT_TRUE(Utils::compareApprox(planner.getAccOut().getSignal().getValue()[0], 0, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getAccOut().getSignal().getValue()[1], 1, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getVelOut().getSignal().getValue()[0], 0, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getVelOut().getSignal().getValue()[1], 0.1, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getPosOut().getSignal().getValue()[0], 10, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getPosOut().getSignal().getValue()[1], 5.005, 1e-10));
for (int i = 0; i < 150; i++) planner.run();
// EXPECT_EQ(planner.getAccOut().getSignal().getValue()[0], 200);
// EXPECT_EQ(planner.getVelOut().getSignal().getValue()[0], 200);
// EXPECT_EQ(planner.getPosOut().getSignal().getValue()[0], 200);
EXPECT_TRUE(Utils::compareApprox(planner.getAccOut().getSignal().getValue()[0], 0, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getAccOut().getSignal().getValue()[1], 0, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getVelOut().getSignal().getValue()[0], 0, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getVelOut().getSignal().getValue()[1], 0, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getPosOut().getSignal().getValue()[0], 10, 1e-10));
EXPECT_TRUE(Utils::compareApprox(planner.getPosOut().getSignal().getValue()[1], 15, 1e-10));
}
| 55.786667 | 98 | 0.709369 | ClaudiaVisentin |
2837ff7f975880ba2dad6461f1db3dda540400d3 | 23,028 | cxx | C++ | VTK/Graphics/vtkSubPixelPositionEdgels.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 1 | 2021-07-31T19:38:03.000Z | 2021-07-31T19:38:03.000Z | VTK/Graphics/vtkSubPixelPositionEdgels.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | null | null | null | VTK/Graphics/vtkSubPixelPositionEdgels.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 2 | 2019-01-22T19:51:40.000Z | 2021-07-31T19:38:05.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile$
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSubPixelPositionEdgels.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkStructuredPoints.h"
vtkCxxRevisionMacro(vtkSubPixelPositionEdgels, "$Revision$");
vtkStandardNewMacro(vtkSubPixelPositionEdgels);
vtkSubPixelPositionEdgels::vtkSubPixelPositionEdgels()
{
this->TargetFlag = 0;
this->TargetValue = 0.0;
this->SetNumberOfInputPorts(2);
}
vtkSubPixelPositionEdgels::~vtkSubPixelPositionEdgels()
{
}
int vtkSubPixelPositionEdgels::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *gradMapsInfo = inputVector[1]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkPolyData *input = vtkPolyData::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkStructuredPoints *gradMaps = vtkStructuredPoints::SafeDownCast(
gradMapsInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPolyData *output = vtkPolyData::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkIdType numPts=input->GetNumberOfPoints();
vtkPoints *newPts;
vtkDoubleArray *newNormals;
vtkPoints *inPts;
vtkDataArray *inVectors;
vtkIdType ptId;
float *MapData = 0;
double *DMapData = 0;
double pnt[3];
int *dimensions;
double result[3], resultNormal[3];
double *spacing, *origin;
vtkDebugMacro(<<"SubPixelPositioning Edgels");
if ( numPts < 1 || (inPts=input->GetPoints()) == NULL )
{
vtkErrorMacro(<<"No data to fit!");
return 1;
}
newPts = vtkPoints::New();
newNormals = vtkDoubleArray::New();
newNormals->SetNumberOfComponents(3);
dimensions = gradMaps->GetDimensions();
spacing = gradMaps->GetSpacing();
origin = gradMaps->GetOrigin();
if (vtkDoubleArray::SafeDownCast(gradMaps->GetPointData()->GetScalars()))
{
DMapData = vtkDoubleArray::SafeDownCast(gradMaps->GetPointData()
->GetScalars())->GetPointer(0);
}
else if (vtkFloatArray::SafeDownCast(gradMaps->GetPointData()->GetScalars()))
{
MapData = vtkFloatArray::SafeDownCast(gradMaps->GetPointData()
->GetScalars())->GetPointer(0);
}
inVectors = gradMaps->GetPointData()->GetVectors();
//
// Loop over all points, adjusting locations
//
for (ptId=0; ptId < inPts->GetNumberOfPoints(); ptId++)
{
inPts->GetPoint(ptId,pnt);
pnt[0] = (pnt[0] - origin[0])/spacing[0];
pnt[1] = (pnt[1] - origin[1])/spacing[1];
pnt[2] = (pnt[2] - origin[2])/spacing[2];
if (MapData)
{
this->Move(dimensions[0],dimensions[1],dimensions[2],
(int)(pnt[0]+0.5),(int)(pnt[1]+0.5),MapData,
inVectors, result, (int)(pnt[2]+0.5), spacing,
resultNormal);
}
else if (DMapData)
{
this->Move(dimensions[0],dimensions[1],dimensions[2],
(int)(pnt[0]+0.5),(int)(pnt[1]+0.5),DMapData,
inVectors, result, (int)(pnt[2]+0.5), spacing,
resultNormal);
}
result[0] = result[0]*spacing[0] + origin[0];
result[1] = result[1]*spacing[1] + origin[1];
result[2] = result[2]*spacing[2] + origin[2];
newPts->InsertNextPoint(result);
newNormals->InsertNextTuple(resultNormal);
}
output->CopyStructure(input);
output->GetPointData()->CopyNormalsOff();
output->GetPointData()->PassData(input->GetPointData());
output->GetPointData()->SetNormals(newNormals);
output->SetPoints(newPts);
newPts->Delete();
newNormals->Delete();
return 1;
}
void vtkSubPixelPositionEdgels::Move(int xdim, int ydim, int zdim,
int x, int y,
double *img, vtkDataArray *inVecs,
double *result, int z, double *spacing,
double *resultNormal)
{
int ypos;
vtkIdType zpos;
double vec[3];
double valn, valp;
double mag;
double a,b,c;
double xp, yp, zp;
double xn, yn, zn;
int xi, yi, zi, i;
zpos = z*xdim*ydim;
ypos = y*xdim;
// handle the 2d case
if (zdim < 2)
{
if (x < 1 || y < 1 || x >= (xdim-2) || y >= (ydim -2))
{
result[0] = x;
result[1] = y;
result[2] = z;
// if the point of off of the grad map just make up a value
if (x < 0 || y < 0 || x > xdim || y > ydim)
{
resultNormal[0] = 1;
resultNormal[1] = 0;
resultNormal[2] = 0;
}
else
{
for (i = 0; i < 3; i++)
{
resultNormal[i] =
inVecs->GetTuple(x + xdim*y)[i];
}
vtkMath::Normalize(resultNormal);
}
}
else
{
// first get the orientation
inVecs->GetTuple(x+ypos,vec);
vec[0] = vec[0]*spacing[0];
vec[1] = vec[1]*spacing[1];
vec[2] = 0;
vtkMath::Normalize(vec);
mag = img[x+ypos];
// compute the sample points
xp = (double)x + vec[0];
yp = (double)y + vec[1];
xn = (double)x - vec[0];
yn = (double)y - vec[1];
// compute their values
xi = (int)xp;
yi = (int)yp;
valp =
img[xi +xdim*yi]*(1.0 -xp +xi)*(1.0 -yp +yi) +
img[1 +xi + xdim*yi]*(xp -xi)*(1.0 -yp +yi) +
img[xi +xdim*(yi +1)]*(1.0 -xp +xi)*(yp -yi) +
img[1 + xi + xdim*(yi +1)]*(xp -xi)*(yp -yi);
xi = (int)xn;
yi = (int)yn;
valn =
img[xi +xdim*yi]*(1.0 -xn +xi)*(1.0 -yn +yi) +
img[1 + xi +xdim*yi]*(xn -xi)*(1.0 -yn +yi) +
img[xi + xdim*(yi +1)]*(1.0 -xn +xi)*(yn -yi) +
img[1 + xi + xdim*(yi +1)]*(xn -xi)*(yn -yi);
result[0] = x;
result[1] = y;
result[2] = z;
// now fit to a parabola and find max
c = mag;
b = (valp - valn)/2.0;
a = (valp - c - b);
// assign the root to c because MSVC5.0 optimizer has problems with this
// function
c = -0.5*b/a;
if (c > 1.0)
{
c = 1.0;
}
if (c < -1.0)
{
c = -1.0;
}
result[0] += vec[0]*c;
result[1] += vec[1]*c;
// now calc the normal, trilinear interp of vectors
xi = (int)result[0];
yi = (int)result[1];
//zi = (int)result[2];
xn = result[0];
yn = result[1];
//zn = result[2];
for (i = 0; i < 3; i++)
{
resultNormal[i] =
inVecs->GetTuple(xi + xdim*yi)[i] * (1.0 -xn +xi)*(1.0 -yn +yi) +
inVecs->GetTuple(1 + xi + xdim*yi)[i] * (xn -xi)*(1.0 -yn +yi) +
inVecs->GetTuple(xi + xdim*(yi +1))[i] * (1.0 -xn +xi)*(yn -yi) +
inVecs->GetTuple(1 + xi + xdim*(yi +1))[i] * (xn -xi)*(yn -yi);
}
vtkMath::Normalize(resultNormal);
}
}
else
{
if (x < 1 || y < 1 || z < 1 ||
x >= (xdim-2) || y >= (ydim -2) || z >= (zdim -2))
{
result[0] = x;
result[1] = y;
result[2] = z;
if (x < 0 || y < 0 || z < 0 ||
x > xdim || y > ydim || z > zdim)
{
resultNormal[0] = 1;
resultNormal[1] = 1;
resultNormal[2] = 1;
}
else
{
for (i = 0; i < 3; i++)
{
resultNormal[i] =
inVecs->GetTuple(x + xdim*y + xdim*ydim*z)[i];
}
vtkMath::Normalize(resultNormal);
}
}
else
{
// first get the orientation
inVecs->GetTuple(x+ypos+zpos,vec);
vec[0] = vec[0]*spacing[0];
vec[1] = vec[1]*spacing[1];
vec[2] = vec[2]*spacing[2];
vtkMath::Normalize(vec);
mag = img[x+ypos+zpos];
// compute the sample points
xp = (double)x + vec[0];
yp = (double)y + vec[1];
zp = (double)z + vec[2];
xn = (double)x - vec[0];
yn = (double)y - vec[1];
zn = (double)z - vec[2];
// compute their values
xi = (int)xp;
yi = (int)yp;
zi = (int)zp;
// This set of statements used to be one statement. It was broken up
// due to problems with MSVC 5.0
valp =
img[xi +xdim*(yi +zi*ydim)]*(1.0 -xp +xi)*(1.0 -yp +yi)*(1.0 -zp +zi);
valp +=
img[1 +xi + xdim*(yi + zi*ydim)]*(xp -xi)*(1.0 -yp +yi)*(1.0 -zp +zi);
valp +=
img[xi +xdim*(yi +1 + zi*ydim)]*(1.0 -xp +xi)*(yp -yi)*(1.0 -zp +zi);
valp +=
img[1 + xi + xdim*(yi +1 +zi*ydim)]*(xp -xi)*(yp -yi)*(1.0 -zp +zi);
valp +=
img[xi +xdim*(yi + (zi+1)*ydim)]*(1.0 -xp +xi)*(1.0 -yp +yi)*(zp -zi);
valp +=
img[1 + xi + xdim*(yi + (zi+1)*ydim)]*(xp -xi)*(1.0 -yp +yi)*(zp -zi);
valp +=
img[xi + xdim*(yi +1 + (zi+1)*ydim)]*(1.0 -xp +xi)*(yp -yi)*(zp -zi);
valp +=
img[1 + xi + xdim*(yi +1 +(zi+1)*ydim)]*(xp -xi)*(yp -yi)*(zp -zi);
xi = (int)xn;
yi = (int)yn;
zi = (int)zn;
// This set of statements used to be one statement. It was broken up
// due to problems with MSVC 5.0
valn =
img[xi +xdim*(yi +zi*ydim)]*(1.0 -xn +xi)*(1.0 -yn +yi)*(1.0 -zn +zi);
valn +=
img[1 + xi +xdim*(yi + zi*ydim)]*(xn -xi)*(1.0 -yn +yi)*(1.0 -zn +zi);
valn +=
img[xi + xdim*(yi +1 + zi*ydim)]*(1.0 -xn +xi)*(yn -yi)*(1.0 -zn +zi);
valn +=
img[1 + xi + xdim*(yi +1 +zi*ydim)]*(xn -xi)*(yn -yi)*(1.0 -zn +zi);
valn +=
img[xi +xdim*(yi + (zi+1)*ydim)]*(1.0 -xn +xi)*(1.0 -yn +yi)*(zn -zi);
valn +=
img[1 + xi + xdim*(yi + (zi+1)*ydim)]*(xn -xi)*(1.0 -yn +yi)*(zn -zi);
valn +=
img[xi + xdim*(yi +1 + (zi+1)*ydim)]*(1.0 -xn +xi)*(yn -yi)*(zn -zi);
valn +=
img[1 + xi + xdim*(yi +1 +(zi+1)*ydim)]*(xn -xi)*(yn -yi)*(zn -zi);
result[0] = x;
result[1] = y;
result[2] = z;
if (this->TargetFlag)
{
// For target, do a simple linear interpolation to avoid binomial.
c = mag;
if (c == this->TargetValue)
{
c = 0.0;
}
else if ((this->TargetValue < c && valp < c) ||
(this->TargetValue > c && valp > c))
{
c = (this->TargetValue - c) / (valp - c);
}
else if ((this->TargetValue < c && valn < c) ||
(this->TargetValue < c && valn > c))
{
c = (this->TargetValue - c) / (c - valn);
}
else
{
c = 0.0;
}
}
else
{
// now fit to a parabola and find max
c = mag;
b = (valp - valn)/2.0;
a = (valp - c - b);
//assign the root to c because MSVC5.0 optimizer has problems with this
// function
c = -0.5*b/a;
}
if (c > 1.0)
{
c = 1.0;
}
if (c < -1.0)
{
c = -1.0;
}
result[0] = result[0] + vec[0]*c;
result[1] = result[1] + vec[1]*c;
result[2] = result[2] + vec[2]*c;
// now calc the normal, trilinear interp of vectors
xi = (int)result[0];
yi = (int)result[1];
zi = (int)result[2];
xn = result[0];
yn = result[1];
zn = result[2];
for (i = 0; i < 3; i++)
{
resultNormal[i] =
inVecs->GetTuple(xi + xdim*(yi + zi*ydim))[i] *
(1.0 -xn +xi)*(1.0 -yn +yi)*(1.0 -zn +zi) +
inVecs->GetTuple(1 + xi + xdim*(yi + zi*ydim))[i] *
(xn -xi)*(1.0 -yn +yi)*(1.0 -zn +zi) +
inVecs->GetTuple(xi + xdim*(yi +1 + zi*ydim))[i] *
(1.0 -xn +xi)*(yn -yi)*(1.0 -zn +zi) +
inVecs->GetTuple(1 + xi + xdim*(yi +1 +zi*ydim))[i] *
(xn -xi)*(yn -yi)*(1.0 -zn +zi) +
inVecs->GetTuple(xi + xdim*(yi + (zi+1)*ydim))[i] *
(1.0 -xn +xi)*(1.0 -yn +yi)*(zn -zi) +
inVecs->GetTuple(1 + xi + xdim*(yi + (zi+1)*ydim))[i] *
(xn -xi)*(1.0 -yn +yi)*(zn -zi) +
inVecs->GetTuple(xi + xdim*(yi +1 + (zi+1)*ydim))[i] *
(1.0 -xn +xi)*(yn -yi)*(zn -zi) +
inVecs->GetTuple(1 + xi + xdim*(yi +1 +(zi+1)*ydim))[i] *
(xn -xi)*(yn -yi)*(zn -zi);
}
vtkMath::Normalize(resultNormal);
}
}
}
void vtkSubPixelPositionEdgels::Move(int xdim, int ydim, int zdim,
int x, int y,
float *img, vtkDataArray *inVecs,
double *result, int z, double *spacing,
double *resultNormal)
{
int ypos;
vtkIdType zpos;
double vec[3];
double valn, valp;
double mag;
double a,b,c;
double xp, yp, zp;
double xn, yn, zn;
int xi, yi, zi, i;
zpos = z*xdim*ydim;
ypos = y*xdim;
// handle the 2d case
if (zdim < 2)
{
if (x < 1 || y < 1 || x >= (xdim-2) || y >= (ydim -2))
{
result[0] = x;
result[1] = y;
result[2] = z;
// if the point of off of the grad map just make up a value
if (x < 0 || y < 0 || x > xdim || y > ydim)
{
resultNormal[0] = 1;
resultNormal[1] = 0;
resultNormal[2] = 0;
}
else
{
for (i = 0; i < 3; i++)
{
resultNormal[i] =
inVecs->GetTuple(x + xdim*y)[i];
}
vtkMath::Normalize(resultNormal);
}
}
else
{
// first get the orientation
inVecs->GetTuple(x+ypos,vec);
vec[0] = vec[0]*spacing[0];
vec[1] = vec[1]*spacing[1];
vec[2] = 0;
vtkMath::Normalize(vec);
mag = img[x+ypos];
// compute the sample points
xp = (double)x + vec[0];
yp = (double)y + vec[1];
xn = (double)x - vec[0];
yn = (double)y - vec[1];
// compute their values
xi = (int)xp;
yi = (int)yp;
valp =
img[xi +xdim*yi]*(1.0 -xp +xi)*(1.0 -yp +yi) +
img[1 +xi + xdim*yi]*(xp -xi)*(1.0 -yp +yi) +
img[xi +xdim*(yi +1)]*(1.0 -xp +xi)*(yp -yi) +
img[1 + xi + xdim*(yi +1)]*(xp -xi)*(yp -yi);
xi = (int)xn;
yi = (int)yn;
valn =
img[xi +xdim*yi]*(1.0 -xn +xi)*(1.0 -yn +yi) +
img[1 + xi +xdim*yi]*(xn -xi)*(1.0 -yn +yi) +
img[xi + xdim*(yi +1)]*(1.0 -xn +xi)*(yn -yi) +
img[1 + xi + xdim*(yi +1)]*(xn -xi)*(yn -yi);
result[0] = x;
result[1] = y;
result[2] = z;
// now fit to a parabola and find max
c = mag;
b = (valp - valn)/2.0;
a = (valp - c - b);
// assign the root to c because MSVC5.0 optimizer has problems with this
// function
c = -0.5*b/a;
if (c > 1.0)
{
c = 1.0;
}
if (c < -1.0)
{
c = -1.0;
}
result[0] += vec[0]*c;
result[1] += vec[1]*c;
// now calc the normal, trilinear interp of vectors
xi = (int)result[0];
yi = (int)result[1];
//zi = (int)result[2];
xn = result[0];
yn = result[1];
//zn = result[2];
for (i = 0; i < 3; i++)
{
resultNormal[i] =
inVecs->GetTuple(xi + xdim*yi)[i] * (1.0 -xn +xi)*(1.0 -yn +yi) +
inVecs->GetTuple(1 + xi + xdim*yi)[i] * (xn -xi)*(1.0 -yn +yi) +
inVecs->GetTuple(xi + xdim*(yi +1))[i] * (1.0 -xn +xi)*(yn -yi) +
inVecs->GetTuple(1 + xi + xdim*(yi +1))[i] * (xn -xi)*(yn -yi);
}
vtkMath::Normalize(resultNormal);
}
}
else
{
if (x < 1 || y < 1 || z < 1 ||
x >= (xdim-2) || y >= (ydim -2) || z >= (zdim -2))
{
result[0] = x;
result[1] = y;
result[2] = z;
if (x < 0 || y < 0 || z < 0 ||
x > xdim || y > ydim || z > zdim)
{
resultNormal[0] = 1;
resultNormal[1] = 1;
resultNormal[2] = 1;
}
else
{
for (i = 0; i < 3; i++)
{
resultNormal[i] =
inVecs->GetTuple(x + xdim*y + xdim*ydim*z)[i];
}
vtkMath::Normalize(resultNormal);
}
}
else
{
// first get the orientation
inVecs->GetTuple(x+ypos+zpos,vec);
vec[0] = vec[0]*spacing[0];
vec[1] = vec[1]*spacing[1];
vec[2] = vec[2]*spacing[2];
vtkMath::Normalize(vec);
mag = img[x+ypos+zpos];
// compute the sample points
xp = (double)x + vec[0];
yp = (double)y + vec[1];
zp = (double)z + vec[2];
xn = (double)x - vec[0];
yn = (double)y - vec[1];
zn = (double)z - vec[2];
// compute their values
xi = (int)xp;
yi = (int)yp;
zi = (int)zp;
// This set of statements used to be one statement. It was broken up
// due to problems with MSVC 5.0
valp =
img[xi +xdim*(yi +zi*ydim)]*(1.0 -xp +xi)*(1.0 -yp +yi)*(1.0 -zp +zi);
valp +=
img[1 +xi + xdim*(yi + zi*ydim)]*(xp -xi)*(1.0 -yp +yi)*(1.0 -zp +zi);
valp +=
img[xi +xdim*(yi +1 + zi*ydim)]*(1.0 -xp +xi)*(yp -yi)*(1.0 -zp +zi);
valp +=
img[1 + xi + xdim*(yi +1 +zi*ydim)]*(xp -xi)*(yp -yi)*(1.0 -zp +zi);
valp +=
img[xi +xdim*(yi + (zi+1)*ydim)]*(1.0 -xp +xi)*(1.0 -yp +yi)*(zp -zi);
valp +=
img[1 + xi + xdim*(yi + (zi+1)*ydim)]*(xp -xi)*(1.0 -yp +yi)*(zp -zi);
valp +=
img[xi + xdim*(yi +1 + (zi+1)*ydim)]*(1.0 -xp +xi)*(yp -yi)*(zp -zi);
valp +=
img[1 + xi + xdim*(yi +1 +(zi+1)*ydim)]*(xp -xi)*(yp -yi)*(zp -zi);
xi = (int)xn;
yi = (int)yn;
zi = (int)zn;
// This set of statements used to be one statement. It was broken up
// due to problems with MSVC 5.0
valn =
img[xi +xdim*(yi +zi*ydim)]*(1.0 -xn +xi)*(1.0 -yn +yi)*(1.0 -zn +zi);
valn +=
img[1 + xi +xdim*(yi + zi*ydim)]*(xn -xi)*(1.0 -yn +yi)*(1.0 -zn +zi);
valn +=
img[xi + xdim*(yi +1 + zi*ydim)]*(1.0 -xn +xi)*(yn -yi)*(1.0 -zn +zi);
valn +=
img[1 + xi + xdim*(yi +1 +zi*ydim)]*(xn -xi)*(yn -yi)*(1.0 -zn +zi);
valn +=
img[xi +xdim*(yi + (zi+1)*ydim)]*(1.0 -xn +xi)*(1.0 -yn +yi)*(zn -zi);
valn +=
img[1 + xi + xdim*(yi + (zi+1)*ydim)]*(xn -xi)*(1.0 -yn +yi)*(zn -zi);
valn +=
img[xi + xdim*(yi +1 + (zi+1)*ydim)]*(1.0 -xn +xi)*(yn -yi)*(zn -zi);
valn +=
img[1 + xi + xdim*(yi +1 +(zi+1)*ydim)]*(xn -xi)*(yn -yi)*(zn -zi);
result[0] = x;
result[1] = y;
result[2] = z;
if (this->TargetFlag)
{
// For target, do a simple linear interpolation to avoid binomial.
c = mag;
if (c == this->TargetValue)
{
c = 0.0;
}
else if ((this->TargetValue < c && valp < c) ||
(this->TargetValue > c && valp > c))
{
c = (this->TargetValue - c) / (valp - c);
}
else if ((this->TargetValue < c && valn < c) ||
(this->TargetValue < c && valn > c))
{
c = (this->TargetValue - c) / (c - valn);
}
else
{
c = 0.0;
}
}
else
{
// now fit to a parabola and find max
c = mag;
b = (valp - valn)/2.0;
a = (valp - c - b);
//assign the root to c because MSVC5.0 optimizer has problems with this
// function
c = -0.5*b/a;
}
if (c > 1.0)
{
c = 1.0;
}
if (c < -1.0)
{
c = -1.0;
}
result[0] = result[0] + vec[0]*c;
result[1] = result[1] + vec[1]*c;
result[2] = result[2] + vec[2]*c;
// now calc the normal, trilinear interp of vectors
xi = (int)result[0];
yi = (int)result[1];
zi = (int)result[2];
xn = result[0];
yn = result[1];
zn = result[2];
for (i = 0; i < 3; i++)
{
resultNormal[i] =
inVecs->GetTuple(xi + xdim*(yi + zi*ydim))[i] *
(1.0 -xn +xi)*(1.0 -yn +yi)*(1.0 -zn +zi) +
inVecs->GetTuple(1 + xi + xdim*(yi + zi*ydim))[i] *
(xn -xi)*(1.0 -yn +yi)*(1.0 -zn +zi) +
inVecs->GetTuple(xi + xdim*(yi +1 + zi*ydim))[i] *
(1.0 -xn +xi)*(yn -yi)*(1.0 -zn +zi) +
inVecs->GetTuple(1 + xi + xdim*(yi +1 +zi*ydim))[i] *
(xn -xi)*(yn -yi)*(1.0 -zn +zi) +
inVecs->GetTuple(xi + xdim*(yi + (zi+1)*ydim))[i] *
(1.0 -xn +xi)*(1.0 -yn +yi)*(zn -zi) +
inVecs->GetTuple(1 + xi + xdim*(yi + (zi+1)*ydim))[i] *
(xn -xi)*(1.0 -yn +yi)*(zn -zi) +
inVecs->GetTuple(xi + xdim*(yi +1 + (zi+1)*ydim))[i] *
(1.0 -xn +xi)*(yn -yi)*(zn -zi) +
inVecs->GetTuple(1 + xi + xdim*(yi +1 +(zi+1)*ydim))[i] *
(xn -xi)*(yn -yi)*(zn -zi);
}
vtkMath::Normalize(resultNormal);
}
}
}
void vtkSubPixelPositionEdgels::SetGradMaps(vtkStructuredPoints *gm)
{
this->SetInput(1, gm);
}
vtkStructuredPoints *vtkSubPixelPositionEdgels::GetGradMaps()
{
if (this->GetNumberOfInputConnections(1) < 1)
{
return NULL;
}
return vtkStructuredPoints::SafeDownCast(
this->GetExecutive()->GetInputData(1, 0));
}
int vtkSubPixelPositionEdgels::FillInputPortInformation(int port,
vtkInformation *info)
{
if (port == 1)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkStructuredPoints");
return 1;
}
return this->Superclass::FillInputPortInformation(port, info);
}
// Print the state of the class.
void vtkSubPixelPositionEdgels::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
if ( this->GetGradMaps() )
{
os << indent << "Gradient Data: " << this->GetGradMaps() << "\n";
}
else
{
os << indent << "Gradient Data: (none)\n";
}
os << indent << "TargetFlag: " << this->TargetFlag << endl;
os << indent << "TargetValue: " << this->TargetValue << endl;
}
| 29.867704 | 79 | 0.472642 | matthb2 |
283a81341237133b5e509f5d9e787dade9951564 | 6,587 | cxx | C++ | proof/clas12_selector.cxx | tylern4/hipoTests | e6c773f009e041a9d96ebdabddcc005fe2c7267c | [
"MIT"
] | null | null | null | proof/clas12_selector.cxx | tylern4/hipoTests | e6c773f009e041a9d96ebdabddcc005fe2c7267c | [
"MIT"
] | null | null | null | proof/clas12_selector.cxx | tylern4/hipoTests | e6c773f009e041a9d96ebdabddcc005fe2c7267c | [
"MIT"
] | null | null | null | #define clas12_selector_cxx
// The class definition in clas12_selector.h has been generated automatically
// by the ROOT utility TTree::MakeSelector(). This class is derived
// from the ROOT class TSelector. For more information on the TSelector
// framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual.
// The following methods are defined in this file:
// Begin(): called every time a loop on the tree starts,
// a convenient place to create your histograms.
// SlaveBegin(): called after Begin(), when on PROOF called only on the
// slave servers.
// Process(): called for each event, in this function you decide what
// to read and fill your histograms.
// SlaveTerminate: called at the end of the loop on the tree, when on PROOF
// called only on the slave servers.
// Terminate(): called at the end of the loop on the tree,
// a convenient place to draw/fit your histograms.
//
// To use this file, try the following session on your Tree T:
//
// root> T->Process("clas12_selector.C")
// root> T->Process("clas12_selector.C","some options")
// root> T->Process("clas12_selector.C+")
//
#include <TH2.h>
#include <TStyle.h>
#include "clas12_selector.h"
void clas12_selector::Begin(TTree * /*tree*/) {
// The Begin() function is called at the start of the query.
// When running with PROOF Begin() is only called on the client.
// The tree argument is deprecated (on PROOF 0 is passed).
TString option = GetOption();
}
void clas12_selector::SlaveBegin(TTree * /*tree*/) {
// The SlaveBegin() function is called after the Begin() function.
// When running with PROOF SlaveBegin() is called on each slave server.
// The tree argument is deprecated (on PROOF 0 is passed).
TString option = GetOption();
wq2_elec = new TH2D("wq2", "W vs Q^{2}", 500, 0, 4.0, 500, 0, 2.5);
fOutput->Add(wq2_elec);
w = new TH1F("w", "W", 500, 0, 4.0);
fOutput->Add(w);
w_cut = new TH1F("w_cut", "w_cut", 250, 0, 4.0);
fOutput->Add(w_cut);
w_mm = new TH2D("w_mm", "w_mm", 500, 0, 4.0, 500, 0, 3);
fOutput->Add(w_mm);
missingMass = new TH1F("missingMass", "missingMass", 200, 0, 5.5);
fOutput->Add(missingMass);
missingMass_cut = new TH1F("missingMass_cut", "missingMass_cut", 200, 0, 5.5);
fOutput->Add(missingMass_cut);
sf_elec = new TH2D("sf_elec", "sf_elec", 200, 0, 7.5, 200, 0.0, 0.5);
fOutput->Add(sf_elec);
dt_pip_hist = new TH2D("dt_pip_hist", "dt_pip_hist", 200, 0, 5.5, 200, -5.0, 5.0);
fOutput->Add(dt_pip_hist);
}
Bool_t clas12_selector::Process(Long64_t entry) {
// The Process() function is called for each entry in the tree (or possibly
// keyed object in the case of PROOF) to be processed. The entry argument
// specifies which entry in the currently loaded tree is to be processed.
// When processing keyed objects with PROOF, the object is already loaded
// and is available via the fObject pointer.
//
// This function should contain the \"body\" of the analysis. It can contain
// simple or elaborate selection criteria, run algorithms on the data
// of the event and typically fill histograms.
//
// The processing can be stopped by calling Abort().
//
// Use fStatus to set the return value of TTree::Process().
//
// The return value is currently not used.
fReader.SetEntry(entry);
TLorentzVector e_mu_prime;
size_t len = 0;
for (auto l = pid.begin(); l != pid.end(); l++) len++;
if (len == 0) return false;
if (charge[0] != -1) return false;
e_mu_prime.SetXYZM(px[0], py[0], pz[0], MASS_E);
sf_elec->Fill(p[0], ec_tot_energy[0] / p[0]);
double e_vertex = vertex_time(sc_ftof_1b_time[0], sc_ftof_1b_path[0], 1.0);
if ((ec_tot_energy[0] / p[0]) < 0.2 || (ec_tot_energy[0] / p[0]) > 0.3) return false;
wq2_elec->Fill(W_calc(e_mu_prime), Q2_calc(e_mu_prime));
w->Fill(W_calc(e_mu_prime));
TLorentzVector *pionP = new TLorentzVector();
int numpip = 0;
int numOther = 0;
for (int part = 1; part < len; part++) {
pionP->SetXYZM(px[part], py[part], pz[part], MASS_PIP);
double pip_dt = NAN;
if (charge[part] == 1) {
double sc_t = sc_ftof_1b_time[part];
double sc_r = sc_ftof_1b_path[part];
pip_dt = delta_t_calc(e_vertex, p[part], sc_t, sc_r, MASS_PIP);
dt_pip_hist->Fill(p[part], pip_dt);
}
if (abs(pip_dt) < 0.5 && charge[part] == 1) {
numpip++;
} else {
numOther++;
}
}
if (numpip == 1 && numOther == 0) {
missingMass->Fill(missM(e_mu_prime, *pionP));
w_mm->Fill(W_calc(e_mu_prime), missM(e_mu_prime, *pionP));
if (missM(e_mu_prime, *pionP) >= 0.8 && missM(e_mu_prime, *pionP) <= 1.1) {
missingMass_cut->Fill(missM(e_mu_prime, *pionP));
w_cut->Fill(W_calc(e_mu_prime));
}
}
return kTRUE;
}
void clas12_selector::SlaveTerminate() {
// The SlaveTerminate() function is called after all entries or objects
// have been processed. When running with PROOF SlaveTerminate() is called
// on each slave server.
}
void clas12_selector::Terminate() {
// The Terminate() function is the last function to be called during
// a query. It always runs on the client, it can be used to present
// the results graphically or save the results to file.
TCanvas *can = new TCanvas("can", "can", 1600, 900);
can->Divide(3, 2);
can->cd(1);
sf_elec->Draw("colz");
TLine *sf_lint_t = new TLine(0, 0.2, 7.5, 0.2);
sf_lint_t->SetLineColor(38);
sf_lint_t->SetLineWidth(4);
sf_lint_t->Draw("same");
TLine *sf_lint_b = new TLine(0, 0.3, 7.5, 0.3);
sf_lint_b->SetLineColor(38);
sf_lint_b->SetLineWidth(4);
sf_lint_b->Draw("same");
can->cd(2);
wq2_elec->Draw("colz");
can->cd(3);
w->Draw();
can->cd(4);
dt_pip_hist->Draw("colz");
TLine *lint_t = new TLine(0, 0.5, 5.5, 0.5);
lint_t->SetLineColor(38);
lint_t->SetLineWidth(4);
lint_t->Draw("same");
TLine *lint_b = new TLine(0, -0.5, 5.5, -0.5);
lint_b->SetLineColor(38);
lint_b->SetLineWidth(4);
lint_b->Draw("same");
can->cd(5);
missingMass->Draw();
missingMass_cut->SetFillColor(38);
missingMass_cut->Draw("same");
can->cd(6);
w_cut->SetFillColor(38);
w_cut->Draw();
TFile *outFile = new TFile("rootTest_output.root", "RECREATE");
outFile->cd();
can->Write();
can->SaveAs("rootTest_analysis.png");
wq2_elec->Write();
w->Write();
w_cut->Write();
w_mm->Write();
missingMass->Write();
missingMass_cut->Write();
sf_elec->Write();
dt_pip_hist->Write();
outFile->Write();
outFile->Close();
}
| 34.851852 | 87 | 0.653256 | tylern4 |
283bca6812d3eca896e2d12520e94c8dbd9d4107 | 9,072 | cpp | C++ | Examples/SimpleExample.cpp | wxie2013/Spike_July_2019 | 5cfa90e6bfaa5bcf6d13568617e39a6725e3c988 | [
"MIT"
] | null | null | null | Examples/SimpleExample.cpp | wxie2013/Spike_July_2019 | 5cfa90e6bfaa5bcf6d13568617e39a6725e3c988 | [
"MIT"
] | 1 | 2019-08-16T21:18:21.000Z | 2019-08-16T21:18:21.000Z | Examples/SimpleExample.cpp | wxie2013/Spike_July_2019 | 5cfa90e6bfaa5bcf6d13568617e39a6725e3c988 | [
"MIT"
] | null | null | null | /*
An Example Model for running the SPIKE simulator
To create the executable for this network:
- Run cmake from the build directory: "cmake ../"
- Make this example: "make ExampleExperiment"
- Finally, execute the binary: "./ExampleExperiment"
*/
#include "Spike/Spike.hpp"
// The function which will autorun when the executable is created
int main (int argc, char *argv[]){
/*
CHOOSE THE COMPONENTS OF YOUR SIMULATION
*/
// Create an instance of the Model
SpikingModel* ExampleModel = new SpikingModel();
// Set up the simulator with a timestep at which the neuron, synapse and STDP properties will be calculated
float timestep = 2e-5; // In seconds
ExampleModel->SetTimestep(timestep);
// Choose an input neuron type
GeneratorInputSpikingNeurons* generator_input_neurons = new GeneratorInputSpikingNeurons();
// PoissonInputSpikingNeurons* input neurons = new PoissonInputSpikingNeurons();
// Choose your neuron type
LIFSpikingNeurons* lif_spiking_neurons = new LIFSpikingNeurons();
// Choose your synapse type
ConductanceSpikingSynapses * conductance_spiking_synapses = new ConductanceSpikingSynapses();
// VoltageSpikingSynapses * voltage_spiking_synapses = new VoltageSpikingSynapses();
// CurrentSpikingSynapses * current_spiking_synapses = new CurrentSpikingSynapses();
// Allocate your chosen components to the simulator
ExampleModel->input_spiking_neurons = generator_input_neurons;
ExampleModel->spiking_neurons = lif_spiking_neurons;
ExampleModel->spiking_synapses = conductance_spiking_synapses;
/*
ADD ANY ACTIVITY MONITORS OR PLASTICITY RULES YOU WISH FOR
*/
SpikingActivityMonitor* spike_monitor = new SpikingActivityMonitor(lif_spiking_neurons);
SpikingActivityMonitor* input_spike_monitor = new SpikingActivityMonitor(generator_input_neurons);
ExampleModel->AddActivityMonitor(spike_monitor);
ExampleModel->AddActivityMonitor(input_spike_monitor);
/*
SETUP PROPERTIES AND CREATE NETWORK:
Note:
All Neuron, Synapse and STDP types have associated parameters structures.
These structures are defined in the header file for that class and allow us to set properties.
*/
int N_neurons = 1000;
// SETTING UP INPUT NEURONS
// Creating an input neuron parameter structure
generator_input_spiking_neuron_parameters_struct* input_neuron_params = new generator_input_spiking_neuron_parameters_struct();
// Setting the dimensions of the input neuron layer
input_neuron_params->group_shape[0] = 1; // x-dimension of the input neuron layer
input_neuron_params->group_shape[1] = N_neurons; // y-dimension of the input neuron layer
// Create a group of input neurons. This function returns the ID of the input neuron group
int input_layer_ID = ExampleModel->AddInputNeuronGroup(input_neuron_params);
// SETTING UP NEURON GROUPS
// Creating an LIF parameter structure for an excitatory neuron population and an inhibitory
// 1 x 100 Layer
lif_spiking_neuron_parameters_struct * excitatory_population_params = new lif_spiking_neuron_parameters_struct();
excitatory_population_params->group_shape[0] = 1;
excitatory_population_params->group_shape[1] = N_neurons;
excitatory_population_params->resting_potential_v0 = -0.074f;
excitatory_population_params->threshold_for_action_potential_spike = -0.053f;
excitatory_population_params->somatic_capacitance_Cm = 500.0*pow(10, -12);
excitatory_population_params->somatic_leakage_conductance_g0 = 25.0*pow(10, -9);
//lif_spiking_neuron_parameters_struct * inhibitory_population_params = new lif_spiking_neuron_parameters_struct();
//inhibitory_population_params->group_shape[0] = 1;
//inhibitory_population_params->group_shape[1] = 100;
//inhibitory_population_params->resting_potential_v0 = -0.082f;
//inhibitory_population_params->threshold_for_action_potential_spike = -0.053f;
//inhibitory_population_params->somatic_capacitance_Cm = 214.0*pow(10, -12);
//inhibitory_population_params->somatic_leakage_conductance_g0 = 18.0*pow(10, -9);
// Create populations of excitatory and inhibitory neurons
int excitatory_neuron_layer_ID = ExampleModel->AddNeuronGroup(excitatory_population_params);
//int inhibitory_neuron_layer_ID = ExampleModel->AddNeuronGroup(inhibitory_population_params);
// SETTING UP SYNAPSES
// Creating a synapses parameter structure for connections from the input neurons to the excitatory neurons
conductance_spiking_synapse_parameters_struct* input_to_excitatory_parameters = new conductance_spiking_synapse_parameters_struct();
input_to_excitatory_parameters->weight_range[0] = 0.5f; // Create uniform distributions of weights [0.5, 10.0]
input_to_excitatory_parameters->weight_range[1] = 10.0f;
input_to_excitatory_parameters->weight_scaling_constant = excitatory_population_params->somatic_leakage_conductance_g0;
input_to_excitatory_parameters->delay_range[0] = 8*timestep; // Create uniform distributions of delays [1 timestep, 5 timesteps]
input_to_excitatory_parameters->delay_range[1] = 8*timestep;
// The connectivity types for synapses include:
// CONNECTIVITY_TYPE_ALL_TO_ALL
// CONNECTIVITY_TYPE_ONE_TO_ONE
// CONNECTIVITY_TYPE_RANDOM
// CONNECTIVITY_TYPE_PAIRWISE
input_to_excitatory_parameters->connectivity_type = CONNECTIVITY_TYPE_ALL_TO_ALL;
//input_to_excitatory_parameters->plasticity_vec.push_back(STDP_RULE);
//// Creating a set of synapse parameters for connections from the excitatory neurons to the inhibitory neurons
//conductance_spiking_synapse_parameters_struct * excitatory_to_inhibitory_parameters = new conductance_spiking_synapse_parameters_struct();
//excitatory_to_inhibitory_parameters->weight_range[0] = 10.0f;
//excitatory_to_inhibitory_parameters->weight_range[1] = 10.0f;
//excitatory_to_inhibitory_parameters->weight_scaling_constant = inhibitory_population_params->somatic_leakage_conductance_g0;
//excitatory_to_inhibitory_parameters->delay_range[0] = 5.0*timestep;
//excitatory_to_inhibitory_parameters->delay_range[1] = 3.0f*pow(10, -3);
//excitatory_to_inhibitory_parameters->connectivity_type = CONNECTIVITY_TYPE_ONE_TO_ONE;
//// Creating a set of synapse parameters from the inhibitory neurons to the excitatory neurons
//conductance_spiking_synapse_parameters_struct * inhibitory_to_excitatory_parameters = new conductance_spiking_synapse_parameters_struct();
//inhibitory_to_excitatory_parameters->weight_range[0] = -5.0f;
//inhibitory_to_excitatory_parameters->weight_range[1] = -2.5f;
//inhibitory_to_excitatory_parameters->weight_scaling_constant = excitatory_population_params->somatic_leakage_conductance_g0;
//inhibitory_to_excitatory_parameters->delay_range[0] = 5.0*timestep;
//inhibitory_to_excitatory_parameters->delay_range[1] = 3.0f*pow(10, -3);
//inhibitory_to_excitatory_parameters->connectivity_type = CONNECTIVITY_TYPE_ALL_TO_ALL;
// CREATING SYNAPSES
// When creating synapses, the ids of the presynaptic and postsynaptic populations are all that are required
// Note: Input neuron populations cannot be post-synaptic on any synapse
ExampleModel->AddSynapseGroup(input_layer_ID, excitatory_neuron_layer_ID, input_to_excitatory_parameters);
//ExampleModel->AddSynapseGroup(excitatory_neuron_layer_ID, inhibitory_neuron_layer_ID, excitatory_to_inhibitory_parameters);
//ExampleModel->AddSynapseGroup(inhibitory_neuron_layer_ID, excitatory_neuron_layer_ID, inhibitory_to_excitatory_parameters);
/*
ADD INPUT STIMULI TO THE GENERATOR NEURONS CLASS
*/
// We can now assign a set of spike times to neurons in the input layer
int s1_num_spikes = N_neurons;
int s1_neuron_ids[s1_num_spikes];
float s1_spike_times[s1_num_spikes];
for(int i = 0; i<s1_num_spikes; i++) {
s1_neuron_ids[i] = i;
s1_spike_times[i] = 0;
}
// Adding this stimulus to the input neurons
int first_stimulus = generator_input_neurons->add_stimulus(s1_num_spikes, s1_neuron_ids, s1_spike_times);
// Creating a second stimulus
//int s2_num_spikes = 5;
//int s2_neuron_ids[5] = {2, 5, 9, 8, 0};
//float s2_spike_times[5] = {5.01f, 6.9f, 7.2f, 8.5f, 9.9f};
//int second_stimulus = generator_input_neurons->add_stimulus(s2_num_spikes, s2_neuron_ids, s2_spike_times);
/*
RUN THE SIMULATION
*/
// The only argument to run is the number of seconds
ExampleModel->finalise_model();
float simtime = 50.0f;
generator_input_neurons->select_stimulus(first_stimulus);
ExampleModel->run(simtime);
//generator_input_neurons->select_stimulus(second_stimulus);
//ExampleModel->run(simtime);
spike_monitor->save_spikes_as_txt("./tmp/neuron_dir/");
input_spike_monitor->save_spikes_as_txt("./tmp/input_dir/");
ExampleModel->spiking_synapses->save_connectivity_as_txt("./tmp/synapse_dir/");
spike_monitor->save_spikes_as_binary("./tmp/neuron_dir/");
input_spike_monitor->save_spikes_as_binary("./tmp/input_dir/");
ExampleModel->spiking_synapses->save_connectivity_as_binary("./tmp/synapse_dir/");
return 0;
}
| 48.255319 | 142 | 0.792549 | wxie2013 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.