hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dbd92830d82fb7c1dbf5cb22f494c1c01ba041f9 | 1,626 | hpp | C++ | include/mtao/geometry/mesh/triangle_fan.hpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | null | null | null | include/mtao/geometry/mesh/triangle_fan.hpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | 4 | 2020-04-18T16:16:05.000Z | 2020-04-18T16:17:36.000Z | include/mtao/geometry/mesh/triangle_fan.hpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | null | null | null | #pragma once
#include "mtao/types.hpp"
#include "mtao/type_utils.h"
#include "mtao/eigen/stl2eigen.hpp"
#include "mtao/iterator/shell.hpp"
#include <list>
namespace mtao::geometry::mesh {
template <typename BeginIt, typename EndIt>
std::vector<std::array<int,3>> triangle_fan_stl(const BeginIt& beginit, const EndIt& endit) {
using Face = std::array<int,3>;
std::vector<Face> stlF;
if constexpr(std::is_integral_v<mtao::types::remove_cvref_t<decltype(*beginit)>>) {
stlF.reserve(std::distance(beginit,endit) - 2);
Face f;
auto it = beginit;
f[0] = *(it++);
f[2] = *(it++);
for(; it != endit; ++it) {
f[1] = f[2];
f[2] = *it;
stlF.push_back(f);
}
} else {
size_t size = 0;
for(auto&& c: mtao::iterator::shell(beginit,endit)) {
size += c.size() - 2;
}
stlF.reserve(size);
for(auto&& c: mtao::iterator::shell(beginit,endit)) {
auto F = triangle_fan_stl(c.begin(),c.end());
stlF.insert(stlF.end(),F.begin(),F.end());
}
}
return stlF;
}
template <typename Container>
mtao::ColVectors<int,3> triangle_fan(const Container& C) {
return eigen::stl2eigen(triangle_fan_stl(C.begin(),C.end()));
}
template <typename T>
mtao::ColVectors<int,3> triangle_fan(const std::initializer_list<T>& C) {
return eigen::stl2eigen(triangle_fan_stl(C.begin(),C.end()));
}
}
| 33.875 | 97 | 0.531365 | mtao |
dbdb9f2fd3ab2ec71471a114984e2591469ef965 | 11,510 | hpp | C++ | src/ganon-classify/include/ganon-classify/Config.hpp | benvenutti/ganon | 0d6f1b73eacb7659a0d541567b9aa60287e05f82 | [
"MIT",
"BSD-3-Clause"
] | 1 | 2021-04-11T22:09:18.000Z | 2021-04-11T22:09:18.000Z | src/ganon-classify/include/ganon-classify/Config.hpp | benvenutti/ganon | 0d6f1b73eacb7659a0d541567b9aa60287e05f82 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/ganon-classify/include/ganon-classify/Config.hpp | benvenutti/ganon | 0d6f1b73eacb7659a0d541567b9aa60287e05f82 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <algorithm>
#include <cinttypes>
#include <iomanip>
#include <iostream>
#include <map>
#include <ostream>
#include <string>
#include <vector>
namespace GanonClassify
{
struct FilterConfig
{
std::string ibf_file;
std::string map_file;
std::string tax_file;
int16_t max_error;
float min_kmers;
};
struct HierarchyConfig
{
std::vector< FilterConfig > filters;
int16_t max_error_unique;
int16_t strata_filter;
std::string output_file_lca;
std::string output_file_rep;
std::string output_file_all;
};
struct Config
{
public:
std::vector< std::string > single_reads;
std::vector< std::string > paired_reads;
std::vector< std::string > ibf;
std::vector< std::string > map;
std::vector< std::string > tax;
std::vector< std::string > hierarchy_labels{ "1_default" };
std::vector< float > min_kmers{ 0.25 };
std::vector< int16_t > max_error;
std::vector< int16_t > max_error_unique{ -1 };
std::vector< int16_t > strata_filter{ 0 };
uint16_t offset = 2;
std::string output_prefix = "";
bool output_all = false;
bool output_unclassified = false;
bool output_single = false;
uint16_t threads = 3;
uint32_t n_batches = 1000;
uint32_t n_reads = 400;
bool verbose = false;
bool quiet = false;
uint16_t threads_classify;
std::map< std::string, HierarchyConfig > parsed_hierarchy;
bool validate()
{
if ( ibf.size() == 0 || map.size() == 0 || tax.size() == 0
|| ( paired_reads.size() == 0 && single_reads.size() == 0 ) )
{
std::cerr << "--ibf, --map, --tax, --[single|paired]-reads are mandatory" << std::endl;
return false;
}
else if ( paired_reads.size() % 2 != 0 )
{
std::cerr << "--paired-reads should be an even number of files (pairs)" << std::endl;
return false;
}
bool valid_val = true;
for ( uint16_t i = 0; i < min_kmers.size(); ++i )
{
if ( min_kmers[i] < 0 || min_kmers[i] > 1 )
{
valid_val = false;
break;
}
}
if ( !valid_val )
{
std::cerr << "--min-kmers value should be between 0 and 1" << std::endl;
return false;
}
valid_val = true;
for ( uint16_t i = 0; i < max_error.size(); ++i )
{
if ( max_error[i] < 0 )
{
valid_val = false;
break;
}
}
if ( !valid_val )
{
std::cerr << "--max-error value should be greater than 0" << std::endl;
return false;
}
// default is min_kmers, if min_error is provided, use it
if ( max_error.size() > 0 )
min_kmers[0] = -1; // reset min_kmers
else
max_error.push_back( -1 ); // reset max_error
if ( threads <= 3 )
{
threads_classify = 1;
}
else
{
threads_classify = threads - 2;
}
if ( n_batches < 1 )
n_batches = 1;
if ( n_reads < 1 )
n_reads = 1;
if ( output_prefix.empty() )
{
output_all = false;
output_unclassified = false;
}
if ( offset < 1 )
offset = 1;
#ifndef GANON_OFFSET
offset = 1;
#endif
return parse_hierarchy();
}
bool parse_hierarchy()
{
if ( ibf.size() != map.size() || ibf.size() != tax.size() )
{
std::cerr << "The number of --ibf, --map and --tax should match" << std::endl;
return false;
}
// One hierarchy value for multiple hierarchies
if ( hierarchy_labels.size() == 1 && ibf.size() > 1 )
{
for ( uint16_t b = 1; b < ibf.size(); ++b )
{
hierarchy_labels.push_back( hierarchy_labels[0] );
}
}
else if ( hierarchy_labels.size() != ibf.size() )
{
std::cerr << "--hierarchy does not match with the number of --ibf, --map and --tax" << std::endl;
return false;
}
// If only one max error was given, repeat it for every filter
if ( max_error.size() == 1 && ibf.size() > 1 )
{
for ( uint16_t b = 1; b < ibf.size(); ++b )
{
max_error.push_back( max_error[0] );
}
}
else if ( max_error.size() != ibf.size() )
{
std::cerr << "Please provide a single or one-per-filter --max-error value[s]" << std::endl;
return false;
}
// If only one max error was given, repeat it for every filter
if ( min_kmers.size() == 1 && ibf.size() > 1 )
{
for ( uint16_t b = 1; b < ibf.size(); ++b )
{
min_kmers.push_back( min_kmers[0] );
}
}
else if ( min_kmers.size() != ibf.size() )
{
std::cerr << "Please provide a single or one-per-filter --min-kmers value[s]" << std::endl;
return false;
}
std::vector< std::string > sorted_hierarchy = hierarchy_labels;
std::sort( sorted_hierarchy.begin(), sorted_hierarchy.end() );
// get unique hierarcy labels
uint16_t unique_hierarchy =
std::unique( sorted_hierarchy.begin(), sorted_hierarchy.end() ) - sorted_hierarchy.begin();
if ( max_error_unique.size() == 1 && unique_hierarchy > 1 )
{
for ( uint16_t b = 1; b < unique_hierarchy; ++b )
{
max_error_unique.push_back( max_error_unique[0] );
}
}
else if ( max_error_unique.size() != unique_hierarchy )
{
std::cerr << "Please provide a single or one-per-hierarchy --max-error-unique value[s]" << std::endl;
return false;
}
if ( strata_filter.size() == 1 && unique_hierarchy > 1 )
{
for ( uint16_t b = 1; b < unique_hierarchy; ++b )
{
strata_filter.push_back( strata_filter[0] );
}
}
else if ( strata_filter.size() != unique_hierarchy )
{
std::cerr << "Please provide a single or one-per-hierarchy --strata-filter value[s]" << std::endl;
return false;
}
uint16_t hierarchy_count = 0;
for ( uint16_t h = 0; h < hierarchy_labels.size(); ++h )
{
auto filter_cfg = FilterConfig{ ibf[h], map[h], tax[h], max_error[h], min_kmers[h] };
if ( parsed_hierarchy.find( hierarchy_labels[h] ) == parsed_hierarchy.end() )
{ // not found
std::vector< FilterConfig > fc;
fc.push_back( filter_cfg );
std::string output_file_lca;
std::string output_file_rep;
std::string output_file_all;
if ( !output_prefix.empty() && unique_hierarchy > 1 && !output_single )
{
output_file_lca = output_prefix + "." + hierarchy_labels[h] + ".lca";
output_file_all = output_prefix + "." + hierarchy_labels[h] + ".all";
output_file_rep = output_prefix + ".rep";
}
else if ( !output_prefix.empty() )
{
output_file_lca = output_prefix + ".lca";
output_file_all = output_prefix + ".all";
output_file_rep = output_prefix + ".rep";
}
parsed_hierarchy[hierarchy_labels[h]] = HierarchyConfig{ fc,
max_error_unique[hierarchy_count],
strata_filter[hierarchy_count],
output_file_lca,
output_file_rep,
output_file_all };
++hierarchy_count;
}
else
{ // found
parsed_hierarchy[hierarchy_labels[h]].filters.push_back( filter_cfg );
}
}
return true;
}
};
inline std::ostream& operator<<( std::ostream& stream, const Config& config )
{
constexpr auto newl{ "\n" };
constexpr auto separator{ "----------------------------------------------------------------------" };
stream << separator << newl;
stream << "Database hierarchy:" << newl;
for ( auto const& hierarchy_config : config.parsed_hierarchy )
{
if ( !hierarchy_config.first.empty() )
{
stream << hierarchy_config.first << ")" << newl;
stream << " --max-error-unique: " << hierarchy_config.second.max_error_unique << newl;
stream << " --strata-filter: " << hierarchy_config.second.strata_filter << newl;
}
for ( auto const& filter_config : hierarchy_config.second.filters )
{
if ( filter_config.min_kmers > -1 )
stream << " --min-kmers: " << filter_config.min_kmers << newl;
if ( filter_config.max_error > -1 )
stream << " --max-error: " << filter_config.max_error << newl;
stream << " --ibf: " << filter_config.ibf_file << newl;
stream << " --map: " << filter_config.map_file << newl;
stream << " --tax: " << filter_config.tax_file << newl;
}
stream << " Output files:" << newl;
stream << " " << hierarchy_config.second.output_file_lca << newl;
stream << " " << hierarchy_config.second.output_file_rep << newl;
if ( config.output_all )
stream << " " << hierarchy_config.second.output_file_all << newl;
}
stream << newl;
stream << "Input files:" << newl;
stream << "--reads-single " << newl;
for ( const auto& s : config.single_reads )
stream << " " << s << newl;
stream << "--reads-paired " << newl;
for ( const auto& s : config.paired_reads )
stream << " " << s << newl;
stream << newl;
stream << "Parameters:" << newl;
stream << "--offset " << config.offset << newl;
stream << "--output-prefix " << config.output_prefix << newl;
stream << "--output-all " << config.output_all << newl;
stream << "--output-unclassified " << config.output_unclassified << newl;
stream << "--output-single " << config.output_single << newl;
stream << "--threads " << config.threads << newl;
stream << "--n-batches " << config.n_batches << newl;
stream << "--n-reads " << config.n_reads << newl;
stream << "--verbose " << config.verbose << newl;
stream << "--quiet " << config.quiet << newl;
stream << separator << newl;
return stream;
}
} // namespace GanonClassify
| 34.878788 | 113 | 0.482884 | benvenutti |
dbdd5abe0accf7f06ccea27f68a7c55dbbaa260a | 51,996 | cpp | C++ | src/pafpython/PythonWrapper.cpp | fdyjfd/paf | fb6b275532483184b5e02f2d6850e503eb9bfad1 | [
"MIT"
] | 1 | 2021-04-02T10:17:59.000Z | 2021-04-02T10:17:59.000Z | src/pafpython/PythonWrapper.cpp | fdyjfd/paf | fb6b275532483184b5e02f2d6850e503eb9bfad1 | [
"MIT"
] | null | null | null | src/pafpython/PythonWrapper.cpp | fdyjfd/paf | fb6b275532483184b5e02f2d6850e503eb9bfad1 | [
"MIT"
] | null | null | null | #include <new.h>
#include "Python.h"
#include "../pafcore/Variant.h"
#include "../pafcore/InstanceMethod.h"
#include "../pafcore/NameSpace.h"
#include "../pafcore/NameSpace.mh"
#include "../pafcore/Metadata.mh"
#include "../pafcore/Type.mh"
#include "../pafcore/ClassType.h"
#include "../pafcore/EnumType.h"
#include "../pafcore/EnumType.mh"
#include "../pafcore/InstanceField.h"
#include "../pafcore/StaticField.h"
#include "../pafcore/InstanceProperty.h"
#include "../pafcore/InstanceArrayProperty.h"
#include "../pafcore/StaticProperty.h"
#include "../pafcore/StaticArrayProperty.h"
#include "../pafcore/InstanceMethod.h"
#include "../pafcore/StaticMethod.h"
#include "../pafcore/Enumerator.h"
#include "../pafcore/PrimitiveType.h"
#include "Utility.h"
#include "PythonWrapper.h"
#include "PythonSubclassInvoker.h"
BEGIN_PAFPYTHON
const size_t max_param_count = 20;
struct VariantWrapper
{
PyObject_HEAD
char m_var[sizeof(pafcore::Variant)];
};
static PyTypeObject s_VariantWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.Object",
sizeof(VariantWrapper),
};
struct InstanceArrayPropertyWrapper
{
PyObject_HEAD
pafcore::InstanceArrayProperty* m_property;
VariantWrapper* m_self;
};
static PyTypeObject s_InstanceArrayPropertyWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.InstanceArrayProperty",
sizeof(InstanceArrayPropertyWrapper),
};
struct StaticArrayPropertyWrapper
{
PyObject_HEAD
pafcore::StaticArrayProperty* m_property;
};
static PyTypeObject s_StaticArrayPropertyWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.StaticArrayProperty",
sizeof(StaticArrayPropertyWrapper),
};
struct InstanceMethodWrapper
{
PyObject_HEAD
pafcore::InstanceMethod* m_method;
VariantWrapper* m_self;
};
static PyTypeObject s_InstanceMethodWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.InstanceMethod",
sizeof(InstanceMethodWrapper),
};
struct FunctionInvokerWrapper
{
PyObject_HEAD
pafcore::FunctionInvoker m_invoker;
};
static PyTypeObject s_FunctionInvokerWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.FunctionInvoker",
sizeof(FunctionInvokerWrapper),
};
struct ProxyCreatorWrapper
{
PyObject_HEAD
pafcore::ClassType* m_classType;
};
static PyTypeObject s_ProxyCreatorWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.ProxyCreator",
sizeof(ProxyCreatorWrapper),
};
struct TypeCasterWrapper
{
PyObject_HEAD
pafcore::Type* m_type;
};
static PyTypeObject s_TypeCasterWrapper_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"PafPython.TypeCaster",
sizeof(TypeCasterWrapper),
};
PyObject* VariantWrapper_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
VariantWrapper* self;
self = (VariantWrapper*)type->tp_alloc(type, 0);
if (self != NULL)
{
void* var = self->m_var;
pafcore::Variant* variant = new(var)pafcore::Variant;
}
return (PyObject*)self;
}
void VariantWrapper_dealloc(VariantWrapper* self)
{
pafcore::Variant* variant = (pafcore::Variant*)self->m_var;
variant->~Variant();
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyObject* FunctionInvokerWrapper_new(PyTypeObject* type, PyObject *args, PyObject *kwds)
{
FunctionInvokerWrapper* self;
self = (FunctionInvokerWrapper*)type->tp_alloc(type, 0);
self->m_invoker = 0;
return (PyObject*)self;
}
void InstanceArrayPropertyWrapper_dealloc(InstanceArrayPropertyWrapper* self)
{
Py_XDECREF(self->m_self);
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyObject* InstanceArrayPropertyWrapper_new(PyTypeObject* type, PyObject *args, PyObject *kwds)
{
InstanceArrayPropertyWrapper* self;
self = (InstanceArrayPropertyWrapper*)type->tp_alloc(type, 0);
self->m_property = 0;
self->m_self = 0;
return (PyObject*)self;
}
PyObject* StaticArrayPropertyWrapper_new(PyTypeObject* type, PyObject *args, PyObject *kwds)
{
StaticArrayPropertyWrapper* self;
self = (StaticArrayPropertyWrapper*)type->tp_alloc(type, 0);
self->m_property = 0;
return (PyObject*)self;
}
void InstanceMethodWrapper_dealloc(InstanceMethodWrapper* self)
{
Py_XDECREF(self->m_self);
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyObject* InstanceMethodWrapper_new(PyTypeObject* type, PyObject *args, PyObject *kwds)
{
InstanceMethodWrapper* self;
self = (InstanceMethodWrapper*)type->tp_alloc(type, 0);
self->m_method = 0;
self->m_self = 0;
return (PyObject*)self;
}
PyObject* ProxyCreatorWrapper_new(PyTypeObject* type, PyObject *args, PyObject *kwds)
{
ProxyCreatorWrapper* self;
self = (ProxyCreatorWrapper*)type->tp_alloc(type, 0);
self->m_classType = 0;
return (PyObject*)self;
}
PyObject* TypeCasterWrapper_new(PyTypeObject* type, PyObject *args, PyObject *kwds)
{
TypeCasterWrapper* self;
self = (TypeCasterWrapper*)type->tp_alloc(type, 0);
self->m_type = 0;
return (PyObject*)self;
}
PyObject* VariantToPython(pafcore::Variant* variant)
{
PyObject* object = VariantWrapper_new(&s_VariantWrapper_Type, 0, 0);
pafcore::Variant* var = (pafcore::Variant*)((VariantWrapper*)object)->m_var;
var->move(*variant);
return object;
}
pafcore::Variant* PythonToVariant(pafcore::Variant* value, PyObject* pyObject)
{
pafcore::Variant* res = value;
PyObject* type = PyObject_Type(pyObject);
if(PyObject_TypeCheck(pyObject, &s_VariantWrapper_Type))
{
res = (pafcore::Variant*)((VariantWrapper*)pyObject)->m_var;
}
else if(PyBool_Check(pyObject))
{
bool b = (pyObject != Py_False);
value->assignPrimitive(RuntimeTypeOf<bool>::RuntimeType::GetSingleton(), &b);
}
else if(PyLong_Check(pyObject))
{
PY_LONG_LONG i = PyLong_AsLongLong(pyObject);
value->assignPrimitive(RuntimeTypeOf<PY_LONG_LONG>::RuntimeType::GetSingleton(), &i);
}
else if(PyFloat_Check(pyObject))
{
double d = PyFloat_AsDouble(pyObject);
value->assignPrimitive(RuntimeTypeOf<double>::RuntimeType::GetSingleton(), &d);
}
else if(PyUnicode_Check(pyObject))
{
Py_ssize_t size;
char* s = PyUnicode_AsUTF8AndSize(pyObject, &size);
value->assignPrimitivePtr(RuntimeTypeOf<char>::RuntimeType::GetSingleton(), (void*)s, true, ::pafcore::Variant::by_ptr);
}
return res;
}
pafcore::ErrorCode GetStaticField(PyObject*& pyObject, pafcore::StaticField* field)
{
pafcore::Variant value;
if(field->isArray())
{
value.assignArray(field->m_type, (void*)field->m_address, field->m_arraySize, field->m_constant, ::pafcore::Variant::by_array);
}
else
{
value.assignPtr(field->m_type, (void*)field->m_address, field->m_constant, ::pafcore::Variant::by_ref);
}
pyObject = VariantToPython(&value);
return pafcore::s_ok;
}
pafcore::ErrorCode SetStaticField(pafcore::StaticField* field, PyObject* pyAttr)
{
if(field->isArray())
{
return pafcore::e_field_is_an_array;
}
if(field->isConstant())
{
return pafcore::e_field_is_constant;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
if(!attr->castToObject(field->m_type, (void*)field->m_address))
{
return pafcore::e_invalid_field_type;
}
return pafcore::s_ok;
}
pafcore::ErrorCode GetInstanceField(PyObject*& pyObject, pafcore::Variant* that, pafcore::InstanceField* field)
{
size_t baseOffset;
if(!static_cast<pafcore::ClassType*>(that->m_type)->getClassOffset(baseOffset, field->m_objectType))
{
return pafcore::e_invalid_type;
}
size_t fieldAddress = (size_t)that->m_pointer + baseOffset + field->m_offset;
pafcore::Variant value;
if(field->isArray())
{
value.assignArray(field->m_type, (void*)fieldAddress, field->m_arraySize, field->m_constant, ::pafcore::Variant::by_array);
}
else
{
value.assignPtr(field->m_type, (void*)fieldAddress, field->m_constant, ::pafcore::Variant::by_ref);
}
pyObject = VariantToPython(&value);
return pafcore::s_ok;
}
pafcore::ErrorCode SetInstanceField(pafcore::Variant* that, pafcore::InstanceField* field, PyObject* pyAttr)
{
if(field->isArray())
{
return pafcore::e_field_is_an_array;
}
if(field->isConstant())
{
return pafcore::e_field_is_constant;
}
size_t baseOffset;
if(!static_cast<pafcore::ClassType*>(that->m_type)->getClassOffset(baseOffset, field->m_objectType))
{
return pafcore::e_invalid_object_type;
}
size_t fieldAddress = (size_t)that->m_pointer + baseOffset + field->m_offset;
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
if(!attr->castToObject(field->m_type, (void*)fieldAddress))
{
return pafcore::e_invalid_field_type;
}
return pafcore::s_ok;
}
pafcore::ErrorCode GetStaticProperty(PyObject*& pyObject, pafcore::StaticProperty* property)
{
if(0 == property->m_getter)
{
return pafcore::e_property_is_write_only;
}
pafcore::Variant value;
pafcore::ErrorCode errorCode = (*property->m_getter)(&value);
if(pafcore::s_ok == errorCode)
{
pyObject = VariantToPython(&value);
}
return errorCode;
}
pafcore::ErrorCode GetStaticArrayPropertySize(PyObject*& pyObject, pafcore::StaticArrayProperty* property)
{
pafcore::Variant value;
pafcore::ErrorCode errorCode = (*property->m_sizer)(&value);
if (pafcore::s_ok == errorCode)
{
pyObject = VariantToPython(&value);
}
return errorCode;
}
pafcore::ErrorCode GetStaticArrayProperty(PyObject*& pyObject, pafcore::StaticArrayProperty* property, size_t index)
{
if (0 == property->m_getter)
{
return pafcore::e_property_is_write_only;
}
pafcore::Variant value;
pafcore::ErrorCode errorCode = (*property->m_getter)(index, &value);
if (pafcore::s_ok == errorCode)
{
pyObject = VariantToPython(&value);
}
return errorCode;
}
pafcore::ErrorCode SetStaticProperty(pafcore::StaticProperty* property, PyObject* pyAttr)
{
if(0 == property->m_setter)
{
return pafcore::e_property_is_read_only;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
pafcore::ErrorCode errorCode = (*property->m_setter)(attr);
return errorCode;
}
pafcore::ErrorCode SetStaticArrayPropertySize(pafcore::StaticArrayProperty* property, PyObject* pyAttr)
{
if (0 == property->m_resizer)
{
return pafcore::e_array_property_is_not_dynamic;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
pafcore::ErrorCode errorCode = (*property->m_resizer)(attr);
return errorCode;
}
pafcore::ErrorCode SetStaticArrayProperty(pafcore::StaticArrayProperty* property, size_t index, PyObject* pyAttr)
{
if (0 == property->m_setter)
{
return pafcore::e_property_is_read_only;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
pafcore::ErrorCode errorCode = (*property->m_setter)(index, attr);
return errorCode;
}
pafcore::ErrorCode MakeStaticArrayProperty(PyObject*& pyObject, pafcore::StaticArrayProperty* property)
{
PyObject* object = StaticArrayPropertyWrapper_new(&s_StaticArrayPropertyWrapper_Type, 0, 0);
((StaticArrayPropertyWrapper*)object)->m_property = property;
pyObject = object;
return pafcore::s_ok;
}
pafcore::ErrorCode GetInstanceProperty(PyObject*& pyObject, pafcore::Variant* that, pafcore::InstanceProperty* property)
{
if(0 == property->m_getter)
{
return pafcore::e_property_is_write_only;
}
pafcore::Variant value;
pafcore::ErrorCode errorCode = (*property->m_getter)(that, &value);
if(pafcore::s_ok == errorCode)
{
pyObject = VariantToPython(&value);
}
return errorCode;
}
pafcore::ErrorCode GetInstanceArrayPropertySize(PyObject*& pyObject, pafcore::Variant* that, pafcore::InstanceArrayProperty* property)
{
pafcore::Variant value;
pafcore::ErrorCode errorCode = (*property->m_sizer)(that, &value);
if (pafcore::s_ok == errorCode)
{
pyObject = VariantToPython(&value);
}
return errorCode;
}
pafcore::ErrorCode GetInstanceArrayProperty(PyObject*& pyObject, pafcore::Variant* that, pafcore::InstanceArrayProperty* property, size_t index)
{
if (0 == property->m_getter)
{
return pafcore::e_property_is_write_only;
}
pafcore::Variant value;
pafcore::ErrorCode errorCode = (*property->m_getter)(that, index, &value);
if (pafcore::s_ok == errorCode)
{
pyObject = VariantToPython(&value);
}
return errorCode;
}
pafcore::ErrorCode SetInstanceProperty(pafcore::Variant* that, pafcore::InstanceProperty* property, PyObject* pyAttr)
{
if(0 == property->m_setter)
{
return pafcore::e_property_is_read_only;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
pafcore::ErrorCode errorCode = (*property->m_setter)(that, attr);
return errorCode;
}
pafcore::ErrorCode SetInstanceArrayPropertySize(pafcore::Variant* that, pafcore::InstanceArrayProperty* property, PyObject* pyAttr)
{
if (0 == property->m_resizer)
{
return pafcore::e_array_property_is_not_dynamic;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
pafcore::ErrorCode errorCode = (*property->m_resizer)(that, attr);
return errorCode;
}
pafcore::ErrorCode SetInstanceArrayProperty(pafcore::Variant* that, pafcore::InstanceArrayProperty* property, size_t index, PyObject* pyAttr)
{
if (0 == property->m_setter)
{
return pafcore::e_property_is_read_only;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
pafcore::ErrorCode errorCode = (*property->m_setter)(that, index, attr);
return errorCode;
}
pafcore::ErrorCode MakeInstanceArrayProperty(PyObject*& pyObject, VariantWrapper* self, pafcore::InstanceArrayProperty* property)
{
PyObject* object = InstanceArrayPropertyWrapper_new(&s_InstanceArrayPropertyWrapper_Type, 0, 0);
((InstanceArrayPropertyWrapper*)object)->m_property = property;
((InstanceArrayPropertyWrapper*)object)->m_self = self;
Py_INCREF(self);
pyObject = object;
return pafcore::s_ok;
}
pafcore::ErrorCode SetArraySize(pafcore::Variant* that, PyObject* pyAttr)
{
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
if (!attr->castToPrimitive(RuntimeTypeOf<size_t>::RuntimeType::GetSingleton(), &that->m_arraySize))
{
return pafcore::e_invalid_property_type;
}
return pafcore::s_ok;
}
pafcore::ErrorCode MakeFunctionInvoker(PyObject*& pyObject, pafcore::FunctionInvoker invoker)
{
PyObject* object = FunctionInvokerWrapper_new(&s_FunctionInvokerWrapper_Type, 0, 0);
((FunctionInvokerWrapper*)object)->m_invoker = invoker;
pyObject = object;
return pafcore::s_ok;
}
pafcore::ErrorCode MakeInstanceMethod(PyObject*& pyObject, VariantWrapper* self, pafcore::InstanceMethod* method)
{
PyObject* object = InstanceMethodWrapper_new(&s_InstanceMethodWrapper_Type, 0, 0);
((InstanceMethodWrapper*)object)->m_method = method;
((InstanceMethodWrapper*)object)->m_self = self;
Py_INCREF(self);
pyObject = object;
return pafcore::s_ok;
}
pafcore::ErrorCode GetNestedType(PyObject*& pyObject, pafcore::Type* nestedType)
{
pafcore::Variant value;
value.assignReferencePtr(RuntimeTypeOf<pafcore::Type>::RuntimeType::GetSingleton(), nestedType, false, ::pafcore::Variant::by_ptr);
pyObject = VariantToPython(&value);
return pafcore::s_ok;
}
pafcore::ErrorCode GetPrimitiveOrEnum(PyObject*& pyObject, pafcore::Variant* variant)
{
if(variant->m_type->isPrimitive())
{
if(variant->byValue() || variant->byRef())
{
pafcore::PrimitiveType* primitiveType = static_cast<pafcore::PrimitiveType*>(variant->m_type);
switch(primitiveType->m_typeCategory)
{
case pafcore::float_type:
case pafcore::double_type:
case pafcore::long_double_type:
{
double value;
primitiveType->castTo(&value, RuntimeTypeOf<double>::RuntimeType::GetSingleton(), variant->m_pointer);
pyObject = PyFloat_FromDouble(value);
}
break;
case pafcore::bool_type:
{
bool value;
primitiveType->castTo(&value, RuntimeTypeOf<bool>::RuntimeType::GetSingleton(), variant->m_pointer);
pyObject = value ? Py_True : Py_False;
}
break;
case pafcore::unsigned_long_long_type:
{
unsigned PY_LONG_LONG value;
primitiveType->castTo(&value, RuntimeTypeOf<unsigned PY_LONG_LONG>::RuntimeType::GetSingleton(), variant->m_pointer);
pyObject = PyLong_FromUnsignedLongLong(value);
}
break;
case pafcore::long_long_type:
{
PY_LONG_LONG value;
primitiveType->castTo(&value, RuntimeTypeOf<PY_LONG_LONG>::RuntimeType::GetSingleton(), variant->m_pointer);
pyObject = PyLong_FromLongLong(value);
}
break;
case pafcore::unsigned_char_type:
case pafcore::unsigned_short_type:
case pafcore::unsigned_int_type:
case pafcore::unsigned_long_type:
{
unsigned long value;
primitiveType->castTo(&value, RuntimeTypeOf<unsigned long>::RuntimeType::GetSingleton(), variant->m_pointer);
pyObject = PyLong_FromUnsignedLong(value);
}
break;
default:
{
long value;
primitiveType->castTo(&value, RuntimeTypeOf<long>::RuntimeType::GetSingleton(), variant->m_pointer);
pyObject = PyLong_FromLong(value);
}
}
return pafcore::s_ok;
}
else
{
pafcore::PrimitiveType* primitiveType = static_cast<pafcore::PrimitiveType*>(variant->m_type);
if(pafcore::char_type == primitiveType->m_typeCategory)
{
pyObject = PyUnicode_FromString((const char*)variant->m_pointer);
return pafcore::s_ok;
}
else if(pafcore::wchar_type == primitiveType->m_typeCategory)
{
pyObject = PyUnicode_FromWideChar((const wchar_t*)variant->m_pointer, -1);
return pafcore::s_ok;
}
}
}
else if(variant->m_type->isEnum())
{
if(variant->byValue() || variant->byRef())
{
long value;
variant->castToPrimitive(RuntimeTypeOf<long>::RuntimeType::GetSingleton(), &value);
pyObject = PyLong_FromLong(value);
return pafcore::s_ok;
}
}
return pafcore::e_invalid_type;
}
pafcore::ErrorCode SetPrimitiveOrEnum(pafcore::Variant* variant, PyObject* pyAttr)
{
if (variant->isConstant())
{
return pafcore::e_field_is_constant;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
if (!attr->castToPrimitive(variant->m_type, variant->m_pointer))
{
return pafcore::e_invalid_property_type;
}
return pafcore::s_ok;
}
pafcore::ErrorCode MakeProxyCreator(PyObject*& pyObject, pafcore::ClassType* classType)
{
PyObject* object = ProxyCreatorWrapper_new(&s_ProxyCreatorWrapper_Type, 0, 0);
((ProxyCreatorWrapper*)object)->m_classType = classType;
pyObject = object;
return pafcore::s_ok;
}
pafcore::ErrorCode MakeTypeCaster(PyObject*& pyObject, pafcore::Type* type)
{
PyObject* object = TypeCasterWrapper_new(&s_TypeCasterWrapper_Type, 0, 0);
((TypeCasterWrapper*)object)->m_type = type;
pyObject = object;
return pafcore::s_ok;
}
pafcore::ErrorCode Variant_GetAttr(PyObject*& pyObject, VariantWrapper* self, const char *name)
{
pafcore::Variant* variant = (pafcore::Variant*)self->m_var;
if(variant->isNull())
{
if (strcmp(name, "_isNullPtr_") == 0)//_isNullPtr_
{
bool isNullPtr = (0 == variant->m_pointer);
pafcore::Variant var;
var.assignPrimitive(RuntimeTypeOf<bool>::RuntimeType::GetSingleton(), &isNullPtr);
pyObject = VariantToPython(&var);
return pafcore::s_ok;
}
return pafcore::e_void_variant;
}
switch(variant->m_type->m_category)
{
case pafcore::name_space:
{
pafcore::NameSpace* ns = (pafcore::NameSpace*)variant->m_pointer;
pafcore::Metadata* member = ns->findMember(name);
if(0 != member)
{
pafcore::Variant value;
value.assignReferencePtr(RuntimeTypeOf<pafcore::Metadata>::RuntimeType::GetSingleton(), member, false, ::pafcore::Variant::by_ptr);
pyObject = VariantToPython(&value);
return pafcore::s_ok;
}
}
break;
case pafcore::class_type:
{
pafcore::ClassType* type = (pafcore::ClassType*)variant->m_pointer;
pafcore::Metadata* member = type->findClassMember(name, true);
if(0 != member)
{
pafcore::Type* memberType = member->getType();
switch(memberType->m_category)
{
case pafcore::static_field:
return GetStaticField(pyObject, static_cast<pafcore::StaticField*>(member));
case pafcore::static_property:
return GetStaticProperty(pyObject, static_cast<pafcore::StaticProperty*>(member));
case pafcore::static_array_property:
return MakeStaticArrayProperty(pyObject, static_cast<pafcore::StaticArrayProperty*>(member));
case pafcore::static_method:
return MakeFunctionInvoker(pyObject, static_cast<pafcore::StaticMethod*>(member)->m_invoker);
case pafcore::enum_type:
case pafcore::class_type:
return GetNestedType(pyObject, static_cast<pafcore::Type*>(member));
}
}
}
break;
case pafcore::primitive_type:
{
pafcore::PrimitiveType* type = (pafcore::PrimitiveType*)variant->m_pointer;
pafcore::Metadata* member = type->findTypeMember(name);
if(0 != member)
{
pafcore::Type* memberType = member->getType();
switch(memberType->m_category)
{
case pafcore::static_method:
return MakeFunctionInvoker(pyObject, static_cast<pafcore::StaticMethod*>(member)->m_invoker);
default:
assert(false);
}
}
}
break;
case pafcore::enum_type:
{
pafcore::EnumType* et = (pafcore::EnumType*)variant->m_pointer;
pafcore::Enumerator* enumerator = et->findEnumerator(name);
if(0 != enumerator)
{
pafcore::Variant value;
value.assignEnum(enumerator->m_type, &enumerator->m_value);
pyObject = VariantToPython(&value);
return pafcore::s_ok;
}
}
break;
}
pafcore::Metadata* member;
member = variant->m_type->findMember(name);
if(0 != member)
{
pafcore::Type* memberType = member->getType();
switch(memberType->m_category)
{
case pafcore::instance_field:
return GetInstanceField(pyObject, variant, static_cast<pafcore::InstanceField*>(member));
case pafcore::static_field:
return GetStaticField(pyObject, static_cast<pafcore::StaticField*>(member));
case pafcore::instance_property:
return GetInstanceProperty(pyObject, variant, static_cast<pafcore::InstanceProperty*>(member));
case pafcore::static_property:
return GetStaticProperty(pyObject, static_cast<pafcore::StaticProperty*>(member));
case pafcore::instance_array_property:
return MakeInstanceArrayProperty(pyObject, self, static_cast<pafcore::InstanceArrayProperty*>(member));
case pafcore::static_array_property:
return MakeStaticArrayProperty(pyObject, static_cast<pafcore::StaticArrayProperty*>(member));
case pafcore::instance_method:
return MakeInstanceMethod(pyObject, self, static_cast<pafcore::InstanceMethod*>(member));
case pafcore::static_method:
return MakeFunctionInvoker(pyObject, static_cast<pafcore::StaticMethod*>(member)->m_invoker);
case pafcore::enum_type:
case pafcore::class_type:
return GetNestedType(pyObject, static_cast<pafcore::Type*>(member));
default:
assert(false);
}
}
else if (name[0] == '_')
{
switch (name[1])
{
case '\0'://_
if (variant->m_type->isPrimitive() || variant->m_type->isEnum())
{
return GetPrimitiveOrEnum(pyObject, variant);
}
break;
case 'C':
if (strcmp(&name[2], "astPtr_") == 0)//_CastPtr_
{
if (pafcore::void_type == variant->m_type->m_category ||
pafcore::primitive_type == variant->m_type->m_category ||
pafcore::enum_type == variant->m_type->m_category ||
pafcore::class_type == variant->m_type->m_category)
{
pafcore::Type* type = (pafcore::Type*)variant->m_pointer;
return MakeTypeCaster(pyObject, type);
}
else
{
return pafcore::e_is_not_type;
}
}
break;
case 'D':
if (strcmp(&name[2], "erive_") == 0)//_Derive_
{
if (pafcore::class_type == variant->m_type->m_category)
{
pafcore::ClassType* classType = (pafcore::ClassType*)variant->m_pointer;
return MakeProxyCreator(pyObject, classType);
}
else
{
return pafcore::e_is_not_class;
}
}
break;
case 'a':
if (strcmp(&name[2], "ddress_") == 0)//_address_
{
pafcore::Variant address;
address.assignPrimitive(RuntimeTypeOf<size_t>::RuntimeType::GetSingleton(), &variant->m_pointer);
pyObject = VariantToPython(&address);
return pafcore::s_ok;
}
break;
case 'c':
if (strcmp(&name[2], "ount_") == 0)//_count_
{
pafcore::Variant count;
count.assignPrimitive(RuntimeTypeOf<size_t>::RuntimeType::GetSingleton(), &variant->m_arraySize);
pyObject = VariantToPython(&count);
return pafcore::s_ok;
}
break;
case 'i':
if (strcmp(&name[2], "sNullPtr_") == 0)//_isNullPtr_
{
bool isNullPtr = (0 == variant->m_pointer);
pafcore::Variant var;
var.assignPrimitive(RuntimeTypeOf<bool>::RuntimeType::GetSingleton(), &isNullPtr);
pyObject = VariantToPython(&var);
return pafcore::s_ok;
}
break;
case 'n':
if (strcmp(&name[2], "ullPtr_") == 0)//_nullPtr_
{
if (pafcore::void_type == variant->m_type->m_category ||
pafcore::primitive_type == variant->m_type->m_category ||
pafcore::enum_type == variant->m_type->m_category ||
pafcore::class_type == variant->m_type->m_category)
{
pafcore::Type* type = (pafcore::Type*)variant->m_pointer;
pafcore::Variant var;
var.assignPtr(type, 0, false, pafcore::Variant::by_ptr);
pyObject = VariantToPython(&var);
return pafcore::s_ok;
}
else
{
return pafcore::e_is_not_type;
}
}
break;
case 's':
if (strcmp(&name[2], "ize_") == 0)//_size_
{
pafcore::Variant size;
size.assignPrimitive(RuntimeTypeOf<size_t>::RuntimeType::GetSingleton(), &variant->m_type->m_size);
pyObject = VariantToPython(&size);
return pafcore::s_ok;
}
break;
case 't':
if (strcmp(&name[2], "ype_") == 0)//_type_
{
pafcore::Variant typeVar;
typeVar.assignReferencePtr(RuntimeTypeOf<pafcore::Type>::RuntimeType::GetSingleton(), variant->m_type, false, ::pafcore::Variant::by_ptr);
pyObject = VariantToPython(&typeVar);
return pafcore::s_ok;
}
break;
}
}
return pafcore::e_member_not_found;
}
pafcore::ErrorCode Variant_SetAttr(pafcore::Variant* variant, char* name, PyObject* pyAttr)
{
switch(variant->m_type->m_category)
{
case pafcore::class_type:
{
pafcore::ClassType* type = (pafcore::ClassType*)variant->m_pointer;
pafcore::Metadata* member = type->findClassMember(name, true);
if(0 != member)
{
pafcore::Type* memberType = member->getType();
switch(memberType->m_category)
{
case pafcore::static_field:
return SetStaticField(static_cast<pafcore::StaticField*>(member), pyAttr);
case pafcore::static_property:
return SetStaticProperty(static_cast<pafcore::StaticProperty*>(member), pyAttr);
}
}
}
break;
}
pafcore::Metadata* member;
member = variant->m_type->findMember(name);
if(0 != member)
{
pafcore::Type* memberType = member->getType();
switch(memberType->m_category)
{
case pafcore::instance_field:
return SetInstanceField(variant, static_cast<pafcore::InstanceField*>(member), pyAttr);
case pafcore::static_field:
return SetStaticField(static_cast<pafcore::StaticField*>(member), pyAttr);
case pafcore::instance_property:
return SetInstanceProperty(variant, static_cast<pafcore::InstanceProperty*>(member), pyAttr);
case pafcore::static_property:
return SetStaticProperty(static_cast<pafcore::StaticProperty*>(member), pyAttr);
}
}
else if (name[0] == '_')
{
switch (name[1])
{
case '\0':
if ((variant->m_type->isPrimitive() || variant->m_type->isEnum()) &&
(variant->byValue() || variant->byRef()))//_
{
return SetPrimitiveOrEnum(variant, pyAttr);
}
break;
case 'c':
if (strcmp(&name[2], "ount_") == 0)//_count_
{
return SetArraySize(variant, pyAttr);
}
break;
}
}
return pafcore::e_member_not_found;
}
pafcore::ErrorCode Variant_Subscript(PyObject*& pyObject, VariantWrapper* wrapper, size_t index)
{
pafcore::Variant* variant = (pafcore::Variant*)wrapper->m_var;
pafcore::Variant item;
if(!variant->subscript(item, index))
{
return pafcore::e_index_out_of_range;
}
pyObject = VariantToPython(&item);
return pafcore::s_ok;
}
pafcore::ErrorCode Variant_AssignSubscript(VariantWrapper* wrapper, size_t index, PyObject* pyAttr)
{
pafcore::Variant* variant = (pafcore::Variant*)wrapper->m_var;
pafcore::Variant item;
if(!variant->subscript(item, index))
{
return pafcore::e_index_out_of_range;
}
pafcore::Variant value;
pafcore::Variant* attr = PythonToVariant(&value, pyAttr);
if(!attr->castToObject(item.m_type, item.m_pointer))
{
return pafcore::e_invalid_type;
}
return pafcore::s_ok;
}
PyObject* VariantWrapper_getattr(VariantWrapper* wrapper, char* name)
{
PyObject* res = 0;
pafcore::ErrorCode errorCode = Variant_GetAttr(res, wrapper, name);
if(pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
return res;
}
int VariantWrapper_setattr(VariantWrapper* wrapper, char* name, PyObject* pyAttr)
{
pafcore::Variant* self = (pafcore::Variant*)wrapper->m_var;
pafcore::ErrorCode errorCode = Variant_SetAttr(self, name, pyAttr);
if(pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 1;
}
return 0;
}
PyObject* VariantWrapper_call(VariantWrapper* wrapper, PyObject* parameters, PyObject*)
{
pafcore::FunctionInvoker invoker = 0;
pafcore::Variant* self = (pafcore::Variant*)wrapper->m_var;
switch(self->m_type->m_category)
{
case pafcore::class_type:
{
pafcore::ClassType* type = (pafcore::ClassType*)self->m_pointer;
pafcore::Metadata* member = type->findClassMember("New", false);
if(0 != member)
{
pafcore::Type* memberType = member->getType();
if(pafcore::static_method == memberType->m_category)
{
invoker = static_cast<pafcore::StaticMethod*>(member)->m_invoker;
}
}
}
break;
case pafcore::primitive_type:
{
pafcore::PrimitiveType* type = (pafcore::PrimitiveType*)self->m_pointer;
assert(strcmp(type->m_staticMethods[0].m_name, "New") == 0);
invoker = type->m_staticMethods[0].m_invoker;
}
break;
case pafcore::static_method:
{
pafcore::StaticMethod* method = (pafcore::StaticMethod*)self->m_pointer;
invoker = method->m_invoker;
}
break;
case pafcore::instance_method:
{
pafcore::InstanceMethod* method = (pafcore::InstanceMethod*)self->m_pointer;
invoker = method->m_invoker;
}
break;
}
if(0 != invoker)
{
pafcore::Variant arguments[max_param_count];
pafcore::Variant* args[max_param_count];
Py_ssize_t numArgs = PyTuple_Size(parameters);
for(Py_ssize_t i = 0; i < numArgs; ++i)
{
PyObject* pyArg = PyTuple_GetItem(parameters, i);
args[i] = PythonToVariant(&arguments[i], pyArg);
}
pafcore::Variant result;
pafcore::ErrorCode errorCode = (*invoker)(&result, args, numArgs);
if(pafcore::s_ok == errorCode)
{
PyObject* pyObject = VariantToPython(&result);
return pyObject;
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
else
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_is_not_type));
}
return 0;
}
Py_ssize_t VariantWrapper_length(VariantWrapper* wrapper)
{
pafcore::ErrorCode errorCode;
Py_ssize_t len;
pafcore::Variant* variant = (pafcore::Variant*)wrapper->m_var;
if (pafcore::void_object == variant->m_type->m_category && variant->byValue())
{
errorCode = pafcore::e_void_variant;
}
else
{
errorCode = pafcore::s_ok;
len = variant->m_arraySize;
}
if (pafcore::s_ok == errorCode)
{
return len;
}
else
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 0;
}
}
bool VariantWrapper_ParseSubscript(size_t& num, PyObject* pyObject)
{
PyObject* type = PyObject_Type(pyObject);
if(PyObject_TypeCheck(pyObject, &s_VariantWrapper_Type))
{
pafcore::Variant* variant = (pafcore::Variant*)((VariantWrapper*)pyObject)->m_var;
if(variant->byValue() || variant->byRef())
{
if(variant->castToPrimitive(RuntimeTypeOf<size_t>::RuntimeType::GetSingleton(), &num))
{
return true;
}
}
}
if(PyLong_Check(pyObject))
{
num = PyLong_AsSize_t(pyObject);
return true;
}
return false;
}
PyObject* VariantWrapper_subscript(VariantWrapper* wrapper, PyObject* subscript)
{
size_t index;
if(!VariantWrapper_ParseSubscript(index, subscript))
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_subscript_type));
return 0;
}
PyObject* res = 0;
pafcore::ErrorCode errorCode = Variant_Subscript(res, wrapper, index);
if(pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
return res;
}
int VariantWrapper_assign_subscript(VariantWrapper* wrapper, PyObject* subscript, PyObject* value)
{
size_t index;
if(!VariantWrapper_ParseSubscript(index, subscript))
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_subscript_type));
return 1;
}
pafcore::ErrorCode errorCode = Variant_AssignSubscript(wrapper, index, value);
if(pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 1;
}
return 0;
}
PyObject* InstanceArrayPropertyWrapper_getattr(InstanceArrayPropertyWrapper* wrapper, char* name)
{
PyObject* res = 0;
pafcore::ErrorCode errorCode;
if (strcmp("_count_", name) == 0)
{
errorCode = GetInstanceArrayPropertySize(res, (pafcore::Variant*)wrapper->m_self->m_var, wrapper->m_property);
}
else
{
errorCode = pafcore::e_member_not_found;
}
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
return res;
}
int InstanceArrayPropertyWrapper_setattr(InstanceArrayPropertyWrapper* wrapper, char* name, PyObject* pyAttr)
{
pafcore::ErrorCode errorCode;
if (strcmp("_count_", name) == 0)
{
errorCode = SetInstanceArrayPropertySize((pafcore::Variant*)wrapper->m_self->m_var, wrapper->m_property, pyAttr);
}
else
{
errorCode = pafcore::e_member_not_found;
}
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 1;
}
return 0;
}
Py_ssize_t InstanceArrayPropertyWrapper_length(InstanceArrayPropertyWrapper* wrapper)
{
pafcore::ErrorCode errorCode;
pafcore::Variant value;
errorCode = (*wrapper->m_property->m_sizer)((pafcore::Variant*)wrapper->m_self->m_var, &value);
if (pafcore::s_ok == errorCode)
{
Py_ssize_t len;
value.castToPrimitive(RuntimeTypeOf<Py_ssize_t>::RuntimeType::GetSingleton(), &len);
return len;
}
else
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 0;
}
}
PyObject* InstanceArrayPropertyWrapper_subscript(InstanceArrayPropertyWrapper* wrapper, PyObject* subscript)
{
size_t index;
if (!VariantWrapper_ParseSubscript(index, subscript))
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_subscript_type));
return 0;
}
PyObject* res = 0;
pafcore::ErrorCode errorCode = GetInstanceArrayProperty(res, (pafcore::Variant*)wrapper->m_self->m_var, wrapper->m_property, index);
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
return res;
}
int InstanceArrayPropertyWrapper_assign_subscript(InstanceArrayPropertyWrapper* wrapper, PyObject* subscript, PyObject* value)
{
size_t index;
if (!VariantWrapper_ParseSubscript(index, subscript))
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_subscript_type));
return 1;
}
pafcore::ErrorCode errorCode = SetInstanceArrayProperty((pafcore::Variant*)wrapper->m_self->m_var, wrapper->m_property, index, value);
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 1;
}
return 0;
}
PyObject* StaticArrayPropertyWrapper_getattr(StaticArrayPropertyWrapper* wrapper, char* name)
{
PyObject* res = 0;
pafcore::ErrorCode errorCode;
if (strcmp("_count_", name) == 0)
{
errorCode = GetStaticArrayPropertySize(res, wrapper->m_property);
}
else
{
errorCode = pafcore::e_member_not_found;
}
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
return res;
}
int StaticArrayPropertyWrapper_setattr(StaticArrayPropertyWrapper* wrapper, char* name, PyObject* pyAttr)
{
pafcore::ErrorCode errorCode;
if (strcmp("_count_", name) == 0)
{
errorCode = SetStaticArrayPropertySize(wrapper->m_property, pyAttr);
}
else
{
errorCode = pafcore::e_member_not_found;
}
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 1;
}
return 0;
}
Py_ssize_t StaticArrayPropertyWrapper_length(StaticArrayPropertyWrapper* wrapper)
{
pafcore::ErrorCode errorCode;
pafcore::Variant value;
errorCode = (*wrapper->m_property->m_sizer)(&value);
if (pafcore::s_ok == errorCode)
{
Py_ssize_t len;
value.castToPrimitive(RuntimeTypeOf<Py_ssize_t>::RuntimeType::GetSingleton(), &len);
return len;
}
else
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 0;
}
}
PyObject* StaticArrayPropertyWrapper_subscript(StaticArrayPropertyWrapper* wrapper, PyObject* subscript)
{
size_t index;
if (!VariantWrapper_ParseSubscript(index, subscript))
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_subscript_type));
return 0;
}
PyObject* res = 0;
pafcore::ErrorCode errorCode = GetStaticArrayProperty(res, wrapper->m_property, index);
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
return res;
}
int StaticArrayPropertyWrapper_assign_subscript(StaticArrayPropertyWrapper* wrapper, PyObject* subscript, PyObject* value)
{
size_t index;
if (!VariantWrapper_ParseSubscript(index, subscript))
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_subscript_type));
return 1;
}
pafcore::ErrorCode errorCode = SetStaticArrayProperty(wrapper->m_property, index, value);
if (pafcore::s_ok != errorCode)
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 1;
}
return 0;
}
PyObject* InstanceMethodWrapper_call(InstanceMethodWrapper* wrapper, PyObject* parameters, PyObject*)
{
pafcore::InstanceMethod* method = wrapper->m_method;
VariantWrapper* self = wrapper->m_self;
pafcore::Variant arguments[max_param_count];
pafcore::Variant* args[max_param_count + 1];
args[0] = (pafcore::Variant*)self->m_var;
Py_ssize_t numArgs = PyTuple_Size(parameters);
for(Py_ssize_t i = 0; i < numArgs; ++i)
{
PyObject* pyArg = PyTuple_GetItem(parameters, i);
args[i+1] = PythonToVariant(&arguments[i], pyArg);
}
pafcore::Variant result;
pafcore::ErrorCode errorCode = (*method->m_invoker)(&result, args, numArgs + 1);
if(pafcore::s_ok == errorCode)
{
PyObject* pyObject = VariantToPython(&result);
return pyObject;
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 0;
}
PyObject* FunctionInvokerWrapper_call(FunctionInvokerWrapper* wrapper, PyObject* parameters, PyObject*)
{
pafcore::FunctionInvoker invoker = wrapper->m_invoker;
pafcore::Variant arguments[max_param_count];
pafcore::Variant* args[max_param_count];
Py_ssize_t numArgs = PyTuple_Size(parameters);
for(Py_ssize_t i = 0; i < numArgs; ++i)
{
PyObject* pyArg = PyTuple_GetItem(parameters, i);
args[i] = PythonToVariant(&arguments[i], pyArg);
}
pafcore::Variant result;
pafcore::ErrorCode errorCode = (*invoker)(&result, args, numArgs);
if(pafcore::s_ok == errorCode)
{
PyObject* pyObject = VariantToPython(&result);
return pyObject;
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
return 0;
}
PyObject* ProxyCreatorWrapper_call(ProxyCreatorWrapper* wrapper, PyObject* parameters, PyObject*)
{
pafcore::ClassType* classType = wrapper->m_classType;
Py_ssize_t numArgs = PyTuple_Size(parameters);
PyObject* pyArg = PyTuple_GetItem(parameters, 0);
if(pyArg)
{
PythonSubclassInvoker* subclassInvoker = paf_new PythonSubclassInvoker(pyArg);
void* implementor = classType->createSubclassProxy(subclassInvoker);
pafcore::Variant impVar;
if(classType->isValue())
{
impVar.assignValuePtr(classType, implementor, false, ::pafcore::Variant::by_new_ptr);
}
else
{
impVar.assignReferencePtr(classType, implementor, false, ::pafcore::Variant::by_new_ptr);
}
return VariantToPython(&impVar);
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_arg_type_1));
return 0;
}
PyObject* TypeCasterWrapper_call(TypeCasterWrapper* wrapper, PyObject* parameters, PyObject*)
{
pafcore::Type* type = wrapper->m_type;
Py_ssize_t numArgs = PyTuple_Size(parameters);
PyObject* pyArg = PyTuple_GetItem(parameters, 0);
if (pyArg)
{
pafcore::Variant value;
pafcore::Variant* arg = PythonToVariant(&value, pyArg);
pafcore::Variant dstPtr;
arg->reinterpretCastToPtr(dstPtr, type);
return VariantToPython(&dstPtr);
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_invalid_arg_type_1));
return 0;
}
PyObject* VariantWrapper_unaryOperator(PyObject* pyObject, const char* op)
{
pafcore::Variant arguments[1];
pafcore::Variant* args[1];
args[0] = PythonToVariant(&arguments[0], pyObject);
pafcore::InstanceMethod* method;
switch (args[0]->m_type->m_category)
{
case pafcore::primitive_object:
{
pafcore::PrimitiveType* type = (pafcore::PrimitiveType*)args[0]->m_type;
method = type->findInstanceMethod(op);
}
break;
case pafcore::value_object:
case pafcore::reference_object:
{
pafcore::ClassType* type = (pafcore::ClassType*)args[0]->m_type;
method = type->findInstanceMethod(op, true);
}
break;
default:
method = 0;
};
if (0 != method)
{
pafcore::Variant result;
pafcore::ErrorCode errorCode = (*method->m_invoker)(&result, args, 1);
if (pafcore::s_ok == errorCode)
{
PyObject* pyObject = VariantToPython(&result);
return pyObject;
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
else
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_member_not_found));
}
return 0;
}
PyObject* VariantWrapper_binaryOperator(PyObject* pyObject1, PyObject* pyObject2, const char* op)
{
pafcore::Variant arguments[2];
pafcore::Variant* args[2];
args[0] = PythonToVariant(&arguments[0], pyObject1);
args[1] = PythonToVariant(&arguments[1], pyObject2);
pafcore::InstanceMethod* method;
switch (args[0]->m_type->m_category)
{
case pafcore::primitive_object:
{
pafcore::PrimitiveType* type = (pafcore::PrimitiveType*)args[0]->m_type;
method = type->findInstanceMethod(op);
}
break;
case pafcore::value_object:
case pafcore::reference_object:
{
pafcore::ClassType* type = (pafcore::ClassType*)args[0]->m_type;
method = type->findInstanceMethod(op, true);
}
break;
default:
method = 0;
};
if (0 != method)
{
pafcore::Variant result;
pafcore::ErrorCode errorCode = (*method->m_invoker)(&result, args, 2);
if (pafcore::s_ok == errorCode)
{
PyObject* pyObject = VariantToPython(&result);
return pyObject;
}
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
}
else
{
PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(pafcore::e_member_not_found));
}
return 0;
}
//PyObject* VariantWrapper_compoundAssignmentOperator(PyObject* pyObject1, PyObject* pyObject2, pafcore::FunctionInvoker invoker)
//{
// pafcore::Variant arguments[2];
// pafcore::Variant* args[2];
// args[0] = PythonToVariant(&arguments[0], pyObject1);
// args[1] = PythonToVariant(&arguments[1], pyObject2);
// pafcore::Variant result;
// pafcore::ErrorCode errorCode = (*invoker)(&result, args, 2);
// if(pafcore::s_ok == errorCode)
// {
// Py_INCREF(pyObject1);
// return pyObject1;
// }
// PyErr_SetString(PyExc_RuntimeError, ErrorCodeToString(errorCode));
// return 0;
//}
PyObject* VariantWrapper_add(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_add");
}
PyObject* VariantWrapper_subtract(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_subtract");
}
PyObject* VariantWrapper_multiply(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_multiply");
}
PyObject* VariantWrapper_mod(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_mod");
}
PyObject* VariantWrapper_negative(PyObject* pyObject)
{
return VariantWrapper_unaryOperator(pyObject, "op_negate");
}
PyObject* VariantWrapper_positive(PyObject* pyObject)
{
return VariantWrapper_unaryOperator(pyObject, "op_plus");
}
PyObject* VariantWrapper_invert(PyObject* pyObject)
{
return VariantWrapper_unaryOperator(pyObject, "op_bitwiseNot");
}
PyObject* VariantWrapper_lshift(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_leftShift");
}
PyObject* VariantWrapper_rshift(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_rightShift");
}
PyObject* VariantWrapper_and(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_bitwiseAnd");
}
PyObject* VariantWrapper_xor(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_bitwiseXor");
}
PyObject* VariantWrapper_or(PyObject* pyObject1, PyObject* pyObject2)
{
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_bitwiseOr");
}
//
//PyObject* VariantWrapper_inplace_add(PyObject* pyObject1, PyObject* pyObject2)
//{
// return VariantWrapper_compoundAssignmentOperator(pyObject1, pyObject2, pafcore::PrimitiveType::Primitive_op_addAssign);
//}
static PyNumberMethods s_VariantWrapper_Operators =
{
VariantWrapper_add,//binaryfunc nb_add;
VariantWrapper_subtract,//binaryfunc nb_subtract;
VariantWrapper_multiply,//binaryfunc nb_multiply;
VariantWrapper_mod,//binaryfunc nb_remainder;
0,//binaryfunc nb_divmod;
0,//ternaryfunc nb_power;
VariantWrapper_negative,//unaryfunc nb_negative;
VariantWrapper_positive,//unaryfunc nb_positive;
0,//unaryfunc nb_absolute;
0,//inquiry nb_bool;
VariantWrapper_invert,//unaryfunc nb_invert;
VariantWrapper_lshift,//binaryfunc nb_lshift;
VariantWrapper_rshift,//binaryfunc nb_rshift;
VariantWrapper_and,//binaryfunc nb_and;
VariantWrapper_xor,//binaryfunc nb_xor;
VariantWrapper_or,//binaryfunc nb_or;
0,//unaryfunc nb_int;
0,//void *nb_reserved; /* the slot formerly known as nb_long */
0,//unaryfunc nb_float;
0,//binaryfunc nb_inplace_add;
0,//binaryfunc nb_inplace_subtract;
0,//binaryfunc nb_inplace_multiply;
0,//binaryfunc nb_inplace_remainder;
0,//ternaryfunc nb_inplace_power;
0,//binaryfunc nb_inplace_lshift;
0,//binaryfunc nb_inplace_rshift;
0,//binaryfunc nb_inplace_and;
0,//binaryfunc nb_inplace_xor;
0,//binaryfunc nb_inplace_or;
0,//binaryfunc nb_floor_divide;
0,//binaryfunc nb_true_divide;
0,//binaryfunc nb_inplace_floor_divide;
0,//binaryfunc nb_inplace_true_divide;
0,//unaryfunc nb_index;
0,//binaryfunc nb_matrix_multiply;
0,//binaryfunc nb_inplace_matrix_multiply;
};
PyObject* VariantWrapper_richcmp(PyObject* pyObject1, PyObject* pyObject2, int op)
{
switch(op)
{
case Py_LT:
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_less");
case Py_LE:
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_lessEqual");
case Py_EQ:
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_equal");
case Py_NE:
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_notEqual");
case Py_GT:
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_greater");
case Py_GE:
return VariantWrapper_binaryOperator(pyObject1, pyObject2, "op_greaterEqual");
}
return 0;
}
static PyMappingMethods s_VariantWrapper_Array_Methods =
{
(lenfunc)VariantWrapper_length,
(binaryfunc)VariantWrapper_subscript,
(objobjargproc)VariantWrapper_assign_subscript
};
static PyMappingMethods s_InstanceArrayPropertyWrapper_Array_Methods =
{
(lenfunc)InstanceArrayPropertyWrapper_length,
(binaryfunc)InstanceArrayPropertyWrapper_subscript,
(objobjargproc)InstanceArrayPropertyWrapper_assign_subscript
};
static PyMappingMethods s_StaticArrayPropertyWrapper_Array_Methods =
{
(lenfunc)StaticArrayPropertyWrapper_length,
(binaryfunc)StaticArrayPropertyWrapper_subscript,
(objobjargproc)StaticArrayPropertyWrapper_assign_subscript
};
static PyModuleDef s_PafPythonModule =
{
PyModuleDef_HEAD_INIT,
"PafPython",
0,
-1,
};
PyMODINIT_FUNC PyInit_PafPython_()
{
PyObject* module;
s_VariantWrapper_Type.tp_dealloc = (destructor)VariantWrapper_dealloc;
s_VariantWrapper_Type.tp_getattr = (getattrfunc)VariantWrapper_getattr;
s_VariantWrapper_Type.tp_setattr = (setattrfunc)VariantWrapper_setattr;
s_VariantWrapper_Type.tp_call = (ternaryfunc)VariantWrapper_call;
s_VariantWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_VariantWrapper_Type.tp_new = VariantWrapper_new;
s_VariantWrapper_Type.tp_as_number = &s_VariantWrapper_Operators;
s_VariantWrapper_Type.tp_as_mapping = &s_VariantWrapper_Array_Methods;
s_VariantWrapper_Type.tp_richcompare = &VariantWrapper_richcmp;
if (PyType_Ready(&s_VariantWrapper_Type) < 0)
{
return NULL;
}
s_InstanceArrayPropertyWrapper_Type.tp_dealloc = (destructor)InstanceArrayPropertyWrapper_dealloc;
s_InstanceArrayPropertyWrapper_Type.tp_getattr = (getattrfunc)InstanceArrayPropertyWrapper_getattr;
s_InstanceArrayPropertyWrapper_Type.tp_setattr = (setattrfunc)InstanceArrayPropertyWrapper_setattr;
s_InstanceArrayPropertyWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_InstanceArrayPropertyWrapper_Type.tp_new = InstanceArrayPropertyWrapper_new;
s_InstanceArrayPropertyWrapper_Type.tp_as_mapping = &s_InstanceArrayPropertyWrapper_Array_Methods;
if (PyType_Ready(&s_InstanceArrayPropertyWrapper_Type) < 0)
{
return NULL;
}
s_StaticArrayPropertyWrapper_Type.tp_getattr = (getattrfunc)StaticArrayPropertyWrapper_getattr;
s_StaticArrayPropertyWrapper_Type.tp_setattr = (setattrfunc)StaticArrayPropertyWrapper_setattr;
s_StaticArrayPropertyWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_StaticArrayPropertyWrapper_Type.tp_new = StaticArrayPropertyWrapper_new;
s_StaticArrayPropertyWrapper_Type.tp_as_mapping = &s_StaticArrayPropertyWrapper_Array_Methods;
if (PyType_Ready(&s_StaticArrayPropertyWrapper_Type) < 0)
{
return NULL;
}
s_InstanceMethodWrapper_Type.tp_dealloc = (destructor)InstanceMethodWrapper_dealloc;
s_InstanceMethodWrapper_Type.tp_call = (ternaryfunc)InstanceMethodWrapper_call;
s_InstanceMethodWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_InstanceMethodWrapper_Type.tp_new = InstanceMethodWrapper_new;
if (PyType_Ready(&s_InstanceMethodWrapper_Type) < 0)
{
return NULL;
}
s_FunctionInvokerWrapper_Type.tp_call = (ternaryfunc)FunctionInvokerWrapper_call;
s_FunctionInvokerWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_FunctionInvokerWrapper_Type.tp_new = FunctionInvokerWrapper_new;
if (PyType_Ready(&s_FunctionInvokerWrapper_Type) < 0)
{
return NULL;
}
s_ProxyCreatorWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_ProxyCreatorWrapper_Type.tp_new = ProxyCreatorWrapper_new;
s_ProxyCreatorWrapper_Type.tp_call = (ternaryfunc)ProxyCreatorWrapper_call;
if (PyType_Ready(&s_ProxyCreatorWrapper_Type) < 0)
{
return NULL;
}
s_TypeCasterWrapper_Type.tp_flags = Py_TPFLAGS_DEFAULT;
s_TypeCasterWrapper_Type.tp_new = TypeCasterWrapper_new;
s_TypeCasterWrapper_Type.tp_call = (ternaryfunc)TypeCasterWrapper_call;
if (PyType_Ready(&s_TypeCasterWrapper_Type) < 0)
{
return NULL;
}
module = PyModule_Create(&s_PafPythonModule);
if (module == NULL)
{
return NULL;
}
Py_INCREF(&s_VariantWrapper_Type);
PyObject* root = VariantWrapper_new(&s_VariantWrapper_Type, 0, 0);
pafcore::Variant* var = (pafcore::Variant*)((VariantWrapper*)root)->m_var;
var->assignReferencePtr(RuntimeTypeOf<pafcore::NameSpace>::RuntimeType::GetSingleton(), pafcore::NameSpace::GetGlobalNameSpace(), false, ::pafcore::Variant::by_ptr);
PyModule_AddObject(module, "paf", root);
return module;
}
END_PAFPYTHON
PyMODINIT_FUNC PyInit_PafPython()
{
return pafpython::PyInit_PafPython_();
}
| 29.244094 | 166 | 0.748846 | fdyjfd |
dbddc049640e172e2976532d88e9479093090ff4 | 1,186 | cc | C++ | ash/wm/window_dimmer_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | ash/wm/window_dimmer_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | ash/wm/window_dimmer_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/wm/window_dimmer.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/test/test_windows.h"
#include "ui/aura/window_occlusion_tracker.h"
namespace ash {
using WindowDimmerTest = aura::test::AuraTestBase;
// Verify that a window underneath the window dimmer is not occluded.
TEST_F(WindowDimmerTest, Occlusion) {
aura::Window* bottom_window = aura::test::CreateTestWindow(
SK_ColorWHITE, 1, root_window()->bounds(), root_window());
aura::WindowOcclusionTracker::Track(bottom_window);
WindowDimmer dimmer(root_window());
EXPECT_EQ(aura::Window::OcclusionState::VISIBLE,
bottom_window->occlusion_state());
// Sanity check: An opaque window on top of |bottom_window| occludes it.
aura::test::CreateTestWindow(SK_ColorWHITE, 2, root_window()->bounds(),
root_window());
EXPECT_EQ(aura::Window::OcclusionState::OCCLUDED,
bottom_window->occlusion_state());
}
} // namespace ash
| 38.258065 | 74 | 0.724283 | zipated |
dbdec26c028ff42e9f5f193c9eea7efe879435dd | 4,500 | cpp | C++ | Signal Flow Simulation/truetime-2.0/examples/advanced_demos/RUNES_demo/node/AODVsndcode.cpp | raulest50/MicroGrid_GITCoD | 885001242c8e581a6998afb4be2ae1c0b923e9c4 | [
"MIT"
] | 1 | 2019-08-31T08:06:48.000Z | 2019-08-31T08:06:48.000Z | Signal Flow Simulation/truetime-2.0/examples/advanced_demos/RUNES_demo/node/AODVsndcode.cpp | raulest50/MicroGrid_GITCoD | 885001242c8e581a6998afb4be2ae1c0b923e9c4 | [
"MIT"
] | null | null | null | Signal Flow Simulation/truetime-2.0/examples/advanced_demos/RUNES_demo/node/AODVsndcode.cpp | raulest50/MicroGrid_GITCoD | 885001242c8e581a6998afb4be2ae1c0b923e9c4 | [
"MIT"
] | 1 | 2020-01-07T10:46:23.000Z | 2020-01-07T10:46:23.000Z | double AODVsndcode(int seg, void* data) {
AODVsnd_Data* d = (AODVsnd_Data*) data;
int myID = d->nodeID;
MailboxMsg *mailboxmsg;
GenericNwkMsg *nwkmsg;
DataMsg *datamsg;
RREQMsg *rreqmsg;
int dest;
double now, etime;
RouteEntry *dest_entry;
DataNode *dn;
switch (seg) {
case 1:
ttFetch("AODVSndBox");
return 0.0001;
case 2:
mailboxmsg = (MailboxMsg*) ttRetrieve("AODVSndBox");
now = ttCurrentTime();
switch (mailboxmsg->type) {
case APPL_DATA:
// Data message from application
datamsg = (DataMsg*) mailboxmsg->datamsg;
delete mailboxmsg;
mexPrintf("Time: %f Application in Node# %d wants to send to Node# %d Data: %f\n", now, myID, datamsg->dest, datamsg->data);
dest_entry = &(d->routing_table[datamsg->dest-1]);
// Is the entry valid?
if (!dest_entry->valid) {
// Not found in routing table
mexPrintf("No (valid) route exists\n");
// Increment broadcast ID and sequence number
d->RREQID++;
d->seqNbrs[myID-1]++;
// Create RREQ
rreqmsg = new RREQMsg;
rreqmsg->hopCnt = 0;
rreqmsg->RREQID = d->RREQID;
rreqmsg->dest = datamsg->dest;
rreqmsg->destSeqNbr = d->seqNbrs[datamsg->dest-1];
rreqmsg->src = myID;
rreqmsg->srcSeqNbr = d->seqNbrs[myID-1];
d->sendTo = 0; // broadcast
d->msg = new GenericNwkMsg;
d->msg->type = RREQ;
d->msg->intermed = myID;
d->msg->msg = rreqmsg;
d->size = 24*8; // 24 bytes
// buffer data until route has been established
// mexPrintf("Buffering message %d\n", d->buffer[datamsg->dest-1]->length()+1);
// d->buffer[datamsg->dest-1]->appendNode(new DataNode(datamsg, ""));
// exectime
etime = 0.0001;;
} else {
// Route to destination exists in table
mexPrintf("Route exists in table ");
mexPrintf("nextHop: %d #Hops: %d\n", dest_entry->nextHop, dest_entry->hops);
// Send data to first node on route to destination
d->sendTo = dest_entry->nextHop;
d->msg = new GenericNwkMsg;
d->msg->type = DATA;
d->msg->intermed = myID;
d->msg->msg = datamsg;
d->size = datamsg->size;
// Update expiry time
d->routing_table[datamsg->dest-1].exptime = now + ACTIVE_ROUTE_TIMEOUT;
updateExpiryTimer(d->routing_table, d->dataTimer, myID);
etime = 0.0001;;
}
return etime;
case ROUTE_EST:
// Message from AODVRcv that a route has been established
dest = mailboxmsg->dest;
delete mailboxmsg;
mexPrintf("Time: %f A new route has been established between Node#%d and Node#%d\n", now, myID, dest);
dest_entry = &(d->routing_table[dest-1]);
// mexPrintf("nextHop: %d #Hops: %d\n", dest_entry->nextHop, dest_entry->hops);
// mexPrintf("%d data messages in buffer\n", d->buffer[dest-1]->length());
d->bufferDest = dest;
d->doEmptyBuffer = 0; // Buffer should be emptied
// Update expiry timer
d->routing_table[dest-1].exptime = now + ACTIVE_ROUTE_TIMEOUT;
updateExpiryTimer(d->routing_table, d->dataTimer, myID);
return 0.0001;;
}
case 3:
// Send buffered data messages?
if (d->doEmptyBuffer) {
dn = (DataNode*) d->buffer[d->bufferDest-1]->getFirst();
if (dn != NULL) {
// Retrieve next message in buffer
datamsg = (DataMsg*) dn->data;
// mexPrintf("Buffer Size: %d Sending buffered message towards Node#%d\n", d->buffer[d->bufferDest-1]->length(), d->bufferDest);
dn->remove();
delete dn;
// Retrieve route entry
dest_entry = &(d->routing_table[datamsg->dest-1]);
nwkmsg = new GenericNwkMsg;
nwkmsg->type = DATA;
nwkmsg->intermed = myID;
nwkmsg->msg = datamsg;
ttSendMsg(1, dest_entry->nextHop, nwkmsg, datamsg->size);
ttSleep(0.001);
return 0.0001;
} else {
// Finished sending data messages
// mexPrintf("Buffer emptied\n");
d->doEmptyBuffer = 0;
ttSetNextSegment(1); // Loop back
return 0.0001;
}
} else {
ttSendMsg(1, d->sendTo, d->msg, d->size);
ttSetNextSegment(1); // Loop back
return 0.0001;
}
case 4:
ttSetNextSegment(3);
return 0.0001;
}
return FINISHED; // to supress compilation warnings
}
| 14.469453 | 136 | 0.582222 | raulest50 |
dbdf58de09ffeed6854c5f822b4fa4d7caa9d730 | 1,563 | cpp | C++ | sdk/object/entity.cpp | playday3008/herby | 3ab4594588c4776182f18edf89d461adef583614 | [
"MIT"
] | null | null | null | sdk/object/entity.cpp | playday3008/herby | 3ab4594588c4776182f18edf89d461adef583614 | [
"MIT"
] | null | null | null | sdk/object/entity.cpp | playday3008/herby | 3ab4594588c4776182f18edf89d461adef583614 | [
"MIT"
] | null | null | null | #include "entity.hpp"
#include "csgo/engine.hpp"
C_BaseEntity* C_BaseEntity::GetBaseEntity(int index)
{
auto client_entity = csgo::m_client_entity_list->GetClientEntity(index);
return (client_entity ? client_entity->GetBaseEntity() : nullptr);
}
int C_BaseEntity::GetMoveType()
{
auto& netvar = csgo::engine::NetPropSystem::Instance();
return netvar.GetDataMap(this->GetPredDescMap(), "m_MoveType");
}
C_AnimationLayer& C_BaseAnimatingOverlay::GetAnimOverlay(int i)
{
static auto field = csgo::engine::NetPropSystem::Instance().GetDataMap(this->GetPredDescMap(), "m_AnimOverlay");
return (*reinterpret_cast<C_AnimationLayer**>(reinterpret_cast<int>(this) + 0x2980))[i];
}
Activity C_BaseAnimatingOverlay::GetSequenceActivity(int sequence)
{
model_t* mdl = this->GetModel();
if (mdl)
{
studiohdr_t* hdr = csgo::m_model_info->GetStudioModel(mdl);
if (hdr)
{
static int offset = memory::scan<int>(L"client.dll","55 8B EC 53 8B 5D 08 56 8B F1 83");
static auto get_sequence_activity = reinterpret_cast<int(__fastcall*)(void*, studiohdr_t*, int)>(offset);
return static_cast<Activity>(get_sequence_activity(this, hdr, sequence));
}
}
return Activity::ACT_RESET;
}
C_CSPlayer* C_CSPlayer::GetCSPlayer(int index)
{
auto base_entity = C_BaseEntity::GetBaseEntity(index);
return ToCSPlayer(base_entity);
}
C_CSPlayer* C_CSPlayer::GetLocalPlayer()
{
auto index = csgo::m_engine_client->GetLocalPlayer();
return GetCSPlayer(index);
}
C_World* C_World::GetWorld()
{
return reinterpret_cast<C_World*>(C_BaseEntity::GetBaseEntity(0));
}
| 28.944444 | 113 | 0.751759 | playday3008 |
dbdf5e502674a08010f428b1000f028875412737 | 14,606 | cpp | C++ | InitFile/Tests/ifTestSupport.cpp | opendragon/IF | 11e9132b896a67115b8fc9fc9cddcd592b838bfa | [
"BSD-3-Clause"
] | null | null | null | InitFile/Tests/ifTestSupport.cpp | opendragon/IF | 11e9132b896a67115b8fc9fc9cddcd592b838bfa | [
"BSD-3-Clause"
] | null | null | null | InitFile/Tests/ifTestSupport.cpp | opendragon/IF | 11e9132b896a67115b8fc9fc9cddcd592b838bfa | [
"BSD-3-Clause"
] | null | null | null | //--------------------------------------------------------------------------------------------------
//
// File: Tests/ifTestSupport.cpp
//
// Project: IF
//
// Contains: The function and class definitions for InitFile test programs.
//
// Written by: Norman Jaffe
//
// Copyright: (c) 2020 by OpenDragon.
//
// All rights reserved. Redistribution and use in source and binary forms, with or
// without modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and / or
// other materials provided with the distribution.
// * Neither the name of the copyright holders nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// Created: 2020-09-25
//
//--------------------------------------------------------------------------------------------------
#include "ifTestSupport.h"
//#include <odlEnable.h>
#include <odlInclude.h>
#include <ifBase.h>
#include <csignal>
#include <sstream>
#if MAC_OR_LINUX_
# include <unistd.h>
#else // ! MAC_OR_LINUX_
# include <Windows.h>
#endif // ! MAC_OR_LINUX_
#if defined(__APPLE__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunknown-pragmas"
# pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
#endif // defined(__APPLE__)
/*! @file
@brief The function and class definitions for %InitFile test programs. */
# if defined(__APPLE__)
# pragma clang diagnostic pop
# endif // defined(__APPLE__)
#if defined(__APPLE__)
# pragma mark Namespace references
#endif // defined(__APPLE__)
using namespace InitFile;
#if defined(__APPLE__)
# pragma mark Private structures, constants and variables
#endif // defined(__APPLE__)
/*! @brief The signal to use for internally-detected timeouts. */
#if MAC_OR_LINUX_
# define STANDARD_SIGNAL_TO_USE_ SIGUSR2
#else // ! MAC_OR_LINUX_
# define STANDARD_SIGNAL_TO_USE_ 42
#endif // ! MAC_OR_LINUX_
#if defined(__APPLE__)
# pragma mark Global constants and variables
#endif // defined(__APPLE__)
std::string InitFile::kDQ{"\""};
#if defined(__APPLE__)
# pragma mark Local functions
#endif // defined(__APPLE__)
#if MAC_OR_LINUX_
/*! @brief The signal handler to catch requests to stop the service.
@param[in] signal The signal being handled. */
[[noreturn]]
static void
localCatcher
(int NOT_USED_(signal))
{
ODL_ENTER(); //####
//ODL_I1("signal = ", signal); //####
#if 0
if (lLogger)
{
std::string message{"Exiting due to signal "};
message += std::to_string(signal);
message += " = ";
message += NameOfSignal(signal);
lLogger->error(message.c_str());
}
#endif//0
ODL_EXIT_EXIT(1); //####
exit(1);
} // localCatcher
#endif // MAC_OR_LINUX_
#if defined(__APPLE__)
# pragma mark Class methods
#endif // defined(__APPLE__)
#if defined(__APPLE__)
# pragma mark Constructors and Destructors
#endif // defined(__APPLE__)
#if defined(__APPLE__)
# pragma mark Actions and Accessors
#endif // defined(__APPLE__)
#if defined(__APPLE__)
# pragma mark Global functions
#endif // defined(__APPLE__)
bool
InitFile::CanReadFromStandardInput
(void)
{
ODL_ENTER(); //####
#if MAC_OR_LINUX_
pid_t fg = tcgetpgrp(STDIN_FILENO);
#else // ! MAC_OR_LINUX_
HWND wind = GetConsoleWindow();
#endif // ! MAC_OR_LINUX_
bool result = false;
#if MAC_OR_LINUX_
if (-1 == fg)
{
// Piped
result = true;
}
else if (getpgrp() == fg)
{
// Foreground
result = true;
}
else
{
// Background
result = false;
}
#else // ! MAC_OR_LINUX_
result = (nullptr != wind);
#endif // ! MAC_OR_LINUX_
ODL_EXIT_B(result); //####
return result;
} // InitFile::CanReadFromStandardInput
std::string
InitFile::ConvertDoubleToString
(const double value)
{
ODL_ENTER(); //####
ODL_D1("value = ", value); //####
// Note that boost::lexical_cast<std::string>(double) generates strings with trailing digits.
// That is, 1E-22 winds up as 9.9999999999999E-21, which is platform-sensitive.
std::ostringstream holder;
holder << std::defaultfloat << value;
std::string result{holder.str()};
ODL_EXIT_s(result); //####
return result;
} // InitFile::ConvertDoubleToString
bool
InitFile::ConvertToDouble
(const char * startPtr,
double & result)
{
ODL_ENTER(); //####
ODL_S1("startPtr = ", startPtr); //####
ODL_P1("result = ", &result); //####
bool okSoFar;
char * endPtr;
double value = strtod(startPtr, &endPtr);
if ((startPtr != endPtr) && (! *endPtr))
{
result = value;
ODL_D1("result <- ", result); //####
okSoFar = true;
}
else
{
okSoFar = false;
}
ODL_EXIT_B(okSoFar); //####
return okSoFar;
} // InitFile::ConvertToDouble
bool
InitFile::ConvertToInt64
(const char * startPtr,
int64_t & result)
{
ODL_ENTER(); //####
ODL_S1("startPtr = ", startPtr); //####
ODL_P1("result = ", &result); //####
bool okSoFar;
char * endPtr;
int64_t value = strtoll(startPtr, &endPtr, 10);
if ((startPtr != endPtr) && (! *endPtr))
{
result = value;
ODL_I1("result <- ", result); //####
okSoFar = true;
}
else
{
okSoFar = false;
}
ODL_EXIT_B(okSoFar); //####
return okSoFar;
} // InitFile::ConvertToInt64
void
InitFile::Initialize
(const std::string & NOT_USED_(progName))
{
ODL_ENTER(); //####
//ODL_S1s("progName = ", progName); //####
try
{
#if defined(__APPLE__)
sranddev();
#else // ! defined(__APPLE__)
srand(static_cast<unsigned int>(time(nullptr)));
#endif // ! defined(__APPLE__)
//Value::initialize();
}
catch (...)
{
ODL_LOG("Exception caught"); //####
throw;
}
ODL_EXIT(); //####
} // InitFile::Initialize
const char *
InitFile::NameOfSignal
(const int theSignal)
{
const char * result;
#if MAC_OR_LINUX_
switch (theSignal)
{
case SIGHUP :
result = "SIGHUP[hangup]";
break;
case SIGINT :
result = "SIGINT[interrupt]";
break;
case SIGQUIT :
result = "SIGQUIT[quit]";
break;
case SIGILL :
result = "SIGILL[illegal instruction]";
break;
case SIGTRAP :
result = "SIGTRAP[trace trap]";
break;
case SIGABRT :
result = "SIGABRT[abort()]";
break;
# if (defined(_POSIX_C_SOURCE) && (! defined(_DARWIN_C_SOURCE)))
case SIGPOLL :
result = "SIGPOLL[pollable evebt]";
break;
# else // (! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE)
case SIGEMT :
result = "SIGEMT[EMT instruction]";
break;
# endif // (! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE)
case SIGFPE :
result = "SIGFPE[floating point exception]";
break;
case SIGKILL :
result = "SIGKILL[kill]";
break;
case SIGBUS :
result = "SIGBUS[bus error]";
break;
case SIGSEGV :
result = "SIGSEGV[segmentation violation]";
break;
case SIGSYS :
result = "SIGSYS[bad argument to system call]";
break;
case SIGPIPE :
result = "SIGPIPE[write on a pipe with no one to read it]";
break;
case SIGALRM :
result = "SIGALRM[alarm clock]";
break;
case SIGTERM :
result = "SIGTERM[software termination signal from kill]";
break;
case SIGURG :
result = "SIGURG[urgent condition on IO channel]";
break;
case SIGSTOP :
result = "SIGSTOP[sendable stop signal not from tty]";
break;
case SIGTSTP :
result = "SIGTSTP[stop signal from tty]";
break;
case SIGCONT :
result = "SIGCONT[continue a stopped process]";
break;
case SIGCHLD :
result = "SIGCHLD[to parent on child stop or exit]";
break;
case SIGTTIN :
result = "SIGTTIN[to readers pgrp upon background tty read]";
break;
case SIGTTOU :
result = "SIGTTOU[like TTIN for output if (tp->t_local <OSTOP)]";
break;
# if ((! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE))
case SIGIO :
result = "SIGIO[input/output possible signal]";
break;
# endif // (! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE)
case SIGXCPU :
result = "SIGXCPU[exceeded CPU time limit]";
break;
case SIGXFSZ :
result = "SIGXFSZ[exceeded file size limit]";
break;
case SIGVTALRM :
result = "SIGVTALRM[virtual time alarm]";
break;
case SIGPROF :
result = "SIGPROF[profiling time alarm]";
break;
# if ((! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE))
case SIGWINCH :
result = "SIGWINCH[window size changes]";
break;
# endif // (! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE)
# if ((! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE))
case SIGINFO :
result = "SIGINFO[information request]";
break;
# endif // (! defined(_POSIX_C_SOURCE)) || defined(_DARWIN_C_SOURCE)
case SIGUSR1 :
result = "SIGUSR1[user defined signal 1]";
break;
case SIGUSR2 :
result = "SIGUSR2[user defined signal 2]";
break;
default :
result = "unknown";
break;
}
#else // ! MAC_OR_LINUX_
switch (theSignal)
{
case SIGINT :
result = "SIGINT[interrupt]";
break;
case SIGABRT :
result = "SIGABRT[abort()]";
break;
default :
result = "unknown";
break;
}
#endif // ! MAC_OR_LINUX_
return result;
} // InitFile::NameOfSignal
double
InitFile::RandomDouble
(const double minValue,
const double maxValue)
{
double zeroOne = (static_cast<double>(rand()) / RAND_MAX);
return (zeroOne * (maxValue - minValue)) + minValue;
} // InitFile::RandomDouble
void
InitFile::SetSignalHandlers
(InitFile::SignalHandler theHandler)
{
#if MAC_OR_LINUX_
sigset_t blocking;
struct sigaction act;
#endif // MAC_OR_LINUX_
ODL_ENTER(); //####
#if MAC_OR_LINUX_
act.sa_handler = theHandler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
# if (defined(SIGABRT) && (SIGABRT != STANDARD_SIGNAL_TO_USE_))
sigaction(SIGABRT, &act, nullptr);
# endif // defined(SIGABRT) && (SIGABRT != STANDARD_SIGNAL_TO_USE_)
# if (defined(SIGHUP) && (SIGHUP != STANDARD_SIGNAL_TO_USE_))
sigaction(SIGHUP, &act, nullptr);
# endif // defined(SIGHUP) && (SIGABRT != STANDARD_SIGNAL_TO_USE_)
# if (defined(SIGINT) && (SIGINT != STANDARD_SIGNAL_TO_USE_))
sigaction(SIGINT, &act, nullptr);
# endif // defined(SIGINT) && (SIGABRT != STANDARD_SIGNAL_TO_USE_)
# if (defined(SIGQUIT) && (SIGQUIT != STANDARD_SIGNAL_TO_USE_))
sigaction(SIGQUIT, &act, nullptr);
# endif // defined(SIGQUIT) && (SIGABRT != STANDARD_SIGNAL_TO_USE_)
# if (defined(SIGUSR1) && (SIGUSR1 != STANDARD_SIGNAL_TO_USE_))
sigaction(SIGUSR1, &act, nullptr);
# endif // defined(SIGUSR1) && (SIGABRT != STANDARD_SIGNAL_TO_USE_)
# if (defined(SIGUSR2) && (SIGUSR2 != STANDARD_SIGNAL_TO_USE_))
sigaction(SIGUSR2, &act, nullptr);
# endif // defined(SIGUSR2) && (SIGABRT != STANDARD_SIGNAL_TO_USE_)
sigemptyset(&blocking);
sigaddset(&blocking, STANDARD_SIGNAL_TO_USE_);
pthread_sigmask(SIG_BLOCK, &blocking, nullptr);
#else // ! MAC_OR_LINUX
#endif // ! MAC_OR_LINUX_
ODL_EXIT(); //####
} // InitFile::SetSignalHandlers
void
InitFile::SetUpCatcher
(void)
{
#if MAC_OR_LINUX_
sigset_t unblocking;
struct sigaction act;
#endif // MAC_OR_LINUX_
ODL_ENTER(); //####
#if MAC_OR_LINUX_
sigemptyset(&unblocking);
sigaddset(&unblocking, STANDARD_SIGNAL_TO_USE_);
pthread_sigmask(SIG_UNBLOCK, &unblocking, nullptr);
act.sa_handler = localCatcher;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(STANDARD_SIGNAL_TO_USE_, &act, nullptr);
#else // ! MAC_OR_LINUX_
#endif // ! MAC_OR_LINUX_
ODL_EXIT(); //####
} // InitFile::SetUpCatcher
void
InitFile::ShutDownCatcher
(void)
{
#if MAC_OR_LINUX_
sigset_t blocking;
struct sigaction act;
#endif // MAC_OR_LINUX_
ODL_ENTER(); //####
#if MAC_OR_LINUX_
sigemptyset(&blocking);
sigaddset(&blocking, STANDARD_SIGNAL_TO_USE_);
pthread_sigmask(SIG_BLOCK, &blocking, nullptr);
act.sa_handler = SIG_DFL;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(STANDARD_SIGNAL_TO_USE_, &act, nullptr);
#else // ! MAC_OR_LINUX_
#endif // ! MAC_OR_LINUX_
ODL_EXIT(); //####
} // InitFile::ShutDownCatcher
| 27.768061 | 100 | 0.598863 | opendragon |
dbe01a7a918e25d8af6f4f4186ca3f27826f9e95 | 1,617 | cc | C++ | net/socket.cc | xingdl2007/polly | c23906d7f58d2eb263cb102b0343dccd5a245881 | [
"BSD-3-Clause"
] | 2 | 2018-04-12T21:13:18.000Z | 2018-06-10T14:18:04.000Z | net/socket.cc | xingdl2007/polly | c23906d7f58d2eb263cb102b0343dccd5a245881 | [
"BSD-3-Clause"
] | null | null | null | net/socket.cc | xingdl2007/polly | c23906d7f58d2eb263cb102b0343dccd5a245881 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2018 The Polly Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <stdlib.h>
#include <sys/socket.h>
#include "socket.h"
#include "log/logger.h"
namespace polly {
void Socket::Bind(InetAddress const &addr_) {
auto addr = addr_.SockAddress();
int ret = ::bind(sockfd_, reinterpret_cast<sockaddr *> (&addr), sizeof addr);
if (ret == -1) {
LOG_FATAL << "Socket::Bind() failed, port: " << addr_.Port();
::abort();
}
}
void Socket::ShutdownWrite() {
if (::shutdown(sockfd_, SHUT_WR) < 0) {
LOG_ERROR << "Socket::ShutdownWrite()";
}
}
// only support IPv4 + TCP for simplicity
int NewNonBlockingSocket() {
int sockfd = ::socket(PF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (sockfd == -1) {
LOG_FATAL << "NewNonBlockingSocket() failed";
::abort();
}
return sockfd;
}
struct sockaddr_in getLocalAddr(int sockfd) {
struct sockaddr_in localaddr;
bzero(&localaddr, sizeof localaddr);
socklen_t addrlen = sizeof localaddr;
if (::getsockname(sockfd, reinterpret_cast<sockaddr *>(&localaddr), &addrlen) < 0) {
LOG_ERROR << "sockets::getLocalAddr";
}
return localaddr;
}
struct sockaddr_in getPeerAddr(int sockfd) {
struct sockaddr_in peeraddr;
bzero(&peeraddr, sizeof peeraddr);
socklen_t addrlen = sizeof peeraddr;
if (::getpeername(sockfd, reinterpret_cast<sockaddr *>(&peeraddr), &addrlen) < 0) {
LOG_ERROR << "sockets::getPeerAddr";
}
return peeraddr;
}
} // namespace polly
| 27.87931 | 86 | 0.687075 | xingdl2007 |
dbe839aaaa905f258032ddd7d5ff5568245b3081 | 1,465 | hpp | C++ | include/xvega/grammar/encodings/encoding-channels/hyperlink-channels/href.hpp | domoritz/xvega | 3754dee3e7e38e79282ba267cd86c3885807a4cd | [
"BSD-3-Clause"
] | 34 | 2020-08-14T14:32:51.000Z | 2022-02-16T23:20:02.000Z | include/xvega/grammar/encodings/encoding-channels/hyperlink-channels/href.hpp | domoritz/xvega | 3754dee3e7e38e79282ba267cd86c3885807a4cd | [
"BSD-3-Clause"
] | 19 | 2020-08-20T20:04:39.000Z | 2022-02-28T14:34:37.000Z | include/xvega/grammar/encodings/encoding-channels/hyperlink-channels/href.hpp | domoritz/xvega | 3754dee3e7e38e79282ba267cd86c3885807a4cd | [
"BSD-3-Clause"
] | 7 | 2020-08-14T14:18:17.000Z | 2022-02-01T10:59:24.000Z | // Copyright (c) 2020, QuantStack and XVega Contributors
//
// Distributed under the terms of the BSD 3-Clause License.
//
// The full license is in the file LICENSE, distributed with this software.
#ifndef XVEGA_ENCODING_HREF_HPP
#define XVEGA_ENCODING_HREF_HPP
#include <xproperty/xobserved.hpp>
#include <xtl/xoptional.hpp>
#include <xtl/xjson.hpp>
#include <nlohmann/json.hpp>
#include "../../../../utils/custom_datatypes.hpp"
#include "../../encoding-channel-options/aggregate.hpp"
#include "../../encoding-channel-options/bin.hpp"
#include "../../encoding-channel-options/field.hpp"
#include "../../encoding-channel-options/timeunit.hpp"
namespace nl = nlohmann;
namespace xv
{
struct Href : public xp::xobserved<Href>
{
XPROPERTY(xtl::xoptional<agg_type>, Href, aggregate);
XPROPERTY(xtl::xoptional<bin_type>, Href, bin);
// XPROPERTY(xtl::xoptional<condition_type>, Href, condition);
XPROPERTY(xtl::xoptional<field_type>, Href, field);
XPROPERTY(xtl::xoptional<string_object_type>, Href, format);
XPROPERTY(xtl::xoptional<std::string>, Href, formatType);
XPROPERTY(xtl::xoptional<std::string>, Href, labelExpr);
XPROPERTY(xtl::xoptional<time_unit_type>, Href, timeUnit);
XPROPERTY(xtl::xoptional<string_vec_none_type>, Href, title);
XPROPERTY(xtl::xoptional<std::string>, Href, type);
};
XVEGA_API void to_json(nl::json& j, const Href& data);
}
#endif
| 32.555556 | 75 | 0.698976 | domoritz |
dbf2034212f87b8a744ba3a9a3b39d9adc0b80ed | 221 | cc | C++ | codeforces/246/a.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | 1 | 2019-05-12T23:41:00.000Z | 2019-05-12T23:41:00.000Z | codeforces/246/a.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | codeforces/246/a.cc | metaflow/contests | 5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
int c = 0;
while (n--) {
int v;
cin >> v;
if (v + k <= 5) c++;
}
cout << (c / 3) << endl;
}
| 13.8125 | 28 | 0.38009 | metaflow |
dbf6e33ac75bfa73b68fa656dddc3b1e5f035c7a | 808 | hpp | C++ | Siv3D/include/Siv3D/EmojiDictionary.hpp | ai2playgame/OpenSiv3D | e8814b4bb2baf23fcfc300325f700b842cce79b1 | [
"MIT"
] | null | null | null | Siv3D/include/Siv3D/EmojiDictionary.hpp | ai2playgame/OpenSiv3D | e8814b4bb2baf23fcfc300325f700b842cce79b1 | [
"MIT"
] | null | null | null | Siv3D/include/Siv3D/EmojiDictionary.hpp | ai2playgame/OpenSiv3D | e8814b4bb2baf23fcfc300325f700b842cce79b1 | [
"MIT"
] | null | null | null | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2019 Ryo Suzuki
// Copyright (c) 2016-2019 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <memory>
# include "Fwd.hpp"
# include "String.hpp"
# include "Array.hpp"
namespace s3d
{
class EmojiDictionary
{
private:
class EmojiDictionaryDetail;
std::shared_ptr<EmojiDictionaryDetail> pImpl;
public:
EmojiDictionary();
EmojiDictionary(const FilePath& path);
~EmojiDictionary();
bool load(const FilePath& path);
[[nodiscard]] size_t check(String::const_iterator it, const String::const_iterator& itEnd);
void clear();
const Array<Array<uint32>>& getList() const;
};
}
| 17.955556 | 93 | 0.612624 | ai2playgame |
dbf8b652b081c6876c2586a5371fc019198306ec | 962 | cpp | C++ | CodeForces/964B/13538902_AC_15ms_3304kB.cpp | BakaErii/ACM_Collection | d368b15c7f1c84472424d5e61e5ebc667f589025 | [
"WTFPL"
] | null | null | null | CodeForces/964B/13538902_AC_15ms_3304kB.cpp | BakaErii/ACM_Collection | d368b15c7f1c84472424d5e61e5ebc667f589025 | [
"WTFPL"
] | null | null | null | CodeForces/964B/13538902_AC_15ms_3304kB.cpp | BakaErii/ACM_Collection | d368b15c7f1c84472424d5e61e5ebc667f589025 | [
"WTFPL"
] | null | null | null | /**
* @author Moe_Sakiya sakiya@tun.moe
* @date 2018-04-17 22:33:09
*
*/
#include <iostream>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
int n, A, B, C, T;
int arr[1001];
int value[1001];
bool isRead[1001];
int main(void) {
ios::sync_with_stdio(false);
cin.tie(NULL);
int i, j;
unsigned long long int ans = 0;
scanf("%d %d %d %d %d", &n, &A, &B, &C, &T);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
value[i] = A;
}
for(i = 1; i < T; i++) {
for(j = 0; j < n; j++) {
if(isRead[j] != true && arr[j] <= i) {
if(value[j] + C - B > value[j]) {
value[j] -= B;
ans += C;
} else {
ans += value[j];
isRead[j] = true;
}
}
}
}
for(j = 0; j < n; j++)
if(isRead[j] == false)
ans += value[j];
printf("%llu\n", ans);
return 0;
} | 17.178571 | 45 | 0.529106 | BakaErii |
dbf90495427ac7591c1027b14ba3c08bdde28591 | 1,513 | cpp | C++ | ch04/e4-08.cpp | nanonashy/PPPUCpp2ndJP | b829867e9e21bf59d9c5ea6c2fbe96bb03597301 | [
"MIT"
] | 3 | 2021-12-17T17:25:18.000Z | 2022-03-02T15:52:23.000Z | ch04/e4-08.cpp | nashinium/PPPUCpp2ndJP | b829867e9e21bf59d9c5ea6c2fbe96bb03597301 | [
"MIT"
] | 1 | 2020-04-22T07:16:34.000Z | 2020-04-22T10:04:04.000Z | ch04/e4-08.cpp | nashinium/PPPUCpp2ndJP | b829867e9e21bf59d9c5ea6c2fbe96bb03597301 | [
"MIT"
] | 1 | 2020-04-22T08:13:51.000Z | 2020-04-22T08:13:51.000Z | // 問題文:
// 「チェス」を考案したものに褒美を与えようと考えた皇帝が、望みは何かと尋ねたという昔話があ
// る。そのものは、チェス盤の1つ目の升目に1グレインのコメ、2つ目の升目に2グレインの米、
// 3つ目の升目には4グレインの米といったように、64の升目ごとに2倍のの量の米を所望した。謙
// 虚な申し出のように思えたが、帝国にはそれだけの米がなかった。少なくとも1,000グレイン、
// 少なくとも100万グレイン、そして少なくとも10億グレインの米を褒美として与えるのに必要
// な升目の数を計算するプログラムを作成する。当然ながら、ループが必要である。また、現在の
// 升目を追跡するための int 型の変数、現在の升目のグレイン量を追跡するための
// int 型の変数、 それまでのすべての升目のグレイン量を追跡するための int
// 型の変数がおそらく必要になるだろ
// ろう。ループを繰り返すたびにすべての変数の値を書き出し、現在の状況がわかるようにすると
// よいだろう。
//
// コメント:
// 1000グレインは10升目まで、100万グレインは20升目まで、10億グレインは30升目までとなった。
#include "../include/std_lib_facilities.h"
int main() {
bool exit = false;
std::string input;
int total_grain{0};
int add_grain{1};
int times{0};
int request_grain{0};
cout << "グレイン数を入力してください...(quitで終了します)\n"
<< "times\t\tadded grain\t\ttotal grain\n>> ";
while (!exit) {
if (std::cin >> request_grain) {
total_grain = 0;
add_grain = 1;
times = 0;
while (total_grain < request_grain) {
++times;
total_grain += add_grain;
add_grain *= 2;
std::cout << times << "\t\t" << add_grain / 2 << "\t\t"
<< total_grain << '\n';
}
} else {
std::cin.clear();
std::cin >> input;
if (input == "quit")
exit = true;
}
std::cout << ">> ";
}
return 0;
} | 29.096154 | 72 | 0.551223 | nanonashy |
dbf9e591593ea426d4d2006806c04acacfe7ecd2 | 2,337 | cpp | C++ | Ray/Mono/RScript.cpp | CAt0mIcS/Ray | 898ebbfe1207513045718a4fb1df339621568de4 | [
"MIT"
] | null | null | null | Ray/Mono/RScript.cpp | CAt0mIcS/Ray | 898ebbfe1207513045718a4fb1df339621568de4 | [
"MIT"
] | null | null | null | Ray/Mono/RScript.cpp | CAt0mIcS/Ray | 898ebbfe1207513045718a4fb1df339621568de4 | [
"MIT"
] | null | null | null | #include "RScript.h"
#include <mono/jit/jit.h>
#include <mono/metadata/object.h>
#include <mono/metadata/environment.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/mono-config.h>
namespace At0::Ray::Mono
{
bool Script::s_MonoInitialized = false;
Script::Script(std::string_view compiledFilePath)
{
MonoInit();
m_Domain = mono_jit_init(compiledFilePath.data());
if (!m_Domain)
ThrowRuntime("[Mono::Script] Failed to initialize mono jit for assembly \"{0}\"",
compiledFilePath);
// Open a assembly in the domain
m_Assembly = mono_domain_assembly_open(m_Domain, compiledFilePath.data());
if (!m_Assembly)
ThrowRuntime("[Mono::Script] Failed to open assembly \"{0}\"", compiledFilePath);
// Get a image from the assembly
m_Image = mono_assembly_get_image(m_Assembly);
if (!m_Image)
ThrowRuntime(
"[Mono::Script] Failed to get image from the assembly \"{0}\"", compiledFilePath);
}
Script Script::FromFile(std::string_view filepath)
{
MonoInit();
if (!Compile(filepath))
ThrowRuntime("[Mono::Script] Failed to compile script file \"{0}\"", filepath);
return Script{ std::filesystem::path(filepath).replace_extension("dll").string() };
}
Script Script::FromCompiled(std::string_view filepath)
{
MonoInit();
return Script{ filepath };
}
StaticFunction Script::GetStaticFunction(std::string_view functionDescriptor) const
{
return StaticFunction{ functionDescriptor, m_Image };
}
Object Script::GetObject(std::string_view className) const
{
return Object{ className, m_Domain, m_Image };
}
bool Script::Compile(std::string_view filepath)
{
RAY_MEXPECTS(!String::Contains(filepath, " "),
"[Mono::Script] Filepath to script not allowed to contain spaces");
#ifdef _WIN32
std::string command =
String::Serialize("\"C:/Program Files/Mono/bin/mcs\" {0} -target:library", filepath);
#else
std::string command = String::Serialize("mcs {0} -target:library", filepath);
#endif
// Compile the script
return system(command.c_str()) == 0;
}
void Script::MonoInit()
{
if (!s_MonoInitialized)
{
#ifdef _WIN32
mono_set_dirs("C:\\Program Files\\Mono\\lib", "C:\\Program Files\\Mono\\etc");
mono_config_parse(NULL);
#endif
s_MonoInitialized = true;
}
}
} // namespace At0::Ray::Mono
| 26.556818 | 88 | 0.708601 | CAt0mIcS |
dbfa42d8d9f64bb063ac1f7144888d06207464df | 730 | cpp | C++ | codeforces/1433/B.cpp | Mohammad-Elsharkawy/CompetitiveProgramming | 8d052465ff08cb36e66b7e6c6813090ac410bf1d | [
"MIT"
] | null | null | null | codeforces/1433/B.cpp | Mohammad-Elsharkawy/CompetitiveProgramming | 8d052465ff08cb36e66b7e6c6813090ac410bf1d | [
"MIT"
] | null | null | null | codeforces/1433/B.cpp | Mohammad-Elsharkawy/CompetitiveProgramming | 8d052465ff08cb36e66b7e6c6813090ac410bf1d | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=200005;
int arr[55];
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;cin>>t;
while(t--){
int n;
cin>>n;
int st=0,en=0;
for(int i=0;i<n;i++){cin>>arr[i];}
for (int i=0;i<n;i++) {
if (arr[i] == 1) {
st = i;
break;
}
}
for (int i=n-1;i>=0;i--){
if(arr[i]==1){
en=i;
break;
}}
int ans=0;
for(int i=st;i<=en;i++)
{
if(arr[i]==0) ans++;
}
cout<<ans<<endl;
}
return 0;
}
| 16.590909 | 39 | 0.367123 | Mohammad-Elsharkawy |
dbfd67a71e765c01d8c37f4754a1bcd787a6f1e3 | 3,956 | cpp | C++ | lib/commonAPI/coreapi/ext/platform/wm/src/NetworkDetect.cpp | hanazuki/rhodes | eff0e410361dba791853a235d58471ba9e25e2fc | [
"MIT"
] | 1 | 2015-11-06T00:31:36.000Z | 2015-11-06T00:31:36.000Z | lib/commonAPI/coreapi/ext/platform/wm/src/NetworkDetect.cpp | rajcybage/rhodes | 40e75776134b79ce269adc9e38ef99dafac42c0d | [
"MIT"
] | null | null | null | lib/commonAPI/coreapi/ext/platform/wm/src/NetworkDetect.cpp | rajcybage/rhodes | 40e75776134b79ce269adc9e38ef99dafac42c0d | [
"MIT"
] | null | null | null | #include "NetworkDetect.h"
INetworkDetection* NetworkDetectionFactory::createNetworkDetection() {
return new CNetworkDetection();
}
void CNetworkDetection::Cleanup()
{
stop(1000);
WSACleanup();
}
void CNetworkDetection::Startup()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
}
/**
* \author Darryn Campbell (DCC, JRQ768)
* \date August 2011 (Initial Creation)
*/
void CNetworkDetection::CheckConnectivity()
{
bool bConnectSuccessful = false;
struct addrinfo hints, *result = NULL, *ptr = NULL;
SOCKET sockfd = INVALID_SOCKET;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
char szPortAsString[5 + 1];
_itoa(m_iPort, szPortAsString, 10);
char* szHost = new char[m_szHost.length() + 1];
memset(szHost, 0, m_szHost.length() + 1);
strcpy(szHost, m_szHost.c_str());
int iResult = getaddrinfo(szHost, szPortAsString, &hints, &result);
if (iResult != 0)
{
// Log the Fact that we can't get the addr info
int iErr = WSAGetLastError();
m_szLastError = "Attempted to resolve hostname to connect to but did not succeed, return value (" + itos(iResult) +
"), last error (" + itos(iErr) + ")";
LOG(INFO) + m_szLastError;
}
else
{
ptr=result;
sockfd = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (sockfd == INVALID_SOCKET)
{
int iErr = WSAGetLastError();
m_szLastError = "Unable to create communications socket, last error was " + itos(iErr);
LOG(INFO) + m_szLastError;
}
else
{
// Make the Socket Non Blocking
u_long iNonBlock = 1;
int iNonBlockRes = ioctlsocket(sockfd, FIONBIO, &iNonBlock);
if (iNonBlockRes != NO_ERROR)
{
m_szLastError = "Error setting socket into Non Blocking mode";
LOG(INFO) + m_szLastError;
}
else
{
int iConnectSuccess = connect(sockfd, ptr->ai_addr, ptr->ai_addrlen);
//#if defined(OS_WINCE)
// if (iConnectSuccess == SOCKET_ERROR)
//#else
// Because Socket is non blocking we expect it to return SOCKET_ERROR
// and WSAGetLastError() would be WSAEWOULDBLOCK
if (!(iConnectSuccess == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK))
//#endif
{
m_szLastError = "Socket Operation unexpectedly blocked, are you connected to a PC?";
LOG(WARNING) + m_szLastError;
}
else
{
fd_set WriteFDs;
FD_ZERO(&WriteFDs);
FD_SET(sockfd, &WriteFDs);
int iSelectReturnVal = select(0, 0, &WriteFDs, 0, &m_connectionTimeout);
if (iSelectReturnVal > 0)
{
// We have a socket to connect to
bConnectSuccessful = true;
}
else if (iSelectReturnVal == 0)
{
m_szLastError = "Unable to connect to specified host " + m_szHost + " on port " + itos(m_iPort);
LOG(INFO) + m_szLastError;
}
else
{
// Some form of error occured
int iErr = WSAGetLastError();
m_szLastError = "Unable to connect to specified host, last error was " + itos(iErr);
LOG(INFO) + m_szLastError;
}
}
}
closesocket(sockfd);
sockfd = INVALID_SOCKET;
}
}
delete[] szHost;
if (result != 0)
{
freeaddrinfo(result);
}
if (bConnectSuccessful)
{
if (m_NetworkState != NETWORK_CONNECTED)
{
m_NetworkState = NETWORK_CONNECTED;
rho::Hashtable<rho::String, rho::String> detectedCallbackData;
detectedCallbackData.put("connectionInformation", "Connected");
detectedCallbackData.put("failureMessage", "Connected");
m_pDetectCallback.set(detectedCallbackData);
}
}
else
{
// We are not connected
if (m_NetworkState != NETWORK_DISCONNECTED)
{
m_NetworkState = NETWORK_DISCONNECTED;
rho::Hashtable<rho::String, rho::String> detectedCallbackData;
detectedCallbackData.put("connectionInformation", "Disconnected");
detectedCallbackData.put("failureMessage", m_szLastError);
m_pDetectCallback.set(detectedCallbackData);
}
}
}
| 27.859155 | 118 | 0.676188 | hanazuki |
dbfe04b57322672e3526d5f6ee42855fd256065c | 4,662 | cpp | C++ | Tests/L0MgrExecuteTest.cpp | intel-go/omniscidb | 86068a229beddf7b117febcacdbd6b60a0279282 | [
"Apache-2.0"
] | 2 | 2020-03-04T12:01:10.000Z | 2020-07-24T15:12:55.000Z | Tests/L0MgrExecuteTest.cpp | intel-go/omniscidb | 86068a229beddf7b117febcacdbd6b60a0279282 | [
"Apache-2.0"
] | 18 | 2019-11-20T11:11:19.000Z | 2020-08-27T13:21:12.000Z | Tests/L0MgrExecuteTest.cpp | intel-go/omniscidb | 86068a229beddf7b117febcacdbd6b60a0279282 | [
"Apache-2.0"
] | 1 | 2020-04-04T06:25:32.000Z | 2020-04-04T06:25:32.000Z | #include <gtest/gtest.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/raw_ostream.h>
#include <LLVMSPIRVLib/LLVMSPIRVLib.h>
#include <level_zero/ze_api.h>
#include "L0Mgr/L0Mgr.h"
#include "TestHelpers.h"
template <typename T, size_t N>
struct alignas(4096) AlignedArray {
T data[N];
};
class SPIRVExecuteTest : public ::testing::Test {
protected:
std::string generateSimpleSPIRV();
};
std::string SPIRVExecuteTest::generateSimpleSPIRV() {
using namespace llvm;
// See source at https://github.com/kurapov-peter/L0Snippets
LLVMContext ctx;
std::unique_ptr<Module> module = std::make_unique<Module>("code_generated", ctx);
module->setTargetTriple("spir-unknown-unknown");
IRBuilder<> builder(ctx);
std::vector<Type*> args{Type::getFloatPtrTy(ctx, 1), Type::getFloatPtrTy(ctx, 1)};
FunctionType* f_type = FunctionType::get(Type::getVoidTy(ctx), args, false);
Function* f = Function::Create(
f_type, GlobalValue::LinkageTypes::ExternalLinkage, "plus1", module.get());
f->setCallingConv(CallingConv::SPIR_KERNEL);
// get_global_id
FunctionType* ggi_type =
FunctionType::get(Type::getInt32Ty(ctx), {Type::getInt32Ty(ctx)}, false);
Function* get_global_idj = Function::Create(ggi_type,
GlobalValue::LinkageTypes::ExternalLinkage,
"_Z13get_global_idj",
module.get());
get_global_idj->setCallingConv(CallingConv::SPIR_FUNC);
BasicBlock* entry = BasicBlock::Create(ctx, "entry", f);
builder.SetInsertPoint(entry);
Constant* zero = ConstantInt::get(Type::getInt32Ty(ctx), 0);
Constant* onef = ConstantFP::get(ctx, APFloat(1.f));
Value* idx = builder.CreateCall(get_global_idj, zero, "idx");
auto argit = f->args().begin();
Value* firstElemSrc = builder.CreateGEP(f->args().begin(), idx, "src.idx");
Value* firstElemDst = builder.CreateGEP(++argit, idx, "dst.idx");
Value* ldSrc = builder.CreateLoad(Type::getFloatTy(ctx), firstElemSrc, "ld");
Value* result = builder.CreateFAdd(ldSrc, onef, "foo");
builder.CreateStore(result, firstElemDst);
builder.CreateRetVoid();
// set metadata -- pretend we're opencl (see
// https://github.com/KhronosGroup/SPIRV-LLVM-Translator/blob/master/docs/SPIRVRepresentationInLLVM.rst#spir-v-instructions-mapped-to-llvm-metadata)
Metadata* spirv_src_ops[] = {
ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(ctx), 3 /*OpenCL_C*/)),
ConstantAsMetadata::get(
ConstantInt::get(Type::getInt32Ty(ctx), 102000 /*OpenCL ver 1.2*/))};
NamedMDNode* spirv_src = module->getOrInsertNamedMetadata("spirv.Source");
spirv_src->addOperand(MDNode::get(ctx, spirv_src_ops));
module->print(errs(), nullptr);
SPIRV::TranslatorOpts opts;
opts.enableAllExtensions();
opts.setDesiredBIsRepresentation(SPIRV::BIsRepresentation::OpenCL12);
opts.setDebugInfoEIS(SPIRV::DebugInfoEIS::OpenCL_DebugInfo_100);
std::ostringstream ss;
std::string err;
auto success = writeSpirv(module.get(), opts, ss, err);
assert(success);
return ss.str();
}
TEST_F(SPIRVExecuteTest, TranslateSimpleWithL0Manager) {
auto mgr = std::make_shared<l0::L0Manager>();
auto driver = mgr->drivers()[0];
auto device = driver->devices()[0];
auto spv = generateSimpleSPIRV();
auto module = device->create_module((uint8_t*)spv.data(), spv.length());
auto command_queue = device->command_queue();
auto command_list = device->create_command_list();
constexpr int a_size = 32;
AlignedArray<float, a_size> a, b;
for (auto i = 0; i < a_size; ++i) {
a.data[i] = a_size - i;
b.data[i] = i;
}
const float copy_size = a_size * sizeof(float);
void* dA = l0::allocate_device_mem(copy_size, *device);
void* dB = l0::allocate_device_mem(copy_size, *device);
void* a_void = a.data;
void* b_void = b.data;
command_list->copy(dA, a_void, copy_size);
command_list->copy(dB, b_void, copy_size);
auto kernel = module->create_kernel("plus1", 1, 1, 1);
command_list->launch(*kernel, &dA, &dB);
command_list->copy(b_void, dB, copy_size);
command_list->submit(*command_queue);
for (int i = 0; i < a_size; ++i) {
std::cout << b.data[i] << " ";
}
std::cout << std::endl;
ASSERT_EQ(b.data[0], 33);
ASSERT_EQ(b.data[1], 1);
ASSERT_EQ(b.data[2], 2);
mgr->freeDeviceMem((int8_t*)dA);
mgr->freeDeviceMem((int8_t*)dB);
}
int main(int argc, char** argv) {
TestHelpers::init_logger_stderr_only(argc, argv);
testing::InitGoogleTest(&argc, argv);
int err = RUN_ALL_TESTS();
return err;
}
| 33.3 | 150 | 0.683398 | intel-go |
dbfe04cf1c58c348023fb999e085cafe93b144da | 1,805 | cpp | C++ | handout/Game/Source/SceneIntro.cpp | MHF13/VideoPlayer | 861790d7482bb32c36f8be77e4a57482cd3d207c | [
"MIT"
] | null | null | null | handout/Game/Source/SceneIntro.cpp | MHF13/VideoPlayer | 861790d7482bb32c36f8be77e4a57482cd3d207c | [
"MIT"
] | null | null | null | handout/Game/Source/SceneIntro.cpp | MHF13/VideoPlayer | 861790d7482bb32c36f8be77e4a57482cd3d207c | [
"MIT"
] | null | null | null | #include "App.h"
#include "Input.h"
#include "Textures.h"
#include "Audio.h"
#include "Render.h"
#include "Fonts.h"
#include "SceneIntro.h"
#include "SceneManager.h"
#include <SDL_mixer\include\SDL_mixer.h>
#include "Defs.h"
#include "Log.h"
SceneIntro::SceneIntro()
{
active = true;
name.Create("sceneIntro");
}
SceneIntro::~SceneIntro()
{
}
bool SceneIntro::Awake()
{
LOG("Loading Scene");
bool ret = true;
return ret;
}
bool SceneIntro::Start()
{
fullScreen = false;
app->SetLastScene((Module*)this);
transition = false;
app->render->camera.x = app->render->camera.y = 0;
posX = 100, posY = 100;
padding = 50;
return true;
}
bool SceneIntro::PreUpdate()
{
return true;
}
bool SceneIntro::Update(float dt)
{
bool ret = true;
if (app->input->GetKey(SDL_SCANCODE_1) == KEY_DOWN) {
TransitionToScene(SceneType::LEVEL1);
}
if (app->input->GetKey(SDL_SCANCODE_2) == KEY_DOWN) {
fullScreen = !fullScreen;
app->fullScreen = fullScreen;
app->win->FullScreen(app->fullScreen);
app->render->FullScreen();
}
if (app->input->GetKey(SDL_SCANCODE_3) == KEY_DOWN) {
return false;
}
return ret;
}
bool SceneIntro::PostUpdate()
{
bool ret = true;
for (int i = 0; i < 3; i++) {
switch (i)
{
case 0:
sprintf_s(Text, 20, "Play Video: 1");
break;
case 1:
sprintf_s(Text, 20, "Full Screen: 2");
break;
case 2:
sprintf_s(Text, 20, "Exit: 3");
break;
default:
break;
}
app->fonts->BlitText(posX, posY + (padding * i), 0, Text, { 255, 255, 255 });
}
return ret;
}
bool SceneIntro::CleanUp()
{
if (!active)
return true;
LOG("Freeing scene");
active = false;
return true;
}
bool SceneIntro::LoadState(pugi::xml_node& data)
{
return true;
}
bool SceneIntro::SaveState(pugi::xml_node& data) const
{
return true;
}
| 13.884615 | 79 | 0.645429 | MHF13 |
e000e988ce3722403b6fc67add980d8361d4bb25 | 1,393 | hpp | C++ | engine/include/ph/util/GltfWriter.hpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | engine/include/ph/util/GltfWriter.hpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | engine/include/ph/util/GltfWriter.hpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | // Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se)
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#pragma once
namespace ph {
/*
The glTF writer is temporarily broken as the way resources are handled by Phantasy Engine has
changed. It should not be too much trouble to fix, but it was not high priority as these changes
were made.
// Writes all the assets corresponding to the meshes specified to glTF.
bool writeAssetsToGltf(
const char* writePath,
const LevelAssets& assets,
const DynArray<uint32_t>& meshIndices) noexcept;
*/
} // namespace ph
| 36.657895 | 96 | 0.758794 | PetorSFZ |
e0080f612766902e08e8491f1d6c6475d041bd54 | 191 | cpp | C++ | Codeforces/Write.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 1 | 2018-08-28T19:58:40.000Z | 2018-08-28T19:58:40.000Z | Codeforces/Write.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 2 | 2017-04-16T00:48:05.000Z | 2017-08-03T20:12:26.000Z | Codeforces/Write.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 4 | 2016-03-04T19:42:00.000Z | 2018-01-08T11:42:00.000Z | #include <stdio.h>
int main() {
freopen("i.in", "w", stdout);
printf("%d\n", 200000);
for(int i = 1; i <= 20000; i++) {
printf("%d ", i);
}
return 0;
}
| 17.363636 | 38 | 0.424084 | aajjbb |
e0088941fbfffd55079b88cf6b541ff017203d01 | 3,635 | cc | C++ | src/network/client_handler.cc | zzunny97/Graduate-Velox | d820e7c8cee52f22d7cd9027623bd82ca59733ca | [
"Apache-2.0"
] | 17 | 2016-11-27T13:13:40.000Z | 2021-09-07T06:42:25.000Z | src/network/client_handler.cc | zzunny97/Graduate-Velox | d820e7c8cee52f22d7cd9027623bd82ca59733ca | [
"Apache-2.0"
] | 22 | 2017-01-18T06:10:18.000Z | 2019-05-15T03:49:19.000Z | src/network/client_handler.cc | zzunny97/Graduate-Velox | d820e7c8cee52f22d7cd9027623bd82ca59733ca | [
"Apache-2.0"
] | 5 | 2017-07-24T15:19:32.000Z | 2022-02-19T09:11:01.000Z | #include "client_handler.hh"
#include "../messages/factory.hh"
#include "../common/context_singleton.hh"
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/spawn.hpp>
#include <exception>
#include <boost/scoped_ptr.hpp>
using namespace eclipse::network;
using namespace std;
using boost::scoped_ptr;
using boost::asio::ip::tcp;
using vec_str = std::vector<std::string>;
// Constructor {{{
ClientHandler::ClientHandler (uint32_t p):
nodes(context.settings.get<vec_str> ("network.nodes")),
port(p),
id(context.id)
{
}
void ClientHandler::attach(NetObserver* n) {
local_router = n;
}
// }}}
// connect {{{
void ClientHandler::connect(uint32_t i, shared_ptr<Server> server) {
spawn(context.io, [this, index = i, server_copy=server, node=nodes[i]]
(boost::asio::yield_context yield) {
try {
shared_ptr<Server> s = server_copy;
boost::system::error_code ec;
tcp::resolver resolver (context.io);
tcp::resolver::query query (node, to_string(port));
auto it = resolver.async_resolve(query, yield[ec]);
if (ec)
BOOST_THROW_EXCEPTION(std::runtime_error("Resolving"));
tcp::endpoint ep (*it);
s->get_socket().async_connect(ep, yield[ec]);
while (ec == boost::asio::error::timed_out) {
s->get_socket().close();
WARN("Re-connecting to %s:%u", node.c_str(), port);
s->get_socket().async_connect(ep, yield[ec]);
}
if (ec)
BOOST_THROW_EXCEPTION(std::runtime_error("Connecting"));
tcp::no_delay option(true);
s->get_socket().set_option(option);
rw_lock.lock();
current_servers.insert({index, s});
rw_lock.unlock();
s->do_write_buffer();
} catch (exception& e) {
ERROR("Connect coroutine exception %s", e.what());
throw;
} catch (boost::exception& e) {
ERROR("Connect corourine exception %s", diagnostic_information(e).c_str());
throw;
}
});
}
// }}}
// try_reuse_client {{{
bool ClientHandler::try_reuse_client(uint32_t i, shared_ptr<std::string> str) {
// If connection is still on.
rw_lock.lock_shared();
auto it = current_servers.find(i);
rw_lock.unlock_shared();
if (it != current_servers.end()) {
shared_ptr<Server> ptr = current_servers[i].lock();
if (ptr) {
DEBUG("REUSING SOCKET");
ptr->do_write(str);
return true;
} else {
rw_lock.lock();
current_servers.erase(i);
rw_lock.unlock();
}
}
return false;
}
// }}}
// send {{{
bool ClientHandler::send(uint32_t i, messages::Message* m) {
if (i >= nodes.size()) return false;
shared_ptr<std::string> message_serialized (save_message(m));
if (!try_reuse_client(i, message_serialized)) {
auto server = make_shared<Server>(local_router);
server->commit(message_serialized);
connect(i, server);
}
return true;
}
// }}}
// send str{{{
bool ClientHandler::send(uint32_t i, shared_ptr<string> str) {
if (i >= nodes.size()) return false;
if (!try_reuse_client(i, str)) {
auto server = make_shared<Server>(local_router);
server->commit(str);
connect(i, server);
}
return true;
}
// }}}
// send_and_replicate {{{
bool ClientHandler::send_and_replicate(std::vector<int> node_indices, messages::Message* m) {
shared_ptr<std::string> message_serialized (save_message(m));
for (auto i : node_indices) {
send(i, message_serialized);
}
return true;
}
// }}}
| 26.727941 | 93 | 0.625585 | zzunny97 |
e008b58e2dff76f4f02393c22eeb36519dc3929e | 1,952 | cpp | C++ | opencl/source/kernel/image_transformer.cpp | lukaszgotszaldintel/compute-runtime | 9b12dc43904806db07616ffb8b1c4495aa7d610f | [
"MIT"
] | 1 | 2019-03-01T13:54:45.000Z | 2019-03-01T13:54:45.000Z | opencl/source/kernel/image_transformer.cpp | lukaszgotszaldintel/compute-runtime | 9b12dc43904806db07616ffb8b1c4495aa7d610f | [
"MIT"
] | 5 | 2019-03-26T17:26:07.000Z | 2021-03-30T12:17:10.000Z | opencl/source/kernel/image_transformer.cpp | lukaszgotszaldintel/compute-runtime | 9b12dc43904806db07616ffb8b1c4495aa7d610f | [
"MIT"
] | 4 | 2018-05-09T10:04:27.000Z | 2018-07-12T13:33:31.000Z | /*
* Copyright (C) 2018-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "opencl/source/kernel/image_transformer.h"
#include "shared/source/helpers/ptr_math.h"
#include "opencl/source/mem_obj/image.h"
#include "opencl/source/program/kernel_info.h"
namespace NEO {
void ImageTransformer::registerImage3d(uint32_t argIndex) {
if (std::find(argIndexes.begin(), argIndexes.end(), argIndex) == argIndexes.end()) {
argIndexes.push_back(argIndex);
}
}
void ImageTransformer::transformImagesTo2dArray(const KernelInfo &kernelInfo, const std::vector<Kernel::SimpleKernelArgInfo> &kernelArguments, void *ssh) {
for (auto const &argIndex : argIndexes) {
const auto &arg = kernelInfo.kernelDescriptor.payloadMappings.explicitArgs[argIndex];
if (arg.getExtendedTypeInfo().isTransformable) {
auto clMemObj = static_cast<cl_mem>(kernelArguments.at(argIndex).object);
auto image = castToObjectOrAbort<Image>(clMemObj);
auto surfaceState = ptrOffset(ssh, arg.as<ArgDescImage>().bindful);
image->transformImage3dTo2dArray(surfaceState);
}
}
transformed = true;
}
void ImageTransformer::transformImagesTo3d(const KernelInfo &kernelInfo, const std::vector<Kernel::SimpleKernelArgInfo> &kernelArguments, void *ssh) {
for (auto const &argIndex : argIndexes) {
const auto &arg = kernelInfo.kernelDescriptor.payloadMappings.explicitArgs[argIndex];
auto clMemObj = static_cast<cl_mem>(kernelArguments.at(argIndex).object);
auto image = castToObjectOrAbort<Image>(clMemObj);
auto surfaceState = ptrOffset(ssh, arg.as<ArgDescImage>().bindful);
image->transformImage2dArrayTo3d(surfaceState);
}
transformed = false;
}
bool ImageTransformer::didTransform() const {
return transformed;
}
bool ImageTransformer::hasRegisteredImages3d() const {
return !argIndexes.empty();
}
} // namespace NEO
| 39.04 | 155 | 0.721311 | lukaszgotszaldintel |
e009d19d55138021b147a48ad8b257c77d85b3b4 | 602 | hpp | C++ | smart_tales_ii/game/ui/scorebubble.hpp | TijmenUU/smarttalesii | c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba | [
"CC-BY-3.0",
"CC-BY-4.0"
] | null | null | null | smart_tales_ii/game/ui/scorebubble.hpp | TijmenUU/smarttalesii | c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba | [
"CC-BY-3.0",
"CC-BY-4.0"
] | 11 | 2018-02-08T14:50:16.000Z | 2022-01-21T19:54:24.000Z | smart_tales_ii/game/ui/scorebubble.hpp | TijmenUU/smarttalesii | c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba | [
"CC-BY-3.0",
"CC-BY-4.0"
] | null | null | null | /*
scorebubble.hpp
This class is nothing more than a number floating upwards.
It has a lifetime and velocity defined in its cpp file.
*/
#pragma once
#include <SFML/Graphics.hpp>
#include <string>
class ScoreBubble : public sf::Drawable
{
private:
sf::Text text;
float timeAlive = 0.f; // in seconds
protected:
void draw(sf::RenderTarget & target, sf::RenderStates states) const override;
public:
bool ShouldRemove() const;
// Return value indicates it is to be removed
bool Update(const sf::Time & elapsed);
ScoreBubble(const sf::Vector2f spawnPosition, const unsigned int score);
}; | 20.758621 | 78 | 0.739203 | TijmenUU |
e00aa79854d72fc0c9d2e918db9f38ff06131034 | 1,209 | cpp | C++ | recordMagData.cpp | chuanstudyup/MPU9250 | aa41c58e8100b56bdcb1261d9617552378417257 | [
"Apache-2.0"
] | 5 | 2021-09-15T09:10:08.000Z | 2022-02-09T11:44:14.000Z | recordMagData.cpp | chuanstudyup/MPU9250 | aa41c58e8100b56bdcb1261d9617552378417257 | [
"Apache-2.0"
] | null | null | null | recordMagData.cpp | chuanstudyup/MPU9250 | aa41c58e8100b56bdcb1261d9617552378417257 | [
"Apache-2.0"
] | 4 | 2021-09-15T09:10:44.000Z | 2022-02-09T11:44:17.000Z | #include "MPU9250.h"
#include <fstream>
using namespace std;
int main()
{
MPU9250 mpu;
bcm2835_init();
mpu.verbose(true);
if(!mpu.setup(0x68))
{
while(1){
printf("MPU connection failed.\n");
delay(5000);
}
}else
printf("MPU setup successfully!\n");
mpu.initRecordCalData(); //记录用来校准的原始数据时,先把校准参数都设置为0或1
delay(5000);
mpu.calibrateAccelGyro(); //粗校准:静置,自动校准acc和gyro的偏移量,然后写入到器件中
mpu.print_calibration();
printf("MagBias: %f, %f, %f\n",mpu.getMagBiasX(),mpu.getMagBiasY(),mpu.getMagBiasZ());
printf("MagScale: %f, %f, %f\n",mpu.getMagScaleX(),mpu.getMagScaleY(),mpu.getMagScaleZ());
delay(3000);
//以下开始记录精校准用的原始数据,
ofstream magFile;
magFile.open("magData.csv",ios::app|ios::out);
float startTime = millis()/1000.f;
while(1)
{
if(mpu.update()){
float now = millis()/1000.f-startTime;
float magx = mpu.getMagX();
float magy = mpu.getMagY();
float magz = mpu.getMagZ();
printf("time=%f, magx=%f, magy=%f, magz=%f\n",
now,magx,magy,magz);
magFile <<now<<","<<magx<<","<<magy<<","<<magz<<endl;
delay(8);
}else{
printf("mpu.update failed\n");
}
}
magFile.close();
return 0;
}
// g++ -o recordMagData recordMagData.cpp ArduTime.cpp -l bcm2835
| 24.673469 | 91 | 0.652605 | chuanstudyup |
e00b8a19609f85c72c7ff49f7a115ce31e908494 | 8,416 | cpp | C++ | test/stdgpu/iterator.cpp | ykkawana/stdgpu | 43442090de76d09626bee542edfe11a5d71390de | [
"Apache-2.0"
] | 1 | 2022-02-10T09:16:27.000Z | 2022-02-10T09:16:27.000Z | test/stdgpu/iterator.cpp | ykkawana/stdgpu | 43442090de76d09626bee542edfe11a5d71390de | [
"Apache-2.0"
] | null | null | null | test/stdgpu/iterator.cpp | ykkawana/stdgpu | 43442090de76d09626bee542edfe11a5d71390de | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 Patrick Stotko
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <vector>
#include <thrust/copy.h>
#include <thrust/sequence.h>
#include <thrust/sort.h>
#include <stdgpu/iterator.h>
#include <stdgpu/memory.h>
class stdgpu_iterator : public ::testing::Test
{
protected:
// Called before each test
virtual void SetUp()
{
}
// Called after each test
virtual void TearDown()
{
}
};
TEST_F(stdgpu_iterator, size_device_void)
{
int* array = createDeviceArray<int>(42);
EXPECT_EQ(stdgpu::size((void*)array), 42 * sizeof(int));
destroyDeviceArray<int>(array);
}
TEST_F(stdgpu_iterator, size_host_void)
{
int* array_result = createHostArray<int>(42);
EXPECT_EQ(stdgpu::size((void*)array_result), 42 * sizeof(int));
destroyHostArray<int>(array_result);
}
TEST_F(stdgpu_iterator, size_nullptr_void)
{
EXPECT_EQ(stdgpu::size((void*)nullptr), static_cast<size_t>(0));
}
TEST_F(stdgpu_iterator, size_device)
{
int* array = createDeviceArray<int>(42);
EXPECT_EQ(stdgpu::size(array), static_cast<size_t>(42));
destroyDeviceArray<int>(array);
}
TEST_F(stdgpu_iterator, size_host)
{
int* array_result = createHostArray<int>(42);
EXPECT_EQ(stdgpu::size(array_result), static_cast<size_t>(42));
destroyHostArray<int>(array_result);
}
TEST_F(stdgpu_iterator, size_nullptr)
{
EXPECT_EQ(stdgpu::size((int*)nullptr), static_cast<size_t>(0));
}
TEST_F(stdgpu_iterator, size_device_shifted)
{
int* array = createDeviceArray<int>(42);
EXPECT_EQ(stdgpu::size(array + 24), static_cast<size_t>(0));
destroyDeviceArray<int>(array);
}
TEST_F(stdgpu_iterator, size_host_shifted)
{
int* array_result = createHostArray<int>(42);
EXPECT_EQ(stdgpu::size(array_result + 24), static_cast<size_t>(0));
destroyHostArray<int>(array_result);
}
TEST_F(stdgpu_iterator, size_device_wrong_alignment)
{
int* array = createDeviceArray<int>(1);
EXPECT_EQ(stdgpu::size(reinterpret_cast<size_t*>(array)), static_cast<size_t>(0));
destroyDeviceArray<int>(array);
}
TEST_F(stdgpu_iterator, size_host_wrong_alignment)
{
int* array_result = createHostArray<int>(1);
EXPECT_EQ(stdgpu::size(reinterpret_cast<size_t*>(array_result)), static_cast<size_t>(0));
destroyHostArray<int>(array_result);
}
TEST_F(stdgpu_iterator, device_begin_end)
{
int* array = createDeviceArray<int>(42);
int* array_begin = stdgpu::device_begin(array).get();
int* array_end = stdgpu::device_end( array).get();
EXPECT_EQ(array_begin, array);
EXPECT_EQ(array_end, array + 42);
destroyDeviceArray<int>(array);
}
TEST_F(stdgpu_iterator, host_begin_end)
{
int* array_result = createHostArray<int>(42);
int* array_result_begin = stdgpu::host_begin(array_result).get();
int* array_result_end = stdgpu::host_end( array_result).get();
EXPECT_EQ(array_result_begin, array_result);
EXPECT_EQ(array_result_end, array_result + 42);
destroyHostArray<int>(array_result);
}
TEST_F(stdgpu_iterator, device_begin_end_const)
{
int* array = createDeviceArray<int>(42);
const int* array_begin = stdgpu::device_begin(reinterpret_cast<const int*>(array)).get();
const int* array_end = stdgpu::device_end( reinterpret_cast<const int*>(array)).get();
EXPECT_EQ(array_begin, array);
EXPECT_EQ(array_end, array + 42);
destroyDeviceArray<int>(array);
}
TEST_F(stdgpu_iterator, host_begin_end_const)
{
int* array_result = createHostArray<int>(42);
const int* array_result_begin = stdgpu::host_begin(reinterpret_cast<const int*>(array_result)).get();
const int* array_result_end = stdgpu::host_end( reinterpret_cast<const int*>(array_result)).get();
EXPECT_EQ(array_result_begin, array_result);
EXPECT_EQ(array_result_end, array_result + 42);
destroyHostArray<int>(array_result);
}
TEST_F(stdgpu_iterator, device_cbegin_cend)
{
int* array = createDeviceArray<int>(42);
const int* array_begin = stdgpu::device_cbegin(array).get();
const int* array_end = stdgpu::device_cend( array).get();
EXPECT_EQ(array_begin, array);
EXPECT_EQ(array_end, array + 42);
destroyDeviceArray<int>(array);
}
TEST_F(stdgpu_iterator, host_cbegin_cend)
{
int* array_result = createHostArray<int>(42);
const int* array_result_begin = stdgpu::host_cbegin(array_result).get();
const int* array_result_end = stdgpu::host_cend( array_result).get();
EXPECT_EQ(array_result_begin, array_result);
EXPECT_EQ(array_result_end, array_result + 42);
destroyHostArray<int>(array_result);
}
struct back_insert_interface
{
using value_type = std::vector<int>::value_type;
back_insert_interface(std::vector<int>& vector)
: vector(vector)
{
}
void
push_back(const int x)
{
vector.push_back(x);
}
std::vector<int>& vector;
};
struct front_insert_interface
{
using value_type = std::vector<int>::value_type;
front_insert_interface(std::vector<int>& vector)
: vector(vector)
{
}
void
push_front(const int x)
{
vector.push_back(x);
}
std::vector<int>& vector;
};
struct insert_interface
{
using value_type = std::vector<int>::value_type;
insert_interface(std::vector<int>& vector)
: vector(vector)
{
}
void
insert(const int x)
{
vector.push_back(x);
}
std::vector<int>& vector;
};
TEST_F(stdgpu_iterator, back_inserter)
{
const stdgpu::index_t N = 100000;
int* array = createHostArray<int>(N);
std::vector<int> numbers;
thrust::sequence(stdgpu::host_begin(array), stdgpu::host_end(array),
1);
back_insert_interface ci(numbers);
thrust::copy(stdgpu::host_cbegin(array), stdgpu::host_cend(array),
stdgpu::back_inserter(ci));
int* array_result = copyCreateHost2HostArray<int>(numbers.data(), N, MemoryCopy::NO_CHECK);
thrust::sort(stdgpu::host_begin(array_result), stdgpu::host_end(array_result));
for (stdgpu::index_t i = 0; i < N; ++i)
{
EXPECT_EQ(array_result[i], i + 1);
}
destroyHostArray<int>(array_result);
destroyHostArray<int>(array);
}
TEST_F(stdgpu_iterator, front_inserter)
{
const stdgpu::index_t N = 100000;
int* array = createHostArray<int>(N);
std::vector<int> numbers;
thrust::sequence(stdgpu::host_begin(array), stdgpu::host_end(array),
1);
front_insert_interface ci(numbers);
thrust::copy(stdgpu::host_cbegin(array), stdgpu::host_cend(array),
stdgpu::front_inserter(ci));
int* array_result = copyCreateHost2HostArray<int>(numbers.data(), N, MemoryCopy::NO_CHECK);
thrust::sort(stdgpu::host_begin(array_result), stdgpu::host_end(array_result));
for (stdgpu::index_t i = 0; i < N; ++i)
{
EXPECT_EQ(array_result[i], i + 1);
}
destroyHostArray<int>(array_result);
destroyHostArray<int>(array);
}
TEST_F(stdgpu_iterator, inserter)
{
const stdgpu::index_t N = 100000;
int* array = createHostArray<int>(N);
std::vector<int> numbers;
thrust::sequence(stdgpu::host_begin(array), stdgpu::host_end(array),
1);
insert_interface ci(numbers);
thrust::copy(stdgpu::host_cbegin(array), stdgpu::host_cend(array),
stdgpu::inserter(ci));
int* array_result = copyCreateHost2HostArray<int>(numbers.data(), N, MemoryCopy::NO_CHECK);
thrust::sort(stdgpu::host_begin(array_result), stdgpu::host_end(array_result));
for (stdgpu::index_t i = 0; i < N; ++i)
{
EXPECT_EQ(array_result[i], i + 1);
}
destroyHostArray<int>(array_result);
destroyHostArray<int>(array);
}
| 22.994536 | 107 | 0.676925 | ykkawana |
e00c96ad564ea7fc974d666898080db71d109d7b | 2,890 | hpp | C++ | include/TE/DrawManager.hpp | bitDaft/grid-game-system | e11e45b6ed3ce12e04ebf76c93c3d8cc5335679e | [
"MIT"
] | 1 | 2020-06-24T16:16:49.000Z | 2020-06-24T16:16:49.000Z | include/DrawManager.hpp | bitDaft/Project-TE | f0e0ec184d42b46799d48d69eb4eb9d369cbfcc3 | [
"MIT"
] | null | null | null | include/DrawManager.hpp | bitDaft/Project-TE | f0e0ec184d42b46799d48d69eb4eb9d369cbfcc3 | [
"MIT"
] | null | null | null | /*
* File: DrawManager.hpp
* Project: Project-TE
* Created Date: Sunday December 1st 2019
* Author: bitDaft
* -----
* Last Modified: Saturday December 28th 2019 11:24:55 pm
* Modified By: bitDaft at <ajaxhis@tutanota.com>
* -----
* Copyright (c) 2019 bitDaft
*/
#ifndef DRAWMANAGER_HPP
#define DRAWMANAGER_HPP
#include <vector>
#include <SFML/System/Time.hpp>
#include <SFML/Graphics/RenderTexture.hpp>
#include "IDrawable.hpp"
/**
* This class manages the drawing queue and drawing of all the objects added to the queue
* ^ Manual initialization of this class is not needed as only one object of this class is needed
* ^ That object is created and managed by the Game class
* ^ Any functionality that needs to be given to drawables can be opened through the IDrawable interface
* TODO allow changing of queues of objects
*/
class DrawManager
{
public:
// constructor destructor
DrawManager();
virtual ~DrawManager();
/**
* Initializes the object to start the drawing pipeline
* @return void
*/
void initialize();
/**
* This runs through all the object queues and draws them to the RenderTexture
* @param dt the remaining delta time needed to calculate an interpolated state
* @param renderTexture a renderable texture to which the objects should be drawn to
* @return void
*/
void draw(const sf::Time &dt, sf::RenderTexture &renderTexture);
/**
* Prevents an object queue from drawing its objects
* @param queuePos the position of the queue which should not be drawn
* @return void
*/
void stopQueue(int queuePos);
/**
* Allows an object queue from drawing its objects
* @param queuePos the position of the queue which should be allowed to be drawn
* @return void
*/
void resumeQueue(int queuePos);
/**
* Pushes a pointer of an IDrawable object into an object queue
* @param queuePos the queue into which the IDrawable pointer is to be pushed into
* @param drawable the IDrawable that is be added to the drawing queue
* @return void
*/
int pushToQueue(int queuePos, IDrawable *drawable);
/**
* Removes a pointer of an IDrawable object from an object queue
* @param queuePos the queue from which the IDrawable pointer is to be removed
* @param objectPos the position of the object in the given queue
* @return void
*/
void removeFromQueue(int queuePos, int objectPos);
private:
/**
* Adds a new object queue
* @param count number of new queues to be added
* @return void
*/
void addQueue(int count);
/**
* Cleans up all deleted and removed objects from the drawing queue to free up space
* @param i the queue to cleanup
* @return void
*/
void cleanupQueue(int pos);
private:
std::vector<bool> drawCheck;
int queueCount;
bool setupDone;
std::vector<std::vector<IDrawable *>> drawList;
};
#endif | 28.058252 | 104 | 0.703806 | bitDaft |
e00f12eaa2adce906e4ec2538793ef56fed030f6 | 303 | cpp | C++ | Assignments/Data Structure/Lab6WordHub/NodeL.cpp | oliviapy960825/oliviapy960825.github.io | 7a07fd0887e5854b0b92e4cc8e20ff1fd2219fde | [
"CC-BY-3.0"
] | null | null | null | Assignments/Data Structure/Lab6WordHub/NodeL.cpp | oliviapy960825/oliviapy960825.github.io | 7a07fd0887e5854b0b92e4cc8e20ff1fd2219fde | [
"CC-BY-3.0"
] | null | null | null | Assignments/Data Structure/Lab6WordHub/NodeL.cpp | oliviapy960825/oliviapy960825.github.io | 7a07fd0887e5854b0b92e4cc8e20ff1fd2219fde | [
"CC-BY-3.0"
] | null | null | null | /*
* NodeL.cpp
*
* Created on: Oct 19, 2017
* Author: Debra
*/
#include "NodeL.hpp"
#include <string>
#include <iostream>
using namespace std;
NodeL::NodeL(string s) {
word = s;
next = NULL;
wscore = 0;
}
NodeL::~NodeL() {
cout << "Deleting " << word << endl;
}
| 13.173913 | 38 | 0.541254 | oliviapy960825 |
e01012d313a06a489d450610f0989ed5d010ee35 | 1,788 | cpp | C++ | Engine/Scene/Common/Mesh.cpp | vitei/Usa | c44f893d5b3d8080529ecf0e227f983fddb829d4 | [
"MIT"
] | 47 | 2018-04-27T02:16:26.000Z | 2022-02-28T05:21:24.000Z | Engine/Scene/Common/Mesh.cpp | vitei/Usa | c44f893d5b3d8080529ecf0e227f983fddb829d4 | [
"MIT"
] | 2 | 2018-11-13T18:46:41.000Z | 2022-03-12T00:04:44.000Z | Engine/Scene/Common/Mesh.cpp | vitei/Usa | c44f893d5b3d8080529ecf0e227f983fddb829d4 | [
"MIT"
] | 6 | 2019-08-10T21:56:23.000Z | 2020-10-21T11:18:29.000Z | /****************************************************************************
// Usagi Engine, Copyright © Vitei, Inc. 2013
****************************************************************************/
#include "Engine/Common/Common.h"
#include "Engine/Graphics/Device/GFXDevice.h"
#include "Engine/Scene/RenderGroup.h"
#include "Engine/PostFX/PostFXSys.h"
#include "Engine/Graphics/Device/GFXContext.h"
#include "Engine/Scene/Common/Mesh.h"
namespace usg {
Mesh::Mesh()
: RenderNode()
{
m_pszName = NULL;
m_uMaxCount = INT_MAX;
}
Mesh::~Mesh()
{
}
void Mesh::SetName(const char* pszName)
{
m_pszName = pszName;
}
bool Mesh::Draw(GFXContext* pContext, RenderContext& renderContext)
{
uint32 uIndexCount = m_indexBuffer.GetIndexCount() > m_uMaxCount ? m_uMaxCount : m_indexBuffer.GetIndexCount();
if(uIndexCount > 0)
{
const RenderGroup* pParent = GetParent();
//const ConstantSet* GetConstantSet();
if(m_pszName)
pContext->BeginGPUTag(m_pszName, Color::Blue);
// FIXME: This has been removed from the render nodes
#if 0
if(pParent->HasTransform())
{
// FIXME: Most things won't need the instance data in the GS
pContext->SetConstantBuffer( SHADER_CONSTANT_INSTANCE, pParent->GetConstantSet(), SHADER_FLAG_VS_GS );
}
#endif
pContext->SetPipelineState(m_pipeline);
if (m_descriptors.GetValid())
{
pContext->SetDescriptorSet(&m_descriptors, 1);
}
pContext->SetVertexBuffer(&m_vertexBuffer);
pContext->DrawIndexedEx(&m_indexBuffer, 0, uIndexCount);
if(m_pszName)
pContext->EndGPUTag();
return true;
}
return false;
}
void Mesh::RenderPassChanged(GFXDevice* pDevice, uint32 uContextId, const RenderPassHndl &renderPass, const SceneRenderPasses& passes)
{
pDevice->ChangePipelineStateRenderPass(renderPass, m_pipeline);
}
}
| 23.84 | 134 | 0.675056 | vitei |
e01452e80d56f1ddb33ff3686662b65255315ca6 | 2,292 | cpp | C++ | mmcv/ops/csrc/parrots/masked_conv2d_parrots.cpp | Alsasolo/mmcv | 6dfc9312fa872c7fd63a5e6971e9ecca8e3d4ef1 | [
"Apache-2.0"
] | 3 | 2022-03-09T13:15:15.000Z | 2022-03-21T06:59:10.000Z | mmcv/ops/csrc/parrots/masked_conv2d_parrots.cpp | Alsasolo/mmcv | 6dfc9312fa872c7fd63a5e6971e9ecca8e3d4ef1 | [
"Apache-2.0"
] | 10 | 2020-10-15T19:31:38.000Z | 2021-03-21T16:16:28.000Z | mmcv/ops/csrc/parrots/masked_conv2d_parrots.cpp | Alsasolo/mmcv | 6dfc9312fa872c7fd63a5e6971e9ecca8e3d4ef1 | [
"Apache-2.0"
] | 1 | 2019-12-14T12:12:48.000Z | 2019-12-14T12:12:48.000Z | #include <parrots/compute/aten.hpp>
#include <parrots/extension.hpp>
#include <parrots/foundation/ssattrs.hpp>
#include "masked_conv2d_pytorch.h"
using namespace parrots;
void masked_im2col_forward_cuda_parrots(CudaContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
// im: (n, ic, h, w), kernel size (kh, kw)
// kernel: (oc, ic * kh * kw), col: (kh * kw * ic, ow * oh)
int kernel_h, kernel_w, pad_h, pad_w;
SSAttrs(attr)
.get<int>("kernel_h", kernel_h)
.get<int>("kernel_w", kernel_w)
.get<int>("pad_h", pad_h)
.get<int>("pad_w", pad_w)
.done();
const auto& im = buildATensor(ctx, ins[0]);
const auto& mask_h_idx = buildATensor(ctx, ins[1]);
const auto& mask_w_idx = buildATensor(ctx, ins[2]);
auto col = buildATensor(ctx, outs[0]);
masked_im2col_forward_cuda(im, mask_h_idx, mask_w_idx, col, kernel_h,
kernel_w, pad_h, pad_w);
}
void masked_col2im_forward_cuda_parrots(CudaContext& ctx, const SSElement& attr,
const OperatorBase::in_list_t& ins,
OperatorBase::out_list_t& outs) {
// im: (n, ic, h, w), kernel size (kh, kw)
// kernel: (oc, ic * kh * kh), col: (kh * kw * ic, ow * oh)
int height, width, channels;
SSAttrs(attr)
.get<int>("height", height)
.get<int>("width", width)
.get<int>("channels", channels)
.done();
const auto& col = buildATensor(ctx, ins[0]);
const auto& mask_h_idx = buildATensor(ctx, ins[1]);
const auto& mask_w_idx = buildATensor(ctx, ins[2]);
auto im = buildATensor(ctx, outs[0]);
masked_col2im_forward_cuda(col, mask_h_idx, mask_w_idx, im, height, width,
channels);
}
PARROTS_EXTENSION_REGISTER(masked_im2col_forward)
.attr("kernel_h")
.attr("kernel_w")
.attr("pad_h")
.attr("pad_w")
.input(3)
.output(1)
.apply(masked_im2col_forward_cuda_parrots)
.done();
PARROTS_EXTENSION_REGISTER(masked_col2im_forward)
.attr("height")
.attr("width")
.attr("channels")
.input(3)
.output(1)
.apply(masked_col2im_forward_cuda_parrots)
.done();
| 32.742857 | 80 | 0.606021 | Alsasolo |
e01558fdf7f7980279a601b4408f553664c36967 | 9,513 | cpp | C++ | engine/src/communication/messages/GPUComponentMessage.cpp | dsusanibarblazing/blazingsql | 8b27fc36cb982b8e2df1acec66a40ff00e79b252 | [
"Apache-2.0"
] | null | null | null | engine/src/communication/messages/GPUComponentMessage.cpp | dsusanibarblazing/blazingsql | 8b27fc36cb982b8e2df1acec66a40ff00e79b252 | [
"Apache-2.0"
] | null | null | null | engine/src/communication/messages/GPUComponentMessage.cpp | dsusanibarblazing/blazingsql | 8b27fc36cb982b8e2df1acec66a40ff00e79b252 | [
"Apache-2.0"
] | null | null | null | #include "GPUComponentMessage.h"
using namespace fmt::literals;
namespace ral {
namespace communication {
namespace messages {
gpu_raw_buffer_container serialize_gpu_message_to_gpu_containers(ral::frame::BlazingTableView table_view){
std::vector<std::size_t> buffer_sizes;
std::vector<const char *> raw_buffers;
std::vector<ColumnTransport> column_offset;
std::vector<std::unique_ptr<rmm::device_buffer>> temp_scope_holder;
for(int i = 0; i < table_view.num_columns(); ++i) {
const cudf::column_view&column = table_view.column(i);
ColumnTransport col_transport = ColumnTransport{ColumnTransport::MetaData{
.dtype = (int32_t)column.type().id(),
.size = column.size(),
.null_count = column.null_count(),
.col_name = {},
},
.data = -1,
.valid = -1,
.strings_data = -1,
.strings_offsets = -1,
.strings_nullmask = -1,
.strings_data_size = 0,
.strings_offsets_size = 0,
.size_in_bytes = 0};
strcpy(col_transport.metadata.col_name, table_view.names().at(i).c_str());
if (column.size() == 0) {
// do nothing
} else if(column.type().id() == cudf::type_id::STRING) {
cudf::strings_column_view str_col_view{column};
auto offsets_column = str_col_view.offsets();
auto chars_column = str_col_view.chars();
if (str_col_view.size() + 1 == offsets_column.size()){
// this column does not come from a buffer than had been zero-copy partitioned
col_transport.strings_data = raw_buffers.size();
buffer_sizes.push_back(chars_column.size());
col_transport.size_in_bytes += chars_column.size();
raw_buffers.push_back(chars_column.head<char>());
col_transport.strings_data_size = chars_column.size();
col_transport.strings_offsets = raw_buffers.size();
col_transport.strings_offsets_size = offsets_column.size() * sizeof(int32_t);
buffer_sizes.push_back(col_transport.strings_offsets_size);
col_transport.size_in_bytes += col_transport.strings_offsets_size;
raw_buffers.push_back(offsets_column.head<char>());
if(str_col_view.has_nulls()) {
col_transport.strings_nullmask = raw_buffers.size();
buffer_sizes.push_back(cudf::bitmask_allocation_size_bytes(str_col_view.size()));
col_transport.size_in_bytes += cudf::bitmask_allocation_size_bytes(str_col_view.size());
raw_buffers.push_back((const char *)str_col_view.null_mask());
}
} else {
// this column comes from a column that was zero-copy partitioned
std::pair<int32_t, int32_t> char_col_start_end = getCharsColumnStartAndEnd(str_col_view);
std::unique_ptr<CudfColumn> new_offsets = getRebasedStringOffsets(str_col_view, char_col_start_end.first);
col_transport.strings_data = raw_buffers.size();
col_transport.strings_data_size = char_col_start_end.second - char_col_start_end.first;
buffer_sizes.push_back(col_transport.strings_data_size);
col_transport.size_in_bytes += col_transport.strings_data_size;
raw_buffers.push_back(chars_column.head<char>() + char_col_start_end.first);
col_transport.strings_offsets = raw_buffers.size();
col_transport.strings_offsets_size = new_offsets->size() * sizeof(int32_t);
buffer_sizes.push_back(col_transport.strings_offsets_size);
col_transport.size_in_bytes += col_transport.strings_offsets_size;
raw_buffers.push_back(new_offsets->view().head<char>());
cudf::column::contents new_offsets_contents = new_offsets->release();
temp_scope_holder.emplace_back(std::move(new_offsets_contents.data));
if(str_col_view.has_nulls()) {
col_transport.strings_nullmask = raw_buffers.size();
buffer_sizes.push_back(cudf::bitmask_allocation_size_bytes(str_col_view.size()));
col_transport.size_in_bytes += cudf::bitmask_allocation_size_bytes(str_col_view.size());
temp_scope_holder.emplace_back(std::make_unique<rmm::device_buffer>(
cudf::copy_bitmask(str_col_view.null_mask(), str_col_view.offset(), str_col_view.offset() + str_col_view.size())));
raw_buffers.push_back((const char *)temp_scope_holder.back()->data());
}
}
} else {
col_transport.data = raw_buffers.size();
buffer_sizes.push_back((std::size_t) column.size() * cudf::size_of(column.type()));
col_transport.size_in_bytes += (std::size_t) column.size() * cudf::size_of(column.type());
raw_buffers.push_back(column.head<char>() + column.offset() * cudf::size_of(column.type())); // here we are getting the beginning of the buffer and manually calculating the offset.
if(column.has_nulls()) {
col_transport.valid = raw_buffers.size();
buffer_sizes.push_back(cudf::bitmask_allocation_size_bytes(column.size()));
col_transport.size_in_bytes += cudf::bitmask_allocation_size_bytes(column.size());
if (column.offset() == 0){
raw_buffers.push_back((const char *)column.null_mask());
} else {
temp_scope_holder.emplace_back(std::make_unique<rmm::device_buffer>(
cudf::copy_bitmask(column)));
raw_buffers.push_back((const char *)temp_scope_holder.back()->data());
}
}
}
column_offset.push_back(col_transport);
}
return std::make_tuple(buffer_sizes, raw_buffers, column_offset, std::move(temp_scope_holder));
}
std::unique_ptr<ral::frame::BlazingHostTable> serialize_gpu_message_to_host_table(ral::frame::BlazingTableView table_view, bool use_pinned) {
std::vector<std::size_t> buffer_sizes;
std::vector<const char *> raw_buffers;
std::vector<ColumnTransport> column_offset;
std::vector<std::unique_ptr<rmm::device_buffer>> temp_scope_holder;
std::tie(buffer_sizes, raw_buffers, column_offset, temp_scope_holder) = serialize_gpu_message_to_gpu_containers(table_view);
typedef std::pair< std::vector<ral::memory::blazing_chunked_column_info>, std::vector<std::unique_ptr<ral::memory::blazing_allocation_chunk> >> buffer_alloc_type;
buffer_alloc_type buffers_and_allocations = ral::memory::convert_gpu_buffers_to_chunks(buffer_sizes,use_pinned);
auto & allocations = buffers_and_allocations.second;
size_t buffer_index = 0;
for(auto & chunked_column_info : buffers_and_allocations.first){
size_t position = 0;
for(size_t i = 0; i < chunked_column_info.chunk_index.size(); i++){
size_t chunk_index = chunked_column_info.chunk_index[i];
size_t offset = chunked_column_info.offset[i];
size_t chunk_size = chunked_column_info.size[i];
cudaMemcpyAsync((void *) (allocations[chunk_index]->data + offset), raw_buffers[buffer_index] + position, chunk_size, cudaMemcpyDeviceToHost,0);
position += chunk_size;
}
buffer_index++;
}
cudaStreamSynchronize(0);
auto table = std::make_unique<ral::frame::BlazingHostTable>(column_offset, std::move(buffers_and_allocations.first),std::move(buffers_and_allocations.second));
return table;
}
auto deserialize_from_gpu_raw_buffers(const std::vector<ColumnTransport> & columns_offsets,
const std::vector<rmm::device_buffer> & raw_buffers) {
auto num_columns = columns_offsets.size();
std::vector<std::unique_ptr<cudf::column>> received_samples(num_columns);
std::vector<std::string> column_names(num_columns);
assert(raw_buffers.size() >= 0);
for(size_t i = 0; i < num_columns; ++i) {
auto data_offset = columns_offsets[i].data;
auto string_offset = columns_offsets[i].strings_data;
if(string_offset != -1) {
cudf::size_type num_strings = columns_offsets[i].metadata.size;
std::unique_ptr<cudf::column> offsets_column
= std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::INT32}, num_strings + 1, std::move(raw_buffers[columns_offsets[i].strings_offsets]));
cudf::size_type total_bytes = columns_offsets[i].strings_data_size;
std::unique_ptr<cudf::column> chars_column = std::make_unique<cudf::column>(cudf::data_type{cudf::type_id::INT8}, total_bytes, std::move(raw_buffers[columns_offsets[i].strings_data]));
rmm::device_buffer null_mask;
if (columns_offsets[i].strings_nullmask != -1)
null_mask = rmm::device_buffer(std::move(raw_buffers[columns_offsets[i].strings_nullmask]));
cudf::size_type null_count = columns_offsets[i].metadata.null_count;
auto unique_column = cudf::make_strings_column(num_strings, std::move(offsets_column), std::move(chars_column), null_count, std::move(null_mask));
received_samples[i] = std::move(unique_column);
} else {
cudf::data_type dtype = cudf::data_type{cudf::type_id(columns_offsets[i].metadata.dtype)};
cudf::size_type column_size = (cudf::size_type)columns_offsets[i].metadata.size;
if(columns_offsets[i].valid != -1) {
// this is a valid
auto valid_offset = columns_offsets[i].valid;
auto unique_column = std::make_unique<cudf::column>(dtype, column_size, std::move(raw_buffers[data_offset]), std::move(raw_buffers[valid_offset]));
received_samples[i] = std::move(unique_column);
} else if (data_offset != -1){
auto unique_column = std::make_unique<cudf::column>(dtype, column_size, std::move(raw_buffers[data_offset]));
received_samples[i] = std::move(unique_column);
} else {
auto unique_column = cudf::make_empty_column(dtype);
received_samples[i] = std::move(unique_column);
}
}
column_names[i] = std::string{columns_offsets[i].metadata.col_name};
}
auto unique_table = std::make_unique<cudf::table>(std::move(received_samples));
return std::make_unique<ral::frame::BlazingTable>(std::move(unique_table), column_names);
}
} // namespace messages
} // namespace communication
} // namespace ral
| 46.632353 | 187 | 0.738253 | dsusanibarblazing |
e015da95851bf7c2cfc045b0baefd8d0ecb543a9 | 2,251 | cpp | C++ | source/basic/ref_ptr.cpp | JianboYan/cppthings-learning | 71c15213474786795fb09800efd3cf19ee562681 | [
"MIT"
] | null | null | null | source/basic/ref_ptr.cpp | JianboYan/cppthings-learning | 71c15213474786795fb09800efd3cf19ee562681 | [
"MIT"
] | null | null | null | source/basic/ref_ptr.cpp | JianboYan/cppthings-learning | 71c15213474786795fb09800efd3cf19ee562681 | [
"MIT"
] | null | null | null | //
// ref_ptr.cpp
// CppThings
//
// Created by Ryan on 2020/10/2.
//
#include <iostream>
#include <vector>
namespace RefPtr{
using namespace std;
// 1. 指针与引用的区别
// 1.1. 定义初始化
// int &ri; // error: Declaration of reference variable 'ri' requires an initializer
int i;
int &ri = i; // 定义必须初始化
int *pi; // 定义可以不初始化
// 1.2. 指针可以为空,引用不可以
void test_p(int* p)
{
if(p != nullptr) //对p所指对象赋值时需先判断p是否为空指针
*p = 3;
return;
}
void test_r(int& r)
{
r = 3; //由于引用不能为空,所以此处无需判断r的有效性就可以对r直接赋值
return;
}
int MAIN(){
// 1.3. 引用不能更换目标
int num = 1, count = 2;
int &rn = num;
rn = count; // 并不是重新修改引用到count,只是修改num的值为count的值
CTLLOG_1(rn); // rn is 2
CTLLOG_1(num); // num is 2
rn = 3;
CTLLOG_1(count); // count is 2
CTLLOG_1(num); // num is 3
return 0;
}
// 2. 引用定义
int MAIN(){
// 2.1 左值引用: 常规引用,一般表示对象的身份
// 2.2 右值引用:就是必须绑定到右值(一个临时对象、将要销毁的对象)的引用,一般表示对象的值
// 2.2.1 右值引用可实现转移语义(Move Sementics)和精确传递(Perfect Forwarding)
// 2.2.2 右值引用可以消除两个对象交互时不必要的对象拷贝,节省运算存储资源,提高效率
// 2.2.3 右值引用能够更简洁明确地定义泛型函数
int num = 2;
// int &i = 1; // error: Non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'
int &i = num;
// int && ii = i; // error: Rvalue reference to type 'int' cannot bind to lvalue of type 'int'
int &&ii = 2;
ii = 3;
CTLLOG_1(ii);// ii is 3。❓:说好的引用不能转换目标呢?
// 2.3. 引用折叠
// 2.3.1 X& &、X& &&、X&& & 可折叠成 X&
// 2.3.2 X&& && 可折叠成 X&&
// int& &ri = i; // error: 'ri' declared as a reference to a reference
// TODO: 增加示例
return 0;
}
// 2.4. 引用参数
void test(const vector<int> &data)
{
}
int MAIN()
{
vector<int> data{1,2,3,4,5,6,7,8};
test(data);
// 2.5. 引用型返回值
vector<int> v(10);
v[5] = 10; //[]操作符返回引用,然后vector对应元素才能被修改
//如果[]操作符不返回引用而是指针的话,赋值语句则需要这样写
// *v[5] = 10; //这种书写方式,完全不符合我们对[]调用的认知,容易产生误解 error: Indirection requires pointer operand ('std::__1::__vector_base<int, std::__1::allocator<int> >::value_type' (aka 'int') invalid)
return 0;
}
// 3. 指针与引用的性能差距
// 结论:使用引用和指针生成的汇编代码完全一样,所以其实引用就是指针的一种简便使用,这点从debug状态下,引用的值为指向对象的地址就可以看出来
// 多说一句,空指针的发明是一个价值10亿美元的糟糕设计,引用算是对指针里会出现空指针的一种设计完善。
}
| 20.651376 | 187 | 0.59307 | JianboYan |
e015dc74a7cc9c7e0145aced78c8ebe431d54bc0 | 7,097 | cc | C++ | src/column/column.cc | marcinz/legate.pandas | 94c21c436f59c06cfba454c6569e9f5d7109d839 | [
"Apache-2.0"
] | 67 | 2021-04-12T18:06:55.000Z | 2022-03-28T06:51:05.000Z | src/column/column.cc | marcinz/legate.pandas | 94c21c436f59c06cfba454c6569e9f5d7109d839 | [
"Apache-2.0"
] | 2 | 2021-06-22T00:30:36.000Z | 2021-07-01T22:12:43.000Z | src/column/column.cc | marcinz/legate.pandas | 94c21c436f59c06cfba454c6569e9f5d7109d839 | [
"Apache-2.0"
] | 6 | 2021-04-14T21:28:00.000Z | 2022-03-22T09:45:25.000Z | /* Copyright 2021 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.
*
*/
#include "column/column.h"
#include "util/type_dispatch.h"
namespace legate {
namespace pandas {
void deserialize(Deserializer &ctx, OutputColumn &column)
{
deserialize(ctx, column.column_);
bool nullable = false;
deserialize(ctx, nullable);
if (nullable) {
column.bitmask_ = std::make_unique<typename decltype(column.bitmask_)::element_type>();
deserialize(ctx, *column.bitmask_);
}
uint32_t num_children;
deserialize(ctx, num_children);
column.children_.resize(num_children);
for (auto &child : column.children_) deserialize(ctx, child);
}
OutputColumn::OutputColumn(OutputColumn &&other) noexcept
: column_(std::move(other.column_)),
bitmask_(std::move(other.bitmask_)),
children_(std::move(other.children_)),
num_elements_(other.num_elements_)
{
}
OutputColumn &OutputColumn::operator=(OutputColumn &&other) noexcept
{
column_ = std::move(other.column_);
bitmask_ = std::move(other.bitmask_);
children_ = std::move(other.children_);
num_elements_ = other.num_elements_;
return *this;
}
void *OutputColumn::raw_column_untyped() const { return column_.untyped_ptr(); }
Bitmask OutputColumn::bitmask() const { return Bitmask(raw_bitmask(), num_elements()); }
std::shared_ptr<Bitmask> OutputColumn::maybe_bitmask() const
{
return nullptr == bitmask_ ? nullptr : std::make_shared<Bitmask>(raw_bitmask(), num_elements_);
}
Bitmask::AllocType *OutputColumn::raw_bitmask() const
{
#ifdef DEBUG_PANDAS
assert(nullable());
assert(valid());
#endif
return bitmask_->ptr<Bitmask::AllocType>();
}
size_t OutputColumn::elem_size() const { return size_of_type(code()); }
namespace detail {
struct FromScalar {
template <TypeCode CODE, std::enable_if_t<is_primitive_type<CODE>::value> * = nullptr>
void operator()(OutputColumn &out, const std::vector<Scalar> &scalars)
{
using VAL = pandas_type_of<CODE>;
out.allocate(scalars.size());
auto p_out = out.raw_column<VAL>();
auto p_out_b = out.raw_bitmask();
for (auto idx = 0; idx < scalars.size(); ++idx) {
auto value = scalars[idx].value<VAL>();
auto valid = scalars[idx].valid();
p_out[idx] = value;
p_out_b[idx] = valid;
}
}
template <TypeCode CODE, std::enable_if_t<CODE == TypeCode::STRING> * = nullptr>
void operator()(OutputColumn &out, const std::vector<Scalar> &scalars)
{
using VAL = pandas_type_of<CODE>;
out.allocate(scalars.size());
size_t num_chars = 0;
for (auto &scalar : scalars)
if (scalar.valid()) num_chars += scalar.value<std::string>().size();
out.child(0).allocate(scalars.size() + 1);
out.child(1).allocate(num_chars);
auto p_out_b = out.raw_bitmask();
auto p_out_o = out.child(0).raw_column<int32_t>();
auto p_out_c = out.child(1).raw_column<int8_t>();
int32_t curr_off = 0;
for (auto idx = 0; idx < scalars.size(); ++idx) {
auto valid = scalars[idx].valid();
p_out_o[idx] = curr_off;
p_out_b[idx] = valid;
if (!valid) continue;
auto &value = scalars[idx].value<std::string>();
memcpy(&p_out_c[curr_off], value.c_str(), value.size());
curr_off += value.size();
}
p_out_o[scalars.size()] = curr_off;
}
template <TypeCode CODE, std::enable_if_t<CODE == TypeCode::CAT32> * = nullptr>
void operator()(OutputColumn &out, const std::vector<Scalar> &scalars)
{
assert(false);
}
};
} // namespace detail
void OutputColumn::return_from_scalars(const std::vector<Scalar> &scalars)
{
type_dispatch(code(), detail::FromScalar{}, *this, scalars);
}
void OutputColumn::return_from_view(alloc::DeferredBufferAllocator &allocator, detail::Column view)
{
#ifdef DEBUG_PANDAS
assert(!valid());
#endif
num_elements_ = view.size();
auto data = view.raw_column();
if (nullptr != data) {
auto column_buffer = allocator.pop_allocation(data);
column_.return_from_instance(column_buffer.get_instance(), num_elements_, elem_size());
} else
column_.allocate(num_elements_);
if (nullable()) {
auto mask = view.raw_bitmask();
if (mask != nullptr) {
auto mask_buffer = allocator.pop_allocation(mask);
bitmask_->return_from_instance(
mask_buffer.get_instance(), num_elements_, sizeof(Bitmask::AllocType));
} else {
bitmask_->allocate(num_elements_);
if (num_elements_ > 0) bitmask().set_all_valid();
}
}
for (auto idx = 0; idx < num_children() && idx < view.num_children(); ++idx)
child(idx).return_from_view(allocator, view.child(idx));
}
void OutputColumn::return_column_from_instance(Realm::RegionInstance instance, size_t num_elements)
{
#ifdef DEBUG_PANDAS
assert(!valid());
#endif
num_elements_ = num_elements;
column_.return_from_instance(instance, num_elements, elem_size());
}
void OutputColumn::allocate(size_t num_elements,
bool recurse,
size_t alignment,
size_t bitmask_alignment)
{
allocate_column(num_elements, alignment);
allocate_bitmask(num_elements, bitmask_alignment);
if (recurse) {
switch (code()) {
case TypeCode::CAT32: {
child(0).allocate(num_elements);
break;
}
case TypeCode::STRING: {
child(0).allocate(num_elements == 0 ? 0 : num_elements + 1);
break;
}
default: {
break;
}
}
}
}
void OutputColumn::allocate_column(size_t num_elements, size_t alignment)
{
#ifdef DEBUG_PANDAS
assert(!valid());
#endif
num_elements_ = num_elements;
column_.allocate(num_elements, alignment);
}
void OutputColumn::allocate_bitmask(size_t num_elements, size_t alignment)
{
#ifdef DEBUG_PANDAS
assert(valid() && num_elements_ == num_elements);
#endif
if (nullable()) bitmask_->allocate(num_elements, alignment);
}
void OutputColumn::make_empty(bool recurse)
{
allocate(0);
if (recurse)
for (auto &child : children_) child.make_empty(recurse);
}
void OutputColumn::copy(const Column<true> &input, bool recurse)
{
auto size = input.num_elements();
allocate(size);
if (size > 0 && !input.is_meta())
memcpy(raw_column_untyped(), input.raw_column_untyped_read(), input.bytes());
if (recurse)
for (auto idx = 0; idx < children_.size(); ++idx)
children_[idx].copy(input.child(idx), recurse);
}
void OutputColumn::check_all_valid() const
{
assert(valid());
for (auto &child : children_) child.check_all_valid();
}
} // namespace pandas
} // namespace legate
| 28.388 | 99 | 0.681837 | marcinz |
e0179465b9cb5aa3cf0b479421f9f0457b5cc1ac | 14,008 | cpp | C++ | Source/FAP.cpp | biug/XBot | 20f51094ee18aeaa58d769a894c68b4f05f900d4 | [
"MIT"
] | 1 | 2017-09-21T19:08:42.000Z | 2017-09-21T19:08:42.000Z | Source/FAP.cpp | biug/XBot | 20f51094ee18aeaa58d769a894c68b4f05f900d4 | [
"MIT"
] | null | null | null | Source/FAP.cpp | biug/XBot | 20f51094ee18aeaa58d769a894c68b4f05f900d4 | [
"MIT"
] | null | null | null | #include "FAP.h"
#include "BWAPI.h"
XBot::FastAPproximation fap;
namespace XBot {
FastAPproximation::FastAPproximation() {
}
void FastAPproximation::addUnitPlayer1(FAPUnit fu) {
player1.push_back(fu);
}
void FastAPproximation::addIfCombatUnitPlayer1(FAPUnit fu) {
if (fu.groundDamage || fu.airDamage || fu.unitType == BWAPI::UnitTypes::Terran_Medic)
addUnitPlayer1(fu);
}
void FastAPproximation::addUnitPlayer2(FAPUnit fu) {
player2.push_back(fu);
}
void FastAPproximation::addIfCombatUnitPlayer2(FAPUnit fu) {
if (fu.groundDamage || fu.airDamage || fu.unitType == BWAPI::UnitTypes::Terran_Medic)
addUnitPlayer2(fu);
}
void FastAPproximation::simulate(int nFrames) {
while (nFrames--) {
if (!player1.size() || !player2.size())
break;
didSomething = false;
isimulate();
if (!didSomething)
break;
}
}
std::pair <int, int> FastAPproximation::playerScores() const {
std::pair <int, int> res;
for (auto & u : player1)
if (u.health && u.maxHealth)
res.first += (u.score * u.health) / (u.maxHealth * 2);
for (auto & u : player2)
if (u.health && u.maxHealth)
res.second += (u.score * u.health) / (u.maxHealth * 2);
return res;
}
std::pair <int, int> FastAPproximation::playerScoresUnits() const {
std::pair <int, int> res;
for (auto & u : player1)
if (u.health && u.maxHealth && !u.unitType.isBuilding())
res.first += (u.score * u.health) / (u.maxHealth * 2);
for (auto & u : player2)
if (u.health && u.maxHealth && !u.unitType.isBuilding())
res.second += (u.score * u.health) / (u.maxHealth * 2);
return res;
}
std::pair <int, int> FastAPproximation::playerScoresBuildings() const {
std::pair <int, int> res;
for (auto & u : player1)
if (u.health && u.maxHealth && u.unitType.isBuilding())
res.first += (u.score * u.health) / (u.maxHealth * 2);
for (auto & u : player2)
if (u.health && u.maxHealth && u.unitType.isBuilding())
res.second += (u.score * u.health) / (u.maxHealth * 2);
return res;
}
std::pair<std::vector<FastAPproximation::FAPUnit>*, std::vector<FastAPproximation::FAPUnit>*> FastAPproximation::getState() {
return { &player1, &player2 };
}
void FastAPproximation::clearState() {
player1.clear(), player2.clear();
}
void FastAPproximation::dealDamage(const FastAPproximation::FAPUnit &fu, int damage, BWAPI::DamageType damageType) const {
if (fu.shields >= damage - fu.shieldArmor) {
fu.shields -= damage - fu.shieldArmor;
return;
}
else if(fu.shields) {
damage -= (fu.shields + fu.shieldArmor);
fu.shields = 0;
}
if (!damage)
return;
if (damageType == BWAPI::DamageTypes::Concussive) {
if(fu.unitSize == BWAPI::UnitSizeTypes::Large)
damage = damage / 2;
else if(fu.unitSize == BWAPI::UnitSizeTypes::Medium)
damage = (damage * 3) / 4;
}
else if (damageType == BWAPI::DamageTypes::Explosive) {
if (fu.unitSize == BWAPI::UnitSizeTypes::Small)
damage = damage / 2;
else if (fu.unitSize == BWAPI::UnitSizeTypes::Medium)
damage = (damage * 3) / 4;
}
#ifdef _DEBUG
//damage = MAX(1, damage - fu.armor);
fu.damageTaken += damage;
fu.health -= damage;
#else
fu.health -= std::max(1, damage - fu.armor);
#endif
}
int inline FastAPproximation::distButNotReally(const FastAPproximation::FAPUnit &u1, const FastAPproximation::FAPUnit &u2) const {
return (u1.x - u2.x)*(u1.x - u2.x) + (u1.y - u2.y)*(u1.y - u2.y);
}
bool FastAPproximation::isSuicideUnit(BWAPI::UnitType ut) {
return (ut == BWAPI::UnitTypes::Zerg_Scourge || ut == BWAPI::UnitTypes::Terran_Vulture_Spider_Mine || ut == BWAPI::UnitTypes::Zerg_Infested_Terran);
}
void FastAPproximation::unitsim(const FastAPproximation::FAPUnit &fu, std::vector <FastAPproximation::FAPUnit> &enemyUnits) {
if (fu.attackCooldownRemaining) {
didSomething = true;
return;
}
auto closestEnemy = enemyUnits.end();
int closestDist;
for (auto enemyIt = enemyUnits.begin(); enemyIt != enemyUnits.end(); ++ enemyIt) {
if (enemyIt->flying) {
if (fu.airDamage) {
int d = distButNotReally(fu, *enemyIt);
if ((closestEnemy == enemyUnits.end() || d < closestDist) && d >= fu.airMinRange) {
closestDist = d;
closestEnemy = enemyIt;
}
}
}
else {
if (fu.groundDamage) {
int d = distButNotReally(fu, *enemyIt);
if ((closestEnemy == enemyUnits.end() || d < closestDist) && d >= fu.groundMinRange) {
closestDist = d;
closestEnemy = enemyIt;
}
}
}
}
if (closestEnemy != enemyUnits.end() && sqrt(closestDist) <= fu.speed && !(fu.x == closestEnemy->x && fu.y == closestEnemy->y)) {
fu.x = closestEnemy->x;
fu.y = closestEnemy->y;
closestDist = 0;
didSomething = true;
}
if (closestEnemy != enemyUnits.end() && closestDist <= (closestEnemy->flying ? fu.groundMaxRange : fu.airMinRange)) {
if (closestEnemy->flying)
dealDamage(*closestEnemy, fu.airDamage, fu.airDamageType), fu.attackCooldownRemaining = fu.airCooldown;
else {
dealDamage(*closestEnemy, fu.groundDamage, fu.groundDamageType);
fu.attackCooldownRemaining = fu.groundCooldown;
if (fu.elevation != -1 && closestEnemy->elevation != -1)
if (closestEnemy->elevation > fu.elevation)
fu.attackCooldownRemaining += fu.groundCooldown;
}
if (closestEnemy->health < 1) {
auto temp = *closestEnemy;
*closestEnemy = enemyUnits.back();
enemyUnits.pop_back();
unitDeath(temp, enemyUnits);
}
didSomething = true;
return;
}
else if(closestEnemy != enemyUnits.end() && sqrt(closestDist) > fu.speed) {
int dx = closestEnemy->x - fu.x, dy = closestEnemy->y - fu.y;
fu.x += (int)(dx*(fu.speed / sqrt(dx*dx + dy*dy)));
fu.y += (int)(dy*(fu.speed / sqrt(dx*dx + dy*dy)));
didSomething = true;
return;
}
}
void FastAPproximation::medicsim(const FAPUnit & fu, std::vector<FAPUnit> &friendlyUnits) {
auto closestHealable = friendlyUnits.end();
int closestDist;
for (auto it = friendlyUnits.begin(); it != friendlyUnits.end(); ++it) {
if (it->isOrganic && it->health < it->maxHealth && !it->didHealThisFrame) {
int d = distButNotReally(fu, *it);
if (closestHealable == friendlyUnits.end() || d < closestDist) {
closestHealable = it;
closestDist = d;
}
}
}
if (closestHealable != friendlyUnits.end()) {
fu.x = closestHealable->x;
fu.y = closestHealable->y;
closestHealable->health += (closestHealable->healTimer += 400) / 256;
closestHealable->healTimer %= 256;
if (closestHealable->health > closestHealable->maxHealth)
closestHealable->health = closestHealable->maxHealth;
closestHealable->didHealThisFrame = false;
}
}
bool FastAPproximation::suicideSim(const FAPUnit & fu, std::vector<FAPUnit>& enemyUnits) {
auto closestEnemy = enemyUnits.end();
int closestDist;
for (auto enemyIt = enemyUnits.begin(); enemyIt != enemyUnits.end(); ++enemyIt) {
if (enemyIt->flying) {
if (fu.airDamage) {
int d = distButNotReally(fu, *enemyIt);
if ((closestEnemy == enemyUnits.end() || d < closestDist) && d >= fu.airMinRange) {
closestDist = d;
closestEnemy = enemyIt;
}
}
}
else {
if (fu.groundDamage) {
int d = distButNotReally(fu, *enemyIt);
if ((closestEnemy == enemyUnits.end() || d < closestDist) && d >= fu.groundMinRange) {
closestDist = d;
closestEnemy = enemyIt;
}
}
}
}
if (closestEnemy != enemyUnits.end() && sqrt(closestDist) <= fu.speed) {
if(closestEnemy->flying)
dealDamage(*closestEnemy, fu.airDamage, fu.airDamageType);
else
dealDamage(*closestEnemy, fu.groundDamage, fu.groundDamageType);
if (closestEnemy->health < 1) {
auto temp = *closestEnemy;
*closestEnemy = enemyUnits.back();
enemyUnits.pop_back();
unitDeath(temp, enemyUnits);
}
didSomething = true;
return true;
}
else if (closestEnemy != enemyUnits.end() && sqrt(closestDist) > fu.speed) {
int dx = closestEnemy->x - fu.x, dy = closestEnemy->y - fu.y;
fu.x += (int)(dx*(fu.speed / sqrt(dx*dx + dy*dy)));
fu.y += (int)(dy*(fu.speed / sqrt(dx*dx + dy*dy)));
didSomething = true;
}
return false;
}
void FastAPproximation::isimulate() {
for (auto fu = player1.begin(); fu != player1.end();) {
if (isSuicideUnit(fu->unitType)) {
bool result = suicideSim(*fu, player2);
if (result)
fu = player1.erase(fu);
else
++fu;
}
else {
if (fu->unitType == BWAPI::UnitTypes::Terran_Medic)
medicsim(*fu, player1);
else
unitsim(*fu, player2);
++fu;
}
}
for (auto fu = player2.begin(); fu != player2.end();) {
if (isSuicideUnit(fu->unitType)) {
bool result = suicideSim(*fu, player1);
if (result)
fu = player2.erase(fu);
else
++fu;
}
else {
if (fu->unitType == BWAPI::UnitTypes::Terran_Medic)
medicsim(*fu, player2);
else
unitsim(*fu, player1);
++fu;
}
}
for (auto &fu : player1) {
if (fu.attackCooldownRemaining)
--fu.attackCooldownRemaining;
if (fu.didHealThisFrame)
fu.didHealThisFrame = false;
}
for (auto &fu : player2) {
if (fu.attackCooldownRemaining)
--fu.attackCooldownRemaining;
if (fu.didHealThisFrame)
fu.didHealThisFrame = false;
}
}
void FastAPproximation::unitDeath(const FAPUnit &fu, std::vector<FAPUnit> &itsFriendlies) {
if (fu.unitType == BWAPI::UnitTypes::Terran_Bunker) {
convertToUnitType(fu, BWAPI::UnitTypes::Terran_Marine);
for(unsigned i = 0; i < 4; ++ i)
itsFriendlies.push_back(fu);
}
}
void FastAPproximation::convertToUnitType(const FAPUnit &fu, BWAPI::UnitType ut)
{
XBot::UnitInfo ui;
ui.lastPosition = BWAPI::Position(fu.x, fu.y);
ui.player = fu.player;
ui.type = ut;
FAPUnit funew(ui);
funew.attackCooldownRemaining = fu.attackCooldownRemaining;
funew.elevation = fu.elevation;
fu.operator=(funew);
}
FastAPproximation::FAPUnit::FAPUnit(BWAPI::Unit u): FAPUnit(UnitInfo(u)) {
}
FastAPproximation::FAPUnit::FAPUnit(UnitInfo ui) :
x(ui.lastPosition.x),
y(ui.lastPosition.y),
speed(ui.player->topSpeed(ui.type)),
health(ui.lastHealth),
maxHealth(ui.type.maxHitPoints()),
shields(ui.lastShields),
shieldArmor(ui.player->getUpgradeLevel(BWAPI::UpgradeTypes::Protoss_Plasma_Shields)),
maxShields(ui.type.maxShields()),
armor(ui.player->armor(ui.type)),
flying(ui.type.isFlyer()),
groundDamage(ui.player->damage(ui.type.groundWeapon())),
groundCooldown(ui.type.groundWeapon().damageFactor() && ui.type.maxGroundHits() ? ui.player->weaponDamageCooldown(ui.type) / (ui.type.groundWeapon().damageFactor() * ui.type.maxGroundHits()) : 0),
groundMaxRange(ui.player->weaponMaxRange(ui.type.groundWeapon())),
groundMinRange(ui.type.groundWeapon().minRange()),
groundDamageType(ui.type.groundWeapon().damageType()),
airDamage(ui.player->damage(ui.type.airWeapon())),
airCooldown(ui.type.airWeapon().damageFactor() && ui.type.maxAirHits() ? ui.type.airWeapon().damageCooldown() / (ui.type.airWeapon().damageFactor() * ui.type.maxAirHits()) : 0),
airMaxRange(ui.player->weaponMaxRange(ui.type.airWeapon())),
airMinRange(ui.type.airWeapon().minRange()),
airDamageType(ui.type.airWeapon().damageType()),
unitType(ui.type),
isOrganic(ui.type.isOrganic()),
score(ui.type.destroyScore()),
player(ui.player)
{
static int nextId = 0;
id = nextId++;
if (ui.type == BWAPI::UnitTypes::Protoss_Carrier) {
groundDamage = ui.player->damage(BWAPI::UnitTypes::Protoss_Interceptor.groundWeapon());
groundDamageType = BWAPI::UnitTypes::Protoss_Interceptor.groundWeapon().damageType();
groundCooldown = 5;
groundMaxRange = 32 * 8;
airDamage = groundDamage;
airDamageType = groundDamageType;
airCooldown = groundCooldown;
airMaxRange = groundMaxRange;
}
else if (ui.type == BWAPI::UnitTypes::Terran_Bunker) {
groundDamage = ui.player->damage(BWAPI::WeaponTypes::Gauss_Rifle);
groundCooldown = BWAPI::UnitTypes::Terran_Marine.groundWeapon().damageCooldown() / 4;
groundMaxRange = ui.player->weaponMaxRange(BWAPI::UnitTypes::Terran_Marine.groundWeapon()) + 32;
airDamage = groundDamage;
airCooldown = groundCooldown;
airMaxRange = groundMaxRange;
}
else if (ui.type == BWAPI::UnitTypes::Protoss_Reaver) {
groundDamage = ui.player->damage(BWAPI::WeaponTypes::Scarab);
}
if (ui.unit && ui.unit->isStimmed()) {
groundCooldown /= 2;
airCooldown /= 2;
}
if (ui.unit && ui.unit->isVisible() && !ui.unit->isFlying()) {
elevation = BWAPI::Broodwar->getGroundHeight(ui.unit->getTilePosition());
}
groundMaxRange *= groundMaxRange;
groundMinRange *= groundMinRange;
airMaxRange *= airMaxRange;
airMinRange *= airMinRange;
groundDamage *= 2;
airDamage *= 2;
shieldArmor *= 2;
armor *= 2;
health *= 2;
maxHealth *= 2;
shields *= 2;
maxShields *= 2;
}
const FastAPproximation::FAPUnit &FastAPproximation::FAPUnit::operator=(const FAPUnit & other) const {
x = other.x, y = other.y;
health = other.health, maxHealth = other.maxHealth;
shields = other.shields, maxShields = other.maxShields;
speed = other.speed, armor = other.armor, flying = other.flying, unitSize = other.unitSize;
groundDamage = other.groundDamage, groundCooldown = other.groundCooldown, groundMaxRange = other.groundMaxRange, groundMinRange = other.groundMinRange, groundDamageType = other.groundDamageType;
airDamage = other.airDamage, airCooldown = other.airCooldown, airMaxRange = other.airMaxRange, airMinRange = other.airMinRange, airDamageType = other.airDamageType;
score = other.score;
attackCooldownRemaining = other.attackCooldownRemaining;
unitType = other.unitType; isOrganic = other.isOrganic;
healTimer = other.healTimer; didHealThisFrame = other.didHealThisFrame;
elevation = other.elevation;
player = other.player;
return *this;
}
bool FastAPproximation::FAPUnit::operator<(const FAPUnit & other) const {
return id < other.id;
}
}
| 29.366876 | 198 | 0.666119 | biug |
e01a758c3acfc94a99a93f10bbd5db16f70d2f6e | 522 | cpp | C++ | Homework/3.35.cpp | TuringGu/C-code | 76085120a930a900e7d686065261032288858fb6 | [
"MIT"
] | null | null | null | Homework/3.35.cpp | TuringGu/C-code | 76085120a930a900e7d686065261032288858fb6 | [
"MIT"
] | null | null | null | Homework/3.35.cpp | TuringGu/C-code | 76085120a930a900e7d686065261032288858fb6 | [
"MIT"
] | null | null | null | #include<iostream>
#include<string>
using namespace std;
const int MAXSIZE=100;
class Stock{
public:
Stock()
{
strcpy_s(stockcode, " ");
}
Stock(char na[MAXSIZE], int q = 1000, double p = 8.98)
{
strcpy_s(stockcode, na);
quan = q;
price = p;
}
void print()
{
cout << stockcode<<" " << quan <<" "<< price << endl;
}
private:
char stockcode[MAXSIZE];
int quan;
double price;
};
int main()
{
Stock A("600001",3000,5.67);
Stock B("600001");
A.print();
B.print();
char x;
cin >> x;
return 0;
} | 13.736842 | 57 | 0.599617 | TuringGu |
e01e77202b5a9ef61ef96c1246e34c6f9ed6f18f | 16,962 | hpp | C++ | flat_map.hpp | pingwindyktator/cpp_sandbox | 815a80f826aa0ea718389ebda0f8e6513a051de1 | [
"WTFPL"
] | 1 | 2018-02-15T21:06:17.000Z | 2018-02-15T21:06:17.000Z | flat_map.hpp | pingwindyktator/cpp_sandbox | 815a80f826aa0ea718389ebda0f8e6513a051de1 | [
"WTFPL"
] | null | null | null | flat_map.hpp | pingwindyktator/cpp_sandbox | 815a80f826aa0ea718389ebda0f8e6513a051de1 | [
"WTFPL"
] | null | null | null | #pragma once
#include <algorithm>
#include <cstddef>
#include <functional>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
namespace sandbox {
template<class Key, class T, class Compare = std::less<Key>, class Allocator = std::allocator<std::pair<const Key, T>>>
class flat_map
{
public:
using key_type = Key;
using mapped_type = T;
// using value_type = std::pair<const Key, T>;
using value_type = std::pair<Key, T>;
using storage_type = std::vector<value_type, Allocator>;
using size_type = typename storage_type::size_type;
using difference_type = typename storage_type::difference_type;
using key_compare = Compare;
using allocator_type = Allocator;
using reference = typename storage_type::reference;
using const_reference = typename storage_type::const_reference;
using pointer = typename storage_type::pointer;
using const_pointer = typename storage_type::const_pointer;
using iterator = typename storage_type::iterator;
using const_iterator = typename storage_type::const_iterator;
using reverse_iterator = typename storage_type::reverse_iterator;
using const_reverse_iterator = typename storage_type::const_reverse_iterator;
public:
class value_compare
{
friend class flat_map;
protected:
explicit value_compare(Compare c) : comp(c)
{}
public:
bool operator()(const value_type &lhs, const value_type &rhs) const
{
return comp(lhs.first, rhs.first);
}
public:
// for convinience
bool operator()(const key_type &lhs, const value_type &rhs) const
{
return comp(lhs, rhs.first);
}
bool operator()(const value_type &lhs, const key_type &rhs) const
{
return comp(lhs.first, rhs);
}
bool operator()(const key_type &lhs, const key_type &rhs) const
{
return comp(lhs, rhs);
}
protected:
Compare comp;
};
public:
flat_map() : flat_map(Compare())
{
}
explicit flat_map(const Compare &comp, const Allocator &alloc = Allocator()) : comp_(comp), storage_(alloc)
{
}
template<class In>
flat_map(In first, In last, const Compare &comp = Compare(), const Allocator &alloc = Allocator()) : comp_(comp), storage_(alloc)
{
insert(first, last);
}
template<class In>
flat_map(In first, In last, const Allocator &alloc) : storage_(alloc)
{
insert(first, last);
}
flat_map(const flat_map &other) : comp_(other.comp_), storage_(other.storage_)
{
}
flat_map(const flat_map &other, const Allocator &alloc) : comp_(other.comp_), storage_(other.storage_, alloc)
{
}
flat_map(const flat_map &&other) noexcept : comp_(std::move(other.comp_)), storage_(std::move(other.storage_))
{
}
flat_map(const flat_map &&other, const Allocator &alloc) : comp_(std::move(other.comp_)), storage_(std::move(other.storage_), alloc)
{
}
flat_map(std::initializer_list<value_type> init, const Compare &comp = Compare(), const Allocator &alloc = Allocator()) : comp_(comp), storage_(alloc)
{
insert(init);
}
flat_map(std::initializer_list<value_type> init, const Allocator &alloc) : comp_(Compare()), storage_(alloc)
{
insert(init);
}
~flat_map() = default;
flat_map &operator=(const flat_map &other)
{
flat_map(other).swap(*this);
return *this;
}
flat_map &operator=(flat_map &&other) noexcept
{
flat_map(std::move(other)).swap(*this);
return *this;
}
flat_map &operator=(std::initializer_list<value_type> ilist)
{
flat_map(ilist).swap(*this);
return *this;
}
allocator_type get_allocator() const
{
return storage_.get_allocator();
}
T &at(const Key &key)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
// found!
return it->second;
} else
{
throw std::out_of_range("out_of_range");
}
}
const T &at(const Key &key) const
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
// found!
return it->second;
} else
{
throw std::out_of_range("out_of_range");
}
}
T &operator[](const Key &key)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
// found!
return it->second;
} else
{
// create it
auto n = storage_.emplace(it, key, T());
return n->second;
}
}
T &operator[](Key &&key)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
// found!
return it->second;
} else
{
// create it
auto n = storage_.emplace(it, std::forward<Key>(key), T());
return n->second;
}
}
iterator begin()
{
return storage_.begin();
}
const_iterator begin() const
{
return storage_.begin();
}
const_iterator cbegin() const
{
return storage_.cbegin();
}
iterator end()
{
return storage_.end();
}
const_iterator end() const
{
return storage_.end();
}
const_iterator cend() const
{
return storage_.cend();
}
reverse_iterator rbegin()
{
return storage_.rbegin();
}
const_reverse_iterator rbegin() const
{
return storage_.rbegin();
}
const_reverse_iterator crbegin() const
{
return storage_.crbegin();
}
reverse_iterator rend()
{
return storage_.rend();
}
const_reverse_iterator rend() const
{
return storage_.rend();
}
const_reverse_iterator crend() const
{
return storage_.crend();
}
bool empty() const
{
return storage_.empty();
}
size_type size() const
{
return storage_.size();
}
size_type max_size() const
{
return storage_.max_size();
}
void clear()
{
storage_.clear();
}
std::pair<iterator, bool> insert(const value_type &value)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), value, comp_);
if (it != end(storage_) && !comp_(value, *it))
{
// found!
return std::make_pair(it, false);
} else
{
// create it
auto n = storage_.insert(it, value);
return std::make_pair(n, true);
}
}
template<class P>
std::pair<iterator, bool> insert(P &&value)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), value, comp_);
if (it != end(storage_) && !comp_(value, *it))
{
// found!
return std::make_pair(it, false);
} else
{
// create it
auto n = storage_.insert(it, std::forward<P>(value));
return std::make_pair(n, true);
}
}
std::pair<iterator, bool> insert(value_type &&value)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), value, comp_);
if (it != end(storage_) && !comp_(value, *it))
{
// found!
return std::make_pair(it, false);
} else
{
// create it
auto n = storage_.insert(it, std::move_if_noexcept(value));
return std::make_pair(n, true);
}
}
std::pair<iterator, bool> insert(const_iterator hint, const value_type &value)
{
(void) hint;
return insert(value);
}
template<class P>
std::pair<iterator, bool> insert(const_iterator hint, P &&value)
{
(void) hint;
return insert(std::forward<P>(value));
}
std::pair<iterator, bool> insert(const_iterator hint, value_type &&value)
{
(void) hint;
return insert(std::move_if_noexcept(value));
}
template<class In>
void insert(In first, In last)
{
while (first != last)
{
insert(*first++);
}
}
void insert(std::initializer_list<value_type> ilist)
{
for (auto &&value : ilist)
{
insert(std::move_if_noexcept(value));
}
}
template<class M>
std::pair<iterator, bool> insert_or_assign(const key_type &key, M &&obj)
{
auto it = insert(key);
if (it.second)
{
it.first->second = std::forward<M>(obj);
}
return it;
}
template<class M>
std::pair<iterator, bool> insert_or_assign(key_type &&key, M &&obj)
{
auto it = insert(std::move_if_noexcept(key));
if (it.second)
{
it.first->second = std::forward<M>(obj);
}
return it;
}
template<class M>
std::pair<iterator, bool> insert_or_assign(const_iterator hint, const key_type &key, M &&obj)
{
auto it = insert(hint, key);
if (it.second)
{
it.first->second = std::forward<M>(obj);
}
return it;
}
template<class M>
std::pair<iterator, bool> insert_or_assign(const_iterator hint, key_type &&key, M &&obj)
{
auto it = insert(hint, key);
if (it.second)
{
it.first->second = std::forward<M>(obj);
}
return it;
}
// TODO: try_emplace
template<class... Args>
std::pair<iterator, bool> emplace(Args &&... args)
{
using std::begin;
using std::end;
value_type temp(std::forward<Args>(args)...);
auto it = std::lower_bound(begin(storage_), end(storage_), temp, comp_);
if (it != end(storage_) && !comp_(temp, *it))
{
// found!
return std::make_pair(it, false);
} else
{
// create it
auto n = storage_.emplace(it, std::move_if_noexcept(temp));
return std::make_pair(n, true);
}
}
template<class... Args>
std::pair<iterator, bool> emplace_hint(const_iterator hint, Args &&... args)
{
(void) hint;
using std::begin;
using std::end;
value_type temp(std::forward<Args>(args)...);
auto it = std::lower_bound(begin(storage_), end(storage_), temp, comp_);
if (it != end(storage_) && !comp_(temp, *it))
{
// found!
return std::make_pair(it, false);
} else
{
// create it
auto n = storage_.emplace(it, std::move_if_noexcept(temp));
return std::make_pair(n, true);
}
}
iterator erase(const_iterator pos)
{
return storage_.erase(pos);
}
iterator erase(iterator pos)
{
return storage_.erase(pos);
}
iterator erase(const_iterator first, const_iterator last)
{
return storage_.erase(first, last);
}
size_type erase(const key_type &key)
{
size_type c = 0;
auto r = equal_range(key);
auto first = r.first;
auto second = r.second;
while (first != second)
{
erase(first++);
++c;
}
return c;
}
void swap(flat_map &other)
{
using std::swap;
swap(comp_, other.comp_);
swap(storage_, other.storage_);
}
size_type count(const Key &key) const
{
size_type c = 0;
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
while (it != end(storage_) && !comp_(key, *it))
{
++c;
}
return c;
}
template<class K>
size_type count(const K &key) const
{
size_type c = 0;
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
while (it != end(storage_) && !comp_(key, *it))
{
++c;
}
return c;
}
iterator find(const Key &key)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
return it;
}
return end(storage_);
}
const_iterator find(const Key &key) const
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
return it;
}
return end(storage_);
}
template<class K>
iterator find(const K &key)
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
return it;
}
return end(storage_);
}
template<class K>
const_iterator find(const K &key) const
{
using std::begin;
using std::end;
auto it = std::lower_bound(begin(storage_), end(storage_), key, comp_);
if (it != end(storage_) && !comp_(key, *it))
{
return it;
}
return end(storage_);
}
std::pair<iterator, iterator> equal_range(const Key &key)
{
using std::begin;
using std::end;
return std::equal_range(begin(storage_), end(storage_), key, comp_);
}
std::pair<const_iterator, const_iterator> equal_range(const Key &key) const
{
using std::begin;
using std::end;
return std::equal_range(begin(storage_), end(storage_), key, comp_);
}
template<class K>
std::pair<iterator, iterator> equal_range(const K &key)
{
using std::begin;
using std::end;
return std::equal_range(begin(storage_), end(storage_), key, comp_);
}
template<class K>
std::pair<const_iterator, const_iterator> equal_range(const K &key) const
{
using std::begin;
using std::end;
return std::equal_range(begin(storage_), end(storage_), key, comp_);
}
iterator lower_bound(const Key &key)
{
using std::begin;
using std::end;
return std::lower_bound(begin(storage_), end(storage_), key, comp_);
}
const_iterator lower_bound(const Key &key) const
{
using std::begin;
using std::end;
return std::lower_bound(begin(storage_), end(storage_), key, comp_);
}
template<class K>
iterator lower_bound(const K &key)
{
using std::begin;
using std::end;
return std::lower_bound(begin(storage_), end(storage_), key, comp_);
}
template<class K>
const_iterator lower_bound(const K &key) const
{
using std::begin;
using std::end;
return std::lower_bound(begin(storage_), end(storage_), key, comp_);
}
iterator upper_bound(const Key &key)
{
using std::begin;
using std::end;
return std::upper_bound(begin(storage_), end(storage_), key, comp_);
}
const_iterator upper_bound(const Key &key) const
{
using std::begin;
using std::end;
return std::upper_bound(begin(storage_), end(storage_), key, comp_);
}
template<class K>
iterator upper_bound(const K &key)
{
using std::begin;
using std::end;
return std::upper_bound(begin(storage_), end(storage_), key, comp_);
}
template<class K>
const_iterator upper_bound(const K &key) const
{
using std::begin;
using std::end;
return std::upper_bound(begin(storage_), end(storage_), key, comp_);
}
key_compare key_comp() const
{
return comp_.comp;
}
value_compare value_comp() const
{
return comp_;
}
private:
value_compare comp_{};
storage_type storage_;
};
} | 24.547033 | 154 | 0.545219 | pingwindyktator |
e01ed24114b75a583eb3245f60b6b9beee369553 | 42,652 | cc | C++ | routerNodeBase.cc | aakritanshuman/mtp | d24c09e99e01904ffc0d779c5e031bb7c03cff8e | [
"MIT"
] | 11 | 2020-03-03T11:58:23.000Z | 2021-04-20T02:01:30.000Z | routerNodeBase.cc | aakritanshuman/mtp | d24c09e99e01904ffc0d779c5e031bb7c03cff8e | [
"MIT"
] | null | null | null | routerNodeBase.cc | aakritanshuman/mtp | d24c09e99e01904ffc0d779c5e031bb7c03cff8e | [
"MIT"
] | 9 | 2020-03-17T02:17:07.000Z | 2022-02-17T16:12:31.000Z | #include "routerNodeBase.h"
#include "hostInitialize.h"
#include <queue>
Define_Module(routerNodeBase);
int routerNodeBase::myIndex(){
return getIndex() + _numHostNodes;
}
/* helper function to go through all transactions in a queue and print their details out
* meant for debugging
*/
void routerNodeBase::checkQueuedTransUnits(vector<tuple<int, double, routerMsg*, Id, simtime_t>>
queuedTransUnits, int nextNode){
if (queuedTransUnits.size() > 0) {
cout << "simTime(): " << simTime() << endl;
cout << "queuedTransUnits size: " << queuedTransUnits.size() << endl;
for (auto q: queuedTransUnits) {
routerMsg* msg = get<2>(q);
transactionMsg *transMsg = check_and_cast<transactionMsg *>(msg->getEncapsulatedPacket());
if (transMsg->getHasTimeOut()){
cout << "(" << (transMsg->getTimeSent() + transMsg->getTimeOut())
<< "," << transMsg->getTransactionId() << "," << nextNode << ") ";
}
else {
cout << "(-1) ";
}
}
cout << endl;
for (auto c: canceledTransactions) {
cout << "(" << get<0>(c) << "," <<get<1>(c) <<","<< get<2>(c)<< "," << get<3>(c)<< ") ";
}
cout << endl;
}
}
/* helper method to print channel balances
*/
void routerNodeBase:: printNodeToPaymentChannel(){
printf("print of channels\n" );
for (auto i : nodeToPaymentChannel){
printf("(key: %d, %f )",i.first, i.second.balance);
}
cout<<endl;
}
/* get total amount on queue to node x */
double routerNodeBase::getTotalAmount(int x) {
if (_hasQueueCapacity && _queueCapacity == 0)
return 0;
return nodeToPaymentChannel[x].totalAmtInQueue;
}
/* get total amount inflight incoming node x */
double routerNodeBase::getTotalAmountIncomingInflight(int x) {
return nodeToPaymentChannel[x].totalAmtIncomingInflight;
}
/* get total amount inflight outgoing node x */
double routerNodeBase::getTotalAmountOutgoingInflight(int x) {
return nodeToPaymentChannel[x].totalAmtOutgoingInflight;
}
/* helper function to delete router message and encapsulated transaction message
*/
void routerNodeBase::deleteTransaction(routerMsg* ttmsg) {
transactionMsg *transMsg = check_and_cast<transactionMsg *>(ttmsg->getEncapsulatedPacket());
ttmsg->decapsulate();
delete transMsg;
delete ttmsg;
}
/* register a signal per channel of the particular type passed in
* and return the signal created
*/
simsignal_t routerNodeBase::registerSignalPerChannel(string signalStart, int id) {
char signalName[64];
string signalPrefix = signalStart + "PerChannel";
string templateString = signalPrefix + "Template";
if (id < _numHostNodes){
sprintf(signalName, "%s(host %d)", signalPrefix.c_str(), id);
} else{
sprintf(signalName, "%s(router %d [%d] )", signalPrefix.c_str(),
id - _numHostNodes, id);
}
simsignal_t signal = registerSignal(signalName);
cProperty *statisticTemplate = getProperties()->get("statisticTemplate",
templateString.c_str());
getEnvir()->addResultRecorders(this, signal, signalName, statisticTemplate);
return signal;
}
/* register a signal per destination for this path of the particular type passed in
* and return the signal created
*/
simsignal_t routerNodeBase::registerSignalPerChannelPerDest(string signalStart, int chnlEndNode, int destNode) {
char signalName[64];
string signalPrefix = signalStart + "PerChannelPerDest";
string templateString = signalPrefix + "Template";
if (chnlEndNode < _numHostNodes){
sprintf(signalName, "%s_%d(host %d)", signalPrefix.c_str(), destNode, chnlEndNode);
} else {
sprintf(signalName, "%s_%d(router %d [%d] )", signalPrefix.c_str(),
destNode, chnlEndNode - _numHostNodes, chnlEndNode);
}
simsignal_t signal = registerSignal(signalName);
cProperty *statisticTemplate = getProperties()->get("statisticTemplate",
templateString.c_str());
getEnvir()->addResultRecorders(this, signal, signalName, statisticTemplate);
return signal;
}
/* register a signal per dest of the particular type passed in
* and return the signal created
*/
simsignal_t routerNodeBase::registerSignalPerDest(string signalStart, int destNode, string suffix) {
string signalPrefix = signalStart + "PerDest" + suffix;
char signalName[64];
string templateString = signalStart + "PerDestTemplate";
sprintf(signalName, "%s(host node %d)", signalPrefix.c_str(), destNode);
simsignal_t signal = registerSignal(signalName);
cProperty *statisticTemplate = getProperties()->get("statisticTemplate",
templateString.c_str());
getEnvir()->addResultRecorders(this, signal, signalName, statisticTemplate);
return signal;
}
/* initialize basic
* per channel information as well as default signals for all
* payment channels
* */
void routerNodeBase::initialize()
{
// Assign gates to all payment channels
const char * gateName = "out";
cGate *destGate = NULL;
int i = 0;
int gateSize = gate(gateName, 0)->size();
do {
destGate = gate(gateName, i++);
cGate *nextGate = destGate->getNextGate();
if (nextGate ) {
PaymentChannel temp = {};
temp.gate = destGate;
bool isHost = nextGate->getOwnerModule()->par("isHost");
int key = nextGate->getOwnerModule()->getIndex();
if (!isHost){
key = key + _numHostNodes;
}
nodeToPaymentChannel[key] = temp;
}
} while (i < gateSize);
//initialize everything for adjacent nodes/nodes with payment channel to me
for(auto iter = nodeToPaymentChannel.begin(); iter != nodeToPaymentChannel.end(); ++iter)
{
int key = iter->first;
nodeToPaymentChannel[key].balance = _balances[make_tuple(myIndex(),key)];
nodeToPaymentChannel[key].balanceEWMA = nodeToPaymentChannel[key].balance;
// intialize capacity
double balanceOpp = _balances[make_tuple(key, myIndex())];
nodeToPaymentChannel[key].origTotalCapacity = nodeToPaymentChannel[key].balance + balanceOpp;
//initialize queuedTransUnits
vector<tuple<int, double , routerMsg *, Id, simtime_t>> temp;
make_heap(temp.begin(), temp.end(), _schedulingAlgorithm);
nodeToPaymentChannel[key].queuedTransUnits = temp;
//register PerChannel signals
if (_signalsEnabled) {
simsignal_t signal;
signal = registerSignalPerChannel("numInQueue", key);
nodeToPaymentChannel[key].amtInQueuePerChannelSignal = signal;
signal = registerSignalPerChannel("numSent", key);
nodeToPaymentChannel[key].numSentPerChannelSignal = signal;
signal = registerSignalPerChannel("balance", key);
nodeToPaymentChannel[key].balancePerChannelSignal = signal;
signal = registerSignalPerChannel("capacity", key);
nodeToPaymentChannel[key].capacityPerChannelSignal = signal;
signal = registerSignalPerChannel("queueDelayEWMA", key);
nodeToPaymentChannel[key].queueDelayEWMASignal = signal;
signal = registerSignalPerChannel("numInflight", key);
nodeToPaymentChannel[key].numInflightPerChannelSignal = signal;
signal = registerSignalPerChannel("timeInFlight", key);
nodeToPaymentChannel[key].timeInFlightPerChannelSignal = signal;
signal = registerSignalPerChannel("implicitRebalancingAmt", key);
nodeToPaymentChannel[key].implicitRebalancingAmtPerChannelSignal = signal;
signal = registerSignalPerChannel("explicitRebalancingAmt", key);
nodeToPaymentChannel[key].explicitRebalancingAmtPerChannelSignal = signal;
}
}
// generate statistic message
routerMsg *statMsg = generateStatMessage();
scheduleAt(simTime() + 0, statMsg);
// generate time out clearing messages
if (_timeoutEnabled) {
routerMsg *clearStateMsg = generateClearStateMessage();
scheduleAt(simTime() + _clearRate, clearStateMsg);
}
}
/* function that is called at the end of the simulation that
* deletes any remaining messages and records scalars
*/
void routerNodeBase::finish(){
deleteMessagesInQueues();
double numPoints = (_transStatEnd - _transStatStart)/(double) _statRate;
double sumRebalancing = 0;
double sumAmtAdded = 0;
// iterate through all payment channels and print last summary statistics for queues
for ( auto it = nodeToPaymentChannel.begin(); it!= nodeToPaymentChannel.end(); it++){
int node = it->first; //key
char buffer[30];
sprintf(buffer, "queueSize %d -> %d", myIndex(), node);
recordScalar(buffer, nodeToPaymentChannel[node].queueSizeSum/numPoints);
sumRebalancing += nodeToPaymentChannel[node].numRebalanceEvents;
sumAmtAdded += nodeToPaymentChannel[node].amtAdded;
}
// total amount of rebalancing incurred by this node
char buffer[60];
sprintf(buffer, "totalNumRebalancingEvents %d blah 1", myIndex());
recordScalar(buffer, sumRebalancing/(_transStatEnd - _transStatStart));
sprintf(buffer, "totalAmtAdded %d blah 2", myIndex());
recordScalar(buffer, sumAmtAdded/(_transStatEnd - _transStatStart));
}
/* given an adjacent node, and TransUnit queue of things to send to that node, sends
* TransUnits until channel funds are too low
* calls forwardTransactionMessage on every individual TransUnit
* returns true when it still can continue processing more transactions
*/
bool routerNodeBase:: processTransUnits(int neighbor,
vector<tuple<int, double , routerMsg *, Id, simtime_t>>& q) {
int successful = true;
while ((int)q.size() > 0 && successful == 1) {
pop_heap(q.begin(), q.end(), _schedulingAlgorithm);
successful = forwardTransactionMessage(get<2>(q.back()), neighbor, get<4>(q.back()));
if (successful == 1){
q.pop_back();
}
}
return (successful != 0); // anything other than balance exhausted implies you can go on
}
/* helper method to delete the messages in any payment channel queues
* and per dest queues at the end of the experiment
*/
void routerNodeBase::deleteMessagesInQueues(){
for (auto iter = nodeToPaymentChannel.begin(); iter!=nodeToPaymentChannel.end(); iter++){
int key = iter->first;
for (auto temp = (nodeToPaymentChannel[key].queuedTransUnits).begin();
temp!= (nodeToPaymentChannel[key].queuedTransUnits).end(); ){
routerMsg * rMsg = get<2>(*temp);
auto tMsg = rMsg->getEncapsulatedPacket();
rMsg->decapsulate();
delete tMsg;
delete rMsg;
temp = (nodeToPaymentChannel[key].queuedTransUnits).erase(temp);
}
}
}
/********** MESSAGE GENERATOR ********************/
/* generates messages responsible for recognizing that a txn is complete
* and funds have been securely transferred from a previous node to a
* neighboring node after the ack/secret has been received
* Always goes only one hop, no more
*/
routerMsg *routerNodeBase::generateUpdateMessage(int transId,
int receiver, double amount, int htlcIndex){
char msgname[MSGSIZE];
sprintf(msgname, "tic-%d-to-%d updateMsg", myIndex(), receiver);
routerMsg *rMsg = new routerMsg(msgname);
vector<int> route={myIndex(),receiver};
rMsg->setRoute(route);
rMsg->setHopCount(0);
rMsg->setMessageType(UPDATE_MSG);
updateMsg *uMsg = new updateMsg(msgname);
uMsg->setAmount(amount);
uMsg->setTransactionId(transId);
uMsg->setHtlcIndex(htlcIndex);
rMsg->encapsulate(uMsg);
return rMsg;
}
/* generate statistic trigger message every x seconds
* to output all statistics which can then be plotted
*/
routerMsg *routerNodeBase::generateTriggerRebalancingMessage(){
char msgname[MSGSIZE];
sprintf(msgname, "node-%d rebalancingMsg", myIndex());
routerMsg *rMsg = new routerMsg(msgname);
rMsg->setMessageType(TRIGGER_REBALANCING_MSG);
return rMsg;
}
/* generate statistic trigger message every x seconds
* to output all statistics which can then be plotted
*/
routerMsg *routerNodeBase::generateStatMessage(){
char msgname[MSGSIZE];
sprintf(msgname, "node-%d statMsg", myIndex());
routerMsg *rMsg = new routerMsg(msgname);
rMsg->setMessageType(STAT_MSG);
return rMsg;
}
/* generate message trigger t generate balances for all the payment channels
*/
routerMsg *routerNodeBase::generateComputeMinBalanceMessage(){
char msgname[MSGSIZE];
sprintf(msgname, "node-%d computeMinBalanceMsg", myIndex());
routerMsg *rMsg = new routerMsg(msgname);
rMsg->setMessageType(COMPUTE_BALANCE_MSG);
return rMsg;
}
/* generate a periodic message to remove
* any state pertaining to transactions that have
* timed out
*/
routerMsg *routerNodeBase::generateClearStateMessage(){
char msgname[MSGSIZE];
sprintf(msgname, "node-%d clearStateMsg", myIndex());
routerMsg *rMsg = new routerMsg(msgname);
rMsg->setMessageType(CLEAR_STATE_MSG);
return rMsg;
}
/* called only when a router in between the sender-receiver path
* wants to send a failure ack due to insfufficent funds
* similar to the endhost ack
* isSuccess denotes whether the ack is in response to a transaction
* that succeeded or failed.
*/
routerMsg *routerNodeBase::generateAckMessage(routerMsg* ttmsg, bool isSuccess) {
int sender = (ttmsg->getRoute())[0];
int receiver = (ttmsg->getRoute())[(ttmsg->getRoute()).size() -1];
vector<int> route = ttmsg->getRoute();
transactionMsg *transMsg = check_and_cast<transactionMsg *>(ttmsg->getEncapsulatedPacket());
int transactionId = transMsg->getTransactionId();
double timeSent = transMsg->getTimeSent();
double amount = transMsg->getAmount();
bool hasTimeOut = transMsg->getHasTimeOut();
char msgname[MSGSIZE];
sprintf(msgname, "receiver-%d-to-sender-%d ackMsg", receiver, sender);
routerMsg *msg = new routerMsg(msgname);
ackMsg *aMsg = new ackMsg(msgname);
aMsg->setTransactionId(transactionId);
aMsg->setIsSuccess(isSuccess);
aMsg->setTimeSent(timeSent);
aMsg->setAmount(amount);
aMsg->setReceiver(transMsg->getReceiver());
aMsg->setHasTimeOut(hasTimeOut);
aMsg->setHtlcIndex(transMsg->getHtlcIndex());
aMsg->setPathIndex(transMsg->getPathIndex());
aMsg->setLargerTxnId(transMsg->getLargerTxnId());
aMsg->setPriorityClass(transMsg->getPriorityClass());
aMsg->setTimeOut(transMsg->getTimeOut());
aMsg->setIsMarked(transMsg->getIsMarked());
if (!isSuccess){
aMsg->setFailedHopNum((route.size()-1) - ttmsg->getHopCount());
}
//no need to set secret - not modelled
reverse(route.begin(), route.end());
msg->setRoute(route);
//need to reverse path from current hop number in case of partial failure
msg->setHopCount((route.size()-1) - ttmsg->getHopCount());
msg->setMessageType(ACK_MSG);
ttmsg->decapsulate();
delete transMsg;
delete ttmsg;
msg->encapsulate(aMsg);
return msg;
}
/* generate a message that designates which payment channels at this router need funds
* and how much funds they need, will be processed a few seconds/minutes later to
* actually add the funds to those payment channels */
routerMsg *routerNodeBase::generateAddFundsMessage(map<int, double> fundsToBeAdded) {
char msgname[MSGSIZE];
map<int,double> pcsNeedingFunds = fundsToBeAdded;
sprintf(msgname, "addfundmessage-at-%d", myIndex());
routerMsg *msg = new routerMsg(msgname);
addFundsMsg *afMsg = new addFundsMsg(msgname);
afMsg->setPcsNeedingFunds(pcsNeedingFunds);
msg->setMessageType(ADD_FUNDS_MSG);
msg->encapsulate(afMsg);
return msg;
}
/****** MESSAGE FORWARDERS ********/
/* responsible for forwarding all messages but transactions which need special care
* in particular, looks up the next node's interface and sends out the message
*/
void routerNodeBase::forwardMessage(routerMsg* msg){
msg->setHopCount(msg->getHopCount()+1);
int nextDest = msg->getRoute()[msg->getHopCount()];
if (_loggingEnabled) cout << "forwarding " << msg->getMessageType() << " at "
<< simTime() << endl;
send(msg, nodeToPaymentChannel[nextDest].gate);
}
/*
* Given a message representing a TransUnit, increments hopCount, finds next destination,
* adjusts (decrements) channel balance, sends message to next node on route
* as long as it isn't cancelled
*/
int routerNodeBase::forwardTransactionMessage(routerMsg *msg, int neighborIdx, simtime_t arrivalTime) {
transactionMsg *transMsg = check_and_cast<transactionMsg *>(msg->getEncapsulatedPacket());
int nextDest = neighborIdx;
int transactionId = transMsg->getTransactionId();
PaymentChannel *neighbor = &(nodeToPaymentChannel[nextDest]);
int amt = transMsg->getAmount();
// return true directly if txn has been cancelled
// so that you waste not resources on this and move on to a new txn
// if you return false processTransUnits won't look for more txns
auto iter = canceledTransactions.find(make_tuple(transactionId, 0, 0, 0, 0));
if (iter != canceledTransactions.end()) {
msg->decapsulate();
delete transMsg;
delete msg;
neighbor->totalAmtInQueue -= amt;
return 1;
}
if (neighbor->balance <= 0 || transMsg->getAmount() > neighbor->balance){
return 0;
}
else {
// update state to send transaction out
msg->setHopCount(msg->getHopCount()+1);
// update service arrival times
neighbor->serviceArrivalTimeStamps.push_back(make_tuple(transMsg->getAmount(), simTime(), arrivalTime));
neighbor->sumServiceWindowTxns += transMsg->getAmount();
if (neighbor->serviceArrivalTimeStamps.size() > _serviceArrivalWindow) {
double frontAmt = get<0>(neighbor->serviceArrivalTimeStamps.front());
neighbor->serviceArrivalTimeStamps.pop_front();
neighbor->sumServiceWindowTxns -= frontAmt;
}
// add amount to outgoing map, mark time sent
Id thisTrans = make_tuple(transMsg->getTransactionId(), transMsg->getHtlcIndex());
(neighbor->outgoingTransUnits)[thisTrans] = transMsg->getAmount();
neighbor->txnSentTimes[thisTrans] = simTime();
neighbor->totalAmtOutgoingInflight += transMsg->getAmount();
// update balance
double newBalance = neighbor->balance - amt;
setPaymentChannelBalanceByNode(nextDest, newBalance);
neighbor-> balanceEWMA = (1 -_ewmaFactor) * neighbor->balanceEWMA +
(_ewmaFactor) * newBalance;
neighbor->totalAmtInQueue -= amt;
if (_loggingEnabled) cout << "forwardTransactionMsg send: " << simTime() << endl;
send(msg, nodeToPaymentChannel[nextDest].gate);
return 1;
}
}
/* overall controller for handling messages that dispatches the right function
* based on message type
*/
void routerNodeBase::handleMessage(cMessage *msg){
routerMsg *ttmsg = check_and_cast<routerMsg *>(msg);
if (simTime() > _simulationLength){
auto encapMsg = (ttmsg->getEncapsulatedPacket());
ttmsg->decapsulate();
delete ttmsg;
delete encapMsg;
return;
}
// handle all messges by type
switch (ttmsg->getMessageType()) {
case ACK_MSG:
if (_loggingEnabled)
cout << "[ROUTER "<< myIndex() <<": RECEIVED ACK MSG] " << msg->getName() << endl;
if (_timeoutEnabled)
handleAckMessageTimeOut(ttmsg);
handleAckMessage(ttmsg);
if (_loggingEnabled) cout << "[AFTER HANDLING:]" <<endl;
break;
case TRANSACTION_MSG:
{
if (_loggingEnabled)
cout<< "[ROUTER "<< myIndex() <<": RECEIVED TRANSACTION MSG] "
<< msg->getName() <<endl;
if (_timeoutEnabled && handleTransactionMessageTimeOut(ttmsg)){
return;
}
handleTransactionMessage(ttmsg);
if (_loggingEnabled) cout << "[AFTER HANDLING:]" << endl;
}
break;
case UPDATE_MSG:
if (_loggingEnabled) cout<< "[ROUTER "<< myIndex()
<<": RECEIVED UPDATE MSG] "<< msg->getName() << endl;
handleUpdateMessage(ttmsg);
if (_loggingEnabled) cout<< "[AFTER HANDLING:] "<< endl;
break;
case STAT_MSG:
if (_loggingEnabled) cout<< "[ROUTER "<< myIndex()
<<": RECEIVED STAT MSG] "<< msg->getName() << endl;
handleStatMessage(ttmsg);
if (_loggingEnabled) cout<< "[AFTER HANDLING:] "<< endl;
break;
case TIME_OUT_MSG:
if (_loggingEnabled) cout<< "[ROUTER "<< myIndex()
<<": RECEIVED TIME_OUT_MSG] "<< msg->getName() << endl;
if (!_timeoutEnabled){
cout << "timeout message generated when it shouldn't have" << endl;
return;
}
handleTimeOutMessage(ttmsg);
if (_loggingEnabled) cout<< "[AFTER HANDLING:] "<< endl;
break;
case CLEAR_STATE_MSG:
if (_loggingEnabled) cout<< "[ROUTER "<< myIndex()
<<": RECEIVED CLEAR_STATE_MSG] "<< msg->getName() << endl;
handleClearStateMessage(ttmsg);
if (_loggingEnabled) cout<< "[AFTER HANDLING:] "<< endl;
break;
case COMPUTE_BALANCE_MSG:
if (_loggingEnabled) cout<< "[ROUTER "<< myIndex()
<<": RECEIVED COMPUTE BALANCE MSG] "<< msg->getName() << endl;
handleComputeMinAvailableBalanceMessage(ttmsg);
if (_loggingEnabled) cout<< "[AFTER HANDLING:] "<< endl;
break;
default:
handleMessage(ttmsg);
}
}
/* Main handler for normal processing of a transaction
* checks if message has reached sender
* 1. has reached (is in rev direction) - turn transactionMsg into ackMsg, forward ackMsg
* 2. has not reached yet - add to appropriate job queue q, process q as
* much as we have funds for
*/
void routerNodeBase::handleTransactionMessage(routerMsg* ttmsg) {
transactionMsg *transMsg = check_and_cast<transactionMsg *>(ttmsg->getEncapsulatedPacket());
int hopcount = ttmsg->getHopCount();
vector<tuple<int, double , routerMsg *, Id, simtime_t>> *q;
int destination = transMsg->getReceiver();
int transactionId = transMsg->getTransactionId();
// ignore if txn is already cancelled
auto iter = canceledTransactions.find(make_tuple(transactionId, 0, 0, 0, 0));
if ( iter!=canceledTransactions.end() ){
ttmsg->decapsulate();
delete transMsg;
delete ttmsg;
return;
}
// add to incoming trans units
int prevNode = ttmsg->getRoute()[ttmsg->getHopCount()-1];
unordered_map<Id, double, hashId> *incomingTransUnits =
&(nodeToPaymentChannel[prevNode].incomingTransUnits);
(*incomingTransUnits)[make_tuple(transMsg->getTransactionId(), transMsg->getHtlcIndex())] =
transMsg->getAmount();
nodeToPaymentChannel[prevNode].totalAmtIncomingInflight += transMsg->getAmount();
// find the outgoing channel to check capacity/ability to send on it
int nextNode = ttmsg->getRoute()[hopcount+1];
PaymentChannel *neighbor = &(nodeToPaymentChannel[nextNode]);
q = &(neighbor->queuedTransUnits);
// mark the arrival on this payment channel
neighbor->arrivalTimeStamps.push_back(make_tuple(transMsg->getAmount(), simTime()));
neighbor->sumArrivalWindowTxns += transMsg->getAmount();
if (neighbor->arrivalTimeStamps.size() > _serviceArrivalWindow) {
double frontAmt = get<0>(neighbor->serviceArrivalTimeStamps.front());
neighbor->arrivalTimeStamps.pop_front();
neighbor->sumArrivalWindowTxns -= frontAmt;
}
// if balance is insufficient at the first node, return failure ack
if (_hasQueueCapacity && _queueCapacity == 0) {
if (forwardTransactionMessage(ttmsg, nextNode, simTime()) == 0) {
routerMsg * failedAckMsg = generateAckMessage(ttmsg, false);
handleAckMessage(failedAckMsg);
}
} else if (_hasQueueCapacity && _queueCapacity<= getTotalAmount(nextNode)) {
//failed transaction, queue at capacity, others are in queue so no point trying this txn
routerMsg * failedAckMsg = generateAckMessage(ttmsg, false);
handleAckMessage(failedAckMsg);
} else {
// add to queue and process in order of priority
(*q).push_back(make_tuple(transMsg->getPriorityClass(), transMsg->getAmount(),
ttmsg, make_tuple(transMsg->getTransactionId(), transMsg->getHtlcIndex()), simTime()));
neighbor->totalAmtInQueue += transMsg->getAmount();
push_heap((*q).begin(), (*q).end(), _schedulingAlgorithm);
processTransUnits(nextNode, *q);
}
}
/* handler responsible for prematurely terminating the processing
* of a transaction if it has timed out and deleteing it. Returns
* true if the transaction is timed out so that no special handlers
* are called after
*/
bool routerNodeBase::handleTransactionMessageTimeOut(routerMsg* ttmsg) {
transactionMsg *transMsg = check_and_cast<transactionMsg *>(ttmsg->getEncapsulatedPacket());
int transactionId = transMsg->getTransactionId();
auto iter = canceledTransactions.find(make_tuple(transactionId, 0, 0, 0, 0));
if (iter != canceledTransactions.end() ){
ttmsg->decapsulate();
delete transMsg;
delete ttmsg;
return true;
}
else{
return false;
}
}
/* Default action for time out message that is responsible for either recognizing
* that txn is complete and timeout is a noop or inserting the transaction into
* a cancelled transaction list
* The actual cancellation/clearing of the state happens on the clear state
* message
* Will only be encountered in forward direction
*/
void routerNodeBase::handleTimeOutMessage(routerMsg* ttmsg){
timeOutMsg *toutMsg = check_and_cast<timeOutMsg *>(ttmsg->getEncapsulatedPacket());
int nextNode = (ttmsg->getRoute())[ttmsg->getHopCount()+1];
int prevNode = (ttmsg->getRoute())[ttmsg->getHopCount()-1];
CanceledTrans ct = make_tuple(toutMsg->getTransactionId(), simTime(),
prevNode, nextNode, toutMsg->getReceiver());
canceledTransactions.insert(ct);
forwardMessage(ttmsg);
}
/* default routine for handling an ack that is responsible for
* updating outgoing transunits and incoming trans units
* and triggering an update message to the next node on the path
* before forwarding the ack back to the previous node
*/
void routerNodeBase::handleAckMessage(routerMsg* ttmsg){
assert(myIndex() == ttmsg->getRoute()[ttmsg->getHopCount()]);
ackMsg *aMsg = check_and_cast<ackMsg *>(ttmsg->getEncapsulatedPacket());
// this is previous node on the ack path, so next node on the forward path
// remove txn from outgone txn list
Id thisTrans = make_tuple(aMsg->getTransactionId(), aMsg->getHtlcIndex());
int prevNode = ttmsg->getRoute()[ttmsg->getHopCount()-1];
PaymentChannel *prevChannel = &(nodeToPaymentChannel[prevNode]);
double timeInflight = (simTime() - prevChannel->txnSentTimes[thisTrans]).dbl();
(prevChannel->outgoingTransUnits).erase(thisTrans);
(prevChannel->txnSentTimes).erase(thisTrans);
int transactionId = aMsg->getTransactionId();
if (aMsg->getIsSuccess() == false){
// increment funds on this channel unless this is the node that caused the fauilure
// in which case funds were never decremented in the first place
if (aMsg->getFailedHopNum() < ttmsg->getHopCount()) {
double updatedBalance = prevChannel->balance + aMsg->getAmount();
prevChannel->balanceEWMA =
(1 -_ewmaFactor) * prevChannel->balanceEWMA + (_ewmaFactor) * updatedBalance;
prevChannel->totalAmtOutgoingInflight -= aMsg->getAmount();
setPaymentChannelBalanceByNode(prevNode, updatedBalance);
}
// this is nextNode on the ack path and so prev node in the forward path or rather
// node sending you mayments
int nextNode = ttmsg->getRoute()[ttmsg->getHopCount()+1];
unordered_map<Id, double, hashId> *incomingTransUnits =
&(nodeToPaymentChannel[nextNode].incomingTransUnits);
(*incomingTransUnits).erase(make_tuple(aMsg->getTransactionId(), aMsg->getHtlcIndex()));
nodeToPaymentChannel[nextNode].totalAmtIncomingInflight -= aMsg->getAmount();
}
else {
// mark the time it spent inflight
routerMsg* uMsg = generateUpdateMessage(aMsg->getTransactionId(), prevNode,
aMsg->getAmount(), aMsg->getHtlcIndex() );
prevChannel->sumTimeInFlight += timeInflight;
prevChannel->timeInFlightSamples += 1;
prevChannel->totalAmtOutgoingInflight -= aMsg->getAmount();
prevChannel->numUpdateMessages += 1;
forwardMessage(uMsg);
amtSuccessfulSoFar += aMsg->getAmount();
if (amtSuccessfulSoFar > _rebalanceRate && _rebalancingEnabled) {
amtSuccessfulSoFar = 0;
performRebalancing();
}
}
forwardMessage(ttmsg);
}
/* handles the logic for ack messages in the presence of timeouts
* in particular, removes the transaction from the cancelled txns
* to mark that it has been received
*/
void routerNodeBase::handleAckMessageTimeOut(routerMsg* ttmsg){
ackMsg *aMsg = check_and_cast<ackMsg *>(ttmsg->getEncapsulatedPacket());
int transactionId = aMsg->getTransactionId();
auto iter = canceledTransactions.find(make_tuple(transactionId, 0, 0, 0, 0));
if (iter != canceledTransactions.end()) {
canceledTransactions.erase(iter);
}
}
/* handleUpdateMessage - called when receive update message, increment back funds, see if we can
* process more jobs with new funds, delete update message
*/
void routerNodeBase::handleUpdateMessage(routerMsg* msg) {
vector<tuple<int, double , routerMsg *, Id, simtime_t>> *q;
int prevNode = msg->getRoute()[msg->getHopCount()-1];
updateMsg *uMsg = check_and_cast<updateMsg *>(msg->getEncapsulatedPacket());
PaymentChannel *prevChannel = &(nodeToPaymentChannel[prevNode]);
// remove transaction from incoming_trans_units
unordered_map<Id, double, hashId> *incomingTransUnits = &(prevChannel->incomingTransUnits);
(*incomingTransUnits).erase(make_tuple(uMsg->getTransactionId(), uMsg->getHtlcIndex()));
prevChannel->totalAmtIncomingInflight -= uMsg->getAmount();
// increment the in flight funds back
double newBalance = prevChannel->balance + uMsg->getAmount();
setPaymentChannelBalanceByNode(prevNode, newBalance);
prevChannel->balanceEWMA = (1 -_ewmaFactor) * prevChannel->balanceEWMA
+ (_ewmaFactor) * newBalance;
msg->decapsulate();
delete uMsg;
delete msg; //delete update message
// see if we can send more jobs out
q = &(prevChannel->queuedTransUnits);
processTransUnits(prevNode, *q);
}
/* handler that periodically computes the minimum balance on a payment channel
* this is then used accordingly to trigger rebalancing events */
void routerNodeBase::handleComputeMinAvailableBalanceMessage(routerMsg* ttmsg) {
// reschedule this message to be sent again
if (simTime() > _simulationLength || !_rebalancingEnabled) {
delete ttmsg;
}
else {
scheduleAt(simTime()+_computeBalanceRate, ttmsg);
}
for (auto it = nodeToPaymentChannel.begin(); it!= nodeToPaymentChannel.end(); it++){
PaymentChannel *p = &(it->second);
if (p->balance < p->minAvailBalance)
p->minAvailBalance = p->balance;
}
}
/* handler for the periodic rebalancing message that gets triggered
* that is responsible for equalizing the available balance across all of the
* payment channels of a given router
*/
void routerNodeBase::performRebalancing() {
// compute avalable stash to redistribute
double stash = 0.0;
int numChannels = 0;
for (auto it = nodeToPaymentChannel.begin(); it!= nodeToPaymentChannel.end(); it++){
PaymentChannel *p = &(it->second);
stash += p->balance;
numChannels += 1;
}
// figure out how much to give each channel
double targetBalancePerChannel = int(stash/numChannels); // target will always be lower as a result
double totalToRemove = 0;
map<int, double> pcsNeedingFunds;
for (auto it = nodeToPaymentChannel.begin(); it!= nodeToPaymentChannel.end(); it++){
int id = it->first;
PaymentChannel *p = &(it->second);
double differential = p->balance - targetBalancePerChannel;
if (differential < 0) {
// add this to the list of payment channels to be addressed
// along with a particular addFundsEvent
pcsNeedingFunds[id] = -1 * differential;
totalToRemove += -1 * differential;
}
}
// make sure the amount given is appropriately removed from other channels
for (auto it = nodeToPaymentChannel.begin(); it!= nodeToPaymentChannel.end(); it++){
int id = it->first;
PaymentChannel *p = &(it->second);
double differential = min(totalToRemove, p->balance - targetBalancePerChannel);
if (differential > 0) {
// remove capacity immediately from these channel
setPaymentChannelBalanceByNode(it->first, p->balance - differential);
p->balanceEWMA -= differential;
p->amtExplicitlyRebalanced -= differential;
if (simTime() > _transStatStart && simTime() < _transStatEnd) {
p->amtAdded += differential;
p->numRebalanceEvents += 1;
}
totalToRemove -= differential;
if (p->balance < 0)
cout << "terrible: " << differential << " balance " << p->balance << "min available balance "
<< p->minAvailBalance << endl;
tuple<int, int> senderReceiverTuple = (id < myIndex()) ? make_tuple(id, myIndex()) :
make_tuple(myIndex(), id);
_capacities[senderReceiverTuple] -= differential;
}
p->minAvailBalance = 1000000;
}
// generate and schedule add funds message to add these funds after some fixed time period
if (pcsNeedingFunds.size() > 0) {
addFunds(pcsNeedingFunds);
}
}
/* handler to add the desired amount of funds to the given payment channels when an addFundsMessage
* is received
*/
void routerNodeBase::addFunds(map<int, double> pcsNeedingFunds) {
for (auto it = pcsNeedingFunds.begin(); it!= pcsNeedingFunds.end(); it++) {
int pcIdentifier = it->first;
double fundsToAdd = it->second;
PaymentChannel *p = &(nodeToPaymentChannel[pcIdentifier]);
// add funds at this end
setPaymentChannelBalanceByNode(pcIdentifier, p->balance+fundsToAdd);
p->balanceEWMA += fundsToAdd;
tuple<int, int> senderReceiverTuple = (pcIdentifier < myIndex()) ? make_tuple(pcIdentifier, myIndex()) :
make_tuple(myIndex(), pcIdentifier);
_capacities[senderReceiverTuple] += fundsToAdd;
// track statistics
if (simTime() > _transStatStart && simTime() < _transStatEnd) {
p->numRebalanceEvents += 1;
p->amtAdded += fundsToAdd;
}
p->amtExplicitlyRebalanced += fundsToAdd;
// process as many new transUnits as you can for this payment channel
processTransUnits(pcIdentifier, p->queuedTransUnits);
}
}
/* emits all the default statistics across all the schemes
* until the end of the simulation
*/
void routerNodeBase::handleStatMessage(routerMsg* ttmsg){
if (simTime() > _simulationLength){
delete ttmsg;
}
else {
scheduleAt(simTime()+_statRate, ttmsg);
}
// per channel Stats
for (auto it = nodeToPaymentChannel.begin(); it!= nodeToPaymentChannel.end(); it++){
PaymentChannel *p = &(it->second);
int id = it->first;
if (simTime() > _transStatStart && simTime() < _transStatEnd)
p->queueSizeSum += getTotalAmount(it->first);
if (_signalsEnabled) {
emit(p->amtInQueuePerChannelSignal, getTotalAmount(it->first));
emit(p->balancePerChannelSignal, p->balance);
emit(p->numInflightPerChannelSignal, getTotalAmountIncomingInflight(it->first) +
getTotalAmountOutgoingInflight(it->first));
emit(p->queueDelayEWMASignal, p->queueDelayEWMA);
tuple<int, int> senderReceiverTuple = (id < myIndex()) ? make_tuple(id, myIndex()) :
make_tuple(myIndex(), id);
emit(p->capacityPerChannelSignal, _capacities[senderReceiverTuple]);
emit(p->explicitRebalancingAmtPerChannelSignal, p->amtExplicitlyRebalanced/_statRate);
emit(p->implicitRebalancingAmtPerChannelSignal, p->amtImplicitlyRebalanced/_statRate);
p->amtExplicitlyRebalanced = 0;
p->amtImplicitlyRebalanced = 0;
emit(p->timeInFlightPerChannelSignal, p->sumTimeInFlight/p->timeInFlightSamples);
p->sumTimeInFlight = 0;
p->timeInFlightSamples = 0;
}
}
}
/* handler that is responsible for removing all the state associated
* with a cancelled transaction once its grace period has passed
* this included removal from outgoing/incoming units and any
* queues
*/
void routerNodeBase::handleClearStateMessage(routerMsg* ttmsg){
if (simTime() > _simulationLength){
delete ttmsg;
}
else{
scheduleAt(simTime()+_clearRate, ttmsg);
}
for ( auto it = canceledTransactions.begin(); it!= canceledTransactions.end(); ) {
int transactionId = get<0>(*it);
simtime_t msgArrivalTime = get<1>(*it);
int prevNode = get<2>(*it);
int nextNode = get<3>(*it);
int destNode = get<4>(*it);
// if grace period has passed
if (simTime() > (msgArrivalTime + _maxTravelTime)){
if (nextNode != -1) {
vector<tuple<int, double, routerMsg*, Id, simtime_t>>* queuedTransUnits =
&(nodeToPaymentChannel[nextNode].queuedTransUnits);
auto iterQueue = find_if((*queuedTransUnits).begin(),
(*queuedTransUnits).end(),
[&transactionId](const tuple<int, double, routerMsg*, Id, simtime_t>& p)
{ return (get<0>(get<3>(p)) == transactionId); });
// delete all occurences of this transaction in the queue
// especially if there are splits
if (iterQueue != (*queuedTransUnits).end()){
routerMsg * rMsg = get<2>(*iterQueue);
auto tMsg = rMsg->getEncapsulatedPacket();
rMsg->decapsulate();
delete tMsg;
delete rMsg;
nodeToPaymentChannel[nextNode].totalAmtInQueue -= get<1>(*iterQueue);
iterQueue = (*queuedTransUnits).erase(iterQueue);
}
make_heap((*queuedTransUnits).begin(), (*queuedTransUnits).end(),
_schedulingAlgorithm);
}
// remove from incoming TransUnits from the previous node
if (prevNode != -1) {
unordered_map<Id, double, hashId> *incomingTransUnits =
&(nodeToPaymentChannel[prevNode].incomingTransUnits);
auto iterIncoming = find_if((*incomingTransUnits).begin(),
(*incomingTransUnits).end(),
[&transactionId](const pair<tuple<int, int >, double> & p)
{ return get<0>(p.first) == transactionId; });
if (iterIncoming != (*incomingTransUnits).end()){
nodeToPaymentChannel[prevNode].totalAmtIncomingInflight -= iterIncoming->second;
iterIncoming = (*incomingTransUnits).erase(iterIncoming);
}
}
}
// remove from outgoing transUnits to nextNode and restore balance on own end
if (simTime() > (msgArrivalTime + _maxTravelTime + _maxOneHopDelay)) {
if (nextNode != -1) {
unordered_map<Id, double, hashId> *outgoingTransUnits =
&(nodeToPaymentChannel[nextNode].outgoingTransUnits);
auto iterOutgoing = find_if((*outgoingTransUnits).begin(),
(*outgoingTransUnits).end(),
[&transactionId](const pair<tuple<int, int >, double> & p)
{ return get<0>(p.first) == transactionId; });
if (iterOutgoing != (*outgoingTransUnits).end()){
double amount = iterOutgoing -> second;
iterOutgoing = (*outgoingTransUnits).erase(iterOutgoing);
PaymentChannel *nextChannel = &(nodeToPaymentChannel[nextNode]);
nextChannel->totalAmtOutgoingInflight -= amount;
double updatedBalance = nextChannel->balance + amount;
setPaymentChannelBalanceByNode(nextNode, updatedBalance);
nextChannel->balanceEWMA = (1 -_ewmaFactor) * nextChannel->balanceEWMA +
(_ewmaFactor) * updatedBalance;
}
}
// all done, can remove txn and update stats
it = canceledTransactions.erase(it);
}
else{
it++;
}
}
}
/* helper method to set a particular payment channel's balance to the passed in amount
*/
void routerNodeBase::setPaymentChannelBalanceByNode(int node, double amt) {
nodeToPaymentChannel[node].balance = amt;
}
| 41.011538 | 112 | 0.647262 | aakritanshuman |
e02014b05501991553ac371e36e42e20de9e0a15 | 222 | cpp | C++ | Leetcode/2001-3000/2239. Find Closest Number to Zero/2239.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/2001-3000/2239. Find Closest Number to Zero/2239.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/2001-3000/2239. Find Closest Number to Zero/2239.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | class Solution {
public:
int findClosestNumber(vector<int>& nums) {
return *min_element(begin(nums), end(nums), [](const int a, const int b) {
return abs(a) == abs(b) ? a > b : abs(a) < abs(b);
});
}
};
| 24.666667 | 78 | 0.572072 | Next-Gen-UI |
e020dbb997287980cb17e804366dd87eb2338188 | 108 | cpp | C++ | ro-string-db/string_pool/run_local_tests.cpp | vladcc/ro-string-db | 6f27a71e583f1816277c4027b51fe45c29e017fd | [
"MIT"
] | 1 | 2020-09-20T22:12:53.000Z | 2020-09-20T22:12:53.000Z | ro-string-db/string_pool/run_local_tests.cpp | vladcc/ro-string-db | 6f27a71e583f1816277c4027b51fe45c29e017fd | [
"MIT"
] | null | null | null | ro-string-db/string_pool/run_local_tests.cpp | vladcc/ro-string-db | 6f27a71e583f1816277c4027b51fe45c29e017fd | [
"MIT"
] | null | null | null | #include "test_string_pool.hpp"
int main()
{
run_test_string_pool();
return test_string_pool_failed();
}
| 13.5 | 34 | 0.759259 | vladcc |
e0249a262cd61106e21005cfabe5f19fb889e8a7 | 1,456 | cpp | C++ | 3DLfC4D shaders/source/DL_Principled_Object.cpp | FilipMalmberg/3Delight-for-Cinema-4D | 3394f8cd9e1121b8c35aa4e2b2443450ef82cbff | [
"MIT"
] | null | null | null | 3DLfC4D shaders/source/DL_Principled_Object.cpp | FilipMalmberg/3Delight-for-Cinema-4D | 3394f8cd9e1121b8c35aa4e2b2443450ef82cbff | [
"MIT"
] | null | null | null | 3DLfC4D shaders/source/DL_Principled_Object.cpp | FilipMalmberg/3Delight-for-Cinema-4D | 3394f8cd9e1121b8c35aa4e2b2443450ef82cbff | [
"MIT"
] | null | null | null | #include "c4d.h"
#include "IDs.h"
/*
We want our shaders to be directly on the create menu of materials
instead of being on create->shader->YourShaderDir->yourShader
to do so we use C4DPL_BUILDMENU to dynamically enhance the menu
In C4D you can only call objects or commands to C4DPL_BUILDMENU.
But cinema4d register an object or command using RegisterObjectPlugin()
and RegisterCommnadPlugin() and we have used RegisterMaterialPlugin()
to register our Dl_principled shader so we can not call it on C4DPL_BUILDMENU
because it does not have a command created for it/
Thus we create this Command plugin and we use it on C4DPL_BUILDMENU to add it
to the create menu of materials. And each time this class is called we create a new
Dl_Principled material. Meanwhile we have hidden Dl_Principled material from
create->shader->3Delight->Dl_Principled because we are calling it directly
using this class and in an easier way from UI part.
*/
class DL_Principled_command : public CommandData
{
public:
virtual Bool Execute(BaseDocument* doc);
};
Bool DL_Principled_command::Execute(BaseDocument* doc)
{
Material* material = (Material*)BaseMaterial::Alloc(DL_PRINCIPLED);
if (!material)
return false;
doc->InsertMaterial(material);
return true;
}
Bool Register_DlPrincipled_Object(void)
{
return RegisterCommandPlugin(DL_PRINCIPLED_COMMAND, "3Delight Principled"_s, PLUGINFLAG_HIDE, 0, String(),NewObjClear(DL_Principled_command));
}
| 33.860465 | 143 | 0.791896 | FilipMalmberg |
e024cf04b6e9269577717c77c6dc6388843a8cc2 | 1,904 | hpp | C++ | library/include/darcel/data_types/callable_data_type.hpp | spiretrading/darcel | a9c32989ad9c1571edaa41c7c3a86b276b782c0d | [
"MIT"
] | null | null | null | library/include/darcel/data_types/callable_data_type.hpp | spiretrading/darcel | a9c32989ad9c1571edaa41c7c3a86b276b782c0d | [
"MIT"
] | null | null | null | library/include/darcel/data_types/callable_data_type.hpp | spiretrading/darcel | a9c32989ad9c1571edaa41c7c3a86b276b782c0d | [
"MIT"
] | 1 | 2020-04-17T13:25:25.000Z | 2020-04-17T13:25:25.000Z | #ifndef DARCEL_CALLABLE_DATA_TYPE_HPP
#define DARCEL_CALLABLE_DATA_TYPE_HPP
#include "darcel/data_types/data_type.hpp"
#include "darcel/data_types/data_type_visitor.hpp"
#include "darcel/data_types/data_types.hpp"
#include "darcel/semantics/function.hpp"
namespace darcel {
//! A data type used to represent all of a function declaration's overloads.
class CallableDataType final : public DataType {
public:
//! Constructs a callable data type.
/*!
\param f The function this data type represents.
*/
CallableDataType(std::shared_ptr<Function> f);
//! Returns the function represented.
const std::shared_ptr<Function> get_function() const;
const Location& get_location() const override;
const std::string& get_name() const override;
void apply(DataTypeVisitor& visitor) const override;
protected:
bool is_equal(const DataType& rhs) const override;
private:
std::string m_name;
std::shared_ptr<Function> m_function;
};
inline CallableDataType::CallableDataType(std::shared_ptr<Function> f)
: m_name("@" + f->get_name()),
m_function(std::move(f)) {}
inline const std::shared_ptr<Function>
CallableDataType::get_function() const {
return m_function;
}
inline const Location& CallableDataType::get_location() const {
return m_function->get_location();
}
inline const std::string& CallableDataType::get_name() const {
return m_name;
}
inline void CallableDataType::apply(DataTypeVisitor& visitor) const {
visitor.visit(*this);
}
inline bool CallableDataType::is_equal(const DataType& rhs) const {
auto& other = static_cast<const CallableDataType&>(rhs);
return m_function == other.get_function();
}
inline void DataTypeVisitor::visit(const CallableDataType& node) {
visit(static_cast<const DataType&>(node));
}
}
#endif
| 27.594203 | 78 | 0.707458 | spiretrading |
e02b48f54b5e5ee32c43890c1ec0aa11543fe7a8 | 7,990 | cpp | C++ | os/internal/threads.cpp | JehTeh/jel | 2c43cf23ea7b89e7ec0f7c2e9549be74ab0bbc4b | [
"MIT"
] | 14 | 2018-10-09T00:08:26.000Z | 2021-09-24T19:49:42.000Z | os/internal/threads.cpp | JehTeh/jel | 2c43cf23ea7b89e7ec0f7c2e9549be74ab0bbc4b | [
"MIT"
] | null | null | null | os/internal/threads.cpp | JehTeh/jel | 2c43cf23ea7b89e7ec0f7c2e9549be74ab0bbc4b | [
"MIT"
] | null | null | null | /** @file os/internal/threads.cpp
* @brief Implementation of the threading wrappers for jel.
*
* @detail
* The Thread wrappers used by the jel perform two functions: Abstracting the C API of the RTOS
* and providing some additional setup and teardown capability, such as exception capture. This
* is done by wrapping the user supplied function and void* arg pointer in a custom dispatcher
* function that accepts a pointer to the Thread object itself, where the user supplied function
* and arg pointers are stored. The call to this function is then wrapped by the dispatcher with
* all needed functionality, including global try/catch guards and any instrumentation that is
* enabled.
*
* @author Jonathan Thomson
*/
/**
* MIT License
*
* Copyright 2018, Jonathan Thomson
*
* 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.
*/
/** C/C++ Standard Library Headers */
#include <cassert>
/** jel Library Headers */
#include "os/api_threads.hpp"
#include "os/api_exceptions.hpp"
#include "os/api_system.hpp"
#include "os/internal/indef.hpp"
namespace jel
{
GenericThread_Base::GenericThread_Base()
{
/** Nothing is done here. All initialization is performed in the startThread() function to ensure
* the Thread* object has completed construction. */
}
void GenericThread_Base::startThread(Thread* threadObject)
{
Thread::ThreadInfo* inf = threadObject->inf_.get();
inf->handle_ = nullptr;
if(inf->cbMem_ && inf->stackMem_)
{
assert(false); //Static thread construction is currently TODO - not simple with freeRTOS, self
//deleting tasks run into issues with memory ownership when idle task attempts to delete them.
}
else
{
//Create with minimum priority. This allows us to insert thread into the ireg_ before it
//executes.
if(xTaskCreate(reinterpret_cast<void(*)(void*)>(&dispatcher),
inf->name_, inf->maxStack_bytes_ / 4 + (inf->maxStack_bytes_ % 4), inf,
static_cast<uint32_t>(Thread::Priority::minimum),
&inf->handle_) != pdPASS)
{
throw Exception{ExceptionCode::threadConstructionFailed,
"Failed to allocate the required memory when constructing a new Thread."};
}
#ifdef ENABLE_THREAD_STATISTICS
Thread::ireg_->push_back(inf);
#endif
vTaskPrioritySet(inf->handle_, static_cast<uint32_t>(inf->priority_));
}
}
void GenericThread_Base::dispatcher(void* threadInf)
{
Thread::ThreadInfo* inf = reinterpret_cast<Thread::ThreadInfo*>(threadInf);
inf->handle_ = xTaskGetCurrentTaskHandle();
#ifdef ENABLE_THREAD_STATISTICS
inf->totalRuntime_ = Duration::zero();
inf->lastEntry_ = SteadyClock::now();
#endif
try
{
inf->userFunc_(inf->userArgPtr_);
}
catch(const std::exception e)
{
switch(inf->ehPolicy_)
{
case Thread::ExceptionHandlerPolicy::haltThread:
{
while(true)
{
ThisThread::sleepfor(Duration::seconds(1));
}
}
break;
case Thread::ExceptionHandlerPolicy::terminate:
std::terminate();
}
}
catch(...)
{
switch(inf->ehPolicy_)
{
case Thread::ExceptionHandlerPolicy::haltThread:
{
while(true)
{
ThisThread::sleepfor(Duration::seconds(1));
}
}
break;
case Thread::ExceptionHandlerPolicy::terminate:
std::terminate();
}
}
if(inf->isDetached_)
{
#ifdef ENABLE_THREAD_STATISTICS
for(auto it = Thread::ireg_->begin(); it != Thread::ireg_->end(); it++)
{
if((*it)->handle_ == inf->handle_)
{
Thread::ireg_->erase(it);
}
}
#endif
delete inf;
}
}
#ifdef ENABLE_THREAD_STATISTICS
std::unique_ptr<Thread::InfoRegistry> Thread::ireg_;
#endif
Thread::Thread(FunctionSignature userFunction, void* args, const char* name,
const size_t stackSize_bytes, const Priority priority, const ExceptionHandlerPolicy ehPolicy)
{
//Allocate and configure inf_ structure. This needs to be seperate from the thread object so that
//if the thread is detached the inf_ still exists.
inf_ = std::make_unique<ThreadInfo>();
inf_->userFunc_ = userFunction; inf_->userArgPtr_ = args; inf_->name_ = name;
inf_->maxStack_bytes_ = stackSize_bytes; inf_->priority_ = priority; inf_->ehPolicy_ = ehPolicy;
inf_->isDetached_ = false; inf_->isDeleted_ = false;
inf_->cbMem_ = nullptr; inf_->stackMem_ = nullptr;
#ifdef ENABLE_THREAD_STATISTICS
inf_->totalRuntime_ = Duration::zero();
inf_->lastEntry_ = Timestamp::min();
if(Thread::ireg_ == nullptr)
{
Thread::ireg_ = std::make_unique<Thread::InfoRegistry>();
}
#endif
startThread(this);
}
Thread::~Thread() noexcept
{
if(inf_ != nullptr)
{
#ifdef ENABLE_THREAD_STATISTICS
for(auto it = Thread::ireg_->begin(); it != Thread::ireg_->end(); it++)
{
if((*it)->handle_ == inf_->handle_)
{
Thread::ireg_->erase(it);
}
}
#endif
if(inf_->handle_ != nullptr)
{
vTaskDelete(inf_->handle_);
}
inf_.reset();
}
}
#ifdef ENABLE_THREAD_STATISTICS
void Thread::schedulerEntry(Handle handle)
{
for(ThreadInfo* it : *ireg_)
{
if(it->handle_ == handle)
{
it->lastEntry_ = SteadyClock::now();
break;
}
}
}
void Thread::schedulerExit(Handle handle)
{
for(ThreadInfo* it : *ireg_)
{
if(it->handle_ == handle)
{
it->totalRuntime_ += SteadyClock::now() - it->lastEntry_;
break;
}
}
}
void Thread::schedulerThreadCreation(Handle)
{
}
void Thread::schedulerAddIdleTask(Handle h, ThreadInfo* inf)
{
(void)h; //Handle no longer used after refactoring from std::map to vector.
if(ireg_ == nullptr)
{
ireg_ = std::make_unique<InfoRegistry>();
}
ireg_->push_back(inf);
}
#endif
const char* Thread::lookupName(const Handle& handle)
{
return pcTaskGetName(handle);
}
void Thread::detach()
{
inf_->isDetached_ = true;
inf_.release();
}
void ThisThread::sleepfor(const Duration& time) noexcept
{
vTaskDelay(toTicks(time));
}
void ThisThread::yield() noexcept
{
taskYIELD();
}
void ThisThread::deleteSelf(bool performCompleteErasure) noexcept
{
if(performCompleteErasure)
{
for(auto it = Thread::ireg_->begin(); it != Thread::ireg_->end(); it++)
{
if((*it)->handle_ == xTaskGetCurrentTaskHandle())
{
delete(*it);
Thread::ireg_->erase(it);
break;
}
}
}
else
{
for(auto&& it : *Thread::ireg_)
{
if(it->handle_ == xTaskGetCurrentTaskHandle())
{
it->isDeleted_ = true;
it->minStackBeforeDeletion_bytes_ = uxTaskGetStackHighWaterMark(nullptr) * 4;
break;
}
}
}
vTaskDelete(nullptr);
}
const char* ThisThread::name()
{
if(System::inIsr())
{
return "ISR";
}
if(System::cpuExceptionActive())
{
return "EXCPT";
}
return pcTaskGetName(nullptr);
}
void* ThisThread::handle()
{
return xTaskGetCurrentTaskHandle();
}
}
/** namespace jel */
| 26.993243 | 100 | 0.673967 | JehTeh |
e02b80492b11d593f0c813c15a06408f4db5b6ec | 3,948 | cpp | C++ | XYModem/examples/example_ymodem.cpp | Riuzakiii/XYModem | 97d5dba9285aaefa2668865e4088a579cccc53a7 | [
"MIT"
] | null | null | null | XYModem/examples/example_ymodem.cpp | Riuzakiii/XYModem | 97d5dba9285aaefa2668865e4088a579cccc53a7 | [
"MIT"
] | null | null | null | XYModem/examples/example_ymodem.cpp | Riuzakiii/XYModem | 97d5dba9285aaefa2668865e4088a579cccc53a7 | [
"MIT"
] | null | null | null | /*
* Usage : ./ymodem.exe -f "filepath" -port COM1
* -h : get help
* -port : the serial port of your device. If you don't add a port after this, it will display the available ports
* -f "filepath1": send file (filepath should be absolute, don't
* know what happens if the path is relative) -hex : activate the hexadecimal
* output of the messages send to the device
*/
#include "XYModem.h"
#include "Devices/SerialHandler.h"
#include "CLIParser.h"
using namespace xymodem;
int main (int argc, [[maybe_unused]] char* argv[])
{
auto serialDevice = serial::Serial ();
CLIParser cliParser;
serialDevice.setBaudrate (115200);
const uint32_t interByteTimeout = 100000;
const uint32_t readTimeoutConstant = 20;
const uint32_t readTimeoutMultiplier = 0;
const uint32_t writeTimeoutConstant = 20;
const uint32_t writeTimeoutMultiplier = 0;
serialDevice.setTimeout (interByteTimeout,
readTimeoutConstant,
readTimeoutMultiplier,
writeTimeoutConstant,
writeTimeoutMultiplier);
auto serialHandler = std::make_shared<SerialHandler>(serialDevice);
auto logger = std::make_shared<Spdlogger>();
YModemSender<xymodem::payloadSize1K> ymodem (serialHandler, logger);
std::vector<std::shared_ptr<File>> files;
bool withHex = false;
std::string lastParam;
cliParser.setCommands({
{"-h", [&logger](std::string_view){
logger->info("This program allows you to send one or more files "
"using the YModem file transfer protocol.\n Options "
":\n -h : get help \n -f \"filepath1\" -port "
"\"serial port of the device\""
"\"filepath2\" ... : send one or more files \n");}},
{"-f", [&files, &logger](std::string_view value){
logger->info (value);
files.emplace_back (std::make_shared<DesktopFile>(value.data()));
}},
{"--hex", [&withHex](std::string_view){withHex = true;}},
{"-port", [&serialDevice, &logger](std::string_view val){
logger->info ("Available devices");
const auto availablePorts = serial::list_ports ();
const auto serialPort =
std::find_if (availablePorts.begin (),
availablePorts.end (),
[&val, &logger] (auto& device) {
logger->info (device.description);
logger->info (device.port);
logger->info (device.hardware_id);
return device.port == val;
});
if (serialPort != availablePorts.end ())
{
serialDevice.setPort (serialPort->port);
serialDevice.open ();
}
else
{
logger->error ("Unable to find the requested device");
}
}}
});
try
{
// parse command line arguments and launch related commands
cliParser.parse (argc, argv);
if (!files.empty ())
{
ymodem.transmit (
files, [] (float) {}, [] () { return false; }, withHex);
}
}
catch (serial::IOException& e)
{
logger->warn (e.what ());
assert (false);
}
catch (XYModemExceptions::Timeout const& e)
{
logger->warn (e.what ());
}
catch (XYModemExceptions::CouldNotOpenFile const& e)
{
logger->warn (e.what ());
}
catch (XYModemExceptions::TransmissionAborted const& e)
{
logger->warn (e.what ());
}
catch (std::exception const& e)
{
logger->warn (e.what ());
assert (false);
}
}
| 36.220183 | 114 | 0.531408 | Riuzakiii |
e02d2784f099894e23c86d2570450059dd5d44ee | 3,978 | cpp | C++ | src/line.cpp | ansko/geom3d | a46d53d28c61491cdaeea38314da12ea00b2c3db | [
"Apache-2.0"
] | null | null | null | src/line.cpp | ansko/geom3d | a46d53d28c61491cdaeea38314da12ea00b2c3db | [
"Apache-2.0"
] | null | null | null | src/line.cpp | ansko/geom3d | a46d53d28c61491cdaeea38314da12ea00b2c3db | [
"Apache-2.0"
] | null | null | null | #include "point.hpp"
#include "line.hpp"
#include "line_segment.hpp"
#include "plane.hpp"
#include "polygon.hpp"
namespace geom3d
{
Point
Line::pt1() const
{
return pt1_;
}
Point
Line::pt2() const
{
return pt2_;
}
double
Line::distance_to(const Point &pt) const
{
double x1 = pt1_.x(), x2 = pt2_.x(), x = pt.x(),
y1 = pt1_.y(), y2 = pt2_.y(), y = pt.y(),
z1 = pt1_.z(), z2 = pt2_.z(), z = pt.z(),
dx = x2 - x1, dy = y2 - y1, dz = z2 - z1, // vec(pt1_ -> pt2_)
len = sqrt(dx*dx + dy*dy + dz*dz),
dx1 = x - x1, dy1 = y - y1, dz1 = z - z1, // vec(pt1_ -> pt)
len1 = sqrt(dx1*dx1 + dy1*dy1 + dz1*dz1);
if (almost_equal(len1) || almost_equal(len))
{
return 0;
}
double cos_angle = (dx*dx1 + dy*dy1 + dz*dz1) / len / len1,
sin_angle = sqrt(1 - cos_angle*cos_angle),
distance = len * sin_angle;
return std::abs(distance);
}
double
Line::distance_to(const LineSegment &ls) const
{
double x1t = pt1_.x(), x2t = pt2_.x(), x1o = ls.pt1().x(), x2o = ls.pt2().x(),
y1t = pt1_.y(), y2t = pt2_.y(), y1o = ls.pt1().y(), y2o = ls.pt2().y(),
z1t = pt1_.z(), z2t = pt2_.z(), z1o = ls.pt1().z(), z2o = ls.pt2().z(),
dxt = x2t - x1t, dyt = y2t - y1t, dzt = z2t - z1t,
lent = sqrt(dxt*dxt + dyt*dyt + dzt*dzt),
dxo = x2o - x1o, dyo = y2o - y1o, dzo = z2o - z1o,
leno = sqrt(dxo*dxo + dyo*dyo + dzo*dzo),
cos_angle = (dxt*dxo + dyt*dyo + dzt*dzo) / lent / leno;
if (almost_equal(std::abs(cos_angle), 1))
{ // Parallel case
return distance_to(ls.pt1());
}
// surely not parallel
// ptt(xt, yt, zt) on *this, pto(xo, yo, zo) on other;
// dxt, -dxo = x1o-x1t
// dyt, -dyo = y1o - y1t
// minimum exists, det != 0
double det = dxo*dyt - dxt*dyo,
det_alpha = dxo*(y1o-y1t) - dyo*(x1o-x1t),
det_beta = dxt*(y1o-y1t) - dyt*(x1o-x1t),
alpha = det_alpha / det,
beta = det_beta / det;
if (beta < 0.)
{
beta = 0.;
}
if (beta > 1.)
{
beta = 1.;
}
double xt = x1t + alpha*dxt, yt = y1t + alpha*dyt, zt = z1t + alpha*dzt,
xo = x1o + beta*dxo, yo = y1o + beta*dyo, zo = z1o + beta*dzo,
dx = xo - xt, dy = yo - yt, dz = zo - zt;
return sqrt(dx*dx + dy*dy + dz*dz);
}
double
Line::distance_to(const Line &l) const
{
double x1t = pt1_.x(), x2t = pt2_.x(), x1o = l.pt1().x(), x2o = l.pt2().x(),
y1t = pt1_.y(), y2t = pt2_.y(), y1o = l.pt1().y(), y2o = l.pt2().y(),
z1t = pt1_.z(), z2t = pt2_.z(), z1o = l.pt1().z(), z2o = l.pt2().z(),
dxt = x2t - x1t, dyt = y2t - y1t, dzt = z2t - z1t,
lent = sqrt(dxt*dxt + dyt*dyt + dzt*dzt),
dxo = x2o - x1o, dyo = y2o - y1o, dzo = z2o - z1o,
leno = sqrt(dxo*dxo + dyo*dyo + dzo*dzo),
cos_angle = (dxt*dxo + dyt*dyo + dzt*dzo) / lent / leno;
if (almost_equal(std::abs(cos_angle), 1))
{ // Parallel case
return distance_to(l.pt1());
}
// surely not parallel
// ptt(xt, yt, zt) on *this, pto(xo, yo, zo) on other;
// dxt, -dxo = x1o-x1t
// dyt, -dyo = y1o - y1t
// minimum exists, det != 0
double det = dxo*dyt - dxt*dyo,
det_alpha = dxo*(y1o-y1t) - dyo*(x1o-x1t),
det_beta = dxt*(y1o-y1t) - dyt*(x1o-x1t),
alpha = det_alpha / det,
beta = det_beta / det,
xt = x1t + alpha*dxt, yt = y1t + alpha*dyt, zt = z1t + alpha*dzt,
xo = x1o + beta*dxo, yo = y1o + beta*dyo, zo = z1o + beta*dzo,
dx = xo - xt, dy = yo - yt, dz = zo - zt;
return sqrt(dx*dx + dy*dy + dz*dz);
}
double
Line::distance_to(const Plane &pl) const
{
return pl.distance_to(*this);
}
double
Line::distance_to(const Polygon &poly) const
{
return poly.distance_to(*this);
}
} // ns geom3d
| 29.25 | 82 | 0.498994 | ansko |
e02dc9f6697a0d173695232b98998a6caee18cb2 | 2,127 | cpp | C++ | fasterrcnnmethod/test/src/face_det.cpp | HorizonRobotics/x2_applications | 4be5724731c8bec56b94a0a1f59c9aab7c457359 | [
"Apache-2.0"
] | 5 | 2020-01-17T10:05:55.000Z | 2020-08-24T02:36:55.000Z | fasterrcnnmethod/test/src/face_det.cpp | HorizonRobotics/x2_applications | 4be5724731c8bec56b94a0a1f59c9aab7c457359 | [
"Apache-2.0"
] | null | null | null | fasterrcnnmethod/test/src/face_det.cpp | HorizonRobotics/x2_applications | 4be5724731c8bec56b94a0a1f59c9aab7c457359 | [
"Apache-2.0"
] | 3 | 2020-02-09T10:51:38.000Z | 2021-11-05T09:50:15.000Z | //
// Created by yaoyao.sun on 2019-05-14.
// Copyright (c) 2019 Horizon Robotics. All rights reserved.
//
#include <gtest/gtest.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <fstream>
#include "yuv_utils.h"
#include "FasterRCNNMethod/dump.h"
#include "bpu_predict/bpu_io.h"
#include "horizon/vision_type/vision_type.hpp"
#include "hobotxsdk/xroc_sdk.h"
#include "opencv2/opencv.hpp"
#include "FasterRCNNMethod.h"
#include "bpu_predict/bpu_predict.h"
using HobotXRoc::BaseData;
using HobotXRoc::BaseDataPtr;
using HobotXRoc::BaseDataVector;
using HobotXRoc::InputData;
using HobotXRoc::InputDataPtr;
using HobotXRoc::XRocData;
using HobotXRoc::InputParamPtr;
using HobotXRoc::FasterRCNNMethod;
using hobot::vision::ImageFrame;
using hobot::vision::CVImageFrame;
TEST(FACE_DET_TEST, Basic) {
FasterRCNNMethod faster_rcnn_method;
std::string config_file = "./configs/face_pose_lmk_config.json";
faster_rcnn_method.Init(config_file);
std::string img_list = "./test/data/image.list";
std::ifstream ifs(img_list);
ASSERT_TRUE(ifs.is_open());
std::string input_image;
while (getline(ifs, input_image)) {
auto img_bgr = cv::imread(input_image);
std::cout << "origin image size, width: " << img_bgr.cols << ", height: " << img_bgr.rows << std::endl;
auto cv_image_frame_ptr = std::make_shared<CVImageFrame>();
cv_image_frame_ptr->img = img_bgr;
cv_image_frame_ptr->pixel_format = HorizonVisionPixelFormat::kHorizonVisionPixelFormatRawBGR;
auto xroc_img = std::make_shared<XRocData<std::shared_ptr<ImageFrame>>>();
xroc_img->value = cv_image_frame_ptr;
std::vector<std::vector<BaseDataPtr>> input;
std::vector<HobotXRoc::InputParamPtr> param;
input.resize(1);
input[0].push_back(xroc_img);
std::vector<std::vector<BaseDataPtr>> xroc_output = faster_rcnn_method.DoProcess(input, param);
ASSERT_TRUE(xroc_output.size() == 1);
auto faster_rcnn_out = xroc_output[0];
auto rects = std::static_pointer_cast<BaseDataVector>(faster_rcnn_out[0]);
ASSERT_TRUE(rects->datas_.size() == 3);
}
faster_rcnn_method.Finalize();
}
| 29.957746 | 107 | 0.740009 | HorizonRobotics |
e02de197270a1e8b93e668161b4a4dae6dc79c54 | 3,040 | cpp | C++ | Projects/ShipGame/src/Main.cpp | SemperParatusGithub/SemperGL | b2866b43224cc1afa17c7ce0445507eb4733adc8 | [
"MIT"
] | 7 | 2020-11-10T23:43:49.000Z | 2021-04-25T20:13:40.000Z | Projects/ShipGame/src/Main.cpp | SemperParatusGithub/SemperGL | b2866b43224cc1afa17c7ce0445507eb4733adc8 | [
"MIT"
] | null | null | null | Projects/ShipGame/src/Main.cpp | SemperParatusGithub/SemperGL | b2866b43224cc1afa17c7ce0445507eb4733adc8 | [
"MIT"
] | null | null | null | #include "Level.h"
enum State
{
MainMenu = 0, Playing, Dead, Close
};
int main()
{
sgl::Core::Init();
sgl::Window window("Ship Game", 1280, 720);
window.SetIcon(sgl::WindowIcon("res/icons/Icon.png"));
window.SetVsync(1);
bool fullscreen = false;
window.SetEventCallback([&](sgl::Event &e)
{
if (e.isType<sgl::KeyPressedEvent>() && e.GetKeyCode() == sgl::Key::F11)
{
if (!fullscreen) {
fullscreen = true;
window.SetFullscreen();
window.SetViewport(0, 0, window.GetWidth(), window.GetHeight());
}
else {
window.SetSize(1280, 720);
window.SetPosition({ 200.0f, 200.0f });
window.SetViewport(0, 0, 1280, 720);
fullscreen = false;
}
}
});
ImGuiIO io = ImGui::GetIO();
ImFont *font = io.Fonts->AddFontFromFileTTF("res/fonts/OpenSans/OpenSans-Bold.ttf", 120.0f);
State GameState = MainMenu;
sgl::Clock clock;
// Player
Player player;
bool respawnt = false;
// Level
Level level;
level.Reset();
// Textures
sgl::Texture backgroundTex("res/textures/Background.jpg");
// Game Loop
while (window.IsOpen())
{
auto deltaTime = clock.Restart();
sgl::ImGuiUtil::BeginFrame();
window.OnUpdate();
if (GameState == MainMenu)
{
if (sgl::Input::IsKeyPressed(sgl::Key::Space) || sgl::Input::IsMouseButtonPressed(sgl::Mouse::Button0))
GameState = Playing;
if (respawnt)
{
sgl::Clock::Sleep(500);
respawnt = false;
}
window.Clear();
auto pos = ImGui::GetWindowPos();
pos.x += window.GetWidth() * 0.5f - 300.0f;
pos.y += window.GetHeight() * 0.6f;
std::string highScore = std::string("Highscore: ") + std::to_string(player.GetHighscore());
ImGui::GetForegroundDrawList()->AddText(font, 120.0f, pos, 0xffffffff, "Click to Play!");
ImGui::GetForegroundDrawList()->AddText(font, 48.0f, ImGui::GetWindowPos(), 0xffffffff, highScore.c_str());
sgl::Renderer2D::BeginScene(0, 0, 1280, 720);
sgl::Renderer2D::DrawQuad({ 640.0f, 360.0f, 0.0f }, { 1280.0f, 720.0f }, backgroundTex);
player.OnRender();
sgl::Renderer2D::EndScene();
}
else if (GameState == Playing)
{
// Update
player.OnUpdate(deltaTime);
level.OnUpdate(deltaTime, player.GetHorizontalVelocity());
if (level.CheckForCollision(player))
GameState = Dead;
window.Clear();
// Render Score
std::string score = std::string("Score: ") + std::to_string(player.GetScore());
ImGui::GetForegroundDrawList()->AddText(font, 48.0f, ImGui::GetWindowPos(), 0xffffffff, score.c_str());
sgl::Renderer2D::BeginScene(0, 0, 1280, 720);
sgl::Renderer2D::DrawQuad( { 640.0f, 360.0f, 0.0f }, { 1280.0f, 720.0f }, backgroundTex);
level.OnRender();
player.OnRender();
sgl::Renderer2D::EndScene();
}
else if (GameState == Dead)
{
if (player.GetScore() > player.GetHighscore())
player.SetHighscore(player.GetScore());
player = Player();
level = Level();
respawnt = true;
GameState = MainMenu;
}
else if (GameState == Close)
{
window.Close();
}
sgl::ImGuiUtil::EndFrame();
}
} | 25.123967 | 110 | 0.642434 | SemperParatusGithub |
e0306a85bdbba3a75ea283908382efea5e64e581 | 2,684 | cpp | C++ | untests/sources/untests_core/debug.cpp | NechukhrinN/enduro2d | 774f120395885a6f0f21418c4de024e7668ee436 | [
"MIT"
] | 92 | 2018-08-07T14:45:33.000Z | 2021-11-14T20:37:23.000Z | untests/sources/untests_core/debug.cpp | NechukhrinN/enduro2d | 774f120395885a6f0f21418c4de024e7668ee436 | [
"MIT"
] | 43 | 2018-09-30T20:48:03.000Z | 2020-04-20T20:05:26.000Z | untests/sources/untests_core/debug.cpp | NechukhrinN/enduro2d | 774f120395885a6f0f21418c4de024e7668ee436 | [
"MIT"
] | 13 | 2018-08-08T13:45:28.000Z | 2020-10-02T11:55:58.000Z | /*******************************************************************************
* This file is part of the "Enduro2D"
* For conditions of distribution and use, see copyright notice in LICENSE.md
* Copyright (C) 2018-2020, by Matvey Cherevko (blackmatov@gmail.com)
******************************************************************************/
#include "_core.hpp"
using namespace e2d;
namespace
{
using namespace e2d;
class test_sink final : public debug::sink {
public:
str on_message_acc;
static str s_on_message_acc;
bool on_message(debug::level lvl, str_view text) noexcept final {
E2D_UNUSED(lvl);
on_message_acc.append(text.cbegin(), text.cend());
s_on_message_acc.append(text.cbegin(), text.cend());
return true;
}
};
str test_sink::s_on_message_acc;
}
TEST_CASE("debug"){
{
debug d;
test_sink& s = d.register_sink<test_sink>();
REQUIRE(test_sink::s_on_message_acc.empty());
d.trace("h");
d.warning("e");
REQUIRE(test_sink::s_on_message_acc == "he");
d.set_min_level(debug::level::error);
d.trace("el");
d.warning("lo");
REQUIRE(test_sink::s_on_message_acc == "he");
d.error("ll");
REQUIRE(test_sink::s_on_message_acc == "hell");
d.fatal("o");
REQUIRE(test_sink::s_on_message_acc == "hello");
d.unregister_sink(s);
d.fatal("!!!");
REQUIRE(test_sink::s_on_message_acc == "hello");
}
{
modules::initialize<debug>();
test_sink& s1 = the<debug>().register_sink_ex<test_sink>(debug::level::warning);
test_sink& s2 = the<debug>().register_sink_ex<test_sink>(debug::level::error);
REQUIRE(s1.on_message_acc.empty());
REQUIRE(s2.on_message_acc.empty());
the<debug>().trace("w");
REQUIRE(s1.on_message_acc.empty());
REQUIRE(s2.on_message_acc.empty());
the<debug>().warning("w");
REQUIRE(s1.on_message_acc == "w");
REQUIRE(s2.on_message_acc.empty());
the<debug>().error("q");
REQUIRE(s1.on_message_acc == "wq");
REQUIRE(s2.on_message_acc == "q");
the<debug>().fatal("e");
REQUIRE(s1.on_message_acc == "wqe");
REQUIRE(s2.on_message_acc == "qe");
the<debug>().set_min_level(debug::level::fatal);
the<debug>().error("r");
REQUIRE(s1.on_message_acc == "wqe");
REQUIRE(s2.on_message_acc == "qe");
the<debug>().fatal("r");
REQUIRE(s1.on_message_acc == "wqer");
REQUIRE(s2.on_message_acc == "qer");
modules::shutdown<debug>();
}
}
| 34.857143 | 88 | 0.552534 | NechukhrinN |
e031a23cbca914c8a235bb565283706ca2800ad9 | 3,009 | cc | C++ | Development/OrignalDev/ProbabilityFramework/Distributions/CPD/CPDDiscreteDiscrete.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | Development/OrignalDev/ProbabilityFramework/Distributions/CPD/CPDDiscreteDiscrete.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | Development/OrignalDev/ProbabilityFramework/Distributions/CPD/CPDDiscreteDiscrete.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2006, OmniPerception Ltd.
// 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$"
//! lib=RavlProb
//! author="Robert Crida"
#include "Ravl/Prob/CPDDiscreteDiscrete.hh"
namespace RavlProbN {
using namespace RavlN;
CPDDiscreteDiscreteBodyC::CPDDiscreteDiscreteBodyC(const VariableDiscreteC& randomVariable,
const VariableSetC& parentVariableSet,
const RCHashC<PropositionSetC,PDFDiscreteC>& probabilityDistributionTable)
: CPDAbstractBodyC(randomVariable, parentVariableSet)
{
SetProbabilityDistributionTable(probabilityDistributionTable);
}
CPDDiscreteDiscreteBodyC::~CPDDiscreteDiscreteBodyC() {
}
ProbabilityDistributionC CPDDiscreteDiscreteBodyC::ConditionalDistribution(const PropositionSetC& parentValues) const
{
PDFDiscreteC pdf;
if (parentValues.Values().Size() != ParentVariableSet().Size())
throw ExceptionC("CPDDiscreteDiscreteBodyC::ConditionalDistribution(), called with incorrect proposition!");
if (!m_probabilityDistributionTable.Lookup(parentValues, pdf)) {
throw ExceptionC(StringC("CPDDiscreteDiscreteBodyC::ConditionalDistribution(), couldn't find distribution ") + parentValues.ToString());
}
return pdf;
}
void CPDDiscreteDiscreteBodyC::SetProbabilityDistributionTable(const RCHashC<PropositionSetC,PDFDiscreteC>& probabilityDistributionTable)
{
// ensure all parents are discrete and calculate combinations
UIntT numCombinations = 1;
for (HSetIterC<VariableC> ht(ParentVariableSet().Variables()); ht; ht++) {
VariableDiscreteC discrete(*ht);
if (!discrete.IsValid())
throw ExceptionC("CPDDiscreteDiscreteBodyC::SetProbabilityDistributionTable(), all parents must be discrete");
numCombinations *= discrete.DomainSize();
}
// check that there is a table for each value
if (numCombinations != probabilityDistributionTable.Size())
throw ExceptionC("CPDDiscreteDiscreteBodyC::SetProbabilityDistributionTable(), need table for each combination of parents");
// check that all tables are for the correct parents
for (HashIterC<PropositionSetC,PDFDiscreteC> ht(probabilityDistributionTable); ht; ht++) {
if (ht.Key().VariableSet() != ParentVariableSet())
throw ExceptionC("CPDDiscreteDiscreteBodyC::SetProbabilityDistributionTable(), each table must be for parent domain");
if (ht.Key().Size() != ParentVariableSet().Size())
throw ExceptionC("CPDDiscreteDiscreteBodyC::SetProbabilityDistributionTable(), each table must be for a complete combination of parent variables");
}
m_probabilityDistributionTable = probabilityDistributionTable.Copy();
}
}
| 47.761905 | 155 | 0.73114 | isuhao |
e03268d013bd44d5ed1d9bc787bf40e15fb1cb46 | 51,165 | cpp | C++ | src/GUI/scrollbar.cpp | HonzaMD/Krkal2 | e53e9b096d89d1441ec472deb6d695c45bcae41f | [
"OLDAP-2.5"
] | 1 | 2018-04-01T16:47:52.000Z | 2018-04-01T16:47:52.000Z | src/GUI/scrollbar.cpp | HonzaMD/Krkal2 | e53e9b096d89d1441ec472deb6d695c45bcae41f | [
"OLDAP-2.5"
] | null | null | null | src/GUI/scrollbar.cpp | HonzaMD/Krkal2 | e53e9b096d89d1441ec472deb6d695c45bcae41f | [
"OLDAP-2.5"
] | null | null | null | ///////////////////////////////////////////////
//
// scrollbar.cpp
//
// Implementace pro scrollbar a jeho casti scrollbarButtons
//
// A: Jan Poduska
//
///////////////////////////////////////////////
#include "stdafx.h"
#include "scrollbar.h"
#include "widgets.h"
#include "dxbliter.h"
//////////////////////////////////////////////////////////////////////
// CGUIScrollBar
//////////////////////////////////////////////////////////////////////
CGUIScrollBar::CGUIScrollBar(enum EScrollBarTypes _scrollBarType, float _x, float _y, float length, float width, float _shift, bool _autohide, bool _slider_resize, CGUIWindow *wnd, char* styleName[3][2], CGUIRectHost* pictures[3], CGUIScrollBar* _dual)
: CGUIMultiWidget(_x,_y)
{
/*-------------------------------------------------------------------------
Velikost scrollbaru: - delka aspon 2x vetsi nez sirka
- slider je minimalne velky jako up, down buttony (sirka x sirka)
- sirka a vyska musi byt aspon takova, aby se tam vesly aspon up, down buttony
- pageUp, pageDown, Nothing buttony jsou pod ostatnima, aby neprekryvaly pri malych velikostech
(vel. mensi nez je mozna velikost buttonu)
- pokud se nevejde slider => pageUp, PageDown buttony se nezobrazuji,
misto mezi up a down je vyplneno nereagujici bitmapou (buttonem?)
-------------------------------------------------------------------------*/
RemoveFromTrash();
SetAvailableEvents(0,0);
float len, pos;
int i;
scrollBarType = _scrollBarType;
autohide = _autohide;
slider_resize=_slider_resize;
active=false;
corner = 0;
shift = _shift;
if(!wnd)
{
throw CExc(eGUI, E_BAD_ARGUMENTS,"CGUIScrollBar::CGUIScrollBar> Parent window is not defined");
}
if(length<=2*width)
{
throw CExc(eGUI, E_BAD_ARGUMENTS,"CGUIScrollBar::CGUIScrollBar> Height & width of scrollbar are badly defined, scrollbar cannot construct");
}
for(i=0;i<6;i++)
buttons[i] = 0;
dual = _dual;
if(dual && (dual->active || !dual->autohide))
{
long_version=false;
length -=width;
}else{
long_version=true;
}
try{
switch(scrollBarType)
{
case Vertical : sx = width;
sy = length;
SetAnchor(WIDGET_FIX,WIDGET_FIX,WIDGET_FREE,WIDGET_FIX);
if(wnd->vp_sy >= wnd->bw_size_normal_y)
{ // viewport je vetsi nez okno
// nezobrazovat? a nepouzivat scrollbary
active=false;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, 0,length-width,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Down, 0, pictures[1]);
// stredove buttony se nezobrazuji, jen se vytvori (o velikosti celeho vnitrku scrollbaru)
buttons[2] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
// pri neaktivnim zobrazenem scrollbaru je ve stredni casti jen neaktivni plocha
buttons[5] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), scrollBarType, S_Nothing);
if(autohide)
{ // nezobrazovat zadnoou cast scrollbaru
SetVisible(0);
for(i=0;i<6;i++)
buttons[i]->SetVisible(0); // buttony jeste nejsou ve fronte, musi se zneviditelnit manualne
}else{
// zobrazit jen kraje a neaktivni stred (5)
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
//buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);buttons[5]->SetVisible(1);
}
}else{
active=true;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, 0,length-width,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Down, 0, pictures[1]);
if(slider_resize)
len = floorf((wnd->vp_sy / wnd->bw_size_normal_y) * (length - 2*width)); // !@#$ zaokrouhlovani ????
else
len = width;
if(len<width)
len=width; // kontrola velikosti slideru
pos = floorf((wnd->vp_y / (wnd->bw_size_normal_y - wnd->vp_sy)) * (length - 2*width - len)); // !@#$ zaokrouhlovani ????
buttons[5] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), scrollBarType, S_Nothing);
if((length - 2*width) < width)
{ // scrollbar je prislis maly => nezobrazuj stredova tlacitka (1,2,3)
// misto nich jen neaktivni plocha
buttons[2] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
}else{
buttons[2] = new CGUIScrollbarButton(this, 0,width+pos,width,len,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, 0,width,width,pos,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, 0,width+pos+len,width,(length-2*width)-(pos+len),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
buttons[5]->SetVisible(0);
}
}
// zmenseni viewportu o misto, ktere zabira scrollbar
if(active || !autohide)
{
float dx, dy;
dx = -width;
dy = 0;
wnd->ChangeViewPortBWSize(dx,dy);
if(dx>-width)
{
float ox,oy;
wnd->GetSize(ox,oy);
wnd->ResizeFrontOnly(width-dx+ox,oy);
}
}
if(dual)
if(long_version)
corner = new CGUIStaticPicture(x,y+length-width,styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
else
corner = new CGUIStaticPicture(x,y+length,styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
break;
case Horizontal : sx = length;
sy = width;
SetAnchor(WIDGET_FREE,WIDGET_FIX,WIDGET_FIX,WIDGET_FIX);
if(wnd->vp_sx >= wnd->bw_size_normal_x)
{
// nezobrazovat? a nepouzivat scrollbary
active=false;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, length-width,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Down, 0, pictures[1]);
// stredove buttony se nezobrazuji, jen se vytvori (o velikosti celeho vnitrku scrollbaru)
buttons[2] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
// pri neaktivnim zobrazenem scrollbaru je ve stredni casti jen neaktivni plocha
buttons[5] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), scrollBarType, S_Nothing);
if(autohide)
{ // nezobrazovat zadnoou cast scrollbaru
SetVisible(0);
for(i=0;i<6;i++)
buttons[i]->SetVisible(0);// buttony jeste nejsou ve fronte, musi se zneviditelnit manualne
}else{
// zobrazit jen kraje a neaktivni stred (5)
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
//buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);buttons[5]->SetVisible(1);
}
}else{
active=true;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, length-width,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), scrollBarType, S_Down, 0, pictures[1]);
if(slider_resize)
len = floorf((wnd->vp_sx / wnd->bw_size_normal_x) * (length - 2*width)); // !@#$ zaokrouhlovani ????
else
len = width;
if(len<width)
len=width; // kontrola velikosti slideru
pos = floorf((wnd->vp_x / (wnd->bw_size_normal_x - wnd->vp_sx)) * (length - 2*width - len)); // !@#$ zaokrouhlovani ????
buttons[5] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), scrollBarType, S_Nothing);
if((length - 2*width) < width)
{ // scrollbar je prislis maly => nezobrazuj stredova tlacitka (1,2,3)
// misto nich jen neaktivni plocha
buttons[2] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
}else{
buttons[2] = new CGUIScrollbarButton(this, width+pos,0,len,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, width,0,pos,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, width+pos+len,0,(length-2*width)-(pos+len),width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
buttons[5]->SetVisible(0);
}
}
// zmenseni viewportu o misto, ktere zabira scrollbar
if(active || !autohide)
{
float dx, dy;
dx = 0;
dy = -width;
wnd->ChangeViewPortBWSize(dx,dy);
if(dy>-width)
{
float ox,oy;
wnd->GetSize(ox,oy);
wnd->ResizeFrontOnly(ox,width-dy+oy);
}
}
if(dual)
if(long_version)
corner = new CGUIStaticPicture(x+length-width, y, styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
else
corner = new CGUIStaticPicture(x+length, y, styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
break;
}
AddElem(buttons[5]); // nejspodneji je neaktivni stred
AddElem(buttons[1]); // pageup
AddElem(buttons[3]); // pageDown
AddElem(buttons[2]); // slider
AddElem(buttons[0]); // na vrcholu up
AddElem(buttons[4]); // a down
// kvuli moznym prekryvum pri prislis male velikosti tlacitka (mensi nez mozne minimum)
// MsgSetConsume(MsgMouseL|MsgMouseOver); // nesmim konzumovat musim preposilat az k buttonum
SetSize(sx,sy);
if(window)
window->SetWindowSize(sx, sy);
wnd->AddFrontElem(this);
wnd->AcceptEvent(GetID(),EUpdateScrollbars);
wnd->AcceptEvent(GetID(),EMouseWheel);
if(corner)
{
corner->MsgSetProduce(MsgNone);
corner->SetAnchor(WIDGET_FREE,WIDGET_FIX,WIDGET_FREE,WIDGET_FIX);
wnd->AddFrontElem(corner);
}
if(dual)
{
dual->dual=this;
if((dual->active || !dual->autohide) && (active || !autohide)) // && dual->long_version
{
dual->RebuildScrollbar();
}else if(corner)
corner->SetVisible(0);
}
for(i=0;i<6;i++)
buttons[i]->RemoveFromTrash();
}catch(CExc)
{
for(i=0;i<6;i++)
SAFE_DELETE(buttons[i]);
if(corner)
wnd->RemoveFrontElem(corner);
SAFE_DELETE(corner);
throw;
}
}
CGUIScrollBar::CGUIScrollBar(enum EScrollBarTypes _scrollBarType, float _x, float _y, float length, float width, float _shift, bool _autohide, bool _slider_resize, CGUIWindow *wnd, char* styleName[4][2], CGUIRectHost* pictures[3], CGUIScrollBar* _dual, bool simple)
: CGUIMultiWidget(_x,_y)
{
/*-------------------------------------------------------------------------
Velikost scrollbaru: - delka aspon 2x vetsi nez sirka
- slider je minimalne velky jako up, down buttony (sirka x sirka)
- sirka a vyska musi byt aspon takova, aby se tam vesly aspon up, down buttony
- pageUp, pageDown, Nothing buttony jsou pod ostatnima, aby neprekryvaly pri malych velikostech
(vel. mensi nez je mozna velikost buttonu)
- pokud se nevejde slider => pageUp, PageDown buttony se nezobrazuji,
misto mezi up a down je vyplneno nereagujici bitmapou (buttonem?)
-------------------------------------------------------------------------*/
RemoveFromTrash();
SetAvailableEvents(0,0);
float len, pos;
int i;
scrollBarType = _scrollBarType;
autohide = _autohide;
slider_resize=_slider_resize;
active=false;
corner = 0;
shift = _shift;
if(!wnd)
{
throw CExc(eGUI, E_BAD_ARGUMENTS,"CGUIScrollBar::CGUIScrollBar> Parent window is not defined");
}
if(length<=2*width)
{
throw CExc(eGUI, E_BAD_ARGUMENTS,"CGUIScrollBar::CGUIScrollBar> Height & width of scrollbar are badly defined, scrollbar cannot construct");
}
for(i=0;i<6;i++)
buttons[i] = 0;
dual = _dual;
if(dual && (dual->active || !dual->autohide))
{
long_version=false;
length -=width;
}else{
long_version=true;
}
try{
switch(scrollBarType)
{
case Vertical : sx = width;
sy = length;
SetAnchor(WIDGET_FIX,WIDGET_FIX,WIDGET_FREE,WIDGET_FIX);
if(wnd->vp_sy >= wnd->bw_size_normal_y)
{ // viewport je vetsi nez okno
// nezobrazovat? a nepouzivat scrollbary
active=false;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), false, scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, 0,length-width,width,width,styleSet->Get(styleName[3][0]),styleSet->Get(styleName[3][1]),styleSet->Get(styleName[3][0]), false, scrollBarType, S_Down, 0, pictures[1]);
// stredove buttony se nezobrazuji, jen se vytvori (o velikosti celeho vnitrku scrollbaru)
if(slider_resize)
buttons[2] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
else
buttons[2] = new CGUIScrollbarButton(this, 0,width,width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), false, scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true,scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageDown);
// pri neaktivnim zobrazenem scrollbaru je ve stredni casti jen neaktivni plocha
buttons[5] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_Nothing);
if(autohide)
{ // nezobrazovat zadnoou cast scrollbaru
SetVisible(0);
for(i=0;i<6;i++)
buttons[i]->SetVisible(0); // buttony jeste nejsou ve fronte, musi se zneviditelnit manualne
}else{
// zobrazit jen kraje a neaktivni stred (5)
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
//buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);buttons[5]->SetVisible(1);
}
}else{
active=true;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), false, scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, 0,length-width,width,width,styleSet->Get(styleName[3][0]),styleSet->Get(styleName[3][1]),styleSet->Get(styleName[3][0]), false, scrollBarType, S_Down, 0, pictures[1]);
if(slider_resize)
len = floorf((wnd->vp_sy / wnd->bw_size_normal_y) * (length - 2*width)); // !@#$ zaokrouhlovani ????
else
len = width;
if(len<width)
len=width; // kontrola velikosti slideru
pos = floorf((wnd->vp_y / (wnd->bw_size_normal_y - wnd->vp_sy)) * (length - 2*width - len)); // !@#$ zaokrouhlovani ????
buttons[5] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_Nothing);
if((length - 2*width) < width)
{ // scrollbar je prislis maly => nezobrazuj stredova tlacitka (1,2,3)
// misto nich jen neaktivni plocha
if(slider_resize)
buttons[2] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
else
buttons[2] = new CGUIScrollbarButton(this, 0,width,width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), false, scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, 0,width,width,length - 2*width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageDown);
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
}else{
if(slider_resize)
buttons[2] = new CGUIScrollbarButton(this, 0,width+pos,width,len,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
else
buttons[2] = new CGUIScrollbarButton(this, 0,width+pos,width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), false, scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, 0,width,width,pos,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]),true, scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, 0,width+pos+len,width,(length-2*width)-(pos+len),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageDown);
buttons[5]->SetVisible(0);
}
}
// zmenseni viewportu o misto, ktere zabira scrollbar
if(active || !autohide)
{
float dx, dy;
dx = -width;
dy = 0;
wnd->ChangeViewPortBWSize(dx,dy);
if(dx>-width)
{
float ox,oy;
wnd->GetSize(ox,oy);
wnd->ResizeFrontOnly(width-dx+ox,oy);
}
}
if(dual)
if(long_version)
corner = new CGUIStaticPicture(x,y+length-width,styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
else
corner = new CGUIStaticPicture(x,y+length,styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
break;
case Horizontal : sx = length;
sy = width;
SetAnchor(WIDGET_FREE,WIDGET_FIX,WIDGET_FIX,WIDGET_FIX);
if(wnd->vp_sx >= wnd->bw_size_normal_x)
{
// nezobrazovat? a nepouzivat scrollbary
active=false;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), false, scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, length-width,0,width,width,styleSet->Get(styleName[3][0]),styleSet->Get(styleName[3][1]),styleSet->Get(styleName[3][0]), false, scrollBarType, S_Down, 0, pictures[1]);
// stredove buttony se nezobrazuji, jen se vytvori (o velikosti celeho vnitrku scrollbaru)
if(slider_resize)
buttons[2] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
else
buttons[2] = new CGUIScrollbarButton(this, width,0,width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), false,scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageDown);
// pri neaktivnim zobrazenem scrollbaru je ve stredni casti jen neaktivni plocha
buttons[5] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_Nothing);
if(autohide)
{ // nezobrazovat zadnoou cast scrollbaru
SetVisible(0);
for(i=0;i<6;i++)
buttons[i]->SetVisible(0);// buttony jeste nejsou ve fronte, musi se zneviditelnit manualne
}else{
// zobrazit jen kraje a neaktivni stred (5)
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
//buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);buttons[5]->SetVisible(1);
}
}else{
active=true;
buttons[0] = new CGUIScrollbarButton(this, 0,0,width,width,styleSet->Get(styleName[0][0]),styleSet->Get(styleName[0][1]),styleSet->Get(styleName[0][0]), false, scrollBarType, S_Up, 0, pictures[0]);
buttons[4] = new CGUIScrollbarButton(this, length-width,0,width,width,styleSet->Get(styleName[3][0]),styleSet->Get(styleName[3][1]),styleSet->Get(styleName[3][0]), false, scrollBarType, S_Down, 0, pictures[1]);
if(slider_resize)
len = floorf((wnd->vp_sx / wnd->bw_size_normal_x) * (length - 2*width)); // !@#$ zaokrouhlovani ????
else
len = width;
if(len<width)
len=width; // kontrola velikosti slideru
pos = floorf((wnd->vp_x / (wnd->bw_size_normal_x - wnd->vp_sx)) * (length - 2*width - len)); // !@#$ zaokrouhlovani ????
buttons[5] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][0]), true,scrollBarType, S_Nothing);
if((length - 2*width) < width)
{ // scrollbar je prislis maly => nezobrazuj stredova tlacitka (1,2,3)
// misto nich jen neaktivni plocha
if(slider_resize)
buttons[2] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
else
buttons[2] = new CGUIScrollbarButton(this, width,0,width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, width,0,length - 2*width,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), scrollBarType, S_PageDown);
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
}else{
if(slider_resize)
buttons[2] = new CGUIScrollbarButton(this, width+pos,0,len,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), scrollBarType, S_Slider,0,pictures[2]);
else
buttons[2] = new CGUIScrollbarButton(this, width+pos,0,width,width,styleSet->Get(styleName[2][0]),styleSet->Get(styleName[2][1]),styleSet->Get(styleName[2][0]), false, scrollBarType, S_Slider,0,pictures[2]);
buttons[1] = new CGUIScrollbarButton(this, width,0,pos,width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageUp);
buttons[3] = new CGUIScrollbarButton(this, width+pos+len,0,(length-2*width)-(pos+len),width,styleSet->Get(styleName[1][0]),styleSet->Get(styleName[1][1]),styleSet->Get(styleName[1][0]), true, scrollBarType, S_PageDown);
buttons[5]->SetVisible(0);
}
}
// zmenseni viewportu o misto, ktere zabira scrollbar
if(active || !autohide)
{
float dx, dy;
dx = 0;
dy = -width;
wnd->ChangeViewPortBWSize(dx,dy);
if(dy>-width)
{
float ox,oy;
wnd->GetSize(ox,oy);
wnd->ResizeFrontOnly(ox,width-dy+oy);
}
}
if(dual)
if(long_version)
corner = new CGUIStaticPicture(x+length-width, y, styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
else
corner = new CGUIStaticPicture(x+length, y, styleSet->Get("SB_Pictures")->GetTexture(6),width,width);
break;
}
AddElem(buttons[5]); // nejspodneji je neaktivni stred
AddElem(buttons[1]); // pageup
AddElem(buttons[3]); // pageDown
AddElem(buttons[2]); // slider
AddElem(buttons[0]); // na vrcholu up
AddElem(buttons[4]); // a down
// kvuli moznym prekryvum pri prislis male velikosti tlacitka (mensi nez mozne minimum)
// MsgSetConsume(MsgMouseL|MsgMouseOver); // nesmim konzumovat musim preposilat az k buttonum
SetSize(sx,sy);
if(window)
window->SetWindowSize(sx, sy);
wnd->AddFrontElem(this);
wnd->AcceptEvent(GetID(),EUpdateScrollbars);
wnd->AcceptEvent(GetID(),EMouseWheel);
if(corner)
{
corner->MsgSetProduce(MsgNone);
corner->SetAnchor(WIDGET_FREE,WIDGET_FIX,WIDGET_FREE,WIDGET_FIX);
wnd->AddFrontElem(corner);
}
if(dual)
{
dual->dual=this;
if((dual->active || !dual->autohide) && (active || !autohide)) // && dual->long_version
{
dual->RebuildScrollbar();
}else if(corner)
corner->SetVisible(0);
}
for(i=0;i<6;i++)
buttons[i]->RemoveFromTrash();
}catch(CExc)
{
for(i=0;i<6;i++)
SAFE_DELETE(buttons[i]);
if(corner)
wnd->RemoveFrontElem(corner);
SAFE_DELETE(corner);
throw;
}
}
CGUIScrollBar::~CGUIScrollBar()
{
}
void CGUIScrollBar::RemoveFromEngine()
{
CGUIMultiWidget::RemoveFromEngine();
float dx, dy;
if(!parent || parent->GetType() < PTWindow)
{
throw CExc(eGUI, E_INTERNAL,"CGUIScrollBar::RemoveFromEngine> Parent window is not found");
}
CGUIWindow *wnd = (CGUIWindow*) parent;
if(active || !autohide)
{
switch(scrollBarType)
{
case Vertical : dx = sx;
dy = 0;
break;
case Horizontal : dx = 0;
dy = sy;
break;
}
float ox, oy;
ox=dx;
oy=dy;
wnd->ChangeViewPortBWSize(dx,dy);
dx-=ox;dy-=oy;
if(dx<0||dy<0)
{
wnd->GetSize(ox,oy);
wnd->ResizeFrontOnly(ox+dx,oy+dy);
}
}
if(corner)
{
wnd->DeleteFrontElem(corner);
corner=0;
}
if(dual)
{
dual->dual=0;
if((dual->active || !dual->autohide) && (active || !autohide))
dual->RebuildScrollbar();
dual = 0;
}
active=false;
autohide=false;
}
void CGUIScrollBar::Resize(float _sx, float _sy)
{
float dx, dy;
CheckResize(_sx,_sy);
GetSize(dx,dy);
dx=_sx-dx; // rozdily ve velikostech
dy=_sy-dy;
SetSize(_sx,_sy);
if(window)
window->SetWindowSize(sx, sy);
RebuildScrollbar();
}
void CGUIScrollBar::RebuildScrollbar()
{
// vola se pri zmene parametru okna nebo scrollbaru
// zmena: sx, sy, vp_x/vp_y, vp_sx/vp_sy, bw_normal_size_x/bw_normal_size_y
float width, length;
float len, pos;
//int i;
bool resize = false;
float dx, dy;
bool old_state=active; // stary stav "active" pred zmenou parametru scrollbaru (kvuli uprave velikosti viewportu => detekce zmeny)
if(!parent || parent->GetType() < PTWindow)
{
throw CExc(eGUI, E_INTERNAL,"CGUIScrollBar::RebuildScrollbar> Parent window is not found");
}
CGUIWindow *wnd = (CGUIWindow*) parent;
switch(scrollBarType)
{
case Vertical : width = sx;
length = sy;
dx = sx;
dy = 0;
break;
case Horizontal : width = sy;
length = sx;
dx = 0;
dy = sy;
break;
}
if(dual && (dual->active || !dual->autohide ))
{
if(long_version)
{
long_version=false;
length -=width;
resize=true;
}
}else{
if(!long_version)
{
long_version=true;
length +=width;
resize=true;
}
}
if(resize)
{
switch(scrollBarType)
{
case Vertical : Resize(width, length); return; // resize vyvola rekurzivne tuto proceduru
case Horizontal : Resize(length, width); return;
}
}
switch(scrollBarType)
{
case Vertical : if((wnd->vp_sy >= wnd->bw_size_normal_y) ||
(active && dual && dual->active && wnd->vp_sy+dual->sy>= wnd->bw_size_normal_y && (wnd->vp_sx + sx >= wnd->bw_size_normal_x)))
{ // viewport je vetsi nez okno
// nezobrazovat? a nepouzivat scrollbary
active=false;
// button[0] beze zmeny
buttons[4]->Move(0,length-width);
// pri neaktivnim zobrazenem scrollbaru je ve stredni casti jen neaktivni plocha
buttons[5]->Move(0,width);
buttons[5]->Resize(width, length - 2*width);
if(autohide)
{ // nezobrazovat zadnoou cast scrollbaru
SetVisible(0);
//for(i=0;i<6;i++)
// buttons[i]->SetVisible(0);
}else{
//SetVisible(1);
// zobrazit jen kraje a neaktivni stred (5)
SetVisible(1);
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);buttons[5]->SetVisible(1);
}
}else{
if(!active && autohide)
SetVisible(1);
active=true;
//SetVisibility(1);
// buttons[0] beze zmeny
buttons[4]->Move(0,length-width);
buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);
if(slider_resize)
len = floorf((wnd->vp_sy / wnd->bw_size_normal_y) * (length - 2*width)); // !@#$ zaokrouhlovani ????
else
len = width;
if(len<width)
len=width; // kontrola velikosti slideru
pos = floorf((wnd->vp_y / (wnd->bw_size_normal_y - wnd->vp_sy)) * (length - 2*width - len)); // !@#$ zaokrouhlovani ????
if((length - 2*width) < width)
{ // scrollbar je prislis maly => nezobrazuj stredova tlacitka (1,2,3)
// misto nich jen neaktivni plocha
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
buttons[5]->Move(0,width);
buttons[5]->Resize(width,length - 2*width);
buttons[5]->SetVisible(1);
}else{
buttons[2]->Move(0,width+pos);
buttons[2]->Resize(width,len);
buttons[1]->Move(0,width);
buttons[1]->Resize(width,pos);
buttons[3]->Move(0,width+pos+len);
buttons[3]->Resize(width,(length-2*width)-(pos+len));
buttons[1]->SetVisible(1);buttons[3]->SetVisible(1);buttons[2]->SetVisible(1);
buttons[5]->SetVisible(0);
}
}
break;
case Horizontal : if((wnd->vp_sx >= wnd->bw_size_normal_x) ||
(active && dual && dual->active && wnd->vp_sx+dual->sx>= wnd->bw_size_normal_x && (wnd->vp_sy + sy >= wnd->bw_size_normal_y)))
{ // viewport je vetsi nez okno
// nezobrazovat? a nepouzivat scrollbary
active=false;
// button[0] beze zmeny
buttons[4]->Move(length-width,0);
// pri neaktivnim zobrazenem scrollbaru je ve stredni casti jen neaktivni plocha
buttons[5]->Move(width,0);
buttons[5]->Resize(length - 2*width,width);
if(autohide)
{ // nezobrazovat zadnoou cast scrollbaru
SetVisible(0);
//for(i=0;i<6;i++)
// buttons[i]->SetVisible(0);
}else{
// zobrazit jen kraje a neaktivni stred (5)
//SetVisibility(1);
SetVisible(1);
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);buttons[5]->SetVisible(1);
}
}else{
if(!active && autohide)
SetVisible(1);
active=true;
//SetVisibility(1);
// buttons[0] beze zmeny
buttons[4]->Move(length-width,0);
buttons[0]->SetVisible(1);buttons[4]->SetVisible(1);
if(slider_resize)
len = floorf((wnd->vp_sx / wnd->bw_size_normal_x) * (length - 2*width)); // !@#$ zaokrouhlovani ????
else
len = width;
if(len<width)
len=width; // kontrola velikosti slideru
pos = floorf((wnd->vp_x / (wnd->bw_size_normal_x - wnd->vp_sx)) * (length - 2*width - len)); // !@#$ zaokrouhlovani ????
if((length - 2*width) < width)
{ // scrollbar je prislis maly => nezobrazuj stredova tlacitka (1,2,3)
// misto nich jen neaktivni plocha
buttons[1]->SetVisible(0);buttons[2]->SetVisible(0);buttons[3]->SetVisible(0);
buttons[5]->Move(width,0);
buttons[5]->Resize(length - 2*width, width);
buttons[5]->SetVisible(1);
}else{
buttons[2]->Move(width+pos, 0);
buttons[2]->Resize(len, width);
buttons[1]->Move(width, 0);
buttons[1]->Resize(pos, width);
buttons[3]->Move(width+pos+len, 0);
buttons[3]->Resize((length-2*width)-(pos+len), width);
buttons[1]->SetVisible(1);buttons[3]->SetVisible(1);buttons[2]->SetVisible(1);
buttons[5]->SetVisible(0);
}
}
break;
}
// zmenseni/zvetseni viewportu o misto, ktere zabira/nezabira scrollbar
if(autohide && old_state!=active)
{
float ox, oy;
if(old_state && !active)
{
ox=dx;
oy=dy;
wnd->ChangeViewPortBWSize(dx,dy);
dx-=ox;dy-=oy;
if(dx<0||dy<0)
{
wnd->GetSize(ox,oy);
wnd->ResizeFrontOnly(ox+dx,oy+dy);
}
}else if(!old_state && active)
{
dx = ox = - dx;
dy = oy = - dy;
wnd->ChangeViewPortBWSize(dx,dy);
if(dx>ox || dy>oy)
{
wnd->GetSize(ox,oy);
if(scrollBarType==Vertical && dx>-width)
wnd->ResizeFrontOnly(width-dx+ox,oy);
if(scrollBarType==Horizontal && dy>-width)
wnd->ResizeFrontOnly(ox,width-dy+oy);
}
}
if(dual)
dual->RebuildScrollbar();
}
if(corner)
{
if(dual && (dual->active || !dual->autohide) && (active || !autohide))
corner->SetVisible(1);
else
corner->SetVisible(0);
}
/*
if(dual && (dual->active || !dual->autohide) && dual->long_version && (active || !autohide))
{
dual->RebuildScrollbar();
}
if(dual && (dual->active || !dual->autohide) && !dual->long_version && !active && autohide)
{
dual->RebuildScrollbar();
}
*/
}
void CGUIScrollBar::EventHandler(CGUIEvent *event)
{
if(!event)
return;
if(event->eventID == EUpdateScrollbars)
RebuildScrollbar();
if(event->eventID == EMouseWheel && active && parent && parent->GetType() >= PTWindow)
{
if(scrollBarType == Vertical)
{
((CGUIWindow*)parent)->SetWindowPositionVP(0,-event->pInt*STD_SCROLLBAR_MWHEEL_COEF*shift,false);
RebuildScrollbar();
mainGUI->SendCursorPos(); // !@#$ aktualizace kurzoru
mainGUI->GetEvent(0);
}else if(!dual || (dual && !dual->active))
{
((CGUIWindow*)parent)->SetWindowPositionVP(-event->pInt*STD_SCROLLBAR_MWHEEL_COEF*shift,0,false);
RebuildScrollbar();
mainGUI->SendCursorPos(); // !@#$ aktualizace kurzoru
mainGUI->GetEvent(0);
}
}
delete(event);
}
//////////////////////////////////////////////////////////////////////
// CGUIScrollbarButton
//////////////////////////////////////////////////////////////////////
CGUIScrollbarButton::CGUIScrollbarButton(CGUIScrollBar* _sb, float _x, float _y, float _sx, float _sy, CGUIStyle *_up, CGUIStyle *_down, CGUIStyle *_mark, enum EScrollBarTypes _scrollBarType, enum EScrollBarButtonTypes _scrollBarButtonType, CGUIStaticText *_label, CGUIRectHost *_picture)
: CGUIButton(_x,_y,_sx,_sy,_up,_down,_mark,_label, _picture)
{
//RemoveFromTrash();
scrollBarType = _scrollBarType;
scrollBarButtonType = _scrollBarButtonType;
sb = _sb;
px = py = 0;
mouse_down=false;
MsgAcceptConsume(MsgTimer);
keySensitive=false;
//AddToTrash();
}
CGUIScrollbarButton::CGUIScrollbarButton(CGUIScrollBar* _sb, float _x, float _y, float _sx, float _sy, CGUIStyle *_up, CGUIStyle *_down, CGUIStyle *_mark, bool resizable, enum EScrollBarTypes _scrollBarType, enum EScrollBarButtonTypes _scrollBarButtonType, CGUIStaticText *_label, CGUIRectHost *_picture)
: CGUIButton(_x,_y,_sx,_sy,_up,_down,_mark, resizable, _label, _picture)
{
//RemoveFromTrash();
scrollBarType = _scrollBarType;
scrollBarButtonType = _scrollBarButtonType;
sb = _sb;
px = py = 0;
mouse_down=false;
MsgAcceptConsume(MsgTimer);
keySensitive=false;
//AddToTrash();
}
CGUIScrollbarButton::~CGUIScrollbarButton()
{
timerGUI->DeleteAllRequests(this);
}
void CGUIScrollbarButton::OnClick()
{
// podle typu scrollovat
// nepouziva se OnClick, ale reaguje se uz na zpravy nizsi urovne - MouseLeft, MouseMove, ...
// viz. dale
}
int CGUIScrollbarButton::MouseLeft(float x, float y, UINT mouseState, UINT keyState)
{ // mouseState 1 == stisknuti cudlitka
CGUIButton::MouseLeft(x,y,mouseState, keyState);
if(!sb || !sb->active)
return 0; // scrollbar neni aktivni
if(!sb->parent || sb->parent->GetType() < PTWindow)
{
throw CExc(eGUI, E_INTERNAL,"CGUIScrollbarButton::MouseLeft> Parent window is not found");
}
CGUIWindow *wnd = (CGUIWindow*) sb->parent;
switch(scrollBarButtonType)
{
case S_Up : if(button_state==2)
{
if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-sb->shift,false);
else
wnd->SetWindowPositionVP(-sb->shift,0,false);
sb->RebuildScrollbar();
timerGUI->DeleteRequest(this);
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER1);
}else
timerGUI->DeleteRequest(this);
break;
case S_PageUp : if(button_state==2)
{
if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(-wnd->vp_sx,0,false);
sb->RebuildScrollbar();
timerGUI->DeleteRequest(this);
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER1);
}else
timerGUI->DeleteRequest(this);
break;
case S_Slider : if(button_state==2)
{
mouse_down=true;
float bx,by;
GetPos(bx,by);
px=x-bx;
py=y-by;
}else{
mouse_down=false;
px=0;
py=0;
}
break;
case S_PageDown : if(button_state==2)
{
if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(wnd->vp_sx,0,false);
sb->RebuildScrollbar();
timerGUI->DeleteRequest(this);
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER1);
}else
timerGUI->DeleteRequest(this);
break;
case S_Down : if(button_state==2)
{
if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,sb->shift,false);
else
wnd->SetWindowPositionVP(sb->shift,0,false);
sb->RebuildScrollbar();
timerGUI->DeleteRequest(this);
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER1);
}else
timerGUI->DeleteRequest(this);
break;
case S_Nothing : break;
}
if(!mouseState)
wnd->FocusOldTOBackEl();
return 0;
}
int CGUIScrollbarButton::MouseOver(float x, float y, UINT over,UINT state)
{
int old_button_state = button_state;
CGUIButton::MouseOver(x,y,over,state);
if(!sb || !sb->active)
return 0; // scrollbar neni aktivni
if(!sb->parent || sb->parent->GetType() < PTWindow)
{
throw CExc(eGUI, E_INTERNAL,"CGUIScrollbarButton::MouseOver> Parent window of scrollbar is not found");
}
CGUIWindow *wnd = (CGUIWindow*) sb->parent;
float bx, by;
float width, length;
float dd;
GetPos(bx,by);
if(scrollBarButtonType == S_Slider && button_state==2)
{
switch(scrollBarType)
{
case Vertical : sb->GetSize(width, length);
if((length - 2*width - sy) && (wnd->bw_size_normal_y - wnd->vp_sy)) // kontrola kvuli deleni nulou (viz. nasledujici radek)
dd = floorf((y-by-py) / (length - 2*width - sy) * (wnd->bw_size_normal_y - wnd->vp_sy));
else
dd=0;
wnd->SetWindowPositionVP(0,dd,false);
sb->RebuildScrollbar();
break;
case Horizontal : sb->GetSize(length, width);
if((length - 2*width - sx) && (wnd->bw_size_normal_x - wnd->vp_sx)) // kontrola kvuli deleni nulou (viz. nasledujici radek)
dd = floorf((x-bx-px) / (length - 2*width - sx) * (wnd->bw_size_normal_x - wnd->vp_sx));
else
dd = 0;
wnd->SetWindowPositionVP(dd, 0,false);
sb->RebuildScrollbar();
break;
}
}else if(scrollBarButtonType != S_Slider && old_button_state!=button_state && button_state==2)
{ // zmenil se stav buttonu (najel jsem zpet nad tlacitko po predchozim zmacknuti a vyjeti) a tlacitko je zmacknute
switch(scrollBarButtonType)
{
case S_Up : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-sb->shift,false);
else
wnd->SetWindowPositionVP(-sb->shift,0,false);
break;
case S_PageUp : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(-wnd->vp_sx,0,false);
break;
case S_PageDown : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(wnd->vp_sx,0,false);
break;
case S_Down : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,sb->shift,false);
else
wnd->SetWindowPositionVP(sb->shift,0,false);
break;
case S_Nothing : break;
}
if(scrollBarButtonType!= S_Nothing)
{
sb->RebuildScrollbar();
timerGUI->DeleteRequest(this);
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER1);
}
}else if((scrollBarButtonType == S_PageUp || scrollBarButtonType == S_PageDown)
&& button_state==2 && !timerGUI->ContainRequest(this))
// zarizuje cinnost za TimerImpulse
// v TimerImpulse nevime zda se kurzor stale naleza nad tlacitkem, to zjistime az
// poslanim zadosti o polohu kurzoru, pokud je odpoved kladna, dostaneme se sem a tady zaridime
// posunuti okna, ktere mel puvodne vykonat TimerImpulse
{
switch(scrollBarButtonType)
{
case S_PageUp : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(-wnd->vp_sx,0,false);
sb->RebuildScrollbar();
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER2);
break;
case S_PageDown : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(wnd->vp_sx,0,false);
sb->RebuildScrollbar();
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER2);
break;
}
}
return 0;
}
int CGUIScrollbarButton::MouseLeftFocus(float x, float y, UINT mouseState, UINT keyState, typeID ID)
{
CGUIButton::MouseLeftFocus(x,y,mouseState, keyState,ID);
if(scrollBarButtonType == S_Slider)
{
mouse_down=false;
px=0;
py=0;
}
return 0;
}
int CGUIScrollbarButton::MouseOverFocus(float x, float y, UINT over,UINT state, typeID ID)
{
int old_button_state = button_state;
CGUIButton::MouseOverFocus(x,y,over,state,ID);
if(!sb || !sb->active)
return 0; // scrollbar neni aktivni
if(!sb->parent || sb->parent->GetType() < PTWindow)
{
throw CExc(eGUI, E_INTERNAL,"CGUIScrollbarButton::MouseOverFocus> Parent window of scrollbar is not found");
}
CGUIWindow *wnd = (CGUIWindow*) sb->parent;
if(mouse_down && !(state & MK_LBUTTON))
{
mouse_down=0;
px=py=0;
}
float bx, by;
float width, length;
float dd;
GetPos(bx,by);
if(scrollBarButtonType == S_Slider && mouse_down)
{
switch(scrollBarType)
{
case Vertical : sb->GetSize(width, length);
if((length - 2*width - sy) && (wnd->bw_size_normal_y - wnd->vp_sy))// kontrola kvuli deleni nulou (viz. nasledujici radek)
dd = floorf((y-by-py) / (length - 2*width - sy) * (wnd->bw_size_normal_y - wnd->vp_sy));
else
dd = 0;
wnd->SetWindowPositionVP(0,dd,false);
sb->RebuildScrollbar();
break;
case Horizontal : sb->GetSize(length, width);
if((length - 2*width - sx) && (wnd->bw_size_normal_x - wnd->vp_sx))// kontrola kvuli deleni nulou (viz. nasledujici radek)
dd = floorf((x-bx-px) / (length - 2*width - sx) * (wnd->bw_size_normal_x - wnd->vp_sx));
else
dd = 0;
wnd->SetWindowPositionVP(dd, 0,false);
sb->RebuildScrollbar();
break;
}
}else if(scrollBarButtonType != S_Slider && scrollBarButtonType != S_Nothing &&
old_button_state == 2 && button_state != old_button_state)
{
timerGUI->DeleteRequest(this);
}
return 0;
}
int CGUIScrollbarButton::TimerImpulse(typeID timerID, float time)
{
if(!sb || !sb->active || button_state!=2)
return 0; // scrollbar neni aktivni
if(!sb->parent || sb->parent->GetType() < PTWindow)
{
throw CExc(eGUI, E_INTERNAL,"CGUIScrollbarButton::TimerImpulse> Parent window of scrollbar is not found");
}
CGUIWindow *wnd = (CGUIWindow*) sb->parent;
switch(scrollBarButtonType)
{
case S_Up : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-sb->shift,false);
else
wnd->SetWindowPositionVP(-sb->shift,0,false);
break;
case S_PageUp : mainGUI->SendCursorPos();
return 0;
/*
if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,-wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(-wnd->vp_sx,0,false);
*/
break;
case S_PageDown : mainGUI->SendCursorPos();
return 0;
/*
if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,wnd->vp_sy,false);
else
wnd->SetWindowPositionVP(wnd->vp_sx,0,false);
*/
break;
case S_Down : if(scrollBarType == Vertical)
wnd->SetWindowPositionVP(0,sb->shift,false);
else
wnd->SetWindowPositionVP(sb->shift,0,false);
break;
}
sb->RebuildScrollbar();
timerGUI->AddRequest(this,STD_SCROLLBAR_TIMER2);
return 0;
}
| 40.192459 | 305 | 0.619936 | HonzaMD |
e035c9a48b1b21dbbe2f9f9aa82a8342d379ddaa | 5,254 | cpp | C++ | torch_mlu/csrc/aten/operators/cnnl/internal/index_put_internal.cpp | Cambricon/catch | 2625da389f25a67066d20fb6b0c38250ef98f8ab | [
"BSD-2-Clause"
] | 20 | 2022-03-01T11:40:51.000Z | 2022-03-30T08:17:47.000Z | torch_mlu/csrc/aten/operators/cnnl/internal/index_put_internal.cpp | Cambricon/catch | 2625da389f25a67066d20fb6b0c38250ef98f8ab | [
"BSD-2-Clause"
] | null | null | null | torch_mlu/csrc/aten/operators/cnnl/internal/index_put_internal.cpp | Cambricon/catch | 2625da389f25a67066d20fb6b0c38250ef98f8ab | [
"BSD-2-Clause"
] | null | null | null | /*
All modification made by Cambricon Corporation: © 2022 Cambricon Corporation
All rights reserved.
All other contributions:
Copyright (c) 2014--2022, the respective contributors
All rights reserved.
For the list of contributors go to https://github.com/pytorch/pytorch/graphs/contributors
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 Intel 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 AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "aten/operators/cnnl/internal/cnnl_internal.h"
#include "aten/operators/cnnl/internal/internal_util.h"
namespace torch_mlu {
namespace cnnl {
namespace ops {
at::Tensor& cnnl_index_put_internal(at::Tensor& output, const at::Tensor& self,
std::vector<at::Tensor> indices, const at::Tensor& value,
bool accumulate) {
auto self_contiguous = cnnl_contiguous(self, c10::MemoryFormat::Contiguous);
auto output_contiguous = cnnl_contiguous(output, c10::MemoryFormat::Contiguous);
auto value_contiguous = cnnl_contiguous(value, c10::MemoryFormat::Contiguous);
// to preserve descriptor
std::vector<CnnlTensorDescriptor> not_skip_desc;
// to preserve transposed tensor
std::vector<at::Tensor> not_skip_tensor;
std::vector<cnnlTensorDescriptor_t> indices_desc;
std::vector<void *> indices_ptr_list;
// initialize descriptor
CnnlTensorDescriptor descInput;
CnnlTensorDescriptor descOutput;
CnnlTensorDescriptor descValue;
descInput.set(self_contiguous);
descOutput.set(output_contiguous);
descValue.set(value_contiguous);
// to generate indice ptr & descriptor
for (auto i = 0; i < indices.size(); ++i) {
if (indices[i].defined()) {
auto indice = cnnl_contiguous(indices[i], c10::MemoryFormat::Contiguous);
not_skip_tensor.emplace_back(indice);
auto impl = getMluTensorImpl(indice);
indices_ptr_list.emplace_back(impl->cnnlMalloc());
not_skip_desc.emplace_back();
not_skip_desc.back().set(indice);
indices_desc.emplace_back(not_skip_desc.back().desc());
} else {
indices_ptr_list.emplace_back(nullptr);
indices_desc.emplace_back(nullptr);
}
}
// malloc mlu memory
auto input_impl = getMluTensorImpl(self_contiguous);
auto output_impl = getMluTensorImpl(output_contiguous);
auto value_impl = getMluTensorImpl(value_contiguous);
auto input_ptr = input_impl->cnnlMalloc();
auto output_ptr = output_impl->cnnlMalloc();
auto value_ptr = value_impl->cnnlMalloc();
// prepare cnnl workspace
size_t workspace_size = 0;
auto handle = getCurrentHandle();
TORCH_CNNL_CHECK(
cnnlGetIndexPutWorkspaceSize(handle, descInput.desc(), indices_desc.data(),
indices_desc.size(), descValue.desc(), accumulate,
&workspace_size));
auto workspace = at::zeros(workspace_size,
self_contiguous.options().dtype(at::ScalarType::Byte).device(at::Device::Type::MLU));
auto workspace_impl = getMluTensorImpl(workspace);
auto workspace_ptr = workspace_impl->cnnlMalloc();
for (unsigned int i = 0; i < indices.size(); ++i) {
if (!indices[i].defined() || (indices[i].numel() == 0))
continue;
TORCH_CHECK(indices[i].dim() > 0,
"zero-dimensional tensor (at position ",
i,
") cannot be concatenated");
}
TORCH_CNNL_CHECK(cnnlIndexPut(handle, descInput.desc(), input_ptr,
indices_desc.data(), indices_ptr_list.data(),
indices_desc.size(),
descValue.desc(), value_ptr,
workspace_ptr, workspace_size, accumulate, true,
descOutput.desc(), output_ptr));
if (!output.is_contiguous(c10::MemoryFormat::Contiguous)) {
output.copy_(output_contiguous);
}
return output;
}
} // namespace ops
} // namespace cnnl
} // namespace torch_mlu
| 44.525424 | 93 | 0.710697 | Cambricon |
e03cc21a2068f1b4eae7e1fb9974d81dbc44ccd5 | 3,016 | cc | C++ | RecoMuon/L2MuonProducer/src/L2MuonCandidateProducer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | RecoMuon/L2MuonProducer/src/L2MuonCandidateProducer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | RecoMuon/L2MuonProducer/src/L2MuonCandidateProducer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | /** \class L2MuonCandidateProducer
*
* Intermediate step in the L2 muons selection.
* This class takes the L2 muons (which are reco::Tracks)
* and creates the correspondent reco::RecoChargedCandidate.
*
* Riccardo's comment:
* The separation between the L2MuonProducer and this class allows
* the interchangeability of the L2MuonProducer and the StandAloneMuonProducer
* This class is supposed to be removed once the
* L2/STA comparison will be done, then the RecoChargedCandidate
* production will be put into the L2MuonProducer class.
*
*
* \author J.Alcaraz
*/
// Framework
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/Common/interface/Handle.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "RecoMuon/L2MuonProducer/src/L2MuonCandidateProducer.h"
// Input and output collections
#include "DataFormats/RecoCandidate/interface/RecoChargedCandidate.h"
#include "DataFormats/RecoCandidate/interface/RecoChargedCandidateFwd.h"
#include <string>
using namespace edm;
using namespace std;
using namespace reco;
/// constructor with config
L2MuonCandidateProducer::L2MuonCandidateProducer(const ParameterSet& parameterSet){
LogTrace("Muon|RecoMuon|L2MuonCandidateProducer")<<" constructor called";
// StandAlone Collection Label
theSACollectionLabel = parameterSet.getParameter<InputTag>("InputObjects");
tracksToken = consumes<reco::TrackCollection>(theSACollectionLabel);
produces<RecoChargedCandidateCollection>();
}
/// destructor
L2MuonCandidateProducer::~L2MuonCandidateProducer(){
LogTrace("Muon|RecoMuon|L2MuonCandidateProducer")<<" L2MuonCandidateProducer destructor called";
}
/// reconstruct muons
void L2MuonCandidateProducer::produce(edm::StreamID sid, Event& event, const EventSetup& eventSetup) const {
const string metname = "Muon|RecoMuon|L2MuonCandidateProducer";
// Take the SA container
LogTrace(metname)<<" Taking the StandAlone muons: "<<theSACollectionLabel;
Handle<TrackCollection> tracks;
event.getByToken(tracksToken,tracks);
// Create a RecoChargedCandidate collection
LogTrace(metname)<<" Creating the RecoChargedCandidate collection";
auto candidates = std::make_unique<RecoChargedCandidateCollection>();
for (unsigned int i=0; i<tracks->size(); i++) {
TrackRef tkref(tracks,i);
Particle::Charge q = tkref->charge();
Particle::LorentzVector p4(tkref->px(), tkref->py(), tkref->pz(), tkref->p());
Particle::Point vtx(tkref->vx(),tkref->vy(), tkref->vz());
int pid = 13;
if(abs(q)==1) pid = q < 0 ? 13 : -13;
else LogWarning(metname) << "L2MuonCandidate has charge = "<<q;
RecoChargedCandidate cand(q, p4, vtx, pid);
cand.setTrack(tkref);
candidates->push_back(cand);
}
event.put(std::move(candidates));
LogTrace(metname)<<" Event loaded"
<<"================================";
}
| 35.904762 | 108 | 0.73508 | nistefan |
e03d6aa003ca8bd54ec8993b909c9093fa671d35 | 717 | cpp | C++ | APIs_Drivers/DigitalIn_ex_1/main.cpp | adbridge/mbed-os-examples-docs_only | 3f71b9fae755955ba6e5b2c8978a9f83f65c0f9c | [
"Apache-2.0"
] | 4 | 2018-11-21T06:56:02.000Z | 2021-12-02T13:51:18.000Z | APIs_Drivers/DigitalIn_ex_1/main.cpp | adbridge/mbed-os-examples-docs_only | 3f71b9fae755955ba6e5b2c8978a9f83f65c0f9c | [
"Apache-2.0"
] | 62 | 2018-10-12T16:19:19.000Z | 2021-09-19T23:44:21.000Z | APIs_Drivers/DigitalIn_ex_1/main.cpp | adbridge/mbed-os-examples-docs_only | 3f71b9fae755955ba6e5b2c8978a9f83f65c0f9c | [
"Apache-2.0"
] | 27 | 2018-10-12T15:52:45.000Z | 2021-08-13T05:42:33.000Z | /*
* Copyright (c) 2006-2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
DigitalIn mypin(SW2); // change this to the button on your board
DigitalOut myled(LED1);
int main()
{
// check mypin object is initialized and connected to a pin
if (mypin.is_connected()) {
printf("mypin is connected and initialized! \n\r");
}
// Optional: set mode as PullUp/PullDown/PullNone/OpenDrain
mypin.mode(PullNone);
// press the button and see the console / led change
while (1) {
printf("mypin has value : %d \n\r", mypin.read());
myled = mypin; // toggle led based on value of button
ThisThread::sleep_for(250);
}
}
| 25.607143 | 65 | 0.645746 | adbridge |
e03e802c063552fbd089e01242b5e9e197ee469f | 2,455 | cpp | C++ | Code/Object Database/Blueprint/Blueprint.cpp | QuestionableM/Blueprint-Converter | 4f9b8d92f0c94a77098bfa2d9b45fe81f79aace9 | [
"MIT"
] | 5 | 2021-08-07T02:45:03.000Z | 2022-01-24T09:30:42.000Z | Code/Object Database/Blueprint/Blueprint.cpp | QuestionableM/Blueprint-Converter | 4f9b8d92f0c94a77098bfa2d9b45fe81f79aace9 | [
"MIT"
] | 1 | 2021-12-26T19:14:14.000Z | 2021-12-26T19:14:14.000Z | Code/Object Database/Blueprint/Blueprint.cpp | QuestionableM/Blueprint-Converter | 4f9b8d92f0c94a77098bfa2d9b45fe81f79aace9 | [
"MIT"
] | 1 | 2022-01-08T19:17:25.000Z | 2022-01-08T19:17:25.000Z | #include "Blueprint.h"
#include "Lib/OtherFunc/OtherFunc.h"
#include "Lib/File/FileFunc.h"
#include "Lib/Json/JsonFunc.h"
#include "Lib/String/String.h"
#include <filesystem>
namespace fs = std::filesystem;
namespace SMBC
{
const static std::unordered_map<std::wstring, bool> SupportedImageExtensions = { { L".jpg", 1 }, { L".png", 1 }, { L".bmp", 1 } };
bool Blueprint::IsSupportedExtension(const std::wstring& _ext)
{
if (SupportedImageExtensions.find(_ext) != SupportedImageExtensions.end())
return true;
return false;
}
std::wstring Blueprint::FixBlueprintName(const std::wstring& name)
{
std::wstring _Output = L"";
for (const wchar_t& _Letter : name)
{
if (Other::IsLetterAllowed(_Letter))
_Output += _Letter;
}
return _Output;
}
void Blueprint::FindBlueprintImage()
{
if (!File::Exists(this->Folder) || !this->ImagePath.empty()) return;
fs::directory_iterator dir_iter(this->Folder, fs::directory_options::skip_permission_denied);
for (const auto& dir : dir_iter)
{
if (!dir.is_regular_file()) continue;
const fs::path& imgPath = dir.path();
if (imgPath.has_extension() && this->IsSupportedExtension(imgPath.extension().wstring()))
{
this->ImagePath = imgPath.wstring();
return;
}
}
}
bool Blueprint::BlueprintExists()
{
bool _FolderExists = File::Exists(this->Folder);
bool _PathExists = File::Exists(this->Path);
return (_FolderExists && _PathExists);
}
Blueprint* Blueprint::CreateBlueprintFromDirectory(const std::wstring& path)
{
const std::wstring bpJson = (path + L"/description.json");
if (!File::Exists(bpJson)) return nullptr;
const nlohmann::json bpDesc = Json::LoadParseJson(bpJson, true);
if (!bpDesc.is_object()) return nullptr;
const auto& bpName = Json::Get(bpDesc, "name");
const auto& bpType = Json::Get(bpDesc, "type");
if (!bpName.is_string() || !bpType.is_string()) return nullptr;
if (bpType.get<std::string>() != "Blueprint") return nullptr;
const auto& file_id_obj = Json::Get(bpDesc, "fileId");
long long file_id = file_id_obj.is_number() ? file_id_obj.get<long long>() : 0ll;
Blueprint* new_bp = new Blueprint();
new_bp->Name = String::ToWide(bpName.get<std::string>());
new_bp->Path = bpJson;
new_bp->Folder = path;
new_bp->WorkshopId = (file_id > 0) ? std::to_wstring(file_id) : L"";
new_bp->LowerName = String::ToLower(new_bp->Name);
new_bp->FindBlueprintImage();
return new_bp;
}
} | 26.978022 | 131 | 0.685947 | QuestionableM |
e0411a6404bca9d2b90aefb3ef94b78edb1ee377 | 8,848 | cpp | C++ | src/puzzles.cpp | LeifAndersen/remarkable_puzzles | 2745eceeb5965406d3e9dd5fbf6b5057706a3f69 | [
"MIT"
] | 8 | 2021-01-14T16:07:05.000Z | 2021-12-07T11:35:31.000Z | src/puzzles.cpp | LeifAndersen/remarkable_puzzles | 2745eceeb5965406d3e9dd5fbf6b5057706a3f69 | [
"MIT"
] | 15 | 2021-01-14T21:00:03.000Z | 2022-01-04T04:09:12.000Z | src/puzzles.cpp | LeifAndersen/remarkable_puzzles | 2745eceeb5965406d3e9dd5fbf6b5057706a3f69 | [
"MIT"
] | 2 | 2021-01-14T20:56:15.000Z | 2021-03-04T19:59:13.000Z | #include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sys/time.h>
#include "puzzles.hpp"
#include "config.hpp"
// === Debug ===
#include "debug.hpp"
#ifdef NDEBUG
#undef DEBUG_FRONTEND
#undef DEBUG_DRAW
#undef DEBUG_TIMER
#endif
#ifdef DEBUG_FRONTEND
#define DEBUG_DRAW
#define DEBUG_TIMER
#endif
#ifdef DEBUG_DRAW
#define dbg_draw debugf
#define dbg_color(color) __dbg_color(handle, color)
int __dbg_color(void *handle, int color) {
float * rgb = static_cast<DrawingApi*>(handle)->get_color(color);
int r = rgb[0] * 255;
int g = rgb[1] * 255;
int b = rgb[2] * 255;
return (r << 16) | (g << 8) | b;
}
#else
#define dbg_draw(...)
#define dbg_color(...)
#endif
#ifdef DEBUG_TIMER
#define dbg_timer debugf
#else
#define dbg_timer(...)
#endif
// === Frontend definitions ===
void frontend::init_midend(DrawingApi * drawer, const game *ourgame)
{
if (me != NULL)
midend_free(me);
this->ourgame = ourgame;
config = Config::from_game(ourgame);
me = midend_new(this, ourgame, &cpp_drawing_api, drawer);
drawer->set_frontend(this);
drawer->update_colors();
}
bool frontend::load_from_file(const std::string & filename)
{
std::ifstream f(filename);
if (!f) {
std::cerr << "Error opening save file for reading: " << filename << std::endl;
return false;
}
auto write_fn = [](void * fs, void * buf, int len) {
std::ifstream * f = static_cast<std::ifstream *>(fs);
f->read(static_cast<char*>(buf), len);
return f->good();
};
const char * err = midend_deserialise(me, write_fn, &f);
if (err == NULL) {
return true;
} else {
std::cerr << "Error parsing save file: " << filename << std::endl;
std::cerr << err << std::endl;
return false;
}
}
bool frontend::save_to_file(const std::string & filename)
{
std::ofstream f(filename);
if (!f) {
std::cerr << "Error opening save file for writing: " << filename << std::endl;
return false;
}
auto write_fn = [](void * fs, const void * buf, int len) {
std::ofstream * f = static_cast<std::ofstream *>(fs);
if (f)
f->write(static_cast<const char*>(buf), len);
};
midend_serialise(me, write_fn, &f);
return f.good();
}
// === Midend API ===
extern "C" {
void fatal(const char *fmt, ...);
void get_random_seed(void **randseed, int *randseedsize);
void frontend_default_colour(frontend *fe, float *output);
void deactivate_timer(frontend *fe);
void activate_timer(frontend *fe);
}
#ifndef PUZZLES_FATAL_NODEF
void fatal(const char *fmt, ...)
{
/* Lifted from nestedvm.c */
va_list ap;
std::fprintf(stderr, "fatal error: ");
va_start(ap, fmt);
std::vfprintf(stderr, fmt, ap);
va_end(ap);
std::fprintf(stderr, "\n");
std::exit(1);
}
#endif
#ifndef PUZZLES_GET_RANDOM_SEED_NODEF
void get_random_seed(void **randseed, int *randseedsize)
{
/* Lifted from nestedvm.c */
struct timeval *tvp = snew(struct timeval);
gettimeofday(tvp, NULL);
*randseed = (void *)tvp;
*randseedsize = sizeof(struct timeval);
}
#endif
void frontend_default_colour(frontend *fe, float *output)
{
fe->frontend_default_colour(output);
}
void deactivate_timer(frontend *fe)
{
dbg_timer("deactivate_timer()\n");
fe->deactivate_timer();
}
void activate_timer(frontend *fe)
{
dbg_timer("activate_timer()\n");
fe->activate_timer();
}
// == Drawing API ==
void DrawingApi::update_colors()
{
// load colors from midend
if (colors != nullptr)
sfree(colors);
colors = midend_colours(fe->me, &ncolors);
// overwrite with colors from the config file
const std::vector<float> & cfg_colors = fe->config.colors;
if (!cfg_colors.empty()) {
for (int i = 0; i < std::min<int>(ncolors, cfg_colors.size()); i++) {
if (cfg_colors[i] < 0.0) continue;
colors[3*i+0] = cfg_colors[i];
colors[3*i+1] = cfg_colors[i];
colors[3*i+2] = cfg_colors[i];
}
}
}
void cpp_draw_text(void *handle, int x, int y, int fonttype,
int fontsize, int align, int colour,
const char *text)
{
dbg_draw("draw_text(%d, %d, %d, %d, %d, %x, \"%s\")\n",
x, y, fonttype, fontsize, align, dbg_color(colour), text);
static_cast<DrawingApi*>(handle)
->draw_text(x, y, fonttype, fontsize, align, colour, text);
}
void cpp_draw_rect(void *handle, int x, int y, int w, int h, int colour)
{
dbg_draw("draw_rect(%d, %d, %d, %d, %x)\n", x, y, w, h, dbg_color(colour));
static_cast<DrawingApi*>(handle)->draw_rect(x, y, w, h, colour);
}
void cpp_draw_line(void *handle, int x1, int y1, int x2, int y2, int colour)
{
dbg_draw("draw_line(%d, %d, %d, %d, %x)\n", x1, y1, x2, y2, dbg_color(colour));
static_cast<DrawingApi*>(handle)->draw_line(x1, y1, x2, y2, colour);
}
void cpp_draw_polygon(void *handle, int *coords, int npoints,
int fillcolour, int outlinecolour)
{
#ifdef DEBUG_DRAW
dbg_draw("draw_polygon(");
dbg_draw("[");
for (int i = 0; i < 2*npoints; i+=2) {
dbg_draw("%d, %d", coords[i], coords[i+1]);
if (i < 2*(npoints-1))
dbg_draw(",");
}
dbg_draw("], ");
dbg_draw("%d, ");
if (fillcolour == -1)
dbg_draw("-1, ");
else
dbg_draw("%x, ", dbg_color(fillcolour));
dbg_draw("%x)\n", dbg_color(outlinecolour));
#endif
static_cast<DrawingApi*>(handle)
->draw_polygon(coords, npoints, fillcolour, outlinecolour);
}
void cpp_draw_circle(void *handle, int cx, int cy, int radius,
int fillcolour, int outlinecolour)
{
#ifdef DEBUG_DRAW
dbg_draw("draw_circle(%d, %d, %d, ", cx, cy, radius);
if (fillcolour == -1)
dbg_draw("-1, ");
else
dbg_draw("%x, ", dbg_color(fillcolour));
dbg_draw("%x)\n", dbg_color(outlinecolour));
#endif
static_cast<DrawingApi*>(handle)
->draw_circle(cx, cy, radius, fillcolour, outlinecolour);
}
void cpp_draw_thick_line(void *handle, float thickness,
float x1, float y1, float x2, float y2,
int colour)
{
dbg_draw("draw_thick_line(%f, %f, %f, %f, %f, %x)\n",
thickness, x1, x2, y1, y2, dbg_color(colour));
static_cast<DrawingApi*>(handle)
->draw_thick_line(thickness, x1, y1, x2, y2, colour);
}
void cpp_draw_update(void *handle, int x, int y, int w, int h)
{
dbg_draw("draw_update(%d, %d, %d, %d)\n", x, y, w, h);
static_cast<DrawingApi*>(handle)->draw_update(x, y, w, h);
}
void cpp_clip(void *handle, int x, int y, int w, int h)
{
dbg_draw("clip(%d, %d, %d, %d)\n", x, y, w, h);
static_cast<DrawingApi*>(handle)->clip(x, y, w, h);
}
void cpp_unclip(void *handle)
{
dbg_draw("unclip()\n");
static_cast<DrawingApi*>(handle)->unclip();
}
void cpp_start_draw(void *handle)
{
dbg_draw("start_draw()\n");
static_cast<DrawingApi*>(handle)->start_draw();
}
void cpp_end_draw(void *handle)
{
dbg_draw("end_draw()\n");
static_cast<DrawingApi*>(handle)->end_draw();
}
void cpp_status_bar(void *handle, const char *text)
{
dbg_draw("status_bar(\"%s\")\n", text);
static_cast<DrawingApi*>(handle)->status_bar(text);
}
blitter * cpp_blitter_new(void *handle, int w, int h)
{
dbg_draw("blitter_new(%d, %d) => ");
blitter * bl = static_cast<DrawingApi*>(handle)->blitter_new(w, h);
dbg_draw("%p\n", (void*)bl);
return bl;
}
void cpp_blitter_free(void *handle, blitter *bl)
{
dbg_draw("blitter_free(%p)\n", (void*)bl);
static_cast<DrawingApi*>(handle)->blitter_free(bl);
}
void cpp_blitter_save(void *handle, blitter *bl, int x, int y)
{
dbg_draw("blitter_save(%p, %d, %d)\n", (void*)bl, x, y);
static_cast<DrawingApi*>(handle)->blitter_save(bl, x, y);
}
void cpp_blitter_load(void *handle, blitter *bl, int x, int y)
{
dbg_draw("blitter_load(%p, %d, %d)\n", (void*)bl, x, y);
static_cast<DrawingApi*>(handle)->blitter_load(bl, x, y);
}
char * cpp_text_fallback(void *handle, const char *const *strings,
int nstrings)
{
return static_cast<DrawingApi*>(handle)->text_fallback(strings, nstrings);
}
struct drawing_api frontend::cpp_drawing_api = {
cpp_draw_text,
cpp_draw_rect,
cpp_draw_line,
cpp_draw_polygon,
cpp_draw_circle,
cpp_draw_update,
cpp_clip,
cpp_unclip,
cpp_start_draw,
cpp_end_draw,
cpp_status_bar,
cpp_blitter_new,
cpp_blitter_free,
cpp_blitter_save,
cpp_blitter_load,
NULL, NULL, NULL, NULL, NULL, NULL, /* {begin,end}_{doc,page,puzzle} */
NULL, NULL, /* line_width, line_dotted */
cpp_text_fallback,
};
| 26.41194 | 86 | 0.615732 | LeifAndersen |
e0416211c0e40fd25cdad8bdd7988763f08e11b4 | 11,279 | cpp | C++ | semantic_kitti/src/semantic_kitti_read.cpp | wangx1996/Semantic-Kitti-Label-Read | 680ab68b1c053fd2e19ddc6f236ab6049ff52305 | [
"MIT"
] | null | null | null | semantic_kitti/src/semantic_kitti_read.cpp | wangx1996/Semantic-Kitti-Label-Read | 680ab68b1c053fd2e19ddc6f236ab6049ff52305 | [
"MIT"
] | null | null | null | semantic_kitti/src/semantic_kitti_read.cpp | wangx1996/Semantic-Kitti-Label-Read | 680ab68b1c053fd2e19ddc6f236ab6049ff52305 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
#include <ctime>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#include <math.h>
//PCL
#include <pcl/common/transforms.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/impl/point_cloud_geometry_handlers.hpp>//自定义点云类型时要加
//Eigen
#include <Eigen/Dense>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
//Boost
#include <boost/tokenizer.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
//ROS
#include <ros/ros.h>
#include <pcl_ros/transforms.h>
#include <pcl_conversions/pcl_conversions.h>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
using namespace std;
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
int range_img_width_ = 2083;
struct PointXYZIR{
PCL_ADD_POINT4D;
float intensity;
uint16_t ring;
uint16_t px;
uint16_t py;
uint16_t seglabel;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
}EIGEN_ALIGN16;
POINT_CLOUD_REGISTER_POINT_STRUCT(PointXYZIR,
(float,x,x)
(float,y,y)
(float,z,z)
(float,intensity,intensity)
(uint16_t,ring,ring)
(uint16_t,px,px)
(uint16_t,py,py)
(uint16_t,seglabel,seglabel)
)
template <class Type>
Type stringToNum(const string& str)
{
istringstream iss(str);
Type num;
iss >> num;
return num;
}
template<typename T> string toString(const T& t) {
ostringstream oss;
oss << t;
return oss.str();
}
void calPolarAngle(float x, float y, float &temp_tangle){
if (x == 0 && y == 0) {
temp_tangle = 0;
} else if (y >= 0) {
temp_tangle = (float) atan2(y, x);
} else if (y <= 0) {
temp_tangle = (float) atan2(y, x) + 2 * M_PI;
}
}
int fileNameFilter(const struct dirent *cur) {
std::string str(cur->d_name);
if (str.find(".bin") != std::string::npos||str.find(".velodata") != std::string::npos
|| str.find(".pcd") != std::string::npos
|| str.find(".png") != std::string::npos
|| str.find(".jpg") != std::string::npos
|| str.find(".txt") != std::string::npos) {
return 1;
}
return 0;
}
bool get_all_files(const std::string& dir_in,
std::vector<std::string>& files) {
if (dir_in.empty()) {
return false;
}
struct stat s;
stat(dir_in.c_str(), &s);
if (!S_ISDIR(s.st_mode)) {
return false;
}
DIR* open_dir = opendir(dir_in.c_str());
if (NULL == open_dir) {
std::exit(EXIT_FAILURE);
}
dirent* p = nullptr;
while ((p = readdir(open_dir)) != nullptr) {
struct stat st;
if (p->d_name[0] != '.') {
std::string name = dir_in + std::string("/")
+ std::string(p->d_name);
stat(name.c_str(), &st);
if (S_ISDIR(st.st_mode)) {
get_all_files(name, files);
} else if (S_ISREG(st.st_mode)) {
boost::char_separator<char> sepp { "." };
tokenizer tokn(std::string(p->d_name), sepp);
vector<string> filename_sep(tokn.begin(), tokn.end());
string type_ = "." + filename_sep[1];
break;
}
}
}
struct dirent **namelist;
int n = scandir(dir_in.c_str(), &namelist, fileNameFilter, alphasort);
if (n < 0) {
return false;
}
for (int i = 0; i < n; ++i) {
std::string filePath(namelist[i]->d_name);
files.push_back(filePath);
free(namelist[i]);
};
free(namelist);
closedir(open_dir);
return true;
}
bool Load_Sensor_Data_Path(std::vector<std::string>& lidarfile_name, string& path){
string lidar_file_path = path;
cout<<lidar_file_path<<endl;
if(!get_all_files(lidar_file_path, lidarfile_name))
return false;
return true;
}
int get_quadrant(pcl::PointXYZI point)
{
int res = 0;
float x = point.x;
float y = point.y;
if (x > 0 && y >= 0)
res = 1;
else if (x <= 0 && y > 0)
res = 2;
else if (x < 0 && y <= 0)
res = 3;
else if (x >= 0 && y < 0)
res = 4;
return res;
}
void AddRingInfo(pcl::PointCloud<pcl::PointXYZI>& input, pcl::PointCloud<PointXYZIR>& output)
{
int previous_quadrant = 0;
uint16_t ring_ = (uint16_t)64-1;
for (pcl::PointCloud<pcl::PointXYZI>::iterator pt = input.points.begin(); pt < input.points.end()-1; ++pt){
int quadrant = get_quadrant(*pt);
if (quadrant == 1 && previous_quadrant == 4 && ring_ > 0)
ring_ -= 1;
PointXYZIR point;
point.x = pt->x;
point.y = pt->y;
point.z = pt->z;
point.intensity = pt->intensity;
point.ring = ring_;
output.push_back(point);
previous_quadrant = quadrant;
}
}
bool LoadKittiPointcloud(pcl::PointCloud<pcl::PointXYZI>& cloud_IN, string path){
string lidar_filename_path = path;
ifstream inputfile;
inputfile.open(lidar_filename_path, ios::binary);
if (!inputfile) {
cerr << "ERROR: Cannot open file " << lidar_filename_path
<< "! Aborting..." << endl;
return false;
}
inputfile.seekg(0, ios::beg);
for (int i = 0; inputfile.good() && !inputfile.eof(); i++) {
pcl::PointXYZI p;
inputfile.read((char *) &p.x, 3 * sizeof(float));
inputfile.read((char *) &p.intensity, sizeof(float));
cloud_IN.points.push_back(p);
}
return true;
}
void RangeProjection(pcl::PointCloud<PointXYZIR>& Cloud_IN){
for(int i=0; i<Cloud_IN.points.size(); ++i){
float u(0);
calPolarAngle(Cloud_IN.points[i].x, Cloud_IN.points[i].y, u);
int col = round((range_img_width_-1)*(u *180.0/M_PI)/360.0);
int ind = Cloud_IN.points[i].ring;
Cloud_IN.points[i].py = ind;
Cloud_IN.points[i].px = col;
}
}
int main(int argc, char** argv){
// ##################### label ########################
unordered_map<int, string> labels;
unordered_map<int, vector<int> > color_map;
labels[0] = "unlabeled";
labels[1] = "outlier";
labels[10]= "car";
labels[11]= "bicycle";
labels[13]= "bus";
labels[15]= "motorcycle";
labels[16]= "on-rails";
labels[18]= "truck";
labels[20]= "other-vehicle";
labels[30]= "person";
labels[31]= "bicyclist";
labels[32]= "motorcyclist";
labels[40]= "road";
labels[44]= "parking";
labels[48]= "sidewalk";
labels[49]= "other-ground";
labels[50]= "building";
labels[51]= "fence";
labels[52]= "other-structure";
labels[60]= "lane-marking";
labels[70]= "vegetation";
labels[71]= "trunk";
labels[72]= "terrain";
labels[80]= "pole";
labels[81]= "traffic-sign";
labels[99]= "other-object";
labels[252]= "moving-car";
labels[253]= "moving-bicyclist";
labels[254]= "moving-person";
labels[255]= "moving-motorcyclist";
labels[256]= "moving-on-rails";
labels[257]= "moving-bus";
labels[258]= "moving-truck";
labels[259]= "moving-other-vehicle";
color_map[0] = {0, 0, 0};
color_map[1] = {0, 0, 255};
color_map[10] = {245, 150, 100};
color_map[11] = {245, 230, 100};
color_map[13] = {250, 80, 100};
color_map[15] = {150, 60, 30};
color_map[16] = {255, 0, 0};
color_map[18] = {180, 30, 80};
color_map[20] = {255, 0, 0};
color_map[30] = {30, 30, 255};
color_map[31] = {200, 40, 255};
color_map[32] = {90, 30, 150};
color_map[40] = {255, 0, 255};
color_map[44] = {255, 150, 255};
color_map[48] = {75, 0, 75};
color_map[49] = {75, 0, 175};
color_map[50] = {0, 200, 255};
color_map[51] = {50, 120, 255};
color_map[52] = {0, 150, 255};
color_map[60] = {170, 255, 150};
color_map[70] = {0, 175, 0};
color_map[71] = {0, 60, 135};
color_map[72] = {80, 240, 150};
color_map[80] = {150, 240, 255};
color_map[81] = {0, 0, 255};
color_map[99] = {255, 255, 50};
color_map[252] = {245, 150, 100};
color_map[256] = {255, 0, 0};
color_map[253] = {200, 40, 255};
color_map[254] = {30, 30, 255};
color_map[255] = {90, 30, 150};
color_map[257] = {250, 80, 100};
color_map[258] = {180, 30, 80};
color_map[259] = {255, 0, 0};
ros::init(argc, argv, "semantic_kitti_node");
ros::NodeHandle nh;
ros::Publisher publidar = nh.advertise <sensor_msgs::PointCloud2> ("/seg_pointcloud", 1);
image_transport::ImageTransport it(nh);
image_transport::Publisher pubimg = it.advertise("/seg_image", 1);
// ##################### data path ########################
string datapath = "/media/wx/Software/semantic_kitti/data_odometry_velodyne/dataset/sequences/05/velodyne/";
string lablespath = "/media/wx/Software/semantic_kitti/data_odometry_labels/dataset/sequences/05/labels/";
vector<string> lidarname;
if(!Load_Sensor_Data_Path(lidarname, datapath)){
cout<<"Detecion file wrong!"<<endl;
std::abort();
}
cout<<lidarname.size()<<endl;
int maxframe = lidarname.size();
vector<int> frame_num;
boost::char_separator<char> sep { " " };
sort(frame_num.begin(), frame_num.end(), [](int a, int b){ return a<b; });
int frame = 0;
ros::Rate r(10);
while(ros::ok() && frame < maxframe){
// ##################### load data ########################
string cloudpath = datapath + lidarname[frame];
boost::char_separator<char> sept {"."};
tokenizer tokn(lidarname[frame], sept);
vector<string> filename_sep(tokn.begin(), tokn.end());
string lablepath = lablespath + filename_sep[0] + ".label";
pcl::PointCloud<pcl::PointXYZI>::Ptr Cloud(
new pcl::PointCloud<pcl::PointXYZI>);
pcl::PointCloud<PointXYZIR>::Ptr cloud_ring(
new pcl::PointCloud<PointXYZIR>);
LoadKittiPointcloud(*Cloud, cloudpath);
AddRingInfo(*Cloud, *cloud_ring);
RangeProjection(*cloud_ring);
// ##################### load label ########################
std::ifstream inputfile;
inputfile.open(lablepath.c_str(), ios::binary);
vector<uint32_t> label;
if (!inputfile) {
cerr << "ERROR: Cannot open file " << lablepath
<< "! Aborting..." << endl;
}
inputfile.seekg(0, ios::beg);
for (int i = 0; inputfile.good() && !inputfile.eof(); i++) {
uint32_t data;
inputfile.read(reinterpret_cast<char*>(&data), sizeof(data));
label.push_back(data);
}
vector<uint16_t> instance;
vector<uint16_t> semantic_label;
for(int i=0; i<label.size(); ++i){
uint16_t slabel = label[i]&0xFFFF;
uint16_t inst = label[i]>>16;
instance.push_back(inst);
semantic_label.push_back(slabel);
cloud_ring->points[i].seglabel = slabel;
}
// ##################### visual ########################
pcl::PointCloud<pcl::PointXYZRGB>::Ptr Cloudcolor(
new pcl::PointCloud<pcl::PointXYZRGB>);
cv::Mat segimage = cv::Mat::zeros(64, (int)range_img_width_, CV_8UC3);
for(int i=0; i<cloud_ring->points.size(); ++i){
pcl::PointXYZRGB p;
p.x = cloud_ring->points[i].x;
p.y = cloud_ring->points[i].y;
p.z = cloud_ring->points[i].z;
p.r = color_map[cloud_ring->points[i].seglabel][2];
p.g = color_map[cloud_ring->points[i].seglabel][1];
p.b = color_map[cloud_ring->points[i].seglabel][0];
segimage.at<cv::Vec3b>(63- cloud_ring->points[i].py, cloud_ring->points[i].px) = cv::Vec3b(p.b, p.g, p.r);
Cloudcolor->points.push_back(p);
}
sensor_msgs::PointCloud2 ros_cloud;
pcl::toROSMsg(*Cloudcolor, ros_cloud);
ros_cloud.header.frame_id = "global_init_frame";
publidar.publish(ros_cloud);
sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8",segimage).toImageMsg();
pubimg.publish(msg);
cv::imshow("seg_gt", segimage);
cv::waitKey(1);
r.sleep();
frame++;
}
return 0;
}
| 25.869266 | 109 | 0.646334 | wangx1996 |
e043eb1f59f4577012d4abf7160302b79a6c3e6b | 8,144 | cpp | C++ | NYPR/PlateLocate/NYPlateDetect.cpp | NathanYu1124/PLR_Vision | 2eceda3462e656a257a6cabb18fef6bee448fb9b | [
"Apache-2.0"
] | 17 | 2018-06-20T17:48:47.000Z | 2021-12-01T10:40:27.000Z | NYPR/PlateLocate/NYPlateDetect.cpp | rsingh2083/PLR_Vision | 2eceda3462e656a257a6cabb18fef6bee448fb9b | [
"Apache-2.0"
] | null | null | null | NYPR/PlateLocate/NYPlateDetect.cpp | rsingh2083/PLR_Vision | 2eceda3462e656a257a6cabb18fef6bee448fb9b | [
"Apache-2.0"
] | 10 | 2019-03-02T07:15:34.000Z | 2021-08-11T12:07:06.000Z | //
// NYPlateDetect.cpp
// NYPlateRecognition
//
// Created by NathanYu on 24/01/2018.
// Copyright © 2018 NathanYu. All rights reserved.
//
#include "NYPlateDetect.hpp"
// 检测图片中的车牌
vector<NYPlate> NYPlateDetect::detectPlates(Mat src)
{
vector<NYPlate> platesVec;
vector<NYPlate> sobel_plates;
vector<NYPlate> color_plates;
NYPlateLocate locater;
NYPlateJudge judge;
// 初始化svm模型地址
judge.SVM_MODEL_PATH = svmModelPath;
// 颜色定位
color_plates = locater.plateLocateWithColor(src);
color_plates = judge.judgePlates(color_plates);
platesVec.insert(platesVec.end(), color_plates.begin(), color_plates.end());
// cout << "color plates size : " << color_plates.size() << endl;
// sobel定位
sobel_plates = locater.plateLocateWithSobel(src);
sobel_plates = judge.judgePlates(sobel_plates);
reProcessPlates(src, sobel_plates);
// cout << "sobel plates size : " << sobel_plates.size() << endl;
platesVec.insert(platesVec.end(), sobel_plates.begin(),sobel_plates.end());
// 去除重复的车牌,去除sobel与color的交集
platesVec = deleteRepeatPlates(color_plates, sobel_plates);
// cout << "total plates size : " << platesVec.size() << endl;
// 设置车牌颜色
for (int i = 0; i < platesVec.size(); i++) {
}
return platesVec;
}
// 检测视频流中的车牌: 牺牲精度,提高处理速度
vector<NYPlate> NYPlateDetect::detectPlatesInVideo(Mat src)
{
vector<NYPlate> platesVec;
NYPlateLocate locater;
NYPlateJudge judge;
// 初始化svm模型地址
judge.SVM_MODEL_PATH = svmModelPath;
// 仅sobel定位
platesVec = locater.plateLocateWithSobel(src);
platesVec = judge.judgePlates(platesVec);
reProcessPlates(src, platesVec);
return platesVec;
}
// 去除重复的车牌 (根据车牌区域中心位置去除)
vector<NYPlate> NYPlateDetect::deleteRepeatPlates(vector<NYPlate> colorVec, vector<NYPlate> sobelVec)
{
vector<NYPlate> resultVec;
if ((colorVec.size() == 0) && (sobelVec.size() != 0)) {
return sobelVec;
} else if ((colorVec.size() != 0) && (sobelVec.size() == 0)){
return colorVec;
} else if ((colorVec.size() == 0) && (sobelVec.size() == 0)){
return resultVec;
} else {
vector<NYPlate>::iterator color_itr = colorVec.begin();
vector<NYPlate>::iterator sobel_itr = sobelVec.begin();
while (color_itr != colorVec.end()) {
NYPlate color_plate = NYPlate(*color_itr);
RotatedRect color_rect = color_plate.getPlatePos();
// 每次都重新指向头指针
sobel_itr = sobelVec.begin();
while (sobel_itr != sobelVec.end()) {
NYPlate sobel_plate = NYPlate(*sobel_itr);
RotatedRect sobel_rect = sobel_plate.getPlatePos();
float offset_x = sobel_rect.center.x - color_rect.center.x;
float offset_y = sobel_rect.center.y - sobel_rect.center.y;
if (abs(offset_x) < 20 && abs(offset_y) < 20) {
sobelVec.erase(sobel_itr);
} else{
sobel_itr++;
}
}
color_itr++;
}
resultVec.insert(resultVec.end(), colorVec.begin(),colorVec.end());
resultVec.insert(resultVec.end(), sobelVec.begin(),sobelVec.end());
return resultVec;
}
}
// 车牌区域精定位
void NYPlateDetect::reProcessPlates(Mat src, vector<NYPlate> &plates)
{
for (int i = 0; i < plates.size(); i++) {
RotatedRect roi_rect = plates[i].getPlatePos();
// 先扩大ROI区域,1,避免ROI区域只截取到部分车牌 2,为下面的膨胀操作提供足够的空间
// roi_rect.size.width += 20;
// roi_rect.size.height += 20;
// 纠正用RotatedRect截取ROI,宽/高<1 错误截取的问题
if (roi_rect.angle < (-70) && roi_rect.size.width < roi_rect.size.height) {
swap(roi_rect.size.width, roi_rect.size.height);
}
Mat roi_mat;
getRectSubPix(src, roi_rect.size, roi_rect.center, roi_mat);
// 转换到HSV空间
Color plateColor = plates[i].getPlateColor();
Mat roi_hsv;
if (plateColor == BLUE) { // 蓝牌
roi_hsv = locater.convertColorToGray(roi_mat, BLUE);
} else if (plateColor == YELLOW) { // 黄牌
roi_hsv = locater.convertColorToGray(roi_mat, YELLOW);
} else { // 未知暂定为蓝牌
roi_hsv = locater.convertColorToGray(roi_mat, BLUE);
}
// 去除噪声
GaussianBlur(roi_hsv, roi_hsv, Size(3, 3), 0,0, BORDER_DEFAULT);
Mat element = getStructuringElement(MORPH_RECT, Size(13,7));
dilate(roi_hsv, roi_hsv, element);
// Canny边缘检测
Canny(roi_hsv, roi_hsv, 50, 200, 3);
// hough变换找直线
vector<Vec4i> lines;
HoughLinesP(roi_hsv, lines, 1, CV_PI/180, 50,50,10);
cvtColor(roi_hsv, roi_hsv, COLOR_GRAY2BGR);
float changedAngle = 0;
int line_count = 0;
for (size_t i = 0; i < lines.size(); i++) {
Vec4i line = lines[i];
Point p1 = Point(line[0], line[1]);
Point p2 = Point(line[2], line[3]);
cv::line(roi_hsv, p1, p2, Scalar(0,255,0), 1, LINE_AA);
float angle = atan2(p1.y-p2.y, p1.x-p2.x) * 180 / CV_PI;
if (angle > 170 || angle < -170) {
if ((angle < 0 && changedAngle > 0) || (angle > 0 && changedAngle < 0)) {
angle = - angle;
}
changedAngle += angle;
line_count++;
}
}
// 直线的平均倾斜角度
changedAngle = changedAngle / line_count;
Mat roi_rotated;
float angle = 0;
if (changedAngle < 0) { // 调整到-180
angle = -(-180 - changedAngle);
} else if (changedAngle == 0) {
angle = 0;
}
else { // 调整到180
if (changedAngle > 170) {
angle = -(180 - changedAngle);
}
}
Point2f center(roi_rect.size.width / 2, roi_rect.size.height / 2); // 旋转中心
Mat matrix = getRotationMatrix2D(center, angle, 1); // 旋转矩阵
Mat src_rotated;
warpAffine(roi_mat, roi_rotated, matrix, Size(roi_rect.size.width, roi_rect.size.height), INTER_CUBIC); // 仿射变换旋转Mat
// 精定位,只截取车牌区域
Mat temp = roi_rotated.clone();
Mat region;
if (plateColor == BLUE) { // 蓝色车牌
region = locater.convertColorToGray(temp, BLUE);
} else if (plateColor == YELLOW) { // 黄色车牌
region = locater.convertColorToGray(temp, YELLOW);
} else { // 车牌颜色未知,暂按蓝色处理
region = locater.convertColorToGray(temp, BLUE);
}
Mat src_closed;
Mat ele = getStructuringElement(MORPH_RECT, Size(17, 3));
morphologyEx(region, src_closed, MORPH_CLOSE, ele);
vector<vector<Point>> contours;
findContours(src_closed, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
vector<RotatedRect> out_rects;
vector<vector<Point>>::iterator itr = contours.begin();
float maxArea = 0;
RotatedRect maxRect;
while (itr != contours.end()) {
RotatedRect mr = minAreaRect((Mat)*itr);
float area = mr.size.width * mr.size.height;
if (area > maxArea) {
maxArea = area;
maxRect = mr;
}
itr++;
}
// 纠正用RotatedRect截取ROI,宽/高<1 错误截取的问题
if (maxRect.angle < (-70) && maxRect.size.width < maxRect.size.height) {
swap(maxRect.size.width, maxRect .size.height);
}
Mat subRegion;
getRectSubPix(roi_rotated, maxRect.size, maxRect.center, subRegion);
if (maxArea > 0 && maxArea < 4800) {
resize(subRegion, subRegion, Size(136, 36));
// 保存旋转后的plate
plates[i].setPlateMat(subRegion);
}
// 保存旋转后的plate
plates[i].setPlateMat(subRegion);
}
}
// 初始化svm模型地址
void NYPlateDetect::setSVMModelPath(string svmPath)
{
svmModelPath = svmPath;
}
| 28.376307 | 125 | 0.564219 | NathanYu1124 |
e046fad6017a6d5a87e8d502f1fd6864f856a370 | 2,960 | cpp | C++ | framework/operators/shuffle_channel.cpp | Shixiaowei02/Anakin | f1ea086c5dfa1009ba15a64bc3e30cde07356360 | [
"Apache-2.0"
] | 1 | 2018-08-03T05:14:27.000Z | 2018-08-03T05:14:27.000Z | framework/operators/shuffle_channel.cpp | Shixiaowei02/Anakin | f1ea086c5dfa1009ba15a64bc3e30cde07356360 | [
"Apache-2.0"
] | 3 | 2018-06-22T09:08:44.000Z | 2018-07-04T08:38:30.000Z | framework/operators/shuffle_channel.cpp | Shixiaowei02/Anakin | f1ea086c5dfa1009ba15a64bc3e30cde07356360 | [
"Apache-2.0"
] | 1 | 2021-01-27T07:44:55.000Z | 2021-01-27T07:44:55.000Z | #include "framework/operators/shuffle_channel.h"
namespace anakin {
namespace ops {
#define INSTANCE_SHUFFLE_CHANNEL(Ttype, Dtype, Ptype) \
template<> \
void ShuffleChannel<Ttype, Dtype, Ptype>::operator()(OpContext<Ttype>& ctx, \
const std::vector<Tensor4dPtr<Ttype, Dtype> >& ins, \
std::vector<Tensor4dPtr<Ttype, Dtype> >& outs) { \
auto* impl = static_cast<ShuffleChannelHelper<Ttype, Dtype, Ptype>*>(this->_helper); \
auto& param = static_cast<ShuffleChannelHelper<Ttype, Dtype, Ptype>*>\
(this->_helper)->_param_shuffle_channel; \
impl->_funcs_shuffle_channel(ins, outs, param, ctx); \
}
template<typename Ttype, DataType Dtype, Precision Ptype>
Status ShuffleChannelHelper<Ttype, Dtype, Ptype>::InitParam() {
auto group = GET_PARAMETER(int, group);
saber::ShuffleChannelParam<Tensor4d<Ttype, Dtype>> param(group);
_param_shuffle_channel = param;
return Status::OK();
}
template<typename Ttype, DataType Dtype, Precision Ptype>
Status ShuffleChannelHelper<Ttype, Dtype, Ptype>::Init(OpContext<Ttype>& ctx,
const std::vector<Tensor4dPtr<Ttype, Dtype> >& ins,
std::vector<Tensor4dPtr<Ttype, Dtype> >& outs) {
SABER_CHECK(_funcs_shuffle_channel.init(ins, outs, _param_shuffle_channel, SPECIFY, SABER_IMPL, ctx));
return Status::OK();
}
template<typename Ttype, DataType Dtype, Precision Ptype>
Status ShuffleChannelHelper<Ttype, Dtype, Ptype>::InferShape(const std::vector<Tensor4dPtr<Ttype, Dtype> >& ins, \
std::vector<Tensor4dPtr<Ttype, Dtype> >& outs) {
SABER_CHECK(_funcs_shuffle_channel.compute_output_shape(ins, outs, _param_shuffle_channel));
return Status::OK();
}
#ifdef USE_CUDA
INSTANCE_SHUFFLE_CHANNEL(NV, AK_FLOAT, Precision::FP32);
template class ShuffleChannelHelper<NV, AK_FLOAT, Precision::FP32>;
ANAKIN_REGISTER_OP_HELPER(ShuffleChannel, ShuffleChannelHelper, NV, AK_FLOAT, Precision::FP32);
#endif
#if defined(USE_X86_PLACE) || defined(BUILD_LITE)
INSTANCE_SHUFFLE_CHANNEL(X86, AK_FLOAT, Precision::FP32);
template class ShuffleChannelHelper<X86, AK_FLOAT, Precision::FP32>;
ANAKIN_REGISTER_OP_HELPER(ShuffleChannel, ShuffleChannelHelper, X86, AK_FLOAT, Precision::FP32);
#endif
#ifdef USE_ARM_PLACE
INSTANCE_SHUFFLE_CHANNEL(ARM, AK_FLOAT, Precision::FP32);
template class ShuffleChannelHelper<ARM, AK_FLOAT, Precision::FP32>;
ANAKIN_REGISTER_OP_HELPER(ShuffleChannel, ShuffleChannelHelper, ARM, AK_FLOAT, Precision::FP32);
#endif
//! register op
ANAKIN_REGISTER_OP(ShuffleChannel)
.Doc("ShuffleChannel operator")
#ifdef USE_CUDA
.__alias__<NV, AK_FLOAT, Precision::FP32>("shufflechannel")
#endif
#ifdef USE_ARM_PLACE
.__alias__<ARM, AK_FLOAT, Precision::FP32>("shufflechannel")
#endif
#if defined(USE_X86_PLACE) || defined(BUILD_LITE)
.__alias__<X86, AK_FLOAT, Precision::FP32>("shufflechannel")
#endif
.num_in(1)
.num_out(1)
.Args<int>("group", " group number for shuffle ");
} /* namespace ops */
} /* namespace anakin */
| 37 | 114 | 0.752703 | Shixiaowei02 |
e04ad05935dea20898a64e88554d93dbc07fd729 | 5,153 | cpp | C++ | Development/External/wxWindows_2.4.0/src/msw/data.cpp | addstone/unrealengine3 | 4579d360dfd52b12493292120b27bb430f978fc8 | [
"FSFAP"
] | 37 | 2020-05-22T18:18:47.000Z | 2022-03-19T06:51:54.000Z | Development/External/wxWindows_2.4.0/src/msw/data.cpp | AdanosGotoman/unrealengine3 | 4579d360dfd52b12493292120b27bb430f978fc8 | [
"FSFAP"
] | null | null | null | Development/External/wxWindows_2.4.0/src/msw/data.cpp | AdanosGotoman/unrealengine3 | 4579d360dfd52b12493292120b27bb430f978fc8 | [
"FSFAP"
] | 27 | 2020-05-17T01:03:30.000Z | 2022-03-06T19:10:14.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: data.cpp
// Purpose: Various data
// Author: Julian Smart
// Modified by:
// Created: 01/02/97
// RCS-ID: $Id: data.cpp,v 1.40.2.5 2002/12/26 19:11:04 RD Exp $
// Copyright: (c) Julian Smart and Markus Holzem
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
#pragma implementation "data.h"
#endif
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#include "wx/treectrl.h"
#endif
#include "wx/prntbase.h"
#define _MAXPATHLEN 500
// Useful buffer, initialized in wxCommonInit
wxChar *wxBuffer = NULL;
// Windows List
wxWindowList wxTopLevelWindows;
// List of windows pending deletion
wxList WXDLLEXPORT wxPendingDelete;
int wxPageNumber;
// GDI Object Lists
wxFontList *wxTheFontList = NULL;
wxPenList *wxThePenList = NULL;
wxBrushList *wxTheBrushList = NULL;
wxBitmapList *wxTheBitmapList = NULL;
wxColourDatabase *wxTheColourDatabase = NULL;
// Stock objects
wxFont *wxNORMAL_FONT;
wxFont *wxSMALL_FONT;
wxFont *wxITALIC_FONT;
wxFont *wxSWISS_FONT;
wxPen *wxRED_PEN;
wxPen *wxCYAN_PEN;
wxPen *wxGREEN_PEN;
wxPen *wxBLACK_PEN;
wxPen *wxWHITE_PEN;
wxPen *wxTRANSPARENT_PEN;
wxPen *wxBLACK_DASHED_PEN;
wxPen *wxGREY_PEN;
wxPen *wxMEDIUM_GREY_PEN;
wxPen *wxLIGHT_GREY_PEN;
wxBrush *wxBLUE_BRUSH;
wxBrush *wxGREEN_BRUSH;
wxBrush *wxWHITE_BRUSH;
wxBrush *wxBLACK_BRUSH;
wxBrush *wxTRANSPARENT_BRUSH;
wxBrush *wxCYAN_BRUSH;
wxBrush *wxRED_BRUSH;
wxBrush *wxGREY_BRUSH;
wxBrush *wxMEDIUM_GREY_BRUSH;
wxBrush *wxLIGHT_GREY_BRUSH;
wxColour *wxBLACK;
wxColour *wxWHITE;
wxColour *wxRED;
wxColour *wxBLUE;
wxColour *wxGREEN;
wxColour *wxCYAN;
wxColour *wxLIGHT_GREY;
wxCursor *wxSTANDARD_CURSOR = NULL;
wxCursor *wxHOURGLASS_CURSOR = NULL;
wxCursor *wxCROSS_CURSOR = NULL;
// 'Null' objects
#if wxUSE_ACCEL
wxAcceleratorTable wxNullAcceleratorTable;
#endif // wxUSE_ACCEL
wxBitmap wxNullBitmap;
wxIcon wxNullIcon;
wxCursor wxNullCursor;
wxPen wxNullPen;
wxBrush wxNullBrush;
#if wxUSE_PALETTE
wxPalette wxNullPalette;
#endif // wxUSE_PALETTE
wxFont wxNullFont;
wxColour wxNullColour;
// Default window names
WXDLLEXPORT_DATA(const wxChar *) wxControlNameStr = wxT("control");
WXDLLEXPORT_DATA(const wxChar *) wxButtonNameStr = wxT("button");
WXDLLEXPORT_DATA(const wxChar *) wxCanvasNameStr = wxT("canvas");
WXDLLEXPORT_DATA(const wxChar *) wxCheckBoxNameStr = wxT("check");
WXDLLEXPORT_DATA(const wxChar *) wxChoiceNameStr = wxT("choice");
WXDLLEXPORT_DATA(const wxChar *) wxComboBoxNameStr = wxT("comboBox");
WXDLLEXPORT_DATA(const wxChar *) wxDialogNameStr = wxT("dialog");
WXDLLEXPORT_DATA(const wxChar *) wxFrameNameStr = wxT("frame");
WXDLLEXPORT_DATA(const wxChar *) wxGaugeNameStr = wxT("gauge");
WXDLLEXPORT_DATA(const wxChar *) wxStaticBoxNameStr = wxT("groupBox");
WXDLLEXPORT_DATA(const wxChar *) wxListBoxNameStr = wxT("listBox");
WXDLLEXPORT_DATA(const wxChar *) wxStaticTextNameStr = wxT("message");
WXDLLEXPORT_DATA(const wxChar *) wxStaticBitmapNameStr = wxT("message");
WXDLLEXPORT_DATA(const wxChar *) wxMultiTextNameStr = wxT("multitext");
WXDLLEXPORT_DATA(const wxChar *) wxPanelNameStr = wxT("panel");
WXDLLEXPORT_DATA(const wxChar *) wxRadioBoxNameStr = wxT("radioBox");
WXDLLEXPORT_DATA(const wxChar *) wxRadioButtonNameStr = wxT("radioButton");
WXDLLEXPORT_DATA(const wxChar *) wxBitmapRadioButtonNameStr = wxT("radioButton");
WXDLLEXPORT_DATA(const wxChar *) wxScrollBarNameStr = wxT("scrollBar");
WXDLLEXPORT_DATA(const wxChar *) wxSliderNameStr = wxT("slider");
WXDLLEXPORT_DATA(const wxChar *) wxStaticNameStr = wxT("static");
WXDLLEXPORT_DATA(const wxChar *) wxTextCtrlWindowNameStr = wxT("textWindow");
WXDLLEXPORT_DATA(const wxChar *) wxTextCtrlNameStr = wxT("text");
WXDLLEXPORT_DATA(const wxChar *) wxVirtListBoxNameStr = wxT("virtListBox");
WXDLLEXPORT_DATA(const wxChar *) wxButtonBarNameStr = wxT("buttonbar");
WXDLLEXPORT_DATA(const wxChar *) wxEnhDialogNameStr = wxT("Shell");
WXDLLEXPORT_DATA(const wxChar *) wxToolBarNameStr = wxT("toolbar");
WXDLLEXPORT_DATA(const wxChar *) wxStatusLineNameStr = wxT("status_line");
WXDLLEXPORT_DATA(const wxChar *) wxGetTextFromUserPromptStr = wxT("Input Text");
WXDLLEXPORT_DATA(const wxChar *) wxMessageBoxCaptionStr = wxT("Message");
WXDLLEXPORT_DATA(const wxChar *) wxFileSelectorPromptStr = wxT("Select a file");
WXDLLEXPORT_DATA(const wxChar *) wxFileSelectorDefaultWildcardStr = wxT("*.*");
WXDLLEXPORT_DATA(const wxChar *) wxTreeCtrlNameStr = wxT("treeCtrl");
WXDLLEXPORT_DATA(const wxChar *) wxDirDialogNameStr = wxT("wxDirCtrl");
WXDLLEXPORT_DATA(const wxChar *) wxDirDialogDefaultFolderStr = wxT("/");
// See wx/utils.h
WXDLLEXPORT_DATA(const wxChar *) wxFloatToStringStr = wxT("%.2f");
WXDLLEXPORT_DATA(const wxChar *) wxDoubleToStringStr = wxT("%.2f");
#ifdef __WXMSW__
WXDLLEXPORT_DATA(const wxChar *) wxUserResourceStr = wxT("TEXT");
#endif
const wxSize wxDefaultSize(-1, -1);
const wxPoint wxDefaultPosition(-1, -1);
| 33.461039 | 81 | 0.750631 | addstone |
e04ceeb56788a5b8cda7f248428ac669cd955aeb | 1,731 | cpp | C++ | Easy/valid-parentheses.cpp | utkarshavardhana/LeetCode-Problems | 1b574945c59d8050a55a9d1c922dde65e6bb7c75 | [
"MIT"
] | 1 | 2020-05-10T07:21:24.000Z | 2020-05-10T07:21:24.000Z | Easy/valid-parentheses.cpp | utkarshavardhana/LeetCode-Problems | 1b574945c59d8050a55a9d1c922dde65e6bb7c75 | [
"MIT"
] | null | null | null | Easy/valid-parentheses.cpp | utkarshavardhana/LeetCode-Problems | 1b574945c59d8050a55a9d1c922dde65e6bb7c75 | [
"MIT"
] | null | null | null | // Problem: https://leetcode.com/problems/valid-parentheses/
//
// Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
//
// An input string is valid if:
//
// Open brackets must be closed by the same type of brackets.
// Open brackets must be closed in the correct order.
// Note that an empty string is also considered valid.
//
// Example 1:
// Input: "()"
// Output: true
//
// Example 2:
// Input: "()[]{}"
// Output: true
//
// Example 3:
// Input: "(]"
// Output: false
//
// Example 4:
// Input: "([)]"
// Output: false
//
// Example 5:
// Input: "{[]}"
// Output: true
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(char c : s) {
if(c == '(' or c == '{' or c == '[') {
st.push(c);
} else {
if(st.empty()) {
return false;
}
if(c == ')') {
if(st.top() == '(') {
st.pop();
} else {
return false;
}
} else if(c == '}') {
if(st.top() == '{') {
st.pop();
} else {
return false;
}
} else {
if(st.top() == '[') {
st.pop();
} else {
return false;
}
}
}
}
if(!st.empty()) {
return false;
}
return true;
}
};
| 25.086957 | 122 | 0.353553 | utkarshavardhana |
e04dfe2331a9c141b5ae3fec88e534d0f6549211 | 1,486 | cpp | C++ | Valtrook/Valtrook/RenderingEngine.cpp | animeenginedev/Valtrook | 10cf7332643765534f8a4263cc4e422c4356487b | [
"MIT"
] | null | null | null | Valtrook/Valtrook/RenderingEngine.cpp | animeenginedev/Valtrook | 10cf7332643765534f8a4263cc4e422c4356487b | [
"MIT"
] | null | null | null | Valtrook/Valtrook/RenderingEngine.cpp | animeenginedev/Valtrook | 10cf7332643765534f8a4263cc4e422c4356487b | [
"MIT"
] | null | null | null | #include "RenderingEngine.h"
#include <gl\glew.h>
#include <iostream>
#include <sstream>
namespace Val {
Window RenderingEngine::window;
RenderingEngine::RenderingEngine() {
}
RenderingEngine::~RenderingEngine() {
}
void RenderingEngine::InitWindow() {
window.create(0);
std::stringstream str = std::stringstream();
str << glGetString(GL_VERSION) << "\n";
std::cout << str.str();
}
void RenderingEngine::initialise() {
renderer.initialise();
GUIRenderer.initialise();
shaderObject = new GenericShaderObject();
}
void RenderingEngine::render() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthFunc(GL_LEQUAL);
renderer.prepare();
GUIRenderer.prepare();
while (!renderer.isPrepared() && !GUIRenderer.isPrepared()) {
}
shaderObject->attach();
renderer.render();
shaderObject->setLineMode(true);
renderer.renderLines();
shaderObject->setLineMode(false);
if (GUIRenderer.VertexCount() > 0) {
glEnable(GL_DEPTH_TEST);
glClear(GL_DEPTH_BUFFER_BIT);
GUIRenderer.render();
shaderObject->setLineMode(true);
GUIRenderer.renderLines();
shaderObject->setLineMode(false);
}
window.swapBuffer();
renderer.clear();
GUIRenderer.clear();
}
VBOBatcher * RenderingEngine::getRenderer() {
return &renderer;
}
VBOBatcher * RenderingEngine::getGUIRenderer() {
return &GUIRenderer;
}
Window RenderingEngine::getWindow() {
return window;
}
} | 20.081081 | 63 | 0.711306 | animeenginedev |
e05059cf8c65f90777bcff5cebe533bfa326746b | 2,229 | hpp | C++ | src/SynthesizeSegment.hpp | haruneko/uzume_vocoder | 63343118fd8d0dd8b7ebb92d98f023bfa6b9855e | [
"MIT"
] | 1 | 2020-04-28T06:29:25.000Z | 2020-04-28T06:29:25.000Z | src/SynthesizeSegment.hpp | haruneko/uzume | 63343118fd8d0dd8b7ebb92d98f023bfa6b9855e | [
"MIT"
] | null | null | null | src/SynthesizeSegment.hpp | haruneko/uzume | 63343118fd8d0dd8b7ebb92d98f023bfa6b9855e | [
"MIT"
] | null | null | null | // Copyright 2020 Hal@shurabaP. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
#ifndef __UZUME_VOCODER_SYNTHESIZE_SEGMENT_HPP__
#define __UZUME_VOCODER_SYNTHESIZE_SEGMENT_HPP__
#include "Spectrogram.hpp"
namespace uzume { namespace vocoder {
/**
* SegmentSignal is a value class for Segment synthesis output.
* This class is not responsible for memory allocation.
* Make sure neither SegmentSignal#indexMin nor SegmentSignal#indexMax is out of array range.
*/
class SegmentSignal final {
public:
SegmentSignal() = delete;
SegmentSignal(double *waveStartPoint, int indexMin, int indexMax, unsigned int samplingFrequency)
: waveStartPoint(waveStartPoint), indexMin(indexMin), indexMax(indexMax), samplingFrequency(samplingFrequency) {
}
double *waveStartPoint;
int indexMin;
int indexMax;
unsigned int samplingFrequency;
};
/**
* SegmentSignal is a value class for Segment synthesis input.
* This class is not responsible for memory allocation.
* SegmentParameters#startPhase and SegmentParameters#startFractionalTimeShift should be set
* when SynthesizeSegment begins synthesis from the middle of music sentence, otherwise they should be 0.0.
*/
class SegmentParameters final {
public:
SegmentParameters() = delete;
SegmentParameters(const Spectrogram *spectrogram, double startPhase, double startFractionalTimeShift)
: spectrogram(spectrogram), startPhase(startPhase), startFractionalTimeShift(startFractionalTimeShift) {
}
const Spectrogram *spectrogram;
double startPhase;
double startFractionalTimeShift;
};
/**
* SynthesizeSegment synthesize a single Segment.
*/
class SynthesizeSegment {
public:
SynthesizeSegment() = default;
SynthesizeSegment(const SynthesizeSegment&) = delete;
virtual ~SynthesizeSegment() = default;
/**
* SynthesizeSegment#() synthesize a single Segment into output from input.
* @return true if synthesis is successful.
* @return false otherwise.
*/
virtual bool operator()(SegmentSignal *output, SegmentParameters *input) = 0;
};
} }
#endif // __UZUME_VOCODER_SYNTHESIZE_SEGMENT_HPP__
| 33.772727 | 124 | 0.75729 | haruneko |
e050f21091ba16d03fa8ce813149006f205678e6 | 3,217 | cpp | C++ | CONTRIB/LLVM/src/lib/Tg/AMDGPU/AMDGPUTargetObjectFile.cpp | Cwc-Test/CpcdosOS2.1 | d52c170be7f11cc50de38ef536d4355743d21706 | [
"Apache-2.0"
] | 30 | 2016-09-06T06:58:43.000Z | 2021-12-23T11:59:38.000Z | CONTRIB/LLVM/src/lib/Tg/AMDGPU/AMDGPUTargetObjectFile.cpp | Cwc-Test/CpcdosOS2.1 | d52c170be7f11cc50de38ef536d4355743d21706 | [
"Apache-2.0"
] | 21 | 2016-08-11T09:43:43.000Z | 2017-01-29T12:52:56.000Z | CONTRIB/LLVM/src/lib/Tg/AMDGPU/AMDGPUTargetObjectFile.cpp | Cwc-Test/CpcdosOS2.1 | d52c170be7f11cc50de38ef536d4355743d21706 | [
"Apache-2.0"
] | 17 | 2016-10-24T06:08:16.000Z | 2022-02-18T17:27:14.000Z | //===-- AMDGPUHSATargetObjectFile.cpp - AMDGPU Object Files ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "AMDGPUTargetObjectFile.h"
#include "AMDGPU.h"
#include "Utils/AMDGPUBaseInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/Support/ELF.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// Generic Object File
//===----------------------------------------------------------------------===//
MCSection *AMDGPUTargetObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
SectionKind Kind,
Mangler &Mang,
const TargetMachine &TM) const {
if (Kind.isReadOnly() && AMDGPU::isReadOnlySegment(GV))
return TextSection;
return TargetLoweringObjectFileELF::SelectSectionForGlobal(GV, Kind, Mang, TM);
}
//===----------------------------------------------------------------------===//
// HSA Object File
//===----------------------------------------------------------------------===//
void AMDGPUHSATargetObjectFile::Initialize(MCContext &Ctx,
const TargetMachine &TM){
TargetLoweringObjectFileELF::Initialize(Ctx, TM);
InitializeELF(TM.Options.UseInitArray);
TextSection = AMDGPU::getHSATextSection(Ctx);
DataGlobalAgentSection = AMDGPU::getHSADataGlobalAgentSection(Ctx);
DataGlobalProgramSection = AMDGPU::getHSADataGlobalProgramSection(Ctx);
RodataReadonlyAgentSection = AMDGPU::getHSARodataReadonlyAgentSection(Ctx);
}
bool AMDGPUHSATargetObjectFile::isAgentAllocationSection(
const char *SectionName) const {
return cast<MCSectionELF>(DataGlobalAgentSection)
->getSectionName()
.equals(SectionName);
}
bool AMDGPUHSATargetObjectFile::isAgentAllocation(const GlobalValue *GV) const {
// Read-only segments can only have agent allocation.
return AMDGPU::isReadOnlySegment(GV) ||
(AMDGPU::isGlobalSegment(GV) && GV->hasSection() &&
isAgentAllocationSection(GV->getSection()));
}
bool AMDGPUHSATargetObjectFile::isProgramAllocation(
const GlobalValue *GV) const {
// The default for global segments is program allocation.
return AMDGPU::isGlobalSegment(GV) && !isAgentAllocation(GV);
}
MCSection *AMDGPUHSATargetObjectFile::SelectSectionForGlobal(
const GlobalValue *GV, SectionKind Kind,
Mangler &Mang,
const TargetMachine &TM) const {
if (Kind.isText() && !GV->hasComdat())
return getTextSection();
if (AMDGPU::isGlobalSegment(GV)) {
if (isAgentAllocation(GV))
return DataGlobalAgentSection;
if (isProgramAllocation(GV))
return DataGlobalProgramSection;
}
return AMDGPUTargetObjectFile::SelectSectionForGlobal(GV, Kind, Mang, TM);
}
| 36.556818 | 81 | 0.578489 | Cwc-Test |
e051d22a254e20b8bfb901f382b8749a23b187cd | 4,221 | cpp | C++ | target/device/libio/arduino/x86/libraries/SPI/SPI.cpp | ilc-opensource/io-js | 462943d67e3e8985d085898cabe5629006f66e33 | [
"BSD-3-Clause"
] | 8 | 2015-01-24T18:40:21.000Z | 2016-03-22T07:04:07.000Z | target/device/libio/arduino/x86/libraries/SPI/SPI.cpp | ilc-opensource/io-js | 462943d67e3e8985d085898cabe5629006f66e33 | [
"BSD-3-Clause"
] | null | null | null | target/device/libio/arduino/x86/libraries/SPI/SPI.cpp | ilc-opensource/io-js | 462943d67e3e8985d085898cabe5629006f66e33 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2010 by Cristian Maglie <c.maglie@bug.st>
* Copyright (c) 2013 Intel Corporation
* SPI Master library for arduino.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either the GNU General Public License version 2
* or the GNU Lesser General Public License version 2.1, both as
* published by the Free Software Foundation.
*/
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <linux/spi/spidev.h>
#include "Arduino.h"
#include "trace.h"
#include "SPI.h"
#define MY_TRACE_PREFIX "SPI"
/* For Arduino, this is assumed to be 4MHz, using SPI_CLOCK_DEV4
* Sticking to this for backward compatibility */
#define SPI_CLK_DEFAULT_HZ 4000000
#define SPI_SS_GPIO_PIN 10
SPIClass SPI;
/* Constructor - establish defaults */
SPIClass::SPIClass()
{
/* reflect Arduino's default behaviour where possible */
this->mode = SPI_MODE0;
this->bitOrder = MSBFIRST;
this->clkDiv = SPI_CLOCK_DIV4;
}
void SPIClass::begin()
{
/* Set the pin mux, for the SCK, MOSI and MISO pins ONLY
*
* Leave the SS pin in GPIO mode (the application will control it)
* but set it's direction to output and initially high
*/
muxSelectDigitalPin(SPI_SS_GPIO_PIN);
pinMode(SPI_SS_GPIO_PIN, OUTPUT);
digitalWrite(SPI_SS_GPIO_PIN, HIGH);
muxSelectSpi(1);
this->fd = open(LINUX_SPIDEV, O_RDWR);
if (this->fd < 0) {
trace_error("Failed to open SPI device\n");
return;
}
/* Load default/last configuration */
this->setClockDivider(this->clkDiv);
this->setBitOrder(this->bitOrder);
this->setDataMode(this->mode);
}
void SPIClass::end()
{
if (this->fd >= 0)
close(this->fd);
}
void SPIClass::setBitOrder(uint8_t bitOrder)
{
uint8_t lsbFirst = 0;
if (bitOrder == LSBFIRST) {
lsbFirst = 1;
}
if (ioctl (this->fd, SPI_IOC_WR_LSB_FIRST, &lsbFirst) < 0) {
trace_error("Failed to set SPI bit justification\n");
return;
}
this->bitOrder = bitOrder;
}
void SPIClass::setDataMode(uint8_t mode)
{
uint8_t linuxSpiMode = 0;
switch(mode) {
case SPI_MODE0:
linuxSpiMode = SPI_MODE_0;
break;
case SPI_MODE1:
linuxSpiMode = SPI_MODE_1;
break;
case SPI_MODE2:
linuxSpiMode = SPI_MODE_2;
break;
case SPI_MODE3:
linuxSpiMode = SPI_MODE_3;
break;
default:
trace_error("Invalid SPI mode specified\n");
return;
}
if (ioctl (this->fd, SPI_IOC_WR_MODE, &linuxSpiMode) < 0) {
trace_error("Failed to set SPI mode\n");
return;
}
this->mode = mode;
}
void SPIClass::setClockDivider(uint8_t clkDiv)
{
uint32_t maxSpeedHz = SPI_CLK_DEFAULT_HZ;
/* Adjust the clock speed relative to the default divider of 4 */
switch(clkDiv)
{
case SPI_CLOCK_DIV2:
maxSpeedHz = SPI_CLK_DEFAULT_HZ << 1;
break;
case SPI_CLOCK_DIV4:
/* Do nothing */
break;
case SPI_CLOCK_DIV8:
maxSpeedHz = SPI_CLK_DEFAULT_HZ >> 1;
break;
case SPI_CLOCK_DIV16:
maxSpeedHz = SPI_CLK_DEFAULT_HZ >> 2;
break;
case SPI_CLOCK_DIV32:
maxSpeedHz = SPI_CLK_DEFAULT_HZ >> 3;
break;
case SPI_CLOCK_DIV64:
maxSpeedHz = SPI_CLK_DEFAULT_HZ >> 4;
break;
case SPI_CLOCK_DIV128:
maxSpeedHz = SPI_CLK_DEFAULT_HZ >> 5;
break;
default:
trace_error("Invalid SPI mode specified\n");
return;
}
if (ioctl (this->fd, SPI_IOC_WR_MAX_SPEED_HZ, &maxSpeedHz) < 0) {
trace_error("Failed to set SPI clock speed\n");
return;
}
this->clkDiv = clkDiv;
}
uint8_t SPIClass::transfer(uint8_t txData)
{
uint8_t rxData = 0xFF;
struct spi_ioc_transfer msg;
memset(&msg, 0, sizeof(msg));
msg.tx_buf = (__u64) &txData;
msg.rx_buf = (__u64) &rxData;
msg.len = sizeof(uint8_t);
if (ioctl (this->fd, SPI_IOC_MESSAGE(1), &msg) < 0)
trace_error("Failed to execute SPI transfer\n");
return rxData;
}
void SPIClass::transferBuffer(const uint8_t *txData,
uint8_t *rxData,
uint32_t len)
{
struct spi_ioc_transfer msg;
memset(&msg, 0, sizeof(msg));
msg.tx_buf = (__u64) txData;
msg.rx_buf = (__u64) rxData;
msg.len = len;
if (ioctl (this->fd, SPI_IOC_MESSAGE(1), &msg) < 0)
trace_error("Failed to execute SPI transfer\n");
}
void SPIClass::attachInterrupt() {
trace_error("SPI slave mode is not currently supported\n");
}
void SPIClass::detachInterrupt() {
/* Do nothing */
}
| 21.105 | 72 | 0.703388 | ilc-opensource |
e051f2422e3ff0ebeea24593e27b4b2762c4b2aa | 539 | hpp | C++ | src/player_human.hpp | a-n-t-h-o-n-y/cursed-chess | a932f48bac0431c927e7ec569e8d167e3b261754 | [
"MIT"
] | null | null | null | src/player_human.hpp | a-n-t-h-o-n-y/cursed-chess | a932f48bac0431c927e7ec569e8d167e3b261754 | [
"MIT"
] | null | null | null | src/player_human.hpp | a-n-t-h-o-n-y/cursed-chess | a932f48bac0431c927e7ec569e8d167e3b261754 | [
"MIT"
] | null | null | null | #ifndef CHESS_PLAYER_HUMAN_HPP
#define CHESS_PLAYER_HUMAN_HPP
#include <mutex>
#include "move.hpp"
#include "player.hpp"
#include "shared_user_input.hpp"
namespace chess {
class Chess_engine;
} // namespace chess
namespace chess::player {
inline auto human() -> Player
{
return {"Human", [](Chess_engine const&) {
auto lock = std::unique_lock{Shared_user_input::move.mtx};
return Shared_user_input::move.get(lock);
}};
}
} // namespace chess::player
#endif // CHESS_PLAYER_HUMAN_HPP
| 21.56 | 74 | 0.679035 | a-n-t-h-o-n-y |
e053d66898ad019e0101859f68cd0c73e58218db | 1,284 | hpp | C++ | include/Game/Item.hpp | darwin-s/nanocraft | dcb8b590fa3310b726529ab5e36b18893f6a3b1f | [
"Apache-2.0"
] | 2 | 2021-08-12T10:05:53.000Z | 2021-08-13T16:25:49.000Z | include/Game/Item.hpp | darwin-s/nanocraft | dcb8b590fa3310b726529ab5e36b18893f6a3b1f | [
"Apache-2.0"
] | null | null | null | include/Game/Item.hpp | darwin-s/nanocraft | dcb8b590fa3310b726529ab5e36b18893f6a3b1f | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Sirbu Dan
//
// 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 NC_GAME_ITEM_HPP
#define NC_GAME_ITEM_HPP
#include <World/Tile.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <string>
namespace nc {
class Item {
public:
explicit Item(const std::string& name = "null");
Item(const std::string& texture, const std::string& name);
void setTexture(const std::string& texture);
sf::Sprite& getSprite();
const sf::Sprite& getSprite() const;
void setPlaceableTile(const std::string& name);
Tile* getPlaceableTile() const;
void setName(const std::string& name);
std::string getName() const;
private:
sf::Sprite m_sprite;
std::string m_name;
std::string m_placeableTile;
};
}
#endif // !NC_GAME_ITEM_HPP | 29.181818 | 75 | 0.715732 | darwin-s |
e0546cb6216e6946ff2b3bec378ac70d890d1da8 | 465 | cpp | C++ | src/tools/tools__MB.cpp | violador/catalyst | 40d5c1dd04269a0764a9804711354a474bc43c15 | [
"Unlicense"
] | null | null | null | src/tools/tools__MB.cpp | violador/catalyst | 40d5c1dd04269a0764a9804711354a474bc43c15 | [
"Unlicense"
] | null | null | null | src/tools/tools__MB.cpp | violador/catalyst | 40d5c1dd04269a0764a9804711354a474bc43c15 | [
"Unlicense"
] | null | null | null | //
//
//
/// @brief Returns the conversion factor from bytes to megabytes.
//
/// @return @f$ 0.000000954 @f$
//
inline const double MB()
{
return 0.000000954;
};
//
//
//
/// @param [in] data_size A numerical (only) argument in byte units.
//
/// @brief Converts the given @c data_size to megabyte units.
//
/// @return @f$ := \times 0.000000954 @f$
//
template<typename data_type>
inline double MB(const data_type &data_size)
{
return data_size*0.000000954;
};
| 17.884615 | 68 | 0.664516 | violador |
e054d96afb4867d6e5dee9a2d51042dce8b99679 | 5,457 | hpp | C++ | src/backend/cuda/kernel/resize.hpp | ckeitz/arrayfire | a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b | [
"BSD-3-Clause"
] | 4 | 2015-12-16T09:41:32.000Z | 2018-10-29T10:38:53.000Z | src/backend/cuda/kernel/resize.hpp | ckeitz/arrayfire | a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b | [
"BSD-3-Clause"
] | 3 | 2015-11-15T18:43:47.000Z | 2015-12-16T09:43:14.000Z | src/backend/cuda/kernel/resize.hpp | pavanky/arrayfire | f983a79c7d402450bd2a704bbc1015b89f0cd504 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <dispatch.hpp>
#include <Param.hpp>
#include <err_cuda.hpp>
#include <debug_cuda.hpp>
namespace cuda
{
namespace kernel
{
// Kernel Launch Config Values
static const unsigned TX = 16;
static const unsigned TY = 16;
///////////////////////////////////////////////////////////////////////////
// nearest-neighbor resampling
///////////////////////////////////////////////////////////////////////////
template<typename T>
__host__ __device__
void resize_n(Param<T> out, CParam<T> in,
const dim_type o_off, const dim_type i_off,
const dim_type blockIdx_x, const dim_type blockIdx_y,
const float xf, const float yf)
{
const dim_type ox = threadIdx.x + blockIdx_x * blockDim.x;
const dim_type oy = threadIdx.y + blockIdx_y * blockDim.y;
dim_type ix = round(ox * xf);
dim_type iy = round(oy * yf);
if (ox >= out.dims[0] || oy >= out.dims[1]) { return; }
if (ix >= in.dims[0]) { ix = in.dims[0] - 1; }
if (iy >= in.dims[1]) { iy = in.dims[1] - 1; }
out.ptr[o_off + ox + oy * out.strides[1]] = in.ptr[i_off + ix + iy * in.strides[1]];
}
///////////////////////////////////////////////////////////////////////////
// bilinear resampling
///////////////////////////////////////////////////////////////////////////
template<typename T>
__host__ __device__
void resize_b(Param<T> out, CParam<T> in,
const dim_type o_off, const dim_type i_off,
const dim_type blockIdx_x, const dim_type blockIdx_y,
const float xf_, const float yf_)
{
const dim_type ox = threadIdx.x + blockIdx_x * blockDim.x;
const dim_type oy = threadIdx.y + blockIdx_y * blockDim.y;
float xf = ox * xf_;
float yf = oy * yf_;
dim_type ix = floorf(xf);
dim_type iy = floorf(yf);
if (ox >= out.dims[0] || oy >= out.dims[1]) { return; }
if (ix >= in.dims[0]) { ix = in.dims[0] - 1; }
if (iy >= in.dims[1]) { iy = in.dims[1] - 1; }
float b = xf - ix;
float a = yf - iy;
const dim_type ix2 = ix + 1 < in.dims[0] ? ix + 1 : ix;
const dim_type iy2 = iy + 1 < in.dims[1] ? iy + 1 : iy;
const T *iptr = in.ptr + i_off;
const T p1 = iptr[ix + in.strides[1] * iy ];
const T p2 = iptr[ix + in.strides[1] * iy2];
const T p3 = iptr[ix2 + in.strides[1] * iy ] ;
const T p4 = iptr[ix2 + in.strides[1] * iy2];
T val = (1.0f-a) * (1.0f-b) * p1 +
(a) * (1.0f-b) * p2 +
(1.0f-a) * (b) * p3 +
(a) * (b) * p4;
out.ptr[o_off + ox + oy * out.strides[1]] = val;
}
///////////////////////////////////////////////////////////////////////////
// Resize Kernel
///////////////////////////////////////////////////////////////////////////
template<typename T, af_interp_type method>
__global__
void resize_kernel(Param<T> out, CParam<T> in,
const dim_type b0, const dim_type b1, const float xf, const float yf)
{
const dim_type bIdx = blockIdx.x / b0;
const dim_type bIdy = blockIdx.y / b1;
// channel adjustment
const dim_type i_off = bIdx * in.strides[2] + bIdy * in.strides[3];
const dim_type o_off = bIdx * out.strides[2] + bIdy * out.strides[3];
const dim_type blockIdx_x = blockIdx.x - bIdx * b0;
const dim_type blockIdx_y = blockIdx.y - bIdy * b1;
// core
if(method == AF_INTERP_NEAREST) {
resize_n(out, in, o_off, i_off, blockIdx_x, blockIdx_y, xf, yf);
} else if(method == AF_INTERP_BILINEAR) {
resize_b(out, in, o_off, i_off, blockIdx_x, blockIdx_y, xf, yf);
}
}
///////////////////////////////////////////////////////////////////////////
// Wrapper functions
///////////////////////////////////////////////////////////////////////////
template <typename T, af_interp_type method>
void resize(Param<T> out, CParam<T> in)
{
dim3 threads(TX, TY, 1);
dim3 blocks(divup(out.dims[0], threads.x), divup(out.dims[1], threads.y));
dim_type blocksPerMatX = blocks.x;
dim_type blocksPerMatY = blocks.y;
if (in.dims[2] > 1) { blocks.x *= in.dims[2]; }
if (in.dims[3] > 1) { blocks.y *= in.dims[3]; }
float xf = (float)in.dims[0] / (float)out.dims[0];
float yf = (float)in.dims[1] / (float)out.dims[1];
resize_kernel<T, method><<<blocks, threads>>>(out, in, blocksPerMatX, blocksPerMatY, xf, yf);
POST_LAUNCH_CHECK();
}
}
}
| 40.422222 | 105 | 0.439069 | ckeitz |
e0576645a761fdeaebb6655a7fbee24b356879da | 25,721 | cpp | C++ | src/Socket.cpp | seppeon/NetChat | 9b30513179f5d97a39ad9444dc94640976218b77 | [
"MIT"
] | null | null | null | src/Socket.cpp | seppeon/NetChat | 9b30513179f5d97a39ad9444dc94640976218b77 | [
"MIT"
] | null | null | null | src/Socket.cpp | seppeon/NetChat | 9b30513179f5d97a39ad9444dc94640976218b77 | [
"MIT"
] | null | null | null | #include "Socket.h"
#include "WinsockRaii.h"
#include "WindowsSocketRaii.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
namespace Net
{
std::string GetStatusDescription(BindStatus status) noexcept
{
switch(status)
{
case BindStatus::Success: return "Bind successful.";
case BindStatus::NotInitialised: return "A successful Startup call must occur before using this function.";
case BindStatus::NetworkDown: return "A network subsystem has failed.";
case BindStatus::Access: return "This error is returned if nn attempt to bind a datagram socket to the broadcast address failed because the setsockopt option SO_BROADCAST is not enabled.";
case BindStatus::AddressInUse: return "This error is returned if a process on the computer is already bound to the same fully qualified address and the socket has not been marked to allow address reuse with SO_REUSEADDR. For example, the IP ad";
case BindStatus::AddressNotAvaliable: return "This error is returned if the specified address pointed to by the name parameter is not a valid local IP address on this computer.";
case BindStatus::InvalidPointerArgument: return "This error is returned if the name parameter is NULL, the name or namelen parameter is not a valid part of the user address space, the namelen parameter is too small, the name parameter contains an incorr";
case BindStatus::OperationInProgress: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case BindStatus::SocketAlreadyBound: return "This error is returned of the socket s is already bound to an address.";
case BindStatus::NoPortsAvaliable: return "An indication that there aren't enough ephemeral ports to allocate for the bind.";
case BindStatus::NotASocket: return "This error is returned if the descriptor in the s parameter is not a socket.";
}
return "";
}
std::string GetStatusDescription(ListenStatus status) noexcept
{
switch(status)
{
case ListenStatus::Success: return "Listen successful.";
case ListenStatus::NotInitialized: return "A successful WSAStartup call must occur before using this function.";
case ListenStatus::NetworkDown: return "The network subsystem has failed.";
case ListenStatus::AddressInUse: return "The socket's local address is already in use and the socket was not marked to allow address reuse with SO_REUSEADDR. This error usually occurs during execution";
case ListenStatus::OperationInProgress: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case ListenStatus::UnboundSocket: return "The socket has not been bound with bind.";
case ListenStatus::AlreadyConnected: return "The socket is already connected.";
case ListenStatus::NoMoreDescriptors: return "No more socket descriptors are available.";
case ListenStatus::NoBufferSpace: return "No buffer space is available.";
case ListenStatus::NotASocket: return "This error is returned if the descriptor in the parameter is not a socket.";
case ListenStatus::NotSupported: return "The referenced socket is not of a type that supports the listen operation. ";
}
return "";
}
std::string GetStatusDescription(AcceptStatus status) noexcept
{
switch (status)
{
case AcceptStatus::Success: return "Accepted successfully.";
case AcceptStatus::NotInitialized: return "A successful WSAStartup call must occur before using this function.";
case AcceptStatus::ConnectionReset: return "An incoming connection was indicated, but was subsequently terminated by the remote peer prior to accepting the call.";
case AcceptStatus::Cancelled: return "A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.";
case AcceptStatus::ListenNotInvoked: return "The listen function was not invoked prior to accept.";
case AcceptStatus::OperationInProgress: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case AcceptStatus::NoMoreDescriptors: return "The queue is nonempty upon entry to accept and there are no descriptors available.";
case AcceptStatus::NetworkDown: return "The network subsystem has failed.";
case AcceptStatus::NoBufferSpace: return "No buffer space is available.";
case AcceptStatus::NotASocket: return "The descriptor is not a socket.";
case AcceptStatus::NotSupported: return "The referenced socket is not a type that supports connection-oriented service.";
case AcceptStatus::WouldBlock: return "The socket is marked as nonblocking and no connections are present to be accepted.";
}
return "";
}
std::string GetStatusDescription(SendStatus status) noexcept
{
switch (status)
{
case SendStatus::Success: return "Sent successfully.";
case SendStatus::NotInitialized: return "A successful WSAStartup call must occur before using this function.";
case SendStatus::NetworkDown: return "The network subsystem has failed.";
case SendStatus::BroadcastAddressNotEnabled: return "The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST socket option to enable use of the broadcast address.";
case SendStatus::Cancelled: return "A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall.";
case SendStatus::OperationInProgress: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case SendStatus::InvalidBufferParameter: return "The buf parameter is not completely contained in a valid part of the user address space.";
case SendStatus::NetworkReset: return "The connection has been broken due to the keep-alive activity detecting a failure while the operation was in progress.";
case SendStatus::NoBufferSpace: return "No buffer space is available.";
case SendStatus::NotConnected: return "The socket is not connected.";
case SendStatus::NotASocket: return "The descriptor is not a socket.";
case SendStatus::NotSupported: return "MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only receive operations.";
case SendStatus::Shutdown: return "The socket has been shut down; it is not possible to send on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH.";
case SendStatus::WouldBlock: return "The socket is marked as nonblocking and the requested operation would block.";
case SendStatus::MessageTooLarge: return "The socket is message oriented, and the message is larger than the maximum supported by the underlying transport.";
case SendStatus::HostUnreachable: return "The remote host cannot be reached from this host at this time.";
case SendStatus::UnboundSocket: return "The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled.";
case SendStatus::ConnectionAborted: return "The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable.";
case SendStatus::ConnectionReset: return "The virtual circuit was reset by the remote side executing a hard or abortive close. For UDP sockets, the remote host was unable to deliver a previously sent UDP datagram and responded with a \"Port Unreachable\" ICMP packet. The application should close the socket as it is no longer usable.";
case SendStatus::Timeout: return "The connection has been dropped, because of a network failure or because the system on the other end went down without notice. ";
}
return "";
}
std::string GetStatusDescription(ReceiveStatus status) noexcept
{
switch (status)
{
case ReceiveStatus::Success: return "Received successfully.";
case ReceiveStatus::NotInitialized: return "A successful WSAStartup call must occur before using this function.";
case ReceiveStatus::NetworkDown: return "The network subsystem has failed.";
case ReceiveStatus::InvalidBufferParameter: return "The buf parameter is not completely contained in a valid part of the user address space.";
case ReceiveStatus::NotConnected: return "The socket is not connected.";
case ReceiveStatus::Cancelled: return "The (blocking) call was canceled through WSACancelBlockingCall.";
case ReceiveStatus::OperationInProgress: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case ReceiveStatus::ConnectionReset: return "For a connection-oriented socket, this error indicates that the connection has been broken due to keep-alive activity that detected a failure while the operation was in progress. For a datagram socket, this error indicates that the time to live has expired.";
case ReceiveStatus::NotASocket: return "The descriptor is not a socket.";
case ReceiveStatus::NotSupported: return "MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only send operations.";
case ReceiveStatus::Shutdown: return "The socket has been shut down; it is not possible to receive on a socket after shutdown has been invoked with how set to SD_RECEIVE or SD_BOTH.";
case ReceiveStatus::WouldBlock: return "The socket is marked as nonblocking and the receive operation would block.";
case ReceiveStatus::MessageTooLarge: return "The message was too large to fit into the specified buffer and was truncated.";
case ReceiveStatus::UnboundSocket: return "The socket has not been bound with bind, or an unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled or (for byte stream sockets only) len was zero or negative.";
case ReceiveStatus::ConnectionAborted: return "The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable.";
case ReceiveStatus::Timeout: return "The connection has been dropped because of a network failure or because the peer system failed to respond.";
case ReceiveStatus::RemoteConnectionReset: return "The virtual circuit was reset by the remote side executing a hard or abortive close. The application should close the socket as it is no longer usable. On a UDP-datagram socket, this error would indicate that a previous send operation resulted in an ICMP \"Port Unreachable\" message.";
}
return "";
}
std::string GetStatusDescription(ConnectStatus status) noexcept
{
switch (status)
{
case ConnectStatus::Success: return "Connected successfully.";
case ConnectStatus::NotInitialized: return "A successful WSAStartup call must occur before using this function.";
case ConnectStatus::NetworkDown: return "The network subsystem has failed.";
case ConnectStatus::AddressInUse: return "The socket's local address is already in use and the socket was not marked to allow address reuse with SO_REUSEADDR. This error usually occurs when executing bind, but could be delayed until the connect function if the bind was to a wildcard address (INADDR_ANY or in6addr_any) for the local IP address. A specific address needs to be implicitly bound by the connect function.";
case ConnectStatus::Cancelled: return "The blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.";
case ConnectStatus::OperationInProgress: return "A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.";
case ConnectStatus::ConnectInProgress: return "A nonblocking connect call is in progress on the specified socket.";
case ConnectStatus::InvalidAddress: return "The remote address is not a valid address (such as INADDR_ANY or in6addr_any) .";
case ConnectStatus::AddressFamilyNotSupported: return "Addresses in the specified family cannot be used with this socket.";
case ConnectStatus::ConnectionRefused: return "The attempt to connect was forcefully rejected.";
case ConnectStatus::InvalidSocketDetails: return "The sockaddr structure pointed to by the name contains incorrect address format for the associated address family or the namelen parameter is too small. This error is also returned if the sockaddr structure pointed to by the name parameter with a length specified in the namelen parameter is not in a valid part of the user address space.";
case ConnectStatus::ListeningSocket: return "The parameter s is a listening socket, it shouldn't be.";
case ConnectStatus::IsConnected: return "The socket is already connected (connection-oriented sockets only).";
case ConnectStatus::NetworkUnreachable: return "The network cannot be reached from this host at this time.";
case ConnectStatus::HostUnreachable: return "A socket operation was attempted to an unreachable host.";
case ConnectStatus::NoBufferSpace: return "No buffer space is available. The socket cannot be connected.";
case ConnectStatus::NotASocket: return "The descriptor specified in the s parameter is not a socket.";
case ConnectStatus::ConnectTimeout: return "An attempt to connect timed out without establishing a connection.";
case ConnectStatus::WouldBlock: return "The socket is marked as nonblocking and the connection cannot be completed immediately.";
case ConnectStatus::BroadcastNotEnabled: return "An attempt to connect a datagram socket to broadcast address failed because setsockopt option SO_BROADCAST is not enabled. ";
}
return "";
}
static auto GetFamily(IpVersion version) noexcept
{
switch (version)
{
case IpVersion::Ipv4: return AF_INET;
case IpVersion::Ipv6: return AF_INET6;
default: return 0;
}
}
static sockaddr_in6 GetIpv6SocketStruct(Ip const & ip, uint16_t port) noexcept
{
auto ip_version = ip.GetVersion();
auto family = GetFamily(ip_version);
sockaddr_in6 output
{
.sin6_family{ static_cast<short>(family) },
.sin6_port{ htons(port) },
};
(void)inet_pton(family, ToString(ip).c_str(), (void *)&output.sin6_addr.s6_addr);
return output;
}
static sockaddr_in GetIpv4SocketStruct(Ip const & ip, uint16_t port) noexcept
{
auto ip_version = ip.GetVersion();
auto family = GetFamily(ip_version);
sockaddr_in output
{
.sin_family{ static_cast<short>(family) },
.sin_port{ htons(port) }
};
(void)inet_pton(family, ToString(ip).c_str(), (void *)&output.sin_addr);
return output;
}
static sockaddr_in6 GetIpv6AnySocketStruct(uint16_t port) noexcept
{
return
{
.sin6_family{ AF_INET6 },
.sin6_port{ htons(port) },
.sin6_addr{ in6addr_any }
};
}
static sockaddr_in GetIpv4AnySocketStruct(uint16_t port) noexcept
{
return
{
.sin_family{ AF_INET },
.sin_port{ htons(port) },
.sin_addr{ INADDR_ANY }
};
}
static BindStatus TranslateBindResult(int r) noexcept
{
if (r == SOCKET_ERROR)
{
switch (WSAGetLastError())
{
case WSANOTINITIALISED: return BindStatus::NotInitialised;
case WSAENETDOWN: return BindStatus::NetworkDown;
case WSAEACCES: return BindStatus::Access;
case WSAEADDRINUSE: return BindStatus::AddressInUse;
case WSAEADDRNOTAVAIL: return BindStatus::AddressNotAvaliable;
case WSAEFAULT: return BindStatus::InvalidPointerArgument;
case WSAEINPROGRESS: return BindStatus::OperationInProgress;
case WSAEINVAL: return BindStatus::SocketAlreadyBound;
case WSAENOBUFS: return BindStatus::NoPortsAvaliable;
case WSAENOTSOCK: return BindStatus::NotASocket;
}
}
return BindStatus::Success;
}
static ConnectStatus TranslateConnectResult(int r) noexcept
{
if (r == SOCKET_ERROR)
{
switch (WSAGetLastError())
{
case WSANOTINITIALISED: return ConnectStatus::NotInitialized;
case WSAENETDOWN: return ConnectStatus::NetworkDown;
case WSAEADDRINUSE: return ConnectStatus::AddressInUse;
case WSAEINTR: return ConnectStatus::Cancelled;
case WSAEINPROGRESS: return ConnectStatus::OperationInProgress;
case WSAEALREADY: return ConnectStatus::ConnectInProgress;
case WSAEADDRNOTAVAIL: return ConnectStatus::InvalidAddress;
case WSAEAFNOSUPPORT: return ConnectStatus::AddressFamilyNotSupported;
case WSAECONNREFUSED: return ConnectStatus::ConnectionRefused;
case WSAEFAULT: return ConnectStatus::InvalidSocketDetails;
case WSAEINVAL: return ConnectStatus::ListeningSocket;
case WSAEISCONN: return ConnectStatus::IsConnected;
case WSAENETUNREACH: return ConnectStatus::NetworkUnreachable;
case WSAEHOSTUNREACH: return ConnectStatus::HostUnreachable;
case WSAENOBUFS: return ConnectStatus::NoBufferSpace;
case WSAENOTSOCK: return ConnectStatus::NotASocket;
case WSAETIMEDOUT: return ConnectStatus::ConnectTimeout;
case WSAEWOULDBLOCK: return ConnectStatus::WouldBlock;
case WSAEACCES: return ConnectStatus::BroadcastNotEnabled;
default: return ConnectStatus::Unknown;
}
}
return ConnectStatus::Success;
}
struct WindowsSocket : BaseSocket
{
WinsockRaii winsock;
WindowsSocketRaii socket;
WindowsSocket(socket_handle handle) noexcept
: socket{ handle }
{}
WindowsSocket(int domain, int type, int protocol)
: socket{ domain, type, protocol }
{}
WindowsSocket(WindowsSocket&&) noexcept = default;
WindowsSocket& operator = (WindowsSocket&&) noexcept = default;
virtual ~WindowsSocket() override {}
BindStatus Bind(Ip const & ip, uint16_t port) const noexcept override
{
auto process = [&](auto sock_address) -> BindStatus
{
return TranslateBindResult(bind(socket.Get(), (sockaddr *)&sock_address, sizeof(sock_address)));
};
switch(ip.GetVersion())
{
case IpVersion::Ipv4: return process(GetIpv4SocketStruct(ip, port));
case IpVersion::Ipv6: return process(GetIpv6SocketStruct(ip, port));
default: return BindStatus::Unknown;
}
}
BindStatus Bind(IpVersion ip_version, uint16_t port) const noexcept override
{
auto process = [&](auto sock_address) -> BindStatus
{
return TranslateBindResult(bind(socket.Get(), (sockaddr *)&sock_address, sizeof(sock_address)));
};
switch(ip_version)
{
case IpVersion::Ipv4: return process(GetIpv4AnySocketStruct(port));
case IpVersion::Ipv6: return process(GetIpv6AnySocketStruct(port));
default: return BindStatus::Unknown;
}
}
ConnectStatus Connect(Ip const & ip, uint16_t port) const noexcept
{
auto process = [&](auto sock_address) -> ConnectStatus
{
return TranslateConnectResult(connect(socket.Get(), (sockaddr *)&sock_address, sizeof(sock_address)));
};
switch(ip.GetVersion())
{
case IpVersion::Ipv4: return process(GetIpv4SocketStruct(ip, port));
case IpVersion::Ipv6: return process(GetIpv6SocketStruct(ip, port));
default: return ConnectStatus::Unknown;
}
}
ListenStatus Listen(size_t backlog) const noexcept override
{
auto r = listen(socket.Get(), backlog);
if (r == SOCKET_ERROR)
{
switch (WSAGetLastError())
{
case WSANOTINITIALISED: return ListenStatus::NotInitialized;
case WSAENETDOWN: return ListenStatus::NetworkDown;
case WSAEADDRINUSE: return ListenStatus::AddressInUse;
case WSAEINPROGRESS: return ListenStatus::OperationInProgress;
case WSAEINVAL: return ListenStatus::UnboundSocket;
case WSAEISCONN: return ListenStatus::AlreadyConnected;
case WSAEMFILE: return ListenStatus::NoMoreDescriptors;
case WSAENOBUFS: return ListenStatus::NoBufferSpace;
case WSAENOTSOCK: return ListenStatus::NotASocket;
case WSAEOPNOTSUPP: return ListenStatus::NotSupported;
default: return ListenStatus::Unknown;
}
}
return ListenStatus::Success;
}
AcceptResult Accept() const noexcept override
{
auto r = accept(socket.Get(), NULL, NULL);
if (r == INVALID_SOCKET)
{
switch(WSAGetLastError())
{
case WSANOTINITIALISED: return { AcceptStatus::NotInitialized };
case WSAECONNRESET: return { AcceptStatus::ConnectionReset };
case WSAEINTR: return { AcceptStatus::Cancelled };
case WSAEINVAL: return { AcceptStatus::ListenNotInvoked };
case WSAEINPROGRESS: return { AcceptStatus::OperationInProgress };
case WSAEMFILE: return { AcceptStatus::NoMoreDescriptors };
case WSAENETDOWN: return { AcceptStatus::NetworkDown };
case WSAENOBUFS: return { AcceptStatus::NoBufferSpace };
case WSAENOTSOCK: return { AcceptStatus::NotASocket };
case WSAEOPNOTSUPP: return { AcceptStatus::NotSupported };
case WSAEWOULDBLOCK: return { AcceptStatus::WouldBlock };
default: return { AcceptStatus::Unknown };
}
}
WindowsSocket output{ r };
return { .status = AcceptStatus::Success, .socket = std::make_unique<Socket>(std::move(static_cast<BaseSocket&>(output))) };
}
SendResult Send(const char * buf, size_t length, int flags) const noexcept override
{
auto r = send(socket.Get(), buf, static_cast<int>(length), flags);
if (r == SOCKET_ERROR)
{
switch( WSAGetLastError())
{
case WSANOTINITIALISED: return { SendStatus::NotInitialized };
case WSAENETDOWN: return { SendStatus::NetworkDown };
case WSAEACCES: return { SendStatus::BroadcastAddressNotEnabled };
case WSAEINTR: return { SendStatus::Cancelled };
case WSAEINPROGRESS: return { SendStatus::OperationInProgress };
case WSAEFAULT: return { SendStatus::InvalidBufferParameter };
case WSAENETRESET: return { SendStatus::NetworkReset };
case WSAENOBUFS: return { SendStatus::NoBufferSpace };
case WSAENOTCONN: return { SendStatus::NotConnected };
case WSAENOTSOCK: return { SendStatus::NotASocket };
case WSAEOPNOTSUPP: return { SendStatus::NotSupported };
case WSAESHUTDOWN: return { SendStatus::Shutdown };
case WSAEWOULDBLOCK: return { SendStatus::WouldBlock };
case WSAEMSGSIZE: return { SendStatus::MessageTooLarge };
case WSAEHOSTUNREACH: return { SendStatus::HostUnreachable };
case WSAEINVAL: return { SendStatus::UnboundSocket };
case WSAECONNABORTED: return { SendStatus::ConnectionAborted };
case WSAECONNRESET: return { SendStatus::ConnectionReset };
case WSAETIMEDOUT: return { SendStatus::Timeout };
default: return { SendStatus::Unknown };
}
}
return { SendStatus::Success, static_cast<size_t>(r) };
}
ReceiveResult Receive(char * buf, size_t length, int flags) const noexcept override
{
auto r = recv(socket.Get(), buf, static_cast<int>(length), flags);
if (r == SOCKET_ERROR)
{
switch (WSAGetLastError())
{
case WSANOTINITIALISED: return { ReceiveStatus::NotInitialized };
case WSAENETDOWN: return { ReceiveStatus::NetworkDown };
case WSAEFAULT: return { ReceiveStatus::InvalidBufferParameter };
case WSAENOTCONN: return { ReceiveStatus::NotConnected };
case WSAEINTR: return { ReceiveStatus::Cancelled };
case WSAEINPROGRESS: return { ReceiveStatus::OperationInProgress };
case WSAENETRESET: return { ReceiveStatus::ConnectionReset };
case WSAENOTSOCK: return { ReceiveStatus::NotASocket };
case WSAEOPNOTSUPP: return { ReceiveStatus::NotSupported };
case WSAESHUTDOWN: return { ReceiveStatus::Shutdown };
case WSAEWOULDBLOCK: return { ReceiveStatus::WouldBlock };
case WSAEMSGSIZE: return { ReceiveStatus::MessageTooLarge };
case WSAEINVAL: return { ReceiveStatus::UnboundSocket };
case WSAECONNABORTED: return { ReceiveStatus::ConnectionAborted };
case WSAETIMEDOUT: return { ReceiveStatus::Timeout };
case WSAECONNRESET: return { ReceiveStatus::RemoteConnectionReset };
default: return { ReceiveStatus::Unknown };
}
}
return { ReceiveStatus::Success, static_cast<size_t>(r) };
}
};
static int GetDomain(IpVersion version) noexcept
{
switch (version)
{
case IpVersion::Ipv4: return AF_INET;
case IpVersion::Ipv6: return AF_INET6;
default: return 0;
}
}
static int GetType(Type type) noexcept
{
switch (type)
{
case Type::TCP: return SOCK_STREAM;
case Type::UDP: return SOCK_DGRAM;
default: return 0;
}
}
static int GetProtocol(Type type) noexcept
{
switch (type)
{
case Type::TCP: return IPPROTO_TCP;
case Type::UDP: return IPPROTO_UDP;
default: return 0;
}
}
Socket::Socket(IpVersion ip_version, Type type) noexcept
: handle{ std::make_unique<WindowsSocket>(GetDomain(ip_version), GetType(type), GetProtocol(type)) }
{}
Socket::Socket(BaseSocket && socket) noexcept
: handle{ std::make_unique<WindowsSocket>(static_cast<WindowsSocket&&>(socket)) }
{}
Socket::~Socket(){}
BindStatus Socket::Bind(Ip const & ip, uint16_t port) const noexcept
{
return handle->Bind(ip, port);
}
BindStatus Socket::Bind(IpVersion ip_version, uint16_t port) const noexcept
{
return handle->Bind(ip_version, port);
}
ListenStatus Socket::Listen(size_t backlog) const noexcept
{
return handle->Listen(backlog);
}
AcceptResult Socket::Accept() const noexcept
{
return handle->Accept();
}
SendResult Socket::Send(const char * buf, size_t length, int flags) const noexcept
{
return handle->Send(buf, length, flags);
}
ReceiveResult Socket::Receive(char * buf, size_t length, int flags) const noexcept
{
return handle->Receive(buf, length, flags);
}
ConnectStatus Socket::Connect(Ip const & ip, uint16_t port) const noexcept
{
return handle->Connect(ip, port);
}
BaseSocket::~BaseSocket(){}
} | 50.832016 | 422 | 0.755647 | seppeon |
e057dc6310154c57912c788292829909feffde5a | 2,169 | cpp | C++ | pc/1.6.4_lcddisplay.cpp | aoibird/pc | b72c0b10117f95d45e2e7423614343b5936b260a | [
"MIT"
] | null | null | null | pc/1.6.4_lcddisplay.cpp | aoibird/pc | b72c0b10117f95d45e2e7423614343b5936b260a | [
"MIT"
] | null | null | null | pc/1.6.4_lcddisplay.cpp | aoibird/pc | b72c0b10117f95d45e2e7423614343b5936b260a | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>
#define VERT 1
#define HOR 0
using namespace std;
const int MAXN = 8+2;
const int MAXS = 10+5;
const int MAXR = 2*MAXS+3;
const int MAXC = MAXN*(MAXS+2);
int S; // [1, 10] size
int N; // [0, 9999 9999] number
int digits[10][7] = {{1, 1, 1, 1, 1, 1, 0},
{0, 1, 1, 0, 0, 0, 0},
{1, 1, 0, 1, 1, 0, 1},
{1, 1, 1, 1, 0, 0, 1},
{0, 1, 1, 0, 0, 1, 1},
{1, 0, 1, 1, 0, 1, 1},
{1, 0, 1, 1, 1, 1, 1},
{1, 1, 1, 0, 0, 0, 0},
{1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 0, 1, 1}};
int segs[7][3] = {{HOR, 0, 0}, {VERT, 0, 1}, {VERT, 1, 1}, {HOR, 2, 0},
{VERT, 1, 0}, {VERT, 0, 0}, {HOR, 1, 0}};
int pad[MAXR][MAXC];
int R, C;
void draw(char s, int pos)
{
// for each segments draw it on pad
//printf("%d\n", s-'0');
for (int i = 0; i < 7; i++) {
if (digits[s-'0'][i] == 1) {
// draw the segment
int r = segs[i][1] * (S+1);
int c = pos + segs[i][2] * (S+1);
//printf("%d %d\n", r, c);
if (segs[i][0] == HOR) {
for (int i = 0; i < S; i++) pad[r][c+1+i] = '-';
}
else if (segs[i][0] == VERT) {
for (int i = 0; i < S; i++) pad[r+1+i][c] = '|';
}
else ;
}
}
}
void print()
{
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
printf("%c", pad[i][j]);
}
printf("\n");
}
}
int main()
{
int first = 1;
while (scanf("%d", &S) == 1) {
if (S == 0) break;
// init
char liter[MAXN];
int c = getchar();
int i = 0;
while (isdigit(c = getchar())) liter[i++] = c;
liter[i] = '\0';
R = 2*S+3;
C = strlen(liter)*(S+2);
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
pad[i][j] = ' ';
}
}
// for each digits draw it on pad
for (int i = 0; liter[i] != '\0'; i++) {
int pos = i * (S + 2);
draw(liter[i], pos);
//print();
}
if (first == 1) first = 0;
else printf("\n");
print();
}
}
| 23.576087 | 71 | 0.384509 | aoibird |
e05844649f727696eca04f4542aab71cbfe7031c | 395 | cc | C++ | src/leetcode/palindromeNumber.cc | yuebanyishenqiu/my_repo | ecc05146eac9f85ccb1ba07717a36f3044652264 | [
"MIT"
] | null | null | null | src/leetcode/palindromeNumber.cc | yuebanyishenqiu/my_repo | ecc05146eac9f85ccb1ba07717a36f3044652264 | [
"MIT"
] | null | null | null | src/leetcode/palindromeNumber.cc | yuebanyishenqiu/my_repo | ecc05146eac9f85ccb1ba07717a36f3044652264 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
bool judge(int i){
if(i < 0 || ((i % 10 == 0 && i != 0)))
return false;
int j = 0;
while(i > j){
j = j*10 + i%10;
i /= 10;
}
return (i == j || i == j/10)? true:false;
}
int main(){
int i;
cin >> i;
if(judge(i))
cout << "true" <<endl;
else
cout << "false" <<endl;
return 0;
}
| 17.954545 | 45 | 0.425316 | yuebanyishenqiu |
e063649cb9f2f51b43d201ae2b3a4d068105ad40 | 675 | cpp | C++ | Problems/234. Palindrome Linked List/pointers_array.cpp | uSlashVlad/MyLeetCode | 3d5e8e347716beb0ffadb538c92eceb42ab7fcf9 | [
"MIT"
] | 1 | 2022-01-29T01:52:58.000Z | 2022-01-29T01:52:58.000Z | Problems/234. Palindrome Linked List/pointers_array.cpp | uSlashVlad/MyLeetCode | 3d5e8e347716beb0ffadb538c92eceb42ab7fcf9 | [
"MIT"
] | null | null | null | Problems/234. Palindrome Linked List/pointers_array.cpp | uSlashVlad/MyLeetCode | 3d5e8e347716beb0ffadb538c92eceb42ab7fcf9 | [
"MIT"
] | null | null | null | #include "../includes.hpp"
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution
{
public:
bool isPalindrome(ListNode *head)
{
std::vector<int> v = {head->val};
while (head->next != nullptr)
{
head = head->next;
v.push_back(head->val);
}
int l = v.size();
for (int i = 0; i < l / 2; i++)
{
if (v[i] != v[l - i - 1])
return false;
}
return true;
}
}; | 19.285714 | 59 | 0.472593 | uSlashVlad |
e0659d765ab0cc8a761b63d0ce40c537f57ba20d | 9,762 | cc | C++ | cblite/cbliteTool+query.cc | mhocouchbase/couchbase-mobile-tools | d2f2a9f45ff7d6ec4956e994561825a13f0be313 | [
"Apache-2.0"
] | null | null | null | cblite/cbliteTool+query.cc | mhocouchbase/couchbase-mobile-tools | d2f2a9f45ff7d6ec4956e994561825a13f0be313 | [
"Apache-2.0"
] | null | null | null | cblite/cbliteTool+query.cc | mhocouchbase/couchbase-mobile-tools | d2f2a9f45ff7d6ec4956e994561825a13f0be313 | [
"Apache-2.0"
] | null | null | null | //
// cbliteTool+Query.cc
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "cbliteTool.hh"
#include "StringUtil.hh"
#ifdef _MSC_VER
#define strncasecmp _strnicmp
#endif
const Tool::FlagSpec CBLiteTool::kQueryFlags[] = {
{"--explain",(FlagHandler)&CBLiteTool::explainFlag},
{"--help", (FlagHandler)&CBLiteTool::helpFlag},
{"--limit", (FlagHandler)&CBLiteTool::limitFlag},
{"--offset", (FlagHandler)&CBLiteTool::offsetFlag},
{"--raw", (FlagHandler)&CBLiteTool::rawFlag},
{"--json5", (FlagHandler)&CBLiteTool::json5Flag},
{nullptr, nullptr}
};
void CBLiteTool::queryUsage() {
writeUsageCommand("query", true, "QUERY");
cerr <<
" Runs a query against the database, in JSON or N1QL format.\n"
" --raw : Output JSON (instead of a table)\n"
" --json5 : Omit quotes around alphanmeric keys in JSON output\n"
" --offset N : Skip first N rows\n"
" --limit N : Stop after N rows\n"
" --explain : Show SQLite query and explain query plan\n"
" " << it("QUERYSTRING") << " : LiteCore JSON or N1QL query expression\n";
if (_interactive)
cerr << " NOTE: Do not quote the query string, just give it literally.\n";
}
void CBLiteTool::selectUsage() {
writeUsageCommand("select", true, "N1QLSTRING");
cerr <<
" Runs a N1QL query against the database.\n"
" --raw : Output JSON (instead of a table)\n"
" --json5 : Omit quotes around alphanmeric keys in JSON output\n"
" --explain : Show translated SQLite query and explain query plan\n"
" " << it("N1QLSTRING") << " : N1QL query, minus the 'SELECT'\n";
if (_interactive)
cerr << " NOTE: Do not quote the query string, just give it literally.\n";
}
void CBLiteTool::queryDatabase() {
C4QueryLanguage language = kC4JSONQuery;
if (_currentCommand != "query") // i.e. it's "select"
language = kC4N1QLQuery;
// Read params:
processFlags(kQueryFlags);
if (_showHelp) {
if (language == kC4JSONQuery)
queryUsage();
else
selectUsage();
return;
}
openDatabaseFromNextArg();
string queryStr = restOfInput("query string");
// Possibly translate query from N1QL to JSON:
unsigned queryStartPos = 9;
if (language == kC4N1QLQuery) {
queryStr = _currentCommand + " " + queryStr;
} else if (queryStr[0] != '{' && queryStr[0] != '[') {
language = kC4N1QLQuery;
queryStartPos += _currentCommand.size() + 1;
}
// Compile query:
C4Error error;
size_t errorPos;
c4::ref<C4Query> query = compileQuery(language, queryStr, &errorPos, &error);
if (!query) {
if (error.domain == LiteCoreDomain && error.code == kC4ErrorInvalidQuery) {
if (_interactive) {
errorPos += queryStartPos;
} else {
cerr << queryStr << "\n";
}
cerr << string(errorPos, ' ') << "^\n";
alloc_slice errorMessage = c4error_getMessage(error);
fail(string(errorMessage));
} else {
fail("compiling query", error);
}
}
if (_explain) {
// Explain query plan:
alloc_slice explanation = c4query_explain(query);
cout << explanation;
} else {
// Run query:
// Set parameters:
alloc_slice params;
if (_offset > 0 || _limit >= 0) {
JSONEncoder enc;
enc.beginDict();
enc.writeKey("offset"_sl);
enc.writeInt(_offset);
enc.writeKey("limit"_sl);
enc.writeInt(_limit);
enc.endDict();
params = enc.finish();
}
c4::ref<C4QueryEnumerator> e = c4query_run(query, nullptr, params, &error);
if (!e)
fail("starting query", error);
if (_prettyPrint)
displayQueryAsTable(query, e);
else
displayQueryAsJSON(query, e);
}
}
void CBLiteTool::displayQueryAsJSON(C4Query *query, C4QueryEnumerator *e) {
unsigned nCols = c4query_columnCount(query);
vector<string> colTitle(nCols);
for (unsigned col = 0; col < nCols; ++col) {
auto title = string(slice(c4query_columnTitle(query, col)));
if (!_json5 || !canBeUnquotedJSON5Key(title))
title = "\"" + title + "\"";
colTitle[col] = title;
}
uint64_t nRows = 0;
C4Error error;
cout << "[";
while (c4queryenum_next(e, &error)) {
// Write a result row:
if (nRows++)
cout << ",\n ";
cout << "{";
int col = 0, n = 0;
for (Array::iterator i(e->columns); i; ++i, ++col) {
if (!(e->missingColumns & (1<<col))) {
if (n++)
cout << ", ";
cout << colTitle[col] << ": ";
rawPrint(i.value(), nullslice);
}
}
cout << "}";
}
if (error.code)
fail("running query", error);
cout << "]\n";
}
void CBLiteTool::displayQueryAsTable(C4Query *query, C4QueryEnumerator *e) {
unsigned nCols = c4query_columnCount(query);
uint64_t nRows;
vector<size_t> widths(nCols);
unsigned col;
C4Error error;
// Compute the column widths:
for (col = 0; col < nCols; ++col) {
auto title = c4query_columnTitle(query, col);
widths[col] = title.size; // not UTF-8-aware...
}
nRows = 0;
while (c4queryenum_next(e, &error)) {
++nRows;
col = 0;
for (Array::iterator i(e->columns); i; ++i) {
if (!(e->missingColumns & (1<<col))) {
size_t width;
if (i.value().type() == kFLString)
width = i.value().asString().size;
else
width = i.value().toJSON(_json5, true).size;
widths[col] = max(widths[col], width);
}
++col;
}
}
if (error.code || !c4queryenum_restart(e, &error))
fail("running query", error);
if (nRows == 0) {
cout << "(No results)\n";
return;
}
// Subroutine that writes a column:
auto writeCol = [&](slice s, int align) {
string pad(widths[col] - s.size, ' ');
if (align < 0)
cout << pad;
cout << s;
if (col < nCols-1) {
if (align > 0)
cout << pad;
cout << ' ';
}
};
// Write the column titles:
if (nCols > 1) {
cout << ansiBold();
for (col = 0; col < nCols; ++col)
writeCol(c4query_columnTitle(query, col), 1);
cout << "\n";
for (col = 0; col < nCols; ++col)
cout << string(widths[col], '_') << ' ';
cout << ansiReset() << "\n";
}
// Write the rows:
nRows = 0;
while (c4queryenum_next(e, &error)) {
// Write a result row:
++nRows;
col = 0;
for (Array::iterator i(e->columns); i; ++i) {
alloc_slice json;
if (!(e->missingColumns & (1<<col))) {
auto type = i.value().type();
if (type == kFLString)
writeCol(i.value().asString(), 1);
else
writeCol(i.value().toJSON(_json5, true),
(type == kFLNumber ? -1 : 1));
}
++col;
}
cout << "\n";
}
if (error.code)
fail("running query", error);
}
C4Query* CBLiteTool::compileQuery(C4QueryLanguage language, string queryStr,
size_t *outErrorPos, C4Error *outError)
{
if (language == kC4JSONQuery) {
// Convert JSON5 to JSON and detect JSON syntax errors:
FLError flErr;
FLStringResult outErrMsg;
alloc_slice queryJSONBuf = FLJSON5_ToJSON(slice(queryStr), &outErrMsg, outErrorPos, &flErr);
if (!queryJSONBuf) {
alloc_slice message(move(outErrMsg));
string messageStr = format("parsing JSON: %.*s", SPLAT(message));
if (flErr == kFLJSONError)
*outError = c4error_make(LiteCoreDomain, kC4ErrorInvalidQuery, slice(messageStr));
else
*outError = c4error_make(FleeceDomain, flErr, slice(messageStr));
return nullptr;
}
// Trim whitespace from either end:
slice queryJSON = queryJSONBuf;
while (isspace(queryJSON[0]))
queryJSON.moveStart(1);
while (isspace(queryJSON[queryJSON.size-1]))
queryJSON.setSize(queryJSON.size-1);
// Insert OFFSET/LIMIT:
stringstream json;
if (queryJSON[0] == '[')
json << "{\"WHERE\": " << queryJSON;
else
json << slice(queryJSON.buf, queryJSON.size - 1);
if (_offset > 0 || _limit >= 0)
json << ", \"OFFSET\": [\"$offset\"], \"LIMIT\": [\"$limit\"]";
json << "}";
queryStr = json.str();
}
int pos;
auto query = c4query_new2(_db, language, slice(queryStr), &pos, outError);
if (!query && outErrorPos)
*outErrorPos = pos;
return query;
}
| 32.006557 | 100 | 0.541487 | mhocouchbase |
e06d9cd70b869e3329ab4b524dd76112e04aa3d9 | 6,439 | cpp | C++ | src/Settings/Constants.cpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 12 | 2020-09-07T11:19:10.000Z | 2022-02-17T17:40:19.000Z | src/Settings/Constants.cpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 110 | 2020-09-02T15:29:24.000Z | 2022-03-09T09:50:01.000Z | src/Settings/Constants.cpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 3 | 2021-05-21T13:24:31.000Z | 2022-02-11T14:43:12.000Z | /**
* Definition of OptionConstants constants.
*/
#include "DREAM/Settings/OptionConstants.hpp"
using namespace DREAM;
/**
* NAMES OF UNKNOWN QUANTITIES
*/
const char *OptionConstants::UQTY_E_FIELD = "E_field";
const char *OptionConstants::UQTY_F_HOT = "f_hot";
const char *OptionConstants::UQTY_F_RE = "f_re";
const char *OptionConstants::UQTY_ION_SPECIES = "n_i";
const char *OptionConstants::UQTY_ION_SPECIES_ABL = "n_i_abl";
const char *OptionConstants::UQTY_I_P = "I_p";
const char *OptionConstants::UQTY_I_WALL = "I_wall";
const char *OptionConstants::UQTY_J_HOT = "j_hot";
const char *OptionConstants::UQTY_J_OHM = "j_ohm";
const char *OptionConstants::UQTY_J_RE = "j_re";
const char *OptionConstants::UQTY_J_TOT = "j_tot";
const char *OptionConstants::UQTY_N_ABL = "n_abl";
const char *OptionConstants::UQTY_N_COLD = "n_cold";
const char *OptionConstants::UQTY_N_HOT = "n_hot";
const char *OptionConstants::UQTY_N_RE = "n_re";
const char *OptionConstants::UQTY_N_RE_NEG = "n_re_neg";
const char *OptionConstants::UQTY_N_TOT = "n_tot";
const char *OptionConstants::UQTY_NI_DENS = "N_i";
const char *OptionConstants::UQTY_POL_FLUX = "psi_p";
const char *OptionConstants::UQTY_PSI_EDGE = "psi_edge";
const char *OptionConstants::UQTY_Q_HOT = "q_hot";
const char *OptionConstants::UQTY_PSI_TRANS = "psi_trans";
const char *OptionConstants::UQTY_PSI_WALL = "psi_wall";
const char *OptionConstants::UQTY_S_PARTICLE = "S_particle";
const char *OptionConstants::UQTY_T_ABL = "T_abl";
const char *OptionConstants::UQTY_T_COLD = "T_cold";
const char *OptionConstants::UQTY_TAU_COLL = "tau_coll";
const char *OptionConstants::UQTY_V_LOOP_TRANS = "V_loop_trans";
const char *OptionConstants::UQTY_V_LOOP_WALL = "V_loop_w";
const char *OptionConstants::UQTY_V_P = "v_p";
const char *OptionConstants::UQTY_W_ABL = "W_abl";
const char *OptionConstants::UQTY_W_COLD = "W_cold";
const char *OptionConstants::UQTY_W_HOT = "W_hot";
const char *OptionConstants::UQTY_WI_ENER = "W_i";
const char *OptionConstants::UQTY_X_P = "x_p";
const char *OptionConstants::UQTY_Y_P = "Y_p";
/**
* DESCRIPTIONS OF UNKNOWN QUANTITIES
*/
const char *OptionConstants::UQTY_E_FIELD_DESC = "Parallel electric field <E*B>/sqrt(<B^2>) [V/m]";
const char *OptionConstants::UQTY_F_HOT_DESC = "Hot electron distribution function [m^-3]";
const char *OptionConstants::UQTY_F_RE_DESC = "Runaway electron distribution function [m^-3]";
const char *OptionConstants::UQTY_ION_SPECIES_DESC = "Ion density [m^-3]";
const char *OptionConstants::UQTY_ION_SPECIES_ABL_DESC = "Flux surface averaged density of ablated but not yet equilibrated ions [m^-3]";
const char *OptionConstants::UQTY_I_P_DESC = "Total toroidal plasma current [A]";
const char *OptionConstants::UQTY_I_WALL_DESC = "Wall current [A]";
const char *OptionConstants::UQTY_J_HOT_DESC = "Hot electron parallel current density j_||*Bmin/B [A/m^2]";
const char *OptionConstants::UQTY_J_OHM_DESC = "Ohmic current density j_||*Bmin/B [A/m^2]";
const char *OptionConstants::UQTY_J_RE_DESC = "Runaway electron current density j_||*Bmin/B [A/m^2]";
const char *OptionConstants::UQTY_J_TOT_DESC = "Total current density j_||*Bmin/B [A/m^2]";
const char *OptionConstants::UQTY_N_ABL_DESC = "Flux surface averaged density of ablated but not yet equilibrated electrons [m^-3]";
const char *OptionConstants::UQTY_N_COLD_DESC = "Cold electron density [m^-3]";
const char *OptionConstants::UQTY_N_HOT_DESC = "Hot electron density [m^-3]";
const char *OptionConstants::UQTY_N_RE_DESC = "Runaway electron density <n> [m^-3]";
const char *OptionConstants::UQTY_N_RE_NEG_DESC = "Runaway electron density in negative direction <n> [m^-3]";
const char *OptionConstants::UQTY_N_TOT_DESC = "Total electron density [m^-3]";
const char *OptionConstants::UQTY_NI_DENS_DESC = "Total ion density of each species [m^-3]";
const char *OptionConstants::UQTY_POL_FLUX_DESC = "Poloidal magnetic flux normalized to major radius R0 [Vs/m]";
const char *OptionConstants::UQTY_PSI_EDGE_DESC = "Poloidal magnetic flux at plasma edge (r=rmax) normalized to major radius R0 [Vs/m]";
const char *OptionConstants::UQTY_Q_HOT_DESC = "Hot out going heat flux density in all directions [J/(s m^2)]";
const char *OptionConstants::UQTY_PSI_TRANS_DESC = "Poloidal magnetic flux at transformer normalized to major radius R0 [Vs/m]";
const char *OptionConstants::UQTY_PSI_WALL_DESC = "Poloidal magnetic flux on tokamak wall (r=rwall) normalized to major radius R0 [Vs/m]";
const char *OptionConstants::UQTY_S_PARTICLE_DESC = "Rate at which cold-electron density is added [m^-3 s^-1]";
const char *OptionConstants::UQTY_T_ABL_DESC = "Ablated but not equilibrated electron temperature [eV]";
const char *OptionConstants::UQTY_T_COLD_DESC = "Cold electron temperature [eV]";
const char *OptionConstants::UQTY_TAU_COLL_DESC = "Time-integrated relativistic collision frequency for analytic hottail formula";
const char *OptionConstants::UQTY_V_LOOP_TRANS_DESC = "Loop voltage applied at transformer normalized to major radius R0 [V/m]";
const char *OptionConstants::UQTY_V_LOOP_WALL_DESC = "Loop voltage on tokamak wall normalized to major radius R0 [V/m]";
const char *OptionConstants::UQTY_V_P_DESC = "Pellet shard velocities (Cartesian) [m/s]";
const char *OptionConstants::UQTY_W_ABL_DESC = "Flux surface averaged ablated but not equilibrated electron energy density (3n_abl T_abl/2) [J/m^3]";
const char *OptionConstants::UQTY_W_COLD_DESC = "Cold electron energy density (3nT/2) [J/m^3]";
const char *OptionConstants::UQTY_W_HOT_DESC = "Hot electron energy density [J/m^3]";
const char *OptionConstants::UQTY_WI_ENER_DESC = "Total ion energy density (3N_iT_i/2) of each species [J/m^3]";
const char *OptionConstants::UQTY_X_P_DESC = "Pellet shard coordinates (Cartesian) [m]";
const char *OptionConstants::UQTY_Y_P_DESC = "Pellet shard radii to the power of 5/3 [m^(5/3)]";
| 72.348315 | 156 | 0.702283 | chalmersplasmatheory |
e06f56385da1f7fcf39d2e6691a2cddca6855a08 | 5,221 | cpp | C++ | src/tests/test_lift.cpp | victimsnino/ReactivePlusPlus | bb187cc52936bce7c1ef4899d7dbb9c970cef291 | [
"MIT"
] | 1 | 2022-03-19T20:15:50.000Z | 2022-03-19T20:15:50.000Z | src/tests/test_lift.cpp | victimsnino/ReactivePlusPlus | bb187cc52936bce7c1ef4899d7dbb9c970cef291 | [
"MIT"
] | 12 | 2022-03-22T21:18:14.000Z | 2022-03-30T05:37:58.000Z | src/tests/test_lift.cpp | victimsnino/ReactivePlusPlus | bb187cc52936bce7c1ef4899d7dbb9c970cef291 | [
"MIT"
] | null | null | null | // ReactivePlusPlus library
//
// Copyright Aleksey Loginov 2022 - present.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/victimsnino/ReactivePlusPlus
//
#include "copy_count_tracker.hpp"
#include "mock_observer.hpp"
#include <catch2/catch_test_macros.hpp>
#include <rpp/observables.hpp>
#include <rpp/sources/create.hpp>
#include <rpp/subscribers.hpp>
#include <rpp/observables/dynamic_observable.hpp>
#include <rpp/observers/state_observer.hpp>
SCENARIO("Observable can be lifted")
{
auto verifier = copy_count_tracker{};
auto validate = [&](auto observable)
{
WHEN("Call lift")
{
int calls_internal = 0;
auto new_observable = observable.template lift<int>([&calls_internal](int val, const auto& sub)
{
++calls_internal;
sub.on_next(val);
});
AND_WHEN("subscribe unsubscribed subscriber")
{
int calls_external = 0;
auto subscriber = rpp::specific_subscriber{[&](int) { ++calls_external; }};
subscriber.unsubscribe();
new_observable.subscribe(subscriber);
THEN("No any calls obtained")
{
CHECK(calls_internal == 0);
CHECK(calls_external == 0);
}
}
}
WHEN("Call lift with exception")
{
auto new_observable = observable.template lift<int>([](int, const auto& )
{
throw std::runtime_error{""};
});
AND_WHEN("subscribe subscriber")
{
auto mock = mock_observer<int>{};
new_observable.subscribe(mock);
THEN("subscriber obtais on error")
{
CHECK(mock.get_total_on_next_count() == 0);
CHECK(mock.get_on_error_count() == 1);
CHECK(mock.get_on_completed_count() == 0);
}
}
}
WHEN("Call lift as lvalue")
{
auto initial_copy_count = verifier.get_copy_count();
auto initial_move_count = verifier.get_move_count();
auto new_observable = observable.lift([](rpp::dynamic_subscriber<double> sub)
{
return rpp::dynamic_subscriber{sub.get_subscription(),
[sub](int val)
{
sub.on_next(static_cast<double>(val) / 2);
}};
});
THEN("On subscribe obtain modified values")
{
std::vector<double> obtained_values{};
new_observable.subscribe([&](double v) { obtained_values.push_back(v); });
CHECK(obtained_values == std::vector{5.0, 2.5});
}
if constexpr (!std::is_same_v<decltype(observable), rpp::dynamic_observable<int>>)
{
AND_THEN("One copy to lambda + one move to new observable")
{
CHECK(verifier.get_copy_count() == initial_copy_count +1);
CHECK(verifier.get_move_count() == initial_move_count +1);
}
}
}
WHEN("Call lift as rvalue")
{
auto initial_copy_count = verifier.get_copy_count();
auto initial_move_count = verifier.get_move_count();
auto new_observable = std::move(observable).lift([](rpp::dynamic_subscriber<double> sub)
{
return rpp::specific_subscriber{sub.get_subscription(),
[sub](int val)
{
sub.on_next(static_cast<double>(val) / 2);
}};
});
THEN("On subscribe obtain modified values")
{
std::vector<double> obtained_values{};
new_observable.subscribe([&](double v) { obtained_values.push_back(v); });
CHECK(obtained_values == std::vector{5.0, 2.5});
}
if constexpr (!std::is_same_v<decltype(observable), rpp::dynamic_observable<int>>)
{
AND_THEN("One move to lambda + one move to new observable")
{
CHECK(verifier.get_copy_count() == initial_copy_count);
CHECK(verifier.get_move_count() == initial_move_count +2);
}
}
}
};
auto observable = rpp::observable::create<int>([verifier](const auto& sub)
{
sub.on_next(10);
sub.on_next(5);
sub.on_completed();
});
GIVEN("Observable")
validate(observable);
GIVEN("DynamicObservable")
validate(observable.as_dynamic());
} | 36.256944 | 107 | 0.500287 | victimsnino |
e070bf8609cf27f34b95d773ab77e70c6157a017 | 17,355 | cpp | C++ | src/zyre/zyre.cpp | staroy/gyro | 3cc048af5605cf4aad50812733cebe1e0232c2f9 | [
"MIT"
] | null | null | null | src/zyre/zyre.cpp | staroy/gyro | 3cc048af5605cf4aad50812733cebe1e0232c2f9 | [
"MIT"
] | null | null | null | src/zyre/zyre.cpp | staroy/gyro | 3cc048af5605cf4aad50812733cebe1e0232c2f9 | [
"MIT"
] | null | null | null | #include "zyre.hpp"
#include "auth.h"
#include <iostream>
#include <boost/filesystem.hpp>
#include "misc_log_ex.h"
#include "sodium.h"
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "zyre.cc"
namespace zyre
{
void *server::ctx_ = nullptr;
server::server(
const std::string& name,
const std::vector<std::string>& groups,
const std::string& pin)
: name_(name)
, glist_(groups)
, pin_(pin)
, verbose_(false)
{
if(!ctx_)
ctx_ = zsys_init();
terminated_ = false;
for(const auto& g : groups)
groups_[g] = 0;
}
void server::start()
{
thread_ = std::thread(std::bind(&server::run, this));
}
void server::stop()
{
terminated_ = true;
}
void server::join()
{
thread_.join();
}
void server::run()
{
std::set<std::string> scripts;
zyre_t *node = zyre_new( name_.c_str() );
if (!node)
{
MLOG_RED(el::Level::Warning, "Could not create new zyre node");
return;
}
if(!pin_.empty())
{
zyre_set_zap_domain(node, ("zap-" + name_).c_str());
zcert_t *cert = pin_to_cert(pin_);
zyre_set_zcert(node, cert);
zyre_set_header(node, "X-PUBLICKEY", "%s", zcert_public_txt(cert));
if(verbose_)
zyre_set_verbose(node);
zcert_destroy(&cert);
}
zyre_start(node);
for(const auto& g : groups_)
zyre_join(node, g.first.c_str());
// connection from inproc clients
zsock_t *inproc = zsock_new_router((inproc_ZYRE "-" + name_).c_str());
zpoller_t *poller = zpoller_new(zyre_socket(node), inproc, NULL);
while(!terminated_)
{
void *which = zpoller_wait(poller, 100);
try
{
if(which == inproc)
{
zmsg_t *msg = zmsg_recv(which);
if (!msg) {
MLOG_RED(el::Level::Error, "Interrupted zyre node");
break;
}
zframe_t *src = zmsg_pop(msg);
zframe_t *op = zmsg_pop(msg);
if(zframe_streq(op, S_JOIN))
{
char *name = zmsg_popstr(msg);
auto s = scripts.find(name);
if(s == scripts.end())
scripts.insert(name);
zstr_free(&name);
}
else if(zframe_streq(op, S_LEAVE))
{
char *name = zmsg_popstr(msg);
auto s = scripts.find(name);
if(s != scripts.end())
scripts.erase(s);
zstr_free(&name);
}
else if(zframe_streq(op, JOIN))
{
char *name = zmsg_popstr(msg);
auto g = groups_.find(name);
if(g == groups_.end())
{
groups_[name] = 1;
zyre_join(node, name);
}
else
g->second++;
zstr_free(&name);
}
else if(zframe_streq(op, LEAVE))
{
char *name = zmsg_popstr(msg);
auto g = groups_.find(name);
if(g != groups_.end())
{
if(g->second == 1)
{
groups_.erase(g);
zyre_leave(node, name);
}
if(g->second > 1)
g->second--;
}
zstr_free(&name);
}
else if(zframe_streq(op, inproc_SHOUT) || zframe_streq(op, inproc_WHISPER))
{
zframe_t *dst = zmsg_pop(msg);
zmsg_prepend(msg, &src);
zmsg_prepend(msg, &op);
zmsg_prepend(msg, &dst);
zmsg_send(&msg, inproc);
}
else if(zframe_streq(op, SHOUT))
{
char *group = zmsg_popstr(msg);
zmsg_prepend(msg, &src);
zyre_shout(node, group, &msg);
zstr_free(&group);
}
else if(zframe_streq(op, WHISPER))
{
char *peer = zmsg_popstr(msg);
zmsg_prepend(msg, &src);
zyre_whisper(node, peer, &msg);
zstr_free(&peer);
}
else
{
MLOG_RED(el::Level::Error, "E: invalid message to zyre actor src=" << zframe_strdup(src) << " op=" << zframe_strdup(op));
}
zmsg_destroy (&msg);
}
else if(which == zyre_socket(node))
{
zmsg_t *msg = zmsg_recv(which);
zframe_t *event = zmsg_first(msg);
if(zframe_streq(event, SHOUT) || zframe_streq(event, WHISPER))
{
//MLOG_GREEN(el::Level::Info, "zframe_streq(event, SHOUT) || zframe_streq(event, WHISPER) == true");
for(const auto& s : scripts)
{
zmsg_t *m = zmsg_dup(msg);
zframe_t *n = zframe_from(s.c_str());
zmsg_prepend(m, &n);
zmsg_send(&m, inproc);
}
}
zmsg_destroy(&msg);
}
}
catch(const std::exception& e)
{
MLOG_RED(el::Level::Error, e.what());
}
catch(...)
{
MLOG_RED(el::Level::Error, "unqnow");
}
}
zpoller_destroy(&poller);
zyre_stop (node);
zclock_sleep (100);
zyre_destroy (&node);
zsock_destroy(&inproc);
}
zcert_t *server::pin_to_cert(const std::string& pin)
{
uint8_t salt[crypto_pwhash_scryptsalsa208sha256_SALTBYTES] = {
128,165, 28,003,132,201,031,250,142,184,186,024, 8,167,68,075,
053,231,105,160,230,167,144,201,176,158, 68,162,78,128,68,109
};
uint8_t seed[crypto_box_SEEDBYTES];
if(0 != ::crypto_pwhash_scryptsalsa208sha256(
seed, crypto_box_SEEDBYTES, pin.c_str(), pin.length(), salt,
crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE,
crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE))
{
MLOG_RED(el::Level::Error, "Could not create seed");
return nullptr;
}
uint8_t pk[crypto_box_PUBLICKEYBYTES];
uint8_t sk[crypto_box_SECRETKEYBYTES];
if(0 != ::crypto_box_seed_keypair(pk, sk, seed))
{
MLOG_RED(el::Level::Error, "Could not create certificate");
return nullptr;
}
return zcert_new_from(pk, sk);
}
std::atomic<uint64_t> client::cookie_n_;
client::client(
boost::asio::io_service& ios,
const std::string& name,
const server& srv)
: ios_(ios)
, name_(name)
, dev_(srv.name())
, zyre_sock_(zmq_socket(server::ctx(), ZMQ_DEALER))
, zyre_(ios, zyre_sock_)
, reply_timeout_(3) // 3 sec
{
zyre_.set_option(azmq::socket::identity(name_.data(), name_.size()));
zyre_.connect((inproc_ZYRE "-" + dev_).c_str());
}
void client::s_join(const std::string& name)
{
if(ios_.stopped())
return;
std::array<boost::asio::const_buffer, 2> data = {{
boost::asio::buffer(S_JOIN, sizeof(S_JOIN)-1),
boost::asio::buffer(name.data(), name.size())
}};
zyre_.send(data);
}
void client::s_leave(const std::string& name)
{
if(ios_.stopped())
return;
std::array<boost::asio::const_buffer, 2> data = {{
boost::asio::buffer(S_LEAVE, sizeof(S_LEAVE)-1),
boost::asio::buffer(name.data(), name.size())
}};
zyre_.send(data);
}
void client::join(const std::string& name)
{
if(ios_.stopped())
return;
for(const auto& g : groups_)
if(g == name) return;
std::array<boost::asio::const_buffer, 2> data = {{
boost::asio::buffer(JOIN, sizeof(JOIN)-1),
boost::asio::buffer(name.data(), name.size())
}};
zyre_.send(data);
groups_.push_back(name);
}
void client::leave(const std::string& name)
{
if(ios_.stopped())
return;
for(auto it=groups_.begin(); it<groups_.end(); it++)
if(*it == name)
{
std::array<boost::asio::const_buffer, 2> data = {{
boost::asio::buffer(LEAVE, sizeof(LEAVE)-1),
boost::asio::buffer(name.data(), name.size())
}};
zyre_.send(data);
groups_.erase(it);
}
}
#define ERROR_SHORT_EVENT "error short event"
void client::start()
{
zyre_.async_receive(
[&](boost::system::error_code const& e, azmq::message& msg, size_t bc)
{
if(!ios_.stopped())
{
try
{
if(e)
throw std::runtime_error(e.message());
if(!msg.more() || bc == 0)
throw std::runtime_error(ERROR_SHORT_EVENT);
azmq::message_vector vec;
boost::system::error_code ec;
zyre_.receive_more(vec, 0, ec);
if(ec)
throw std::runtime_error(ec.message());
bool is_shout = false;
bool is_whisper = false;
bool is_local = false;
std::string op = msg.string();
/*std::string v0 = vec[0].string();
std::string v1 = vec[1].string();
std::string v2 = vec[2].string();
std::string v3 = vec[3].string();
std::string v4 = vec[4].string();
std::string v5 = vec[5].string();
ZLOG(ERROR) << (std::string() +
+ "op=" + op + "\n"
+ "v0=" + v0 + "\n"
+ "v1=" + v1 + "\n"
+ "v2=" + v2 + "\n"
+ "v3=" + v3 + "\n"
+ "v4=" + v4 + "\n"
+ "v5=" + v5 + "\n");*/
if(op == SHOUT)
is_shout = true;
if(op == inproc_SHOUT)
{ is_shout = true; is_local = true; }
if(op == WHISPER)
is_whisper = true;
if(op == inproc_WHISPER)
{ is_whisper = true; is_local = true; }
size_t peer = size_t(-1),
name = size_t(-1),
group = size_t(-1),
src = size_t(-1),
cmd = size_t(-1),
data = size_t(-1),
n = 0;
if(!is_local)
{
peer = n; n++;
name = n; n++;
if(is_shout) {
group = n; n++;
}
src = n; n++;
}
else
{
peer = n; n++;
}
if (is_shout || is_whisper)
{
if(n+5 > vec.size())
throw std::runtime_error(ERROR_SHORT_EVENT);
uint64_t ver_major = 0;
uint64_t ver_minor = 0;
msgpack::unpack(static_cast<const char *>(vec[n].data()), vec[n].size())
.get().convert(ver_major); n++;
msgpack::unpack(static_cast<const char *>(vec[n].data()), vec[n].size())
.get().convert(ver_minor); n++;
uint64_t cookie = 0;
msgpack::unpack(static_cast<const char *>(vec[n].data()), vec[n].size())
.get().convert(cookie); n++;
cmd = n; n++;
data = n; n++;
/*MLOG_RED(el::Level::Warning, (std::string("CLIENT ") + name_ + " RECEIVED\n"
+ "op=" + op + "\n"
+ "peer=" + vec[peer].string() + "\n"
+ "src=" + (src == size_t(-1) ? "" : vec[src].string()) + "\n"
+ "cmd=" + vec[cmd].string() + "\n"
+ "ver_major=" + std::to_string(ver_major) + "\n"
+ "ver_minor=" + std::to_string(ver_minor) + "\n"
+ "cookie=" + std::to_string(cookie)));*/
if(ver_minor == VER_MINOR && ver_major == VER_MAJOR)
{
std::string cmd_s = vec[cmd].string();
if(cmd_s == REPLY)
{
const auto& ri = reply_.find(cookie);
if(ri != reply_.end())
ri->second.f(vec[data].string());
}
else
{
const auto& f1 = meth_r_.find(cmd_s);
if(f1 != meth_r_.end())
{
std::string dd = vec[data].string();
f1->second(vec[data].string(), [&](const std::string& res){
do_send(
is_local ? inproc_WHISPER : WHISPER,
is_local ? sizeof(inproc_WHISPER)-1 : sizeof(WHISPER)-1,
static_cast<const char*>(vec[peer].data()), vec[peer].size(),
REPLY, sizeof(REPLY)-1,
res.data(), res.size(),
cookie);
});
}
else
{
const auto& f2 = meth_.find(cmd_s);
if(f2 != meth_.end())
f2->second(vec[data].string());
}
}
}
else
{
MLOG_RED(el::Level::Error, (std::string("CLIENT ") + name_ + " RECEIVED\n"
+ "Error version: name: " + (name == size_t(-1) ? "" : vec[name].string()) + "\n"
+ "peer: " + (peer == size_t(-1) ? "" : vec[peer].string()) + "\n"
+ "group: " + (group == size_t(-1) ? "" : vec[group].string()) + "\n"
+ "src: " + (src == size_t(-1) ? "" : vec[src].string()) + "\n"
+ "cmd: " + (cmd == size_t(-1) ? "" : vec[cmd].string()) + "\n"
+ "ver_major: " + std::to_string(ver_major) + "\n"
+ "ver_minor: " + std::to_string(ver_minor) + "\n"
+ "cookie: " + std::to_string(cookie) + "\n"
+ "cmd: " + (cmd == size_t(-1) ? "" : vec[cmd].string())));
return;
}
}
// remove timeout replyes
std::vector<std::map<uint64_t, r_info_t>::iterator> r_timeout;
for(auto it=reply_.begin(); it!=reply_.end(); it++)
if(it->second.t < time(nullptr))
r_timeout.push_back(it);
for(auto it : r_timeout)
reply_.erase(it);
}
catch(const std::exception& e)
{
MLOG_RED(el::Level::Error, e.what());
}
catch(...)
{
MLOG_RED(el::Level::Error, "unqnow");
}
start();
}
});
}
void client::stop()
{
if(zyre_sock_) {
zmq_close(zyre_sock_);
zyre_sock_ = nullptr;
}
}
uint64_t client::do_send(
const char *zyre_action_p, size_t zyre_action_sz,
const char *peer_or_group_p, size_t peer_or_group_sz,
const char *cmd_p, size_t cmd_sz,
const char *params_p, size_t params_sz,
uint64_t cookie)
{
if(ios_.stopped())
return cookie;
std::stringstream ss_v1;
msgpack::pack(ss_v1, uint64_t(VER_MAJOR));
std::string v1 = ss_v1.str();
std::stringstream ss_v2;
msgpack::pack(ss_v2, uint64_t(VER_MINOR));
std::string v2 = ss_v2.str();
if(cookie == COOKIE_NEXT) {
cookie_n_++; cookie = cookie_n_;
}
std::stringstream ss_cookie;
msgpack::pack(ss_cookie, cookie);
std::string cookie_s = ss_cookie.str();
std::array<boost::asio::const_buffer, 7> buf = {{
boost::asio::buffer(zyre_action_p, zyre_action_sz),
boost::asio::buffer(peer_or_group_p, peer_or_group_sz),
boost::asio::buffer(v1.data(), v1.size()),
boost::asio::buffer(v2.data(), v2.size()),
boost::asio::buffer(cookie_s.data(), cookie_s.size()),
boost::asio::buffer(cmd_p, cmd_sz),
boost::asio::buffer(params_p, params_sz)
}};
boost::system::error_code ec;
zyre_.send(buf, 0, ec);
if(ec)
throw std::runtime_error(ec.message());
return cookie;
}
void client::do_send(const std::string& zyre_action, const std::string& group, const std::string& cmd, const std::string& pars)
{
do_send(
zyre_action.data(), zyre_action.size(),
group.data(), group.size(),
cmd.data(), cmd.size(),
pars.data(), pars.size(), COOKIE_NEXT);
}
void client::do_send_r(const std::string& zyre_action, const std::string& group, const std::string& cmd, const func_t& r, const std::string& pars)
{
uint64_t cookie = do_send(
zyre_action.data(), zyre_action.size(),
group.data(), group.size(),
cmd.data(), cmd.size(),
pars.data(), pars.size(), COOKIE_NEXT);
reply_[cookie] = { time(nullptr) + reply_timeout_, r };
}
void client::do_send(const char *zyre_action, const char *group, char *cmd, const char *pars_p, size_t pars_sz)
{
do_send(
zyre_action, strlen(zyre_action),
group, strlen(group),
cmd, strlen(cmd),
pars_p, pars_sz, COOKIE_NEXT);
}
void client::do_send_r(const char *zyre_action, const char *group, char *cmd, const func_t& r, const char *pars_p, size_t pars_sz)
{
uint64_t cookie = do_send(
zyre_action, strlen(zyre_action),
group, strlen(group),
cmd, strlen(cmd),
pars_p, pars_sz, COOKIE_NEXT);
reply_[cookie] = { time(nullptr) + reply_timeout_, r };
}
void client::on(const std::string& cmd, const func_t& f)
{
meth_[cmd] = f;
}
void client::on_r(const std::string& cmd, const func_r_t& f)
{
meth_r_[cmd] = f;
}
}
| 29.666667 | 148 | 0.492711 | staroy |
e072d136e19f02ac31b851992288d07fa419b358 | 6,594 | cpp | C++ | lammps-master/src/USER-OMP/angle_class2_omp.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/src/USER-OMP/angle_class2_omp.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/src/USER-OMP/angle_class2_omp.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | /* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing author: Axel Kohlmeyer (Temple U)
------------------------------------------------------------------------- */
#include "angle_class2_omp.h"
#include "atom.h"
#include "comm.h"
#include "force.h"
#include "neighbor.h"
#include "domain.h"
#include "math_const.h"
#include <cmath>
#include "suffix.h"
using namespace LAMMPS_NS;
using namespace MathConst;
#define SMALL 0.001
/* ---------------------------------------------------------------------- */
AngleClass2OMP::AngleClass2OMP(class LAMMPS *lmp)
: AngleClass2(lmp), ThrOMP(lmp,THR_ANGLE)
{
suffix_flag |= Suffix::OMP;
}
/* ---------------------------------------------------------------------- */
void AngleClass2OMP::compute(int eflag, int vflag)
{
ev_init(eflag,vflag);
const int nall = atom->nlocal + atom->nghost;
const int nthreads = comm->nthreads;
const int inum = neighbor->nanglelist;
#if defined(_OPENMP)
#pragma omp parallel default(none) shared(eflag,vflag)
#endif
{
int ifrom, ito, tid;
loop_setup_thr(ifrom, ito, tid, inum, nthreads);
ThrData *thr = fix->get_thr(tid);
thr->timer(Timer::START);
ev_setup_thr(eflag, vflag, nall, eatom, vatom, thr);
if (inum > 0) {
if (evflag) {
if (eflag) {
if (force->newton_bond) eval<1,1,1>(ifrom, ito, thr);
else eval<1,1,0>(ifrom, ito, thr);
} else {
if (force->newton_bond) eval<1,0,1>(ifrom, ito, thr);
else eval<1,0,0>(ifrom, ito, thr);
}
} else {
if (force->newton_bond) eval<0,0,1>(ifrom, ito, thr);
else eval<0,0,0>(ifrom, ito, thr);
}
}
thr->timer(Timer::BOND);
reduce_thr(this, eflag, vflag, thr);
} // end of omp parallel region
}
template <int EVFLAG, int EFLAG, int NEWTON_BOND>
void AngleClass2OMP::eval(int nfrom, int nto, ThrData * const thr)
{
int i1,i2,i3,n,type;
double delx1,dely1,delz1,delx2,dely2,delz2;
double eangle,f1[3],f3[3];
double dtheta,dtheta2,dtheta3,dtheta4,de_angle;
double dr1,dr2,tk1,tk2,aa1,aa2,aa11,aa12,aa21,aa22;
double rsq1,rsq2,r1,r2,c,s,a,a11,a12,a22,b1,b2;
double vx11,vx12,vy11,vy12,vz11,vz12,vx21,vx22,vy21,vy22,vz21,vz22;
const dbl3_t * _noalias const x = (dbl3_t *) atom->x[0];
dbl3_t * _noalias const f = (dbl3_t *) thr->get_f()[0];
const int4_t * _noalias const anglelist = (int4_t *) neighbor->anglelist[0];
const int nlocal = atom->nlocal;
eangle = 0.0;
for (n = nfrom; n < nto; n++) {
i1 = anglelist[n].a;
i2 = anglelist[n].b;
i3 = anglelist[n].c;
type = anglelist[n].t;
// 1st bond
delx1 = x[i1].x - x[i2].x;
dely1 = x[i1].y - x[i2].y;
delz1 = x[i1].z - x[i2].z;
rsq1 = delx1*delx1 + dely1*dely1 + delz1*delz1;
r1 = sqrt(rsq1);
// 2nd bond
delx2 = x[i3].x - x[i2].x;
dely2 = x[i3].y - x[i2].y;
delz2 = x[i3].z - x[i2].z;
rsq2 = delx2*delx2 + dely2*dely2 + delz2*delz2;
r2 = sqrt(rsq2);
// angle (cos and sin)
c = delx1*delx2 + dely1*dely2 + delz1*delz2;
c /= r1*r2;
if (c > 1.0) c = 1.0;
if (c < -1.0) c = -1.0;
s = sqrt(1.0 - c*c);
if (s < SMALL) s = SMALL;
s = 1.0/s;
// force & energy for angle term
dtheta = acos(c) - theta0[type];
dtheta2 = dtheta*dtheta;
dtheta3 = dtheta2*dtheta;
dtheta4 = dtheta3*dtheta;
de_angle = 2.0*k2[type]*dtheta + 3.0*k3[type]*dtheta2 +
4.0*k4[type]*dtheta3;
a = -de_angle*s;
a11 = a*c / rsq1;
a12 = -a / (r1*r2);
a22 = a*c / rsq2;
f1[0] = a11*delx1 + a12*delx2;
f1[1] = a11*dely1 + a12*dely2;
f1[2] = a11*delz1 + a12*delz2;
f3[0] = a22*delx2 + a12*delx1;
f3[1] = a22*dely2 + a12*dely1;
f3[2] = a22*delz2 + a12*delz1;
if (EFLAG) eangle = k2[type]*dtheta2 + k3[type]*dtheta3 + k4[type]*dtheta4;
// force & energy for bond-bond term
dr1 = r1 - bb_r1[type];
dr2 = r2 - bb_r2[type];
tk1 = bb_k[type] * dr1;
tk2 = bb_k[type] * dr2;
f1[0] -= delx1*tk2/r1;
f1[1] -= dely1*tk2/r1;
f1[2] -= delz1*tk2/r1;
f3[0] -= delx2*tk1/r2;
f3[1] -= dely2*tk1/r2;
f3[2] -= delz2*tk1/r2;
if (EFLAG) eangle += bb_k[type]*dr1*dr2;
// force & energy for bond-angle term
aa1 = s * dr1 * ba_k1[type];
aa2 = s * dr2 * ba_k2[type];
aa11 = aa1 * c / rsq1;
aa12 = -aa1 / (r1 * r2);
aa21 = aa2 * c / rsq1;
aa22 = -aa2 / (r1 * r2);
vx11 = (aa11 * delx1) + (aa12 * delx2);
vx12 = (aa21 * delx1) + (aa22 * delx2);
vy11 = (aa11 * dely1) + (aa12 * dely2);
vy12 = (aa21 * dely1) + (aa22 * dely2);
vz11 = (aa11 * delz1) + (aa12 * delz2);
vz12 = (aa21 * delz1) + (aa22 * delz2);
aa11 = aa1 * c / rsq2;
aa21 = aa2 * c / rsq2;
vx21 = (aa11 * delx2) + (aa12 * delx1);
vx22 = (aa21 * delx2) + (aa22 * delx1);
vy21 = (aa11 * dely2) + (aa12 * dely1);
vy22 = (aa21 * dely2) + (aa22 * dely1);
vz21 = (aa11 * delz2) + (aa12 * delz1);
vz22 = (aa21 * delz2) + (aa22 * delz1);
b1 = ba_k1[type] * dtheta / r1;
b2 = ba_k2[type] * dtheta / r2;
f1[0] -= vx11 + b1*delx1 + vx12;
f1[1] -= vy11 + b1*dely1 + vy12;
f1[2] -= vz11 + b1*delz1 + vz12;
f3[0] -= vx21 + b2*delx2 + vx22;
f3[1] -= vy21 + b2*dely2 + vy22;
f3[2] -= vz21 + b2*delz2 + vz22;
if (EFLAG) eangle += ba_k1[type]*dr1*dtheta + ba_k2[type]*dr2*dtheta;
// apply force to each of 3 atoms
if (NEWTON_BOND || i1 < nlocal) {
f[i1].x += f1[0];
f[i1].y += f1[1];
f[i1].z += f1[2];
}
if (NEWTON_BOND || i2 < nlocal) {
f[i2].x -= f1[0] + f3[0];
f[i2].y -= f1[1] + f3[1];
f[i2].z -= f1[2] + f3[2];
}
if (NEWTON_BOND || i3 < nlocal) {
f[i3].x += f3[0];
f[i3].y += f3[1];
f[i3].z += f3[2];
}
if (EVFLAG) ev_tally_thr(this,i1,i2,i3,nlocal,NEWTON_BOND,eangle,f1,f3,
delx1,dely1,delz1,delx2,dely2,delz2,thr);
}
}
| 27.247934 | 79 | 0.53397 | rajkubp020 |
e0748d77b416cedd619686df8638e1e61c33663c | 26,624 | cpp | C++ | Source/FemPhysicsLinear.cpp | MihaiF/SolidFEM | 58e08130e2f31be3b056c387ed03aab3b0b3db38 | [
"BSD-3-Clause"
] | 3 | 2020-05-19T10:59:01.000Z | 2022-02-04T08:59:32.000Z | Source/FemPhysicsLinear.cpp | MihaiF/SolidFEM | 58e08130e2f31be3b056c387ed03aab3b0b3db38 | [
"BSD-3-Clause"
] | null | null | null | Source/FemPhysicsLinear.cpp | MihaiF/SolidFEM | 58e08130e2f31be3b056c387ed03aab3b0b3db38 | [
"BSD-3-Clause"
] | 1 | 2019-11-08T16:14:53.000Z | 2019-11-08T16:14:53.000Z | /*
BSD 3-Clause License
Copyright (c) 2019, Mihai Francu
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "FemPhysicsLinear.h"
#include "MeshFactory.h"
#include "TetrahedralMesh.h"
#include <Engine/Profiler.h>
#pragma warning( disable : 4244) // for double-float conversions
#pragma warning( disable : 4267) // for size_t-uint conversions
// References:
// [Weber] Weber, D. et al., Interactive deformable models with quadratic bases in Bernstein-Bezier form
// TODO: add Rayleigh damping
namespace FEM_SYSTEM
{
FemPhysicsLinear::FemPhysicsLinear(const std::vector<Tet>& tetrahedra,
const std::vector<Node>& nodes, const FemConfig& config)
: FemPhysicsBase(config)
, mOrder(config.mOrder)
, mUseLumpedMass(true)
{
ASSERT(tetrahedra.size() != 0);
ASSERT(nodes.size() != 0);
CreateMeshAndDofs(tetrahedra, nodes);
mElementVolumes.resize(GetNumElements());
mBarycentricJacobians.resize(GetNumElements());
for (uint32 e = 0; e < GetNumElements(); e++)
{
ComputeBarycentricJacobian(e, mBarycentricJacobians[e].y);
}
if (mSimType > ST_QUASI_STATIC)
AssembleMassMatrix();
mBodyForces.resize(GetNumFreeNodes());
ComputeBodyForces(mBodyForces);
}
void FemPhysicsLinear::CreateMeshAndDofs(const std::vector<Tet>& tetrahedra, const std::vector<Node>& nodes)
{
#ifdef LOG_TIMES
Printf(("----- FemPhysicsAnyOrderCorotationalElasticity for order " + std::to_string(order) + "\n").c_str());
#endif // LOG_TIMES
// 1. Build the higher order mesh/convert to a TetrahedralMesh instance
// use the linear mesh stored as an array of Tetrahedron in the base class
StridedVector<uint32> stridedVec(&(tetrahedra[0].idx[0]), (uint)tetrahedra.size(), sizeof(Tet));
double mesh_time;
TetrahedralMesh<uint32>* tetMesh = nullptr;
{
MEASURE_TIME_P("mesh_time", mesh_time);
tetMesh = MeshFactory::MakeMesh<TetrahedralMesh<uint32>>(mOrder, nodes.size(), stridedVec, tetrahedra.size());
mTetMesh.reset(tetMesh);
}
std::vector<Vector3R> points(nodes.size());
std::vector<Vector3R> points0(nodes.size());
double other_time = 0;
{
MEASURE_TIME_P("other_time", other_time);
// 2. Compute the interpolated positions
// copy over the node positions of the linear mesh to a linear array
// TODO: could use a strided vector instead
for (uint32 i = 0; i < nodes.size(); i++)
{
points[i] = nodes[i].pos;
points0[i] = nodes[i].pos0;
}
}
std::vector<Vector3R> interpolatedPositions(GetNumNodes());
std::vector<Vector3R> interpolatedPositions0(GetNumNodes());
double interpolate_time;
{
MEASURE_TIME_P("interpolate_time", interpolate_time);
// interpolate the mesh node positions (for the given order)
// the first resulting nodes are the same as in the linear mesh
MeshFactory::Interpolate<TetrahedralMesh<uint32>, Vector3R>(*tetMesh, &points[0], &interpolatedPositions[0]);
MeshFactory::Interpolate<TetrahedralMesh<uint32>, Vector3R>(*tetMesh, &points0[0], &interpolatedPositions0[0]);
}
std::vector<bool> fixed(GetNumNodes(), false);
double other_time2 = 0;
{
MEASURE_TIME_P("other_time2", other_time2);
// 3. Mark all boundary nodes
// initialize the fixed flags array
for (uint32 i = 0; i < nodes.size(); i++)
{
fixed[i] = nodes[i].invMass == 0;
}
}
other_time += other_time2;
double boundary_time = 0;
{
MEASURE_TIME_P("boundary_time", boundary_time);
// 3.5 Check the higher order nodes and ensure that the expected leftmost cantilever nodes are marked fixed
if (mOrder > 1)
{
for (uint32 e = 0; e < GetNumElements(); e++)
{
// TODO These are hacky solutions, need supported iterators from the mesh class..
// First check all edge nodes
std::tuple<int, int> edge_pairs[]{
std::make_tuple(0, 1),
std::make_tuple(0, 2),
std::make_tuple(0, 3),
std::make_tuple(1, 2),
std::make_tuple(1, 3),
std::make_tuple(2, 3)
};
int no_nodes_pr_edge = mTetMesh->GetNodesPerEdge(mOrder);
int edge_startidx = 4;
for (int i = 0; i < 6; i++)
{
int c1, c2; std::tie(c1, c2) = edge_pairs[i];
uint32 gidx_c1 = mTetMesh->GetGlobalIndex(e, c1);
uint32 gidx_c2 = mTetMesh->GetGlobalIndex(e, c2);
//if (nodes[gidx_c1].invMass == 0 && nodes[gidx_c2].invMass == 0)
if (fixed[gidx_c1] && fixed[gidx_c2])
{
for (int j = 0; j < no_nodes_pr_edge; j++)
{
int edge_lidx = edge_startidx + i * no_nodes_pr_edge + j;
uint32 gidx_edgej = mTetMesh->GetGlobalIndex(e, edge_lidx);
fixed[gidx_edgej] = true;
}
}
}
// Then check all face nodes, if any
std::tuple<int, int, int> face_pairs[]{
std::make_tuple(0, 1, 2), std::make_tuple(0, 1, 3),
std::make_tuple(0, 2, 3), std::make_tuple(1, 2, 3)
};
int no_nodes_pr_face = mTetMesh->GetNodesPerFace(mOrder);
int face_startidx = 4 + no_nodes_pr_edge * 6;
for (int i = 0; i < 4; i++)
{
int c1, c2, c3; std::tie(c1, c2, c3) = face_pairs[i];
uint32 gidx_c1 = mTetMesh->GetGlobalIndex(e, c1);
uint32 gidx_c2 = mTetMesh->GetGlobalIndex(e, c2);
uint32 gidx_c3 = mTetMesh->GetGlobalIndex(e, c3);
if (fixed[gidx_c1] && fixed[gidx_c2] && fixed[gidx_c3])
{
for (int j = 0; j < no_nodes_pr_face; j++)
{
int face_lidx = face_startidx + i * no_nodes_pr_face + j;
uint32 gidx_facej = mTetMesh->GetGlobalIndex(e, face_lidx);
fixed[gidx_facej] = true;
}
}
}
}
}
}
// 4. Create a index-mapping from mesh-global-index to index into the mReferencePosition and mDeformedPositions vectors
// - this is too allow all of the fixed nodes to be listed first in the two vectors.
double other_time3 = 0;
{
MEASURE_TIME_P("other_time3", other_time3);
#ifdef USE_CONSTRAINT_BCS
// create the reference positions - first ones are the fixed ones
mReferencePositions.resize(GetNumNodes());
mReshuffleMap.resize(GetNumNodes());
mReshuffleMapInv.resize(GetNumNodes());
for (uint32 i = 0; i < GetNumNodes(); i++)
{
mReferencePositions[i] = interpolatedPositions0[i];
mReshuffleMap[i] = i;
mReshuffleMapInv[i] = i;
}
// create a mapping with the fixed nodes first
for (uint32 i = 0; i < fixed.size(); i++)
{
if (fixed[i])
{
AddDirichletBC(i, AXIS_X | AXIS_Y | AXIS_Z);
}
}
mNumBCs = 0;
#else
// create a mapping with the fixed nodes first
mReshuffleMapInv.clear();
for (uint32 i = 0; i < fixed.size(); i++)
{
if (fixed[i])
mReshuffleMapInv.push_back(i);
}
mNumBCs = mReshuffleMapInv.size();
for (uint32 i = 0; i < fixed.size(); i++)
{
if (!fixed[i])
mReshuffleMapInv.push_back(i);
}
// create the reference positions - first ones are the fixed ones
mReferencePositions.resize(GetNumNodes());
mReshuffleMap.resize(GetNumNodes());
for (uint32 i = 0; i < GetNumNodes(); i++)
{
uint32 idx = mReshuffleMapInv[i];
mReferencePositions[i] = interpolatedPositions0[idx];
mReshuffleMap[idx] = i;
}
#endif
// 5. Copy the mReferencePositions into mDeformedPositions, to initialize it
// - note that mDeformedPositions does not contain the boundary/fixed nodes.
// create a vector of deformed positions (dofs)
// the first mNumBCs nodes are fixed so we only consider the remaining ones
mDeformedPositions.resize(GetNumFreeNodes());
for (uint32 i = 0; i < GetNumFreeNodes(); i++)
{
uint32 idx = mReshuffleMapInv[i + mNumBCs];
mDeformedPositions[i] = interpolatedPositions[idx];
}
// 6. Initialize the velocities vector, note that it does not consider the fixed nodes either
// velocities should be zero by construction
mVelocities.resize(GetNumFreeNodes());
for (uint32 i = mNumBCs; i < nodes.size(); i++)
{
int idx = mReshuffleMapInv[i];
mVelocities[i - mNumBCs] = nodes[idx].vel;
}
// initialize initial displacements vector (mostly for non-zero displacements)
mInitialDisplacements.resize(mNumBCs);
for (uint32 i = 0; i < mNumBCs; i++)
{
int idx = mReshuffleMapInv[i];
mInitialDisplacements[i] = interpolatedPositions[idx] - interpolatedPositions0[idx];
}
}
other_time += other_time3;
}
void FemPhysicsLinear::UpdatePositions(std::vector<Node>& nodes)
{
// re-interpolate the current positions on the potentially high-order mesh
std::vector<Vector3R> points(nodes.size());
//double other_time;
{
//MEASURE_TIME_P("other_time", other_time);
// 2. Compute the interpolated positions
// copy over the node positions of the linear mesh to a linear array
// TODO: could use a strided vector instead
for (uint32 i = 0; i < nodes.size(); i++)
{
points[i] = nodes[i].pos;
}
}
std::vector<Vector3R> interpolatedPositions(GetNumNodes());
//double interpolate_time;
{
//MEASURE_TIME_P("interpolate_time", interpolate_time);
// interpolate the mesh node positions (for the given order)
// the first resulting nodes are the same as in the linear mesh
//MeshFactory::Interpolate(*mTetMesh, &points[0], &interpolatedPositions[0]);
interpolatedPositions = points;
}
for (uint32 i = 0; i < GetNumNodes(); i++)
{
int idx = mReshuffleMapInv[i];
if (i < mNumBCs)
mInitialDisplacements[i] = interpolatedPositions[idx] - mReferencePositions[i];
}
}
void FemPhysicsLinear::ComputeBarycentricJacobian(uint32 i, Vector3R y[4])
{
uint32 i0 = mTetMesh->GetGlobalIndex(i, 0);
uint32 i1 = mTetMesh->GetGlobalIndex(i, 1);
uint32 i2 = mTetMesh->GetGlobalIndex(i, 2);
uint32 i3 = mTetMesh->GetGlobalIndex(i, 3);
const Vector3R& x0 = mReferencePositions[mReshuffleMap[i0]];
const Vector3R& x1 = mReferencePositions[mReshuffleMap[i1]];
const Vector3R& x2 = mReferencePositions[mReshuffleMap[i2]];
const Vector3R& x3 = mReferencePositions[mReshuffleMap[i3]];
Vector3R d1 = x1 - x0;
Vector3R d2 = x2 - x0;
Vector3R d3 = x3 - x0;
Matrix3R mat(d1, d2, d3); // this is the reference shape matrix Dm [Sifakis][Teran]
Matrix3R X = mat.GetInverse(); // Dm^-1
real vol = (mat.Determinant()) / 6.f; // volume of the tet
mElementVolumes[i] = vol;
// compute the gradient of the shape functions [Erleben][Mueller]
y[1] = X[0];
y[2] = X[1];
y[3] = X[2];
y[0] = y[1] + y[2] + y[3];
y[0].Flip();
}
real FemPhysicsLinear::GetTotalVolume() const
{
real totalVol = 0;
for (uint32 e = 0; e < GetNumElements(); e++)
{
uint32 i0 = mTetMesh->GetGlobalIndex(e, 0);
uint32 i1 = mTetMesh->GetGlobalIndex(e, 1);
uint32 i2 = mTetMesh->GetGlobalIndex(e, 2);
uint32 i3 = mTetMesh->GetGlobalIndex(e, 3);
const Vector3R& x0 = GetDeformedPosition(i0);
const Vector3R& x1 = GetDeformedPosition(i1);
const Vector3R& x2 = GetDeformedPosition(i2);
const Vector3R& x3 = GetDeformedPosition(i3);
Vector3R d1 = x1 - x0;
Vector3R d2 = x2 - x0;
Vector3R d3 = x3 - x0;
Matrix3R mat(d1, d2, d3); // this is the spatial shape matrix Ds [Sifakis][Teran]
real vol = abs(mat.Determinant()) / 6.f; // volume of the tet
totalVol += vol;
}
return totalVol;
}
void FemPhysicsLinear::ComputeStrainJacobian(uint32 i, Matrix3R Bn[4], Matrix3R Bs[4])
{
Vector3R* y = mBarycentricJacobians[i].y;
// compute the Cauchy strain Jacobian matrix according to [Mueller]: B = de/dx
for (int j = 0; j < 4; j++)
{
Bn[j] = Matrix3R(y[j]); // diagonal matrix
Bs[j] = Symm(y[j]);
}
}
// compute local mass matrix (using linear shape functions)
void ComputeLocalMassMatrix(real density, uint32 numLocalNodes, EigenMatrix& Mlocal)
{
// this is actually wrong for (i,i) terms - see ComputeLocalMassMatrixBB1
ASSERT(numLocalNodes == 4);
real massDiv = density / 20.f;
for (size_t i = 0; i < numLocalNodes; i++)
{
size_t offsetI = i * 3;
for (size_t j = 0; j < numLocalNodes; j++)
{
size_t offsetJ = j * 3;
// build a diagonal matrix
for (size_t k = 0; k < 3; k++)
Mlocal(offsetI + k, offsetJ + k) = (i == j) ? 2 * massDiv : massDiv;
}
}
//std::cout << "Mlocal" << std::endl << Mlocal << std::endl;
}
void ComputeLocalMassMatrixLumped(real density, uint32 numLocalNodes, EigenMatrix& Mlocal)
{
// this is actually wrong for (i,i) terms - see ComputeLocalMassMatrixBB1
ASSERT(numLocalNodes == 4);
// 4x4 identity blocks times the total mass / 20
real massDiv = density / 4.0;
for (size_t i = 0; i < numLocalNodes * 3; i++)
{
Mlocal(i, i) = massDiv;
}
}
// // compute local mass matrix using any order Bernstein-Bezier shape functions
void FemPhysicsLinear::ComputeLocalMassMatrixBB(real density, uint32 numLocalNodes, EigenMatrix& Mlocal)
{
int *i_ijkl, *j_mnop;
size_t i, j, k;
real factor = density * (1.f / Binom(2 * mOrder + 3, 3));
for (i = 0; i < numLocalNodes; i++)
{
i_ijkl = mTetMesh->GetIJKL(i);
for (j = 0; j < numLocalNodes; j++)
{
j_mnop = mTetMesh->GetIJKL(j);
real mass = factor * G(i_ijkl, j_mnop, mOrder);
for (k = 0; k < 3; k++)
{
Mlocal(i * 3 + k, j * 3 + k) = mass;
}
}
}
}
// compute local mass matrix using quadratic Bernstein-Bezier shape functions
void FemPhysicsLinear::ComputeLocalMassMatrixBB2(real density, uint32 numLocalNodes, EigenMatrix& Mlocal)
{
ASSERT(numLocalNodes == 10);
for (size_t i = 0; i < numLocalNodes; i++)
{
size_t offsetI = i * 3;
auto multiIndexI = mTetMesh->GetIJKL(i);
for (size_t j = 0; j < numLocalNodes; j++)
{
//if (i != j) continue;
auto multiIndexJ = mTetMesh->GetIJKL(j);
uint32 c1 = Combinations(multiIndexI[0] + multiIndexJ[0], multiIndexI[0]);
uint32 c2 = Combinations(multiIndexI[1] + multiIndexJ[1], multiIndexI[1]);
uint32 c3 = Combinations(multiIndexI[2] + multiIndexJ[2], multiIndexI[2]);
uint32 c4 = Combinations(multiIndexI[3] + multiIndexJ[3], multiIndexI[3]);
real massDiv = c1 * c2 * c3 * c4 * density / 210.f;
//real massDiv = density * ComputeMultiIndexSumFactor(2, multiIndexI, multiIndexJ) / 10.f;
// build a diagonal matrix
size_t offsetJ = j * 3;
for (size_t k = 0; k < 3; k++)
Mlocal(offsetI + k, offsetJ + k) = massDiv;
}
}
}
// assemble the global mass matrix
void FemPhysicsLinear::AssembleMassMatrix()
{
// compute the local mass matrix first
size_t numLocalNodes = GetNumLocalNodes();
size_t numLocalDofs = NUM_POS_COMPONENTS * numLocalNodes;
// !NOTE assumed to be constant/equal for all tetrahedrons (except for the volume) -> true for linear rest shapes and subparametric formulation
EigenMatrix Mlocal(numLocalDofs, numLocalDofs);
Mlocal.setZero();
if (mOrder == 1 && mUseLumpedMass)
ComputeLocalMassMatrixLumped(mDensity, numLocalNodes, Mlocal);
else
ComputeLocalMassMatrixBB(mDensity, numLocalNodes, Mlocal);
size_t numNodes = GetNumFreeNodes();
size_t numDofs = numNodes * 3;
EigenMatrix M(numDofs, numDofs);
M.setZero();
for (size_t i = 0; i < GetNumElements(); i++)
{
real vol = mElementVolumes[i];
// for every local node there corresponds a 3x3 block matrix
// we go through all of these blocks so that we know what the current pair is
for (size_t j = 0; j < numLocalNodes; j++)
{
for (size_t k = 0; k < numLocalNodes; k++)
{
size_t jGlobal = mReshuffleMap[mTetMesh->GetGlobalIndex(i, j)];
size_t kGlobal = mReshuffleMap[mTetMesh->GetGlobalIndex(i, k)];
// do not add to the global matrix if at least one of the nodes is fixed
if (jGlobal < mNumBCs || kGlobal < mNumBCs)
continue;
// add the local 3x3 matrix to the global matrix
int jOffset = (jGlobal - mNumBCs) * NUM_POS_COMPONENTS;
int kOffset = (kGlobal - mNumBCs) * NUM_POS_COMPONENTS;
for (size_t x = 0; x < NUM_POS_COMPONENTS; x++)
{
for (size_t y = 0; y < NUM_POS_COMPONENTS; y++)
{
M.coeffRef(jOffset + x, kOffset + y) += vol * Mlocal(j * NUM_POS_COMPONENTS + x, k * NUM_POS_COMPONENTS + y);
}
}
}
}
}
mMassMatrix = M.sparseView();
}
// compute the contribution of gravity (as a force distribution) to the current forces (using BB shape functions)
void FemPhysicsLinear::ComputeBodyForces(Vector3Array& f)
{
Vector3R flocal = mDensity * mGravity * (1.f / Binom(mOrder + 3, 3));
for (size_t e = 0; e < GetNumElements(); e++)
{
// We note that the body force is constant across the element.
real vol = mElementVolumes[e];
Vector3R bforce = vol * flocal;
for (size_t i = 0; i < GetNumLocalNodes(); i++)
{
size_t globalI = mReshuffleMap[mTetMesh->GetGlobalIndex(e, i)];
if (globalI < mNumBCs)
continue;
int offset = (globalI - mNumBCs);
f[offset] += bforce;
}
}
}
void FemPhysicsLinear::ComputeDeformationGradient(uint32 e, Matrix3R& F) const
{
// compute deformed/spatial shape matrix Ds [Sifakis]
uint32 i0 = mTetMesh->GetGlobalIndex(e, 0);
uint32 i1 = mTetMesh->GetGlobalIndex(e, 1);
uint32 i2 = mTetMesh->GetGlobalIndex(e, 2);
uint32 i3 = mTetMesh->GetGlobalIndex(e, 3);
// TODO: avoid calling virtual function
const Vector3R& x0 = GetDeformedPosition(i0);
const Vector3R& x1 = GetDeformedPosition(i1);
const Vector3R& x2 = GetDeformedPosition(i2);
const Vector3R& x3 = GetDeformedPosition(i3);
Vector3R d1 = x1 - x0;
Vector3R d2 = x2 - x0;
Vector3R d3 = x3 - x0;
Matrix3R Ds(d1, d2, d3);
Matrix3R X(mBarycentricJacobians[e].y[1], mBarycentricJacobians[e].y[2], mBarycentricJacobians[e].y[3]);
// compute deformation gradient
F = Ds * !X;
}
// computes the local stiffness matrix using Bernstein-Bezier polynomials given the Lame parameters
void FemPhysicsLinear::ComputeLocalStiffnessMatrixBB(uint32 elementidx, real mu, real lambda, EigenMatrix& Klocal)
{
uint32 numLocalNodes = GetNumLocalNodes();
uint32 NUM_POS_COMPONENTS = 3;
Klocal = EigenMatrix(numLocalNodes * NUM_POS_COMPONENTS, numLocalNodes * NUM_POS_COMPONENTS);
Vector3R* barycentric_over_x = mBarycentricJacobians[elementidx].y;
real common_factor = (3.f * mOrder * mElementVolumes[elementidx]) / (4.f * mOrder * mOrder - 1.f);
for (uint32 i = 0; i < GetNumLocalNodes(); i++)
{
int *i_ijkl = mTetMesh->GetIJKL(i);
int ijkl_c[4]{ 0 }; memcpy(ijkl_c, i_ijkl, 4 * sizeof(int));
for (uint32 j = 0; j < GetNumLocalNodes(); j++)
{
int *j_mnop = mTetMesh->GetIJKL(j);
int mnop_d[4]{ 0 }; memcpy(mnop_d, j_mnop, 4 * sizeof(int));
for (uint32 a = 0; a < NUM_POS_COMPONENTS; a++)
{
for (uint32 b = 0; b < NUM_POS_COMPONENTS; b++)
{
real sum1 = 0;
for (int c = 0; c < 4; c++)
{
ijkl_c[c] -= 1;
for (int d = 0; d < 4; d++)
{
mnop_d[d] -= 1;
sum1 += barycentric_over_x[c][a] * barycentric_over_x[d][b] * ComputeMultiIndexSumFactor(mOrder - 1, ijkl_c, mnop_d);
mnop_d[d] += 1;
}
ijkl_c[c] += 1;
}
real sum2 = 0;
for (int c = 0; c < 4; c++)
{
ijkl_c[c] -= 1;
for (int d = 0; d < 4; d++)
{
mnop_d[d] -= 1;
sum2 += barycentric_over_x[c][b] * barycentric_over_x[d][a] * ComputeMultiIndexSumFactor(mOrder - 1, ijkl_c, mnop_d);
mnop_d[d] += 1;
}
ijkl_c[c] += 1;
}
real sum3 = 0;
if (a == b)
{
for (int c = 0; c < 4; c++)
{
ijkl_c[c] -= 1;
for (int d = 0; d < 4; d++)
{
mnop_d[d] -= 1;
real Gv = ComputeMultiIndexSumFactor(mOrder - 1, ijkl_c, mnop_d);
for (int k = 0; k < 3; k++)
{
sum3 += barycentric_over_x[c][k] * barycentric_over_x[d][k] * Gv;
}
mnop_d[d] += 1;
}
ijkl_c[c] += 1;
}
}
real V_ij_ab = lambda * common_factor * sum1;
real U_ij_ab = mu * common_factor * sum2;
real W_ij_ab = mu * common_factor * sum3;
real K_ij_ab = V_ij_ab + U_ij_ab + W_ij_ab;
Klocal(i * NUM_POS_COMPONENTS + a, j * NUM_POS_COMPONENTS + b) = K_ij_ab;
}
}
}
}
}
void FemPhysicsLinear::SetBoundaryConditionsSurface(const std::vector<uint32>& triangleList, real pressure)
{
mAppliedPressure = pressure;
mTractionSurface.clear();
for (uint32 i = 0; i < triangleList.size(); i += 3)
{
int idx1 = mReshuffleMap[triangleList[i]] - mNumBCs;
int idx2 = mReshuffleMap[triangleList[i + 1]] - mNumBCs;
int idx3 = mReshuffleMap[triangleList[i + 2]] - mNumBCs;
if (idx1 >= 0 && idx2 >= 0 && idx3 >= 0)
{
mTractionSurface.push_back(idx1);
mTractionSurface.push_back(idx2);
mTractionSurface.push_back(idx3);
}
}
}
void FemPhysicsLinear::AssembleTractionStiffnessMatrixFD()
{
uint32 numNodes = GetNumFreeNodes();
uint32 numDofs = numNodes * 3;
mTractionStiffnessMatrix.resize(numDofs, numDofs);
mTractionStiffnessMatrix.setZero();
// current pressure forces
ComputeTractionForces();
EigenVector fp0 = GetEigenVector(mTractionForces);
real eps = 1e-6;
for (uint32 j = 0; j < numDofs; j++)
{
mDeformedPositions[j / 3][j % 3] += eps;
ComputeTractionForces();
EigenVector fp = GetEigenVector(mTractionForces);
auto dfp = (1.0 / eps) * (fp - fp0);
for (uint32 i = 0; i < numDofs; i++)
{
mTractionStiffnessMatrix(i, j) = dfp(i);
}
mDeformedPositions[j / 3][j % 3] -= eps;
}
}
void FemPhysicsLinear::ComputeTractionForces()
{
if (mTractionSurface.empty())
return;
if (mUseImplicitPressureForces)
{
uint32 numDofs = GetNumFreeNodes() * NUM_POS_COMPONENTS;
mTractionStiffnessMatrix.resize(numDofs, numDofs);
mTractionStiffnessMatrix.setZero();
}
// accumulate forces
mTractionForces.resize(GetNumFreeNodes());
for (uint32 i = 0; i < mTractionForces.size(); i++)
mTractionForces[i].SetZero();
auto computeForce = [&](const Vector3R& p1, const Vector3R& p2, const Vector3R& p3)->Vector3R
{
Vector3R a = p2 - p1;
Vector3R b = p3 - p1;
Vector3R normal = cross(a, b);
real area = 0.5f * normal.Length();
normal.Normalize();
Vector3R traction = mAppliedPressure * normal;
Vector3R force = (area / 3.0f) * traction;
return force;
};
// go through all inner boundary triangles
for (uint32 t = 0; t < mTractionSurface.size() / 3; t++)
{
int base = t * 3;
// global (shuffled) indices of nodes
uint32 i1 = mTractionSurface[base];
uint32 i2 = mTractionSurface[base + 1];
uint32 i3 = mTractionSurface[base + 2];
// compute triangle area and normal
const Vector3R& p1 = mDeformedPositions[i1];
const Vector3R& p2 = mDeformedPositions[i2];
const Vector3R& p3 = mDeformedPositions[i3];
// apply traction to triangle nodes
Vector3R force = computeForce(p1, p2, p3);
mTractionForces[i1] += force;
mTractionForces[i2] += force;
mTractionForces[i3] += force;
if (mUseImplicitPressureForces)
{
// compute local stiffness matrix
Matrix3R K[3];
Vector3R a = p2 - p1;
Vector3R b = p3 - p1;
a.Scale(mAppliedPressure / 6.0f);
b.Scale(mAppliedPressure / 6.0f);
K[2] = Matrix3R::Skew(a);
K[1] = Matrix3R::Skew(-b);
K[0] = -K[1] - K[2];
// finite difference approximation - for verification purposes
//real dx = 1e-4f;
//real invDx = 1.f / dx;
//Vector3R dfdx = invDx * (computeForce(p1, p2, p3 + Vector3R(dx, 0, 0)) - force);
//Vector3R dfdy = invDx * (computeForce(p1, p2, p3 + Vector3R(0, dx, 0)) - force);
//Vector3R dfdz = invDx * (computeForce(p1, p2, p3 + Vector3R(0, 0, dx)) - force);
//Matrix3 K2(dfdx, dfdy, dfdz);
//dfdx = invDx * (computeForce(p1, p2 + Vector3R(dx, 0, 0), p3) - force);
//dfdy = invDx * (computeForce(p1, p2 + Vector3R(0, dx, 0), p3) - force);
//dfdz = invDx * (computeForce(p1, p2 + Vector3R(0, 0, dx), p3) - force);
//Matrix3 K1(dfdx, dfdy, dfdz);
//dfdx = invDx * (computeForce(p1 + Vector3R(dx, 0, 0), p2, p3) - force);
//dfdy = invDx * (computeForce(p1 + Vector3R(0, dx, 0), p2, p3) - force);
//dfdz = invDx * (computeForce(p1 + Vector3R(0, 0, dx), p2, p3) - force);
//Matrix3 K0(dfdx, dfdy, dfdz);
// assemble global stiffness matrix
for (uint32 x = 0; x < 3; x++)
{
for (uint32 y = 0; y < 3; y++)
{
mTractionStiffnessMatrix(i1 * 3 + x, i1 * 3 + y) += K[0](x, y);
mTractionStiffnessMatrix(i1 * 3 + x, i2 * 3 + y) += K[1](x, y);
mTractionStiffnessMatrix(i1 * 3 + x, i3 * 3 + y) += K[2](x, y);
mTractionStiffnessMatrix(i2 * 3 + x, i1 * 3 + y) += K[0](x, y);
mTractionStiffnessMatrix(i2 * 3 + x, i2 * 3 + y) += K[1](x, y);
mTractionStiffnessMatrix(i2 * 3 + x, i3 * 3 + y) += K[2](x, y);
mTractionStiffnessMatrix(i3 * 3 + x, i1 * 3 + y) += K[0](x, y);
mTractionStiffnessMatrix(i3 * 3 + x, i2 * 3 + y) += K[1](x, y);
mTractionStiffnessMatrix(i3 * 3 + x, i3 * 3 + y) += K[2](x, y);
}
}
}
}
}
EigenVector FemPhysicsLinear::ComputeLoadingForces()
{
// add the gravity forces
EigenVector f = GetEigenVector(mBodyForces);
// add boundary traction forces
ComputeTractionForces();
if (mTractionForces.size() > 0)
{
f += GetEigenVector(mTractionForces);
}
f *= mForceFraction; // slow application of forces
return f;
}
} // namespace FEM_SYSTEM
| 33.829733 | 145 | 0.654485 | MihaiF |
2fd93bac461a6dfdcac6bdd0aacdba4d908f5c8b | 91 | cpp | C++ | 80186PC/UI/Keyboard.cpp | moon-touched/80186PC | 60b461b584f6454b36a863f473d812658ee1e54d | [
"MIT"
] | null | null | null | 80186PC/UI/Keyboard.cpp | moon-touched/80186PC | 60b461b584f6454b36a863f473d812658ee1e54d | [
"MIT"
] | null | null | null | 80186PC/UI/Keyboard.cpp | moon-touched/80186PC | 60b461b584f6454b36a863f473d812658ee1e54d | [
"MIT"
] | null | null | null | #include <UI/Keyboard.h>
Keyboard::Keyboard() = default;
Keyboard::~Keyboard() = default;
| 18.2 | 32 | 0.703297 | moon-touched |
2fdc5c5102a0a36fbca5887981673ee8aaf857dd | 963 | cpp | C++ | test/sequenceobjects.cpp | tschijnmo/cpypp | ee9c6e7c4bcd4579c7b5a58a4c7626630f8c8ffd | [
"MIT"
] | null | null | null | test/sequenceobjects.cpp | tschijnmo/cpypp | ee9c6e7c4bcd4579c7b5a58a4c7626630f8c8ffd | [
"MIT"
] | null | null | null | test/sequenceobjects.cpp | tschijnmo/cpypp | ee9c6e7c4bcd4579c7b5a58a4c7626630f8c8ffd | [
"MIT"
] | null | null | null | /** Tests for the utility for sequence objects.
*/
#include <catch.hpp>
#include <Python.h>
#include <cpypp.hpp>
using namespace cpypp;
TEST_CASE("Tuples can be constructed", "[Handle][Tuple]")
{
Tuple tup(2);
tup.setitem(0, Handle(1l));
tup.setitem(1, Handle(2l));
CHECK(tup.check_tuple());
Handle ref("ii", 1, 2);
CHECK(ref.check_tuple());
CHECK(tup == ref);
}
//
// Test of building of struct sequences
//
// Here the utility about static type objects are also tested.
//
static PyStructSequence_Field fields[] = { { "field", "doc" }, { NULL, NULL } };
static PyStructSequence_Desc desc = { "StructSequence", "type doc", fields, 1 };
static Static_type tp{};
TEST_CASE("Struct sequence can be constructed",
"[Handle][Struct_sequence][Static_type]")
{
tp.make_ready(desc);
CHECK(tp.is_ready());
Struct_sequence obj(tp);
obj.setitem(0, Handle(1l));
CHECK(obj.getattr("field").as<long>() == 1);
}
| 20.489362 | 80 | 0.650052 | tschijnmo |
2fdd9b4502588839b2fc890eccd9542edf134894 | 625 | cpp | C++ | hash/hash_test.cpp | hjinlin/toft | ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441 | [
"BSD-3-Clause"
] | 264 | 2015-01-03T11:50:17.000Z | 2022-03-17T02:38:34.000Z | hash/hash_test.cpp | hjinlin/toft | ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441 | [
"BSD-3-Clause"
] | 12 | 2015-04-27T15:17:34.000Z | 2021-05-01T04:31:18.000Z | hash/hash_test.cpp | hjinlin/toft | ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441 | [
"BSD-3-Clause"
] | 128 | 2015-02-07T18:13:10.000Z | 2022-02-21T14:24:14.000Z | // Copyright (c) 2013, The Toft Authors. All rights reserved.
// Author: Ye Shunping <yeshunping@gmail.com>
#include <string>
#include "toft/hash/hash.h"
#include "thirdparty/gtest/gtest.h"
namespace toft {
TEST(HashUnittest, Fingerprint) {
const std::string& url = "http://app.kid.qq.com/exam/5528/5528_103392.htm";
uint64_t hash_value = Fingerprint64(url);
EXPECT_EQ(hash_value, 17105673616436300159UL);
std::string str = Fingerprint64ToString(hash_value);
EXPECT_EQ(str, "7F09753F868F63ED");
uint64_t hash2 = StringToFingerprint64(str);
EXPECT_EQ(hash_value, hash2);
}
} // namespace toft
| 29.761905 | 79 | 0.7264 | hjinlin |
2fddce6a0d5df9e95639c4bfb13c1be6925b3aa3 | 2,011 | hpp | C++ | labs/parallel_merge/helper.hpp | amirsojoodi/gpu-algorithms-labs | 27993d0f40822d7195ada79645ca1ed7dd875803 | [
"NCSA"
] | 23 | 2019-01-15T23:13:22.000Z | 2022-03-18T05:25:11.000Z | labs/parallel_merge/helper.hpp | amirsojoodi/gpu-algorithms-labs | 27993d0f40822d7195ada79645ca1ed7dd875803 | [
"NCSA"
] | 9 | 2019-01-15T22:25:02.000Z | 2021-07-15T16:59:49.000Z | labs/parallel_merge/helper.hpp | amirsojoodi/gpu-algorithms-labs | 27993d0f40822d7195ada79645ca1ed7dd875803 | [
"NCSA"
] | 19 | 2019-01-22T17:09:00.000Z | 2022-03-10T11:57:05.000Z | #pragma once
#define CATCH_CONFIG_CPP11_TO_STRING
#define CATCH_CONFIG_COLOUR_ANSI
#define CATCH_CONFIG_MAIN
#include "common/catch.hpp"
#include "common/fmt.hpp"
#include "common/utils.hpp"
#include "assert.h"
#include "stdint.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include <algorithm>
#include <random>
#include <string>
#include <chrono>
#include <cuda.h>
static bool verify(const std::vector<float> &ref_sol, const std::vector<float> &sol) {
for (size_t i = 0; i < ref_sol.size(); i++) {
INFO("Merge results differ from reference solution.");
REQUIRE(ref_sol[i] == sol[i]);
}
return true;
}
static std::chrono::time_point<std::chrono::high_resolution_clock> now() {
return std::chrono::high_resolution_clock::now();
}
#define CUDA_RUNTIME(stmt) checkCuda(stmt, __FILE__, __LINE__);
void checkCuda(cudaError_t result, const char *file, const int line) {
if (result != cudaSuccess) {
LOG(critical,
std::string(fmt::format("{}@{}: CUDA Runtime Error: {}\n", file, line,
cudaGetErrorString(result))));
exit(-1);
}
}
void generate_input(std::vector<float> &A_h, const std::pair<float, float> &A_range, std::vector<float> &B_h, const std::pair<float, float> &B_range) {
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_real_distribution<float> dis_A(A_range.first, A_range.second);
std::uniform_real_distribution<float> dis_B(B_range.first, B_range.second);
std::generate(A_h.begin(), A_h.end(), std::bind(dis_A, std::ref(gen)));
std::generate(B_h.begin(), B_h.end(), std::bind(dis_B, std::ref(gen)));
std::sort(A_h.begin(), A_h.end());
std::sort(B_h.begin(), B_h.end());
}
static void print_vector(const std::vector<float> vec) {
for (const auto &elem : vec) {
std::cout << elem << ' ';
}
std::cout << "" << '\n';
}
| 30.469697 | 151 | 0.663352 | amirsojoodi |
2fdf0ec1e8a7781618bdc3ca01cfa62307675cde | 410 | cpp | C++ | tests/doc/vector3d/vector3d-3.cpp | jmintser/chemfiles | fb1ed5ee47790cc004468e5484954e2b3d1adff2 | [
"BSD-3-Clause"
] | 116 | 2015-11-05T01:18:13.000Z | 2022-02-20T06:33:47.000Z | tests/doc/vector3d/vector3d-3.cpp | jmintser/chemfiles | fb1ed5ee47790cc004468e5484954e2b3d1adff2 | [
"BSD-3-Clause"
] | 307 | 2015-10-08T09:22:46.000Z | 2022-03-28T13:42:51.000Z | tests/doc/vector3d/vector3d-3.cpp | Luthaf/Chemharp | d41036ff5645954bd691f868f066c760560eee13 | [
"BSD-3-Clause"
] | 57 | 2015-10-22T06:45:40.000Z | 2022-03-27T17:33:05.000Z | // Chemfiles, a modern library for chemistry file reading and writing
// Copyright (C) Guillaume Fraux and contributors -- BSD license
#include <catch.hpp>
#include <chemfiles.hpp>
using namespace chemfiles;
#undef assert
#define assert CHECK
TEST_CASE() {
// [example]
auto u = Vector3D(1.5, 2.0, -3.0);
assert(u[0] == 1.5);
assert(u[1] == 2.0);
assert(u[2] == -3.0);
// [example]
}
| 22.777778 | 69 | 0.639024 | jmintser |
2fe400e50fb276b4251a23540e03497e989f210e | 616 | cpp | C++ | Dynamic Programming/Knapsnack.cpp | aviral243/interviewbit-solutions-1 | 7b4bda68b2ff2916263493f40304b20fade16c9a | [
"MIT"
] | null | null | null | Dynamic Programming/Knapsnack.cpp | aviral243/interviewbit-solutions-1 | 7b4bda68b2ff2916263493f40304b20fade16c9a | [
"MIT"
] | null | null | null | Dynamic Programming/Knapsnack.cpp | aviral243/interviewbit-solutions-1 | 7b4bda68b2ff2916263493f40304b20fade16c9a | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int maximiseProfit(vector<int> &p, vector<int> &w, int m) {
int n = w.size();
vector<int> ans(n, 0);
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for (int i = 1; i < n + 1; i++)
for (int j = 1; j < m + 1; j++)
if (w[i - 1] > j)
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
else
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - w[i - 1]] + p[i - 1]);
return dp[n][m];
}
int main() {
vector<int> p{60, 100, 120};
vector<int> w{10, 20, 30};
int m = 50;
int v2 = maximiseProfit(p, w, m);
cout << v2;
return 0;
}
| 21.241379 | 73 | 0.477273 | aviral243 |
2fe57690a55e66d9578c20a9c04b5aafec7e0c30 | 253 | cpp | C++ | problemas-resolvidos/neps-academy/programacao-basica-competicoes-c++/c++/Raizes.cpp | Ramo-UERJ/competitive-programming | 7f2b821862853a7ebc1de5454914bcc9ea626083 | [
"MIT"
] | null | null | null | problemas-resolvidos/neps-academy/programacao-basica-competicoes-c++/c++/Raizes.cpp | Ramo-UERJ/competitive-programming | 7f2b821862853a7ebc1de5454914bcc9ea626083 | [
"MIT"
] | 1 | 2020-07-29T13:23:25.000Z | 2020-07-29T13:23:25.000Z | problemas-resolvidos/neps-academy/programacao-basica-competicoes-c++/c++/Raizes.cpp | ieee-uerj/competitive-programming | 7f2b821862853a7ebc1de5454914bcc9ea626083 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int N;
double x;
cin >> N;
cout.precision(4);
cout.setf(ios::fixed);
for (int i =0; i < N; i++){
cin >> x;
cout << sqrt(x) << endl;
}
} | 11.5 | 31 | 0.490119 | Ramo-UERJ |
2fe6891ff90c388888df3ff5931d7343b3d09b48 | 3,670 | cpp | C++ | src/foundation/Buffer.cpp | ma-bo/lua-poco | b19a38c42ff6bcd06a4fda2a5aff826056735678 | [
"BSD-3-Clause"
] | 16 | 2015-10-15T16:38:32.000Z | 2022-01-29T16:20:14.000Z | src/foundation/Buffer.cpp | ma-bo/lua-poco | b19a38c42ff6bcd06a4fda2a5aff826056735678 | [
"BSD-3-Clause"
] | 2 | 2016-08-11T22:14:31.000Z | 2016-08-12T16:02:20.000Z | src/foundation/Buffer.cpp | ma-bo/lua-poco | b19a38c42ff6bcd06a4fda2a5aff826056735678 | [
"BSD-3-Clause"
] | 8 | 2015-07-17T09:15:56.000Z | 2021-05-20T06:49:57.000Z | /// Mutable buffers.
// A module that implements mutable buffers for use with memoryostream and memoryistream.
// Note: buffer userdata are copyable between threads.
// @module buffer
#include <iostream>
#include "Buffer.h"
#include <Poco/Exception.h>
int luaopen_poco_buffer(lua_State* L)
{
LuaPoco::BufferUserdata::registerBuffer(L);
return LuaPoco::loadConstructor(L, LuaPoco::BufferUserdata::Buffer);
}
namespace LuaPoco
{
const char* POCO_BUFFER_METATABLE_NAME = "Poco.Buffer.metatable";
BufferUserdata::BufferUserdata(size_t size) :
mBuffer(size),
mCapacity(size)
{
}
BufferUserdata::~BufferUserdata()
{
}
bool BufferUserdata::copyToState(lua_State *L)
{
registerBuffer(L);
BufferUserdata* bud = new(lua_newuserdata(L, sizeof *bud)) BufferUserdata(mCapacity);
setupPocoUserdata(L, bud, POCO_BUFFER_METATABLE_NAME);
bud->mCapacity = mCapacity;
std::memcpy(bud->mBuffer.begin(), mBuffer.begin(), mCapacity);
return true;
}
// register metatable for this class
bool BufferUserdata::registerBuffer(lua_State* L)
{
struct CFunctions methods[] =
{
{ "__gc", metamethod__gc },
{ "__tostring", metamethod__tostring },
{ "clear", clear },
{ "size", size },
{ "data", data },
{ NULL, NULL }
};
setupUserdataMetatable(L, POCO_BUFFER_METATABLE_NAME, methods);
return true;
}
/// constructs a new buffer userdata.
// @param init number specifying the size of the empty buffer in bytes, or a string
// of bytes that will be used to initialize the buffer of the same size as the string.
// @return userdata or nil. (error)
// @return error message
// @function new
int BufferUserdata::Buffer(lua_State* L)
{
int rv = 0;
int top = lua_gettop(L);
int firstArg = lua_istable(L, 1) ? 2 : 1;
luaL_checkany(L, firstArg);
size_t dataSize = 0;
const char* dataInit = NULL;
if (lua_type(L, firstArg) == LUA_TSTRING) dataInit = luaL_checklstring(L, firstArg, &dataSize);
else dataSize = static_cast<size_t>(luaL_checknumber(L, firstArg));
try
{
BufferUserdata* bud = new(lua_newuserdata(L, sizeof *bud)) BufferUserdata(dataSize);
setupPocoUserdata(L, bud, POCO_BUFFER_METATABLE_NAME);
if (dataInit) std::memcpy(bud->mBuffer.begin(), dataInit, dataSize);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
///
// @type buffer
// metamethod infrastructure
int BufferUserdata::metamethod__tostring(lua_State* L)
{
BufferUserdata* bud = checkPrivateUserdata<BufferUserdata>(L, 1);
lua_pushfstring(L, "Poco.Buffer (%p)", static_cast<void*>(bud));
return 1;
}
// userdata methods
/// Sets all bytes of the buffer to '\0'.
// @function clear
int BufferUserdata::clear(lua_State* L)
{
BufferUserdata* bud = checkPrivateUserdata<BufferUserdata>(L, 1);
std::memset(bud->mBuffer.begin(), '\0', bud->mBuffer.size());
return 0;
}
/// Gets the capacity of the buffer.
// @return number indicating the capacity of the buffer.
// @function size
int BufferUserdata::size(lua_State* L)
{
BufferUserdata* bud = checkPrivateUserdata<BufferUserdata>(L, 1);
lua_pushinteger(L, bud->mCapacity);
return 1;
}
/// Gets the entire buffer as a string.
// @return string containing all bytes of the buffer.
// @function data
int BufferUserdata::data(lua_State* L)
{
BufferUserdata* bud = checkPrivateUserdata<BufferUserdata>(L, 1);
lua_pushlstring(L, bud->mBuffer.begin(), bud->mCapacity);
return 1;
}
} // LuaPoco
| 26.402878 | 99 | 0.677384 | ma-bo |
2fe79310e5405c3a6e4a499ed6b5b31d2678df9a | 8,565 | cpp | C++ | 2A. C++ Advanced (STL)/Attic/sorts.cpp | alemesa1991/School-Projects | ed9170fa4cadfe18c6d9850a17077686ca16d1a1 | [
"MIT"
] | null | null | null | 2A. C++ Advanced (STL)/Attic/sorts.cpp | alemesa1991/School-Projects | ed9170fa4cadfe18c6d9850a17077686ca16d1a1 | [
"MIT"
] | null | null | null | 2A. C++ Advanced (STL)/Attic/sorts.cpp | alemesa1991/School-Projects | ed9170fa4cadfe18c6d9850a17077686ca16d1a1 | [
"MIT"
] | null | null | null | // best reference:
// https://en.wikibooks.org/wiki/Special:Search/Algorithm_Implementation/Sorting/
// some sorts are also in see Numerical Recipes in C
// GB original code hacked from
// http://stackoverflow.com/questions/244252/a-good-reference-card-cheat-sheet-with-the-basic-sort-algorithms-in-c
// GB ported C-code to C++ function templates, new/delete
#include <cstring> // memcpy
#include <iostream>
#include <algorithm> // for std::make_heap, std::sort_heap
using namespace std;
template <typename T> // function template
static void swap(T* a, T* b) {
if (a != b) {
T c = *a;
*a = *b;
*b = c;
}
}
template <typename Iterator>
void heap_sort(Iterator begin, Iterator end)
{
std::make_heap(begin, end);
std::sort_heap(begin, end);
}
template <typename T> // function template
void heapsortCPP(T* a, int l)
{
heap_sort(a, a+l);
}
template <typename T> // function template
void heapsortC(T arr[], unsigned int N)
{
// https://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Heapsort#C
// This is a fast implementation of heapsort in C, adapted from Numerical Recipes in C
// but designed to be slightly more readable and to index from 0.
if(N==0) // check if heap is empty
return;
T t; /* the temporary value */
unsigned int n = N, parent = N/2, index, child; /* heap indexes */
/* loop until array is sorted */
while (1) {
if (parent > 0) {
/* first stage - Sorting the heap */
t = arr[--parent]; /* save old value to t */
} else {
/* second stage - Extracting elements in-place */
n--; /* make the heap smaller */
if (n == 0) {
return; /* When the heap is empty, we are done */
}
t = arr[n]; /* save lost heap entry to temporary */
arr[n] = arr[0]; /* save root entry beyond heap */
}
/* insert operation - pushing t down the heap to replace the parent */
index = parent; /* start at the parent index */
child = index * 2 + 1; /* get its left child index */
while (child < n) {
/* choose the largest child */
if (child + 1 < n && arr[child + 1] > arr[child]) {
child++; /* right child exists and is bigger */
}
/* is the largest child larger than the entry? */
if (arr[child] > t) {
arr[index] = arr[child]; /* overwrite entry with child */
index = child; /* move index to the child */
child = index * 2 + 1; /* get the left child and go around again */
} else {
break; /* t's place is found */
}
}
/* store the temporary value at its new location */
arr[index] = t;
}
}
template <typename T> // function template
void bubblesort(T* a, int l)
{
int i, j; // GB cannot be unsigned (or size_t)
for (i = l - 2; i >= 0; i--) // GB NOTE >=0 terminate condition
for (j = i; j < l - 1 && a[j] > a[j + 1]; j++)
swap(a + j, a + j + 1);
}
template <typename T> // function template
void selectionsort(T* a, size_t l)
{
size_t i, j, k;
for (i = 0; i < l; i++) {
for (j = (k = i) + 1; j < l; j++) {
if (a[j] < a[k])
k = j;
}
swap(a + i, a + k);
}
}
template <typename T> // function template
static void hsort_helper(T* a, int i, int l)
{
int j;
for (j = 2 * i + 1; j < l; i = j, j = 2 * j + 1) {
if (a[i] < a[j]) {
if (j + 1 < l && a[j] < a[j + 1]) {
swap(a + i, a + ++j);
} else {
swap(a + i, a + j);
}
} else if (j + 1 < l && a[i] < a[j + 1]) {
swap(a + i, a + ++j);
} else {
break;
}
}
}
template <typename T> // function template
void heapsort(T* a, int l)
{ // see Numerical Recipes in C
int i;
for (i = (l - 2) / 2; i >= 0; i--)
hsort_helper(a, i, l);
while (l-- > 0) {
swap(a, a + l);
hsort_helper(a, 0, l);
}
}
template <typename T> // function template
static void msort_helper(T* a, T* b, size_t l)
{
size_t i, j, k, m;
switch (l) {
case 1:
a[0] = b[0];
case 0:
return;
}
m = l / 2;
msort_helper(b, a, m);
msort_helper(b + m, a + m, l - m);
for (i = 0, j = 0, k = m; i < l; i++)
a[i] = b[j < m && !(k < l && b[j] > b[k]) ? j++ : k++];
}
template <typename T> // function template
void mergesort(T* a, size_t l)
{
T *b;
if (l < 0)
return;
// b = (T*) malloc(l * sizeof(T));
b = new T[l];
memcpy(b, a, l * sizeof(T));
msort_helper(a, b, l);
// free((void*) b);
delete [] b;
}
template <typename T> // function template
static int pivot(T* a, size_t l)
{
size_t i, j;
for (i = j = 1; i < l; i++)
if (a[i] <= a[0])
swap(a + i, a + j++);
swap(a, a + j - 1);
return j;
}
template <typename T> // function template
void quicksort(T* a, size_t l)
{
if (l <= 1)
return;
size_t m = pivot(a, l);
quicksort(a, m - 1);
quicksort(a + m, l - m);
}
template <typename T> // function template
void btreesort(T* a, size_t l)
{
size_t i;
struct node {
T value;
struct node *left, *right;
};
struct node *root = NULL, **ptr;
for (i = 0; i < l; i++) {
for (ptr = &root; *ptr;)
ptr = a[i] < (*ptr)->value ? &(*ptr)->left : &(*ptr)->right;
*ptr = (struct node*) malloc(sizeof(struct node));
// *ptr = new node;
**ptr = (struct node){.value = a[i]};
}
for (i = 0; i < l; i++) {
struct node *node;
for (ptr = &root; (*ptr)->left; ptr = &(*ptr)->left);
a[i] = (*ptr)->value;
node = (*ptr)->right;
free((void*) *ptr);
// delete ptr;
(*ptr) = node; // GB: Delete node then store something at that address?
// aborts with new/delete. Runs with malloc/free.
// munmap_chunk(): invalid pointer: 0x0000000000f49c98 ***
// /bin/bash: line 1: 7236 Aborted
}
}
template <typename T> // function template
void shellsort(T a[], const int size)// Nothing to do with shells. Named after D.H. Shell
{
int i, j, inc;
T tmp;
inc = 3;
while (inc > 0) {
for (i=0; i < size; i++) {
j = i;
tmp = a[i];
while ((j >= inc) && (a[j-inc] > tmp)) {
a[j] = a[j - inc];
j = j - inc;
}
a[j] = tmp;
}
if (inc/2 != 0)
inc = inc/2;
else if (inc == 1)
inc = 0;
else
inc = 1;
}
}
template <typename T> // function template
void insertionsort(T a[], const int length)
// https://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Insertion_sort
{
int i, j;
T value;
for(i = 1 ; i < length ; i++)
{
value = a[i];
for (j = i - 1; j >= 0 && a[j] > value; j--)
a[j + 1] = a[j];
a[j + 1] = value;
}
}
int main(int argc, char**argv)
{
int a[] = {42,19,2,66,1,33,8,5,19};
int l = sizeof(a) / sizeof(a[0]);
int b[l];
memcpy(b,a,sizeof(a));
cout << "input data "; for(auto e: a) cout << e << " "; cout << "\n\n";
bubblesort(a, l);
cout << "bubblesort "; for(auto e: a) cout << e << " "; cout << "\n";
memcpy(a,b,sizeof(a));
selectionsort(a, l);
cout << "selectionsort "; for(auto e: a) cout << e << " "; cout << "\n";
memcpy(a,b,sizeof(a));
heapsort(a, l);
cout << "heapsort "; for(auto e: a) cout << e << " "; cout << "\n";
memcpy(a,b,sizeof(a));
heapsortC(a, l);
cout << "heapsortC "; for(auto e: a) cout << e << " "; cout << "\n";
memcpy(a,b,sizeof(a));
heapsortCPP(a, l);
cout << "heapsortCPP "; for(auto e: a) cout << e << " "; cout << "\n";
memcpy(a,b,sizeof(a));
mergesort(a, l);
cout << "mergesort "; for(auto e: a) cout << e << " "; cout << "\n";
memcpy(a,b,sizeof(a));
quicksort(a, l);
cout << "quicksort "; for(auto e: a) cout << e << " "; cout << "\n";
memcpy(a,b,sizeof(a));
btreesort(a, l);
cout << "btreesort "; for(auto e: a) cout << e << " "; cout << "\n";
memcpy(a,b,sizeof(a));
shellsort(a, l);
cout << "shellsort "; for(auto e: a) cout << e << " "; cout << "\n";
memcpy(a,b,sizeof(a));
insertionsort(a, l);
cout << "insertionsort "; for(auto e: a) cout << e << " "; cout << "\n";
}
| 25.876133 | 114 | 0.493053 | alemesa1991 |
2fe9fcca7db0175ba5a6f7130e4c6f32c562f968 | 6,912 | hpp | C++ | HugeCTR/include/gpu_resource.hpp | awesome-archive/HugeCTR | ee920b03bbcd68414a30cc76ec98bae32d6047cd | [
"Apache-2.0"
] | 2 | 2019-11-27T10:40:30.000Z | 2019-11-27T10:40:35.000Z | HugeCTR/include/gpu_resource.hpp | awesome-archive/HugeCTR | ee920b03bbcd68414a30cc76ec98bae32d6047cd | [
"Apache-2.0"
] | null | null | null | HugeCTR/include/gpu_resource.hpp | awesome-archive/HugeCTR | ee920b03bbcd68414a30cc76ec98bae32d6047cd | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019, 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 "HugeCTR/include/common.hpp"
#include "HugeCTR/include/device_map.hpp"
#include "HugeCTR/include/utils.hpp"
#include "ctpl/ctpl_stl.h"
#include <cudnn.h>
#include <nccl.h>
#ifdef ENABLE_MPI
#include <mpi.h>
#endif
namespace HugeCTR {
/**
* @brief GPU resource allocated on a target gpu.
*
* This class implement unified resource managment on the target GPU.
*/
class GPUResource {
private:
cudaStream_t stream_; /**< cuda stream for computation */
cudaStream_t data_copy_stream_; /**< cuda stream for data copy */
cublasHandle_t cublas_handle_;
cudnnHandle_t cudnn_handle_;
const int device_id_;
const ncclComm_t* comm_;
public:
/**
* Ctor
*/
GPUResource(int device_id, const ncclComm_t* comm) : device_id_(device_id), comm_(comm) {
int o_device = -1;
CK_CUDA_THROW_(get_set_device(device_id_, &o_device));
CK_CUBLAS_THROW_(cublasCreate(&cublas_handle_));
CK_CUDNN_THROW_(cudnnCreate(&cudnn_handle_));
CK_CUDA_THROW_(cudaStreamCreate(&stream_));
CK_CUDA_THROW_(cudaStreamCreate(&data_copy_stream_));
CK_CUDA_THROW_(get_set_device(o_device));
return;
}
GPUResource(const GPUResource&) = delete;
GPUResource& operator=(const GPUResource&) = delete;
/*
* Dtor
*/
~GPUResource() {
try {
int o_device = -1;
CK_CUDA_THROW_(get_set_device(device_id_, &o_device));
CK_CUBLAS_THROW_(cublasDestroy(cublas_handle_));
CK_CUDNN_THROW_(cudnnDestroy(cudnn_handle_));
CK_CUDA_THROW_(cudaStreamDestroy(stream_));
CK_CUDA_THROW_(cudaStreamDestroy(data_copy_stream_));
CK_CUDA_THROW_(get_set_device(o_device));
} catch (const std::runtime_error& rt_err) {
std::cerr << rt_err.what() << std::endl;
}
return;
}
int get_device_id() const { return device_id_; }
const cudaStream_t* get_stream_ptr() const { return &stream_; }
const cudaStream_t* get_data_copy_stream_ptr() const { return &data_copy_stream_; }
const cublasHandle_t* get_cublas_handle_ptr() const { return &cublas_handle_; }
const cudnnHandle_t* get_cudnn_handle_ptr() const { return &cudnn_handle_; }
const ncclComm_t* get_nccl_ptr() const { return comm_; }
};
/**
* @brief GPU resources container.
*
* A GPU resource container in one node. An instant includes:
* GPU resource vector, thread pool for training, nccl communicators.
*/
class GPUResourceGroup {
private:
ncclComm_t* comms_;
const DeviceMap device_map_;
std::vector<GPUResource*> gpu_resources_; /**< GPU resource vector */
public:
ctpl::thread_pool train_thread_pool; /**< cpu thread pool for training */
std::vector<std::future<void>> results;
GPUResourceGroup(const DeviceMap& device_map)
: comms_(nullptr),
device_map_(device_map),
gpu_resources_(device_map_.get_device_list().size(), nullptr),
train_thread_pool(device_map_.get_device_list().size()),
results(device_map_.get_device_list().size()) {
auto& device_list = device_map_.get_device_list();
size_t local_gpu_count = device_list.size();
if (local_gpu_count == 0) {
CK_THROW_(Error_t::WrongInput, "Empty device_list");
}
if (local_gpu_count != size()) {
CK_THROW_(Error_t::WrongInput, "local_gpu_count != size()");
}
int dev_count;
cudaGetDeviceCount(&dev_count);
for (int dev : device_list) {
if (dev >= dev_count) {
CK_THROW_(Error_t::WrongInput, "Invalid device id: " + std::to_string(dev));
}
}
if (gpu_resources_.size() != local_gpu_count) {
CK_THROW_(Error_t::WrongInput, "gpu_resource_.size() != local_gpu_count");
}
int total_gpu_count = get_total_gpu_count();
// if ther are multiple GPUs within a node or/and across nodes
if (total_gpu_count > 1) {
int my_rank = 0;
int n_ranks = 1;
comms_ = new ncclComm_t[local_gpu_count]();
#ifdef ENABLE_MPI
CK_MPI_THROW_(MPI_Comm_rank(MPI_COMM_WORLD, &my_rank));
CK_MPI_THROW_(MPI_Comm_size(MPI_COMM_WORLD, &n_ranks));
ncclUniqueId nid;
if (my_rank == 0) CK_NCCL_THROW_(ncclGetUniqueId(&nid));
CK_MPI_THROW_(MPI_Bcast((void*)&nid, sizeof(nid), MPI_BYTE, 0, MPI_COMM_WORLD));
CK_NCCL_THROW_(ncclGroupStart());
for (size_t i = 0; i < local_gpu_count; i++) {
CK_CUDA_THROW_(cudaSetDevice(device_list[i]));
CK_NCCL_THROW_(ncclCommInitRank(comms_ + i, total_gpu_count, nid,
device_map_.get_global_id(device_list[i])));
}
CK_NCCL_THROW_(ncclGroupEnd());
#else
CK_NCCL_THROW_(ncclCommInitAll(comms_, device_list.size(), device_list.data()));
#endif
} else {
comms_ = nullptr;
}
for (size_t i = 0; i < local_gpu_count; i++) {
gpu_resources_[i] = (new GPUResource(device_list[i], comms_ + i));
}
}
GPUResourceGroup(const GPUResourceGroup& C) = delete;
GPUResourceGroup& operator=(const GPUResourceGroup&) = delete;
const GPUResource* operator[](int idx) const { return gpu_resources_[idx]; }
size_t size() const {
// return gpu_resources_.size();
return device_map_.get_device_list().size();
}
bool empty() const { return size() == 0; }
~GPUResourceGroup() {
try {
if (gpu_resources_.size() > 1) {
for (unsigned int i = 0; i < gpu_resources_.size(); i++) {
CK_NCCL_THROW_(ncclCommDestroy(comms_[i]));
}
delete[] comms_;
}
for (auto gpu_resource : gpu_resources_) {
delete gpu_resource;
}
} catch (const std::runtime_error& rt_err) {
std::cerr << rt_err.what() << std::endl;
}
}
const std::vector<int>& get_device_list() const { return device_map_.get_device_list(); }
int get_global_id(int local_device_id) const {
return device_map_.get_global_id(local_device_id);
}
int get_local_id(int global_id) const { // sequential GPU indices
return device_map_.get_local_id(global_id);
}
int get_local_device_id(int global_id) const { // the actual GPU ids
return device_map_.get_local_device_id(global_id);
}
int get_total_gpu_count() const { return device_map_.size(); }
int get_node_count() const { return device_map_.num_nodes(); }
int get_pid(int global_id) const { return device_map_.get_pid(global_id); }
};
} // namespace HugeCTR
| 33.882353 | 91 | 0.689525 | awesome-archive |
2ff1c3c9c70262f567269e823da531dc31be2115 | 8,452 | cpp | C++ | MeshTools/QuadricFit.cpp | EMinsight/FEBioStudio | d3e6485610d19217550fb94cb22180bc4bda45f9 | [
"MIT"
] | 27 | 2020-06-25T06:34:52.000Z | 2022-03-11T08:58:57.000Z | MeshTools/QuadricFit.cpp | EMinsight/FEBioStudio | d3e6485610d19217550fb94cb22180bc4bda45f9 | [
"MIT"
] | 42 | 2020-06-15T18:40:57.000Z | 2022-03-24T05:38:54.000Z | MeshTools/QuadricFit.cpp | EMinsight/FEBioStudio | d3e6485610d19217550fb94cb22180bc4bda45f9 | [
"MIT"
] | 12 | 2020-06-27T13:58:57.000Z | 2022-03-24T05:39:10.000Z | /*This file is part of the FEBio Studio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio-Studio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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.*/
// onchoidFit.cpp: implementation of the QuadricFit class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "QuadricFit.h"
#include <MathLib/powell.h>
#include <stdio.h>
using std::swap;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//-------------------------------------------------------------------------------
// constructor
QuadricFit::QuadricFit()
{
m_rc = m_c2 = vec3d(0,0,0);
m_c = 0;
m_ax[0] = m_ax[1] = m_ax [2] = vec3d(0,0,0);
m_quad = new Quadric();
m_eps = 1e-3;
}
//-------------------------------------------------------------------------------
// copy constructor
QuadricFit::QuadricFit(const QuadricFit& qf)
{
m_rc = qf.m_rc;
m_c2 = qf.m_c2;
m_c = qf.m_c;
m_ax[0] = qf.m_ax[0];
m_ax[1] = qf.m_ax[1];
m_ax[2] = qf.m_ax[2];
m_quad = new Quadric(*qf.m_quad);
m_eps = qf.m_eps;
}
//-------------------------------------------------------------------------------
// destructor
QuadricFit::~QuadricFit()
{
}
//-------------------------------------------------------------------------------
void QuadricFit::GetOrientation()
{
mat3ds C(m_quad->m_c[0], m_quad->m_c[1], m_quad->m_c[2],
m_quad->m_c[5], m_quad->m_c[3], m_quad->m_c[4]);
vec3d v = vec3d(m_quad->m_c[6], m_quad->m_c[7], m_quad->m_c[8]);
double c = m_quad->m_c[9];
double eval[3];
vec3d evec[3];
C.eigen2(eval, evec); // eigenvalues sorted from smallest to largest
// rectify sign of eigenvalues
if (eval[2] <= 0) {
eval[0] = -eval[0];
eval[1] = -eval[1];
eval[2] = -eval[2];
v = -v;
c = -c;
}
// re-sort eigenvalues and eigenvectors from largest to smalles
if (eval[0] < eval[2]) { swap(eval[0],eval[2]); swap(evec[0], evec[2]); }
if (eval[0] < eval[1]) { swap(eval[0],eval[1]); swap(evec[0], evec[1]); }
if (eval[1] < eval[2]) { swap(eval[1],eval[2]); swap(evec[1], evec[2]); }
// estimate the relative magnitudes of the eigenvalues
double emag = sqrt(eval[0]*eval[0] + eval[1]*eval[1] + eval[2]*eval[2]);
if (fabs(eval[0]) < m_eps*emag) eval[0] = 0;
if (fabs(eval[1]) < m_eps*emag) eval[1] = 0;
if (fabs(eval[2]) < m_eps*emag) eval[2] = 0;
// normalize vectors
evec[0].Normalize(); evec[1].Normalize(); evec[2].Normalize();
// clean up vector
if (fabs(evec[0].x) < m_eps) evec[0].x = 0; if (fabs(evec[0].y) < m_eps) evec[0].y = 0; if (fabs(evec[0].z) < m_eps) evec[0].z = 0;
if (fabs(evec[1].x) < m_eps) evec[1].x = 0; if (fabs(evec[1].y) < m_eps) evec[1].y = 0; if (fabs(evec[1].z) < m_eps) evec[1].z = 0;
if (fabs(evec[2].x) < m_eps) evec[2].x = 0; if (fabs(evec[2].y) < m_eps) evec[2].y = 0; if (fabs(evec[2].z) < m_eps) evec[2].z = 0;
evec[0].Normalize(); evec[1].Normalize(); evec[2].Normalize();
// check if basis is right-handed or not
double rh = (evec[0] ^ evec[1])*evec[2];
if (rh < 0) evec[1] = evec[2] ^ evec[0];
// estimate the relative magnitudes of the components of v
double vmag = v.Length();
if (fabs(v.x) < m_eps*vmag) v.x = 0;
if (fabs(v.y) < m_eps*vmag) v.y = 0;
if (fabs(v.z) < m_eps*vmag) v.z = 0;
mat3d Q(evec[0].x, evec[1].x, evec[2].x,
evec[0].y, evec[1].y, evec[2].y,
evec[0].z, evec[1].z, evec[2].z);
m_ax[0] = evec[0];
m_ax[1] = evec[1];
m_ax[2] = evec[2];
m_c2 = vec3d(eval[0], eval[1], eval[2]);
vec3d d = Q.transpose()*v;
vec3d X0;
if (m_c2.x*m_c2.y*m_c2.z != 0) {
X0.x = -d.x/(2*m_c2.x);
X0.y = -d.y/(2*m_c2.y);
X0.z = -d.z/(2*m_c2.z);
m_c = c - m_c2.x*pow(X0.x,2) - m_c2.y*pow(X0.y,2) - m_c2.z*pow(X0.z,2);
if (fabs(m_c) < m_eps) m_c = 0;
if (m_c != 0) {
m_c2 /= fabs(m_c);
m_c /= fabs(m_c);
}
}
else if (m_c2.x*m_c2.y != 0) {
X0.x = -d.x/(2*m_c2.x);
X0.y = -d.y/(2*m_c2.y);
X0.z = 0;
m_c = c - m_c2.x*pow(X0.x,2) - m_c2.y*pow(X0.y,2);
if (m_c != 0) {
m_c2 /= fabs(m_c);
m_c /= fabs(m_c);
}
}
else {
X0.x = -d.x/(2*m_c2.x);
X0.y = 0;
X0.z = 0;
m_c = c - m_c2.x*pow(X0.x,2);
if (m_c != 0) {
m_c2 /= fabs(m_c);
m_c /= fabs(m_c);
}
}
m_rc = Q*X0;
// clean up
double rc = m_rc.Length();
if (fabs(m_rc.x) < m_eps*rc) m_rc.x = 0;
if (fabs(m_rc.y) < m_eps*rc) m_rc.y = 0;
if (fabs(m_rc.z) < m_eps*rc) m_rc.z = 0;
}
//-------------------------------------------------------------------------------
// complete fit algorithm
bool QuadricFit::Fit(PointCloud3d* pc)
{
m_quad->SetPointCloud3d(pc);
if (m_quad->GetQuadricCoeficients())
{
GetOrientation();
return true;
}
else
return false;
}
//-------------------------------------------------------------------------------
bool QuadricFit::isSame(const double& a, const double&b)
{
if (fabs(b-a) < m_eps*fabs(a+b)/2) return true;
else return false;
}
//-------------------------------------------------------------------------------
QuadricFit::Q_TYPE QuadricFit::GetType()
{
// determine quadric type
Q_TYPE type = Q_UNKNOWN;
double A = m_c2.x, B = m_c2.y, C = m_c2.z;
double c = m_c;
if ((A > 0) && (B > 0)) {
if ((C > 0) && (c == -1)) {
type = Q_ELLIPSOID;
if (isSame(A,B)) {
type = Q_SPHEROID;
if (isSame(B,C)) type = Q_SPHERE;
}
}
else if (C == 0) {
if ((m_v.z == -1) && (c == 0)) {
type = Q_ELLIPTIC_PARABOLOID;
if (isSame(A,B))
type = Q_CIRCULAR_PARABOLOID;
}
else if ((m_v.z == 0) && (c == -1)) {
type = Q_ELLIPTIC_CYLINDER;
if (isSame(A,B))
type = Q_CIRCULAR_CYLINDER;
}
}
else if (C < 0) {
if (c == -1) {
type = Q_ELLIPTIC_HYPERBOLOID_1;
if (isSame(A,B)) {
type = Q_CIRCULAR_HYPERBOLOID_1;
}
}
else if (c == 1) {
type = Q_ELLIPTIC_HYPERBOLOID_2;
if (isSame(A,B)) {
type = Q_CIRCULAR_HYPERBOLOID_2;
}
}
else if (c == 0) {
type = Q_ELLIPTIC_CONE;
if (isSame(A,B)) {
type = Q_CIRCULAR_CONE;
}
}
}
}
else if ((A > 0) && (B < 0)) {
if ((C == 0) && (c == 0) && (m_v.z == -1)) {
type = Q_HYPERBOLIC_PARABOLOID;
}
else if ((C == 0) && (c == -1) && (m_v.z == 0)) {
type = Q_HYPERBOLIC_CYLINDER;
}
}
else if ((A > 0) && (B == 0)) {
type = Q_PARABOLIC_CYLINDER;
}
return type;
}
| 32.507692 | 135 | 0.479886 | EMinsight |
2ff7457bf2fe4d2d3c0bc27af0930303fb70b26b | 432 | cpp | C++ | libfairygui/proj.ios_mac/libfairygui MAC/libfairygui_MAC.cpp | umair6/FairyGUI-cocos2dx | 7b21889a48b6ff5878b407c2a484670ebd8a4549 | [
"MIT"
] | 308 | 2017-10-15T14:26:45.000Z | 2022-03-22T09:06:57.000Z | libfairygui/proj.ios_mac/libfairygui MAC/libfairygui_MAC.cpp | umair6/FairyGUI-cocos2dx | 7b21889a48b6ff5878b407c2a484670ebd8a4549 | [
"MIT"
] | 73 | 2017-10-25T06:41:57.000Z | 2022-03-21T06:49:38.000Z | libfairygui/proj.ios_mac/libfairygui MAC/libfairygui_MAC.cpp | umair6/FairyGUI-cocos2dx | 7b21889a48b6ff5878b407c2a484670ebd8a4549 | [
"MIT"
] | 108 | 2017-11-01T08:22:00.000Z | 2021-11-19T10:29:29.000Z | /*
* libfairygui_MAC.cpp
* libfairygui MAC
*
* Created by ytom on 17/11/9.
*
*
*/
#include <iostream>
#include "libfairygui_MAC.hpp"
#include "libfairygui_MACPriv.hpp"
void libfairygui_MAC::HelloWorld(const char * s)
{
libfairygui_MACPriv *theObj = new libfairygui_MACPriv;
theObj->HelloWorldPriv(s);
delete theObj;
};
void libfairygui_MACPriv::HelloWorldPriv(const char * s)
{
std::cout << s << std::endl;
};
| 16.615385 | 57 | 0.699074 | umair6 |
2ff8a072db190083a0bd4de78330e881d25a0bf3 | 239 | cpp | C++ | src/autowiring/CallExtractor.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 87 | 2015-01-18T00:43:06.000Z | 2022-02-11T17:40:50.000Z | src/autowiring/CallExtractor.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 274 | 2015-01-03T04:50:49.000Z | 2021-03-08T09:01:09.000Z | src/autowiring/CallExtractor.cpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 15 | 2015-09-30T20:58:43.000Z | 2020-12-19T21:24:56.000Z | // Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "CallExtractor.h"
#include "AutoPacket.h"
using namespace autowiring;
CESetup<>::CESetup(AutoPacket& packet) :
pshr(packet.GetContext())
{}
| 21.727273 | 65 | 0.732218 | CaseyCarter |
2ffacb880e69077ba5223c6dc2e378a75dfb4f87 | 41,267 | hpp | C++ | libnd4j/include/ops/declarable/helpers/cpu/indexReductions.hpp | steljord2/deeplearning4j | 4653c97a713cc59e41d4313ddbafc5ff527f8714 | [
"Apache-2.0"
] | 2,206 | 2019-06-12T18:57:14.000Z | 2022-03-29T08:14:27.000Z | libnd4j/include/ops/declarable/helpers/cpu/indexReductions.hpp | steljord2/deeplearning4j | 4653c97a713cc59e41d4313ddbafc5ff527f8714 | [
"Apache-2.0"
] | 1,685 | 2019-06-12T17:41:33.000Z | 2022-03-29T21:45:15.000Z | libnd4j/include/ops/declarable/helpers/cpu/indexReductions.hpp | steljord2/deeplearning4j | 4653c97a713cc59e41d4313ddbafc5ff527f8714 | [
"Apache-2.0"
] | 572 | 2019-06-12T22:13:57.000Z | 2022-03-31T16:46:46.000Z | /* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author AbdelRauf
//
#include <execution/ThreadPool.h>
#include <execution/Threads.h>
#include <helpers/LoopsCoordsHelper.h>
#include <ops/declarable/helpers/reductions.h>
#include <cmath>
#include <memory>
#include <stdexcept>
#include <type_traits>
#if 1
#define LOG_CALLS(X)
#else
#define LOG_CALLS(X) sd_printf("___%s_________%d+\n", __PRETTY_FUNCTION__, X);
#endif
namespace sd {
namespace ops {
namespace helpers {
constexpr int threadingThreshold = 4096;
template <typename X, typename Z, typename ReductionOp>
static SD_INLINE void indexInnerReductionRank1(const X* buffer, X& current, Z& argCurrent,
const sd::LongType& loopCount) {
argCurrent = 0;
current = buffer[0];
LOG_CALLS(0)
sd::LongType j_offset = 0;
for (Z j = 0; j < loopCount; j++) {
ReductionOp::update(current, argCurrent, buffer[j], j);
}
}
template <typename X, typename Z, typename ReductionOp>
static SD_INLINE void indexInnerReductionRank1(const X* buffer, X& current, Z& argCurrent,
const sd::LongType& loopCount, const sd::LongType& inner_stride) {
argCurrent = 0;
current = buffer[0];
LOG_CALLS(0)
sd::LongType j_offset = 0;
for (Z j = 0; j < loopCount; j++) {
ReductionOp::update(current, argCurrent, buffer[j_offset], j);
j_offset += inner_stride;
}
}
template <typename X, typename Z, typename ReductionOp, size_t constRank, bool LastIndexFaster = true>
static SD_INLINE void indexInnerReductionConstRank(const X* buffer, X& current, Z& argCurrent,
const sd::LongType* bases, const sd::LongType* strides,
const sd::LongType outerLoopCount,
const sd::LongType& innerLoopCount) {
// skip 1 from the beginning or end depending the Order
constexpr size_t updated_index = LastIndexFaster ? 0 : 1;
constexpr size_t updated_rank = constRank - 1;
sd::CoordsState<updated_rank - 1> cst;
// we skip 1
size_t offset =
sd::init_coords<updated_rank, 0, LastIndexFaster>(cst, 0, bases + updated_index, strides + updated_index);
Z startIndex = 0;
argCurrent = 0;
current = buffer[offset];
LOG_CALLS(0)
for (Z i = 0; i < outerLoopCount; i++) {
const X* inner_buffer = &(buffer[offset]);
// typename std::make_signed<Z>::type iArgMax = -1;
for (Z j = 0; j < innerLoopCount; j++) {
ReductionOp::update(current, argCurrent, inner_buffer[j], j + startIndex);
}
// we skip 1
offset = sd::inc_coords<updated_rank, 0, LastIndexFaster>(cst, offset);
startIndex += innerLoopCount;
}
}
template <typename X, typename Z, typename ReductionOp, size_t constRank, bool LastIndexFaster = true>
static SD_INLINE void indexInnerReductionConstRank(const X* buffer, X& current, Z& argCurrent,
const sd::LongType* bases, const sd::LongType* strides,
const sd::LongType outerLoopCount,
const sd::LongType& innerLoopCount,
const sd::LongType& inner_stride) {
// skip 1 from the beginning or end depending the Order
constexpr size_t updated_index = LastIndexFaster ? 0 : 1;
constexpr size_t updated_rank = constRank - 1;
sd::CoordsState<updated_rank - 1> cst;
// we skip 1
size_t offset =
sd::init_coords<updated_rank, 0, LastIndexFaster>(cst, 0, bases + updated_index, strides + updated_index);
Z startIndex = 0;
argCurrent = 0;
current = buffer[offset];
LOG_CALLS(0)
for (Z i = 0; i < outerLoopCount; i++) {
const X* inner_buffer = &(buffer[offset]);
for (Z j = 0; j < innerLoopCount; j++) {
ReductionOp::update(current, argCurrent, *inner_buffer, j + startIndex);
inner_buffer += inner_stride;
}
// we alreaddy skiped
offset = sd::inc_coords<updated_rank, 0, LastIndexFaster>(cst, offset);
startIndex += innerLoopCount;
}
}
template <typename X, typename Z, typename ReductionOp, bool LastIndexFaster = true>
static SD_INLINE void indexInnerReduction(const int& rank, const X* buffer, X& current, Z& argCurrent,
const sd::LongType* bases, const sd::LongType* strides,
const sd::LongType& outerLoopStart, const sd::LongType& outerLoopStop,
const sd::LongType& innerLoopCount) {
size_t offset = 0;
sd::LongType outerLoopCount = outerLoopStop - outerLoopStart;
sd::LongType coords[SD_MAX_RANK] = {};
sd::LongType* ptr_coords = (sd::LongType*)&coords;
if (outerLoopStart > 0) {
sd::index2coords_C(outerLoopStart, rank - 1, bases, ptr_coords);
offset = sd::offset_from_coords(strides, ptr_coords, rank);
}
Z startIndex = outerLoopStart * innerLoopCount;
argCurrent = startIndex;
current = buffer[offset];
LOG_CALLS(0)
for (Z i = 0; i < outerLoopCount; i++) {
const X* inner_buffer = &(buffer[offset]);
// typename std::make_signed<Z>::type iArgMax = -1;
for (Z j = 0; j < innerLoopCount; j++) {
// sd_printf("%f\n", inner_buffer[j]);
ReductionOp::update(current, argCurrent, inner_buffer[j], j + startIndex);
}
offset = inc_coords<true>(bases, strides, ptr_coords, offset, rank, 1);
// if (iArgMax >= 0) argCurrent = startIndex + iArgMax;
startIndex += innerLoopCount;
}
}
template <typename X, typename Z, typename ReductionOp, bool LastIndexFaster = true>
static SD_INLINE void indexInnerReduction(const int& rank, const X* buffer, X& current, Z& argCurrent,
const sd::LongType* bases, const sd::LongType* strides,
const sd::LongType& outerLoopStart, const sd::LongType& outerLoopStop,
const sd::LongType& innerLoopCount, const sd::LongType& inner_stride) {
size_t offset = 0;
sd::LongType outerLoopCount = outerLoopStop - outerLoopStart;
sd::LongType coords[SD_MAX_RANK] = {};
sd::LongType* ptr_coords = (sd::LongType*)&coords;
if (outerLoopStart > 0) {
sd::index2coords_C(outerLoopStart, rank - 1, bases, ptr_coords);
offset = sd::offset_from_coords(strides, ptr_coords, rank);
}
Z startIndex = outerLoopStart * innerLoopCount;
argCurrent = startIndex;
current = buffer[offset];
LOG_CALLS(0)
for (Z i = 0; i < outerLoopCount; i++) {
const X* inner_buffer = &(buffer[offset]);
// typename std::make_signed<Z>::type iArgMax = -1;
for (Z j = 0; j < innerLoopCount; j++) {
ReductionOp::update(current, argCurrent, inner_buffer[j * inner_stride], startIndex + j);
}
offset = inc_coords<true>(bases, strides, ptr_coords, offset, rank, 1);
// offset = inc_coords<LastIndexFaster>(bases, strides, ptr_coords, offset, rank, 1);
// if (iArgMax >= 0) argCurrent = startIndex + iArgMax;
startIndex += innerLoopCount;
}
}
template <typename X, typename Z, typename ReductionOp>
static SD_INLINE void indexInnerReductionRank1Block4WithMerge(const X* buffer, X& current, Z& argCurrent,
const sd::LongType& loopCount) {
argCurrent = 0;
current = buffer[0];
LOG_CALLS(0)
sd::LongType loopCount4 = loopCount / 4;
sd::LongType loopCountEnd = loopCount4 + (loopCount & 3);
const X* buffer1 = buffer + 1 * loopCount4;
const X* buffer2 = buffer1 + 1 * loopCount4;
const X* buffer3 = buffer2 + 1 * loopCount4;
X current1 = *buffer1;
X current2 = *buffer2;
X current3 = *buffer3;
Z argCurrent1 = 0;
Z argCurrent2 = 0;
Z argCurrent3 = 0;
for (Z j = 0; j < loopCount4; j++) {
ReductionOp::update(current, argCurrent, buffer[j], j);
ReductionOp::update(current1, argCurrent1, buffer1[j], j);
ReductionOp::update(current2, argCurrent2, buffer2[j], j);
ReductionOp::update(current3, argCurrent3, buffer3[j], j);
}
// tail
for (Z j = loopCount4; j < loopCountEnd; j++) {
ReductionOp::update(current3, argCurrent3, buffer3[j], j);
}
// merge
argCurrent1 += loopCount4;
argCurrent2 += 2 * loopCount4;
argCurrent3 += 3 * loopCount4;
ReductionOp::update(current, argCurrent, current1, argCurrent1);
ReductionOp::update(current, argCurrent, current2, argCurrent2);
ReductionOp::update(current, argCurrent, current3, argCurrent3);
}
template <typename X, typename Z, typename ReductionOp>
static SD_INLINE void indexInnerReductionRank1Block4WithMerge(const X* buffer, X& current, Z& argCurrent,
const sd::LongType& loopCount,
const sd::LongType& inner_stride) {
argCurrent = 0;
current = buffer[0];
LOG_CALLS(0)
sd::LongType loopCount4 = loopCount / 4;
sd::LongType loopCountEnd = loopCount4 + (loopCount & 3);
const X* buffer1 = buffer + inner_stride * loopCount4;
const X* buffer2 = buffer1 + inner_stride * loopCount4;
const X* buffer3 = buffer2 + inner_stride * loopCount4;
X current1 = *buffer1;
X current2 = *buffer2;
X current3 = *buffer3;
Z argCurrent1 = 0;
Z argCurrent2 = 0;
Z argCurrent3 = 0;
sd::LongType j_offset = 0;
for (Z j = 0; j < loopCount4; j++) {
ReductionOp::update(current, argCurrent, buffer[j_offset], j);
ReductionOp::update(current1, argCurrent1, buffer1[j_offset], j);
ReductionOp::update(current2, argCurrent2, buffer2[j_offset], j);
ReductionOp::update(current3, argCurrent3, buffer3[j_offset], j);
j_offset += inner_stride;
}
// tail
for (Z j = loopCount4; j < loopCountEnd; j++) {
ReductionOp::update(current3, argCurrent3, buffer3[j_offset], j);
j_offset += inner_stride;
}
// merge
argCurrent1 += loopCount4;
argCurrent2 += 2 * loopCount4;
argCurrent3 += 3 * loopCount4;
ReductionOp::update(current, argCurrent, current1, argCurrent1);
ReductionOp::update(current, argCurrent, current2, argCurrent2);
ReductionOp::update(current, argCurrent, current3, argCurrent3);
}
template <typename X, typename Z, typename ReductionOp>
static SD_INLINE void indexInnerReductionRank1Block4(const X* buffer, const X* buffer1, const X* buffer2,
const X* buffer3, Z* output, Z* output1, Z* output2, Z* output3,
const sd::LongType& loopCount) {
LOG_CALLS(0)
Z argCurrent = 0;
Z argCurrent1 = 0;
Z argCurrent2 = 0;
Z argCurrent3 = 0;
X current = buffer[0];
X current1 = buffer1[0];
X current2 = buffer2[0];
X current3 = buffer3[0];
for (Z j = 0; j < loopCount; j++) {
ReductionOp::update(current, argCurrent, buffer[j], j);
ReductionOp::update(current1, argCurrent1, buffer1[j], j);
ReductionOp::update(current2, argCurrent2, buffer2[j], j);
ReductionOp::update(current3, argCurrent3, buffer3[j], j);
}
*output = argCurrent;
*output1 = argCurrent1;
*output2 = argCurrent2;
*output3 = argCurrent3;
return;
}
template <typename X, typename Z, typename ReductionOp>
static SD_INLINE void indexInnerReductionRank1Block4(const X* buffer, const X* buffer1, const X* buffer2,
const X* buffer3, Z* output, Z* output1, Z* output2, Z* output3,
const sd::LongType& loopCount, const sd::LongType& inner_stride) {
LOG_CALLS(0)
Z argCurrent = 0;
Z argCurrent1 = 0;
Z argCurrent2 = 0;
Z argCurrent3 = 0;
X current = buffer[0];
X current1 = buffer1[0];
X current2 = buffer2[0];
X current3 = buffer3[0];
sd::LongType j_offset = 0;
for (Z j = 0; j < loopCount; j++) {
ReductionOp::update(current, argCurrent, buffer[j_offset], j);
ReductionOp::update(current1, argCurrent1, buffer1[j_offset], j);
ReductionOp::update(current2, argCurrent2, buffer2[j_offset], j);
ReductionOp::update(current3, argCurrent3, buffer3[j_offset], j);
j_offset += inner_stride;
}
*output = argCurrent;
*output1 = argCurrent1;
*output2 = argCurrent2;
*output3 = argCurrent3;
return;
}
template <typename X, typename Z, typename ReductionOp, size_t constRank, bool LastIndexFaster = true>
static SD_INLINE void indexInnerReductionConstRankBlock4(const X* buffer, const X* buffer1, const X* buffer2,
const X* buffer3, Z* output, Z* output1, Z* output2,
Z* output3, const sd::LongType* bases,
const sd::LongType* strides,
const sd::LongType& outerLoopCount,
const sd::LongType& innerLoopCount) {
LOG_CALLS(0)
// skip 1 from the beginning or end depending the Order
constexpr size_t updated_index = LastIndexFaster ? 0 : 1;
constexpr size_t updated_rank = constRank - 1;
sd::CoordsState<updated_rank - 1> cst;
// we skip 1
size_t offset =
sd::init_coords<updated_rank, 0, LastIndexFaster>(cst, 0, bases + updated_index, strides + updated_index);
Z startIndex = 0;
Z argCurrent = 0;
Z argCurrent1 = 0;
Z argCurrent2 = 0;
Z argCurrent3 = 0;
X current = buffer[0];
X current1 = buffer1[0];
X current2 = buffer2[0];
X current3 = buffer3[0];
// LOG_CALLS(0)
for (Z i = 0; i < outerLoopCount; i++) {
const X* inner_buffer = &(buffer[offset]);
const X* inner_buffer1 = &(buffer1[offset]);
const X* inner_buffer2 = &(buffer2[offset]);
const X* inner_buffer3 = &(buffer3[offset]);
// typename std::make_signed<Z>::type iArgMax = -1;
for (Z j = 0; j < innerLoopCount; j++) {
ReductionOp::update(current, argCurrent, inner_buffer[j], j + startIndex);
ReductionOp::update(current1, argCurrent1, inner_buffer1[j], j + startIndex);
ReductionOp::update(current2, argCurrent2, inner_buffer2[j], j + startIndex);
ReductionOp::update(current3, argCurrent3, inner_buffer3[j], j + startIndex);
}
// we skip 1
offset = sd::inc_coords<updated_rank, 0, LastIndexFaster>(cst, offset);
startIndex += innerLoopCount;
}
*output = argCurrent;
*output1 = argCurrent1;
*output2 = argCurrent2;
*output3 = argCurrent3;
return;
}
template <typename X, typename Z, typename ReductionOp, size_t constRank, bool LastIndexFaster = true>
static SD_INLINE void indexInnerReductionConstRankBlock4(
const X* buffer, const X* buffer1, const X* buffer2, const X* buffer3, Z* output, Z* output1, Z* output2,
Z* output3, const sd::LongType* bases, const sd::LongType* strides, const sd::LongType& outerLoopCount,
const sd::LongType& innerLoopCount, const sd::LongType& inner_stride) {
LOG_CALLS(0)
// skip 1 from the beginning or end depending the Order
constexpr size_t updated_index = LastIndexFaster ? 0 : 1;
constexpr size_t updated_rank = constRank - 1;
sd::CoordsState<updated_rank - 1> cst;
// we skip 1
size_t offset =
sd::init_coords<updated_rank, 0, LastIndexFaster>(cst, 0, bases + updated_index, strides + updated_index);
Z startIndex = 0;
Z argCurrent = 0;
Z argCurrent1 = 0;
Z argCurrent2 = 0;
Z argCurrent3 = 0;
X current = buffer[0];
X current1 = buffer1[0];
X current2 = buffer2[0];
X current3 = buffer3[0];
// LOG_CALLS(0)
for (Z i = 0; i < outerLoopCount; i++) {
const X* inner_buffer = &(buffer[offset]);
const X* inner_buffer1 = &(buffer1[offset]);
const X* inner_buffer2 = &(buffer2[offset]);
const X* inner_buffer3 = &(buffer3[offset]);
// typename std::make_signed<Z>::type iArgMax = -1;
sd::LongType inner_offset = 0;
for (Z j = 0; j < innerLoopCount; j++) {
ReductionOp::update(current, argCurrent, inner_buffer[inner_offset], j + startIndex);
ReductionOp::update(current1, argCurrent1, inner_buffer1[inner_offset], j + startIndex);
ReductionOp::update(current2, argCurrent2, inner_buffer2[inner_offset], j + startIndex);
ReductionOp::update(current3, argCurrent3, inner_buffer3[inner_offset], j + startIndex);
inner_offset += inner_stride;
}
// we skip 1
offset = sd::inc_coords<updated_rank, 0, LastIndexFaster>(cst, offset);
startIndex += innerLoopCount;
}
*output = argCurrent;
*output1 = argCurrent1;
*output2 = argCurrent2;
*output3 = argCurrent3;
return;
}
template <typename X, typename Z, typename ReductionOp, bool LastIndexFaster = true>
static void argIndexCase1Scalar(const int& second_rank, const sd::LongType* inner_bases,
const sd::LongType* inner_strides, const X* bufferX, Z* outputZ) {
sd::LongType inner_total;
sd::LongType inner_last = 0;
int maxThreads = sd::Environment::getInstance().maxMasterThreads();
if (second_rank == 1) {
inner_total = inner_bases[0];
if (inner_total < threadingThreshold) {
maxThreads = 1;
}
} else {
inner_total = getLength<LastIndexFaster>(inner_bases, second_rank, 1, inner_last);
if (inner_total * inner_last < threadingThreshold) {
maxThreads = 1;
}
}
std::unique_ptr<X[]> maxValues(new X[maxThreads]);
std::unique_ptr<Z[]> maxIndices(new Z[maxThreads]);
X* ptrMaxValues = maxValues.get();
Z* ptrMaxIndices = maxIndices.get();
auto func = [ptrMaxValues, ptrMaxIndices, inner_last, second_rank, inner_bases, inner_strides, bufferX](
uint64_t thread_id, int64_t start, int64_t stop, int64_t increment) -> void {
// LOG_CALLS(0)
const sd::LongType inner_stride = LastIndexFaster ? inner_strides[second_rank - 1] : inner_strides[0];
Z argCurrent;
X current;
if (second_rank == 1) {
const sd::LongType loopTotal = stop - start;
if (inner_stride == 1) {
indexInnerReductionRank1Block4WithMerge<X, Z, ReductionOp>(&(bufferX[start]), current, argCurrent, loopTotal);
} else {
indexInnerReductionRank1Block4WithMerge<X, Z, ReductionOp>(&(bufferX[start * inner_stride]), current,
argCurrent, loopTotal, inner_stride);
}
ptrMaxIndices[thread_id] = argCurrent + start;
} else {
if (inner_stride == 1) {
indexInnerReduction<X, Z, ReductionOp, LastIndexFaster>(second_rank, bufferX, current, argCurrent, inner_bases,
inner_strides, start, stop, inner_last, inner_stride);
} else {
indexInnerReduction<X, Z, ReductionOp, LastIndexFaster>(second_rank, bufferX, current, argCurrent, inner_bases,
inner_strides, start, stop, inner_last, inner_stride);
}
ptrMaxIndices[thread_id] = argCurrent;
}
ptrMaxValues[thread_id] = current;
};
#if 0
int Count = 0;
func(0, 0, inner_total, 1);
#else
int Count = samediff::Threads::parallel_tad(func, 0, inner_total, 1, maxThreads);
#endif
Z arg = 0;
X current = ptrMaxValues[0];
for (Z i = 1; i < Count; i++) {
ReductionOp::update(current, arg, ptrMaxValues[i], i);
}
*outputZ = ptrMaxIndices[arg];
}
template <typename X, typename Z, typename ReductionOp, typename Movement, bool LastIndexFaster = true>
static void argReductionInnerCases(Movement& movement, sd::LongType loopTotal, const int& second_rank,
const sd::LongType* inner_bases, const sd::LongType* inner_strides, const X* bufferX,
Z* outputZ) {
sd::LongType inner_stride = true /*LastIndexFaster*/ ? inner_strides[second_rank - 1] : inner_strides[0];
sd::LongType loopTotal_K = loopTotal / 4;
sd::LongType loopTotal_Tail = loopTotal & 3;
if (inner_stride == 1) {
if (second_rank == 1) {
LOG_CALLS(0)
sd::LongType inner_total = getLength<true>(inner_bases, second_rank);
for (sd::LongType i = 0; i < loopTotal_K; i++) {
const X* buffer0 = &(bufferX[movement.First()]);
Z* output0 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer1 = &(bufferX[movement.First()]);
Z* output1 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer2 = &(bufferX[movement.First()]);
Z* output2 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer3 = &(bufferX[movement.First()]);
Z* output3 = &(outputZ[movement.Second()]);
movement.increment();
indexInnerReductionRank1Block4<X, Z, ReductionOp>(buffer0, buffer1, buffer2, buffer3, output0, output1, output2,
output3, inner_total);
}
if (inner_total >= 2048) {
for (sd::LongType i = 0; i < loopTotal_Tail; i++) {
X current;
const X* buffer0 = &(bufferX[movement.First()]);
indexInnerReductionRank1Block4WithMerge<X, Z, ReductionOp>(buffer0, current, outputZ[movement.Second()],
inner_total);
movement.increment();
}
} else {
for (sd::LongType i = 0; i < loopTotal_Tail; i++) {
X current;
const X* buffer0 = &(bufferX[movement.First()]);
indexInnerReductionRank1<X, Z, ReductionOp>(buffer0, current, outputZ[movement.Second()], inner_total);
movement.increment();
}
}
} else {
sd::LongType inner_last;
sd::LongType inner_loop = getLength<true>(inner_bases, second_rank, 1, inner_last);
if (second_rank == 2) {
LOG_CALLS(1)
for (sd::LongType i = 0; i < loopTotal_K; i++) {
const X* buffer0 = &(bufferX[movement.First()]);
Z* output0 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer1 = &(bufferX[movement.First()]);
Z* output1 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer2 = &(bufferX[movement.First()]);
Z* output2 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer3 = &(bufferX[movement.First()]);
Z* output3 = &(outputZ[movement.Second()]);
movement.increment();
indexInnerReductionConstRankBlock4<X, Z, ReductionOp, 2>(buffer0, buffer1, buffer2, buffer3, output0, output1,
output2, output3, inner_bases, inner_strides,
inner_loop, inner_last);
}
for (sd::LongType i = 0; i < loopTotal_Tail; i++) {
X current;
const X* buffer0 = &(bufferX[movement.First()]);
indexInnerReductionConstRank<X, Z, ReductionOp, 2>(buffer0, current, outputZ[movement.Second()], inner_bases,
inner_strides, inner_loop, inner_last);
movement.increment();
}
} else if (second_rank == 3) {
LOG_CALLS(2)
for (sd::LongType i = 0; i < loopTotal_K; i++) {
const X* buffer0 = &(bufferX[movement.First()]);
Z* output0 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer1 = &(bufferX[movement.First()]);
Z* output1 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer2 = &(bufferX[movement.First()]);
Z* output2 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer3 = &(bufferX[movement.First()]);
Z* output3 = &(outputZ[movement.Second()]);
movement.increment();
indexInnerReductionConstRankBlock4<X, Z, ReductionOp, 3>(buffer0, buffer1, buffer2, buffer3, output0, output1,
output2, output3, inner_bases, inner_strides,
inner_loop, inner_last);
}
for (sd::LongType i = 0; i < loopTotal_Tail; i++) {
X current;
const X* buffer0 = &(bufferX[movement.First()]);
indexInnerReductionConstRank<X, Z, ReductionOp, 3>(buffer0, current, outputZ[movement.Second()], inner_bases,
inner_strides, inner_loop, inner_last);
movement.increment();
}
} else {
LOG_CALLS(3)
// sd_printf("-----%d \n", loopTotal);
for (sd::LongType i = 0; i < loopTotal; i++) {
X current;
const X* buffer0 = &(bufferX[movement.First()]);
indexInnerReduction<X, Z, ReductionOp>(second_rank, buffer0, current, outputZ[movement.Second()], inner_bases,
inner_strides, 0, inner_loop, inner_last);
movement.increment();
}
}
}
} else {
if (second_rank == 1) {
LOG_CALLS(10)
sd::LongType inner_total = getLength<true>(inner_bases, second_rank);
for (sd::LongType i = 0; i < loopTotal_K; i++) {
const X* buffer0 = &(bufferX[movement.First()]);
Z* output0 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer1 = &(bufferX[movement.First()]);
Z* output1 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer2 = &(bufferX[movement.First()]);
Z* output2 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer3 = &(bufferX[movement.First()]);
Z* output3 = &(outputZ[movement.Second()]);
movement.increment();
indexInnerReductionRank1Block4<X, Z, ReductionOp>(buffer0, buffer1, buffer2, buffer3, output0, output1, output2,
output3, inner_total, inner_stride);
}
if (inner_total >= 2048) {
for (sd::LongType i = 0; i < loopTotal_Tail; i++) {
X current;
const X* buffer0 = &(bufferX[movement.First()]);
indexInnerReductionRank1Block4WithMerge<X, Z, ReductionOp>(buffer0, current, outputZ[movement.Second()],
inner_total, inner_stride);
movement.increment();
}
} else {
for (sd::LongType i = 0; i < loopTotal_Tail; i++) {
X current;
const X* buffer0 = &(bufferX[movement.First()]);
indexInnerReductionRank1<X, Z, ReductionOp>(buffer0, current, outputZ[movement.Second()], inner_total,
inner_stride);
movement.increment();
}
}
} else {
sd::LongType inner_last;
sd::LongType inner_loop = getLength<true>(inner_bases, second_rank, 1, inner_last);
if (second_rank == 2) {
LOG_CALLS(11)
for (sd::LongType i = 0; i < loopTotal_K; i++) {
const X* buffer0 = &(bufferX[movement.First()]);
Z* output0 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer1 = &(bufferX[movement.First()]);
Z* output1 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer2 = &(bufferX[movement.First()]);
Z* output2 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer3 = &(bufferX[movement.First()]);
Z* output3 = &(outputZ[movement.Second()]);
movement.increment();
indexInnerReductionConstRankBlock4<X, Z, ReductionOp, 2>(buffer0, buffer1, buffer2, buffer3, output0, output1,
output2, output3, inner_bases, inner_strides,
inner_loop, inner_last, inner_stride);
}
for (sd::LongType i = 0; i < loopTotal_Tail; i++) {
X current;
const X* buffer0 = &(bufferX[movement.First()]);
indexInnerReductionConstRank<X, Z, ReductionOp, 2>(buffer0, current, outputZ[movement.Second()], inner_bases,
inner_strides, inner_loop, inner_last, inner_stride);
movement.increment();
}
} else if (second_rank == 3) {
LOG_CALLS(12)
for (sd::LongType i = 0; i < loopTotal_K; i++) {
const X* buffer0 = &(bufferX[movement.First()]);
Z* output0 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer1 = &(bufferX[movement.First()]);
Z* output1 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer2 = &(bufferX[movement.First()]);
Z* output2 = &(outputZ[movement.Second()]);
movement.increment();
const X* buffer3 = &(bufferX[movement.First()]);
Z* output3 = &(outputZ[movement.Second()]);
movement.increment();
indexInnerReductionConstRankBlock4<X, Z, ReductionOp, 3>(buffer0, buffer1, buffer2, buffer3, output0, output1,
output2, output3, inner_bases, inner_strides,
inner_loop, inner_last, inner_stride);
}
for (sd::LongType i = 0; i < loopTotal_Tail; i++) {
X current;
const X* buffer0 = &(bufferX[movement.First()]);
indexInnerReductionConstRank<X, Z, ReductionOp, 3>(buffer0, current, outputZ[movement.Second()], inner_bases,
inner_strides, inner_loop, inner_last, inner_stride);
movement.increment();
}
} else {
LOG_CALLS(13)
// sd_printf("-------%d inner loop %d inner_last %d\n", loopTotal, inner_loop,inner_last);
for (sd::LongType i = 0; i < loopTotal; i++) {
X current;
const X* buffer0 = &(bufferX[movement.First()]);
indexInnerReduction<X, Z, ReductionOp>(second_rank, buffer0, current, outputZ[movement.Second()], inner_bases,
inner_strides, 0, inner_loop, inner_last, inner_stride);
movement.increment();
}
}
}
}
}
template <typename X, typename Z, typename ReductionOp, bool LastIndexFaster = true>
static void argIndexCaseNonScalar(const int& first_rank, const int& output_rank, bool squashed, const int& second_rank,
const sd::LongType*& outer_bases, const sd::LongType* outer_strides,
const sd::LongType* output_strides, const sd::LongType& output_stride,
const sd::LongType*& inner_bases, const sd::LongType* inner_strides, const X* bufferX,
Z* outputZ) {
sd::LongType total = getLength<LastIndexFaster>(outer_bases, first_rank);
sd::LongType inner_stride = true /*LastIndexFaster*/ ? inner_strides[second_rank - 1] : inner_strides[0];
sd::LongType outer_stride = LastIndexFaster ? outer_strides[second_rank - 1] : outer_strides[0];
auto func = [first_rank, output_rank, squashed, outer_bases, outer_strides, output_strides, output_stride,
second_rank, inner_bases, inner_strides, bufferX,
outputZ](uint64_t thread_id, int64_t start, int64_t stop, int64_t increment) -> void {
sd::LongType loopTotal = stop - start;
sd::LongType stride = LastIndexFaster ? outer_strides[first_rank - 1] : outer_strides[0];
if (first_rank == 1) {
if (stride == 1) {
ZipGenericCoordsRank1Stride1 movement;
movement.init(nullptr, nullptr, nullptr, 0, start);
argReductionInnerCases<X, Z, ReductionOp>(movement, loopTotal, second_rank, inner_bases, inner_strides, bufferX,
outputZ);
} else {
ZipGenericCoordsRank1BothStrideN movement;
movement.init(nullptr, &stride, &output_stride, 0, start);
argReductionInnerCases<X, Z, ReductionOp>(movement, loopTotal, second_rank, inner_bases, inner_strides, bufferX,
outputZ);
}
} else if (squashed && first_rank <= output_rank) {
if (first_rank == 2) {
if (output_stride == 1) {
ZipGenericCoordsConstMovementSecondStride1<2, LastIndexFaster> movement;
movement.init(outer_bases, outer_strides, nullptr, first_rank, start);
argReductionInnerCases<X, Z, ReductionOp>(movement, loopTotal, second_rank, inner_bases, inner_strides,
bufferX, outputZ);
} else {
ZipGenericCoordsConstMovementSecondStrideN<2, LastIndexFaster> movement;
movement.init(outer_bases, outer_strides, &output_stride, first_rank, start);
argReductionInnerCases<X, Z, ReductionOp>(movement, loopTotal, second_rank, inner_bases, inner_strides,
bufferX, outputZ);
}
} else if (first_rank == 3) {
if (output_stride == 1) {
ZipGenericCoordsConstMovementSecondStride1<3, LastIndexFaster> movement;
movement.init(outer_bases, outer_strides, nullptr, first_rank, start);
argReductionInnerCases<X, Z, ReductionOp>(movement, loopTotal, second_rank, inner_bases, inner_strides,
bufferX, outputZ);
} else {
ZipGenericCoordsConstMovementSecondStrideN<3, LastIndexFaster> movement;
movement.init(outer_bases, outer_strides, &output_stride, first_rank, start);
argReductionInnerCases<X, Z, ReductionOp>(movement, loopTotal, second_rank, inner_bases, inner_strides,
bufferX, outputZ);
}
} else {
ZipGenericCoordsMovementSecondStrideN<LastIndexFaster> movement;
movement.init(outer_bases, outer_strides, &output_stride, first_rank, start);
argReductionInnerCases<X, Z, ReductionOp>(movement, loopTotal, second_rank, inner_bases, inner_strides, bufferX,
outputZ);
}
} else {
ZipGenericCoordsMovement<LastIndexFaster> movement;
movement.init(outer_bases, outer_strides, output_strides, first_rank, start);
argReductionInnerCases<X, Z, ReductionOp>(movement, loopTotal, second_rank, inner_bases, inner_strides, bufferX,
outputZ);
}
};
#if 0
func(0, 0, total, 1);
#else
//
uint32_t numThreads = sd::Environment::getInstance().maxMasterThreads();
sd::LongType inner_total = getLength<true>(inner_bases, second_rank);
if (total * inner_total <= threadingThreshold) {
numThreads = 1;
} else {
if (inner_stride > outer_stride && total <= 256) {
auto desired = total > 4 ? (total / 4) : 1;
numThreads = numThreads > desired ? desired : numThreads;
}
}
samediff::Threads::parallel_tad(func, 0, total, 1, numThreads);
#endif
}
template <typename X, typename Z, typename ReductionOp>
SD_LIB_HIDDEN void argIndex_(const NDArray& input, NDArray& output, const std::vector<int>& dimensions) {
char input_order = input.ordering();
bool try_squash_outer = (input_order == output.ordering()) && output.ews() != 0;
const sd::LongType* input_shapeInfo = input.shapeInfo();
const sd::LongType* output_shapeInfo = output.shapeInfo();
const sd::LongType rank = input_shapeInfo[0];
const sd::LongType* input_bases = &(input_shapeInfo[1]);
const sd::LongType* input_strides = &(input_shapeInfo[rank + 1]);
const sd::LongType output_rank = output_shapeInfo[0];
const sd::LongType* output_strides = &(output_shapeInfo[output_rank + 1]);
sd::LongType new_bases[SD_MAX_RANK];
sd::LongType new_strides[SD_MAX_RANK];
int first_begin, first_end, second_begin, second_end;
// rePartition into two parts based on the selection
rePartition(input_order, dimensions, rank, input_bases, input_strides, new_bases, new_strides, first_begin, first_end,
second_begin, second_end, try_squash_outer, input_order == 'c');
int first_rank = first_end - first_begin; // the first rank can be 0 for scalar cases
int second_rank = second_end - second_begin;
auto bufferX = input.bufferAsT<X>();
auto outputZ = output.bufferAsT<Z>();
const sd::LongType* outer_bases = &(new_bases[first_begin]);
const sd::LongType* outer_strides = &(new_strides[first_begin]);
const sd::LongType* inner_bases = &(new_bases[second_begin]);
const sd::LongType* inner_strides = &(new_strides[second_begin]);
const sd::LongType output_stride = output.ordering() == 'c' ? output_strides[output_rank - 1] : output_strides[0];
if (input_order == 'c') {
if (first_rank == 0) {
argIndexCase1Scalar<X, Z, ReductionOp>(second_rank, inner_bases, inner_strides, bufferX, outputZ);
} else {
argIndexCaseNonScalar<X, Z, ReductionOp>(first_rank, output_rank, try_squash_outer, second_rank, outer_bases,
outer_strides, output_strides, output_stride, inner_bases, inner_strides,
bufferX, outputZ);
}
} else {
if (first_rank == 0) {
LOG_CALLS(0);
if (second_rank == 1) {
argIndexCase1Scalar<X, Z, ReductionOp, false>(second_rank, inner_bases, inner_strides, bufferX, outputZ);
} else {
argIndexCase1Scalar<X, Z, ReductionOp, true>(second_rank, inner_bases, inner_strides, bufferX, outputZ);
}
} else {
LOG_CALLS(1);
argIndexCaseNonScalar<X, Z, ReductionOp, false>(first_rank, output_rank, try_squash_outer, second_rank,
outer_bases, outer_strides, output_strides, output_stride,
inner_bases, inner_strides, bufferX, outputZ);
}
}
}
template <typename X, typename Z>
struct IndexMax {
static SD_INLINE void update(X& current, Z& currentIndex, const X& candidate, const Z& candidateIndex) {
if (candidate > current) {
current = candidate;
currentIndex = candidateIndex;
}
}
};
template <typename X, typename Z>
struct IndexMin {
static SD_INLINE void update(X& current, Z& currentIndex, const X& candidate, const Z& candidateIndex) {
if (candidate < current) {
current = candidate;
currentIndex = candidateIndex;
}
}
};
template <typename X, typename Z>
struct IndexAbsMax {
static SD_INLINE void update(X& current, Z& currentIndex, const X& candidate, const Z& candidateIndex) {
auto absCandidate = sd::math::sd_abs<X>(candidate);
if (absCandidate > current) {
current = absCandidate;
currentIndex = candidateIndex;
}
}
};
template <typename X, typename Z>
struct IndexAbsMin {
static SD_INLINE void update(X& current, Z& currentIndex, const X& candidate, const Z& candidateIndex) {
auto absCandidate = sd::math::sd_abs<X>(candidate);
if (absCandidate < current) {
current = absCandidate;
currentIndex = candidateIndex;
}
}
};
//////////////////////////////////////////////////////////////////////////
template <typename X, typename Z>
SD_LIB_HIDDEN void argMax_(const NDArray& input, NDArray& output, const std::vector<int>& dimensions) {
return argIndex_<X, Z, IndexMax<X, Z>>(input, output, dimensions);
}
template <typename X, typename Z>
SD_LIB_HIDDEN void argMin_(const NDArray& input, NDArray& output, const std::vector<int>& dimensions) {
return argIndex_<X, Z, IndexMin<X, Z>>(input, output, dimensions);
}
template <typename X, typename Z>
SD_LIB_HIDDEN void argAbsMax_(const NDArray& input, NDArray& output, const std::vector<int>& dimensions) {
return argIndex_<X, Z, IndexAbsMax<X, Z>>(input, output, dimensions);
}
template <typename X, typename Z>
SD_LIB_HIDDEN void argAbsMin_(const NDArray& input, NDArray& output, const std::vector<int>& dimensions) {
return argIndex_<X, Z, IndexAbsMin<X, Z>>(input, output, dimensions);
}
} // namespace helpers
} // namespace ops
} // namespace sd
| 45.699889 | 120 | 0.613081 | steljord2 |
2fff5d5a1f67ca52bd17486a69e8e7b2188919cf | 4,437 | cpp | C++ | CPM/SlabSpectrumCode.cpp | FrancisKhan/ALMOST | 06e36666ca18aa06167baac3123dbbe913f74b5d | [
"MIT"
] | 5 | 2020-12-20T15:37:59.000Z | 2021-03-18T18:11:17.000Z | CPM/SlabSpectrumCode.cpp | FrancisKhan/ALMOST | 06e36666ca18aa06167baac3123dbbe913f74b5d | [
"MIT"
] | null | null | null | CPM/SlabSpectrumCode.cpp | FrancisKhan/ALMOST | 06e36666ca18aa06167baac3123dbbe913f74b5d | [
"MIT"
] | null | null | null | #include "BaseSpectrumCode.h"
#include "SlabSpectrumCode.h"
#include "numeric_tools.h"
#include <boost/math/special_functions/expint.hpp>
#include <iostream>
using namespace Eigen;
using namespace Numerics;
using namespace PrintFuncs;
using namespace boost::math;
std::pair<Tensor3d, Tensor4d> SlabSpectrumCode::calcTracks()
{
Tensor4d tau = Tensor4d(m_cells, m_cells, m_rays, m_energies);
tau.setZero();
Tensor3d zz(m_cells, m_cells, m_rays);
zz.setZero();
std::vector<double> delta(m_radii.size() - 1, 0.0);
for(size_t i = 0; i < delta.size(); i++)
{
delta[i] = m_radii[i + 1] - m_radii[i];
}
for(int h = 0; h < m_energies; h++)
for(int i = 0; i < m_cells; i++)
for(int j = i; j < m_cells; j++)
{
if (i == j)
tau(i, j, 0, h) = delta[i] * m_totalXS(h, i);
else
{
if (i == 0)
tau(i, j, 0, h) = delta[j] * m_totalXS(h, j) + tau(0, j - 1, 0, h);
else
tau(i, j, 0, h) = delta[j] * m_totalXS(h, j)
+ tau(0, j - 1, 0, h) - tau(0, i - 1, 0, h);
}
}
for(int h = 0; h < m_energies; h++)
for(int i = 0; i < m_cells; i++)
for(int j = i; j < m_cells; j++)
{
if (i != j) tau(i, j, 0, h) -= delta[j] * m_totalXS(h, j) + delta[i] * m_totalXS(h, i);
if (tau(i, j, 0, h) < 0.0) tau(i, j, 0, h) = 0.0;
out.print(TraceLevel::TRACE, "Tau: {:3d} {:3d} {:3d} {:5.4f}", h, i, j, tau(i, j, 0, h));
}
std::pair<Tensor3d, Tensor4d> trackData = std::make_pair(zz, tau);
return trackData;
}
Tensor3d SlabSpectrumCode::calcCPs(std::pair<Tensor3d, Tensor4d> &trackData)
{
Tensor4d tau = trackData.second;
Tensor3d gcpm = Tensor3d(m_cells, m_cells, m_energies);
gcpm.setZero();
Tensor3d CSet1(m_cells, m_cells, m_cells);
Tensor3d CSet2(m_cells, m_cells, m_cells);
MatrixXd P = MatrixXd::Zero(m_cells, m_cells);
for(int h = 0; h < m_energies; h++)
{
for(int i = 0; i < m_cells; i++)
for(int j = i; j < m_cells; j++)
{
if (j == i)
P(i, j) = 1.0 - (1.0 / (2.0 * tau(i, i, 0, h))) * (1.0 - 2.0 * expint(3, tau(i, i, 0, h)));
else
P(i, j) = (1.0 / (2.0 * tau(i, i, 0, h))) * (expint(3, tau(i, j, 0, h))
- expint(3, tau(i, j, 0, h) + tau(i, i, 0, h))
- expint(3, tau(i, j, 0, h) + tau(j, j, 0, h))
+ expint(3, tau(i, j, 0, h) + tau(j, j, 0, h) + tau(i, i, 0, h)));
}
for(int i = 0; i < m_cells; i++)
for(int j = i + 1; j < m_cells; j++)
P(j, i) = P(i, j) * (m_totalXS(h, i) / m_totalXS(h, j)) * (m_volumes(i) / m_volumes(j));
for(int i = 0; i < m_cells; i++)
for(int j = 0; j < m_cells; j++)
gcpm(i, j, h) = P(i, j);
}
out.print(TraceLevel::INFO, "P matrix (vacuum BC)");
printMatrix(gcpm, out, TraceLevel::INFO, "Group");
return gcpm;
}
void SlabSpectrumCode::applyBoundaryConditions(Tensor3d &gcpm)
{
for(int h = 0; h < m_energies; h++)
{
out.print(TraceLevel::INFO, "Apply boundary conditions Group {}", h + 1);
double albedo = m_solverData.getAlbedo()[0];
VectorXd Pis = VectorXd::Zero(m_cells);
VectorXd psi = VectorXd::Zero(m_cells);
Pis.setZero();
psi.setZero();
for(int i = 0; i < m_cells; i++)
{
for(int j = 0; j < m_cells; j++)
{
gcpm(i, j, h) /= m_totalXS(h, j); //reduced
}
}
for(int i = 0; i < m_cells; i++)
{
for(int j = 0; j < m_cells; j++)
{
Pis(i) += gcpm(i, j, h) * m_totalXS(h, j);
}
Pis(i) = 1.0 - Pis(i);
psi(i) = (4.0 * m_volumes(i) / m_surface) * Pis(i);
out.print(TraceLevel::INFO, "Cell n: {} Pis: {:7.6e} psi [cm]: {:7.6e}", i, Pis(i), psi(i));
}
double Pss = 0.0;
for(int i = 0; i < m_cells; i++)
{
Pss += psi(i) * m_totalXS(h, i);
}
Pss = 1.0 - Pss;
out.print(TraceLevel::INFO, "Pss [cm2]: {:7.6e} \n", Pss);
for(int i = 0; i < m_cells; i++)
{
for(int j = 0; j < m_cells; j++)
{
gcpm(i, j, h) += Pis(i) * psi(j) * (albedo / (1.0 - Pss * albedo));
gcpm(i, j, h) *= m_totalXS(h, j);
}
}
}
out.print(TraceLevel::INFO, "P matrix (white BC)");
printMatrix(gcpm, out, TraceLevel::INFO, "Group");
for(int h = 0; h < m_energies; h++)
{
for(int i = 0; i < m_cells; i++)
{
for(int j = 0; j < m_cells; j++)
{
gcpm(i, j, h) /= m_totalXS(h, j);
}
}
}
}
| 26.254438 | 103 | 0.506874 | FrancisKhan |
6402960a16739f7901cfd5a7baac7cf3bb5ff7bc | 5,847 | cc | C++ | cpp/normalize.cc | streamcorpus/streamcorpus-filter | 7687aa25260d95b861efa63d7369e6dcd6bb20a4 | [
"MIT"
] | 1 | 2015-11-13T15:48:23.000Z | 2015-11-13T15:48:23.000Z | cpp/normalize.cc | streamcorpus/streamcorpus-filter | 7687aa25260d95b861efa63d7369e6dcd6bb20a4 | [
"MIT"
] | null | null | null | cpp/normalize.cc | streamcorpus/streamcorpus-filter | 7687aa25260d95b861efa63d7369e6dcd6bb20a4 | [
"MIT"
] | null | null | null |
#include <assert.h>
#include <ctype.h>
#include <stddef.h>
#include "normalize.h"
// icu
//#include <normalizer2.h>
#if HAVE_ICU
#include <unicode/normalizer2.h>
#include <unicode/unistr.h>
#include <unicode/utypes.h>
#include <vector>
#include <iostream>
using std::vector;
using std::cerr;
using std::endl;
using icu::Normalizer2;
using icu::UnicodeString;
static const Normalizer2* norm = NULL;
// strip accents, lowercase
// offsets could be weird, e.g. there's a 'fi' glyph that will expand into "fi"
int lesserUnicodeString(const icu::UnicodeString& in, icu::UnicodeString* out, vector<size_t>* offsets, bool squashSpace ) {
if (norm == NULL) {
UErrorCode uerr = U_ZERO_ERROR;
norm = icu::Normalizer2::getInstance(NULL, "nfkc", UNORM2_DECOMPOSE, uerr);
if ((norm == NULL) || U_FAILURE(uerr)) {
cerr << u_errorName(uerr) << endl;
return -1;
}
}
bool wasSpace = true;
int32_t len = in.countChar32();
for (int32_t i = 0; i < len; i++) {
UChar32 c = in.char32At(i);
if (norm->isInert(c)) {
if (u_isspace(c)) {
if (wasSpace) {
// drop redundant space
continue;
}
wasSpace = true;
// fall through to outputting the first space normally
c = ' ';
} else {
wasSpace = false;
}
if (out != NULL) {
(*out) += u_tolower(c);
}
if (offsets != NULL) {
offsets->push_back(i);
}
} else {
UnicodeString texpand;
norm->getDecomposition(c, texpand);
int32_t exlen = texpand.countChar32();
for (int32_t xi = 0; xi < exlen; xi++) {
UChar32 xc = texpand.char32At(xi);
if (u_getCombiningClass(xc) == 0) {
if (u_isspace(xc)) {
if (wasSpace) {
// drop redundant space
continue;
}
wasSpace = true;
// fall through to outputting the first space normally
xc = ' ';
} else {
wasSpace = false;
}
if (out != NULL) {
(*out) += u_tolower(xc);
}
if (offsets != NULL) {
offsets->push_back(i);
}
}
}
}
}
return 0;
}
int lesserUTF8String(const std::string& in, std::string* out, vector<size_t>* offsets, vector<size_t>* sourceByteToUCharIndex) {
// We reach into the utf8 decoding manually here so that we can
// track byte offsets.
int errout = 0;
UnicodeString raw;
vector<int32_t> rawOffsets; // maps utf32 pos to utf8 byte offset
{
int32_t pos = 0;
int32_t length = in.size();
const uint8_t* utf8 = (const uint8_t*)in.data();
UChar32 c;
while (pos < length) {
int32_t prevpos = pos;
U8_NEXT(utf8, pos, length, c);
if (((int32_t)c) < 0) {
// report that there was an error, but try to process as much data as possible
errout = -1;
break;
}
if (offsets != NULL) {
rawOffsets.push_back(prevpos);
}
if (sourceByteToUCharIndex != NULL) {
int32_t sbipos = prevpos;
while (sbipos < pos) {
sourceByteToUCharIndex->push_back(raw.length());
sbipos++;
}
}
raw += c;
}
}
vector<size_t> uuoffsets; // maps intermediate utf32 to source utf32
UnicodeString cooked;
int decomposeErr = lesserUnicodeString(raw, &cooked, (offsets != NULL) ? &uuoffsets : NULL);
if (decomposeErr != 0) { errout = decomposeErr; }
// convert back to UTF8, write out final offset mapping
{
uint8_t u8buf[5] = {'\0','\0','\0','\0','\0'};
int32_t pos;
int32_t capacity = 5;
UChar32 c;
UBool err;
int32_t cookedlen = cooked.countChar32();
for (int32_t i = 0; i < cookedlen; i++) {
c = cooked.char32At(i);
pos = 0;
U8_APPEND(u8buf, pos, capacity, c, err);
u8buf[pos] = '\0';
(*out) += (char*)u8buf;
if (offsets != NULL) {
// map offset all the way back through source
size_t offset = rawOffsets[uuoffsets[i]];
for (int32_t oi = 0; oi < pos; oi++) {
// every output byte gets a source offset
offsets->push_back(offset);
}
}
}
}
return errout;
}
#else
#warning "compliing without ICU, which makes unicode possible. you should really go get ICU. http://icu-project.org/"
#endif /* HAVE_ICU */
enum State {
initial = 0,
normal,
space,
lastState
};
// semi-depricated. ICU library is preferred for unicode handling.
// orig: original text
// len: length of that text
// offsets: size_t[len] for offsets output
// out: char[len] for normalized text output
size_t normalize(const char* orig, size_t len, size_t* offsets, char* out) {
size_t outi = 0;
State state = initial;
for (size_t i = 0; i < len; i++) {
char c = orig[i];
if (isspace(c) || (c == '.')) {
switch (state) {
case initial:
// drop leading space, remain in initial state
break;
case normal:
// transition into a run of space, emit one space
state = space;
out[outi] = ' ';
offsets[outi] = i;
outi++;
break;
case space:
// drop redundant space
break;
case lastState:
default:
assert(0); // never get here
}
} else {
state = normal;
out[outi] = tolower(orig[i]);
offsets[outi] = i;
outi++;
}
}
return outi;
}
int normalize(const std::string& orig, std::string* out, std::vector<size_t>* offsets, vector<size_t>* sourceByteToUCharIndex) {
#if HAVE_ICU
return lesserUTF8String(orig, out, offsets, sourceByteToUCharIndex);
#else
// fall back to ye olde C and ASCII way
size_t origlen = orig.size();
char* tmpout = new char[origlen];
size_t* offsetA = new size_t[origlen];
size_t outlen = normalize(orig.data(), origlen, offsetA, tmpout);
(*out) = std::string(tmpout, outlen);
if (offsets != NULL) {
for (int i = 0; i < outlen; i++) {
offsets->push_back(offsetA[i]);
}
}
delete [] tmpout;
delete [] offsetA;
return 0;
#endif
}
| 24.880851 | 128 | 0.601676 | streamcorpus |
6408e3aa3f1b0a96ed2553fffb6042fbcf4c2c49 | 5,304 | cpp | C++ | src/test/SlamManagerTest.cpp | AlexeyMerzlyakov/lpslam | e473de4f53c49d2fc3cc123758d0ac987afdabbd | [
"Apache-2.0"
] | 4 | 2021-05-27T21:42:46.000Z | 2022-03-07T04:47:13.000Z | src/test/SlamManagerTest.cpp | AlexeyMerzlyakov/lpslam | e473de4f53c49d2fc3cc123758d0ac987afdabbd | [
"Apache-2.0"
] | 1 | 2021-11-17T08:42:43.000Z | 2021-12-07T03:11:11.000Z | src/test/SlamManagerTest.cpp | AlexeyMerzlyakov/lpslam | e473de4f53c49d2fc3cc123758d0ac987afdabbd | [
"Apache-2.0"
] | 2 | 2021-09-05T11:02:12.000Z | 2021-11-16T01:17:23.000Z |
#include "Manager/SlamManager.h"
#include "Interface/LpSlamTypes.h"
#include <gtest/gtest.h>
#include <string>
#include <sstream>
using namespace LpSlam;
// make sure providing wrong json config is handled
// properly
TEST(slam_manager, read_config_file)
{
const std::string testJsonConfigFile = "lpgf_unitttest_config_file.json";
{
// no config provided
SlamManager fm;
ASSERT_FALSE(fm.readConfigurationFile("does_not_exist.json"));
}
{
SlamManager fm;
nlohmann::json j_test_datasource = {
{"datasources", { {
{ "type", "FileSource" }}
}
} };
{
std::ofstream o(testJsonConfigFile);
o << std::setw(4) << j_test_datasource << std::endl;
o.close();
}
ASSERT_TRUE(fm.readConfigurationFile(testJsonConfigFile));
}
{
SlamManager fm;
{
std::ofstream o(testJsonConfigFile);
o << std::setw(4) << "datasources {{" << std::endl;
o.close();
}
// syntax error in Json
ASSERT_FALSE(fm.readConfigurationFile(testJsonConfigFile));
}
{
SlamManager fm;
nlohmann::json j_test_datasource = {
{"datasources", { {
{ "type", "FileSource" },
{ "configuration",
{
{ "file_names" , "blah"}
}
}
}
}
} };
{
std::ofstream o(testJsonConfigFile);
o << std::setw(4) << j_test_datasource << std::endl;
o.close();
}
ASSERT_TRUE(fm.readConfigurationFile(testJsonConfigFile));
}
}
TEST(slam_manager, read_camera_calibration)
{
const std::string testJsonConfigFile = "lpgf_unitttest_config_file.json";
{
SlamManager fm;
nlohmann::json j_test_datasource = {
{"cameras", {
{
{ "number", 0 },
{ "model", "fisheye" },
{ "fx", 1.0},
{ "fy", 2.0},
{ "cx", 3.0},
{ "cy", 4.0},
{ "distortion", {10.0, 11.0, 12.0, 13.0 }},
{ "resolution_x", 320},
{ "resolution_y", 240}
},
{
{ "number", 1 },
{ "model", "perspective" },
{ "fx", 21.0},
{ "fy", 22.0},
{ "cx", 23.0},
{ "cy", 24.0},
{ "distortion", {110.0, 111.0, 112.0, 113.0, 114.0}},
{ "resolution_x", 320},
{ "resolution_y", 240}
}
}
}};
{
std::ofstream o(testJsonConfigFile);
o << std::setw(4) << j_test_datasource << std::endl;
o.close();
}
ASSERT_TRUE(fm.readConfigurationFile(testJsonConfigFile));
ASSERT_TRUE(fm.getCameraConfiguration(0).has_value());
ASSERT_TRUE(fm.getCameraConfiguration(1).has_value());
auto cam0 = fm.getCameraConfiguration(0).value();
auto cam1 = fm.getCameraConfiguration(1).value();
ASSERT_EQ(cam0.distortion_function, LpSlamCameraDistortionFunction_Fisheye);
ASSERT_NEAR(cam0.f_x, 1.0, 0.001);
ASSERT_NEAR(cam0.f_y, 2.0, 0.001);
ASSERT_NEAR(cam0.c_x, 3.0, 0.001);
ASSERT_NEAR(cam0.c_y, 4.0, 0.001);
ASSERT_NEAR(cam0.dist[0], 10.0, 0.001);
ASSERT_NEAR(cam0.dist[1], 11.0, 0.001);
ASSERT_NEAR(cam0.dist[2], 12.0, 0.001);
ASSERT_NEAR(cam0.dist[3], 13.0, 0.001);
ASSERT_EQ(cam1.distortion_function, LpSlamCameraDistortionFunction_Pinhole);
ASSERT_NEAR(cam1.f_x, 21.0, 0.001);
ASSERT_NEAR(cam1.f_y, 22.0, 0.001);
ASSERT_NEAR(cam1.c_x, 23.0, 0.001);
ASSERT_NEAR(cam1.c_y, 24.0, 0.001);
ASSERT_NEAR(cam1.dist[0], 110.0, 0.001);
ASSERT_NEAR(cam1.dist[1], 111.0, 0.001);
ASSERT_NEAR(cam1.dist[2], 112.0, 0.001);
ASSERT_NEAR(cam1.dist[3], 113.0, 0.001);
ASSERT_NEAR(cam1.dist[4], 114.0, 0.001);
}
// too many parameters in distortion
{
SlamManager fm;
nlohmann::json j_test_datasource = {
{"cameras", {
{
{ "number", 0 },
{ "model", "fisheye" },
{ "fx", 1.0},
{ "fy", 2.0},
{ "cx", 3.0},
{ "cy", 4.0},
{ "distortion", {10.0, 11.0, 12.0, 13.0, 34.0, 23.02, 2.3 }},
}
}}};
{
std::ofstream o(testJsonConfigFile);
o << std::setw(4) << j_test_datasource << std::endl;
o.close();
}
ASSERT_FALSE(fm.readConfigurationFile(testJsonConfigFile));
}
// unknown camera model
{
SlamManager fm;
nlohmann::json j_test_datasource = {
{"cameras", {
{
{ "number", 0 },
{ "model", "what_!?" },
{ "fx", 1.0},
{ "fy", 2.0},
{ "cx", 3.0},
{ "cy", 4.0},
{ "distortion", {10.0, 11.0, 12.0}},
}
}}};
{
std::ofstream o(testJsonConfigFile);
o << std::setw(4) << j_test_datasource << std::endl;
o.close();
}
ASSERT_FALSE(fm.readConfigurationFile(testJsonConfigFile));
}
} | 26.787879 | 84 | 0.49227 | AlexeyMerzlyakov |
6409e68ce5c1b3308fd36d1367609cc3a1ac8fbb | 392 | hpp | C++ | include/clpp/map_access.hpp | Robbepop/clpp | 7723bb68c55d861ac2135ccf84d3c5b92b2b2b50 | [
"MIT"
] | 5 | 2015-09-08T01:59:26.000Z | 2018-11-26T10:19:29.000Z | include/clpp/map_access.hpp | Robbepop/clpp | 7723bb68c55d861ac2135ccf84d3c5b92b2b2b50 | [
"MIT"
] | 6 | 2015-11-29T03:00:11.000Z | 2015-11-29T03:11:52.000Z | include/clpp/map_access.hpp | Robbepop/clpp | 7723bb68c55d861ac2135ccf84d3c5b92b2b2b50 | [
"MIT"
] | null | null | null | #ifndef CLPP_MAP_ACCESS_HPP
#define CLPP_MAP_ACCESS_HPP
#include "clpp/detail/common.hpp"
namespace cl {
enum class MapAccess : cl_map_flags {
read = CL_MAP_READ
, write = CL_MAP_WRITE
, readWrite = CL_MAP_READ | CL_MAP_WRITE
#if defined(CL_VERSION_1_2)
, writeInvalidateRegion = CL_MAP_WRITE_INVALIDATE_REGION
#endif
};
}
#endif
| 21.777778 | 58 | 0.67602 | Robbepop |
640a44df0c5786d5b2701bcc72f0a14a0b2f89bd | 829 | cc | C++ | kth-smallest-element-in-a-sorted-matrix.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | kth-smallest-element-in-a-sorted-matrix.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | kth-smallest-element-in-a-sorted-matrix.cc | ArCan314/leetcode | 8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd | [
"MIT"
] | null | null | null | #include <vector>
class Solution
{
public:
int kthSmallest(std::vector<std::vector<int>> &matrix, int k)
{
std::vector<int> pos(matrix.size(), 0);
int res = 0;
for (int i = 0; i < k; i++)
{
int min_ind = -1;
for (int j = 0; j < pos.size(); j++)
{
if (min_ind == -1 && pos[j] < matrix.front().size())
min_ind = j;
else if (min_ind >= 0 && matrix[j][pos[j]] < matrix[min_ind][pos[min_ind]])
min_ind = j;
// std::cout << "min_ind: " << min_ind << ", j:" << j << std::endl;
}
// std::cout << i << ", " << min_ind << std::endl;
res = matrix[min_ind][pos[min_ind]];
pos[min_ind]++;
}
return res;
}
}; | 28.586207 | 91 | 0.408926 | ArCan314 |
640ae043eeef8995bda27b9f94ef630cb19df36f | 3,531 | hpp | C++ | orca_shared/include/orca_shared/mw/observation.hpp | clydemcqueen/orca2 | 9a8add5e65201e84af19f037c187d0ce6ec702e3 | [
"BSD-3-Clause"
] | 9 | 2019-07-08T08:55:34.000Z | 2020-11-23T16:57:41.000Z | orca_shared/include/orca_shared/mw/observation.hpp | clydemcqueen/orca2 | 9a8add5e65201e84af19f037c187d0ce6ec702e3 | [
"BSD-3-Clause"
] | 11 | 2019-06-01T00:25:18.000Z | 2021-02-06T18:15:58.000Z | orca_shared/include/orca_shared/mw/observation.hpp | clydemcqueen/orca2 | 9a8add5e65201e84af19f037c187d0ce6ec702e3 | [
"BSD-3-Clause"
] | 3 | 2019-07-19T10:26:34.000Z | 2020-02-03T09:14:08.000Z | // Copyright (c) 2020, Clyde McQueen.
// All rights reserved.
//
// Software License Agreement (BSD License 2.0)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef ORCA_SHARED__MW__OBSERVATION_HPP_
#define ORCA_SHARED__MW__OBSERVATION_HPP_
#include "fiducial_vlam_msgs/msg/observation.hpp"
#include "opencv2/core/types.hpp"
namespace mw
{
constexpr int NOT_A_MARKER = -1;
class Observation
{
int id_{NOT_A_MARKER};
cv::Point2d c0_;
cv::Point2d c1_;
cv::Point2d c2_;
cv::Point2d c3_;
public:
static const Observation None;
Observation() = default;
explicit Observation(const fiducial_vlam_msgs::msg::Observation & msg)
{
id_ = msg.id;
c0_ = cv::Point2d{msg.x0, msg.y0};
c1_ = cv::Point2d{msg.x1, msg.y1};
c2_ = cv::Point2d{msg.x2, msg.y2};
c3_ = cv::Point2d{msg.x3, msg.y3};
}
Observation(
const int & id,
const cv::Point2d & c0, const cv::Point2d & c1, const cv::Point2d & c2, const cv::Point2d & c3)
: id_{id},
c0_{c0},
c1_{c1},
c2_{c2},
c3_{c3} {}
fiducial_vlam_msgs::msg::Observation msg() const
{
fiducial_vlam_msgs::msg::Observation msg;
msg.id = id_;
msg.x0 = c0_.x;
msg.y0 = c0_.y;
msg.x1 = c1_.x;
msg.y1 = c1_.y;
msg.x2 = c2_.x;
msg.y2 = c2_.y;
msg.x3 = c3_.x;
msg.y3 = c3_.y;
return msg;
}
const int & id() const
{
return id_;
}
const cv::Point2d & c0() const
{
return c0_;
}
const cv::Point2d & c1() const
{
return c1_;
}
const cv::Point2d & c2() const
{
return c2_;
}
const cv::Point2d & c3() const
{
return c3_;
}
bool operator==(const Observation & that) const
{
return id_ == that.id_ &&
c0_ == that.c0_ &&
c1_ == that.c1_ &&
c2_ == that.c2_ &&
c3_ == that.c3_;
}
bool operator!=(const Observation & that) const
{
return !(*this == that);
}
friend std::ostream & operator<<(std::ostream & os, const Observation & v);
};
} // namespace mw
#endif // ORCA_SHARED__MW__OBSERVATION_HPP_
| 26.155556 | 99 | 0.673464 | clydemcqueen |
640afb480f49cf8e501b89bd72d5f630eaaec055 | 6,377 | cpp | C++ | lib/1d/FinSolveUser.cpp | dcseal/finess | 766e583ae9e84480640c7c3b3c157bf40ab87fe4 | [
"BSD-3-Clause"
] | null | null | null | lib/1d/FinSolveUser.cpp | dcseal/finess | 766e583ae9e84480640c7c3b3c157bf40ab87fe4 | [
"BSD-3-Clause"
] | null | null | null | lib/1d/FinSolveUser.cpp | dcseal/finess | 766e583ae9e84480640c7c3b3c157bf40ab87fe4 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <iomanip>
#include "dog_math.h"
#include "stdlib.h"
#include "dogdefs.h"
#include "IniParams.h"
#include "StateVars.h"
using namespace std;
// ------------------------------------------------------------
// Function definitions
void ConSoln( const StateVars& Q );
// Stuff used for a single (Euler) step
void SetBndValues( StateVars& Q );
void BeforeStep(double dt, StateVars& Q );
void ConstructL(
dTensorBC2& aux,
dTensorBC2& q, // setbndy conditions modifies q
dTensorBC2& Lstar,
dTensorBC1& smax);
void AfterStep(double dt, StateVars& Q );
double GetCFL(double dt, double dtmax, const dTensorBC2& aux, const dTensorBC1& smax);
void BeforeFullTimeStep(double dt, const StateVars& Qold, StateVars& Qnew );
void AfterFullTimeStep (double dt, const StateVars& Qold, StateVars& Qnew );
// ------------------------------------------------------------
// ------------------------------------------------------------
// Example function that describes how the main time stepping loop works.
//
// This routine will terminate the code upon entrance.
// ------------------------------------------------------------
void FinSolveUser( StateVars& Qnew, double tend, double dtv[] )
{
dTensorBC2& qnew = Qnew.ref_q ();
dTensorBC2& aux = Qnew.ref_aux();
// Time stepping information
const double CFL_max = global_ini_params.get_max_cfl(); // max CFL number
const double CFL_target = global_ini_params.get_desired_cfl(); // target CFL number
double t = Qnew.get_t(); // Current time
double dt = dtv[1]; // Start with time step from last frame
double cfl = 0.0; // current CFL number
double dtmin = dt; // Counters for max and min time step taken
double dtmax = dt;
// Grid information
const int mx = qnew.getsize(1);
const int meqn = qnew.getsize(2);
const int maux = aux.getsize(2);
const int mbc = qnew.getmbc();
const int numel = qnew.numel();
// Maximum wave speed
dTensorBC1 smax(mx, mbc);
// Needed for rejecting a time step
StateVars Qold( t, mx, meqn, maux, mbc );
dTensorBC2& qold = Qold.ref_q();
dTensorBC2& auxold = Qold.ref_aux();
// Allocate storage for this solver
// Intermediate stages
StateVars Qstar( t, mx, meqn, maux, mbc );
dTensorBC2& qstar = Qstar.ref_q();
dTensorBC2& auxstar = Qstar.ref_aux();
// Right side for a MOL formulation:
dTensorBC2 Lstar(mx, meqn, mbc);
// ---------------------------------------------- //
// -- MAIN TIME STEPPING LOOP (for this frame) -- //
// ---------------------------------------------- //
int n_step = 0;
const int nv = global_ini_params.get_nv(); // Maximum allowable time steps
while (t<tend)
{
// initialize time step
int m_accept = 0;
n_step = n_step + 1;
// check if max number of time steps exceeded
if (n_step>nv)
{
cout << " Error in DogSolveUser.cpp: "<<
" Exceeded allowed # of time steps " << endl;
cout << " n_step = " << n_step << endl;
cout << " nv = " << nv << endl;
printf("Terminating program.\n" );
cout << endl;
exit(1);
}
// copy qnew into qold in case of rejecting a time step
Qold.copyfrom( Qnew );
// keep trying until we get time step that doesn't violate CFL condition
while (m_accept==0)
{
// set current time
Qnew.set_t( t );
double told = t;
if (told+dt > tend)
{ dt = tend - told; }
t = told + dt;
// Set initial maximum wave speed to zero
smax.setall(0.);
BeforeFullTimeStep(dt, Qold, Qnew);
// ----------------------------------------------------------------
//
// THIS IS WHERE THE USER-DEFINED TIME-STEPPING SCHEME
// SHOULD BE ADDED. IN THE DEFAULT FILE: DogSolveUser.cpp,
// THE PROGRAM WILL NOW RETURN AN ERROR MESSAGE.
//
// ----------------------------------------------------------------
cout << endl;
cout << " No user-defined time-stepping scheme has been defined yet. " << endl;
cout << " Copy $FINESS/lib/1d/DogSolveUser.cpp into the current " << endl;
cout << " directory and modify as needed." << endl << endl;
exit(1);
// ----------------------------------------------------------------
// do any extra work
AfterFullTimeStep(dt, Qold, Qnew );
// compute cfl number
cfl = GetCFL(dt, dtv[2], aux, smax);
// output time step information
if( global_ini_params.get_verbosity() )
{
cout << setprecision(3);
cout << "FinSolve1D ... Step" << setw(5) << n_step;
cout << " CFL =" << setw(6) << fixed << cfl;
cout << " dt =" << setw(11) << scientific << dt;
cout << " t =" << setw(11) << scientific << t <<endl;
}
// choose new time step
if (cfl>0.0)
{
dt = Min(dtv[2],dt*CFL_target/cfl);
dtmin = Min(dt,dtmin);
dtmax = Max(dt,dtmax);
}
else
{
dt = dtv[2];
}
// see whether to accept or reject this step
if (cfl<=CFL_max) // accept
{ m_accept = 1; }
else //reject
{
t = told;
if( global_ini_params.get_verbosity() )
{
cout<<"FinSolve1D rejecting step...";
cout<<"CFL number too large";
cout<<endl;
}
// copy qold into qnew
qnew.copyfrom( qold );
}
}
// compute (scalar) conservation values and print to file
SetBndValues( Qnew );
ConSoln ( Qnew );
}
// set initial time step for next call to DogSolve
dtv[1] = dt;
}
| 33.740741 | 91 | 0.476556 | dcseal |
640e99307016e080ef588472bf9b43881ab0020a | 4,354 | cpp | C++ | tests/stl/concept_check.cpp | Mogball/waterloop-wlib | 41890e0c1b12d0d1df8eecf84a466d4e1558fe9d | [
"MIT"
] | 2 | 2017-11-06T22:57:31.000Z | 2017-12-06T14:51:16.000Z | tests/stl/concept_check.cpp | Mogball/waterloop-wlib | 41890e0c1b12d0d1df8eecf84a466d4e1558fe9d | [
"MIT"
] | 43 | 2017-10-30T04:31:38.000Z | 2017-12-06T05:39:38.000Z | tests/stl/concept_check.cpp | Mogball/waterloop-wlib | 41890e0c1b12d0d1df8eecf84a466d4e1558fe9d | [
"MIT"
] | 8 | 2017-11-02T03:00:19.000Z | 2017-11-25T21:36:02.000Z | #include <gtest/gtest.h>
#include <wlib/strings/String.h>
#include <wlib/stl/Comparator.h>
#include <wlib/stl/HashMap.h>
#include <wlib/stl/OpenMap.h>
#include <wlib/stl/TreeMap.h>
#include <wlib/stl/ArrayList.h>
#include <wlib/stl/HashSet.h>
#include <wlib/stl/OpenSet.h>
#include <wlib/stl/TreeSet.h>
#include <wlib/stl/LinkedList.h>
#include <wlib/stl/Concept.h>
using namespace wlp;
TEST(concept_checks, check_comparator_concept) {
bool c = comparator_concept<comparator<int>, int>::value;
ASSERT_TRUE(c);
c = comparator_concept<hash<int, int>, int>::value;
ASSERT_FALSE(c);
}
TEST(concept_checks, check_is_comparator) {
ASSERT_TRUE((is_comparator<comparator<const char *>, const char *>()));
ASSERT_FALSE((is_comparator<equals<const char *>, const char *>()));
ASSERT_FALSE((is_comparator<hash<const char *, uint16_t>, const char *>()));
ASSERT_TRUE((is_comparator<reverse_comparator<char>, char>()));
ASSERT_FALSE((is_comparator<hash_map<uint16_t, uint16_t>, uint16_t>()));
}
TEST(concept_checks, check_has_size_val_type) {
bool c;
c = has_size_type<int>::value;
ASSERT_FALSE(c);
c = has_size_type<pair<int, int>>::value;
ASSERT_FALSE(c);
c = has_val_type<int>::value;
ASSERT_FALSE(c);
c = has_val_type<pair<int, int>>::value;
ASSERT_FALSE(c);
c = has_size_type<array_list<int>>::value;
ASSERT_TRUE(c);
c = has_size_type<hash_map<int, int>::iterator>::value;
ASSERT_TRUE(c);
c = has_val_type<hash_map<int, int>>::value;
ASSERT_TRUE(c);
c = has_val_type<array_list<int>::iterator>::value;
ASSERT_TRUE(c);
}
TEST(concept_checks, check_random_access_iterator_concept) {
bool c;
c = random_access_iterator_concept<int>::value;
ASSERT_FALSE(c);
c = random_access_iterator_concept<array_list<int>>::value;
ASSERT_FALSE(c);
c = random_access_iterator_concept<hash_map<int, int>::iterator>::value;
ASSERT_FALSE(c);
c = random_access_iterator_concept<array_list<int>::iterator>::value;
ASSERT_TRUE(c);
c = random_access_iterator_concept<array_list<int>::const_iterator>::value;
ASSERT_TRUE(c);
ASSERT_TRUE((is_random_access_iterator<array_list<int>::iterator>()));
ASSERT_TRUE((is_random_access_iterator<array_list<int>::const_iterator>()));
ASSERT_FALSE((is_random_access_iterator<hash_map<int, int>::iterator>()));
ASSERT_FALSE((is_random_access_iterator<hash_map<int, int>::const_iterator>()));
ASSERT_FALSE((is_random_access_iterator<open_map<int, int>::iterator>()));
ASSERT_FALSE((is_random_access_iterator<open_map<int, int>::const_iterator>()));
}
TEST(concept_checks, check_forward_iterator_concept) {
ASSERT_TRUE((is_iterator<hash_map<int, int>::iterator>()));
ASSERT_TRUE((is_iterator<hash_map<int, int>::const_iterator>()));
ASSERT_TRUE((is_iterator<open_map<int, int>::iterator>()));
ASSERT_TRUE((is_iterator<open_map<int, int>::const_iterator>()));
ASSERT_TRUE((is_iterator<array_list<int>::iterator>()));
ASSERT_TRUE((is_iterator<array_list<int>::const_iterator>()));
ASSERT_FALSE((is_iterator<array_list<int>>()));
ASSERT_FALSE((is_iterator<comparator<int>>()));
}
TEST(concept_checks, check_map_concept) {
ASSERT_TRUE((is_map<hash_map<int, int>>()));
ASSERT_TRUE((is_map<open_map<int, int>>()));
ASSERT_TRUE((is_map<tree_map<int, int>>()));
ASSERT_FALSE((is_map<int>()));
ASSERT_FALSE((is_map<array_list<int>>()));
}
TEST(concept_checks, check_set_concept) {
ASSERT_FALSE((is_set<array_list<int>>()));
ASSERT_FALSE((is_set<int>()));
ASSERT_TRUE((is_set<open_set<int>>()));
ASSERT_TRUE((is_set<hash_set<int>>()));
ASSERT_TRUE((is_set<tree_set<int>>()));
}
TEST(concept_checks, check_list_concept) {
ASSERT_FALSE((is_list<hash_map<int, int>>()));
ASSERT_FALSE((is_list<int>()));
ASSERT_FALSE((is_list<comparator<int>>()));
ASSERT_TRUE((is_list<array_list<int>>()));
ASSERT_TRUE((is_list<linked_list<int>>()));
}
TEST(concept_checks, check_string_concept) {
ASSERT_FALSE((is_string<array_list<char>>()));
ASSERT_FALSE((is_string<const char *>()));
ASSERT_FALSE((is_string<hash_map<char, char>>()));
ASSERT_TRUE((is_string<static_string<8>>()));
ASSERT_TRUE((is_string<static_string<32>>()));
ASSERT_TRUE((is_string<dynamic_string>()));
}
| 35.983471 | 84 | 0.703261 | Mogball |
640f35f24e39299c8c63bb8978e717a69721bccb | 430 | cpp | C++ | archive_cppthreads/thread_creation.cpp | kumar-parveen/csbits | a18c099dbde45a4e0dff0bced9986623b81089a6 | [
"MIT"
] | 1 | 2020-06-14T07:14:45.000Z | 2020-06-14T07:14:45.000Z | archive_cppthreads/thread_creation.cpp | kumar-parveen/csbits | a18c099dbde45a4e0dff0bced9986623b81089a6 | [
"MIT"
] | null | null | null | archive_cppthreads/thread_creation.cpp | kumar-parveen/csbits | a18c099dbde45a4e0dff0bced9986623b81089a6 | [
"MIT"
] | null | null | null | #include<iostream>
#include<thread>
using namespace std;
void fun(){
cout<< "fun function" << endl;
}
class FunObject{
public:
void operator()() const {
cout << "Fun Object" << endl;
}
};
int main(){
cout << endl;
thread t1(fun);
FunObject obj;
thread t2(obj);
thread t3([]{ cout<< "lambda function" << endl;});
t1.join();
t2.join();
t3.join();
cout << endl;
};
| 13.4375 | 54 | 0.534884 | kumar-parveen |
640f68e7ce0055e795b52ae3b4162f9d6c40c764 | 1,050 | cpp | C++ | Homework4/Q47/Source.cpp | DeepAQ/Cpp-Homework | 1ad64deb7b25ee35d01c3c9f8a873a54dfff2c21 | [
"MIT"
] | 1 | 2017-10-08T18:16:12.000Z | 2017-10-08T18:16:12.000Z | Homework4/Q47/Source.cpp | DeepAQ/Cpp-Homework | 1ad64deb7b25ee35d01c3c9f8a873a54dfff2c21 | [
"MIT"
] | null | null | null | Homework4/Q47/Source.cpp | DeepAQ/Cpp-Homework | 1ad64deb7b25ee35d01c3c9f8a873a54dfff2c21 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
class Point
{
public:
Point(int x, int y) : x(x), y(y) {}
void Output() const
{
cout << "(" << x << "," << y << ")";
}
double Distance(Point& p) const
{
return round(sqrt(pow(p.x - x, 2) + pow(p.y - y, 2)) * 100.0) / 100.0;
}
private:
int x, y;
};
class Triangle
{
public:
Triangle(Point &a, Point &b, Point &c) : a(a), b(b), c(c) {}
double Circum()
{
auto ab = a.Distance(b), bc = b.Distance(c), ac = a.Distance(c);
return (ab + bc < ac || ab + ac < bc || bc + ac < ab) ? 0 : (ab + bc + ac);
}
private:
Point a, b, c;
};
int main()
{
int x, y;
cin >> x >> y;
Point a(x, y);
cin >> x >> y;
Point b(x, y);
cin >> x >> y;
Point c(x, y);
a.Output();
cout << " ";
b.Output();
cout << " ";
c.Output();
cout << " ";
cout.setf(ios::showpoint);
cout.setf(ios::fixed);
cout.precision(2);
cout << a.Distance(b) << " " << a.Distance(c) << " " << b.Distance(c) << " ";
Triangle t(a, b, c);
auto z = t.Circum();
z == 0 ? cout << 0 : cout << z;
return 0;
} | 16.935484 | 78 | 0.506667 | DeepAQ |