hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
64356a56e03c56ce69c3546a7c1b1e5ca2f881a0 | 6,119 | hpp | C++ | examples/simple/src/codegen_helpers/type_erasure_common.hpp | mohibqureshi/CXXCTP | db7c80da469fe3511f7d8ac7f7dee7391122dac6 | [
"MIT"
] | 63 | 2019-08-30T11:53:47.000Z | 2021-05-19T06:17:47.000Z | examples/simple/src/codegen_helpers/type_erasure_common.hpp | mohibqureshi/CXXCTP | db7c80da469fe3511f7d8ac7f7dee7391122dac6 | [
"MIT"
] | 96 | 2019-09-16T05:03:31.000Z | 2020-10-14T14:33:50.000Z | examples/simple/src/codegen_helpers/type_erasure_common.hpp | mohibqureshi/CXXCTP | db7c80da469fe3511f7d8ac7f7dee7391122dac6 | [
"MIT"
] | 27 | 2019-09-25T10:12:37.000Z | 2020-05-06T02:59:44.000Z | #pragma once
//#include <iterator> // see https://vjordan.info/log/fpga/c-enum-range-based-for-loop.html
#include <array>
#include <memory>
namespace cxxctp {
namespace generated {
// _tc_model_t is the base class for _tc_impl_t. _tc_impl_t has the storage for the
// object of type_t. _tc_model_t has a virtual dtor to trigger _tc_impl_t's dtor.
// _tc_model_t has a virtual clone function to copy-construct an instance of
// _tc_impl_t into heap memory, which is returned via unique_ptr. _tc_model_t has
// a pure virtual function for each method in the interface class typeclass.
//#if 0
template<typename... typeclass>
struct _tc_model_t /*: public common__tc_model_t*/ {
//typedef typeclass... typeclass_type_t;
virtual ~_tc_model_t() noexcept { }
virtual std::unique_ptr<_tc_model_t>
clone() noexcept = 0;
virtual std::unique_ptr<_tc_model_t>
move_clone() noexcept = 0;
virtual std::string
get_GUID() noexcept = 0;
// Loop over each member function on the interface.
/*@meta for(int i = 0; i < @method_count(typeclass); ++i) {
@meta std::string func_name = @method_name(typeclass, i);
// Declare a "has_" function.
virtual bool @(format("has_%s", func_name.c_str()))() const = 0;
// Declare a pure virtual function for each interface method.
virtual @func_decl(@method_type(typeclass, i), func_name, args) = 0;
}*/
};
//#endif // 0
template<typename type_t, typename... typeclass>
struct _tc_impl_t : public _tc_model_t<typeclass...> {
typedef type_t val_type_t;
// Construct the embedded concrete type.
/*template<typename... args_t>
_tc_impl_t(args_t&&... args) : concrete(std::forward<args_t>(args)...) { }
std::unique_ptr<_tc_model_t<typeclass> > clone() override {
// Copy-construct a new instance of _tc_impl_t on the heap.
return std::make_unique<_tc_impl_t>(concrete);
}*/
// Loop over each member function on the interface.
/*@meta for(int i = 0; i < @method_count(typeclass); ++i) {
@meta std::string func_name = @method_name(typeclass, i);
@meta bool is_valid = @sfinae(
std::declval<type_t>().@(func_name)(
std::declval<@method_params(typeclass, i)>()...
)
);
// Implement the has_XXX function.
bool @(format("has_%s", func_name.c_str()))() const override {
return is_valid;
}
// Declare an override function with the same signature as the pure virtual
// function in _tc_model_t.
@func_decl(@method_type(typeclass, i), func_name, args) override {
@meta if(is_valid || @sfinae(typeclass::required::@(__func__))) {
// Forward to the correspondingly-named member function in type_t.
return concrete.@(__func__)(std::forward<decltype(args)>(args)...);
} else {
// We could also call __cxa_pure_virtual or std::terminate here.
throw std::runtime_error(@string(format("%s::%s not implemented",
@type_name(type_t), __func__
)));
}
}
}*/
// Our actual data.
//type_t concrete;
};
#if 0
// var_t is an 8-byte type that serves as the common wrapper for the
// type-erasure _tc_model_t. It implements move
template<typename... typeclass>
struct var_t {
//typedef typeclass typeclass_t;
// Default initializer creates an empty var_t.
//var_t() = default;
/*// Allow initialization from a unique_ptr.
var_t(std::unique_ptr<_tc_model_t<typeclass> >&& model) :
model(std::move(model)) { }
// Move ctor/assign by default.
var_t(var_t&&) = default;
var_t& operator=(var_t&&) = default;
// Call clone for copy ctor/assign.
var_t(const var_t& rhs) {
if(rhs)
model = rhs.model->clone();
}
var_t& operator=(const var_t& rhs) {
model.reset();
if(rhs)
model = rhs.model->clone();
return *this;
}*/
// A virtual dtor triggers the dtor in the impl.
//virtual ~var_t() { }
/*// The preferred initializer for a var_t. This constructs an _tc_impl_t of
// type_t on the heap, and stores the pointer in a new var_t.
template<typename type_t, typename... args_t>
static var_t construct(args_t&&... args) {
return var_t(std::make_unique<_tc_impl_t<typeclass, type_t> >(
std::forward<args_t>(args)...
));
}
// Loop over each member function on the interface.
@meta for(int i = 0; i < @method_count(typeclass); ++i) {
// Define a has_XXX member function.
bool @(format("has_%s", @method_name(typeclass, i)))() const {
@meta if(@sfinae(typeclass::required::@(@method_name(typeclass, i))))
return true;
else
return model->@(__func__)();
}
// Declare a non-virtual forwarding function for each interface method.
@func_decl(@method_type(typeclass, i), @method_name(typeclass, i), args) {
// Forward to the model's virtual function.
return model->@(__func__)(std::forward<decltype(args)>(args)...);
}
}
explicit operator bool() const {
return (bool)model;
}
// This is actually a unique_ptr to an impl type. We store a pointer to
// the base type and rely on _tc_model_t's virtual dtor to free the object.
std::unique_ptr<_tc_model_t<typeclass> > model;*/
};
#endif // 0
template<typename... typeclass>
struct _tc_combined_t {
};
// see https://github.com/joboccara/NamedType/blob/093e597e4d1d51614bc729fe2382c2db8925de75/named_type_impl.hpp#L18
template<typename T>
using IsNotReference = typename std::enable_if<!std::is_reference<T>::value, void>::type;
/*int constexpr strlength(const char* str)
{
return *str ? 1 + strlength(str + 1) : 0;
}
size_t constexpr Hash(const char *first)
{ // FNV-1a hash function
const size_t FNVoffsetBasis = 14695981039346656037ULL;
const size_t FNVprime = 1099511628211ULL;
const size_t count = strlength(first);
size_t val = FNVoffsetBasis;
for (size_t next = 0; next < count; ++next)
{
val ^= (size_t)first[next];
val *= FNVprime;
}
return val;
}*/
/*#ifdef COMPILE_DLL
#define CXXCTP_EXPORT __declspec( dllexport )
#else
#define CXXCTP_EXPORT __declspec( dllimport )
#endif*/
} // namespace cxxctp
} // namespace generated
| 30.442786 | 115 | 0.673639 | [
"object",
"model"
] |
643796154b2ded67ea531601698ec7d7fca011bc | 9,457 | cc | C++ | wrappers/8.1.1/vtkSubdivisionFilterWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 6 | 2016-02-03T12:48:36.000Z | 2020-09-16T15:07:51.000Z | wrappers/8.1.1/vtkSubdivisionFilterWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 4 | 2016-02-13T01:30:43.000Z | 2020-03-30T16:59:32.000Z | wrappers/8.1.1/vtkSubdivisionFilterWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | null | null | null | /* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>
#include "vtkPolyDataAlgorithmWrap.h"
#include "vtkSubdivisionFilterWrap.h"
#include "vtkObjectBaseWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkSubdivisionFilterWrap::ptpl;
VtkSubdivisionFilterWrap::VtkSubdivisionFilterWrap()
{ }
VtkSubdivisionFilterWrap::VtkSubdivisionFilterWrap(vtkSmartPointer<vtkSubdivisionFilter> _native)
{ native = _native; }
VtkSubdivisionFilterWrap::~VtkSubdivisionFilterWrap()
{ }
void VtkSubdivisionFilterWrap::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("vtkSubdivisionFilter").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("SubdivisionFilter").ToLocalChecked(), ConstructorGetter);
}
void VtkSubdivisionFilterWrap::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void VtkSubdivisionFilterWrap::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkPolyDataAlgorithmWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkPolyDataAlgorithmWrap::ptpl));
tpl->SetClassName(Nan::New("VtkSubdivisionFilterWrap").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "CheckForTrianglesOff", CheckForTrianglesOff);
Nan::SetPrototypeMethod(tpl, "checkForTrianglesOff", CheckForTrianglesOff);
Nan::SetPrototypeMethod(tpl, "CheckForTrianglesOn", CheckForTrianglesOn);
Nan::SetPrototypeMethod(tpl, "checkForTrianglesOn", CheckForTrianglesOn);
Nan::SetPrototypeMethod(tpl, "GetCheckForTriangles", GetCheckForTriangles);
Nan::SetPrototypeMethod(tpl, "getCheckForTriangles", GetCheckForTriangles);
Nan::SetPrototypeMethod(tpl, "GetCheckForTrianglesMaxValue", GetCheckForTrianglesMaxValue);
Nan::SetPrototypeMethod(tpl, "getCheckForTrianglesMaxValue", GetCheckForTrianglesMaxValue);
Nan::SetPrototypeMethod(tpl, "GetCheckForTrianglesMinValue", GetCheckForTrianglesMinValue);
Nan::SetPrototypeMethod(tpl, "getCheckForTrianglesMinValue", GetCheckForTrianglesMinValue);
Nan::SetPrototypeMethod(tpl, "GetNumberOfSubdivisions", GetNumberOfSubdivisions);
Nan::SetPrototypeMethod(tpl, "getNumberOfSubdivisions", GetNumberOfSubdivisions);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "SetCheckForTriangles", SetCheckForTriangles);
Nan::SetPrototypeMethod(tpl, "setCheckForTriangles", SetCheckForTriangles);
Nan::SetPrototypeMethod(tpl, "SetNumberOfSubdivisions", SetNumberOfSubdivisions);
Nan::SetPrototypeMethod(tpl, "setNumberOfSubdivisions", SetNumberOfSubdivisions);
#ifdef VTK_NODE_PLUS_VTKSUBDIVISIONFILTERWRAP_INITPTPL
VTK_NODE_PLUS_VTKSUBDIVISIONFILTERWRAP_INITPTPL
#endif
ptpl.Reset( tpl );
}
void VtkSubdivisionFilterWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
Nan::ThrowError("Cannot create instance of abstract class.");
return;
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void VtkSubdivisionFilterWrap::CheckForTrianglesOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSubdivisionFilterWrap *wrapper = ObjectWrap::Unwrap<VtkSubdivisionFilterWrap>(info.Holder());
vtkSubdivisionFilter *native = (vtkSubdivisionFilter *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CheckForTrianglesOff();
}
void VtkSubdivisionFilterWrap::CheckForTrianglesOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSubdivisionFilterWrap *wrapper = ObjectWrap::Unwrap<VtkSubdivisionFilterWrap>(info.Holder());
vtkSubdivisionFilter *native = (vtkSubdivisionFilter *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CheckForTrianglesOn();
}
void VtkSubdivisionFilterWrap::GetCheckForTriangles(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSubdivisionFilterWrap *wrapper = ObjectWrap::Unwrap<VtkSubdivisionFilterWrap>(info.Holder());
vtkSubdivisionFilter *native = (vtkSubdivisionFilter *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetCheckForTriangles();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkSubdivisionFilterWrap::GetCheckForTrianglesMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSubdivisionFilterWrap *wrapper = ObjectWrap::Unwrap<VtkSubdivisionFilterWrap>(info.Holder());
vtkSubdivisionFilter *native = (vtkSubdivisionFilter *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetCheckForTrianglesMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkSubdivisionFilterWrap::GetCheckForTrianglesMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSubdivisionFilterWrap *wrapper = ObjectWrap::Unwrap<VtkSubdivisionFilterWrap>(info.Holder());
vtkSubdivisionFilter *native = (vtkSubdivisionFilter *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetCheckForTrianglesMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkSubdivisionFilterWrap::GetNumberOfSubdivisions(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSubdivisionFilterWrap *wrapper = ObjectWrap::Unwrap<VtkSubdivisionFilterWrap>(info.Holder());
vtkSubdivisionFilter *native = (vtkSubdivisionFilter *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetNumberOfSubdivisions();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkSubdivisionFilterWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSubdivisionFilterWrap *wrapper = ObjectWrap::Unwrap<VtkSubdivisionFilterWrap>(info.Holder());
vtkSubdivisionFilter *native = (vtkSubdivisionFilter *)wrapper->native.GetPointer();
vtkSubdivisionFilter * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
VtkSubdivisionFilterWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkSubdivisionFilterWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkSubdivisionFilterWrap *w = new VtkSubdivisionFilterWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkSubdivisionFilterWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSubdivisionFilterWrap *wrapper = ObjectWrap::Unwrap<VtkSubdivisionFilterWrap>(info.Holder());
vtkSubdivisionFilter *native = (vtkSubdivisionFilter *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject());
vtkSubdivisionFilter * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObjectBase *) a0->native.GetPointer()
);
VtkSubdivisionFilterWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkSubdivisionFilterWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkSubdivisionFilterWrap *w = new VtkSubdivisionFilterWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkSubdivisionFilterWrap::SetCheckForTriangles(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSubdivisionFilterWrap *wrapper = ObjectWrap::Unwrap<VtkSubdivisionFilterWrap>(info.Holder());
vtkSubdivisionFilter *native = (vtkSubdivisionFilter *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetCheckForTriangles(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkSubdivisionFilterWrap::SetNumberOfSubdivisions(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkSubdivisionFilterWrap *wrapper = ObjectWrap::Unwrap<VtkSubdivisionFilterWrap>(info.Holder());
vtkSubdivisionFilter *native = (vtkSubdivisionFilter *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetNumberOfSubdivisions(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
| 33.416961 | 109 | 0.757111 | [
"object"
] |
6437e7973d927c5c107924438bcc119e2ad6f34f | 7,809 | cpp | C++ | Fragmenter/SortedOrderFragmenter.cpp | titawork/omniscidb | 4d89ae397a00adedd91697b49ed06078cbf33e64 | [
"Apache-2.0"
] | null | null | null | Fragmenter/SortedOrderFragmenter.cpp | titawork/omniscidb | 4d89ae397a00adedd91697b49ed06078cbf33e64 | [
"Apache-2.0"
] | null | null | null | Fragmenter/SortedOrderFragmenter.cpp | titawork/omniscidb | 4d89ae397a00adedd91697b49ed06078cbf33e64 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 OmniSci, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstring>
#include <numeric>
#include "../Catalog/Catalog.h"
#include "SortedOrderFragmenter.h"
namespace Fragmenter_Namespace {
template <typename T>
void shuffleByIndexesImpl(const std::vector<size_t>& indexes, T* buffer) {
std::vector<T> new_buffer;
new_buffer.reserve(indexes.size());
for (const auto i : indexes) {
new_buffer.push_back(buffer[i]);
}
std::memcpy(buffer, new_buffer.data(), indexes.size() * sizeof(T));
}
template <typename T>
void shuffleByIndexesImpl(const std::vector<size_t>& indexes, std::vector<T>& buffer) {
std::vector<T> new_buffer;
new_buffer.reserve(indexes.size());
for (const auto i : indexes) {
new_buffer.push_back(buffer[i]);
}
buffer.swap(new_buffer);
}
void shuffleByIndexes(const ColumnDescriptor* cd,
const std::vector<size_t>& indexes,
DataBlockPtr& data) {
const auto& ti = cd->columnType;
switch (ti.get_type()) {
case kBOOLEAN:
shuffleByIndexesImpl(indexes, reinterpret_cast<int8_t*>(data.numbersPtr));
break;
case kTINYINT:
shuffleByIndexesImpl(indexes, reinterpret_cast<int8_t*>(data.numbersPtr));
break;
case kSMALLINT:
shuffleByIndexesImpl(indexes, reinterpret_cast<int16_t*>(data.numbersPtr));
break;
case kINT:
shuffleByIndexesImpl(indexes, reinterpret_cast<int32_t*>(data.numbersPtr));
break;
case kBIGINT:
case kNUMERIC:
case kDECIMAL:
shuffleByIndexesImpl(indexes, reinterpret_cast<int64_t*>(data.numbersPtr));
break;
case kFLOAT:
shuffleByIndexesImpl(indexes, reinterpret_cast<float*>(data.numbersPtr));
break;
case kDOUBLE:
shuffleByIndexesImpl(indexes, reinterpret_cast<double*>(data.numbersPtr));
break;
case kTEXT:
case kVARCHAR:
case kCHAR:
if (ti.is_varlen()) {
shuffleByIndexesImpl(indexes, *data.stringsPtr);
} else {
switch (ti.get_size()) {
case 1:
shuffleByIndexesImpl(indexes, reinterpret_cast<int8_t*>(data.numbersPtr));
break;
case 2:
shuffleByIndexesImpl(indexes, reinterpret_cast<int16_t*>(data.numbersPtr));
break;
case 4:
shuffleByIndexesImpl(indexes, reinterpret_cast<int32_t*>(data.numbersPtr));
break;
default:
CHECK(false);
}
}
break;
case kDATE:
case kTIME:
case kTIMESTAMP:
shuffleByIndexesImpl(indexes, reinterpret_cast<int64_t*>(data.numbersPtr));
break;
case kARRAY:
shuffleByIndexesImpl(indexes, *data.arraysPtr);
break;
case kPOINT:
case kLINESTRING:
case kPOLYGON:
case kMULTIPOLYGON:
shuffleByIndexesImpl(indexes, *data.stringsPtr);
break;
default:
CHECK(false);
}
}
template <typename T>
void sortIndexesImpl(std::vector<size_t>& indexes, const T* buffer) {
std::sort(indexes.begin(), indexes.end(), [&](const auto a, const auto b) {
return buffer[a] < buffer[b];
});
}
void sortIndexesImpl(std::vector<size_t>& indexes,
const std::vector<std::string>& buffer) {
std::sort(indexes.begin(), indexes.end(), [&](const auto a, const auto b) {
return buffer[a].size() < buffer[b].size() ||
(buffer[a].size() == buffer[b].size() && buffer[a] < buffer[b]);
});
}
void sortIndexesImpl(std::vector<size_t>& indexes,
const std::vector<ArrayDatum>& buffer) {
std::sort(indexes.begin(), indexes.end(), [&](const auto a, const auto b) {
return buffer[a].is_null || buffer[a].length < buffer[b].length ||
(!buffer[b].is_null && buffer[a].length == buffer[b].length &&
memcmp(buffer[a].pointer, buffer[b].pointer, buffer[a].length) < 0);
});
}
void sortIndexes(const ColumnDescriptor* cd,
std::vector<size_t>& indexes,
const DataBlockPtr& data) {
const auto& ti = cd->columnType;
switch (ti.get_type()) {
case kBOOLEAN:
sortIndexesImpl(indexes, reinterpret_cast<int8_t*>(data.numbersPtr));
break;
case kTINYINT:
sortIndexesImpl(indexes, reinterpret_cast<int8_t*>(data.numbersPtr));
break;
case kSMALLINT:
sortIndexesImpl(indexes, reinterpret_cast<int16_t*>(data.numbersPtr));
break;
case kINT:
sortIndexesImpl(indexes, reinterpret_cast<int32_t*>(data.numbersPtr));
break;
case kBIGINT:
case kNUMERIC:
case kDECIMAL:
sortIndexesImpl(indexes, reinterpret_cast<int64_t*>(data.numbersPtr));
break;
case kFLOAT:
sortIndexesImpl(indexes, reinterpret_cast<float*>(data.numbersPtr));
break;
case kDOUBLE:
sortIndexesImpl(indexes, reinterpret_cast<double*>(data.numbersPtr));
break;
case kTEXT:
case kVARCHAR:
case kCHAR:
if (ti.is_varlen()) {
sortIndexesImpl(indexes, *data.stringsPtr);
} else {
switch (ti.get_size()) {
case 1:
sortIndexesImpl(indexes, reinterpret_cast<int8_t*>(data.numbersPtr));
break;
case 2:
sortIndexesImpl(indexes, reinterpret_cast<int16_t*>(data.numbersPtr));
break;
case 4:
sortIndexesImpl(indexes, reinterpret_cast<int32_t*>(data.numbersPtr));
break;
default:
CHECK(false);
}
}
break;
case kDATE:
case kTIME:
case kTIMESTAMP:
sortIndexesImpl(indexes, reinterpret_cast<int64_t*>(data.numbersPtr));
break;
case kARRAY:
sortIndexesImpl(indexes, *data.arraysPtr);
break;
default:
CHECK(false) << "invalid type '" << ti.get_type() << "' to sort";
}
}
void SortedOrderFragmenter::sortData(InsertData& insertDataStruct) {
// coming here table must have defined a sort_column for mini sort
const auto table_desc = catalog_->getMetadataForTable(physicalTableId_);
CHECK(table_desc);
CHECK_GT(table_desc->sortedColumnId, 0);
const auto logical_cd =
catalog_->getMetadataForColumn(table_desc->tableId, table_desc->sortedColumnId);
CHECK(logical_cd);
const auto physical_cd = catalog_->getMetadataForColumn(
table_desc->tableId,
table_desc->sortedColumnId + (logical_cd->columnType.is_geometry() ? 1 : 0));
const auto it = std::find(insertDataStruct.columnIds.begin(),
insertDataStruct.columnIds.end(),
physical_cd->columnId);
CHECK(it != insertDataStruct.columnIds.end());
// sort row indexes of the sort column
std::vector<size_t> indexes(insertDataStruct.numRows);
std::iota(indexes.begin(), indexes.end(), 0);
const auto dist = std::distance(insertDataStruct.columnIds.begin(), it);
CHECK_LT(dist, insertDataStruct.data.size());
sortIndexes(physical_cd, indexes, insertDataStruct.data[dist]);
// shuffle rows of all columns
for (size_t i = 0; i < insertDataStruct.columnIds.size(); ++i) {
const auto cd = catalog_->getMetadataForColumn(table_desc->tableId,
insertDataStruct.columnIds[i]);
shuffleByIndexes(cd, indexes, insertDataStruct.data[i]);
}
}
} // namespace Fragmenter_Namespace
| 34.25 | 87 | 0.651812 | [
"vector"
] |
644218e055124d28ddd3ea117900f86042caef31 | 20,584 | cpp | C++ | plugins/opencv/uw_predictor/featureExtraction.cpp | Kitware/VAIME | 47b24b9d8a208cf8c621e5bb1088c61fcf507af6 | [
"BSD-3-Clause"
] | 127 | 2019-05-23T10:05:25.000Z | 2022-03-28T05:14:11.000Z | plugins/opencv/uw_predictor/featureExtraction.cpp | Kitware/VAIME | 47b24b9d8a208cf8c621e5bb1088c61fcf507af6 | [
"BSD-3-Clause"
] | 39 | 2019-06-18T21:44:58.000Z | 2022-01-12T14:47:01.000Z | plugins/opencv/uw_predictor/featureExtraction.cpp | Kitware/VAIME | 47b24b9d8a208cf8c621e5bb1088c61fcf507af6 | [
"BSD-3-Clause"
] | 40 | 2016-08-23T21:44:17.000Z | 2019-04-20T23:39:53.000Z | #include "featureExtraction.h"
#include "util.h"
void localBinaryPatterns(InputArray src, OutputArray dst, int radius)
{
if(!src.obj) return;
Mat img = src.getMat();
dst.create(img.size(), CV_8U);
Mat outImg = dst.getMat();
for(int y = radius; y < img.rows - radius; ++y){
for(int x = radius; x < img.cols - radius; ++x){
Point cen(x, y);
uchar cenVal = img.at<uchar>(cen);
uchar lbpDecimal = 0;
for(int t = 0; t < 8; ++t){
float xx = cen.x + radius*cos(t*PI_/4.0);
float yy = cen.y + radius*sin(t*PI_/4.0);
float a = xx - floor(xx);
float b = yy - floor(yy);
uchar ptVal = uchar((1-a) * (1-b) * img.at<uchar>(int(floor(yy)), int(floor(xx)))
+ a * (1-b) * img.at<uchar>(int(floor(yy)), int(ceil(xx)))
+ (1-a) * b * img.at<uchar>(int(ceil(yy)), int(floor(xx)))
+ a * b * img.at<uchar>(int(ceil(yy)), int(ceil(xx))) );
if (ptVal > cenVal - 3){
lbpDecimal += 1 << (7-t);
}
}
outImg.at<uchar>(cen) = lbpDecimal;
}
}
}
vector<int>
FeatureExtraction::getCurvatureMaxIdx(const vector<Point>& contour)
{
int nP = contour.size(); // number of sample points around the contour
double s = 16.0; // Gaussian sigma
vector<int> x, y;
x.reserve(nP);
y.reserve(nP);
size_t size = contour.size();
for(int u = 0; u < nP; ++u){
x.push_back(contour[u*size/nP].x);
y.push_back(contour[u*size/nP].y);
}
// 1D gaussian kernel
vector<double> g, gu, guu;
for(int v = 0; v <= 4*s; ++v){
double G = exp(-0.5 * pow((v-2*s)/s, 2)) / sqrt(2*PI_) / s;
g.push_back(G);
gu.push_back(-(v-2*s)/pow(s, 2) * G);
guu.push_back((-pow(s, 2) + pow(v-2*s, 2)) / pow(s, 4) * G);
}
vector<double> X, Xu, Xuu, Y, Yu, Yuu, k;
X.reserve(nP);
Xu.reserve(nP);
Xuu.reserve(nP);
Y.reserve(nP);
Yu.reserve(nP);
Yuu.reserve(nP);
k.reserve(nP);
double maxAbsK = 0;
for(int i = 0; i < nP; ++i){
X.push_back(0);
Xu.push_back(0);
Xuu.push_back(0);
Y.push_back(0);
Yu.push_back(0);
Yuu.push_back(0);
for(int j = 0; j <= 4*s; ++j){
int idx = int(i-j+2*s);
idx = idx < 0 ? idx + nP : (idx >= nP ? idx - nP : idx);
X[i] += x[idx] * g[j];
Xu[i] += x[idx] * gu[j];
Xuu[i] += x[idx] * guu[j];
Y[i] += y[idx] * g[j];
Yu[i] += y[idx] * gu[j];
Yuu[i] += y[idx] * guu[j];
}
double ki = (Xu[i]*Yuu[i] - Xuu[i]*Yu[i]) / pow((Xu[i]*Xu[i] + Yu[i]*Yu[i]), 1.5);
k.push_back(ki);
if(abs(ki) > maxAbsK) maxAbsK = abs(ki);
}
vector<int> curvatureMaxIdx;
double prevK, nextK;
for(int i = 0; i < k.size(); ++i){
prevK = k[i-1 >= 0 ? i-1 : k.size()-1];
nextK = k[i+1 < k.size() ? i+1 : 0];
double absKi = abs(k[i]);
if(absKi > 0.1 * maxAbsK && abs(prevK) < absKi && abs(nextK) < absKi){
int idx = int(i * size / (float)nP + 0.5);
curvatureMaxIdx.push_back(idx);
}
}
return curvatureMaxIdx;
}
vector<double>
FeatureExtraction::getCurvature(const vector<Point>& contour)
{
int nP = contour.size();
double s = 4.0; // Gaussian sigma
vector<int> x, y;
x.reserve(nP);
y.reserve(nP);
size_t size = contour.size();
for(int u = 0; u < nP; ++u){
x.push_back(contour[u].x);
y.push_back(contour[u].y);
}
// 1D gaussian kernel
vector<double> g, gu, guu;
for(int v = 0; v <= 4*s; ++v){
double G = exp(-0.5 * pow((v-2*s)/s, 2)) / sqrt(2*PI_) / s;
g.push_back(G);
gu.push_back(-(v-2*s)/pow(s, 2) * G);
guu.push_back((-pow(s, 2) + pow(v-2*s, 2)) / pow(s, 4) * G);
}
vector<double> X, Xu, Xuu, Y, Yu, Yuu, kappa;
X.reserve(nP);
Xu.reserve(nP);
Xuu.reserve(nP);
Y.reserve(nP);
Yu.reserve(nP);
Yuu.reserve(nP);
kappa.reserve(nP);
for(int i = 0; i < nP; ++i){
X.push_back(0);
Xu.push_back(0);
Xuu.push_back(0);
Y.push_back(0);
Yu.push_back(0);
Yuu.push_back(0);
for(int j = 0; j <= 4*s; ++j){
int idx = int(i-j+2*s);
idx = idx < 0 ? idx + nP : (idx >= nP ? idx - nP : idx);
X[i] += x[idx] * g[j];
Xu[i] += x[idx] * gu[j];
Xuu[i] += x[idx] * guu[j];
Y[i] += y[idx] * g[j];
Yu[i] += y[idx] * gu[j];
Yuu[i] += y[idx] * guu[j];
}
double k = (Xu[i]*Yuu[i] - Xuu[i]*Yu[i]) / pow((Xu[i]*Xu[i] + Yu[i]*Yu[i]), 1.5);
kappa.push_back(k);
}
return kappa;
}
vector<pair<double, int>>
FeatureExtraction::getCSSMaxima(const FGObject& obj, OutputArray cssImg)
{
vector<Point> contour = obj.contour;
int nS = 200;
int nP = 200;
cssImg.create(nS, nP, CV_8U);
Mat css = cssImg.getMat();
cssImage(contour, css);
Mat cssImg8U = css.clone();
Mat se = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
dilate(cssImg8U, cssImg8U, se);
vector<vector<Point>> cssContours = extractContours(cssImg8U);
vector<pair<double, int>> cssMax;
for(int j = cssContours.size()-1; j >= 0; --j){
Point pt = cssContours[j][0];
double s = (199.0 - pt.y)*0.15 + 1.0;
if(j == cssContours.size()-1){
cssMax.push_back(make_pair(s, pt.x));
continue;
}
if(cssMax.size() > 0 && s <= cssMax.front().first / 5.0) break;
pair<double, int> back = cssMax.back();
// calculate the midpoint of two branch peaks
if(abs(back.first - s) < 0.15 && abs(back.second - pt.x) < 7){
int midX = (pt.x + back.second)/2;
cssMax.pop_back();
cssMax.push_back(make_pair(s, midX));
}
else{
cssMax.push_back(make_pair(s, pt.x));
}
}
return cssMax;
}
vector<double>
FeatureExtraction::getCurvature(const FGObject& obj)
{
int nP = 50; // number of sample points around the contour
int kw = 4; // Gaussian kernel width
double s = 2.0; // Gaussian sigma
vector<Point> contour = obj.contour;
vector<int> x, y;
x.reserve(nP);
y.reserve(nP);
size_t size = contour.size();
for(int u = 0; u < nP; ++u){
x.push_back(contour[u*size/nP].x);
y.push_back(contour[u*size/nP].y);
}
// 1D gaussian kernel
vector<double> g, gu, guu;
for(int v = 0; v <= 2*kw*s; ++v){
double G = exp(-0.5 * pow((v-kw*s)/s, 2)) / sqrt(2*PI_) / s;
g.push_back(G);
gu.push_back(-(v-kw*s)/pow(s, 2) * G);
guu.push_back((-pow(s, 2) + pow(v-kw*s, 2)) / pow(s, 4) * G);
}
vector<double> X, Xu, Xuu, Y, Yu, Yuu, k;
X.reserve(nP);
Xu.reserve(nP);
Xuu.reserve(nP);
Y.reserve(nP);
Yu.reserve(nP);
Yuu.reserve(nP);
k.reserve(nP);
for(int i = 0; i < nP; ++i){
X.push_back(0);
Xu.push_back(0);
Xuu.push_back(0);
Y.push_back(0);
Yu.push_back(0);
Yuu.push_back(0);
for(int j = 0; j <= 2*kw*s; ++j){
int idx = int(i-j+kw*s);
idx = idx < 0 ? idx + nP : (idx >= nP ? idx - nP : idx);
X[i] += x[idx] * g[j];
Xu[i] += x[idx] * gu[j];
Xuu[i] += x[idx] * guu[j];
Y[i] += y[idx] * g[j];
Yu[i] += y[idx] * gu[j];
Yuu[i] += y[idx] * guu[j];
}
double ki = (Xu[i]*Yuu[i] - Xuu[i]*Yu[i]) / pow((Xu[i]*Xu[i] + Yu[i]*Yu[i]), 1.5);
k.push_back(ki);
}
return k;
}
vector<int>
FeatureExtraction::getConcaveIndices(const FGObject& obj)
{
int nP = 100; // number of sample points around the contour
int kw = 4; // Gaussian kernel width
double s = 2.0; // Gaussian sigma
vector<Point> contour = obj.contour;
vector<int> x, y;
x.reserve(nP);
y.reserve(nP);
size_t size = contour.size();
for(int u = 0; u < nP; ++u){
x.push_back(contour[u*size/nP].x);
y.push_back(contour[u*size/nP].y);
}
// 1D gaussian kernel
vector<double> g, gu, guu;
for(int v = 0; v <= 2*kw*s; ++v){
double G = exp(-0.5 * pow((v-kw*s)/s, 2)) / sqrt(2*PI_) / s;
g.push_back(G);
gu.push_back(-(v-kw*s)/pow(s, 2) * G);
guu.push_back((-pow(s, 2) + pow(v-kw*s, 2)) / pow(s, 4) * G);
}
vector<double> X, Xu, Xuu, Y, Yu, Yuu, k;
X.reserve(nP);
Xu.reserve(nP);
Xuu.reserve(nP);
Y.reserve(nP);
Yu.reserve(nP);
Yuu.reserve(nP);
k.reserve(nP);
double maxK = 0;
for(int i = 0; i < nP; ++i){
X.push_back(0);
Xu.push_back(0);
Xuu.push_back(0);
Y.push_back(0);
Yu.push_back(0);
Yuu.push_back(0);
for(int j = 0; j <= 2*kw*s; ++j){
int idx = int(i-j+kw*s);
idx = idx < 0 ? idx + nP : (idx >= nP ? idx - nP : idx);
X[i] += x[idx] * g[j];
Xu[i] += x[idx] * gu[j];
Xuu[i] += x[idx] * guu[j];
Y[i] += y[idx] * g[j];
Yu[i] += y[idx] * gu[j];
Yuu[i] += y[idx] * guu[j];
}
double ki = (Xu[i]*Yuu[i] - Xuu[i]*Yu[i]) / pow((Xu[i]*Xu[i] + Yu[i]*Yu[i]), 1.5);
k.push_back(ki);
if(ki > maxK) maxK = ki;
}
vector<int> concave;
double prevK, nextK;
for(int i = 0; i < k.size(); ++i){
prevK = k[i-1 >= 0 ? i-1 : k.size()-1];
nextK = k[i+1 < k.size() ? i+1 : 0];
if(k[i] > 0.001*maxK && prevK < k[i] && nextK < k[i]){
int idx = int(i * size / (float)nP + 0.5);
concave.push_back(idx);
}
}
return concave;
}
void
FeatureExtraction::cssImage(vector<Point> contour, OutputArray cssImg)
{
int nP = 200;
int nS = 200;
double step = 0.15;
int kw = 4;
cssImg.create(nS, nP, CV_8U);
Mat outImg8U = cssImg.getMat();
outImg8U.setTo(Scalar(0));
vector<int> x, y;
x.reserve(nP);
y.reserve(nP);
size_t size = contour.size();
for(int u = 0; u < nP; ++u){
x.push_back(contour[u*size/nP].x);
y.push_back(contour[u*size/nP].y);
}
int r = nS-1;
for(double s = 1.0; s < 1.14+(nS-1)*step; s+=step){
// 1D gaussian kernel
vector<double> g, gu, guu;
for(int v = 0; v <= 2*kw*s; ++v){
double G = exp(-0.5 * pow((v-kw*s)/s, 2)) / sqrt(2*PI_) / s;
g.push_back(G);
gu.push_back(-(v-kw*s)/pow(s, 2) * G);
guu.push_back((-pow(s, 2) + pow(v-kw*s, 2)) / pow(s, 4) * G);
}
// convolution and calculate curvature
vector<double> X, Xu, Xuu, Y, Yu, Yuu, k;
vector<bool> dyLarge;
X.reserve(nP);
Xu.reserve(nP);
Xuu.reserve(nP);
Y.reserve(nP);
Yu.reserve(nP);
Yuu.reserve(nP);
k.reserve(nP);
dyLarge.reserve(nP);
for(int i = 0; i < nP; ++i){
X.push_back(0);
Xu.push_back(0);
Xuu.push_back(0);
Y.push_back(0);
Yu.push_back(0);
Yuu.push_back(0);
dyLarge.push_back(true);
for(int j = 0; j <= 2*kw*s; ++j){
int idx = int(i-j+kw*s);
idx = idx < 0 ? idx + nP : (idx >= nP ? idx - nP : idx);
X[i] += x[idx] * g[j];
Xu[i] += x[idx] * gu[j];
Xuu[i] += x[idx] * guu[j];
Y[i] += y[idx] * g[j];
Yu[i] += y[idx] * gu[j];
Yuu[i] += y[idx] * guu[j];
}
double ki = (Xu[i]*Yuu[i] - Xuu[i]*Yu[i]) / pow((Xu[i]*Xu[i] + Yu[i]*Yu[i]), 1.5);
k.push_back(ki);
}
/*for(int u = 1; u < nP-1; ++u){
if(abs(Y[u] - Y[u-1]) < 0.5 && abs(Y[u] - Y[u+1]) < 0.5){
for(int v = -1; v <= 1; ++v){
int idx = u+v < 0 ? 0 : (u+v >= nP ? nP-1 : u+v);
dyLarge[idx] = false;
}
}
}*/
for(int u = 0; u < nP; ++u){
if(k[u]*k[(u+1)%nP] < 0)
outImg8U.at<uchar>(r, u) = 255;
else
outImg8U.at<uchar>(r, u) = 0;
}
r--;
/*if(r % 10 == 9){
vector<Point> cc;
cc.reserve(200);
for(int i = 0; i < nP; ++i)
cc.push_back(Point(X[i], Y[i]));
vector<vector<Point>> ccs;
ccs.push_back(cc);
Mat smoothContour = Mat::zeros(param.getFrameHeight(), param.getFrameWidth(), CV_8U);
drawContours(smoothContour, ccs, 0, Scalar(255), -1);
showImage("smoothContour", smoothContour, 1, 1);
showImage("cssImg", outImg8U, 1);
int a = 1;
}*/
}
/*Mat se = getStructuringElement(MORPH_RECT, Size(1, 3));
morphologyEx(outImg8U, outImg8U, CV_MOP_CLOSE, se);
morphologyEx(outImg8U, outImg8U, CV_MOP_OPEN, se);*/
/*vector<vector<Point> > cssContours = extractContours(outImg8U);
for(size_t i = 0; i < cssContours.size(); ++i){
Rect bRect = boundingRect(cssContours[i]);
if(bRect.tl().y < 2 && bRect.height/(double)bRect.width > 4.0)
drawContours(outImg8U, cssContours, i, Scalar(0), -1);
}*/
//showImage("CSS", outImg8U, 1, 0);
}
float
FeatureExtraction::cssMatchingCost(const vector<pair<double, int>>& cssMax, const vector<pair<double, int>>& cssMaxRef)
{
float cost = abs(cssMax[0].first - cssMaxRef[0].first);
int shift = cssMax[0].second - cssMaxRef[0].second;
for(size_t j = 1; j < cssMax.size(); ++j){
if(j >= cssMaxRef.size() || abs(cssMax[j].second - cssMaxRef[j].second - shift) > 0.2*100)
cost += cssMax[j].first;
else
cost += abs(cssMax[j].first - cssMaxRef[j].first);
}
if(cssMax.size() < cssMaxRef.size()){
for(size_t k = cssMax.size(); k < cssMaxRef.size(); ++k)
cost += cssMaxRef[k].first;
}
return cost;
}
vector<double>
FeatureExtraction::getFourierDescriptor( const FGObject& obj )
{
int nP = 100;
vector<int> x, y;
x.reserve(nP);
y.reserve(nP);
size_t size = obj.contour.size();
for(int u = 0; u < nP; ++u){
x.push_back(obj.contour[u*size/nP].x);
y.push_back(obj.contour[u*size/nP].y);
}
vector<double> centDist;
centDist.reserve(nP);
for(int u = 0; u < nP; ++u){
Point2f p (x[u], y[u]);
double dist = norm(p - obj.uCenter);
centDist.push_back(dist);
}
vector<complex<double>> DFT;
DFT.reserve(centDist.size());
DFT = discreteFourierTransform(centDist);
vector<double> FD;
FD.reserve(DFT.size());
double dcMag = abs(DFT[0]);
for(size_t i = 1; i < DFT.size()/2; ++i){
double mag = abs(DFT[i]);
FD.push_back(mag / dcMag);
}
return FD;
}
vector<double>
FeatureExtraction::getFourierDescriptor( const vector<Point>& contour )
{
int nP = 40;
vector<int> x, y;
x.reserve(nP);
y.reserve(nP);
size_t size = contour.size();
int sumX = 0, sumY = 0;
for(int u = 0; u < nP; ++u){
x.push_back(contour[u*size/nP].x);
y.push_back(contour[u*size/nP].y);
sumX += contour[u*size/nP].x;
sumY += contour[u*size/nP].y;
}
Point2f cen (sumX / nP, sumY / nP);
vector<double> centDist;
centDist.reserve(nP);
for(int u = 0; u < nP; ++u){
Point2f p (x[u], y[u]);
double dist = norm(p - cen);
centDist.push_back(dist);
}
vector<complex<double>> DFT;
DFT.reserve(centDist.size());
DFT = discreteFourierTransform(centDist);
vector<double> FD;
FD.reserve(DFT.size()/2);
double dcMag = abs(DFT[0]);
for(size_t i = 1; i < DFT.size()/2; ++i){
double mag = abs(DFT[i]);
FD.push_back(mag / dcMag);
}
return FD;
}
vector<double> FeatureExtraction::getCorrelation(const vector<Point>& contour, bool isTailAtRight) {
int nP = 40;
vector<int> x, y;
x.reserve(nP);
y.reserve(nP);
size_t size = contour.size();
int sumX = 0, sumY = 0;
int root = contour[0].x;
for(int u = 0; u < nP; ++u){
x.push_back(contour[u*size/nP].x);
y.push_back(contour[u*size/nP].y);
sumX += contour[u*size/nP].x;
sumY += contour[u*size/nP].y;
if (!isTailAtRight) {
if (x[u]<root)
root = x[u];
}
else {
if (x[u]>root)
root = x[u];
}
}
Point2f cen (root, sumY / nP);
vector<double> centDist;
centDist.reserve(nP);
for(int u = 0; u < nP; ++u){
Point2f p (x[u], y[u]);
double dist = norm(p - cen);
centDist.push_back(dist);
}
// normalize
double vectNorm = 0.0;
for (int u = 0; u < nP; ++u) {
vectNorm += centDist[u]*centDist[u];
}
vectNorm = sqrt(vectNorm);
for (int u = 0; u < nP; ++u) {
centDist[u] = centDist[u]/vectNorm;
}
vector<double> autoCorr(nP/2, 0.0);
for (int n = 1; n <= autoCorr.size(); n++) {
vector<double> x2 = centDist;
rotate(x2.begin(),x2.begin()+n,x2.end());
//for (int m = 0; m < n; m++) {
// x2[m] = 0.0;
//}
for (int u = 0; u < nP; u++)
autoCorr[n-1] += centDist[u]*x2[u];
}
return autoCorr;
}
// returns the magnitude of the DFT of a real-number series
vector<complex<double>> FeatureExtraction::discreteFourierTransform( const vector<double>& inputSeries )
{
int M = inputSeries.size();
vector<complex<double>> DFT;
DFT.reserve(inputSeries.size());
for(int k = 0; k < M; ++k){
double re = 0;
double im = 0;
for(int n = 0; n < M; ++n){
double theta = -2 * PI_ * k * (double)n / (double)M;
double cos_theta = cos(theta);
double sin_theta = sin(theta);
re += inputSeries[n] * cos_theta;
im += inputSeries[n] * sin_theta;
}
complex<double> z (re, im);
DFT.push_back(z);
}
return DFT;
}
/*void FeatureExtraction::getSIFTdescriptor( const FGObject& obj, InputArray src, OutputArray dst )
{
if(!src.getObj()) return;
Mat inImg = src.getMat();
Size dsize;
if(inImg.rows >= inImg.cols)
dsize = Size(300, int(inImg.cols/(float)inImg.rows * 300 + 0.5));
else
dsize = Size(int(inImg.rows/(float)inImg.cols * 300 + 0.5), 300);
Mat resizedImg;
resize(inImg, resizedImg, dsize);
// dense sampling for keypoints
int patchWidth = 16;
int step = 8;
vector<KeyPoint> keypoints;
for(int y = step; y < resizedImg.rows - step; y += step){
for(int x = step; x < resizedImg.cols - step; x += step){
float angle = principalOrientation(resizedImg, x, y, patchWidth);
KeyPoint kp(x, y, patchWidth, angle);
keypoints.push_back(kp);
}
}
Mat descriptors;
SiftDescriptorExtractor extractor;
extractor.compute(resizedImg, keypoints, descriptors);
dst.create(descriptors.size(), descriptors.type());
Mat outMat = dst.getMat();
descriptors.copyTo(outMat);
}*/
float
FeatureExtraction::principalOrientation(Mat img, int x, int y, int size)
{
vector<int> histOri;
histOri.reserve(8);
for(int k = 0; k < 8; ++k)
histOri.push_back(0);
for(int j = y - size/2; j <= y + size/2; ++j){
for(int i = x - size/2; i <= x + size/2; ++i){
float diffX = 0, diffY = 0;
if(j+1 >= img.rows)
diffY = (float)img.at<uchar>(j, i) - (float)img.at<uchar>(j-1, i);
else if(j-1 < 0)
diffY = (float)img.at<uchar>(j+1, i) - (float)img.at<uchar>(j, i);
else
diffY = (float)img.at<uchar>(j+1, i) - (float)img.at<uchar>(j-1, i);
if(i+1 >= img.cols)
diffX = (float)img.at<uchar>(j, i) - (float)img.at<uchar>(j, i-1);
else if(i-1 < 0)
diffX = (float)img.at<uchar>(j, i+1) - (float)img.at<uchar>(j, i);
else
diffX = (float)img.at<uchar>(j, i+1) - (float)img.at<uchar>(j, i-1);
int angle = int(atan2(diffY, diffX) / (0.25*PI_) + 4.0);
if(angle == 8) angle = 7;
++histOri[angle];
}
}
int binHeight = 0;
int idx = 0;
for(int k = 0; k < 8; ++k){
if(histOri[k] > binHeight){
binHeight = histOri[k];
idx = k;
}
}
float ori = (idx - 4) * (0.25*PI_);
return ori;
}
void getHOGFeat(Mat& src, vector<float>& dst) {
int blockSize = 32;
int blockStride = 16;
int cellSize = 16;
int nbin = 9;
HOGDescriptor hog(src.size(), Size(blockSize, blockSize), Size(blockStride,blockStride), Size(cellSize,cellSize), nbin);
vector<Point> locs;
hog.compute(src, dst, Size(0,0), Size(0,0), locs);
}
vector<double> getGradHist(Mat img, Mat fg) {
int ddepth = CV_16S;
int scale = 1;
int delta = 0;
Mat grad;
//GaussianBlur(img, img, Size(3,3), 0, 0, BORDER_DEFAULT);
/// Generate grad_x and grad_y
Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
/// Gradient X
Sobel(img, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT );
convertScaleAbs(grad_x, abs_grad_x);
/// Gradient Y
Sobel(img, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT );
convertScaleAbs(grad_y, abs_grad_y);
/// Total Gradient (approximate)
addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
double min, max;
minMaxLoc(grad, &min, &max);
vector<double> grad_hist(6,0.0);
for (int m = 0; m < grad.rows; m++) {
for (int n = 0; n < grad.cols; n++) {
if (grad.at<uchar>(m,n)<16.0 || fg.at<uchar>(m,n)==0)
continue;
if (grad.at<uchar>(m,n)>=16.0 && grad.at<uchar>(m,n)<60.0) {
grad_hist[0]++;
continue;
}
if (grad.at<uchar>(m,n)>=60.0 && grad.at<uchar>(m,n)<117.0) {
grad_hist[1]++;
continue;
}
if (grad.at<uchar>(m,n)>=117.0 && grad.at<uchar>(m,n)<150.0) {
grad_hist[2]++;
continue;
}
if (grad.at<uchar>(m,n)>=150.0 && grad.at<uchar>(m,n)<180.0) {
grad_hist[3]++;
continue;
}
if (grad.at<uchar>(m,n)>=180.0 && grad.at<uchar>(m,n)<235.0) {
grad_hist[4]++;
continue;
}
if (grad.at<uchar>(m,n)>=235.0) {
grad_hist[5]++;
continue;
}
}
}
double sum_v = grad_hist[0]+grad_hist[1]+grad_hist[2]+grad_hist[3]+grad_hist[4]+grad_hist[5];
for (int n = 0; n < 6; n++)
grad_hist[n] = grad_hist[n]/sum_v;
//imshow("grad",grad);
//waitKey(0);
return grad_hist;
} | 25.506815 | 122 | 0.557035 | [
"vector"
] |
6447c609515cc9871eb51966f7cf5366b51ee96a | 3,780 | hpp | C++ | pc/attr_id.hpp | rtilder/pyth-client | aaf33e1dd13c7c945f1545dd5b207646cba034d3 | [
"Apache-2.0"
] | 89 | 2021-05-13T15:05:45.000Z | 2022-03-17T16:42:21.000Z | pc/attr_id.hpp | rtilder/pyth-client | aaf33e1dd13c7c945f1545dd5b207646cba034d3 | [
"Apache-2.0"
] | 46 | 2021-05-14T15:26:14.000Z | 2022-03-31T11:33:48.000Z | pc/attr_id.hpp | rtilder/pyth-client | aaf33e1dd13c7c945f1545dd5b207646cba034d3 | [
"Apache-2.0"
] | 50 | 2021-05-18T05:10:38.000Z | 2022-03-31T22:26:28.000Z | #pragma once
#include <pc/hash_map.hpp>
#include <pc/net_socket.hpp>
#include <pc/misc.hpp>
#include <pc/jtree.hpp>
#include <oracle/oracle.h>
namespace pc
{
// product reference attribute id
class attr_id
{
public:
attr_id();
attr_id( uint32_t );
attr_id( str );
bool is_valid() const;
str get_str() const;
uint32_t get_id() const;
static attr_id add( str );
private:
uint32_t id_;
};
// dictionary of attribute values corresponding to attribute ids
class attr_dict
{
public:
// get string value corresponding to attribute id
bool get_attr( attr_id, str& ) const;
// number of attributes in dictionary
unsigned get_num_attr() const;
// for iterating through attributes - for example:
// str vstr;
// attr_dict d;
// for(attr_id id; d.get_next_attr( id, vstr ); ) {
// std::string key( id.get_str() ), val( vstr );
// std::cout << "attr=" << key << ",val=" << val << std::endl;
// }
bool get_next_attr( attr_id&, str& ) const;
public:
// initialize from on-chain product account data
bool init_from_account( pc_prod_t * );
// initialize from json parse tree
bool init_from_json( jtree&, uint32_t tok = 1 );
// serialize in account format
void write_account( net_wtr& );
// serialize to json
void write_json( json_wtr& ) const;
private:
struct pos { pos(); uint16_t idx_, len_; };
typedef std::vector<char> abuf_t;
typedef std::vector<pos> attr_t;
void add_ref( attr_id aid, str val );
void clear();
abuf_t abuf_;
attr_t avec_;
unsigned num_;
};
// manager unique set of attribute ids
class attr_id_set
{
public:
// get or add attribute id
attr_id add_attr_id( str );
// get attribute by string
attr_id get_attr_id( str );
// get string from attribute id
str get_str( attr_id );
// is a valid attribute id
bool is_valid( attr_id );
// number of attribute ids
unsigned get_num_attr_id() const;
// singleton instance
static attr_id_set& inst();
private:
attr_id_set();
class attr_wtr : public net_wtr {
public:
str add_attr( str );
};
struct trait_str {
static const size_t hsize_ = 307UL;
typedef uint32_t idx_t;
typedef str key_t;
typedef str keyref_t;
typedef attr_id val_t;
struct hash_t {
idx_t operator() ( keyref_t s ) {
if ( s.len_ >= 8 ) return ((uint64_t*)s.str_)[0];
if ( s.len_ >= 4 ) return ((uint32_t*)s.str_)[0];
if ( s.len_ >= 2 ) return ((uint16_t*)s.str_)[0];
return s.len_ ? (idx_t)s.str_[0] : 0;
}
};
};
typedef hash_map<trait_str> attr_map_t;
typedef std::vector<str> attr_vec_t;
attr_map_t amap_;
attr_vec_t avec_;
attr_wtr abuf_;
uint32_t aid_;
};
inline unsigned attr_id_set::get_num_attr_id() const
{
return aid_;
}
inline bool attr_id_set::is_valid( attr_id aid )
{
return aid.get_id() != 0 && aid.get_id() < avec_.size();
}
inline attr_id::attr_id() : id_( 0 ) {
}
inline attr_id::attr_id( uint32_t id ) : id_( id ) {
}
inline attr_id::attr_id( str v ) {
*this = attr_id_set::inst().get_attr_id( v );
}
inline bool attr_id::is_valid() const {
return attr_id_set::inst().is_valid( *this );
}
inline str attr_id::get_str() const {
return attr_id_set::inst().get_str( *this );
}
inline uint32_t attr_id::get_id() const {
return id_;
}
inline attr_id attr_id::add( str val ) {
return attr_id_set::inst().add_attr_id( val );
}
inline attr_id_set& attr_id_set::inst() {
static attr_id_set aset;
return aset;
}
}
| 21.355932 | 68 | 0.609524 | [
"vector"
] |
644da7afb6cea9c330617f868cdad6b87bac95f7 | 534 | cpp | C++ | Pinochle/Pinochle.cpp | nparajul/Pinochle | 5cf692deb21be40929dd77659e98e42a79aedbbd | [
"MIT"
] | 1 | 2020-11-03T18:08:18.000Z | 2020-11-03T18:08:18.000Z | Pinochle/Pinochle.cpp | nparajul/Pinochle | 5cf692deb21be40929dd77659e98e42a79aedbbd | [
"MIT"
] | null | null | null | Pinochle/Pinochle.cpp | nparajul/Pinochle | 5cf692deb21be40929dd77659e98e42a79aedbbd | [
"MIT"
] | null | null | null | /*
************************************************************
* Name: Nitesh Parajuli *
* Project: Project 1 Pinochle C++ *
* Class: CMPS366 OPL *
* Date: 09/29/2020 *
************************************************************
*/
#include "pch.h"
#include "Game.h"
#include"Deck.h"
using namespace std;
int main()
{
// Initialize a game object
Game game = Game();
//start the game
game.beginGame();
return 0;
}
| 19.777778 | 60 | 0.361423 | [
"object"
] |
644eff020961c8a4035bb94ac813950ff11d32ed | 6,298 | hpp | C++ | lib/clustering_phases/initialization.hpp | YannisLamp/crypto_recommendation | b7c0d2a4e11080470a6ded43459ab39cd183dd81 | [
"MIT"
] | 1 | 2021-03-17T00:43:46.000Z | 2021-03-17T00:43:46.000Z | lib/clustering_phases/initialization.hpp | YannisLamp/crypto-recommendation | b7c0d2a4e11080470a6ded43459ab39cd183dd81 | [
"MIT"
] | null | null | null | lib/clustering_phases/initialization.hpp | YannisLamp/crypto-recommendation | b7c0d2a4e11080470a6ded43459ab39cd183dd81 | [
"MIT"
] | null | null | null | #ifndef CLUSTER_INITIALIZATION_H
#define CLUSTER_INITIALIZATION_H
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <chrono>
#include <random>
#include "../data_structures/cust_vector.hpp"
/*
* Functions used to implement various initialization algorithms required for vector clustering
* Namely, random selection and k-means++
*
* All functions are templated, so they can be used for any kind of input vector type
*/
// Function that selects random k unique vectors uniformly from input to serve as initial centroids
template <typename vector_type>
std::vector< CustVector<vector_type>* > rand_selection(std::vector< CustVector<vector_type> >& input_vectors, int cluster_num);
// Function uses the k-means++ algorithm to select initial centroids
// Basically, in each iteration, pick a new centroid randomly among input vectors, but with probability proportional to
// the distance of that vector to its closest centroid (that have been previously selected)
template <typename vector_type>
std::vector< CustVector<vector_type>* > k_means_pp(std::vector< CustVector<vector_type> >& input_vectors, int cluster_num,
std::string metric_type);
/*
* Function definitions
*/
template <typename vector_type>
std::vector< CustVector<vector_type>* > rand_selection(std::vector< CustVector<vector_type> >& input_vectors, int cluster_num) {
// Uniform integer random stuff and rand_generator initialization
unsigned long seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine rand_generator;
rand_generator.seed(seed);
std::uniform_int_distribution<int> uni_int_dist(0, input_vectors.size()-1);
int rand_i = uni_int_dist(rand_generator);
// Random centroids to return
std::vector< CustVector<vector_type>* > centroids(cluster_num);
centroids[0] = &input_vectors[rand_i];
for (int i = 1; i < cluster_num; i++) {
rand_i = uni_int_dist(rand_generator);
int centroid_i = 0;
while (centroid_i < i) {
// If the same centroid happens to be chosen randomly a second time, then choose another and search again
if (input_vectors[rand_i].getId() == centroids[centroid_i]->getId()) {
rand_i = uni_int_dist(rand_generator);
centroid_i = 0;
}
else
centroid_i++;
}
centroids[i] = &input_vectors[rand_i];
}
return centroids;
}
template <typename vector_type>
std::vector< CustVector<vector_type>* > k_means_pp(std::vector< CustVector<vector_type> >& input_vectors, int cluster_num,
std::string metric_type) {
// Uniform integer random stuff and rand_generator initialization
unsigned long seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine rand_generator;
rand_generator.seed(seed);
std::uniform_int_distribution<int> uni_int_dist(0, input_vectors.size()-1);
int rand_i = uni_int_dist(rand_generator);
// Centroids to return
// Initially, pick a random vector as the first centroid to start the main algorithm
std::vector<CustVector<vector_type>* > centroids(cluster_num);
centroids[0] = &input_vectors[rand_i];
// Cache distances that have already been calculated
std::unordered_map<std::string, double> distanceMap;
std::vector<double> min_dists(input_vectors.size());
for (int i = 1; i < cluster_num; i++) {
double max_for_normalizing = 0;
for (int vector_i = 0; vector_i < input_vectors.size(); vector_i++) {
// Find min distance from cetroids
double min = -1;
for (int centroid_i = 0; centroid_i < i; centroid_i++) {
std::string key = input_vectors[vector_i].getId() + "to" + centroids[centroid_i]->getId();
double distance = 0;
if (distanceMap.count(key) == 1) {
distance = distanceMap[key];
}
else {
if (metric_type == "euclidean")
distance = input_vectors[vector_i].euclideanDistance(centroids[centroid_i]);
else if (metric_type == "cosine")
distance = input_vectors[vector_i].cosineDistance(centroids[centroid_i]);
distanceMap[key] = distance;
}
if (min == -1 || distance < min)
min = distance;
}
min_dists[vector_i] = min;
if (min > max_for_normalizing)
max_for_normalizing = min;
}
// Divide all minimums with the one with the greates value for normalizing, square them and
// for each one, add the previous to its value
min_dists[0] = min_dists[0] / max_for_normalizing;
min_dists[0] = min_dists[0] * min_dists[0];
for (int min_i = 1; min_i < min_dists.size(); min_i++) {
min_dists[min_i] = min_dists[min_i] / max_for_normalizing;
min_dists[min_i] = min_dists[min_i] * min_dists[min_i];
min_dists[min_i] = min_dists[min_i] + min_dists[min_i-1];
}
// Choose random double and perform a binary search to find the input vector whose area corresponds to it
std::uniform_real_distribution<double> uni_double_dist(0.0, min_dists[min_dists.size()-1]);
double rand_dis = uni_double_dist(rand_generator);
int left = 0;
int right = min_dists.size()-1;
// Custom binary search, basically search for the two numbers that the random float can be put between
// When found, exit and return the index of the right one, only if the random number is not lower than the first
int chosen_i = 0;
if (rand_dis > min_dists[left]) {
while (right - left > 1) {
int m = left + (right - left) / 2;
if (rand_dis <= min_dists[m])
right = m;
else
left = m;
}
chosen_i = right;
}
// Add chosen centroid
centroids[i] = &input_vectors[chosen_i];
}
return centroids;
}
#endif //CLUSTER_INITIALIZATION_H
| 39.3625 | 128 | 0.638457 | [
"vector"
] |
6457340b2216555e3291c670e24c3588c1a6ae1c | 3,640 | cxx | C++ | source/Tools/ComputeLandmarkRegistrationError.cxx | tschuls/ETH-SegReg-DLL | 34bd10464dc5e8b3c7bf3371ca1e190d692385b7 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | source/Tools/ComputeLandmarkRegistrationError.cxx | tschuls/ETH-SegReg-DLL | 34bd10464dc5e8b3c7bf3371ca1e190d692385b7 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | source/Tools/ComputeLandmarkRegistrationError.cxx | tschuls/ETH-SegReg-DLL | 34bd10464dc5e8b3c7bf3371ca1e190d692385b7 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #include "Log.h"
#include <stdio.h>
#include <iostream>
#include "ArgumentParser.h"
#include "ImageUtils.h"
#include "TransformationUtils.h"
#include <itkWarpImageFilter.h>
#include <fstream>
#include <itkInverseDisplacementFieldImageFilter.h>
using namespace std;
using namespace itk;
int main(int argc, char ** argv)
{
//feraiseexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);
typedef unsigned short PixelType;
const unsigned int D=2;
typedef Image<PixelType,D> ImageType;
typedef ImageType::IndexType IndexType;
typedef ImageType::PointType PointType;
typedef ImageType::Pointer ImagePointerType;
typedef ImageType::ConstPointer ImageConstPointerType;
typedef Vector<float,D> LabelType;
typedef Image<LabelType,D> LabelImageType;
typedef LabelImageType::Pointer LabelImagePointerType;
typedef ImageType::IndexType IndexType;
LabelImagePointerType deformation = ImageUtils<LabelImageType>::readImage(argv[1]);
PointType p;
p.Fill(0.0);
deformation->SetOrigin(0.0);
ImagePointerType referenceImage=ImageUtils<ImageType>::readImage(argv[2]);
ImagePointerType targetLandmarkImage=ImageUtils<ImageType>::createEmpty(referenceImage);
ImagePointerType deformedReferenceLandmarkImage=ImageUtils<ImageType>::createEmpty(referenceImage);
targetLandmarkImage->FillBuffer(0); deformedReferenceLandmarkImage->FillBuffer(0);
vector<PointType> landmarksReference, landmarksTarget;
ifstream ifs(argv[3]);
int i=0;
while ( ! ifs.eof() ) {
PointType point;
for (int d=0;d<D;++d){
ifs>>point[d];
}
LOG<<point<<endl;
landmarksReference.push_back(point);
}
std::cout<<"read "<<landmarksReference.size()<<" landmarks"<<std::endl;
double sumSquareError=0.0;
ifstream ifs2(argv[4]);
i=0;
for (;i<landmarksReference.size();++i){
PointType idx;
for (int d=0;d<D;++d){
ifs2>>idx[d];
}
IndexType index;
targetLandmarkImage->TransformPhysicalPointToIndex(idx,index);
targetLandmarkImage->SetPixel(index,65535);
PointType deformedReferencePoint,targetPoint=idx;
//referenceImage->TransformIndexToPhysicalPoint(landmarksReference[i],deformedReferencePoint);
//deformation->TransformIndexToPhysicalPoint(idx,targetPoint);
referenceImage->TransformPhysicalPointToIndex(landmarksReference[i],index);
//std::cout<<VAR(targetPoint)<<endl;
for (int i2 = 0; i2 < D; i2++) {
deformedReferencePoint[i2] = landmarksReference[i][i2] + deformation->GetPixel(index)[i2];
}
//deformedReferencePoint+=invertedDeformation->GetPixel(landmarksReference[i]);
referenceImage->TransformPhysicalPointToIndex(deformedReferencePoint,index);
deformedReferenceLandmarkImage->SetPixel(index,65535);
double localSquaredError=0;
for (int d=0;d<D;++d){
localSquaredError+=(targetPoint[d]-deformedReferencePoint[d])*(targetPoint[d]-deformedReferencePoint[d]);
}
//std::cout<<VAR(targetPoint)<<" "<<VAR(deformedReferencePoint)<<endl;
std::cout<<"pt"<<i<<": "<<sqrt(localSquaredError)<<" ";
sumSquareError+=sqrt(localSquaredError);
}
std::cout<<std::endl<<"totalAverage: "<<(sumSquareError)/(i+1)<<std::endl;
if (argc>6){
ImageUtils<ImageType>::writeImage(argv[5], (ImageConstPointerType) deformedReferenceLandmarkImage );
ImageUtils<ImageType>::writeImage(argv[6], (ImageConstPointerType) targetLandmarkImage );
}
return 1;
}
| 35.686275 | 117 | 0.688462 | [
"vector"
] |
645b85254dc80d0fe61415795c2d4e9aee7228f4 | 19,236 | cpp | C++ | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGTextContentElement.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGTextContentElement.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8SVGTextContentElement.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8SVGTextContentElement.h"
#include "bindings/core/v8/V8SVGAnimatedEnumeration.h"
#include "bindings/core/v8/V8SVGAnimatedLength.h"
#include "bindings/core/v8/V8SVGPoint.h"
#include "bindings/core/v8/V8SVGRect.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/V8DOMConfiguration.h"
#include "bindings/v8/V8HiddenValue.h"
#include "bindings/v8/V8ObjectConstructor.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace WebCore {
static void initializeScriptWrappableForInterface(SVGTextContentElement* object)
{
if (ScriptWrappable::wrapperCanBeStoredInObject(object))
ScriptWrappable::fromObject(object)->setTypeInfo(&V8SVGTextContentElement::wrapperTypeInfo);
else
ASSERT_NOT_REACHED();
}
} // namespace WebCore
void webCoreInitializeScriptWrappableForInterface(WebCore::SVGTextContentElement* object)
{
WebCore::initializeScriptWrappableForInterface(object);
}
namespace WebCore {
const WrapperTypeInfo V8SVGTextContentElement::wrapperTypeInfo = { gin::kEmbedderBlink, V8SVGTextContentElement::domTemplate, V8SVGTextContentElement::derefObject, 0, V8SVGTextContentElement::toEventTarget, 0, V8SVGTextContentElement::installPerContextEnabledMethods, &V8SVGGraphicsElement::wrapperTypeInfo, WrapperTypeObjectPrototype, WillBeGarbageCollectedObject };
namespace SVGTextContentElementV8Internal {
template <typename T> void V8_USE(T) { }
static void textLengthAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGTextContentElement* impl = V8SVGTextContentElement::toNative(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->textLength()), impl);
}
static void textLengthAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGTextContentElementV8Internal::textLengthAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void lengthAdjustAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGTextContentElement* impl = V8SVGTextContentElement::toNative(holder);
v8SetReturnValueFast(info, WTF::getPtr(impl->lengthAdjust()), impl);
}
static void lengthAdjustAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGTextContentElementV8Internal::lengthAdjustAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void getNumberOfCharsMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGTextContentElement* impl = V8SVGTextContentElement::toNative(info.Holder());
v8SetReturnValueInt(info, impl->getNumberOfChars());
}
static void getNumberOfCharsMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGTextContentElementV8Internal::getNumberOfCharsMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void getComputedTextLengthMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
SVGTextContentElement* impl = V8SVGTextContentElement::toNative(info.Holder());
v8SetReturnValue(info, impl->getComputedTextLength());
}
static void getComputedTextLengthMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGTextContentElementV8Internal::getComputedTextLengthMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void getSubStringLengthMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "getSubStringLength", "SVGTextContentElement", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 2)) {
throwMinimumArityTypeError(exceptionState, 2, info.Length());
return;
}
SVGTextContentElement* impl = V8SVGTextContentElement::toNative(info.Holder());
unsigned offset;
unsigned length;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(offset, toUInt32(info[0], exceptionState), exceptionState);
TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(length, toUInt32(info[1], exceptionState), exceptionState);
}
float result = impl->getSubStringLength(offset, length, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8SetReturnValue(info, result);
}
static void getSubStringLengthMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGTextContentElementV8Internal::getSubStringLengthMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void getStartPositionOfCharMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "getStartPositionOfChar", "SVGTextContentElement", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeError(exceptionState, 1, info.Length());
return;
}
SVGTextContentElement* impl = V8SVGTextContentElement::toNative(info.Holder());
unsigned offset;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(offset, toUInt32(info[0], exceptionState), exceptionState);
}
RefPtr<SVGPointTearOff> result = impl->getStartPositionOfChar(offset, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8SetReturnValueFast(info, WTF::getPtr(result.release()), impl);
}
static void getStartPositionOfCharMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGTextContentElementV8Internal::getStartPositionOfCharMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void getEndPositionOfCharMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "getEndPositionOfChar", "SVGTextContentElement", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeError(exceptionState, 1, info.Length());
return;
}
SVGTextContentElement* impl = V8SVGTextContentElement::toNative(info.Holder());
unsigned offset;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(offset, toUInt32(info[0], exceptionState), exceptionState);
}
RefPtr<SVGPointTearOff> result = impl->getEndPositionOfChar(offset, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8SetReturnValueFast(info, WTF::getPtr(result.release()), impl);
}
static void getEndPositionOfCharMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGTextContentElementV8Internal::getEndPositionOfCharMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void getExtentOfCharMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "getExtentOfChar", "SVGTextContentElement", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeError(exceptionState, 1, info.Length());
return;
}
SVGTextContentElement* impl = V8SVGTextContentElement::toNative(info.Holder());
unsigned offset;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(offset, toUInt32(info[0], exceptionState), exceptionState);
}
RefPtr<SVGRectTearOff> result = impl->getExtentOfChar(offset, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8SetReturnValueFast(info, WTF::getPtr(result.release()), impl);
}
static void getExtentOfCharMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGTextContentElementV8Internal::getExtentOfCharMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void getRotationOfCharMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "getRotationOfChar", "SVGTextContentElement", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeError(exceptionState, 1, info.Length());
return;
}
SVGTextContentElement* impl = V8SVGTextContentElement::toNative(info.Holder());
unsigned offset;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(offset, toUInt32(info[0], exceptionState), exceptionState);
}
float result = impl->getRotationOfChar(offset, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8SetReturnValue(info, result);
}
static void getRotationOfCharMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGTextContentElementV8Internal::getRotationOfCharMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void getCharNumAtPositionMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "getCharNumAtPosition", "SVGTextContentElement", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeError(exceptionState, 1, info.Length());
return;
}
SVGTextContentElement* impl = V8SVGTextContentElement::toNative(info.Holder());
SVGPointTearOff* point;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
if (info.Length() > 0 && !V8SVGPoint::hasInstance(info[0], info.GetIsolate())) {
exceptionState.throwTypeError("parameter 1 is not of type 'SVGPoint'.");
exceptionState.throwIfNeeded();
return;
}
TONATIVE_VOID_INTERNAL(point, V8SVGPoint::toNativeWithTypeCheck(info.GetIsolate(), info[0]));
}
int result = impl->getCharNumAtPosition(point, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
v8SetReturnValueInt(info, result);
}
static void getCharNumAtPositionMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGTextContentElementV8Internal::getCharNumAtPositionMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void selectSubStringMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "selectSubString", "SVGTextContentElement", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 2)) {
throwMinimumArityTypeError(exceptionState, 2, info.Length());
return;
}
SVGTextContentElement* impl = V8SVGTextContentElement::toNative(info.Holder());
unsigned offset;
unsigned length;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(offset, toUInt32(info[0], exceptionState), exceptionState);
TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(length, toUInt32(info[1], exceptionState), exceptionState);
}
impl->selectSubString(offset, length, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void selectSubStringMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGTextContentElementV8Internal::selectSubStringMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
} // namespace SVGTextContentElementV8Internal
static const V8DOMConfiguration::AttributeConfiguration V8SVGTextContentElementAttributes[] = {
{"textLength", SVGTextContentElementV8Internal::textLengthAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"lengthAdjust", SVGTextContentElementV8Internal::lengthAdjustAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
};
static const V8DOMConfiguration::MethodConfiguration V8SVGTextContentElementMethods[] = {
{"getNumberOfChars", SVGTextContentElementV8Internal::getNumberOfCharsMethodCallback, 0, 0},
{"getComputedTextLength", SVGTextContentElementV8Internal::getComputedTextLengthMethodCallback, 0, 0},
{"getSubStringLength", SVGTextContentElementV8Internal::getSubStringLengthMethodCallback, 0, 2},
{"getStartPositionOfChar", SVGTextContentElementV8Internal::getStartPositionOfCharMethodCallback, 0, 1},
{"getEndPositionOfChar", SVGTextContentElementV8Internal::getEndPositionOfCharMethodCallback, 0, 1},
{"getExtentOfChar", SVGTextContentElementV8Internal::getExtentOfCharMethodCallback, 0, 1},
{"getRotationOfChar", SVGTextContentElementV8Internal::getRotationOfCharMethodCallback, 0, 1},
{"getCharNumAtPosition", SVGTextContentElementV8Internal::getCharNumAtPositionMethodCallback, 0, 1},
{"selectSubString", SVGTextContentElementV8Internal::selectSubStringMethodCallback, 0, 2},
};
static void configureV8SVGTextContentElementTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "SVGTextContentElement", V8SVGGraphicsElement::domTemplate(isolate), V8SVGTextContentElement::internalFieldCount,
V8SVGTextContentElementAttributes, WTF_ARRAY_LENGTH(V8SVGTextContentElementAttributes),
0, 0,
V8SVGTextContentElementMethods, WTF_ARRAY_LENGTH(V8SVGTextContentElementMethods),
isolate);
v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate();
v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate();
static const V8DOMConfiguration::ConstantConfiguration V8SVGTextContentElementConstants[] = {
{"LENGTHADJUST_UNKNOWN", 0},
{"LENGTHADJUST_SPACING", 1},
{"LENGTHADJUST_SPACINGANDGLYPHS", 2},
};
V8DOMConfiguration::installConstants(functionTemplate, prototypeTemplate, V8SVGTextContentElementConstants, WTF_ARRAY_LENGTH(V8SVGTextContentElementConstants), isolate);
COMPILE_ASSERT(0 == SVGTextContentElement::LENGTHADJUST_UNKNOWN, TheValueOfSVGTextContentElement_LENGTHADJUST_UNKNOWNDoesntMatchWithImplementation);
COMPILE_ASSERT(1 == SVGTextContentElement::LENGTHADJUST_SPACING, TheValueOfSVGTextContentElement_LENGTHADJUST_SPACINGDoesntMatchWithImplementation);
COMPILE_ASSERT(2 == SVGTextContentElement::LENGTHADJUST_SPACINGANDGLYPHS, TheValueOfSVGTextContentElement_LENGTHADJUST_SPACINGANDGLYPHSDoesntMatchWithImplementation);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Handle<v8::FunctionTemplate> V8SVGTextContentElement::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8SVGTextContentElementTemplate);
}
bool V8SVGTextContentElement::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Handle<v8::Object> V8SVGTextContentElement::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
SVGTextContentElement* V8SVGTextContentElement::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value)
{
return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0;
}
EventTarget* V8SVGTextContentElement::toEventTarget(v8::Handle<v8::Object> object)
{
return toNative(object);
}
v8::Handle<v8::Object> wrap(SVGTextContentElement* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8SVGTextContentElement>(impl, isolate));
return V8SVGTextContentElement::createWrapper(impl, creationContext, isolate);
}
v8::Handle<v8::Object> V8SVGTextContentElement::createWrapper(PassRefPtrWillBeRawPtr<SVGTextContentElement> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8SVGTextContentElement>(impl.get(), isolate));
if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) {
const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo();
// Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have
// the same object de-ref functions, though, so use that as the basis of the check.
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction);
}
v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate);
if (UNLIKELY(wrapper.IsEmpty()))
return wrapper;
installPerContextEnabledProperties(wrapper, impl.get(), isolate);
V8DOMWrapper::associateObjectWithWrapper<V8SVGTextContentElement>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Dependent);
return wrapper;
}
void V8SVGTextContentElement::derefObject(void* object)
{
#if !ENABLE(OILPAN)
fromInternalPointer(object)->deref();
#endif // !ENABLE(OILPAN)
}
template<>
v8::Handle<v8::Value> toV8NoInline(SVGTextContentElement* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
return toV8(impl, creationContext, isolate);
}
} // namespace WebCore
| 45.261176 | 367 | 0.764192 | [
"object"
] |
645f0c1046133da1ce8db1dc9d385778931f2e3f | 11,008 | cpp | C++ | Extern/mssdk_dx7/samples/Multimedia/DSound/src/AdjustSound/adjustsound.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 1,040 | 2021-07-27T12:12:06.000Z | 2021-08-02T14:24:49.000Z | Extern/mssdk_dx7/samples/Multimedia/DSound/src/AdjustSound/adjustsound.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 20 | 2021-07-27T12:25:22.000Z | 2021-08-02T12:22:19.000Z | Extern/mssdk_dx7/samples/Multimedia/DSound/src/AdjustSound/adjustsound.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 71 | 2021-07-27T14:19:49.000Z | 2021-08-02T05:51:52.000Z | //-----------------------------------------------------------------------------
// File: AdjustSound.cpp
//
// Desc: DirectSound support for how to load a wave file and play it using a
// static DirectSound buffer and adjust its focus, frequency,
// pan, and volume.
//
// Copyright (c) 1999 Microsoft Corp. All rights reserved.
//-----------------------------------------------------------------------------
#define STRICT
#include <objbase.h>
#include <initguid.h>
#include <mmsystem.h>
#include <mmreg.h>
#include <dsound.h>
#include <commdlg.h>
#include "resource.h"
#include "WavRead.h"
//-----------------------------------------------------------------------------
// Function-prototypes
//-----------------------------------------------------------------------------
extern VOID OnEnablePlayUI( HWND hDlg, BOOL bEnable );
extern VOID SetStatusUI( HWND hDlg, TCHAR* strStatus );
extern VOID SetFileUI( HWND hDlg, TCHAR* strFileName );
extern VOID SetSlidersPos( HWND hDlg, LONG lFreqSlider, LONG lPanSlider, LONG lVolumeSlider );
extern VOID OnSliderChanged( HWND hDlg );
HRESULT RestoreBuffer();
//-----------------------------------------------------------------------------
// Defines, constants, and global variables
//-----------------------------------------------------------------------------
#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } }
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
LPDIRECTSOUND g_pDS = NULL;
LPDIRECTSOUNDBUFFER g_pDSBuffer = NULL;
CWaveSoundRead* g_pWaveSoundRead = NULL;
//-----------------------------------------------------------------------------
// Name: InitDirectSound()
// Desc: Initilizes DirectSound
//-----------------------------------------------------------------------------
HRESULT InitDirectSound( HWND hDlg )
{
HRESULT hr;
LPDIRECTSOUNDBUFFER pDSBPrimary = NULL;
// Initialize COM
if( hr = CoInitialize( NULL ) )
return hr;
// Create IDirectSound using the primary sound device
if( FAILED( hr = DirectSoundCreate( NULL, &g_pDS, NULL ) ) )
return hr;
// Set coop level to DSSCL_PRIORITY
if( FAILED( hr = g_pDS->SetCooperativeLevel( hDlg, DSSCL_PRIORITY ) ) )
return hr;
// Get the primary buffer
DSBUFFERDESC dsbd;
ZeroMemory( &dsbd, sizeof(DSBUFFERDESC) );
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER;
dsbd.dwBufferBytes = 0;
dsbd.lpwfxFormat = NULL;
if( FAILED( hr = g_pDS->CreateSoundBuffer( &dsbd, &pDSBPrimary, NULL ) ) )
return hr;
// Set primary buffer format to 22kHz and 16-bit output.
WAVEFORMATEX wfx;
ZeroMemory( &wfx, sizeof(WAVEFORMATEX) );
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nChannels = 2;
wfx.nSamplesPerSec = 22050;
wfx.wBitsPerSample = 16;
wfx.nBlockAlign = wfx.wBitsPerSample / 8 * wfx.nChannels;
wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
if( FAILED( hr = pDSBPrimary->SetFormat(&wfx) ) )
return hr;
SAFE_RELEASE( pDSBPrimary );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: FreeDirectSound()
// Desc: Releases DirectSound
//-----------------------------------------------------------------------------
HRESULT FreeDirectSound()
{
// Release DirectSound interfaces
SAFE_DELETE( g_pWaveSoundRead );
SAFE_RELEASE( g_pDSBuffer );
SAFE_RELEASE( g_pDS );
// Release COM
CoUninitialize();
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: SetBufferOptions()
// Desc: Sets the DirectSound buffer options
//-----------------------------------------------------------------------------
VOID SetBufferOptions( LONG lFrequency, LONG lPan, LONG lVolume )
{
if( g_pDSBuffer )
{
g_pDSBuffer->SetFrequency( lFrequency );
g_pDSBuffer->SetPan( lPan );
g_pDSBuffer->SetVolume( lVolume );
}
}
//-----------------------------------------------------------------------------
// Name: LoadWaveFile()
// Desc: Loads a wave file into a secondary static DirectSound buffer
//-----------------------------------------------------------------------------
VOID LoadWaveFile( HWND hDlg, TCHAR* strFileName )
{
SAFE_DELETE( g_pWaveSoundRead );
g_pWaveSoundRead = new CWaveSoundRead();
// Load the wave file
if( FAILED( g_pWaveSoundRead->Open( strFileName ) ) )
{
SetStatusUI( hDlg, TEXT("Bad wave file.") );
}
else // The load call succeeded
{
// Update the UI controls to show the sound as the file is loaded
OnEnablePlayUI( hDlg, TRUE );
SetFileUI( hDlg, strFileName );
SetStatusUI( hDlg, TEXT("File loaded.") );
// Get the samples per sec from the wave file
INT nSamplesPerSec = g_pWaveSoundRead->m_pwfx->nSamplesPerSec;
// Set the slider positions
SetSlidersPos( hDlg, nSamplesPerSec, 0, 0 );
}
}
//-----------------------------------------------------------------------------
// Name: CreateStaticBuffer()
// Desc: Uses data from a CWaveSoundRead class to create the sound buffer
//-----------------------------------------------------------------------------
HRESULT CreateStaticBuffer( HWND hDlg, DWORD dwCreatationFlags )
{
HRESULT hr;
BYTE* pbWavData; // Pointer to actual wav data
UINT cbWavSize; // Size of data
// Reset the wave file to the beginning
g_pWaveSoundRead->Reset();
// The size of wave data is in pWaveFileSound->m_ckIn
INT nWaveFileSize = g_pWaveSoundRead->m_ckIn.cksize;
// Allocate that buffer.
pbWavData = new BYTE[ nWaveFileSize ];
if( NULL == pbWavData )
return E_OUTOFMEMORY;
if( FAILED( hr = g_pWaveSoundRead->Read( nWaveFileSize,
pbWavData,
&cbWavSize ) ) )
return hr;
// Set up the direct sound buffer, and only request the flags needed
// since each requires some overhead and limits if the buffer can
// be hardware accelerated
DSBUFFERDESC dsbd;
ZeroMemory( &dsbd, sizeof(DSBUFFERDESC) );
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME |
DSBCAPS_CTRLFREQUENCY | DSBCAPS_STATIC;
dsbd.dwBufferBytes = cbWavSize;
dsbd.lpwfxFormat = g_pWaveSoundRead->m_pwfx;
// Add in the passed in creation flags
dsbd.dwFlags |= dwCreatationFlags;
// Create the static DirectSound buffer using the focus set by the UI
if( FAILED( hr = g_pDS->CreateSoundBuffer( &dsbd, &g_pDSBuffer, NULL ) ) )
return hr;
VOID* pbData = NULL;
VOID* pbData2 = NULL;
DWORD dwLength;
DWORD dwLength2;
// Make sure we have focus, and we didn't just switch in from
// an app which had a DirectSound device
if( FAILED( hr = RestoreBuffer() ) )
return hr;
// Lock the buffer down
if( FAILED( hr = g_pDSBuffer->Lock( 0, dsbd.dwBufferBytes, &pbData, &dwLength,
&pbData2, &dwLength2, 0L ) ) )
return hr;
// Copy the memory to it.
memcpy( pbData, pbWavData, dsbd.dwBufferBytes );
// Unlock the buffer, we don't need it anymore.
g_pDSBuffer->Unlock( pbData, dsbd.dwBufferBytes, NULL, 0 );
pbData = NULL;
// We dont need the wav file data buffer anymore, so delete it
SAFE_DELETE( pbWavData );
// Set the buffer options to what the sliders are set to
OnSliderChanged( hDlg );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: RestoreBuffer()
// Desc: Restore lost buffer and fill them up with sound if possible
//-----------------------------------------------------------------------------
HRESULT RestoreBuffer()
{
HRESULT hr;
if( NULL == g_pDSBuffer )
return S_OK;
DWORD dwStatus;
if( FAILED( hr = g_pDSBuffer->GetStatus( &dwStatus ) ) )
return hr;
if( dwStatus & DSBSTATUS_BUFFERLOST )
{
// Since the app could have just been activated, then
// DirectSound may not be giving us control yet, so
// the restoring the buffer may fail.
// If it does, sleep until DirectSound gives us control.
do
{
hr = g_pDSBuffer->Restore();
if( hr == DSERR_BUFFERLOST )
Sleep( 10 );
}
while( hr = g_pDSBuffer->Restore() );
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: PlayBuffer()
// Desc: User hit the "Play" button, so play the DirectSound buffer
//-----------------------------------------------------------------------------
HRESULT PlayBuffer( HWND hDlg, BOOL bLooped, DWORD dwCreationFlags )
{
HRESULT hr;
DWORD dwStatus;
// Since the user can change the focus before the sound is played, we
// need to create the sound buffer every time the play button is pressed
// Free any previous g_pDSBuffer buffer
SAFE_RELEASE( g_pDSBuffer );
// Create the sound buffer object from the wave file data
if( FAILED( hr = CreateStaticBuffer( hDlg, dwCreationFlags ) ) )
{
// Not a critical failure, so just update the status
SetStatusUI( hDlg, TEXT("Couldn't create sound buffer.") );
return S_FALSE;
}
if( NULL == g_pDSBuffer )
return E_FAIL;
// Now that the buffer is created, play the buffer
if( FAILED( hr = g_pDSBuffer->GetStatus( &dwStatus ) ) )
return hr;
if( dwStatus & DSBSTATUS_PLAYING )
{
// Don't bother playing, just restart
g_pDSBuffer->SetCurrentPosition( 0 );
}
else
{
DWORD dwLooped = bLooped ? DSBPLAY_LOOPING : 0L;
if( FAILED( hr = g_pDSBuffer->Play( 0, 0, dwLooped ) ) )
return hr;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: StopBuffer()
// Desc: Stop the DirectSound buffer from playing
//-----------------------------------------------------------------------------
VOID StopBuffer()
{
if( NULL == g_pDSBuffer )
return;
g_pDSBuffer->Stop();
g_pDSBuffer->SetCurrentPosition( 0L );
}
//-----------------------------------------------------------------------------
// Name: IsSoundPlaying()
// Desc: Checks to see if a sound is playing and returns TRUE if it is.
//-----------------------------------------------------------------------------
BOOL IsSoundPlaying()
{
if( g_pDSBuffer )
{
DWORD dwStatus = 0;
g_pDSBuffer->GetStatus( &dwStatus );
return( ( dwStatus & DSBSTATUS_PLAYING ) != 0 );
}
else
{
return FALSE;
}
}
| 29.831978 | 94 | 0.520803 | [
"object"
] |
6463716f4cc7cedfb990fd99ab9e79833cb20bbb | 3,077 | cpp | C++ | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/lists/SoPickedPointList.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/lists/SoPickedPointList.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/lists/SoPickedPointList.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | /**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) by Kongsberg Oil & Gas Technologies.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Kongsberg Oil & Gas Technologies
* about acquiring a Coin Professional Edition License.
*
* See http://www.coin3d.org/ for more information.
*
* Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.
* http://www.sim.no/ sales@sim.no coin-support@coin3d.org
*
\**************************************************************************/
#include <Inventor/lists/SoPickedPointList.h>
#include <Inventor/SoPickedPoint.h>
/*!
\class SoPickedPointList SoPickedPointList.h Inventor/lists/SoPickedPointList.h
\brief The SoPickedPointList class is a container for pointers to SoPickedPoint objects.
\ingroup general
This list class will delete the picked points when
destructed/truncated, or when a picked point in the list is replaced
by another picked point The caller is responsible for allocating the
picked points passed to the list, but should not deallocate them since
this will be handled by the list.
\sa SbPList
*/
/*!
\fn SoPickedPointList::SoPickedPointList(void)
Default constructor.
*/
/*!
\fn SoPickedPointList::SoPickedPointList(const int sizehint)
This constructor initializes the internal allocated size for the
list to \a sizehint. Note that the list will still initially contain
zero items.
\sa SbList::SbList(const int sizehint)
*/
/*!
\fn SoPickedPoint * SoPickedPointList::operator[](const int idx) const
Returns element at \a idx.
Will automatically expand the size of the internal array if \a idx
is outside the current bounds of the list. The values of any
additional pointers are then set to \c NULL.
*/
/*!
Copy constructor. Will copy picked points, not just pointers.
\sa SbList::SbList(const SbList<Type> & l)
*/
SoPickedPointList::SoPickedPointList(const SoPickedPointList & l)
: SbPList(l.getLength())
{
for (int i = 0; i < l.getLength(); i++) {
this->append(l[i]->copy());
}
}
/*!
Overridden to delete truncated items.
*/
void
SoPickedPointList::truncate(const int start, const int fit)
{
int oldlen = this->getLength();
for (int i = start; i < oldlen; i++) {
delete (*this)[i];
}
SbPList::truncate(start, fit);
}
/*!
Overridden to destruct the replaced item.
*/
void
SoPickedPointList::set(const int idx, SoPickedPoint * pp)
{
if (idx < this->getLength()) delete (*this)[idx];
SbPList::operator[](idx) = (void*) pp;
}
| 29.304762 | 90 | 0.685408 | [
"3d"
] |
6465e52c8f2da78c0d0ec53714dc7494e07d6df5 | 1,491 | cpp | C++ | C++/restore-ip-addresses.cpp | xenron/sandbox-dev-lintcode | 114145723af43eafc84ff602ad3ac7b353a9fc38 | [
"MIT"
] | 695 | 2015-04-18T16:11:56.000Z | 2022-03-11T13:28:44.000Z | C++/restore-ip-addresses.cpp | Abd-Elrazek/LintCode | 8f6ee0ff38cb7cf8bf9fca800243823931604155 | [
"MIT"
] | 4 | 2015-07-04T13:07:35.000Z | 2020-08-11T11:32:29.000Z | C++/restore-ip-addresses.cpp | Abd-Elrazek/LintCode | 8f6ee0ff38cb7cf8bf9fca800243823931604155 | [
"MIT"
] | 338 | 2015-04-28T04:39:03.000Z | 2022-03-16T03:00:15.000Z | // Time: O(n^m) = O(3^4)
// Space: O(n * m) = O(3 * 4)
class Solution {
public:
/**
* @param s the IP string
* @return All possible valid IP addresses
*/
vector<string> restoreIpAddresses(string& s) {
vector<string> result;
string cur;
restoreIpAddressesHelper(s, 0, 0, &cur, &result);
return result;
}
void restoreIpAddressesHelper(const string& s,
int start, int dots,
string *cur,
vector<string> *result) {
// Pruning to improve performance.
if (((4 - dots) * 3 < s.length() - start) ||
((4 - dots) > s.length() - start)) {
return;
}
if (start == s.length() && dots == 4) {
result->emplace_back(cur->begin(), prev(cur->end()));
} else {
for (int i = start; i < start + 3; ++i) {
string tmp = s.substr(start, i - start + 1);
if (i < s.length() && isValid(tmp)) {
tmp.push_back('.');
cur->append(tmp);
restoreIpAddressesHelper(s, i + 1, dots + 1, cur, result);
cur->resize(cur->length() - (i - start + 2));
}
}
}
}
bool isValid(const string &s) {
if (s.empty() || (s[0] == '0' && s != "0")) {
return false;
}
return stoi(s) < 256;
}
};
| 30.428571 | 78 | 0.423877 | [
"vector"
] |
6472f43613f9515d00829665f21f64096799147f | 5,770 | cpp | C++ | src/tgcreator/tgCompoundRigidInfo.cpp | wvat/NTRTsim | 0443cbd542e12e23c04adf79ea0d8d003c428baa | [
"Apache-2.0"
] | 148 | 2015-01-08T22:44:00.000Z | 2022-03-19T18:42:48.000Z | src/tgcreator/tgCompoundRigidInfo.cpp | wvat/NTRTsim | 0443cbd542e12e23c04adf79ea0d8d003c428baa | [
"Apache-2.0"
] | 107 | 2015-01-02T16:41:42.000Z | 2021-06-14T22:09:19.000Z | src/tgcreator/tgCompoundRigidInfo.cpp | wvat/NTRTsim | 0443cbd542e12e23c04adf79ea0d8d003c428baa | [
"Apache-2.0"
] | 86 | 2015-01-06T07:02:36.000Z | 2022-02-28T17:36:14.000Z | /*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/**
* @file tgCompoundRigidInfo.cpp
* @brief Implementaton of class tgCompoundRigidInfo
* @author Ryan Adams
* @date January 2014
* $Id$
*/
#include "tgCompoundRigidInfo.h"
tgCompoundRigidInfo::tgCompoundRigidInfo() : m_compoundShape(NULL), tgRigidInfo()
{
}
tgModel* tgCompoundRigidInfo::createModel(tgWorld& world)
{
// @todo: make tgModel a true composite and use that here
tgModel* result = new tgModel();
for(int i = 0; i < m_rigids.size(); i++) {
result->addChild(m_rigids[i]->createModel(world));
}
return result;
}
void tgCompoundRigidInfo::addRigid(tgRigidInfo& rigid)
{
m_rigids.push_back(&rigid);
}
btVector3 tgCompoundRigidInfo::getCenterOfMass() const
{
btVector3 sum = btVector3(0.0, 0.0, 0.0);
for (int ii = 0; ii < m_rigids.size(); ii++)
{
/* const */ tgRigidInfo * const rigid = m_rigids[ii];
sum += (rigid->getCenterOfMass() * rigid->getMass());
}
const double totalMass = getMass();
return
(totalMass == 0.0) ? btVector3(0.0, 0.0, 0.0) : (sum / totalMass);
}
btCompoundShape* tgCompoundRigidInfo::createCompoundShape(tgWorld& world) const
{
if (m_compoundShape == 0)
{
// Deallocated by the world implementation
m_compoundShape = new btCompoundShape(&world);
const btVector3 com = getCenterOfMass();
for (int ii = 0; ii < m_rigids.size(); ii++)
{
tgRigidInfo* const rigid = m_rigids[ii];
btTransform t = rigid->getTransform();
t.setOrigin(t.getOrigin() - com);
m_compoundShape->addChildShape(t, rigid->getCollisionShape(world));
}
// Add the collision shape to the array so we can delete it later
tgWorldBulletPhysicsImpl& bulletWorld =
(tgWorldBulletPhysicsImpl&)world.implementation();
bulletWorld.addCollisionShape(m_compoundShape);
}
return m_compoundShape;
}
btCollisionShape* tgCompoundRigidInfo::getCollisionShape(tgWorld& world) const
{
if (m_compoundShape == 0)
{
m_compoundShape = createCompoundShape(world);
}
return m_compoundShape;
}
btTransform tgCompoundRigidInfo::getTransform() const
{
btTransform t;
t.setIdentity();
t.setOrigin(getCenterOfMass());
return t;
}
double tgCompoundRigidInfo::getMass() const
{
/// @todo Use std::accumulate()
double mass = 0.0;
for (int ii = 0; ii < m_rigids.size(); ii++)
{
mass += m_rigids[ii]->getMass();
}
return mass;
}
btRigidBody* tgCompoundRigidInfo::getRigidBody()
{
btRigidBody* rb = tgCast::cast<btCollisionObject, btRigidBody>(m_collisionObject);
return rb;
}
const btRigidBody* tgCompoundRigidInfo::getRigidBody() const
{
btRigidBody* rb = tgCast::cast<btCollisionObject, btRigidBody>(m_collisionObject);
return rb;
}
void tgCompoundRigidInfo::setRigidBody(btRigidBody* const rigidBody)
{
m_collisionObject = rigidBody;
// Set the rigid body for all components
/// @todo Use std::for_each()
for (int ii = 0; ii < m_rigids.size(); ii++) {
m_rigids[ii]->setRigidBody(rigidBody);
}
}
void tgCompoundRigidInfo::setCollisionObject(btCollisionObject* collisionObject)
{
m_collisionObject = collisionObject;
// Set the rigid body for all components
/// @todo Use std::for_each()
for (int ii = 0; ii < m_rigids.size(); ii++) {
m_rigids[ii]->setCollisionObject(collisionObject);
}
}
std::set<tgRigidInfo*> tgCompoundRigidInfo::getLeafRigids()
{
std::set<tgRigidInfo*> leaves;
for (int ii = 0; ii < m_rigids.size(); ii++) {
tgRigidInfo * const rigid = m_rigids[ii];
if (rigid->isCompound())
{
// Insert the leaves from the compound recursively
const std::set<tgRigidInfo*> compoundLeaves =
rigid->getLeafRigids();
leaves.insert(compoundLeaves.begin(), compoundLeaves.end());
}
else
{
leaves.insert(rigid);
}
}
return leaves;
}
bool tgCompoundRigidInfo::containsNode(const btVector3& nodeVector) const
{
/// @todo Use std::find_if()
for (int ii = 0; ii < m_rigids.size(); ii++)
{
if (m_rigids[ii]->containsNode(nodeVector))
{
return true;
}
}
return false;
}
bool tgCompoundRigidInfo::sharesNodesWith(const tgRigidInfo& other) const
{
/// @todo Use std::find_if()
for (int ii = 0; ii < m_rigids.size(); ii++)
{
if (m_rigids[ii]->sharesNodesWith(other)) {
return true;
}
}
return false;
}
std::set<btVector3> tgCompoundRigidInfo::getContainedNodes() const
{
/// @todo Use std::accumulate()
std::set<btVector3> contained;
for (int ii = 0; ii < m_rigids.size(); ii++)
{
const std::set<btVector3> nodes = m_rigids[ii]->getContainedNodes();
contained.insert(nodes.begin(), nodes.end());
}
return contained;
}
| 28.284314 | 83 | 0.647834 | [
"shape"
] |
6474f2407e76a71779ccb29de0890d34cb71665f | 3,738 | cpp | C++ | src/app/voltdb/voltdb_src/src/ee/topics/encode/CsvEncoder.cpp | OpenMPDK/SMDK | 8f19d32d999731242cb1ab116a4cb445d9993b15 | [
"BSD-3-Clause"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | src/app/voltdb/voltdb_src/src/ee/topics/encode/CsvEncoder.cpp | H2O0Lee/SMDK | eff49bc17a55a83ea968112feb2e2f2ea18c4ff5 | [
"BSD-3-Clause"
] | 1 | 2022-03-29T02:30:28.000Z | 2022-03-30T03:40:46.000Z | src/app/voltdb/voltdb_src/src/ee/topics/encode/CsvEncoder.cpp | H2O0Lee/SMDK | eff49bc17a55a83ea968112feb2e2f2ea18c4ff5 | [
"BSD-3-Clause"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | /* This file is part of VoltDB.
* Copyright (C) 2020 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <vector>
#include "common/MiscUtil.h"
#include "topics/encode/CsvEncoder.h"
namespace voltdb { namespace topics {
const std::string CsvEncoder::PROP_CSV_SEPARATOR = "config.csv.separator";
const std::string CsvEncoder::PROP_CSV_QUOTE = "config.csv.quote";
const std::string CsvEncoder::PROP_CSV_ESCAPE = "config.csv.escape";
const std::string CsvEncoder::PROP_CSV_NULL = "config.csv.null";
const std::string CsvEncoder::PROP_CSV_QUOTE_ALL = "config.csv.quoteAll";
const char CsvEncoder::DEFAULT_CSV_SEPARATOR = ',';
const char CsvEncoder::DEFAULT_CSV_QUOTE = '"';
const char CsvEncoder::DEFAULT_CSV_ESCAPE = DEFAULT_CSV_QUOTE;
const std::string CsvEncoder::DEFAULT_CSV_NULL = "\\N";
CsvEncoder::CsvEncoder(const std::vector<int32_t>& indexes,
const TopicProperties& props)
: m_indexes(indexes),
m_separator(parseCharProperty(props, PROP_CSV_SEPARATOR, DEFAULT_CSV_SEPARATOR)),
m_quote(parseCharProperty(props, PROP_CSV_QUOTE, DEFAULT_CSV_QUOTE)),
m_escape(parseCharProperty(props, PROP_CSV_ESCAPE, DEFAULT_CSV_ESCAPE)),
m_null(parseStringProperty(props, PROP_CSV_NULL, DEFAULT_CSV_NULL)),
m_quoteAll(parseBoolProperty(props, PROP_CSV_QUOTE_ALL, false)),
m_tuple(nullptr),
m_oss()
{
// We must quote any string with separator
m_quotables = {m_separator, m_quote, '\n', '\r'};
m_escapables = {m_quote, m_escape};
}
int32_t CsvEncoder::encode(const TableTuple& tuple) {
m_tuple = &tuple;
m_oss.str("");
// Encode tuple values referred to by index vector
bool first = true;
for (int32_t index : m_indexes) {
if (!first) {
m_oss << m_separator;
}
else {
first = false;
}
const NValue value = tuple.getNValue(index);
if (value.isNull()) {
if (m_quoteAll) {
m_oss << m_quote;
}
m_oss << m_null;
if (m_quoteAll) {
m_oss << m_quote;
}
continue;
}
std::string strValue = value.toCsvString();
bool hasEscapes = containsEscapableCharacters(strValue);
bool mustQuote = m_quoteAll || strValue.find_first_of(m_quotables) != std::string::npos;
if (mustQuote) {
m_oss << m_quote;
}
if (hasEscapes) {
insertEscapedValue(strValue);
}
else {
m_oss << strValue;
}
if (mustQuote) {
m_oss << m_quote;
}
}
// Note: Volt CSV encoding does not encode a newline at the end of each record
return m_oss.str().length();
}
bool CsvEncoder::containsEscapableCharacters(const std::string& value) {
return value.find_first_of(m_escapables) != std::string::npos;
}
void CsvEncoder::insertEscapedValue(const std::string& value) {
for (const char c : value) {
if (m_escapables.find(c) != std::string::npos) {
m_oss << m_escape;
}
m_oss << c;
}
}
} }
| 32.504348 | 96 | 0.654093 | [
"vector"
] |
647ceb477f51df8e0f0f1dfd56fa101838cbee1b | 3,515 | cpp | C++ | PyFlex/core/voxelize.cpp | ipab-rad/softgym | eeee770d8720c2cebaa9c5f72408b3340b07d367 | [
"BSD-3-Clause"
] | 147 | 2020-11-12T16:48:55.000Z | 2022-03-29T02:21:13.000Z | PyFlex/core/voxelize.cpp | ipab-rad/softgym | eeee770d8720c2cebaa9c5f72408b3340b07d367 | [
"BSD-3-Clause"
] | 28 | 2020-11-20T23:09:58.000Z | 2022-03-31T14:51:16.000Z | PyFlex/core/voxelize.cpp | ipab-rad/softgym | eeee770d8720c2cebaa9c5f72408b3340b07d367 | [
"BSD-3-Clause"
] | 29 | 2020-11-12T06:25:19.000Z | 2022-03-28T14:10:55.000Z | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2013-2016 NVIDIA Corporation. All rights reserved.
#include "aabbtree.h"
#include "mesh.h"
void Voxelize(const Vec3* vertices, int numVertices, const int* indices, int numTriangleIndices, uint32_t width, uint32_t height, uint32_t depth, uint32_t* volume, Vec3 minExtents, Vec3 maxExtents)
{
memset(volume, 0, sizeof(uint32_t)*width*height*depth);
// build an aabb tree of the mesh
AABBTree tree(vertices, numVertices, (const uint32_t*)indices, numTriangleIndices/3);
// parity count method, single pass
const Vec3 extents(maxExtents-minExtents);
const Vec3 delta(extents.x/width, extents.y/height, extents.z/depth);
const Vec3 offset(0.5f*delta.x, 0.5f*delta.y, 0.5f*delta.z);
// this is the bias we apply to step 'off' a triangle we hit, not very robust
const float eps = 0.00001f*extents.z;
for (uint32_t x=0; x < width; ++x)
{
for (uint32_t y=0; y < height; ++y)
{
bool inside = false;
Vec3 rayDir = Vec3(0.0f, 0.0f, 1.0f);
Vec3 rayStart = minExtents + Vec3(x*delta.x + offset.x, y*delta.y + offset.y, 0.0f);
uint32_t lastTri = uint32_t(-1);
for (;;)
{
// calculate ray start
float t, u, v, w, s;
uint32_t tri;
if (tree.TraceRay(rayStart, rayDir, t, u, v, w, s, tri))
{
// calculate cell in which intersection occurred
const float zpos = rayStart.z + t*rayDir.z;
const float zhit = (zpos-minExtents.z)/delta.z;
uint32_t z = uint32_t(floorf((rayStart.z-minExtents.z)/delta.z + 0.5f));
uint32_t zend = std::min(uint32_t(floorf(zhit + 0.5f)), depth-1);
if (inside)
{
// march along column setting bits
for (uint32_t k=z; k < zend; ++k)
volume[k*width*height + y*width + x] = uint32_t(-1);
}
inside = !inside;
// we hit the tri we started from
if (tri == lastTri)
printf("Error self-intersect\n");
lastTri = tri;
rayStart += rayDir*(t+eps);
}
else
break;
}
}
}
}
| 37.393617 | 197 | 0.708108 | [
"mesh"
] |
647d6f2d50c816016c77a7ea85ca97610e633841 | 6,025 | cpp | C++ | GRL/Axon/Main.cpp | teppyboy/Generic_Exploit_Loader | 5323751195d25cdfd2dc8823c67ede579d0e1aa3 | [
"MIT"
] | 1 | 2020-08-11T04:44:31.000Z | 2020-08-11T04:44:31.000Z | GRL/Axon/Main.cpp | teppyboy/Generic_Exploit_Loader | 5323751195d25cdfd2dc8823c67ede579d0e1aa3 | [
"MIT"
] | 1 | 2019-09-17T18:39:00.000Z | 2019-10-12T12:52:15.000Z | GRL/Axon/Main.cpp | teppyboy/Generic_Exploit_Loader | 5323751195d25cdfd2dc8823c67ede579d0e1aa3 | [
"MIT"
] | 2 | 2020-06-15T04:43:59.000Z | 2021-04-09T23:53:51.000Z |
#include "globals.h"
#include "Bridge.h"
#include <string>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <iterator>
#include <fstream>
#include <intrin.h>
#include <Tlhelp32.h>
#include <CommCtrl.h>
#include <Wininet.h>
#pragma comment(lib, "wininet.lib")
using namespace std;
DWORD ScriptContext;
DWORD ScriptContextVFTable = x(0x01E8B378);
DWORD grabGlobalStateIndex(DWORD ScriptContext, int idx)
{
DWORD* context = reinterpret_cast<DWORD*>(ScriptContext);
return context[idx] - (DWORD)&context[idx];
}
using Bridge::m_rL;
using Bridge::m_L;
void PushGlobal(DWORD rL, lua_State* L, const char* s)
{
r_lua_getglobal(rL, s);
Bridge::push(rL, L, -1);
lua_setglobal(L, s);
r_lua_pop(rL, 1);
}
DWORD WINAPI input(PVOID lvpParameter)
{
string WholeScript = "";
HANDLE hPipe;
char buffer[999999];
DWORD dwRead;
hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\Axon"),
PIPE_ACCESS_DUPLEX | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
PIPE_WAIT,
1,
999999,
999999,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);
while (hPipe != INVALID_HANDLE_VALUE)
{
if (ConnectNamedPipe(hPipe, NULL) != FALSE)
{
while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &dwRead, NULL) != FALSE)
{
buffer[dwRead] = '\0';
try {
try {
WholeScript = WholeScript + buffer;
}
catch (...) {
}
}
catch (std::exception e) {
}
catch (...) {
}
}
if (luaL_loadstring(m_L, WholeScript.c_str()))
printf("Error: %s\n", lua_tostring(m_L, -1));
else
lua_pcall(m_L, 0, 0, 0);
WholeScript = "";
}
DisconnectNamedPipe(hPipe);
}
}
bool CompareData(const char* Data, const char* Pattern, const char* Mask) {
while (*Mask) {
if (*Mask != '?') {
if (*Data != *Pattern) {
return false;
};
};
++Mask;
++Data;
++Pattern;
};
return true;
};
DWORD ScanForScriptContext(const char* SCVFT_Offsetted) {
MEMORY_BASIC_INFORMATION BasicMemoryInformation = {};
SYSTEM_INFO SystemInformation = {};
GetSystemInfo(&SystemInformation);
DWORD StartingMemorySearchPosition = (DWORD)SystemInformation.lpMinimumApplicationAddress;
DWORD MaximumSearchBoundary = (DWORD)SystemInformation.lpMaximumApplicationAddress;
do {
while (VirtualQuery((void*)StartingMemorySearchPosition, &BasicMemoryInformation, sizeof(BasicMemoryInformation))) {
if ((BasicMemoryInformation.Protect & PAGE_READWRITE) && !(BasicMemoryInformation.Protect & PAGE_GUARD)) {
for (DWORD Key = (DWORD)(BasicMemoryInformation.BaseAddress); ((Key - (DWORD)(BasicMemoryInformation.BaseAddress) < BasicMemoryInformation.RegionSize)); ++Key) {
if (CompareData((const char*)Key, SCVFT_Offsetted, "xxxx")) {
return Key;
};
};
};
StartingMemorySearchPosition += BasicMemoryInformation.RegionSize;
};
} while (StartingMemorySearchPosition < MaximumSearchBoundary);
return 0x0;
};
int getRawMetaTable(lua_State *L) {
Bridge::push(L, m_rL, 1);
if (r_lua_getmetatable(m_rL, -1) == 0) {
lua_pushnil(L);
return 0;
}
Bridge::push(m_rL, L, -1);
return 1;
}
static int UserDataGC(lua_State *Thread) {
void *UD = lua_touserdata(Thread, 1);
if (m_rL) {
r_lua_rawgeti(m_rL, LUA_REGISTRYINDEX, (int)UD);
if (r_lua_type(m_rL, -1) <= R_LUA_TNIL) {
lua_pushnil(Thread);
lua_rawseti(Thread, LUA_REGISTRYINDEX, (int)UD);
}
}
return 0;
}
void main()
{
ScriptContext = ScanForScriptContext((char*)&ScriptContextVFTable);
m_rL = grabGlobalStateIndex(ScriptContext, 41);
m_L = luaL_newstate();
Bridge::VehHandlerpush();
luaL_openlibs(m_L);
luaL_newmetatable(m_L, "garbagecollector");
lua_pushcfunction(m_L, UserDataGC);
lua_setfield(m_L, -2, "__gc");
lua_pushvalue(m_L, -1);
lua_setfield(m_L, -2, "__index");
PushGlobal(m_rL, m_L, "game");
PushGlobal(m_rL, m_L, "Game");
PushGlobal(m_rL, m_L, "workspace");
PushGlobal(m_rL, m_L, "Workspace");
PushGlobal(m_rL, m_L, "Axes");
PushGlobal(m_rL, m_L, "BrickColor");
PushGlobal(m_rL, m_L, "CFrame");
PushGlobal(m_rL, m_L, "Color3");
PushGlobal(m_rL, m_L, "ColorSequence");
PushGlobal(m_rL, m_L, "ColorSequenceKeypoint");
PushGlobal(m_rL, m_L, "NumberRange");
PushGlobal(m_rL, m_L, "NumberSequence");
PushGlobal(m_rL, m_L, "NumberSequenceKeypoint");
PushGlobal(m_rL, m_L, "PhysicalProperties");
PushGlobal(m_rL, m_L, "Ray");
PushGlobal(m_rL, m_L, "Rect");
PushGlobal(m_rL, m_L, "Region3");
PushGlobal(m_rL, m_L, "Region3int16");
PushGlobal(m_rL, m_L, "TweenInfo");
PushGlobal(m_rL, m_L, "UDim");
PushGlobal(m_rL, m_L, "UDim2");
PushGlobal(m_rL, m_L, "Vector2");
PushGlobal(m_rL, m_L, "Vector2int16");
PushGlobal(m_rL, m_L, "Vector3");
PushGlobal(m_rL, m_L, "Vector3int16");
PushGlobal(m_rL, m_L, "Enum");
PushGlobal(m_rL, m_L, "Faces");
PushGlobal(m_rL, m_L, "Instance");
PushGlobal(m_rL, m_L, "math");
PushGlobal(m_rL, m_L, "warn");
PushGlobal(m_rL, m_L, "typeof");
PushGlobal(m_rL, m_L, "type");
PushGlobal(m_rL, m_L, "spawn");
PushGlobal(m_rL, m_L, "Spawn");
PushGlobal(m_rL, m_L, "print");
PushGlobal(m_rL, m_L, "printidentity");
PushGlobal(m_rL, m_L, "ypcall");
PushGlobal(m_rL, m_L, "Wait");
PushGlobal(m_rL, m_L, "wait");
PushGlobal(m_rL, m_L, "delay");
PushGlobal(m_rL, m_L, "Delay");
PushGlobal(m_rL, m_L, "tick");
PushGlobal(m_rL, m_L, "LoadLibrary");
lua_register(m_L, "getrawmetatable", getRawMetaTable);
lua_newtable(m_L);
lua_setglobal(m_L, "_G");
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)input, NULL, NULL, NULL);
printf("RVX INJECTED!\n");
MessageBoxA(NULL, "Africanus is better than you\nKai fucked me on my house :D\nAero is Gay\nSettings bombed a school\n<Aspect> bditt is less gay than Pudding Mug\nxGladius is less gay than Kai but still true gay love\nTrapFX is a weeb", "The Truth", MB_OK);
}
BOOL APIENTRY DllMain(HMODULE Module, DWORD Reason, void* Reserved)
{
switch (Reason)
{
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(Module);
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)main, NULL, NULL, NULL);
break;
case DLL_PROCESS_DETACH:
break;
default: break;
}
return TRUE;
} | 26.897321 | 258 | 0.699253 | [
"vector"
] |
647e6cba30d78cb67204c172f83e4f7cd9612b9a | 10,629 | cpp | C++ | ExplorerF1Disabler/ExplorerF1Disabler.cpp | udaken/ExplorerF1Disabler | 871e0b4d0f64255f78ce34c355af9c6b4d3eccce | [
"MIT"
] | null | null | null | ExplorerF1Disabler/ExplorerF1Disabler.cpp | udaken/ExplorerF1Disabler | 871e0b4d0f64255f78ce34c355af9c6b4d3eccce | [
"MIT"
] | null | null | null | ExplorerF1Disabler/ExplorerF1Disabler.cpp | udaken/ExplorerF1Disabler | 871e0b4d0f64255f78ce34c355af9c6b4d3eccce | [
"MIT"
] | null | null | null | #include "framework.h"
#include "resource.h"
#include <shlobj.h>
#include <assert.h>
#include <wil/com.h>
#include <wil/resource.h>
#include <wil/result.h>
#pragma comment(lib, "Version.lib")
#pragma comment(linker, "/manifestdependency:\"type='win32' \
name='Microsoft.Windows.Common-Controls' \
version='6.0.0.0' \
processorArchitecture='*' \
publicKeyToken='6595b64144ccf1df' \
language='*'\"")
#define MAX_LOADSTRING 100
#define WM_NOTIFYICON (WM_USER + 100)
#define CATCH_SHOW_MSGBOX() \
catch (const wil::ResultException &e) \
{ \
wchar_t message[2048]{}; \
wil::GetFailureLogString(message, ARRAYSIZE(message), e.GetFailureInfo()); \
MessageBox(hWnd, message, g_szTitle, MB_ICONERROR); \
}
using namespace std::string_literals;
using namespace std::string_view_literals;
namespace my
{
inline auto GetWindowThreadProcessId(HWND hwnd)
{
DWORD pid{};
return std::make_tuple(::GetWindowThreadProcessId(hwnd, &pid), pid);
}
inline std::wstring GetClassName(HWND hwnd)
{
WCHAR className[256]{};
unsigned len = ::GetClassName(hwnd, className, ARRAYSIZE(className));
return { className, len };
}
inline std::wstring GetModuleFileName()
{
WCHAR fileName[256]{};
unsigned len = ::GetModuleFileName(nullptr, fileName, ARRAYSIZE(fileName));
return { fileName, len };
}
} // namespace my
HINSTANCE g_hInst;
HHOOK g_hook;
WCHAR g_szTitle[MAX_LOADSTRING];
HWND g_hwnd;
LRESULT CALLBACK wndProc(HWND, UINT, WPARAM, LPARAM) noexcept;
INT_PTR CALLBACK about(HWND, UINT, WPARAM, LPARAM) noexcept;
constexpr auto NOTIFY_UID = 1;
constexpr auto szWindowClass = L"{B9EA841C-34B1-467B-8792-F7E2AE21D640}";
auto constexpr targetClassName{ L"CabinetWClass" };
// auto constexpr targetClassName{ L"Notepad" };
struct WindowInfo
{
bool isExplorer;
std::wstring filename;
};
WindowInfo getWindowInfo(HWND hWnd)
{
WindowInfo info{};
auto className{ my::GetClassName(hWnd) };
auto [tid, pid] = my::GetWindowThreadProcessId(hWnd);
if (wcscmp(className.c_str(), targetClassName) == 0)
{
info.isExplorer = true;
}
else if (pid != 0)
{
wil::unique_handle hProcess{ OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid) };
FILETIME creationTime, exitTime, kernelTime, userTime{};
GetProcessTimes(hProcess.get(), &creationTime, &exitTime, &kernelTime, &userTime);
WCHAR filename[MAX_PATH]{};
GetProcessImageFileName(hProcess.get(), filename, ARRAYSIZE(filename));
auto sep = wcsrchr(filename, L'\\');
info.filename = sep ? sep + 1 : filename;
}
return info;
}
LRESULT CALLBACK lowLevelKeyboardProc(int code, WPARAM wParam, LPARAM lParam) noexcept
{
if (code < 0)
return CallNextHookEx(NULL, code, wParam, lParam);
auto pKbdll = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam);
if (!(pKbdll->flags & LLKHF_LOWER_IL_INJECTED) && pKbdll->vkCode == VK_F1)
{
auto hWnd{ GetFocus() };
if (hWnd == nullptr)
hWnd = GetForegroundWindow();
if (hWnd)
{
auto info{ getWindowInfo(hWnd) };
if (info.isExplorer || lstrcmpiW(info.filename.c_str(), L"excel.exe") == 0)
return 1;
}
}
return CallNextHookEx(NULL, code, wParam, lParam);
}
void uninstallHook()
{
if (g_hook)
{
UnhookWindowsHookEx(g_hook);
g_hook = nullptr;
}
}
void installHook()
{
if (g_hook)
uninstallHook();
g_hook = { SetWindowsHookEx(WH_KEYBOARD_LL, &lowLevelKeyboardProc, nullptr, 0 /*global*/) };
THROW_LAST_ERROR_IF_NULL(g_hook);
}
bool isWorking()
{
return g_hook;
}
BOOL addNotifyIcon(HWND hWnd, unsigned int uID)
{
NOTIFYICONDATA nid{ sizeof(nid) };
nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
nid.hWnd = hWnd;
nid.uID = uID;
nid.uCallbackMessage = WM_NOTIFYICON;
nid.hIcon = LoadIcon(g_hInst, MAKEINTRESOURCE(IDI_SMALL));
wcscpy_s(nid.szTip, g_szTitle);
return Shell_NotifyIcon(NIM_ADD, &nid);
}
void deleteNotifyIcon(HWND hWnd, unsigned int uID)
{
NOTIFYICONDATA nid = {};
nid.cbSize = sizeof(nid);
nid.hWnd = hWnd;
nid.uID = uID;
Shell_NotifyIcon(NIM_DELETE, &nid);
}
ATOM registerMyClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex{
sizeof(WNDCLASSEX),
CS_HREDRAW | CS_VREDRAW,
&wndProc,
};
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SMALL));
wcex.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SMALL));
wcex.lpszClassName = szWindowClass;
return RegisterClassExW(&wcex);
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_SYSTEM32);
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
g_hInst = hInstance;
LoadStringW(hInstance, IDS_APP_TITLE, g_szTitle, MAX_LOADSTRING);
wcscat_s(g_szTitle,
#if _M_X64
L" (64bit)"
#else
L" (32bit)"
#endif
);
wil::unique_mutex m{ CreateMutex(nullptr, FALSE, g_szTitle) };
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
::MessageBox(nullptr, L"Another instance is already running.", g_szTitle, MB_ICONEXCLAMATION);
return 0;
}
auto hr{ CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) };
/*
SHELLEXECUTEINFO sei{
sizeof(SHELLEXECUTEINFO),
SEE_MASK_WAITFORINPUTIDLE | SEE_MASK_NO_CONSOLE,
};
sei.lpFile = L"notepad.exe";
sei.nShow = SW_SHOWNORMAL;
ShellExecuteEx(&sei);
//*/
installHook();
registerMyClass(hInstance);
HWND hWnd = CreateWindowW(szWindowClass, g_szTitle, 0, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr,
hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
if (!addNotifyIcon(hWnd, NOTIFY_UID))
{
return FALSE;
}
MSG msg{};
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
uninstallHook();
deleteNotifyIcon(hWnd, NOTIFY_UID);
return (int)msg.wParam;
}
void registerToShortcut(HWND hWnd)
try
{
WCHAR targetPath[MAX_PATH]{};
THROW_IF_WIN32_BOOL_FALSE(SHGetSpecialFolderPath(hWnd, targetPath, CSIDL_STARTUP, FALSE));
StringCchCat(targetPath, ARRAYSIZE(targetPath), (L"\\"s + g_szTitle + L".lnk"s).c_str());
auto pShellLink{ wil::CoCreateInstance<IShellLink>(CLSID_ShellLink) };
auto pPersistFile{ pShellLink.query<IPersistFile>() };
THROW_IF_FAILED(pShellLink->SetPath(my::GetModuleFileName().c_str()));
THROW_IF_FAILED(pPersistFile->Save(targetPath, TRUE));
}
CATCH_SHOW_MSGBOX()
LRESULT CALLBACK wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) noexcept
{
static UINT s_uTaskbarRestart;
static HMENU s_menu = nullptr;
switch (message)
{
case WM_CREATE:
g_hwnd = hWnd;
s_uTaskbarRestart = RegisterWindowMessage(L"TaskbarCreated");
s_menu = LoadMenu(g_hInst, MAKEINTRESOURCE(IDR_MENU1));
return DefWindowProc(hWnd, message, wParam, lParam);
case WM_COMMAND:
switch (LOWORD(wParam))
{
case ID_ROOT_ABOUT:
DialogBox(g_hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, &about);
break;
case ID_ROOT_REGISTERTOSTARTUPPROGRAM:
registerToShortcut(hWnd);
break;
case ID_ROOT_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_NOTIFYICON:
switch (lParam)
{
case WM_RBUTTONDOWN:
{
POINT pt{};
GetCursorPos(&pt);
SetForegroundWindow(hWnd);
TrackPopupMenu(GetSubMenu(s_menu, 0), TPM_LEFTALIGN, pt.x, pt.y, 0, hWnd, NULL);
}
break;
default:
;
}
return 0;
default:
if (message == s_uTaskbarRestart)
addNotifyIcon(hWnd, NOTIFY_UID);
else
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
void getProductAndVersion(LPWSTR szCopyright, UINT uCopyrightLen, LPWSTR szProductVersion, UINT uProductVersionLen)
{
WCHAR szFilename[MAX_PATH]{};
GetModuleFileName(nullptr, szFilename, ARRAYSIZE(szFilename));
DWORD dwHandle;
DWORD dwSize = GetFileVersionInfoSize(szFilename, &dwHandle);
if (dwSize == 0)
std::abort();
std::vector<BYTE> data(dwSize);
if (!GetFileVersionInfo(szFilename, 0, dwSize, data.data()))
std::abort();
LPWSTR pvCopyright{}, pvProductVersion{};
UINT iCopyrightLen{}, iProductVersionLen{};
if (!VerQueryValue(data.data(), L"\\StringFileInfo\\040004b0\\LegalCopyright", (LPVOID*)&pvCopyright,
&iCopyrightLen))
std::abort();
if (!VerQueryValue(data.data(), L"\\StringFileInfo\\040004b0\\ProductVersion", (LPVOID*)&pvProductVersion,
&iProductVersionLen))
std::abort();
wcsncpy_s(szCopyright, uCopyrightLen, pvCopyright, iCopyrightLen);
wcsncpy_s(szProductVersion, uProductVersionLen, pvProductVersion, iProductVersionLen);
}
INT_PTR CALLBACK about(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) noexcept
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG: {
WCHAR szCopyright[MAX_LOADSTRING]{};
WCHAR szVersion[MAX_LOADSTRING]{};
getProductAndVersion(szCopyright, ARRAYSIZE(szCopyright), szVersion, ARRAYSIZE(szVersion));
SetWindowText(hDlg, g_szTitle);
SetWindowText(GetDlgItem(hDlg, IDC_STATIC_COPYRIGHT), szCopyright);
SetWindowText(GetDlgItem(hDlg, IDC_STATIC_VERSION), szVersion);
return (INT_PTR)TRUE;
}
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
| 27.679688 | 115 | 0.636184 | [
"vector"
] |
52cb6be6d6d48535cdfe44fdb0f5dc8c238a79a0 | 3,375 | cpp | C++ | qtmultimedia/src/multimedia/controls/qcameracapturebufferformatcontrol.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtmultimedia/src/multimedia/controls/qcameracapturebufferformatcontrol.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtmultimedia/src/multimedia/controls/qcameracapturebufferformatcontrol.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qcameracapturebufferformatcontrol.h>
QT_BEGIN_NAMESPACE
/*!
\class QCameraCaptureBufferFormatControl
\brief The QCameraCaptureBufferFormatControl class provides a control for setting the capture buffer format.
The format is of type QVideoFrame::PixelFormat.
\inmodule QtMultimedia
\ingroup multimedia_control
The interface name of QCameraCaptureBufferFormatControl is \c org.qt-project.qt.cameracapturebufferformatcontrol/5.0 as
defined in QCameraCaptureBufferFormatControl_iid.
\sa QMediaService::requestControl()
*/
/*!
\macro QCameraCaptureBufferFormatControl_iid
\c org.qt-project.qt.cameracapturebufferformatcontrol/5.0
Defines the interface name of the QCameraCaptureBufferFormatControl class.
\relates QCameraCaptureBufferFormatControl
*/
/*!
Constructs a new image buffer capture format control object with the given \a parent
*/
QCameraCaptureBufferFormatControl::QCameraCaptureBufferFormatControl(QObject *parent)
:QMediaControl(parent)
{
}
/*!
Destroys an image buffer capture format control.
*/
QCameraCaptureBufferFormatControl::~QCameraCaptureBufferFormatControl()
{
}
/*!
\fn QCameraCaptureBufferFormatControl::supportedBufferFormats() const
Returns the list of the supported buffer capture formats.
*/
/*!
\fn QCameraCaptureBufferFormatControl::bufferFormat() const
Returns the current buffer capture format.
*/
/*!
\fn QCameraCaptureBufferFormatControl::setBufferFormat(QVideoFrame::PixelFormat format)
Sets the buffer capture \a format.
*/
/*!
\fn QCameraCaptureBufferFormatControl::bufferFormatChanged(QVideoFrame::PixelFormat format)
Signals the buffer image capture format changed to \a format.
*/
#include "moc_qcameracapturebufferformatcontrol.cpp"
QT_END_NAMESPACE
| 31.542056 | 123 | 0.737778 | [
"object"
] |
52d1026340694c4e142f722976168e926293a96f | 2,357 | hpp | C++ | src/mlpack/bindings/python/import_decl.hpp | MJ10/mlpack | 3f87ab1d419493dead8ef59250c02cc7aacc0adb | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-05-02T21:10:55.000Z | 2021-05-02T21:10:55.000Z | src/mlpack/bindings/python/import_decl.hpp | MJ10/mlpack | 3f87ab1d419493dead8ef59250c02cc7aacc0adb | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | src/mlpack/bindings/python/import_decl.hpp | MJ10/mlpack | 3f87ab1d419493dead8ef59250c02cc7aacc0adb | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /**
* @file import_decl.hpp
* @author Ryan Curtin
*
* For a serializable model, print the class import.
*/
#ifndef MLPACK_BINDINGS_PYTHON_IMPORT_DECL_HPP
#define MLPACK_BINDINGS_PYTHON_IMPORT_DECL_HPP
#include <mlpack/prereqs.hpp>
#include "strip_type.hpp"
namespace mlpack {
namespace bindings {
namespace python {
/**
* For a serializable type, print a cppclass definition.
*/
template<typename T>
void ImportDecl(
const util::ParamData& d,
const size_t indent,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::enable_if<data::HasSerialize<T>>::type* = 0)
{
// First, we have to parse the type. If we have something like, e.g.,
// 'LogisticRegression<>', we must convert this to 'LogisticRegression[T=*].'
std::string strippedType, printedType, defaultsType;
StripType(d.cppType, strippedType, printedType, defaultsType);
/**
* This will give output of the form:
*
* cdef cppclass Type:
* Type() nogil
*/
const std::string prefix = std::string(indent, ' ');
std::cout << prefix << "cdef cppclass " << defaultsType << ":" << std::endl;
std::cout << prefix << " " << strippedType << "() nogil" << std::endl;
std::cout << prefix << std::endl;
}
/**
* For a non-serializable type, print nothing.
*/
template<typename T>
void ImportDecl(
const util::ParamData& /* d */,
const size_t /* indent */,
const typename boost::disable_if<arma::is_arma_type<T>>::type* = 0,
const typename boost::disable_if<data::HasSerialize<T>>::type* = 0)
{
// Print nothing.
}
/**
* For a matrix type, print nothing.
*/
template<typename T>
void ImportDecl(
const util::ParamData& /* d */,
const size_t /* indent */,
const typename boost::enable_if<arma::is_arma_type<T>>::type* = 0)
{
// Print nothing.
}
/**
* Print the cppclass definition for a serializable model; print nothing for a
* non-serializable type.
*
* @param d Parameter info struct.
* @param input Pointer to size_t indicating indent.
* @param output Unused parameter.
*/
template<typename T>
void ImportDecl(const util::ParamData& d,
const void* indent,
void* /* output */)
{
ImportDecl<typename std::remove_pointer<T>::type>(d, *((size_t*) indent));
}
} // namespace python
} // namespace bindings
} // namespace mlpack
#endif
| 26.188889 | 79 | 0.66695 | [
"model"
] |
52d4f670eaf71ba3033ff7546b1401129251d1ad | 7,965 | cpp | C++ | Gems/Atom/RPI/Code/Tests.Builders/ResourcePoolBuilderTest.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T12:39:24.000Z | 2021-07-20T12:39:24.000Z | Gems/Atom/RPI/Code/Tests.Builders/ResourcePoolBuilderTest.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/Atom/RPI/Code/Tests.Builders/ResourcePoolBuilderTest.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzTest/AzTest.h>
#include <AtomCore/Serialization/Json/JsonUtils.h>
#include <Atom/RHI.Reflect/BufferPoolDescriptor.h>
#include <Atom/RHI.Reflect/ImagePoolDescriptor.h>
#include <Atom/RHI.Reflect/StreamingImagePoolDescriptor.h>
#include <Atom/RPI.Reflect/Image/StreamingImagePoolAsset.h>
#include <AzCore/Serialization/ObjectStream.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/Utils.h>
#include <ResourcePool/ResourcePoolBuilder.h>
#include <Tests.Builders/BuilderTestFixture.h>
namespace UnitTest
{
using namespace AZ;
class ResourcePoolBuilderTests
: public BuilderTestFixture
{
protected:
AZStd::unique_ptr<RPI::StreamingImagePoolAssetHandler> m_streamingImagePoolAssetHandler;
AZStd::unique_ptr<RPI::ResourcePoolAssetHandler> m_resourcePoolAssetHandler;
void SetUp() override
{
BuilderTestFixture::SetUp();
m_streamingImagePoolAssetHandler = AZStd::make_unique<RPI::StreamingImagePoolAssetHandler>();
m_resourcePoolAssetHandler = AZStd::make_unique<RPI::ResourcePoolAssetHandler>();
m_streamingImagePoolAssetHandler->m_serializeContext = m_context.get();
m_resourcePoolAssetHandler->m_serializeContext = m_context.get();
m_streamingImagePoolAssetHandler->Register();
m_resourcePoolAssetHandler->Register();
}
void TearDown() override
{
m_streamingImagePoolAssetHandler->Unregister();
m_resourcePoolAssetHandler->Unregister();
m_streamingImagePoolAssetHandler.reset();
m_resourcePoolAssetHandler.reset();
BuilderTestFixture::TearDown();
}
};
TEST_F(ResourcePoolBuilderTests, ProcessJob_OutputBufferPool)
{
RPI::ResourcePoolBuilder builder;
AssetBuilderSDK::ProcessJobRequest request;
AssetBuilderSDK::ProcessJobResponse response;
// Initial job request
const char* testAssetName = "BufferPool.resourcepool";
request.m_fullPath = testAssetName;
request.m_tempDirPath = m_currentDir;
RPI::ResourcePoolSourceData sourceData;
sourceData.m_poolName = "DefaultIndexBufferPool";
sourceData.m_poolType = RPI::ResourcePoolAssetType::BufferPool;
sourceData.m_budgetInBytes = 25165824;
sourceData.m_heapMemoryLevel = RHI::HeapMemoryLevel::Device;
sourceData.m_hostMemoryAccess = RHI::HostMemoryAccess::Write;
sourceData.m_bufferPoolBindFlags = RHI::BufferBindFlags::InputAssembly;
Outcome<void, AZStd::string> saveResult = AZ::JsonSerializationUtils::SaveObjectToFile<RPI::ResourcePoolSourceData>(&sourceData,
testAssetName);
// Process
builder.ProcessJob(request, response);
// verify job output
EXPECT_TRUE(response.m_resultCode == AssetBuilderSDK::ProcessJobResult_Success);
EXPECT_TRUE(response.m_outputProducts.size() == 1);
EXPECT_TRUE(response.m_outputProducts[0].m_dependencies.size() == 0);
// verify output file and verify loaded asset
auto outAsset = Utils::LoadObjectFromFile<RPI::ResourcePoolAsset>(response.m_outputProducts[0].m_productFileName, m_context.get());
auto poolDescriptor = outAsset->GetPoolDescriptor();
EXPECT_TRUE(sourceData.m_poolName == outAsset->GetPoolName());
EXPECT_TRUE(azrtti_typeid <RHI::BufferPoolDescriptor>() == azrtti_typeid(poolDescriptor.get()));
auto bufferPoolDesc = azrtti_cast<RHI::BufferPoolDescriptor*>(poolDescriptor.get());
EXPECT_TRUE(sourceData.m_budgetInBytes == bufferPoolDesc->m_budgetInBytes);
EXPECT_TRUE(sourceData.m_heapMemoryLevel == bufferPoolDesc->m_heapMemoryLevel);
EXPECT_TRUE(sourceData.m_hostMemoryAccess == bufferPoolDesc->m_hostMemoryAccess);
EXPECT_TRUE(sourceData.m_bufferPoolBindFlags == bufferPoolDesc->m_bindFlags);
delete outAsset;
}
TEST_F(ResourcePoolBuilderTests, ProcessJob_OutputImagePool)
{
RPI::ResourcePoolBuilder builder;
AssetBuilderSDK::ProcessJobRequest request;
AssetBuilderSDK::ProcessJobResponse response;
// Initial job request
const char* testAssetName = "ImagePool.resourcepool";
request.m_fullPath = testAssetName;
request.m_tempDirPath = m_currentDir;
RPI::ResourcePoolSourceData sourceData;
sourceData.m_poolName = "DefaultImagePool";
sourceData.m_poolType = RPI::ResourcePoolAssetType::ImagePool;
sourceData.m_budgetInBytes = 25165824;
sourceData.m_imagePoolBindFlags = RHI::ImageBindFlags::Color;
Outcome<void, AZStd::string> saveResult = AZ::JsonSerializationUtils::SaveObjectToFile<RPI::ResourcePoolSourceData>(&sourceData,
testAssetName);
// Process
builder.ProcessJob(request, response);
// verify job output
EXPECT_TRUE(response.m_resultCode == AssetBuilderSDK::ProcessJobResult_Success);
EXPECT_TRUE(response.m_outputProducts.size() == 1);
EXPECT_TRUE(response.m_outputProducts[0].m_dependencies.size() == 0);
// verify output file and verify loaded asset
auto outAsset = Utils::LoadObjectFromFile<RPI::ResourcePoolAsset>(response.m_outputProducts[0].m_productFileName, m_context.get());
auto poolDescriptor = outAsset->GetPoolDescriptor();
EXPECT_TRUE(sourceData.m_poolName == outAsset->GetPoolName());
EXPECT_TRUE(azrtti_typeid<RHI::ImagePoolDescriptor>() == azrtti_typeid(poolDescriptor.get()));
auto imagePoolDesc = azrtti_cast<RHI::ImagePoolDescriptor*>(poolDescriptor.get());
EXPECT_TRUE(sourceData.m_budgetInBytes == imagePoolDesc->m_budgetInBytes);
EXPECT_TRUE(sourceData.m_imagePoolBindFlags == imagePoolDesc->m_bindFlags);
delete outAsset;
}
TEST_F(ResourcePoolBuilderTests, ProcessJob_OutputStreamingImagePool)
{
RPI::ResourcePoolBuilder builder;
AssetBuilderSDK::ProcessJobRequest request;
AssetBuilderSDK::ProcessJobResponse response;
// Initial job request
const char* testAssetName = "streamingImagePool.resourcepool";
request.m_fullPath = testAssetName;
request.m_tempDirPath = m_currentDir;
RPI::ResourcePoolSourceData sourceData;
sourceData.m_poolName = "DefaultStreamingImagePool";
sourceData.m_poolType = RPI::ResourcePoolAssetType::StreamingImagePool;
sourceData.m_budgetInBytes = 2147483648;
Outcome<void, AZStd::string> saveResult = AZ::JsonSerializationUtils::SaveObjectToFile<RPI::ResourcePoolSourceData>(&sourceData,
testAssetName);
// Process
builder.ProcessJob(request, response);
// verify job output
EXPECT_TRUE(response.m_resultCode == AssetBuilderSDK::ProcessJobResult_Success);
EXPECT_TRUE(response.m_outputProducts.size() == 1);
EXPECT_TRUE(response.m_outputProducts[0].m_dependencies.size() == 0);
// verify output file and verify loaded asset
Utils::FilterDescriptor filter; // disable loading the controller asset inside
filter.m_assetCB = AZ::Data::AssetFilterNoAssetLoading;
auto outAsset = Utils::LoadObjectFromFile<RPI::StreamingImagePoolAsset>(response.m_outputProducts[0].m_productFileName, m_context.get(), filter);
auto poolDescriptor = outAsset->GetPoolDescriptor();
EXPECT_TRUE(azrtti_typeid <RHI::StreamingImagePoolDescriptor>() == azrtti_typeid(poolDescriptor));
EXPECT_TRUE(sourceData.m_budgetInBytes == poolDescriptor.m_budgetInBytes);
delete outAsset;
}
} // namespace UnitTests
| 43.763736 | 158 | 0.717137 | [
"3d"
] |
52e72fc0252e86ce399f03238cefb4c980a684d1 | 3,635 | cpp | C++ | ork.tool/src/qtui/pybindings.cpp | tweakoz/orkid | e3f78dfb3375853fd512a9d0828b009075a18345 | [
"BSL-1.0"
] | 25 | 2015-02-21T04:21:21.000Z | 2022-01-20T05:19:27.000Z | ork.tool/src/qtui/pybindings.cpp | tweakoz/orkid | e3f78dfb3375853fd512a9d0828b009075a18345 | [
"BSL-1.0"
] | 113 | 2019-08-23T04:52:14.000Z | 2021-09-13T04:04:11.000Z | ork.tool/src/qtui/pybindings.cpp | tweakoz/orkid | e3f78dfb3375853fd512a9d0828b009075a18345 | [
"BSL-1.0"
] | 4 | 2017-02-20T18:17:55.000Z | 2020-06-28T03:47:55.000Z | #include <Python.h>
#include <pybind11/pybind11.h>
#include <pybind11/operators.h>
#include <pybind11/stl.h>
#include <orktool/qtui/qtui_tool.h>
#include <ork/kernel/fixedstring.hpp>
#include <pkg/ent/scene.h>
#include <ostream>
///////////////////////////////////////////////////////////////////////////////
namespace py = pybind11;
using namespace pybind11::literals;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
namespace ork { namespace tool {
///////////////////////////////////////////////////////////////////////////////
ent::SceneData* PyNewScene();
ent::SceneData* PyGetScene();
void PyNewRefArch(const std::string& name);
void PyNewArch(const std::string& classname, const std::string& name);
void PyNewEntity(const std::string& name, const std::string& archname = "");
///////////////////////////////////////////////////////////////////////////////
class ed {
public:
std::string whatup() {
return std::string("whatup yourself");
}
std::string damn() {
return std::string("hot damn");
}
ent::SceneData* getscene() {
return PyGetScene();
}
ent::SceneData* newscene() {
return PyNewScene();
}
void newentity(const std::string& entname, const std::string& archname = "no_arch") {
PyNewEntity(entname, archname);
}
void newrefarch(const std::string& name) {
PyNewRefArch(name);
}
void newarch(const std::string& classname, const std::string& name) {
PyNewArch(classname, name);
}
};
///////////////////////////////////////////////////////////////////////////////
void orkpy_initork() {
////////////////////////
// ork::fvec3
////////////////////////
py::module mm("__main__", "Orkid");
py::object main_namespace = mm.attr("__dict__");
main_namespace["scene"] = py::class_<ent::SceneData>(mm, "Scene")
.def("objects", [](ent::SceneData* sd) -> std::list<std::pair<std::string, ork::Object*>> {
std::list<std::pair<std::string, ork::Object*>> rval;
auto& objs = sd->GetSceneObjects();
for (const auto& item : objs) {
auto name = item.first.c_str();
auto obj = (ork::Object*)item.second;
auto p = std::pair<std::string, ork::Object*>(name, obj);
rval.push_back(p);
}
return rval;
});
////////////////////////
// scene editor
////////////////////////
main_namespace["editor"] = py::class_<ed>(mm, "editor")
.def(py::init<>())
.def("whatup", &ed::whatup)
.def("damn", &ed::damn)
.def("newscene", &ed::newscene)
.def("newentity", &ed::newentity)
.def("newrefarch", &ed::newrefarch)
.def("newarch", &ed::newarch)
.def("s", &ed::getscene)
.def("ns", &ed::newscene)
.def("ne", &ed::newentity)
.def("na", &ed::newarch)
.def("nra", &ed::newrefarch);
}
///////////////////////////////////////////////////////////////////////////////
}} // namespace ork::tool
| 37.864583 | 123 | 0.4 | [
"object"
] |
52e971f1eb98e4527292118224742d0514c4bffe | 1,905 | cpp | C++ | test/delaunator-test.cpp | harveydevereux/CUDA-Whirligigs | b03b3271d4959cc22631bf5e71b0f04c7d583727 | [
"CC0-1.0"
] | 1 | 2021-04-09T21:36:16.000Z | 2021-04-09T21:36:16.000Z | test/delaunator-test.cpp | harveydevereux/CUDA-Whirligigs | b03b3271d4959cc22631bf5e71b0f04c7d583727 | [
"CC0-1.0"
] | null | null | null | test/delaunator-test.cpp | harveydevereux/CUDA-Whirligigs | b03b3271d4959cc22631bf5e71b0f04c7d583727 | [
"CC0-1.0"
] | null | null | null | #include "../include/density.h"
int main(int argc, char ** argv) {
int N = 0;
std::ifstream inputFile;
inputFile.open(argv[1]);
std::vector<double> coords;
if (inputFile.is_open()){
std::string line;
while (std::getline(inputFile,line)){
// x,y
double x = 0.0;
double y = 0.0;
int c = 0;
std::string lineStr = line;
while (c < 2){
if (c == 1){
y = std::stod(lineStr);
break;
}
size_t position = lineStr.find(",");
std::string str = lineStr.substr(0,position);
if (c == 0){
x = std::stod(str);
}
lineStr = lineStr.substr(position+1);
c += 1;
}
coords.push_back(x);
coords.push_back(y);
N += 1;
}
}
else{
std::cout << "Could not open input file: " << argv[1] << std::endl;
return -1;
}
/* x0, y0, x1, y1, ... */
auto t1 = std::chrono::high_resolution_clock::now();
//triangulation happens here
delaunator::Delaunator d(coords);
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
std::cout << "Triangulation complete in: " << duration * 1e-6 << " seconds\n";
std::ofstream out("out.txt");
std::vector<double> cells(N);
for (int i = 0; i < N; i++){
cells[i] = WeightedDTFELocalDensity(d,coords,i);
out << cells[i] << std::endl;
}
auto t3 = std::chrono::high_resolution_clock::now();
auto duration2 = std::chrono::duration_cast<std::chrono::microseconds>( t3 - t1 ).count();
std::cout << "density complete in: " << duration2 * 1e-6 << " seconds\n";
}
| 27.608696 | 94 | 0.491864 | [
"vector"
] |
52f76ecf435844f979fe37fcddd2fa52bc3c7a27 | 3,780 | cpp | C++ | MMOCoreORB/src/server/zone/objects/tangible/terminal/components/PowerRegulatorMenuComponent.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/src/server/zone/objects/tangible/terminal/components/PowerRegulatorMenuComponent.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/src/server/zone/objects/tangible/terminal/components/PowerRegulatorMenuComponent.cpp | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | /*
* PowerRegulatorMenuComponent.cpp
*
* Created on: Nov 2, 2012
* Author: root
*/
#include "PowerRegulatorMenuComponent.h"
#include "server/zone/Zone.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/objects/scene/SceneObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/building/BuildingObject.h"
#include "server/zone/managers/gcw/GCWManager.h"
void PowerRegulatorMenuComponent::fillObjectMenuResponse(SceneObject* sceneObject, ObjectMenuResponse* menuResponse, CreatureObject* player) const {
ManagedReference<BuildingObject*> building = sceneObject->getParentRecursively(SceneObjectType::FACTIONBUILDING).castTo<BuildingObject*>();
if (building == nullptr)
return;
if (player == nullptr || player->isDead() || player->isIncapacitated())
return;
Zone* zone = building->getZone();
if (zone == nullptr)
return;
GCWManager* gcwMan = zone->getGCWManager();
if (gcwMan == nullptr)
return;
if (!gcwMan->isBaseVulnerable(building))
return;
menuResponse->addRadialMenuItem(20, 3, "@hq:mnu_set_overload"); // Set to overload
}
int PowerRegulatorMenuComponent::handleObjectMenuSelect(SceneObject* sceneObject, CreatureObject* player, byte selectedID) const {
if (player->isDead() || player->isIncapacitated() || selectedID != 20)
return 1;
ManagedReference<BuildingObject*> building = sceneObject->getParentRecursively(SceneObjectType::FACTIONBUILDING).castTo<BuildingObject*>();
ManagedReference<TangibleObject*> powerRegulator = cast<TangibleObject*>(sceneObject);
if (building == nullptr)
return 1;
Zone* zone = building->getZone();
if (zone == nullptr)
return 1;
GCWManager* gcwMan = zone->getGCWManager();
if (gcwMan == nullptr)
return 1;
if (!gcwMan->isBaseVulnerable(building))
return 1;
if (!gcwMan->areOpposingFactions(player->getFaction(), building->getFaction())) {
player->sendSystemMessage("@faction/faction_hq/faction_hq_response:no_tamper"); // You are not an enemy of this structure. Why would you want to tamper?
return 1;
} else if (gcwMan->isPowerOverloaded(building)) {
player->sendSystemMessage("@faction/faction_hq/faction_hq_response:already_overloading"); // The power regulator has already been set to overload.
return 1;
} else if (!gcwMan->isDNASampled(building)) {
player->sendSystemMessage("@faction/faction_hq/faction_hq_response:other_objectives"); // Other objectives must be disabled prior to gaining access to this one.
return 1;
} else if (player->isInCombat()) {
player->sendSystemMessage("@faction/faction_hq/faction_hq_response:power_not_in_combat"); // You cannot align the power flow to overload if you are in combat!
return 1;
} else if (powerRegulator->getParentID() != player->getParentID()) {
player->sendSystemMessage("@faction/faction_hq/faction_hq_response:power_not_in_room"); // You cannot align the power flow if you are not even in the same room!
return 1;
} else if (powerRegulator->getDistanceTo(player) > 15) {
player->sendSystemMessage("@faction/faction_hq/faction_hq_response:power_too_far"); // You are too far away from the power regulator to continue the setup!
return 1;
} else if (!player->hasSkill("combat_commando_heavyweapon_speed_02")) {
player->sendSystemMessage("@faction/faction_hq/faction_hq_response:commando_only"); // Only an experienced commando with heavy weapons training could expect to rig the regulators for overload
return 1;
}
Reference<CreatureObject*> playerRef = player;
Core::getTaskManager()->executeTask([=] () {
Locker locker(playerRef);
Locker clocker(building, playerRef);
gcwMan->sendPowerRegulatorControls(playerRef, building, powerRegulator);
}, "SendPowerRegulatorControlsLambda");
return 0;
}
| 38.181818 | 193 | 0.759524 | [
"object"
] |
52f77e84a767b22cc7659568158805418159e009 | 23,521 | cc | C++ | db/db_mv_test.cc | essethon/leveldb | fc604bf7ba7e67026e84b19f8baa553fc249719f | [
"BSD-3-Clause"
] | 1 | 2021-06-08T16:03:50.000Z | 2021-06-08T16:03:50.000Z | db/db_mv_test.cc | essethon/leveldb | fc604bf7ba7e67026e84b19f8baa553fc249719f | [
"BSD-3-Clause"
] | null | null | null | db/db_mv_test.cc | essethon/leveldb | fc604bf7ba7e67026e84b19f8baa553fc249719f | [
"BSD-3-Clause"
] | null | null | null | //
// Created by Xiaofei ZHAO on 30/4/2021.
//
#include "leveldb/db.h"
#include <atomic>
#include <cinttypes>
#include <string>
#include <chrono>
#include <ctime>
#include "gtest/gtest.h"
#include "benchmark/benchmark.h"
#include "db/db_impl.h"
#include "db/filename.h"
#include "db/version_set.h"
#include "db/write_batch_internal.h"
#include "leveldb/cache.h"
#include "leveldb/env.h"
#include "leveldb/filter_policy.h"
#include "leveldb/table.h"
#include "port/port.h"
#include "port/thread_annotations.h"
#include "util/hash.h"
#include "util/logging.h"
#include "util/mutexlock.h"
#include "util/testutil.h"
namespace leveldb {
static std::string RandomString(Random* rnd, int len) {
std::string r;
test::RandomString(rnd, len, &r);
return r;
}
static std::string RandomKey(Random* rnd) {
int len =
(rnd->OneIn(3) ? 1 // Short sometimes to encourage collisions
: (rnd->OneIn(100) ? rnd->Skewed(10) : rnd->Uniform(10)));
return test::RandomKey(rnd, len);
}
std::string MakeKey(unsigned int num) {
char buf[30];
std::snprintf(buf, sizeof(buf), "%016u", num);
return std::string(buf);
}
namespace {
class AtomicCounter {
public:
AtomicCounter() : count_(0) {}
void Increment() { IncrementBy(1); }
void IncrementBy(int count) LOCKS_EXCLUDED(mu_) {
MutexLock l(&mu_);
count_ += count;
}
int Read() LOCKS_EXCLUDED(mu_) {
MutexLock l(&mu_);
return count_;
}
void Reset() LOCKS_EXCLUDED(mu_) {
MutexLock l(&mu_);
count_ = 0;
}
private:
port::Mutex mu_;
int count_ GUARDED_BY(mu_);
};
void DelayMilliseconds(int millis) {
Env::Default()->SleepForMicroseconds(millis * 1000);
}
} // namespace
// Test Env to override default Env behavior for testing.
class TestEnv : public EnvWrapper {
public:
explicit TestEnv(Env* base) : EnvWrapper(base), ignore_dot_files_(false) {}
void SetIgnoreDotFiles(bool ignored) { ignore_dot_files_ = ignored; }
Status GetChildren(const std::string& dir,
std::vector<std::string>* result) override {
Status s = target()->GetChildren(dir, result);
if (!s.ok() || !ignore_dot_files_) {
return s;
}
std::vector<std::string>::iterator it = result->begin();
while (it != result->end()) {
if ((*it == ".") || (*it == "..")) {
it = result->erase(it);
} else {
++it;
}
}
return s;
}
private:
bool ignore_dot_files_;
};
// Special Env used to delay background operations.
class SpecialEnv : public EnvWrapper {
public:
// sstable/log Sync() calls are blocked while this pointer is non-null.
std::atomic<bool> delay_data_sync_;
// sstable/log Sync() calls return an error.
std::atomic<bool> data_sync_error_;
// Simulate no-space errors while this pointer is non-null.
std::atomic<bool> no_space_;
// Simulate non-writable file system while this pointer is non-null.
std::atomic<bool> non_writable_;
// Force sync of manifest files to fail while this pointer is non-null.
std::atomic<bool> manifest_sync_error_;
// Force write to manifest files to fail while this pointer is non-null.
std::atomic<bool> manifest_write_error_;
bool count_random_reads_;
AtomicCounter random_read_counter_;
explicit SpecialEnv(Env* base)
: EnvWrapper(base),
delay_data_sync_(false),
data_sync_error_(false),
no_space_(false),
non_writable_(false),
manifest_sync_error_(false),
manifest_write_error_(false),
count_random_reads_(false) {}
Status NewWritableFile(const std::string& f, WritableFile** r) {
class DataFile : public WritableFile {
private:
SpecialEnv* const env_;
WritableFile* const base_;
public:
DataFile(SpecialEnv* env, WritableFile* base) : env_(env), base_(base) {}
~DataFile() { delete base_; }
Status Append(const Slice& data) {
if (env_->no_space_.load(std::memory_order_acquire)) {
// Drop writes on the floor
return Status::OK();
} else {
return base_->Append(data);
}
}
Status Close() { return base_->Close(); }
Status Flush() { return base_->Flush(); }
Status Sync() {
if (env_->data_sync_error_.load(std::memory_order_acquire)) {
return Status::IOError("simulated data sync error");
}
while (env_->delay_data_sync_.load(std::memory_order_acquire)) {
DelayMilliseconds(100);
}
return base_->Sync();
}
};
class ManifestFile : public WritableFile {
private:
SpecialEnv* env_;
WritableFile* base_;
public:
ManifestFile(SpecialEnv* env, WritableFile* b) : env_(env), base_(b) {}
~ManifestFile() { delete base_; }
Status Append(const Slice& data) {
if (env_->manifest_write_error_.load(std::memory_order_acquire)) {
return Status::IOError("simulated writer error");
} else {
return base_->Append(data);
}
}
Status Close() { return base_->Close(); }
Status Flush() { return base_->Flush(); }
Status Sync() {
if (env_->manifest_sync_error_.load(std::memory_order_acquire)) {
return Status::IOError("simulated sync error");
} else {
return base_->Sync();
}
}
};
if (non_writable_.load(std::memory_order_acquire)) {
return Status::IOError("simulated write error");
}
Status s = target()->NewWritableFile(f, r);
if (s.ok()) {
if (strstr(f.c_str(), ".ldb") != nullptr ||
strstr(f.c_str(), ".log") != nullptr) {
*r = new DataFile(this, *r);
} else if (strstr(f.c_str(), "MANIFEST") != nullptr) {
*r = new ManifestFile(this, *r);
}
}
return s;
}
Status NewRandomAccessFile(const std::string& f, RandomAccessFile** r) {
class CountingFile : public RandomAccessFile {
private:
RandomAccessFile* target_;
AtomicCounter* counter_;
public:
CountingFile(RandomAccessFile* target, AtomicCounter* counter)
: target_(target), counter_(counter) {}
~CountingFile() override { delete target_; }
Status Read(uint64_t offset, size_t n, Slice* result,
char* scratch) const override {
counter_->Increment();
return target_->Read(offset, n, result, scratch);
}
};
Status s = target()->NewRandomAccessFile(f, r);
if (s.ok() && count_random_reads_) {
*r = new CountingFile(*r, &random_read_counter_);
}
return s;
}
};
class DBTest : public testing::Test {
public:
std::string dbname_;
SpecialEnv* env_;
DB* db_;
Options last_options_;
DBTest() : env_(new SpecialEnv(Env::Default())), option_config_(kDefault) {
filter_policy_ = NewBloomFilterPolicy(10);
dbname_ = testing::TempDir() + "db_test";
DestroyDB(dbname_, Options());
db_ = nullptr;
Reopen();
}
~DBTest() {
delete db_;
DestroyDB(dbname_, Options());
delete env_;
delete filter_policy_;
}
// Switch to a fresh database with the next option configuration to
// test. Return false if there are no more configurations to test.
bool ChangeOptions() {
option_config_++;
if (option_config_ > kDefault) { // MVLevelDB: only test default option
return false;
} else {
DestroyAndReopen();
return true;
}
}
// Return the current option configuration.
Options CurrentOptions() {
Options options;
options.reuse_logs = false;
switch (option_config_) {
case kReuse:options.reuse_logs = true;
break;
case kFilter:options.filter_policy = filter_policy_;
break;
case kUncompressed:options.compression = kNoCompression;
break;
default:break;
}
return options;
}
DBImpl* dbfull() { return reinterpret_cast<DBImpl*>(db_); }
void Reopen(Options* options = nullptr) {
ASSERT_LEVELDB_OK(TryReopen(options));
}
void Close() {
delete db_;
db_ = nullptr;
}
void DestroyAndReopen(Options* options = nullptr) {
delete db_;
db_ = nullptr;
DestroyDB(dbname_, Options());
ASSERT_LEVELDB_OK(TryReopen(options));
}
Status TryReopen(Options* options) {
delete db_;
db_ = nullptr;
Options opts;
if (options != nullptr) {
opts = *options;
} else {
opts = CurrentOptions();
opts.create_if_missing = true;
}
last_options_ = opts;
return DB::Open(opts, dbname_, &db_);
}
Status Put(const std::string& k, const std::string& v) {
return db_->Put(WriteOptions(), k, v);
}
Status PutMV(const std::string& k, ValidTime vt, const std::string& v) {
return db_->PutMV(WriteOptions(), k, vt, v);
}
Status Delete(const std::string& k) { return db_->Delete(WriteOptions(), k); }
std::string Get(const std::string& k, const Snapshot* snapshot = nullptr) {
ReadOptions options;
options.snapshot = snapshot;
std::string result;
Status s = db_->Get(options, k, &result);
if (s.IsNotFound()) {
result = "NOT_FOUND";
} else if (!s.ok()) {
result = s.ToString();
}
return result;
}
std::string GetMV(const std::string& k, ValidTime vt, ValidTimePeriod* period,
const Snapshot* snapshot = nullptr) {
ReadOptions options;
options.snapshot = snapshot;
std::string result;
Status s = db_->GetMV(options, k, vt, period, &result);
if (s.IsNotFound()) {
result = "NOT_FOUND";
} else if (!s.ok()) {
result = s.ToString();
}
return result;
}
// Return a string that contains all key,value pairs in order,
// formatted like "(k1->v1)(k2->v2)".
std::string Contents() {
std::vector<std::string> forward;
std::string result;
Iterator* iter = db_->NewIterator(ReadOptions());
for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
std::string s = IterStatus(iter);
result.push_back('(');
result.append(s);
result.push_back(')');
forward.push_back(s);
}
// Check reverse iteration results are the reverse of forward results
size_t matched = 0;
for (iter->SeekToLast(); iter->Valid(); iter->Prev()) {
EXPECT_LT(matched, forward.size());
EXPECT_EQ(IterStatus(iter), forward[forward.size() - matched - 1]);
matched++;
}
EXPECT_EQ(matched, forward.size());
delete iter;
return result;
}
std::string AllEntriesFor(const Slice& user_key) {
Iterator* iter = dbfull()->TEST_NewInternalIterator();
InternalKey target(user_key, kMaxSequenceNumber, kTypeValue);
iter->Seek(target.Encode());
std::string result;
if (!iter->status().ok()) {
result = iter->status().ToString();
} else {
result = "[ ";
bool first = true;
while (iter->Valid()) {
ParsedInternalKey ikey;
if (!ParseInternalKey(iter->key(), &ikey)) {
result += "CORRUPTED";
} else {
if (last_options_.comparator->Compare(ikey.user_key, user_key) != 0) {
break;
}
if (!first) {
result += ", ";
}
first = false;
switch (ikey.type) {
case kTypeValue:result += iter->value().ToString();
break;
case kTypeDeletion:result += "DEL";
break;
}
}
iter->Next();
}
if (!first) {
result += " ";
}
result += "]";
}
delete iter;
return result;
}
int NumTableFilesAtLevel(int level) {
std::string property;
EXPECT_TRUE(db_->GetProperty(
"leveldb.num-files-at-level" + NumberToString(level), &property));
return std::stoi(property);
}
int TotalTableFiles() {
int result = 0;
for (int level = 0; level < config::kNumLevels; level++) {
result += NumTableFilesAtLevel(level);
}
return result;
}
// Return spread of files per level
std::string FilesPerLevel() {
std::string result;
int last_non_zero_offset = 0;
for (int level = 0; level < config::kNumLevels; level++) {
int f = NumTableFilesAtLevel(level);
char buf[100];
std::snprintf(buf, sizeof(buf), "%s%d", (level ? "," : ""), f);
result += buf;
if (f > 0) {
last_non_zero_offset = result.size();
}
}
result.resize(last_non_zero_offset);
return result;
}
int CountFiles() {
std::vector<std::string> files;
env_->GetChildren(dbname_, &files);
return static_cast<int>(files.size());
}
uint64_t Size(const Slice& start, const Slice& limit) {
Range r(start, limit);
uint64_t size;
db_->GetApproximateSizes(&r, 1, &size);
return size;
}
void Compact(const Slice& start, const Slice& limit) {
db_->CompactRange(&start, &limit);
}
// Do n memtable compactions, each of which produces an sstable
// covering the range [small_key,large_key].
void MakeTables(int n, const std::string& small_key,
const std::string& large_key) {
for (int i = 0; i < n; i++) {
Put(small_key, "begin");
Put(large_key, "end");
dbfull()->TEST_CompactMemTable();
}
}
// Prevent pushing of new sstables into deeper levels by adding
// tables that cover a specified range to all levels.
void FillLevels(const std::string& smallest, const std::string& largest) {
MakeTables(config::kNumLevels, smallest, largest);
}
void DumpFileCounts(const char* label) {
std::fprintf(stderr, "---\n%s:\n", label);
std::fprintf(
stderr, "maxoverlap: %lld\n",
static_cast<long long>(dbfull()->TEST_MaxNextLevelOverlappingBytes()));
for (int level = 0; level < config::kNumLevels; level++) {
int num = NumTableFilesAtLevel(level);
if (num > 0) {
std::fprintf(stderr, " level %3d : %d files\n", level, num);
}
}
}
std::string DumpSSTableList() {
std::string property;
db_->GetProperty("leveldb.sstables", &property);
return property;
}
std::string IterStatus(Iterator* iter) {
std::string result;
if (iter->Valid()) {
result = iter->key().ToString() + "->" + iter->value().ToString();
} else {
result = "(invalid)";
}
return result;
}
bool DeleteAnSSTFile() {
std::vector<std::string> filenames;
EXPECT_LEVELDB_OK(env_->GetChildren(dbname_, &filenames));
uint64_t number;
FileType type;
for (size_t i = 0; i < filenames.size(); i++) {
if (ParseFileName(filenames[i], &number, &type) && type == kTableFile) {
EXPECT_LEVELDB_OK(env_->RemoveFile(TableFileName(dbname_, number)));
return true;
}
}
return false;
}
// Returns number of files renamed.
int RenameLDBToSST() {
std::vector<std::string> filenames;
EXPECT_LEVELDB_OK(env_->GetChildren(dbname_, &filenames));
uint64_t number;
FileType type;
int files_renamed = 0;
for (size_t i = 0; i < filenames.size(); i++) {
if (ParseFileName(filenames[i], &number, &type) && type == kTableFile) {
const std::string from = TableFileName(dbname_, number);
const std::string to = SSTTableFileName(dbname_, number);
EXPECT_LEVELDB_OK(env_->RenameFile(from, to));
files_renamed++;
}
}
return files_renamed;
}
private:
// Sequence of option configurations to try
enum OptionConfig { kDefault, kReuse, kFilter, kUncompressed, kEnd };
const FilterPolicy* filter_policy_;
int option_config_;
};
TEST_F(DBTest, Empty) {
do {
Options options = CurrentOptions();
options.multi_version = true;
Reopen(&options);
auto* period = new ValidTimePeriod(0, 0);
ASSERT_TRUE(db_ != nullptr);
ASSERT_EQ("NOT_FOUND", GetMV("foo", 0x0, period));
} while (ChangeOptions());
}
TEST_F(DBTest, EmptyKey) {
do {
Options options = CurrentOptions();
options.multi_version = true;
Reopen(&options);
auto* period = new ValidTimePeriod(0, 0);
ASSERT_LEVELDB_OK(PutMV("", 100, "v1"));
ASSERT_EQ("v1", GetMV("", 101, period));
ASSERT_EQ(100, period->lo);
ASSERT_LEVELDB_OK(PutMV("", 200, "v2"));
ASSERT_EQ("v2", GetMV("", 201, period));
ASSERT_EQ(200, period->lo);
} while (ChangeOptions());
}
TEST_F(DBTest, EmptyValue) {
do {
Options options = CurrentOptions();
options.multi_version = true;
Reopen(&options);
auto* period = new ValidTimePeriod(0, 0);
ASSERT_LEVELDB_OK(PutMV("key", 100, "v1"));
ASSERT_EQ("v1", GetMV("key", 100, period));
ASSERT_LEVELDB_OK(PutMV("key", 200, ""));
ASSERT_EQ("", GetMV("key", 200, period));
ASSERT_LEVELDB_OK(PutMV("key", 300, "v2"));
ASSERT_EQ("v2", GetMV("key", 350, period));
} while (ChangeOptions());
}
TEST_F(DBTest, ReadWriteOldVersion) {
do {
Options options = CurrentOptions();
options.multi_version = true;
Reopen(&options);
auto* period = new ValidTimePeriod(0, 0);
ASSERT_LEVELDB_OK(PutMV("foo", 100, "v1"));
ASSERT_EQ("v1", GetMV("foo", 100, period));
ASSERT_LEVELDB_OK(PutMV("bar", 100, "v2"));
ASSERT_LEVELDB_OK(PutMV("foo", 200, "v3"));
ASSERT_EQ("v3", GetMV("foo", 200, period));
ASSERT_EQ("v2", GetMV("bar", 100, period));
// Historical Versions
ASSERT_EQ("v1", GetMV("foo", 100, period));
ASSERT_EQ(100, period->lo);
ASSERT_EQ(200, period->hi);
ASSERT_EQ("v3", GetMV("foo", 50000, period));
ASSERT_EQ(200, period->lo);
ASSERT_EQ(kMaxValidTime, period->hi);
} while (ChangeOptions());
}
TEST_F(DBTest, PutDeleteGetOldVersion) {
do {
Options options = CurrentOptions();
options.multi_version = true;
Reopen(&options);
auto* period = new ValidTimePeriod(0, 0);
ASSERT_LEVELDB_OK(db_->PutMV(WriteOptions(), "foo", 100, "v1"));
ASSERT_EQ("v1", GetMV("foo", 100, period));
ASSERT_LEVELDB_OK(db_->PutMV(WriteOptions(), "foo", 200, "v2"));
ASSERT_EQ("v2", GetMV("foo", 200, period));
ASSERT_LEVELDB_OK(db_->DeleteMV(WriteOptions(), "foo", 300));
ASSERT_EQ("NOT_FOUND", GetMV("foo", 300, period));
} while (ChangeOptions());
}
TEST_F(DBTest, GetFromImmutableLayer) {
do {
Options options = CurrentOptions();
options.env = env_;
options.write_buffer_size = 20 * 1024 * 1024; // Small write buffer
options.multi_version = true;
Reopen(&options);
auto* period = new ValidTimePeriod(0, 0);
ASSERT_LEVELDB_OK(PutMV("foo", 100, "v1"));
ASSERT_EQ("v1", GetMV("foo", 100, period));
// Block sync calls.
env_->delay_data_sync_.store(true, std::memory_order_release);
PutMV("k1", 100, std::string(100000, 'x')); // Fill memtable.
PutMV("k1", 120, std::string(100000, 'u')); // Insert a new version of k1
dbfull()->TEST_MVCreateImmutableMemTable(150); // Trigger compaction mem -> imm.
ASSERT_EQ(std::string(100000, 'x'), GetMV("k1", 100, period));
ASSERT_EQ(100, period->lo);
// TODO: Check upper valid time.
// ASSERT_EQ(120, period->hi); // In current implementation, this will be 150.
ASSERT_EQ(std::string(100000, 'u'), GetMV("k1", 120, period));
ASSERT_EQ(120, period->lo);
ASSERT_EQ(150, period->hi);
ASSERT_EQ(std::string(100000, 'u'), GetMV("k1", 160, period));
ASSERT_EQ(150, period->lo);
ASSERT_EQ(kMaxValidTime, period->hi);
PutMV("k2", 200, std::string(100000, 'y')); // Trigger compaction.
ASSERT_EQ("v1", GetMV("foo", 200, period));
// Release sync calls.
env_->delay_data_sync_.store(false, std::memory_order_release);
} while (ChangeOptions());
}
TEST_F(DBTest, GetFromVersions) {
do {
Options options = CurrentOptions();
options.env = env_;
options.multi_version = true;
Reopen(&options);
auto* period = new ValidTimePeriod(0, 0);
ASSERT_LEVELDB_OK(PutMV("foo", 100, "v1"));
// ASSERT_EQ("v1", GetMV("foo", 100, period));
env_->delay_data_sync_.store(true, std::memory_order_release);
// dbfull()->TEST_MVCreateImmutableMemTable(150);
env_->delay_data_sync_.store(false, std::memory_order_release);
dbfull()->TEST_CompactMemTable();
ASSERT_EQ("v1", GetMV("foo", 100, period));
// ASSERT_EQ(100, period->lo);
} while (ChangeOptions());
}
TEST_F(DBTest, GetRangeFromMemTable) {
do {
Options options = CurrentOptions();
options.multi_version = true;
Reopen(&options);
ASSERT_LEVELDB_OK(PutMV("1", 100, "v1"));
ASSERT_LEVELDB_OK(PutMV("1", 110, "v1"));
ASSERT_LEVELDB_OK(PutMV("2", 120, "v2"));
ASSERT_LEVELDB_OK(PutMV("1", 130, "v1"));
ASSERT_LEVELDB_OK(PutMV("3", 150, "v3"));
KeyList k_list{Slice("1"), Slice("2"), Slice("3")};
TimeRange t_range(100, 150);
ResultSet res;
dbfull()->GetMVRange(ReadOptions(), k_list, t_range, &res);
ASSERT_EQ("v1", res[0].value);
ASSERT_EQ("v1", res[1].value);
ASSERT_EQ("v1", res[2].value);
ASSERT_EQ("v2", res[3].value);
ASSERT_EQ("v3", res[4].value);
res.clear();
t_range.lo = 120; // hi = 150
dbfull()->GetMVRange(ReadOptions(), k_list, t_range, &res);
ASSERT_EQ("v1", res[0].value);
ASSERT_EQ("v1", res[1].value);
ASSERT_EQ("v2", res[2].value);
ASSERT_EQ("v3", res[3].value);
} while (ChangeOptions());
}
TEST_F(DBTest, GetRangeFromImmutableLayer) {
do {
Options options = CurrentOptions();
options.multi_version = true;
Reopen(&options);
env_->delay_data_sync_.store(true, std::memory_order_release);
ASSERT_LEVELDB_OK(PutMV("1", 100, "v1"));
ASSERT_LEVELDB_OK(PutMV("1", 110, "v1"));
ASSERT_LEVELDB_OK(PutMV("2", 120, "v2"));
ASSERT_LEVELDB_OK(PutMV("1", 130, "v1"));
ASSERT_LEVELDB_OK(PutMV("3", 150, "v3"));
dbfull()->TEST_MVCreateImmutableMemTable(180);
env_->delay_data_sync_.store(false, std::memory_order_release);
KeyList k_list{Slice("1"), Slice("2"), Slice("3")};
TimeRange t_range(100, 150);
ResultSet res;
dbfull()->GetMVRange(ReadOptions(), k_list, t_range, &res);
ASSERT_EQ("v1", res[0].value);
ASSERT_EQ("v1", res[1].value);
ASSERT_EQ("v1", res[2].value);
ASSERT_EQ("v2", res[3].value);
ASSERT_EQ("v3", res[4].value);
res.clear();
t_range.lo = 120; // hi = 150
dbfull()->GetMVRange(ReadOptions(), k_list, t_range, &res);
ASSERT_EQ("v1", res[0].value);
ASSERT_EQ("v1", res[1].value);
ASSERT_EQ("v2", res[2].value);
ASSERT_EQ("v3", res[3].value);
} while (ChangeOptions());
}
TEST_F(DBTest, GetRangeFromVersions) {
do {
Options options = CurrentOptions();
options.env = env_;
options.multi_version = true;
Reopen(&options);
ASSERT_LEVELDB_OK(PutMV("foo", 100, "bar"));
ASSERT_LEVELDB_OK(PutMV("foo", 200, "bar2"));
ASSERT_LEVELDB_OK(PutMV("1", 100, "v1"));
ASSERT_LEVELDB_OK(PutMV("1", 110, "v1"));
ASSERT_LEVELDB_OK(PutMV("2", 120, "v2"));
ASSERT_LEVELDB_OK(PutMV("1", 130, "v1"));
ASSERT_LEVELDB_OK(PutMV("3", 150, "v3"));
dbfull()->SetDBCurrentTime(200);
dbfull()->TEST_CompactMemTable();
KeyList k_list{Slice("1"), Slice("2"), Slice("3")};
TimeRange t_range(110, 150);
ResultSet res;
ValidTimePeriod period(0,0);
GetMV("foo", 100, &period);
ASSERT_EQ(100, period.lo);
dbfull()->GetMVRange(ReadOptions(), k_list, t_range, &res);
ASSERT_EQ("v1", res[0].value);
} while (ChangeOptions());
}
} // namesapce leveldb
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
// benchmark::RunSpecifiedBenchmarks();
return RUN_ALL_TESTS();
} | 29.218634 | 85 | 0.62289 | [
"vector",
"3d"
] |
52f890007a999f32a5e7eadde94adf43b80958d6 | 2,193 | cpp | C++ | BioNetGen-2.3.0/source_NFsim/validate/BioNetGen-2.2.6-stable/Network3/src/pla/util/sbChecker.cpp | joseph-hellerstein/RuleBasedProgramming | fb88118ab764035979dc7c2bf8c89a7b484e4472 | [
"MIT"
] | 53 | 2015-03-15T20:33:36.000Z | 2022-02-25T12:07:26.000Z | BioNetGen-2.3.0/source_NFsim/validate/BioNetGen-2.2.6-stable/Network3/src/pla/util/sbChecker.cpp | joseph-hellerstein/RuleBasedProgramming | fb88118ab764035979dc7c2bf8c89a7b484e4472 | [
"MIT"
] | 85 | 2015-03-19T19:58:19.000Z | 2022-02-28T20:38:17.000Z | BioNetGen-2.3.0/source_NFsim/validate/BioNetGen-2.2.6-stable/Network3/src/pla/util/sbChecker.cpp | joseph-hellerstein/RuleBasedProgramming | fb88118ab764035979dc7c2bf8c89a7b484e4472 | [
"MIT"
] | 34 | 2015-05-02T23:46:57.000Z | 2021-12-22T19:35:58.000Z | /*
* sbChecker.cpp
*
* Created on: Mar 15, 2012
* Author: Leonard Harris
*/
#include "plCheckers.hh"
SBChecker::SBChecker(double eps, vector<SimpleSpecies*>& sp) : eps(eps), sp(sp){
if (debug)
cout << "SBChecker constructor called." << endl;
// Error check
if (eps < 0.0 || eps > 1.0){
cout << "Error in SBChecker constructor: ";
cout << "epsilon must be >= 0.0 and <= 1.0; your eps = " << eps << ". Exiting." << endl;
exit(1);
}
}
SBChecker::SBChecker(const SBChecker& ch) : eps(ch.eps), sp(ch.sp){
if (debug)
cout << "SBChecker copy constructor called." << endl;
}
SBChecker::~SBChecker(){
if (debug)
cout << "SBChecker destructor called." << endl;
}
bool SBChecker::check(double w, vector<double>& x_check, vector<double>& x_ref, vector<double>& g_ref, bool postcheck){
// Error check
if (x_check.size() != this->sp.size()){
cout << "Error in SBChecker::check(): 'X_eff' and 'sp' vectors must be equal sizes. Exiting.\n";
exit(1);
}
if (x_ref.size() != this->sp.size()){
cout << "Error in SBChecker::check(): 'refPop' and 'sp' vectors must be equal sizes. Exiting.\n";
exit(1);
}
if (g_ref.size() != this->sp.size()){
cout << "Error in SBChecker::check(): 'ref_g' and 'sp' vectors must be equal sizes. Exiting.\n";
exit(1);
}
double X_j, dX_j, dXcheck_j;
for (unsigned int j=0;j < this->sp.size();j++){
X_j = this->sp[j]->population;
if (X_j < 0.0 || x_ref[j] < 0.0){
/* if (X_j < 0.0){
cout << "Uh oh, species " << this->sp[j]->name << " has a negative population (" << X_j << ").\n";
}*/
return false;
}
dX_j = fabs(X_j - x_ref[j]);
dXcheck_j = fabs(X_j - x_check[j]);
double xScale;
if (postcheck) xScale = x_check[j];
else xScale = X_j;
if ( dXcheck_j > w*this->eps*xScale/g_ref[j] && dX_j > (1.0 + TOL) ){
/* cout << this->sp[j]->name << ": "
<< "X_old = " << x_ref[j]
<< ", Xeff[" << j << "] = " << x_check[j]
<< ", X_target = " << x_check[j]*(1+this->eps/g_ref[j])
<< ", X[" << j << "] = " << X_j
<< ", abs(Xj-Xeff)/Xeff = " << fabs(X_j-x_check[j])/x_check[j]
<< ", eps/g_j = " << this->eps/g_ref[j] << endl; //*/
return false;
}
}
return true;
}
| 30.458333 | 119 | 0.565891 | [
"vector"
] |
52fd9ca1c65dc2c4c6be0a53e97d929851de02b2 | 927 | cpp | C++ | src/player/player_smart_cross.cpp | KrutNA/tic-tac-toe-cpp | a356fc168281df6ee114c3f2ac6ba6bf766479ae | [
"MIT"
] | 1 | 2021-12-23T21:32:14.000Z | 2021-12-23T21:32:14.000Z | src/player/player_smart_cross.cpp | KrutNA/tic-tac-toe-cpp | a356fc168281df6ee114c3f2ac6ba6bf766479ae | [
"MIT"
] | null | null | null | src/player/player_smart_cross.cpp | KrutNA/tic-tac-toe-cpp | a356fc168281df6ee114c3f2ac6ba6bf766479ae | [
"MIT"
] | null | null | null | #include "player_smart.hpp"
namespace core::player {
static const std::vector<std::pair<StateHash, Point>> pointMapsByStepCross[] = {
{ // Step 0
{0'111'111'111, {0, 0}},
},
{ // Step 1
{0'211'111'114, {0, 2}}, // leads to win
{0'277'777'771, {2, 2}},
},
{ // Step 2
{0'277'717'772, {1, 1}}, // win
{0'214'141'112, {2, 0}},
{0'241'141'112, {2, 1}},
{0'212'777'774, {0, 1}}, // win
{0'242'111'114, {2, 0}},
},
{ // Step 3
{0'777'777'212, {2, 1}}, // win
{0'247'747'122, {2, 0}}, // win
{0'241'141'422, {0, 2}},
{0'242'411'214, {1, 1}}, // win
{0'242'177'274, {1, 0}}, // win
},
{ // Step 4
{0'242'441'422, {1, 2}}, // win
{0'242'144'422, {1, 0}},
}
};
Point SmartPlayerLogicCross::findActionPoint(StateHash hash) {
return SmartPlayerLogic::findActionPointWithLogic(
hash,
pointMapsByStepCross,
transformationsCross);
}
}
| 21.068182 | 80 | 0.519957 | [
"vector"
] |
5e06960b5fdc2514f6b6f166aa8d86bdd3621282 | 3,704 | cpp | C++ | tools/bpp-core/src/Bpp/Text/StringTokenizer.cpp | danydoerr/spp_dcj | 1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a | [
"MIT"
] | 2 | 2021-08-24T16:03:30.000Z | 2022-03-18T14:52:43.000Z | tools/bpp-core/src/Bpp/Text/StringTokenizer.cpp | danydoerr/spp_dcj | 1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a | [
"MIT"
] | null | null | null | tools/bpp-core/src/Bpp/Text/StringTokenizer.cpp | danydoerr/spp_dcj | 1ab9dacb1f0dc34a3ebbeed9e74226a9a53c297a | [
"MIT"
] | null | null | null | //
// File: StringTokenizer.cpp
// Author : Julien Dutheil
// Sylvain Gaillard
// Last modification : Monday September 20 2004
//
/*
Copyright or © or Copr. Bio++ Development Team, (November 17, 2004)
This software is a computer program whose purpose is to provide utilitary
classes. This file belongs to the Bio++ Project.
This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use,
modify and/ or redistribute the software under the terms of the CeCILL
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info".
As a counterpart to the access to the source code and rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty and the software's author, the holder of the
economic rights, and the successive licensors have only limited
liability.
In this respect, the user's attention is drawn to the risks associated
with loading, using, modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean that it is complicated to manipulate, and that also
therefore means that it is reserved for developers and experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and, more generally, to use and operate it in the
same conditions as regards security.
The fact that you are presently reading this means that you have had
knowledge of the CeCILL license and that you accept its terms.
*/
#include "StringTokenizer.h"
using namespace bpp;
using namespace std;
StringTokenizer::StringTokenizer(const std::string& s, const std::string& delimiters, bool solid, bool allowEmptyTokens):
tokens_(),
splits_(),
currentPosition_(0)
{
if (!solid)
{
string::size_type index = s.find_first_not_of(delimiters, 0);
while( index != s.npos)
{
string::size_type newIndex = s.find_first_of(delimiters, index);
if (newIndex != s.npos)
{
tokens_.push_back(s.substr(index, newIndex - index));
if (!allowEmptyTokens) index = s.find_first_not_of(delimiters, newIndex);
else index = newIndex + 1;
splits_.push_back(s.substr(newIndex, index - newIndex));
}
else
{
tokens_.push_back(s.substr(index));
index = newIndex;
}
}
}
else
{
string::size_type index = 0;
while (index != s.npos)
{
string::size_type newIndex = s.find(delimiters, index);
if (newIndex != s.npos)
{
tokens_.push_back(s.substr(index, newIndex - index));
if (!allowEmptyTokens)
{
index = newIndex + delimiters.size();
while (index != string::npos && s.substr(index, delimiters.size()) == delimiters)
index += delimiters.size();
}
else index = newIndex + delimiters.size();
splits_.push_back(s.substr(newIndex, index - newIndex));
}
else
{
tokens_.push_back(s.substr(index));
index = newIndex;
}
}
}
}
void StringTokenizer::removeEmptyTokens()
{
for (size_t i = tokens_.size(); i > currentPosition_; i--)
{
if (tokens_[i - 1] == "") tokens_.erase(tokens_.begin() + static_cast<ptrdiff_t>(i - 1));
}
}
std::string StringTokenizer::unparseRemainingTokens() const
{
string s;
for (size_t i = currentPosition_; i < tokens_.size() - 1; ++i) {
s += tokens_[i] + splits_[i];
}
if (numberOfRemainingTokens() > 0)
s += tokens_.back();
return s;
}
| 31.65812 | 121 | 0.693305 | [
"solid"
] |
5e0786e0a2bb31ccac5f19f0cf1db500f0b3a13b | 2,846 | cpp | C++ | src/game/state.cpp | Gripnook/dynamic-connect-4 | 88bfcd7a6f6528e065e9c232d0c77e80cd212e8b | [
"MIT"
] | null | null | null | src/game/state.cpp | Gripnook/dynamic-connect-4 | 88bfcd7a6f6528e065e9c232d0c77e80cd212e8b | [
"MIT"
] | null | null | null | src/game/state.cpp | Gripnook/dynamic-connect-4 | 88bfcd7a6f6528e065e9c232d0c77e80cd212e8b | [
"MIT"
] | null | null | null | #include "game/state.h"
#include <vector>
#include <iostream>
#include <algorithm>
namespace DynamicConnect4 {
bool operator==(const State& lhs, const State& rhs)
{
return lhs.isPlayerOne == rhs.isPlayerOne &&
lhs.whitePieces == rhs.whitePieces &&
lhs.blackPieces == rhs.blackPieces;
}
bool operator!=(const State& lhs, const State& rhs)
{
return !(lhs == rhs);
}
std::istream& operator>>(std::istream& in, State& state)
{
std::vector<Point> whitePieces;
std::vector<Point> blackPieces;
int i = 0, j = 0;
for (char ch; j < boardSize && in.get(ch);)
{
if (ch == 'O')
{
if (i == boardSize)
{
in.clear(std::ios::failbit);
return in;
}
whitePieces.emplace_back(i++, j);
}
else if (ch == 'X')
{
if (i == boardSize)
{
in.clear(std::ios::failbit);
return in;
}
blackPieces.emplace_back(i++, j);
}
else if (ch == ' ')
{
if (i == boardSize)
{
in.clear(std::ios::failbit);
return in;
}
++i;
}
if (ch == '\n')
{
i = 0;
++j;
}
}
if (whitePieces.size() != piecesPerPlayer ||
blackPieces.size() != piecesPerPlayer)
{
in.clear(std::ios::failbit);
return in;
}
// Very important to sort.
std::sort(std::begin(whitePieces), std::end(whitePieces));
std::copy(
std::begin(whitePieces),
std::end(whitePieces),
std::begin(state.whitePieces));
// Very important to sort.
std::sort(std::begin(blackPieces), std::end(blackPieces));
std::copy(
std::begin(blackPieces),
std::end(blackPieces),
std::begin(state.blackPieces));
state.isPlayerOne = true;
return in;
}
std::ostream& operator<<(std::ostream& out, const State& state)
{
out << " 1 2 3 4 5 6 7" << std::endl;
for (int y = 0; y < boardSize; ++y)
{
out << (y + 1) << " ";
for (int x = 0; x < boardSize; ++x)
{
if (std::find(
std::begin(state.whitePieces),
std::end(state.whitePieces),
Point{x, y}) != std::end(state.whitePieces))
out << "O";
else if (
std::find(
std::begin(state.blackPieces),
std::end(state.blackPieces),
Point{x, y}) != std::end(state.blackPieces))
out << "X";
else
out << " ";
if (x + 1 < boardSize)
out << ",";
}
out << std::endl;
}
return out;
}
}
| 24.118644 | 64 | 0.453619 | [
"vector"
] |
5e0c26734f9633ac13bdd51b20d112a43af313f7 | 3,211 | cpp | C++ | tabnine-vim/third_party/ycmd/cpp/ycm/CodePoint.cpp | MrMonk3y/vimrc | 950230fb3fd7991d1234c2ab516ec03245945677 | [
"MIT"
] | null | null | null | tabnine-vim/third_party/ycmd/cpp/ycm/CodePoint.cpp | MrMonk3y/vimrc | 950230fb3fd7991d1234c2ab516ec03245945677 | [
"MIT"
] | null | null | null | tabnine-vim/third_party/ycmd/cpp/ycm/CodePoint.cpp | MrMonk3y/vimrc | 950230fb3fd7991d1234c2ab516ec03245945677 | [
"MIT"
] | null | null | null | // Copyright (C) 2018 ycmd contributors
//
// This file is part of ycmd.
//
// ycmd is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ycmd 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 ycmd. If not, see <http://www.gnu.org/licenses/>.
#include "CodePoint.h"
#include "CodePointRepository.h"
#include <array>
#include <cstring>
namespace YouCompleteMe {
namespace {
int GetCodePointLength( uint8_t leading_byte ) {
// 0xxxxxxx
if ( ( leading_byte & 0x80 ) == 0x00 ) {
return 1;
}
// 110xxxxx
if ( ( leading_byte & 0xe0 ) == 0xc0 ) {
return 2;
}
// 1110xxxx
if ( ( leading_byte & 0xf0 ) == 0xe0 ) {
return 3;
}
// 11110xxx
if ( ( leading_byte & 0xf8 ) == 0xf0 ) {
return 4;
}
throw UnicodeDecodeError( "Invalid leading byte in code point." );
}
const RawCodePoint FindCodePoint( const char *text ) {
#include "UnicodeTable.inc"
// Do a binary search on the array of code points to find the raw code point
// corresponding to the text. If no code point is found, return the default
// raw code point for that text.
auto first = code_points.begin();
size_t count = code_points.size();
while ( count > 0 ) {
size_t step = count / 2;
auto it = first + step;
int cmp = std::strcmp( it->original, text );
if ( cmp == 0 ) {
return *it;
}
if ( cmp < 0 ) {
first = ++it;
count -= step + 1;
} else {
count = step;
}
}
return { text, text, text, text, false, false, false, 0, 0 };
}
} // unnamed namespace
CodePoint::CodePoint( const std::string &code_point )
: CodePoint( FindCodePoint( code_point.c_str() ) ) {
}
CodePoint::CodePoint( const RawCodePoint &code_point )
: normal_( code_point.normal ),
folded_case_( code_point.folded_case ),
swapped_case_( code_point.swapped_case ),
is_letter_( code_point.is_letter ),
is_punctuation_( code_point.is_punctuation ),
is_uppercase_( code_point.is_uppercase ),
break_property_(
static_cast< BreakProperty >( code_point.break_property ) ),
combining_class_( code_point.combining_class ) {
}
CodePointSequence BreakIntoCodePoints( const std::string &text ) {
// NOTE: for efficiency, we don't check if the number of continuation bytes
// and the bytes themselves are valid (they must start with bits '10').
std::vector< std::string > code_points;
for ( auto iter = text.begin(); iter != text.end(); ) {
int length = GetCodePointLength( *iter );
if ( text.end() - iter < length ) {
throw UnicodeDecodeError( "Invalid code point length." );
}
code_points.emplace_back( iter, iter + length );
iter += length;
}
return CodePointRepository::Instance().GetCodePoints( code_points );
}
} // namespace YouCompleteMe
| 28.415929 | 78 | 0.670819 | [
"vector"
] |
5e0c73f752ac4cf0bd0b9e37b4b96151a66dd929 | 1,422 | hpp | C++ | src/core/storage/query_engine/operators/all_operators.hpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 11,356 | 2017-12-08T19:42:32.000Z | 2022-03-31T16:55:25.000Z | src/core/storage/query_engine/operators/all_operators.hpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 2,402 | 2017-12-08T22:31:01.000Z | 2022-03-28T19:25:52.000Z | src/core/storage/query_engine/operators/all_operators.hpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | /* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef TURI_SFRAME_QUERY_ALL_OPERATORS_H_
#define TURI_SFRAME_QUERY_ALL_OPERATORS_H_
#include <core/storage/query_engine/operators/append.hpp>
#include <core/storage/query_engine/operators/binary_transform.hpp>
#include <core/storage/query_engine/operators/constant.hpp>
#include <core/storage/query_engine/operators/logical_filter.hpp>
#include <core/storage/query_engine/operators/project.hpp>
#include <core/storage/query_engine/operators/range.hpp>
#include <core/storage/query_engine/operators/sarray_source.hpp>
#include <core/storage/query_engine/operators/sframe_source.hpp>
#include <core/storage/query_engine/operators/transform.hpp>
#include <core/storage/query_engine/operators/generalized_transform.hpp>
#include <core/storage/query_engine/operators/union.hpp>
#include <core/storage/query_engine/operators/generalized_union_project.hpp>
#include <core/storage/query_engine/operators/reduce.hpp>
#ifdef TC_HAS_PYTHON
#include <core/storage/query_engine/operators/lambda_transform.hpp>
#endif
#include <core/storage/query_engine/operators/optonly_identity_operator.hpp>
#include <core/storage/query_engine/operators/ternary_operator.hpp>
#endif /* TURI_SFRAME_QUERY_ALL_OPERATORS_H_ */
| 47.4 | 86 | 0.829114 | [
"transform"
] |
5e122e0635fc8f45bc10442c932756b1e5fd5933 | 7,465 | cpp | C++ | contrib/samples/win32/mfc/loggerwnd/loggerwnddlg.cpp | nanocortex/vscp | 0b1a51a35a886921179a8112c592547f84c9771a | [
"CC-BY-3.0"
] | 2 | 2020-12-01T18:54:20.000Z | 2022-01-24T20:18:33.000Z | samples/win32/mfc/loggerwnd/loggerwnddlg.cpp | grodansparadis/vscp-samples | 43becaafe267de0b772e99d9608e8ec4eb8343c8 | [
"MIT"
] | null | null | null | samples/win32/mfc/loggerwnd/loggerwnddlg.cpp | grodansparadis/vscp-samples | 43becaafe267de0b772e99d9608e8ec4eb8343c8 | [
"MIT"
] | null | null | null | // loggerWndDlg.cpp : implementation file
//
#include "stdafx.h"
#include "loggerWnd.h"
#include "loggerWndDlg.h"
#include "dlgfilter.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CLoggerWndDlg dialog
CLoggerWndDlg::CLoggerWndDlg(CWnd* pParent /*=NULL*/)
: CDialog(CLoggerWndDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CLoggerWndDlg)
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_idx = 0;
}
void CLoggerWndDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CLoggerWndDlg)
DDX_Control(pDX, IDC_LIST_AREA, m_ctrFrame);
DDX_Control(pDX, IDC_EDIT1, m_ctrlLog);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CLoggerWndDlg, CDialog)
//{{AFX_MSG_MAP(CLoggerWndDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_TIMER()
ON_WM_CLOSE()
ON_BN_CLICKED(IDFILTER, OnFilter)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CLoggerWndDlg message handlers
BOOL CLoggerWndDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
if ( !m_canalif.doCmdOpen( "ctrl", 1 ) ) {
AfxMessageBox("Unable to open channel to daemon! Please start canal server/service.");
exit(-1);
}
DWORD dwStyle = LVS_AUTOARRANGE | LVS_SINGLESEL | LVS_ALIGNTOP | LVS_REPORT;
CRect rc;
m_ctrFrame.GetClientRect( &rc );
m_ctrlList.Create( dwStyle,
rc,
this,
IDC_LIST );
m_ctrFrame.GetWindowRect( &rc );
ScreenToClient( &rc );
m_ctrlList.MoveWindow( &rc );
m_ctrlList.SetBkColor( LIST_BACK_COLOR );
m_ctrlList.SetTextBkColor( LIST_BACK_COLOR );
m_ctrlList.SetTextColor( LIST_FONT_COLOR );
m_ctrlList.SetExtendedStyle( LVS_EX_FULLROWSELECT );
m_ctrlList.InsertColumn( 0, _T("Time"), LVCFMT_LEFT, LIST_WIDTH_TIME );
m_ctrlList.InsertColumn( 1, _T("Timestamp"), LVCFMT_LEFT, LIST_WIDTH_TIMESTAMP );
m_ctrlList.InsertColumn( 2, _T("Flags"), LVCFMT_LEFT, LIST_WIDTH_FLAGS );
m_ctrlList.InsertColumn( 3, _T("Id"), LVCFMT_LEFT, LIST_WIDTH_ID );
m_ctrlList.InsertColumn( 4, _T("Data"), LVCFMT_LEFT, rc.Width() -
LIST_WIDTH_TIME -
LIST_WIDTH_TIMESTAMP -
LIST_WIDTH_FLAGS - LIST_WIDTH_ID );
m_ctrlList.ShowWindow( SW_SHOW );
m_ctrlList.SetExtendedStyle( LVS_REPORT | LVS_EX_FULLROWSELECT |
LVS_EX_ONECLICKACTIVATE |
LVS_EX_UNDERLINEHOT |
LVS_EX_GRIDLINES );
m_uTimerID = SetTimer( ID_MAIN_TIMER, 500, NULL );
return TRUE; // return TRUE unless you set the focus to a control
}
void CLoggerWndDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CLoggerWndDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CLoggerWndDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CLoggerWndDlg::OnTimer(UINT nIDEvent)
{
fillData();
CDialog::OnTimer(nIDEvent);
}
void CLoggerWndDlg::OnOK()
{
m_canalif.doCmdClose();
CDialog::OnOK();
}
void CLoggerWndDlg::OnClose()
{
m_canalif.doCmdClose();
CDialog::OnClose();
}
void CLoggerWndDlg::fillData( void )
{
int cnt;
canalMsg Msg;
if ( cnt = m_canalif.doCmdDataAvailable() ) {
for ( int i=0; i<cnt; i++ ) {
if ( m_canalif.doCmdReceive( &Msg ) ) {
insertItem( &Msg, m_idx++ );
}
}
}
}
void CLoggerWndDlg::insertItem( canalMsg *pMsg, int idx )
{
LVITEM lvi;
char buf[ 1024 ];
char smallbuf[ 32 ];
char tempbuf[ 32 ];
time_t ltime;
idx = 0;
/* Get UNIX-style time and display as number and string. */
time( <ime );
strcpy( tempbuf, ctime( <ime ) );
tempbuf[ strlen( tempbuf ) - 1 ] = 0; // Remove /n
m_ctrlList.InsertItem( idx, "" );
// Time
sprintf( buf, "%s", tempbuf );
lvi.mask = LVIF_TEXT;
lvi.iItem = idx;
lvi.iSubItem = 0;
lvi.lParam = 1;
lvi.pszText = buf;
m_ctrlList.SetItem( &lvi );
// Timestamp
sprintf( buf, "%08X", pMsg->timestamp );
lvi.iItem = idx;
lvi.iSubItem = 1;
lvi.pszText = buf;
m_ctrlList.SetItem( &lvi );
// Flags
sprintf( buf, "%08X", pMsg->flags );
lvi.iItem = idx;
lvi.iSubItem = 2;
lvi.pszText = buf;
m_ctrlList.SetItem( &lvi );
// Id
sprintf( buf, "%08X", pMsg->id );
lvi.iItem = idx;
lvi.iSubItem = 3;
lvi.pszText = buf;
m_ctrlList.SetItem( &lvi );
// Data
sprintf( buf, "(%i) - " , pMsg->sizeData );
for ( int i=0; i < 8; i++ ) {
if ( i < pMsg->sizeData ) {
sprintf( smallbuf, "%02X ", pMsg->data[ i ] );
strcat( buf, smallbuf );
}
}
lvi.iItem = idx;
lvi.iSubItem = 4;
lvi.pszText = buf;
m_ctrlList.SetItem( &lvi );
if ( m_ctrlList.GetItemCount( ) > MAX_LISTITEMS ) {
m_ctrlList.DeleteItem( MAX_LISTITEMS );
}
}
void CLoggerWndDlg::OnFilter()
{
CDlgFilter dlg;
if ( IDOK == dlg.DoModal() ) {
unsigned long filter = atol( dlg.m_szMask );
unsigned long mask = atol( dlg.m_szMask );
m_canalif.doCmdMask( mask );
m_canalif.doCmdFilter( filter );
}
}
| 22.55287 | 88 | 0.668185 | [
"model"
] |
5e1331a47a7ec5a208dd7f84cc96f0ea8252d7f8 | 11,072 | cc | C++ | tools/fulltopic_check/src/broken_points.cc | wahidHarb/rdp-1 | 73a0813d9a08f0aad34b56ba678167e6387b5e74 | [
"Apache-2.0"
] | 112 | 2018-12-05T07:45:42.000Z | 2022-01-24T11:28:11.000Z | tools/fulltopic_check/src/broken_points.cc | wahidHarb/rdp-1 | 73a0813d9a08f0aad34b56ba678167e6387b5e74 | [
"Apache-2.0"
] | 2 | 2020-02-29T02:34:59.000Z | 2020-05-12T06:34:29.000Z | tools/fulltopic_check/src/broken_points.cc | wahidHarb/rdp-1 | 73a0813d9a08f0aad34b56ba678167e6387b5e74 | [
"Apache-2.0"
] | 88 | 2018-12-16T07:35:10.000Z | 2022-03-09T17:41:16.000Z | //
//Copyright 2018 vip.com.
//
//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 "broken_points.h"
#include <vector>
#include <jansson.h>
using std::vector;
typedef vector<ErrOffsetSet *> ErrOffsetVector;
static ErrOffsetVector err_vec;
// 进入该函数的数据都是不通过连续性验证的
// 1.数据丢失
// 2.RDP切换:判断切换前后的事件是否连续,可校验通过则不为断点,否则为断点
// 3.binlog file切换同时RDP切换:情况比较复杂,直接报告为断点,人工看是否存在数据丢失
static ErrSetType IsErrSet(ErrOffsetSet *set) {
return ERR_NO_ERROR;
ErrOffset *before = &(set->before);
ErrOffset *after = &(set->after);
// Rotate 事件已经解析,所以不会出现由于binlog file切换导致的连续性校验错误的问题
static ErrOffsetSet *previous_set = NULL;
// 遇到RDP切换,但还没到正常Binlog数据
if (previous_set != NULL) {
// 如果再遇到一个断点,断点后为FORMAT_DESCRIPTION_EVENT事件且Epoch变大,则忽略,为RDP连续切换
if (before->trans && after->trans && before->epoch < after->epoch) {
const ::rdp::messages::Event &after_event = after->trans->events(0);
if (after_event.event_type() == FORMAT_DESCRIPTION_EVENT) {
// 需要保留previous_set,继续往下校验
set->set_type = ERR_NO_ERROR;
return ERR_NO_ERROR;
}
}
// 判断previous_set断点的before和当前断点set的after是否连续,连续不为断点,不连续,报告两个断点
before = &(previous_set->before);
after = &(set->after);
if (before->trans && after->trans &&
before->trans->next_position() == after->trans->position() &&
0 == before->trans->next_binlog_file_name().compare(after->trans->binlog_file_name())) {
// 通过连续性校验,两个都不为断点
previous_set->set_type = ERR_NO_ERROR;
set->set_type = ERR_NO_ERROR;
// 是否为断点已经确定,重置previous_set
previous_set = NULL;
return ERR_NO_ERROR;
} else {
// 不通过连续性校验,两个都为断点
previous_set->set_type = ERR_BROKEN_POINT;
set->set_type = ERR_BROKEN_POINT;
// 是否为断点已经确定,重置previous_set
previous_set = NULL;
return ERR_BROKEN_POINT;
}
} else {
// 如果Epoch变大,且断点后为FORMAT_DESCRIPTION_EVENT事件则为RDP切换
if (before->trans && after->trans && before->epoch < after->epoch) {
const ::rdp::messages::Event &after_event = after->trans->events(0);
if (after_event.event_type() == FORMAT_DESCRIPTION_EVENT) {
previous_set = set;
set->set_type = ERR_NOT_CONFIRM;
return ERR_NOT_CONFIRM;
}
}
return ERR_BROKEN_POINT;
}
}
static void ErrOffsetPrint(ErrOffset *err) {
RDP_LOG_INFO << "Offset:[" << err->begin_offset << ":" << err->end_offset << "]";
RDP_LOG_INFO << "GTID: " << err->trans->gtid() << ", Epoch: " << err->epoch
<< ", Transaction Seq No: " << err->trans->seq()
<< ", Binlog File Name: " << err->trans->binlog_file_name()
<< ", Position: " << err->trans->position()
<< ", Next Binlog File Name: " << err->trans->next_binlog_file_name()
<< ", Next Position: " << err->trans->next_position();
int event_list_size = err->trans->events_size();
RDP_LOG_INFO << "Event List Size: " << event_list_size;
for (int i = 0; i < event_list_size; ++i) {
const ::rdp::messages::Event &one_event = err->trans->events(i);
RDP_LOG_INFO << "Index: " << i << ", Event Type: " << one_event.event_type()
<< ", Binlog File Name: " << one_event.binlog_file_name()
<< ", Position: " << one_event.position()
<< ", Next Binlog Position: " << one_event.next_position();
}
}
static json_t *ErrOffsetToJson(ErrOffset *err) {
json_t *json = json_object();
char buffer[32] = {0x0};
size_t buffer_str_len = 0;
buffer_str_len = snprintf(buffer, sizeof(buffer) - 1, "%" PRIu64, err->begin_offset);
json_object_set_new(json, "begin_offset", json_stringn(buffer, buffer_str_len));
buffer_str_len = snprintf(buffer, sizeof(buffer) - 1, "%" PRIu64, err->end_offset);
json_object_set_new(json, "end_offset", json_stringn(buffer, buffer_str_len));
json_object_set_new(json, "GTID", json_string(err->trans->gtid().c_str()));
buffer_str_len = snprintf(buffer, sizeof(buffer) - 1, "%" PRIu64, err->epoch);
json_object_set_new(json, "epoch", json_stringn(buffer, buffer_str_len));
buffer_str_len = snprintf(buffer, sizeof(buffer) - 1, "%" PRId32, err->trans->seq());
json_object_set_new(json, "trans_seqno", json_stringn(buffer, buffer_str_len));
return json;
}
static void ErrOffsetSetPrint(ErrOffsetSet *set) {
ErrOffset *before = &(set->before);
ErrOffset *after = &(set->after);
switch (set->type) {
case EventErr:
RDP_LOG_INFO << "Event List Broken Offset:[" << before->begin_offset << ":"
<< before->end_offset << "]";
ErrOffsetPrint(before);
break;
case TransErr:
RDP_LOG_INFO << "Transaction Broken Offset:[" << before->end_offset << ":"
<< after->begin_offset << "]";
RDP_LOG_INFO << "Before Broken Point";
ErrOffsetPrint(before);
RDP_LOG_INFO << "After Broken Point";
ErrOffsetPrint(after);
break;
default:
assert(0);
}
}
static json_t *ErrOffsetSetToJson(ErrOffsetSet *set) {
json_t *json = NULL;
ErrOffset *before = &(set->before);
ErrOffset *after = &(set->after);
int rc = 0;
switch (set->type) {
case EventErr:
return ErrOffsetToJson(before);
case TransErr:
json = json_object();
if (0 != (rc = json_object_set_new(json, "pre", ErrOffsetToJson(before)))) {
RDP_LOG_ERROR << "Column json_array_append_new failed:" << rc;
goto err;
}
if (0 != (rc = json_object_set_new(json, "next", ErrOffsetToJson(after)))) {
RDP_LOG_ERROR << "Column json_array_append_new failed:" << rc;
goto err;
}
break;
default:
assert(0);
}
return json;
err:
if (json) {
json_decref(json);
json = NULL;
}
return NULL;
}
void ErrPrint() {
if (err_vec.size() == 0) {
RDP_LOG_INFO << "No Broken Position!";
return;
}
int broken_count = 0;
ErrSetType err_set_type;
for (ErrOffsetVector::iterator it = err_vec.begin(); it != err_vec.end(); ++it) {
switch ((*it)->type) {
case EventErr:
broken_count++;
ErrOffsetSetPrint(*it);
break;
case TransErr:
//if (ERR_BROKEN_POINT == (err_set_type = (*it)->set_type)) {
broken_count++;
RDP_LOG_INFO << "Broken Point Index: " << broken_count;
ErrOffsetSetPrint(*it);
//}
break;
default:
assert(0);
}
}
RDP_LOG_INFO << "Total Broken Point: " << broken_count;
// not delete err_vec, free err_vec memory in program exit
}
void AddErr(ErrType type, PackingMsg *before_msg, PackingMsg *after_msg) {
ErrOffsetSet *set = new ErrOffsetSet();
set->type = type;
switch (type) {
case EventErr:
// events连续性错误只需保存到before, after不需要
set->before.begin_offset = before_msg->begin_offset;
set->before.end_offset = before_msg->end_offset;
set->before.trans = before_msg->transaction;
set->before.epoch = before_msg->epoch;
set->type = type;
// before_msg->transaction had save in err_vec
before_msg->save_in_err_flag = true;
RDP_LOG_ERROR << "Find a broken point at offset: " << before_msg->begin_offset;
break;
case TransErr:
set->before.begin_offset = before_msg->begin_offset;
set->before.end_offset = before_msg->end_offset;
set->before.trans = before_msg->transaction;
set->before.epoch = before_msg->epoch;
set->after.begin_offset = after_msg->begin_offset;
set->after.end_offset = after_msg->end_offset;
set->after.trans = after_msg->transaction;
set->after.epoch = after_msg->epoch;
// before_msg->transaction had save in err_vec
before_msg->save_in_err_flag = true;
// after_msg->transaction had save in err_vec
after_msg->save_in_err_flag = true;
RDP_LOG_ERROR << "Find a broken point after offset: " << before_msg->begin_offset << ", and before offset: " << after_msg->begin_offset;
break;
default:
assert(0);
}
err_vec.push_back(set);
}
static bool ErrJsonArrayAdd(json_t *array, ErrType type, int *broken_count) {
json_t *erroffset_json = NULL;
int rc = 0;
// 确定是否为断点
//for (ErrOffsetVector::iterator it = err_vec.begin(); it != err_vec.end(); ++it) {
// IsErrSet(*it);
//}
// 断点输出
for (ErrOffsetVector::iterator it = err_vec.begin(); it != err_vec.end(); ++it) {
if ((*it)->type == type /*&& ERR_BROKEN_POINT == (*it)->set_type*/) {
(*broken_count)++;
if (NULL == (erroffset_json = ErrOffsetSetToJson(*it))) {
RDP_LOG_ERROR << "ErrOffset Set To Json Failt";
goto err;
}
if (0 != (rc = json_array_append_new(array, erroffset_json))) {
RDP_LOG_ERROR << "Column json_array_append_new failed:" << rc;
goto err;
}
erroffset_json = NULL;
}
}
return true;
err:
if (erroffset_json) {
json_decref(erroffset_json);
erroffset_json = NULL;
}
return false;
}
bool ErrToJson(const string file, int64_t start_offset, int64_t stop_offset) {
char offset_str[32] = {0x0};
size_t offset_str_len = 0;
int broken_count = 0;
int rc = 0;
json_t *json = json_object();
offset_str_len = snprintf(offset_str, sizeof(offset_str) - 1, "%" PRIu64, start_offset);
json_object_set_new(json, "start_offset", json_stringn(offset_str, offset_str_len));
offset_str_len = snprintf(offset_str, sizeof(offset_str) - 1, "%" PRIu64, stop_offset);
json_object_set_new(json, "stop_offset", json_stringn(offset_str, offset_str_len));
json_t *trans_array = json_array();
json_object_set_new(json, "trans_miss", trans_array);
json_t *event_array = json_array();
json_object_set_new(json, "event_miss", event_array);
if (err_vec.size() == 0) {
goto end;
}
if (!ErrJsonArrayAdd(trans_array, TransErr, &broken_count)) {
RDP_LOG_ERROR << "Add Trans Miss Array Failt";
goto err;
}
if (!ErrJsonArrayAdd(event_array, EventErr, &broken_count)) {
RDP_LOG_ERROR << "Add Event Miss Array Failt";
goto err;
}
end:
offset_str_len = snprintf(offset_str, sizeof(offset_str) - 1, "%d", broken_count);
json_object_set_new(json, "broken_count", json_stringn(offset_str, offset_str_len));
if (0 != (rc = json_dump_file(json, file.c_str(),
JSON_COMPACT | JSON_ESCAPE_SLASH | JSON_SORT_KEYS))) {
RDP_LOG_ERROR << "Dump Json To File: " << file << " Failt";
goto err;
}
if (json) {
json_decref(json);
json = NULL;
}
return true;
err:
if (json) {
json_decref(json);
json = NULL;
}
return false;
}
| 30.841226 | 142 | 0.644509 | [
"vector"
] |
5e2eadca64520b5d69137288ce0aa5fa84667be4 | 1,378 | cpp | C++ | src/primitives/zerocoin.cpp | gkc202011129/gkc2022 | bc4b414677b455ff1b024d405df9860f7b8c694d | [
"MIT"
] | null | null | null | src/primitives/zerocoin.cpp | gkc202011129/gkc2022 | bc4b414677b455ff1b024d405df9860f7b8c694d | [
"MIT"
] | null | null | null | src/primitives/zerocoin.cpp | gkc202011129/gkc2022 | bc4b414677b455ff1b024d405df9860f7b8c694d | [
"MIT"
] | 1 | 2022-03-15T23:03:32.000Z | 2022-03-15T23:03:32.000Z | // Copyright (c) 2017 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/zerocoin.h"
void CZerocoinSpendReceipt::AddSpend(const CZerocoinSpend& spend)
{
vSpends.emplace_back(spend);
}
std::vector<CZerocoinSpend> CZerocoinSpendReceipt::GetSpends()
{
return vSpends;
}
void CZerocoinSpendReceipt::SetStatus(std::string strStatus, int nStatus, int nNeededSpends)
{
strStatusMessage = strStatus;
this->nStatus = nStatus;
this->nNeededSpends = nNeededSpends;
}
std::string CZerocoinSpendReceipt::GetStatusMessage()
{
return strStatusMessage;
}
int CZerocoinSpendReceipt::GetStatus()
{
return nStatus;
}
int CZerocoinSpendReceipt::GetNeededSpends()
{
return nNeededSpends;
}
std::string CZerocoinMint::ToString() const
{
return ToUniValue().write();
}
UniValue CZerocoinMint::ToUniValue() const
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("denomination",(int)denomination));
result.push_back(Pair("nHeight",nHeight));
result.push_back(Pair("value",value.GetHex()));
result.push_back(Pair("randomness",randomness.GetHex()));
result.push_back(Pair("serialNumber",serialNumber.GetHex()));
result.push_back(Pair("txid",txid.GetHex()));
result.push_back(Pair("isUsed",isUsed));
return result;
}
| 24.175439 | 92 | 0.753266 | [
"vector"
] |
5e2ec0b74e4f8c6bb179d1c122482f799024e306 | 672 | cpp | C++ | 581.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 8 | 2018-10-31T11:00:19.000Z | 2020-07-31T05:25:06.000Z | 581.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | null | null | null | 581.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 2 | 2018-05-31T11:29:22.000Z | 2019-09-11T06:34:40.000Z | class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int ans=0;
int left=0,right=nums.size()-1;
while(left<nums.size()-1 && nums[left]<=nums[left+1]) left++;
while(right>0 && nums[right]>=nums[right-1]) right--;
if(left<right){
int mmin=INT_MAX,mmax=INT_MIN;
for(int i=left;i<=right;i++){
if(nums[i]>mmax) mmax=nums[i];
if(nums[i]<mmin) mmin=nums[i];
}
while(left>=0 && nums[left]>mmin) left--;
while(right<nums.size() && nums[right]<mmax) right++;
ans=right-left-1;
}
return ans;
}
};
| 32 | 69 | 0.5 | [
"vector"
] |
1e10a8e58ea9d4a3c36263d66757e40b7e370c8a | 3,034 | cpp | C++ | src/cpp/pyNodeWrapper.cpp | dulikvor/reactive | 993d0f91a5dbb4ea8dabc240605f46bf35b606e9 | [
"MIT"
] | null | null | null | src/cpp/pyNodeWrapper.cpp | dulikvor/reactive | 993d0f91a5dbb4ea8dabc240605f46bf35b606e9 | [
"MIT"
] | null | null | null | src/cpp/pyNodeWrapper.cpp | dulikvor/reactive | 993d0f91a5dbb4ea8dabc240605f46bf35b606e9 | [
"MIT"
] | 1 | 2020-07-28T00:00:00.000Z | 2020-07-28T00:00:00.000Z | #include "sweetPy/sweetPy.h"
#include "PyNode.h"
#include "InputAdapter.h"
#include "ConstNode.h"
#include "CurveNode.h"
namespace reactive{
static PyNode& PyNode_UpCast(UnitNode& node){return static_cast<PyNode&>(node);}
INIT_MODULE(_pyNode, "reactive pyNode")
{
module.add_function("pyNode_UpCast", "will upcast UnitNode& -> PyNode&", &PyNode_UpCast);
sweetPy::Clazz<PyNodeFactory> pyNodeFactory(module, "PyNodeFactory", "A py node unit factory.");
pyNodeFactory.add_static_method("create", "Creates PyNode instance", &PyNodeFactory::Create);
sweetPy::Clazz<PyNode> pyNode(module, "PyNode", "A representation for graph node");
pyNode.add_method("initWithConcurrent", "constructor extension for pyNode", static_cast<void(PyNode::*)(const std::string&, const PyFunctionSignature&, const PyNodeEdgesMetaData&)>(&PyNode::Init));
pyNode.add_method("init", "constructor extension for pyNode", static_cast<void(PyNode::*)(PyObject*, const PyFunctionSignature&, const PyNodeEdgesMetaData&)>(&PyNode::Init));
sweetPy::Clazz<UnitNode> unitNode(module, "UnitNode", "A basic representation for graph node");
unitNode.add_method("addConsumer", "will wire a consumer", &UnitNode::AddConsumer);
unitNode.add_method("getOutEdge", "will retrieve a abstract representation of a selected out edge", &UnitNode::GetOutEdge);
unitNode.add_static_method("produceOutEdgeData", "Will produce a new event by using a specific out edge", &UnitNode::ProduceOutEdgeData);
sweetPy::Clazz<PyFunctionSignature> pySignature(module, "PyFunctionSignature", "Function signature descriptor");
pySignature.add_method("addParam", "Add a new description for a specific param", &PyFunctionSignature::AddParameter);
sweetPy::Clazz<PyNodeEdgesMetaData> pyMeta(module, "PyNodeEdgesMetaData", "A PyFunction unit edges descriptor");
pyMeta.add_constructor<std::vector<int>>();
sweetPy::Enum parameterUpdate(module, "pySignature_ParameterUpdate");
parameterUpdate.add_value("Scalar", PyFunctionSignature::Scalar);
parameterUpdate.add_value("Edge", PyFunctionSignature::Edge);
sweetPy::Clazz<ConstNodeFactory> constNodeFactory(module, "ConstNodeFactory", "A ConstNode unit factory.");
constNodeFactory.add_static_method("create", "Creates ConstNode instance", &ConstNodeFactory::Create);
sweetPy::Clazz<CurveNodeFactory> curveNodeFactory(module, "CurveNodeFactory", "A CurveNode unit factory.");
curveNodeFactory.add_static_method("create", "Creates CurveNode instance", &CurveNodeFactory::Create);
sweetPy::Clazz<InputAdapter> inputAdapter(module, "InputAdapter", "A basic representation for a graph root");
inputAdapter.add_constructor<int>();
inputAdapter.add_method("addConsumer", "will wire a consumer", &InputAdapter::AddConsumer);
inputAdapter.add_static_method("generateId", "will generate a unique edge id", &InputAdapter::GenerateId);
}
}
| 61.918367 | 205 | 0.733685 | [
"vector"
] |
1e15db11206cb4827da3e1ee280697538cdb6a26 | 3,249 | cc | C++ | third_party/blink/renderer/bindings/tests/results/core/double_or_string.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/bindings/tests/results/core/double_or_string.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/bindings/tests/results/core/double_or_string.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/union_container.cpp.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/tests/results/core/double_or_string.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
namespace blink {
DoubleOrString::DoubleOrString() : type_(SpecificType::kNone) {}
double DoubleOrString::GetAsDouble() const {
DCHECK(IsDouble());
return double_;
}
void DoubleOrString::SetDouble(double value) {
DCHECK(IsNull());
double_ = value;
type_ = SpecificType::kDouble;
}
DoubleOrString DoubleOrString::FromDouble(double value) {
DoubleOrString container;
container.SetDouble(value);
return container;
}
const String& DoubleOrString::GetAsString() const {
DCHECK(IsString());
return string_;
}
void DoubleOrString::SetString(const String& value) {
DCHECK(IsNull());
string_ = value;
type_ = SpecificType::kString;
}
DoubleOrString DoubleOrString::FromString(const String& value) {
DoubleOrString container;
container.SetString(value);
return container;
}
DoubleOrString::DoubleOrString(const DoubleOrString&) = default;
DoubleOrString::~DoubleOrString() = default;
DoubleOrString& DoubleOrString::operator=(const DoubleOrString&) = default;
void DoubleOrString::Trace(blink::Visitor* visitor) {
}
void V8DoubleOrString::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, DoubleOrString& impl, UnionTypeConversionMode conversionMode, ExceptionState& exceptionState) {
if (v8Value.IsEmpty())
return;
if (conversionMode == UnionTypeConversionMode::kNullable && IsUndefinedOrNull(v8Value))
return;
if (v8Value->IsNumber()) {
double cppValue = NativeValueTraits<IDLDouble>::NativeValue(isolate, v8Value, exceptionState);
if (exceptionState.HadException())
return;
impl.SetDouble(cppValue);
return;
}
{
V8StringResource<> cppValue = v8Value;
if (!cppValue.Prepare(exceptionState))
return;
impl.SetString(cppValue);
return;
}
}
v8::Local<v8::Value> ToV8(const DoubleOrString& impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) {
switch (impl.type_) {
case DoubleOrString::SpecificType::kNone:
return v8::Null(isolate);
case DoubleOrString::SpecificType::kDouble:
return v8::Number::New(isolate, impl.GetAsDouble());
case DoubleOrString::SpecificType::kString:
return V8String(isolate, impl.GetAsString());
default:
NOTREACHED();
}
return v8::Local<v8::Value>();
}
DoubleOrString NativeValueTraits<DoubleOrString>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) {
DoubleOrString impl;
V8DoubleOrString::ToImpl(isolate, value, impl, UnionTypeConversionMode::kNotNullable, exceptionState);
return impl;
}
} // namespace blink
| 30.364486 | 177 | 0.746999 | [
"object"
] |
1e18313966f8b8effd4ff1d760133fb2d3b965db | 1,620 | cpp | C++ | Openalpr API/src/statedetection/state_detector.cpp | IOT-smart-car-park/project | 3701d5a92eb0a6a35af67e9e254a63425b663760 | [
"Apache-2.0"
] | 13 | 2017-02-22T02:20:06.000Z | 2018-06-06T04:18:03.000Z | Openalpr API/src/statedetection/state_detector.cpp | IOT-smart-car-park/project | 3701d5a92eb0a6a35af67e9e254a63425b663760 | [
"Apache-2.0"
] | null | null | null | Openalpr API/src/statedetection/state_detector.cpp | IOT-smart-car-park/project | 3701d5a92eb0a6a35af67e9e254a63425b663760 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "state_detector.h"
#include "state_detector_impl.h"
using namespace std;
namespace alpr {
StateDetector::StateDetector(const std::string country, const std::string configFile, const std::string runtimeDir) {
impl = new StateDetectorImpl(country, runtimeDir);
}
StateDetector::~StateDetector() {
delete impl;
}
bool StateDetector::isLoaded() {
return impl->isLoaded();
}
void StateDetector::setTopN(int topN) {
impl->setTopN(topN);
}
vector<StateCandidate> StateDetector::detect(vector<char> imageBytes) {
return impl->detect(imageBytes);
}
vector<StateCandidate> StateDetector::detect(unsigned char *pixelData, int bytesPerPixel, int imgWidth,
int imgHeight) {
return impl->detect(pixelData, bytesPerPixel, imgWidth, imgHeight);
}
}
| 30.566038 | 120 | 0.711111 | [
"vector"
] |
1e26ad04a150264aaa765b665ecda78fc44c1c50 | 7,165 | cc | C++ | lib/util/semver/parser.cc | poacpm/cpm | 1e004120990d952ec8f20cdc72e58b57fba9e333 | [
"Apache-2.0"
] | null | null | null | lib/util/semver/parser.cc | poacpm/cpm | 1e004120990d952ec8f20cdc72e58b57fba9e333 | [
"Apache-2.0"
] | null | null | null | lib/util/semver/parser.cc | poacpm/cpm | 1e004120990d952ec8f20cdc72e58b57fba9e333 | [
"Apache-2.0"
] | null | null | null | // internal
#include "poac/util/semver/parser.hpp"
namespace semver {
/// Skip whitespace if present.
void
Parser::skip_whitespace() {
if (peek().is_whitespace()) {
pop();
}
}
/// Parse an optional comma separator, then if that is present a predicate.
std::optional<Predicate>
Parser::comma_predicate() {
const bool has_comma = has_ws_separator(Token::Comma);
if (const auto predicate = this->predicate()) {
return predicate;
} else if (has_comma) {
return std::nullopt; // Err(EmptyPredicate)
} else {
return std::nullopt;
}
}
/// Parse an optional or separator `||`, then if that is present a range.
std::optional<VersionReq>
Parser::or_range() {
if (!this->has_ws_separator(Token::Or)) {
return std::nullopt;
}
return this->range();
}
/// Parse a single component.
///
/// Returns `None` if the component is a wildcard.
std::optional<std::uint_fast64_t>
Parser::component() {
if (const Token token = this->pop(); token.kind == Token::Numeric) {
return std::get<Token::numeric_type>(token.component);
} else if (token.is_wildcard()) {
return std::nullopt;
} else {
return std::nullopt; // Err(UnexpectedToken(tok))
}
}
/// Parse a single numeric.
std::optional<std::uint_fast64_t>
Parser::numeric() {
if (const Token token = this->pop(); token.kind == Token::Numeric) {
return std::get<Token::numeric_type>(token.component);
}
return std::nullopt;
}
/// Optionally parse a dot, then a component.
///
/// The second component of the tuple indicates if a wildcard has been
/// encountered, and is always `false` if the first component is `Some`.
///
/// If a dot is not encountered, `(None, false)` is returned.
///
/// If a wildcard is encountered, `(None, true)` is returned.
std::optional<std::uint_fast64_t>
Parser::dot_component() {
if (this->peek() != Token::Dot) {
return std::nullopt;
}
// pop the peeked dot.
this->pop();
return this->component();
}
/// Parse a dot, then a numeric.
std::optional<std::uint_fast64_t>
Parser::dot_numeric() {
if (pop() != Token::Dot) {
return std::nullopt;
}
return numeric();
}
/// Parse an string identifier.
///
/// Like, `foo`, or `bar`.
std::optional<Identifier>
Parser::identifier() {
const Token& token = pop();
if (token.kind == Token::AlphaNumeric) {
return Identifier(
Identifier::AlphaNumeric,
std::get<Token::alphanumeric_type>(token.component)
);
} else if (token.kind == Token::Numeric) {
return Identifier(
Identifier::Numeric, std::get<Token::numeric_type>(token.component)
);
}
return std::nullopt;
}
/// Parse all pre-release identifiers, separated by dots.
///
/// Like, `abcdef.1234`.
std::vector<Identifier>
Parser::pre() {
if (const Token p = peek(); p.kind == Token::Whitespace) {
pop(); // Drop whitespace
if (const Token p2 = peek();
p2 != Token::Unexpected && !p2.is_whitespace()) {
// `1.2.3 a.b.c`
throw version_error(
"continuing pre-release identifiers after spaces is not allowed"
);
}
return {};
} else if (p != Token::Hyphen) {
return {};
}
// pop the peeked hyphen.
pop();
return parts();
}
/// Parse a dot-separated set of identifiers.
std::vector<Identifier>
Parser::parts() {
std::vector<Identifier> parts{};
parts.push_back(identifier().value());
while (peek() == Token::Dot) {
// pop the peeked hyphen.
pop();
parts.push_back(identifier().value());
}
return parts;
}
/// Parse optional build metadata.
///
/// Like, `` (empty), or `+abcdef`.
std::vector<Identifier>
Parser::plus_build_metadata() {
if (peek() != Token::Plus) {
return {};
}
// pop the peeked plus.
pop();
return parts();
}
/// Optionally parse a single operator.
///
/// Like, `~`, or `^`.
Op
Parser::op() {
Op op(Op::Compatible);
switch (peek().kind) {
case Token::Eq:
op.kind = Op::Ex;
break;
case Token::Gt:
op.kind = Op::Gt;
break;
case Token::GtEq:
op.kind = Op::GtEq;
break;
case Token::Lt:
op.kind = Op::Lt;
break;
case Token::LtEq:
op.kind = Op::LtEq;
break;
case Token::Tilde:
op.kind = Op::Tilde;
break;
case Token::Caret:
op.kind = Op::Compatible;
break;
// default op
default:
op.kind = Op::Compatible;
break;
}
// remove the matched token.
pop();
skip_whitespace();
return op;
}
/// Parse a single predicate.
///
/// Like, `^1`, or `>=2.0.0`.
std::optional<Predicate>
Parser::predicate() {
if (is_eof()) {
return std::nullopt;
}
Op op = this->op();
std::uint_fast64_t major;
if (const auto m = this->component()) {
major = m.value();
} else {
return std::nullopt;
}
const auto minor = this->dot_component();
const auto patch = this->dot_component();
const auto pre = this->pre();
// TODO(ken-matsui): avoid illegal combinations, like `1.*.0`.
if (!minor.has_value()) {
op = Op(Op::Wildcard, WildcardVersion::Minor);
}
if (!patch.has_value()) {
op = Op(Op::Wildcard, WildcardVersion::Patch);
}
// ignore build metadata
this->plus_build_metadata();
return Predicate{op, major, minor, patch, pre};
}
/// Parse a single range.
///
/// Like, `^1.0` or `>=3.0.0, <4.0.0`.
VersionReq
Parser::range() {
std::vector<Predicate> predicates{};
if (const auto predicate = this->predicate()) {
predicates.push_back(predicate.value());
while (const auto next = this->comma_predicate()) {
predicates.push_back(next.value());
}
}
return VersionReq{predicates};
}
/// Parse a comparator.
///
/// Like, `1.0 || 2.0` or `^1 || >=3.0.0, <4.0.0`.
Comparator
Parser::comparator() {
std::vector<VersionReq> ranges{};
ranges.push_back(this->range());
while (const auto next = this->or_range()) {
ranges.push_back(next.value());
}
return Comparator{ranges};
}
/// Parse a version.
///
/// Like, `1.0.0` or `3.0.0-beta.1`.
Version
Parser::version() {
this->skip_whitespace();
const std::uint_fast64_t major = this->numeric().value();
const std::uint_fast64_t minor = this->dot_numeric().value();
const std::uint_fast64_t patch = this->dot_numeric().value();
const std::vector<Identifier> pre = this->pre();
const std::vector<Identifier> build = this->plus_build_metadata();
this->skip_whitespace();
return Version{major, minor, patch, pre, build};
}
/// Get the rest of the tokens in the parser.
///
/// Useful for debugging.
std::vector<Token>
Parser::tail() {
std::vector<Token> out{};
out.push_back(c1);
for (const Token token = lexer.next(); token != Token::Unexpected;) {
out.push_back(token);
}
return out;
}
bool
Parser::has_ws_separator(const Token::Kind& pat) {
skip_whitespace();
if (peek() == pat) {
// pop the separator.
pop();
// strip suffixing whitespace.
skip_whitespace();
return true;
}
return false;
}
Version
parse(std::string_view input) {
try {
Parser parser(input);
return parser.version();
} catch (const std::bad_optional_access& e) {
throw semver::version_error(e.what());
}
}
} // end namespace semver
| 22.390625 | 75 | 0.623447 | [
"vector"
] |
1e301915ded3de3a05621727f8ba77ff369c2832 | 10,547 | cpp | C++ | src/bin2llvmir/optimizations/phi2seq/phi2seq.cpp | Andrik-555/retdec | 1ac63a520da02912daf836b924f41d95b1b5fa10 | [
"MIT",
"BSD-3-Clause"
] | 521 | 2019-03-29T15:44:08.000Z | 2022-03-22T09:46:19.000Z | src/bin2llvmir/optimizations/phi2seq/phi2seq.cpp | Andrik-555/retdec | 1ac63a520da02912daf836b924f41d95b1b5fa10 | [
"MIT",
"BSD-3-Clause"
] | 30 | 2019-06-04T17:00:49.000Z | 2021-09-08T20:44:19.000Z | src/bin2llvmir/optimizations/phi2seq/phi2seq.cpp | Andrik-555/retdec | 1ac63a520da02912daf836b924f41d95b1b5fa10 | [
"MIT",
"BSD-3-Clause"
] | 99 | 2019-03-29T16:04:13.000Z | 2022-03-28T16:59:34.000Z | /**
* @file src/bin2llvmir/optimizations/phi2seq/phi2seq.cpp
* @brief Implementation of PHI2seq.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include <llvm/ADT/StringMap.h>
#include <llvm/IR/CFG.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Transforms/Scalar.h>
#include "retdec/bin2llvmir/optimizations/phi2seq/phi2seq.h"
using namespace llvm;
namespace retdec {
namespace bin2llvmir {
namespace {
/// Suffix of name for predecessor temp basic block.
const std::string SUFFIX_OF_PRE_BLOCK_NAME = ".phi2seq.pre";
/// Suffix of name for temp PHI node.
const std::string SUFFIX_OF_VAR_TMP_NAME = ".phi2seq.tmp";
} // anonymous namespace
const char* PHI2Seq::NAME = "phi2seq";
// It is the address of the variable that matters, not the value, so we can
// initialize the ID to anything.
char PHI2Seq::ID = 0;
RegisterPass<PHI2Seq> PHI2SeqRegistered(PHI2Seq::getName(),
"Phi2Seq optimization", false, false);
/**
* @brief Constructs a new optimizer.
*/
PHI2Seq::PHI2Seq(): FunctionPass(ID) {}
/**
* @brief Destructs the optimizer.
*/
PHI2Seq::~PHI2Seq() {}
void PHI2Seq::getAnalysisUsage(AnalysisUsage& au) const {
au.addRequiredID(InstructionNamerID);
}
bool PHI2Seq::runOnFunction(Function &func) {
// Iterate through basic blocks.
for (BasicBlock &bb : func) {
orderDependentPHINodesAndSolveCycles(bb);
}
return true;
}
/**
* @brief Orders PHI nodes in the given basic block according to their
* dependencies and solves cycles.
*
* @param[in, out] bb Basic block to order.
*/
void PHI2Seq::orderDependentPHINodesAndSolveCycles(BasicBlock &bb) {
initVarDependAnalysis(bb);
// Solving cycle variable dependency.
solveCycleVarDependency(bb, varDependAnalysis.detectCycleVarDependency());
// Solving non-cycle variable dependency.
orderDependentPHINodes(bb, varDependAnalysis.detectNonCycleVarDependency());
}
/**
* @brief Initializes variable dependency analysis.
*
* @param[in] bb Basic block to analyze.
*/
void PHI2Seq::initVarDependAnalysis(BasicBlock &bb) {
// Each basic block needs to have its own analysis.
varDependAnalysis.clear();
iteratePHINodesAndInitVarDependAnalysis(bb);
}
/**
* @brief Iterates through @a bb and initializes variable dependency analysis.
*
* @param[in] bb Basic block to analyze.
*/
void PHI2Seq::iteratePHINodesAndInitVarDependAnalysis(BasicBlock &bb) {
auto it = bb.begin();
while (PHINode *phiNode = dyn_cast<llvm::PHINode>(it)) {
iterateIncValuesAndInitVarDependAnalysis(*phiNode);
++it;
}
}
/**
* @brief Iterates through @a phiNode and adds incoming values to variable
* dependency analysis.
*
* @param[in] phiNode PHI node to iterate.
*/
void PHI2Seq::iterateIncValuesAndInitVarDependAnalysis(PHINode &phiNode) {
for (unsigned j = 0, k = phiNode.getNumIncomingValues(); j < k; ++j) {
Value *incValue(phiNode.getIncomingValue(j));
BasicBlock *incBB(phiNode.getIncomingBlock(j));
std::string lVarName(phiNode.getName());
std::string incVarName(incValue->getName());
if (!incVarName.empty() && lVarName != incVarName) {
// We support only variables with name.
//
// If incoming variable has same name with variable that is
// assigned we don't need to do something with this, because
// parallel processing is same like sequential.
// Creating edge in variable dependency analysis has some
// conditions.
// For example:
// %A = phi i32 [ %B, %bb1 ]
//
// We must create edge from B -> A.
varDependAnalysis.addEdge(incVarName, lVarName, *incBB, &phiNode);
}
}
}
/**
* @brief Solves cycle variable dependency in @a bb.
*
* @param[in, out] bb Basic block to solve.
* @param[in] cyclesDetectResult Result of variable dependency analysis.
*/
void PHI2Seq::solveCycleVarDependency(BasicBlock &bb, const VarDependAnalysis::
StringBBVecOfPHINodesMap &cyclesDetectResult) {
// Iterates through results of cycle variable dependency analysis.
for (auto &item : cyclesDetectResult) {
// Create pre basic block.
BasicBlock &preTmpBB(createPreBBAndSolveConnection(item.second, bb));
// Updates predecessors and values in cycled PHI nodes.
updateBBWithCycle(bb, *item.second.bb, preTmpBB);
}
}
/**
* @brief Creates predecessor temp basic block for basic block with cycle.
* Also solve connection with other basic blocks.
*
* @param[in] bbWithPHINodesVec Basic block with PHI nodes vector. For these PHI
* nodes are created temp PHI nodes.
* @param[in] currBB Basic block that contains cycle of PHI nodes.
*/
BasicBlock &PHI2Seq::createPreBBAndSolveConnection(const VarDependAnalysis::
BBVecOfPHINodes &bbWithPHINodesVec, BasicBlock &currBB) {
// Get name and create temp basic block.
std::string preTmpBBName(currBB.getName().str() + SUFFIX_OF_PRE_BLOCK_NAME);
BasicBlock *preTmpBB(BasicBlock::Create(currBB.getContext(), preTmpBBName,
currBB.getParent(), &currBB));
IRBuilder<> builder(preTmpBB);
// We create the following connection:
// Predecessor of BlockWithCycle -> temp block for blockWithCycle ->
// BlockWithCycle.
updateBBTermInstr(*bbWithPHINodesVec.bb, currBB, *preTmpBB);
// Create new temp PHI nodes in temp basic block.
createTmpPHINodes(builder, bbWithPHINodesVec);
// Create branch to basic block with cycle.
builder.CreateBr(&currBB);
return *preTmpBB;
}
/**
* @brief Updates successor in termination instruction in @a bbToUpdate from @a
* oldSucc to @a newSucc.
*
* @param[in, out] bbToUpdate Basic block to update.
* @param[in] oldSucc Old successor.
* @param[in] newSucc New successor.
*/
void PHI2Seq::updateBBTermInstr(BasicBlock &bbToUpdate, BasicBlock &oldSucc,
BasicBlock &newSucc) {
TerminatorInst *termInstr(bbToUpdate.getTerminator());
for (unsigned j = 0, k = termInstr->getNumSuccessors(); j < k; ++j) {
if (termInstr->getSuccessor(j)->getName() == oldSucc.getName()) {
termInstr->setSuccessor(j, &newSucc);
}
}
}
/**
* @brief Creates temp PHI nodes in new temp basic block.
*
* Also save new and old value that have to be replaced in basic block with cycle.
* This things are saved in @c vecOfPHINodesToSubs.
*
* @param[in] builder Builder for new temp basic block.
* @param[in] bbWithPHINodesVec Basic block with PHI nodes vector. For these PHI
* nodes are created temp PHI nodes.
*/
void PHI2Seq::createTmpPHINodes(IRBuilder<> &builder,
const VarDependAnalysis::BBVecOfPHINodes &bbWithPHINodesVec) {
// Iterates through PHI nodes to optimize and create temp PHI nodes.
for (PHINode *phiNode : bbWithPHINodesVec.phiNodeVec) {
// Get incoming value and create name for new temp PHI node.
Value *incValue(phiNode->getIncomingValueForBlock(bbWithPHINodesVec.bb));
std::string lvarName(incValue->getName().str() + SUFFIX_OF_VAR_TMP_NAME);
// Create new temp PHI node.
PHINode *createdPHINode(builder.CreatePHI(phiNode->getType(), 1,
lvarName));
createdPHINode->addIncoming(incValue, bbWithPHINodesVec.bb);
// Add information for later update PHI nodes in basic block with cycle.
phiNodeToSubsVec.push_back(PHINodeToSubs(phiNode, incValue,
createdPHINode->getValueName()->getValue()));
}
}
/**
* @brief Updates values and predecessors in PHI nodes in @a bb.
*
* Updates values. Example:
* @code
* %A = [ %B, %.bb ]
* to
* %A = [ %B.phi2seq.tmp, %.bb ]
* @endcode
*
* Updates predecessors in PHI nodes. Example:
* @code
* %A = [ %B.phi2seq.tmp, %.bb ]
* to
* %A = [ %B.phi2seq.tmp, %.bb.phi2seq.pre ]
* @endcode
*
* @param[in, out] bb Basic block with cycle.
* @param[in] oldBB Old predecessor block in PHI nodes.
* @param[in] newBB New predecessor block in PHI nodes.
*/
void PHI2Seq::updateBBWithCycle(BasicBlock &bbWithCycle, BasicBlock &oldBB,
BasicBlock &newBB) {
for (PHINodeToSubs &phiNodeToSubs : phiNodeToSubsVec) {
PHINode *phiNodeToUpdate(phiNodeToSubs.phiNodeToSubs);
// Update value in PHI node.
replaceValueForPHINode(*phiNodeToUpdate, *phiNodeToSubs.oldValue,
*phiNodeToSubs.newValue, oldBB);
// Create in analysis new edge for updated PHI node.
varDependAnalysis.addEdge(phiNodeToSubs.newValue->getName(),
phiNodeToUpdate->getName(), newBB, phiNodeToUpdate);
}
// Update predecessors in PHI nodes. We updates only one predecessor basic
// block in phi nodes, so need to run at the end.
updatePredecessorsInPHINodes(bbWithCycle, oldBB, newBB);
// Need to clear after updates.
phiNodeToSubsVec.clear();
}
/**
* @brief Updates @a oldValue in @a phiNodeToUpdate with @a newValue.
*
* @param[in] phiNodeToUpdate For this PHI node is value updated.
* @param[in] oldValue Old value that will be updated.
* @param[in] newValue To this value will be updated old value.
* @param[in] pred We are replacing value for this predecessor.
*/
void PHI2Seq::replaceValueForPHINode(PHINode &phiNodeToUpdate, Value &oldValue,
Value &newValue, BasicBlock &pred) {
for (unsigned i = 0, e = phiNodeToUpdate.getNumOperands(); i < e; ++i) {
if (phiNodeToUpdate.getOperand(i) == &oldValue &&
phiNodeToUpdate.getIncomingBlock(i) == &pred) {
// Example:
// oldValue = %var1, newValue = %var.phi2seq.tmp,
// pred = %bb1.
// phiNodeToUpdate = phi i8* [ %var1, %bb1 ], [ %var1, %bb2 ].
// We want to update only %var1 for basic block %bb1.
phiNodeToUpdate.setOperand(i, &newValue);
}
}
}
/**
* @brief Update predecessors in PHI nodes in @a bb. @a oldBB is updated to
* @a newBB.
*
* @param[in, out] bb Basic block with PHI nodes to update.
* @param[in] oldBB Old predecessor basic block in PHI node.
* @param[in] newBB New predecessor basic block in PHI node.
*/
void PHI2Seq::updatePredecessorsInPHINodes(BasicBlock &bb, BasicBlock &oldBB,
BasicBlock &newBB) {
auto it = bb.begin();
while (PHINode *phiNodeToUpdate = dyn_cast<PHINode>(it)) {
int ixB(phiNodeToUpdate->getBasicBlockIndex(&oldBB));
assert(ixB != -1 && "Trying to update predecessor that doesn't exist");
phiNodeToUpdate->setIncomingBlock(ixB, &newBB);
++it;
}
}
/**
* @brief Orders PHI nodes to correct sequential order.
*
* @param[in, out] bb Basic block to update.
* @param[in] nonCyclesDependResult Result of variable dependency analysis.
*/
void PHI2Seq::orderDependentPHINodes(BasicBlock &bb, const VarDependAnalysis::
PHINodeVec &nonCyclesDependResult) {
auto &instrList(bb.getInstList());
// Ordering PHI nodes. Uses results of analysis.
for (auto ri = nonCyclesDependResult.rbegin(),
re = nonCyclesDependResult.rend(); ri != re; ++ri) {
(*ri)->removeFromParent();
instrList.push_front(*ri);
}
}
} // namespace bin2llvmir
} // namespace retdec
| 31.672673 | 81 | 0.727126 | [
"vector"
] |
1e342608dca77d0efe05c48af22abc54ac2d5228 | 6,787 | hpp | C++ | StarcraftBuildOrderSearch/Source/starcraftsearch/StarcraftAction.hpp | abeshry/StarcraftAI | 2eca612783d1b4c06469885ebc3cce46cc0c6fce | [
"Apache-2.0"
] | null | null | null | StarcraftBuildOrderSearch/Source/starcraftsearch/StarcraftAction.hpp | abeshry/StarcraftAI | 2eca612783d1b4c06469885ebc3cce46cc0c6fce | [
"Apache-2.0"
] | null | null | null | StarcraftBuildOrderSearch/Source/starcraftsearch/StarcraftAction.hpp | abeshry/StarcraftAI | 2eca612783d1b4c06469885ebc3cce46cc0c6fce | [
"Apache-2.0"
] | null | null | null | #ifndef STARCRAFT_ACTION_H
#define STARCRAFT_ACTION_H
///////////////////////////////////////////////////////////////////////////////
//
// StarcraftAction
//
// StarcraftActions are to ONLY be constructed by StarcraftData
//
// The int id passed in is its location within the ActionMap vector
//
// If you wish to get a StarcraftAction, use ActionMap::getStarcraftAction()
//
///////////////////////////////////////////////////////////////////////////////
#include "BWAPI.h"
#include "ActionSet.hpp"
#include <assert.h>
#include <sstream>
#include "Common.h"
namespace BuildOrderSearch
{
class StarcraftAction {
public:
// types of actions
enum ActionType {UnitType, UpgradeType, TechType, Error};
private:
ActionType type; // the enum type of action this is
BWAPI::Race race; // the race of this action
BWAPI::UnitType unit; // holds UnitType, if it's a unit
BWAPI::UpgradeType upgrade; // holds UpgradeType, if it's an upgrade
BWAPI::TechType tech; // holds TechType, if it's a tech
Action actionID; // unique identifier to this action
ResourceCountType mineralPriceVal; // mineral price of the action
ResourceCountType gasPriceVal; // gas price of the action
SupplyCountType supplyRequiredVal; // supply price of the action
SupplyCountType supplyProvidedVal; // supply created by the action
FrameCountType buildTimeVal; // build time of the action
UnitCountType repeat; // how many times to repeat this action (meta action)
UnitCountType numberProduced; // the number of units produced
std::string name; // name of the action
std::string metaName; // meta name of this action, adds 'repeat' to the string
ActionSet pre; // prerequisites of the action
bool building, // is this a building
worker, // is this a worker
refinery, // is this a refinery
resourceDepot, // is this a resource depot
supplyProvider, // is this a supply provider
canProduceBool,
canAttackBool,
whatBuildsIsBuildingBool, // is what builds this action a building?
whatBuildsIsLarvaBool;
BWAPI::UnitType whatBuildsUnitType; // the unit type that builds this
Action whatBuildsActionUnit; // the action that builds this
public:
// default constructor, should never be called
StarcraftAction() : type(Error) { assert(false); }
// UnitType constructor
StarcraftAction(BWAPI::UnitType t, int id)
: type(UnitType)
, unit(t)
, actionID((Action)id)
, mineralPriceVal(t.mineralPrice())
, gasPriceVal(t.gasPrice())
, supplyRequiredVal(t.supplyRequired())
, supplyProvidedVal(t.supplyProvided())
, buildTimeVal(t.buildTime())
, repeat(1)
, numberProduced(1)
, name(t.getName())
, metaName(t.getName())
, building(t.isBuilding())
, worker(t.isWorker())
, refinery(t.isRefinery())
, resourceDepot(t.isResourceDepot())
, supplyProvider(t.supplyProvided() > 0 && !t.isResourceDepot())
, canProduceBool(t.isBuilding() && t.canProduce())
, canAttackBool(t.canAttack())
, whatBuildsUnitType(t.whatBuilds().first)
{
if (t == BWAPI::UnitTypes::Zerg_Zergling || t == BWAPI::UnitTypes::Zerg_Scourge)
{
numberProduced = 2;
}
std::stringstream ss("");
ss << repeat << " " << name;
metaName = ss.str();
}
// UpgradeType action
StarcraftAction(BWAPI::UpgradeType t, int id)
: type(UpgradeType)
, upgrade(t)
, actionID((Action)id)
, mineralPriceVal(t.mineralPrice())
, gasPriceVal(t.gasPrice())
, supplyRequiredVal(0)
, supplyProvidedVal(0)
, buildTimeVal(t.upgradeTime())
, repeat(1)
, numberProduced(1)
, name(t.getName())
, metaName(t.getName())
, building(false)
, worker(false)
, refinery(false)
, resourceDepot(false)
, supplyProvider(false)
, canProduceBool(false)
, canAttackBool(false)
, whatBuildsUnitType(t.whatUpgrades())
{}
// TechType action
StarcraftAction(BWAPI::TechType t, int id)
: type(TechType)
, tech(t)
, actionID((Action)id)
, mineralPriceVal(t.mineralPrice())
, gasPriceVal(t.gasPrice())
, supplyRequiredVal(0)
, supplyProvidedVal(0)
, buildTimeVal(t.researchTime())
, repeat(1)
, numberProduced(1)
, name(t.getName())
, metaName(t.getName())
, building(false)
, worker(false)
, refinery(false)
, resourceDepot(false)
, supplyProvider(false)
, canProduceBool(false)
, canAttackBool(false)
, whatBuildsUnitType(t.whatResearches())
{}
BWAPI::UnitType getUnitType() const { return unit; }
BWAPI::UnitType whatBuilds() const { return whatBuildsUnitType; }
BWAPI::UpgradeType getUpgradeType() const { return upgrade; }
BWAPI::TechType getTechType() const { return tech; }
Action whatBuildsAction() const { return whatBuildsActionUnit; }
ActionSet getPrerequisites() const { return pre; }
ActionType getType() const { return type; }
std::string getName() const { return name; }
std::string getMetaName() const { return metaName; }
FrameCountType buildTime() const { return buildTimeVal; }
ResourceCountType mineralPrice() const { return mineralPriceVal; }
ResourceCountType mineralPriceScaled() const { return mineralPriceVal * 100; }
ResourceCountType gasPrice() const { return gasPriceVal; }
ResourceCountType gasPriceScaled() const { return gasPriceVal * 100; }
SupplyCountType supplyRequired() const { return supplyRequiredVal; }
SupplyCountType supplyProvided() const { return supplyProvidedVal; }
UnitCountType numProduced() const { return numberProduced; }
UnitCountType repetitions() const { return repeat; }
bool isRefinery() const { return refinery; }
bool isWorker() const { return worker; }
bool isBuilding() const { return building; }
bool isResourceDepot() const { return resourceDepot; }
bool isSupplyProvider() const { return supplyProvider; }
bool isUnit() const { return type == UnitType; }
bool isTech() const { return type == TechType; }
bool isUpgrade() const { return type == UpgradeType; }
bool whatBuildsIsBuilding() const { return whatBuildsIsBuildingBool; }
bool whatBuildsIsLarva() const { return whatBuildsIsLarvaBool; }
bool canProduce() const { return canProduceBool; }
bool canAttack() const { return canAttackBool; }
void setPrerequisites(const ActionSet a) { pre = a; }
void setRepetitions(const UnitCountType r) { repeat = r; }
bool operator == (const StarcraftAction & a) const { return actionID == a.actionID; }
bool operator < (const StarcraftAction & a) const { return actionID < a.actionID; }
void setWhatBuildsAction(const Action a, const bool wbib, const bool wbil)
{
whatBuildsActionUnit = a;
whatBuildsIsBuildingBool = wbib;
whatBuildsIsLarvaBool = wbil;
}
};
}
#endif
| 33.107317 | 86 | 0.681745 | [
"vector"
] |
1e35d936e9de091994f5d7d73bdbe070676dc515 | 860 | cpp | C++ | graph/bellmanford.cpp | anu9901998/competitive-programming | 2a3325bc42d027197449d85c519a74d104a5461c | [
"MIT"
] | 6 | 2020-04-08T00:25:44.000Z | 2021-09-04T20:39:15.000Z | graph/bellmanford.cpp | anu9901998/competitive-programming | 2a3325bc42d027197449d85c519a74d104a5461c | [
"MIT"
] | 2 | 2020-04-09T06:59:12.000Z | 2020-04-09T14:56:32.000Z | graph/bellmanford.cpp | anu9901998/competitive-programming | 2a3325bc42d027197449d85c519a74d104a5461c | [
"MIT"
] | 6 | 2020-04-16T03:47:06.000Z | 2021-09-07T10:21:32.000Z | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<tuple<int, int, int>>edges;
// max can find positive cycle
// min can find negative cycle
void bellmanford(vector<int>&d){
for(int i = 1;i <= n-1;i++){
for(auto &e:edges){
int a, b, w;
tie(a, b, w) = e;
d[b] = max(d[b], d[a]+w);
}
}
}
int main(){
cin>>n>>m;
for(int i = 0;i < m;i++){
int a, b, w;cin>>a>>b>>w;
edges.push_back({a, b, w});
}
vector<int>d1(n+11, -1e9);
d1[1] = 0;
bellmanford(d1);
vector<int>d2 = d1;
bellmanford(d2);
for(int i = 1;i <= n;i++){
if (d2[i] > d1[i]){
cout << "the node " << i << " is part of a positive cycle" << endl;
}
}
/* input
3 3
1 2 1
2 3 1
3 1 100
*/
return 0;
}
| 17.2 | 79 | 0.437209 | [
"vector"
] |
1e442152441b012689bf8e19676bbfc86f1e0d7f | 882 | cpp | C++ | src/caffe/layers/warp_layer.cpp | liruoteng/Caffe | 9fb981df47b5f6e79b544813c38b10daa813d2d0 | [
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/warp_layer.cpp | liruoteng/Caffe | 9fb981df47b5f6e79b544813c38b10daa813d2d0 | [
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/warp_layer.cpp | liruoteng/Caffe | 9fb981df47b5f6e79b544813c38b10daa813d2d0 | [
"BSD-2-Clause"
] | null | null | null | #include <vector>
#include "caffe/layers/warp_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void WarpLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top)
{
}
template <typename Dtype>
void WarpLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top)
{}
template <typename Dtype>
void WarpLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top)
{}
template <typename Dtype>
void WarpLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top)
{}
template <typename Dtype>
void WarpLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top)
{}
//INSTANTIATE_CLASS(WarpLayer);
//REGISTER_LAYER_CLASS(Warp);
} // namespace caffe
| 22.05 | 104 | 0.738095 | [
"vector"
] |
1e469c530de7f5abc674a0ddcdb4bf309a4a59d8 | 3,109 | cpp | C++ | tests/hierarchical/hierarchical_private_memory.cpp | jbrodman/SYCL-CTS | 9cbe1a719b25c269ef78a2ee08f2e5ed12a1cc6d | [
"Apache-2.0"
] | null | null | null | tests/hierarchical/hierarchical_private_memory.cpp | jbrodman/SYCL-CTS | 9cbe1a719b25c269ef78a2ee08f2e5ed12a1cc6d | [
"Apache-2.0"
] | null | null | null | tests/hierarchical/hierarchical_private_memory.cpp | jbrodman/SYCL-CTS | 9cbe1a719b25c269ef78a2ee08f2e5ed12a1cc6d | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
//
// SYCL 1.2.1 Conformance Test Suite
//
// Copyright: (c) 2018 by Codeplay Software LTD. All Rights Reserved.
//
*******************************************************************************/
#include "../common/common.h"
#define TEST_NAME hierarchical_private_memory
namespace TEST_NAMESPACE {
using namespace sycl_cts;
/** test cl::sycl::range::get(int index) return size_t
*/
class TEST_NAME : public util::test_base {
public:
/** return information about this test
*/
void get_info(test_base::info &out) const override {
set_test_info(out, TOSTRING(TEST_NAME), TEST_FILE);
}
/** execute the test
*/
void run(util::logger &log) override {
try {
constexpr unsigned globalRange1d = 6;
constexpr unsigned globalRange2d = 2;
constexpr unsigned local = globalRange2d;
std::vector<size_t> data(globalRange1d * globalRange2d);
auto myQueue = util::get_cts_object::queue();
// using this scope we ensure that the buffer will update the host values
// after the wait_and_throw
{
cl::sycl::buffer<size_t, 1> buf(
data.data(), cl::sycl::range<1>(globalRange1d * globalRange2d));
myQueue.submit([&](cl::sycl::handler &cgh) {
auto accessor =
buf.template get_access<cl::sycl::access::mode::read_write>(cgh);
cl::sycl::range<2> globalRange(globalRange1d, globalRange2d);
cl::sycl::range<2> localRange(local, local);
auto groupRange = globalRange / localRange;
cgh.parallel_for_work_group<class hierarchical_private_memory>(
groupRange, localRange, [=](cl::sycl::group<2> group_pid) {
cl::sycl::private_memory<size_t, 2> priv(group_pid);
group_pid.parallel_for_work_item(
[&](cl::sycl::h_item<2> itemID) {
priv(itemID) = itemID.get_global().get_linear_id();
});
group_pid.parallel_for_work_item([&](
cl::sycl::h_item<2> itemID) {
accessor[itemID.get_global().get_linear_id()] = priv(itemID);
});
});
});
myQueue.wait_and_throw();
}
for (size_t i = 0; i < data.size(); i++) {
if (data[i] != i) {
cl::sycl::string_class errorMessage =
cl::sycl::string_class("Value for global id ") +
std::to_string(i) + cl::sycl::string_class(" was not correct (") +
std::to_string(data[i]) + cl::sycl::string_class(" instead of ") +
std::to_string(i) + ")";
FAIL(log, errorMessage);
}
}
} catch (const cl::sycl::exception &e) {
log_exception(log, e);
cl::sycl::string_class errorMsg =
"a SYCL exception was caught: " + cl::sycl::string_class(e.what());
FAIL(log, errorMsg.c_str());
}
}
};
// construction of this proxy will register the above test
util::test_proxy<TEST_NAME> proxy;
} // namespace TEST_NAMESPACE
| 34.164835 | 80 | 0.560952 | [
"vector"
] |
1e4c8410765fd68b60c9f21afa2dd61b1d71a64f | 14,554 | cpp | C++ | cowsay.cpp | quantum5/cowsay | 8ef8598087d7e4cde2608beb7ebafdddc2f15c97 | [
"MIT"
] | 4 | 2016-03-11T12:50:43.000Z | 2021-09-07T09:00:52.000Z | cowsay.cpp | quantum5/cowsay | 8ef8598087d7e4cde2608beb7ebafdddc2f15c97 | [
"MIT"
] | null | null | null | cowsay.cpp | quantum5/cowsay | 8ef8598087d7e4cde2608beb7ebafdddc2f15c97 | [
"MIT"
] | 3 | 2016-12-05T03:43:30.000Z | 2021-07-31T01:13:02.000Z | #include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <functional>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include "OptionParser.h"
#ifdef WIN32
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# include <shlwapi.h>
#else
# include <unistd.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <pwd.h>
#endif
#ifdef __GNUC__
# define GCC_VERSION (__GNUC__ * 10000 \
+ __GNUC_MINOR__ * 100 \
+ __GNUC_PATCHLEVEL__)
#endif
#if (defined(_MSC_VER) && _MSC_VER >= 1600) || \
(defined(GCC_VERSION) && GCC_VERSION >= 40900)
# include <regex>
#else
# include <boost/regex.hpp>
namespace std {
using boost::regex;
using boost::regex_replace;
using boost::regex_search;
using boost::smatch;
}
#endif
bool get_executable_directory(std::string &buffer) {
#ifdef WIN32
char name[MAX_PATH];
if (!GetModuleFileName(NULL, name, MAX_PATH))
return false;
PathRemoveFileSpec(name);
buffer = name;
return true;
#else
char path[512];
int ch = readlink("/proc/self/exe", path, 512);
if (ch != -1) {
path[ch] = 0;
buffer = path;
buffer = buffer.substr(0, buffer.find_last_of("/"));
}
return ch != -1;
#endif
}
void replace(std::string &string, const std::string &find, const std::string &replace) {
size_t index = 0;
while (true) {
index = string.find(find, index);
if (index == std::string::npos)
break;
string.replace(index, find.length(), replace);
index += replace.length();
}
}
std::string get_home_directory() {
static std::string home;
if (!home.empty())
return home;
char *env = getenv("HOME");
if (env)
return home = env;
#ifdef WIN32
env = getenv("USERPROFILE");
if (env)
return home = env;
home = getenv("HOMEDRIVE");
home += getenv("HOMEPATH");
return home;
#else
struct passwd *pw = getpwuid(getuid());
return home = pw->pw_dir;
#endif
}
std::string expanduser(const std::string &path) {
std::string copy(path);
replace(copy, "~", get_home_directory());
return copy;
}
void add_cow_path_if_exists(std::vector<std::string> &cowpath, const std::string &path) {
#ifdef WIN32
if (PathIsDirectory(path.c_str()))
cowpath.push_back(path);
#else
struct stat buf;
if (stat(path.c_str(), &buf) == 0 && S_ISDIR(buf.st_mode))
cowpath.push_back(path);
#endif
}
void add_default_cowpath(std::vector<std::string> &cowpath) {
std::string path;
if (!get_executable_directory(path))
return;
add_cow_path_if_exists(cowpath, expanduser("~/.cows"));
add_cow_path_if_exists(cowpath, expanduser("~/cows"));
add_cow_path_if_exists(cowpath, path + "/../share/cows");
add_cow_path_if_exists(cowpath, path + "/../share/cows");
add_cow_path_if_exists(cowpath, "/usr/share/cows");
add_cow_path_if_exists(cowpath, "/usr/local/share/cows");
add_cow_path_if_exists(cowpath, path + "/cows");
}
bool file_exist(const std::string &file) {
#ifdef WIN32
return PathFileExists(file.c_str());
#else
struct stat buf;
return stat(file.c_str(), &buf) == 0 && S_ISREG(buf.st_mode);
#endif
}
bool endswith(std::string const &string, std::string const &ending) {
if (string.length() >= ending.length()) {
return !string.compare(string.length() - ending.length(), ending.length(), ending);
} else {
return false;
}
}
bool startswith(std::string const &string, std::string const &ending) {
if (string.length() >= ending.length()) {
return !string.compare(0, ending.length(), ending);
} else {
return false;
}
}
std::string findcow(const std::vector<std::string> &cowpath, const std::string &cow) {
if (file_exist(cow))
return cow;
for (auto i = cowpath.cbegin(); i < cowpath.cend(); ++i) {
std::string check = *i + "/" + cow;
if (file_exist(check))
return check;
}
if (endswith(cow, ".cow"))
throw std::string("Cow exists not: ") + cow;
return findcow(cowpath, cow + ".cow");
}
static inline void ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
}
static inline std::string <rim(std::string &&s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
static inline void rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
}
static inline std::string &rtrim(std::string &&s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
static inline void trim(std::string &s) {
ltrim(s);
rtrim(s);
}
static inline std::string &trim(std::string &&s) {
rtrim(s);
ltrim(s);
return s;
}
int isnewline(int ch) {
switch (ch) {
case '\r':
case '\n':
case '\f':
return 1;
}
return 0;
}
std::string loadcow(const std::string &file, const std::string &thoughts,
const std::string &eyes, const std::string &tongue) {
if (!file_exist(file))
throw std::string("Can't find cow: ") + file;
std::string cow, buf;
try {
std::ifstream cowfile(file);
if (!cowfile)
throw std::string("Can't open cow: ") + file;
cowfile.exceptions(std::ifstream::badbit);
while (std::getline(cowfile, buf))
if (!startswith(ltrim(std::string(buf)), "#"))
cow += buf + '\n';
cowfile.close();
} catch (std::ifstream::failure e) {
throw std::string("Can't open cow: ") + e.what();
}
if (cow.find("$the_cow") != std::string::npos) {
// Perl format, 'tis because of thee that I need regex
std::regex cowstart("\\$the_cow\\s*=\\s*<<[\"']?(\\w+)[\"']?;?");
std::smatch match;
if (!regex_search(cow, match, cowstart))
throw std::string("Can't find a perl cow declaration");
int start = match.position() + match.length(), end;
std::string heredoc = match.str(1);
const std::regex esc("[\\^\\.\\$\\|\\(\\)\\[\\]\\*\\+\\?\\/\\\\]");
const std::string escaped("\\\\\\1");
std::regex cowend("[\r\n]*" + std::regex_replace(heredoc, esc, escaped) + "[\r\n]+");
if (regex_search(cow, match, cowend))
end = match.position();
else
end = cow.length();
cow = cow.substr(start, end - start);
cow = std::regex_replace(cow, std::regex("\\$\\{?thoughts(?:\\}|\\b)"), thoughts);
cow = std::regex_replace(cow, std::regex("\\$\\{?eyes(?:\\}|\\b)"), eyes);
cow = std::regex_replace(cow, std::regex("\\$\\{?tongue(?:\\}|\\b)"), tongue);
replace(cow, "\\\\", "\\");
replace(cow, "\\@", "@");
cow.erase(cow.begin(), std::find_if(cow.begin(), cow.end(), std::not1(std::ptr_fun<int, int>(isnewline))));
if (!cow.empty() && !isnewline(cow.length() - 1))
cow.push_back('\n');
} else {
// Now, my own cow format, just basic formatting
rtrim(cow);
replace(cow, "{thoughts}", thoughts);
replace(cow, "{eyes}", eyes);
replace(cow, "{tongue}", tongue);
}
return cow;
}
void write_ballon(FILE *out, const std::vector<std::string> &lines, int width, bool think=false) {
std::stringstream formatter;
formatter << "%c %-" << width << "s %c\n";
width += 2;
std::string format = formatter.str();
fprintf(out, " %s \n", std::string(width, '_').c_str());
if (think) {
for (auto line = lines.cbegin(); line < lines.cend(); ++line)
fprintf(out, format.c_str(), '(', line->c_str(), ')');
} else if (lines.size() < 2) {
fprintf(out, format.c_str(), '<', lines.size() ? lines[0].c_str() : "", '>');
} else {
auto line = lines.cbegin();
auto end = lines.cend();
--end;
fprintf(out, format.c_str(), '/', (line++)->c_str(), '\\');
for (; line < end; ++line)
fprintf(out, format.c_str(), '|', line->c_str(), '|');
fprintf(out, format.c_str(), '\\', line->c_str(), '/');
}
fprintf(out, " %s \n", std::string(width, '-').c_str());
}
int wrap(const std::string& input, std::vector<std::string>& result, size_t width) {
std::string line;
size_t index = 0, maxwidth = 0;
while (index < input.length()) {
int i = input.find_first_of(" \t\n", index);
if (i == std::string::npos)
i = input.length() - 1;
if (line.length() + i - index > width) {
rtrim(line);
result.push_back(line);
if (line.length() > maxwidth)
maxwidth = line.length();
line.clear();
}
line += input.substr(index, i - index) + " ";
if (input[i] == '\n') {
rtrim(line);
if (line.length() > maxwidth)
maxwidth = line.length();
result.push_back(line);
if (line.length() > maxwidth)
maxwidth = line.length();
line.clear();
}
index = i + 1;
}
if (!line.empty()) {
rtrim(line);
result.push_back(line);
if (line.length() > maxwidth)
maxwidth = line.length();
}
return maxwidth;
}
void open_streams(std::string &data, const std::vector<std::string> &files) {
if (!files.size()) {
std::stringstream stream;
stream << std::cin.rdbuf();
data = stream.str();
return;
}
data = "";
for (auto file = files.cbegin(); file < files.cend(); ++file) {
if (*file == "-") {
std::stringstream stream;
stream << std::cin.rdbuf();
data += stream.str();
continue;
}
std::ifstream stream;
stream.exceptions(std::ifstream::badbit);
try {
stream.open(*file);
std::stringstream string;
string << stream.rdbuf();
data += string.str();
} catch (std::ifstream::failure e) {
std::cerr << "Can't open file: " << *file << ": " << e.what() << std::endl;
}
}
}
int main(int argc, char *argv[]) {
optparse::OptionParser parser = optparse::OptionParser()
.description("C++ reimplementation of the classic cowsay.");
parser.set_defaults("eyes", "oo");
parser.set_defaults("tongue", "");
parser.set_defaults("thoughts", std::strstr(argv[0], "think") ? "o" : "\\");
parser.add_option("-b", "--borg"). action("store_const").dest("eyes").set_const("==");
parser.add_option("-d", "--dead"). action("store_const").dest("eyes").set_const("xx");
parser.add_option("-g", "--greedy"). action("store_const").dest("eyes").set_const("$$");
parser.add_option("-p", "--paranoid").action("store_const").dest("eyes").set_const("@@");
parser.add_option("-s", "--stoned"). action("store_const").dest("eyes").set_const("**");
parser.add_option("-t", "--tired"). action("store_const").dest("eyes").set_const("--");
parser.add_option("-w", "--wired"). action("store_const").dest("eyes").set_const("OO");
parser.add_option("-y", "--young"). action("store_const").dest("eyes").set_const("..");
parser.add_option("-e", "--eyes"). action("store").dest("eyes");
parser.add_option("-T", "--tongue"). action("store").dest("tongue");
parser.add_option("-l", "--list").action("store_true").dest("list")
.help("displays cow file location");
parser.add_option("-f", "--file").action("store").dest("file")
.set_default("default.cow").help("cow file, searches in cowpath. "
".cow is automatically appended");
parser.add_option("-W", "--wrap").action("store").type("int").dest("wrap")
.set_default(70).help("wraps the cow text, default 70");
parser.add_option("--thoughts").action("store").dest("thoughts")
.help("the method of communication cow uses. "
"Default to `o` if invoked as cowthink, otherwise `\\`");
parser.add_option("-c", "--command-line").action("store_true").dest("cmd")
.help("treat command line as text, not files");
std::string cowpath_opts[5] = {"-a", "--add", "--add-cow", "--add-path", "--add-cow-path"};
parser.add_option(std::vector<std::string>(&cowpath_opts[0], &cowpath_opts[5]))
.action("append").dest("cowpath");
optparse::Values& options = parser.parse_args(argc, argv);
std::vector<std::string> args = parser.args();
std::vector<std::string> cowpath(options.all("cowpath").cbegin(), options.all("cowpath").cend());
std::reverse(cowpath.begin(), cowpath.end());
add_default_cowpath(cowpath);
std::string tongue, eyes;
eyes = (options["eyes"] + " ").substr(0, 2);
if (options["tongue"].empty()) {
if (eyes == "xx" || eyes == "**") // one of the predefined dead faces
tongue = "U ";
else
tongue = " ";
} else
tongue = (options["tongue"] + " ").substr(0, 2);
if (options.is_set("list")) {
try {
std::string path = findcow(cowpath, options["file"]);
#ifdef WIN32
replace(path, "/", "\\");
#endif
std::cout << path << std::endl;
return 0;
} catch (std::string e) {
std::cerr << argv[0] << ": " << e << std::endl;
return 1;
}
}
std::string cow;
std::vector<std::string> lines;
std::string input;
try {
cow = loadcow(findcow(cowpath, options["file"]), options["thoughts"], eyes, tongue);
if (options.get("cmd")) {
std::stringstream stream;
for (auto line = args.cbegin(); line < args.cend(); ++line)
stream << *line << '\n';
input = stream.str();
} else
open_streams(input, args);
int width = wrap(input, lines, options.get("wrap"));
write_ballon(stdout, lines, width, options["thoughts"] == "o");
fputs(cow.c_str(), stdout);
} catch (std::string e) {
std::cerr << argv[0] << ": " << e << std::endl;
}
}
| 34.004673 | 115 | 0.552632 | [
"vector"
] |
1e4c977656a8dc5133cfefee8c1ad39314bde651 | 5,688 | cpp | C++ | examples/bare_wasm_cpp/main.cpp | yaram/constraint-based-layout | baeee0aa61a560c478c243b1ecc8364f0bb5ad97 | [
"MIT"
] | null | null | null | examples/bare_wasm_cpp/main.cpp | yaram/constraint-based-layout | baeee0aa61a560c478c243b1ecc8364f0bb5ad97 | [
"MIT"
] | null | null | null | examples/bare_wasm_cpp/main.cpp | yaram/constraint-based-layout | baeee0aa61a560c478c243b1ecc8364f0bb5ad97 | [
"MIT"
] | null | null | null | #include <stdint.h>
#include <stddef.h>
#include "debug.h"
#include "environment.h"
#include "controls.h"
const size_t max_allocator_space = 1024 * 16;
size_t next_allocation_start = 0;
uint8_t __attribute__((aligned(sizeof(size_t)))) allocator_space[max_allocator_space];
static void clear_allocator() {
next_allocation_start = 0;
}
void *allocate(size_t size) {
auto size_offset = next_allocation_start;
auto data_offset = size_offset + sizeof(size_t);
// Align to sizeof(size_t)
auto new_next_allocation_start = ((data_offset + size) * sizeof(size_t) + sizeof(size_t) / 2) / sizeof(size_t);
if(new_next_allocation_start > max_allocator_space) {
return nullptr;
}
next_allocation_start = new_next_allocation_start;
*(size_t*)&allocator_space[size_offset] = size;
auto pointer = (void*)&allocator_space[data_offset];
return pointer;
}
void *reallocate(void *pointer, size_t new_size) {
auto new_pointer = allocate(new_size);
if(new_pointer == nullptr) {
return nullptr;
}
if(pointer != nullptr) {
auto offset = (size_t)pointer - (size_t)allocator_space;
auto old_size = *(size_t*)&allocator_space[offset - sizeof(size_t)];
for(size_t i = 0; i < old_size; i += 1) {
((uint8_t*)new_pointer)[i] = ((uint8_t*)pointer)[i];
}
}
return new_pointer;
}
void deallocate(void *pointer) {
// Do nothing, is a simple arena allocator with no non-global deallocation/freeing
}
static size_t uint_to_string(unsigned int value, char *buffer, unsigned int radix = 10) {
if(value == 0) {
buffer[0] = '0';
return 1;
}
size_t length = 0;
const char digits[] = "0123456789ABCDEF";
while(value != 0) {
buffer[length] = digits[value % radix];
value /= radix;
length += 1;
}
for(size_t i = 0; i < length / 2; i += 1) {
auto temp = buffer[i];
buffer[i] = buffer[length - 1 - i];
buffer[length - 1 - i] = temp;
}
return length;
}
unsigned int count = 0;
const size_t test_text_max_length = 32;
char test_text_buffer[test_text_max_length];
size_t test_text_length = 0;
float frame_width;
float frame_height;
void render();
void increment_press_handler() {
count += 1;
clear_allocator();
render();
}
void frame_resize_handler(float width, float height) {
frame_width = width;
frame_height = height;
clear_allocator();
render();
}
void test_change_handler(String text) {
for(size_t i = 0; i < text.length; i += 1) {
if(i >= test_text_max_length) {
break;
}
test_text_buffer[i] = text.data[i];
}
if(text.length <= test_text_max_length) {
test_text_length = text.length;
} else {
test_text_length = test_text_max_length;
}
clear_allocator();
render();
}
void render() {
LayoutContext context {};
context.frame_resize_handler = frame_resize_handler;
auto content = create_container(&context, nullptr);
char count_string[32];
auto count_string_length = uint_to_string(count, count_string);
auto test_label = create_label(&context, content, { test_text_buffer, test_text_length }, "sans-serif"_S, 20);
auto test_label_width = get_text_width(test_label->text, test_label->font_family, test_label->font_size);
auto test_label_height = test_label->font_size;
auto count_label = create_label(&context, content, { count_string, count_string_length }, "sans-serif"_S, 20);
auto count_label_width = get_text_width(count_label->text, count_label->font_family, count_label->font_size);
auto count_label_height = count_label->font_size;
auto increment_button = create_button(&context, content, "Increment"_S, "sans-serif"_S, 20);
auto increment_button_text_width = get_text_width(increment_button->text, increment_button->font_family, increment_button->font_size);
auto increment_button_text_height = increment_button->font_size;
increment_button->press_handler = increment_press_handler;
auto test_text_input = create_text_input(&context, content, { test_text_buffer, test_text_length }, "sans-serif"_S, 20);
auto test_text_input_text_height = test_text_input->font_size;
test_text_input->change_handler = test_change_handler;
auto padding = 8.0f;
horizontal_middle(content) == frame_width / 2;
vertical_middle(content) == frame_height / 2;
top(test_label) == 0;
width(test_text_input) == frame_width / 3;
height(test_text_input) == test_text_input->font_size + padding * 2;
horizontal_middle(test_text_input) == width(content) / 2;
top(test_text_input) == bottom(increment_button) + padding;
width(increment_button) == frame_width / 2;
height(increment_button) == increment_button->font_size + padding * 2;
horizontal_middle(increment_button) == width(content) / 2;
horizontal_middle(count_label) == width(content) / 2;
bottom(count_label) == top(increment_button) - padding;
horizontal_middle(test_label) == width(content) / 2;
bottom(test_label) == top(count_label) - padding;
perform_layout(&context);
}
extern "C" void init() {
get_frame_size(&frame_width, &frame_height);
render();
}
extern "C" void *memcpy(void *destination, void *source, size_t num) {
for(size_t i = 0; i < num; i += 1) {
((uint8_t*)destination)[i] = ((uint8_t*)source)[i];
}
return destination;
}
extern "C" void *memset(void *pointer, int value, size_t count) {
for(size_t i = 0; i < count; i += 1) {
((uint8_t*)pointer)[i] = (uint8_t)value;
}
return pointer;
} | 26.704225 | 138 | 0.675105 | [
"render"
] |
1e51f2ecbba007bdb28dd53469a1ea988f9fa77d | 1,905 | hpp | C++ | cpp/include/cuml/common/rmmPoolAllocatorAdapter.hpp | alxhrzg/cuml | fbf619a4aa5752b7f8647d1c129eb3def7d8ba78 | [
"Apache-2.0"
] | 2 | 2020-12-19T23:34:37.000Z | 2022-01-13T21:08:51.000Z | cpp/include/cuml/common/rmmPoolAllocatorAdapter.hpp | alxhrzg/cuml | fbf619a4aa5752b7f8647d1c129eb3def7d8ba78 | [
"Apache-2.0"
] | null | null | null | cpp/include/cuml/common/rmmPoolAllocatorAdapter.hpp | alxhrzg/cuml | fbf619a4aa5752b7f8647d1c129eb3def7d8ba78 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019-2020, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "rmmAllocatorAdapter.hpp"
#include <cuml/common/logger.hpp>
#include <cuml/common/utils.hpp>
#include <cuml/cuml.hpp>
#include <rmm/mr/device/cuda_memory_resource.hpp>
#include <rmm/mr/device/owning_wrapper.hpp>
#include <rmm/mr/device/pool_memory_resource.hpp>
#include <memory>
namespace ML {
namespace {
// simple helpers for creating RMM MRs
inline auto make_cuda() {
return std::make_shared<rmm::mr::cuda_memory_resource>();
}
inline auto make_pool() {
return rmm::mr::make_owning_wrapper<rmm::mr::pool_memory_resource>(
make_cuda());
}
} // namespace
/**
* @brief Implemententation of ML::deviceAllocator using the RMM pool
*
* @todo rmmPoolAllocatorAdapter currently only uses the default ctor of the
* underlying device_memory_resource.
*/
class rmmPoolAllocatorAdapter : public rmmAllocatorAdapter {
public:
rmmPoolAllocatorAdapter() : mr_(make_pool()) {
prev_mr_ = rmm::mr::set_current_device_resource(mr_.get());
}
~rmmPoolAllocatorAdapter() {
// restore the previous memory resource when this object goes out-of-scope
rmm::mr::set_current_device_resource(prev_mr_);
}
private:
std::shared_ptr<rmm::mr::device_memory_resource> mr_;
rmm::mr::device_memory_resource* prev_mr_;
};
} // end namespace ML
| 28.014706 | 78 | 0.739108 | [
"object"
] |
1e52782d358001b4b2a163991f3d42b68b989268 | 489 | cpp | C++ | Olympiad Solutions/DMOJ/ccc17s2.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | Olympiad Solutions/DMOJ/ccc17s2.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | Olympiad Solutions/DMOJ/ccc17s2.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | // Ivan Carvalho
// Solution to https://dmoj.ca/problem/ccc17s2
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
vector<int> E(n);
for(int i=0;i<n;i++) cin >> E[i];
sort(E.begin(),E.end());
int ini_lo = (n + 1)/2 - 1;
int ini_hi = ini_lo + 1;
while(true){
if(ini_lo < 0 && ini_hi >= n) break;
if(ini_lo >= 0){
cout << E[ini_lo] << " ";
ini_lo--;
}
if(ini_hi < n){
cout << E[ini_hi] << " ";
ini_hi++;
}
}
cout << endl;
return 0;
} | 18.807692 | 46 | 0.535787 | [
"vector"
] |
1e52f363240c6bd222b070d6566e28e120664543 | 1,550 | cpp | C++ | src/BoundingBox.cpp | Seong-su/hierarchical-data-structure | a56e0df2c9b6a8c5c38349c90a49d57fd49b4102 | [
"MIT"
] | null | null | null | src/BoundingBox.cpp | Seong-su/hierarchical-data-structure | a56e0df2c9b6a8c5c38349c90a49d57fd49b4102 | [
"MIT"
] | null | null | null | src/BoundingBox.cpp | Seong-su/hierarchical-data-structure | a56e0df2c9b6a8c5c38349c90a49d57fd49b4102 | [
"MIT"
] | null | null | null | #include <algorithm>
#include "BoundingBox.hpp"
BoundingBox::BoundingBox(int id, const std::string &name, aiMesh *mesh)
: id_(id) {
set_name(name);
uint64_t num_vertices = mesh->mNumVertices;
if (num_vertices > 0) {
init_max(mesh->mVertices[0]);
init_min(mesh->mVertices[0]);
std::for_each(mesh->mVertices, mesh->mVertices + num_vertices,
[this](const aiVector3D &vertex) {
this->find_max(vertex);
this->find_min(vertex);
});
find_center();
find_radius();
}
}
BoundingBox::BoundingBox(BoundingBox *const b1, BoundingBox *const b2) {
set_name(b1->name_ + "-" + b2->name_);
init_max(b1->max_);
init_min(b1->min_);
find_max(b2->max_);
find_min(b2->min_);
find_center();
find_radius();
}
BoundingBox::~BoundingBox() {}
void BoundingBox::init_max(const aiVector3D &point) { max_ = point; }
void BoundingBox::init_min(const aiVector3D &point) { min_ = point; }
void BoundingBox::find_max(const aiVector3D &point) {
if (max_.x < point.x) max_.x = point.x;
if (max_.y < point.y) max_.y = point.y;
if (max_.z < point.z) max_.z = point.z;
}
void BoundingBox::find_min(const aiVector3D &point) {
if (min_.x > point.x) min_.x = point.x;
if (min_.y > point.y) min_.y = point.y;
if (min_.z > point.z) min_.z = point.z;
}
void BoundingBox::find_center() {
center_ = (max_ + min_);
center_ /= 2;
}
void BoundingBox::find_radius() {
aiVector3D diameter_vec = max_ - min_;
radius_ = diameter_vec.Length() / 2;
}
| 24.603175 | 72 | 0.632903 | [
"mesh"
] |
1e5d1ec71f72873046034085b369161d47450c64 | 2,287 | cc | C++ | src/data/sparse_page_raw_format.cc | bclehmann/xgboost | 345796825f7bbeb0251bca1244e296fda211551b | [
"Apache-2.0"
] | 23,866 | 2015-03-22T05:53:05.000Z | 2022-03-31T23:59:37.000Z | src/data/sparse_page_raw_format.cc | bclehmann/xgboost | 345796825f7bbeb0251bca1244e296fda211551b | [
"Apache-2.0"
] | 6,405 | 2015-03-22T09:41:16.000Z | 2022-03-31T23:28:40.000Z | src/data/sparse_page_raw_format.cc | bclehmann/xgboost | 345796825f7bbeb0251bca1244e296fda211551b | [
"Apache-2.0"
] | 9,745 | 2015-03-22T05:25:51.000Z | 2022-03-31T09:24:51.000Z | /*!
* Copyright (c) 2015-2021 by Contributors
* \file sparse_page_raw_format.cc
* Raw binary format of sparse page.
*/
#include <xgboost/data.h>
#include <dmlc/registry.h>
#include "xgboost/logging.h"
#include "./sparse_page_writer.h"
namespace xgboost {
namespace data {
DMLC_REGISTRY_FILE_TAG(sparse_page_raw_format);
template<typename T>
class SparsePageRawFormat : public SparsePageFormat<T> {
public:
bool Read(T* page, dmlc::SeekStream* fi) override {
auto& offset_vec = page->offset.HostVector();
if (!fi->Read(&offset_vec)) {
return false;
}
auto& data_vec = page->data.HostVector();
CHECK_NE(page->offset.Size(), 0U) << "Invalid SparsePage file";
data_vec.resize(offset_vec.back());
if (page->data.Size() != 0) {
size_t n_bytes = fi->Read(dmlc::BeginPtr(data_vec),
(page->data).Size() * sizeof(Entry));
CHECK_EQ(n_bytes, (page->data).Size() * sizeof(Entry))
<< "Invalid SparsePage file";
}
fi->Read(&page->base_rowid, sizeof(page->base_rowid));
return true;
}
size_t Write(const T& page, dmlc::Stream* fo) override {
const auto& offset_vec = page.offset.HostVector();
const auto& data_vec = page.data.HostVector();
CHECK(page.offset.Size() != 0 && offset_vec[0] == 0);
CHECK_EQ(offset_vec.back(), page.data.Size());
fo->Write(offset_vec);
auto bytes = page.MemCostBytes();
bytes += sizeof(uint64_t);
if (page.data.Size() != 0) {
fo->Write(dmlc::BeginPtr(data_vec), page.data.Size() * sizeof(Entry));
}
fo->Write(&page.base_rowid, sizeof(page.base_rowid));
bytes += sizeof(page.base_rowid);
return bytes;
}
private:
/*! \brief external memory column offset */
std::vector<size_t> disk_offset_;
};
XGBOOST_REGISTER_SPARSE_PAGE_FORMAT(raw)
.describe("Raw binary data format.")
.set_body([]() {
return new SparsePageRawFormat<SparsePage>();
});
XGBOOST_REGISTER_CSC_PAGE_FORMAT(raw)
.describe("Raw binary data format.")
.set_body([]() {
return new SparsePageRawFormat<CSCPage>();
});
XGBOOST_REGISTER_SORTED_CSC_PAGE_FORMAT(raw)
.describe("Raw binary data format.")
.set_body([]() {
return new SparsePageRawFormat<SortedCSCPage>();
});
} // namespace data
} // namespace xgboost
| 28.949367 | 76 | 0.663752 | [
"vector"
] |
1e5f823249a95753b88d952c698b45f4773c32f3 | 5,857 | cc | C++ | chrome/browser/android/preferences/important_sites_util_unittest.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | chrome/browser/android/preferences/important_sites_util_unittest.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/android/preferences/important_sites_util_unittest.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/preferences/important_sites_util.h"
#include <memory>
#include <utility>
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/engagement/site_engagement_score.h"
#include "chrome/browser/engagement/site_engagement_service.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_pattern.h"
#include "components/history/core/browser/history_database_params.h"
#include "components/history/core/browser/history_service.h"
#include "components/history/core/test/test_history_database.h"
#include "components/keyed_service/core/keyed_service.h"
#include "content/public/browser/web_contents.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const size_t kNumImportantSites = 5;
base::FilePath g_temp_history_dir;
std::unique_ptr<KeyedService> BuildTestHistoryService(
content::BrowserContext* context) {
std::unique_ptr<history::HistoryService> service(
new history::HistoryService());
service->Init(history::TestHistoryDatabaseParamsForPath(g_temp_history_dir));
return std::move(service);
}
} // namespace
class ImportantSitesUtilTest : public ChromeRenderViewHostTestHarness {
public:
void SetUp() override {
ChromeRenderViewHostTestHarness::SetUp();
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
g_temp_history_dir = temp_dir_.path();
HistoryServiceFactory::GetInstance()->SetTestingFactory(
profile(), &BuildTestHistoryService);
SiteEngagementScore::SetParamValuesForTesting();
}
void AddContentSetting(ContentSettingsType type,
ContentSetting setting,
const GURL& origin) {
ContentSettingsForOneType settings_list;
HostContentSettingsMapFactory::GetForProfile(profile())
->SetContentSettingCustomScope(
ContentSettingsPattern::FromURLNoWildcard(origin),
ContentSettingsPattern::Wildcard(),
CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
content_settings::ResourceIdentifier(), setting);
}
private:
base::ScopedTempDir temp_dir_;
};
TEST_F(ImportantSitesUtilTest, TestNoImportantSites) {
EXPECT_TRUE(ImportantSitesUtil::GetImportantRegisterableDomains(
profile(), kNumImportantSites, nullptr)
.empty());
}
TEST_F(ImportantSitesUtilTest, NotificationsThenEngagement) {
SiteEngagementService* service = SiteEngagementService::Get(profile());
ASSERT_TRUE(service);
GURL url1("http://www.google.com/");
GURL url2("https://www.google.com/");
GURL url3("https://drive.google.com/");
GURL url4("https://www.chrome.com/");
GURL url5("https://www.example.com/");
GURL url6("https://youtube.com/");
GURL url7("https://foo.bar/");
service->ResetScoreForURL(url1, 5);
service->ResetScoreForURL(url2, 2); // Below medium engagement (5).
service->ResetScoreForURL(url3, 7);
service->ResetScoreForURL(url4, 8);
service->ResetScoreForURL(url5, 9);
service->ResetScoreForURL(url6, 1); // Below the medium engagement (5).
service->ResetScoreForURL(url7, 11);
// Here we should have:
// 1: removed domains below minimum engagement,
// 2: combined the google.com entries, and
// 3: sorted by the score.
std::vector<std::string> expected_sorted_domains = {
"foo.bar", "example.com", "chrome.com", "google.com"};
std::vector<GURL> example_origins;
EXPECT_THAT(ImportantSitesUtil::GetImportantRegisterableDomains(
profile(), kNumImportantSites, &example_origins),
::testing::ElementsAreArray(expected_sorted_domains));
std::vector<GURL> expected_sorted_origins = {url7, url5, url4, url3};
EXPECT_THAT(example_origins,
::testing::ElementsAreArray(expected_sorted_origins));
// Test that notifications get moved to the front.
AddContentSetting(CONTENT_SETTINGS_TYPE_NOTIFICATIONS, CONTENT_SETTING_ALLOW,
url6);
// BLOCK'ed sites don't count. We want to make sure we only bump sites that
// were granted the permsion.
AddContentSetting(CONTENT_SETTINGS_TYPE_NOTIFICATIONS, CONTENT_SETTING_BLOCK,
url1);
// Same as above, but the site with notifications should be at the front.
expected_sorted_domains = {"youtube.com", "foo.bar", "example.com",
"chrome.com", "google.com"};
example_origins.clear();
EXPECT_THAT(ImportantSitesUtil::GetImportantRegisterableDomains(
profile(), kNumImportantSites, &example_origins),
::testing::ElementsAreArray(expected_sorted_domains));
expected_sorted_origins = {url6, url7, url5, url4, url3};
EXPECT_THAT(example_origins,
::testing::ElementsAreArray(expected_sorted_origins));
}
TEST_F(ImportantSitesUtilTest, TestNoOriginPopulation) {
SiteEngagementService* service = SiteEngagementService::Get(profile());
ASSERT_TRUE(service);
GURL url1("http://www.google.com/");
service->ResetScoreForURL(url1, 5);
std::vector<std::string> expected_sorted_domains = {"google.com"};
EXPECT_THAT(ImportantSitesUtil::GetImportantRegisterableDomains(
profile(), kNumImportantSites, nullptr),
::testing::ElementsAreArray(expected_sorted_domains));
}
| 40.393103 | 79 | 0.736555 | [
"vector"
] |
1e67bfa27781eb227a6a5426d2d7f37c0e906543 | 5,995 | hpp | C++ | src/indexing.hpp | willfurnass/pFIRE | 251cac173f2337f504dfde122851b834fe3e77be | [
"Apache-2.0"
] | 9 | 2019-02-14T09:03:03.000Z | 2021-11-30T16:03:32.000Z | src/indexing.hpp | willfurnass/pFIRE | 251cac173f2337f504dfde122851b834fe3e77be | [
"Apache-2.0"
] | 64 | 2019-01-29T16:22:42.000Z | 2021-06-07T07:54:28.000Z | src/indexing.hpp | tartarini/pFIRE | 406fdbb188a17b6413edcd0a229213464628ab15 | [
"Apache-2.0"
] | 5 | 2019-01-29T15:32:53.000Z | 2021-08-19T10:24:42.000Z | //
// Copyright 2019 University of Sheffield
//
// 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 INDEXING_HPP
#define INDEXING_HPP
#include <utility>
#include <vector>
#include "types.hpp"
#include "exceptions.hpp"
/*! Flatten a 3D array index into 1D array location
*
*/
template <typename inttype>
coord<typename std::enable_if<
std::is_integral<inttype>::value && !std::is_same<inttype, bool>::value, inttype>::type>
unravel(const inttype& idx, const coord<inttype>& shape)
{
// This routine only makes sense to use for inttype types
static_assert(std::is_integral<inttype>::value, "Integral element type required");
coord<inttype> loc;
inttype midx = idx;
for (size_t i = 0; i < shape.size(); i++)
{
loc[i] = midx % shape[i];
midx /= shape[i];
}
return loc;
}
/*! Unflatten a 1D array location into 3D array index
*
*/
template <typename inttype>
typename std::enable_if<std::is_integral<inttype>::value && !std::is_same<inttype, bool>::value,
inttype>::type
ravel(const coord<inttype>& loc, const coord<inttype>& shape)
{
// This routine only makes sense to use for inttype types
static_assert(std::is_integral<inttype>::value, "Integral element type required");
size_t end = loc.size() - 1;
inttype idx = loc[end];
for (inttype i = end - 1; i >= 0; i--)
{
idx *= shape[i];
idx += loc[i];
}
return idx;
}
/*! Calculate offsets for neighbour indices to a given mesh cell using a Von Neumann stencil
*
*/
template <typename inttype, typename inttype2>
std::vector<typename std::make_signed<typename std::enable_if<
std::is_integral<inttype>::value && !std::is_same<inttype, bool>::value, inttype>::type>::type>
calculate_von_neumann_offsets(const coord<inttype>& mesh_shape, const inttype2& ndof)
{
size_t ndim = mesh_shape[2] == 1 ? 2 : 3;
using inttype_s = typename std::make_signed<inttype>::type;
std::vector<inttype_s> offsets(2 * ndim + 1, 0);
size_t centre_idx = ndim;
inttype offset = 1;
for (size_t idx = 1; idx <= ndim; idx++)
{
offsets[centre_idx + idx] = offset * ndof;
offsets[centre_idx - idx] = -offset * ndof;
offset *= mesh_shape[idx - 1];
}
return offsets;
}
/*! Calculate offsets for neighbour indices to a mesh cell using a Moore stencil
*
*/
template <typename inttype, typename inttype2>
std::vector<typename std::make_signed<typename std::enable_if<
std::is_integral<inttype>::value && !std::is_same<inttype, bool>::value, inttype>::type>::type>
calculate_moore_offsets(const coord<inttype>& mesh_shape, inttype2 ndof)
{
using inttype_s = typename std::make_signed<inttype>::type;
std::vector<inttype_s> offsets;
integer zmin(-1), zmax(1);
if (mesh_shape[2] == 1)
{
zmin = 0;
zmax = 0;
}
for (inttype_s zz = zmin; zz <= zmax; zz++)
{
for (inttype_s yy = -1; yy <= 1; yy++)
{
for (inttype_s xx = -1; xx <= 1; xx++)
{
offsets.push_back(ndof * (xx + mesh_shape[0] * (yy + mesh_shape[1] * zz)));
}
}
}
return offsets;
}
/*
template <typename T>
bool ranges_overlap(coord<T> a_lo, coord<T> a_hi,
coord<T> b_lo, coord<T> b_hi)
{
for(int i=0; i<3; i++)
{
if(b_hi[i] < a_lo[i] || a_hi[i] < b_lo[1])
{
return false;
}
}
return true;
}
*/
/*! Given two ranges, return a new range that is the overlap of the two input ranges
*
*/
template <typename T>
std::pair<coord<T>, coord<T>> get_overlap(coord<T> a_lo, coord<T> a_hi, coord<T> b_lo,
coord<T> b_hi)
{
coord<T> reslo, reshi;
for (int i = 0; i < 3; i++)
{
reslo[i] = std::max(a_lo[i], b_lo[i]);
reshi[i] = std::min(a_hi[i], b_hi[i]);
}
return std::make_pair(reslo, reshi);
}
template <typename T>
T range_get_nelements(coord<T> lo, coord<T> hi)
{
T nelem = 1;
for (int i = 0; i < 3; i++)
{
nelem *= hi[i] - lo[i];
}
return nelem;
}
template <typename T>
void clamp_location_lo(coord<T>& loc, coord<T> const& min)
{
for (size_t idx = 0; idx < loc.size(); idx++)
{
loc[idx] = loc[idx] >= min[idx] ? loc[idx] : min[idx];
}
}
template <typename T>
void clamp_location_hi(coord<T>& loc, coord<T> const& max)
{
for (size_t idx = 0; idx < loc.size(); idx++)
{
loc[idx] = loc[idx] <= max[idx] ? loc[idx] : max[idx];
}
}
template <typename T>
void clamp_location(coord<T>& loc, coord<T> const& min, coord<T> const& max)
{
for (size_t idx = 0; idx < loc.size(); idx++)
{
loc[idx] = loc[idx] >= min[idx] ? loc[idx] : min[idx];
loc[idx] = loc[idx] <= max[idx] ? loc[idx] : max[idx];
}
}
template <typename Input1, typename Input2, typename Input3>
floating calculate_scaled_basis_coefficient(Input1 first1, Input1 last1, Input2 first2,
Input3 scale)
{
floating res = 1;
auto it1 = first1;
auto it2 = first2;
auto scaleit = scale;
for (; it1 != last1;)
{
res *= 1 - std::abs(*it1++ - *it2++) / (*scaleit++);
}
if (res > 1.)
{
throw InternalError("Coefficient too large");
}
return res;
}
template <typename Input1, typename Input2>
floating calculate_unscaled_basis_coefficient(Input1 first1, Input1 last1, Input2 first2)
{
floating res = 1;
auto it1 = first1;
auto it2 = first2;
for (; it1 != last1;)
{
res *= 1 - std::abs(*it1++ - *it2++);
}
if (res > 1.)
{
throw InternalError("Coefficient too large");
}
return res;
}
#endif
| 25.295359 | 99 | 0.630025 | [
"mesh",
"shape",
"vector",
"3d"
] |
1e687bea5babdba2ca92a12a8962115587254916 | 7,529 | cpp | C++ | ibtk/src/utilities/StandardTagAndInitStrategySet.cpp | akashdhruv/IBAMR | a2b47946d795fb5a40c181b43e44a6ec387585a9 | [
"BSD-3-Clause"
] | 264 | 2015-01-04T12:11:02.000Z | 2022-03-31T13:10:37.000Z | ibtk/src/utilities/StandardTagAndInitStrategySet.cpp | akashdhruv/IBAMR | a2b47946d795fb5a40c181b43e44a6ec387585a9 | [
"BSD-3-Clause"
] | 1,057 | 2015-04-27T04:27:57.000Z | 2022-03-31T13:14:59.000Z | ibtk/src/utilities/StandardTagAndInitStrategySet.cpp | drwells/IBAMR | 0ceda3873405a35da4888c99e7d2b24d132f9071 | [
"BSD-3-Clause"
] | 126 | 2015-02-13T15:36:02.000Z | 2022-03-27T21:59:50.000Z | // ---------------------------------------------------------------------
//
// Copyright (c) 2014 - 2020 by the IBAMR developers
// All rights reserved.
//
// This file is part of IBAMR.
//
// IBAMR is free software and is distributed under the 3-clause BSD
// license. The full text of the license can be found in the file
// COPYRIGHT at the top level directory of IBAMR.
//
// ---------------------------------------------------------------------
/////////////////////////////// INCLUDES /////////////////////////////////////
#include "ibtk/StandardTagAndInitStrategySet.h"
#include "BasePatchHierarchy.h"
#include "BasePatchLevel.h"
#include "IntVector.h"
#include "PatchHierarchy.h"
#include "PatchLevel.h"
#include "StandardTagAndInitStrategy.h"
#include "tbox/Pointer.h"
#include <algorithm>
#include <limits>
#include <vector>
#include "ibtk/namespaces.h" // IWYU pragma: keep
/////////////////////////////// NAMESPACE ////////////////////////////////////
namespace IBTK
{
/////////////////////////////// STATIC ///////////////////////////////////////
/////////////////////////////// PUBLIC ///////////////////////////////////////
StandardTagAndInitStrategySet::~StandardTagAndInitStrategySet()
{
if (d_managed)
{
for (const auto& strategy : d_strategy_set)
{
delete strategy;
}
}
return;
} // ~StandardTagAndInitStrategySet
double
StandardTagAndInitStrategySet::getLevelDt(const Pointer<BasePatchLevel<NDIM> > level,
const double dt_time,
const bool initial_time)
{
double dt = std::numeric_limits<double>::max();
for (const auto& strategy : d_strategy_set)
{
dt = std::min(dt, strategy->getLevelDt(level, dt_time, initial_time));
}
return dt;
} // getLevelDt
double
StandardTagAndInitStrategySet::advanceLevel(const Pointer<BasePatchLevel<NDIM> > level,
const Pointer<BasePatchHierarchy<NDIM> > hierarchy,
const double current_time,
const double new_time,
const bool first_step,
const bool last_step,
const bool regrid_advance)
{
double dt = std::numeric_limits<double>::max();
for (const auto& strategy : d_strategy_set)
{
dt = std::min(
dt,
strategy->advanceLevel(level, hierarchy, current_time, new_time, first_step, last_step, regrid_advance));
}
return dt;
} // advanceLevel
void
StandardTagAndInitStrategySet::resetTimeDependentData(const Pointer<BasePatchLevel<NDIM> > level,
const double new_time,
const bool can_be_refined)
{
for (const auto& strategy : d_strategy_set)
{
strategy->resetTimeDependentData(level, new_time, can_be_refined);
}
return;
} // resetTimeDependentData
void
StandardTagAndInitStrategySet::resetDataToPreadvanceState(const Pointer<BasePatchLevel<NDIM> > level)
{
for (const auto& strategy : d_strategy_set)
{
strategy->resetDataToPreadvanceState(level);
}
return;
} // resetDataToPreadvanceState
void
StandardTagAndInitStrategySet::initializeLevelData(const Pointer<BasePatchHierarchy<NDIM> > hierarchy,
const int level_number,
const double init_data_time,
const bool can_be_refined,
const bool initial_time,
const Pointer<BasePatchLevel<NDIM> > old_level,
const bool allocate_data)
{
for (const auto& strategy : d_strategy_set)
{
strategy->initializeLevelData(
hierarchy, level_number, init_data_time, can_be_refined, initial_time, old_level, allocate_data);
}
return;
} // initializeLevelData
void
StandardTagAndInitStrategySet::resetHierarchyConfiguration(const Pointer<BasePatchHierarchy<NDIM> > hierarchy,
const int coarsest_level,
const int finest_level)
{
for (const auto& strategy : d_strategy_set)
{
strategy->resetHierarchyConfiguration(hierarchy, coarsest_level, finest_level);
}
return;
} // resetHierarchyConfiguration
void
StandardTagAndInitStrategySet::applyGradientDetector(const Pointer<BasePatchHierarchy<NDIM> > hierarchy,
const int level_number,
const double error_data_time,
const int tag_index,
const bool initial_time,
const bool uses_richardson_extrapolation_too)
{
for (const auto& strategy : d_strategy_set)
{
strategy->applyGradientDetector(
hierarchy, level_number, error_data_time, tag_index, initial_time, uses_richardson_extrapolation_too);
}
return;
} // applyGradientDetector
void
StandardTagAndInitStrategySet::applyRichardsonExtrapolation(const Pointer<PatchLevel<NDIM> > level,
const double error_data_time,
const int tag_index,
const double deltat,
const int error_coarsen_ratio,
const bool initial_time,
const bool uses_gradient_detector_too)
{
for (const auto& strategy : d_strategy_set)
{
strategy->applyRichardsonExtrapolation(
level, error_data_time, tag_index, deltat, error_coarsen_ratio, initial_time, uses_gradient_detector_too);
}
return;
} // applyRichardsonExtrapolation
void
StandardTagAndInitStrategySet::coarsenDataForRichardsonExtrapolation(const Pointer<PatchHierarchy<NDIM> > hierarchy,
const int level_number,
const Pointer<PatchLevel<NDIM> > coarser_level,
const double coarsen_data_time,
const bool before_advance)
{
for (const auto& strategy : d_strategy_set)
{
strategy->coarsenDataForRichardsonExtrapolation(
hierarchy, level_number, coarser_level, coarsen_data_time, before_advance);
}
return;
} // coarsenDataForRichardsonExtrapolation
/////////////////////////////// PROTECTED ////////////////////////////////////
/////////////////////////////// PRIVATE //////////////////////////////////////
/////////////////////////////// NAMESPACE ////////////////////////////////////
} // namespace IBTK
//////////////////////////////////////////////////////////////////////////////
| 39.213542 | 118 | 0.502059 | [
"vector"
] |
1e6ab398f02112a6e365a6bea15c081b670e77e1 | 12,256 | cpp | C++ | rdkPlugins/Thunder/source/ThunderSecurityAgent.cpp | WKonieczny/Dobby | ade2f9724d05cb6ce365c4707bd397b74b8598f0 | [
"Apache-2.0"
] | null | null | null | rdkPlugins/Thunder/source/ThunderSecurityAgent.cpp | WKonieczny/Dobby | ade2f9724d05cb6ce365c4707bd397b74b8598f0 | [
"Apache-2.0"
] | null | null | null | rdkPlugins/Thunder/source/ThunderSecurityAgent.cpp | WKonieczny/Dobby | ade2f9724d05cb6ce365c4707bd397b74b8598f0 | [
"Apache-2.0"
] | null | null | null | /*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2021 Sky UK
*
* 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 "ThunderSecurityAgent.h"
#include <Logging.h>
#include <poll.h>
#include <unistd.h>
#include <sys/un.h>
#include <sys/socket.h>
ThunderSecurityAgent::ThunderSecurityAgent(const std::string &socketAddr,
const std::chrono::milliseconds &defaultTimeout)
: mSocketPath(socketAddr),
mTimeout(defaultTimeout),
mSocket(-1)
{
}
ThunderSecurityAgent::~ThunderSecurityAgent()
{
if ((mSocket >= 0) && (::close(mSocket) != 0))
{
AI_LOG_SYS_ERROR(errno, "failed to close socket");
}
}
// -----------------------------------------------------------------------------
/**
* @brief Returns true if we have an open connection to the security agent.
*
*/
bool ThunderSecurityAgent::isOpen() const
{
std::lock_guard<std::mutex> locker(mLock);
return (mSocket >= 0);
}
// -----------------------------------------------------------------------------
/**
* @brief Opens a connection to the security agent. This must be called, and
* return true before calling getToken()
*
*/
bool ThunderSecurityAgent::open()
{
std::lock_guard<std::mutex> locker(mLock);
return openNoLock();
}
bool ThunderSecurityAgent::openNoLock()
{
AI_LOG_FN_ENTRY();
if (mSocket >= 0)
{
AI_LOG_WARN("socket is already opened");
AI_LOG_FN_EXIT();
return true;
}
// create the socket
mSocket = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (mSocket < 0)
{
AI_LOG_SYS_ERROR(errno, "failed to create socket");
}
else
{
struct sockaddr_un addr;
bzero(&addr, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, mSocketPath.c_str(), sizeof(addr.sun_path) - 1);
if (TEMP_FAILURE_RETRY(connect(mSocket,
reinterpret_cast<struct sockaddr *>(&addr),
sizeof(struct sockaddr_un))) != 0)
{
AI_LOG_SYS_ERROR(errno, "failed to connect to socket @ '%s'",
mSocketPath.c_str());
::close(mSocket);
mSocket = -1;
}
else
{
AI_LOG_INFO("open IPC connection to socket @ '%s'", mSocketPath.c_str());
}
}
AI_LOG_FN_EXIT();
return (mSocket >= 0);
}
// -----------------------------------------------------------------------------
/**
* @brief Closes the connection to the security agent.
*
*/
void ThunderSecurityAgent::close()
{
std::lock_guard<std::mutex> locker(mLock);
closeNoLock();
}
void ThunderSecurityAgent::closeNoLock()
{
if ((mSocket >= 0) && (::close(mSocket) != 0))
AI_LOG_SYS_ERROR(errno, "failed to close socket");
mSocket = -1;
}
// -----------------------------------------------------------------------------
/**
* @brief Attempts to get a token from the security agent.
*
*/
std::string ThunderSecurityAgent::getToken(const std::string &bearerUrl)
{
// ensure this is serialised
std::lock_guard<std::mutex> locker(mLock);
// sanity check
if (mSocket < 0)
{
AI_LOG_ERROR("not connect to the security agent");
return std::string();
}
// the id for token data is 10, see IPCSecurityToken.h
if (send(10, bearerUrl))
{
// get the reply
uint16_t replyId;
std::string replyData;
if (recv(&replyId, &replyData))
{
if ((replyId == 10) || (replyData.length() >= 64))
{
return replyData;
}
else
{
AI_LOG_ERROR("invalid reply received from security agent "
"(id:%hu length:%zu)",
replyId, replyData.length());
}
}
}
// if we've dropped out here it means something failed, to avoid a situation
// where the reply may just have been delayed - and if we keep the socket
// open then the next read may read the wrong security token - then we
// close and re-open the socket on any error
closeNoLock();
openNoLock();
// return empty token
return std::string();
}
// -----------------------------------------------------------------------------
/**
* @brief Sends an IPC message to the security agent.
*
* @param[in] id The message id, for getting the token this is 10.
* @param[in] data The data to add to the message.
*
* @return true on success, false on failure.
*/
bool ThunderSecurityAgent::send(uint16_t id, const std::string &data) const
{
// sanity check
if (mSocket < 0)
{
AI_LOG_ERROR("ipc socket is not connected");
return false;
}
// construct the message
const std::vector<uint8_t> message = constructMessage(id, data);
// and send it
ssize_t wr = TEMP_FAILURE_RETRY(::send(mSocket, message.data(), message.size(), 0));
if (wr < 0)
{
AI_LOG_SYS_ERROR(errno, "failed to send %zu bytes on ipc socket",
message.size());
return false;
}
else if (wr != static_cast<ssize_t>(message.size()))
{
AI_LOG_ERROR("failed to send entire message, only %zd bytes of %zu sent",
wr, message.size());
return false;
}
AI_LOG_DEBUG("sent IPC message with id %u and data length %zu bytes",
id, data.size());
return true;
}
// -----------------------------------------------------------------------------
/**
* @brief Creates a basic WPEFramework IPC::Core message for standard buffer
* arguments.
*
* @param[in] id The message id.
* @param[in] data The data to add to the message.
*
* @return a vector containing the serialised message buffer to send.
*/
std::vector<uint8_t> ThunderSecurityAgent::constructMessage(uint16_t id,
const std::string &data)
{
// construct the request, the IPC format is, you can work it out from the
// IPCConnector.h header, the Serialize and Deserialize methods
// - length of data
// - data identifier
// - data
std::vector<uint8_t> message;
message.reserve(6 + data.size());
uint32_t idLength = (id > 0x3fff) ? 3 : (id > 0x007f) ? 2
: 1;
uint32_t length = data.size() + idLength;
// the length and id fields are in little endian format and variable length,
// bit 7 is used to determine if it is the last byte that makes up the field
do
{
uint8_t value = length & 0x7f;
length >>= 7;
if (length != 0)
value |= 0x80;
message.push_back(value);
} while (length != 0);
// the id's are bit shift by one, presumably because the reply is the id
// with the lsb bit set
id <<= 1;
do
{
uint8_t value = id & 0x7f;
id >>= 7;
if (id != 0)
value |= 0x80;
message.push_back(value);
} while (id != 0);
// then just append the data and return
message.insert(message.end(), data.begin(), data.end());
return message;
}
// -----------------------------------------------------------------------------
/**
* @brief Attempts to read a message from the ipc socket. It will wait for a
* max @a mTimeout for a message before giving up and returning @c false.
*
* @param[out] id Pointer to a value to store the id of the received
* message in.
* @param[out] data Pointer to a string to populate with the messsage
* data.
*
* @return true on success, false on failure.
*/
bool ThunderSecurityAgent::recv(uint16_t *id, std::string *data) const
{
// sanity check
if (mSocket < 0)
{
AI_LOG_ERROR("ipc socket is not connected");
return false;
}
// wait for data
struct pollfd fd;
fd.fd = mSocket;
fd.events = POLLIN;
int ret = TEMP_FAILURE_RETRY(poll(&fd, 1, mTimeout.count()));
if (ret < 0)
{
AI_LOG_SYS_ERROR(errno, "error occurred polling on socket");
}
else if (ret == 0)
{
AI_LOG_WARN("timed-out waiting for IPC reply");
return false;
}
if (fd.events & (POLLERR | POLLHUP))
{
AI_LOG_WARN("ipc socket closed unexpectedly");
}
// now try and read the socket
uint8_t buffer[2048];
ssize_t rd = TEMP_FAILURE_RETRY(::recv(mSocket, buffer, sizeof(buffer), 0));
if (rd < 0)
{
AI_LOG_SYS_ERROR(errno, "failed to read messge from ipc socket");
return false;
}
else if (rd == 0)
{
AI_LOG_WARN("ipc socket closed unexpectedly");
return false;
}
AI_LOG_DEBUG("received IPC message of size %zd", rd);
// process the reply
return deconstructMessage(buffer, rd, id, data);
}
// -----------------------------------------------------------------------------
/**
* @brief Given a buffer containing a serialised IPC message it attempts to
* validate and extract the id and data.
*
* @param[in] buf Pointer to the message data received.
* @param[in] bufLength The length of the message in buf.
* @param[out] id Pointer to a value to store the id of the received
* message in.
* @param[out] data Pointer to a string to populate with the message
* data.
*
* @return true if the message was valid, otherwise false.
*/
bool ThunderSecurityAgent::deconstructMessage(const uint8_t *buf, size_t bufLength,
uint16_t *id, std::string *data)
{
if (bufLength < 2)
{
AI_LOG_ERROR("ipc message received to small (%zu bytes)", bufLength);
return false;
}
size_t n, index = 0;
// the length and id fields are in little endian format and variable length,
// bit 7 is used to determine if it is the last byte that makes up the field
uint32_t length = 0;
n = 0;
while (true)
{
const uint32_t value = buf[index++];
length |= ((value & 0x7f) << (7 * n++));
if ((value & 0x80) == 0)
{
break;
}
if (index >= bufLength)
{
AI_LOG_ERROR("invalid or truncated ipc message - length field");
return false;
}
}
// the length value is the length of the message minus the size of the
// length field itself
if ((length == 0) || ((length + index) != bufLength))
{
AI_LOG_ERROR("invalid or truncated ipc message - length mismatch");
return false;
}
// the ident field is formatted the same as the length field
uint32_t ident = 0;
n = 0;
while (true)
{
const uint32_t value = buf[index++];
ident |= ((value & 0x7f) << (7 * n++));
if ((value & 0x80) == 0)
{
break;
}
if (index >= bufLength)
{
AI_LOG_ERROR("invalid or truncated ipc message - id field");
return false;
}
}
// copy the id, the id's are bit shifted by 1 on the wire
if (id)
{
*id = static_cast<uint16_t>((ident >> 1) & 0xffff);
}
// the rest of the message is the data
if (data && (index < bufLength))
{
data->assign(buf + index, buf + bufLength);
}
AI_LOG_INFO("received IPC reply with id %u and data size %zu",
(ident >> 1), bufLength - index);
return true;
}
| 30.487562 | 91 | 0.54969 | [
"vector"
] |
1e7efb440f554215ca88bdc3b2985a0e2817b560 | 5,184 | cxx | C++ | Base/QTGUI/Testing/Cxx/qSlicerLoadableModuleWithPythonTest.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | Base/QTGUI/Testing/Cxx/qSlicerLoadableModuleWithPythonTest.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | Base/QTGUI/Testing/Cxx/qSlicerLoadableModuleWithPythonTest.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Copyright (c) Kitware Inc.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
and was partially funded by NIH grant 3P41RR013218-12S1
==============================================================================*/
// CTK includes
#include <ctkTest.h>
// Slicer includes
#include "qSlicerLoadableModule.h"
#include "qSlicerPythonManager.h"
// ----------------------------------------------------------------------------
class qSlicerLoadableHelloWorldModule : public qSlicerLoadableModule
{
Q_OBJECT
public:
typedef qSlicerLoadableModule Superclass;
qSlicerLoadableHelloWorldModule(QObject *parent=0):Superclass(parent){}
virtual ~qSlicerLoadableHelloWorldModule(){}
virtual QString helpText()const { return QString("helpText"); }
virtual QString acknowledgementText()const { return QString("acknowledgementText"); }
qSlicerGetTitleMacro("Loadable Hello world");
protected:
/// Create and return the widget representation associated to this module
virtual qSlicerAbstractModuleRepresentation * createWidgetRepresentation()
{
return 0;
}
/// Create and return the logic associated to this module
virtual vtkMRMLAbstractLogic* createLogic()
{
return 0;
}
};
// ----------------------------------------------------------------------------
class qSlicerLoadableModuleWithPythonTester: public QObject
{
Q_OBJECT
private:
qSlicerPythonManager PythonManager;
QHash<QString, qSlicerAbstractModule*> Modules;
private slots:
void testInitialize();
void testAddModuleToSlicerModules();
void testAddModuleToSlicerModules_data();
void testAddModuleNameToSlicerModuleNames();
void testAddModuleNameToSlicerModuleNames_data();
};
// ----------------------------------------------------------------------------
void qSlicerLoadableModuleWithPythonTester::testInitialize()
{
this->PythonManager.initialize();
this->PythonManager.executeString("import slicer");
this->Modules.insert("LoadableHelloWorld", new qSlicerLoadableHelloWorldModule(this));
}
// ----------------------------------------------------------------------------
void qSlicerLoadableModuleWithPythonTester::testAddModuleToSlicerModules()
{
QFETCH(bool, validPythonManager);
QFETCH(QString, moduleName);
QFETCH(bool, expectedResult);
qSlicerAbstractModule * module = this->Modules.value(moduleName);
QVERIFY(moduleName.isEmpty() ? true : module != 0);
bool currentResult = qSlicerLoadableModule::addModuleToSlicerModules(
validPythonManager ? &this->PythonManager : 0,
module,
moduleName);
QCOMPARE(currentResult, expectedResult);
if (expectedResult)
{
this->PythonManager.executeString(QString("dir(slicer.modules.%1)").arg(moduleName.toLower()));
QCOMPARE(!this->PythonManager.pythonErrorOccured(), expectedResult);
}
}
// ----------------------------------------------------------------------------
void qSlicerLoadableModuleWithPythonTester::testAddModuleToSlicerModules_data()
{
QTest::addColumn<bool>("validPythonManager");
QTest::addColumn<QString>("moduleName");
QTest::addColumn<bool>("expectedResult");
QTest::newRow("1") << true << "LoadableHelloWorld" << true;
QTest::newRow("2") << true << "" << false;
QTest::newRow("3") << false << "" << false;
}
// ----------------------------------------------------------------------------
void qSlicerLoadableModuleWithPythonTester::testAddModuleNameToSlicerModuleNames()
{
QFETCH(bool, validPythonManager);
QFETCH(QString, moduleName);
QFETCH(bool, expectedResult);
bool currentResult = qSlicerLoadableModule::addModuleNameToSlicerModuleNames(
validPythonManager ? &this->PythonManager : 0, moduleName);
QCOMPARE(currentResult, expectedResult);
if (expectedResult)
{
this->PythonManager.executeString(QString("dir(slicer.moduleNames.%1)").arg(moduleName.toLower()));
QCOMPARE(!this->PythonManager.pythonErrorOccured(), expectedResult);
}
}
// ----------------------------------------------------------------------------
void qSlicerLoadableModuleWithPythonTester::testAddModuleNameToSlicerModuleNames_data()
{
QTest::addColumn<bool>("validPythonManager");
QTest::addColumn<QString>("moduleName");
QTest::addColumn<bool>("expectedResult");
QTest::newRow("0") << true << "CoreHelloWorld" << true;
QTest::newRow("1") << true << "LoadableHelloWorld" << true;
QTest::newRow("2") << true << "" << false;
QTest::newRow("3") << false << "" << false;
}
// ----------------------------------------------------------------------------
CTK_TEST_MAIN(qSlicerLoadableModuleWithPythonTest)
#include "moc_qSlicerLoadableModuleWithPythonTest.cxx"
| 33.445161 | 103 | 0.640432 | [
"3d"
] |
1e82d03fca6cbb8fe75359683742cb54b794b8f4 | 11,770 | cpp | C++ | ege/scene/Scene.cpp | sppmacd/ege | a82ff6fccc8ac1bce5a50ed5a8f101b63f58b020 | [
"MIT"
] | 1 | 2020-12-30T17:21:11.000Z | 2020-12-30T17:21:11.000Z | ege/scene/Scene.cpp | sppmacd/ege | a82ff6fccc8ac1bce5a50ed5a8f101b63f58b020 | [
"MIT"
] | 20 | 2020-09-02T08:37:13.000Z | 2021-09-02T06:47:08.000Z | ege/scene/Scene.cpp | sppmacd/ege | a82ff6fccc8ac1bce5a50ed5a8f101b63f58b020 | [
"MIT"
] | null | null | null | /*
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* ,---- ,---- ,----
* | | |
* |---- | --, |----
* | | | |
* '---- '---' '----
*
* Framework Library for Hexagon
*
* Copyright (c) Sppmacd 2020 - 2021
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
*/
#include "Scene.h"
#include "SceneLoader.h"
#include "ege/debug/ProfilerSectionStarter.h"
#include <algorithm>
#include <ege/debug/Dump.h>
#include <ege/debug/Logger.h>
namespace EGE
{
Scene::Scene(SharedPtr<SceneObjectRegistry> registry)
: Component<SceneObject>("Scene (headless)"), m_registry(registry), m_loop(nullptr)
{
ege_log.notice() << "Creating headless scene!";
if(!m_registry)
m_registry = make<SceneObjectRegistry>();
}
Scene::Scene(GUIGameLoop& loop, SharedPtr<SceneObjectRegistry> registry)
: Component<SceneObject>(loop, "Scene"), m_registry(registry), m_loop(&loop)
{
if(!m_registry)
m_registry = make<SceneObjectRegistry>();
}
Scene::~Scene()
{
if(!m_lastLoadFile.empty())
saveToFile(m_lastLoadFile);
}
bool Scene::loadFromFile(String saveFile, String sceneFile,
const IOStreamConverter& converter)
{
m_lastLoadFile = saveFile;
SceneLoader loader(*this);
bool success = loader.loadSceneAndSave(saveFile, sceneFile, converter);
return success;
}
bool Scene::saveToFile(String saveFile, const IOStreamConverter& converter)
{
SceneLoader loader(*this);
return loader.saveScene(saveFile, converter);
}
void Scene::doRender(Renderer& renderer, const RenderStates& states)
{
std::lock_guard<std::recursive_mutex> lock(m_objectsMutex);
Renderable::doRender(renderer, states);
}
void Scene::render(Renderer& renderer) const
{
ASSERT_WITH_MESSAGE(m_loop, "Cannot render headless scenes");
for(auto& pr: m_objectsByLayer)
pr.second->doRender(renderer, renderer.getStates());
}
void Scene::onTick()
{
ProfilerSectionStarter starter(*getProfiler(), "eventLoop");
// Note that we don't call SceneObject's onTick() here; it's done in Component loop.
auto doUpdateForObjectMap = [this, &starter](Scene::ObjectMapType& objects, bool allowDead) {
for(auto it = objects.begin(); it != objects.end();)
{
starter.switchSection("update");
auto& object = *it;
auto oldIt = it++;
if(allowDead)
{
starter.switchSection("deadCheck");
if(object.second->isDead())
{
ege_log.debug() << "SceneObject is dead: " << object.second->getObjectId() << " @" << object.second;
fire<RemoveObjectEvent>(*object.second);
// Set all children dead
if(object.second->m_children.size() > 0)
{
ege_log.debug() << "SceneObject is dead: Removing " << object.second->m_children.size() << " children of " << object.second;
for(auto& so: object.second->m_children)
{
so->setDead();
}
}
// Remove object from its parent's children list
if(object.second->m_parent)
object.second->m_parent->m_children.erase(object.second.get());
m_objectsByName.erase(object.second->getName());
objects.erase(oldIt);
rebuildLayers();
}
}
}
};
// FIXME: Separate mutex for objects / staticObjects
std::lock_guard<std::recursive_mutex> lock(m_objectsMutex);
starter.switchSection("objectUpdate");
doUpdateForObjectMap(m_objects, true);
starter.switchSection("staticObjectUpdate");
doUpdateForObjectMap(m_staticObjects, false);
}
UidType Scene::addObject(SharedPtr<SceneObject> const& object)
{
if(!object)
return 0;
if(!object->getObjectId())
{
// On server, give entities negative IDs to separate client and server objects.
if(!getLoop())
--m_greatestId;
else
++m_greatestId;
object->setObjectId(m_greatestId);
}
else
{
if(m_greatestId < object->getObjectId())
m_greatestId = object->getObjectId();
}
object->init();
{
std::lock_guard<std::recursive_mutex> lock(m_objectsMutex);
auto objIdDupe = m_objects.find(object->getObjectId());
if(objIdDupe != m_objects.end())
{
// It's NOT normal!
ege_log.critical() << "Duplicate SceneObject ID: " << object->getName() << " collides with " << objIdDupe->second->getName();
return object->getObjectId();
}
if(m_objectsByName.find(object->getName()) != m_objectsByName.end())
{
// If it happens, fix your code!
ege_log.crash() << "Duplicate SceneObject name: " << object->getName();
CRASH_WITH_MESSAGE("Duplicate SceneObject name");
}
m_objects.insert(std::make_pair(object->getObjectId(), object));
if(object->getName().empty())
object->setName("SO" + std::to_string(object->getObjectId()));
m_objectsByName.insert(std::make_pair(object->getName(), object.get()));
}
fire<AddObjectEvent>(*object);
// TODO: Do not rebuild layers if adding multiple objects in one tick
rebuildLayers();
return object->getObjectId();
}
UidType Scene::addStaticObject(SharedPtr<SceneObject> const& object, bool overwrite)
{
if(!object)
return 0;
ASSERT_WITH_MESSAGE(!object->getName().empty(), "Static SceneObjects must have assigned name in scene data file");
if(!object->getObjectId())
{
// On server, give entities negative IDs to separate client and server objects.
if(!getLoop())
--m_greatestStaticId;
else
++m_greatestStaticId;
object->setObjectId(m_greatestStaticId);
}
else
{
if(m_greatestStaticId < object->getObjectId())
m_greatestStaticId = object->getObjectId();
}
object->init();
{
std::lock_guard<std::recursive_mutex> lock(m_objectsMutex);
if(m_staticObjects.find(object->getObjectId()) != m_staticObjects.end())
{
ege_log.critical() << "Duplicate SceneObject ID: " << object->getObjectId();
return object->getObjectId();
}
auto it = m_objectsByName.find(object->getName());
if(it != m_objectsByName.end())
{
// It's normal for static objects when static objects were saved!
ege_log.verbose() << "Duplicate SceneObject name: " << object->getName();
if(overwrite)
{
ege_log.debug() << "Scene::addObject(): overwriting " << it->second << " by " << object->getName();
auto& oldObject = m_objectsByName[it->second->getName()];
// Remove old object and add new (with new ID etc.)
m_staticObjects.erase(oldObject->getObjectId());
m_staticObjects.insert(std::make_pair(object->getObjectId(), object));
// Set another 'object by name'.
oldObject = object.get();
}
return object->getObjectId();
}
m_staticObjects.insert(std::make_pair(object->getObjectId(), object));
m_objectsByName.insert(std::make_pair(object->getName(), object.get()));
}
// TODO: Do not rebuild layers if adding multiple objects in one tick
rebuildLayers();
return object->getObjectId();
}
std::vector<SceneObject*> Scene::getObjects(std::function<bool(SceneObject*)> predicate)
{
std::vector<SceneObject*> objects;
for(ObjectMapType::value_type it: m_objects)
{
if(predicate(it.second.get()))
{
objects.push_back(it.second.get());
}
}
return objects;
}
std::vector<SceneObject*> Scene::getObjects(std::string typeId)
{
return getObjects([typeId](SceneObject* object)->bool { return object->getType()->getId() == typeId; });
}
SharedPtr<SceneObject> Scene::getObject(UidType id)
{
auto it = m_objects.find(id);
if(it != m_objects.end())
return it->second;
return nullptr;
}
SharedPtr<SceneObject> Scene::getStaticObject(UidType id)
{
auto it = m_staticObjects.find(id);
if(it != m_staticObjects.end())
return it->second;
return nullptr;
}
SceneObject* Scene::getObjectByName(String id)
{
auto it = m_objectsByName.find(id);
if(it != m_objectsByName.end())
return it->second;
return nullptr;
}
SharedPtr<SceneObject> Scene::addNewObject(String typeId, SharedPtr<ObjectMap> data)
{
SharedPtr<SceneObject> sceneObject = createObject(typeId, data);
addObject(sceneObject);
return sceneObject;
}
SharedPtr<SceneObject> Scene::addNewStaticObject(String typeId, SharedPtr<ObjectMap> data)
{
SharedPtr<SceneObject> sceneObject = createObject(typeId, data);
addStaticObject(sceneObject);
return sceneObject;
}
SharedPtr<SceneObject> Scene::createObject(String typeId, SharedPtr<ObjectMap> data)
{
ege_log.debug() << "Creating SceneObject " << typeId << ": " << (data ? data->toString() : "null");
auto& registry = getRegistry();
auto type = registry.getType(typeId);
if(!type)
{
ege_log.warning() << "Invalid SceneObjectType: " << typeId;
return nullptr;
}
SharedPtr<SceneObject> sceneObject = type->createEmptyObject(*this);
if(!sceneObject)
{
ege_log.error() << "Object refused creation!";
return nullptr;
}
sceneObject->setType(type);
if(!data)
return sceneObject;
if(!sceneObject->deserialize(data))
{
ege_log.error() << "Failed to deserialize SceneObject!";
return nullptr;
}
return sceneObject;
}
void Scene::rebuildLayers()
{
std::lock_guard<std::recursive_mutex> lock(m_objectsMutex);
m_objectsByLayer.clear();
for(auto& pr: m_staticObjects)
m_objectsByLayer.insert(std::make_pair(pr.second->getRenderLayer(), pr.second.get()));
for(auto& pr: m_objects)
m_objectsByLayer.insert(std::make_pair(pr.second->getRenderLayer(), pr.second.get()));
}
void Scene::forEachChildImpl(_ForEachChildCallbackBase& function)
{
for(auto& object: m_staticObjects)
function(*object.second);
for(auto& object: m_objects)
function(*object.second);
}
}
| 31.897019 | 148 | 0.613849 | [
"render",
"object",
"vector"
] |
1e8344de8d8c38d8a89a64362a046df70fe8bb7a | 829 | hpp | C++ | include/ant_colony_optimization.hpp | dmarcini/ACO-TSP | e433dbba2506486f41f4414f3d0c3244baf61333 | [
"MIT"
] | null | null | null | include/ant_colony_optimization.hpp | dmarcini/ACO-TSP | e433dbba2506486f41f4414f3d0c3244baf61333 | [
"MIT"
] | null | null | null | include/ant_colony_optimization.hpp | dmarcini/ACO-TSP | e433dbba2506486f41f4414f3d0c3244baf61333 | [
"MIT"
] | null | null | null | #ifndef ANT_COLONY_OPTIMIZATION_HPP_
#define ANT_COLONY_OPTIMIZATION_HPP_
#include <string>
#include <vector>
#include <functional>
#include "graph.hpp"
#include "ant.hpp"
using ACO = class AntColonyOptimization;
class AntColonyOptimization
{
public:
using LoadDataFcntPtr =
std::function<std::vector<std::vector<int>>(const std::string&)>;
void load_data(LoadDataFcntPtr load_data);
void enter_stop_criterium();
void enter_algorithm_parameters();
void start();
private:
void do_iteration();
void update_initial_pheromones_concentration();
void update_pheromones_concentration();
double get_double_parameter(std::string_view param);
int get_int_parameter(std::string_view param);
Graph graph_;
std::vector<Ant> ants_;
};
#endif // ANT_COLONY_OPTIMIZATION_HPP_
| 20.725 | 73 | 0.74427 | [
"vector"
] |
1e94130eece377ad08ce82cda461521ca5efa7c9 | 2,644 | cpp | C++ | src/lib/materials/textures/formats/png/PngLoader.cpp | Lut99/Rasterizer | 453864506db749a93fb82fb17cc5ee88cc4ada01 | [
"MIT"
] | 1 | 2021-08-15T19:20:14.000Z | 2021-08-15T19:20:14.000Z | src/lib/materials/textures/formats/png/PngLoader.cpp | Lut99/Rasterizer | 453864506db749a93fb82fb17cc5ee88cc4ada01 | [
"MIT"
] | 17 | 2021-06-05T12:37:04.000Z | 2021-10-01T10:20:09.000Z | src/lib/materials/textures/formats/png/PngLoader.cpp | Lut99/Rasterizer | 453864506db749a93fb82fb17cc5ee88cc4ada01 | [
"MIT"
] | null | null | null | /* PNG LOADER.cpp
* by Lut99
*
* Created:
* 16/08/2021, 12:22:16
* Last edited:
* 16/08/2021, 12:22:16
* Auto updated?
* Yes
*
* Description:
* Function that loads the given file as if it were a file in PNG-format.
**/
#include <vector>
#include "LodePNG.hpp"
#include "PngLoader.hpp"
using namespace std;
using namespace Makma3D;
using namespace Makma3D::Materials;
/***** CONSTANTS *****/
/* Channel name for the PngLoader function. */
static constexpr const char* channel = "PngLoader";
/***** LIBRARY FUNCTIONS *****/
/* Loads the file at the given path as a .png file, and returns a populated Image. */
Rendering::Image* Materials::load_png_texture(Rendering::MemoryManager& memory_manager, const std::string& path) {
// Try to load the given .png file with lodepng
std::vector<unsigned char> png;
unsigned error = lodepng::load_file(png, path);
if (error) {
logger.fatalc(channel, "Could not load '", path, "' as .png file: ", lodepng_error_text(error), " (error code ", error, ")");
}
// Decode the .png to raw image data
std::vector<unsigned char> image;
unsigned width, height;
error = lodepng::decode(image, width, height, png);
if (error) {
logger.fatalc(channel, "Could not decode '", path, "' as .png file: ", lodepng_error_text(error), " (error code ", std::to_string(error), ")");
}
// With the pixels in memory, allocate the Vulkan image
VkExtent2D texture_extent({ static_cast<uint32_t>(width), static_cast<uint32_t>(height) });
Rendering::Image* result = memory_manager.draw_pool.allocate(texture_extent, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
// Allocate a staging buffer
VkDeviceSize texture_size = 4 * texture_extent.width * texture_extent.height * sizeof(unsigned char);
Rendering::Buffer* stage = memory_manager.stage_pool.allocate(texture_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
void* stage_mem;
stage->map(&stage_mem);
// Copy the image to the stage buffer
memcpy(stage_mem, image.data(), texture_size);
stage->flush();
stage->unmap();
// Copy the stage memory to the image once its in the correct layout
Rendering::CommandBuffer* draw_cmd = memory_manager.draw_cmd_pool.allocate();
stage->copyto(result, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, draw_cmd, memory_manager.gpu.queues(Rendering::QueueType::graphics)[0]);
memory_manager.draw_cmd_pool.free(draw_cmd);
// Deallocate the staging buffer and we're done
memory_manager.stage_pool.free(stage);
return result;
}
| 35.253333 | 195 | 0.703858 | [
"vector"
] |
1e9a2fe135eecfc4e87d8b68a6f0695c598df863 | 631 | cpp | C++ | sort/quickSort.cpp | ctrlzhang/algorithm | 4db12ea6246b7bd6ac4ab9296de4e736f73a0bf0 | [
"Apache-2.0"
] | 1 | 2017-05-08T15:41:17.000Z | 2017-05-08T15:41:17.000Z | sort/quickSort.cpp | ctrlzhang/algorithm | 4db12ea6246b7bd6ac4ab9296de4e736f73a0bf0 | [
"Apache-2.0"
] | null | null | null | sort/quickSort.cpp | ctrlzhang/algorithm | 4db12ea6246b7bd6ac4ab9296de4e736f73a0bf0 | [
"Apache-2.0"
] | 2 | 2016-09-05T17:12:08.000Z | 2021-11-21T11:29:42.000Z | #include <iostream>
#include <vector>
using namespace std;
void output(vector<int>& v) {
for(vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout<<*it<<" ";
}
}
void quickSort(vector<int>& v, int s, int e) {
output(v);
cout<<endl;
int tmp = 0;
if(s >= e) return;
int i = s;
for(int k=s;k<=e;k++) {
if(v[k]<=v[e]) {
tmp = v[k];
v[k]=v[i];
v[i++]=tmp;
}
}
quickSort(v, s, i-2);
quickSort(v, i,e);
}
int main(int argc, char* argv[]) {
int a[] = {10, 4, 5, 2, 1, 19, 3, 5, 7};
vector<int> v(a, a+sizeof(a)/sizeof(int));
quickSort(v, 0, v.size()-1);
output(v);
cout<<endl;
return 0;
}
| 16.179487 | 65 | 0.530903 | [
"vector"
] |
1eacd0dd479bf89015841c813d4ca038a432d909 | 888 | cpp | C++ | project/src/app/ApplicationEvent.cpp | matthewswallace/lime | 43a6f0598cd3ba0998ce2d02441e3284999d1047 | [
"MIT"
] | 3 | 2018-05-04T18:06:07.000Z | 2018-05-07T12:30:43.000Z | project/src/app/ApplicationEvent.cpp | matthewswallace/lime | 43a6f0598cd3ba0998ce2d02441e3284999d1047 | [
"MIT"
] | 5 | 2018-03-28T13:38:03.000Z | 2019-05-13T15:33:26.000Z | project/src/app/ApplicationEvent.cpp | matthewswallace/lime | 43a6f0598cd3ba0998ce2d02441e3284999d1047 | [
"MIT"
] | 4 | 2016-09-18T03:58:34.000Z | 2020-09-16T06:28:50.000Z | #include <hx/CFFI.h>
#include <app/ApplicationEvent.h>
namespace lime {
AutoGCRoot* ApplicationEvent::callback = 0;
AutoGCRoot* ApplicationEvent::eventObject = 0;
static int id_deltaTime;
static int id_type;
static bool init = false;
ApplicationEvent::ApplicationEvent () {
deltaTime = 0;
type = UPDATE;
}
void ApplicationEvent::Dispatch (ApplicationEvent* event) {
if (ApplicationEvent::callback) {
if (!init) {
id_deltaTime = val_id ("deltaTime");
id_type = val_id ("type");
init = true;
}
value object = (ApplicationEvent::eventObject ? ApplicationEvent::eventObject->get () : alloc_empty_object ());
alloc_field (object, id_deltaTime, alloc_int (event->deltaTime));
alloc_field (object, id_type, alloc_int (event->type));
val_call0 (ApplicationEvent::callback->get ());
}
}
} | 18.5 | 114 | 0.657658 | [
"object"
] |
1eaee81a9298adc768eeca16a49a1e66a5b4be20 | 1,789 | cpp | C++ | faceDetect/pyfaceDetection/pyfaceDetection/demo.cpp | ForrestPi/FaceSolution | cf19b2916a8bf285e457903e8d202055b092fc73 | [
"MIT"
] | 1 | 2022-01-04T02:24:48.000Z | 2022-01-04T02:24:48.000Z | faceDetect/pyfaceDetection/pyfaceDetection/demo.cpp | ForrestPi/FaceSolution | cf19b2916a8bf285e457903e8d202055b092fc73 | [
"MIT"
] | null | null | null | faceDetect/pyfaceDetection/pyfaceDetection/demo.cpp | ForrestPi/FaceSolution | cf19b2916a8bf285e457903e8d202055b092fc73 | [
"MIT"
] | null | null | null |
//https://www.jianshu.com/p/5dc844002d72
#include <opencv2/opencv.hpp>
#include"ncnn_mtcnn_tld_so.hpp"
#include <stdio.h>
#include<pybind11/pybind11.h>
#include<pybind11/stl.h>
#include<pybind11/numpy.h>
#include"ndarray_converter.h"
using namespace cv;
using namespace std;
namespace py = pybind11;
class FaceTracker :private faceTrack
{
public:
FaceTracker() { faceTrack(); };
~FaceTracker() {};
public:
void trackerInit(const std::string& model_path, const int min_face) {
this->Init(model_path, min_face);
}
std::vector<int> trackerUpdate(cv::Mat& image) {
cv::Rect rect;
this->DetectFace(rect, image);
return vector<int>{rect.x, rect.y, rect.x + rect.width, rect.y + rect.height};
};
public:
std::string version = "v1.0.0";
};
#if 0
int main() {
cv::VideoCapture capture;
capture.open("./test.avi");
cv::Mat frame;
faceTrack tracker;
std::string modelPath = "./models";
int minFace = 40;
tracker.Init(modelPath, minFace);
while (capture.read(frame)) {
int q = cv::waitKey(1);
if (q == 27) break;
cv::Rect result;
double t1 = (double)getTickCount();
tracker.DetectFace(result, frame);
printf("total %gms\n", ((double)getTickCount() - t1) * 1000 / getTickFrequency());
printf("------------------\n");
rectangle(frame, result, Scalar(0, 0, 255), 2);
imshow("frame", frame);
// outputVideo << frame;
}
// outputVideo.release();
capture.release();
cv::destroyAllWindows();
return 0;
}
#endif // 0
#if 1
PYBIND11_MODULE(face_tracking_demo, m) {
NDArrayConverter::init_numpy();
py::class_<FaceTracker>(m, "FaceTracker")
.def(py::init<>())
.def("trackerInit", &FaceTracker::trackerInit, py::arg("model_path"), py::arg("min_face"))
.def("trackerUpdate", &FaceTracker::trackerUpdate, py::arg("img"));
}
#endif
| 20.563218 | 92 | 0.669648 | [
"vector"
] |
1eb6dc0a43a0527fead1f94e9651b73532b70374 | 524 | cpp | C++ | test_rvo/main.cpp | fantasialin/cpp_sandbox | c2b24c30871d1528e45c9c0c0d233d3e9f4dbd3e | [
"Apache-2.0"
] | null | null | null | test_rvo/main.cpp | fantasialin/cpp_sandbox | c2b24c30871d1528e45c9c0c0d233d3e9f4dbd3e | [
"Apache-2.0"
] | null | null | null | test_rvo/main.cpp | fantasialin/cpp_sandbox | c2b24c30871d1528e45c9c0c0d233d3e9f4dbd3e | [
"Apache-2.0"
] | null | null | null | #include <iostream>
int n = 0;
struct C {
explicit C(int) {}
C(const C&) { ++n; } // the copy constructor has a visible side effect
}; // it modifies an object with static storage duration
int main() {
C c1(42); // direct-initialization, calls C::C(int)
C c2 = C(42); // copy-initialization, calls C::C(const C&)
std::cout << "if below output is zero, then the copy elison works.\n";
std::cout << n << std::endl; // prints 0 if the copy was elided, 1 otherwise
}
| 30.823529 | 80 | 0.585878 | [
"object"
] |
363c051f0195893dbe3b197c8ac29315c88444f4 | 967 | hpp | C++ | src/triangle.hpp | lconn-dev/MinimalRT | a7485fb6ac6723b18fd92c881d96826320b643c4 | [
"MIT"
] | null | null | null | src/triangle.hpp | lconn-dev/MinimalRT | a7485fb6ac6723b18fd92c881d96826320b643c4 | [
"MIT"
] | null | null | null | src/triangle.hpp | lconn-dev/MinimalRT | a7485fb6ac6723b18fd92c881d96826320b643c4 | [
"MIT"
] | null | null | null | #pragma once
#include <glm/glm.hpp>
#include <glm/gtx/normal.hpp>
struct material {
glm::vec3 amb, diffuse, specular, specularColor;
float shine = 16.f;
material() : amb(0.f), diffuse(1.f), specular(1.f), specularColor(1.f){}
};
struct triangle {
glm::vec3 v0, v1, v2, n0, n1, n2;
material* mat = nullptr;
glm::vec3 getSurfNormal() {
return glm::triangleNormal(v0, v1, v2);
}
void applyModel(glm::mat4 const& mo) {
v0 = mo * glm::vec4(v0, 1.f);
v1 = mo * glm::vec4(v1, 1.f);
v2 = mo * glm::vec4(v2, 1.f);
}
triangle() :
v0(0.f), v1(0.f), v2(0.f),
n0(0.f), n1(0.f), n2(0.f) {}
triangle(std::vector<glm::vec3> const& face, material* matPtr, std::vector<glm::vec3> norms) : mat(matPtr) {
assert(face.size() == 3);
assert(norms.size() == 3);
v0 = face[0];
v1 = face[1];
v2 = face[2];
n0 = norms[0];
n1 = norms[1];
n2 = norms[2];
}
};
| 21.021739 | 111 | 0.535677 | [
"vector"
] |
36422f44da1add9dc2b909bf16c1b40750956c68 | 7,909 | cpp | C++ | openfpga/src/fabric/build_fabric_io_location_map.cpp | avesus/OpenFPGA | c1dab2168655d41eb59d4923156dabd253ffbd3e | [
"MIT"
] | 246 | 2020-12-03T08:49:29.000Z | 2022-03-28T21:19:55.000Z | openfpga/src/fabric/build_fabric_io_location_map.cpp | a-canela/OpenFPGA | 063c58b6cbe2e01aa5520ec43ec80ff064d7f228 | [
"MIT"
] | 261 | 2020-12-03T00:23:54.000Z | 2022-03-31T10:00:37.000Z | openfpga/src/fabric/build_fabric_io_location_map.cpp | a-canela/OpenFPGA | 063c58b6cbe2e01aa5520ec43ec80ff064d7f228 | [
"MIT"
] | 66 | 2020-12-12T09:05:53.000Z | 2022-03-28T07:51:41.000Z | /********************************************************************
* This file includes functions that are used to build the location
* map information for the top-level module of the FPGA fabric
* It helps OpenFPGA to link the I/O port index in top-level module
* to the VPR I/O mapping results
*******************************************************************/
#include <map>
#include <algorithm>
/* Headers from vtrutil library */
#include "vtr_assert.h"
#include "vtr_time.h"
#include "vtr_log.h"
/* Headers from vpr library */
#include "vpr_utils.h"
#include "openfpga_reserved_words.h"
#include "openfpga_naming.h"
#include "module_manager_utils.h"
#include "openfpga_device_grid_utils.h"
#include "build_fabric_io_location_map.h"
/* begin namespace openfpga */
namespace openfpga {
/********************************************************************
* Find all the GPIO ports in the grid module
* and cache their port/pin index in the top-level module
*******************************************************************/
IoLocationMap build_fabric_io_location_map(const ModuleManager& module_manager,
const DeviceGrid& grids) {
vtr::ScopedStartFinishTimer timer("Create I/O location mapping for top module");
IoLocationMap io_location_map;
std::map<std::string, size_t> io_counter;
/* Create the coordinate range for each side of FPGA fabric */
std::map<e_side, std::vector<vtr::Point<size_t>>> io_coordinates = generate_perimeter_grid_coordinates( grids);
/* Walk through all the grids on the perimeter, which are I/O grids */
for (const e_side& io_side : FPGA_SIDES_CLOCKWISE) {
for (const vtr::Point<size_t>& io_coordinate : io_coordinates[io_side]) {
/* Bypass EMPTY grid */
if (true == is_empty_type(grids[io_coordinate.x()][io_coordinate.y()].type)) {
continue;
}
/* Skip width or height > 1 tiles (mostly heterogeneous blocks) */
if ( (0 < grids[io_coordinate.x()][io_coordinate.y()].width_offset)
|| (0 < grids[io_coordinate.x()][io_coordinate.y()].height_offset)) {
continue;
}
t_physical_tile_type_ptr grid_type = grids[io_coordinate.x()][io_coordinate.y()].type;
/* Find the module name for this type of grid */
std::string grid_module_name_prefix(GRID_MODULE_NAME_PREFIX);
std::string grid_module_name = generate_grid_block_module_name(grid_module_name_prefix, std::string(grid_type->name), is_io_type(grid_type), io_side);
ModuleId grid_module = module_manager.find_module(grid_module_name);
VTR_ASSERT(true == module_manager.valid_module_id(grid_module));
/* Find all the GPIO ports in the grid module */
/* MUST DO: register in io location mapping!
* I/O location mapping is a critical look-up for testbench generators
* As we add the I/O grid instances to top module by following order:
* TOP -> RIGHT -> BOTTOM -> LEFT
* The I/O index will increase in this way as well.
* This organization I/O indices is also consistent to the way
* that GPIOs are wired in function connect_gpio_module()
*
* Note: if you change the GPIO function, you should update here as well!
*/
for (int z = 0; z < grids[io_coordinate.x()][io_coordinate.y()].type->capacity; ++z) {
for (const ModuleManager::e_module_port_type& module_io_port_type : MODULE_IO_PORT_TYPES) {
for (const ModulePortId& gpio_port_id : module_manager.module_port_ids_by_type(grid_module, module_io_port_type)) {
/* Only care mappable I/O */
if (false == module_manager.port_is_mappable_io(grid_module, gpio_port_id)) {
continue;
}
const BasicPort& gpio_port = module_manager.module_port(grid_module, gpio_port_id);
auto curr_io_index = io_counter.find(gpio_port.get_name());
/* Index always start from zero */
if (curr_io_index == io_counter.end()) {
io_counter[gpio_port.get_name()] = 0;
}
io_location_map.set_io_index(io_coordinate.x(), io_coordinate.y(), z,
gpio_port.get_name(),
io_counter[gpio_port.get_name()]);
io_counter[gpio_port.get_name()]++;
}
}
}
}
}
/* Walk through all the center grids, which may include I/O grids */
for (size_t ix = 1; ix < grids.width() - 1; ++ix) {
for (size_t iy = 1; iy < grids.height() - 1; ++iy) {
/* Bypass EMPTY grid */
if (true == is_empty_type(grids[ix][iy].type)) {
continue;
}
/* Skip width or height > 1 tiles (mostly heterogeneous blocks) */
if ( (0 < grids[ix][iy].width_offset)
|| (0 < grids[ix][iy].height_offset)) {
continue;
}
t_physical_tile_type_ptr grid_type = grids[ix][iy].type;
/* Find the module name for this type of grid */
std::string grid_module_name_prefix(GRID_MODULE_NAME_PREFIX);
std::string grid_module_name = generate_grid_block_module_name(grid_module_name_prefix, std::string(grid_type->name), is_io_type(grid_type), NUM_SIDES);
ModuleId grid_module = module_manager.find_module(grid_module_name);
VTR_ASSERT(true == module_manager.valid_module_id(grid_module));
/* Find all the GPIO ports in the grid module */
/* MUST DO: register in io location mapping!
* I/O location mapping is a critical look-up for testbench generators
* As we add the I/O grid instances to top module by following order:
* TOP -> RIGHT -> BOTTOM -> LEFT
* The I/O index will increase in this way as well.
* This organization I/O indices is also consistent to the way
* that GPIOs are wired in function connect_gpio_module()
*
* Note: if you change the GPIO function, you should update here as well!
*/
for (int z = 0; z < grids[ix][iy].type->capacity; ++z) {
for (const ModuleManager::e_module_port_type& module_io_port_type : MODULE_IO_PORT_TYPES) {
for (const ModulePortId& gpio_port_id : module_manager.module_port_ids_by_type(grid_module, module_io_port_type)) {
/* Only care mappable I/O */
if (false == module_manager.port_is_mappable_io(grid_module, gpio_port_id)) {
continue;
}
const BasicPort& gpio_port = module_manager.module_port(grid_module, gpio_port_id);
auto curr_io_index = io_counter.find(gpio_port.get_name());
/* Index always start from zero */
if (curr_io_index == io_counter.end()) {
io_counter[gpio_port.get_name()] = 0;
}
io_location_map.set_io_index(ix, iy, z,
gpio_port.get_name(),
io_counter[gpio_port.get_name()]);
io_counter[gpio_port.get_name()]++;
}
}
}
}
}
/* Check all the GPIO ports in the top-level module has been mapped */
std::string top_module_name = generate_fpga_top_module_name();
ModuleId top_module = module_manager.find_module(top_module_name);
VTR_ASSERT(true == module_manager.valid_module_id(top_module));
for (const ModuleManager::e_module_port_type& module_io_port_type : MODULE_IO_PORT_TYPES) {
for (const ModulePortId& gpio_port_id : module_manager.module_port_ids_by_type(top_module, module_io_port_type)) {
/* Only care mappable I/O */
if (false == module_manager.port_is_mappable_io(top_module, gpio_port_id)) {
continue;
}
const BasicPort& gpio_port = module_manager.module_port(top_module, gpio_port_id);
VTR_ASSERT(io_counter[gpio_port.get_name()] == gpio_port.get_width());
}
}
return io_location_map;
}
} /* end namespace openfpga */
| 43.456044 | 158 | 0.633329 | [
"vector"
] |
3645ada2f339588fcac7a64be391f145400ba15e | 6,986 | cc | C++ | asv_wave_sim_gazebo_plugins/src/Utilities.cc | minzlee/asv_wave_sim | d9426e1b7b75d43f0c1bd3201e6ba62e54af968f | [
"Apache-2.0"
] | 25 | 2019-05-29T04:55:19.000Z | 2022-03-18T19:07:07.000Z | asv_wave_sim_gazebo_plugins/src/Utilities.cc | minzlee/asv_wave_sim | d9426e1b7b75d43f0c1bd3201e6ba62e54af968f | [
"Apache-2.0"
] | 12 | 2019-02-14T16:26:57.000Z | 2022-03-30T19:44:33.000Z | asv_wave_sim_gazebo_plugins/src/Utilities.cc | minzlee/asv_wave_sim | d9426e1b7b75d43f0c1bd3201e6ba62e54af968f | [
"Apache-2.0"
] | 11 | 2019-05-29T04:55:22.000Z | 2022-02-23T11:55:32.000Z | // Copyright (C) 2019 Rhys Mainwaring
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "asv_wave_sim_gazebo_plugins/Utilities.hh"
#include "asv_wave_sim_gazebo_plugins/Convert.hh"
#include <gazebo/gazebo.hh>
#include <gazebo/common/common.hh>
#include <ignition/math/Vector3.hh>
#include <sdf/sdf.hh>
#include <algorithm>
#include <iostream>
#include <string>
namespace asv
{
///////////////////////////////////////////////////////////////////////////////
// Templates
// This code adapted vmrc/usv_gazebo_plugins/usv_gazebo_dynamics_plugin.cc
template <typename T>
T SdfParam(sdf::Element& _sdf, const std::string &_paramName, const T _defaultVal)
{
if (!_sdf.HasElement(_paramName))
{
gzmsg << "Parameter <" << _paramName << "> not found: "
<< "Using default value of <" << _defaultVal << ">." << std::endl;
return _defaultVal;
}
T val = _sdf.Get<T>(_paramName);
gzmsg << "Parameter found - setting <" << _paramName
<< "> to <" << val << ">." << std::endl;
return val;
}
/// \brief Template function for extracting a value from a parameter message.
template <typename T>
T MsgParamGetValue(const gazebo::msgs::Param& _msg)
{
gzwarn << "Using default template for MsgParamGetValue" << std::endl;
return T();
}
/// \brief Template specialization for extracting a bool from a parameter message.
template <>
bool MsgParamGetValue<bool>(const gazebo::msgs::Param& _msg)
{
auto paramValue = _msg.value();
return paramValue.bool_value();
}
/// \brief Template specialization for extracting an int from a parameter message.
template <>
int MsgParamGetValue<int>(const gazebo::msgs::Param& _msg)
{
auto paramValue = _msg.value();
return paramValue.int_value();
}
/// \brief Template specialization for extracting a size_t from a parameter message.
template <>
size_t MsgParamGetValue<size_t>(const gazebo::msgs::Param& _msg)
{
auto paramValue = _msg.value();
return paramValue.int_value();
}
/// \brief Template specialization for extracting a double from a parameter message.
template <>
double MsgParamGetValue<double>(const gazebo::msgs::Param& _msg)
{
auto paramValue = _msg.value();
return paramValue.double_value();
}
/// \brief Template specialization for extracting a string from a parameter message.
template <>
std::string MsgParamGetValue<std::string>(const gazebo::msgs::Param& _msg)
{
auto paramValue = _msg.value();
return paramValue.string_value();
}
/// \brief Template specialization for extracting a Vector2 from a parameter message.
template <>
Vector2 MsgParamGetValue<Vector2>(const gazebo::msgs::Param& _msg)
{
auto paramValue = _msg.value();
auto vec = paramValue.vector3d_value();
return Vector2(vec.x(), vec.y());
}
/// \brief Template specialization for extracting a Vector3 from a parameter message.
template <>
Vector3 MsgParamGetValue<Vector3>(const gazebo::msgs::Param& _msg)
{
auto paramValue = _msg.value();
auto vec = paramValue.vector3d_value();
return Vector3(vec.x(), vec.y(), vec.z());
}
/// \brief Template for extracting a named parameter from a parameter vector message.
template <typename T>
T MsgParam(const gazebo::msgs::Param_V& _msg, const std::string &_paramName, const T _defaultVal)
{
// Custom compare for params
auto compare = [=](auto& _param)
{
return _param.name() == _paramName;
};
auto it = std::find_if(std::begin(_msg.param()), std::end(_msg.param()), compare);
// Not found
if (it == std::end(_msg.param()))
{
// @DEBUG_INFO
// gzmsg << "Parameter <" << _paramName << "> not found: "
// << "Using default value of <" << _defaultVal << ">." << std::endl;
return _defaultVal;
}
// Found
auto& param = *it;
T val = MsgParamGetValue<T>(param);
// @DEBUG_INFO
// gzmsg << "Parameter found - setting <" << _paramName
// << "> to <" << val << ">." << std::endl;
return val;
}
///////////////////////////////////////////////////////////////////////////////
// Utilities
bool Utilities::SdfParamBool(sdf::Element& _sdf,
const std::string& _paramName, const bool _defaultVal)
{
return SdfParam<bool>(_sdf, _paramName, _defaultVal);
}
size_t Utilities::SdfParamSizeT(sdf::Element& _sdf,
const std::string& _paramName, const size_t _defaultVal)
{
return SdfParam<double>(_sdf, _paramName, _defaultVal);
}
double Utilities::SdfParamDouble(sdf::Element& _sdf,
const std::string& _paramName, const double _defaultVal)
{
return SdfParam<double>(_sdf, _paramName, _defaultVal);
}
std::string Utilities::SdfParamString(sdf::Element& _sdf,
const std::string& _paramName, const std::string _defaultVal)
{
return SdfParam<std::string>(_sdf, _paramName, _defaultVal);
}
Vector2 Utilities::SdfParamVector2(sdf::Element& _sdf,
const std::string& _paramName, const Vector2 _defaultVal)
{
return ToVector2(SdfParam<ignition::math::Vector2d>(
_sdf, _paramName, ToIgn(_defaultVal)));
}
Vector3 Utilities::SdfParamVector3(sdf::Element& _sdf,
const std::string& _paramName, const Vector3 _defaultVal)
{
return ToVector3(SdfParam<ignition::math::Vector3d>(
_sdf, _paramName, ToIgn(_defaultVal)));
}
bool Utilities::MsgParamBool(const gazebo::msgs::Param_V& _msg,
const std::string &_paramName, const bool _defaultVal)
{
return MsgParam<bool>(_msg, _paramName, _defaultVal);
}
size_t Utilities::MsgParamSizeT(const gazebo::msgs::Param_V& _msg,
const std::string &_paramName, const size_t _defaultVal)
{
return MsgParam<size_t>(_msg, _paramName, _defaultVal);
}
double Utilities::MsgParamDouble(const gazebo::msgs::Param_V& _msg,
const std::string &_paramName, const double _defaultVal)
{
return MsgParam<double>(_msg, _paramName, _defaultVal);
}
std::string Utilities::MsgParamString(const gazebo::msgs::Param_V& _msg,
const std::string &_paramName, const std::string _defaultVal)
{
return MsgParam<std::string>(_msg, _paramName, _defaultVal);
}
Vector2 Utilities::MsgParamVector2(const gazebo::msgs::Param_V& _msg,
const std::string &_paramName, const Vector2 _defaultVal)
{
return MsgParam<Vector2>(_msg, _paramName, _defaultVal);
}
Vector3 Utilities::MsgParamVector3(const gazebo::msgs::Param_V& _msg,
const std::string &_paramName, const Vector3 _defaultVal)
{
return MsgParam<Vector3>(_msg, _paramName, _defaultVal);
}
///////////////////////////////////////////////////////////////////////////////
} // namespace asv
| 30.112069 | 97 | 0.695248 | [
"vector"
] |
36466194838e312b68f1c10c0cf9216100a721d8 | 15,444 | cc | C++ | test/buffer_manager_test.cc | AhmetTanakol/btree | eaa74f400e059e7d1d908006e198961cb04c1393 | [
"MIT"
] | 1 | 2022-01-10T00:25:19.000Z | 2022-01-10T00:25:19.000Z | test/buffer_manager_test.cc | AhmetTanakol/buffer-manager | 570c26a7ba11907e6ec0c730e90bfd2e3231df05 | [
"MIT"
] | null | null | null | test/buffer_manager_test.cc | AhmetTanakol/buffer-manager | 570c26a7ba11907e6ec0c730e90bfd2e3231df05 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <atomic>
#include <cstring>
#include <memory>
#include <random>
#include <thread>
#include <vector>
#include <gtest/gtest.h>
#include "moderndbs/buffer_manager.h"
namespace {
// NOLINTNEXTLINE
TEST(BufferManagerTest, FixSingle) {
moderndbs::BufferManager buffer_manager{1024, 10};
std::vector<uint64_t> expected_values(1024 / sizeof(uint64_t), 123);
{
auto& page = buffer_manager.fix_page(1, true);
std::memcpy(page.get_data(), expected_values.data(), 1024);
buffer_manager.unfix_page(page, true);
EXPECT_EQ(std::vector<uint64_t>{1}, buffer_manager.get_fifo_list());
EXPECT_TRUE(buffer_manager.get_lru_list().empty());
}
{
std::vector<uint64_t> values(1024 / sizeof(uint64_t));
auto& page = buffer_manager.fix_page(1, false);
std::memcpy(values.data(), page.get_data(), 1024);
buffer_manager.unfix_page(page, true);
EXPECT_TRUE(buffer_manager.get_fifo_list().empty());
EXPECT_EQ(std::vector<uint64_t>{1}, buffer_manager.get_lru_list());
ASSERT_EQ(expected_values, values);
}
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, PersistentRestart) {
auto buffer_manager = std::make_unique<moderndbs::BufferManager>(1024, 10);
for (uint16_t segment = 0; segment < 3; ++segment) {
for (uint64_t segment_page = 0; segment_page < 10; ++segment_page) {
uint64_t page_id = (static_cast<uint64_t>(segment) << 48) | segment_page;
auto& page = buffer_manager->fix_page(page_id, true);
uint64_t& value = *reinterpret_cast<uint64_t*>(page.get_data());
value = segment * 10 + segment_page;
buffer_manager->unfix_page(page, true);
}
}
// Destroy the buffer manager and create a new one.
buffer_manager = std::make_unique<moderndbs::BufferManager>(1024, 10);
for (uint16_t segment = 0; segment < 3; ++segment) {
for (uint64_t segment_page = 0; segment_page < 10; ++segment_page) {
uint64_t page_id = (static_cast<uint64_t>(segment) << 48) | segment_page;
auto& page = buffer_manager->fix_page(page_id, false);
uint64_t value = *reinterpret_cast<uint64_t*>(page.get_data());
buffer_manager->unfix_page(page, false);
EXPECT_EQ(segment * 10 + segment_page, value);
}
}
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, FIFOEvict) {
moderndbs::BufferManager buffer_manager{1024, 10};
for (uint64_t i = 1; i < 11; ++i) {
auto& page = buffer_manager.fix_page(i, false);
buffer_manager.unfix_page(page, false);
}
{
std::vector<uint64_t> expected_fifo{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
EXPECT_EQ(expected_fifo, buffer_manager.get_fifo_list());
EXPECT_TRUE(buffer_manager.get_lru_list().empty());
}
{
auto& page = buffer_manager.fix_page(11, false);
buffer_manager.unfix_page(page, false);
}
{
std::vector<uint64_t> expected_fifo{2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
EXPECT_EQ(expected_fifo, buffer_manager.get_fifo_list());
EXPECT_TRUE(buffer_manager.get_lru_list().empty());
}
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, BufferFull) {
moderndbs::BufferManager buffer_manager{1024, 10};
std::vector<moderndbs::BufferFrame*> pages;
pages.reserve(10);
for (uint64_t i = 1; i < 11; ++i) {
auto& page = buffer_manager.fix_page(i, false);
pages.push_back(&page);
}
EXPECT_THROW(buffer_manager.fix_page(11, false), moderndbs::buffer_full_error);
for (auto* page : pages) {
buffer_manager.unfix_page(*page, false);
}
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, MoveToLRU) {
moderndbs::BufferManager buffer_manager{1024, 10};
auto& fifo_page = buffer_manager.fix_page(1, false);
auto* lru_page = &buffer_manager.fix_page(2, false);
buffer_manager.unfix_page(fifo_page, false);
buffer_manager.unfix_page(*lru_page, false);
EXPECT_EQ((std::vector<uint64_t>{1, 2}), buffer_manager.get_fifo_list());
EXPECT_TRUE(buffer_manager.get_lru_list().empty());
lru_page = &buffer_manager.fix_page(2, false);
buffer_manager.unfix_page(*lru_page, false);
EXPECT_EQ(std::vector<uint64_t>{1}, buffer_manager.get_fifo_list());
EXPECT_EQ(std::vector<uint64_t>{2}, buffer_manager.get_lru_list());
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, LRURefresh) {
moderndbs::BufferManager buffer_manager{1024, 10};
auto* page1 = &buffer_manager.fix_page(1, false);
buffer_manager.unfix_page(*page1, false);
page1 = &buffer_manager.fix_page(1, false);
buffer_manager.unfix_page(*page1, false);
auto* page2 = &buffer_manager.fix_page(2, false);
buffer_manager.unfix_page(*page2, false);
page2 = &buffer_manager.fix_page(2, false);
buffer_manager.unfix_page(*page2, false);
EXPECT_TRUE(buffer_manager.get_fifo_list().empty());
EXPECT_EQ((std::vector<uint64_t>{1, 2}), buffer_manager.get_lru_list());
page1 = &buffer_manager.fix_page(1, false);
buffer_manager.unfix_page(*page1, false);
EXPECT_TRUE(buffer_manager.get_fifo_list().empty());
EXPECT_EQ((std::vector<uint64_t>{2, 1}), buffer_manager.get_lru_list());
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, MultithreadParallelFix) {
moderndbs::BufferManager buffer_manager{1024, 10};
std::vector<std::thread> threads;
for (size_t i = 0; i < 4; ++i) {
threads.emplace_back([i, &buffer_manager] {
auto& page1 = buffer_manager.fix_page(i, false);
auto& page2 = buffer_manager.fix_page(i + 4, false);
buffer_manager.unfix_page(page1, false);
buffer_manager.unfix_page(page2, false);
});
}
for (auto& thread : threads) {
thread.join();
}
auto fifo_list = buffer_manager.get_fifo_list();
std::sort(fifo_list.begin(), fifo_list.end());
std::vector<uint64_t> expected_fifo{0, 1, 2, 3, 4, 5, 6, 7};
EXPECT_EQ(expected_fifo, fifo_list);
EXPECT_TRUE(buffer_manager.get_lru_list().empty());
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, MultithreadExclusiveAccess) {
moderndbs::BufferManager buffer_manager{1024, 10};
{
auto& page = buffer_manager.fix_page(0, true);
std::memset(page.get_data(), 0, 1024);
buffer_manager.unfix_page(page, true);
}
std::vector<std::thread> threads;
for (size_t i = 0; i < 4; ++i) {
threads.emplace_back([&buffer_manager] {
for (size_t j = 0; j < 1000; ++j) {
auto& page = buffer_manager.fix_page(0, true);
uint64_t& value = *reinterpret_cast<uint64_t*>(page.get_data());
++value;
buffer_manager.unfix_page(page, true);
}
});
}
for (auto& thread : threads) {
thread.join();
}
EXPECT_TRUE(buffer_manager.get_fifo_list().empty());
EXPECT_EQ(std::vector<uint64_t>{0}, buffer_manager.get_lru_list());
auto& page = buffer_manager.fix_page(0, false);
uint64_t value = *reinterpret_cast<uint64_t*>(page.get_data());
buffer_manager.unfix_page(page, false);
EXPECT_EQ(4000, value);
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, MultithreadBufferFull) {
moderndbs::BufferManager buffer_manager{1024, 10};
std::atomic<uint64_t> num_buffer_full = 0;
std::atomic<uint64_t> finished_threads = 0;
std::vector<std::thread> threads;
for (size_t i = 0; i < 4; ++i) {
threads.emplace_back([i, &buffer_manager, &num_buffer_full, &finished_threads] {
std::vector<moderndbs::BufferFrame*> pages;
pages.reserve(4);
for (size_t j = 0; j < 4; ++j) {
try {
pages.push_back(&buffer_manager.fix_page(i + j * 4, false));
} catch (const moderndbs::buffer_full_error&) {
++num_buffer_full;
}
}
++finished_threads;
// Busy wait until all threads have finished.
while (finished_threads.load() < 4) {}
for (auto* page : pages) {
buffer_manager.unfix_page(*page, false);
}
});
}
for (auto& thread : threads) {
thread.join();
}
EXPECT_EQ(10, buffer_manager.get_fifo_list().size());
EXPECT_TRUE(buffer_manager.get_lru_list().empty());
EXPECT_EQ(6, num_buffer_full.load());
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, MultithreadManyPages) {
moderndbs::BufferManager buffer_manager{1024, 10};
std::vector<std::thread> threads;
for (size_t i = 0; i < 4; ++i) {
threads.emplace_back([i, &buffer_manager] {
std::mt19937_64 engine{i};
std::geometric_distribution<uint64_t> distr{0.1};
for (size_t j = 0; j < 10000; ++j) {
auto& page = buffer_manager.fix_page(distr(engine), false);
buffer_manager.unfix_page(page, false);
}
});
}
for (auto& thread : threads) {
thread.join();
}
}
// NOLINTNEXTLINE
TEST(BufferManagerTest, MultithreadReaderWriter) {
{
// Zero out all pages first
moderndbs::BufferManager buffer_manager{1024, 10};
for (uint16_t segment = 0; segment <= 3; ++segment) {
for (uint64_t segment_page = 0; segment_page <= 100; ++segment_page) {
uint64_t page_id = (static_cast<uint64_t>(segment) << 48) | segment_page;
auto& page = buffer_manager.fix_page(page_id, true);
std::memset(page.get_data(), 0, 1024);
buffer_manager.unfix_page(page, true);
}
}
// Let the buffer manager be destroyed here so that the caches are
// empty before running the actual test.
}
moderndbs::BufferManager buffer_manager{1024, 10};
std::atomic<size_t> aborts = 0;
std::vector<std::thread> threads;
for (size_t i = 0; i < 4; ++i) {
threads.emplace_back([i, &buffer_manager, &aborts] {
std::mt19937_64 engine{i};
// 5% of queries are scans.
std::bernoulli_distribution scan_distr{0.05};
// Number of pages accessed by a point query is geometrically
// distributed.
std::geometric_distribution<size_t> num_pages_distr{0.5};
// 60% of point queries are reads.
std::bernoulli_distribution reads_distr{0.6};
// Out of 20 accesses, 12 are from segment 0, 5 from segment 1,
// 2 from segment 2, and 1 from segment 3.
std::discrete_distribution<uint16_t> segment_distr{12.0, 5.0, 2.0, 1.0};
// Page accesses for point queries are uniformly distributed in
// [0, 100].
std::uniform_int_distribution<uint64_t> page_distr{0, 100};
std::vector<uint64_t> scan_sums(4);
for (size_t j = 0; j < 100; ++j) {
uint16_t segment = segment_distr(engine);
uint64_t segment_shift = static_cast<uint64_t>(segment) << 48;
if (scan_distr(engine)) {
// scan
uint64_t scan_sum = 0;
for (uint64_t segment_page = 0; segment_page <= 100; ++segment_page) {
uint64_t page_id = segment_shift | segment_page;
moderndbs::BufferFrame* page;
while (true) {
try {
page = &buffer_manager.fix_page(page_id, false);
break;
} catch (const moderndbs::buffer_full_error&) {
// Don't abort scan when the buffer is full, retry
// the current page.
}
}
uint64_t value = *reinterpret_cast<uint64_t*>(page->get_data());
scan_sum += value;
buffer_manager.unfix_page(*page, false);
}
EXPECT_GE(scan_sum, scan_sums[segment]);
scan_sums[segment] = scan_sum;
} else {
// point query
auto num_pages = num_pages_distr(engine) + 1;
// For point queries all accesses but the last are always
// reads. Only the last is potentially a write. Also,
// all pages but the last are held for the entire duration
// of the query.
std::vector<moderndbs::BufferFrame*> pages;
auto unfix_pages = [&] {
for (auto it = pages.rbegin(); it != pages.rend(); ++it) {
auto& page = **it;
buffer_manager.unfix_page(page, false);
}
pages.clear();
};
for (size_t page_number = 0; page_number < num_pages - 1; ++page_number) {
uint64_t segment_page = page_distr(engine);
uint64_t page_id = segment_shift | segment_page;
moderndbs::BufferFrame* page;
try {
page = &buffer_manager.fix_page(page_id, false);
} catch (const moderndbs::buffer_full_error&) {
// Abort query when buffer is full.
++aborts;
goto abort;
}
pages.push_back(page);
}
// Unfix all pages before accessing the last one
// (potentially exclusively) to avoid deadlocks.
unfix_pages();
{
uint64_t segment_page = page_distr(engine);
uint64_t page_id = segment_shift | segment_page;
if (reads_distr(engine)) {
// read
moderndbs::BufferFrame* page;
try {
page = &buffer_manager.fix_page(page_id, false);
} catch (const moderndbs::buffer_full_error&) {
++aborts;
goto abort;
}
buffer_manager.unfix_page(*page, false);
} else {
// write
moderndbs::BufferFrame* page;
try {
page = &buffer_manager.fix_page(page_id, true);
} catch (const moderndbs::buffer_full_error&) {
++aborts;
goto abort;
}
auto& value = *reinterpret_cast<uint64_t*>(page->get_data());
++value;
buffer_manager.unfix_page(*page, true);
}
}
abort:
unfix_pages();
}
}
});
}
for (auto& thread : threads) {
thread.join();
}
EXPECT_LT(aborts.load(), 20);
}
} // namespace
| 40.857143 | 94 | 0.560153 | [
"vector"
] |
364be4a4dddc24a04a12ac5e3e099336596138eb | 16,901 | cpp | C++ | c/Haxe/OpenFL/01.HelloWorld/Export/windows/cpp/obj/src/openfl/geom/Transform.cpp | amenoyoya/old-project | 640ec696af5d18267d86629098f41451857f8103 | [
"MIT"
] | null | null | null | c/Haxe/OpenFL/01.HelloWorld/Export/windows/cpp/obj/src/openfl/geom/Transform.cpp | amenoyoya/old-project | 640ec696af5d18267d86629098f41451857f8103 | [
"MIT"
] | 1 | 2019-07-07T09:52:20.000Z | 2019-07-07T09:52:20.000Z | c/Haxe/OpenFL/01.HelloWorld/Export/windows/cpp/obj/src/openfl/geom/Transform.cpp | amenoyoya/old-project | 640ec696af5d18267d86629098f41451857f8103 | [
"MIT"
] | null | null | null | #include <hxcpp.h>
#ifndef INCLUDED_hxMath
#include <hxMath.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObject
#include <openfl/display/DisplayObject.h>
#endif
#ifndef INCLUDED_openfl_display_IBitmapDrawable
#include <openfl/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_openfl_events_EventDispatcher
#include <openfl/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_IEventDispatcher
#include <openfl/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_geom_ColorTransform
#include <openfl/geom/ColorTransform.h>
#endif
#ifndef INCLUDED_openfl_geom_Matrix
#include <openfl/geom/Matrix.h>
#endif
#ifndef INCLUDED_openfl_geom_Matrix3D
#include <openfl/geom/Matrix3D.h>
#endif
#ifndef INCLUDED_openfl_geom_Rectangle
#include <openfl/geom/Rectangle.h>
#endif
#ifndef INCLUDED_openfl_geom_Transform
#include <openfl/geom/Transform.h>
#endif
namespace openfl{
namespace geom{
Void Transform_obj::__construct(::openfl::display::DisplayObject displayObject)
{
HX_STACK_FRAME("openfl.geom.Transform","new",0x993cc92a,"openfl.geom.Transform.new","openfl/geom/Transform.hx",134,0xf4f475e6)
HX_STACK_THIS(this)
HX_STACK_ARG(displayObject,"displayObject")
{
HX_STACK_LINE(136)
::openfl::geom::ColorTransform _g = ::openfl::geom::ColorTransform_obj::__new(null(),null(),null(),null(),null(),null(),null(),null()); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(136)
this->__colorTransform = _g;
HX_STACK_LINE(137)
::openfl::geom::ColorTransform _g1 = ::openfl::geom::ColorTransform_obj::__new(null(),null(),null(),null(),null(),null(),null(),null()); HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(137)
this->concatenatedColorTransform = _g1;
HX_STACK_LINE(138)
::openfl::geom::Matrix _g2 = ::openfl::geom::Matrix_obj::__new(null(),null(),null(),null(),null(),null()); HX_STACK_VAR(_g2,"_g2");
HX_STACK_LINE(138)
this->concatenatedMatrix = _g2;
HX_STACK_LINE(139)
::openfl::geom::Rectangle _g3 = ::openfl::geom::Rectangle_obj::__new(null(),null(),null(),null()); HX_STACK_VAR(_g3,"_g3");
HX_STACK_LINE(139)
this->pixelBounds = _g3;
HX_STACK_LINE(141)
this->__displayObject = displayObject;
HX_STACK_LINE(142)
this->__hasMatrix = true;
}
;
return null();
}
//Transform_obj::~Transform_obj() { }
Dynamic Transform_obj::__CreateEmpty() { return new Transform_obj; }
hx::ObjectPtr< Transform_obj > Transform_obj::__new(::openfl::display::DisplayObject displayObject)
{ hx::ObjectPtr< Transform_obj > result = new Transform_obj();
result->__construct(displayObject);
return result;}
Dynamic Transform_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< Transform_obj > result = new Transform_obj();
result->__construct(inArgs[0]);
return result;}
::openfl::geom::ColorTransform Transform_obj::get_colorTransform( ){
HX_STACK_FRAME("openfl.geom.Transform","get_colorTransform",0xc8c832c8,"openfl.geom.Transform.get_colorTransform","openfl/geom/Transform.hx",156,0xf4f475e6)
HX_STACK_THIS(this)
HX_STACK_LINE(156)
return this->__colorTransform;
}
HX_DEFINE_DYNAMIC_FUNC0(Transform_obj,get_colorTransform,return )
::openfl::geom::ColorTransform Transform_obj::set_colorTransform( ::openfl::geom::ColorTransform value){
HX_STACK_FRAME("openfl.geom.Transform","set_colorTransform",0xa577653c,"openfl.geom.Transform.set_colorTransform","openfl/geom/Transform.hx",161,0xf4f475e6)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(163)
this->__colorTransform = value;
HX_STACK_LINE(165)
if (((value != null()))){
HX_STACK_LINE(167)
this->__displayObject->set_alpha(value->alphaMultiplier);
}
HX_STACK_LINE(171)
return this->__colorTransform;
}
HX_DEFINE_DYNAMIC_FUNC1(Transform_obj,set_colorTransform,return )
::openfl::geom::Matrix Transform_obj::get_matrix( ){
HX_STACK_FRAME("openfl.geom.Transform","get_matrix",0x80c3ba80,"openfl.geom.Transform.get_matrix","openfl/geom/Transform.hx",176,0xf4f475e6)
HX_STACK_THIS(this)
HX_STACK_LINE(178)
if ((this->__hasMatrix)){
HX_STACK_LINE(180)
::openfl::geom::Matrix matrix = ::openfl::geom::Matrix_obj::__new(null(),null(),null(),null(),null(),null()); HX_STACK_VAR(matrix,"matrix");
HX_STACK_LINE(181)
Float _g = this->__displayObject->get_scaleX(); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(181)
Float _g1 = this->__displayObject->get_scaleY(); HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(181)
matrix->scale(_g,_g1);
HX_STACK_LINE(182)
Float _g2 = this->__displayObject->get_rotation(); HX_STACK_VAR(_g2,"_g2");
HX_STACK_LINE(182)
Float _g3 = (_g2 * ((Float(::Math_obj::PI) / Float((int)180)))); HX_STACK_VAR(_g3,"_g3");
HX_STACK_LINE(182)
matrix->rotate(_g3);
HX_STACK_LINE(183)
Float _g4 = this->__displayObject->get_x(); HX_STACK_VAR(_g4,"_g4");
HX_STACK_LINE(183)
Float _g5 = this->__displayObject->get_y(); HX_STACK_VAR(_g5,"_g5");
HX_STACK_LINE(183)
matrix->translate(_g4,_g5);
HX_STACK_LINE(184)
return matrix;
}
HX_STACK_LINE(188)
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(Transform_obj,get_matrix,return )
::openfl::geom::Matrix Transform_obj::set_matrix( ::openfl::geom::Matrix value){
HX_STACK_FRAME("openfl.geom.Transform","set_matrix",0x844158f4,"openfl.geom.Transform.set_matrix","openfl/geom/Transform.hx",193,0xf4f475e6)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(195)
if (((value == null()))){
HX_STACK_LINE(197)
this->__hasMatrix = false;
HX_STACK_LINE(198)
return null();
}
HX_STACK_LINE(202)
this->__hasMatrix = true;
HX_STACK_LINE(203)
this->__hasMatrix3D = false;
HX_STACK_LINE(205)
if (((this->__displayObject != null()))){
HX_STACK_LINE(207)
this->__displayObject->set_x(value->tx);
HX_STACK_LINE(208)
this->__displayObject->set_y(value->ty);
HX_STACK_LINE(209)
Float _g = ::Math_obj::sqrt(((value->a * value->a) + (value->b * value->b))); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(209)
this->__displayObject->set_scaleX(_g);
HX_STACK_LINE(210)
Float _g1 = ::Math_obj::sqrt(((value->c * value->c) + (value->d * value->d))); HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(210)
this->__displayObject->set_scaleY(_g1);
HX_STACK_LINE(211)
Float _g2 = ::Math_obj::atan2(value->b,value->a); HX_STACK_VAR(_g2,"_g2");
HX_STACK_LINE(211)
Float _g3 = (_g2 * ((Float((int)180) / Float(::Math_obj::PI)))); HX_STACK_VAR(_g3,"_g3");
HX_STACK_LINE(211)
this->__displayObject->set_rotation(_g3);
}
HX_STACK_LINE(215)
return value;
}
HX_DEFINE_DYNAMIC_FUNC1(Transform_obj,set_matrix,return )
::openfl::geom::Matrix3D Transform_obj::get_matrix3D( ){
HX_STACK_FRAME("openfl.geom.Transform","get_matrix3D",0x05078731,"openfl.geom.Transform.get_matrix3D","openfl/geom/Transform.hx",220,0xf4f475e6)
HX_STACK_THIS(this)
HX_STACK_LINE(222)
if ((this->__hasMatrix3D)){
HX_STACK_LINE(224)
::openfl::geom::Matrix matrix = ::openfl::geom::Matrix_obj::__new(null(),null(),null(),null(),null(),null()); HX_STACK_VAR(matrix,"matrix");
HX_STACK_LINE(225)
Float _g = this->__displayObject->get_scaleX(); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(225)
Float _g1 = this->__displayObject->get_scaleY(); HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(225)
matrix->scale(_g,_g1);
HX_STACK_LINE(226)
Float _g2 = this->__displayObject->get_rotation(); HX_STACK_VAR(_g2,"_g2");
HX_STACK_LINE(226)
Float _g3 = (_g2 * ((Float(::Math_obj::PI) / Float((int)180)))); HX_STACK_VAR(_g3,"_g3");
HX_STACK_LINE(226)
matrix->rotate(_g3);
HX_STACK_LINE(227)
Float _g4 = this->__displayObject->get_x(); HX_STACK_VAR(_g4,"_g4");
HX_STACK_LINE(227)
Float _g5 = this->__displayObject->get_y(); HX_STACK_VAR(_g5,"_g5");
HX_STACK_LINE(227)
matrix->translate(_g4,_g5);
HX_STACK_LINE(229)
return ::openfl::geom::Matrix3D_obj::__new(Array_obj< Float >::__new().Add(matrix->a).Add(matrix->b).Add(0.0).Add(0.0).Add(matrix->c).Add(matrix->d).Add(0.0).Add(0.0).Add(0.0).Add(0.0).Add(1.0).Add(0.0).Add(matrix->tx).Add(matrix->ty).Add(0.0).Add(1.0));
}
HX_STACK_LINE(233)
return null();
}
HX_DEFINE_DYNAMIC_FUNC0(Transform_obj,get_matrix3D,return )
::openfl::geom::Matrix3D Transform_obj::set_matrix3D( ::openfl::geom::Matrix3D value){
HX_STACK_FRAME("openfl.geom.Transform","set_matrix3D",0x1a00aaa5,"openfl.geom.Transform.set_matrix3D","openfl/geom/Transform.hx",238,0xf4f475e6)
HX_STACK_THIS(this)
HX_STACK_ARG(value,"value")
HX_STACK_LINE(240)
if (((value == null()))){
HX_STACK_LINE(242)
this->__hasMatrix3D = false;
HX_STACK_LINE(243)
return null();
}
HX_STACK_LINE(247)
this->__hasMatrix = false;
HX_STACK_LINE(248)
this->__hasMatrix3D = true;
HX_STACK_LINE(250)
if (((this->__displayObject != null()))){
HX_STACK_LINE(252)
this->__displayObject->set_x(value->rawData->__get((int)12));
HX_STACK_LINE(253)
this->__displayObject->set_y(value->rawData->__get((int)13));
HX_STACK_LINE(254)
Float _g = ::Math_obj::sqrt(((value->rawData->__get((int)0) * value->rawData->__get((int)0)) + (value->rawData->__get((int)1) * value->rawData->__get((int)1)))); HX_STACK_VAR(_g,"_g");
HX_STACK_LINE(254)
this->__displayObject->set_scaleX(_g);
HX_STACK_LINE(255)
Float _g1 = ::Math_obj::sqrt(((value->rawData->__get((int)4) * value->rawData->__get((int)4)) + (value->rawData->__get((int)5) * value->rawData->__get((int)5)))); HX_STACK_VAR(_g1,"_g1");
HX_STACK_LINE(255)
this->__displayObject->set_scaleY(_g1);
HX_STACK_LINE(256)
Float _g2 = ::Math_obj::atan2(value->rawData->__get((int)1),value->rawData->__get((int)0)); HX_STACK_VAR(_g2,"_g2");
HX_STACK_LINE(256)
Float _g3 = (_g2 * ((Float((int)180) / Float(::Math_obj::PI)))); HX_STACK_VAR(_g3,"_g3");
HX_STACK_LINE(256)
this->__displayObject->set_rotation(_g3);
}
HX_STACK_LINE(260)
return value;
}
HX_DEFINE_DYNAMIC_FUNC1(Transform_obj,set_matrix3D,return )
Transform_obj::Transform_obj()
{
}
void Transform_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(Transform);
HX_MARK_MEMBER_NAME(concatenatedColorTransform,"concatenatedColorTransform");
HX_MARK_MEMBER_NAME(concatenatedMatrix,"concatenatedMatrix");
HX_MARK_MEMBER_NAME(pixelBounds,"pixelBounds");
HX_MARK_MEMBER_NAME(__colorTransform,"__colorTransform");
HX_MARK_MEMBER_NAME(__displayObject,"__displayObject");
HX_MARK_MEMBER_NAME(__hasMatrix,"__hasMatrix");
HX_MARK_MEMBER_NAME(__hasMatrix3D,"__hasMatrix3D");
HX_MARK_END_CLASS();
}
void Transform_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(concatenatedColorTransform,"concatenatedColorTransform");
HX_VISIT_MEMBER_NAME(concatenatedMatrix,"concatenatedMatrix");
HX_VISIT_MEMBER_NAME(pixelBounds,"pixelBounds");
HX_VISIT_MEMBER_NAME(__colorTransform,"__colorTransform");
HX_VISIT_MEMBER_NAME(__displayObject,"__displayObject");
HX_VISIT_MEMBER_NAME(__hasMatrix,"__hasMatrix");
HX_VISIT_MEMBER_NAME(__hasMatrix3D,"__hasMatrix3D");
}
Dynamic Transform_obj::__Field(const ::String &inName,bool inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"matrix") ) { return get_matrix(); }
break;
case 8:
if (HX_FIELD_EQ(inName,"matrix3D") ) { return get_matrix3D(); }
break;
case 10:
if (HX_FIELD_EQ(inName,"get_matrix") ) { return get_matrix_dyn(); }
if (HX_FIELD_EQ(inName,"set_matrix") ) { return set_matrix_dyn(); }
break;
case 11:
if (HX_FIELD_EQ(inName,"pixelBounds") ) { return pixelBounds; }
if (HX_FIELD_EQ(inName,"__hasMatrix") ) { return __hasMatrix; }
break;
case 12:
if (HX_FIELD_EQ(inName,"get_matrix3D") ) { return get_matrix3D_dyn(); }
if (HX_FIELD_EQ(inName,"set_matrix3D") ) { return set_matrix3D_dyn(); }
break;
case 13:
if (HX_FIELD_EQ(inName,"__hasMatrix3D") ) { return __hasMatrix3D; }
break;
case 14:
if (HX_FIELD_EQ(inName,"colorTransform") ) { return get_colorTransform(); }
break;
case 15:
if (HX_FIELD_EQ(inName,"__displayObject") ) { return __displayObject; }
break;
case 16:
if (HX_FIELD_EQ(inName,"__colorTransform") ) { return __colorTransform; }
break;
case 18:
if (HX_FIELD_EQ(inName,"concatenatedMatrix") ) { return concatenatedMatrix; }
if (HX_FIELD_EQ(inName,"get_colorTransform") ) { return get_colorTransform_dyn(); }
if (HX_FIELD_EQ(inName,"set_colorTransform") ) { return set_colorTransform_dyn(); }
break;
case 26:
if (HX_FIELD_EQ(inName,"concatenatedColorTransform") ) { return concatenatedColorTransform; }
}
return super::__Field(inName,inCallProp);
}
Dynamic Transform_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"matrix") ) { return set_matrix(inValue); }
break;
case 8:
if (HX_FIELD_EQ(inName,"matrix3D") ) { return set_matrix3D(inValue); }
break;
case 11:
if (HX_FIELD_EQ(inName,"pixelBounds") ) { pixelBounds=inValue.Cast< ::openfl::geom::Rectangle >(); return inValue; }
if (HX_FIELD_EQ(inName,"__hasMatrix") ) { __hasMatrix=inValue.Cast< bool >(); return inValue; }
break;
case 13:
if (HX_FIELD_EQ(inName,"__hasMatrix3D") ) { __hasMatrix3D=inValue.Cast< bool >(); return inValue; }
break;
case 14:
if (HX_FIELD_EQ(inName,"colorTransform") ) { return set_colorTransform(inValue); }
break;
case 15:
if (HX_FIELD_EQ(inName,"__displayObject") ) { __displayObject=inValue.Cast< ::openfl::display::DisplayObject >(); return inValue; }
break;
case 16:
if (HX_FIELD_EQ(inName,"__colorTransform") ) { __colorTransform=inValue.Cast< ::openfl::geom::ColorTransform >(); return inValue; }
break;
case 18:
if (HX_FIELD_EQ(inName,"concatenatedMatrix") ) { concatenatedMatrix=inValue.Cast< ::openfl::geom::Matrix >(); return inValue; }
break;
case 26:
if (HX_FIELD_EQ(inName,"concatenatedColorTransform") ) { concatenatedColorTransform=inValue.Cast< ::openfl::geom::ColorTransform >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void Transform_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_CSTRING("colorTransform"));
outFields->push(HX_CSTRING("concatenatedColorTransform"));
outFields->push(HX_CSTRING("concatenatedMatrix"));
outFields->push(HX_CSTRING("matrix"));
outFields->push(HX_CSTRING("matrix3D"));
outFields->push(HX_CSTRING("pixelBounds"));
outFields->push(HX_CSTRING("__colorTransform"));
outFields->push(HX_CSTRING("__displayObject"));
outFields->push(HX_CSTRING("__hasMatrix"));
outFields->push(HX_CSTRING("__hasMatrix3D"));
super::__GetFields(outFields);
};
static ::String sStaticFields[] = {
String(null()) };
#if HXCPP_SCRIPTABLE
static hx::StorageInfo sMemberStorageInfo[] = {
{hx::fsObject /*::openfl::geom::ColorTransform*/ ,(int)offsetof(Transform_obj,concatenatedColorTransform),HX_CSTRING("concatenatedColorTransform")},
{hx::fsObject /*::openfl::geom::Matrix*/ ,(int)offsetof(Transform_obj,concatenatedMatrix),HX_CSTRING("concatenatedMatrix")},
{hx::fsObject /*::openfl::geom::Rectangle*/ ,(int)offsetof(Transform_obj,pixelBounds),HX_CSTRING("pixelBounds")},
{hx::fsObject /*::openfl::geom::ColorTransform*/ ,(int)offsetof(Transform_obj,__colorTransform),HX_CSTRING("__colorTransform")},
{hx::fsObject /*::openfl::display::DisplayObject*/ ,(int)offsetof(Transform_obj,__displayObject),HX_CSTRING("__displayObject")},
{hx::fsBool,(int)offsetof(Transform_obj,__hasMatrix),HX_CSTRING("__hasMatrix")},
{hx::fsBool,(int)offsetof(Transform_obj,__hasMatrix3D),HX_CSTRING("__hasMatrix3D")},
{ hx::fsUnknown, 0, null()}
};
#endif
static ::String sMemberFields[] = {
HX_CSTRING("concatenatedColorTransform"),
HX_CSTRING("concatenatedMatrix"),
HX_CSTRING("pixelBounds"),
HX_CSTRING("__colorTransform"),
HX_CSTRING("__displayObject"),
HX_CSTRING("__hasMatrix"),
HX_CSTRING("__hasMatrix3D"),
HX_CSTRING("get_colorTransform"),
HX_CSTRING("set_colorTransform"),
HX_CSTRING("get_matrix"),
HX_CSTRING("set_matrix"),
HX_CSTRING("get_matrix3D"),
HX_CSTRING("set_matrix3D"),
String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(Transform_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(Transform_obj::__mClass,"__mClass");
};
#endif
Class Transform_obj::__mClass;
void Transform_obj::__register()
{
hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("openfl.geom.Transform"), hx::TCanCast< Transform_obj> ,sStaticFields,sMemberFields,
&__CreateEmpty, &__Create,
&super::__SGetClass(), 0, sMarkStatics
#ifdef HXCPP_VISIT_ALLOCS
, sVisitStatics
#endif
#ifdef HXCPP_SCRIPTABLE
, sMemberStorageInfo
#endif
);
}
void Transform_obj::__boot()
{
}
} // end namespace openfl
} // end namespace geom
| 37.474501 | 257 | 0.72404 | [
"transform"
] |
365cfb7673a21fc78b7ca51edb175fef04a29ae1 | 15,720 | cpp | C++ | modules/skeletonPlayer/src/main.cpp | robotology/assistive-rehab | 7c148385010483202d91b92d6b20c09996d6452e | [
"BSD-3-Clause"
] | 17 | 2019-01-28T08:38:42.000Z | 2022-03-25T13:23:08.000Z | modules/skeletonPlayer/src/main.cpp | robotology/assistive-rehab | 7c148385010483202d91b92d6b20c09996d6452e | [
"BSD-3-Clause"
] | 120 | 2019-01-29T10:54:53.000Z | 2022-03-30T13:18:37.000Z | modules/skeletonPlayer/src/main.cpp | robotology/assistive-rehab | 7c148385010483202d91b92d6b20c09996d6452e | [
"BSD-3-Clause"
] | 5 | 2019-04-29T14:30:40.000Z | 2020-09-10T06:29:48.000Z | /******************************************************************************
* *
* Copyright (C) 2018 Fondazione Istituto Italiano di Tecnologia (IIT) *
* All Rights Reserved. *
* *
******************************************************************************/
/**
* @file main.cpp
* @authors: Ugo Pattacini <ugo.pattacini@iit.it>
*/
#include <cstdlib>
#include <mutex>
#include <memory>
#include <vector>
#include <iterator>
#include <string>
#include <fstream>
#include <yarp/os/all.h>
#include <yarp/sig/all.h>
#include <yarp/math/Math.h>
#include "AssistiveRehab/skeleton.h"
#include "src/skeletonPlayer_IDL.h"
using namespace std;
using namespace yarp::os;
using namespace yarp::sig;
using namespace yarp::math;
using namespace assistive_rehab;
/****************************************************************/
struct MetaSkeleton
{
shared_ptr<Skeleton> s;
double t;
};
/****************************************************************/
class Player : public RFModule, public skeletonPlayer_IDL
{
mutex mtx;
vector<MetaSkeleton> skeletons;
vector<MetaSkeleton>::iterator it,it_begin,it_end;
enum class State { idle, loaded, opced, running } state;
const int opc_id_invalid=-1;
int opc_id;
double opacity;
Bottle color;
int n_sessions;
double t_warp;
double T0;
double t_origin;
BufferedPort<Bottle> viewerPort;
RpcClient opcPort;
RpcServer cmdPort;
/****************************************************************/
void viewerUpdate(Property &prop)
{
if (viewerPort.getOutputCount()>0)
{
prop.put("opacity",opacity);
prop.put("color",color.get(0));
Bottle &msg=viewerPort.prepare();
msg.clear();
msg.addList().read(prop);
viewerPort.writeStrict();
}
}
/****************************************************************/
bool opcAdd()
{
if (opcPort.getOutputCount())
{
Bottle cmd,rep;
cmd.addVocab32("add");
Property prop=it->s->toProperty();
cmd.addList().read(prop);
if (opcPort.write(cmd,rep))
{
if (rep.get(0).asVocab32()==Vocab32::encode("ack"))
{
opc_id=rep.get(1).asList()->get(1).asInt32();
viewerUpdate(prop);
return true;
}
}
}
return false;
}
/****************************************************************/
bool opcSet()
{
if (opcPort.getOutputCount())
{
Bottle cmd,rep;
cmd.addVocab32("set");
Bottle &pl=cmd.addList();
Property prop=it->s->toProperty();
pl.read(prop);
Bottle id;
Bottle &id_pl=id.addList();
id_pl.addString("id");
id_pl.addInt32(opc_id);
pl.append(id);
if (opcPort.write(cmd,rep))
{
if (rep.get(0).asVocab32()==Vocab32::encode("ack"))
{
viewerUpdate(prop);
return true;
}
}
}
return false;
}
/****************************************************************/
bool opcDel()
{
if (opcPort.getOutputCount())
{
Bottle cmd,rep;
cmd.addVocab32("del");
Bottle &pl=cmd.addList().addList();
pl.addString("id");
pl.addInt32(opc_id);
if (opcPort.write(cmd,rep))
{
if (rep.get(0).asVocab32()==Vocab32::encode("ack"))
{
opc_id=opc_id_invalid;
return true;
}
}
}
return false;
}
/****************************************************************/
bool findFrameDirect(const vector<MetaSkeleton>::iterator &it_begin,
const double t_begin, vector<MetaSkeleton>::iterator &it,
const double t_warp=1.0)
{
for (auto it_=it_begin; it_!=end(skeletons); it_++)
{
if (t_warp*(it_->t-T0)>=t_begin)
{
it=it_;
return true;
}
}
return false;
}
/****************************************************************/
bool findFrameReverse(const vector<MetaSkeleton>::iterator &it_end,
const double t_end, vector<MetaSkeleton>::iterator &it,
const double t_warp=1.0)
{
for (auto it_=it_end; it_--!=begin(skeletons);)
{
if (t_warp*(skeletons.back().t-it_->t)>=t_end)
{
it=it_;
return true;
}
}
return false;
}
/****************************************************************/
bool load(const string& file, const string& context) override
{
lock_guard<mutex> lg(mtx);
ResourceFinder rf;
rf.setDefaultContext(context);
rf.configure(0,nullptr);
string abspathFile=rf.findFile(file);
if (abspathFile.empty())
{
yError()<<"Unable to find"<<file;
return false;
}
ifstream fin(abspathFile);
if (!fin.is_open())
{
yError()<<"Unable to open"<<file;
return false;
}
bool ok=true;
vector<MetaSkeleton> skeletons_;
for (string line; getline(fin,line);)
{
Bottle bottle(line);
if (bottle.size()!=4)
{
ok=false;
break;
}
MetaSkeleton sk;
sk.t=bottle.get(1).asFloat64();
if (Bottle *b=bottle.get(3).asList())
{
Property prop;
b->write(prop);
sk.s=shared_ptr<Skeleton>(skeleton_factory(prop));
}
else
{
ok=(bottle.get(3).asString()=="empty");
continue;
}
skeletons_.push_back(sk);
}
fin.close();
if (ok && !skeletons_.empty())
{
skeletons=skeletons_;
T0=skeletons.front().t;
if ((state==State::opced) || (state==State::running))
{
opcDel();
}
state=State::loaded;
yInfo()<<"found file:"<<abspathFile;
yInfo()<<"loaded #"<<skeletons.size()<<"skeletons";
yInfo()<<"time span of"<<skeletons.back().t-T0<<"seconds";
yInfo()<<"average frame time of"<<(skeletons.back().t-T0)/(double)skeletons.size()<<"seconds";
}
else
{
yError()<<"Wrong file format!";
}
return ok;
}
/****************************************************************/
bool start(const int n_sessions, const double t_warp,
const double t_begin, const double t_end) override
{
lock_guard<mutex> lg(mtx);
if ((state==State::loaded) || (state==State::opced))
{
if (findFrameDirect(begin(skeletons),t_begin,it_begin) &&
findFrameReverse(end(skeletons),t_end,it_end))
{
this->n_sessions=n_sessions;
this->t_warp=t_warp;
it=it_begin;
if (state==State::loaded)
{
if (!opcAdd())
{
yError()<<"Unable to stream!";
return false;
}
}
yInfo()<<"Streaming started";
state=State::running;
t_origin=Time::now();
return true;
}
}
yError()<<"Unable to stream!";
return false;
}
/****************************************************************/
bool stop() override
{
lock_guard<mutex> lg(mtx);
if (state==State::running)
{
yInfo()<<"Streaming ended";
state=State::opced;
}
return true;
}
/****************************************************************/
bool is_running() override
{
lock_guard<mutex> lg(mtx);
return (state==State::running);
}
/****************************************************************/
bool put_in_opc(const double t_begin) override
{
lock_guard<mutex> lg(mtx);
if (skeletons.empty())
{
yError()<<"No file loaded yet!";
return false;
}
else if (state==State::running)
{
state=State::opced;
}
if (findFrameDirect(begin(skeletons),t_begin,it))
{
if (state==State::opced)
{
return opcSet();
}
else if (opcAdd())
{
state=State::opced;
return true;
}
}
yError()<<"Skeleton not present in OPC!";
return false;
}
/****************************************************************/
bool remove_from_opc() override
{
lock_guard<mutex> lg(mtx);
if ((state==State::opced) || (state==State::running))
{
if (opcDel())
{
state=State::loaded;
return true;
}
}
yError()<<"Skeleton not present in OPC!";
return false;
}
/****************************************************************/
bool set_tag(const string& new_tag) override
{
lock_guard<mutex> lg(mtx);
if (skeletons.empty())
{
yError()<<"No file loaded yet!";
return false;
}
for (auto &sk:skeletons)
{
sk.s->setTag(new_tag);
}
return true;
}
/****************************************************************/
double get_maxpath(const double t_begin) override
{
lock_guard<mutex> lg(mtx);
if (skeletons.empty())
{
yError()<<"No file loaded yet!";
}
else if (t_begin>=0.0)
{
vector<MetaSkeleton>::iterator it_;
if (findFrameDirect(begin(skeletons),t_begin,it_))
{
return it_->s->getMaxPath();
}
else
{
yError()<<"Unable to find the frame!";
}
}
else
{
double maxPath=0.0;
for (auto &sk:skeletons)
{
maxPath+=sk.s->getMaxPath();
}
return (maxPath/(double)skeletons.size());
}
return 0.0;
}
/****************************************************************/
bool normalize() override
{
lock_guard<mutex> lg(mtx);
if (skeletons.empty())
{
yError()<<"No file loaded yet!";
return false;
}
for (auto &sk:skeletons)
{
sk.s->normalize();
}
return true;
}
/****************************************************************/
bool scale(const double s) override
{
lock_guard<mutex> lg(mtx);
if (skeletons.empty())
{
yError()<<"No file loaded yet!";
return false;
}
for (auto &sk:skeletons)
{
sk.s->scale(s);
}
return true;
}
/****************************************************************/
bool move(const Matrix &T) override
{
lock_guard<mutex> lg(mtx);
if (skeletons.empty())
{
yError()<<"No file loaded yet!";
return false;
}
for (auto &sk:skeletons)
{
if (!sk.s->setTransformation(T))
{
yError()<<"Invalid transformation!";
return false;
}
sk.s->update();
}
return true;
}
/****************************************************************/
bool set_opacity(const double new_opacity) override
{
lock_guard<mutex> lg(mtx);
opacity=new_opacity;
return true;
}
/****************************************************************/
bool set_color(const double new_r, const double new_g, const double new_b) override
{
lock_guard<mutex> lg(mtx);
color.clear();
Bottle &c=color.addList();
c.addFloat64(new_r);
c.addFloat64(new_g);
c.addFloat64(new_b);
return true;
}
/****************************************************************/
bool attach(RpcServer &source) override
{
return yarp().attachAsServer(source);
}
/****************************************************************/
bool configure(ResourceFinder &rf) override
{
viewerPort.open("/skeletonPlayer/viewer:o");
opcPort.open("/skeletonPlayer/opc:rpc");
cmdPort.open("/skeletonPlayer/cmd:rpc");
attach(cmdPort);
color.addList().read(Vector(3,0.7));
return true;
}
/****************************************************************/
double getPeriod() override
{
return 0.01;
}
/****************************************************************/
bool updateModule() override
{
lock_guard<mutex> lg(mtx);
double t=Time::now()-t_origin;
if (state==State::running)
{
vector<MetaSkeleton>::iterator it_next=end(skeletons);
findFrameDirect(it,t,it_next,t_warp);
if (it_next<=it_end)
{
it=it_next;
yInfo()<<"Streaming frame #"<<distance(begin(skeletons),it)
<<"in ["<<distance(begin(skeletons),it_begin)
<<","<<distance(begin(skeletons),it_end)<<"]";
}
else if (n_sessions!=1)
{
yInfo()<<"Session ended";
it=it_begin;
t_origin=Time::now();
if (n_sessions>1)
{
n_sessions--;
}
}
else
{
yInfo()<<"Streaming ended";
state=State::opced;
}
}
if ((state==State::opced) || (state==State::running))
{
opcSet();
}
return true;
}
/****************************************************************/
bool close() override
{
viewerPort.close();
opcPort.close();
cmdPort.close();
return true;
}
/****************************************************************/
public:
/****************************************************************/
Player() : state(State::idle), opc_id(opc_id_invalid), opacity(0.2) { }
};
/****************************************************************/
int main(int argc, char *argv[])
{
Network yarp;
if (!yarp.checkNetwork())
{
yError()<<"Unable to find Yarp server!";
return EXIT_FAILURE;
}
ResourceFinder rf;
rf.configure(argc,argv);
Player player;
return player.runModule(rf);
}
| 26.963979 | 106 | 0.397901 | [
"vector"
] |
365fd9b8b1e2f26c18715b62afe6a7216a3d4666 | 1,539 | hpp | C++ | wall.hpp | StijnOost/ILI9481_Lib | 625f7e17058d646e216f0401d9353e41de525c55 | [
"BSL-1.0"
] | null | null | null | wall.hpp | StijnOost/ILI9481_Lib | 625f7e17058d646e216f0401d9353e41de525c55 | [
"BSL-1.0"
] | null | null | null | wall.hpp | StijnOost/ILI9481_Lib | 625f7e17058d646e216f0401d9353e41de525c55 | [
"BSL-1.0"
] | null | null | null | #ifndef WALL_HPP
#define WALL_HPP
#include "line.hpp"
class wall : public Drawable
{
private:
Line left,right,top,bottom;
const int & name;
const int & color;
public:
/// \brief
/// Construct wall
/// \details
/// needs the screen xy start and xy end also needs color end bounce and name
/// makes top down left right line objects and fills those values
wall(ILI9481 & LCD, const int & x_start, const int & y_start, const int & x_end, const int & y_end, int color , std::array< int, 2> bounce, const int & name);
/// \brief
/// draw draws all the lines
/// \details
/// Draw draws the line object top right bottom left
void draw();
/// \brief
/// Updates the position of the wall and draws it.
/// \details
/// It can be used to override the class drawable update funcion
/// And you can makes it so that a wall is drawn
/// it is empty
void update() override;
/// \brief
/// Checks if the wall interacts with an object
/// \details
/// It can be used to override the class drawable interact funcion
/// to check if there is an interact
/// it is empty
void interact( Drawable & other ) override;
/// \brief
/// Says the name of the object
/// \details
/// mostly used for debugging It overrides the class drawable say_name funcion
/// and used to say the drawable objects name
void say_name() override;
/// \brief
/// set_color sets the color of the wall
/// \details
/// set the color of all lines with the function line.set_color
void set_color(const int & new_color);
};
#endif // WALL_HPP
| 30.176471 | 161 | 0.690058 | [
"object"
] |
366533246cd0a5a8ae52da57c3b847640c5e62a5 | 2,011 | hpp | C++ | include/SFGUI/Container.hpp | growlitheharpo/SFGUI | 30ef3a8657b99dc5a099f47cac623c9e400f7edb | [
"Zlib"
] | null | null | null | include/SFGUI/Container.hpp | growlitheharpo/SFGUI | 30ef3a8657b99dc5a099f47cac623c9e400f7edb | [
"Zlib"
] | null | null | null | include/SFGUI/Container.hpp | growlitheharpo/SFGUI | 30ef3a8657b99dc5a099f47cac623c9e400f7edb | [
"Zlib"
] | null | null | null | #pragma once
#include <SFGUI/Widget.hpp>
#include <memory>
#include <vector>
namespace sfg {
/**
* Base class for container-like widgets.
*/
class SFGUI_API Container : public Widget {
public:
typedef std::shared_ptr<Container> Ptr; //!< Shared pointer.
typedef std::shared_ptr<const Container> PtrConst; //!< Shared pointer.
typedef std::vector<Widget::Ptr> WidgetsList;
/** Dtor.
*/
virtual ~Container() = default;
/** Add child.
* @param widget Widget to add.
*/
void Add( Widget::Ptr widget );
/** Remove child (from container).
* @param widget Widget to remove.
*/
void Remove( Widget::Ptr widget );
/** Remove all children from container.
*/
void RemoveAll();
/** Check if a widget is a child of this container.
* @param widget Widget to search for.
*/
bool IsChild( Widget::Ptr widget ) const;
/** Get children.
* @return std::list with children.
*/
const WidgetsList& GetChildren() const;
void Refresh() override;
bool HandleEvent( const sf::Event& event ) override;
/** Used to inform parent that a child has been invalidated
* @param child Widget that was invalidated.
*/
virtual void HandleChildInvalidate( Widget::PtrConst child ) const;
/** Handle changing of absolute position
*/
void HandleAbsolutePositionChange() override;
protected:
/** Handle adding children.
* @param child Child widget.
* @return true if child was added, false otherwise.
*/
virtual bool HandleAdd( Widget::Ptr child );
/** Handle removing children.
* @param child Child widget.
*/
virtual void HandleRemove( Widget::Ptr child );
/** Handle visibility change.
*/
void HandleGlobalVisibilityChange() override;
/** Handle update.
*/
void HandleUpdate( float seconds ) override;
/** Handle hierarchy level change.
*/
void HandleSetHierarchyLevel() override;
/** Handle viewport change.
*/
void HandleViewportUpdate() override;
private:
WidgetsList m_children;
};
}
| 21.623656 | 73 | 0.675783 | [
"vector"
] |
36785c3ec75ea0bcb1b6f10d20e58d8dcb146aa3 | 6,292 | cpp | C++ | swssconfig/swssconfig.cpp | kcudnik/sonic-swss | 46fa3d1593aaeadb01083e72461630de5fc84c37 | [
"Apache-2.0"
] | null | null | null | swssconfig/swssconfig.cpp | kcudnik/sonic-swss | 46fa3d1593aaeadb01083e72461630de5fc84c37 | [
"Apache-2.0"
] | null | null | null | swssconfig/swssconfig.cpp | kcudnik/sonic-swss | 46fa3d1593aaeadb01083e72461630de5fc84c37 | [
"Apache-2.0"
] | null | null | null | #include <stdlib.h>
#include <iostream>
#include <vector>
#include "logger.h"
#include <fstream>
#include "dbconnector.h"
#include "producertable.h"
#include "json.hpp"
using namespace std;
using namespace swss;
using json = nlohmann::json;
int db_port = 6379;
const char* const hostname = "localhost";
const char* const op_name = "OP";
const char* const name_delimiter = ":";
const int el_count = 2;
#define _in_
#define _out_
#define _inout_
typedef struct _sonic_db_item_t {
string op_val;
string hash_name;
std::vector<FieldValueTuple> fvVector;
}sonic_db_item_t;
void usage(char **argv)
{
cout <<"Usage: " << argv[0] << " json_file_path\n";
}
void dump_db_item_cout(_in_ sonic_db_item_t &db_item)
{
cout << "db_item [\n";
cout << "operation: " << db_item.op_val << "\n";
cout << "hash: " << db_item.hash_name << "\n";
cout << "[\n";
for(auto &fv: db_item.fvVector) {
cout << "field: " << fvField(fv);
cout << "value: " << fvValue(fv) << "\n";
}
cout << "]\n";
cout << "]\n";
}
void dump_db_item(_in_ sonic_db_item_t &db_item)
{
SWSS_LOG_NOTICE("db_item: [\n");
SWSS_LOG_NOTICE("operation: %s", db_item.op_val.c_str());
SWSS_LOG_NOTICE("hash: %s\n", db_item.hash_name.c_str());
SWSS_LOG_NOTICE("fields: [\n");
for(auto &fv: db_item.fvVector) {
SWSS_LOG_NOTICE("field: %s", fvField(fv).c_str());
SWSS_LOG_NOTICE("value: %s\n", fvValue(fv).c_str());
}
SWSS_LOG_NOTICE("]\n");
SWSS_LOG_NOTICE("]\n");
}
bool write_db_data(_in_ std::vector<sonic_db_item_t> &db_items)
{
DBConnector db(APPL_DB, hostname, db_port, 0);
#ifdef _DUMPT_TO_COUT_
for (sonic_db_item_t &db_item : db_items) {
dump_db_item_cout(db_item);
}
#endif //_DUMPT_TO_COUT_
for (sonic_db_item_t &db_item : db_items) {
dump_db_item(db_item);
std::size_t pos = db_item.hash_name.find(name_delimiter);
if((string::npos == pos) || ((db_item.hash_name.size() - 1) == pos)) {
SWSS_LOG_ERROR("Invalid formatted hash:%s\n", db_item.hash_name.c_str());
return false;
}
string table_name = db_item.hash_name.substr(0, pos);
string key_name = db_item.hash_name.substr(pos + 1);
ProducerTable producer(&db, table_name);
if(db_item.op_val == SET_COMMAND) {
producer.set(key_name, db_item.fvVector, SET_COMMAND);
}
if(db_item.op_val == DEL_COMMAND) {
producer.del(key_name, DEL_COMMAND);
}
}
return true;
}
bool load_json_db_data(
_in_ std::iostream &fs,
_out_ std::vector<sonic_db_item_t> &db_items)
{
json json_array;
fs >> json_array;
if(!json_array.is_array()) {
SWSS_LOG_ERROR("root element must be an array\n");
return false;
}
for (size_t i = 0; i < json_array.size(); i++) {
auto &arr_item = json_array[i];
if(arr_item.is_object()) {
if(el_count != arr_item.size()) {
SWSS_LOG_ERROR("root element must be an array\n");
return false;
}
db_items.push_back(sonic_db_item_t());
sonic_db_item_t &cur_db_item = db_items[db_items.size() - 1];
//
// iterate over array items
// each item must have following structure:
// {
// "OP":"SET/DEL",
// db_key_name {
// 1*Nfield:value
// }
// }
//
//
for (json::iterator child_it = arr_item.begin(); child_it != arr_item.end(); ++child_it) {
auto cur_obj_key = child_it.key();
auto &cur_obj = child_it.value();
string field_str;
int val;
string value_str;
if(cur_obj.is_object()) {
cur_db_item.hash_name = cur_obj_key;
for (json::iterator cur_obj_it = cur_obj.begin(); cur_obj_it != cur_obj.end(); ++cur_obj_it) {
field_str = cur_obj_it.key();
if((*cur_obj_it).is_number()) {
val = (*cur_obj_it).get<int>();
value_str = std::to_string(val);
}
if((*cur_obj_it).is_string()) {
value_str = (*cur_obj_it).get<string>();
}
cur_db_item.fvVector.push_back(FieldValueTuple(field_str, value_str));
}
}
else {
if(op_name != child_it.key()) {
SWSS_LOG_ERROR("Invalid entry. expected item:%s\n", op_name);
return false;
}
cur_db_item.op_val = cur_obj.get<std::string>();
}
}
}
else {
SWSS_LOG_WARN("Skipping processing of an array item which is not an object\n:%s", arr_item.dump().c_str());
}
}
return true;
}
int main(int argc, char **argv)
{
Logger::setMinPrio(Logger::SWSS_DEBUG);
if (argc != 2)
{
usage(argv);
exit(EXIT_FAILURE);
}
std::vector<sonic_db_item_t> db_items;
std::fstream fs;
try {
fs.open (argv[1], std::fstream::in | std::fstream::out | std::fstream::app);
if(!load_json_db_data(fs, db_items)) {
SWSS_LOG_ERROR("Failed loading data from json file\n");
fs.close();
return EXIT_FAILURE;
}
fs.close();
}
catch(...) {
cout << "Failed loading json file: " << argv[1] << " Please refer to logs\n";
return EXIT_FAILURE;
}
try {
if(!write_db_data(db_items)) {
SWSS_LOG_ERROR("Failed writing data to db\n");
return EXIT_FAILURE;
}
}
catch(...) {
cout << "Failed applying settings from json file: " << argv[1] << " Please refer to logs\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 31.148515 | 119 | 0.52384 | [
"object",
"vector"
] |
367e6475e466f922accdc148f8bee623de3420fc | 2,022 | hpp | C++ | tests/pendulum/pendulum.hpp | nim65s/py-dynamic-graph | e4480ea6f13627cbd6b149140ffc8f3d2db006a0 | [
"BSD-2-Clause"
] | null | null | null | tests/pendulum/pendulum.hpp | nim65s/py-dynamic-graph | e4480ea6f13627cbd6b149140ffc8f3d2db006a0 | [
"BSD-2-Clause"
] | null | null | null | tests/pendulum/pendulum.hpp | nim65s/py-dynamic-graph | e4480ea6f13627cbd6b149140ffc8f3d2db006a0 | [
"BSD-2-Clause"
] | null | null | null | #ifndef PY_DG_TEST_PENDULUM_HH
#define PY_DG_TEST_PENDULUM_HH
#include <dynamic-graph/entity.h>
#include <dynamic-graph/signal-ptr.h>
#include <dynamic-graph/linear-algebra.h>
namespace dynamicgraph {
class InvertedPendulum : public Entity::Entity
{
public:
InvertedPendulum(const std::string& inName, double cartMass = 1.0, double
pendulumMass = 1.0, double pendulumLength = 1.0, double viscosity =
0.1);
/// Each entity should provide the name of the class it belongs to
virtual const std::string& getClassName (void) const {
return CLASS_NAME;
}
/// Header documentation of the python class
virtual std::string getDocString () const {
return
"Classical inverted pendulum dynamic model\n";
}
double getCartMass() const {
return cartMass_;
}
void setCartMass(const double& mass) {
cartMass_ = mass;
}
double getPendulumMass() const {
return pendulumMass_;
}
void setPendulumMass(const double& mass) {
pendulumMass_ = mass;
}
double getPendulumLength() const {
return pendulumLength_;
}
void setPendulumLength(const double& length) {
pendulumLength_ = length;
}
double getViscosity() {
return viscosity_;
}
void setViscosity(const double& visc) {
viscosity_ = visc;
}
void incr(double inTimeStep);
std::shared_ptr<const SignalPtr<double, int> > getForce() const;
std::shared_ptr<const Signal<Vector, int> > getState() const;
protected:
static const std::string CLASS_NAME;
private:
double cartMass_;
double pendulumMass_;
double pendulumLength_;
double viscosity_;
std::shared_ptr<SignalPtr<double, int> > forceSIN;
std::shared_ptr<Signal<Vector, int> > stateSOUT;
Vector computeDynamics(const Vector& inState, const double& inControl, double& inTimeStep);
};
}
#endif
| 24.361446 | 97 | 0.641444 | [
"vector",
"model"
] |
3684f1e657f68e5c4e1afa7ad7c5d3335013a8ad | 6,271 | cpp | C++ | example/ch7_ex7_5_HistBackProj.cpp | gdijaejung/Learning-OpenCV | 20942678b467e4ce6053ed2f9c59f852affa4a24 | [
"MIT"
] | null | null | null | example/ch7_ex7_5_HistBackProj.cpp | gdijaejung/Learning-OpenCV | 20942678b467e4ce6053ed2f9c59f852affa4a24 | [
"MIT"
] | null | null | null | example/ch7_ex7_5_HistBackProj.cpp | gdijaejung/Learning-OpenCV | 20942678b467e4ce6053ed2f9c59f852affa4a24 | [
"MIT"
] | null | null | null | // ch7_ex7_5_HistBackProj OK, OK, this isn't in the book, its' "extra"
// We cut the source code for actually doing back project in the book
// but here it is no extra charge.
// Gary Bradski Oct 3, 2008
//
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <stdio.h>
/* *************** License:**************************
Oct. 3, 2008
Right to use this code in any way you want without warrenty, support or any guarentee of it working.
BOOK: It would be nice if you cited it:
Learning OpenCV: Computer Vision with the OpenCV Library
by Gary Bradski and Adrian Kaehler
Published by O'Reilly Media, October 3, 2008
AVAILABLE AT:
http://www.amazon.com/Learning-OpenCV-Computer-Vision-Library/dp/0596516134
Or: http://oreilly.com/catalog/9780596516130/
ISBN-10: 0596516134 or: ISBN-13: 978-0596516130
OTHER OPENCV SITES:
* The source code is on sourceforge at:
http://sourceforge.net/projects/opencvlibrary/
* The OpenCV wiki page (As of Oct 1, 2008 this is down for changing over servers, but should come back):
http://opencvlibrary.sourceforge.net/
* An active user group is at:
http://tech.groups.yahoo.com/group/OpenCV/
* The minutes of weekly OpenCV development meetings are at:
http://pr.willowgarage.com/wiki/OpenCV
************************************************** */
void help(){
printf("\nCall is:\n"
" ch7_ex7_5_HistBackProj modelImage testImage patch_type\n"
" patch_type takes on the following methods of matching:\n"
" 0 Correlation, 1 ChiSqr, 2 Intersect, 3 Bhattacharyya\n"
" Projection is done using cvCalcBackProject()\n\n");
}
//Learns histogram from derived from the first image, and backprojects it onto the second
// If patch_type is present, it does cvCalcBackProjectPatch()
// patch_type takes on the following methods of matching:
// 0 Correlation, 1 ChiSqr, 2 Intersect, 3 Bhattacharyya
// it does cvCalcBackProject().
// Call is:
// ch7BackProj modelImage testImage patch_type
//
int main( int argc, char** argv ) {
IplImage* src[2],*dst=0,*ftmp=0; //dst is what to display on
int i,type = 0;
int patch = 0; //default to cvCalcBackProject()
if( argc >= 3){
if(argc > 3) {
patch = 1;
type = atoi(argv[3]); //turn on cvCalcBackProjecPatch() using type
}
printf("Patch = %d, type = %d\n",patch,type);
//Load 2 images, first on is to build histogram of, 2nd is to run on
src[0] = 0; src[1] = 0;
for(i = 1; i<3; ++i){
if((src[i-1]=cvLoadImage(argv[i], 1))== 0) {
printf("Error on reading image %d: %s\n",i,argv[i]);
return(-1);
}
}
// Compute the HSV image, and decompose it into separate planes.
//
IplImage *hsv[2], *h_plane[2],*s_plane[2],*v_plane[2],*planes[2][2];
IplImage* hist_img[2];
CvHistogram* hist[2];
// int h_bins = 30, s_bins = 32;
int h_bins = 16, s_bins = 16;
int hist_size[] = { h_bins, s_bins };
float h_ranges[] = { 0, 180 }; // hue is [0,180]
float s_ranges[] = { 0, 255 };
float* ranges[] = { h_ranges, s_ranges };
int scale = 10;
#define patchx 61
#define patchy 61
if(patch){
int iwidth = src[1]->width - patchx + 1;
int iheight = src[1]->height - patchy + 1;
ftmp = cvCreateImage( cvSize(iwidth,iheight),32,1);
cvZero(ftmp);
}
dst = cvCreateImage( cvGetSize(src[1]),8,1);
cvZero(dst);
for(i = 0; i<2; ++i){
hsv[i] = cvCreateImage( cvGetSize(src[i]), 8, 3 );
cvCvtColor( src[i], hsv[i], CV_BGR2HSV );
h_plane[i] = cvCreateImage( cvGetSize(src[i]), 8, 1 );
s_plane[i] = cvCreateImage( cvGetSize(src[i]), 8, 1 );
v_plane[i] = cvCreateImage( cvGetSize(src[i]), 8, 1 );
planes[i][0] = h_plane[i];
planes[i][1] = s_plane[i];
cvCvtPixToPlane( hsv[i], h_plane[i], s_plane[i], v_plane[i], 0 );
// Build the histogram and compute its contents.
//
hist[i] = cvCreateHist(
2,
hist_size,
CV_HIST_ARRAY,
ranges,
1
);
cvCalcHist( planes[i], hist[i], 0, 0 );
if(patch)
cvNormalizeHist( hist[i], 1.0 ); //Don't normalize for cvCalcBackProject(),
// Create an image to use to visualize our histogram.
//
hist_img[i] = cvCreateImage(
cvSize( h_bins * scale, s_bins * scale ),
8,
3
);
cvZero( hist_img[i] );
// populate our visualization with little gray squares.
//
float max_value = 0;
float *fp,fval;
cvGetMinMaxHistValue( hist[i], 0, &max_value, 0, 0 );
for( int h = 0; h < h_bins; h++ ) {
for( int s = 0; s < s_bins; s++ ) {
float bin_val = cvQueryHistValue_2D( hist[i], h, s );
int intensity = cvRound( bin_val * 255 / max_value );
cvRectangle(
hist_img[i],
cvPoint( h*scale, s*scale ),
cvPoint( (h+1)*scale - 1, (s+1)*scale - 1),
CV_RGB(intensity,intensity,intensity),
CV_FILLED
);
}
}
}//For the 2 images
//DO THE BACK PROJECTION
if((patch)) {
printf("Doing cvCalcBackProjectPatch() with type =%d\n",type);
cvCalcBackProjectPatch(planes[1],ftmp,cvSize(61,61),hist[0],type,1.0);
printf("ftmp count = %d\n",cvCountNonZero(ftmp));
}else {
printf("Doing cvCalcBackProject()\n");
cvCalcBackProject(planes[1],dst,hist[0]);
}
//DISPLAY
cvNamedWindow( "Model Image", 0 );
cvShowImage( "Model Image", src[0] );
cvNamedWindow( "Model H-S Histogram", 0 );
cvShowImage( "Model H-S Histogram", hist_img[0] );
cvNamedWindow( "Test Image", 0 );
cvShowImage( "Test Image", src[1] );
cvNamedWindow( "Test H-S Histogram", 0 );
cvShowImage( "Test H-S Histogram", hist_img[1] );
cvNamedWindow( "Back Projection",0);
cvShowImage( "Back Projection", ftmp );
cvWaitKey(0);
}
else { printf("Error: Wrong number of arguments\n"); help(); return -1;}
}
| 36.04023 | 107 | 0.576782 | [
"model"
] |
36860e0c976ddb1076acabff6af7bf3d45566c11 | 885 | cxx | C++ | examples/myexec.cxx | marco-fedele/3dimagetoolkit | c58db95c52e7d434080e0de28f3b9ce519d7ad3f | [
"BSD-3-Clause"
] | 11 | 2016-02-26T17:33:13.000Z | 2021-01-20T12:52:15.000Z | examples/myexec.cxx | marco-fedele/3dimagetoolkit | c58db95c52e7d434080e0de28f3b9ce519d7ad3f | [
"BSD-3-Clause"
] | null | null | null | examples/myexec.cxx | marco-fedele/3dimagetoolkit | c58db95c52e7d434080e0de28f3b9ce519d7ad3f | [
"BSD-3-Clause"
] | 3 | 2016-03-16T17:01:50.000Z | 2018-05-05T02:57:55.000Z | /*
=========================================================================================
3D Image Toolkit
Copyright 2013:
Marco Fedele, Luca Barbarotta, Francesco Cremonesi, Elena Faggiano.
All rights reserved.
Read details of the license in the file license.txt provided with the library.
=========================================================================================
*/
/*!
\file myexec.cxx
\brief File to create an executable to show a selected image in some diferent way using
some members of class \ref im3d::interface.
*/
#include "../header/names.hxx"
#include "../header/image3d.hxx"
#include "../header/interface.hxx"
#include "../header/convolution.hxx"
#include <string>
using namespace std;
using namespace im3d;
typedef float MY_REAL;
int main (int argc, char** argv)
{
// write here your code exploiting the library
return 0;
}
| 21.071429 | 89 | 0.577401 | [
"3d"
] |
36911fefee5d225075a2d28233852a6ca9fa07d1 | 466 | cpp | C++ | examples/line_plot/stairs/stairs_5.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | 2 | 2020-09-02T14:02:26.000Z | 2020-10-28T07:00:44.000Z | examples/line_plot/stairs/stairs_5.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | null | null | null | examples/line_plot/stairs/stairs_5.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | 2 | 2020-09-01T16:22:07.000Z | 2020-09-02T14:02:27.000Z | #include <cmath>
#include <matplot/matplot.h>
int main() {
using namespace matplot;
std::vector<double> x1 = linspace(0,2*pi);
std::vector<double> x2 = linspace(0,pi);
std::vector<std::vector<double>> X = {x1,x2};
std::vector<std::vector<double>> Y(2);
Y[0] = transform(x1, [](double x) {return sin(5*x); });
Y[1] = transform(x2, [](double x) {return exp(x) * sin(5*x); });
figure();
stairs(X, Y);
wait();
return 0;
} | 23.3 | 68 | 0.56867 | [
"vector",
"transform"
] |
3692b67a3414793bcf5c6bf1a7a622b39644a108 | 3,478 | hpp | C++ | tools/Vitis-AI-Runtime/VART/vart/xrt-device-handle/include/xir/xrt_device_handle.hpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | 848 | 2019-12-03T00:16:17.000Z | 2022-03-31T22:53:17.000Z | tools/Vitis-AI-Runtime/VART/vart/xrt-device-handle/include/xir/xrt_device_handle.hpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 656 | 2019-12-03T00:48:46.000Z | 2022-03-31T18:41:54.000Z | tools/Vitis-AI-Runtime/VART/vart/xrt-device-handle/include/xir/xrt_device_handle.hpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 506 | 2019-12-03T00:46:26.000Z | 2022-03-30T10:34:56.000Z | /*
* Copyright 2019 Xilinx Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <glog/logging.h>
#include <cstring>
#include <fstream>
#include <functional>
#include <memory>
#include <string>
static constexpr size_t SIZE_OF_UUID = 16u;
namespace xir {
class XrtDeviceHandle {
public:
/** @brief register a new factory method for creating a buffer
* object, only one factory method is working. Invoking this
* function second time will overwrite the last factory method.
*/
static void registar(const std::string& name,
std::function<std::shared_ptr<XrtDeviceHandle>()>);
// dirty hack, for dp_buffer_object, use get_instance(), shared among all cu.
// for dp_dpu_controller, use create(), every controller own a handle.
/** @brief return the install of xrt device handle
*/
static std::shared_ptr<XrtDeviceHandle> get_instance();
// static std::unique_ptr<XrtDeviceHandle> create();
protected:
explicit XrtDeviceHandle() = default;
public:
virtual ~XrtDeviceHandle() = default;
// dirty hack, avoid include xrt.h
// typedef void * xclDeviceHandle;
virtual void* get_handle(const std::string& cu_name, size_t core_idx) = 0;
virtual size_t get_cu_index(const std::string& cu_name,
size_t core_idx) const = 0;
virtual size_t get_ip_index(const std::string& cu_name,
size_t core_idx) const = 0;
virtual unsigned int get_cu_mask(const std::string& cu_name,
size_t core_idx) const = 0;
virtual uint64_t get_cu_addr(const std::string& cu_name,
size_t core_idx) const = 0;
virtual unsigned int get_num_of_cus(const std::string& cu_name) const = 0;
virtual std::string get_cu_full_name(const std::string& cu_name,
size_t core_idx) const = 0;
virtual std::string get_cu_kernel_name(const std::string& cu_name,
size_t core_idx) const = 0;
virtual std::string get_instance_name(const std::string& cu_name,
size_t core_idx) const = 0;
virtual size_t get_device_id(const std::string& cu_name,
size_t core_idx) const = 0;
virtual size_t get_core_id(const std::string& cu_name,
size_t core_idx) const = 0;
virtual uint64_t get_fingerprint(const std::string& cu_name,
size_t core_idx) const = 0;
virtual unsigned int get_bank_flags(const std::string& cu_name,
size_t core_idx) const {
return 0u;
}
virtual std::array<unsigned char, SIZE_OF_UUID> get_uuid(
const std::string& cu_name, size_t core_idx) const = 0;
private:
XrtDeviceHandle(const XrtDeviceHandle& rhs) = delete;
XrtDeviceHandle& operator=(const XrtDeviceHandle& rhs) = delete;
};
} // namespace xir
| 39.522727 | 79 | 0.657849 | [
"object"
] |
36a034f764e9ae1f75c6470ae159b1ecc39f74d4 | 15,347 | cpp | C++ | src/my_transport.cpp | vhvb1989/libcurl-callbacks-transport-adapter | 3fbd133467c1ecf3702e4f4f650502f6742e70a4 | [
"MIT"
] | null | null | null | src/my_transport.cpp | vhvb1989/libcurl-callbacks-transport-adapter | 3fbd133467c1ecf3702e4f4f650502f6742e70a4 | [
"MIT"
] | null | null | null | src/my_transport.cpp | vhvb1989/libcurl-callbacks-transport-adapter | 3fbd133467c1ecf3702e4f4f650502f6742e70a4 | [
"MIT"
] | null | null | null | #include "my_transport.hpp"
#include <curl/curl.h>
#include <memory>
#include <vector>
using namespace Azure::Core::Http;
using namespace Azure::Core;
namespace
{
class CurlSession final : public Azure::Core::IO::BodyStream
{
private:
CURL *m_curlHandle;
struct curl_slist *m_headerHandle = NULL;
std::vector<uint8_t> m_responseData;
std::vector<uint8_t> m_sendBuffer;
std::unique_ptr<RawResponse> m_response = nullptr;
std::unique_ptr<Azure::Core::IO::BodyStream> m_responseStream;
bool m_chunked = false;
// ----- BodyStream implementation ( overrides ) ---- //
size_t OnRead(uint8_t *buffer, size_t count, Azure::Core::Context const &context) override
{
return m_responseStream->Read(buffer, count, context);
}
int64_t Length() const override
{
return m_chunked ? -1 : m_responseStream->Length();
}
void Rewind() override { return m_responseStream->Rewind(); }
// util functions
template <class T = int>
static T GetNextToken(
char const **begin,
char const *const last,
char const separator,
std::function<T(std::string)> mutator = [](std::string const &value)
{ return std::stoi(value); })
{
auto start = *begin;
auto end = std::find(start, last, separator);
// Move the original ptr to one place after the separator
*begin = end + 1;
return mutator(std::string(start, end));
}
constexpr static const int HttpWordLen = 4;
static std::unique_ptr<RawResponse> CreateHTTPResponse(
char const *const begin,
char const *const last)
{
// set response code, HTTP version and reason phrase (i.e. HTTP/1.1 200 OK)
auto start = begin + HttpWordLen + 1; // HTTP = 4, / = 1, moving to 5th place for version
auto majorVersion = GetNextToken(&start, last, '.');
auto minorVersion = GetNextToken(&start, last, ' ');
auto statusCode = GetNextToken(&start, last, ' ');
auto reasonPhrase = GetNextToken<std::string>(
&start, last, '\r', [](std::string const &value)
{ return value; });
// allocate the instance of response to heap with shared ptr
// So this memory gets delegated outside CurlTransport as a shared_ptr so memory will be
// eventually released
return std::make_unique<RawResponse>(
static_cast<uint16_t>(majorVersion),
static_cast<uint16_t>(minorVersion),
HttpStatusCode(statusCode),
reasonPhrase);
}
static void StaticSetHeader(
Azure::Core::Http::RawResponse &response,
char const *const first,
char const *const last)
{
// get name and value from header
auto start = first;
auto end = std::find(start, last, ':');
if ((last - first) == 2 && *start == '\r' && *(start + 1) == '\n')
{
// Libcurl gives the end of headers as `\r\n`, we just ignore it
return;
}
if (end == last)
{
throw std::invalid_argument("Invalid header. No delimiter ':' found.");
}
// Always toLower() headers
auto headerName = Azure::Core::_internal::StringExtensions::ToLower(std::string(start, end));
start = end + 1; // start value
while (start < last && (*start == ' ' || *start == '\t'))
{
++start;
}
end = std::find(start, last, '\r');
auto headerValue = std::string(start, end); // remove \r
response.SetHeader(headerName, headerValue);
}
// ------ libcurl callbacks
static size_t ReceiveInitialResponse(char *contents, size_t size, size_t nmemb, void *userp)
{
size_t const expectedSize = size * nmemb;
std::unique_ptr<RawResponse> *rawResponse = static_cast<std::unique_ptr<RawResponse> *>(userp);
// First response
if (*rawResponse == nullptr)
{
// parse header to get init data
*rawResponse = CreateHTTPResponse(contents, contents + expectedSize);
}
else
{
StaticSetHeader(*(*rawResponse), contents, contents + expectedSize);
}
// This callback needs to return the response size or curl will consider it as it failed
return expectedSize;
}
static size_t ReceiveData(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t const expectedSize = size * nmemb;
std::vector<uint8_t> &rawResponse = *(static_cast<std::vector<uint8_t> *>(userp));
uint8_t *data = static_cast<uint8_t *>(contents);
rawResponse.insert(rawResponse.end(), data, data + expectedSize);
// This callback needs to return the response size or curl will consider it as it failed
return expectedSize;
}
static size_t UploadData(void *dst, size_t size, size_t nmemb, void *userdata)
{
// Calculate the size of the *dst buffer
auto destSize = nmemb * size;
Azure::Core::IO::BodyStream *uploadStream = static_cast<Azure::Core::IO::BodyStream *>(userdata);
// Terminate the upload if the destination buffer is too small
if (destSize < 1)
{
throw std::runtime_error("Not enough size to continue to upload data.");
}
// Copy as many bytes as possible from the stream to libcurl's destination buffer
return uploadStream->Read(static_cast<uint8_t *>(dst), destSize);
}
public:
CurlSession()
{
m_curlHandle = curl_easy_init();
if (!m_curlHandle)
{
throw std::runtime_error("Could not create a new libcurl handle");
}
}
~CurlSession()
{
// Avoid leaks
if (m_curlHandle)
{
curl_easy_cleanup(m_curlHandle);
}
}
std::unique_ptr<RawResponse> Send(Request &request, Context const &context)
{
// optional
context.ThrowIfCancelled();
{
// 1.- Parse request into libcurl
auto const &url = request.GetUrl();
auto port = url.GetPort();
// 2.- Perform network call
CURLcode operationResult;
//url
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_URL, url.GetAbsoluteUrl().data());
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set URL for libcurl");
}
//port
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_PORT, port);
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set Port for libcurl");
}
// headers
auto const &headers = request.GetHeaders();
if (headers.size() > 0)
{
for (auto const &header : headers)
{
auto newHandle = curl_slist_append(m_headerHandle, (header.first + ":" + header.second).c_str());
if (newHandle == NULL)
{
throw std::runtime_error("Failing creating header list for libcurl");
}
m_headerHandle = newHandle;
}
// Add header list to handle
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_HTTPHEADER, m_headerHandle);
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set Port for libcurl");
}
}
// libcurl callbacks
// Headers
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_HEADERFUNCTION, ReceiveInitialResponse);
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set Header Function for libcurl");
}
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_HEADERDATA, static_cast<void *>(&m_response));
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set Header Function Data for libcurl");
}
// Receive data
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_WRITEFUNCTION, ReceiveData);
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set Receive Function for libcurl");
}
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_WRITEDATA, static_cast<void *>(&m_responseData));
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set Receive Function Data for libcurl");
}
// libcurl Http Metod
auto const &method = request.GetMethod();
if (method == Azure::Core::Http::HttpMethod::Delete)
{
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_CUSTOMREQUEST, "DELETE");
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set Custom DELETE for libcurl");
}
}
else if (method == Azure::Core::Http::HttpMethod::Patch)
{
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_CUSTOMREQUEST, "PATCH");
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set Custom PATCH for libcurl");
}
}
else if (method == Azure::Core::Http::HttpMethod::Head)
{
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_NOBODY, 1L);
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set Head NoBody for libcurl");
}
}
else if (method == Azure::Core::Http::HttpMethod::Post)
{
// Adds special header "Expect:" for libcurl to avoid sending only headers to server and wait
// for a 100 Continue response before sending a PUT method
auto newHandle = curl_slist_append(m_headerHandle, "Expect:");
if (newHandle == NULL)
{
throw std::runtime_error("Failing adding Expect header for POST");
}
m_headerHandle = newHandle;
m_sendBuffer = request.GetBodyStream()->ReadToEnd();
m_sendBuffer.emplace_back('\0'); // the body is expected to be null terminated
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_POSTFIELDS, reinterpret_cast<char *>(m_sendBuffer.data()));
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set CURLOPT_POSTFIELDS for libcurl");
}
}
else if (method == Azure::Core::Http::HttpMethod::Put)
{
// As of CURL 7.12.1 CURLOPT_PUT is deprecated. PUT requests should be made using
// CURLOPT_UPLOAD
// Adds special header "Expect:" for libcurl to avoid sending only headers to server and wait
// for a 100 Continue response before sending a PUT method
auto newHandle = curl_slist_append(m_headerHandle, "Expect:");
if (newHandle == NULL)
{
throw Azure::Core::Http::TransportException("Failing adding Expect header for POST");
}
m_headerHandle = newHandle;
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_UPLOAD, 1L);
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set CURLOPT_UPLOAD for libcurl");
}
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_READFUNCTION, UploadData);
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set CURLOPT_READFUNCTION for libcurl");
}
auto uploadStream = request.GetBodyStream();
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_READDATA, static_cast<void *>(uploadStream));
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set CURLOPT_READDATA for libcurl");
}
operationResult = curl_easy_setopt(m_curlHandle, CURLOPT_INFILESIZE, static_cast<curl_off_t>(uploadStream->Length()));
if (operationResult != CURLE_OK)
{
throw std::runtime_error("Could not set CURLOPT_INFILESIZE for libcurl");
}
}
// Perform libcurl transfer
auto performResult = curl_easy_perform(m_curlHandle);
}
// 3.- Create a Azure body stream for the RawResponse
m_responseStream = std::make_unique<Azure::Core::IO::MemoryBodyStream>(m_responseData);
// ** special case for Azure Reponse -> size - unknown or chunked
auto const &responseHeaders = m_response->GetHeaders();
auto transferEncodingHeader = responseHeaders.find("transfer-encoding");
if (transferEncodingHeader != responseHeaders.end())
{
auto headerValue = transferEncodingHeader->second;
m_chunked = headerValue.find("chunked") != std::string::npos;
}
// 4.- Return the rawResponse
return std::move(m_response);
}
};
}
namespace MyNameSpace
{
std::unique_ptr<RawResponse> MyTransport::Send(Request &request, Context const &context)
{
// Set up.
auto session = std::make_unique<CurlSession>();
auto response = session->Send(request, context);
response->SetBodyStream(std::move(session));
return response;
}
} | 42.046575 | 138 | 0.52955 | [
"vector"
] |
36a3ba58c4dae0401326d9d18f00a5c97a185b7c | 1,400 | cpp | C++ | Hackerrank/Encryption/solution.cpp | arushmangal/Hack-CP-DSA | 91f5aabc4741c1c518f35065273c7fcfced67061 | [
"MIT"
] | 205 | 2021-09-30T15:41:05.000Z | 2022-03-27T18:34:56.000Z | Hackerrank/Encryption/solution.cpp | arushmangal/Hack-CP-DSA | 91f5aabc4741c1c518f35065273c7fcfced67061 | [
"MIT"
] | 566 | 2021-09-30T15:27:27.000Z | 2021-10-16T21:21:02.000Z | Hackerrank/Encryption/solution.cpp | arushmangal/Hack-CP-DSA | 91f5aabc4741c1c518f35065273c7fcfced67061 | [
"MIT"
] | 399 | 2021-09-29T05:40:46.000Z | 2022-03-27T18:34:58.000Z | #include <bits/stdc++.h>
using namespace std;
// Complete the encryption function below.
string encryption(string s) {
s.erase(remove(s.begin(),s.end(),' '),s.end()); //remove all the spaces.
int l = s.size();
int row = sqrt(l); //typecasting to int will turn it to floor value.
int column;
if(row == sqrt(l)) //if sqrt(l) is proper integer.
column = row;
else
column = row+1;
if(row*column<l)
row++;
char vec[row][column];
int it=0;
for(int i=0;i<row;i++) //store the string in 2-d vector
{
for(int j=0;j<column;j++)
{
if(it<l)
vec[i][j]=s[it++];
else //if we reach the end of string and still there is space in the vector
vec[i][j]='0'; //add 0 to remove garbage value
}
}
string res;
for(int i=0;i<column;i++)
{
for(int j=0;j<row;j++) // traverse the vector column-wise
{
if(vec[j][i]=='0') //Ignore the '0' that were put to handle garbage values
continue;
res.push_back(vec[j][i]);
}
res.push_back(' ');
}
return res;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string s;
getline(cin, s);
string result = encryption(s);
fout << result << "\n";
fout.close();
return 0;
}
| 24.137931 | 100 | 0.508571 | [
"vector"
] |
a5e31c52720c9e7e1bcb5b4390d272ea6501f701 | 21,470 | cpp | C++ | cognitics/meshgen/meshgen.cpp | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | cognitics/meshgen/meshgen.cpp | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null | cognitics/meshgen/meshgen.cpp | mikedig/cdb-productivity-api | e2bedaa550a8afa780c01f864d72e0aebd87dd5a | [
"MIT"
] | null | null | null |
#include <ccl/ObjLog.h>
#include <ccl/LogStream.h>
#include <ccl/Timer.h>
#include <ccl/FileInfo.h>
#include <cdb_util/cdb_util.h>
#include <tg/TerrainGenerator.h>
#include <tg/GltfTerrainGenerator.h>
#include <tg/ObjTerrainGenerator.h>
#include <tg/OpenFlightTerrainGenerator.h>
#include <tg/FbxTerrainGenerator.h>
#include "elev/SimpleDEMReader.h"
#include "ws/WebServices.h"
#include <ccl/gdal.h>
#include <fstream>
ccl::ObjLog logger;
void CopyBuildingFeatureFiles(const std::string& modelCache, const std::string& featurePath);
void CopyFeatureFiles(const std::string& sOutputPath, const std::string& sFeaturePath);
void CopyFeatureFile(const std::string& sOutputPath, const std::string& sFeaturePath, const std::string& sFile);
cognitics::TerrainGenerator* CreateTerrainGenerator(const std::string& format);
void RecordStatsForTileSize(const std::string& sOutputPath, int nTileSize, cognitics::TerrainGenerator& terrainGenerator, const std::set<std::string>& elevationFiles, const std::string& featurePath, const std::string& modelCachePath, std::string outputFormat);
void TestAllTileSizes(const std::string& sOutputPath, cognitics::TerrainGenerator& terrainGenerator, const std::set<std::string>& elevationFiles, const std::string& modelCachePath, std::string outputFormat);
void DeleteDirectory(const std::string &dir);
std::string CheckFormatString(std::string inFormat);
int usage(const std::string &error = std::string())
{
std::cout << "usage: [options] <infile.shp>" << std::endl;
std::cout << "\t-origin <lat> <lon>\tspecifies the origin" << std::endl;
std::cout << "\t-bounds <north> <south> <east> <west>\tspecifies the bounding box" << std::endl;
std::cout << "\t-output <path>\tspecifies the path for OpenFlight output" << std::endl;
std::cout << "\t-outputTmpPath <path>\tspecifies the path for temporary files" << std::endl;
std::cout << "\t-imagery <path>\tspecifies a path to imagery (multiple)" << std::endl;
std::cout << "\t-elevation <filename>\tspecifies a DEM (multiple)" << std::endl;
std::cout << "\t-features <path>\tspecifies a path to feature data" << std::endl;
std::cout << "\t-texturesize <width> <height>\tspecifies the texture size (default: 1024x1024)" << std::endl;
std::cout << "\t-texelsize <size>\tspecifies the texel size (default: 5)" << std::endl;
std::cout << "\t-row <row>\tspecifies the row of tiles to generate" << std::endl;
std::cout << "\t-col <col>\tspecifies the column of tiles to generate" << std::endl;
std::cout << "\t-format <format>\tspecifies the format of the output. Choices are obj fbx b3dm and flt" << std::endl;
std::cout << "\t-ws\tindicates that web services should be used to query a geoserver rather than using file input" << std::endl;
std::cout << "\t-tileSize <size>\tspecifies the size of the tiles (default: 256)" << std::endl;
std::cout << "\t-startLOD <lod>\tspecifies the lower LOD of the desired export (default: 8)" << std::endl;
std::cout << "\t-endLOD <lod>\tspecifies the higher LOD of the desired export (default: 8)" << std::endl;
std::cout << "\t-projection <projection>\tspecifies the projection of the extents" << std::endl;
std::cout << "\t-combineMeshes \tindicates that the feature meshes should be combined with the terrain mesh" << std::endl;
if (error.size())
std::cerr << "ERROR: " << error << std::endl;
return (error.size()) ? -1 : 0;
}
int main(int argc, char **argv)
{
logger.init("main");
logger << ccl::LINFO;
cognitics::gdal::init(argv[0]);
ccl::Log::instance()->attach(ccl::LogObserverSP(new ccl::LogStream(ccl::LDEBUG)));
ccl::Timer execTimer;
execTimer.startTimer();
double north = 0.0f;
double south = 0.0f;
double west = 0.0f;
double east = 0.0f;
double originLat;
double originLon;
std::string modelKitPath("modelkits/");
std::string texturePath("textures/");
std::string outputPath("output/");
std::string outputTmpPath("output/tmp/");
std::set<std::string> imageryPaths;
std::set<std::string> oddbFiles;
std::set<std::string> elevationFiles;
std::string featurePath = "data/";
std::string modelCachePath = "";
int textureWidth = 512;
int textureHeight = 512;
double texelSize = 5.0f;
bool originSet = false;
std::string rulesFilename;
int row = -1;
int col = -1;
std::string outputFormat = ".gltf";
bool useWebServices = false;
std::string geoServerURL = "localhost:81/geoserver";
int tileSize = 256;
std::string projection = "";
int startLOD = 8;
int endLOD = 8;
bool combineMeshes = false;
if (argc <= 1)
return usage();
for (int argi = 1; argi < argc; ++argi)
{
std::string param(argv[argi]);
if (param == "-origin")
{
++argi;
if ((argi + 1) >= argc)
return usage("Missing latitude and longitude for origin");
originLat = atof(argv[argi]);
++argi;
originLon = atof(argv[argi]);
originSet = true;
continue;
}
if (param == "-bounds")
{
if ((argi + 1) < argc)
{
north = atof(argv[argi + 1]);
argi++;
}
if ((argi + 1) < argc)
{
south = atof(argv[argi + 1]);
argi++;
}
if ((argi + 1) < argc)
{
east = atof(argv[argi + 1]);
argi++;
}
if ((argi + 1) < argc)
{
west = atof(argv[argi + 1]);
argi++;
}
continue;
}
if (param == "-modelkits")
{
++argi;
if (argi >= argc)
return usage("Missing model kit path");
modelKitPath = argv[argi];
continue;
}
if (param == "-textures")
{
++argi;
if (argi >= argc)
return usage("Missing textures path");
texturePath = argv[argi];
continue;
}
if (param == "-output")
{
++argi;
if (argi >= argc)
return usage("Missing output path");
outputPath = argv[argi];
outputPath += "/";
continue;
}
if (param == "-outputTmpPath")
{
++argi;
if (argi >= argc)
return usage("Missing output temp path");
outputTmpPath = argv[argi];
outputTmpPath += "/";
continue;
}
if (param == "-imagery")
{
++argi;
if (argi >= argc)
return usage("Missing imagery path");
imageryPaths.insert(argv[argi]);
continue;
}
if (param == "-elevation")
{
++argi;
if (argi >= argc)
return usage("Missing elevation file");
elevationFiles.insert(argv[argi]);
continue;
}
if (param == "-features")
{
++argi;
if (argi >= argc)
return usage("Missing feature path");
featurePath = argv[argi];
featurePath += "/";
continue;
}
if (param == "-texturesize")
{
++argi;
if ((argi + 1) >= argc)
return usage("Missing width and height for texture size");
textureWidth = atoi(argv[argi]);
++argi;
textureHeight = atoi(argv[argi]);
continue;
}
if (param == "-row")
{
++argi;
if (argi >= argc)
return usage("Missing row");
row = atof(argv[argi]);
continue;
}
if (param == "-col")
{
++argi;
if (argi >= argc)
return usage("Missing col");
col = atof(argv[argi]);
continue;
}
if (param == "-texelsize")
{
++argi;
if (argi >= argc)
return usage("Missing texel size");
texelSize = atof(argv[argi]);
continue;
}
if (param == "-format")
{
++argi;
if (argi >= argc)
return usage("Missing format");
outputFormat = argv[argi];
continue;
}
if (param == "-ws")
{
useWebServices = true;
continue;
}
if (param == "-geoserverURL")
{
++argi;
if (argi >= argc)
return usage("Missing geoserver URL");
geoServerURL = argv[argi];
}
if (param == "-modelCache")
{
++argi;
if (argi >= argc)
return usage("Missing model cache path");
modelCachePath = argv[argi];
}
if (param == "-tileSize")
{
++argi;
if (argi >= argc)
return usage("Missing tile size");
tileSize = atoi(argv[argi]);
if (tileSize < 0)
{
tileSize = 256;
return usage("Invalid tile size.");
}
}
if (param == "-projection")
{
++argi;
if (argi >= argc)
return usage("Missing projection");
projection = argv[argi];
}
if (param == "-startLOD")
{
++argi;
if (argi >= argc)
return usage("missing start LOD");
startLOD = atoi(argv[argi]);
}
if (param == "-endLOD")
{
++argi;
if (argi >= argc)
return usage("missing end LOD");
endLOD = atoi(argv[argi]);
}
if (param == "-combineMeshes")
{
combineMeshes = true;
continue;
}
if (param == "-text")
return usage("Invalid parameters");
}
outputFormat = CheckFormatString(outputFormat);
if (!originSet)
{
originLat = (north + south) / 2;
originLon = (west + east) / 2;
}
// TODO: projInfo.txt for origin
// TODO: use files to determine bounds
logger << ccl::LINFO;
logger << "CDB Mesh Generator" << logger.endl;
cognitics::TerrainGenerator* terrainGenerator = CreateTerrainGenerator(outputFormat);
if (useWebServices)
{
// Create necessary directories
if (!ccl::directoryExists(outputPath))
{
ccl::makeDirectory(outputPath);
}
if (!ccl::directoryExists(outputTmpPath))
{
ccl::makeDirectory(outputTmpPath);
}
if (!ccl::directoryExists(outputTmpPath + "/data"))
{
ccl::makeDirectory(outputTmpPath + "/data");
}
if (!ccl::directoryExists(outputTmpPath + "/img"))
{
ccl::makeDirectory(outputTmpPath + "/img");
}
std::cout << "using Web Services..." << std::endl;
ws::GetFeatureData(geoServerURL, outputTmpPath, north, south, east, west);
GDALAllRegister();
auto filename = ws::GetName(originLon, originLat, textureHeight, textureWidth, outputFormat, ".tif");
auto elevationFilename = outputTmpPath + "/" + filename;
elevationFiles.insert(elevationFilename);
ws::GetElevation(geoServerURL, north, south, east, west, textureWidth, textureHeight, elevationFilename);
ws::GetImagery(geoServerURL, north, south, east, west, textureWidth, textureHeight, outputTmpPath + "/img/" + filename);
//terrainGenerator.parseFeatures(outputTmpPath);
terrainGenerator->addImageryPath(outputTmpPath + "/img");
terrainGenerator->setOrigin(originLat, originLon);
terrainGenerator->setBounds(north, south, west, east);
terrainGenerator->setOutputPath(outputPath);
terrainGenerator->setOutputTmpPath(outputTmpPath);
terrainGenerator->setOutputFormat(outputFormat);
//terrainGenerator.setTextureSize(textureWidth, textureHeight);
//terrainGenerator.setTexelSize(texelSize);
}
else
{
#ifdef CAE_MESH
CopyBuildingFeatureFiles(modelCachePath, featurePath);
CopyFeatureFiles(outputTmpPath, featurePath);
#endif
terrainGenerator->setOrigin(originLat, originLon);
terrainGenerator->setBounds(north, south, west, east);
terrainGenerator->setOutputPath(outputPath);
terrainGenerator->setOutputTmpPath(outputTmpPath);
logger << "Adding imagery paths..." << logger.endl;
for (std::set<std::string>::iterator it = imageryPaths.begin(), end = imageryPaths.end(); it != end; ++it)
terrainGenerator->addImageryPath(*it);
logger << "Adding elevation paths..." << logger.endl;
for (std::set<std::string>::iterator it = elevationFiles.begin(), end = elevationFiles.end(); it != end; ++it)
terrainGenerator->addElevationFile(*it);
#ifdef CAE_MESH
terrainGenerator->parseFeatures(outputTmpPath);
#endif
terrainGenerator->setTextureSize(textureWidth, textureHeight);
terrainGenerator->setTexelSize(texelSize);
}
//ws::generateFixedGridSofprep(north, south, west, east, geoServerURL, outputTmpPath, outputPath, outputFormat);
//return 0;
//terrainGenerator.generate(row, col);
//terrainGenerator.generateFixedGrid(*elevationFiles.begin());
//terrainGenerator.generateFixedGrid(*elevationFiles.begin(), featurePath, outputPath, 128);
//terrainGenerator.generateFixedGrid(*elevationFiles.begin(), featurePath, outputFormat, 0);
//if(outputFormat == ".b3dm")
//{
// ws::generateCesiumLods(north, south, west, east, geoServerURL, outputTmpPath, outputPath, *terrainGenerator, 2);
//}
//else
{
if (startLOD == endLOD)
{
if (tileSize == 0)
{
if (outputFormat == ".obj")
{
auto secondElement = std::next(elevationFiles.begin(), 1);
ws::GenerateSingleOBJ(*secondElement, geoServerURL, outputPath, outputTmpPath);
}
}
else
{
terrainGenerator->generateFixedGrid(*elevationFiles.begin(), featurePath, modelCachePath, outputFormat, tileSize);
}
//ws::generateFixedGridSofprep(north, south, west, east, geoServerURL, outputTmpPath, outputPath, outputFormat);
}
//terrainGenerator->generateFixedGrid(*elevationFiles.begin(), featurePath, modelCachePath, outputFormat, tileSize);
//ws::generateFixedGridWeb(north, south, west, east, outputFormat, geoServerIPAddress, outputTmpPath, outputPath, featurePath, outputFormat, textureWidth, textureHeight, terrainGenerator);
//ws::generateFixedGridWeb2(north, south, west, east, outputFormat, geoServerURL, outputTmpPath, outputPath, outputFormat, terrainGenerator, 5);
if (startLOD < endLOD)
{
terrainGenerator->generateFixedGridWithLOD(geoServerURL, north, south, east, west, outputFormat, outputTmpPath, outputPath, outputFormat, (endLOD - startLOD), textureHeight, textureWidth);
}
}
//terrainGenerator->generateFixedGrid(*elevationFiles.begin(), featurePath, modelCachePath, outputFormat, tileSize);
//ws::generateFixedGridWeb(north, south, west, east, outputFormat, geoServerIPAddress, outputTmpPath, outputPath, featurePath, outputFormat, textureWidth, textureHeight, terrainGenerator);
//ws::generateFixedGridWeb2(north, south, west, east, outputFormat, geoServerURL, outputTmpPath, outputPath, outputFormat, terrainGenerator, 5);
//TestAllTileSizes(outputPath, terrainGenerator, elevationFiles, outputFormat);
//DeleteDirectory(outputTmpPath);
delete terrainGenerator;
terrainGenerator = nullptr;
logger << "EXECUTION: " << execTimer.getElapsedTime() << " seconds" << logger.endl;
return 0;
}
void CopyBuildingFeatureFiles(const std::string& modelCache, const std::string& featurePath)
{
std::string modelCacheFrom = ccl::joinPaths(featurePath, "ModelCache");
logger << "Copying files from " << modelCacheFrom << " to " << modelCache << "..." << logger.endl;
ccl::copyFilesRecursive(modelCacheFrom, modelCache);
}
void CopyFeatureFiles(const std::string& outputPath, const std::string& featurePath)
{
CopyFeatureFile(outputPath, featurePath, "building_footprints.xml");
CopyFeatureFile(outputPath, featurePath, "building_models.xml");
CopyFeatureFile(outputPath, featurePath, "tree_points.xml");
}
void CopyFeatureFile(const std::string& outputPath, const std::string& featurePath, const std::string& sFile)
{
std::string srcPath = ccl::joinPaths(featurePath, sFile);
std::string dstPath = ccl::joinPaths(outputPath, "data\\"+sFile);
std::string outputDataPath = ccl::joinPaths(outputPath, "data");
if (!ccl::fileExists(outputDataPath))
{
ccl::makeDirectory(outputDataPath);
}
if (!ccl::fileExists(srcPath))
{
logger << "File does not exist " << srcPath << logger.endl;
return;
}
ccl::copyFile(srcPath, dstPath);
}
void DeleteDirectory(const std::string &dir)
{
std::string name = dir;
//std::uintmax_t n = std::experimental::filesystem::remove_all(dir);
int n = 0;
#ifndef LINUX
if (_rmdir(dir.c_str()) == 0)
#else
if (rmdir(dir.c_str()) == 0)
#endif // !LINUX
{
logger << "Did not delete all the files in " << name << logger.endl;
}
else
{
logger << "Deleted " << n << " files or directories in " << name << logger.endl;
}
}
void TestAllTileSizes(const std::string& sOutputPath, cognitics::TerrainGenerator& terrainGenerator, const std::set<std::string>& elevationFiles, const std::string& featurePath, const std::string& modelCachePath, std::string outputFormat)
{
for (int nTileSize = 1024; nTileSize >= 16; nTileSize /= 2)
{
RecordStatsForTileSize(sOutputPath, nTileSize, terrainGenerator, elevationFiles, featurePath, modelCachePath, outputFormat);
}
}
void RecordStatsForTileSize(const std::string& sOutputPath, int nTileSize, cognitics::TerrainGenerator& terrainGenerator, const std::set<std::string>& elevationFiles, const std::string& featurePath, const std::string& modelCachePath, std::string outputFormat)
{
ccl::Timer timer;
timer.startTimer();
std::stringstream sstream;
sstream << sOutputPath << "\\" << nTileSize;
std::string sTileSizeOutput = sstream.str();
#if 0
if (!std::experimental::filesystem::exists(sTileSizeOutput))
{
std::experimental::filesystem::create_directory(sTileSizeOutput);
}
#endif
if(!ccl::directoryExists(sTileSizeOutput))
{
ccl::makeDirectory(sTileSizeOutput,true);
}
terrainGenerator.setOutputPath(sTileSizeOutput);
terrainGenerator.generateFixedGrid(*elevationFiles.begin(), featurePath, modelCachePath, outputFormat, nTileSize);
std::ofstream fout(sOutputPath + "\\stats.csv", std::ofstream::out | std::ofstream::app);
int nNumOBJs = 0;
int nTotalFileSize = 0;
std::string path = sTileSizeOutput;
std::vector<ccl::FileInfo> files = ccl::FileInfo::getAllFiles(path,"*.*", true);
for (auto&& fi : files)
{
//ext does NOT include the dot (.)
std::string ext = fi.getSuffix();
if (ext == "obj")
{
++nNumOBJs;
nTotalFileSize += ccl::getFileSize(fi.getFileName());
}
else if (ext == "jpg" /*|| ext == "attr"*/)
{
nTotalFileSize += ccl::getFileSize(fi.getFileName());
}
}
#if 0
for (const auto& entry : std::experimental::filesystem::directory_iterator(path))
{
//std::cout << entry.path() << std::endl;
if (entry.path().extension() == ".obj")
{
++nNumOBJs;
nTotalFileSize += std::experimental::filesystem::file_size(entry.path());
}
else if (entry.path().extension() == ".jpg" /*|| entry.path().extension() == ".attr"*/)
{
nTotalFileSize += std::experimental::filesystem::file_size(entry.path());
}
}
#endif
nTotalFileSize /= static_cast<float>(1024 * 1024);//get total file size in MB
fout << nTileSize << "\t" << nNumOBJs << "\t" << nTotalFileSize / static_cast<float>(nNumOBJs) << "\t" << timer.getElapsedTime() / static_cast<float>(nNumOBJs) << "\t" << nTotalFileSize << "\t" << timer.getElapsedTime() << std::endl;
fout.close();
}
std::string CheckFormatString(std::string inFormat)
{
std::string outFormat;
if (inFormat.size() == 0)
{
// default to OBJ output
return ".obj";
}
if (inFormat.at(0) != '.')
{
outFormat = ".";
outFormat += inFormat;
}
else
{
outFormat = inFormat;
}
return outFormat;
}
cognitics::TerrainGenerator* CreateTerrainGenerator(const std::string& format)
{
if (cognitics::TerrainGenerator::IsGltfTypeOutput(format))
{
return new cognitics::GltfTerrainGenerator();
}
else if (cognitics::TerrainGenerator::IsObjOutput(format))
{
return new cognitics::ObjTerrainGenerator();
}
else if (cognitics::TerrainGenerator::IsFbxOutput(format))
{
return new cognitics::FbxTerrainGenerator();
}
else if (cognitics::TerrainGenerator::IsOpenFlightOutput(format))
{
return new cognitics::OpenFlightTerrainGenerator();
}
return nullptr;
} | 35.664452 | 261 | 0.598882 | [
"mesh",
"vector",
"model"
] |
a5f2d378f5507d9cd121a42c4e9ab886c7e2160b | 31,902 | cpp | C++ | src/cpu/aarch64/cpu_reducer.cpp | qnet-araki/oneDNN | 599c56e9f0ca5243aaa8d27d031b4935cc0ce174 | [
"Apache-2.0"
] | 13 | 2020-05-29T07:39:23.000Z | 2021-11-22T14:01:28.000Z | src/cpu/aarch64/cpu_reducer.cpp | qnet-araki/oneDNN | 599c56e9f0ca5243aaa8d27d031b4935cc0ce174 | [
"Apache-2.0"
] | 8 | 2020-09-04T02:05:19.000Z | 2021-12-24T02:18:37.000Z | src/cpu/aarch64/cpu_reducer.cpp | qnet-araki/oneDNN | 599c56e9f0ca5243aaa8d27d031b4935cc0ce174 | [
"Apache-2.0"
] | 24 | 2020-08-07T04:21:48.000Z | 2021-12-09T02:03:35.000Z | /*******************************************************************************
* Copyright 2017-2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include <assert.h>
#include "dnnl_types.h"
#include "common/dnnl_thread.hpp"
#include "common/nstl.hpp"
#include "common/utils.hpp"
#include "cpu/platform.hpp"
#include "cpu/aarch64/cpu_reducer.hpp"
#ifndef DNNL_X64_IMPLEMENTATION
#ifdef CG
#undef CG
#endif
#define CG CodeGeneratorAArch64
#define IDX(a) static_cast<uint32_t>(a.getIdx())
#endif //#ifdef DNNL_X64_IMPLEMENTATION
namespace dnnl {
namespace impl {
namespace cpu {
namespace aarch64 {
using namespace memory_tracking::names;
void reduce_balancer_t::balance() {
using namespace nstl;
using namespace utils;
assert(nthr_ > 0 && job_size_ > 0 && njobs_ > 0 && reduction_size_ > 0);
const int job_complexity = 1;
const int min_njobs_per_group = max(1, njobs_ / nthr_);
const int max_njobs_per_group
= max(1, static_cast<int>(max_buffer_size_ / (nthr_ * job_size_)));
/* initial guess */
int ngroups = min(njobs_ / min_njobs_per_group, nthr_);
int nthr_per_group
= allow_nthr_in_group_ ? min(nthr_ / ngroups, reduction_size_) : 1;
int njobs_per_group_ub = div_up(njobs_, ngroups);
/* rough upper-bound estimation, will be fixed during brute force */
size_t thread_complexity_ub = (size_t)njobs_ * job_size_ * reduction_size_;
/* brute force parameters for the best balance... */
for (int c_njobs_per_group = min_njobs_per_group;
c_njobs_per_group < njobs_; ++c_njobs_per_group) {
/* current assumption */
int c_ngroups = min(njobs_ / c_njobs_per_group, nthr_);
int c_nthr_per_group = allow_nthr_in_group_
? min(nthr_ / c_ngroups, reduction_size_)
: 1;
int c_njobs_per_group_ub = div_up(njobs_, c_ngroups);
if (c_nthr_per_group > 1 && c_njobs_per_group_ub > max_njobs_per_group)
continue;
int c_thread_reduction_ub = div_up(reduction_size_, c_nthr_per_group);
size_t c_group_size_ub = job_size_ * c_njobs_per_group_ub;
size_t c_thread_complexity_ub = c_group_size_ub
* (job_complexity * c_thread_reduction_ub
+ (c_nthr_per_group != 1));
if (c_thread_complexity_ub < thread_complexity_ub) {
ngroups = c_ngroups;
nthr_per_group = c_nthr_per_group;
njobs_per_group_ub = c_njobs_per_group_ub;
thread_complexity_ub = c_thread_complexity_ub;
}
}
assert(njobs_per_group_ub <= max_njobs_per_group || nthr_per_group == 1);
assert(ngroups * nthr_per_group <= nthr_);
assert((size_t)njobs_per_group_ub * job_size_ * nthr_ <= max_buffer_size_
|| nthr_per_group == 1); /* no reduction buffer overflow */
assert(IMPLICATION(!allow_nthr_in_group_, nthr_per_group == 1));
ngroups_ = ngroups;
nthr_per_group_ = nthr_per_group;
njobs_per_group_ub_ = njobs_per_group_ub;
}
/* reducer jit-ted driver */
using namespace Xbyak;
template <impl::data_type_t data_type>
struct reducer_2d_driver_t : public c_compatible {
typedef typename prec_traits<data_type>::type data_t;
reducer_2d_driver_t(int n_src, size_t src_ld, size_t src_step,
size_t dst_step, bool nullify_dst)
: n_src_(n_src)
, src_ld_(src_ld)
, src_step_(src_step)
, dst_step_(dst_step)
, nullify_dst_(nullify_dst)
, ker_(nullptr) {}
virtual ~reducer_2d_driver_t() {}
void operator()(data_t *dst, const data_t *srcs, size_t ny, size_t nx) {
assert(ker_);
ker_(dst, srcs, ny, nx);
}
protected:
int n_src_;
size_t src_ld_, src_step_, dst_step_;
bool nullify_dst_;
void (*ker_)(data_t *dst, const data_t *srcs, size_t ny, size_t nx);
};
template <impl::data_type_t data_type, cpu_isa_t isa>
struct reducer_2d_driver_f_s_32_t : public reducer_2d_driver_t<data_type>,
public jit_generator {
DECLARE_CPU_JIT_AUX_FUNCTIONS(reducer_2d_driver_f_s_32_t)
/* cpu specific part */
using Vmm = typename utils::conditional<isa == avx2, Ymm, Zmm>::type;
const AddressFrame &vmmword = (isa == avx2) ? yword : zword;
void uni_vadd(const Xmm &x1, const Xmm &x2, const Operand &op) {
if (data_type == data_type::f32)
vaddps(x1, x2, op);
else
vpaddd(x1, x2, op);
}
void uni_add(const Xmm &x1, const Operand &op) {
if (data_type == data_type::f32)
addss(x1, op);
else
paddd(x1, op);
}
const int vlen = cpu_isa_traits<isa>::vlen;
const int typesize
= sizeof(typename dnnl::impl::prec_traits<data_type>::type);
Xbyak::Reg64 reg_dst = abi_param1;
Xbyak::Reg64 reg_src = abi_param2;
Xbyak::Reg64 reg_ny = abi_param3;
Xbyak::Reg64 reg_nx = abi_param4;
Xbyak::Reg64 reg_x = rax;
Xbyak::Reg64 reg_src_id = r10;
reducer_2d_driver_f_s_32_t(int n_src, size_t src_ld, size_t src_step,
size_t dst_step, bool nullify_dst)
: reducer_2d_driver_t<data_type>(
n_src, src_ld, src_step, dst_step, nullify_dst) {
generate();
}
void nullify_dst(int nloads, int load_len) {
UNUSED(load_len);
for (int i = 0; i < nloads; ++i)
uni_vpxor(Vmm(i), Vmm(i), Vmm(i));
/* prefetches[dst] ? */
}
void load_dst(int nloads, int load_len) {
#ifdef DNNL_X64_IMPLEMENTATION
for (int i = 0; i < nloads; ++i) {
if (load_len == typesize)
movd(Xmm(i), ptr[reg_dst + i * load_len]);
else if (load_len == vlen)
vmovups(Vmm(i), ptr[reg_dst + i * load_len]);
else
assert(!"unsupported");
}
#else //#ifdef DNNL_X64_IMPLEMENTATION
xa::XReg x_reg_dst {IDX(reg_dst)};
if (load_len == typesize) {
uint32_t i = 0;
while (i < static_cast<uint32_t>(nloads)) {
uint32_t old_i = i;
uint32_t count = 0;
do {
CG::add_imm(x_tmp_vec[count++], x_reg_dst, i * load_len,
X_DEFAULT_ADDR);
i++;
} while (i < static_cast<uint32_t>(nloads)
&& count < x_tmp_vec_size);
for (uint32_t j = old_i; j < old_i + count; j++) {
CG::ldr(xa::SReg {j}, xa::ptr(x_tmp_vec[j]));
}
}
} else if (load_len == vlen) {
if (vlen == 64) {
CG::mov(X_TMP_0, xa::XReg {IDX(reg_dst)});
for (uint32_t i = 0; i < static_cast<uint32_t>(nloads); ++i) {
CG::ldr(xa::ZReg {i}, xa::ptr(x_reg_dst, i, xa::MUL_VL));
}
} else if (vlen == 32) {
uint32_t i = 0;
while (i < static_cast<uint32_t>(nloads)) {
uint32_t old_i = i;
uint32_t count = 0;
do {
CG::add_imm(x_tmp_vec[count++], x_reg_dst, i * load_len,
X_DEFAULT_ADDR);
i++;
} while (i < static_cast<uint32_t>(nloads)
&& count < x_tmp_vec_size);
for (uint32_t j = old_i; j < old_i + count; j++) {
CG::ld1w(xa::ZRegS {j}, p_lsb, xa::ptr(x_tmp_vec[j]));
}
}
} else if (vlen == 16) {
for (uint32_t i = 0; i < static_cast<uint32_t>(nloads); ++i) {
CG::mov(X_TMP_0, xa::XReg {IDX(reg_dst)});
CG::ldr(xa::QReg {i}, xa::post_ptr(X_TMP_0, vlen));
}
}
} else {
assert(!"unsupported");
}
#endif //#ifdef DNNL_X64_IMPLEMENTATION
}
void store_dst(int nloads, int load_len) {
#ifdef DNNL_X64_IMPLEMENTATION
for (int i = 0; i < static_cast<uint32_t>(nloads); ++i) {
if (load_len == typesize)
movd(ptr[reg_dst + i * load_len], Xmm(i));
else if (load_len == vlen)
vmovups(ptr[reg_dst + i * load_len], Vmm(i));
else
assert(!"unsupported");
}
#else //#ifdef DNNL_X64_IMPLEMENTATION
xa::XReg x_reg_dst {IDX(reg_dst)};
if (load_len == typesize) {
uint32_t i = 0;
while (i < static_cast<uint32_t>(nloads)) {
uint32_t old_i = i;
uint32_t count = 0;
do {
CG::add_imm(x_tmp_vec[count++], x_reg_dst, i * load_len,
X_DEFAULT_ADDR);
i++;
} while (i < static_cast<uint32_t>(nloads)
&& count < x_tmp_vec_size);
for (uint32_t j = old_i; j < old_i + count; j++) {
CG::str(xa::SReg {j}, xa::ptr(x_tmp_vec[j]));
}
}
} else if (load_len == vlen) {
if (vlen == 64) {
CG::mov(X_TMP_0, xa::XReg {IDX(reg_dst)});
for (uint32_t i = 0; i < static_cast<uint32_t>(nloads); ++i) {
CG::str(xa::ZReg {i}, xa::ptr(x_reg_dst, i, xa::MUL_VL));
}
} else if (vlen == 32) {
uint32_t i = 0;
while (i < static_cast<uint32_t>(nloads)) {
uint32_t old_i = i;
uint32_t count = 0;
do {
CG::add_imm(x_tmp_vec[count++], x_reg_dst, i * load_len,
X_DEFAULT_ADDR);
i++;
} while (i < static_cast<uint32_t>(nloads)
&& count < x_tmp_vec_size);
for (uint32_t j = old_i; j < old_i + count; j++) {
CG::st1w(xa::ZRegS {j}, p_lsb, xa::ptr(x_tmp_vec[j]));
}
}
} else if (vlen == 16) {
for (uint32_t i = 0; i < static_cast<uint32_t>(nloads); ++i) {
CG::mov(X_TMP_0, xa::XReg {IDX(reg_dst)});
CG::str(xa::QReg {i}, xa::post_ptr(X_TMP_0, vlen));
}
}
} else {
assert(!"unsupported");
}
#endif //#ifdef DNNL_X64_IMPLEMENTATION
}
#ifdef DNNL_X64_IMPLEMENTATION
void accumulate(int nloads, int load_len, size_t base_off) {
for (int i = 0; i < nloads; ++i) {
size_t off = base_off + i * load_len;
if (load_len == typesize)
uni_add(Xmm(i), ptr[reg_src + off]);
else if (load_len == vlen)
uni_vadd(Vmm(i), Vmm(i), vmmword[reg_src + off]);
else
assert(!"unsupported");
}
}
#else //#ifdef DNNL_X64_IMPLEMENTATION
#if AARCH64_OLD_IMPLEMENTATION
void accumulate(int nloads, int load_len, size_t base_off) {
const int n_vregs = cpu_isa_traits<isa>::n_vregs;
xa::XReg x_sp {IDX(rsp)};
xa::XReg x_src {IDX(reg_src)};
xa::ZReg z_tmp {n_vregs - 1};
/* Push a SVE register to prepare
temporal use for memory operand */
CG::sub(X_TRANSLATOR_STACK, X_TRANSLATOR_STACK, vlen);
if (vlen == 64)
CG::str(z_tmp, xa::ptr(X_TRANSLATOR_STACK));
else if (vlen == 32)
CG::st1w(z_tmp.s, p_lsb, xa::ptr(X_TRANSLATOR_STACK));
else if (vlen == 16)
CG::str(xa::QReg {n_vregs - 1}, xa::ptr(X_TRANSLATOR_STACK));
CG::add_imm(X_TMP_0, xa::XReg {IDX(reg_src)}, base_off, X_TMP_1);
for (uint32_t i = 0;
i < static_cast<uint32_t>(nloads) && i < n_vregs - 1; ++i) {
if (load_len == typesize) {
if (data_type == data_type::f32) {
xa::SReg s {i};
xa::SReg s_tmp {n_vregs - 1};
CG::ldr(s_tmp, xa::ptr(X_TMP_0));
CG::fadd(s, s, s_tmp);
} else {
xa::VReg4S v {i};
CG::ldr(xa::QReg {n_vregs - 1}, xa::ptr(X_TMP_0));
CG::add(v, v, xa::VReg4S {n_vregs - 1});
}
CG::add_imm(X_TMP_0, X_TMP_0, load_len, X_TMP_1);
} else if (load_len == vlen) {
xa::ZRegS z {i};
xa::ZRegS z_tmp {n_vregs - 1};
CG::ld1w(z_tmp, p_lsb / xa::T_z, xa::ptr(X_TMP_0));
if (data_type == data_type::f32) {
CG::fadd(z, p_lsb / xa::T_m, z_tmp);
} else {
CG::add(z, p_lsb / xa::T_m, z_tmp);
}
CG::add_imm(X_TMP_0, X_TMP_0, load_len, X_TMP_1);
} else {
assert(!"unsupported");
}
}
/* Pop a SVE register */
if (vlen == 64)
CG::ldr(z_tmp, xa::ptr(X_TRANSLATOR_STACK));
else if (vlen == 32)
CG::ld1w(z_tmp.s, p_lsb, xa::ptr(X_TRANSLATOR_STACK));
else if (vlen == 16)
CG::ldr(xa::QReg {n_vregs - 1}, xa::ptr(X_TRANSLATOR_STACK));
if (static_cast<uint32_t>(nloads) == n_vregs) {
/* Push a SVE register to prepare
temporal use for memory operand */
z_tmp = z0;
if (vlen == 64)
CG::str(z_tmp, xa::ptr(X_TRANSLATOR_STACK));
else if (vlen == 32)
CG::st1w(z_tmp.s, p_lsb, xa::ptr(X_TRANSLATOR_STACK));
else if (vlen == 16)
CG::str(xa::QReg {0}, xa::ptr(X_TRANSLATOR_STACK));
if (load_len == typesize) {
if (data_type == data_type::f32) {
xa::SReg s {n_vregs - 1};
xa::SReg s_tmp {0};
CG::ldr(s_tmp, xa::ptr(X_TMP_0));
CG::fadd(s, s, s_tmp);
} else {
xa::VReg4S v {n_vregs - 1};
CG::ldr(xa::QReg {0}, xa::ptr(X_TMP_0));
CG::add(v, v, xa::VReg4S {0});
}
CG::add_imm(X_TMP_0, X_TMP_0, load_len, X_TMP_1);
} else if (load_len == vlen) {
xa::ZRegS z {n_vregs - 1};
xa::ZRegS z_tmp {0};
CG::ld1w(z_tmp, p_lsb / xa::T_z, xa::ptr(X_TMP_0));
if (data_type == data_type::f32) {
CG::fadd(z, p_lsb / xa::T_m, z_tmp);
} else {
CG::add(z, p_lsb / xa::T_m, z_tmp);
}
CG::add_imm(X_TMP_0, X_TMP_0, load_len, X_TMP_1);
} else {
assert(!"unsupported");
}
if (vlen == 64)
CG::ldr(z_tmp, xa::ptr(X_TRANSLATOR_STACK));
else if (vlen == 32)
CG::ld1w(z_tmp.s, p_lsb, xa::ptr(X_TRANSLATOR_STACK));
else if (vlen == 16)
CG::ldr(xa::QReg {0}, xa::ptr(X_TRANSLATOR_STACK));
}
CG::add(X_TRANSLATOR_STACK, X_TRANSLATOR_STACK, vlen);
}
#else //#if AARCH64_OLD_IMPLEMENTATION
void accumulate(int nloads, int load_len, size_t base_off) {
const int n_vregs = cpu_isa_traits<isa>::n_vregs;
const int n_vregs_h = n_vregs / 2;
xa::XReg x_sp {IDX(rsp)};
xa::XReg x_src {IDX(reg_src)};
xa::ZReg z_tmp {n_vregs - 1};
assert(nloads <= n_vregs_h);
CG::add_imm(X_TMP_0, xa::XReg {IDX(reg_src)}, base_off, X_DEFAULT_ADDR);
CG::add_imm(X_TMP_1, xa::XReg {IDX(reg_src)}, base_off + 8 * vlen,
X_DEFAULT_ADDR);
if (load_len == typesize) {
if (data_type == data_type::f32) {
for (int i = 0; i < nloads; ++i) {
CG::ldr(xa::SReg(n_vregs_h + i),
xa::post_ptr(X_TMP_0, typesize));
}
for (int i = 0; i < nloads; ++i) {
xa::SReg s(i);
CG::fadd(s, s, xa::SReg(n_vregs_h + i));
}
} else {
for (int i = 0; i < nloads; ++i) {
xa::VReg4S v(i);
CG::ldr(xa::QReg(n_vregs_h + i),
xa::post_ptr(X_TMP_0, vlen));
}
for (int i = 0; i < nloads; ++i) {
xa::VReg4S v(i);
CG::add(v, v, xa::VReg4S(n_vregs_h + i));
}
}
} else if (load_len == vlen) {
if (vlen == 64) {
int i = 0;
/* imm index must be in the range -8 to 7. */
for (i = 0; i < nloads && i < 8; ++i)
CG::ld1w(xa::ZRegS(n_vregs_h + i), p_lsb / xa::T_z,
xa::ptr(X_TMP_0, i, xa::MUL_VL));
for (; i < nloads; ++i)
CG::ld1w(xa::ZRegS(n_vregs_h + i), p_lsb / xa::T_z,
xa::ptr(X_TMP_1, i - 8, xa::MUL_VL));
} else {
for (int i = 0; i < nloads; ++i) {
CG::ld1w(xa::ZRegS(n_vregs_h + i), p_lsb / xa::T_z,
xa::ptr(X_TMP_0));
CG::add_imm(X_TMP_0, X_TMP_0, load_len, X_TMP_1);
}
}
for (int i = 0; i < nloads; ++i) {
if (data_type == data_type::f32) {
CG::fadd(xa::ZRegS(i), p_lsb / xa::T_m,
xa::ZRegS(n_vregs_h + i));
} else {
CG::add(xa::ZRegS(i), p_lsb / xa::T_m,
xa::ZRegS(n_vregs_h + i));
}
}
} else {
assert(!"unsupported");
}
}
#endif //#if AARCH64_OLD_IMPLEMENTATION
#endif //#ifdef DNNL_X64_IMPLEMENTATION
void loop_x() {
#ifdef DNNL_X64_IMPLEMENTATION
const int nloads[] = {cpu_isa_traits<isa>::n_vregs, 1, 1};
#else //#ifdef DNNL_X64_IMPLEMENTATION
const int nloads[] = {cpu_isa_traits<isa>::n_vregs / 2, 1, 1};
#endif //#ifdef DNNL_X64_IMPLEMENTATION
const int nbranches = sizeof(nloads) / sizeof(nloads[0]);
const int load_len[nbranches] = {vlen, vlen, typesize};
Label loop_x_label[nbranches + 1];
mov(reg_x, reg_nx);
for (int id = 0; id < nbranches; ++id) {
L(loop_x_label[id]);
cmp(reg_x, nloads[id] * load_len[id]);
jl(loop_x_label[id + 1], T_NEAR);
if (this->nullify_dst_)
nullify_dst(nloads[id], load_len[id]);
else
load_dst(nloads[id], load_len[id]);
if (nloads[id] > 1) {
Label loop_srcs;
mov(reg_src_id, this->n_src_);
L(loop_srcs);
accumulate(nloads[id], load_len[id], 0);
add(reg_src, this->src_ld_ * typesize);
dec(reg_src_id);
jnz(loop_srcs, T_NEAR);
sub(reg_src, this->n_src_ * this->src_ld_ * typesize);
} else {
for (int src_id = 0; src_id < this->n_src_; ++src_id) {
const size_t base_off = src_id * this->src_ld_ * typesize;
accumulate(nloads[id], load_len[id], base_off);
}
}
store_dst(nloads[id], load_len[id]);
add(reg_src, nloads[id] * load_len[id]);
add(reg_dst, nloads[id] * load_len[id]);
sub(reg_x, nloads[id] * load_len[id]);
jmp(loop_x_label[id], T_NEAR);
}
L(loop_x_label[nbranches]);
/* restore address registers */
sub(reg_src, reg_nx);
sub(reg_dst, reg_nx);
}
void generate() {
assert(isa == sve);
preamble();
#ifndef DNNL_X64_IMPLEMENTATION
CG::ptrue(p_512.b);
CG::ptrue(p_256.b, xa::VL32);
CG::ptrue(p_128.b, xa::VL16);
if (vlen == 32) {
p_lsb = p_256;
} else if (vlen == 16) {
p_lsb = p_128;
}
#endif
shl(reg_nx, 2);
Label ny_loop;
L(ny_loop);
loop_x();
add(reg_dst, this->dst_step_ * typesize);
add(reg_src, this->src_step_ * typesize);
dec(reg_ny);
jnz(ny_loop, T_NEAR);
postamble();
this->ker_ = reinterpret_cast<decltype(this->ker_)>(
const_cast<uint8_t *>(this->getCode()));
}
private:
xa::PReg p_lsb {7}; /* If Vmm = Ymm(Xmm), then p_lsb set to p_256, p_128. */
xa::PReg p_512 {7};
xa::PReg p_256 {6};
xa::PReg p_128 {5};
const std::vector<xa::XReg> x_tmp_vec
= {X_TMP_0, X_TMP_1, X_TMP_2, X_TMP_3, X_TMP_4};
constexpr static int x_tmp_vec_size = 5;
};
template <impl::data_type_t data_type>
inline reducer_2d_driver_t<data_type> *create_reduce_2d_drv(int n_src,
size_t src_ld, size_t src_step, size_t dst_step, bool nullify_dst) {
if (mayiuse(sve))
return new reducer_2d_driver_f_s_32_t<data_type, sve>(
n_src, src_ld, src_step, dst_step, nullify_dst);
return nullptr;
}
/* cpu_reducer_t */
template <impl::data_type_t data_type>
void cpu_reducer_t<data_type>::conf_t::init_scratchpad(
memory_tracking::registrar_t &scratchpad) const {
if (balancer_.nthr_per_group_ == 1) return;
const size_t space_size = balancer_.ngroups_
* (balancer_.nthr_per_group_ - 1)
* cpu_reducer_t<data_type>::space_per_thread(balancer_);
scratchpad.book<data_t>(key_reducer_space, space_size, PAGE_4K);
scratchpad.book<simple_barrier::ctx_t>(
key_reducer_space_bctx, balancer_.ngroups_);
}
template <impl::data_type_t data_type>
cpu_reducer_t<data_type>::cpu_reducer_t(const conf_t &conf)
: conf_(conf), drv_(nullptr) {
if (balancer().nthr_per_group_ == 1) return;
drv_ = create_reduce_2d_drv<data_type>(balancer().nthr_per_group_ - 1,
space_per_thread(balancer()), 0, 0, false);
}
template <impl::data_type_t data_type>
cpu_reducer_t<data_type>::~cpu_reducer_t() {
delete drv_;
}
template <impl::data_type_t data_type>
typename cpu_reducer_t<data_type>::data_t *
cpu_reducer_t<data_type>::get_local_ptr(int ithr, data_t *dst,
const memory_tracking::grantor_t &scratchpad) const {
const int id_in_grp = balancer().id_in_group(ithr);
/* threads 0 from each group writes directly to the destination */
if (id_in_grp == 0)
return dst + balancer().ithr_job_off(ithr) * balancer().job_size_;
const int grp_id = balancer().group_id(ithr);
const int offset_factor
= grp_id * (balancer().nthr_per_group_ - 1) + (id_in_grp - 1);
auto space = scratchpad.template get<data_t>(key_reducer_space);
return space + offset_factor * space_per_thread(balancer());
}
template <impl::data_type_t data_type>
void cpu_reducer_t<data_type>::reduce_nolock(int ithr, data_t *dst,
const memory_tracking::grantor_t &scratchpad) const {
bool redundant_reduction
= balancer().nthr_per_group_ == 1 || balancer().idle(ithr);
if (redundant_reduction) return;
#ifdef SIMPLE_IMPL
if (balancer().id_in_group(ithr) != 0)
return; /* only threads 0 do the reduction */
const int njobs_in_grp = balancer().ithr_njobs(ithr);
data_t *d = get_local_ptr(ithr, dst, scratchpad);
for (int id_in_grp = 1; id_in_grp < balancer_.nthr_per_group_;
++id_in_grp) {
const data_t *space = get_local_ptr(ithr + id_in_grp, dst, scratchpad);
for (size_t i = 0; i < (size_t)njobs_in_grp * balancer().job_size_; ++i)
d[i] += space[i];
}
#else
using namespace utils;
const int id_in_grp = balancer().id_in_group(ithr);
const int njobs_in_grp = balancer().ithr_njobs(ithr);
const size_t cl = 64 / sizeof(data_t);
const size_t reduction_size = njobs_in_grp * balancer().job_size_;
size_t start {0}, end {0};
balance211(div_up(reduction_size, cl), balancer().nthr_per_group_,
id_in_grp, start, end);
if (start == end) return;
data_t *d = get_local_ptr(ithr - id_in_grp, dst, scratchpad) + start * cl;
const data_t *space
= get_local_ptr(ithr - id_in_grp + 1, dst, scratchpad) + start * cl;
const size_t len = nstl::min(end * cl, reduction_size) - start * cl;
(*drv_)(d, space, 1, len);
#endif
}
template struct cpu_reducer_t<data_type::f32>;
template struct cpu_reducer_t<data_type::s32>;
/* cpu_reducer_2d_t */
template <impl::data_type_t data_type>
void cpu_reducer_2d_t<data_type>::conf_t::init_scratchpad(
memory_tracking::registrar_t &scratchpad) const {
if (balancer_.nthr_per_group_ == 1) return;
const size_t space_size = balancer_.ngroups_ * balancer_.nthr_per_group_
* cpu_reducer_2d_t<data_type>::space_per_thread(balancer_);
scratchpad.book<data_t>(key_reducer_space, space_size);
scratchpad.book<simple_barrier::ctx_t>(
key_reducer_space_bctx, balancer_.ngroups_);
}
template <impl::data_type_t data_type>
cpu_reducer_2d_t<data_type>::cpu_reducer_2d_t(const conf_t &conf)
: conf_(conf), drv_(nullptr) {
if (balancer().nthr_per_group_ == 1) return;
drv_ = create_reduce_2d_drv<data_type>(balancer().nthr_per_group_,
space_per_thread(balancer()), conf_.job_size_x_, conf_.dst_x_,
true);
}
template <impl::data_type_t data_type>
cpu_reducer_2d_t<data_type>::~cpu_reducer_2d_t() {
delete drv_;
}
template <impl::data_type_t data_type>
typename cpu_reducer_2d_t<data_type>::data_t *
cpu_reducer_2d_t<data_type>::get_local_ptr(
int ithr, const memory_tracking::grantor_t &scratchpad) const {
const int id_in_grp = balancer().id_in_group(ithr);
const int grp_id = balancer().group_id(ithr);
const int offset_factor = grp_id * balancer().nthr_per_group_ + id_in_grp;
auto space = scratchpad.template get<data_t>(key_reducer_space);
return space + offset_factor * space_per_thread(balancer());
}
template <impl::data_type_t data_type>
int cpu_reducer_2d_t<data_type>::choose_x_blocking(
int nx, int ny, int nthr_per_grp) const {
// find x_blocking for better balance reducing work between threads
assert(conf_.x_block_ > 0 && nx > conf_.x_block_
&& nx % conf_.x_block_ == 0);
int x_blocking = nx / conf_.x_block_;
int min_x_blocking
= utils::div_up(x_blocking, nstl::max(1, nthr_per_grp / ny));
while (true) {
if (x_blocking % 2 == 0 && x_blocking >= min_x_blocking * 2)
x_blocking /= 2;
else if (x_blocking % 3 == 0 && x_blocking >= min_x_blocking * 3)
x_blocking /= 3;
else
break;
}
if (x_blocking >= min_x_blocking * 4) x_blocking = 1;
x_blocking *= conf_.x_block_;
return x_blocking;
}
template <impl::data_type_t data_type>
void cpu_reducer_2d_t<data_type>::reduce_block(const data_t *space_base,
data_t *dst, int job, int start_y, int start_x, int ny_start,
int nx_start, int ny_step, int nx_step) const {
data_t *d = dst + (start_y + ny_start) * conf_.dst_x_ + start_x + nx_start;
const data_t *space = space_base + job * balancer().job_size_
+ ny_start * conf_.job_size_x_ + nx_start;
#ifdef SIMPLE_IMPL
for (int idg = 0; idg < balancer().nthr_per_group_; ++idg) {
const data_t *w = &space[idg * space_per_thread(balancer())];
for (int y = 0; y < ny_step; ++y)
for (int x = 0; x < nx_step; ++x) {
d[y * conf_.dst_x_ + x]
= (idg == 0 ? 0 : d[y * conf_.dst_x_ + x])
+ w[y * conf_.job_size_x_ + x];
}
}
#else
(*drv_)(d, space, ny_step, nx_step);
#endif
}
template <impl::data_type_t data_type>
void cpu_reducer_2d_t<data_type>::reduce_nolock(int ithr, data_t *dst,
const memory_tracking::grantor_t &scratchpad) const {
bool redundant_reduction
= balancer().nthr_per_group_ == 1 || balancer().idle(ithr);
if (redundant_reduction) return;
const int id_in_grp = balancer().id_in_group(ithr);
const int njobs_in_grp = balancer().ithr_njobs(ithr);
const int njobs_x = utils::div_up(conf_.dst_x_, conf_.job_size_x_);
const int global_job_start = balancer().ithr_job_off(ithr);
const data_t *space_base = get_local_ptr(ithr - id_in_grp, scratchpad);
const int pr_grps = nstl::min(njobs_in_grp, balancer().nthr_per_group_);
const int pr_nthr_per_grp = balancer().nthr_per_group_ / pr_grps;
if (id_in_grp >= pr_grps * pr_nthr_per_grp) return; /* idle */
const int pr_my_grp = id_in_grp / pr_nthr_per_grp;
const int pr_my_id = id_in_grp % pr_nthr_per_grp;
int pr_job_start {0}, pr_job_end {0};
balance211(njobs_in_grp, pr_grps, pr_my_grp, pr_job_start, pr_job_end);
for (int j = pr_job_start; j < pr_job_end; ++j) {
const int global_job = global_job_start + j;
const int j_y = global_job / njobs_x;
const int j_x = global_job % njobs_x;
const int start_y = j_y * conf_.job_size_y_;
const int start_x = j_x * conf_.job_size_x_;
const int ny = nstl::min(conf_.dst_y_ - start_y, conf_.job_size_y_);
const int nx = nstl::min(conf_.dst_x_ - start_x, conf_.job_size_x_);
int x_blocking = choose_x_blocking(nx, ny, pr_nthr_per_grp);
int nxy_start {0}, nxy_end {0};
balance211(ny * nx / x_blocking, pr_nthr_per_grp, pr_my_id, nxy_start,
nxy_end);
if (nxy_start == nxy_end) continue;
nxy_start *= x_blocking;
nxy_end *= x_blocking;
int nxy = nxy_start;
if (nxy % nx != 0) {
int nx_step = nstl::min(nx - nxy % nx, nxy_end - nxy);
reduce_block(space_base, dst, j, start_y, start_x, nxy / nx,
nxy % nx, 1, nx_step);
nxy += nx_step;
}
if ((nxy_end - nxy) > nx) {
int ny_step = (nxy_end - nxy) / nx;
reduce_block(space_base, dst, j, start_y, start_x, nxy / nx,
nxy % nx, ny_step, nx);
nxy += nx * ny_step;
}
if ((nxy_end - nxy) > 0) {
reduce_block(space_base, dst, j, start_y, start_x, nxy / nx,
nxy % nx, 1, nxy_end - nxy);
}
}
}
template struct cpu_reducer_2d_t<data_type::f32>;
template struct cpu_reducer_2d_t<data_type::s32>;
/* accumulator section */
template <impl::data_type_t data_type>
cpu_accumulator_1d_t<data_type>::cpu_accumulator_1d_t() : drv_(nullptr) {
drv_ = create_reduce_2d_drv<data_type>(1, 0, 0, 0, false);
}
template <impl::data_type_t data_type>
cpu_accumulator_1d_t<data_type>::~cpu_accumulator_1d_t() {
delete drv_;
}
template <impl::data_type_t data_type>
void cpu_accumulator_1d_t<data_type>::accumulate(
data_t *dst, const data_t *src, size_t size) {
(*drv_)(dst, src, 1, size);
}
template struct cpu_accumulator_1d_t<data_type::f32>;
template struct cpu_accumulator_1d_t<data_type::s32>;
} // namespace aarch64
} // namespace cpu
} // namespace impl
} // namespace dnnl
// vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
| 36.668966 | 80 | 0.55799 | [
"vector"
] |
a5f315a0771e07ee7b0840efe97a318e6859eca8 | 301 | cpp | C++ | graph/bipartite_matching.cpp | nicotina04/cp-library | 68181722ff86ed2b133cf3282c183eb8b9bbb050 | [
"MIT"
] | null | null | null | graph/bipartite_matching.cpp | nicotina04/cp-library | 68181722ff86ed2b133cf3282c183eb8b9bbb050 | [
"MIT"
] | null | null | null | graph/bipartite_matching.cpp | nicotina04/cp-library | 68181722ff86ed2b133cf3282c183eb8b9bbb050 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define BI_G 2001
bool visited[BI_G];
int bpt[BI_G];
vector<int> graph[BI_G];
int bi_match(int cur) {
if (visited[cur]) return 0;
visited[cur] = 1;
for (int i: graph[cur]) {
if (!bpt[i] || bi_match(i)) {
bpt[i] = cur;
return 1;
}
}
return 0;
}
| 15.842105 | 33 | 0.568106 | [
"vector"
] |
a5fb597312bc34d981d9160aa90d6178531819fd | 6,421 | cc | C++ | chrome/browser/media_galleries/fileapi/picasa/pmp_column_reader_unittest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/media_galleries/fileapi/picasa/pmp_column_reader_unittest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/media_galleries/fileapi/picasa/pmp_column_reader_unittest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <vector>
#include "chrome/browser/media_galleries/fileapi/picasa/pmp_column_reader.h"
#include "chrome/browser/media_galleries/fileapi/picasa/pmp_constants.h"
#include "chrome/browser/media_galleries/fileapi/picasa/pmp_test_helper.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
using picasa::PmpColumnReader;
using picasa::PmpTestHelper;
// Overridden version of Read method to make test code templatable.
bool DoRead(const PmpColumnReader* reader, uint32 row, std::string* target) {
return reader->ReadString(row, target);
}
bool DoRead(const PmpColumnReader* reader, uint32 row, uint32* target) {
return reader->ReadUInt32(row, target);
}
bool DoRead(const PmpColumnReader* reader, uint32 row, double* target) {
return reader->ReadDouble64(row, target);
}
bool DoRead(const PmpColumnReader* reader, uint32 row, uint8* target) {
return reader->ReadUInt8(row, target);
}
bool DoRead(const PmpColumnReader* reader, uint32 row, uint64* target) {
return reader->ReadUInt64(row, target);
}
// TestValid
template<class T>
void TestValid(const picasa::PmpFieldType field_type,
const std::vector<T>& elems) {
PmpTestHelper test_helper("test");
ASSERT_TRUE(test_helper.Init());
PmpColumnReader reader;
std::vector<uint8> data =
PmpTestHelper::MakeHeaderAndBody(field_type, elems.size(), elems);
ASSERT_TRUE(test_helper.InitColumnReaderFromBytes(
&reader, data, field_type));
EXPECT_EQ(elems.size(), reader.rows_read());
for (uint32 i = 0; i < elems.size() && i < reader.rows_read(); i++) {
T target;
EXPECT_TRUE(DoRead(&reader, i, &target));
EXPECT_EQ(elems[i], target);
}
}
template<class T>
void TestMalformed(const picasa::PmpFieldType field_type,
const std::vector<T>& elems) {
PmpTestHelper test_helper("test");
ASSERT_TRUE(test_helper.Init());
PmpColumnReader reader_too_few_declared_rows;
std::vector<uint8> data_too_few_declared_rows =
PmpTestHelper::MakeHeaderAndBody(field_type, elems.size()-1, elems);
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader_too_few_declared_rows,
data_too_few_declared_rows,
field_type));
PmpColumnReader reader_too_many_declared_rows;
std::vector<uint8> data_too_many_declared_rows =
PmpTestHelper::MakeHeaderAndBody(field_type, elems.size()+1, elems);
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader_too_many_declared_rows,
data_too_many_declared_rows,
field_type));
PmpColumnReader reader_truncated;
std::vector<uint8> data_truncated =
PmpTestHelper::MakeHeaderAndBody(field_type, elems.size(), elems);
data_truncated.resize(data_truncated.size()-10);
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader_truncated, data_truncated, field_type));
PmpColumnReader reader_padded;
std::vector<uint8> data_padded =
PmpTestHelper::MakeHeaderAndBody(field_type, elems.size(), elems);
data_padded.resize(data_padded.size()+10);
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader_padded, data_padded, field_type));
}
template<class T>
void TestPrimitive(const picasa::PmpFieldType field_type) {
// Make an ascending vector of the primitive.
uint32 n = 100;
std::vector<T> data(n, 0);
for (uint32 i = 0; i < n; i++) {
data[i] = i*3;
}
TestValid<T>(field_type, data);
TestMalformed<T>(field_type, data);
}
TEST(PmpColumnReaderTest, HeaderParsingAndValidation) {
PmpTestHelper test_helper("test");
ASSERT_TRUE(test_helper.Init());
PmpColumnReader reader_good_header;
std::vector<uint8> good_header =
PmpTestHelper::MakeHeader(picasa::PMP_TYPE_STRING, 0);
EXPECT_TRUE(test_helper.InitColumnReaderFromBytes(
&reader_good_header,
good_header,
picasa::PMP_TYPE_STRING));
EXPECT_EQ(0U, reader_good_header.rows_read()) <<
"Read non-zero rows from header-only data.";
PmpColumnReader reader_bad_magic_bytes;
std::vector<uint8> bad_magic_bytes =
PmpTestHelper::MakeHeader(picasa::PMP_TYPE_STRING, 0);
bad_magic_bytes[0] = 0xff;
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader_bad_magic_bytes,
bad_magic_bytes,
picasa::PMP_TYPE_STRING));
PmpColumnReader reader_inconsistent_types;
std::vector<uint8> inconsistent_type =
PmpTestHelper::MakeHeader(picasa::PMP_TYPE_STRING, 0);
inconsistent_type[picasa::kPmpFieldType1Offset] = 0xff;
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader_inconsistent_types,
inconsistent_type,
picasa::PMP_TYPE_STRING));
PmpColumnReader reader_invalid_type;
std::vector<uint8> invalid_type =
PmpTestHelper::MakeHeader(picasa::PMP_TYPE_STRING, 0);
invalid_type[picasa::kPmpFieldType1Offset] = 0xff;
invalid_type[picasa::kPmpFieldType2Offset] = 0xff;
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader_invalid_type,
invalid_type,
picasa::PMP_TYPE_STRING));
PmpColumnReader reader_incomplete_header;
std::vector<uint8> incomplete_header =
PmpTestHelper::MakeHeader(picasa::PMP_TYPE_STRING, 0);
incomplete_header.resize(10);
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader_incomplete_header,
incomplete_header,
picasa::PMP_TYPE_STRING));
}
TEST(PmpColumnReaderTest, StringParsing) {
std::vector<std::string> empty_strings(100, "");
// Test empty strings read okay.
TestValid(picasa::PMP_TYPE_STRING, empty_strings);
std::vector<std::string> mixed_strings;
mixed_strings.push_back("");
mixed_strings.push_back("Hello");
mixed_strings.push_back("World");
mixed_strings.push_back("");
mixed_strings.push_back("123123");
mixed_strings.push_back("Q");
mixed_strings.push_back("");
// Test that a mixed set of strings read correctly.
TestValid(picasa::PMP_TYPE_STRING, mixed_strings);
// Test with the data messed up in a variety of ways.
TestMalformed(picasa::PMP_TYPE_STRING, mixed_strings);
}
TEST(PmpColumnReaderTest, PrimitiveParsing) {
TestPrimitive<uint32>(picasa::PMP_TYPE_UINT32);
TestPrimitive<double>(picasa::PMP_TYPE_DOUBLE64);
TestPrimitive<uint8>(picasa::PMP_TYPE_UINT8);
TestPrimitive<uint64>(picasa::PMP_TYPE_UINT64);
}
} // namespace
| 33.26943 | 77 | 0.749727 | [
"vector"
] |
5701a0871b6387ef2d8db7b52f4e2a1fd87d3473 | 11,035 | cpp | C++ | tests/test_cpp_api.cpp | sriramch/nvcomp | 5483204bc5ba2eb61d1ead4e4942d56dbfaf5fd1 | [
"BSD-3-Clause"
] | null | null | null | tests/test_cpp_api.cpp | sriramch/nvcomp | 5483204bc5ba2eb61d1ead4e4942d56dbfaf5fd1 | [
"BSD-3-Clause"
] | null | null | null | tests/test_cpp_api.cpp | sriramch/nvcomp | 5483204bc5ba2eb61d1ead4e4942d56dbfaf5fd1 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "cascaded.hpp"
#include "nvcomp.hpp"
#include <assert.h>
#include <stdlib.h>
#include <vector>
// Test GPU decompression with cascaded compression API //
using namespace std;
using namespace nvcomp;
#define CUDA_CHECK(cond) \
do { \
cudaError_t err = cond; \
REQUIRE(err == cudaSuccess); \
} while (false)
TEST_CASE("comp/decomp RLE-Delta", "[nvcomp]")
{
using T = int;
int packing = 0;
int RLE = 1;
int Delta = 1;
std::vector<T> input = {0, 2, 2, 3, 0, 0, 0, 0, 0, 3, 1, 1, 1, 1, 1, 1};
size_t chunk_size = 10000;
// create GPU only input buffer
T* d_in_data;
const size_t in_bytes = sizeof(T) * input.size();
CUDA_CHECK(cudaMalloc((void**)&d_in_data, in_bytes));
CUDA_CHECK(
cudaMemcpy(d_in_data, input.data(), in_bytes, cudaMemcpyHostToDevice));
cudaStream_t stream;
cudaStreamCreate(&stream);
size_t comp_temp_bytes = 0;
size_t comp_out_bytes = 0;
void* d_comp_temp;
void* d_comp_out;
// Get comptess temp size
CascadedCompressor<T> compressor(
d_in_data, input.size(), RLE, Delta, packing);
comp_temp_bytes = compressor.get_temp_size();
REQUIRE(comp_temp_bytes > 0);
// allocate temp buffer
CUDA_CHECK(cudaMalloc(&d_comp_temp, comp_temp_bytes));
// Get compressed output size
comp_out_bytes = compressor.get_max_output_size(d_comp_temp, comp_temp_bytes);
REQUIRE(comp_out_bytes > 0);
// Allocate output buffer
CUDA_CHECK(cudaMalloc(&d_comp_out, comp_out_bytes));
compressor.compress_async(
d_comp_temp, comp_temp_bytes, d_comp_out, &comp_out_bytes, stream);
CUDA_CHECK(cudaStreamSynchronize(stream));
// printf("%d, %d, %d, %d\n", ((int*)d_comp_out)[0],((int*)d_comp_out)[1],((int*)d_comp_out)[2],((int*)d_comp_out)[3]);
cudaFree(d_comp_temp);
cudaFree(d_in_data);
size_t temp_bytes = 0;
size_t num_out = 0;
void* temp_ptr;
T* out_ptr;
Decompressor<T> decompressor(d_comp_out, comp_out_bytes, stream);
// get temp size
temp_bytes = decompressor.get_temp_size();
REQUIRE(temp_bytes > 0);
// allocate temp buffer
cudaMalloc(&temp_ptr, temp_bytes); // also can use RMM_ALLOC instead
// get output size
num_out = decompressor.get_num_elements();
// allocate output buffer
cudaMalloc(&out_ptr, num_out * sizeof(T)); // also can use RMM_ALLOC instead
// execute decompression (asynchronous)
decompressor.decompress_async(temp_ptr, temp_bytes, out_ptr, num_out, stream);
cudaStreamSynchronize(stream);
// Copy result back to host
std::vector<T> res(num_out);
cudaMemcpy(&res[0], out_ptr, num_out * sizeof(T), cudaMemcpyDeviceToHost);
cudaFree(temp_ptr);
cudaFree(d_comp_out);
cudaFree(out_ptr);
// Verify correctness
REQUIRE(res == input);
}
TEST_CASE("comp/decomp RLE-Delta-BP", "[nvcomp]")
{
using T = int;
int packing = 1;
int RLE = 1;
int Delta = 1;
std::vector<T> input = {0, 2, 2, 3, 0, 0, 3, 1, 1, 1, 1, 1};
size_t chunk_size = 10000;
// create GPU only input buffer
T* d_in_data;
const size_t in_bytes = sizeof(T) * input.size();
CUDA_CHECK(cudaMalloc((void**)&d_in_data, in_bytes));
CUDA_CHECK(
cudaMemcpy(d_in_data, input.data(), in_bytes, cudaMemcpyHostToDevice));
cudaStream_t stream;
cudaStreamCreate(&stream);
size_t comp_temp_bytes = 0;
size_t comp_out_bytes = 0;
void* d_comp_temp;
void* d_comp_out;
CascadedCompressor<T> compressor(
d_in_data, input.size(), RLE, Delta, packing);
comp_temp_bytes = compressor.get_temp_size();
REQUIRE(comp_temp_bytes > 0);
// allocate temp buffer
CUDA_CHECK(cudaMalloc(&d_comp_temp, comp_temp_bytes));
// Get compressed output size
comp_out_bytes = compressor.get_max_output_size(d_comp_temp, comp_temp_bytes);
REQUIRE(comp_out_bytes > 0);
// Allocate output buffer
CUDA_CHECK(cudaMalloc(&d_comp_out, comp_out_bytes));
compressor.compress_async(
d_comp_temp, comp_temp_bytes, d_comp_out, &comp_out_bytes, stream);
CUDA_CHECK(cudaStreamSynchronize(stream));
cudaFree(d_comp_temp);
cudaFree(d_in_data);
size_t temp_bytes;
void* temp_ptr;
size_t num_out = 0;
T* out_ptr = nullptr;
Decompressor<T> decompressor(d_comp_out, comp_out_bytes, stream);
// get temp size
temp_bytes = decompressor.get_temp_size();
// allocate temp buffer
cudaMalloc(&temp_ptr, temp_bytes); // also can use RMM_ALLOC instead
// get output size
num_out = decompressor.get_num_elements();
// allocate output buffer
cudaMalloc(&out_ptr, num_out * sizeof(T)); // also can use RMM_ALLOC instead
// execute decompression (asynchronous)
decompressor.decompress_async(temp_ptr, temp_bytes, out_ptr, num_out, stream);
cudaStreamSynchronize(stream);
// Copy result back to host
std::vector<T> res(num_out);
cudaMemcpy(&res[0], out_ptr, num_out * sizeof(T), cudaMemcpyDeviceToHost);
cudaFree(out_ptr);
// Verify result
REQUIRE(res == input);
cudaFree(temp_ptr);
cudaFree(d_comp_out);
}
TEST_CASE("C++ API Error handling", "[nvcomp]")
{
using T = int;
int packing = 1;
int RLE = 1;
int Delta = 1;
std::vector<T> input = {0, 2, 2, 3, 0, 0, 3, 1, 1, 1, 1, 1};
size_t chunk_size = 10000;
// create GPU only input buffer
T* d_in_data;
const size_t in_bytes = sizeof(T) * input.size();
CUDA_CHECK(cudaMalloc(&d_in_data, in_bytes));
CUDA_CHECK(
cudaMemcpy(d_in_data, input.data(), in_bytes, cudaMemcpyHostToDevice));
cudaStream_t stream;
cudaStreamCreate(&stream);
size_t comp_temp_bytes = 0;
size_t comp_out_bytes = 0;
void* d_comp_temp;
void* d_comp_out;
CascadedCompressor<T> compressor(
d_in_data, input.size(), RLE, Delta, packing);
comp_temp_bytes = compressor.get_temp_size();
// allocate temp buffer
CUDA_CHECK(cudaMalloc(&d_comp_temp, comp_temp_bytes));
try {
comp_out_bytes = compressor.get_max_output_size(NULL, 15);
REQUIRE(false);
} catch (const NVCompException&) {
// make sure an exception was thrown
}
// Get compressed output size
comp_out_bytes = compressor.get_max_output_size(d_comp_temp, comp_temp_bytes);
// Allocate output buffer
CUDA_CHECK(cudaMalloc(&d_comp_out, comp_out_bytes));
try {
compressor.compress_async(NULL, 0, NULL, NULL, stream);
REQUIRE(false);
} catch (const NVCompException&) {
// make sure an exception was thrown
}
compressor.compress_async(
d_comp_temp, comp_temp_bytes, d_comp_out, &comp_out_bytes, stream);
CUDA_CHECK(cudaStreamSynchronize(stream));
cudaFree(d_comp_temp);
cudaFree(d_in_data);
size_t temp_bytes;
void* temp_ptr;
size_t num_out;
T* out_ptr;
try {
Decompressor<T> decompressor(NULL, 0, stream);
REQUIRE(false);
} catch (const NVCompException&) {
// make sure an exception was thrown
}
Decompressor<T> decompressor(d_comp_out, comp_out_bytes, stream);
// get temp size
temp_bytes = decompressor.get_temp_size();
// allocate temp buffer
cudaMalloc(&temp_ptr, temp_bytes); // also can use RMM_ALLOC instead
// get output size
num_out = decompressor.get_num_elements();
// allocate output buffer
cudaMalloc(&out_ptr, num_out * sizeof(T)); // also can use RMM_ALLOC instead
try { // execute decompression (asynchronous)
decompressor.decompress_async(NULL, 0, NULL, num_out, stream);
REQUIRE(false);
} catch (const NVCompException&) {
// make sure an exception was thrown
}
decompressor.decompress_async(temp_ptr, temp_bytes, out_ptr, num_out, stream);
cudaStreamSynchronize(stream);
// Copy result back to host
std::vector<T> res(num_out);
cudaMemcpy(&res[0], out_ptr, num_out * sizeof(T), cudaMemcpyDeviceToHost);
// Verify result
REQUIRE(res == input);
cudaFree(temp_ptr);
cudaFree(d_comp_out);
cudaFree(out_ptr);
}
TEST_CASE("max_size_test", "[nvcomp]")
{
using T = uint8_t;
int packing = 1;
int RLE = 1;
int Delta = 1;
const size_t size = static_cast<size_t>(std::numeric_limits<int>::max()) + 1;
std::vector<T> input(size);
// create GPU only input buffer
T* d_in_data;
const size_t in_bytes = sizeof(T) * input.size();
CUDA_CHECK(cudaMalloc(&d_in_data, in_bytes));
CUDA_CHECK(
cudaMemcpy(d_in_data, input.data(), in_bytes, cudaMemcpyHostToDevice));
cudaStream_t stream;
cudaStreamCreate(&stream);
size_t comp_temp_bytes = 0;
size_t comp_out_bytes = 0;
void* d_comp_temp = nullptr;
void* d_comp_out = nullptr;
try {
CascadedCompressor<T> compressor(
d_in_data, input.size(), RLE, Delta, packing);
comp_temp_bytes = compressor.get_temp_size();
// allocate temp buffer
CUDA_CHECK(cudaMalloc(&d_comp_temp, comp_temp_bytes));
// Get compressed output size
comp_out_bytes = compressor.get_max_output_size(
d_comp_temp, comp_temp_bytes);
// Allocate output buffer
CUDA_CHECK(cudaMalloc(&d_comp_out, comp_out_bytes));
compressor.compress_async(
d_comp_temp, comp_temp_bytes, d_comp_out, &comp_out_bytes, stream);
// should have thrown an exception by now
REQUIRE(false);
} catch (const NVCompException&) {
// we through the right exception, pass
}
if (d_comp_temp) {
cudaFree(d_comp_temp);
}
if (d_comp_out) {
cudaFree(d_comp_out);
}
}
| 28.440722 | 120 | 0.698777 | [
"vector"
] |
570823c0e4154075513945f12f210f22b62d2cf5 | 3,633 | cpp | C++ | engine/src/virtualmachine/virtualmachine.cpp | anujv99/GameEngine | 644cb6667800cfecaa429666e5610e27f923e953 | [
"MIT"
] | null | null | null | engine/src/virtualmachine/virtualmachine.cpp | anujv99/GameEngine | 644cb6667800cfecaa429666e5610e27f923e953 | [
"MIT"
] | null | null | null | engine/src/virtualmachine/virtualmachine.cpp | anujv99/GameEngine | 644cb6667800cfecaa429666e5610e27f923e953 | [
"MIT"
] | null | null | null | #include "virtualmachine.h"
#include "vmlogger.h"
#include "utils/datafile.h"
#include "luabind/bindcorelib.h"
#include "luabind/bindimguilib.h"
#include "luabind/bindgraphicslib.h"
#include "luabind/bindmath.h"
#include "luabind/bindsystemlib.h"
namespace prev {
static lua_State * S;
VirtualMachine::VirtualMachine() : L(nullptr), m_GuiFunction(-1), m_RenderFunction(-1), m_UpdateFunction(-1) {
L = luaL_newstate();
luaL_openlibs(L);
LuaBindMath(L);
LuaBindCoreLib(L);
LuaBindImGuiLib(L);
LuaBindGraphicsLib(L);
LuaBindSystemLib(L);
}
VirtualMachine::~VirtualMachine() {
lua_close(L);
}
void VirtualMachine::DoString(const pvstring & script) {
if (luaL_dostring(L, script.c_str()) != LUA_OK) {
LOG_ERROR("LUA ERROR : %s", lua_tostring(L, -1));
lua_pop(L, 1);
return;
}
}
Config VirtualMachine::ReadConfigFile(const pvstring & path) {
DataFile file;
if (!file.OpenFile(path)) { return Config(); }
DoString(file.ReadEntireFile());
Config c;
lua_getglobal(L, "Config");
if (lua_type(L, -1) != LUA_TTABLE) { LOG_ERROR("Invalid config file : %s", path.c_str()); return c; }
lua_pushstring(L, "Width");
lua_gettable(L, -2);
if (lua_type(L, -1) == LUA_TNUMBER) { c.WindowWidth = lua_tointeger(L, -1); lua_pop(L, 1); }
lua_pushstring(L, "Height");
lua_gettable(L, -2);
if (lua_type(L, -1) == LUA_TNUMBER) { c.WindowHeight = lua_tointeger(L, -1); lua_pop(L, 1); }
lua_pushstring(L, "Title");
lua_gettable(L, -2);
if (lua_type(L, -1) == LUA_TSTRING) { c.WindowTitle = lua_tostring(L, -1); lua_pop(L, 1); }
lua_pushstring(L, "API");
lua_gettable(L, -2);
if (lua_type(L, -1) == LUA_TSTRING) { c.GraphicsAPI = lua_tostring(L, -1); lua_pop(L, 1); }
lua_pushstring(L, "ResDir");
lua_gettable(L, -2);
if (lua_type(L, -1) == LUA_TSTRING) { c.ResFolderDir = lua_tostring(L, -1); lua_pop(L, 1); }
lua_pop(L, 1);
return c;
}
void VirtualMachine::Init(const pvstring & script) {
if (!FileUtils::FileExists(script)) { LOG_ERROR("Unable to find main script file"); return; }
if (luaL_dofile(L, script.c_str()) != LUA_OK) {
VMLogger::Log("%s", lua_tostring(L, -1));
}
lua_getglobal(L, "g_main_app");
ASSERTM(lua_type(L, -1) == LUA_TTABLE, "Invalid script file");
lua_pushstring(L, "update");
lua_gettable(L, -2);
ASSERTM(lua_type(L, -1) == LUA_TFUNCTION, "main_app table should contain update function");
m_UpdateFunction = luaL_ref(L, LUA_REGISTRYINDEX);
lua_pushstring(L, "render");
lua_gettable(L, -2);
ASSERTM(lua_type(L, -1) == LUA_TFUNCTION, "main_app table should contain render function");
m_RenderFunction = luaL_ref(L, LUA_REGISTRYINDEX);
lua_pushstring(L, "gui");
lua_gettable(L, -2);
ASSERTM(lua_type(L, -1) == LUA_TFUNCTION, "main_app table should contain gui function");
m_GuiFunction = luaL_ref(L, LUA_REGISTRYINDEX);
lua_pop(L, 1);
}
void VirtualMachine::Update(float dt) {
lua_rawgeti(L, LUA_REGISTRYINDEX, m_UpdateFunction);
lua_getglobal(L, "g_main_app");
lua_pushnumber(L, dt);
int err = lua_pcall(L, 2, 0, 0);
if (err != LUA_OK) {
LOG_ERROR("LUA ERROR : %s", lua_tostring(L, -1));
}
}
void VirtualMachine::Render() {
lua_rawgeti(L, LUA_REGISTRYINDEX, m_RenderFunction);
lua_getglobal(L, "g_main_app");
int err = lua_pcall(L, 1, 0, 0);
if (err != LUA_OK) {
LOG_ERROR("LUA ERROR : %s", lua_tostring(L, -1));
}
}
void VirtualMachine::Gui() {
lua_rawgeti(L, LUA_REGISTRYINDEX, m_GuiFunction);
lua_getglobal(L, "g_main_app");
int err = lua_pcall(L, 1, 0, 0);
if (err != LUA_OK) {
LOG_ERROR("LUA ERROR : %s", lua_tostring(L, -1));
}
}
} | 27.732824 | 111 | 0.667492 | [
"render"
] |
570ad4cbb166cc7ab5d568313ad80ac3b2a40c13 | 8,730 | cpp | C++ | src/AppLogic/Filter.cpp | h4koo/FSP_ImageDeconvolution | 724b3c9a1a0a7c45803bd783f61e0363046a2d79 | [
"MIT"
] | null | null | null | src/AppLogic/Filter.cpp | h4koo/FSP_ImageDeconvolution | 724b3c9a1a0a7c45803bd783f61e0363046a2d79 | [
"MIT"
] | null | null | null | src/AppLogic/Filter.cpp | h4koo/FSP_ImageDeconvolution | 724b3c9a1a0a7c45803bd783f61e0363046a2d79 | [
"MIT"
] | null | null | null | #include "Filter.hpp"
namespace AppLogic
{
Filter::Filter() : last_used_noise_type(noise_type_t::GAUSSIAN), last_used_noise_value(0), is_canceled(false)
{
}
string Filter::getImagePath(size_t index)
{
if (index > this->loaded_file_paths.size())
index = 0;
return this->loaded_file_paths[index];
}
vector<string> Filter::loadImagesFromFolder(string folder_path)
{
this->clearWorkingImages();
ImageLoader il;
this->working_images = il.loadImagesFromFolder(folder_path.c_str());
this->loaded_file_names = il.getLoadedImageNames();
this->loaded_file_paths = il.getLoadedImagePaths();
this->calc_info.file_image_source = il.getSourceDirectory();
this->image_set = this->getWorkingImagesMat();
return this->loaded_file_names;
}
string Filter::loadSingleImage(string folder_path)
{
ImageLoader il;
// this->working_images.clear();
this->working_images.push_back(il.loadSingleImage(folder_path.c_str()));
this->loaded_file_names.push_back(il.getLoadedImageNames()[0]);
this->loaded_file_paths.push_back(il.getLoadedImagePaths()[0]);
this->image_set = this->getWorkingImagesMat();
return il.getLoadedImageNames()[0];
}
bool Filter::calculateFilter(size_t rank, calc_method_t calc_method)
{
try{
std::chrono::_V2::system_clock::time_point t1, t2;
switch (calc_method)
{
case calc_method_t::RCIMA_METHOD:
t1 = high_resolution_clock::now();
this->F_matrix = frcima::rcima(this->image_set, this->getDirtyWorkingImagesMat(), rank);
t2 = high_resolution_clock::now();
break;
case calc_method_t::FAST_RCIMA_METHOD:
t1 = high_resolution_clock::now();
this->F_matrix = frcima::fast_rcima(this->image_set, this->getDirtyWorkingImagesMat(), rank);
t2 = high_resolution_clock::now();
break;
default:
break;
}
auto duration = duration_cast<std::chrono::milliseconds>(t2 - t1);
this->calc_info.calc_time_seconds = float(duration.count()) / 1000;
this->calc_info.f_matrix_num_col = this->F_matrix.n_cols;
this->calc_info.f_matrix_num_row = this->F_matrix.n_rows;
this->calc_info.image_calc_amount = this->working_images.size();
this->calc_info.rank = rank;
this->calc_info.calculation_method = Filter::getCalculationMethodName(calc_method);
this->calc_info.noise_type = VecImage::getNoiseName(this->last_used_noise_type);
this->calc_info.noise_value = this->last_used_noise_value;
return true;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
return false;
}
}
VecImage Filter::applyNoiseToImage(size_t image_id, size_t noise_value, noise_type_t noise_type)
{
this->last_used_noise_type = noise_type;
this->last_used_noise_value = noise_value;
VecImage result;
if (image_id > this->working_images.size())
{
return result;
}
result = VecImage(this->working_images[image_id]);
result.applyNoise(noise_value, noise_type);
return result;
}
// void Filter::applyNoiseToWorkingImages(size_t noise_value, noise_type_t noise_type)
// {
// this->last_used_noise_type = noise_type;
// this->last_used_noise_value = noise_value;
// for (auto &image : this->working_images)
// image.applyNoise(noise_value, noise_type);
// this->calc_info.noise_type = VecImage::getNoiseName(noise_type);
// this->calc_info.noise_value = noise_value;
// }
bool Filter::saveToFile(string folder_path)
{
if (this->F_matrix.n_rows > 0)
{
string file_name = folder_path + this->calc_info.filter_name + FILTER_FILE_EXTENSION;
return this->F_matrix.save(file_name);
}
return false;
}
bool Filter::loadFmatrixFromFile(string file_path)
{
this->F_matrix.reset();
return this->F_matrix.load(file_path);
}
mat Filter::getWorkingImagesMat()
{
mat w_image_set;
if (this->working_images.size())
{
size_t columns = working_images.size(); //training set amount of images
size_t rows = working_images[0].numCols() * working_images[0].numRows(); // training set size of vectorized image
w_image_set = mat(rows, columns);
for (size_t col = 0; col < columns; ++col)
{
vec current_image = this->working_images[col].getDoubleData();
for (size_t r = 0; r < rows; ++r)
{
w_image_set(r, col) = current_image(r);
}
}
}
return w_image_set;
}
mat Filter::getDirtyWorkingImagesMat()
{
mat w_image_set;
if (this->working_images.size())
{
size_t columns = working_images.size(); //training set amount of images
size_t rows = working_images[0].numCols() * working_images[0].numRows(); // training set size of vectorized image
w_image_set = mat(rows, columns);
for (size_t col = 0; col < columns; ++col)
{
VecImage v_img(this->working_images[col]);
v_img.applyNoise(this->last_used_noise_value, this->last_used_noise_type);
vec current_image = v_img.getVecDoubleData();
for (size_t r = 0; r < rows; ++r)
{
w_image_set(r, col) = current_image(r);
}
}
}
return w_image_set;
}
bool Filter::saveFilterInfo(string folder_path)
{
string file_name = folder_path + this->calc_info.filter_name + FILTER_INFO_EXTENSION;
fstream fi_binary_file(file_name, std::ios::out | std::ios::binary | std::ios::app);
if (fi_binary_file.is_open())
{
fi_binary_file << this->calc_info;
fi_binary_file.close();
return true;
}
return false;
}
void Filter::cancelSaveDirtyImages()
{
this->is_canceled = true;
}
bool Filter::saveAllDirtyImages(string folder_path)
{
for (size_t index = 0; index < this->working_images.size(); ++index)
{
if (this->is_canceled)
{
this->is_canceled = false;
return false;
}
string filename = folder_path + "/" + this->loaded_file_names[index] + DIRTY_IMAGE_SUFFIX;
if (!this->applyNoiseToImage(index, this->last_used_noise_value, this->last_used_noise_type).save(filename))
return false;
}
return true;
}
bool Filter::saveDirtyImage(size_t image_id, string folder_path)
{
if (image_id > this->working_images.size())
return false;
return this->applyNoiseToImage(image_id, this->last_used_noise_value, this->last_used_noise_type).save(folder_path);
}
string Filter::getCalculationMethodName(calc_method_t calc_method)
{
// **NOTE** don't add whitespace to the names since it breaks FilterInfo loading
switch (calc_method)
{
case calc_method_t::FAST_RCIMA_METHOD:
return "Fast-RCIMA";
case calc_method_t::RCIMA_METHOD:
return "RCIMA";
default:
return "Unknown";
}
}
vector<string> Filter::loadImagesFromZip(string file_path)
{
this->clearWorkingImages();
ImageLoader il;
this->working_images = il.loadImagesFromZip(file_path.c_str());
this->loaded_file_names = il.getLoadedImageNames();
this->loaded_file_paths = il.getLoadedImagePaths();
this->calc_info.file_image_source = il.getSourceDirectory();
this->image_set = this->getWorkingImagesMat(); // can be done on a different thread to avoid blocking
return this->loaded_file_names;
}
VecImage *Filter::getLoadedImage(const size_t index)
{
if (index > this->working_images.size())
return NULL;
return &(this->working_images[index]);
}
}
| 35.201613 | 126 | 0.583963 | [
"vector"
] |
5714572a1ac663fde9324937bfc82ac50974a4a0 | 3,579 | cpp | C++ | CF R426/C.cpp | parthlathiya/Codeforces_Submissions | 6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68 | [
"MIT"
] | null | null | null | CF R426/C.cpp | parthlathiya/Codeforces_Submissions | 6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68 | [
"MIT"
] | null | null | null | CF R426/C.cpp | parthlathiya/Codeforces_Submissions | 6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define re(i,b) for(ll i=0;i<b;i++)
#define repr(i,n) for(ll i=n-1;i>=0;i--)
#define ll long long
#define ld long double
#define llu long long unsigned
#define pll std::pair<ll, ll>
#define ppll std::pair<ll, pll>
#define vll std::vector<ll>
#define vpll std::vector<pll>
#define vppll std::vector<ppll>
#define mll std::map<ll, ll>
#define mpll std::map<pll, ll>
#define mppll std::map<ppll, ll>
#define sll std::set<ll>
#define ff first
#define ss second
#define msll std::multiset<ll>
#define all(c) c.begin(), c.end()
#define allr(c) c.rbegin(), c.rend()
#define srt(x) sort(all(x))
#define rsrt(x) sort(allr(x))
#define mp make_pair
#define mt make_tuple
#define eb emplace_back
#define pb push_back
#define s(yy) ll yy;cin>>yy
#define mod 1e9+7
#define maxlong 1e18+5
/*
######################################################
# #
# @author #
# Parth Lathiya #
# https://www.cse.iitb.ac.in/~parthiitb/ #
# #
######################################################
*/
vll primes;
mll prime;
mll primee;
void sieve(ll n)
{
rep(i,2,n+1)
{
if(!prime[i])
{
primes.pb(i);
primee[i]=1;
// s.pb(i);
for(ll j=i+i;j<=n;j+=i)
prime[j]=1;
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifdef PARTH_LATHIYA_HOME
freopen("C_in.txt","r",stdin);
ll ttt,bkkk;
cin>>ttt;
bkkk=ttt;
while(ttt--) {
cout<<"Testcase - "<<bkkk-ttt<<"\n";
#endif
//--------------------------------------------------------------------------------------
// std::vector<int> v[100];
// std::vector<int> temp(100,4);
// rep(i,0,100)
// v[i] = temp;
s(n);
sieve(31634);
ll x,y;
while(n--)
{
cin>>x>>y;
ll bkx=x;
ll bky=y;
vpll vx,vy;
for(auto a:primes)
{
if(a>x)break;
ll cnt=0;
while(x!=1 && x%a==0)
{
cnt++;
x/=a;
}
if(primee[x]==1)
{
vx.pb({x,1});x=1;
// break;
}
if(cnt)
vx.pb({a,cnt});
}
for(auto a:primes)
{
if(a>y)break;
ll cnt=0;
while(y!=1 && y%a==0)
{
cnt++;
y/=a;
}
if(primee[y]==1)
{
// cout<<y;
vy.pb({y,1});y=1;
// break;
}
// cout<<y<<"dd"<<cnt<<"d"<<endl;
if(cnt)
vy.pb({a,cnt});
}
int ans=-1;
// cout<<vx.size()<<vy.size();
if(bkx==1 && bky==1)
ans=1;
else if(x!=1 && y!=1)
ans=0;
else if(vx.size()!=vy.size())
ans=0;
else
{
srt(vx);
srt(vy);
ll i=0;
while(i<vx.size())
{
if(vx[i].ff!=vy[i].ff)
{ans=0; break;}
else
{
// ll temp=vx[i].ss;
int f=0;
// re(p,temp/2+1)
// {
// cout<<p<<"s";
// cout<<p<<" "<<(temp-p*2)*2+p<<endl;
// if((temp-p*2)*2+p==vy[i].ss){
// f=1;break;}
// }
// if(f==0)
// {ans=0; break;}
ll t1=vx[i].ss;
ll t2=vy[i].ss;
while(t1>=0 && t2>=0)
{
if(t1>t2){t1-=2;
t2--;
}
else
{
t1--;
t2-=2;
}
if(t1==0 && t2==0){f=1;break;}
}
if(f==0)
{ ans=0;break;}
}
i++;
}
if(ans==-1)
ans=1;
}
if(ans==0)
cout<<"No\n";
else
cout<<"Yes\n";
}
//--------------------------------------------------------------------------------------
#ifdef PARTH_LATHIYA_HOME
cout<<"\n"; }
#endif
return 0;
} | 17.373786 | 88 | 0.4247 | [
"vector"
] |
571679ff65c400cf2d9e7f6ac3429a1a7b789eb4 | 198 | cpp | C++ | NOTLA C++/NOTLA C++/Enemies.cpp | AlbertVanNeinstein/NOTLA-C- | cb6be106fc426137c66769d5b11bf8cc327fedf0 | [
"MIT"
] | null | null | null | NOTLA C++/NOTLA C++/Enemies.cpp | AlbertVanNeinstein/NOTLA-C- | cb6be106fc426137c66769d5b11bf8cc327fedf0 | [
"MIT"
] | null | null | null | NOTLA C++/NOTLA C++/Enemies.cpp | AlbertVanNeinstein/NOTLA-C- | cb6be106fc426137c66769d5b11bf8cc327fedf0 | [
"MIT"
] | null | null | null | #include "stdafx.h"
//#include "Objects.h"
//#include <iostream>
//#include <string>
//#include <vector>
//Enemy Array Stats. Order: Health, Attack, Defense, Speed.
//int zombie[4]{ 100, 10, 5, 1}; | 24.75 | 59 | 0.661616 | [
"vector"
] |
571b2ec5d4d3cecda52873adbaf7596b6d3d1530 | 1,708 | hpp | C++ | includes/concept.hpp | whackashoe/sdr | 4655263ce28bd6990b70c2b560982a31e65c89a9 | [
"MIT"
] | 1 | 2015-07-27T00:52:11.000Z | 2015-07-27T00:52:11.000Z | includes/concept.hpp | whackashoe/sdr | 4655263ce28bd6990b70c2b560982a31e65c89a9 | [
"MIT"
] | null | null | null | includes/concept.hpp | whackashoe/sdr | 4655263ce28bd6990b70c2b560982a31e65c89a9 | [
"MIT"
] | null | null | null | #ifndef SDR_CONCEPT_H_
#define SDR_CONCEPT_H_
#include "constants.hpp"
#include <vector>
#include <array>
#include <bitset>
#include <algorithm>
#include <cstddef>
#include <iterator>
namespace sdr
{
// this holds all of the traits for a single concept
// ie - if width is 1024, this could hold up to 1024 values between 0 and 1024
// designed to be fast to create, pass around, and as util to compress sparse data
struct concept
{
std::vector<sdr::position_t> data;
// for vector of positions we assume the data has already been dealt with
explicit concept(const std::vector<sdr::position_t> & input)
: data(input) {}
// otherwise we assume that is hasn't, thus we only add non zero fields
template <sdr::width_t W>
concept(const std::bitset<W> & input)
: data()
{
for(std::size_t i=0; i < input.size(); ++i) {
if(input[i]) {
data.emplace_back(i);
}
}
}
// store [amount] largest ones from input
template <typename T, sdr::width_t W>
concept(
const std::array<T, W> & input,
const std::size_t amount
)
: data()
{
std::vector<sdr::position_t> idx(input.size());
std::iota(std::begin(idx), std::end(idx), 0);
std::partial_sort(std::begin(idx), std::begin(idx) + amount, std::end(idx), [&](
const T a,
const T b
) {
return input[a] > input[b];
});
for(std::size_t i=0; i < amount; ++i) {
// end if value is 0
if(! input[idx[i]]) {
break;
}
data.emplace_back(idx[i]);
}
}
};
} //namespace sdr
#endif
| 23.722222 | 88 | 0.564988 | [
"vector"
] |
571c5c9aee1a4cc4d635e97bf2a89a2c5b9da252 | 5,356 | cpp | C++ | gl/old-2oo7/foo.cpp | vmiklos/vmexam | ff4ef386d3cfd84b8ed06387cbd87b119dd50448 | [
"MIT"
] | 1 | 2015-02-09T10:21:51.000Z | 2015-02-09T10:21:51.000Z | gl/old-2oo7/foo.cpp | vmiklos/vmexam | ff4ef386d3cfd84b8ed06387cbd87b119dd50448 | [
"MIT"
] | null | null | null | gl/old-2oo7/foo.cpp | vmiklos/vmexam | ff4ef386d3cfd84b8ed06387cbd87b119dd50448 | [
"MIT"
] | null | null | null | /*
* kisfeladat1.cpp
*
* Copyright (c) 2007 by Miklos Vajna <vmiklos@frugalware.org>
*/
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <stdio.h>
#include <math.h>
#include <limits.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Vector
{
float x, y;
Vector(float x0, float y0)
{
x = x0;
y = y0;
}
};
Vector** vectors[4];
int vsizes[4];
int dlevel = 0;
float divide(float a, float b)
{
float ret = a/b;
if(fpclassify(ret) == FP_INFINITE)
ret = INT_MAX*isinf(ret);
return ret;
}
int intersect(float x1, float y1, float x2, float y2, float u1, float v1, float u2, float v2, float *xi, float*yi)
{
float b1 = divide((y2-y1),(x2-x1));
float b2 = divide((v2-v1),(u2-u1));
float a1 = (y1-b1*x1);
float a2 = (v1-b2*u1);
*xi = - divide((a1-a2),(b1-b2));
*yi = (a1+b1 * *xi);
// ez lenne a teljes ellenorzes ket szakasz eseten, viszont itt mi csak
// a masodik szakaszra akarunk ellenorizni
//if (((x1-*xi)*(*xi-x2))>=0 && ((u1-*xi)*(*xi-u2))>=0 && ((y1-*yi)*(*yi-y2))>=0 && ((v1-*yi)*(*yi-v2))>=0)
if (((u1-*xi)*(*xi-u2))>=0 && ((v1-*yi)*(*yi-v2))>=0)
return(0);
else
return(-1);
}
bool is_inside(float qx, float qy)
{
int count = 0;
// fektetunk egy vizszintes egyenest a kerdeses pontra
float qx2 = qx + 1;
float qy2 = qy;
for(int i=0;i<vsizes[dlevel];i++)
{
int n;
if(i+1 < vsizes[dlevel])
n = i+1;
else
n = 0;
float mx, my;
if(intersect(qx, qy, qx2, qy2, (*vectors[dlevel][i]).x, (*vectors[dlevel][i]).y,
(*vectors[dlevel][n]).x, (*vectors[dlevel][n]).y, &mx, &my) == 0 && mx > qx)
count++;
}
return (count%2);
}
void ReDraw( ) {
glClearColor(0, 0, 1, 0);
glClear(GL_COLOR_BUFFER_BIT);
glColor3d( 1.0, 1.0, 1.0 );
glBegin(GL_LINE_LOOP);
// a dlevel mondja megy, hogy milyen szintu simitas kell, es a vsizes
// tomb mondja meg, hogy hany pontot rajzolunk ezen a szinten
for(int i=0;i<vsizes[dlevel];i++)
// a pontok koordinataihoz pedig kozvetlenul hozzaferhetunk
glVertex2d((*vectors[dlevel][i]).x, (*vectors[dlevel][i]).y);
glEnd( );
glFlush( );
}
void Mouse(int button, int state, int x, int y)
{
if(state != GLUT_DOWN)
return;
// szamoljuk at a virtualis vilag koordinataiba
float vx = float(x)/2;
float vy = float(200-y)/2;
if(!is_inside(vx, vy))
// kivul kattintottak
return;
if(button == GLUT_LEFT_BUTTON)
{
if(dlevel == 3)
// mar a maximumon vagyunk
return;
dlevel++;
// kiszamoljuk, hogy az uj levelen hany pont lesz
int size = (vsizes[dlevel-1]*2);
if(vectors[dlevel] == NULL)
{
// ezen a levelen meg nem jartunk, ki kell szamolni a pontokat
vectors[dlevel] = new Vector* [size];
vsizes[dlevel] = size;
for(int i=1;i<=size;i++)
{
int p = i/2-1;
int n = i/2;
if(i==size)
n = 0;
if(i%2==0)
{
// a paros (zold) pontokat szamoljuk ki
// eloszor. atlagoljuk az elozo korben
// felvett ket pont koordinatait
float x = ((*vectors[dlevel-1][p]).x+(*vectors[dlevel-1][n]).x)/2;
float y = ((*vectors[dlevel-1][p]).y+(*vectors[dlevel-1][n]).y)/2;
vectors[dlevel][i-1] = new Vector(x,y);
}
}
for(int i=1;i<=size;i++)
{
// ebben a masodik korben szamoljuk a paratlan
// pontokat, mivel mostmar megvan a kovetkezo
// paros pont erteke is minden paratlan ponthoz
int pp = i/2;
int p = i-2;
int n = i;
if(i==1)
{
// az elso vagy utolso pont spec eset
p = vsizes[dlevel]-1;
}
else if(i==size)
n = 0;
if(i%2==1)
{
float x = 0.5*(*vectors[dlevel-1][pp]).x + 0.25*((*vectors[dlevel][p]).x + (*vectors[dlevel][n]).x);
float y = 0.5*(*vectors[dlevel-1][pp]).y + 0.25*((*vectors[dlevel][p]).y + (*vectors[dlevel][n]).y);
vectors[dlevel][i-1] = new Vector(x,y);
}
}
// elkeszultunk a pontok kiszamitasaval
}
}
else if(button == GLUT_RIGHT_BUTTON)
{
if(dlevel == 0)
// ennel tovabb nem lehet csokkenteni a simitast
return;
dlevel--;
}
// vegul rajzoljuk ki azt amit alkottunk
ReDraw();
}
main(int argc, char **argv)
{
ifstream myfile ("pontok.txt");
string line;
// oprendszer ablak init glut modra
glutInitWindowSize(200, 200);
glutInitWindowPosition(100, 100);
glutInit(&argc, argv);
glutInitDisplayMode( GLUT_RGB );
glutCreateWindow("kisfeladat1");
// meret a kepernyon
glViewport(0, 0, 200, 200);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity( );
glMatrixMode(GL_PROJECTION);
glLoadIdentity( );
// ablak merete a virtualis vilagra
gluOrtho2D(0., 100., 0., 100.);
// callbackek
glutMouseFunc(Mouse);
glutDisplayFunc( ReDraw );
// vektorok feltoltese
if (myfile.is_open())
{
getline (myfile,line);
// ennyi pontunk lesz
int count = (int)atoi(line.c_str());
vectors[dlevel] = new Vector* [count];
vsizes[dlevel] = count;
int i=0;
// mostpedig beolvassuk a koordinatakat
while (! myfile.eof() )
{
getline (myfile,line);
if(line.length())
{
size_t pos = line.find(',');
string buf = line.substr(0,pos);
float x = (float)atof(buf.c_str());
buf = line.substr(pos+1);
float y = (float)atof(buf.c_str());
vectors[dlevel][i++] = new Vector(x, y);
}
}
myfile.close();
}
else
cout << "nem lehet megnyitni a file-t";
// rajzoljuk a kezdeti koordinatakat
ReDraw();
// fo hurok
glutMainLoop();
}
| 22.888889 | 114 | 0.612584 | [
"vector"
] |
5727407d82faf1cc027a1e9b977626ee3e893e36 | 581 | cpp | C++ | Aula04/Ejercicio3_MayorSuma.cpp | VanessaMMH/ProgComp2021A | 03a3e0394b26eb78801246c7d6b7888fe53141bd | [
"BSD-3-Clause"
] | null | null | null | Aula04/Ejercicio3_MayorSuma.cpp | VanessaMMH/ProgComp2021A | 03a3e0394b26eb78801246c7d6b7888fe53141bd | [
"BSD-3-Clause"
] | null | null | null | Aula04/Ejercicio3_MayorSuma.cpp | VanessaMMH/ProgComp2021A | 03a3e0394b26eb78801246c7d6b7888fe53141bd | [
"BSD-3-Clause"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
/*
Dado un array que contiene números enteros positivos y negativos. Encuentre
la mayor suma de sus subarrays
*/
int mayor_sum(vector <int>& v){
int mayor_suma = v[0];
int suma = 0;
for (int i = 0; i < v.size(); i++){
suma = suma + v[i];
if(suma > mayor_suma )
{
mayor_suma = suma;
}
else if(suma < 0)
suma = 0;
}
return mayor_suma;
}
int main(){
vector <int> v= {1,-2, 3, 10, -4, 7, 2, -5};
cout << mayor_sum(v);
return 0;
} | 19.366667 | 75 | 0.518072 | [
"vector"
] |
573231584ce8c4976fbacc9a58d3d0738047b2f1 | 7,069 | hpp | C++ | include/MixtureWCRP.hpp | robert-lindsey/WCRP | 7e46c02d430b5fdc7a13dda42cc965b87f640346 | [
"MIT"
] | 19 | 2015-11-02T01:28:57.000Z | 2022-03-31T06:14:46.000Z | include/MixtureWCRP.hpp | wpmarinho/WCRP | 7e46c02d430b5fdc7a13dda42cc965b87f640346 | [
"MIT"
] | 1 | 2017-04-13T08:18:40.000Z | 2017-04-13T08:18:40.000Z | include/MixtureWCRP.hpp | wpmarinho/WCRP | 7e46c02d430b5fdc7a13dda42cc965b87f640346 | [
"MIT"
] | 6 | 2016-11-08T02:18:47.000Z | 2020-12-20T20:18:05.000Z | /*
The MIT License (MIT)
Copyright (c) 2015 Robert Lindsey
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MIXTURE_WCRP_H
#define MIXTURE_WCRP_H
#include "Random.hpp"
#include "common.hpp"
typedef double(*prior_log_density_fn) (const double x);
class MixtureWCRP {
public:
MixtureWCRP(Random * generator,
const set<size_t> & train_students,
const vector< vector<bool> > & recall_sequences,
const vector< vector<size_t> > & item_sequences,
const vector<size_t> & provided_skill_assignments,
const double gamma,
const double init_alpha_prime,
const size_t num_students,
const size_t num_items,
const size_t num_subsamples);
~MixtureWCRP();
void run_mcmc(const size_t num_iterations, const size_t burn, const bool infer_gamma, const bool infer_alpha_prime);
// returns the expected posterior probability that the student responds correctly to the trial number
double get_estimated_recall_prob(const size_t student, const size_t trial) const;
// returns the skill assignments for each item across all samples
// each returned vector has one entry per item denoting the skill id
vector< vector<size_t> > get_sampled_skill_labels() const;
// returns the skill assignments which maximized the training data log likelihood
// the returned vector has one entry per item denoting the skill id
vector<size_t> get_most_likely_skill_labels() const;
protected:
double full_data_log_likelihood(const bool is_training, size_t & trials_included) const;
double data_log_likelihood(const vector<size_t> & students, const vector<size_t> & first_exposures) const;
double data_log_likelihood(const size_t student, const size_t first_exposure, size_t & num_trials) const;
bool studied_any_of(const size_t student, const vector<size_t> & items) const;
void record_sample(const double train_ll);
double log_seating_prob() const;
// resample the skill assignment (table) for this item (customer)
// see algorithm 8 from http://www.stat.purdue.edu/~rdutta/24.PDF
void gibbs_resample_skill(const size_t item);
double slice_resample_bkt_parameter(const size_t skill_id, double * param, const vector<size_t> & students_to_include, const vector<size_t> & first_exposures, const double cur_ll);
double slice_resample_wcrp_param(double * param, const double cur_seating_lp, const double lower_bound, const double upper_bound, const double init_bracket, prior_log_density_fn prior_lp);
// bootstraps calculating a student's data log likelihood by precomputed forward state
void cache_p_hat(const size_t student, const size_t end_trial, boost::unordered_map<size_t, double> & p_hat) const;
double skill_log_likelihood(const size_t skill_id, const vector<size_t> & affected_students, const vector<size_t> & first_exposures, const vector< boost::unordered_map<size_t, double> > & init_p_hat) const;
double skill_log_likelihood(const size_t skill_id, const vector<size_t> & affected_students, const vector<size_t> & first_exposures) const;
void draw_bkt_param_prior(struct bkt_parameters & params) const;
double compute_K(const size_t item, const size_t table_id, const bool am_initializing) const;
bool remove_item_from_table(const size_t item, const size_t table_id);
void assign_item_to_table(const size_t item, const size_t table_id, const bool is_new_table);
Random * generator;
// constants
const set<size_t> & train_students;
const vector< vector<bool> > & recall_sequences;
const vector< vector<size_t> > & item_sequences;
const vector<size_t> & provided_skill_assignments;
const size_t num_students;
const size_t num_items;
const size_t num_subsamples;
const bool use_expert_labels;
// Markov chain state
vector<size_t> seating_arrangement; // seating_arrangement[item] = table id
boost::unordered_map<size_t, struct bkt_parameters> parameters; // mapping b/w table id and parameter values
double log_alpha_prime;
double log_gamma;
// MCMC helper variables
size_t num_used_skills;
boost::unordered_map<size_t, size_t> table_sizes; // table_sizes[table_id] = # of items assigned to it
set<size_t> extant_tables;
boost::unordered_map<size_t, boost::unordered_map<size_t, vector<size_t> > > trial_lookup; // trial_lookup[table_id][student_id] = sequence of trial #s assigned to the student-skill pair
size_t tables_ever_instantiated;
vector<struct bkt_parameters> prior_samples; // auxiliary variables for the non-conjugate gibbs sampler
vector< vector<double> > singleton_skill_data_lp;
// dataset helper variables
vector< vector<bool> > ever_studied; // ever_studied[student][item] = true if at any time the student studied the item (and is in the training set)
vector<size_t> all_items;
vector< vector<size_t> > students_who_studied; // students_who_studied[item] = list of TRAINING students who at any time studied the item
vector< vector<size_t> > all_first_encounters; // all_first_encounters[item]....
vector< vector<size_t> > first_encounter; // first_encounter[student][item] = trial index the student first studied the item. ='s -1 if they never did
vector< vector< vector<size_t> > > trials_studied; // trials_studied[student][item] = list of all trials where the student studied the item
size_t num_expert_provided_skills;
vector< vector<pair<size_t, bool> > > item_and_recall_sequences; // student, trial, (item, recall)
// these variables record the sampler state for later reporting
vector< vector< vector<double> > > pRT_samples; // pRT_samples[student][trial][sample number]
vector< vector<size_t> > skill_label_samples; // skill_label_samples[sample number][item] = skill id (note: skill ids are sample-specific)
vector<double> train_ll_samples; // train_ll[sample number] = the training data log likelihood of that sample
};
#endif
| 51.224638 | 210 | 0.751733 | [
"vector"
] |
573dbfde0412d2d6be932c00e68ba70969b091b3 | 1,446 | cc | C++ | RAVL2/3D/CameraCal/PinholeCamera0.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/3D/CameraCal/PinholeCamera0.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/3D/CameraCal/PinholeCamera0.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2001, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
//! rcsid="$Id: PinholeCamera0.cc 1533 2002-08-08 16:03:23Z craftit $"
//! lib=RavlCameraCal
//! file="Ravl/3D/CameraCal/PinholeCamera0.cc"
#include "Ravl/3D/PinholeCamera0.hh"
namespace Ravl3DN
{
using namespace RavlN;
istream& operator>>(istream& s, PinholeCamera0C& camera)
{
s >> camera.fx() >> camera.fy() >> camera.cx() >> camera.cy();
s >> camera.R();
s >> camera.t();
return s;
}
ostream& operator<<(ostream& s, const PinholeCamera0C& camera)
{
s << camera.fx()
<< " " << camera.fy()
<< " " << camera.cx()
<< " " << camera.cy()
<< endl;
s << camera.R();
s << camera.t();
return s;
}
BinIStreamC& operator>>(BinIStreamC& s, PinholeCamera0C& camera)
{
s >>
camera.fx() >>
camera.fy() >>
camera.cx() >>
camera.cy() >>
camera.R() >>
camera.t();
return s;
}
BinOStreamC& operator<<(BinOStreamC& s, const PinholeCamera0C& camera)
{
s << camera.fx()
<< camera.fy()
<< camera.cx()
<< camera.cy()
<< camera.R()
<< camera.t();
return s;
}
};
| 24.1 | 74 | 0.574689 | [
"3d"
] |
57425c790fdba0e0cd81f826a523705d3dae4572 | 7,698 | cpp | C++ | source/tests/FlattenIteratorTest.cpp | 0xflotus/mariana-trench | 6c8c28a2b89a9eea70c09cae9b594ae4594d97a6 | [
"MIT"
] | null | null | null | source/tests/FlattenIteratorTest.cpp | 0xflotus/mariana-trench | 6c8c28a2b89a9eea70c09cae9b594ae4594d97a6 | [
"MIT"
] | 4 | 2021-08-21T07:51:53.000Z | 2022-02-27T20:22:41.000Z | source/tests/FlattenIteratorTest.cpp | LaudateCorpus1/mariana-trench | 35595e2782d823a5ed9908dd4fe3bdc06d611ba1 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <list>
#include <map>
#include <vector>
#include <gmock/gmock.h>
#include <mariana-trench/FlattenIterator.h>
#include <mariana-trench/tests/Test.h>
namespace marianatrench {
class FlattenIteratorTest : public test::Test {};
namespace {
template <typename Iterator>
std::vector<typename std::iterator_traits<Iterator>::value_type> collect(
Iterator begin,
Iterator end) {
std::vector<typename std::iterator_traits<Iterator>::value_type> result;
for (; begin != end; ++begin) {
result.push_back(*begin);
}
return result;
}
} // namespace
TEST_F(FlattenIteratorTest, VectorVectorInt) {
using Vector = std::vector<int>;
using VectorVector = std::vector<std::vector<int>>;
using Iterator = FlattenIterator<
/* OuterIterator */ std::vector<std::vector<int>>::iterator,
/* InnerIterator */ std::vector<int>::iterator>;
VectorVector container = {};
EXPECT_EQ(
collect(
Iterator(container.begin(), container.end()),
Iterator(container.end(), container.end())),
Vector{});
container = {{1}, {2, 3}, {4, 5, 6}};
EXPECT_EQ(
collect(
Iterator(container.begin(), container.end()),
Iterator(container.end(), container.end())),
(Vector{1, 2, 3, 4, 5, 6}));
container = {{}, {1}, {}, {2, 3}, {}, {4, 5, 6}, {}};
EXPECT_EQ(
collect(
Iterator(container.begin(), container.end()),
Iterator(container.end(), container.end())),
(Vector{1, 2, 3, 4, 5, 6}));
container = {{1}, {}, {2, 3}, {}, {4, 5}, {}, {6}};
EXPECT_EQ(
collect(
Iterator(container.begin(), container.end()),
Iterator(container.end(), container.end())),
(Vector{1, 2, 3, 4, 5, 6}));
}
TEST_F(FlattenIteratorTest, ListVectorInt) {
using Vector = std::vector<int>;
using ListVector = std::list<std::vector<int>>;
using Iterator = FlattenIterator<
/* OuterIterator */ std::list<std::vector<int>>::iterator,
/* InnerIterator */ std::vector<int>::iterator>;
ListVector container = {};
EXPECT_EQ(
collect(
Iterator(container.begin(), container.end()),
Iterator(container.end(), container.end())),
Vector{});
container = {{1}, {2, 3}, {4, 5, 6}};
EXPECT_EQ(
collect(
Iterator(container.begin(), container.end()),
Iterator(container.end(), container.end())),
(Vector{1, 2, 3, 4, 5, 6}));
container = {{}, {1}, {}, {2, 3}, {}, {4, 5, 6}, {}};
EXPECT_EQ(
collect(
Iterator(container.begin(), container.end()),
Iterator(container.end(), container.end())),
(Vector{1, 2, 3, 4, 5, 6}));
container = {{1}, {}, {2, 3}, {}, {4, 5}, {}, {6}};
EXPECT_EQ(
collect(
Iterator(container.begin(), container.end()),
Iterator(container.end(), container.end())),
(Vector{1, 2, 3, 4, 5, 6}));
}
TEST_F(FlattenIteratorTest, ConstVectorVectorInt) {
using Vector = std::vector<int>;
using VectorVector = std::vector<std::vector<int>>;
using Iterator = FlattenIterator<
/* OuterIterator */ std::vector<std::vector<int>>::const_iterator,
/* InnerIterator */ std::vector<int>::const_iterator,
/* Dereference */
FlattenConstDereference<std::vector<std::vector<int>>::const_iterator>>;
VectorVector container = {};
EXPECT_EQ(
collect(
Iterator(container.cbegin(), container.cend()),
Iterator(container.cend(), container.cend())),
Vector{});
container = {{1}, {2, 3}, {4, 5, 6}};
EXPECT_EQ(
collect(
Iterator(container.cbegin(), container.cend()),
Iterator(container.cend(), container.cend())),
(Vector{1, 2, 3, 4, 5, 6}));
container = {{}, {1}, {}, {2, 3}, {}, {4, 5, 6}, {}};
EXPECT_EQ(
collect(
Iterator(container.cbegin(), container.cend()),
Iterator(container.cend(), container.cend())),
(Vector{1, 2, 3, 4, 5, 6}));
container = {{1}, {}, {2, 3}, {}, {4, 5}, {}, {6}};
EXPECT_EQ(
collect(
Iterator(container.cbegin(), container.cend()),
Iterator(container.cend(), container.cend())),
(Vector{1, 2, 3, 4, 5, 6}));
}
TEST_F(FlattenIteratorTest, MapVectorInt) {
using Vector = std::vector<int>;
using MapVector = std::map<int, std::vector<int>>;
struct Dereference {
static std::vector<int>::const_iterator begin(
const std::pair<const int, std::vector<int>>& p) {
return p.second.cbegin();
}
static std::vector<int>::const_iterator end(
const std::pair<const int, std::vector<int>>& p) {
return p.second.cend();
}
};
using Iterator = FlattenIterator<
/* OuterIterator */ std::map<int, std::vector<int>>::const_iterator,
/* InnerIterator */ std::vector<int>::const_iterator,
Dereference>;
MapVector container = {};
EXPECT_EQ(
collect(
Iterator(container.cbegin(), container.cend()),
Iterator(container.cend(), container.cend())),
Vector{});
container = {{0, {1}}, {1, {2, 3}}, {3, {4, 5, 6}}};
EXPECT_EQ(
collect(
Iterator(container.cbegin(), container.cend()),
Iterator(container.cend(), container.cend())),
(Vector{1, 2, 3, 4, 5, 6}));
container = {
{0, {}},
{1, {1}},
{2, {}},
{3, {2, 3}},
{4, {}},
{5, {4, 5, 6}},
{6, {}}};
EXPECT_EQ(
collect(
Iterator(container.cbegin(), container.cend()),
Iterator(container.cend(), container.cend())),
(Vector{1, 2, 3, 4, 5, 6}));
container = {
{0, {1}}, {1, {}}, {2, {2, 3}}, {3, {}}, {4, {4, 5}}, {5, {}}, {6, {6}}};
EXPECT_EQ(
collect(
Iterator(container.cbegin(), container.cend()),
Iterator(container.cend(), container.cend())),
(Vector{1, 2, 3, 4, 5, 6}));
}
TEST_F(FlattenIteratorTest, MapListInt) {
using Vector = std::vector<int>;
using MapVector = std::map<int, std::list<int>>;
struct Dereference {
static std::list<int>::const_iterator begin(
const std::pair<const int, std::list<int>>& p) {
return p.second.cbegin();
}
static std::list<int>::const_iterator end(
const std::pair<const int, std::list<int>>& p) {
return p.second.cend();
}
};
using Iterator = FlattenIterator<
/* OuterIterator */ std::map<int, std::list<int>>::const_iterator,
/* InnerIterator */ std::list<int>::const_iterator,
Dereference>;
MapVector container = {};
EXPECT_EQ(
collect(
Iterator(container.cbegin(), container.cend()),
Iterator(container.cend(), container.cend())),
Vector{});
container = {{0, {1}}, {1, {2, 3}}, {3, {4, 5, 6}}};
EXPECT_EQ(
collect(
Iterator(container.cbegin(), container.cend()),
Iterator(container.cend(), container.cend())),
(Vector{1, 2, 3, 4, 5, 6}));
container = {
{0, {}},
{1, {1}},
{2, {}},
{3, {2, 3}},
{4, {}},
{5, {4, 5, 6}},
{6, {}}};
EXPECT_EQ(
collect(
Iterator(container.cbegin(), container.cend()),
Iterator(container.cend(), container.cend())),
(Vector{1, 2, 3, 4, 5, 6}));
container = {
{0, {1}}, {1, {}}, {2, {2, 3}}, {3, {}}, {4, {4, 5}}, {5, {}}, {6, {6}}};
EXPECT_EQ(
collect(
Iterator(container.cbegin(), container.cend()),
Iterator(container.cend(), container.cend())),
(Vector{1, 2, 3, 4, 5, 6}));
}
} // namespace marianatrench
| 29.494253 | 79 | 0.561055 | [
"vector"
] |
5748f9f5f9e968a1519d273ddef7b1ca5b7ee6fc | 9,160 | cc | C++ | cfg4/attic/CSurLib.cc | seriksen/opticks | 2173ea282bdae0bbd1abf4a3535bede334413ec1 | [
"Apache-2.0"
] | 1 | 2020-05-13T06:55:49.000Z | 2020-05-13T06:55:49.000Z | cfg4/attic/CSurLib.cc | seriksen/opticks | 2173ea282bdae0bbd1abf4a3535bede334413ec1 | [
"Apache-2.0"
] | null | null | null | cfg4/attic/CSurLib.cc | seriksen/opticks | 2173ea282bdae0bbd1abf4a3535bede334413ec1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019 Opticks Team. All Rights Reserved.
*
* This file is part of Opticks
* (see https://bitbucket.org/simoncblyth/opticks).
*
* 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 <sstream>
#include "G4MaterialPropertiesTable.hh"
#include "G4OpticalSurface.hh"
#include "G4LogicalBorderSurface.hh"
#include "G4LogicalSkinSurface.hh"
#include "G4LogicalVolume.hh"
#include "BStr.hh"
#include "Opticks.hh"
#include "GVector.hh"
#include "GProperty.hh"
#include "GPropertyMap.hh"
#include "GOpticalSurface.hh"
#include "GSurfaceLib.hh"
#include "GSurLib.hh"
#include "GSur.hh"
#include "CMPT.hh"
#include "CSurLib.hh"
#include "COptical.hh"
#include "COpticalSurface.hh"
#include "CDetector.hh"
#include "PLOG.hh"
CSurLib::CSurLib(GSurLib* surlib)
:
m_surlib(surlib),
m_ok(surlib->getOpticks()),
m_dbgsurf(m_ok->isDbgSurf()),
m_surfacelib(surlib->getSurfaceLib()),
m_detector(NULL)
{
}
void CSurLib::setDetector(CDetector* detector)
{
assert(m_detector == NULL);
m_detector = detector ;
}
std::string CSurLib::brief()
{
std::stringstream ss;
ss << "CSurLib "
<< " num CSur " << m_surlib->getNumSur()
<< " --> "
<< " numBorderSurface " << m_border.size()
<< " numSkinSurface " << m_skin.size()
;
return ss.str();
}
unsigned CSurLib::getNumSur()
{
return m_surlib->getNumSur();
}
GSur* CSurLib::getSur(unsigned index)
{
return m_surlib->getSur(index);
}
// called by CGeometry::init for both CGDMLDetector and CTestDetector branches
//
// TODO:converse method would seems more appropriate
//
// detector->attachSurfaces(CSurLib* )
//
void CSurLib::convert(CDetector* detector)
{
assert(m_surlib->isClosed()); // typically closed in CDetector::attachSurfaces
setDetector(detector);
unsigned numSur = m_surlib->getNumSur();
if(m_dbgsurf)
LOG(info) << "[--dbgsurf] CSurLib::convert numSur " << numSur ;
for(unsigned i=0 ; i < numSur ; i++)
{
GSur* sur = m_surlib->getSur(i);
if(sur->isBorder())
{
G4OpticalSurface* os = makeOpticalSurface(sur);
unsigned nvp = sur->getNumVolumePair();
for(unsigned ivp=0 ; ivp < nvp ; ivp++)
{
G4LogicalBorderSurface* lbs = makeBorderSurface(sur, ivp, os);
m_border.push_back(lbs);
}
}
else if(sur->isSkin())
{
G4OpticalSurface* os = makeOpticalSurface(sur);
unsigned nlv = sur->getNumLV();
for(unsigned ilv=0 ; ilv < nlv ; ilv++)
{
G4LogicalSkinSurface* lss = makeSkinSurface(sur, ilv, os);
m_skin.push_back(lss);
}
}
else
{
LOG(verbose) << "CSurLib::convert SKIPPED GSur index " << i << " : " << sur->brief() ;
}
}
LOG(info) << brief();
}
G4OpticalSurface* CSurLib::makeOpticalSurface(GSur* sur)
{
bool bs = sur->isBorder();
bool ss = sur->isSkin();
assert( bs ^ ss );
const char* flavor = bs ? "border" : "skin" ;
GPropertyMap<float>* pmap = sur->getPMap();
GOpticalSurface* os_ = pmap->getOpticalSurface();
const char* name = os_->getName() ;
guint4 optical = os_->getOptical();
G4OpticalSurface* os = new G4OpticalSurface(name);
G4OpticalSurfaceModel model = COptical::Model(1) ; // 0:glisur, 1:unified (no SPECULARSPIKE SPECULARLOBE, just Lambertian?)
G4OpticalSurfaceFinish finish = COptical::Finish(optical.z) ; // polished,,,ground,,,
G4SurfaceType type = COptical::Type(optical.y) ; // dielectric_metal, dielectric_dielectric
os->SetModel(model);
os->SetFinish(finish);
os->SetType(type);
LOG(debug) << "CSurLib::makeOpticalSurface "
<< std::setw(10) << flavor
<< COpticalSurface::Brief(os)
;
G4MaterialPropertiesTable* mpt = new G4MaterialPropertiesTable();
os->SetMaterialPropertiesTable(mpt);
addProperties(mpt, pmap);
return os ;
}
// lookup G4 pv1,pv2 from volume indices recorded in pairs
G4LogicalBorderSurface* CSurLib::makeBorderSurface(GSur* sur, unsigned ivp, G4OpticalSurface* os)
{
GPropertyMap<float>* pmap = sur->getPMap();
const char* name = pmap->getName() ;
guint4 pair = sur->getVolumePair(ivp);
unsigned ipv1 = pair.x ;
unsigned ipv2 = pair.y ;
if(m_dbgsurf)
LOG(info) << "CSurLib::makeBorderSurface"
<< " name " << name
<< " ipv1 " << ipv1
<< " ipv2 " << ipv2
;
assert(pair.w == ivp);
assert( ipv1 != GSurLib::UNSET && "CSurLib::makeBorderSurface ipv1 UNSET" );
assert( ipv2 != GSurLib::UNSET && "CSurLib::makeBorderSurface ipv2 UNSET" );
const G4VPhysicalVolume* pv1 = m_detector->getPV(ipv1);
const G4VPhysicalVolume* pv2 = m_detector->getPV(ipv2);
assert( pv1 );
assert( pv2 );
G4LogicalBorderSurface* lbs = new G4LogicalBorderSurface(name,
const_cast<G4VPhysicalVolume*>(pv1),
const_cast<G4VPhysicalVolume*>(pv2),
os);
return lbs ;
}
// lookup G4 lv via name
G4LogicalSkinSurface* CSurLib::makeSkinSurface(GSur* sur, unsigned ilv, G4OpticalSurface* os)
{
GPropertyMap<float>* pmap = sur->getPMap();
const char* name = pmap->getName() ;
const char* daelvn = sur->getLV(ilv); // assuming LV identity is 1-to-1 with name
bool trimPtr = false ;
char* lvn = BStr::DAEIdToG4(daelvn, trimPtr);
const G4LogicalVolume* lv = m_detector->getLV(lvn);
if(m_dbgsurf)
LOG(info) << "CSurLib::makeSkinSurface"
<< " ilv " << std::setw(5) << ilv
<< " name " << std::setw(35) << name
<< " lvn " << std::setw(35) << lvn
<< " daelvn " << std::setw(35) << daelvn
<< " lv " << ( lv ? lv->GetName() : "NULL" )
;
G4LogicalSkinSurface* lss = new G4LogicalSkinSurface(name, const_cast<G4LogicalVolume*>(lv), os );
return lss ;
}
void CSurLib::addProperties(G4MaterialPropertiesTable* mpt_, GPropertyMap<float>* pmap)
{
/**
Property values hail from GSurfaceLib::createStandardSurface
which did the preparations for the Opticks texture, so
there should be little to do here other than translate into
EFFICIENCY and REFLECTIVITY ?
**/
CMPT mpt(mpt_);
GOpticalSurface* os_ = pmap->getOpticalSurface();
//unsigned nprop = pmap->getNumProperties();
//const char* name = pmap->getShortName();
//LOG(info) << "CSurLib::addProperties " << name ;
GProperty<float>* detect = pmap->getProperty(GSurfaceLib::detect);
GProperty<float>* absorb = pmap->getProperty(GSurfaceLib::absorb);
GProperty<float>* specular = pmap->getProperty(GSurfaceLib::reflect_specular);
GProperty<float>* diffuse = pmap->getProperty(GSurfaceLib::reflect_diffuse);
bool is_sensor = pmap->isSensor(); // ?? always false
bool is_specular = os_->isSpecular();
bool detect_zero = detect->isZero();
bool absorb_zero = absorb->isZero();
bool specular_zero = specular->isZero();
bool diffuse_zero = diffuse->isZero();
bool spline = false ;
std::stringstream ss, tt ;
if(!detect_zero) ss << " sensor " ;
mpt.addProperty("EFFICIENCY", detect, spline );
// Opticks distinguishes specular from diffuse by putting
// the REFLECTIVITY prop in either
// reflect_specular or reflect_diffuse slot
// so reverse that here...
if(specular_zero && diffuse_zero )
{
ss << " zerorefl " ;
mpt.addProperty("REFLECTIVITY", specular , spline );
}
else if(specular_zero && !diffuse_zero )
{
ss << " diffuse " ;
mpt.addProperty("REFLECTIVITY", diffuse , spline );
}
else if(!specular_zero && diffuse_zero )
{
ss << " specular " ;
mpt.addProperty("REFLECTIVITY", specular , spline );
}
else
{
assert(0);
}
if(detect_zero) tt << "detect_zero " ;
if(absorb_zero) tt << "absorb_zero " ;
if(specular_zero) tt << "specular_zero " ;
if(diffuse_zero) tt << "diffuse_zero " ;
if(is_sensor) tt << " is_sensor " ;
if(is_specular) tt << " is_specular " ;
/*
LOG(info)
<< " name " << std::setw(35) << name
<< " nprop " << std::setw(4) << nprop
<< std::setw(30) << ss.str()
<< std::setw(50) << tt.str()
;
LOG(info) << mpt.description("MPT:");
*/
}
| 27.42515 | 129 | 0.61059 | [
"model"
] |
5749ac83f345923b9e2ce2feb5c2beb1e590d971 | 5,890 | cpp | C++ | ReleaseTests/SpAsgnTest.cpp | vishalbelsare/CombBLAS | 426f6be0b29831025cdcacc1f8f69e3520bfb0ff | [
"BSD-3-Clause-LBNL"
] | 22 | 2020-08-14T19:14:13.000Z | 2022-02-05T20:14:59.000Z | ReleaseTests/SpAsgnTest.cpp | vishalbelsare/CombBLAS | 426f6be0b29831025cdcacc1f8f69e3520bfb0ff | [
"BSD-3-Clause-LBNL"
] | 8 | 2020-10-09T23:23:36.000Z | 2021-08-05T20:35:18.000Z | ReleaseTests/SpAsgnTest.cpp | vishalbelsare/CombBLAS | 426f6be0b29831025cdcacc1f8f69e3520bfb0ff | [
"BSD-3-Clause-LBNL"
] | 8 | 2020-12-04T09:10:06.000Z | 2022-01-04T15:37:59.000Z | /****************************************************************/
/* Parallel Combinatorial BLAS Library (for Graph Computations) */
/* version 1.5 -------------------------------------------------*/
/* date: 10/09/2015 ---------------------------------------------*/
/* authors: Ariful Azad, Aydin Buluc, Adam Lugowski ------------*/
/****************************************************************/
/*
Copyright (c) 2010-2015, The Regents of the University of California
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <mpi.h>
#include <sys/time.h>
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
#include <sstream>
#include "CombBLAS/CombBLAS.h"
using namespace std;
using namespace combblas;
template <typename IT, typename NT>
pair< FullyDistVec<IT,IT>, FullyDistVec<IT,NT> > TopK(FullyDistSpVec<IT,NT> & v, IT k)
{
// FullyDistVec::FullyDistVec(IT glen, NT initval)
FullyDistVec<IT,IT> sel(v.getcommgrid(), k, 0);
//void FullyDistVec::iota(IT globalsize, NT first)
sel.iota(k, v.TotalLength() - k);
FullyDistSpVec<IT,NT> sorted(v);
FullyDistSpVec<IT,IT> perm = sorted.sort();
// FullyDistVec FullyDistSpVec::operator(FullyDistVec & v)
FullyDistVec<IT,IT> topkind = perm(sel);
FullyDistVec<IT,NT> topkele = v(topkind);
return make_pair(topkind, topkele);
}
struct mypair
{
mypair(double rhs)
{
val = make_pair(rhs, -rhs);
}
mypair()
{
val = make_pair(1,-1);
}
pair<double, double> val;
};
int main(int argc, char* argv[])
{
int nprocs, myrank;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD,&nprocs);
MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
if(argc < 8)
{
if(myrank == 0)
{
cout << "Usage: ./SpAsgnTest <BASEADDRESS> <Matrix> <PrunedMatrix> <RHSMatrix> <AssignedMatrix> <VectorRowIndices> <VectorColIndices>" << endl;
cout << "Example: ./SpAsgnTest TESTDATA/ A_100x100.txt A_with20x30hole.txt dense_20x30matrix.txt A_wdenseblocks.txt 20outta100.txt 30outta100.txt" << endl;
cout << "Input files should be under <BASEADDRESS> in triples format" << endl;
}
MPI_Finalize();
return -1;
}
{
string directory(argv[1]);
string normalname(argv[2]);
string prunedname(argv[3]);
string rhsmatname(argv[4]);
string assignname(argv[5]);
string vec1name(argv[6]);
string vec2name(argv[7]);
normalname = directory+"/"+normalname;
prunedname = directory+"/"+prunedname;
rhsmatname = directory+"/"+rhsmatname;
assignname = directory+"/"+assignname;
vec1name = directory+"/"+vec1name;
vec2name = directory+"/"+vec2name;
ifstream inputvec1(vec1name.c_str());
ifstream inputvec2(vec2name.c_str());
if(myrank == 0)
{
if(inputvec1.fail() || inputvec2.fail())
{
cout << "One of the input vector files do not exist, aborting" << endl;
MPI_Abort(MPI_COMM_WORLD, NOFILE);
return -1;
}
}
MPI_Barrier(MPI_COMM_WORLD);
typedef SpParMat <int64_t, double , SpDCCols<int64_t,double> > PARDBMAT;
typedef SpParMat <int64_t, mypair , SpDCCols<int64_t, mypair > > PARPAIRMAT;
shared_ptr<CommGrid> fullWorld;
fullWorld.reset( new CommGrid(MPI_COMM_WORLD, 0, 0) );
PARDBMAT A(fullWorld);
PARDBMAT Apr(fullWorld);
PARDBMAT B(fullWorld);
PARDBMAT C(fullWorld);
FullyDistVec<int64_t,int64_t> vec1(fullWorld);
FullyDistVec<int64_t,int64_t> vec2(fullWorld);
A.ReadDistribute(normalname, 0);
Apr.ReadDistribute(prunedname, 0);
B.ReadDistribute(rhsmatname, 0);
C.ReadDistribute(assignname, 0);
vec1.ReadDistribute(inputvec1, 0);
vec2.ReadDistribute(inputvec2, 0);
vec1.Apply(bind2nd(minus<int64_t>(), 1)); // For 0-based indexing
vec2.Apply(bind2nd(minus<int64_t>(), 1));
PARDBMAT Atemp = A;
Atemp.Prune(vec1, vec2);
PARPAIRMAT Apair = A;
Apair.Prune(vec1, vec2);
PARDBMAT Apruned = A;
Apruned.PruneFull(vec1, vec2);
Apruned.ParallelWriteMM("ArowscolsPruned.mtx", true);
// We should get the original A back.
if( Atemp == Apr)
{
SpParHelper::Print("Pruning is working\n");
}
else
{
SpParHelper::Print("Error in pruning, go fix it\n");
}
A.SpAsgn(vec1, vec2, B);
if (A == C)
{
SpParHelper::Print("SpAsgn working correctly\n");
}
else
{
SpParHelper::Print("ERROR in SpAsgn, go fix it!\n");
A.SaveGathered("Erroneous_SpAsgnd.txt");
}
FullyDistVec<int64_t,int64_t> crow(fullWorld);
FullyDistVec<int64_t,int64_t> ccol(fullWorld);
FullyDistVec<int64_t,double> cval(fullWorld);
A.Find(crow, ccol, cval);
FullyDistSpVec<int64_t, double> sval = cval;
// sval.DebugPrint();
pair< FullyDistVec<int64_t,int64_t> , FullyDistVec<int64_t,double> > ptopk;
ptopk = TopK(sval, (int64_t) 3);
//ptopk.first.DebugPrint();
//ptopk.second.DebugPrint();
inputvec1.clear();
inputvec1.close();
inputvec2.clear();
inputvec2.close();
}
MPI_Finalize();
return 0;
}
| 30.518135 | 158 | 0.673005 | [
"vector"
] |
5750f4026d97bdf1fe6e2be831f9f5105f8c849a | 3,437 | cpp | C++ | src/caffe/layers/weight_transfer_layer.cpp | apir8181/caffe_icml2016 | b0a318bf76a005a89dc9d46c39e37cb9b4a7f201 | [
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/weight_transfer_layer.cpp | apir8181/caffe_icml2016 | b0a318bf76a005a89dc9d46c39e37cb9b4a7f201 | [
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/weight_transfer_layer.cpp | apir8181/caffe_icml2016 | b0a318bf76a005a89dc9d46c39e37cb9b4a7f201 | [
"BSD-2-Clause"
] | null | null | null | #include <vector>
#include "caffe/filler.hpp"
#include "caffe/layers/weight_transfer_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void WeightTransferLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const int axis = bottom[0]->CanonicalAxisIndex(
this->layer_param_.weight_transfer_param().axis());
const int weight_output = this->layer_param_.weight_transfer_param().weight_output_num();
const int weight_input = bottom[0]->count(axis);
N_ = weight_output;
K_ = weight_input;
// Check if we need to set up the weights
bias_term_ = this->layer_param_.weight_transfer_param().bias_term();
if (this->blobs_.size() > 0) {
LOG(INFO) << "Skipping parameter initialization";
} else {
if (bias_term_) {
this->blobs_.resize(2);
} else {
this->blobs_.resize(1);
}
// Intialize the weight
vector<int> weight_shape(2);
weight_shape[0] = N_;
weight_shape[1] = K_;
this->blobs_[0].reset(new Blob<Dtype>(weight_shape));
// fill the weights
shared_ptr<Filler<Dtype> > weight_filler(GetFiller<Dtype>(
this->layer_param_.weight_transfer_param().weight_filler()));
weight_filler->Fill(this->blobs_[0].get());
// If necessary, intiialize and fill the bias term
if (bias_term_) {
vector<int> bias_shape(1, N_);
this->blobs_[1].reset(new Blob<Dtype>(bias_shape));
shared_ptr<Filler<Dtype> > bias_filler(GetFiller<Dtype>(
this->layer_param_.weight_transfer_param().bias_filler()));
bias_filler->Fill(this->blobs_[1].get());
caffe_gpu_set(this->blobs_[1]->count(), Dtype(0), this->blobs_[1]->mutable_gpu_diff());
}
} // parameter initialization
this->param_propagate_down_.resize(this->blobs_.size(), true);
caffe_gpu_set(bottom[0]->count(), Dtype(0), bottom[0]->mutable_gpu_diff());
caffe_gpu_set(this->blobs_[0]->count(), Dtype(0), this->blobs_[0]->mutable_gpu_diff());
}
template <typename Dtype>
void WeightTransferLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
// Figure out the dimensions
// const int axis = bottom[0]->CanonicalAxisIndex(
// this->layer_param_.weight_transfer_param().axis());
// const int new_N = bottom[0]->count(axis);
// CHECK_EQ(N_, new_N)
// << "Input size incompatible with weight transfer parameters.";
// M_ = bottom[0]->count(0, axis);
// The top shape will be the bottom shape with the flattened axes dropped,
// and replaced by a single axis with dimension num_output (N_).
vector<int> top_shape(2);
top_shape[0] = N_;
top_shape[1] = K_;
top[0]->Reshape(top_shape);
// Set up the bias multiplier
// if (bias_term_) {
// vector<int> bias_shape(1, M_);
// bias_multiplier_.Reshape(bias_shape);
// caffe_set(M_, Dtype(1), bias_multiplier_.mutable_cpu_data());
// }
}
template <typename Dtype>
void WeightTransferLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
}
template <typename Dtype>
void WeightTransferLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype>*>& bottom) {
}
#ifdef CPU_ONLY
STUB_GPU(WeightTransferLayer);
#endif
INSTANTIATE_CLASS(WeightTransferLayer);
REGISTER_LAYER_CLASS(WeightTransfer);
} // namespace caffe
| 36.178947 | 93 | 0.693337 | [
"shape",
"vector"
] |
57589907a18039f26e907a7067ca83af0f9c7205 | 6,165 | cpp | C++ | locomotion_framework/models/robot_class/src/contacts.cpp | ADVRHumanoids/DrivingFramework | 34715c37bfe3c1f2bd92aeacecc12704a1a7820e | [
"Zlib"
] | 1 | 2019-12-02T07:10:42.000Z | 2019-12-02T07:10:42.000Z | locomotion_framework/models/robot_class/src/contacts.cpp | ADVRHumanoids/DrivingFramework | 34715c37bfe3c1f2bd92aeacecc12704a1a7820e | [
"Zlib"
] | null | null | null | locomotion_framework/models/robot_class/src/contacts.cpp | ADVRHumanoids/DrivingFramework | 34715c37bfe3c1f2bd92aeacecc12704a1a7820e | [
"Zlib"
] | 2 | 2020-10-22T19:06:44.000Z | 2021-06-07T03:32:52.000Z | #include "mwoibn/robot_class/contacts.h"
namespace mwoibn
{
namespace robot_class
{
bool mwoibn::robot_class::Contacts::remove(int i)
{
if (i < 0 || i >= _contacts.size())
return false;
_contacts.erase(_contacts.begin() + i);
resize();
return true;
}
int mwoibn::robot_class::Contacts::getId(std::string name) const
{
auto foundItem = std::find_if(_contacts.begin(), _contacts.end(),
[&name](auto const& contact)
{
return contact->getName() == name;
});
if (foundItem == _contacts.end())
return -1;
else
return std::distance(_contacts.begin(), foundItem);
}
mwoibn::robot_points::Contact&
mwoibn::robot_class::Contacts::contact(unsigned int id)
{
if (id < _contacts.size())
return *_contacts.at(id);
else
throw std::out_of_range("Given ID is beyond a vector scope");
}
std::vector<unsigned int>
mwoibn::robot_class::Contacts::getActive(std::vector<std::string>* names) const
{
std::vector<unsigned int> ids;
for (int i = 0; i < _contacts.size(); i++)
{
if (_contacts[i]->isActive())
ids.push_back(i);
}
if (names)
{
for (auto& id : ids)
names->push_back(_contacts[id]->getName());
}
return ids;
}
std::vector<unsigned int> mwoibn::robot_class::Contacts::getInactive(
std::vector<std::string>* names) const
{
std::vector<unsigned int> ids;
for (int i = 0; i < _contacts.size(); i++)
{
if (!_contacts[i]->isActive())
ids.push_back(i);
}
if (names)
{
for (auto& id : ids)
names->push_back(_contacts[id]->getName());
}
return ids;
}
unsigned int mwoibn::robot_class::Contacts::sizeActive() const
{
int i = 0;
for (auto& contact : _contacts)
if (contact->isActive())
++i;
return i;
}
unsigned int mwoibn::robot_class::Contacts::sizeInactive() const
{
int i = 0;
for (auto& contact : _contacts)
if (!contact->isActive())
++i;
return i;
}
const mwoibn::Matrix& mwoibn::robot_class::Contacts::getJacobian()
{
_jacobian.setZero();
unsigned int i = 0;
for (auto& contact : _contacts)
{
_jacobian.block(i, 0, contact->jacobianSize(), _dofs) = contact->getPointJacobian();
i += contact->jacobianSize();
}
return _jacobian;
}
const mwoibn::Matrix& mwoibn::robot_class::Contacts::getWorldJacobian()
{
_jacobian.setZero();
unsigned int i = 0;
for (auto& contact : _contacts)
{
_jacobian.block(i, 0, contact->jacobianSize(), _dofs) = contact->getWorldJacobian();
i += contact->jacobianSize();
}
return _jacobian;
}
mwoibn::Matrix
mwoibn::robot_class::Contacts::getMinimumJacobian()
{
_jacobian.setZero();
unsigned int i = 0;
int j = 0;
for (auto& contact : _contacts)
{
if (contact->isActive())
{
_jacobian.block(i, 0, contact->jacobianSize(), _dofs) = contact->getPointJacobian();
i += contact->jacobianSize();
j++;
}
}
return _jacobian.topRows(i);
}
std::vector<mwoibn::Matrix>
mwoibn::robot_class::Contacts::getJacobians()
{
std::vector<mwoibn::Matrix> jacobians;
for (auto& contact : _contacts)
{
jacobians.push_back(contact->getPointJacobian());
}
return jacobians;
}
std::vector<mwoibn::Matrix>
mwoibn::robot_class::Contacts::getWorldJacobians()
{
std::vector<mwoibn::Matrix> jacobians;
for (auto& contact : _contacts)
{
jacobians.push_back(contact->getWorldJacobian());
}
return jacobians;
}
std::vector<mwoibn::Matrix>
mwoibn::robot_class::Contacts::getMinimumJacobians()
{
std::vector<mwoibn::Matrix> jacobians;
for (auto& contact : _contacts)
{
if (contact->isActive())
jacobians.push_back(contact->getPointJacobian());
}
return jacobians;
}
const mwoibn::VectorN& mwoibn::robot_class::Contacts::getReactionForce()
{
_forces.setZero();
unsigned int i = 0;
for (auto& contact : _contacts)
{
// std::cout << contact->getName() << "\t" << contact->jacobianSize() << "\t\t\t" << contact->getReactionForce().transpose() << std::endl;
_forces.segment(i,contact->jacobianSize()) = contact->getReactionForce();
i += contact->jacobianSize();
}
return _forces;
}
std::vector<mwoibn::VectorN>
mwoibn::robot_class::Contacts::getReactionForces()
{
std::vector<mwoibn::VectorN> forces;
for (auto& contact : _contacts)
{
forces.push_back(contact->getReactionForce());
}
return forces;
}
const mwoibn::VectorN& mwoibn::robot_class::Contacts::getPosition()
{
_positions.setZero();
unsigned int i = 0;
for (auto& contact : _contacts)
{
_positions.segment<7>(i) = contact->getPosition();
i += 7;
}
return _positions;
}
std::vector<mwoibn::VectorN>
mwoibn::robot_class::Contacts::getPositions()
{
std::vector<mwoibn::VectorN> positions;
for (auto& contact : _contacts)
{
positions.push_back(contact->getPosition());
}
return positions;
}
mwoibn::VectorBool
mwoibn::robot_class::Contacts::getTypes(std::vector<CONTACT_TYPE> types)
{
mwoibn::VectorBool state(size());
for (int i = 0; i < size(); i++)
{
if (std::find(types.begin(), types.end(), _contacts.at(i)->type()) !=
types.end())
state[i] = true;
else
state[i] = false;
}
return state;
}
const mwoibn::VectorBool& mwoibn::robot_class::Contacts::getDofs()
{
_boolean_checks.setConstant(false);
for (auto& contact : _contacts)
{
for (int i = 0; i < contact->getChain().size(); i++)
_boolean_checks[contact->getChain()[i]] = true;
}
return _boolean_checks;
}
const mwoibn::VectorBool& mwoibn::robot_class::Contacts::getActiveDofs()
{
_boolean_checks.setConstant(false);
int i = 0;
for (auto& contact : _contacts)
{
if (!contact->isActive())
continue;
for (int i = 0; i < contact->getChain().size(); i++)
_boolean_checks[contact->getChain()[i]] = true;
}
return _boolean_checks;
}
const mwoibn::VectorBool& mwoibn::robot_class::Contacts::getInactiveDofs()
{
_boolean_checks.noalias() = mwoibn::eigen_utils::flip(getActiveDofs());
return _boolean_checks;
}
} // namespace package
} // namespace library
| 20.346535 | 143 | 0.640876 | [
"vector"
] |
57656c39dfde3b22d499ad3797eefbe4614c87d5 | 698 | cpp | C++ | qtcreator/MToNdri/main.cpp | fasShare/cpp-study | b7d691a02324260e09e5e35c0a71650ddb37fd97 | [
"MIT"
] | null | null | null | qtcreator/MToNdri/main.cpp | fasShare/cpp-study | b7d691a02324260e09e5e35c0a71650ddb37fd97 | [
"MIT"
] | null | null | null | qtcreator/MToNdri/main.cpp | fasShare/cpp-study | b7d691a02324260e09e5e35c0a71650ddb37fd97 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stack>
#include <vector>
#include <string>
// 把数M转化为N进制数
using namespace std;
int abs(int n) {
return n < 0 ? -n : n;
}
int main() {
int M, N;
cin >> M >> N;
stack<char> nums;
vector<char> chars = {'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'A', 'B',
'C', 'D', 'E', 'F'};
int dri = abs(M);
while (dri != 0) {
nums.push(chars[dri % N]);
dri /= N;
}
if (M < 0) {
std::cout << "-";
}
while(!nums.empty()) {
std::cout << nums.top();
nums.pop();
}
std::cout << std::endl;
return 0;
}
| 17.02439 | 46 | 0.383954 | [
"vector"
] |
576ce59fe05a4030c8de54541805cf25117e9168 | 3,128 | cpp | C++ | SoundFontInfoLib/SoundFontInfoLib/Render/Voice/State.cpp | kant/SoundFonts | a5d678e2cfbd299e460db4f7ec747fcb6554512f | [
"MIT"
] | 41 | 2019-01-04T07:09:03.000Z | 2022-03-15T05:36:23.000Z | SoundFontInfoLib/SoundFontInfoLib/Render/Voice/State.cpp | kant/SoundFonts | a5d678e2cfbd299e460db4f7ec747fcb6554512f | [
"MIT"
] | 2 | 2020-12-02T22:31:01.000Z | 2021-12-30T19:58:21.000Z | SoundFontInfoLib/SoundFontInfoLib/Render/Voice/State.cpp | kant/SoundFonts | a5d678e2cfbd299e460db4f7ec747fcb6554512f | [
"MIT"
] | 7 | 2019-01-04T07:09:09.000Z | 2022-02-25T13:31:47.000Z | // Copyright © 2021 Brad Howes. All rights reserved.
#include <cmath>
#include "Render/Envelope/Generator.hpp"
#include "Render/Voice/Config.hpp"
#include "Render/Voice/State.hpp"
using namespace SF2::Render::Voice;
State::State(double sampleRate, const MIDI::Channel& channel, const Config& config) :
sampleRate_{sampleRate}, channel_{channel}, key_{config.key()}, velocity_{config.velocity()}
{
// (1) Initialize to default values
setDefaults();
// (2) Set values from preset and instrument zone configurations that matched the MIDI key/velocity combination.
config.apply(*this);
// (3) Now finish configuring the modulators by resolving any links between them.
for (const auto& modulator : modulators_) {
if (!modulator.configuration().hasModulatorDestination()) continue;
for (auto& destination : modulators_) {
if (destination.configuration().source().isLinked() &&
modulator.configuration().linkDestination() == destination.index()) {
// Set up the destination modulator so that it pulls a value from another modulator when it is asked for a value
// to apply to a generator.
destination.setSource(modulator);
}
}
}
}
void
State::setDefaults() {
gens_.fill(GenValue());
setPrincipleValue(Index::initialFilterCutoff, 13500);
setPrincipleValue(Index::delayModulatorLFO, -12000);
setPrincipleValue(Index::delayVibratoLFO, -12000);
setPrincipleValue(Index::delayModulatorEnvelope, -12000);
setPrincipleValue(Index::attackModulatorEnvelope, -12000);
setPrincipleValue(Index::holdModulatorEnvelope, -12000);
setPrincipleValue(Index::decayModulatorEnvelope, -12000);
setPrincipleValue(Index::releaseModulatorEnvelope, -12000);
setPrincipleValue(Index::delayVolumeEnvelope, -12000);
setPrincipleValue(Index::attackVolumeEnvelope, -12000);
setPrincipleValue(Index::holdVolumeEnvelope, -12000);
setPrincipleValue(Index::decayVolumeEnvelope, -12000);
setPrincipleValue(Index::releaseVolumeEnvelope, -12000);
setPrincipleValue(Index::forcedMIDIKey, -1);
setPrincipleValue(Index::forcedMIDIVelocity, -1);
setPrincipleValue(Index::scaleTuning, 100);
setPrincipleValue(Index::overridingRootKey, -1);
// Install default modulators for the voice. Zones can override them and add new ones.
for (const auto& modulator : Entity::Modulator::Modulator::defaults) {
addModulator(modulator);
}
}
void
State::addModulator(const Entity::Modulator::Modulator& modulator) {
// Per spec, there must only be one modulator with specific (sfModSrcOper, sfModDestOper, and sfModSrcAmtOper)
// values. If we find a duplicate, flag it as not being used, but keep it around so that modulator linking is not
// broken if it is used.
for (auto pos = modulators_.begin(); pos < modulators_.end(); ++pos) {
if (pos->configuration() == modulator) {
pos->flagInvalid();
break;
}
}
size_t index = modulators_.size();
modulators_.emplace_back(index, modulator, *this);
if (modulator.hasGeneratorDestination()) {
gens_[indexValue(modulator.generatorDestination())].mods.push_front(index);
}
}
| 37.686747 | 120 | 0.736893 | [
"render"
] |
5775a1d35c3f4ab0ec7c5486047601bfc1119df1 | 2,286 | hpp | C++ | game_of_life/lib/game_of_life.hpp | rickmarson/game_of_life_nn | 728bb009b9d54268e96f33bb752a3e5ba1ae15d1 | [
"MIT"
] | null | null | null | game_of_life/lib/game_of_life.hpp | rickmarson/game_of_life_nn | 728bb009b9d54268e96f33bb752a3e5ba1ae15d1 | [
"MIT"
] | null | null | null | game_of_life/lib/game_of_life.hpp | rickmarson/game_of_life_nn | 728bb009b9d54268e96f33bb752a3e5ba1ae15d1 | [
"MIT"
] | null | null | null | #include <vector>
#include <stdint.h>
#include <string>
class BLContext;
class BLImage;
namespace common {
namespace gol {
typedef std::vector<std::vector<bool>> Grid;
typedef std::vector<std::vector<float>> ProbabilisticGrid;
class GameOfLife {
public:
GameOfLife() = default;
~GameOfLife() = default;
void initialise(int grid_width, int grid_height, int pixel_size);
void set_output_dir(const std::string& dir) { m_output_dir = dir; }
void update();
void reset();
int get_current_step() const { return m_step; }
const Grid& get_current_grid() const { return m_current_grid; }
const Grid& get_last_grid() const { return m_last_grid; }
[[nodiscard]] std::vector<uint8_t> render_current_grid();
[[nodiscard]] std::vector<uint8_t> render_last_grid();
void render_current_grid_to_file();
void render_last_grid_to_file();
std::vector<uint8_t> render_grid(const Grid& grid, bool save_to_file = false, bool grayscale = true);
std::vector<std::vector<uint8_t>> render_probabilities(const ProbabilisticGrid& grid, bool save_to_file = false);
private:
void render_grid_internal(const Grid& grid, bool save_to_file, std::vector<uint8_t>& pixels_out, std::string file_name = "", bool grayscale = true);
void draw_grid_lines(BLContext& ctx);
void fill_grid(BLContext& ctx, const Grid& grid);
void fill_grid_shaded(BLContext& ctx, const ProbabilisticGrid& grid);
void save_image_to_file(BLImage& img);
int m_step = 0;
int m_width = 0;
int m_height = 0;
int m_cell_pixel_size = 0;
std::string m_output_dir;
Grid m_current_grid;
Grid m_last_grid;
struct Location {
int x;
int y;
};
const std::vector<Location> neighbour_offsets = { {-1, -1},
{-1, 0},
{-1, 1},
{0, -1},
{0, 1},
{1, -1},
{1, 0},
{1, 1} };
};
}
}
| 35.169231 | 154 | 0.551181 | [
"vector"
] |
57766a4f9ebfe1ef4e787fcf5883665e22766f4c | 1,760 | cpp | C++ | srcs/graphics/Map.cpp | Aracthor/pathfindingplusplus | 628516348906c808a866579a41bd2184fa140b8c | [
"Apache-2.0"
] | null | null | null | srcs/graphics/Map.cpp | Aracthor/pathfindingplusplus | 628516348906c808a866579a41bd2184fa140b8c | [
"Apache-2.0"
] | null | null | null | srcs/graphics/Map.cpp | Aracthor/pathfindingplusplus | 628516348906c808a866579a41bd2184fa140b8c | [
"Apache-2.0"
] | null | null | null | #include <SFML/Graphics/RenderTarget.hpp>
#include "graphic/Map.hpp"
namespace graphic
{
Map::Map(const algo::Map& map) :
m_width(map.getWidth()),
m_height(map.getHeight()),
m_shapes(new sf::RectangleShape[m_width * m_height])
{
this->initRectangles(map);
this->initCircles(map);
}
Map::~Map()
{
delete[] m_shapes;
}
void
Map::initRectangles(const algo::Map& map)
{
unsigned int x, y;
sf::RectangleShape model;
model.setSize(sf::Vector2f(TILE_SIZE, TILE_SIZE));
model.setOutlineThickness(TILE_OUTLINE_THICKNESS);
model.setOutlineColor(TILE_OUTLINE_COLOR);
for (x = 0; x < m_width; x++)
{
for (y = 0; y < m_height; y++)
{
sf::RectangleShape& shape = m_shapes[y * m_width + x];
shape = model;
shape.setFillColor(map.at(x, y) == '0' ? WALL_COLOR : PATH_COLOR);
shape.setPosition(x * TILE_SIZE + TILE_OUTLINE_THICKNESS, y * TILE_SIZE + TILE_OUTLINE_THICKNESS);
}
}
}
void
Map::initCircles(const algo::Map& map)
{
sf::CircleShape model;
model.setRadius(POINT_RADIUS);
model.setOutlineThickness(POINT_OUTLINE_THICKNESS);
model.setOutlineColor(POINT_OUTLINE_COLOR);
m_begin = model;
m_begin.setFillColor(BEGIN_FILL_COLOR);
m_begin.move(map.getBegin().x * TILE_SIZE + POINT_SHIFT, map.getBegin().y * TILE_SIZE + POINT_SHIFT);
m_end = model;
m_end.setFillColor(END_FILL_COLOR);
m_end.move(map.getEnd().x * TILE_SIZE + POINT_SHIFT, map.getEnd().y * TILE_SIZE + POINT_SHIFT);
}
void
Map::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
unsigned int i;
for (i = 0; i < m_width * m_height; i++)
{
target.draw(m_shapes[i], states);
}
target.draw(m_begin, states);
target.draw(m_end, states);
}
}
| 22 | 105 | 0.670455 | [
"shape",
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.