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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c9529c4b9e99a13b2715677fa31104504797f9a0 | 3,025 | hpp | C++ | boost/histogram/make_profile.hpp | cpp-pm/boost | 38c6c8c07f2fcc42d573b10807fef27ec14930f8 | [
"BSL-1.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | boost/histogram/make_profile.hpp | cpp-pm/boost | 38c6c8c07f2fcc42d573b10807fef27ec14930f8 | [
"BSL-1.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | boost/histogram/make_profile.hpp | cpp-pm/boost | 38c6c8c07f2fcc42d573b10807fef27ec14930f8 | [
"BSL-1.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | // Copyright 2018 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_HISTOGRAM_MAKE_PROFILE_HPP
#define BOOST_HISTOGRAM_MAKE_PROFILE_HPP
#include <boost/histogram/accumulators/mean.hpp>
#include <boost/histogram/accumulators/weighted_mean.hpp>
#include <boost/histogram/fwd.hpp>
#include <boost/histogram/make_histogram.hpp>
/**
\file boost/histogram/make_profile.hpp
Collection of factory functions to conveniently create profiles.
Profiles are histograms which accept an additional sample and compute the mean of the
sample in each cell.
*/
namespace boost {
namespace histogram {
/**
Make profle from compile-time axis configuration.
@param axis First axis instance.
@param axes Other axis instances.
*/
template <typename Axis, typename... Axes, typename = detail::requires_axis<Axis>>
auto make_profile(Axis&& axis, Axes&&... axes) {
return make_histogram_with(profile_storage(), std::forward<Axis>(axis),
std::forward<Axes>(axes)...);
}
/**
Make profle from compile-time axis configuration which accepts weights.
@param axis First axis instance.
@param axes Other axis instances.
*/
template <typename Axis, typename... Axes, typename = detail::requires_axis<Axis>>
auto make_weighted_profile(Axis&& axis, Axes&&... axes) {
return make_histogram_with(weighted_profile_storage(), std::forward<Axis>(axis),
std::forward<Axes>(axes)...);
}
/**
Make profile from iterable range.
@param iterable Iterable range of axis objects.
*/
template <typename Iterable, typename = detail::requires_sequence_of_any_axis<Iterable>>
auto make_profile(Iterable&& iterable) {
return make_histogram_with(profile_storage(), std::forward<Iterable>(iterable));
}
/**
Make profile from iterable range which accepts weights.
@param iterable Iterable range of axis objects.
*/
template <typename Iterable, typename = detail::requires_sequence_of_any_axis<Iterable>>
auto make_weighted_profile(Iterable&& iterable) {
return make_histogram_with(weighted_profile_storage(),
std::forward<Iterable>(iterable));
}
/**
Make profile from iterator interval.
@param begin Iterator to range of axis objects.
@param end Iterator to range of axis objects.
*/
template <typename Iterator, typename = detail::requires_iterator<Iterator>>
auto make_profile(Iterator begin, Iterator end) {
return make_histogram_with(profile_storage(), begin, end);
}
/**
Make profile from iterator interval which accepts weights.
@param begin Iterator to range of axis objects.
@param end Iterator to range of axis objects.
*/
template <typename Iterator, typename = detail::requires_iterator<Iterator>>
auto make_weighted_profile(Iterator begin, Iterator end) {
return make_histogram_with(weighted_profile_storage(), begin, end);
}
} // namespace histogram
} // namespace boost
#endif
| 33.241758 | 88 | 0.745455 | cpp-pm |
c954364d0ef7fca47eadeb48c2eef07b91d08b14 | 2,943 | hpp | C++ | saga/saga/adaptors/register_workitem.hpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 5 | 2015-09-15T16:24:14.000Z | 2021-08-12T11:05:55.000Z | saga/saga/adaptors/register_workitem.hpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | null | null | null | saga/saga/adaptors/register_workitem.hpp | saga-project/saga-cpp | 7376c0de0529e7d7b80cf08b94ec484c2e56d38e | [
"BSL-1.0"
] | 3 | 2016-11-17T04:38:38.000Z | 2021-04-10T17:23:52.000Z | // Copyright (c) 2005-2010 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef SAGA_ADAPTORS_REGISTER_WORKITEM_HPP
#define SAGA_ADAPTORS_REGISTER_WORKITEM_HPP
#include <saga/saga/util.hpp>
#include <saga/saga/session.hpp>
#include <boost/date_time/posix_time/posix_time_duration.hpp>
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/system/error_code.hpp>
// suppress warnings about dependent classes not being exported from the dll
#if defined(BOOST_MSVC)
#pragma warning(push)
#pragma warning(disable: 4251 4231 4660)
#endif
namespace saga { namespace adaptors
{
///////////////////////////////////////////////////////////////////////////
// we use the boost::posix_time::ptime type for time representation
typedef boost::posix_time::ptime time_type;
// we use the boost::posix_time::time_duration type as the duration
// representation
typedef boost::posix_time::time_duration duration_type;
///////////////////////////////////////////////////////////////////////////
// This is the prototype of any work item to be registered with this
// interface. The function will be called as soon as the expiration time
// specified while registering is reached. This function will be called at
// most once, so re-occurring events need to be registered separately.
typedef TR1::function<void(boost::system::error_code const&)>
workitem_function;
///////////////////////////////////////////////////////////////////////////
typedef unsigned int workitem_cookie_handle;
///////////////////////////////////////////////////////////////////////////
// This is the main API for adaptors to register a work item to be executed
// at a certain point in time or after a certain amount of time
SAGA_EXPORT workitem_cookie_handle register_workitem(
workitem_function f, time_type const& expire_at,
saga::session const& s = saga::detail::get_the_session());
SAGA_EXPORT workitem_cookie_handle register_workitem(
workitem_function f, duration_type const& expire_from_now,
saga::session const& s = saga::detail::get_the_session());
///////////////////////////////////////////////////////////////////////////
// This is the API allowing to cancel the execution of a registered work
// item. Note, this will call the registered function but will get passed
// the error code 'booast::asio::error::operation_aborted'. If the
// referenced work item has already expired but not called yet it cannot
// be unregistered anymore and will be called with a success code.
SAGA_EXPORT void unregister_workitem(workitem_cookie_handle,
saga::session const& s = saga::detail::get_the_session());
}}
#if defined(BOOST_MSVC)
#pragma warning(pop)
#endif
#endif
| 41.450704 | 81 | 0.64526 | saga-project |
c9549e09b578d7f93590ce1251b08cb9fe01bf68 | 4,119 | cpp | C++ | marsyas-vamp/marsyas/src/marsyas/marsystems/Memory.cpp | jaouahbi/VampPlugins | 27c2248d1c717417fe4d448cdfb4cb882a8a336a | [
"Apache-2.0"
] | null | null | null | marsyas-vamp/marsyas/src/marsyas/marsystems/Memory.cpp | jaouahbi/VampPlugins | 27c2248d1c717417fe4d448cdfb4cb882a8a336a | [
"Apache-2.0"
] | null | null | null | marsyas-vamp/marsyas/src/marsyas/marsystems/Memory.cpp | jaouahbi/VampPlugins | 27c2248d1c717417fe4d448cdfb4cb882a8a336a | [
"Apache-2.0"
] | null | null | null | /*
** Copyright (C) 1998-2010 George Tzanetakis <gtzan@cs.uvic.ca>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "Memory.h"
#include "../common_source.h"
using std::cout;
using std::endl;
using std::ostringstream;
using namespace Marsyas;
Memory::Memory(mrs_string name):MarSystem("Memory",name)
{
end_ = 0;
counter_since_reset_ = 0;
addControls();
}
Memory::~Memory()
{
}
Memory::Memory(const Memory& a):MarSystem(a)
{
end_ = 0;
counter_since_reset_ = 0 ;
ctrl_reset_ = getctrl("mrs_bool/reset");
ctrl_memSize_ = getctrl("mrs_natural/memSize");
}
MarSystem*
Memory::clone() const
{
return new Memory(*this);
}
void
Memory::addControls()
{
addctrl("mrs_natural/memSize", 40, ctrl_memSize_);
setctrlState("mrs_natural/memSize", true);
addctrl("mrs_bool/reset", false, ctrl_reset_);
setctrlState("mrs_bool/reset", true);
}
void
Memory::myUpdate(MarControlPtr sender)
{
(void) sender; //suppress warning of unused parameter(s)
MRSDIAG("Memory.cpp - Memory:myUpdate");
mrs_natural memSize = ctrl_memSize_->to<mrs_natural>();
if (memSize != 0)
{
ctrl_onSamples_->setValue(ctrl_inSamples_->to<mrs_natural>() * memSize,
NOUPDATE);
ctrl_onObservations_->setValue(ctrl_inObservations_, NOUPDATE);
ctrl_osrate_->setValue(ctrl_israte_, NOUPDATE);
}
else
{
ctrl_onSamples_->setValue(ctrl_inSamples_->to<mrs_natural>(), NOUPDATE);
ctrl_onObservations_->setValue(ctrl_inObservations_, NOUPDATE);
ctrl_osrate_->setValue(ctrl_israte_, NOUPDATE);
}
inObservations_ = ctrl_inObservations_->to<mrs_natural>();
onObservations_ = ctrl_onObservations_->to<mrs_natural>();
onSamples_ = ctrl_onSamples_->to<mrs_natural>();
cir_out_.stretch(onObservations_, onSamples_);
ostringstream oss;
mrs_string inObsNames = ctrl_inObsNames_->to<mrs_string>();
for (int i = 0; i < inObservations_; ++i)
{
mrs_string inObsName;
mrs_string temp;
inObsName = inObsNames.substr(0, inObsNames.find(","));
temp = inObsNames.substr(inObsNames.find(",")+1, inObsNames.length());
inObsNames = temp;
oss << "Mem" << memSize << "_" << inObsName << ",";
}
ctrl_onObsNames_->setValue(oss.str(), NOUPDATE);
}
void
Memory::myProcess(realvec& in, realvec& out)
{
mrs_natural t,o,j;
mrs_natural memSize = ctrl_memSize_->to<mrs_natural>();
if (ctrl_reset_->to<mrs_bool>())
{
cir_out_.setval(0.0);
end_ = 0;
counter_since_reset_ = 0;
// fill up with copies of first incoming vector
for (j=0; j < onSamples_; j++)
{
for (o=0; o < inObservations_; o++)
{
cir_out_(o, end_) = in(o,0);
}
end_ = (end_ + 1) % onSamples_; // circular buffer index
}
}
if (memSize != 0)
{
for (t=0; t < inSamples_; t++)
{
for (o=0; o < inObservations_; o++)
{
cir_out_(o, end_) = in(o,t);
}
end_ = (end_ + 1) % onSamples_; // circular buffer index
}
counter_since_reset_++;
}
else // memSize == 0
{
for (t = 0; t < inSamples_; t++)
{
for (o=0; o < inObservations_; o++)
{
cir_out_(o,t) = in(o,t);
}
}
}
mrs_natural i_cir = end_;
for (t = 0; t < onSamples_; t++)
{
for (o=0; o < inObservations_; o++)
{
out(o, t) = cir_out_(o, i_cir);
}
i_cir = (i_cir + 1) % onSamples_;
}
//MATLAB_PUT(out, "Memory_out");
//MATLAB_EVAL("plot(Memory_out);");
}
| 24.517857 | 77 | 0.652586 | jaouahbi |
c955da2616ff9d9577c48b60fe66b2c854cb02c8 | 1,865 | cpp | C++ | src/simulator/simulator.cpp | unhuman-io/motor | 06f87820f3b4f4819ee09dd9ac133ce8cbc789d3 | [
"MIT"
] | null | null | null | src/simulator/simulator.cpp | unhuman-io/motor | 06f87820f3b4f4819ee09dd9ac133ce8cbc789d3 | [
"MIT"
] | null | null | null | src/simulator/simulator.cpp | unhuman-io/motor | 06f87820f3b4f4819ee09dd9ac133ce8cbc789d3 | [
"MIT"
] | null | null | null | #include <messages.h>
#include "simulator.h"
#include "easylogging++.h"
#include "system.h"
#include "hal_adc.h"
#include "motor_simulation.h"
#include "sensor/encoder.h"
#include "communication.h"
Simulator::Simulator(System &system) : system_(system), position_(), velocity_() {
motor_simulation_ = new MotorSimulation;
motor_simulation_->set_dt(get_dt());
}
Simulator::~Simulator() {
delete motor_simulation_;
}
void Simulator::send_message(Message *m) {
system_.communication_->send_message(m);
}
void Simulator::init(int32_t frequency_hz) {
PeriodicLoop::init(frequency_hz);
}
void Simulator::update() {
update_command();
status_.motor_status = system_.get_status();
//
// // BrushlessMotorSimulation::Command command;// = { .v_abc[0] = status_.motor_status.v_abc[0],
// // .v_abc[1] = status_.motor_status.v_abc[1],
// // .v_abc[2] = status_.motor_status.v_abc[2]};
// command.v_abc[0] = status_.motor_status.v_abc[0];
// command.v_abc[1] = status_.motor_status.v_abc[1];
// command.v_abc[2] = status_.motor_status.v_abc[2];
MotorSimulation::Command command;
command.i = status_.motor_status.foc_status.desired.i_q;
motor_simulation_->set_command(command);
motor_simulation_->update();
MotorSimulation::Status status;
motor_simulation_->get_status(&status);
//TODO below is temporary status force, should be done through hal
status_.motor_status.position = status.position;
status_.motor_status.velocity = status.velocity;
update_status();
// update sensors
system_.adc_->set_adc();
system_.motor_encoder_->set_position(status.position);
}
float Simulator::get_position() const { return position_; }
float Simulator::get_velocity() const { return velocity_; }
| 31.083333 | 99 | 0.680965 | unhuman-io |
c95697aeea57894759a1f00fa1ca956222cb0415 | 12,238 | cpp | C++ | src/helpers.cpp | unbornchikken/nodeanything | dd380645fd61c92cf1874cb2c880a4d00430925a | [
"BSD-3-Clause"
] | 115 | 2015-07-28T10:01:29.000Z | 2022-03-05T23:02:11.000Z | src/helpers.cpp | unbornchikken/nodeanything | dd380645fd61c92cf1874cb2c880a4d00430925a | [
"BSD-3-Clause"
] | 13 | 2015-08-03T09:01:37.000Z | 2021-01-28T02:49:01.000Z | src/helpers.cpp | unbornchikken/nodeanything | dd380645fd61c92cf1874cb2c880a4d00430925a | [
"BSD-3-Clause"
] | 12 | 2015-10-05T00:15:06.000Z | 2019-07-23T09:27:12.000Z | /*
Copyright (c) 2014-2015, ArrayFire
Copyright (c) 2015 Gábor Mező aka unbornchikken (gabor.mezo@outlook.com)
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 ArrayFire 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 "ext.h"
#include "helpers.h"
#include "errors.h"
#include "arraywrapper.h"
#include "symbols.h"
using namespace std;
using namespace v8;
using namespace node;
pair<af::dtype, unsigned> GetDTypeInfo(unsigned udtype)
{
unsigned sizeOf;
af::dtype dtype;
switch (udtype)
{
case 0:
dtype = f32;
sizeOf = 32 / 8;
break;
case 1:
dtype = c32;
sizeOf = 32 / 8;
break;
case 2:
dtype = f64;
sizeOf = 64 / 8;
break;
case 3:
dtype = c64;
sizeOf = 64 / 8;
break;
case 4:
dtype = b8;
sizeOf = 8 / 8;
break;
case 5:
dtype = s32;
sizeOf = 32 / 8;
break;
case 6:
dtype = u32;
sizeOf = 32 / 8;
break;
case 7:
dtype = u8;
sizeOf = 8 / 8;
break;
case 8:
dtype = s64;
sizeOf = 64 / 8;
break;
case 9:
dtype = u64;
sizeOf = 64 / 8;
break;
default:
ARRAYFIRE_THROW("DType is out of range.");
}
return move(make_pair(dtype, sizeOf));
}
std::pair<af::dtype, unsigned> GetDTypeInfo(v8::Local<v8::Value> value)
{
if (value->IsNumber())
{
return GetDTypeInfo(value->Uint32Value());
}
ARRAYFIRE_THROW("Value is not a number.");
}
string ErrToString(af_err err)
{
switch (err)
{
case AF_ERR_INTERNAL:
return "Internal error (AF_ERR_INTERNAL).";
break;
case AF_ERR_NO_MEM:
return "Not enough memory error (AF_ERR_NO_MEM).";
break;
case AF_ERR_DRIVER:
return "Driver error (AF_ERR_DRIVER).";
break;
case AF_ERR_RUNTIME:
return "Runtime error (AF_ERR_RUNTIME).";
break;
case AF_ERR_INVALID_ARRAY:
return "Invalid array error (AF_ERR_INVALID_ARRAY).";
break;
case AF_ERR_ARG:
return "Argument error (AF_ERR_ARG).";
break;
case AF_ERR_SIZE:
return "Size error (AF_ERR_SIZE).";
break;
case AF_ERR_DIFF_TYPE:
return "Diff type error (AF_ERR_DIFF_TYPE).";
break;
case AF_ERR_NOT_SUPPORTED:
return "Operation is not supported (AF_ERR_NOT_SUPPORTED).";
break;
case AF_ERR_NOT_CONFIGURED:
return "Not configured error (AF_ERR_NOT_CONFIGURED).";
break;
default:
return "Uknown ArrayFire error (AF_ERR_UNKNOWN).";
};
}
v8::Local<v8::Object> WrapPointer(void* ptr)
{
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::NewBuffer((char*)ptr, 0, [](char*v1, void*v2) {}, nullptr).ToLocalChecked());
}
af::dim4 ToDim4(v8::Local<v8::Object> obj)
{
Local<Array> dims;
if (obj->IsArray())
{
dims = obj.As<Array>();
}
else
{
auto member = obj->Get(Nan::New(Symbols::Values));
if (member->IsArray())
{
dims = member.As<Array>();
}
else
{
ARRAYFIRE_THROW_ARG_IS_NOT_A_DIM4();
}
}
int dim0 = 1;
int dim1 = 1;
int dim2 = 1;
int dim3 = 1;
if (dims->Length() > 0)
{
dim0 = dims->Get(0)->Uint32Value();
}
if (dims->Length() > 1)
{
dim1 = dims->Get(1)->Uint32Value();
}
if (dims->Length() > 2)
{
dim2 = dims->Get(2)->Uint32Value();
}
if (dims->Length() > 3)
{
dim3 = dims->Get(3)->Uint32Value();
}
return move(af::dim4(dim0, dim1, dim2, dim3));
}
af::dim4 ToDim4(v8::Local<v8::Value> value)
{
if (value->IsObject())
{
return ToDim4(value.As<Object>());
}
ARRAYFIRE_THROW_ARG_IS_NOT_AN_OBJ();
}
af::seq ToSeq(v8::Local<v8::Object> obj)
{
auto begin = obj->Get(Nan::New(Symbols::Begin));
auto end = obj->Get(Nan::New(Symbols::End));
auto step = obj->Get(Nan::New(Symbols::Step));
auto isGFor = obj->Get(Nan::New(Symbols::IsGFor));
if (begin->IsNumber() && end->IsNumber())
{
double stepValue = 1;
if (step->IsNumber())
{
stepValue = step->NumberValue();
}
bool isGForValue = false;
if (isGFor->IsBoolean())
{
isGForValue = isGFor->BooleanValue();
}
if (isGForValue)
{
return move(af::seq(af::seq(begin->NumberValue(), end->NumberValue(), stepValue), isGForValue));
}
return move(af::seq(begin->NumberValue(), end->NumberValue(), stepValue));
}
ARRAYFIRE_THROW_ARG_IS_NOT_A_SEQ();
}
af::seq ToSeq(v8::Local<v8::Value> value)
{
if (value->IsObject())
{
return ToSeq(value.As<Object>());
}
ARRAYFIRE_THROW_ARG_IS_NOT_AN_OBJ();
}
af::index ToIndex(v8::Local<v8::Value> value)
{
if (value->IsNull())
{
return af::span;
}
if (value->IsNumber())
{
return af::index(value->Int32Value());
}
if (value->IsString())
{
String::Utf8Value str(value);
if (strcmp(*str, "span") == 0)
{
return af::span;
}
else if (strcmp(*str, "end") == 0)
{
return af::end;
}
}
if (value->IsObject())
{
auto pArray = ArrayWrapper::TryGetArray(value);
if (pArray)
{
return af::index(*pArray);
}
return ToSeq(value.As<Object>());
}
ARRAYFIRE_THROW_ARG_IS_NOT_AN_INDEX();
}
af::af_cdouble ToDComplex(v8::Local<v8::Object> obj)
{
auto imag = obj->Get(Nan::New(Symbols::Imag));
auto real = obj->Get(Nan::New(Symbols::Real));
if (imag->IsNumber() && real->IsNumber())
{
return { real->NumberValue(), imag->NumberValue() };
}
ARRAYFIRE_THROW_ARG_IS_NOT_A_CPLX();
}
af::af_cdouble ToDComplex(v8::Local<v8::Value> value)
{
if (value->IsObject())
{
return ToDComplex(value.As<Object>());
}
ARRAYFIRE_THROW_ARG_IS_NOT_AN_OBJ();
}
af::af_cfloat ToFComplex(v8::Local<v8::Object> obj)
{
auto imag = obj->Get(Nan::New(Symbols::Imag));
auto real = obj->Get(Nan::New(Symbols::Real));
if (imag->IsNumber() && real->IsNumber())
{
return { (float)real->NumberValue(), (float)imag->NumberValue() };
}
ARRAYFIRE_THROW_ARG_IS_NOT_A_CPLX();
}
af::af_cfloat ToFComplex(v8::Local<v8::Value> value)
{
if (value->IsObject())
{
return ToFComplex(value.As<Object>());
}
ARRAYFIRE_THROW_ARG_IS_NOT_AN_OBJ();
}
v8::Local<v8::Object> ToV8Complex(const af::af_cdouble& value)
{
auto obj = Nan::New<Object>();
obj->Set(Nan::New(Symbols::Imag), Nan::New(value.imag));
obj->Set(Nan::New(Symbols::Real), Nan::New(value.real));
return obj;
}
v8::Local<v8::Object> ToV8Complex(const af::af_cfloat& value)
{
auto obj = Nan::New<Object>();
obj->Set(Nan::New(Symbols::Imag), Nan::New(value.imag));
obj->Set(Nan::New(Symbols::Real), Nan::New(value.real));
return obj;
}
std::pair<af::dim4, af::dtype> ParseDimAndTypeArgs(const Nan::FunctionCallbackInfo<v8::Value>& info, int assumedArgsLength, int argsFollowingDims, int dimsStartAt)
{
if (assumedArgsLength == -1)
{
assumedArgsLength = info.Length();
if (info[assumedArgsLength - 1]->IsFunction())
{
// Async
assumedArgsLength--;
}
}
af::dim4 dims(1, 1, 1, 1);
bool any = false;
for (int idx = dimsStartAt; idx < ((assumedArgsLength - 1) - argsFollowingDims); idx++)
{
int dimIdx = idx - dimsStartAt;
assert(dimIdx < 4);
any = true;
if (dimIdx == 0 && info[idx]->IsObject())
{
dims = move(ToDim4(info[idx].As<Object>()));
break;
}
dims[dimIdx] = info[idx]->Int32Value();
}
if (any)
{
af::dtype type = GetDTypeInfo(info[assumedArgsLength - 1 + dimsStartAt]->Uint32Value()).first;
return move(make_pair(move(dims), type));
}
ARRAYFIRE_THROW("Cannot extract dimensions and dtype from argumens.");
}
Nan::Callback* GetCallback(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if (info.Length() && info[info.Length() - 1]->IsFunction())
{
return new Nan::Callback(info[info.Length() - 1].As<Function>());
}
ARRAYFIRE_THROW_CB_EXPECTED();
}
v8::Local<v8::Object> ToV8Features(const af::features& feat)
{
auto obj = Nan::New<Object>();
obj->Set(Nan::New(Symbols::NumFeatures), Nan::New((unsigned)feat.getNumFeatures()));
obj->Set(Nan::New(Symbols::X), ArrayWrapper::New(feat.getX()));
obj->Set(Nan::New(Symbols::Y), ArrayWrapper::New(feat.getY()));
obj->Set(Nan::New(Symbols::Score), ArrayWrapper::New(feat.getScore()));
obj->Set(Nan::New(Symbols::Orientation), ArrayWrapper::New(feat.getOrientation()));
obj->Set(Nan::New(Symbols::Size), ArrayWrapper::New(feat.getSize()));
return obj;
}
RegionIndex ToRegionIndex(v8::Local<v8::Object> obj)
{
auto cn = obj->GetConstructorName();
if (cn->Equals(Nan::New(Symbols::RowClass)))
{
return make_tuple(Region::Row, obj->Get(Nan::New(Symbols::Index))->Uint32Value(), (unsigned)0);
}
else if (cn->Equals(Nan::New(Symbols::RowsClass)))
{
return make_tuple(Region::Rows, obj->Get(Nan::New(Symbols::FirstIndex))->Uint32Value(), obj->Get(Nan::New(Symbols::LastIndex))->Uint32Value());
}
else if (cn->Equals(Nan::New(Symbols::ColClass)))
{
return make_tuple(Region::Col, obj->Get(Nan::New(Symbols::Index))->Uint32Value(), (unsigned)0);
}
else if (cn->Equals(Nan::New(Symbols::ColsClass)))
{
return make_tuple(Region::Cols, obj->Get(Nan::New(Symbols::FirstIndex))->Uint32Value(), obj->Get(Nan::New(Symbols::LastIndex))->Uint32Value());
}
else if (cn->Equals(Nan::New(Symbols::SliceClass)))
{
return make_tuple(Region::Slice, obj->Get(Nan::New(Symbols::Index))->Uint32Value(), (unsigned)0);
}
else if (cn->Equals(Nan::New(Symbols::SlicesClass)))
{
return make_tuple(Region::Slices, obj->Get(Nan::New(Symbols::FirstIndex))->Uint32Value(), obj->Get(Nan::New(Symbols::LastIndex))->Uint32Value());
}
return make_tuple(Region::None, (unsigned)0, (unsigned)0);
}
RegionIndex ToRegionIndex(v8::Local<v8::Value> value)
{
if (value->IsObject())
{
return ToRegionIndex(value.As<Object>());
}
return make_tuple(Region::None, (unsigned)0, (unsigned)0);
}
| 29.347722 | 163 | 0.592826 | unbornchikken |
c95774b3dd49362ce5f9283027fc8ecbf94574df | 60 | hpp | C++ | src/boost_mpl_aux__preprocessed_no_ctps_bind_fwd.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_mpl_aux__preprocessed_no_ctps_bind_fwd.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_mpl_aux__preprocessed_no_ctps_bind_fwd.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/mpl/aux_/preprocessed/no_ctps/bind_fwd.hpp>
| 30 | 59 | 0.816667 | miathedev |
c95c0fddb5f6dd773b7dac909993d18325ddf3d2 | 6,684 | cpp | C++ | tst/OpcUaStackCore/ServiceSet/Cancel_t.cpp | gianricardo/OpcUaStack | ccdef574175ffe8b7e82b886abc5e5403968b280 | [
"Apache-2.0"
] | 108 | 2018-10-08T17:03:32.000Z | 2022-03-21T00:52:26.000Z | tst/OpcUaStackCore/ServiceSet/Cancel_t.cpp | gianricardo/OpcUaStack | ccdef574175ffe8b7e82b886abc5e5403968b280 | [
"Apache-2.0"
] | 287 | 2018-09-18T14:59:12.000Z | 2022-01-13T12:28:23.000Z | tst/OpcUaStackCore/ServiceSet/Cancel_t.cpp | gianricardo/OpcUaStack | ccdef574175ffe8b7e82b886abc5e5403968b280 | [
"Apache-2.0"
] | 32 | 2018-10-19T14:35:03.000Z | 2021-11-12T09:36:46.000Z | #include "unittest.h"
#include "boost/asio.hpp"
#include "OpcUaStackCore/BuildInTypes/BuildInTypes.h"
#include "OpcUaStackCore/BuildInTypes/OpcUaIdentifier.h"
#include "OpcUaStackCore/SecureChannel/MessageHeader.h"
#include "OpcUaStackCore/SecureChannel/SequenceHeader.h"
#include "OpcUaStackCore/ServiceSet/CancelRequest.h"
#include "OpcUaStackCore/ServiceSet/CancelResponse.h"
#include "OpcUaStackCore/Base/Utility.h"
#include <streambuf>
#include <iostream>
using namespace OpcUaStackCore;
BOOST_AUTO_TEST_SUITE(Cancel_)
BOOST_AUTO_TEST_CASE(Cancel_)
{
std::cout << "Cancel_t" << std::endl;
}
BOOST_AUTO_TEST_CASE(Cancel_Request)
{
uint32_t pos;
MessageHeader::SPtr messageHeaderSPtr;
boost::posix_time::ptime ptime = boost::posix_time::from_iso_string("16010101T000000.000000000");
OpcUaGuid::SPtr opcUaGuidSPtr;
CancelRequest::SPtr cancelRequestSPtr;
SequenceHeader::SPtr sequenceHeaderSPtr;
OpcUaNodeId typeId;
// stream
boost::asio::streambuf sb1;
std::iostream ios1(&sb1);
boost::asio::streambuf sb2;
std::iostream ios2(&sb2);
boost::asio::streambuf sb;
std::iostream ios(&sb);
// encode channel id
OpcUaUInt32 channelId;
channelId = 153451225;
OpcUaNumber::opcUaBinaryEncode(ios1, channelId);
// encode token id
OpcUaInt32 tokenId;
tokenId = 1;
OpcUaNumber::opcUaBinaryEncode(ios1, tokenId);
// encode sequence header
sequenceHeaderSPtr = constructSPtr<SequenceHeader>();
sequenceHeaderSPtr->sequenceNumber(140);
sequenceHeaderSPtr->requestId(90);
sequenceHeaderSPtr->opcUaBinaryEncode(ios1);
// encode message type id
typeId.nodeId((OpcUaUInt32)OpcUaId_CancelRequest_Encoding_DefaultBinary);
typeId.opcUaBinaryEncode(ios1);
// encode CancelRequest
cancelRequestSPtr = constructSPtr<CancelRequest>();
cancelRequestSPtr->requestHandle(4711);
cancelRequestSPtr->opcUaBinaryEncode(ios1);
// encode MessageHeader
messageHeaderSPtr = constructSPtr<MessageHeader>();
messageHeaderSPtr->messageType(MessageType_Message);
messageHeaderSPtr->messageSize(OpcUaStackCore::count(sb1)+8);
messageHeaderSPtr->opcUaBinaryEncode(ios2);
// stream
ios << ios2.rdbuf() << ios1.rdbuf();
OpcUaStackCore::dumpHex(ios);
std::stringstream ss;
ss << "4d 53 47 46 20 00 00 00 d9 7a 25 09 01 00 00 00"
<< "8c 00 00 00 5a 00 00 00 01 00 df 01 67 12 00 00";
BOOST_REQUIRE(OpcUaStackCore::compare(ios, ss.str(), pos) == true);
// decode MessageHeader
messageHeaderSPtr = constructSPtr<MessageHeader>();
messageHeaderSPtr->opcUaBinaryDecode(ios);
BOOST_REQUIRE(messageHeaderSPtr->messageType() == MessageType_Message);
// decode channel id
OpcUaNumber::opcUaBinaryDecode(ios, channelId);
BOOST_REQUIRE(channelId == 153451225);
// decode token id
OpcUaNumber::opcUaBinaryDecode(ios, tokenId);
BOOST_REQUIRE(tokenId == 1);
// decode sequence header
sequenceHeaderSPtr = constructSPtr<SequenceHeader>();
sequenceHeaderSPtr->opcUaBinaryDecode(ios);
BOOST_REQUIRE(sequenceHeaderSPtr->sequenceNumber() == 140);
BOOST_REQUIRE(sequenceHeaderSPtr->requestId() == 90);
// decode message type id
typeId.opcUaBinaryDecode(ios);
BOOST_REQUIRE(typeId.namespaceIndex() == 0);
BOOST_REQUIRE(typeId.nodeId<OpcUaUInt32>() == OpcUaId_CancelRequest_Encoding_DefaultBinary);
// decode CancelRequest
cancelRequestSPtr = constructSPtr<CancelRequest>();
cancelRequestSPtr->opcUaBinaryDecode(ios);
}
BOOST_AUTO_TEST_CASE(Cancel_Response)
{
uint32_t pos;
MessageHeader::SPtr messageHeaderSPtr;
boost::posix_time::ptime ptime = boost::posix_time::from_iso_string("16010101T000000.000000000");
OpcUaGuid::SPtr opcUaGuidSPtr;
CancelResponse::SPtr cancelResponseSPtr;
SequenceHeader::SPtr sequenceHeaderSPtr;
OpcUaNodeId typeId;
// stream
boost::asio::streambuf sb1;
std::iostream ios1(&sb1);
boost::asio::streambuf sb2;
std::iostream ios2(&sb2);
boost::asio::streambuf sb;
std::iostream ios(&sb);
// encode channel id
OpcUaUInt32 channelId;
channelId = 153451225;
OpcUaNumber::opcUaBinaryEncode(ios1, channelId);
// encode token id
OpcUaInt32 tokenId;
tokenId = 1;
OpcUaNumber::opcUaBinaryEncode(ios1, tokenId);
// encode sequence header
sequenceHeaderSPtr = constructSPtr<SequenceHeader>();
sequenceHeaderSPtr->sequenceNumber(140);
sequenceHeaderSPtr->requestId(90);
sequenceHeaderSPtr->opcUaBinaryEncode(ios1);
// encode message type id
typeId.nodeId(OpcUaId_CancelResponse_Encoding_DefaultBinary);
typeId.opcUaBinaryEncode(ios1);
// encode CancelResponse
cancelResponseSPtr = constructSPtr<CancelResponse>();
cancelResponseSPtr->responseHeader()->time(ptime);
cancelResponseSPtr->responseHeader()->requestHandle(1);
cancelResponseSPtr->responseHeader()->serviceResult(Success);
cancelResponseSPtr->cancelCount(1);
cancelResponseSPtr->opcUaBinaryEncode(ios1);
// encode MessageHeader
messageHeaderSPtr = constructSPtr<MessageHeader>();
messageHeaderSPtr->messageType(MessageType_Message);
messageHeaderSPtr->messageSize(OpcUaStackCore::count(sb1)+8);
messageHeaderSPtr->opcUaBinaryEncode(ios2);
// stream
ios << ios2.rdbuf() << ios1.rdbuf();
OpcUaStackCore::dumpHex(ios);
std::stringstream ss;
ss << "4d 53 47 46 38 00 00 00 d9 7a 25 09 01 00 00 00"
<< "8c 00 00 00 5a 00 00 00 01 00 e2 01 00 00 00 00"
<< "00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00"
<< "00 00 00 00 01 00 00 00";
BOOST_REQUIRE(OpcUaStackCore::compare(ios, ss.str(), pos) == true);
// decode MessageHeader
messageHeaderSPtr = constructSPtr<MessageHeader>();
messageHeaderSPtr->opcUaBinaryDecode(ios);
BOOST_REQUIRE(messageHeaderSPtr->messageType() == MessageType_Message);
// decode channel id
OpcUaNumber::opcUaBinaryDecode(ios, channelId);
BOOST_REQUIRE(channelId == 153451225);
// decode token id
OpcUaNumber::opcUaBinaryDecode(ios, tokenId);
BOOST_REQUIRE(tokenId == 1);
// decode sequence header
sequenceHeaderSPtr = constructSPtr<SequenceHeader>();
sequenceHeaderSPtr->opcUaBinaryDecode(ios);
BOOST_REQUIRE(sequenceHeaderSPtr->sequenceNumber() == 140);
BOOST_REQUIRE(sequenceHeaderSPtr->requestId() == 90);
// decode message type id
typeId.opcUaBinaryDecode(ios);
BOOST_REQUIRE(typeId.namespaceIndex() == 0);
BOOST_REQUIRE(typeId.nodeId<OpcUaUInt32>() == OpcUaId_CancelResponse_Encoding_DefaultBinary);
//decode CancelResponse
cancelResponseSPtr = constructSPtr<CancelResponse>();
cancelResponseSPtr->opcUaBinaryDecode(ios);
BOOST_REQUIRE(cancelResponseSPtr->responseHeader()->time().dateTime() == ptime);
BOOST_REQUIRE(cancelResponseSPtr->responseHeader()->requestHandle() == 1);
BOOST_REQUIRE(cancelResponseSPtr->responseHeader()->serviceResult() == Success);
BOOST_REQUIRE(cancelResponseSPtr->cancelCount() == 1);
}
BOOST_AUTO_TEST_SUITE_END()
| 31.677725 | 98 | 0.774686 | gianricardo |
e920dccfe5066f042bc8f7a60f02b5f3528be619 | 785 | cpp | C++ | solved/o-q/pole-position/pole.cpp | abuasifkhan/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-09-30T19:18:04.000Z | 2021-06-26T21:11:30.000Z | solved/o-q/pole-position/pole.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | null | null | null | solved/o-q/pole-position/pole.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-01-04T09:49:54.000Z | 2021-06-03T13:18:44.000Z | #include <cstdio>
#include <cstring>
#define MAXN 1000
#define Zero(v) memset((v), 0, sizeof(v))
int N;
int grid[MAXN];
int main()
{
while (true) {
scanf("%d", &N);
if (N == 0) break;
Zero(grid);
bool valid = true;
for (int i = 0; i < N; ++i) {
int C, P;
scanf("%d%d", &C, &P);
int idx = i + P;
if (idx < 0 || idx >= N || grid[idx] != 0) {
valid = false;
continue;
}
grid[idx] = C;
}
if (valid) {
printf("%d", grid[0]);
for (int i = 1; i < N; ++i)
printf(" %d", grid[i]);
putchar('\n');
}
else
puts("-1");
}
return 0;
}
| 16.354167 | 56 | 0.35414 | abuasifkhan |
e9267eeda8e83643522c8d052654483f35dc5939 | 1,392 | hpp | C++ | include/MyElf/Sections/SectionHeader.hpp | korreborg/MyElf | f7514cb7ecf923702cc34b344d1a0a51419588ee | [
"MIT"
] | 1 | 2022-03-29T21:10:43.000Z | 2022-03-29T21:10:43.000Z | include/MyElf/Sections/SectionHeader.hpp | korreborg/MyElf | f7514cb7ecf923702cc34b344d1a0a51419588ee | [
"MIT"
] | 6 | 2022-03-29T20:21:08.000Z | 2022-03-29T20:56:09.000Z | include/MyElf/Sections/SectionHeader.hpp | korreborg/MyElf | f7514cb7ecf923702cc34b344d1a0a51419588ee | [
"MIT"
] | null | null | null | #pragma once
#include "../Common.hpp"
//special section indexes
#define SHN_UNDEF 0x0
#define SHN_LORESERVE 0xFF00
#define SHN_LOPROC 0xFF00
#define SHN_HIPROC 0xFF1F
#define SHN_ABS 0xFFF1
#define SHN_COMMON 0xFFF2
#define SHN_HIRESERVE 0xFFFF
//Section types
#define SHT_NULL 0
#define SHT_PROGBITS 1
#define SHT_SYMTAB 2
#define SHT_STRTAB 3
#define SHT_RELA 4
#define SHT_HASH 5
#define SHT_DYNAMIC 6
#define SHT_NOTE 7
#define SHT_NOBITS 8
#define SHT_REL 9
#define SHT_SHLIB 10
#define SHT_DYNSYM 11
#define SHT_LOPROC 0x70000000
#define SHT_HIPROC 0x7FFFFFFF
#define SHT_LOUSER 0x80000000
#define SHT_HIUSER 0xFFFFFFFF
struct SectionHeader
{
U32 NameOffset;
U32 Type;
U64 Flags;
U64 Address;
U64 Offset;
U64 Size;
U32 Link;
U32 Info;
U64 AddrAlign;
U64 EntSize;
void Read(std::istream& stream, bool elf64)
{
MYELF_READ(stream, this->NameOffset);
MYELF_READ(stream, this->Type);
MYELF_READ_DIFF(stream, this->Flags, U32, elf64);
MYELF_READ_DIFF(stream, this->Address, U32, elf64);
MYELF_READ_DIFF(stream, this->Offset, U32, elf64);
MYELF_READ_DIFF(stream, this->Size, U32, elf64);
MYELF_READ(stream, this->Link);
MYELF_READ(stream, this->Info);
MYELF_READ_DIFF(stream, this->AddrAlign, U32, elf64);
MYELF_READ_DIFF(stream, this->EntSize, U32, elf64);
}
};
| 22.095238 | 57 | 0.713362 | korreborg |
e929255ab8732af5534eb27118457cf3a3a44b14 | 2,969 | hpp | C++ | higan/processor/r65816/registers.hpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | 3 | 2016-03-23T01:17:36.000Z | 2019-10-25T06:41:09.000Z | higan/processor/r65816/registers.hpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | null | null | null | higan/processor/r65816/registers.hpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | null | null | null | struct flag_t {
bool n{0};
bool v{0};
bool m{0};
bool x{0};
bool d{0};
bool i{0};
bool z{0};
bool c{0};
inline operator unsigned() const {
return (n << 7) + (v << 6) + (m << 5) + (x << 4)
+ (d << 3) + (i << 2) + (z << 1) + (c << 0);
}
inline auto operator=(uint8 data) -> unsigned {
n = data & 0x80; v = data & 0x40; m = data & 0x20; x = data & 0x10;
d = data & 0x08; i = data & 0x04; z = data & 0x02; c = data & 0x01;
return data;
}
};
struct reg16_t {
union {
uint16 w = 0;
struct { uint8 order_lsb2(l, h); };
};
inline operator unsigned() const { return w; }
inline auto operator = (unsigned i) -> unsigned { return w = i; }
inline auto operator |= (unsigned i) -> unsigned { return w |= i; }
inline auto operator ^= (unsigned i) -> unsigned { return w ^= i; }
inline auto operator &= (unsigned i) -> unsigned { return w &= i; }
inline auto operator <<= (unsigned i) -> unsigned { return w <<= i; }
inline auto operator >>= (unsigned i) -> unsigned { return w >>= i; }
inline auto operator += (unsigned i) -> unsigned { return w += i; }
inline auto operator -= (unsigned i) -> unsigned { return w -= i; }
inline auto operator *= (unsigned i) -> unsigned { return w *= i; }
inline auto operator /= (unsigned i) -> unsigned { return w /= i; }
inline auto operator %= (unsigned i) -> unsigned { return w %= i; }
};
struct reg24_t {
union {
uint32 d = 0;
struct { uint16 order_lsb2(w, wh); };
struct { uint8 order_lsb4(l, h, b, bh); };
};
inline operator unsigned() const { return d; }
inline auto operator = (unsigned i) -> unsigned { return d = uclip<24>(i); }
inline auto operator |= (unsigned i) -> unsigned { return d = uclip<24>(d | i); }
inline auto operator ^= (unsigned i) -> unsigned { return d = uclip<24>(d ^ i); }
inline auto operator &= (unsigned i) -> unsigned { return d = uclip<24>(d & i); }
inline auto operator <<= (unsigned i) -> unsigned { return d = uclip<24>(d << i); }
inline auto operator >>= (unsigned i) -> unsigned { return d = uclip<24>(d >> i); }
inline auto operator += (unsigned i) -> unsigned { return d = uclip<24>(d + i); }
inline auto operator -= (unsigned i) -> unsigned { return d = uclip<24>(d - i); }
inline auto operator *= (unsigned i) -> unsigned { return d = uclip<24>(d * i); }
inline auto operator /= (unsigned i) -> unsigned { return d = uclip<24>(d / i); }
inline auto operator %= (unsigned i) -> unsigned { return d = uclip<24>(d % i); }
};
struct regs_t {
reg24_t pc;
reg16_t a;
reg16_t x;
reg16_t y;
reg16_t z; //pseudo-register (zero register)
reg16_t s;
reg16_t d;
flag_t p;
uint8 db{0};
bool e{0};
bool irq{0}; //IRQ pin (0 = low, 1 = trigger)
bool wai{0}; //raised during wai, cleared after interrupt triggered
uint8 mdr{0}; //memory data register
uint16 vector{0}; //interrupt vector address
};
| 36.654321 | 85 | 0.575951 | ameer-bauer |
e92b941bdb2953b41b65166d5e70b2b8c3e78df8 | 5,101 | cc | C++ | translator/fortran_output_fix.cc | naoyam/physis | 39ee5250a2d5baa545ca03e7c5c9aa9c81f1ab19 | [
"BSD-3-Clause"
] | 30 | 2015-01-27T02:45:34.000Z | 2022-02-17T03:50:49.000Z | translator/fortran_output_fix.cc | naoyam/physis | 39ee5250a2d5baa545ca03e7c5c9aa9c81f1ab19 | [
"BSD-3-Clause"
] | 8 | 2015-01-02T02:10:04.000Z | 2015-04-21T08:42:12.000Z | translator/fortran_output_fix.cc | naoyam/physis | 39ee5250a2d5baa545ca03e7c5c9aa9c81f1ab19 | [
"BSD-3-Clause"
] | 4 | 2015-12-16T10:18:31.000Z | 2021-12-28T22:43:56.000Z | // Licensed under the BSD license. See LICENSE.txt for more details.
#include "translator/fortran_output_fix.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
using std::ios_base;
using std::ifstream;
using std::ofstream;
using std::ostringstream;
namespace physis {
namespace translator {
// BEFORE: TYPE (PSStencil_kernel)
// FIXED: TYPE (PSStencil_kernel), extends(PSStencil)
static bool FixStencilMapDecl(string &line, const vector<string> &tokens) {
if (tokens.size() != 3) return false;
if (tokens[0] != "TYPE" ||
tokens[1] != "::") return false;
if (!startswith(tokens[2], "PSStencil_")) return false;
LOG_DEBUG() << "Before: " << line << "\n";
line = tokens[0] + ", extends(PSStencil) " + tokens[1] + tokens[2];
LOG_DEBUG() << "Fixed: " << line << "\n";
return true;
//return false;
}
// BEFORE: end type PSStencil_kernel
// FIXED: contains procedure run => PSStencilRun_kernel end type PSStencil_kernel
static bool FixStencilMapDeclTypeBoundProc(string &line, const vector<string> &tokens) {
if (tokens.size() != 3) return false;
if (tokens[0] != "END" ||
tokens[1] != "TYPE") return false;
string run_func_name = tokens[2];
PSAssert(startswith(run_func_name, "PSStencil_"));
boost::algorithm::replace_first(run_func_name, "PSStencil_", "PSStencilRun_");
string proc_decl = "contains\nprocedure :: run => " + run_func_name + "\n";
LOG_DEBUG() << "Before: " << line << "\n";
line = proc_decl + line;
LOG_DEBUG() << "Fixed: " << line << "\n";
return true;
}
static bool FixStencilMapVarDecl(string &line, const vector<string> &tokens) {
if (tokens.size() != 8) return false;
if (tokens[0] != "TYPE" ||
tokens[1] != "(" ||
tokens[3] != ")" ||
tokens[4] != "," ||
tokens[5] != "POINTER" ||
tokens[6] != "::" ||
tokens[7] != "ps_stencil_p") return false;
StringJoin sj(" ");
sj << "CLASS (PSStencil)";
BOOST_FOREACH (const string &s, make_pair(tokens.begin()+4, tokens.end())) {
sj << s;
}
LOG_DEBUG() << "Before: " << line << "\n";
line = sj.str();
LOG_DEBUG() << "Fixed: " << line << "\n";
return true;
}
static bool FixBaseStenciVarDecl(string &line, const vector<string> &tokens) {
if (tokens.size() < 6) return false;
if (tokens[0] != "TYPE" ||
tokens[1] != "(" ||
tokens[2] != "PSStencil" ||
tokens[3] != ")" ||
tokens[4] != "," ||
tokens[5] != "POINTER") return false;
StringJoin sj(" ");
sj << "CLASS";
BOOST_FOREACH (const string &s, make_pair(tokens.begin()+1, tokens.end())) {
sj << s;
}
LOG_DEBUG() << "Before: " << line << "\n";
line = sj.str();
LOG_DEBUG() << "Fixed: " << line << "\n";
return true;
}
// Assumption: within PSStencilRUn_kernel function
// Before: TYPE (PSStencil_kernel) :: s
// Fixed: CLASS (PSStencil_kernel) :: s
static bool FixRunStencilParamDecl(string &line, const vector<string> &tokens) {
if (tokens.size() != 6) return false;
if (tokens[0] != "TYPE" ||
tokens[1] != "(" ||
tokens[3] != ")" ||
tokens[4] != "::" ||
tokens[5] != "s") return false;
string tn = tokens[2];
if (!startswith(tn, "PSStencil_")) return false;
StringJoin sj(" ");
sj << "CLASS";
BOOST_FOREACH (const string &s, make_pair(tokens.begin()+1, tokens.end())) {
sj << s;
}
LOG_DEBUG() << "Before: " << line << "\n";
line = sj.str();
LOG_DEBUG() << "Fixed: " << line << "\n";
return true;
}
static bool RunFuncBegin(const string &line, const vector<string> &tokens) {
return startswith(line, "SUBROUTINE PSStencilRun_");
}
static bool SubroutineEnd(const string &line, const vector<string> &tokens) {
return startswith(line, "END SUBROUTINE");
}
void FixFortranOutput(const string &path) {
ifstream in(path.c_str());
ostringstream os;
string tmp;
bool within_map_type = false;
bool within_run_func = false;
while (!in.eof()) {
std::getline(in, tmp, '\n');
//std::cout << tmp << "\n";
vector<string> tokens;
boost::algorithm::split(tokens, tmp, boost::is_any_of(" "),
boost::algorithm::token_compress_on);
if (FixStencilMapDecl(tmp, tokens)) {
within_map_type = true;
} else if (within_map_type && FixStencilMapDeclTypeBoundProc(tmp, tokens)) {
within_map_type = false;
} else if (FixStencilMapVarDecl(tmp, tokens)) {
} else if (FixBaseStenciVarDecl(tmp, tokens)) {
} else if (RunFuncBegin(tmp, tokens)) {
within_run_func = true;
} else if (SubroutineEnd(tmp, tokens)) {
within_run_func = false;
} else if (within_run_func && FixRunStencilParamDecl(tmp, tokens)) {
} else {
//LOG_DEBUG() << "Unchanged\n";
}
os << tmp << "\n";
tmp.clear();
}
in.close();
const string &fixed = os.str();
ofstream out(path.c_str());
//ofstream out((path + ".fixd").c_str());
out.write(fixed.c_str(), fixed.size());
out.close();
}
} // namespace translator
} // namespace physis
| 29.830409 | 88 | 0.608704 | naoyam |
e93265f9f07efe2d169dd68bf147138c45361cdb | 1,621 | cpp | C++ | src/account/GetApplicationSubscriptionHistoryResponse.cpp | Sherlock92/greentop | aa278d08babe02326b3ab85a6eafb858d780dec5 | [
"MIT"
] | 5 | 2019-06-30T06:29:46.000Z | 2021-12-17T12:41:23.000Z | src/account/GetApplicationSubscriptionHistoryResponse.cpp | Sherlock92/greentop | aa278d08babe02326b3ab85a6eafb858d780dec5 | [
"MIT"
] | 2 | 2018-01-09T17:14:45.000Z | 2020-03-23T00:16:50.000Z | src/account/GetApplicationSubscriptionHistoryResponse.cpp | Sherlock92/greentop | aa278d08babe02326b3ab85a6eafb858d780dec5 | [
"MIT"
] | 7 | 2015-09-13T18:40:58.000Z | 2020-01-24T10:57:56.000Z | /**
* Copyright 2017 Colin Doig. Distributed under the MIT license.
*/
#include "greentop/account/GetApplicationSubscriptionHistoryResponse.h"
namespace greentop {
namespace account {
GetApplicationSubscriptionHistoryResponse::GetApplicationSubscriptionHistoryResponse() {
}
GetApplicationSubscriptionHistoryResponse::GetApplicationSubscriptionHistoryResponse(const std::vector<SubscriptionHistory>& subscriptionHistorys) :
subscriptionHistorys(subscriptionHistorys) {
}
void GetApplicationSubscriptionHistoryResponse::fromJson(const Json::Value& json) {
if (validateJson(json)) {
for (unsigned i = 0; i < json.size(); ++i) {
SubscriptionHistory subscriptionHistory;
subscriptionHistory.fromJson(json[i]);
subscriptionHistorys.push_back(subscriptionHistory);
}
}
}
Json::Value GetApplicationSubscriptionHistoryResponse::toJson() const {
Json::Value json(Json::arrayValue);
if (subscriptionHistorys.size() > 0) {
for (unsigned i = 0; i < subscriptionHistorys.size(); ++i) {
json.append(subscriptionHistorys[i].toJson());
}
}
return json;
}
bool GetApplicationSubscriptionHistoryResponse::isValid() const {
return subscriptionHistorys.size() > 0;
}
const std::vector<SubscriptionHistory>& GetApplicationSubscriptionHistoryResponse::getSubscriptionHistorys() const {
return subscriptionHistorys;
}
void GetApplicationSubscriptionHistoryResponse::setSubscriptionHistorys(const std::vector<SubscriptionHistory>& subscriptionHistorys) {
this->subscriptionHistorys = subscriptionHistorys;
}
}
}
| 31.784314 | 148 | 0.750771 | Sherlock92 |
e932a041f73bb9bf4b667c23bde3a38241c66cf2 | 28,526 | cc | C++ | test/sema/test_analyzer.cc | ligangwang/m | 8a470441305689f4107c1c8b54276ef8910609c5 | [
"MIT"
] | 9 | 2020-01-25T05:27:46.000Z | 2022-01-24T02:40:50.000Z | test/sema/test_analyzer.cc | ligangwang/m | 8a470441305689f4107c1c8b54276ef8910609c5 | [
"MIT"
] | 1 | 2020-06-01T00:06:12.000Z | 2020-06-01T00:06:12.000Z | test/sema/test_analyzer.cc | ligangwang/m | 8a470441305689f4107c1c8b54276ef8910609c5 | [
"MIT"
] | 1 | 2020-05-08T05:19:13.000Z | 2020-05-08T05:19:13.000Z | /*
* Copyright (C) 2020 Ligang Wang <ligangwangs@gmail.com>
*
* Unit tests for type inference and semantic analsysis
*/
#include "codegen/codegen.h"
#include "codegen/env.h"
#include "parser/m_parser.h"
#include "sema/analyzer.h"
#include "sema/sema_context.h"
#include "tutil.h"
#include "gtest/gtest.h"
#include <stdio.h>
TEST(testAnalyzer, testIntVariable)
{
char test_code[] = "x = 11";
env *env = env_new(false);
ast_node *block = parse_string(env->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("x", string_get(node->var->var_name));
ASSERT_EQ(VAR_NODE, node->node_type);
ASSERT_EQ(TYPE_INT, node->var->init_value->type->type);
ASSERT_EQ(KIND_OPER, node->type->kind);
string type_str = to_string(node->type);
ASSERT_STREQ("int", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testDoubleVariable)
{
char test_code[] = "x = 11.0";
env *env = env_new(false);
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("x", string_get(node->var->var_name));
ASSERT_EQ(VAR_NODE, node->node_type);
ASSERT_EQ(TYPE_DOUBLE, node->var->init_value->type->type);
string type_str = to_string(node->type);
ASSERT_STREQ("double", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testBoolVariable)
{
char test_code[] = "x = true";
env *env = env_new(false);
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("x", string_get(node->var->var_name));
ASSERT_EQ(VAR_NODE, node->node_type);
ASSERT_EQ(TYPE_BOOL, node->var->init_value->type->type);
string type_str = to_string(node->type);
ASSERT_STREQ("bool", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testCharVariable)
{
char test_code[] = "x = 'c'";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("x", string_get(node->var->var_name));
ASSERT_EQ(VAR_NODE, node->node_type);
ASSERT_EQ(TYPE_CHAR, node->var->init_value->type->type);
string type_str = to_string(node->type);
ASSERT_STREQ("char", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testStringVariable)
{
char test_code[] = "x = \"hello world!\"";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("x", string_get(node->var->var_name));
ASSERT_EQ(VAR_NODE, node->node_type);
ASSERT_EQ(TYPE_STRING, node->var->init_value->type->type);
string type_str = to_string(node->type);
ASSERT_STREQ("string", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testCallNode)
{
char test_code[] = "printf \"hello\"";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_EQ(CALL_NODE, node->node_type);
ASSERT_EQ(TYPE_INT, node->type->type);
string type_str = to_string(node->type);
ASSERT_STREQ("int", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testDoubleIntLiteralError)
{
char test_code[] = "x = 11.0 + 10";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("x", string_get(node->var->var_name));
ASSERT_EQ(VAR_NODE, node->node_type);
ASSERT_EQ(0, node->type);
env_free(env);
}
TEST(testAnalyzer, testGreaterThan)
{
char test_code[] = R"(
11>10
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
auto node = *(ast_node **)array_front(&block->block->nodes);
emit_code(env, (ast_node *)block);
ASSERT_EQ(BINARY_NODE, node->node_type);
string type_str = to_string(node->type);
ASSERT_STREQ("bool", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testIdentityFunc)
{
reset_id_name("a");
char test_code[] = "id x = x";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("id", string_get(node->func->func_type->ft->name));
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(2, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("a -> a", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testIntIntFunc)
{
char test_code[] = "f x = x + 10";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("f", string_get(node->func->func_type->ft->name));
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(2, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("int -> int", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testDoubleDoubleFunc)
{
char test_code[] = "f x = x + 10.0";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("f", string_get(node->func->func_type->ft->name));
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(2, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("double -> double", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testBoolFunc)
{
char test_code[] = "f x = !x";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("f", string_get(node->func->func_type->ft->name));
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(2, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("bool -> bool", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testMultiParamFunc)
{
char test_code[] = "avg x y = (x + y) / 2.0";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("avg", string_get(node->func->func_type->ft->name));
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(3, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("double * double -> double", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testRecursiveFunc)
{
char test_code[] = R"(
factorial n =
if n < 2 then n
else n * factorial (n-1)
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("factorial", string_get(node->func->func_type->ft->name));
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(2, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("int -> int", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testForLoopFunc)
{
char test_code[] = R"(
# using for loop
loopprint n =
for i in 0..n
printf "%d" i
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("loopprint", string_get(node->func->func_type->ft->name));
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(2, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("int -> ()", string_get(&type_str));
ast_node *forn = *(ast_node **)array_front(&node->func->body->block->nodes);
ASSERT_EQ(TYPE_INT, get_type(forn->forloop->step->type));
ASSERT_EQ(TYPE_INT, get_type(forn->forloop->start->type));
ASSERT_EQ(TYPE_BOOL, get_type(forn->forloop->end->type));
ASSERT_EQ(TYPE_INT, get_type(forn->forloop->body->type));
env_free(env);
}
TEST(testAnalyzer, testLocalVariableFunc)
{
char test_code[] = R"(
# using for loop
distance x1 y1 x2 y2 =
xx = (x1-x2) * (x1-x2)
yy = (y1-y2) * (y1-y2)
sqrt (xx + yy)
)";
reset_id_name("a");
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("distance", string_get(node->func->func_type->ft->name));
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(5, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("double * double * double * double -> double", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testLocalStringFunc)
{
char test_code[] = R"(
to_string () =
x = "hello"
y = x
y
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("to_string", string_get(node->func->func_type->ft->name));
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(1, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("() -> string", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testVariadicFunc)
{
char test_code[] = R"(
var_func ... = 0
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("var_func", string_get(node->func->func_type->ft->name));
ASSERT_EQ(true, node->func->func_type->ft->is_variadic);
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(2, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("... -> int", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testPrintfFunc)
{
char test_code[] = R"(
printf "%d" 100
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_EQ(CALL_NODE, node->node_type);
string type_str = to_string(node->type);
ASSERT_STREQ("int", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testStructLikeType)
{
char test_code[] = R"(
type Point2D = x:double y:double
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_EQ(TYPE_NODE, node->node_type);
string type_str = to_string(node->type);
ASSERT_EQ(TYPE_EXT, node->type->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testFunctionTypeAnnotation)
{
char test_code[] = R"(
print x:int = printf "%d" x
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("print", string_get(node->func->func_type->ft->name));
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(2, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("int -> int", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testFunctionTypeAnnotationWithParentheses)
{
char test_code[] = R"(
prt (x:int) = printf "%d" x
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("prt", string_get(node->func->func_type->ft->name));
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(2, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("int -> int", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testFunctionTypeAnnotationWithReturnType)
{
char test_code[] = R"(
prt (x:int):int = printf "%d" x
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
ASSERT_EQ(1, array_size(&block->block->nodes));
ASSERT_STREQ("prt", string_get(node->func->func_type->ft->name));
ASSERT_EQ(FUNCTION_NODE, node->node_type);
auto var = (type_oper *)node->type;
ASSERT_EQ(TYPE_FUNCTION, var->base.type);
ASSERT_EQ(2, array_size(&var->args));
string type_str = to_string(node->type);
ASSERT_STREQ("int -> int", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testVariableWithScope)
{
char test_code[] = R"(
x = 10
getx()=
x = 1.3
x
getx()
x
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
ASSERT_EQ(4, array_size(&block->block->nodes));
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
string type_str = to_string(node->type);
ASSERT_STREQ("int", string_get(&type_str));
/*fun definition*/
node = *(ast_node **)array_get(&block->block->nodes, 1);
type_str = to_string(node->type);
ASSERT_STREQ("() -> double", string_get(&type_str));
node = *(ast_node **)array_get(&block->block->nodes, 2);
ASSERT_EQ(CALL_NODE, node->node_type);
type_str = to_string(node->type);
ASSERT_STREQ("double", string_get(&type_str));
node = *(ast_node **)array_get(&block->block->nodes, 3);
ASSERT_EQ(IDENT_NODE, node->node_type);
type_str = to_string(node->type);
ASSERT_STREQ("int", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testRedefinitionInTheSameScropeIsNotAllowed)
{
char test_code[] = R"(
x = 10.0
x = 10
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
ASSERT_EQ(2, array_size(&block->block->nodes));
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
string type_str = to_string(node->type);
ASSERT_STREQ("double", string_get(&type_str));
/*fun definition*/
node = *(ast_node **)array_get(&block->block->nodes, 1);
type_str = to_string(node->type);
ASSERT_STREQ("type mismatch", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testStructTypeVariables)
{
char test_code[] = R"(
type Point2D = x:double y:double
xy:Point2D = 0.0 0.0
xy.x
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
ASSERT_EQ(3, array_size(&block->block->nodes));
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
string type_str = to_string(node->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
node = *(ast_node **)array_get(&block->block->nodes, 1);
type_str = to_string(node->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
node = *(ast_node **)array_get(&block->block->nodes, 2);
ASSERT_EQ(IDENT_NODE, node->node_type);
struct ast_node *id_node = node;
ASSERT_STREQ("xy.x", string_get(id_node->ident->name));
type_str = to_string(node->type);
ASSERT_STREQ("double", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testStructTypeVariablesNewForm)
{
char test_code[] = R"(
type Point2D = x:double y:double
xy = Point2D 10.0 20.0
xy.x
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
ASSERT_EQ(3, array_size(&block->block->nodes));
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
string type_str = to_string(node->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
node = *(ast_node **)array_get(&block->block->nodes, 1);
type_str = to_string(node->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
node = *(ast_node **)array_get(&block->block->nodes, 2);
ASSERT_EQ(IDENT_NODE, node->node_type);
struct ast_node *id_node = node;
ASSERT_STREQ("xy.x", string_get(id_node->ident->name));
type_str = to_string(node->type);
ASSERT_STREQ("double", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testStructTypeLocalVariables)
{
char test_code[] = R"(
type Point2D = x:double y:double
getx()=
xy:Point2D = 10.0 0.0
xy.x
getx()
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
ASSERT_EQ(3, array_size(&block->block->nodes));
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
string type_str = to_string(node->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
/*fun definition*/
node = *(ast_node **)array_get(&block->block->nodes, 1);
type_str = to_string(node->type);
ASSERT_STREQ("() -> double", string_get(&type_str));
node = *(ast_node **)array_get(&block->block->nodes, 2);
ASSERT_EQ(CALL_NODE, node->node_type);
type_str = to_string(node->type);
ASSERT_STREQ("double", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testStructTypeLocalVariablesNewForm)
{
char test_code[] = R"(
type Point2D = x:double y:double
getx()=
xy = Point2D 10.0 0.0
xy.x
getx()
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
ASSERT_EQ(3, array_size(&block->block->nodes));
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
string type_str = to_string(node->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
/*fun definition*/
node = *(ast_node **)array_get(&block->block->nodes, 1);
type_str = to_string(node->type);
ASSERT_STREQ("() -> double", string_get(&type_str));
node = *(ast_node **)array_get(&block->block->nodes, 2);
ASSERT_EQ(CALL_NODE, node->node_type);
type_str = to_string(node->type);
ASSERT_STREQ("double", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testStructTypeReturn)
{
char test_code[] = R"(
type Point2D = x:double y:double
getx()=
xy:Point2D = 10.0 0.0
xy
z = getx()
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
ASSERT_EQ(3, array_size(&block->block->nodes));
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
string type_str = to_string(node->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
/*fun definition*/
node = *(ast_node **)array_get(&block->block->nodes, 1);
type_str = to_string(node->type);
ASSERT_STREQ("() -> Point2D", string_get(&type_str));
/*variable node*/
node = *(ast_node **)array_get(&block->block->nodes, 2);
ASSERT_EQ(VAR_NODE, node->node_type);
struct ast_node *var = node;
/*initial value is a call expression*/
ASSERT_EQ(CALL_NODE, var->var->init_value->node_type);
type_str = to_string(var->var->init_value->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
type_str = to_string(var->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
/*verify variable xy in inner function is out of scope*/
symbol xy = to_symbol("xy");
ASSERT_EQ(false, has_symbol(&env->cg->sema_context->decl_2_typexps, xy));
env_free(env);
}
TEST(testAnalyzer, testStructTypeReturnNewForm)
{
char test_code[] = R"(
type Point2D = x:double y:double
getx()=
xy = Point2D 10.0 0.0
xy
z = getx()
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
ASSERT_EQ(3, array_size(&block->block->nodes));
emit_code(env, (ast_node *)block);
auto node = *(ast_node **)array_front(&block->block->nodes);
string type_str = to_string(node->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
/*fun definition*/
node = *(ast_node **)array_get(&block->block->nodes, 1);
type_str = to_string(node->type);
ASSERT_STREQ("() -> Point2D", string_get(&type_str));
/*variable node*/
node = *(ast_node **)array_get(&block->block->nodes, 2);
ASSERT_EQ(VAR_NODE, node->node_type);
struct ast_node *var = node;
/*initial value is a call expression*/
ASSERT_EQ(CALL_NODE, var->var->init_value->node_type);
type_str = to_string(var->var->init_value->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
type_str = to_string(var->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
/*verify variable xy in inner function is out of scope*/
symbol xy = to_symbol("xy");
ASSERT_EQ(false, has_symbol(&env->cg->sema_context->decl_2_typexps, xy));
env_free(env);
}
TEST(testAnalyzer, testStructTypeReturnNoNamed)
{
char test_code[] = R"(
type Point2D = x:double y:double
get_point() = Point2D 10.0 0.0
z() = get_point()
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
ASSERT_EQ(3, array_size(&block->block->nodes));
emit_code(env, (ast_node *)block);
//1. type definition
auto node = *(ast_node **)array_front(&block->block->nodes);
string type_str = to_string(node->type);
ASSERT_STREQ("Point2D", string_get(&type_str));
//2. function definition
node = *(ast_node **)array_get(&block->block->nodes, 1);
type_str = to_string(node->type);
ASSERT_STREQ("() -> Point2D", string_get(&type_str));
//3. function definition again
node = *(ast_node **)array_get(&block->block->nodes, 2);
ASSERT_EQ(FUNCTION_NODE, node->node_type);
type_str = to_string(node->type);
ASSERT_STREQ("() -> Point2D", string_get(&type_str));
env_free(env);
}
TEST(testAnalyzer, testReturnValueFlag)
{
char test_code[] = R"(
getx()=
x = 10
y = x + 1
y
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
ASSERT_EQ(1, array_size(&block->block->nodes));
emit_code(env, (ast_node *)block);
/*validate fun definition*/
auto node = *(ast_node **)array_get(&block->block->nodes, 0);
auto type_str = to_string(node->type);
ASSERT_STREQ("() -> int", string_get(&type_str));
/*validate inside functions*/
auto fun = (ast_node *)node;
auto var_x = *(ast_node **)array_get(&fun->func->body->block->nodes, 0);
auto var_y = *(ast_node **)array_get(&fun->func->body->block->nodes, 1);
ASSERT_EQ(false, var_x->is_ret);
ASSERT_EQ(true, var_y->is_ret);
env_free(env);
}
TEST(testAnalyzer, testReturnExpression)
{
char test_code[] = R"(
getx()=
x = 10
x + 1
)";
env *env = env_new(false);
create_ir_module(env->cg, "test");
ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code);
ASSERT_EQ(1, array_size(&block->block->nodes));
emit_code(env, (ast_node *)block);
/*validate fun definition*/
auto node = *(ast_node **)array_get(&block->block->nodes, 0);
auto type_str = to_string(node->type);
ASSERT_STREQ("() -> int", string_get(&type_str));
/*validate inside functions*/
auto fun = (ast_node *)node;
auto var_x = *(ast_node **)array_get(&fun->func->body->block->nodes, 0);
auto exp = *(ast_node **)array_get(&fun->func->body->block->nodes, 1);
ASSERT_EQ(false, var_x->is_ret);
ASSERT_EQ(BINARY_NODE, exp->node_type);
env_free(env);
}
| 36.154626 | 87 | 0.660836 | ligangwang |
e939075a417e77963819f7de45b5c08465e91cea | 2,463 | cpp | C++ | Wml/Source/Intersection/WmlIntrLin3Loz3.cpp | 1iyiwei/deform2d | 1a350dd20f153e72de1ea9cffb873eb67bf3d668 | [
"MIT"
] | 26 | 2018-07-04T15:31:11.000Z | 2021-09-23T02:43:46.000Z | Wml/Source/Intersection/WmlIntrLin3Loz3.cpp | 1iyiwei/deform2d | 1a350dd20f153e72de1ea9cffb873eb67bf3d668 | [
"MIT"
] | null | null | null | Wml/Source/Intersection/WmlIntrLin3Loz3.cpp | 1iyiwei/deform2d | 1a350dd20f153e72de1ea9cffb873eb67bf3d668 | [
"MIT"
] | 1 | 2019-06-11T03:20:28.000Z | 2019-06-11T03:20:28.000Z | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2004. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlIntrLin3Loz3.h"
#include "WmlDistLin3Rct3.h"
using namespace Wml;
//----------------------------------------------------------------------------
template <class Real>
bool Wml::TestIntersection (const Segment3<Real>& rkSegment,
const Lozenge3<Real>& rkLozenge)
{
Real fSqrDist = SqrDistance(rkSegment,rkLozenge.Rectangle());
return fSqrDist <= rkLozenge.Radius()*rkLozenge.Radius();
}
//----------------------------------------------------------------------------
template <class Real>
bool Wml::TestIntersection (const Ray3<Real>& rkRay,
const Lozenge3<Real>& rkLozenge)
{
Real fSqrDist = SqrDistance(rkRay,rkLozenge.Rectangle());
return fSqrDist <= rkLozenge.Radius()*rkLozenge.Radius();
}
//----------------------------------------------------------------------------
template <class Real>
bool Wml::TestIntersection (const Line3<Real>& rkLine,
const Lozenge3<Real>& rkLozenge)
{
Real fSqrDist = SqrDistance(rkLine,rkLozenge.Rectangle());
return fSqrDist <= rkLozenge.Radius()*rkLozenge.Radius();
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
namespace Wml
{
template WML_ITEM bool TestIntersection<float> (
const Segment3<float>&, const Lozenge3<float>&);
template WML_ITEM bool TestIntersection<float> (
const Ray3<float>&, const Lozenge3<float>&);
template WML_ITEM bool TestIntersection<float> (
const Line3<float>&, const Lozenge3<float>&);
template WML_ITEM bool TestIntersection<double> (
const Segment3<double>&, const Lozenge3<double>&);
template WML_ITEM bool TestIntersection<double> (
const Ray3<double>&, const Lozenge3<double>&);
template WML_ITEM bool TestIntersection<double> (
const Line3<double>&, const Lozenge3<double>&);
}
//----------------------------------------------------------------------------
| 40.377049 | 79 | 0.556232 | 1iyiwei |
e940b4be85a624b4ba9cf03cc80366adf9e6af7a | 2,777 | cpp | C++ | aesc/render/render.cpp | ExternalRepositories/ansi-escape | 5019e1d0530100722005acf361d0fa0932021454 | [
"MIT"
] | null | null | null | aesc/render/render.cpp | ExternalRepositories/ansi-escape | 5019e1d0530100722005acf361d0fa0932021454 | [
"MIT"
] | 15 | 2019-10-08T12:28:29.000Z | 2020-10-07T06:55:05.000Z | aesc/render/render.cpp | ExternalRepositories/ansi-escape | 5019e1d0530100722005acf361d0fa0932021454 | [
"MIT"
] | 1 | 2021-04-02T20:44:21.000Z | 2021-04-02T20:44:21.000Z | /*
* Wrap the Select Graphic Rendition codes
*/
#include "aesc/render/render.hpp"
#include "aesc/internal/sequences.hpp"
#include "aesc/render/internal.hpp"
namespace aesc { // Ansi Escape Terminal
inline namespace render { // Select Graphic Rendition
namespace {
constexpr const char* reset_expr = "0";
constexpr const char* bold_expr = "1";
constexpr const char* faint_expr = "2";
constexpr const char* italic_expr = "3";
constexpr const char* underline_expr = "4";
constexpr const char* slow_blink_expr = "5";
constexpr const char* rapid_blink_expr = "6";
constexpr const char* reverse_expr = "7";
constexpr const char* cross_out_expr = "9";
constexpr const char* reset_intensity_expr = "22";
constexpr const char* cancel_underline_expr = "24";
constexpr const char* cancel_blink_expr = "25";
constexpr const char* cancel_inverse_expr = "27";
constexpr const char* cancel_cross_out_expr = "29";
} // anonymous namespace
std::ostream& reset(std::ostream& stream) {
stream << CSI_expr << reset_expr << end_expr;
return stream;
}
std::ostream& bold(std::ostream& stream) {
stream << CSI_expr << bold_expr << end_expr;
return stream;
}
std::ostream& faint(std::ostream& stream) {
stream << CSI_expr << faint_expr << end_expr;
return stream;
}
std::ostream& italic(std::ostream& stream) {
stream << CSI_expr << italic_expr << end_expr;
return stream;
}
std::ostream& underline(std::ostream& stream) {
stream << CSI_expr << underline_expr << end_expr;
return stream;
}
namespace blink {
std::ostream& slow(std::ostream& stream) {
stream << CSI_expr << slow_blink_expr << end_expr;
return stream;
}
std::ostream& rapid(std::ostream& stream) {
stream << CSI_expr << rapid_blink_expr << end_expr;
return stream;
}
} // namespace blink
std::ostream& reverse_color(std::ostream& stream) {
stream << CSI_expr << reverse_expr << end_expr;
return stream;
}
std::ostream& cross_out(std::ostream& stream) {
stream << CSI_expr << cross_out_expr << end_expr;
return stream;
}
std::ostream& reset_intensity(std::ostream& stream) {
stream << CSI_expr << reset_intensity_expr << end_expr;
return stream;
}
std::ostream& cancel_underline(std::ostream& stream) {
stream << CSI_expr << cancel_underline_expr << end_expr;
return stream;
}
std::ostream& cancel_blink(std::ostream& stream) {
stream << CSI_expr << cancel_blink_expr << end_expr;
return stream;
}
std::ostream& cancel_inverse(std::ostream& stream) {
stream << CSI_expr << cancel_inverse_expr << end_expr;
return stream;
}
std::ostream& cancel_cross_out(std::ostream& stream) {
stream << CSI_expr << cancel_cross_out_expr << end_expr;
return stream;
}
} // namespace render
} // namespace aesc
| 25.712963 | 60 | 0.697875 | ExternalRepositories |
e941f9a0997255a80bf6e6d0d68620c9cdeb3cfd | 16,557 | hpp | C++ | DataStructures/HashMap/include/hash_map/hash_map_bucket.hpp | kant/Always-be-learning | 7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5 | [
"Unlicense"
] | null | null | null | DataStructures/HashMap/include/hash_map/hash_map_bucket.hpp | kant/Always-be-learning | 7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5 | [
"Unlicense"
] | null | null | null | DataStructures/HashMap/include/hash_map/hash_map_bucket.hpp | kant/Always-be-learning | 7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5 | [
"Unlicense"
] | null | null | null | #ifndef DATA_STRUCTURES_HASH_MAP_BUCKET_HPP
#define DATA_STRUCTURES_HASH_MAP_BUCKET_HPP
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <memory>
#include <type_traits>
#include <utility>
#include <forward_list>
#include "utils/Assertion.h"
#include "utils/traits.h"
// template<typename Derived>
struct BucketNodeBase {
mutable BucketNodeBase* next{nullptr};
constexpr BucketNodeBase() noexcept = default;
constexpr BucketNodeBase(BucketNodeBase&& other) noexcept : next{std::move(other.next)}
{
other.next = nullptr;
}
constexpr BucketNodeBase& operator=(BucketNodeBase&& other) noexcept
{
next = std::move(other.next);
other.next = nullptr;
return *this;
}
BucketNodeBase(BucketNodeBase const&) = delete;
BucketNodeBase& operator=(BucketNodeBase const&) = delete;
~BucketNodeBase() noexcept = default;
// decltype(auto) data() & noexcept { return derived().data; }
// decltype(auto) data() const& noexcept { return derived().data; }
// decltype(auto) data() && noexcept { return derived().data; }
// decltype(auto) data() const&& noexcept { return derived().data; }
// Derived& derived() & noexcept { return static_cast<Derived&>(*this); }
// Derived const& derived() const& noexcept { return static_cast<Derived const&>(*this); }
// Derived&& derived() && noexcept { return static_cast<Derived&&>(*this); }
// Derived const&& derived() const&& noexcept { return static_cast<Derived const&&>(*this); }
};
template <typename Key, typename T>
struct BucketNode : public BucketNodeBase
{
using value_type = std::pair<const Key, T>;
using key_type = Key;
using mapped_type = T;
constexpr BucketNode() noexcept(std::is_nothrow_default_constructible_v<value_type>) = default;
template<typename... Args>
constexpr BucketNode(Args&&... args) noexcept(std::is_nothrow_constructible_v<value_type, Args&&...>)
: data{std::forward<Args>(args)...} { }
value_type data;
};
template<typename NodeType, typename Reference>
class HashMapBucketIterator;
template<typename Key, typename T, typename Allocator = std::allocator<BucketNode<Key, T>>>
class HashMapBucket {
public:
using NodeBase = BucketNodeBase;
using Node = BucketNode<Key, T>;
private:
using AllocatorTraits = std::allocator_traits<Allocator>;
using Alloc = typename AllocatorTraits::template rebind_alloc<Node>;
using AllocTraits = std::allocator_traits<Alloc>;
using Self = HashMapBucket;
Alloc alloc_{};
NodeBase head_{};
public:
using value_type = typename Node::value_type;
using key_type = typename Node::key_type;
using mapped_type = typename Node::mapped_type;
using reference = std::add_lvalue_reference_t<value_type>;
using const_reference = std::add_lvalue_reference_t<std::add_const_t<value_type>>;
using pointer = std::add_pointer_t<value_type>;
using const_pointer = std::add_pointer_t<std::add_const_t<value_type>>;
using difference_type = typename AllocTraits::difference_type;
using size_type = std::size_t;
using iterator = HashMapBucketIterator<Node, reference>;
using const_iterator = HashMapBucketIterator<Node const, const_reference>;
// --- constructors
HashMapBucket() noexcept = default;
template<typename InputIt, typename = RequiresInputIterator<InputIt>>
HashMapBucket(InputIt first, InputIt last)
{
if (first != last) {
auto nodes{make_range(first, last)};
head_.next = nodes.first;
}
}
HashMapBucket(HashMapBucket const& other)
: alloc_{AllocTraits::select_on_container_copy_construction(other.alloc_)}
{
if (!other.empty()) {
auto nodes{make_range(other.cbegin(), other.cend())};
head_.next = nodes.first;
}
}
HashMapBucket(HashMapBucket&& other) noexcept
: alloc_{std::move(other.alloc_)}, head_{std::move(other.head_)} { }
// HashMapBucket& operator=(HashMapBucket const&);
HashMapBucket& operator=(HashMapBucket&& other) noexcept
{
if (AllocTraits::propagate_on_container_move_assignment::value) {
alloc_ = std::move(other.alloc_);
}
head_ = std::move(other.head_);
return *this;
}
~HashMapBucket() noexcept { free(); }
// --- iterators
iterator before_begin() noexcept { return iterator{static_cast<Node*>(&head_)}; }
const_iterator before_begin() const noexcept { return const_iterator{static_cast<Node const*>(&head_)}; }
const_iterator before_cbegin() const noexcept { return const_iterator{static_cast<Node const*>(&head_)}; }
iterator begin() noexcept { return iterator{static_cast<Node*>(head_.next)}; }
const_iterator begin() const noexcept { return const_iterator{static_cast<Node*>(head_.next)}; }
const_iterator cbegin() const noexcept { return const_iterator{static_cast<Node*>(head_.next)}; }
iterator end() noexcept { return iterator{}; }
const_iterator end() const noexcept { return const_iterator{}; }
const_iterator cend() const noexcept { return const_iterator{}; }
// --- capacity
bool empty() const noexcept { return head_.next == nullptr; }
size_type size() const noexcept
{
size_type count{0};
for (NodeBase* n{head_.next}; n != nullptr; n = n->next) {
++count;
}
return count;
}
void clear() noexcept { free(); }
void push_front(value_type const& value)
{
Node* nn{make_node(value)};
insert_front(nn);
}
void push_front(value_type&& value)
{
Node* nn{make_node(std::move(value))};
insert_front(nn);
}
template<typename P, typename = std::enable_if_t<std::is_convertible_v<P&&, value_type>>>
std::pair<iterator, bool> insert_unique(P&& value)
{
auto const it{std::find_if(begin(), end(),
[&key=value.first](auto const& v)noexcept { return v.first == key; })
};
if (it != end()) { return {it, false}; }
else {
push_front(std::forward<P>(value));
return {begin(), true};
}
}
iterator find(key_type const& key) noexcept
{
return std::find_if(begin(), end(), [&key](auto const& v)noexcept { return v.first == key; });
}
const_iterator find(key_type const& key) const noexcept
{
return std::find_if(cbegin(), cend(), [&key](auto const& v)noexcept { return v.first == key; });
}
template<typename K, typename... Args>
iterator find_iter(K&& key, Args&&... args) const noexcept
{
return std::find_if(begin(), end(), [&key](auto const& v)noexcept { return v.first == key; });
}
template<typename... Args>
std::pair<iterator, bool> emplace_unique(Args&&... args)
{
auto const it{find_iter(args...)};
if (it != end()) { return {it, false}; }
else {
emplace_front(std::forward<Args>(args)...);
return {begin(), true};
}
}
template<typename M, typename = std::enable_if_t<std::is_convertible_v<M&&, mapped_type>>>
std::pair<iterator, bool> insert_or_assign(key_type const& key, M&& value)
{
auto const it{std::find_if(begin(), end(),
[&key=key](auto const& v)noexcept { return v.first == key; })
};
if (it != end()) {
it->second = std::forward<M>(value);
return {it, false};
}
else {
push_front({key, std::forward<M>(value)});
return {begin(), true};
}
}
template<typename M, typename = std::enable_if_t<std::is_convertible_v<M&&, mapped_type>>>
std::pair<iterator, bool> insert_or_assign(key_type&& key, M&& value)
{
auto const it{std::find_if(begin(), end(),
[&key=key](auto const& v)noexcept { return v.first == key; })
};
if (it != end()) {
it->second = std::forward<M>(value);
return {it, false};
}
else {
push_front({std::move(key), std::forward<M>(value)});
return {begin(), true};
}
}
template<typename... Args>
std::pair<iterator, bool> try_emplace(key_type const& key, Args&&... args)
{
auto const it{std::find_if(begin(), end(),
[&key=key](auto const& v) noexcept { return v.first == key; }
)};
if (it != end()) {
return {it, false};
}
else {
emplace_front(key, std::forward<Args>(args)...);
return {begin(), true};
}
}
template<typename... Args>
std::pair<iterator, bool> try_emplace(key_type&& key, Args&&... args)
{
auto const it{std::find_if(begin(), end(),
[&key=key](auto const& v) noexcept { return v.first == key; }
)};
if (it != end()) {
return {it, false};
}
else {
emplace_front(std::move(key), std::forward<Args>(args)...);
return {begin(), true};
}
}
template<typename... Args>
void emplace_front(Args&&... args)
{
Node* nn{make_node(std::forward<Args>(args)...)};
insert_front(nn);
}
iterator insert_after(const_iterator pos, value_type const& value)
{
Node* nn{make_node(value)};
return insert_after(pos.node_, nn);
}
iterator insert_after(const_iterator pos, value_type&& value)
{
Node* nn{make_node(std::move(value))};
return insert_after(pos.node_, nn);
}
template<typename InputIt>
iterator insert_after(const_iterator pos, InputIt first, InputIt last)
{
Node* p{const_cast<Node*>(pos.node_)};
while (first != last) {
Node* nn{make_node(*first)};
insert_after(p, nn);
p = nn;
++first;
}
return iterator{p};
}
template<typename... Args>
iterator emplace_after(const_iterator pos, Args&&... args)
{
Node* nn{make_node(std::forward<Args>(args)...)};
return insert_after(pos.node_, nn);
}
size_type erase(key_type const& key) noexcept
{
size_type count{0};
for (Node* n{static_cast<Node*>(&head_)}; n != nullptr && n->next != nullptr; n = static_cast<Node*>(n->next)) {
if (static_cast<Node*>(n->next)->data.first == key) {
erase_after(n);
++count;
}
}
return count;
}
iterator erase_after(const_iterator pos) noexcept
{
erase_after(pos->node_);
return iterator{pos->node_->next};
}
iterator erase(const_iterator pos) noexcept
{
auto pred{before_begin()};
auto it{begin()};
while (/* it != end() && */ it != pos) {
pred = it;
++it;
}
JAM_ENSURE(it == pos, "Invalid erase position");
erase_after(pred.node_);
return iterator{++pred};
}
protected:
template<typename... Args>
Node* make_node(Args&&... args)
{
Node* nn{AllocTraits::allocate(alloc_, 1)};
AllocTraits::construct(alloc_, nn, std::forward<Args>(args)...);
return nn;
}
template<typename... Args>
std::pair<Node*, Node*> make_n(size_type count, Args&&... args)
{
// keep allocating and linking nodes until count == 0;
Node* nn{make_node(args...)};
Node* front{nn};
while (--count) {
Node* next_node{make_node(args...)};
// link_nodes(nn, next_node);
nn->next = next_node;
nn = next_node;
}
return {front, nn};
}
template<typename Iter>
std::pair<Node*, Node*> make_range(Iter first, Iter last)
{
JAM_EXPECT(first != last, "Range must contain at least one value");
Node* nn{make_node(*first)};
Node* front{nn};
while (++first != last) {
Node* next_node{make_node(*first)};
nn->next = next_node;
nn = next_node;
}
return {front, nn};
}
void insert_front(NodeBase* node) noexcept
{
node->next = head_.next;
head_.next = node;
}
static iterator insert_after(const NodeBase* pos, NodeBase* node) noexcept
{
node->next = pos->next;
pos->next = node;
return iterator{static_cast<Node*>(node)};
}
void erase_after(NodeBase* node) noexcept
{
JAM_EXPECT(node != nullptr, "nullptr node");
Node* to_free{static_cast<Node*>(node->next)};
node->next = to_free->next;
free(to_free);
}
void free(Node* node) noexcept
{
AllocTraits::destroy(alloc_, node);
AllocTraits::deallocate(alloc_, node, 1);
}
void free() noexcept
{
Node* node{static_cast<Node*>(head_.next)};
while (node != nullptr) {
Node* temp{node};
node = static_cast<Node*>(node->next);
free(temp);
}
}
};
template<typename NodeType, typename Reference>
class HashMapBucketIterator
{
using Node = NodeType;
using Self = HashMapBucketIterator;
template<typename K, typename T, typename Alloc> friend class HashMapBucket;
template<typename N, typename R> friend class HashMapBucketIterator;
Node* node_{nullptr};
public:
using iterator_category = std::forward_iterator_tag;
using value_type = std::remove_reference_t<std::remove_const_t<Reference>>;
using reference = Reference;
using pointer = std::add_pointer_t<std::remove_reference_t<Reference>>;
using difference_type = std::ptrdiff_t;
using const_iterator = HashMapBucketIterator<Node, std::add_lvalue_reference_t<std::add_const_t<value_type>>>;
constexpr HashMapBucketIterator() noexcept = default;
constexpr explicit HashMapBucketIterator(Node* node) noexcept : node_{node} { }
template<typename N2, typename R2>
constexpr explicit HashMapBucketIterator(HashMapBucketIterator<N2, R2> other)
: node_{const_cast<Node*>(other.node_)}
{
}
constexpr HashMapBucketIterator(HashMapBucketIterator const& other) noexcept
: node_{other.node_}
{
}
constexpr HashMapBucketIterator(HashMapBucketIterator&& other) noexcept
: node_{std::move(other.node_)}
{
}
HashMapBucketIterator& operator=(HashMapBucketIterator const& other) noexcept = default;
HashMapBucketIterator& operator=(HashMapBucketIterator&& other) noexcept = default;
template<typename N2, typename R2>
HashMapBucketIterator& operator=(HashMapBucketIterator<N2, R2> other) noexcept
{
node_ = const_cast<Node*>(other.node_);
return *this;
}
constexpr reference operator*() const noexcept { return node_->data; }
constexpr pointer operator->() const noexcept { return &(operator*()); }
constexpr Self& operator++() noexcept
{
node_ = static_cast<Node*>(node_->next);
return *this;
}
constexpr Self operator++(int) noexcept
{
auto res{*this};
operator++();
return res;
}
constexpr operator const_iterator() const noexcept { return const_iterator{node_}; }
constexpr bool operator==(Self const& other) const noexcept { return node_ == other.node_; }
constexpr bool operator!=(Self const& other) const noexcept { return node_ != other.node_; }
template<typename N1, typename N2, typename R1, typename R2> friend constexpr
bool operator==(HashMapBucketIterator<N1, R1> const& lhs, HashMapBucketIterator<N2, R2> const& rhs) noexcept;
template<typename N1, typename N2, typename R1, typename R2> friend constexpr
bool operator!=(HashMapBucketIterator<N1, R1> const& lhs, HashMapBucketIterator<N2, R2> const& rhs) noexcept;
};
template<typename N1, typename N2, typename R1, typename R2> constexpr
bool operator==(HashMapBucketIterator<N1, R1> const& lhs, HashMapBucketIterator<N2, R2> const& rhs) noexcept
{
return lhs.node_ == rhs.node_;
}
template<typename N1, typename N2, typename R1, typename R2> constexpr
bool operator!=(HashMapBucketIterator<N1, R1> const& lhs, HashMapBucketIterator<N2, R2> const& rhs) noexcept
{
return lhs.node_ != rhs.node_;
}
#endif // DATA_STRUCTURES_HASH_MAP_BUCKET_HPP
| 33.313883 | 121 | 0.613457 | kant |
e94311f08e55bd0801b00c03edc1fb5cdbeec616 | 3,814 | cpp | C++ | tests/class_destruction_with_annotation.cpp | preempt/fruit | 9ea3e31b63836797ec7ba1dd759ead8c00d0d227 | [
"Apache-2.0"
] | null | null | null | tests/class_destruction_with_annotation.cpp | preempt/fruit | 9ea3e31b63836797ec7ba1dd759ead8c00d0d227 | [
"Apache-2.0"
] | null | null | null | tests/class_destruction_with_annotation.cpp | preempt/fruit | 9ea3e31b63836797ec7ba1dd759ead8c00d0d227 | [
"Apache-2.0"
] | null | null | null | // expect-success
/*
* Copyright 2014 Google 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 <fruit/fruit.h>
#include "test_macros.h"
using fruit::Component;
using fruit::Injector;
struct Annotation {};
// The shared_ptr objects below ensure (since these tests are run under Valgrind) that deletion occurs, and only once.
struct I1 {
std::shared_ptr<int> x = std::make_shared<int>(3);
virtual ~I1() {}
};
struct I2 {
std::shared_ptr<int> x = std::make_shared<int>(3);
};
struct I3 {
std::shared_ptr<int> x = std::make_shared<int>(3);
};
struct I4 {
std::shared_ptr<int> x = std::make_shared<int>(3);
};
struct X1 : I1 {
using Inject = X1();
std::shared_ptr<int> x = std::make_shared<int>(3);
};
struct X2 : I2 {
// Taking an X1 here prevents binding compression.
using Inject = X2(fruit::Annotated<Annotation, X1>);
X2(X1) {}
std::shared_ptr<int> x = std::make_shared<int>(3);
};
struct X3 : public I3 {
std::shared_ptr<int> x = std::make_shared<int>(3);
};
struct X4 : public I4 {
// Taking an X3 here prevents binding compression.
X4(X3) {};
std::shared_ptr<int> x = std::make_shared<int>(3);
};
struct X5 {
std::shared_ptr<int> x = std::make_shared<int>(3);
};
struct X6 : public I1 {
using Inject = X6();
X6() = default;
std::shared_ptr<int> x = std::make_shared<int>(3);
};
struct X7 : public I1 {
std::shared_ptr<int> x = std::make_shared<int>(3);
};
struct X8 : public I1 {
std::shared_ptr<int> x = std::make_shared<int>(3);
virtual ~X8() {}
};
using I1Annot = fruit::Annotated<Annotation, I1>;
using I2Annot = fruit::Annotated<Annotation, I2>;
using I3Annot = fruit::Annotated<Annotation, I3>;
using I4Annot = fruit::Annotated<Annotation, I4>;
using X1Annot = fruit::Annotated<Annotation, X1>;
using X2Annot = fruit::Annotated<Annotation, X2>;
using X3Annot = fruit::Annotated<Annotation, X3>;
using X4Annot = fruit::Annotated<Annotation, X4>;
using X5Annot = fruit::Annotated<Annotation, X5>;
using X6Annot = fruit::Annotated<Annotation, X6>;
using X7Annot = fruit::Annotated<Annotation, X7>;
using X8Annot = fruit::Annotated<Annotation, X8>;
Component<I1Annot, I2Annot, I3Annot, I4Annot, X5Annot> getComponent() {
static X5 x5;
static std::unique_ptr<I1> x7(new X7());
return fruit::createComponent()
.bind<I1Annot, X1Annot>()
.bind<I2Annot, X2Annot>()
.bind<I3Annot, X3Annot>()
.bind<I4Annot, X4Annot>()
.registerProvider<X3Annot()>([]() { return X3(); })
.registerProvider<X4Annot(X3Annot)>([](X3 x3) { return X4(x3); })
.bindInstance<X5Annot>(x5)
.addMultibinding<I1Annot, X6Annot>()
.addInstanceMultibinding<X7Annot>(*x7)
.addMultibindingProvider<fruit::Annotated<Annotation, X1*>()>([]() { return (X1*) new X8(); });
}
int main() {
// Create an injector without creating any instances.
Injector<I1Annot, I2Annot, I3Annot, I4Annot, X5Annot> injector1(getComponent());
// And an injector where we do create the instances.
Injector<I1Annot, I2Annot, I3Annot, I4Annot, X5Annot> injector2(getComponent());
injector2.get<I1Annot>();
injector2.get<I2Annot>();
injector2.get<I3Annot>();
injector2.get<I4Annot>();
injector2.get<X5Annot>();
injector2.getMultibindings<I1Annot>();
return 0;
}
| 28.462687 | 118 | 0.684583 | preempt |
e9448e421b170fc05fd93e559f978d0aa21b85db | 33,689 | cpp | C++ | svo/src/initialization.cpp | jsz0913/rpg_dvs_evo_open | 93edc7a2d215ed097e3f6a9abbefd0b572958b74 | [
"BSD-2-Clause-Patent"
] | 97 | 2021-06-24T09:34:08.000Z | 2022-02-28T01:58:09.000Z | svo/src/initialization.cpp | jsz0913/rpg_dvs_evo_open | 93edc7a2d215ed097e3f6a9abbefd0b572958b74 | [
"BSD-2-Clause-Patent"
] | 14 | 2021-06-14T13:01:27.000Z | 2022-03-30T01:49:57.000Z | svo/src/initialization.cpp | jsz0913/rpg_dvs_evo_open | 93edc7a2d215ed097e3f6a9abbefd0b572958b74 | [
"BSD-2-Clause-Patent"
] | 32 | 2021-06-24T09:34:12.000Z | 2022-03-01T15:23:29.000Z | // This file is part of SVO - Semi-direct Visual Odometry.
//
// Copyright (C) 2014 Christian Forster <forster at ifi dot uzh dot ch>
// (Robotics and Perception Group, University of Zurich, Switzerland).
//
// This file is subject to the terms and conditions defined in the file
// 'LICENSE', which is part of this source code package.
#include <svo/initialization.h>
#include <random> // std::mt19937
#include <vector>
#include <svo/common/frame.h>
#include <svo/common/point.h>
#include <svo/common/camera.h>
#include <svo/common/container_helpers.h>
#include <svo/direct/feature_detection.h>
#include <svo/direct/feature_detection_utils.h>
#include <svo/direct/feature_alignment.h>
#include <svo/direct/matcher.h>
#include <svo/stereo_triangulation.h>
#include <svo/pose_optimizer.h>
#include <svo/tracker/feature_tracker.h>
#include <svo/tracker/feature_tracking_utils.h>
#include <vikit/cameras/ncamera.h>
#include <vikit/math_utils.h>
#include <vikit/homography.h>
#include <vikit/sample.h>
#include <opencv2/video/tracking.hpp> // for lucas kanade tracking
#include <opencv2/opencv.hpp> // for display
#ifdef SVO_USE_OPENGV
// used for opengv
# include <opengv/sac/Ransac.hpp>
// used for TwoPoint and FivePoint
# include <opengv/sac_problems/relative_pose/TranslationOnlySacProblem.hpp>
# include <opengv/sac_problems/relative_pose/CentralRelativePoseSacProblem.hpp>
# include <opengv/relative_pose/methods.hpp>
# include <opengv/relative_pose/CentralRelativeAdapter.hpp>
# include <opengv/triangulation/methods.hpp>
// used for array
# include <opengv/relative_pose/NoncentralRelativeAdapter.hpp>
# include <opengv/sac_problems/relative_pose/NoncentralRelativePoseSacProblem.hpp>
#endif
#ifdef SVO_USE_GTSAM
# include <gtsam/geometry/SimpleCamera.h>
# include <gtsam/linear/NoiseModel.h>
# include <gtsam/nonlinear/Values.h>
# include <gtsam/nonlinear/NonlinearFactorGraph.h>
# include <gtsam/slam/PriorFactor.h>
# include <gtsam/slam/ProjectionFactor.h>
# include <gtsam/inference/Symbol.h>
# include <gtsam/geometry/Point2.h>
# include <gtsam/geometry/Pose3.h>
# include <gtsam/geometry/Point3.h>
# include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>
# include <gtsam/slam/BetweenFactor.h>
#endif
namespace svo {
AbstractInitialization::AbstractInitialization(
const InitializationOptions& init_options,
const FeatureTrackerOptions& tracker_options,
const DetectorOptions& detector_options,
const CameraBundlePtr& cams)
: options_(init_options)
{
tracker_.reset(new FeatureTracker(tracker_options, detector_options, cams));
}
AbstractInitialization::~AbstractInitialization()
{}
void AbstractInitialization::reset()
{
frames_ref_.reset();
have_rotation_prior_ = false;
have_translation_prior_ = false;
have_depth_prior_ = false;
tracker_->reset();
}
bool AbstractInitialization::trackFeaturesAndCheckDisparity(const FrameBundlePtr& frames)
{
tracker_->trackFrameBundle(frames);
std::vector<size_t> num_tracked;
std::vector<double> disparity;
tracker_->getNumTrackedAndDisparityPerFrame(
options_.init_disparity_pivot_ratio, &num_tracked, &disparity);
const size_t num_tracked_tot =
std::accumulate(num_tracked.begin(), num_tracked.end(), 0u);
const double avg_disparity =
std::accumulate(disparity.begin(), disparity.end(), 0.0) / disparity.size();
VLOG(3) << "Init: Tracked " << num_tracked_tot << " features with disparity = " << avg_disparity;
if(num_tracked_tot < options_.init_min_features)
{
tracker_->resetActiveTracks();
for(const FramePtr& frame : frames->frames_)
frame->clearFeatureStorage();
const size_t n = tracker_->initializeNewTracks(frames);
VLOG(3) << "Init: New Tracks initialized = " << n;
frames_ref_ = frames;
R_ref_world_ = R_cur_world_;
return false;
}
if(avg_disparity < options_.init_min_disparity)
return false;
return true;
}
InitResult HomographyInit::addFrameBundle(
const FrameBundlePtr& frames_cur)
{
// Track and detect features.
if(!trackFeaturesAndCheckDisparity(frames_cur))
return InitResult::kTracking;
// Create vector of bearing vectors
const FrameBundlePtr frames_ref = tracker_->getOldestFrameInTrack(0);
const Frame& frame_ref = *frames_ref->at(0);
const Frame& frame_cur = *frames_cur->at(0);
FeatureMatches matches_cur_ref;
feature_tracking_utils::getFeatureMatches(frame_cur, frame_ref, &matches_cur_ref);
const size_t n = matches_cur_ref.size();
Bearings f_cur(3, n);
Bearings f_ref(3, n);
for(size_t i = 0; i < n; ++i)
{
f_cur.col(i) = frame_cur.f_vec_.col(matches_cur_ref[i].first);
f_ref.col(i) = frame_ref.f_vec_.col(matches_cur_ref[i].second);
}
// Compute model
const vk::Homography H_cur_ref = vk::estimateHomography(
f_cur, f_ref, frames_ref_->at(0)->getErrorMultiplier(),
options_.reproj_error_thresh, options_.init_min_inliers);
if(H_cur_ref.score < options_.init_min_inliers)
{
SVO_WARN_STREAM("Init Homography: Have " << H_cur_ref.score << "inliers. "
<< options_.init_min_inliers << " inliers minimum required.");
return InitResult::kFailure;
}
T_cur_from_ref_ = Transformation(Quaternion(H_cur_ref.R_cur_ref), H_cur_ref.t_cur_ref);
// Triangulate
if(initialization_utils::triangulateAndInitializePoints(
frames_cur->at(0), frames_ref_->at(0), T_cur_from_ref_, options_.reproj_error_thresh,
depth_at_current_frame_, options_.init_min_inliers, matches_cur_ref))
{
return InitResult::kSuccess;
}
// Restart
tracker_->reset();
frames_cur->at(0)->clearFeatureStorage();
return InitResult::kTracking;
}
#ifdef SVO_USE_OPENGV
//! Same as in opengv, but stores the triangulated values
class TranslationSacProblemWithTriangulation : public opengv::sac_problems::relative_pose::TranslationOnlySacProblem
{
public:
typedef opengv::sac_problems::relative_pose::TranslationOnlySacProblem Base;
TranslationSacProblemWithTriangulation(adapter_t & adapter) : Base(adapter) {}
void getSelectedDistancesToModel(
const model_t & model,
const std::vector<int> & indices,
std::vector<double> & scores) const
{
using namespace opengv;
translation_t translation = model.col(3);
rotation_t rotation = model.block<3,3>(0,0);
_adapter.sett12(translation);
_adapter.setR12(rotation);
model_t inverseSolution;
inverseSolution.block<3,3>(0,0) = rotation.transpose();
inverseSolution.col(3) = -inverseSolution.block<3,3>(0,0)*translation;
Eigen::Matrix<double,4,1> p_hom;
p_hom[3] = 1.0;
points_.resize(indices.size());
for( size_t i = 0; i < indices.size(); i++ )
{
p_hom.block<3,1>(0,0) =
opengv::triangulation::triangulate2(_adapter,indices[i]);
points_[i] = p_hom.block<3,1>(0,0);
bearingVector_t reprojection1 = p_hom.block<3,1>(0,0);
bearingVector_t reprojection2 = inverseSolution * p_hom;
reprojection1 = reprojection1 / reprojection1.norm();
reprojection2 = reprojection2 / reprojection2.norm();
bearingVector_t f1 = _adapter.getBearingVector1(indices[i]);
bearingVector_t f2 = _adapter.getBearingVector2(indices[i]);
//bearing-vector based outlier criterium (select threshold accordingly):
//1-(f1'*f2) = 1-cos(alpha) \in [0:2]
double reprojError1 = 1.0 - (f1.transpose() * reprojection1);
double reprojError2 = 1.0 - (f2.transpose() * reprojection2);
scores.push_back(reprojError1 + reprojError2);
}
}
mutable opengv::points_t points_;
};
#endif
InitResult TwoPointInit::addFrameBundle(
const FrameBundlePtr& frames_cur)
{
#ifdef SVO_USE_OPENGV
if(!have_rotation_prior_)
{
SVO_ERROR_STREAM("TwoPointInit has no rotation prior.");
return InitResult::kFailure;
}
have_rotation_prior_ = false;
// Track and detect features.
if(!trackFeaturesAndCheckDisparity(frames_cur))
return InitResult::kTracking;
// Create vector of bearing vectors
const FrameBundlePtr frames_ref = tracker_->getOldestFrameInTrack(0);
FeatureMatches matches_cur_ref;
feature_tracking_utils::getFeatureMatches(
*frames_cur->at(0), *frames_ref->at(0), &matches_cur_ref);
// Create vector of bearing vectors
BearingVectors f_cur;
BearingVectors f_ref;
initialization_utils::copyBearingVectors(
*frames_cur->at(0), *frames_ref->at(0), matches_cur_ref, &f_cur, &f_ref);
// Compute model
static double inlier_threshold =
1.0 - std::cos(frames_cur->at(0)->getAngleError(options_.reproj_error_thresh));
const Eigen::Matrix3d R_cur_ref = (R_cur_world_ * R_ref_world_.inverse()).getRotationMatrix();
opengv::relative_pose::CentralRelativeAdapter adapter(f_cur, f_ref, R_cur_ref);
typedef TranslationSacProblemWithTriangulation TwoPtProblem;
std::shared_ptr<TwoPtProblem> problem_ptr(new TwoPtProblem(adapter));
opengv::sac::Ransac<TwoPtProblem> ransac;
ransac.sac_model_ = problem_ptr;
ransac.threshold_ = inlier_threshold;
ransac.max_iterations_ = 100;
ransac.probability_ = 0.995;
ransac.computeModel();
// enough inliers?
if(ransac.inliers_.size() < options_.init_min_inliers)
return InitResult::kNoKeyframe;
Eigen::Vector3d t = ransac.model_coefficients_.rightCols(1);
Matrix3d R = ransac.model_coefficients_.leftCols(3);
T_cur_from_ref_ = Transformation(
Quaternion(R),
ransac.model_coefficients_.rightCols(1));
VLOG(5) << "2Pt RANSAC:" << std::endl
<< "# Iter = " << ransac.iterations_ << std::endl
<< "# Inliers = " << ransac.inliers_.size() << std::endl
<< "Model = " << ransac.model_coefficients_ << std::endl
<< "Rot prior (imu) = " << R_cur_ref << std::endl
<< "H.rotation_matrix() = " << T_cur_from_ref_.getRotationMatrix() << std::endl
<< "H.translation() = " << T_cur_from_ref_.getPosition();
// Triangulate
if(initialization_utils::triangulateAndInitializePoints(
frames_cur->at(0), frames_ref->at(0), T_cur_from_ref_, options_.reproj_error_thresh,
depth_at_current_frame_, options_.init_min_inliers, matches_cur_ref))
{
return InitResult::kSuccess;
}
return InitResult::kFailure;
#else
SVO_ERROR_STREAM("You need to compile SVO with OpenGV to use TwoPointInit!");
return InitResult::kFailure;
#endif
}
InitResult FivePointInit::addFrameBundle(
const FrameBundlePtr& frames_cur)
{
#ifdef SVO_USE_OPENGV
// Track and detect features.
if(!trackFeaturesAndCheckDisparity(frames_cur))
return InitResult::kTracking;
// Create vector of bearing vectors
const FrameBundlePtr frames_ref = tracker_->getOldestFrameInTrack(0);
FeatureMatches matches_cur_ref;
feature_tracking_utils::getFeatureMatches(
*frames_cur->at(0), *frames_ref->at(0), &matches_cur_ref);
// Create vector of bearing vectors
BearingVectors f_cur;
BearingVectors f_ref;
initialization_utils::copyBearingVectors(
*frames_cur->at(0), *frames_ref->at(0), matches_cur_ref, &f_cur, &f_ref);
// Compute model
static double inlier_threshold = 1.0 - std::cos(frames_cur->at(0)->getAngleError(options_.reproj_error_thresh));
typedef opengv::sac_problems::relative_pose::CentralRelativePoseSacProblem CentralRelative;
opengv::relative_pose::CentralRelativeAdapter adapter(f_cur, f_ref);
std::shared_ptr<CentralRelative> problem_ptr(
new CentralRelative(adapter, CentralRelative::NISTER));
opengv::sac::Ransac<CentralRelative> ransac;
ransac.sac_model_ = problem_ptr;
ransac.threshold_ = inlier_threshold;
ransac.max_iterations_ = 100;
ransac.probability_ = 0.995;
ransac.computeModel();
// enough inliers?
if(ransac.inliers_.size() < options_.init_min_inliers)
{
VLOG(3) << "5Pt RANSAC has only " << ransac.inliers_.size() << " inliers. "
<< options_.init_min_inliers << " required.";
return InitResult::kNoKeyframe;
}
Eigen::Vector3d t = ransac.model_coefficients_.rightCols(1);
Matrix3d R = ransac.model_coefficients_.leftCols(3);
T_cur_from_ref_ = Transformation(
Quaternion(R),
ransac.model_coefficients_.rightCols(1));
VLOG(5) << "5Pt RANSAC:" << std::endl
<< "# Iter = " << ransac.iterations_ << std::endl
<< "# Inliers = " << ransac.inliers_.size() << std::endl
<< "Model = " << ransac.model_coefficients_ << std::endl
<< "T.rotation_matrix() = " << T_cur_from_ref_.getRotationMatrix() << std::endl
<< "T.translation() = " << T_cur_from_ref_.getPosition();
// Triangulate
if(initialization_utils::triangulateAndInitializePoints(
frames_cur->at(0), frames_ref->at(0), T_cur_from_ref_, options_.reproj_error_thresh,
depth_at_current_frame_, options_.init_min_inliers, matches_cur_ref))
{
return InitResult::kSuccess;
}
return InitResult::kFailure;
#else
SVO_ERROR_STREAM("You need to compile SVO with OpenGV to use TwoPointInit!");
return InitResult::kFailure;
#endif
}
InitResult OneShotInit::addFrameBundle(const FrameBundlePtr &frames_cur)
{
CHECK(frames_cur->size() == 1) << "OneShot Initialization doesn't work with Camera Array";
// Track and detect features.
trackFeaturesAndCheckDisparity(frames_cur);
if(frames_cur->numFeatures() < options_.init_min_features)
{
return InitResult::kTracking;
}
if(frames_ref_ == frames_cur)
{
// First frame
return InitResult::kTracking;
}
// Initialize 3D points at known depth
const FrameBundlePtr frames_ref = tracker_->getOldestFrameInTrack(0);
FramePtr frame_ref = frames_ref->at(0);
FramePtr frame_cur = frames_cur->at(0);
FeatureMatches matches_cur_ref;
feature_tracking_utils::getFeatureMatches(*frame_cur, *frame_ref, &matches_cur_ref);
for(const std::pair<size_t, size_t> it : matches_cur_ref)
{
const BearingVector f_ref = frame_ref->f_vec_.col(it.second);
const Vector3d xyz_in_cam = (f_ref/f_ref.z()) * depth_at_current_frame_;
const Vector3d xyz_in_world = frame_ref->T_world_cam() * xyz_in_cam;
PointPtr new_point(new Point(xyz_in_world));
new_point->addObservation(frame_ref, it.second);
frame_ref->landmark_vec_.at(it.second) = new_point;
frame_cur->landmark_vec_.at(it.first) = new_point;
}
// to estimate pose of current frame we do pose optimization
PoseOptimizer::SolverOptions options = PoseOptimizer::getDefaultSolverOptions();
options.verbose = true;
PoseOptimizer optimizer(options);
optimizer.run(frames_cur, 2.0);
// Add all references to 3d point
for(size_t i = 0; i < frame_cur->numFeatures(); ++i)
{
if(!frame_cur->landmark_vec_.at(i))
continue;
const PointPtr point = frame_cur->landmark_vec_.at(i);
point->addObservation(frame_cur, i);
// TODO: we should also remove references in previous frame.
}
if(frames_cur->numLandmarks() < options_.init_min_features)
{
std::cout << "tracking " << frames_ref->numLandmarks() << " features" << std::endl;
return InitResult::kFailure;
}
return InitResult::kSuccess;
}
StereoInit::StereoInit(
const InitializationOptions& init_options,
const FeatureTrackerOptions& tracker_options,
const DetectorOptions& detector_options,
const CameraBundlePtr& cams)
: AbstractInitialization(init_options, tracker_options, detector_options, cams)
{
StereoTriangulationOptions stereo_options;
detector_ = feature_detection_utils::makeDetector(detector_options, cams->getCameraShared(0));
stereo_.reset(new StereoTriangulation(stereo_options, detector_));
}
InitResult StereoInit::addFrameBundle(
const FrameBundlePtr& frames)
{
CHECK_EQ(frames->size(), 2u) << "StereoInit: Bundle has not two frames!";
reset();
frames_ref_ = frames;
VLOG(20) << "FRAME 1" << std::endl << frames->at(0)->T_world_cam() <<std::endl
<< "FRAME 2" << std::endl << frames->at(1)->T_cam_world();
stereo_->compute(frames->at(0), frames->at(1));
if(frames->at(0)->numLandmarks() < options_.init_min_features)
return InitResult::kFailure;
return InitResult::kSuccess;
}
InitResult ArrayInitGeometric::addFrameBundle(
const FrameBundlePtr& frames_cur)
{
#ifdef SVO_USE_OPENGV
/*
InitResult res = trackBundleFeatures(frames_cur);
if(res != InitResult::kSuccess)
return res;
// Create vector of bearing vectors and camera correspondences
opengv::bearingVectors_t f_cur; f_cur.reserve(frames_cur->numFeatures());
opengv::bearingVectors_t f_ref; f_ref.reserve(f_cur.size());
std::vector<int> cam_correspondences_cur, cam_correspondences_ref;
cam_correspondences_cur.reserve(f_cur.size());
cam_correspondences_ref.reserve(f_ref.size());
opengv::translations_t cam_translations;
opengv::rotations_t cam_rotations;
for(size_t cam_id=0; cam_id<frames_cur->size(); ++cam_id)
{
cam_translations.push_back(frames_cur->at(cam_id)->T_imu_cam().getPosition());
cam_rotations.push_back(frames_cur->at(cam_id)->T_imu_cam().getRotationMatrix());
const FramePtr& frame_cur = frames_cur->at(cam_id);
const FramePtr& frame_ref = frames_ref_->at(cam_id);
for(size_t i = 0; i < frame_cur->numFeatures(); ++i)
{
if(ref_masks_[cam_id](i))
{
f_cur.push_back(frame_cur->f_vec_.col(i));
cam_correspondences_cur.push_back(cam_id);
f_ref.push_back(frame_ref->f_vec_.col(i));
cam_correspondences_ref.push_back(cam_id);
}
}
}
// set prior
Matrix3d R_cur_ref =
frames_cur->at(0)->T_imu_world().getRotationMatrix()
*frames_ref_->at(0)->T_world_imu().getRotationMatrix();
// Compute model
opengv::relative_pose::NoncentralRelativeAdapter adapter(
f_cur, f_ref, cam_correspondences_cur, cam_correspondences_ref,
cam_translations, cam_rotations, R_cur_ref);
// Create RANSAC object
typedef opengv::sac_problems::relative_pose::NoncentralRelativePoseSacProblem Problem;
opengv::sac::Ransac<Problem> ransac;
// Create Problem
auto algorithm = opengv::sac_problems::relative_pose::NoncentralRelativePoseSacProblem::SIXPT;
boost::shared_ptr<Problem> problem_ptr(new Problem(adapter, algorithm));
// Run RANSAC:
static double inlier_threshold = 1.0 - std::cos(frames_cur->at(0)->getAngleError(options_.reproj_error_thresh));
ransac.sac_model_ = problem_ptr;
ransac.threshold_ = inlier_threshold;
ransac.max_iterations_ = 500;
ransac.probability_ = 0.995;
ransac.computeModel(1);
VLOG(5) << "RANSAC:" << std::endl
<< "# Iter = " << ransac.iterations_ << std::endl
<< "# Inliers = " << ransac.inliers_.size() << std::endl
<< "Model = " << ransac.model_coefficients_;
// enough inliers?
if(ransac.inliers_.size() < options_.init_min_inliers)
return InitResult::kFailure;
Matrix3d R = ransac.model_coefficients_.leftCols(3);
T_cur_from_ref_ = Transformation(
Quaternion(R),
ransac.model_coefficients_.rightCols(1));
std::cout << "T_cur_ref computed = " << T_cur_from_ref_ << std::endl;
T_cur_from_ref_ = Transformation(Quaternion(), Vector3d(-0.6, 0, 0));
std::cout << "T_cur_ref set = " << T_cur_from_ref_ << std::endl;
// for every frame individually
for(size_t cam_id=0; cam_id<frames_cur->size(); ++cam_id)
{
const FramePtr& frame_cur = frames_cur->at(cam_id);
const FramePtr& frame_ref = frames_ref_->at(cam_id);
frame_cur->T_f_w_ =
frame_cur->T_cam_imu()*T_cur_from_ref_*frame_ref->T_imu_world();
Transformation T_cur_ref = frame_cur->T_f_w_*frame_ref->T_f_w_.inverse();
// Triangulate
std::vector<Vector3d, Eigen::aligned_allocator<Vector3d> > points_in_cur;
//TODO(cfo)
//initialization_utils::triangulatePoints(
// frame_cur, frame_ref, T_cur_ref, options_.reproj_error_thresh, points_in_cur);
VLOG(3) << "-- CAMERA " << frame_cur->cam()->getLabel()
<< ": inliers verified = " << points_in_cur.size();
TODO(cfo)
// Rescale 3D points and add to features
Transformation T_world_cur = frame_cur->T_f_w_.inverse();
auto it_cur = frame_cur->fts_.begin();
auto it_ref = frame_ref->fts_.begin();
auto it_xyz = points_in_cur.begin();
for(; it_cur != frame_cur->fts_.end(); ++it_cur, ++it_ref, ++it_xyz)
{
const Vector3d xyz_in_world = T_world_cur * (*it_xyz);
PointPtr new_point(new Point(xyz_in_world));
new_point->addObservation(frame_ref, *it_ref);
new_point->addObservation(frame_cur, *it_cur);
(*it_ref)->point = new_point;
(*it_cur)->point = new_point;
}
}
if(options_.verbose)
std::cout << "Total triangulated points = " << frames_cur->nFts() << std::endl;
if(frames_cur->nFts() < options_.init_min_inliers)
{
SVO_WARN_STREAM("Init WARNING: "<<options_.init_min_inliers<<" inliers minimum required.");
return InitResult::kFailure;
}
for(size_t i=0; i<frames_cur->size(); ++i)
{
initialization_utils::displayFeatureTracks(frames_cur->at(i), frames_ref_->at(i));
}
*/
return InitResult::kSuccess;
#else
SVO_ERROR_STREAM("You need to compile SVO with OpenGV to use TwoPointInit!");
return InitResult::kFailure;
#endif
}
InitResult ArrayInitOptimization::addFrameBundle(
const FrameBundlePtr& frames_cur)
{
#ifdef SVO_USE_GTSAM
InitResult res = trackBundleFeatures(frames_cur);
if(res != InitResult::kSuccess)
return res;
gtsam::Cal3_S2::shared_ptr K(new gtsam::Cal3_S2(1.0, 1.0, 0.0, 0.0, 0.0));
gtsam::noiseModel::Isotropic::shared_ptr pixel_noise_base =
gtsam::noiseModel::Isotropic::Sigma(2, 1.0/frames_cur->at(0)->getErrorMultiplier());
gtsam::SharedNoiseModel pixel_noise =
gtsam::noiseModel::Robust::Create(
//gtsam::noiseModel::mEstimator::Tukey::Create(4.685), pixel_noise_base);
//gtsam::noiseModel::mEstimator::Fair::Create(1.3998), pixel_noise_base);
//gtsam::noiseModel::mEstimator::Cauchy::Create(0.1), pixel_noise_base);
//gtsam::noiseModel::mEstimator::Welsh::Create(2.9846), pixel_noise_base);
gtsam::noiseModel::mEstimator::Huber::Create(1.345), pixel_noise_base);
gtsam::NonlinearFactorGraph graph;
gtsam::Values initial_estimate;
// Add a prior on reference pose.
Matrix<double, 6, 1> refpose_prior_sigmas;
refpose_prior_sigmas << 0.0001, 0.0001, 0.0001, // rotation
0.00001, 0.00001, 0.00001; // translation, 1mm
gtsam::noiseModel::Gaussian::shared_ptr pose_prior_noise =
gtsam::noiseModel::Diagonal::Sigmas(refpose_prior_sigmas);
Transformation T_world_refimu = frames_ref_->at(0)->T_world_imu();
gtsam::Pose3 pose_ref(
gtsam::Rot3(T_world_refimu.getRotationMatrix()),
gtsam::Point3(T_world_refimu.getPosition()));
graph.push_back(gtsam::PriorFactor<gtsam::Pose3>(
gtsam::Symbol('x', 0), pose_ref, pose_prior_noise)); // add directly to graph
Matrix3d eye = Matrix3d::Identity();
gtsam::Pose3 T_prior(gtsam::Rot3(eye), Vector3d::Zero());
std::cout << "Prior = " << T_prior << std::endl;
Matrix<double, 6, 6> relpose_prior_info;
relpose_prior_info.setZero();
relpose_prior_info.block<3,3>(0,0) = Matrix3d::Identity()*1e8;
gtsam::noiseModel::Gaussian::shared_ptr T_prior_noise =
gtsam::noiseModel::Diagonal::Information(relpose_prior_info); // translation
// Add prior on relative pose between first two frames
graph.push_back(gtsam::BetweenFactor<gtsam::Pose3>(
gtsam::Symbol('x', 0), gtsam::Symbol('x', 1),
T_prior, T_prior_noise));
// Add values for reference and current frame. init at same pose.
initial_estimate.insert(gtsam::Symbol('x', 0), pose_ref);
initial_estimate.insert(gtsam::Symbol('x', 1), pose_ref);
/* TODO(cfo)
*
// Add values for 3D points. Initialize with random depth.
int point_id = 0;
for(const FramePtr& frame : frames_ref_->frames_)
{
for(const FeaturePtr& ftr : frame->fts_)
{
double depth = depth_at_current_frame_
+vk::Sample::gaussian(depth_at_current_frame_/3.0);
Vector3d xyz = frame->T_world_cam()*(ftr->f*depth);
initial_estimate.insert(gtsam::Symbol('l', point_id++), gtsam::Point3(xyz));
}
}
// Add reprojection factors.
int point_id_ref = 0;
typedef gtsam::GenericProjectionFactor<gtsam::Pose3, gtsam::Point3, gtsam::Cal3_S2> ProjectionFactor;
for(const FramePtr& frame : frames_ref_->frames_)
{
gtsam::Pose3 T_imu_cam(frame->T_imu_cam().getRotationMatrix(),
frame->T_imu_cam().getPosition());
for(const FeaturePtr& ftr : frame->fts_)
{
graph.push_back(
ProjectionFactor(
gtsam::Point2(vk::project2(ftr->f)), pixel_noise, gtsam::Symbol('x', 0),
gtsam::Symbol('l', point_id_ref++), K, T_imu_cam));
}
}
int point_id_cur = 0;
for(const FramePtr& frame : frames_cur->frames_)
{
gtsam::Pose3 T_imu_cam(frame->T_imu_cam().getRotationMatrix(),
frame->T_imu_cam().getPosition());
for(const FeaturePtr& ftr : frame->fts_)
{
graph.push_back(
ProjectionFactor(
gtsam::Point2(vk::project2(ftr->f)), pixel_noise, gtsam::Symbol('x', 1),
gtsam::Symbol('l', point_id_cur++), K, T_imu_cam));
}
}
SVO_ASSERT(point_id_cur == point_id_ref,
"Initialization: Cur and Ref Bundles don't have same amount of features.");
SVO_ASSERT(point_id_cur == point_id,
"Initialization: Cur Bundle and Values don't have same amount of features.");
// solve
gtsam::LevenbergMarquardtParams params;
params.verbosity = gtsam::LevenbergMarquardtParams::ERROR;
gtsam::Values result = gtsam::LevenbergMarquardtOptimizer(graph, initial_estimate, params).optimize();
//result.print("Final results:\n");
std::cout << "initial error = " << graph.error(initial_estimate) << std::endl;
std::cout << "final error = " << graph.error(result) << std::endl;
gtsam::Pose3 T_ref = result.at<gtsam::Pose3>(gtsam::Symbol('x',0));
gtsam::Pose3 T_cur = result.at<gtsam::Pose3>(gtsam::Symbol('x',1));
T_world_refimu = Transformation(T_ref.rotation().toQuaternion(), T_ref.translation().vector());
Transformation T_world_curimu(T_cur.rotation().toQuaternion(), T_cur.translation().vector());
Transformation T_ref_cur = T_world_refimu.inverse()*T_world_curimu;
std::cout << T_ref_cur.inverse() << std::endl;
for(size_t i=0; i<frames_cur->size(); ++i)
{
initialization_utils::displayFeatureTracks(frames_cur->at(i), frames_ref_->at(i));
}
*/
return InitResult::kSuccess;
#else
SVO_ERROR_STREAM("You need to compile SVO with GTSAM to use ArrayInitOptimization!");
return InitResult::kFailure;
#endif
}
namespace initialization_utils {
bool triangulateAndInitializePoints(
const FramePtr& frame_cur,
const FramePtr& frame_ref,
const Transformation& T_cur_ref,
const double reprojection_threshold,
const double depth_at_current_frame,
const size_t min_inliers_threshold,
AbstractInitialization::FeatureMatches& matches_cur_ref)
{
Positions points_in_cur;
initialization_utils::triangulatePoints(
*frame_cur, *frame_ref, T_cur_ref, reprojection_threshold, matches_cur_ref, points_in_cur);
if(matches_cur_ref.size() < min_inliers_threshold)
{
LOG(WARNING) << "Init WARNING: " <<min_inliers_threshold <<" inliers minimum required. "
<< "Have only " << matches_cur_ref.size();
return false;
}
// Scale 3D points to given scene depth and initialize Points
initialization_utils::rescaleAndInitializePoints(
frame_cur, frame_ref, matches_cur_ref, points_in_cur, T_cur_ref, depth_at_current_frame);
return true;
}
void triangulatePoints(
const Frame& frame_cur,
const Frame& frame_ref,
const Transformation& T_cur_ref,
const double reprojection_threshold,
AbstractInitialization::FeatureMatches& matches_cur_ref,
Positions& points_in_cur)
{
points_in_cur.resize(Eigen::NoChange, frame_cur.num_features_);
const Transformation T_ref_cur = T_cur_ref.inverse();
std::vector<size_t> outliers;
size_t num_inliers = 0;
const double angle_threshold =
frame_cur.getAngleError(reprojection_threshold);
for(size_t i = 0; i < matches_cur_ref.size(); ++i)
{
BearingVector f_cur = frame_cur.f_vec_.col(matches_cur_ref[i].first);
BearingVector f_ref = frame_ref.f_vec_.col(matches_cur_ref[i].second);
// TODO(cfo): should take reference to eigen
const Position xyz_in_cur =
vk::triangulateFeatureNonLin(
T_cur_ref.getRotationMatrix(), T_cur_ref.getPosition(), f_cur, f_ref);
const double e1 = angleError(f_cur, xyz_in_cur);
const double e2 = angleError(f_ref, T_ref_cur * xyz_in_cur);
if(e1 > angle_threshold || e2 > angle_threshold ||
(frame_cur.cam()->getType() == Camera::Type::kPinhole &&
xyz_in_cur.z() < 0.0))
{
outliers.push_back(i);
}
else
{
points_in_cur.col(num_inliers) = xyz_in_cur;
++num_inliers;
}
}
if(!outliers.empty())
{
svo::common::container_helpers::eraseIndicesFromVector(
outliers, &matches_cur_ref);
}
}
void rescaleAndInitializePoints(
const FramePtr& frame_cur,
const FramePtr& frame_ref,
const AbstractInitialization::FeatureMatches& matches_cur_ref,
const Positions& points_in_cur,
const Transformation& T_cur_ref,
const double depth_at_current_frame)
{
// compute scale factor
std::vector<double> depth_vec;
for(size_t i = 0; i < matches_cur_ref.size(); ++i)
{
depth_vec.push_back(points_in_cur.col(i).norm());
}
CHECK_GT(depth_vec.size(), 1u);
const double scene_depth_median = vk::getMedian(depth_vec);
const double scale = depth_at_current_frame / scene_depth_median;
// reset pose of current frame to have right scale
frame_cur->T_f_w_ = T_cur_ref * frame_ref->T_f_w_;
frame_cur->T_f_w_.getPosition() =
- frame_cur->T_f_w_.getRotation().rotate(
frame_ref->pos() + scale * (frame_cur->pos() - frame_ref->pos()));
// Rescale 3D points and add to features
Transformation T_world_cur = frame_cur->T_f_w_.inverse();
for(size_t i = 0; i < matches_cur_ref.size(); ++i)
{
const Vector3d xyz_in_world = T_world_cur * (points_in_cur.col(i) * scale);
const int point_id_cur = frame_cur->track_id_vec_(matches_cur_ref[i].first);
const int point_id_ref = frame_ref->track_id_vec_(matches_cur_ref[i].second);
CHECK_EQ(point_id_cur, point_id_ref);
PointPtr new_point(new Point(point_id_cur, xyz_in_world));
frame_cur->landmark_vec_.at(matches_cur_ref[i].first) = new_point;
frame_ref->landmark_vec_.at(matches_cur_ref[i].second) = new_point;
new_point->addObservation(frame_ref, matches_cur_ref[i].second);
new_point->addObservation(frame_cur, matches_cur_ref[i].first);
}
SVO_INFO_STREAM("Init: Triangulated " << matches_cur_ref.size() << " points");
}
void displayFeatureTracks(
const FramePtr& frame_cur,
const FramePtr& frame_ref)
{
cv::Mat img_rgb(frame_cur->img().size(), CV_8UC3);
cv::cvtColor(frame_cur->img(), img_rgb, cv::COLOR_GRAY2RGB);
/* TODO(cfo)
for(size_t i=0; i<frame_cur->fts_.size(); ++i)
{
const FeaturePtr& ftr_cur = frame_cur->fts_.at(i);
const FeaturePtr& ftr_ref = frame_ref->fts_.at(i);
cv::line(img_rgb,
cv::Point2f(ftr_cur->px[0], ftr_cur->px[1]),
cv::Point2f(ftr_ref->px[0], ftr_ref->px[1]),
cv::Scalar(0,0,255), 2);
}
*/
cv::imshow(frame_cur->cam_->getLabel().c_str(), img_rgb);
cv::waitKey(0);
}
AbstractInitialization::UniquePtr makeInitializer(
const InitializationOptions& init_options,
const FeatureTrackerOptions& tracker_options,
const DetectorOptions& detector_options,
const CameraBundle::Ptr& cams)
{
AbstractInitialization::UniquePtr initializer;
switch(init_options.init_type)
{
case InitializerType::kHomography:
initializer.reset(new HomographyInit(init_options, tracker_options, detector_options, cams));
break;
case InitializerType::kTwoPoint:
initializer.reset(new TwoPointInit(init_options, tracker_options, detector_options, cams));
break;
case InitializerType::kFivePoint:
initializer.reset(new FivePointInit(init_options, tracker_options, detector_options, cams));
break;
case InitializerType::kOneShot:
initializer.reset(new OneShotInit(init_options, tracker_options, detector_options, cams));
break;
case InitializerType::kStereo:
initializer.reset(new StereoInit(init_options, tracker_options, detector_options, cams));
break;
case InitializerType::kArrayGeometric:
initializer.reset(new ArrayInitGeometric(init_options, tracker_options, detector_options, cams));
break;
case InitializerType::kArrayOptimization:
initializer.reset(new ArrayInitOptimization(init_options, tracker_options, detector_options, cams));
break;
default:
LOG(FATAL) << "Initializer type not known.";
}
return initializer;
}
void copyBearingVectors(
const Frame& frame_cur,
const Frame& frame_ref,
const AbstractInitialization::FeatureMatches& matches_cur_ref,
AbstractInitialization::BearingVectors* f_cur,
AbstractInitialization::BearingVectors* f_ref)
{
CHECK_NOTNULL(f_cur);
CHECK_NOTNULL(f_ref);
f_cur->reserve(matches_cur_ref.size());
f_ref->reserve(matches_cur_ref.size());
for(size_t i = 0; i < matches_cur_ref.size(); ++i)
{
f_cur->push_back(frame_cur.f_vec_.col(matches_cur_ref[i].first));
f_ref->push_back(frame_ref.f_vec_.col(matches_cur_ref[i].second));
}
}
} // namespace initialization_utils
} // namespace svo
| 36.539046 | 116 | 0.711538 | jsz0913 |
e946a0e063efa142ad15381004e7d41e78a2bee0 | 1,111 | cpp | C++ | src/Engine/map/MapAltitude.cpp | turesnake/tprPixelGames | 6b5471a072a1a8b423834ab04ff03e64df215d5e | [
"BSD-3-Clause"
] | 591 | 2020-03-12T05:10:33.000Z | 2022-03-30T13:41:59.000Z | src/Engine/map/MapAltitude.cpp | turesnake/tprPixelGames | 6b5471a072a1a8b423834ab04ff03e64df215d5e | [
"BSD-3-Clause"
] | 4 | 2020-04-06T01:55:06.000Z | 2020-05-02T04:28:04.000Z | src/Engine/map/MapAltitude.cpp | turesnake/tprPixelGames | 6b5471a072a1a8b423834ab04ff03e64df215d5e | [
"BSD-3-Clause"
] | 112 | 2020-04-05T23:55:36.000Z | 2022-03-17T11:58:02.000Z | /*
* ====================== MapAltitude.cpp =======================
* -- tpr --
* CREATE -- 2019.03.11
* MODIFY --
* ----------------------------------------------------------
*/
#include "pch.h"
#include "MapAltitude.h"
void MapAltitude::init( double altiVal_from_gpgpu_ ){
tprAssert( (altiVal_from_gpgpu_>=-100.0) && (altiVal_from_gpgpu_<=100.0) );
this->val = static_cast<int>(floor(altiVal_from_gpgpu_));
//------------------//
// lvl
//------------------//
int tmpLvl {};
double waterStep { 7.0 }; //- 水下梯度,tmp...
double landStep { 14.0 }; //- 陆地梯度,tmp...
if( this->val < 0 ){ //- under water
tmpLvl = static_cast<int>( floor(altiVal_from_gpgpu_/waterStep) );
if( tmpLvl < -5 ){ //- 抹平 水域底部
tmpLvl = -5;
}
}else{ //- land
tmpLvl = static_cast<int>( floor(altiVal_from_gpgpu_/landStep) );
if( tmpLvl > 2 ){ //- 抹平 陆地高区
tmpLvl = 2;
}
}
this->lvl = tmpLvl;
}
| 29.236842 | 79 | 0.414941 | turesnake |
e94c305c2b3cd0447ccdfb89a80fa1faf09529a2 | 10,273 | cpp | C++ | MandarinInstrInfo.cpp | WheretIB/llvm-mandarin | 073fd12ba433e531a05a211439bb23405196811a | [
"MIT"
] | null | null | null | MandarinInstrInfo.cpp | WheretIB/llvm-mandarin | 073fd12ba433e531a05a211439bb23405196811a | [
"MIT"
] | null | null | null | MandarinInstrInfo.cpp | WheretIB/llvm-mandarin | 073fd12ba433e531a05a211439bb23405196811a | [
"MIT"
] | null | null | null | //===-- MandarinInstrInfo.cpp - Mandarin Instruction Information ----------------===//
//
// Vyacheslav Egorov
//
// This file is distributed under the MIT License
//
//===----------------------------------------------------------------------===//
//
// This file contains the Mandarin implementation of the TargetInstrInfo class.
//
//===----------------------------------------------------------------------===//
#include "MandarinInstrInfo.h"
#include "Mandarin.h"
#include "MandarinMachineFunctionInfo.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
#define GET_INSTRINFO_CTOR_DTOR
#include "MandarinGenInstrInfo.inc"
using namespace llvm;
// Pin the vtable to this file.
void MandarinInstrInfo::anchor() {}
MandarinInstrInfo::MandarinInstrInfo(MandarinSubtarget &ST)
: MandarinGenInstrInfo(MD::ADJCALLSTACKDOWN, MD::ADJCALLSTACKUP),
RI(ST), Subtarget(ST) {
}
/// isLoadFromStackSlot - If the specified machine instruction is a direct
/// load from a stack slot, return the virtual or physical register number of
/// the destination along with the FrameIndex of the loaded stack slot. If
/// not, return 0. This predicate must return 0 if the instruction has
/// any side effects other than loading from the stack slot.
unsigned MandarinInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
int &FrameIndex) const
{
MI->dump();
/*if (MI->getOpcode() == MD::LOADri ||
MI->getOpcode() == SP::LDXri ||
MI->getOpcode() == SP::LDFri ||
MI->getOpcode() == SP::LDDFri ||
MI->getOpcode() == SP::LDQFri) {
if (MI->getOperand(1).isFI() && MI->getOperand(2).isImm() &&
MI->getOperand(2).getImm() == 0) {
FrameIndex = MI->getOperand(1).getIndex();
return MI->getOperand(0).getReg();
}
}*/
return 0;
}
/// isStoreToStackSlot - If the specified machine instruction is a direct
/// store to a stack slot, return the virtual or physical register number of
/// the source reg along with the FrameIndex of the loaded stack slot. If
/// not, return 0. This predicate must return 0 if the instruction has
/// any side effects other than storing to the stack slot.
unsigned MandarinInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
int &FrameIndex) const
{
MI->dump();
/*if (MI->getOpcode() == SP::STri ||
MI->getOpcode() == SP::STXri ||
MI->getOpcode() == SP::STFri ||
MI->getOpcode() == SP::STDFri ||
MI->getOpcode() == SP::STQFri) {
if (MI->getOperand(0).isFI() && MI->getOperand(1).isImm() &&
MI->getOperand(1).getImm() == 0) {
FrameIndex = MI->getOperand(0).getIndex();
return MI->getOperand(2).getReg();
}
}*/
return 0;
}
bool MandarinInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
MachineBasicBlock *&TBB,
MachineBasicBlock *&FBB,
SmallVectorImpl<MachineOperand> &Cond,
bool AllowModify) const
{
MachineBasicBlock::iterator I = MBB.end();
while (I != MBB.begin()) {
--I;
if (I->isDebugValue())
continue;
// When we see a non-terminator, we are done.
if (!isUnpredicatedTerminator(I))
break;
// Terminator is not a branch.
if (!I->isBranch())
return true;
// Cannot handle indirect branches.
if (I->getOpcode() == MD::JMPr || I->getOpcode() == MD::JCCr)
return true;
// Handle unconditional branches.
if (I->getOpcode() == MD::JMPi) {
if (!AllowModify) {
TBB = I->getOperand(0).getMBB();
continue;
}
// If the block has any instructions after a JMP, delete them.
while (llvm::next(I) != MBB.end())
llvm::next(I)->eraseFromParent();
Cond.clear();
FBB = 0;
// Delete the JMP if it's equivalent to a fall-through.
if (MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
TBB = 0;
I->eraseFromParent();
I = MBB.end();
continue;
}
// TBB is used to indicate the unconditinal destination.
TBB = I->getOperand(0).getMBB();
continue;
}
MDCC::CondCodes BranchCode = static_cast<MDCC::CondCodes>(I->getOperand(1).getImm());
if (BranchCode == MDCC::COND_INVALID)
return true; // Can't handle weird stuff.
// Working from the bottom, handle the first conditional branch.
if (Cond.empty()) {
FBB = TBB;
TBB = I->getOperand(0).getMBB();
Cond.push_back(MachineOperand::CreateImm(BranchCode));
continue;
}
// Handle subsequent conditional branches. Only handle the case where all
// conditional branches branch to the same destination.
assert(Cond.size() == 1);
assert(TBB);
// Only handle the case where all conditional branches branch to
// the same destination.
if (TBB != I->getOperand(0).getMBB())
return true;
MDCC::CondCodes OldBranchCode = (MDCC::CondCodes)Cond[0].getImm();
// If the conditions are the same, we can leave them alone.
if (OldBranchCode == BranchCode)
continue;
return true;
}
return false;
}
unsigned
MandarinInstrInfo::InsertBranch(MachineBasicBlock &MBB,MachineBasicBlock *TBB,
MachineBasicBlock *FBB,
const SmallVectorImpl<MachineOperand> &Cond,
DebugLoc DL) const {
assert(TBB && "InsertBranch must not be told to insert a fallthrough");
assert((Cond.size() == 1 || Cond.size() == 0) &&
"Mandarin branch conditions should have one component!");
if (Cond.empty()) {
assert(!FBB && "Unconditional branch with multiple successors!");
BuildMI(&MBB, DL, get(MD::JMPi)).addMBB(TBB);
return 1;
}
// Conditional branch
unsigned Count = 0;
BuildMI(&MBB, DL, get(MD::JCCi)).addMBB(TBB).addImm(Cond[0].getImm());
++Count;
if (FBB)
{
// Two-way Conditional branch. Insert the second branch.
BuildMI(&MBB, DL, get(MD::JMPi)).addMBB(FBB);
++Count;
}
return Count;
}
unsigned MandarinInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const
{
MachineBasicBlock::iterator I = MBB.end();
unsigned Count = 0;
while (I != MBB.begin()) {
--I;
if (I->isDebugValue())
continue;
if (I->getOpcode() != MD::JMPi &&
I->getOpcode() != MD::JCCi &&
I->getOpcode() != MD::JMPr &&
I->getOpcode() != MD::JCCr)
break; // Not a branch
// Remove the branch.
I->eraseFromParent();
I = MBB.end();
++Count;
}
return Count;
}
void MandarinInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator I, DebugLoc DL,
unsigned DestReg, unsigned SrcReg,
bool KillSrc) const
{
if(MD::GenericRegsRegClass.contains(DestReg, SrcReg))
{
BuildMI(MBB, I, DL, get(MD::MOVrr), DestReg).addReg(SrcReg, getKillRegState(KillSrc));
}
else if(MD::DoubleRegsRegClass.contains(DestReg, SrcReg) )
{
BuildMI(MBB, I, DL, get(MD::MOV2rr), DestReg).addReg(SrcReg, getKillRegState(KillSrc));
}
else if(MD::DoubleRegsRegClass.contains(DestReg) && (SrcReg == MD::R0 || SrcReg == MD::R2))
{
printf("Registers are already there\n");
}
else if(MD::QuadRegsRegClass.contains(DestReg, SrcReg))
{
BuildMI(MBB, I, DL, get(MD::MOV4rr), DestReg).addReg(SrcReg, getKillRegState(KillSrc));
}
else if(MD::QuadRegsRegClass.contains(DestReg) && SrcReg == MD::R0)
{
printf("Registers are already there\n");
}
else
{
llvm_unreachable("Impossible reg-to-reg copy");
}
}
/// storeRegToStackSlot - Store the specified register of the given register
/// class to the specified stack frame index. The store instruction is to be
/// added to the given machine basic block before the specified machine
/// instruction. If isKill is true, the register operand is the last use and
/// must be marked kill.
void MandarinInstrInfo::
storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
unsigned SrcReg, bool isKill, int FrameIndex,
const TargetRegisterClass *RC,
const TargetRegisterInfo *TRI) const {
DebugLoc DL;
if (MI != MBB.end())
DL = MI->getDebugLoc();
MachineFunction *MF = MBB.getParent();
const MachineFrameInfo &MFI = *MF->getFrameInfo();
MachineMemOperand *MMO =
MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIndex),
MachineMemOperand::MOStore,
MFI.getObjectSize(FrameIndex),
MFI.getObjectAlignment(FrameIndex));
if (RC == &MD::GenericRegsRegClass)
{
BuildMI(MBB, MI, DL, get(MD::STORErr))
.addFrameIndex(FrameIndex).addImm(0)
.addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO);
}else{
llvm_unreachable("Cannot store this register to stack slot!");
}
}
/// loadRegFromStackSlot - Load the specified register of the given register
/// class from the specified stack frame index. The load instruction is to be
/// added to the given machine basic block before the specified machine
/// instruction.
void MandarinInstrInfo::
loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
unsigned DestReg, int FrameIndex,
const TargetRegisterClass *RC,
const TargetRegisterInfo *TRI) const {
DebugLoc DL;
if (MI != MBB.end())
DL = MI->getDebugLoc();
MachineFunction &MF = *MBB.getParent();
MachineFrameInfo &MFI = *MF.getFrameInfo();
MachineMemOperand *MMO =
MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIndex),
MachineMemOperand::MOLoad,
MFI.getObjectSize(FrameIndex),
MFI.getObjectAlignment(FrameIndex));
if (RC == &MD::GenericRegsRegClass)
{
BuildMI(MBB, MI, DL, get(MD::LOADrr), DestReg)
.addFrameIndex(FrameIndex).addImm(0).addMemOperand(MMO);
}else{
llvm_unreachable("Cannot store this register to stack slot!");
}
}
| 32.003115 | 92 | 0.632727 | WheretIB |
e94ec877a7f3cc056a9555adfffecd019977ac2b | 1,093 | cpp | C++ | src/Horn.cpp | mauriciocele/fast-rotor-estimation | 1ee3f5a4aaee83f66e8ced209c2891b6e2045856 | [
"MIT"
] | 2 | 2020-07-28T15:34:57.000Z | 2021-09-24T06:04:03.000Z | src/Horn.cpp | mauriciocele/fast-rotor-estimation | 1ee3f5a4aaee83f66e8ced209c2891b6e2045856 | [
"MIT"
] | null | null | null | src/Horn.cpp | mauriciocele/fast-rotor-estimation | 1ee3f5a4aaee83f66e8ced209c2891b6e2045856 | [
"MIT"
] | null | null | null | #include "Horn.h"
#include <Eigen/Eigenvalues>
using Eigen::Vector3d;
using Eigen::Vector4d;
using Eigen::Matrix3d;
using Eigen::Matrix4d;
using Eigen::Quaterniond;
using std::vector;
Quaterniond Horn(const vector<Vector3d>& P, const vector<Vector3d>& Q, const vector<double>& w)
{
Matrix3d M;
Matrix4d N;
const size_t n = P.size();
M.setZero();
for (size_t j = 0; j < n; ++j)
{
M += w[j] * P[j] * Q[j].transpose();
}
// on-diagonal elements
N(0, 0) = M(0, 0) + M(1, 1) + M(2, 2);
N(1, 1) = M(0, 0) - M(1, 1) - M(2, 2);
N(2, 2) = -M(0, 0) + M(1, 1) - M(2, 2);
N(3, 3) = -M(0, 0) - M(1, 1) + M(2, 2);
// off-diagonal elements
N(0, 1) = N(1, 0) = M(1, 2) - M(2, 1);
N(0, 2) = N(2, 0) = M(2, 0) - M(0, 2);
N(0, 3) = N(3, 0) = M(0, 1) - M(1, 0);
N(1, 2) = N(2, 1) = M(0, 1) + M(1, 0);
N(1, 3) = N(3, 1) = M(2, 0) + M(0, 2);
N(2, 3) = N(3, 2) = M(1, 2) + M(2, 1);
Eigen::SelfAdjointEigenSolver<Matrix4d> eigen(N);
Vector4d V = eigen.eigenvectors().col(3);
Quaterniond quaternion(V(0), V(1), V(2), V(3));
return quaternion;
}
| 26.02381 | 96 | 0.513266 | mauriciocele |
e951afd2269895e8d535509a9f19580f203a1bbb | 507 | cc | C++ | DataFormats/METReco/src/HaloClusterCandidateHCAL.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | DataFormats/METReco/src/HaloClusterCandidateHCAL.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | DataFormats/METReco/src/HaloClusterCandidateHCAL.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "DataFormats/METReco/interface/HaloClusterCandidateHCAL.h"
using namespace reco;
HaloClusterCandidateHCAL::HaloClusterCandidateHCAL() :
et(0),
seed_et(0),
seed_eta(0),
seed_phi(0),
seed_Z(0),
seed_R(0),
seed_time(0),
ishalofrompattern(false),
ishalofrompattern_hlt(false),
eoverh(0),
etstrip_phiseedplus1(0),
etstrip_phiseedminus1(0),
nbtowersineta(0),
timediscriminatoritbh(0),
timediscriminatorotbh(0),
h1overh123(0),
clustersize(0),
timediscriminator(0)
{
}
| 20.28 | 67 | 0.739645 | nistefan |
e952343c13a600e55880909a6c7f042ae515207b | 9,426 | cc | C++ | android_ar/app/src/main/cpp/game_renderer.cc | oseiskar/3dtris | 16f60c10b8496db1a584c0eaf55cc9959bffab3a | [
"Apache-2.0"
] | 4 | 2018-07-06T21:03:00.000Z | 2022-02-10T10:17:21.000Z | android_ar/app/src/main/cpp/game_renderer.cc | oseiskar/3dtris | 16f60c10b8496db1a584c0eaf55cc9959bffab3a | [
"Apache-2.0"
] | null | null | null | android_ar/app/src/main/cpp/game_renderer.cc | oseiskar/3dtris | 16f60c10b8496db1a584c0eaf55cc9959bffab3a | [
"Apache-2.0"
] | 2 | 2021-08-04T05:49:30.000Z | 2022-02-26T12:19:45.000Z | /*
* Copyright 2017 Google 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.
*
* Modifications copyright (C) Otto Seiskari 2018
*/
#include "game_renderer.h"
#include "util.h"
#include <array>
namespace {
const glm::vec4 kLightDirection(0.5f, 1.0f, 2.0f, 0.0f);
// Shader material lighting "pateremrs" [sic]
// ... just wondering how sleep-deprived the Google interns who wrote the original
// shader were after the ARKit release :P
constexpr float AMBIENT = 0.0f;
constexpr float DIFFUSE = 3.5f;
constexpr float SPECULAR = 1.0f;
constexpr float SPECULAR_POWER = 6.0f;
constexpr char kVertexShader[] = R"(
uniform mat4 u_ModelView;
uniform mat4 u_ModelViewProjection;
attribute vec4 a_Position;
attribute vec3 a_Normal;
attribute vec2 a_TexCoord;
varying vec3 v_ViewPosition;
varying vec3 v_ViewNormal;
varying vec2 v_TexCoord;
void main() {
v_ViewPosition = (u_ModelView * a_Position).xyz;
v_ViewNormal = normalize((u_ModelView * vec4(a_Normal, 0.0)).xyz);
v_TexCoord = a_TexCoord;
gl_Position = u_ModelViewProjection * a_Position;
})";
constexpr char kFragmentShader[] = R"(
precision mediump float;
uniform vec4 u_LightingParameters;
uniform vec4 u_MaterialParameters;
uniform vec3 u_DiffuseColor;
varying vec3 v_ViewPosition;
varying vec3 v_ViewNormal;
varying vec2 v_TexCoord;
void main() {
// We support approximate sRGB gamma.
const float kGamma = 0.4545454;
const float kInverseGamma = 2.2;
const float EDGE_WIDTH = 0.02;
const float EDGE_BRIGHTNESS = 0.3;
// Unpack lighting and material parameters for better naming.
vec3 viewLightDirection = u_LightingParameters.xyz;
float lightIntensity = u_LightingParameters.w;
float materialAmbient = u_MaterialParameters.x;
float materialDiffuse = u_MaterialParameters.y;
float materialSpecular = u_MaterialParameters.z;
float materialSpecularPower = u_MaterialParameters.w;
// Normalize varying parameters, because they are linearly interpolated in
// the vertex shader.
vec3 viewFragmentDirection = normalize(v_ViewPosition);
vec3 viewNormal = normalize(v_ViewNormal);
vec4 objectColor = vec4(u_DiffuseColor, 1.0);
objectColor.rgb = pow(objectColor.rgb, vec3(kInverseGamma));
// Ambient light is unaffected by the light intensity.
float ambient = materialAmbient;
// Approximate a hemisphere light (not a harsh directional light).
float diffuse = lightIntensity * materialDiffuse *
0.5 * (dot(viewNormal, viewLightDirection) + 1.0);
vec2 edgeVec = abs((v_TexCoord - 0.5)*2.0);
float edgeness = max(edgeVec.x, edgeVec.y);
if (edgeness > 1.0 - EDGE_WIDTH) objectColor.rgb = objectColor.rgb * EDGE_BRIGHTNESS;
// Compute specular light.
vec3 reflectedLightDirection = reflect(viewLightDirection, viewNormal);
float specularStrength = max(0.0, dot(viewFragmentDirection,
reflectedLightDirection));
float specular = lightIntensity * materialSpecular *
pow(specularStrength, materialSpecularPower);
// Apply SRGB gamma before writing the fragment color.
gl_FragColor.a = objectColor.a;
gl_FragColor.rgb = pow(objectColor.rgb * (ambient + diffuse) + specular,
vec3(kGamma));
}
)";
constexpr float yIsUpInsteadOfZEl[16] = {
1, 0, 0, 0,
0, 0,-1, 0,
0, 1, 0, 0,
0, 0, 0, 1
};
constexpr int32_t kBlockColorRgbaSize = 16;
constexpr std::array<uint32_t, kBlockColorRgbaSize> kBlockColorRgba = {{
0xFFFFFFFF, 0xF44336FF, 0xE91E63FF, 0x9C27B0FF, 0x673AB7FF, 0x3F51B5FF,
0x2196F3FF, 0x03A9F4FF, 0x00BCD4FF, 0x009688FF, 0x4CAF50FF, 0x8BC34AFF,
0xCDDC39FF, 0xFFEB3BFF, 0xFFC107FF, 0xFF9800FF }};
constexpr float COLOR_LIGHTNESS = 1.0;
inline glm::vec3 GetBlockColor(int i) {
const int32_t colorRgba = kBlockColorRgba[i % kBlockColorRgbaSize];
return glm::vec3(((colorRgba >> 24) & 0xff) / 255.0f,
((colorRgba >> 16) & 0xff) / 255.0f,
((colorRgba >> 8) & 0xff) / 255.0f) * COLOR_LIGHTNESS;
}
} // namespace
GameRenderer::Model GameRenderer::blocksToModel(const std::vector<Block>& blocks,
Pos3d dims,
float game_scale) const {
Model m = Model();
int index_offset = 0;
for (Block block : blocks) {
float pos[3] = {
block.pos.x + 0.5f - dims.x*0.5f,
block.pos.y + 0.5f - dims.y*0.5f,
block.pos.z + 0.5f
};
for (int vertex_index=0; vertex_index < cube_.vertices.size() / 3; ++vertex_index) {
for (int coord = 0; coord < 3; ++coord) {
m.vertices.push_back((cube_.vertices[vertex_index*3+coord]+pos[coord])*game_scale);
}
}
for (int index : cube_.indices) {
m.indices.push_back(index + index_offset);
}
index_offset += cube_.indices.size();
// copy others unmodified
m.uvs.insert(m.uvs.end(), cube_.uvs.begin(), cube_.uvs.end());
m.normals.insert(m.normals.end(), cube_.normals.begin(), cube_.normals.end());
}
return m;
}
const glm::mat4 GAME_MODEL_TRANSFORM = glm::make_mat4(yIsUpInsteadOfZEl);
void GameRenderer::InitializeGlContent(AAssetManager* asset_manager) {
shader_program_ = util::CreateProgram(kVertexShader, kFragmentShader);
if (!shader_program_) {
LOGE("Could not create program.");
}
uniform_mvp_mat_ =
glGetUniformLocation(shader_program_, "u_ModelViewProjection");
uniform_mv_mat_ = glGetUniformLocation(shader_program_, "u_ModelView");
uniform_lighting_param_ =
glGetUniformLocation(shader_program_, "u_LightingParameters");
uniform_material_param_ =
glGetUniformLocation(shader_program_, "u_MaterialParameters");
uniform_diffuse_color_ =
glGetUniformLocation(shader_program_, "u_DiffuseColor");
attri_vertices_ = glGetAttribLocation(shader_program_, "a_Position");
attri_uvs_ = glGetAttribLocation(shader_program_, "a_TexCoord");
attri_normals_ = glGetAttribLocation(shader_program_, "a_Normal");
util::LoadObjFile(asset_manager, "cube.obj", &cube_.vertices, &cube_.normals, &cube_.uvs, &cube_.indices);
util::CheckGlError("obj_renderer::InitializeGlContent()");
// initialize colors
material_colors_.clear();
scene_by_material_.clear();
const int nMaterials = kBlockColorRgbaSize;
const int randomOffset = std::rand();
for (int i = 0; i < nMaterials; ++i) {
material_colors_.push_back(GetBlockColor(i + randomOffset));
scene_by_material_.push_back(Model());
}
}
void GameRenderer::update(const Game& game, float game_scale) {
const int nMaterials = material_colors_.size();
std::vector< std::vector<Block> > blocks_by_material(nMaterials);
for (Block block : game.getAllBlocks()) {
const int materialId = block.pieceId % nMaterials;
blocks_by_material[materialId].push_back(block);
}
for (int i = 0; i < nMaterials; ++i) {
scene_by_material_[i] = blocksToModel(blocks_by_material[i], game.getDimensions(), game_scale);
}
}
void GameRenderer::Draw(const glm::mat4& projection_mat,
const glm::mat4& view_mat, const glm::mat4& model_mat,
float light_intensity) const {
if (!shader_program_) {
LOGE("shader_program is null.");
return;
}
glUseProgram(shader_program_);
glm::mat4 mvp_mat = projection_mat * view_mat * model_mat * GAME_MODEL_TRANSFORM;
glm::mat4 mv_mat = view_mat * model_mat;
glm::vec4 view_light_direction = glm::normalize(mv_mat * kLightDirection);
glUniform4f(uniform_lighting_param_, view_light_direction[0],
view_light_direction[1], view_light_direction[2],
light_intensity);
glUniform4f(uniform_material_param_, AMBIENT, DIFFUSE, SPECULAR, SPECULAR_POWER);
glUniformMatrix4fv(uniform_mvp_mat_, 1, GL_FALSE, glm::value_ptr(mvp_mat));
glUniformMatrix4fv(uniform_mv_mat_, 1, GL_FALSE, glm::value_ptr(mv_mat));
for (int i = 0; i < scene_by_material_.size(); ++i) {
const Model& model = scene_by_material_[i];
if (model.vertices.size() == 0) {
continue;
}
const glm::vec3 color = material_colors_[i] * light_intensity;
glUniform3f(uniform_diffuse_color_, color.x, color.y, color.z);
glEnableVertexAttribArray(attri_vertices_);
glVertexAttribPointer(attri_vertices_, 3, GL_FLOAT, GL_FALSE, 0,
model.vertices.data());
glEnableVertexAttribArray(attri_normals_);
glVertexAttribPointer(attri_normals_, 3, GL_FLOAT, GL_FALSE, 0,
model.normals.data());
glEnableVertexAttribArray(attri_uvs_);
glVertexAttribPointer(attri_uvs_, 2, GL_FLOAT, GL_FALSE, 0, model.uvs.data());
glDrawElements(GL_TRIANGLES, model.indices.size(), GL_UNSIGNED_SHORT,
model.indices.data());
glDisableVertexAttribArray(attri_vertices_);
glDisableVertexAttribArray(attri_uvs_);
glDisableVertexAttribArray(attri_normals_);
}
glUseProgram(0);
util::CheckGlError("obj_renderer::Draw()");
}
| 33.190141 | 108 | 0.711436 | oseiskar |
e957f50abe95b4ce045a51ea3741abaf9d6ec67d | 1,846 | cpp | C++ | EM4205.cpp | bert386/arduino_utft_hmi | f720bf61b7c9d9cf46fb4902db9e8833d5b15410 | [
"Apache-2.0"
] | null | null | null | EM4205.cpp | bert386/arduino_utft_hmi | f720bf61b7c9d9cf46fb4902db9e8833d5b15410 | [
"Apache-2.0"
] | null | null | null | EM4205.cpp | bert386/arduino_utft_hmi | f720bf61b7c9d9cf46fb4902db9e8833d5b15410 | [
"Apache-2.0"
] | null | null | null | #include "EM4205.h"
bool initRFID()
{
RFIDSerial.end();
//
RFIDSerial.begin(9600);
RFIDSerial.flush();
RFIDSerial.print(F("SD2\r"));
uint32_t nStartTime = millis();
bool bReceving = false;
String resp = "";
while (1)
{
if (RFIDSerial.available())
{
bReceving = true;
resp += String((char)RFIDSerial.read());
nStartTime = millis();
}
if (bReceving == false)
{
if (millis() - nStartTime > 1000)
return false;
}
else
{
if (millis() - nStartTime > 100)
break;
}
}
Serial.println(resp);
if (resp.indexOf("OK") != -1)
return true;
}
bool checkTag()
{
/*
while (RFIDSerial.available())
char ch = RFIDSerial.read();
String req = "LTG\r";
//RFIDSerial.flush();
RFIDSerial.print(req);
uint32_t nStartTime = millis();
bool bReceving = false;
String resp = "";
while (1)
{
if (RFIDSerial.available())
{
bReceving = true;
resp += String((char)RFIDSerial.read());
nStartTime = millis();
}
if (bReceving == false)
{
if (millis() - nStartTime > 1000)
{
Serial.println("Timeout in communication!");
return false;
}
}
else
{
if (millis() - nStartTime > 10)
break;
}
}
Serial.println(resp);
if (resp.indexOf("OK") != -1)
{
return true;
}*/
return false;
}
String getResponse()
{
uint32_t nStartTime = millis();
bool bReceving = false;
String resp = "";
if (RFIDSerial.available())
{
while (1)
{
if (RFIDSerial.available())
{
bReceving = true;
char ch = RFIDSerial.read();
if (ch == 0x0D)
break;
else
resp += String(ch);
nStartTime = millis();
}
if (bReceving == false)
{
if (millis() - nStartTime > 1000)
{
Serial.println(F("Timeout in communication!"));
}
}
else
{
if (millis() - nStartTime > 30)
break;
}
}
}
return resp;
} | 14.768 | 52 | 0.576381 | bert386 |
e95ade09c141745de16b5e440e985348c8459076 | 401 | cpp | C++ | src/compliance.cpp | cran/ruimtehol | 8e2bbf1a67c7868192a457ba58492dcb43e26e87 | [
"BSD-3-Clause"
] | null | null | null | src/compliance.cpp | cran/ruimtehol | 8e2bbf1a67c7868192a457ba58492dcb43e26e87 | [
"BSD-3-Clause"
] | null | null | null | src/compliance.cpp | cran/ruimtehol | 8e2bbf1a67c7868192a457ba58492dcb43e26e87 | [
"BSD-3-Clause"
] | null | null | null | /*
#include <Rcpp.h>
#include <stdlib.h>
// [[Rcpp::export]]
int rand() {
int r = R::unif_rand() * RAND_MAX;
return r;
}
// [[Rcpp::export]]
void srand(unsigned int seed){
Rcpp::Environment base("package:base");
Rcpp::Function set_seed = base["set.seed"];
set_seed(seed);
};
namespace std {
std::ostream Rcout(Rcpp::Rcout.rdbuf());
std::ostream Rcerr(Rcpp::Rcerr.rdbuf());
}
*/
| 17.434783 | 49 | 0.620948 | cran |
e95f4d29ee1c0054f8a378bc5fab1b1655df7316 | 1,811 | cpp | C++ | LeetCode/Problems/Algorithms/#662_MaximumWidthOfBinaryTree_sol2_bfs.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#662_MaximumWidthOfBinaryTree_sol2_bfs.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#662_MaximumWidthOfBinaryTree_sol2_bfs.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
int max_width = 0;
queue<pair<TreeNode*, int>> q;
if(root != NULL){
q.push({root, 1});
}
while(!q.empty()){
if(q.size() == 1){
// use this trick to avoid overflow
q.front().second = 1;
}
// min and max pos of the current level
int min_pos = q.front().second;
int max_pos = q.front().second;
// check only the nodes from the current level
for(int nodes_cnt = q.size(); nodes_cnt > 0; --nodes_cnt){
TreeNode* node = q.front().first;
int pos = q.front().second;
q.pop();
// update min and max pos of the current level
min_pos = min(pos, min_pos);
max_pos = max(pos, max_pos);
// add nodes for the next level
if(node->left != NULL){
q.push({node->left, 2 * pos});
}
if(node->right != NULL){
q.push({node->right, 2 * pos + 1});
}
}
max_width = max(max_pos - min_pos + 1, max_width);
}
return max_width;
}
}; | 32.339286 | 94 | 0.429045 | Tudor67 |
e9604b41c710292d935908af771b4d184a785ff8 | 11,423 | cpp | C++ | Source/Model/CSceneAppMediaEngine.cpp | StevoGTA/SceneApp | a24337bb749d13411b5f78460b8a7915024cbeb7 | [
"MIT"
] | null | null | null | Source/Model/CSceneAppMediaEngine.cpp | StevoGTA/SceneApp | a24337bb749d13411b5f78460b8a7915024cbeb7 | [
"MIT"
] | null | null | null | Source/Model/CSceneAppMediaEngine.cpp | StevoGTA/SceneApp | a24337bb749d13411b5f78460b8a7915024cbeb7 | [
"MIT"
] | null | null | null | //----------------------------------------------------------------------------------------------------------------------
// CSceneAppMediaEngine.cpp ©2020 Stevo Brock All rights reserved.
//----------------------------------------------------------------------------------------------------------------------
#include "CSceneAppMediaEngine.h"
#include "CAudioDecoder.h"
#include "CDictionary.h"
#include "CFilesystemPath.h"
#include "CMediaSourceRegistry.h"
#include "CVideoDecoder.h"
#if defined(TARGET_OS_IOS) || defined(TARGET_OS_MACOS) || defined(TARGET_OS_TVOS)
#include "CCoreAudioAudioConverter.h"
#elif defined(TARGET_OS_WINDOWS)
#include "CSecretRabbitCodeAudioConverter.h"
#endif
//----------------------------------------------------------------------------------------------------------------------
// MARK: CSceneAppMediaPlayer
class CSceneAppMediaPlayer : public CMediaPlayer {
public:
CSceneAppMediaPlayer(CSRSWMessageQueues& messageQueues, const CMediaPlayer::Info& info,
const CString& resourceFilename,
TReferenceDictionary<CSceneAppMediaPlayer>& sceneAppMediaPlayerMap) :
CMediaPlayer(messageQueues, info), mResourceFilename(resourceFilename),
mSceneAppMediaPlayerMap(sceneAppMediaPlayerMap), mReferenceCount(0)
{}
void addReference()
{ mReferenceCount++; }
void removeReference()
{
// Check if last reference
if (--mReferenceCount == 0) {
// Going away now
mSceneAppMediaPlayerMap.remove(mResourceFilename);
CSceneAppMediaPlayer* THIS = this;
Delete(THIS);
}
}
CString mResourceFilename;
TReferenceDictionary<CSceneAppMediaPlayer>& mSceneAppMediaPlayerMap;
UInt32 mReferenceCount;
};
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
// MARK: - CSceneAppMediaPlayerReference
class CSceneAppMediaPlayerReference : public CMediaPlayer {
public:
CSceneAppMediaPlayerReference(CSRSWMessageQueues& messageQueues,
const CMediaPlayer::Info& info, CSceneAppMediaPlayer& sceneAppMediaPlayer) :
CMediaPlayer(messageQueues, info), mSceneAppMediaPlayer(sceneAppMediaPlayer)
{ mSceneAppMediaPlayer.addReference(); }
~CSceneAppMediaPlayerReference()
{ mSceneAppMediaPlayer.removeReference(); }
void setupComplete()
{ mSceneAppMediaPlayer.setupComplete(); }
I<CAudioPlayer> newAudioPlayer(const CString& identifier, UInt32 trackIndex)
{ return mSceneAppMediaPlayer.newAudioPlayer(identifier, trackIndex); }
void setAudioGain(Float32 audioGain)
{ mSceneAppMediaPlayer.setAudioGain(audioGain); }
I<CVideoFrameStore> newVideoFrameStore(const CString& identifier, UInt32 trackIndex)
{ return mSceneAppMediaPlayer.newVideoFrameStore(identifier, trackIndex); }
void setLoopCount(OV<UInt32> loopCount = OV<UInt32>())
{ mSceneAppMediaPlayer.setLoopCount(loopCount); }
void play()
{ mSceneAppMediaPlayer.play(); }
void pause()
{ mSceneAppMediaPlayer.pause(); }
bool isPlaying() const
{ return mSceneAppMediaPlayer.isPlaying(); }
void reset()
{ mSceneAppMediaPlayer.reset(); }
CSceneAppMediaPlayer& mSceneAppMediaPlayer;
};
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
// MARK: - CSceneAppMediaEngineInternals
class CSceneAppMediaEngineInternals {
public:
CSceneAppMediaEngineInternals(CSRSWMessageQueues& messageQueues,
const SSceneAppResourceLoading& sceneAppResourceLoading) :
mMessageQueues(messageQueues), mSSceneAppResourceLoading(sceneAppResourceLoading)
{}
CSRSWMessageQueues& mMessageQueues;
SSceneAppResourceLoading mSSceneAppResourceLoading;
TReferenceDictionary<CSceneAppMediaPlayer> mSceneAppMediaPlayerMap;
};
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
// MARK: - CSceneAppMediaEngine
// MARK: Lifecycle methods
//----------------------------------------------------------------------------------------------------------------------
CSceneAppMediaEngine::CSceneAppMediaEngine(CSRSWMessageQueues& messageQueues,
const SSceneAppResourceLoading& sceneAppResourceLoading) : CMediaEngine()
//----------------------------------------------------------------------------------------------------------------------
{
mInternals = new CSceneAppMediaEngineInternals(messageQueues, sceneAppResourceLoading);
}
//----------------------------------------------------------------------------------------------------------------------
CSceneAppMediaEngine::~CSceneAppMediaEngine()
//----------------------------------------------------------------------------------------------------------------------
{
Delete(mInternals);
}
// MARK: Instance methods
//----------------------------------------------------------------------------------------------------------------------
OI<CMediaPlayer> CSceneAppMediaEngine::getMediaPlayer(const CAudioInfo& audioInfo, const CMediaPlayer::Info& info)
//----------------------------------------------------------------------------------------------------------------------
{
// Setup
const CString& resourceFilename = audioInfo.getResourceFilename();
// CAudioInfo::Options audioInfoOptions = audioInfo.getOptions();
// Look for existing media player
const OR<CSceneAppMediaPlayer> sceneAppMediaPlayerReference =
mInternals->mSceneAppMediaPlayerMap[resourceFilename];
if (sceneAppMediaPlayerReference.hasReference())
// Have reference
return OI<CMediaPlayer>(
new CSceneAppMediaPlayerReference(mInternals->mMessageQueues, info, *sceneAppMediaPlayerReference));
// Query audio tracks
I<CSeekableDataSource> seekableDataSource =
mInternals->mSSceneAppResourceLoading
.createSeekableDataSource(resourceFilename);
CString extension =
CFilesystemPath(resourceFilename).getExtension();
TIResult<CMediaSourceRegistry::IdentifyInfo> identifyInfo =
CMediaSourceRegistry::mShared.identify(
seekableDataSource, extension,
SMediaSource::kComposeDecodeInfo);
const CMediaTrackInfos& mediaTrackInfos =
identifyInfo.getValue().getMediaTrackInfos();
const TArray<CMediaTrackInfos::AudioTrackInfo>& audioTrackInfos = mediaTrackInfos.getAudioTrackInfos();
// Setup Media Player
CSceneAppMediaPlayer* sceneAppMediaPlayer =
new CSceneAppMediaPlayer(mInternals->mMessageQueues, info, resourceFilename,
mInternals->mSceneAppMediaPlayerMap);
for (CArray::ItemIndex i = 0; i < audioTrackInfos.getCount(); i++) {
// Setup
I<CAudioSource> audioSource = getAudioSource(audioTrackInfos[i]);
I<CAudioPlayer> audioPlayer = sceneAppMediaPlayer->newAudioPlayer(resourceFilename, i);
// Connect
ConnectResult connectResult =
connect((I<CAudioProcessor>&) audioSource, (I<CAudioProcessor>&) audioPlayer,
composeAudioProcessingFormat(*audioSource, *audioPlayer));
if (!connectResult.isSuccess()) {
// Cleanup
Delete(sceneAppMediaPlayer);
return OI<CMediaPlayer>();
}
}
// Finish setup
sceneAppMediaPlayer->setAudioGain(audioInfo.getGain());
sceneAppMediaPlayer->setLoopCount(audioInfo.getLoopCount());
sceneAppMediaPlayer->setupComplete();
// Success
mInternals->mSceneAppMediaPlayerMap.set(resourceFilename, *sceneAppMediaPlayer);
return OI<CMediaPlayer>(new CSceneAppMediaPlayerReference(mInternals->mMessageQueues, info, *sceneAppMediaPlayer));
}
//----------------------------------------------------------------------------------------------------------------------
OI<CMediaPlayer> CSceneAppMediaEngine::getMediaPlayer(const VideoInfo& videoInfo,
CVideoFrame::Compatibility compatibility, const CMediaPlayer::Info& info)
//----------------------------------------------------------------------------------------------------------------------
{
// Setup
const CString& filename = videoInfo.mFilename;
// Query tracks
I<CSeekableDataSource> seekableDataSource =
mInternals->mSSceneAppResourceLoading
.createSeekableDataSource(filename);
CString extension = CFilesystemPath(filename).getExtension();
TIResult<CMediaSourceRegistry::IdentifyInfo> identifyInfo =
CMediaSourceRegistry::mShared.identify(
seekableDataSource, extension,
SMediaSource::kComposeDecodeInfo);
const CMediaTrackInfos& mediaTrackInfos =
identifyInfo.getValue().getMediaTrackInfos();
const TArray<CMediaTrackInfos::AudioTrackInfo>& audioTrackInfos = mediaTrackInfos.getAudioTrackInfos();
const TArray<CMediaTrackInfos::VideoTrackInfo>& videoTrackInfos = mediaTrackInfos.getVideoTrackInfos();
// Setup Media Player
CSceneAppMediaPlayer* sceneAppMediaPlayer =
new CSceneAppMediaPlayer(mInternals->mMessageQueues, info, filename,
mInternals->mSceneAppMediaPlayerMap);
for (CArray::ItemIndex i = 0; i < audioTrackInfos.getCount(); i++) {
// Setup
I<CAudioSource> audioSource = getAudioSource(audioTrackInfos[i]);
I<CAudioPlayer> audioPlayer = sceneAppMediaPlayer->newAudioPlayer(filename, i);
// Connect
ConnectResult connectResult =
connect((I<CAudioProcessor>&) audioSource, (I<CAudioProcessor>&) audioPlayer,
composeAudioProcessingFormat(*audioSource, *audioPlayer));
if (!connectResult.isSuccess()) {
// Cleanup
Delete(sceneAppMediaPlayer);
return OI<CMediaPlayer>();
}
}
for (CArray::ItemIndex i = 0; i < videoTrackInfos.getCount(); i++) {
// Setup
I<CVideoSource> videoSource = getVideoSource(videoTrackInfos[i], compatibility);
I<CVideoFrameStore> videoFrameStore = sceneAppMediaPlayer->newVideoFrameStore(filename, i);
// Connect
OI<SError> error = videoFrameStore->connectInput((const I<CVideoProcessor>&) videoSource);
if (error.hasInstance()) {
// Cleanup
Delete(sceneAppMediaPlayer);
return OI<CMediaPlayer>();
}
}
// Finish setup
sceneAppMediaPlayer->setupComplete();
// Success
mInternals->mSceneAppMediaPlayerMap.set(filename, *sceneAppMediaPlayer);
return OI<CMediaPlayer>(new CSceneAppMediaPlayerReference(mInternals->mMessageQueues, info, *sceneAppMediaPlayer));
}
// MARK: Subclass methods
//----------------------------------------------------------------------------------------------------------------------
I<CAudioConverter> CSceneAppMediaEngine::createAudioConverter() const
//----------------------------------------------------------------------------------------------------------------------
{
#if defined(TARGET_OS_IOS) || defined(TARGET_OS_MACOS) || defined(TARGET_OS_TVOS)
// Apple
return I<CAudioConverter>(new CCoreAudioAudioConverter());
#elif defined(TARGET_OS_WINDOWS)
// Windows
return I<CAudioConverter>(new CSecretRabbitCodeAudioConverter());
#endif
}
| 42.151292 | 120 | 0.594327 | StevoGTA |
e960df1ae0f33fa355bb35e37644c81bce130494 | 2,390 | cc | C++ | sippet/message/header.cc | sippet/sippet | c6f4b0e9723f56cfb6d345d307a48f1ff0eb2c65 | [
"BSD-3-Clause"
] | 26 | 2015-04-01T22:56:51.000Z | 2021-11-29T08:46:35.000Z | sippet/message/header.cc | sippet/sippet | c6f4b0e9723f56cfb6d345d307a48f1ff0eb2c65 | [
"BSD-3-Clause"
] | null | null | null | sippet/message/header.cc | sippet/sippet | c6f4b0e9723f56cfb6d345d307a48f1ff0eb2c65 | [
"BSD-3-Clause"
] | 8 | 2015-04-01T22:56:56.000Z | 2021-06-10T02:21:26.000Z | // Copyright (c) 2013 The Sippet 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 "sippet/message/header.h"
#include <cstring>
#include <algorithm>
#include "sippet/message/headers/generic.h"
#include "base/basictypes.h"
#include "base/strings/string_util.h"
namespace sippet {
namespace {
static const char *names[] = {
#define X(class_name, compact_form, header_name, enum_name, format) \
#header_name,
#include "sippet/message/header_list.h"
#undef X
};
static const char compact_forms[] = {
#define X(class_name, compact_form, header_name, enum_name, format) \
compact_form,
#include "sippet/message/header_list.h"
#undef X
};
bool HeaderNameLess(const char *a, const char *b) {
return base::strcasecmp(a, b) < 0;
}
} // namespace
Header::Header(Type type)
: type_(type) {
}
Header::Header(const Header &other)
: type_(other.type_) {
}
Header::~Header() {
}
const char *Header::name() const {
if (isa<Generic>(this))
return dyn_cast<Generic>(this)->header_name_.c_str();
return AtomTraits<Header::Type>::string_of(type());
}
const char Header::compact_form() const {
return compact_forms[static_cast<int>(type_)];
}
void Header::print(raw_ostream &os) const {
if (compact_form() != 0)
os << static_cast<signed char>(compact_form());
else
os << name();
os << ": ";
}
const char *AtomTraits<Header::Type>::string_of(type t) {
return names[static_cast<int>(t)];
}
AtomTraits<Header::Type>::type
AtomTraits<Header::Type>::coerce(const char *str) {
Header::Type type = Header::HDR_GENERIC;
size_t len = strlen(str);
if (strlen(str) == 1) {
char h = tolower(str[0]);
for (int i = 0; i < arraysize(compact_forms); ++i) {
if (h == compact_forms[i]) {
type = static_cast<Header::Type>(i);
break;
}
}
} else {
// Perform a simple binary search
const char **first = names;
const char **last = names + arraysize(names);
const char **found = std::lower_bound(first, last, str, HeaderNameLess);
if (found != last
&& base::strcasecmp(*found, str) == 0) {
type = static_cast<Header::Type>(found - first);
}
}
return type;
}
} // namespace sippet
| 24.387755 | 77 | 0.630126 | sippet |
e964a248419155561dad97b26eed0340ad045b78 | 134 | cpp | C++ | persistence/backend.cpp | czpwpq/hotel | 2e003b019cf6b21349228740a8dae6c639945510 | [
"MIT"
] | 7 | 2017-04-05T20:06:30.000Z | 2022-01-01T00:14:42.000Z | persistence/backend.cpp | czpwpq/hotel | 2e003b019cf6b21349228740a8dae6c639945510 | [
"MIT"
] | 1 | 2017-01-06T13:47:45.000Z | 2017-01-06T13:49:47.000Z | persistence/backend.cpp | decden/hotel | 1d7d16ad0a97c9a24f8e54b9b180fcd3166d0c89 | [
"MIT"
] | 4 | 2017-04-05T20:06:31.000Z | 2020-10-29T14:50:12.000Z | #include "persistence/backend.h"
namespace persistence
{
Backend::Backend() {}
Backend::~Backend() {}
} // namespace persistence
| 16.75 | 32 | 0.701493 | czpwpq |
e96739bf6e4bc7f698b1de5c069b552058138a1f | 309 | cpp | C++ | SignalTester/playsoundfile/playfile.cpp | GeertRoks/DSP_theory | 508e6b52261460c7d06caffa02cab66b38d87e88 | [
"MIT"
] | null | null | null | SignalTester/playsoundfile/playfile.cpp | GeertRoks/DSP_theory | 508e6b52261460c7d06caffa02cab66b38d87e88 | [
"MIT"
] | null | null | null | SignalTester/playsoundfile/playfile.cpp | GeertRoks/DSP_theory | 508e6b52261460c7d06caffa02cab66b38d87e88 | [
"MIT"
] | null | null | null |
#include "playfile.hpp"
Playfile::Playfile() {
}
Playfile::Playfile(std::string file) {
}
std::vector<double> Playfile::getSamples(const unsigned int num_samples) {
std::vector<double> file = {};
for (unsigned int i = 0; i < num_samples; i++) {
file.push_back(sample0[i]);
}
return file;
}
| 17.166667 | 74 | 0.653722 | GeertRoks |
e96cb2a50dc79efaf5825c78e77700732319be4c | 2,265 | cpp | C++ | tests/util/uint_types_test.cpp | patflick/dpt | 5b300500c97f41d1d24c4e660af2d4499ad40520 | [
"BSD-2-Clause"
] | 7 | 2017-03-23T05:19:53.000Z | 2021-02-26T14:25:08.000Z | tests/util/uint_types_test.cpp | patflick/dpt | 5b300500c97f41d1d24c4e660af2d4499ad40520 | [
"BSD-2-Clause"
] | 2 | 2019-04-04T02:24:06.000Z | 2019-04-04T02:57:08.000Z | tests/util/uint_types_test.cpp | patflick/dpt | 5b300500c97f41d1d24c4e660af2d4499ad40520 | [
"BSD-2-Clause"
] | 2 | 2019-04-03T20:09:47.000Z | 2021-10-30T16:06:47.000Z | /*******************************************************************************
* tests/util/uint_types_test.cpp
*
* Part of dpt - Distributed Patricia Trie
*
* Copyright (C) 2013 Timo Bingmann <tb@panthema.net>
*
* Copied from:
* > tests/common/uint_types_test.cpp
* >
* > Class representing a 40-bit or 48-bit unsigned integer encoded in five or
* > six bytes.
* > Part of Project Thrill - http://project-thrill.org
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#include <gtest/gtest.h>
#include <limits>
#include <dpt/util/uint_types.hpp>
// forced instantiation
template class dpt::UIntPair<uint8_t>;
template class dpt::UIntPair<uint16_t>;
template <typename uint>
void dotest(unsigned int nbytes) {
// simple initialize
uint a = 42;
// check sizeof (again)
ASSERT_EQ(sizeof(a), nbytes);
// count up 1024 and down again
uint b = 0xFFFFFF00;
uint b_save = b;
uint64_t b64 = b;
for (uint32_t i = 0; i < 1024; ++i)
{
ASSERT_EQ(b.u64(), b64);
ASSERT_EQ(b.ull(), b64);
ASSERT_NE(b, a);
++b, ++b64;
}
ASSERT_NE(b, b_save);
for (uint32_t i = 0; i < 1024; ++i)
{
ASSERT_EQ(b.u64(), b64);
ASSERT_EQ(b.ull(), b64);
ASSERT_NE(b, a);
--b, --b64;
}
ASSERT_EQ(b.u64(), b64);
ASSERT_EQ(b.ull(), b64);
ASSERT_EQ(b, b_save);
// check min and max value
ASSERT_LE(uint::min(), a);
ASSERT_GE(uint::max(), a);
ASSERT_LT(std::numeric_limits<uint>::min(), a);
ASSERT_GT(std::numeric_limits<uint>::max(), a);
// check simple math
a = 42;
a = a + a;
ASSERT_EQ(a, uint(84));
ASSERT_EQ(a.ull(), uint(84));
a += uint(0xFFFFFF00);
ASSERT_EQ(a.ull(), 0xFFFFFF54llu);
a += uint(0xFFFFFF00);
ASSERT_EQ(a.ull(), 0x1FFFFFE54llu);
a -= uint(0xFFFFFF00);
ASSERT_EQ(a.ull(), 0xFFFFFF54llu);
a -= uint(0xFFFFFF00);
ASSERT_EQ(a.ull(), uint(84));
}
TEST(UIntPair, Uint40) {
dotest<dpt::uint40>(5);
}
TEST(UIntPair, Uint48) {
dotest<dpt::uint48>(6);
}
/******************************************************************************/
| 23.112245 | 80 | 0.535541 | patflick |
e96fa3a34c947073127ea50e215fbfcafa254d93 | 5,120 | hpp | C++ | pylc/src/pylc_lib/converters.hpp | CMU-Light-Curtains/ObjectDetection | d2002f6d1ebcf05a78f179bf0474703ed0211ac0 | [
"BSD-3-Clause"
] | null | null | null | pylc/src/pylc_lib/converters.hpp | CMU-Light-Curtains/ObjectDetection | d2002f6d1ebcf05a78f179bf0474703ed0211ac0 | [
"BSD-3-Clause"
] | null | null | null | pylc/src/pylc_lib/converters.hpp | CMU-Light-Curtains/ObjectDetection | d2002f6d1ebcf05a78f179bf0474703ed0211ac0 | [
"BSD-3-Clause"
] | null | null | null | #ifndef CONVERTERS_H
#define CONVERTERS_H
#include <memory>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include <stdexcept>
#include <opencv2/core/core.hpp>
#include <Eigen/Dense>
#include <eigen3/Eigen/src/Core/Matrix.h>
#include <pybind11/eigen.h>
#include <opencv2/opencv.hpp>
#include <opencv/cxeigen.hpp>
namespace py = pybind11;
// Numpy - cv::Mat interop
namespace pybind11 { namespace detail {
template <> struct type_caster<cv::Mat> {
public:
PYBIND11_TYPE_CASTER(cv::Mat, _("numpy.ndarray"));
// Cast numpy to cv::Mat
bool load(handle src, bool)
{
/* Try a default converting into a Python */
//array b(src, true);
array b = reinterpret_borrow<array>(src);
buffer_info info = b.request();
int ndims = info.ndim;
decltype(CV_32F) dtype;
size_t elemsize;
if (info.format == format_descriptor<float>::format()) {
if (ndims == 3) {
dtype = CV_32FC3;
} else {
dtype = CV_32FC1;
}
elemsize = sizeof(float);
} else if (info.format == format_descriptor<double>::format()) {
if (ndims == 3) {
dtype = CV_64FC3;
} else {
dtype = CV_64FC1;
}
elemsize = sizeof(double);
} else if (info.format == format_descriptor<unsigned char>::format()) {
if (ndims == 3) {
dtype = CV_8UC3;
} else {
dtype = CV_8UC1;
}
elemsize = sizeof(unsigned char);
} else {
throw std::logic_error("Unsupported type");
return false;
}
std::vector<int> shape = {(int)info.shape[0], (int)info.shape[1]};
value = cv::Mat(cv::Size(shape[1], shape[0]), dtype, info.ptr, cv::Mat::AUTO_STEP);
return true;
}
// Cast cv::Mat to numpy
static handle cast(const cv::Mat &m, return_value_policy, handle defval)
{
std::string format = format_descriptor<unsigned char>::format();
size_t elemsize = sizeof(unsigned char);
int dim, channels;
switch(m.type()) {
case CV_8U:
format = format_descriptor<unsigned char>::format();
elemsize = sizeof(unsigned char);
dim = 2;
channels = 0;
break;
case CV_8UC3:
format = format_descriptor<unsigned char>::format();
elemsize = sizeof(unsigned char);
dim = 3;
channels = 3;
break;
case CV_32F:
format = format_descriptor<float>::format();
elemsize = sizeof(float);
dim = 2;
channels = 0;
break;
case CV_64F:
format = format_descriptor<double>::format();
elemsize = sizeof(double);
dim = 2;
channels = 0;
break;
case CV_32FC4:
format = format_descriptor<float>::format();
elemsize = sizeof(float);
dim = 3;
channels = 4;
break;
default:
throw std::logic_error("Unsupported type");
}
std::vector<size_t> bufferdim;
std::vector<size_t> strides;
if (dim == 2) {
bufferdim = {(size_t) m.rows, (size_t) m.cols};
strides = {elemsize * (size_t) m.cols, elemsize};
} else if (dim == 3) {
bufferdim = {(size_t) m.rows, (size_t) m.cols, (size_t) channels};
strides = {(size_t) elemsize * m.cols * channels, (size_t) elemsize * channels, (size_t) elemsize};
}
return array(buffer_info(
m.data, /* Pointer to buffer */
elemsize, /* Size of one scalar */
format, /* Python struct-style format descriptor */
dim, /* Number of dimensions */
bufferdim, /* Buffer dimensions */
strides /* Strides (in bytes) for each index */
)).release();
}
};
}} // namespace pybind11::detail
#endif | 38.208955 | 119 | 0.426953 | CMU-Light-Curtains |
e971b1083ac5316aa29749b05674ff5cf40ad582 | 1,880 | cpp | C++ | code/5/5_pre2_4_bombard.cpp | kdh9949/snups-scpc2020 | 7a3266ea6ba618e5ae066f156f404689d5e270b6 | [
"MIT"
] | 6 | 2020-07-14T01:46:39.000Z | 2021-06-15T06:08:28.000Z | code/5/5_pre2_4_bombard.cpp | kdh9949/snups-scpc2020 | 7a3266ea6ba618e5ae066f156f404689d5e270b6 | [
"MIT"
] | null | null | null | code/5/5_pre2_4_bombard.cpp | kdh9949/snups-scpc2020 | 7a3266ea6ba618e5ae066f156f404689d5e270b6 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pil = pair<int, ll>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
using vint = vector<int>;
using vll = vector<ll>;
using vld = vector<ld>;
using vpii = vector<pii>;
using vpil = vector<pil>;
using vpli = vector<pli>;
using vpll = vector<pll>;
#define x first
#define y second
#define all(v) v.begin(),v.end()
void solve() {
int n, m;
cin >> n >> m;
vector<string> b(n + 2);
b[0] = b[n + 1] = string("0", m + 2);
for(int i = 1; i <= n; i++) {
cin >> b[i];
b[i] = "0" + b[i] + "0";
}
vpii ans;
auto cnt = [&](int x, int y) {
if(x <= 0 || y <= 0) return -1;
int r = 0;
for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++)
if(b[x + i][y + j] == '1') r++;
return r;
};
auto bomb = [&](int x, int y) {
ans.emplace_back(x, y);
for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++)
b[x + i][y + j] = '0';
};
for(int i = 1; i <= n - 3; i++) {
for(int j = 1; j <= m - 3; j++) {
if(b[i][j] == '1') {
int c[3] = {cnt(i, j - 2), cnt(i, j - 1), cnt(i, j)};
int mx = max({c[0], c[1], c[2]});
if(mx == c[0]) bomb(i, j - 2);
else if(mx == c[1]) bomb(i, j - 1);
else bomb(i, j);
}
}
}
for(int i = 1; i <= n - 3; i++) {
if(b[i][m - 2] + b[i][m - 1] + b[i][m] > 3 * '0') bomb(i, m - 2);
}
for(int i = 1; i <= m - 3; i++) {
if(b[n - 2][i] + b[n - 1][i] + b[n][i] > 3 * '0') bomb(n - 2, i);
}
if(cnt(n - 2, m - 2)) bomb(n - 2, m - 2);
cout << ans.size() << '\n';
for(pii &p : ans) cout << p.x << ' ' << p.y << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tc;
cin >> tc;
for(int i = 1; i <= tc; i++) {
cout << "Case #" << i << '\n';
solve();
}
return 0;
} | 22.650602 | 69 | 0.435106 | kdh9949 |
e9779e6332cd2d77705c5ddf66cba1f12eb3205a | 2,847 | cpp | C++ | venv/boost_1_73_0/libs/graph/example/kuratowski_subgraph.cpp | uosorio/heroku_face | 7d6465e71dba17a15d8edaef520adb2fcd09d91e | [
"Apache-2.0"
] | 106 | 2015-08-07T04:23:50.000Z | 2020-12-27T18:25:15.000Z | 3rdparty/boost_1_73_0/libs/graph/example/kuratowski_subgraph.cpp | qingkouwei/mediaones | cec475e1bfd5807b5351cc7e38d244ac5298ca16 | [
"MIT"
] | 130 | 2016-06-22T22:11:25.000Z | 2020-11-29T20:24:09.000Z | Libs/boost_1_76_0/libs/graph/example/kuratowski_subgraph.cpp | Antd23rus/S2DE | 47cc7151c2934cd8f0399a9856c1e54894571553 | [
"MIT"
] | 41 | 2015-07-08T19:18:35.000Z | 2021-01-14T16:39:56.000Z | //=======================================================================
// Copyright 2007 Aaron Windsor
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/ref.hpp>
#include <vector>
#include <boost/graph/boyer_myrvold_planar_test.hpp>
#include <boost/graph/is_kuratowski_subgraph.hpp>
using namespace boost;
int main(int argc, char** argv)
{
typedef adjacency_list< vecS, vecS, undirectedS,
property< vertex_index_t, int >, property< edge_index_t, int > >
graph;
// Create a K_6 (complete graph on 6 vertices), which
// contains both Kuratowski subgraphs as minors.
graph g(6);
add_edge(0, 1, g);
add_edge(0, 2, g);
add_edge(0, 3, g);
add_edge(0, 4, g);
add_edge(0, 5, g);
add_edge(1, 2, g);
add_edge(1, 3, g);
add_edge(1, 4, g);
add_edge(1, 5, g);
add_edge(2, 3, g);
add_edge(2, 4, g);
add_edge(2, 5, g);
add_edge(3, 4, g);
add_edge(3, 5, g);
add_edge(4, 5, g);
// Initialize the interior edge index
property_map< graph, edge_index_t >::type e_index = get(edge_index, g);
graph_traits< graph >::edges_size_type edge_count = 0;
graph_traits< graph >::edge_iterator ei, ei_end;
for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)
put(e_index, *ei, edge_count++);
// Test for planarity - we know it is not planar, we just want to
// compute the kuratowski subgraph as a side-effect
typedef std::vector< graph_traits< graph >::edge_descriptor >
kuratowski_edges_t;
kuratowski_edges_t kuratowski_edges;
if (boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,
boyer_myrvold_params::kuratowski_subgraph
= std::back_inserter(kuratowski_edges)))
std::cout << "Input graph is planar" << std::endl;
else
{
std::cout << "Input graph is not planar" << std::endl;
std::cout << "Edges in the Kuratowski subgraph: ";
kuratowski_edges_t::iterator ki, ki_end;
ki_end = kuratowski_edges.end();
for (ki = kuratowski_edges.begin(); ki != ki_end; ++ki)
{
std::cout << *ki << " ";
}
std::cout << std::endl;
std::cout << "Is a kuratowski subgraph? ";
if (is_kuratowski_subgraph(
g, kuratowski_edges.begin(), kuratowski_edges.end()))
std::cout << "Yes." << std::endl;
else
std::cout << "No." << std::endl;
}
return 0;
}
| 33.104651 | 75 | 0.594661 | uosorio |
e979f182915b3388f0bd4b6af035cb26c02a6dbf | 953 | cpp | C++ | controller.cpp | dridk/tankfighter | 2a4f9e72b524bb991ad1d5c665890845d4e288ba | [
"Zlib",
"MIT"
] | 1 | 2019-04-17T14:54:19.000Z | 2019-04-17T14:54:19.000Z | controller.cpp | dridk/tankfighter | 2a4f9e72b524bb991ad1d5c665890845d4e288ba | [
"Zlib",
"MIT"
] | null | null | null | controller.cpp | dridk/tankfighter | 2a4f9e72b524bb991ad1d5c665890845d4e288ba | [
"Zlib",
"MIT"
] | 1 | 2019-04-17T14:54:20.000Z | 2019-04-17T14:54:20.000Z | #include "controller.h"
#include "missile.h"
#include <math.h>
#include "coretypes.h"
#include "engine.h"
#include "parameters.h"
using namespace sf;
Controller::Controller() {
player = NULL;
}
Controller::~Controller() {}
void Controller::reportMissileMovement(Missile *missile, MissileControllingData &mcd) {
double angle = missile->getAngle();
mcd.flags = MCD_Movement;
mcd.movement = Vector2d(cos(angle), sin(angle));
mcd.must_die = missile->usecGetLifetime() >= 1000*(Int64)parameters.maxMissileLifeDurationMS();
}
void Controller::setPlayer(Player *player0) {
player = player0;
}
Player *Controller::getPlayer(void) const {return player;}
bool LocalController::isConcerned(const sf::Event &e) const {
return false;
}
bool Controller::missileCreation(Missile *ml) {
return ml->getEngine()->canCreateMissile(ml->getOwner());
}
bool Controller::missileCollision(Missile *, Player *) {
return true;
}
void Controller::teleported(void) {
}
| 26.472222 | 96 | 0.741868 | dridk |
e97b04f1c26a1cac1113ce8c27355b665709f46c | 1,034 | cpp | C++ | Plugins/SkillEditor2D/Source/SkillEditor2D/Private/Editor/Preview/SkillEditorPreviewClient.cpp | UnderGround-orchestra-band/SuperRogue | 65a520ac6ccf859c5994e429ffe915e9ff6f1028 | [
"MIT"
] | 1 | 2021-12-18T13:50:51.000Z | 2021-12-18T13:50:51.000Z | Plugins/SkillEditor2D/Source/SkillEditor2D/Private/Editor/Preview/SkillEditorPreviewClient.cpp | UnderGround-orchestra-band/SuperRogue | 65a520ac6ccf859c5994e429ffe915e9ff6f1028 | [
"MIT"
] | 1 | 2021-11-30T08:09:46.000Z | 2021-11-30T08:09:46.000Z | Plugins/SkillEditor2D/Source/SkillEditor2D/Private/Editor/Preview/SkillEditorPreviewClient.cpp | UnderGround-orchestra-band/SuperRogue | 65a520ac6ccf859c5994e429ffe915e9ff6f1028 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "SkillEditorPreviewClient.h"
void SkillEditorPreviewClient::Draw(FViewport* InViewport, FCanvas* Canvas)
{
FEditorViewportClient::Draw(InViewport, Canvas);
}
void SkillEditorPreviewClient::Tick(float DeltaSeconds)
{
FEditorViewportClient::Tick(DeltaSeconds);
if(DeltaSeconds>0.f)
{
PreviewScene->GetWorld()->Tick(LEVELTICK_All,DeltaSeconds);
}
}
UWorld* SkillEditorPreviewClient::GetWorld() const
{
if(PreviewScene!=nullptr)
return PreviewScene->GetWorld();
return GWorld;
}
SkillEditorPreviewClient::SkillEditorPreviewClient(FEditorModeTools* InModeTools,
FPreviewScene* InPreviewScene,
const TWeakPtr<SEditorViewport>& InEditorViewportWidget ):
FEditorViewportClient(InModeTools,InPreviewScene,InEditorViewportWidget)
{
SetViewLocation(FVector(100,100,100));
}
SkillEditorPreviewClient::~SkillEditorPreviewClient()
{
}
| 25.85 | 109 | 0.727273 | UnderGround-orchestra-band |
e97c1d5791d125eafba685fcb4c2e3545ff12396 | 5,365 | cpp | C++ | cert/gen_rsa_and_cert.cpp | alecmus/lecnet | a520e60ce1c407dbe3507117946692f2b98f3600 | [
"MIT"
] | 5 | 2020-03-13T16:20:28.000Z | 2020-03-18T16:54:17.000Z | cert/gen_rsa_and_cert.cpp | alecmus/lecnet | a520e60ce1c407dbe3507117946692f2b98f3600 | [
"MIT"
] | 2 | 2020-04-24T15:49:12.000Z | 2020-04-24T15:50:16.000Z | cert/gen_rsa_and_cert.cpp | alecmus/lecnet | a520e60ce1c407dbe3507117946692f2b98f3600 | [
"MIT"
] | 2 | 2021-05-20T00:37:27.000Z | 2021-06-24T21:05:41.000Z | //
// gen_rsa_and_cert.cpp - generate rsa and certificate implementation
//
// lecnet network library, part of the liblec library
// Copyright (c) 2018 Alec Musasa (alecmus at live dot com)
//
// Released under the MIT license. For full details see the
// file LICENSE.txt
//
#include "../cert.h"
#include "openssl_helper/openssl_helper.h"
// openssl includes
#include <openssl/ssl.h>
#include <openssl/err.h>
#define SERIAL_RAND_BITS 64
/*
** workaround for the
** #define in wincrypt.h
*/
#undef X509_NAME
/* Generates a self-signed x509 certificate. */
X509* generate_x509(EVP_PKEY* pkey,
int days,
const char* ccCountry,
const char* ccIssuer,
std::string & error)
{
/* Allocate memory for the X509 structure. */
X509* x509 = X509_new();
if (!x509)
{
error = "Unable to create X509 structure";
std::string _error = openssl_error();
if (_error.empty())
error += ".";
else
error += ": " + _error;
return NULL;
}
// generate random serial number
ASN1_INTEGER* serialNo = ASN1_INTEGER_new();
if (!serialNo || !rand_serial(NULL, serialNo))
{
error = "Unable to generate random serial number";
std::string _error = openssl_error();
if (!_error.empty())
error += ": " + _error;
return NULL;
}
/* Set the serial number. */
if (!X509_set_serialNumber(x509, serialNo))
{
error = "Unable to set serial number to certificate";
ASN1_INTEGER_free(serialNo);
return NULL;
}
ASN1_INTEGER_free(serialNo);
/* This certificate is valid from now until exactly one year from now. */
X509_gmtime_adj(X509_get_notBefore(x509), 0);
X509_gmtime_adj(X509_get_notAfter(x509), (long)60 * 60 * 24 * days);
/* Set the public key for our certificate. */
X509_set_pubkey(x509, pkey);
/* We want to copy the subject name to the issuer name. */
X509_NAME* name = X509_get_subject_name(x509);
/* Set the country code and common name. */
X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned char*)ccCountry, -1, -1, 0);
X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char*)ccIssuer, -1, -1, 0);
/* Now set the issuer name. */
X509_set_issuer_name(x509, name);
/* Actually sign the certificate with our key. */
if (!X509_sign(x509, pkey, EVP_sha1()))
{
error = "Error signing certificate";
std::string _error = openssl_error();
if (_error.empty())
error += ".";
else
error += ": " + _error;
X509_free(x509);
return NULL;
}
return x509;
}
bool write_to_disk(EVP_PKEY* pkey,
const char* ccPrivateKeyName,
const char* ccPrivateKeyPassword,
X509* x509,
const char* ccCertName,
std::string& error)
{
/* Open the PEM file for writing the certificate to disk. */
BIO* x509_file = NULL;
x509_file = BIO_new(BIO_s_file());
if (x509_file == NULL)
{
error = "Unable to open PEM certificate file for writing";
std::string _error = openssl_error();
if (!_error.empty())
error += ": " + _error;
BIO_free_all(x509_file);
return false;
}
else
{
if (BIO_write_filename(x509_file, (char*)ccCertName) <= 0)
{
error = "Unable to open PEM certificate file for writing";
std::string _error = openssl_error();
if (!_error.empty())
error += ": " + _error;
BIO_free_all(x509_file);
return false;
}
}
/* Write the certificate to disk. */
if (!PEM_write_bio_X509(x509_file, x509))
{
error = "Unable to write certificate to disk";
std::string _error = openssl_error();
if (!_error.empty())
error += ": " + _error;
BIO_free_all(x509_file);
return false;
}
/* Open the PEM file for writing the key to disk. */
BIO* pkey_file = NULL;
if (strcmp(ccPrivateKeyName, ccCertName))
pkey_file = BIO_new_file(ccPrivateKeyName, "wb");
else
pkey_file = BIO_new_file(ccPrivateKeyName, "ab");
if (!pkey_file)
{
error = "Unable to open PEM key file for writing.";
std::string _error = openssl_error();
if (!_error.empty())
error += ": " + _error;
BIO_free_all(x509_file);
BIO_free_all(pkey_file);
return false;
}
int ret = 0;
/* Write the key to disk. */
if (strlen(ccPrivateKeyPassword) > 0)
{
// DES-EDE3-CBC
ret = PEM_write_bio_PrivateKey(pkey_file, pkey, EVP_des_ede3_cbc(),
(unsigned char*)ccPrivateKeyPassword, (int)strlen(ccPrivateKeyPassword), NULL, NULL);
}
else
ret = PEM_write_bio_PrivateKey(pkey_file, pkey, NULL, NULL, 0, NULL, NULL);
if (!ret)
{
error = "Unable to write private key to disk";
std::string _error = openssl_error();
if (!_error.empty())
error += ": " + _error;
BIO_free_all(x509_file);
BIO_free_all(pkey_file);
return false;
}
BIO_free_all(x509_file);
BIO_free_all(pkey_file);
return true;
}
bool liblec::lecnet::cert::gen_rsa_and_cert(const private_key& key,
const certificate& cert,
std::string& error)
{
error.clear();
// Initialize OpenSSL
init_openssl();
// Generate the key.
EVP_PKEY* pkey = generate_key(key.bits, error);
if (!pkey)
return false;
// Generate the certificate.
X509* x509 = generate_x509(pkey,
cert.days, cert.country.c_str(), cert.issuer.c_str(), error);
if (!x509)
{
EVP_PKEY_free(pkey);
return false;
}
// Write the private key and certificate out to disk.
bool ret = write_to_disk(pkey,
key.file_name.c_str(), key.password.c_str(), x509, cert.file_name.c_str(), error);
EVP_PKEY_free(pkey);
X509_free(x509);
if (ret)
return true;
else
return false;
}
| 21.039216 | 91 | 0.680895 | alecmus |
e97de411487d43c4efb38f9363180d927d70a36b | 1,949 | cpp | C++ | MainWindow.cpp | LaudateCorpus1/QtEntropyGraph | 71b1b42286c3ee0ad063961f49f335e5b905144e | [
"MIT"
] | 3 | 2015-12-11T01:48:53.000Z | 2016-03-28T14:00:45.000Z | MainWindow.cpp | x64dbg/QtEntropyGraph | 71b1b42286c3ee0ad063961f49f335e5b905144e | [
"MIT"
] | 1 | 2021-10-15T08:43:22.000Z | 2021-10-15T08:43:22.000Z | MainWindow.cpp | LaudateCorpus1/QtEntropyGraph | 71b1b42286c3ee0ad063961f49f335e5b905144e | [
"MIT"
] | 3 | 2015-08-06T13:39:48.000Z | 2021-10-15T08:41:25.000Z | #include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QGraphicsItem>
#include <QFile>
#include "Entropy.h"
MainWindow::MainWindow(QWidget* parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
_initialized = false;
}
void MainWindow::initializeGraph()
{
if(_initialized)
return;
_initialized = true;
ui->entropyView->InitializeGraph();
}
MainWindow::~MainWindow()
{
delete ui;
}
static QColor randomColor()
{
return QColor(rand() % 256, rand() % 256, rand() % 256);
}
void MainWindow::nextColor()
{
ui->editColor->setText(randomColor().name());
}
static double fRand(double fMin = 0, double fMax = 1)
{
double f = (double)rand() / RAND_MAX;
return fMin + f * (fMax - fMin);
}
void MainWindow::on_btnRandomGraph_clicked()
{
initializeGraph();
std::vector<double> points;
int pointCount = ui->editPointCount->text().toInt();
for(int i = 0; i < pointCount; i++)
points.push_back(fRand(fRand(), fRand()));
points[0] = 0;
points[points.size() - 1] = 1;
ui->entropyView->AddGraph(points, QColor(ui->editColor->text()));
nextColor();
}
void MainWindow::on_btnGraphEntropy_clicked()
{
initializeGraph();
int blockSize = ui->editBlockSize->text().toInt();
int pointCount = ui->editPointCount->text().toInt();
ui->entropyView->GraphFile(ui->editPath->text(), blockSize, pointCount, QColor(ui->editColor->text()));
nextColor();
}
void MainWindow::on_btnClear_clicked()
{
_initialized = false;
initializeGraph();
}
void MainWindow::on_sliderBlockSize_sliderMoved(int position)
{
ui->editBlockSize->setText(QString("%1").arg(position));
on_btnClear_clicked();
on_btnGraphEntropy_clicked();
}
void MainWindow::on_sliderPointCount_sliderMoved(int position)
{
ui->editPointCount->setText(QString("%1").arg(position));
on_btnClear_clicked();
on_btnGraphEntropy_clicked();
}
| 21.655556 | 107 | 0.671113 | LaudateCorpus1 |
e97e242c15b3b9cc5ec0a0027dd2eca45893abb7 | 17,718 | cpp | C++ | Overdrive/render/shaderprogram.cpp | png85/Overdrive | e763827546354c7c75395ab1a82949a685ecb880 | [
"MIT"
] | 41 | 2015-02-21T08:54:00.000Z | 2021-05-11T16:01:29.000Z | Overdrive/render/shaderprogram.cpp | png85/Overdrive | e763827546354c7c75395ab1a82949a685ecb880 | [
"MIT"
] | 1 | 2018-05-14T10:02:09.000Z | 2018-05-14T10:02:09.000Z | Overdrive/render/shaderprogram.cpp | png85/Overdrive | e763827546354c7c75395ab1a82949a685ecb880 | [
"MIT"
] | 10 | 2015-10-07T05:44:08.000Z | 2020-12-01T09:00:01.000Z | #include "stdafx.h"
#include "shaderprogram.h"
#include "shaderAttribute.h"
#include "shaderUniform.h"
#include "../core/logger.h"
#include <fstream>
namespace overdrive {
namespace render {
namespace {
int getShaderIndex(eShaderType type) {
switch (type) {
case eShaderType::VERTEX: return 0;
case eShaderType::FRAGMENT: return 1;
case eShaderType::GEOMETRY: return 2;
case eShaderType::TESSELATION_CONTROL: return 3;
case eShaderType::TESSELATION_EVAL: return 4;
case eShaderType::COMPUTE: return 5;
default:
throw ShaderException("Unsupported shader type");
}
}
}
ShaderProgram::ShaderProgram():
mHandle(0),
mIsLinked(false)
{
}
ShaderProgram::~ShaderProgram() {
if (mHandle) {
for (const auto& shader : mShaders)
if (shader)
glDetachShader(mHandle, shader->getHandle());
glDeleteProgram(mHandle);
}
}
GLuint ShaderProgram::getHandle() const {
return mHandle;
}
void ShaderProgram::attachShader(const std::string& source, eShaderType type) {
if (mHandle == 0) {
mHandle = glCreateProgram();
if (mHandle == 0) {
gLogError << "Failed to create shader program";
throw ShaderException("Failed to create shader program");
}
}
int idx = getShaderIndex(type);
if (mShaders[idx]) {
gLogWarning << "Duplicate shader type provided; overwriting previous shader";
glDetachShader(mHandle, mShaders[idx]->getHandle());
}
mShaders[idx] = std::make_unique<Shader>(type);
mShaders[idx]->compile(source);
glAttachShader(mHandle, mShaders[idx]->getHandle());
}
void ShaderProgram::loadShader(const boost::filesystem::path& p, eShaderType type) {
using namespace boost::filesystem;
if (!exists(p)) {
gLogError << "File not found: " << p;
throw ShaderException("File not found");
}
if (!is_regular_file(p)) {
gLogError << "Not a regular file: " << p;
throw ShaderException("Not a regular file");
}
std::ifstream ifs(p.c_str());
if (!ifs.good()) {
gLogError << "Could not open file: " << p;
throw ShaderException("Could not open file");
}
std::string content(
(std::istreambuf_iterator<char>(ifs)), // <~ Most Vexing Parse... hence the extra ()
std::istreambuf_iterator<char>()
);
attachShader(content, type);
}
void ShaderProgram::link() {
if (mIsLinked) {
gLogWarning << "Shader program already linked";
return;
}
if (mHandle == 0) {
gLogError << "No program handle available, cannot link";
return;
}
glLinkProgram(mHandle);
GLint result;
glGetProgramiv(mHandle, GL_LINK_STATUS, &result);
if (result == GL_FALSE) {
// something went wrong, extract and log the error message
GLint messageLength = 0;
glGetProgramiv(mHandle, GL_INFO_LOG_LENGTH, &messageLength);
if (messageLength > 0) {
auto message = std::make_unique<char[]>(messageLength);
GLsizei bytesWritten = 0;
glGetProgramInfoLog(
mHandle,
messageLength,
&bytesWritten,
message.get()
);
gLogError << message.get();
return;
}
}
mIsLinked = true;
#ifdef OVERDRIVE_DEBUG
validate();
#endif
gatherUniforms();
gatherAttributes();
}
bool ShaderProgram::isLinked() const {
return mIsLinked;
}
void ShaderProgram::validate() {
if (!isLinked()) {
gLogWarning << "Cannot validate a shader program that is not linked yet";
return;
}
glValidateProgram(mHandle);
GLint result;
glGetProgramiv(mHandle, GL_LINK_STATUS, &result);
if (result == GL_FALSE) {
// something went wrong, extract and log the error message
GLint messageLength = 0;
glGetProgramiv(
mHandle,
GL_INFO_LOG_LENGTH,
&messageLength
);
if (messageLength > 0) {
auto message = std::make_unique<char[]>(messageLength);
GLsizei bytesWritten = 0;
glGetProgramInfoLog(
mHandle,
messageLength,
&bytesWritten,
message.get()
);
gLogError << message.get();
}
}
}
void ShaderProgram::bind() {
assert(mHandle);
glUseProgram(mHandle);
}
void ShaderProgram::unbind() {
glUseProgram(0);
}
void ShaderProgram::listUniforms() const {
// [NOTE] perhaps sort the names alphabetically?
gLogDebug << " ---- Active Uniforms ---- ";
gLogDebug << "Number of uniforms: " << mUniforms.size();
unsigned int i = 0;
for (const auto& item : mUniforms)
gLog << i++ << ":\t" << item.first << " " << item.second;
gLogDebug << " ------------------------- ";
}
void ShaderProgram::listAttributes() const {
// [NOTE] perhapse sort the attributes alphabetically?
gLogDebug << " ---- Active Attributes ---- ";
gLogDebug << " Number of attributes: " << mAttributes.size();
unsigned int i = 0;
for (const auto& item : mAttributes)
gLog << i++ << ":\t" << item.second;
gLogDebug << " ------------------------- ";
}
Shader* ShaderProgram::getShader(eShaderType type) const {
return mShaders[getShaderIndex(type)].get();
}
/*
void ShaderProgram::bindAttributeLocation(GLuint id, const std::string& name) {
}
void ShaderProgram::bindFragDataLocation(GLuint id, const std::string& name) {
}
*/
GLint ShaderProgram::getUniformLocation(const std::string& name) const {
auto it = mUniforms.find(name);
if (it == mUniforms.end())
throw ShaderException(std::string("Cannot locate uniform: ") + name);
return it->second.mLocation;
}
const ShaderUniform& ShaderProgram::getUniformData(const std::string& name) const {
auto it = mUniforms.find(name);
if (it == mUniforms.end())
throw ShaderException(std::string("Cannot locate uniform: ") + name);
return it->second;
}
GLint ShaderProgram::getAttributeLocation(const std::string& name) const {
auto it = mAttributes.find(name);
if (it == mAttributes.end())
throw ShaderException(std::string("Cannot locate attribute: ") + name);
return it->second.getLocation();
}
const ShaderAttribute& ShaderProgram::getAttributeData(const std::string& name) const {
auto it = mAttributes.find(name);
if (it == mAttributes.end())
throw ShaderException(std::string("Cannot locate attribute: ") + name);
return it->second;
}
// http://docs.gl/gl4/glGetProgramInterface
// http://docs.gl/gl4/glGetProgramResource
void ShaderProgram::gatherUniforms() {
using std::pair;
using std::string;
typedef pair<string, ShaderUniform> UniformPair;
GLint numUniforms = 0;
glGetProgramInterfaceiv(mHandle, GL_UNIFORM, GL_ACTIVE_RESOURCES, &numUniforms);
// [NOTE] this must correspond to the constructor in ShaderUniform!
GLenum properties[] = {
GL_NAME_LENGTH,
GL_TYPE,
GL_LOCATION,
GL_ARRAY_SIZE,
GL_ARRAY_STRIDE,
GL_MATRIX_STRIDE,
GL_OFFSET,
GL_BLOCK_INDEX,
GL_ATOMIC_COUNTER_BUFFER_INDEX,
GL_IS_ROW_MAJOR,
GL_REFERENCED_BY_VERTEX_SHADER,
GL_REFERENCED_BY_FRAGMENT_SHADER,
GL_REFERENCED_BY_GEOMETRY_SHADER,
GL_REFERENCED_BY_TESS_CONTROL_SHADER,
GL_REFERENCED_BY_TESS_EVALUATION_SHADER,
GL_REFERENCED_BY_COMPUTE_SHADER
};
const size_t numProperties = sizeof(properties) / sizeof(properties[0]);
for (GLint i = 0; i < numUniforms; ++i) {
GLint results[numProperties];
glGetProgramResourceiv(
mHandle,
GL_UNIFORM,
i,
numProperties,
properties,
numProperties,
nullptr,
results
);
GLint nameLength = results[0];
std::unique_ptr<GLchar[]> uniformName(new GLchar[nameLength]);
glGetProgramResourceName(
mHandle,
GL_UNIFORM,
i,
nameLength,
nullptr,
uniformName.get()
);
mUniforms.insert(UniformPair(
uniformName.get(),
ShaderUniform(uniformName.get(), results)
));
}
}
// http://docs.gl/gl4/glGetProgramInterface
// http://docs.gl/gl4/glGetProgramResource
void ShaderProgram::gatherAttributes() {
using std::pair;
using std::string;
typedef pair<string, ShaderAttribute> AttributePair;
GLint numAttributes = 0;
glGetProgramInterfaceiv(mHandle, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &numAttributes);
// [NOTE] this must correspond to the constructor in ShaderAttribute!
GLenum properties[] = {
GL_NAME_LENGTH,
GL_TYPE,
GL_LOCATION,
GL_REFERENCED_BY_VERTEX_SHADER,
GL_REFERENCED_BY_FRAGMENT_SHADER,
GL_REFERENCED_BY_GEOMETRY_SHADER,
GL_REFERENCED_BY_TESS_CONTROL_SHADER,
GL_REFERENCED_BY_TESS_EVALUATION_SHADER,
GL_REFERENCED_BY_COMPUTE_SHADER,
GL_IS_PER_PATCH,
GL_LOCATION_COMPONENT
};
const size_t numProperties = sizeof(properties) / sizeof(properties[0]);
for (GLint i = 0; i < numAttributes; ++i) {
GLint results[numProperties];
glGetProgramResourceiv(
mHandle,
GL_PROGRAM_INPUT,
i,
numProperties,
properties,
numProperties,
nullptr,
results
);
GLint nameSize = results[0];
std::unique_ptr<GLchar[]> attributeName(new GLchar[nameSize]);
glGetProgramResourceName(
mHandle,
GL_PROGRAM_INPUT,
i,
nameSize,
nullptr,
attributeName.get()
);
mAttributes.insert(AttributePair(
attributeName.get(),
ShaderAttribute(attributeName.get(), results)
));
}
}
void ShaderProgram::setUniform(GLint location, GLfloat x) {
glUniform1f(location, x);
}
void ShaderProgram::setUniform(GLint location, GLfloat x, GLfloat y) {
glUniform2f(location, x, y);
}
void ShaderProgram::setUniform(GLint location, GLfloat x, GLfloat y, GLfloat z) {
glUniform3f(location, x, y, z);
}
void ShaderProgram::setUniform(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w) {
glUniform4f(location, x, y, z, w);
}
void ShaderProgram::setUniform(GLint location, const glm::vec2& v) {
glUniform2f(location, v.x, v.y);
}
void ShaderProgram::setUniform(GLint location, const glm::vec3& v) {
glUniform3f(location, v.x, v.y, v.z);
}
void ShaderProgram::setUniform(GLint location, const glm::vec4& v) {
glUniform4f(location, v.x, v.y, v.z, v.w);
}
void ShaderProgram::setUniform(GLint location, GLdouble x) {
glUniform1d(location, x);
}
void ShaderProgram::setUniform(GLint location, GLdouble x, GLdouble y) {
glUniform2d(location, x, y);
}
void ShaderProgram::setUniform(GLint location, GLdouble x, GLdouble y, GLdouble z) {
glUniform3d(location, x, y, z);
}
void ShaderProgram::setUniform(GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w) {
glUniform4d(location, x, y, z, w);
}
void ShaderProgram::setUniform(GLint location, const glm::dvec2& v) {
glUniform2d(location, v.x, v.y);
}
void ShaderProgram::setUniform(GLint location, const glm::dvec3& v) {
glUniform3d(location, v.x, v.y, v.z);
}
void ShaderProgram::setUniform(GLint location, const glm::dvec4& v) {
glUniform4d(location, v.x, v.y, v.z, v.w);
}
void ShaderProgram::setUniform(GLint location, GLint x) {
glUniform1i(location, x);
}
void ShaderProgram::setUniform(GLint location, GLint x, GLint y) {
glUniform2i(location, x, y);
}
void ShaderProgram::setUniform(GLint location, GLint x, GLint y, GLint z) {
glUniform3i(location, x, y, z);
}
void ShaderProgram::setUniform(GLint location, GLint x, GLint y, GLint z, GLint w) {
glUniform4i(location, x, y, z, w);
}
void ShaderProgram::setUniform(GLint location, const glm::ivec2& v) {
glUniform2i(location, v.x, v.y);
}
void ShaderProgram::setUniform(GLint location, const glm::ivec3& v) {
glUniform3i(location, v.x, v.y, v.z);
}
void ShaderProgram::setUniform(GLint location, const glm::ivec4& v) {
glUniform4i(location, v.x, v.y, v.z, v.w);
}
void ShaderProgram::setUniform(GLint location, GLuint x) {
glUniform1ui(location, x);
}
void ShaderProgram::setUniform(GLint location, GLuint x, GLuint y) {
glUniform2ui(location, x, y);
}
void ShaderProgram::setUniform(GLint location, GLuint x, GLuint y, GLuint z) {
glUniform3ui(location, x, y, z);
}
void ShaderProgram::setUniform(GLint location, GLuint x, GLuint y, GLuint z, GLuint w) {
glUniform4ui(location, x, y, z, w);
}
void ShaderProgram::setUniform(GLint location, const glm::uvec2& v) {
glUniform2ui(location, v.x, v.y);
}
void ShaderProgram::setUniform(GLint location, const glm::uvec3& v) {
glUniform3ui(location, v.x, v.y, v.z);
}
void ShaderProgram::setUniform(GLint location, const glm::uvec4& v) {
glUniform4ui(location, v.x, v.y, v.z, v.w);
}
void ShaderProgram::setUniform(GLint location, GLboolean x) {
glUniform1i(location, x);
}
void ShaderProgram::setUniform(GLint location, GLboolean x, GLboolean y) {
glUniform2i(location, x, y);
}
void ShaderProgram::setUniform(GLint location, GLboolean x, GLboolean y, GLboolean z) {
glUniform3i(location, x, y, z);
}
void ShaderProgram::setUniform(GLint location, GLboolean x, GLboolean y, GLboolean z, GLboolean w) {
glUniform4i(location, x, y, z, w);
}
void ShaderProgram::setUniform(GLint location, const glm::bvec2& v) {
glUniform2i(location, v.x, v.y);
}
void ShaderProgram::setUniform(GLint location, const glm::bvec3& v) {
glUniform3i(location, v.x, v.y, v.z);
}
void ShaderProgram::setUniform(GLint location, const glm::bvec4& v) {
glUniform4i(location, v.x, v.y, v.z, v.w);
}
void ShaderProgram::setUniform(GLint location, const glm::mat2& m) {
glUniformMatrix2fv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::mat3& m) {
glUniformMatrix3fv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::mat4& m) {
glUniformMatrix4fv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::mat2x3& m) {
glUniformMatrix2x3fv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::mat2x4& m) {
glUniformMatrix2x4fv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::mat3x2& m) {
glUniformMatrix3x2fv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::mat3x4& m) {
glUniformMatrix3x4fv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::mat4x2& m) {
glUniformMatrix4x2fv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::mat4x3& m) {
glUniformMatrix4x3fv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::dmat2& m) {
glUniformMatrix2dv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::dmat3& m) {
glUniformMatrix3dv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::dmat4& m) {
glUniformMatrix4dv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::dmat2x3& m) {
glUniformMatrix2x3dv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::dmat2x4& m) {
glUniformMatrix2x4dv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::dmat3x2& m) {
glUniformMatrix3x2dv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::dmat3x4& m) {
glUniformMatrix3x4dv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::dmat4x2& m) {
glUniformMatrix4x2dv(location, 1, GL_FALSE, &m[0][0]);
}
void ShaderProgram::setUniform(GLint location, const glm::dmat4x3& m) {
glUniformMatrix4x3dv(location, 1, GL_FALSE, &m[0][0]);
}
std::ostream& operator << (std::ostream& os, const ShaderProgram& program) {
os
<< "Shader program: "
<< program.getHandle()
<< "\n";
if (program.isLinked()) {
program.listAttributes();
program.listUniforms();
}
/*
auto vtx = program.getShader(eShaderType::VERTEX);
auto frag = program.getShader(eShaderType::FRAGMENT);
auto geom = program.getShader(eShaderType::GEOMETRY);
auto tess_ctrl = program.getShader(eShaderType::TESSELATION_CONTROL);
auto tess_eval = program.getShader(eShaderType::TESSELATION_EVAL);
auto compute = program.getShader(eShaderType::COMPUTE);
if (vtx)
os << "\nVertex shader:\n" << vtx->getSource();
if (frag)
os << "\nFragment shader:\n" << frag->getSource();
if (geom)
os << "\nGeometry shader:\n" << geom->getSource();
if (tess_ctrl)
os << "\nTesselation control:\n" << tess_ctrl->getSource();
if (tess_eval)
os << "\nTesselation evaluation:\n" << tess_eval->getSource();
if (compute)
os << "\nCompute shader:\n" << compute->getSource();
*/
return os;
}
}
}
| 26.968037 | 103 | 0.642454 | png85 |
e980b12a489a4e89883a9d7920f0541f45d6ff5d | 870 | cpp | C++ | src/breadboard/node_signature.cpp | Coolgamer0403/breadboard | 45537cea0d6cdee70ed91d86cc6114465c351325 | [
"Apache-2.0"
] | 138 | 2015-11-19T05:00:41.000Z | 2021-12-13T14:26:34.000Z | src/breadboard/node_signature.cpp | Coolgamer0403/breadboard | 45537cea0d6cdee70ed91d86cc6114465c351325 | [
"Apache-2.0"
] | 3 | 2015-11-20T01:25:44.000Z | 2019-09-21T11:45:12.000Z | src/breadboard/node_signature.cpp | Coolgamer0403/breadboard | 45537cea0d6cdee70ed91d86cc6114465c351325 | [
"Apache-2.0"
] | 27 | 2015-11-28T02:47:02.000Z | 2021-10-15T11:17:20.000Z | // Copyright 2015 Google 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 "breadboard/node_signature.h"
namespace breadboard {
BaseNode* NodeSignature::Constructor() const { return constructor_(); }
void NodeSignature::Destructor(BaseNode* base_node) const {
return destructor_(base_node);
}
} // namespace breadboard
| 33.461538 | 75 | 0.752874 | Coolgamer0403 |
e98355928269503f85125b2b2affb2ef3c9bbbcf | 2,137 | cc | C++ | tests/catch/unit/device/hipDeviceGetLimit.cc | neon60/HIP | 586165ebc281eb9461898a5b2abbc74595f5d97d | [
"MIT"
] | null | null | null | tests/catch/unit/device/hipDeviceGetLimit.cc | neon60/HIP | 586165ebc281eb9461898a5b2abbc74595f5d97d | [
"MIT"
] | null | null | null | tests/catch/unit/device/hipDeviceGetLimit.cc | neon60/HIP | 586165ebc281eb9461898a5b2abbc74595f5d97d | [
"MIT"
] | null | null | null | /*
Copyright (c) 2021-Present Advanced Micro Devices, Inc. All rights reserved.
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 WARRANNTY OF ANY KIND, EXPRESS OR
IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*
* Conformance test for checking functionality of
* hipError_t hipDeviceGetLimit(size_t* pValue, enum hipLimit_t limit);
*/
#include <hip_test_common.hh>
/**
* hipDeviceGetLimit tests
* Scenario1: Validates if pValue = nullptr returns hip error code.
* Scenario2: Validates if *pValue > 0 is returned for limit = hipLimitMallocHeapSize.
* Scenario3: Validates if error code is returned for limit = Invalid Flag = 0xff.
*/
TEST_CASE("Unit_hipDeviceGetLimit_NegTst") {
size_t Value = 0;
// Scenario1
SECTION("NULL check") {
REQUIRE_FALSE(hipDeviceGetLimit(nullptr, hipLimitMallocHeapSize)
== hipSuccess);
}
// Scenario3
SECTION("Invalid Input Flag") {
REQUIRE_FALSE(hipDeviceGetLimit(&Value, static_cast<hipLimit_t>(0xff)) ==
hipSuccess);
}
}
TEST_CASE("Unit_hipDeviceGetLimit_CheckValidityOfOutputVal") {
size_t Value = 0;
// Scenario2
REQUIRE(hipDeviceGetLimit(&Value, hipLimitMallocHeapSize) ==
hipSuccess);
REQUIRE_FALSE(Value <= 0);
}
| 41.096154 | 86 | 0.759008 | neon60 |
e984dc80cc35a62fdb73bb71feeca42ebae1a025 | 15,164 | cpp | C++ | Blizzlike/ArcEmu/C++/WorldPvPScripts/ZoneHellfirePeninsula.cpp | 499453466/Lua-Other | 43fd2b72405faf3f2074fd2a2706ef115d16faa6 | [
"Unlicense"
] | 2 | 2015-06-23T16:26:32.000Z | 2019-06-27T07:45:59.000Z | Blizzlike/ArcEmu/C++/WorldPvPScripts/ZoneHellfirePeninsula.cpp | Eduardo-Silla/Lua-Other | db610f946dbcaf81b3de9801f758e11a7bf2753f | [
"Unlicense"
] | null | null | null | Blizzlike/ArcEmu/C++/WorldPvPScripts/ZoneHellfirePeninsula.cpp | Eduardo-Silla/Lua-Other | db610f946dbcaf81b3de9801f758e11a7bf2753f | [
"Unlicense"
] | 3 | 2015-01-10T18:22:59.000Z | 2021-04-27T21:28:28.000Z | /**
* Summit MMORPG Server Software
* Copyright (c) 2008 Summit Server Team
* See COPYING for license details.
*/
#include "StdAfx.h"
// Some customizable defines.
// Maybe move these to config?
#define BANNER_RANGE 900
#define UPDATE_PERIOD 5000
#define CAPTURE_RATE 20
// Towers
enum Towers
{
TOWER_STADIUM,
TOWER_OVERLOOK,
TOWER_BROKENHILL,
TOWER_COUNT,
};
// Tower GameObject Ids
#define TOWER_WEST 182173
#define TOWER_NORTH 182174
#define TOWER_SOUTH 182175
// Buff Ids
#define HELLFIRE_SUPERORITY_ALLIANCE 32071
#define HELLFIRE_SUPERORITY_HORDE 32049
// Owners of the towers, used for save/restore
int32 g_towerOwners[TOWER_COUNT] = { -1, -1, -1 };
// global variables
uint32 g_hordeTowers = 0;
uint32 g_allianceTowers = 0;
int32 g_superiorTeam = -1; // SUPERIORITY
// Fields to update visual view of the client map
static const uint32 g_hordeStateFields[3] = { WORLDSTATE_HELLFIRE_STADIUM_HORDE, WORLDSTATE_HELLFIRE_OVERLOOK_HORDE, WORLDSTATE_HELLFIRE_BROKENHILL_HORDE };
static const uint32 g_allianceStateFields[3] = { WORLDSTATE_HELLFIRE_STADIUM_ALLIANCE, WORLDSTATE_HELLFIRE_OVERLOOK_ALLIANCE, WORLDSTATE_HELLFIRE_BROKENHILL_ALLIANCE };
static const uint32 g_neutralStateFields[3] = { WORLDSTATE_HELLFIRE_STADIUM_NEUTRAL, WORLDSTATE_HELLFIRE_OVERLOOK_NEUTRAL, WORLDSTATE_HELLFIRE_BROKENHILL_NEUTRAL };
// updates clients visual counter, and adds the buffs to players if needed
HEARTHSTONE_INLINE void UpdateTowerCount(shared_ptr<MapMgr> mgr)
{
if(!mgr)
return;
mgr->GetStateManager().UpdateWorldState(WORLDSTATE_HELLFIRE_ALLIANCE_TOWERS_CONTROLLED, g_allianceTowers);
mgr->GetStateManager().UpdateWorldState(WORLDSTATE_HELLFIRE_HORDE_TOWERS_CONTROLLED, g_hordeTowers);
if(g_superiorTeam == 0 && g_allianceTowers != 3)
{
mgr->RemovePositiveAuraFromPlayers(0, HELLFIRE_SUPERORITY_ALLIANCE);
g_superiorTeam = -1;
}
if(g_superiorTeam == 1 && g_hordeTowers != 3)
{
mgr->RemovePositiveAuraFromPlayers(1, HELLFIRE_SUPERORITY_HORDE);
g_superiorTeam = -1;
}
if(g_allianceTowers == 3 && g_superiorTeam != 0)
{
g_superiorTeam = 0;
mgr->CastSpellOnPlayers(0, HELLFIRE_SUPERORITY_ALLIANCE);
}
if(g_hordeTowers == 3 && g_superiorTeam != 1)
{
g_superiorTeam = 1;
mgr->CastSpellOnPlayers(1, HELLFIRE_SUPERORITY_HORDE);
}
}
enum BannerStatus
{
BANNER_STATUS_NEUTRAL = 0,
BANNER_STATUS_ALLIANCE = 1,
BANNER_STATUS_HORDE = 2,
};
class HellfirePeninsulaBannerAI : public GameObjectAIScript
{
map<uint32, uint32> StoredPlayers;
uint32 Status;
const char* ControlPointName;
uint32 towerid;
uint32 m_bannerStatus;
public:
GameObjectPointer pBanner;
HellfirePeninsulaBannerAI(GameObjectPointer go) : GameObjectAIScript(go)
{
m_bannerStatus = BANNER_STATUS_NEUTRAL;
Status = 50;
switch(go->GetEntry())
{
case TOWER_WEST:
ControlPointName = "The Stadium";
towerid = TOWER_STADIUM;
break;
case TOWER_NORTH:
ControlPointName = "The Overlook";
towerid = TOWER_OVERLOOK;
break;
case TOWER_SOUTH:
ControlPointName = "Broken Hill";
towerid = TOWER_BROKENHILL;
break;
default:
ControlPointName = "Unknown";
break;
}
}
void AIUpdate()
{
uint32 plrcounts[2] = { 0, 0 };
// details:
// loop through inrange players, for new ones, send the enable CP worldstate.
// the value of the map is a timestamp of the last update, to avoid cpu time wasted
// doing lookups of objects that have already been updated
unordered_set<PlayerPointer>::iterator itr = _gameobject->GetInRangePlayerSetBegin();
unordered_set<PlayerPointer>::iterator itrend = _gameobject->GetInRangePlayerSetEnd();
map<uint32, uint32>::iterator it2, it3;
uint32 timeptr = (uint32)UNIXTIME;
bool in_range;
bool is_valid;
PlayerPointer plr = NULLPLR;
for(; itr != itrend; ++itr)
{
if(!(*itr)->IsPvPFlagged() || (*itr)->InStealth())
is_valid = false;
else
is_valid = true;
in_range = (_gameobject->GetDistance2dSq((*itr)) <= BANNER_RANGE) ? true : false;
it2 = StoredPlayers.find((*itr)->GetLowGUID());
if(it2 == StoredPlayers.end())
{
// new player :)
if(in_range)
{
(*itr)->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_DISPLAY, 1);
(*itr)->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_VALUE, Status);
StoredPlayers.insert(make_pair((*itr)->GetLowGUID(), timeptr));
if(is_valid)
plrcounts[(*itr)->GetTeam()]++;
}
}
else
{
// oldie
if(!in_range)
{
(*itr)->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_DISPLAY, 0);
StoredPlayers.erase(it2);
}
else
{
(*itr)->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_VALUE, Status);
it2->second = timeptr;
if(is_valid)
plrcounts[(*itr)->GetTeam()]++;
}
}
}
// handle stuff for the last tick
if(Status == 100 && m_bannerStatus != BANNER_STATUS_ALLIANCE)
{
m_bannerStatus = BANNER_STATUS_ALLIANCE;
SetArtKit();
// send message to everyone in the zone, has been captured by the Alliance
_gameobject->GetMapMgr()->SendPvPCaptureMessage(ZONE_HELLFIRE_PENINSULA, ZONE_HELLFIRE_PENINSULA, "|cffffff00%s has been taken by the Alliance!|r", ControlPointName);
// tower update
g_allianceTowers++;
UpdateTowerCount(_gameobject->GetMapMgr());
// state update
_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 0);
_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_allianceStateFields[towerid], 1);
// woot
g_towerOwners[towerid] = 1;
UpdateInDB();
}
else if(Status == 0 && m_bannerStatus != BANNER_STATUS_HORDE)
{
m_bannerStatus = BANNER_STATUS_HORDE;
SetArtKit();
// send message to everyone in the zone, has been captured by the Horde
_gameobject->GetMapMgr()->SendPvPCaptureMessage(ZONE_HELLFIRE_PENINSULA, ZONE_HELLFIRE_PENINSULA, "|cffffff00%s has been taken by the Horde!|r", ControlPointName);
// tower update
g_hordeTowers++;
UpdateTowerCount(_gameobject->GetMapMgr());
// state update
_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 0);
_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_hordeStateFields[towerid], 1);
// woot
g_towerOwners[towerid] = 0;
UpdateInDB();
}
else if(m_bannerStatus != BANNER_STATUS_NEUTRAL)
{
// if the difference for the faction is >50, change to neutral
if(m_bannerStatus == BANNER_STATUS_ALLIANCE && Status <= 50)
{
// send message: The Alliance has lost control of point xxx
m_bannerStatus = BANNER_STATUS_NEUTRAL;
SetArtKit();
g_allianceTowers--;
UpdateTowerCount(_gameobject->GetMapMgr());
_gameobject->GetMapMgr()->SendPvPCaptureMessage(ZONE_HELLFIRE_PENINSULA, ZONE_HELLFIRE_PENINSULA, "|cffffff00The Alliance have lost control of %s!|r", ControlPointName);
// state update
_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_allianceStateFields[towerid], 0);
_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 1);
// woot
g_towerOwners[towerid] = -1;
UpdateInDB();
}
else if(m_bannerStatus == BANNER_STATUS_HORDE && Status >= 50)
{
// send message: The Alliance has lost control of point xxx
m_bannerStatus = BANNER_STATUS_NEUTRAL;
SetArtKit();
g_hordeTowers--;
UpdateTowerCount(_gameobject->GetMapMgr());
_gameobject->GetMapMgr()->SendPvPCaptureMessage(ZONE_HELLFIRE_PENINSULA, ZONE_HELLFIRE_PENINSULA, "|cffffff00The Horde have lost control of %s!|r", ControlPointName);
// state update
_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_hordeStateFields[towerid], 0);
_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 1);
// woot
g_towerOwners[towerid] = -1;
UpdateInDB();
}
}
// send any out of range players the disable flag
for(it2 = StoredPlayers.begin(); it2 != StoredPlayers.end();)
{
it3 = it2;
++it2;
if(it3->second != timeptr)
{
plr = _gameobject->GetMapMgr()->GetPlayer(it3->first);
// they WILL be out of range at this point. this is guaranteed. means they left the set rly quickly.
if(plr != NULL)
plr->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_DISPLAY, 0);
StoredPlayers.erase(it3);
}
}
// work out current status for next tick
uint32 delta;
if(plrcounts[0] > plrcounts[1])
{
delta = plrcounts[0] - plrcounts[1];
delta *= CAPTURE_RATE;
// cap it at 25 so the banner always gets removed.
if(delta > 25)
delta = 25;
Status += delta;
if(Status >= 100)
Status = 100;
}
else if(plrcounts[1] > plrcounts[0])
{
delta = plrcounts[1] - plrcounts[0];
delta *= CAPTURE_RATE;
// cap it at 25 so the banner always gets removed.
if(delta > 25)
delta = 25;
if(delta > Status)
Status = 0;
else
Status -= delta;
}
}
void SetArtKit()
{
// big towers
static const uint32 artkits_towers[3][3] =
{
{ 69, 67, 68 }, { 63, 62, 61 }, { 66, 65, 64 },
};
// flag poles
static const uint32 artkits_flagpole[3] = { 3, 2, 1 };
// set away - we don't know the artkits anymore :(((
//_gameobject->SetUInt32Value(GAMEOBJECT_ARTKIT, artkits_flagpole[m_bannerStatus]);
//pBanner->SetUInt32Value(GAMEOBJECT_ARTKIT, artkits_towers[towerid][m_bannerStatus]);
}
void OnSpawn()
{
m_bannerStatus = BANNER_STATUS_NEUTRAL;
// preloaded data, do we have any?
if(g_towerOwners[towerid] == 1)
{
m_bannerStatus = BANNER_STATUS_HORDE;
Status = 0;
// state update
_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_hordeStateFields[towerid], 1);
_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 0);
// countz
g_hordeTowers++;
UpdateTowerCount(_gameobject->GetMapMgr());
SetArtKit();
}
else if(g_towerOwners[towerid] == 0)
{
m_bannerStatus = BANNER_STATUS_ALLIANCE;
Status = 100;
// state update
_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_allianceStateFields[towerid], 1);
_gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 0);
// countz
g_allianceTowers++;
UpdateTowerCount(_gameobject->GetMapMgr());
SetArtKit();
}
// start the event timer
RegisterAIUpdateEvent(UPDATE_PERIOD);
}
//////////////////////////////////////////////////////////////////////////
// Save Data To DB
//////////////////////////////////////////////////////////////////////////
void UpdateInDB()
{
static const char* fieldnames[TOWER_COUNT] = { "hellfire-stadium-status", "hellfire-overlook-status", "hellfire-brokenhill-status" };
const char* msg = "-1";
if(Status == 100)
msg = "0";
else
msg = "1";
WorldStateManager::SetPersistantSetting(fieldnames[towerid], msg);
}
};
//////////////////////////////////////////////////////////////////////////
// Zone Hook
//////////////////////////////////////////////////////////////////////////
void ZoneHook(PlayerPointer plr, uint32 Zone, uint32 OldZone)
{
static uint32 spellids[2] = { HELLFIRE_SUPERORITY_ALLIANCE, HELLFIRE_SUPERORITY_HORDE };
if(Zone == ZONE_HELLFIRE_PENINSULA)
{
if(g_superiorTeam == plr->GetTeam())
plr->CastSpell(plr, dbcSpell.LookupEntry(spellids[plr->GetTeam()]), true);
}
else if(OldZone == ZONE_HELLFIRE_PENINSULA)
{
if(g_superiorTeam == plr->GetTeam())
plr->RemovePositiveAura(spellids[plr->GetTeam()]);
}
}
//////////////////////////////////////////////////////////////////////////
// Object Spawn Data
//////////////////////////////////////////////////////////////////////////
struct sgodata
{
uint32 entry;
float posx;
float posy;
float posz;
float facing;
float orientation[4];
uint32 state;
uint32 flags;
uint32 faction;
float scale;
uint32 is_banner;
};
void SpawnObjects(shared_ptr<MapMgr> pmgr)
{
if(!pmgr || pmgr->GetMapId() != 530)
return;
const static sgodata godata[] =
{
{ 182173, -290.016f, 3702.42f, 56.6729f, 0.0349066f, 0, 0, 0.0174524f, 0.999848f, 1, 32, 0, 1 }, // stadium
{ 182174, -184.889f, 3476.93f, 38.205f, -0.0174535f, 0, 0, 0.00872664f, -0.999962f, 1, 32, 0, 1 }, // overlook
{ 182175, -471.462f, 3451.09f, 34.6432f, 0.174533f, 0, 0, 0.0871557f, 0.996195f, 1, 32, 0, 1 }, // brokenhill
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
};
const static sgodata godata_banner[] =
{
{ 183515, -289.61f, 3696.83f, 75.9447f, 3.12414f, 0, 0, 0.999962f, 0.00872656f, 1, 32, 1375, 1 }, // stadium
{ 182525, -187.887f, 3459.38f, 60.0403f, -3.12414f, 0, 0, 0.999962f, -0.00872653f, 1, 32, 1375, 1 }, // overlook
{ 183514, -467.078f, 3528.17f, 64.7121f, 3.14159f, 0, 0, 1, -4.37114E-8f, 1, 32, 1375, 1 }, // brokenhill
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
};
uint32 i;
const sgodata* p, *p2;
for(i = 0; i < 3; ++i)
{
p = &godata[i];
p2 = &godata_banner[i];
GameObjectPointer pGo = pmgr->GetInterface()->SpawnGameObject(p->entry, p->posx, p->posy, p->posz, p->facing, false, 0, 0);
if(pGo == NULL)
continue;
GameObjectPointer pGo2 = pmgr->GetInterface()->SpawnGameObject(p2->entry, p2->posx, p2->posy, p2->posz, p2->facing, false, 0, 0);
if(pGo2 == NULL)
continue;
pGo->SetByte(GAMEOBJECT_BYTES_1, GAMEOBJECT_BYTES_STATE, p->state);
pGo2->SetByte(GAMEOBJECT_BYTES_1, GAMEOBJECT_BYTES_STATE, p2->state);
pGo->SetUInt32Value(GAMEOBJECT_FLAGS, p->flags);
pGo2->SetUInt32Value(GAMEOBJECT_FLAGS, p2->flags);
pGo->SetUInt32Value(GAMEOBJECT_FACTION, p->faction);
pGo2->SetUInt32Value(GAMEOBJECT_FACTION, p2->faction);
for(uint32 j = 0; j < 4; ++j)
{
pGo->SetFloatValue(GAMEOBJECT_ROTATION + j, p->orientation[j]);
pGo2->SetFloatValue(GAMEOBJECT_ROTATION + j, p2->orientation[j]);
}
// now make his script
pGo->SetScript(new HellfirePeninsulaBannerAI(pGo));
((HellfirePeninsulaBannerAI*)pGo->GetScript())->pBanner = pGo2;
pGo->PushToWorld(pmgr);
pGo2->PushToWorld(pmgr);
pGo->GetScript()->OnSpawn();
printf("Spawned gameobject entry %u for world pvp on hellfire.\n", p->entry);
}
}
void SetupPvPHellfirePeninsula(ScriptMgr* mgr)
{
// register instance hooker
mgr->register_hook(SERVER_HOOK_EVENT_ON_ZONE, (void*)&ZoneHook);
mgr->register_hook(SERVER_HOOK_EVENT_ON_CONTINENT_CREATE, (void*)&SpawnObjects);
// load data
const string tstadium = WorldStateManager::GetPersistantSetting("hellfire-stadium-status", "-1");
const string toverlook = WorldStateManager::GetPersistantSetting("hellfire-overlook-status", "-1");
const string tbrokenhill = WorldStateManager::GetPersistantSetting("hellfire-brokenhill-status", "-1");
g_towerOwners[TOWER_STADIUM] = atoi(tstadium.c_str());
g_towerOwners[TOWER_OVERLOOK] = atoi(toverlook.c_str());
g_towerOwners[TOWER_BROKENHILL] = atoi(tbrokenhill.c_str());
}
| 30.027723 | 174 | 0.672975 | 499453466 |
e985dab5ed0bb48e420189b274a354d982507df7 | 3,477 | hpp | C++ | src/entry_node.hpp | BrightTux/model_server | cdbeb464c78b161e5706490fc18b0a8cf16138fb | [
"Apache-2.0"
] | 234 | 2020-04-24T22:09:49.000Z | 2022-03-30T10:40:04.000Z | src/entry_node.hpp | BrightTux/model_server | cdbeb464c78b161e5706490fc18b0a8cf16138fb | [
"Apache-2.0"
] | 199 | 2020-04-29T08:43:21.000Z | 2022-03-29T09:05:52.000Z | src/entry_node.hpp | BrightTux/model_server | cdbeb464c78b161e5706490fc18b0a8cf16138fb | [
"Apache-2.0"
] | 80 | 2020-04-29T14:54:41.000Z | 2022-03-30T14:50:29.000Z | //*****************************************************************************
// Copyright 2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <memory>
#include <optional>
#include <string>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
#include "tensorflow_serving/apis/prediction_service.grpc.pb.h"
#pragma GCC diagnostic pop
#include "logging.hpp"
#include "node.hpp"
#include "tensorinfo.hpp"
namespace ovms {
const std::string ENTRY_NODE_NAME = "request";
class EntryNode : public Node {
const tensorflow::serving::PredictRequest* request;
const tensor_map_t inputsInfo;
public:
EntryNode(const tensorflow::serving::PredictRequest* request,
const tensor_map_t& inputsInfo,
std::optional<uint32_t> demultiplyCount = std::nullopt) :
Node(ENTRY_NODE_NAME, demultiplyCount),
request(request),
inputsInfo(inputsInfo) {}
Status execute(session_key_t sessionId, PipelineEventQueue& notifyEndQueue) override;
Status fetchResults(NodeSession& nodeSession, SessionResults& nodeSessionOutputs) override;
protected:
Status fetchResults(BlobMap& outputs);
Status createShardedBlob(InferenceEngine::Blob::Ptr& dividedBlob, const InferenceEngine::TensorDesc& dividedBlobDesc, InferenceEngine::Blob::Ptr blob, size_t i, size_t step, const NodeSessionMetadata& metadata, const std::string blobName) override;
public:
// Entry nodes have no dependency
void addDependency(Node&, const Aliases&) override {
throw std::logic_error("This node cannot have dependency");
}
Status isInputBinary(const std::string& name, bool& isBinary) const;
const Status validateNumberOfInputs(const tensorflow::serving::PredictRequest* request,
const size_t expectedNumberOfInputs);
const Status checkIfShapeValuesNegative(const tensorflow::TensorProto& requestInput);
const Status validateNumberOfBinaryInputShapeDimensions(const tensorflow::TensorProto& requestInput);
const bool checkBinaryInputBatchSizeMismatch(const ovms::TensorInfo& networkInput,
const tensorflow::TensorProto& requestInput);
const Status validatePrecision(const ovms::TensorInfo& networkInput,
const tensorflow::TensorProto& requestInput);
const Status validateNumberOfShapeDimensions(const ovms::TensorInfo& networkInput,
const tensorflow::TensorProto& requestInput);
const bool checkBatchSizeMismatch(const ovms::TensorInfo& networkInput,
const tensorflow::TensorProto& requestInput);
const bool checkShapeMismatch(const ovms::TensorInfo& networkInput,
const tensorflow::TensorProto& requestInput);
const Status validateTensorContentSize(const ovms::TensorInfo& networkInput,
const tensorflow::TensorProto& requestInput);
const Status validate();
};
} // namespace ovms
| 38.208791 | 252 | 0.724475 | BrightTux |
e985df3717495afbf993ed59fe2ec49ffdcd2273 | 1,542 | cpp | C++ | test/gcc/harden.cpp | triton/cc-wrapper | 4be147e091897efc080691567034127dfafd75b9 | [
"Apache-2.0"
] | 1 | 2018-09-27T05:08:35.000Z | 2018-09-27T05:08:35.000Z | test/gcc/harden.cpp | triton/cc-wrapper | 4be147e091897efc080691567034127dfafd75b9 | [
"Apache-2.0"
] | null | null | null | test/gcc/harden.cpp | triton/cc-wrapper | 4be147e091897efc080691567034127dfafd75b9 | [
"Apache-2.0"
] | 3 | 2017-12-24T22:07:05.000Z | 2020-11-26T01:20:16.000Z | #include <catch2/catch.hpp>
#include <gcc/harden.hpp>
namespace cc_wrapper {
namespace gcc {
namespace harden {
TEST_CASE("Enabled flags", "[isValidFlag]") {
Env env;
env.position_independent = true;
env.optimize = true;
CHECK(isValidFlag("-Wl,-rpath", env));
CHECK(isValidFlag("-c", env));
CHECK(isValidFlag("-o", env));
CHECK(isValidFlag("main.o", env));
CHECK(!isValidFlag("-fPIC", env));
CHECK(!isValidFlag("-fpic", env));
CHECK(!isValidFlag("-fPIE", env));
CHECK(!isValidFlag("-no-pie", env));
CHECK(!isValidFlag("-pie", env));
CHECK(!isValidFlag("-O0", env));
CHECK(!isValidFlag("-Ofast", env));
CHECK(!isValidFlag("-Os", env));
CHECK(isValidFlag("-O3", env));
CHECK(!isValidFlag("-march=native", env));
CHECK(!isValidFlag("-mtune=native", env));
}
TEST_CASE("Disabled Flags", "[isValidFlag]") {
Env env;
env.position_independent = false;
env.optimize = false;
CHECK(isValidFlag("-Wl,-rpath", env));
CHECK(isValidFlag("-c", env));
CHECK(isValidFlag("-o", env));
CHECK(isValidFlag("main.o", env));
CHECK(isValidFlag("-fPIC", env));
CHECK(isValidFlag("-fpic", env));
CHECK(isValidFlag("-fPIE", env));
CHECK(isValidFlag("-no-pie", env));
CHECK(isValidFlag("-pie", env));
CHECK(isValidFlag("-O0", env));
CHECK(isValidFlag("-Ofast", env));
CHECK(isValidFlag("-Os", env));
CHECK(isValidFlag("-O3", env));
CHECK(!isValidFlag("-march=native", env));
CHECK(!isValidFlag("-mtune=native", env));
}
} // namespace harden
} // namespace gcc
} // namespace cc_wrapper
| 27.535714 | 46 | 0.64786 | triton |
e986ad7b854127019cf155b41e9197d3c7668e30 | 102,076 | cpp | C++ | core/sql/executor/cluster.cpp | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 148 | 2015-06-18T21:26:04.000Z | 2017-12-25T01:47:01.000Z | core/sql/executor/cluster.cpp | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 1,352 | 2015-06-20T03:05:01.000Z | 2017-12-25T14:13:18.000Z | core/sql/executor/cluster.cpp | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 166 | 2015-06-19T18:52:10.000Z | 2017-12-27T06:19:32.000Z | /**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
/* -*-C++-*-
******************************************************************************
*
* File: cluster.C
* Description: Methods for Cluster and Buckets of a hash join
*
*
*
* Created: 08/14/96
* Language: C++
*
*
*
*
******************************************************************************
*/
// begining of regular compilation
#include "cluster.h"
#include "memorymonitor.h"
#include "ExStats.h"
#include "ComResourceInfo.h"
#include "logmxevent.h"
#include "SortError.h"
HashBufferHeader::HashBufferHeader()
: rowCount_(0),
bucketCount_(0)
{
};
/////////////////////////////////////////////////////////////////////////////
HashBuffer::HashBuffer (Cluster * cluster)
: cluster_(NULL),
bufferSize_(0),
maxRowLength_(0),
rows_(NULL),
maxNumFullRowsSer_(0),
freeSpace_(0),
currRow_(NULL),
nextAvailRow_(NULL),
next_(NULL),
prev_(NULL),
heap_(NULL),
data_(NULL)
{
ClusterDB * clusterDb = cluster->clusterDb_;
bufferSize_ = clusterDb->bufferSize_;
data_ = (char *)clusterDb->bufferHeap_->allocateAlignedHeapMemory((UInt32)bufferSize_, 512, FALSE);
if ( !data_ ) return; // memory allocation failed
// adjust memory usage statistics
clusterDb->availableMemory_ -= bufferSize_;
clusterDb->memoryUsed_ += bufferSize_;
if ( clusterDb->hashOperStats_ ) clusterDb->updateMemoryStats();
// if we did not see pressure yet, the maximum cluster
// size is as big as the total memory used
if ( clusterDb->memMonitor_ && !clusterDb->sawPressure_ )
clusterDb->maxClusterSize_ = clusterDb->memoryUsed_;
// initialize this buffer
init(cluster);
if (clusterDb->bmoStats_)
clusterDb->bmoStats_->updateBMOHeapUsage((NAHeap *)clusterDb->collHeap());
};
// A constructor for cases when the HashBuffer is used without a
// Cluster object.
// Currently, this is only used by the UniqueHashJoin (ExUniqueHashJoinTcb).
//
HashBuffer::HashBuffer(ULng32 bufferSize,
ULng32 rowSize,
NABoolean useVariableLength,
CollHeap *heap,
ClusterDB * clusterDb,
ExeErrorCode * rc)
: cluster_(NULL),
bufferSize_(bufferSize),
maxRowLength_(rowSize),
isVariableLength_(useVariableLength),
rows_(NULL),
maxNumFullRowsSer_(0),
freeSpace_(0),
currRow_(NULL),
nextAvailRow_(NULL),
next_(NULL),
prev_(NULL),
heap_(heap),
data_(NULL)
{
// assume success
*rc = EXE_OK;
data_ = (char *)((NAHeap *)heap)->allocateAlignedHeapMemory((UInt32)bufferSize, 512, FALSE);
if (!data_) {
*rc = EXE_NO_MEM_TO_EXEC;
return;
};
if ( clusterDb ) {
// adjust memory usage statistics
clusterDb->availableMemory_ -= bufferSize;
clusterDb->memoryUsed_ += bufferSize;
if ( clusterDb->hashOperStats_ ) clusterDb->updateMemoryStats();
if (clusterDb->bmoStats_)
clusterDb->bmoStats_->updateBMOHeapUsage((NAHeap *)clusterDb->collHeap());
}
// initialize this buffer
// Make sure that all rows in buffer are aligned.
//
maxRowLength_ = ROUND4(rowSize);
if(maxRowLength_ < sizeof(HashRow) + sizeof(UInt32)) {
isVariableLength_ = false;
}
// first row starts after the buffer header
rows_ = data_ + ROUND8(sizeof(HashBufferHeader));
nextAvailRow_ = rows_;
// The number of allocated rows from this buffer.
header_->setRowCount(0);
// Determine the number of rows that can be allocated from this buffer.
//
maxNumFullRowsSer_ = ((bufferSize_ - ROUND8(sizeof(HashBufferHeader)) - 8 )
/ maxRowLength_);
freeSpace_ = bufferSize_ - ROUND8(sizeof(HashBufferHeader)) -8;
};
HashBufferSerial::HashBufferSerial (Cluster * cluster)
: HashBuffer(cluster)
{};
// A constructor for cases when the HashBuffer is used without a
// Cluster object.
// Currently, this is only used by the UniqueHashJoin (ExUniqueHashJoinTcb).
//
/*
HashBufferSerial::HashBufferSerial(ULng32 bufferSize,
ULng32 rowSize,
NABoolean useVariableLength,
CollHeap *heap,
ExeErrorCode * rc)
: HashBuffer(bufferSize, rowSize, useVariableLength, heap, rc)
{};
*/
/////////////////////////////////////////////////////////////////////////////
void HashBuffer::init(Cluster * cluster) {
cluster_ = cluster;
maxRowLength_ = ROUND4(cluster->rowLength_);
bufferSize_ = cluster_->clusterDb_->bufferSize_;
isVariableLength_ = cluster->useVariableLength_;
considerBufferDefrag_ = cluster->considerBufferDefrag_;
if(maxRowLength_ < sizeof(HashRow) + sizeof(UInt32)) {
isVariableLength_ = false;
considerBufferDefrag_ = FALSE;
}
// first row starts after the buffer header
rows_ = data_ + ROUND8(sizeof(HashBufferHeader));
nextAvailRow_ = rows_;
header_->setRowCount(0);
maxNumFullRowsSer_ = ((bufferSize_ - ROUND8(sizeof(HashBufferHeader)) - 8 )
/ maxRowLength_);
freeSpace_ = bufferSize_ - ROUND8(sizeof(HashBufferHeader)) - 8;
};
/////////////////////////////////////////////////////////////////////////////
HashBuffer::~HashBuffer() {
if (data_) {
if ( ! cluster_ ) {
heap_->deallocateMemory(data_);
return;
}
// NOTE: we do NOT ajust the memory usage statistics for the cluster,
// because totalClusterSize_ denotes the overall size of a cluster.
// this is later used in PHASE 3 do decide if we switch the role of
// the inner and the outer cluster and to determine if hash loops
// are required.
// But we adjust the overall availableMemory_, because it denotes
// the currently available main memory.
ClusterDB * clusterDb = cluster_->clusterDb_;
NAHeap *heap = clusterDb->bufferHeap_;
heap->deallocateHeapMemory(data_);
clusterDb->availableMemory_ += bufferSize_;
clusterDb->memoryUsed_ -= bufferSize_;
if (clusterDb->bmoStats_)
clusterDb->bmoStats_->updateBMOHeapUsage((NAHeap *)clusterDb->collHeap());
};
// unchain buffer from the list of buffers
if (cluster_) {
cluster_->bufferPool_ = next_;
cluster_->numInMemBuffers_-- ; // one less in-memory buffer
#ifdef DO_DEBUG
if ( ! next_ && ! cluster_->keepRecentBuffer_ ) { // DEBUG
char msg[256];
sprintf(msg,
"NULL bufferPool_ for (%lu %lu). recent %lu inMemBuffs %lu ",
(ULng32)cluster_ & 0x0FFF,
(ULng32)cluster_->clusterDb_ & 0x0FFF,
(ULng32)cluster_->keepRecentBuffer_ & 0x0FFF,
cluster_->numInMemBuffers_);
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL,0,msg,cluster_->clusterDb_->explainNodeId_);
}
//ex_assert( next_ || cluster_->numInMemBuffers_ == 0 || // ** DEBUG **
// cluster_->keepRecentBuffer_ && cluster_->numInMemBuffers_ == 1,
// "Buffer pool is empty, but not num-in-mem");
#endif
}
};
/////////////////////////////////////////////////////////////////////////////
Bucket::Bucket() {
init();
};
void Bucket::init() {
innerCluster_ = NULL;
outerCluster_ = NULL;
rowCount_ = 0;
};
/////////////////////////////////////////////////////////////////////////////
ClusterDB::ClusterDB(HashOperator hashOperator,
ULng32 bufferSize,
atp_struct * workAtp,
Lng32 explainNodeId,
short hashTableRowAtpIndex1,
short hashTableRowAtpIndex2,
ex_expr * searchExpr,
Bucket * buckets,
ULng32 bucketCount,
ULng32 availableMemory,
MemoryMonitor * memMonitor,
short pressureThreshold,
ExExeStmtGlobals * stmtGlobals,
ExeErrorCode *rc,
NABoolean noOverFlow,
NABoolean isPartialGroupBy,
unsigned short minBuffersToFlush,
ULng32 numInBatch,
UInt16 forceOverflowEvery,
UInt16 forceHashLoopAfterNumBuffers,
UInt16 forceClusterSplitAfterMB,
ExSubtask * ioEventHandler,
ex_tcb * callingTcb,
UInt16 scratchThresholdPct,
NABoolean doLog,
NABoolean bufferedWrites,
NABoolean disableCmpHintsOverflow,
ULng32 memoryQuotaMB,
ULng32 minMemoryQuotaMB,
ULng32 minMemBeforePressureCheck,
Float32 bmoCitizenshipFactor,
Int32 pMemoryContingencyMB,
Float32 estimateErrorPenalty,
Float32 hashMemEstInKBPerNode,
ULng32 initialHashTableSize,
ExOperStats * hashOperStats
)
: hashOperator_(hashOperator),
bufferSize_(bufferSize),
bufferHeap_(NULL),
workAtp_(workAtp),
explainNodeId_(explainNodeId),
hashTableRowAtpIndex1_(hashTableRowAtpIndex1),
hashTableRowAtpIndex2_(hashTableRowAtpIndex2),
searchExpr_(searchExpr),
buckets_(buckets),
bucketCount_(bucketCount),
memoryUsed_(0),
memMonitor_(memMonitor),
pressureThreshold_(pressureThreshold),
sawPressure_(FALSE),
stmtGlobals_(stmtGlobals),
hashLoop_(FALSE),
noOverFlow_(noOverFlow),
isPartialGroupBy_(isPartialGroupBy),
availableMemory_(availableMemory),
maxClusterSize_(0),
clusterToFlush_(NULL),
clusterToProbe_(NULL),
clusterToRead_(NULL),
clusterReturnRightRows_(NULL),
clusterList_(NULL),
tempFile_(NULL),
minBuffersToFlush_(minBuffersToFlush),
minNumWriteOuterBatch_((UInt16)(numInBatch ? (numInBatch/100) % 100
: minBuffersToFlush)),
maxNumWriteOuterBatch_((UInt16)(numInBatch/10000)),
numReadOuterBatch_((UInt16)( numInBatch ? numInBatch % 100 :
minBuffersToFlush ) ),
forceOverflowEvery_(forceOverflowEvery),
forceOverflowCounter_(forceOverflowEvery), // initialize counter
forceHashLoopAfterNumBuffers_(forceHashLoopAfterNumBuffers),
forceClusterSplitAfterMB_(forceClusterSplitAfterMB),
ioEventHandler_(ioEventHandler),
callingTcb_(callingTcb),
scratchThresholdPct_(scratchThresholdPct),
sequenceGenerator_(0),
outerReadBuffers_(NULL),
doLog_(doLog),
bufferedWrites_(bufferedWrites),
disableCmpHintsOverflow_(disableCmpHintsOverflow),
memoryQuotaMB_(memoryQuotaMB),
minMemoryQuotaMB_(minMemoryQuotaMB),
minMemBeforePressureCheck_(minMemBeforePressureCheck),
bmoCitizenshipFactor_(bmoCitizenshipFactor),
pMemoryContingencyMB_(pMemoryContingencyMB),
estimateErrorPenalty_(estimateErrorPenalty),
hashMemEstInKBPerNode_(hashMemEstInKBPerNode),
totalPhase3TimeNoHL_(0),
maxPhase3Time_(0),
minPhase3Time_(0), // zero means not set yet!
numClustersNoHashLoop_(0),
totalIOCnt_(0),
earlyOverflowStarted_(FALSE),
bmoMaxMemThresholdMB_(0),
hashOperStats_(NULL),
bmoStats_(NULL),
initialHashTableSize_(initialHashTableSize),
scratchIOVectorSize_(0),
overFlowMode_(SCRATCH_DISK)
{
if (hashOperStats)
{
bmoStats_ = hashOperStats->castToExBMOStats();
if ( bmoStats_ && bmoStats_->statType() != ExOperStats::BMO_STATS)
hashOperStats_ = hashOperStats;
else
hashOperStats_ = NULL;
}
else
{
hashOperStats_ = NULL;
bmoStats_ = NULL;
}
// assume success
*rc = EXE_OK;
// set up the bufferHeap. The default is collHeap(), which is just
// the regular statement heap. We want this in DP2. If we are not running
// in DP2, we set up a seperate heap (see below)
bufferHeap_ = (NAHeap*)collHeap();
// we are not running in DP2. Setup our own bufferHeap. We want at least
// 10 buffers in each block of this heap. Also add a few bytes to the buffer
// size to account for some memory management overhead.
bufferHeap_ = new(collHeap()) NAHeap("Buffer Heap",
bufferHeap_,
10 * ((Lng32)bufferSize_ + 20));
// These fields are used to ensure that #buckets and #hash-table-entries
// have no common prime factors (to make even use of the hash table entries)
evenFactor_ = 0 == bucketCount % 2 ;
primeFactor_ = bucketCount_ ;
// If needed (HJ), remove factor of buckets-per-cluster (always a power of 2)
if ( primeFactor_ ) // skip it for UHJ
while ( 0 == primeFactor_ % 2 ) primeFactor_ /= 2 ;
};
/////////////////////////////////////////////////////////////////////////////
ClusterDB::~ClusterDB() {
// there is no point of checking pending I/O, as either there shouldn't
// be any pending I/O, or we should aband pending I/Os (by closing the
// file at delete) in case of error.
if (tempFile_) {
SortError *sortError = tempFile_->getSortError();
delete tempFile_; // this dtor does not delete the sort error
if ( sortError ) delete sortError;
tempFile_ = NULL;
};
// deallocate the read buffers
for ( HashBuffer *tmpB = outerReadBuffers_ ; tmpB; tmpB = outerReadBuffers_){
outerReadBuffers_ = outerReadBuffers_->getNext() ;
tmpB->deallocateData(collHeap()); // must deallocate before calling dtor
delete tmpB;
memoryUsed_ -= bufferSize_;
availableMemory_ += bufferSize_;
};
while (clusterList_) {
Cluster * p = clusterList_->next_;
Cluster * q;
if (clusterList_->isInner_)
q = clusterList_->buckets_->getOuterCluster();
else
q = clusterList_->buckets_->getInnerCluster();
if (q)
delete q;
delete clusterList_;
clusterList_ = p;
};
// if we allocated a seperate heap for buffers, get rid of it now
if (bufferHeap_ != collHeap())
delete bufferHeap_;
};
/////////////////////////////////////////////////////////////////////////////
// given the time it took some cluster to run phase 3, add to local stats
void ClusterDB::updatePhase3Time(Int64 someClusterTime)
{
totalPhase3TimeNoHL_ += someClusterTime;
if ( ! minPhase3Time_ || // first time
minPhase3Time_ > someClusterTime ) // found smaller time
minPhase3Time_ = someClusterTime ;
if ( maxPhase3Time_ < someClusterTime ) maxPhase3Time_ = someClusterTime ;
++numClustersNoHashLoop_;
}
////// Q U O T A /////////
// Return all the memory quota allocation for this operator to the global pool
// (Not exactly "all"; keep at least minMemoryQuotaMB_ )
void ClusterDB::yieldAllMemoryQuota()
{
if ( memoryQuotaMB_ == 0 || memoryQuotaMB_ <= minMemoryQuotaMB_ ) return;
stmtGlobals_->yieldMemoryQuota( memoryQuotaMB_ - minMemoryQuotaMB_ );
if ( doLog_ ) { // LOG -- to show that memory was yielded
char msg[256];
sprintf(msg,
"YIELDED ALL MEMORY ALLOWED: %u MB (%u). Unused pool %u MB",
memoryQuotaMB_-minMemoryQuotaMB_,
0,
stmtGlobals_->unusedMemoryQuota() );
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL, 0, msg, explainNodeId_);
}
memoryQuotaMB_ = minMemoryQuotaMB_ ;
}
////////
void ClusterDB::YieldQuota(UInt32 memNeeded)
{
// Convert to MegaBytes, upper ceiling
ULng32 memNeededMB = memNeeded / ONE_MEG ;
if ( memNeeded % ONE_MEG ) memNeededMB++ ; // one more
// Do not get below the minimum quota
memNeededMB = MAXOF(memNeededMB, minMemoryQuotaMB_);
// mem quota to yield (could be negative; e.g. with a big flushed cluster)
Lng32 memToYieldMB = (Lng32) memoryQuotaMB_ - (Lng32) memNeededMB ;
// if there is no memory to yield - then return
if ( memToYieldMB <= 1 ) return; // 1 MB - to avoid thrashing
stmtGlobals_->yieldMemoryQuota( memToYieldMB ); // Now yield
if ( doLog_ ) { // LOG -- to show that memory was yielded
char msg[256], msg1[64];
unsigned short id = (unsigned short)((ULong)this & 0x0FFF);
if ( memoryUsed_ ) sprintf(msg1,"Memory used %d, ",memoryUsed_);
else msg1[0] = (char) 0;
sprintf(msg, "%s YIELDED %d MB (%u). %s needed %u MB, unused pool %u",
hashOperator_ == HASH_GROUP_BY ? "HGB" :
hashOperator_ == SEQUENCE_OLAP ? "OLAP" : "HJ",
memToYieldMB, id, msg1, memNeededMB,
stmtGlobals_->unusedMemoryQuota());
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL, 0, msg, explainNodeId_);
}
memoryQuotaMB_ = memNeededMB ; // adjust the new limit
}
// At the end of HJ phase 1, check quota to see if there's enough for (the
// outer clusters of) phase-2. If not then return TRUE (and some in-memory
// inner may get flushed to free some memory).
NABoolean ClusterDB::checkQuotaOrYield(UInt32 numFlushed, UInt32 maxSizeMB)
{
if ( memoryQuotaMB_ == 0 ) return FALSE; // memory quota not used
UInt32 sizeNeededOuter = bufferSize_ * numFlushed * minNumWriteOuterBatch_;
if ( sizeNeededOuter + memoryUsed_ > memoryQuotaMB_ * ONE_MEG )
return TRUE ; // need to flush another cluster to free some memory
UInt32 sizeDesiredOuter = bufferSize_ * numFlushed * maxNumWriteOuterBatch_;
UInt32 sizeNeededInPhase2 =
memoryUsed_ + MAXOF( sizeNeededOuter, sizeDesiredOuter );
UInt32 sizeNeededInPhase3 =
bufferSize_ * numReadOuterBatch_ +
ONE_MEG * (maxSizeMB + 1) ; // + 1 to round up
UInt32 memNeeded = MAXOF(sizeNeededInPhase3, sizeNeededInPhase2 );
YieldQuota(memNeeded);
return FALSE;
}
// Return some memory allocation of this operator to the global pool.
// HGB gives theOFList (HJ keeps OF clusters with the regular cluster list)
// Calculate memory needed - max of what is in memory, or the largest on
// disk plus those extra buffers - and yield the rest.
void ClusterDB::yieldUnusedMemoryQuota(Cluster * theOFList,
ULng32 extraBuffers )
{
if ( memoryQuotaMB_ == 0 ) return; // nothing to yield
// Need to keep the greater of what is currently used, or the largest
// flushed (inner) cluster plus a needed hash table
Int64 maxFlushedClusterSize = 0; // find max size of flushed cluster
ULng32 maxRowCount = 0;
// HGB uses a seperate list for the overflown clusters
Cluster * clusters = theOFList ? theOFList : clusterList_ ;
for (Cluster * cl = clusters ; cl ; cl = cl->getNext() ) {
if ( cl->getState() == Cluster::FLUSHED && cl->isInner_ ) {
if ( maxFlushedClusterSize < cl->clusterSize() ) {
maxFlushedClusterSize = cl->clusterSize() ;
maxRowCount = cl->getRowCount();
}
}
}
// add the size of the needed hash table
maxFlushedClusterSize += maxRowCount * sizeof(HashTableHeader) * 3 / 2;
// Needed is max: either what's in memory now, or the largest flushed cluster
ULng32 memNeeded
= MAXOF(memoryUsed_, (ULng32) maxFlushedClusterSize) ;
// add buffers (either one for the outer for HJ, or one per each new
// cluster for HGB)
memNeeded += extraBuffers * bufferSize_ ;
// Convert to MegaBytes, upper ceiling
ULng32 memNeededMB = memNeeded / ONE_MEG ;
if ( memNeeded % ONE_MEG ) memNeededMB++ ; // one more
// Do not get below the minimum quota
memNeededMB = MAXOF(memNeededMB, minMemoryQuotaMB_);
// mem quota to yield (could be negative; e.g. with a big flushed cluster)
Lng32 memToYieldMB = (Lng32) memoryQuotaMB_ - (Lng32) memNeededMB ;
// if there is no memory to yield - then return
if ( memToYieldMB <= 1 ) return; // 1 MB - to avoid thrashing
stmtGlobals_->yieldMemoryQuota( memToYieldMB ); // Now yield
if ( doLog_ ) { // LOG -- to show that memory was yielded
char msg[256], msg1[64];
if ( memoryUsed_ ) sprintf(msg1,"Memory used %d, ",memoryUsed_);
else msg1[0] = (char) 0;
sprintf(msg, "%s YIELDED %d MB (%u). %s needed %u MB, unused pool %u",
extraBuffers == 1 ? "HJ" : "HGB", memToYieldMB,
0,
msg1, memNeededMB,
stmtGlobals_->unusedMemoryQuota());
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL, 0, msg, explainNodeId_);
}
memoryQuotaMB_ = memNeededMB ; // adjust the new limit
}
//
// Return a prime number equal or greater than the given (# clusters)
// (Used to avoid common prime factors with the hash table size)
// (Smallest value returned == 3)
//
static const ULng32 primes[70] = {
3 /*2*/, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349 };
ULng32 ClusterDB::roundUpToPrime(ULng32 noOfClusters)
{
ULng32 ind = noOfClusters / 5 ; // approximate (floor) index
if ( ind >= 70 ) return noOfClusters; // handle absurd case: #clusters >= 350
while ( primes[ind] < noOfClusters ) ind++ ; // find next prime
return primes[ind] ;
}
/////////////////////////////////////////////////////////////////////////////
// Perform checks to find if memory allocation of reqSize bytes is possible
// Return FALSE if allocation is not possible.
// Checks made:
// 1. Are we within the memory quota system limits.
// 2. Is the process' memory "crowded".
// 3. Is there a system memory pressure.
// 4. Do the hints from the compiler suggest we start overflow early ?
/////////////////////////////////////////////////////////////////////////////
NABoolean ClusterDB::enoughMemory(ULng32 reqSize, NABoolean checkCompilerHints)
{
char msg[512]; // for logging messages
// For testing overflow only -- Simulate extreme memory conditions
// Force overflow after every "count" of requests
if ( forceOverflowEvery_ )
if ( ! --forceOverflowCounter_ ) {
sawPressure_ = TRUE;
forceOverflowCounter_ = forceOverflowEvery_; // reinitialize the counter
return FALSE;
}
// Check the forced memory limit
if (memoryQuotaMB_ && // a forced max memory allowed was set
// would we exceed the max memory allowed ?
memoryQuotaMB_ * ONE_MEG < memoryUsed_ + reqSize ) {
// calculate how much memory (in MB) is needed
UInt32 memNeededMB = 1 ; // usually a small request - just take 1 MB
if ( reqSize > ONE_MEG ) {
memNeededMB =
(memoryUsed_ + reqSize - memoryQuotaMB_ * ONE_MEG) / ONE_MEG ;
if ( reqSize % ONE_MEG ) memNeededMB++ ; // upper ceiling
}
// Try to increase the memory quota (from the global "pool") to meet need
if ( stmtGlobals_->grabMemoryQuotaIfAvailable(memNeededMB) ) {
memoryQuotaMB_ += memNeededMB ; // got it
// Even though we saw pressure before; having more memory now may mean
// we can have bigger inner clusters (useful only for HJ in phase 1)
if ( sawPressure_ && memoryQuotaMB_ * ONE_MEG > maxClusterSize_ )
maxClusterSize_ = memoryQuotaMB_ * ONE_MEG ;
if ( doLog_ && memNeededMB > 1 ) { // LOG -- only for more than a buffer
sprintf(msg,
"GRABBED %u MB (%u). Memory used %u, now allowed %u MB, request size %u, unused pool %u",
memNeededMB, 0,
memoryUsed_,
memoryQuotaMB_, reqSize,stmtGlobals_->unusedMemoryQuota() );
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL, 0, msg, explainNodeId_);
}
}
else { // sorry - not enough memory
if ( ! sawPressure_ && doLog_ ) { // log first time quota overflow
sprintf(msg,
"QUOTA LIMIT OVERFLOW started. Total memory used %u, quota allowed %u MB",
memoryUsed_, memoryQuotaMB_ );
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL, 0, msg, explainNodeId_);
}
sawPressure_ = TRUE;
return FALSE;
}
}
/*
// Check if we are running out of address space or swap space.
// getUsage() would return TRUE if and only if memory gets crowded (i.e. we
// failed at least once to allocate a desired flat segment size, and the
// free memory is less than half the total memory allocated.)
size_t lastSegSize, freeSize, totalSize;
if ( collHeap()->getUsage(&lastSegSize, &freeSize, &totalSize) ) {
// Another safety check - are we using at least half of the memory in the
// last flat segment allocated ?
if (lastSegSize / 2 < memoryUsed_) {
if ( ! sawPressure_ && doLog_ ) { // log first time
sprintf(msg,
"USAGE OVERFLOW started. Memory used %u, last seg size %u, free size %u, total size %u",
memoryUsed_, (ULng32)lastSegSize,
(ULng32)freeSize, (ULng32)totalSize );
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL, 0, msg, explainNodeId_);
}
sawPressure_ = TRUE;
return FALSE;
}
}
*/
if (memMonitor_ && memoryUsed_ >= minMemBeforePressureCheck_ ) {
NABoolean pressure = (memMonitor_->memoryPressure() > pressureThreshold_);
// the first time we see pressure, we set the sawPressure flag.
// The total memory used at this point determines the maximum
// cluster size.
if (pressure) {
if ( ! sawPressure_ && doLog_ ) { // first time system memory pressure
sprintf(msg,
"PRESSURE OVERFLOW started. Total memory used %u",
memoryUsed_);
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL, 0, msg, explainNodeId_);
}
sawPressure_ = TRUE;
}
if ( pressure ) return FALSE; // cannot allocate memory
if ( isPartialGroupBy_ ) return availableMemory_ >= reqSize ;
// -----------------------------------------------------------------
// Below - Check compiler hints to trigger a possible early overflow
// -----------------------------------------------------------------
// Can be disabled with the CQD EXE_BMO_DISABLE_CMP_HINTS_OVERFLOW
if ( ! disableCmpHintsOverflow_ ) {
/*
Compiler hints:
================
Compiler provides two hints to BMO operators.
1. bmoExpectedSize:
The compiler's estimate of total memory usage by the BMO operator
2. bmoEstErrorPenalty
The fraction penalty factor that can be used at runtime to adjust
the estimated bmo size as described below.
Explanation:
-------------
bmoEstErrorPenalty can also be viewed as uncertainty penalty factor.
The higher the uncertainty of expected memory consumption,
the better is to overflow early.
bmoEstErrorPenalty is derived by the following equation:
uncertainty = { [max potential cardinality - expected cardinality] /
expected cardinality } * 100%
bmoEstErrorPenalty is set to 10% if uncertainty <= 100%,
else bmogrowthpercent is set at 25%.
Executor usage:
---------------
On Seaquest, operators overflow once memory quota is reached or
physical memory pressure is detected. Memory pressure is currently
disabled but eventually memory pressure detection mechanisms would be
enabled.
Memory quota limits and memory pressure checks do help enforce limits,
however BMO operators could utilize compiler hints to trigger overflow
and behave as a good citizen even before quota limits and memory
pressure enforcements kick in.
BMO operators often consume small chunks of memory or buffer, in
repeated cycles until memory quota limit is reached. Compiler hints
would be exercised each time a buffer allocation is required. However
the size of buffer allocation is not relevant in the calculation below.
C = Total consumed memory by BMO operator. Initially this is zero.
E = Total estimated size of memory that will be consumed by BMO.
This is initially the bmoExpectedSize hint given by compiler,
but adjusted if C started exceeding the estimate:
E = max(bmoExpectedSize, C * (1+bmoEstErrorPenalty) )
This allow us to modify the estimate at runtime after receiving
more data and penalize operators that have the chance of being much
bigger than initially thought. Note, it's possible for the runtime
logic to increase the value of bmoEstErrorPenalty on its own after
certain threshold (e.g C > 10*bmoExpectedSize) but bmoEstErrorPenalty
should not exceed 1 i.e. 100%.
Z = CitizenshipFactor which is a parameter representing how much of
the available physical memory an operator can assume for itself
as compared to leaving it to other potential players. It can have
the value of 1>= Z > 0. While we can suggest an initial value
e.g. 0.5 we think this is better to set after tuning based on
some performance tests. In the future this may also be adjusted
as input from WMS based on existing concurrency on the system.
M = Available physical memory at that instant.
U = Contingency physical memory (e.g. 10% of Phys memory in the node.
Point it to keep always phys memory available for executables,
buffers, non-BMO ops, etc)
m = [E- C] or in other words the estimated delta memory required
by BMO to complete processing.
If ( m < Z * (M-U)) then continue memory allocation else overflow.
*/
// free physical memory in MB
Float32 M = (Float32) memMonitor_->availablePhyMemKb()/1024;
// consumed memory in MB
Float32 C = memoryUsed_ / ONE_MEG;
//U : minimum percent free physical memory to be spared for other players
//on the node. Could be other processes, etc.
Float32 U = pMemoryContingencyMB_ ;
// Z: percent free physical memory to assume for myself and thereby
// allowing reminaing free space for other operators in my esp process.
// WMS could set this based on concurrency, there by it can increase
// the desity of BMO operators residing on the node.
Float32 Z = bmoCitizenshipFactor_ ;
Float32 m = 0; //delta memory required to avoid overflow.
// do the following check if HJ still in phase 1.
if ( checkCompilerHints )
{
Float32 E = hashMemEstInKBPerNode_ / 1024 ; //expected memory consumption
#ifdef FUTURE_WORK
//check extreme case first. Expected cannot be more than
//available quota.
if( memoryQuotaMB_ && E > memoryQuotaMB_ )
{
if ( ! earlyOverflowStarted_ && doLog_ ) { // log first time
sprintf(msg,
"Estimate %ld MB exceeded quota %ld MB: OVERFLOW started. Total memory used %lu",
(Lng32) E, (Lng32) memoryQuotaMB_,
memoryUsed_);
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL, 0, msg, explainNodeId_);
}
sawPressure_ = TRUE;
earlyOverflowStarted_ = TRUE;
return FALSE;
}
#endif
//general comments pasted above for explanation of this field.
Float32 estimateErrorPenalty = estimateErrorPenalty_ ;
/*
adjust expected memory to higher than consumed so that a target
expected memory is readjusted based on estimateErrorPenalty.
estimateErrorPenalty is high if confidance level of E is low and
vice versa. This in essence creates large delta memory requirement
for sort, which in essence may trigger overflow.
*/
if ( C > E ) // consumed memory exceeded the expected -- adjust E
{
E = C * ( 1 + estimateErrorPenalty ) ;
hashMemEstInKBPerNode_ = E * 1024;
}
Float32 m = E - C; //delta memory required to avoid overflow.
// if delta memory required is more than physical memory available
// then overflow.
if( m > ( Z * (M -U))) {
if ( ! earlyOverflowStarted_ && doLog_ ) { // log first time
sprintf(msg,
"Hash encountered memory pressure [m > (Z*(M-U))]: memReq m=%f, memFree M=%f, "
"memExpected E=%f, memConsumed C=%f, estimateErrorPenalty e=%f,"
"memContingency U=%f, citizenshipFactor Z=%f", m,M,E,C,estimateErrorPenalty,U,Z);
SQLMXLoggingArea::logExecRtInfo(NULL, 0,msg, explainNodeId_);
}
sawPressure_ = TRUE;
earlyOverflowStarted_ = TRUE;
return FALSE;
}
} // if ( checkCompilerHints )
else
{
// if HJ is in phase 2, memory checks done here is purely
// memory requirements against available physical memory.
m = (Float32)reqSize/ONE_MEG;
if( m > ( Z * (M - U))) {
if ( doLog_ ) {
sprintf(msg,
"HJ phase 2/3 encountered memory pressure [m > (Z*(M-U))]: memReq m=%f, memFree M=%f, memContingency U=%f, citizenshipFactor Z=%f", m,M,U,Z);
SQLMXLoggingArea::logExecRtInfo(NULL, 0,msg, explainNodeId_);
}
return FALSE;
}
} // else -- if ( checkCompilerHints )
} // if ( ! disableCmpHintsOverflow_ )
// ---------------------------------------------------------------
// End of hints' check
// ---------------------------------------------------------------
//The following checks any threshold limits set by the user. This
//check is static in nature and directly controlled by cqds
//SSD_BMO_MAX_MEM_THRESHOLD_MB if SSD disk type is in use OR
//EXE_MEMORY_AVAILABLE_IN_MB if disk type is in use.
if( (memoryUsed_ / ONE_MEG) >= bmoMaxMemThresholdMB_)
return FALSE;
} // if (memMonitor_ && memoryUsed_ >= minMemBeforePressureCheck_ )
// Always return TRUE, but for Partial HGB there's one more check
return (!isPartialGroupBy_ || availableMemory_ >= reqSize);
};
/////////////////////////////////////////////////////////////////////////////
// A superset of setClusterToRead, for an outer cluster.
// Also allocates the global list of buffers (in the first time) and
// initializes the outer cluster to start reading more
NABoolean ClusterDB::setOuterClusterToRead(Cluster * oCluster,
ExeErrorCode * rc)
{
* rc = EXE_OK;
// In case oCluster has its own hash buffers allocated, remove them
oCluster->releaseAllHashBuffers();
// when called first time for this ClusterDB, allocate the buffer list
if ( NULL == outerReadBuffers_ ) {
// Allocate a list of hash buffers to be kept at the ClusterDB
for ( Int32 bnum = 0; bnum < numReadOuterBatch_; bnum++ ) {
HashBuffer * newBuffer = NULL;
newBuffer = new(collHeap(), FALSE)
HashBuffer(bufferSize_, oCluster->rowLength_, oCluster->useVariableLength_, collHeap(), this, rc );
// if buffer allocation failed
if ( !newBuffer || *rc ) {
if (newBuffer) delete newBuffer;
if ( ! bnum ) { // we must get at least one buffer, else fail
*rc = EXE_NO_MEM_TO_EXEC;
return TRUE;
};
break; // we'd have a shorter list
}; // if failed
memoryUsed_ += bufferSize_; // the above ctor does not add
availableMemory_ -= bufferSize_;
// chain buffer into the list
newBuffer->setNext(outerReadBuffers_) ;
outerReadBuffers_ = newBuffer ;
}; // for bnum
}; // buffer list is allocated
// Mark each buffer as having zero rows, in case we finish reading in the
// middle of the buffer list
for ( HashBuffer * tmpB = outerReadBuffers_; tmpB ; tmpB = tmpB->getNext() )
tmpB->castToSerial()->clearRowCount();
// start reading into the first buffer in the list.
oCluster->nextBufferToRead_ = outerReadBuffers_ ;
oCluster->completeCurrentRead_ = FALSE;
oCluster->buffersRead_ = 0;
setClusterToRead(oCluster);
return FALSE;
};
////////////////////////////////////////////////////////////////////////
ClusterBitMap::ClusterBitMap(ULng32 size, ExeErrorCode * rc)
: size_(size) {
// assume success
*rc = EXE_OK;
ULng32 charCount = size_/8;
if (size_ % 8)
charCount++;
bitMap_ = (char *) collHeap()->allocateMemory((size_t)charCount,FALSE);
if (!bitMap_) {
*rc = EXE_NO_MEM_TO_EXEC;
return;
};
// initialize bitMap to zero
for (ULng32 i = 0; i < charCount; i++)
bitMap_[i] = 0;
};
ClusterBitMap::~ClusterBitMap() {
if (bitMap_)
collHeap()->deallocateMemory((void *)bitMap_);
};
void ClusterBitMap::setBit(ULng32 bitIndex) {
ex_assert ((bitIndex < size_), "ClusterBitMap::setBit() ot of bounds");
char bitMask = (char) (1 << (bitIndex & 7));
bitMap_[bitIndex >> 3] |= bitMask;
};
NABoolean ClusterBitMap::testBit(ULng32 bitIndex) {
ex_assert ((bitIndex < size_), "ClusterBitMap::testBit() ot of bounds");
char bitMask = (char) (1 << (bitIndex & 7));
return (NABoolean)(bitMap_[bitIndex >> 3] & bitMask);
};
/////////////////////////////////////////////////////////////////////////////
// Internal utility: Calculate memory and create a hash table
HashTable * Cluster::createHashTable(UInt32 memForHashTable,
ExeErrorCode * rc,
NABoolean checkMemory // enough avail ?
)
{
ex_assert(!hashTable_, "hash table exists already");
// do we have enough memory for this hash table ?
if ( checkMemory &&
!clusterDb_->enoughMemory(memForHashTable) ) return NULL;
UInt32 hashTableEntryCount = memForHashTable / sizeof(HashTableHeader);
NABoolean doResize = clusterDb_->hashOperator_ == ClusterDB::HASH_GROUP_BY ;
NABoolean noHVDups =
// only real HJ enforces no-Hash-Value-duplicates in the Hash Table chains
// HGB has no value duplicates, and X-product uses a single chain
! ( clusterDb_->hashOperator_ == ClusterDB::HASH_GROUP_BY ||
clusterDb_->hashOperator_ == ClusterDB::CROSS_PRODUCT ) ;
//
// create the hash table
//
hashTable_ = new(collHeap(), FALSE)
HashTable(hashTableEntryCount,
clusterDb_->evenFactor_, // can #entries be even ?
clusterDb_->primeFactor_, // #entries not divisible by this PF
noHVDups,
doResize );
// If ctor failed, or could not even get a table of MIN_HEADER_COUNT
// then we return (with error code in case we ignore memory pressure,
// otherwise no error as we would overflow to rectify the situation.)
if ( ! checkMemory )
*rc = EXE_NO_MEM_TO_EXEC; // just in case we return below
if ( !hashTable_ ) return NULL;
else if ( hashTable_->noTableAllocated() ) {
delete hashTable_;
hashTable_ = NULL;
return NULL;
}
// we got a new hash table. The constructor of HashTable might
// have adjusted the size of the table. Report the memory usage
clusterDb_->memoryUsed_ +=
(hashTable_->getHeaderCount() * sizeof(HashTableHeader));
if ( clusterDb_->hashOperStats_ ) clusterDb_->updateMemoryStats();
*rc = EXE_OK; // no error
if (clusterDb_->bmoStats_)
clusterDb_->bmoStats_->updateBMOHeapUsage((NAHeap *)clusterDb_->collHeap());
return hashTable_;
}
Cluster::Cluster(ClusterState state,
ClusterDB * clusterDb,
Bucket * buckets,
ULng32 bucketCount,
ULng32 rowLength,
NABoolean useVariableLength,
NABoolean considerBufferDefrag,
short insertAtpIndex,
NABoolean isInner,
NABoolean bitMapEnable,
Cluster * next,
ExeErrorCode * rc,
HashBuffer * bufferPool)
: state_(state),
clusterDb_(clusterDb),
buckets_(buckets),
bucketCount_(bucketCount),
rowLength_(rowLength),
useVariableLength_(useVariableLength),
considerBufferDefrag_(considerBufferDefrag),
insertAtpIndex_(insertAtpIndex),
isInner_(isInner),
bitMapEnable_(bitMapEnable),
next_(next),
ioPending_(FALSE),
totalClusterSize_(0),
outerBitMap_(NULL),
tempFile_(NULL),
readHandle_(NULL),
completeCurrentRead_(FALSE),
buffersRead_(0),
hashTable_(NULL),
rowCount_(0),
readCount_(0),
writeIOCnt_(0),
readIOCnt_(0),
bufferPool_(bufferPool),
numInMemBuffers_(0),
scanPosition_(NULL)
,returnOverflowRows_(FALSE)
,batchCountDown_(clusterDb->numReadOuterBatch_)
,lastSqueezedBuffer_(NULL) // no buffer squeezed yet
,dontSplit_(FALSE)
,nextBufferToFlush_(NULL)
,firstBufferInList_(NULL)
,afterLastBufferToFlush_(NULL)
,nextBufferToRead_(NULL)
,afterLastBufferToRead_(NULL)
,numLoops_(0)
,startTimePhase3_(0)
,keepRecentBuffer_(NULL)
,flushMe_(FALSE)
,defragBuffer_(NULL)
{
// assume success
*rc = EXE_OK;
if (bufferPool_) {
// reset the given buffer to this cluster
bufferPool_->init(this);
// the cluster got a buffer. Thus, it used memory
totalClusterSize_ += clusterDb_->bufferSize_;
numInMemBuffers_++ ;
};
// set up pointers from buckets to clusters
ULng32 i = 0;
for (; i < bucketCount_; i++)
if (isInner) {
// determine the rowCount_. For the initial clusters this will
// be 0. But in case of a cluster split, we have to sum up
// the rows in the corresponding buckets. We do this only for
// inner clusters. New outer clusters are always empty.
buckets_[i].setInnerCluster(this);
rowCount_ += buckets_[i].getRowCount();
}
else
buckets_[i].setOuterCluster(this);
// in case of the partial group by we allocate one buffer, to
// make sure we can group at least a few rows. If we can't
// allocate this one buffer, we give up. In all other cases, the
// buffer is only allocated, if it really gets a row. Note, that
// in case of a partial group by we always have only one cluster
// and therefore allocate only one buffer.
if (clusterDb_->isPartialGroupBy_) {
HashBuffer * newBuffer = NULL;
newBuffer = new(collHeap(), FALSE) HashBuffer(this);
if (!newBuffer || !newBuffer->getDataPointer() ) {
if (newBuffer)
delete newBuffer;
*rc = EXE_NO_MEM_TO_EXEC;
return;
};
bufferPool_ = newBuffer;
totalClusterSize_ += clusterDb_->bufferSize_;
numInMemBuffers_++;
};
// if the initial state is CHAINED (i.e. hash groupby), then allocate a
// hash table of the initial size (to be resized later, as needed).
if (state_ == CHAINED) {
hashTable_ = createHashTable(clusterDb_->initialHashTableSize_, rc);
if (!hashTable_) return;
};
// set up a unique sequence ID for this cluster to use for overflow
maxSeqIDIndex_ = seqIDIndex_ = 0 ;
seqID_[seqIDIndex_] = clusterDb_->generateSequenceID();
seqID_[1] = seqID_[2] = 0 ; // 0 is an invalid seq value
if (considerBufferDefrag_)
{
defragBuffer_ = (char *)clusterDb->bufferHeap_->allocateAlignedHeapMemory((UInt32)rowLength_, 512, FALSE);
}
}; // Cluster::Cluster()
/////////////////////////////////////////////////////////////////////////////
Cluster::~Cluster() {
releaseAllHashBuffers();
if (outerBitMap_) {
delete outerBitMap_;
outerBitMap_ = NULL;
};
if ( readHandle_ ) delete readHandle_;
removeHashTable();
// remove references to this cluster from the buckets
if ( buckets_ )
for (ULng32 i = 0; i < bucketCount_; i++)
if (isInner_)
buckets_[i].setInnerCluster(NULL);
else
buckets_[i].setOuterCluster(NULL);
if (defragBuffer_)
{
NAHeap *heap = clusterDb_->bufferHeap_;
heap->deallocateHeapMemory(defragBuffer_);
}
defragBuffer_ = NULL;
}
/////////////////////////////////////////////////////////////////////////////
void Cluster::removeHashTable() {
if (hashTable_) {
clusterDb_->memoryUsed_ -=
(hashTable_->getHeaderCount() * sizeof(HashTableHeader));
delete hashTable_;
hashTable_ = NULL;
};
if (clusterDb_->bmoStats_)
clusterDb_->bmoStats_->updateBMOHeapUsage((NAHeap *)clusterDb_->collHeap());
};
/////////////////////////////////////////////////////////////////////////////
// Decide which cluster to flush: Find the FLUSHED cluster with the max
// #buffers, and use that one if that #buffers > minimum ; else pick one of
// the non-flushed clusters, and if none -- use the "last resort" cluster
void ClusterDB::chooseClusterToFlush(Cluster * lastResort)
{
clusterToFlush_ = NULL ;
Cluster * maxBuffsFlushedCluster = NULL;
Cluster * anyNonFlushedCluster = NULL;
ULng32 maxBuffers = 0;
NABoolean outersOnly = ! lastResort->isInner_ ; // HJ in phase 2
unsigned short minNumBuffersToFlush =
outersOnly ? minNumWriteOuterBatch_ : minBuffersToFlush_ ;
// search thru all clusters, find the flushed cluster with max buffers
// (in case a "flush me" cluster is found, just return this one)
for ( Cluster * currCluster = clusterList_ ;
currCluster ;
currCluster = currCluster->next_ ) {
// When HJ in phase 2 -- only select outer clusters
if ( outersOnly && currCluster->isInner_ ) continue;
// Skip clusters with fewer (full) buffers than the minimum
// (We use "<=" below because the last buffer is typically not full)
if ( currCluster->numInMemBuffers_ <= minNumBuffersToFlush ) continue;
if ( currCluster->flushMe_ ) { // higher priority
currCluster->flushMe_ = FALSE;
clusterToFlush_ = currCluster ;
break;
}
if ( currCluster->state_ == Cluster::FLUSHED ) {
if ( maxBuffers < currCluster->numInMemBuffers_ ) {
maxBuffsFlushedCluster = currCluster;
maxBuffers = currCluster->numInMemBuffers_ ;
}
else // lastResort gets some priority (as its recent buffer is full)
// (when it is flushed, and has the min # buffers, and 1 <= the max)
if ( lastResort == currCluster &&
lastResort->numInMemBuffers_ + 1 >= maxBuffers )
maxBuffsFlushedCluster = lastResort;
}
else // pick a "random" non flushed cluster
anyNonFlushedCluster = currCluster ;
}
if ( ! clusterToFlush_ )
clusterToFlush_ =
maxBuffsFlushedCluster ? maxBuffsFlushedCluster :
anyNonFlushedCluster ? anyNonFlushedCluster :
lastResort ;
// Keep most recent buffer if not full
if ( clusterToFlush_->bufferPool_->castToSerial()->notFull() ) {
clusterToFlush_->keepRecentBuffer_ = clusterToFlush_->bufferPool_ ;
// start flushing from the second most recent buffer
clusterToFlush_->bufferPool_ = clusterToFlush_->bufferPool_->getNext();
// the buffer to keep would become the new buffer list
clusterToFlush_->keepRecentBuffer_->setNext(NULL);
}
else // in case it is not NULL from a previous flush
clusterToFlush_->keepRecentBuffer_ = NULL;
// start with the first (also most recent) buffer in chain
clusterToFlush_->nextBufferToFlush_ = clusterToFlush_->bufferPool_ ;
#ifdef DO_DEBUG
if ( doLog_ && clusterToFlush_->seqIDIndex_ > 0 ) { // DEBUG
char msg[256];
sprintf(msg,
"chooseClusterToFlush() (%lu %lu). next buff %lu inMemBuffs %lu ",
(ULng32)clusterToFlush_ & 0x0FFF,
(ULng32)this & 0x0FFF,
(ULng32)clusterToFlush_->nextBufferToFlush_ & 0x0FFF,
clusterToFlush_->numInMemBuffers_);
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL,0,msg,explainNodeId_);
}
#endif
}
/////////////////////////////////////////////////////////////////////////////
NABoolean Cluster::insert(atp_struct * newEntry,
ex_expr * moveExpr,
SimpleHashValue hashValue,
ExeErrorCode * rc,
NABoolean skipMemoryCheck) {
// assume success
*rc = EXE_OK;
HashRow *dataPointer = NULL;
// make sure that we have a buffer
if (!bufferPool_) {
// no buffer means, we don't have rows yet
ex_assert(!rowCount_,
"cluster without a buffer has rows");
HashBuffer * newBuffer = new(collHeap(), FALSE) HashBuffer(this);
if ( !newBuffer || !newBuffer->getDataPointer() ) {
// this is the first buffer for this cluster. If we couldn't
// allocate it, we give up
if (newBuffer)
delete newBuffer;
*rc = EXE_NO_MEM_TO_EXEC;
return FALSE;
};
bufferPool_ = newBuffer;
numInMemBuffers_ = 1; // the first in-memory buffer
totalClusterSize_ += clusterDb_->bufferSize_;
};
lastDataPointer_ = NULL;
NABoolean defragmented = FALSE;
// allocate space for the new row in the buffer pool
if ((dataPointer = bufferPool_->castToSerial()->getFreeRow()) == NULL)
{
if (defragBuffer_)
{
#if defined(_DEBUG)
assert(defragBuffer_);
#endif
atp_struct * workAtp = clusterDb_->workAtp_;
workAtp->getTupp(insertAtpIndex_).setDataPointer(defragBuffer_);
UInt32 maxDataLen = bufferPool_->getMaxRowLength() - sizeof(HashRow);
UInt32 rowLen = maxDataLen;
UInt32 *rowLenPtr = &rowLen;
if (moveExpr)
{
if(moveExpr->eval(newEntry, workAtp, 0, -1, rowLenPtr) == ex_expr::EXPR_ERROR)
{
*rc = (ExeErrorCode)(-newEntry->getDiagsArea()->mainSQLCODE());
return FALSE;
}
}
if(rowLen != maxDataLen)
{
UInt32 len = ROUND4(rowLen) + sizeof(HashRow);
if ((dataPointer = bufferPool_->castToSerial()->getFreeRow(len)) != NULL)
{
// we got a row
defragmented = TRUE;
char *rowPointer = dataPointer->getData();
//set work atp (insertAtpIndex_) data address -- needed for hash group by
workAtp->getTupp(insertAtpIndex_).setDataPointer(rowPointer);
str_cpy_all(rowPointer,
defragBuffer_,
rowLen);
//rows are variable-- set row length
bufferPool_->castToSerial()->setRowLength(dataPointer, rowLen);
#if (defined(_DEBUG))
char txt[] = "Cluster::insert";
sql_buffer_pool::logDefragInfo(txt,bufferPool_->getMaxRowLength(),
ROUND4(rowLen) + sizeof(HashRow),
bufferPool_->getFreeSpace(),
bufferPool_,
bufferPool_->getRowCount());
#endif
}
}
}
}
if (dataPointer == NULL)
{
// old buffer is full -- allocate a new buffer
if ( skipMemoryCheck || // first check the memory
clusterDb_->enoughMemory(clusterDb_->bufferSize_, isInner_) ) {
// either we generally do not overflow, or
// just for this row we should avoid overflow, or
// we have enough memory to allocate another buffer,
// so create a new buffer and chain it into the bufferlist
HashBuffer * newBuffer = new(collHeap(), FALSE) HashBuffer(this);
if ( !newBuffer || !newBuffer->getDataPointer() ) {
if (skipMemoryCheck) {
// we skipped memory pressure check (e.g., due to no-overflow)
// and we did not get a new buffer, then we must fail
*rc = EXE_NO_MEM_TO_EXEC;
return FALSE;
};
// reset rc in case it was set in the constructor of HashBuffer
*rc = EXE_OK;
// set saw pressure as we indeed can not allocate memory
// fix for CR 10-071012-6254
clusterDb_->sawPressure_ = TRUE;
// our estimate for available memory was wrong. We don't
// have memory left. Select a cluster for flushing and return
// if we are in DP2 and it is a partial group by, DP2 starts
// returning partial groups
if (!clusterDb_->isPartialGroupBy_)
clusterDb_->chooseClusterToFlush(this);
return FALSE;
};
totalClusterSize_ += clusterDb_->bufferSize_;
numInMemBuffers_++;
// we got a new buffer. Chain it into the list of buffers
newBuffer->setNext(bufferPool_);
bufferPool_ = newBuffer;
// allocate space for new row
dataPointer = bufferPool_->castToSerial()->getFreeRow();
}
else {
// not enough memory avaliable. Select a cluster
// for flushing
if (!clusterDb_->isPartialGroupBy_)
clusterDb_->chooseClusterToFlush(this);
return FALSE;
};
};
if (!defragmented)
{
char *rowPointer = dataPointer->getData();
// now we have a slot in a buffer and dataPointer points to it
// move input row to pool
atp_struct * workAtp = clusterDb_->workAtp_;
workAtp->getTupp(insertAtpIndex_).setDataPointer(rowPointer);
UInt32 maxDataLen = bufferPool_->getMaxRowLength() - sizeof(HashRow);
UInt32 rowLen = maxDataLen;
UInt32 *rowLenPtr = &rowLen;
if (moveExpr) {
if(moveExpr->eval(newEntry, workAtp, 0, -1, rowLenPtr) == ex_expr::EXPR_ERROR)
{
*rc = (ExeErrorCode)(-newEntry->getDiagsArea()->mainSQLCODE());
return FALSE;
}
}
if(bufferPool_->isVariableLength()) {
bufferPool_->castToSerial()->setRowLength(dataPointer, rowLen);
if(rowLen != maxDataLen) {
bufferPool_->castToSerial()->resizeLastRow(rowLen, dataPointer);
}
}
}
lastDataPointer_ = dataPointer; // keep location of most recent row
// set the hash value in the row header
dataPointer->setHashValueRaw(hashValue);
// SimpleHashValue * headerHashValue = (SimpleHashValue *)dataPointer;
// * headerHashValue = hashValue;
// For hash-groupby, insert the row into the hash chain.
if ( clusterDb_->hashOperator_ == ClusterDB::HASH_GROUP_BY ) {
NABoolean resizeNeeded;
// We know that we don't have duplicates (each group is unique
// with respect to the grouping (hash) columns. Just insert
// the row at the beginning of the chain.
resizeNeeded = hashTable_->insert(dataPointer);
if ( resizeNeeded ) {
NABoolean enoughMem =
clusterDb_->enoughMemory(hashTable_->resizeTo());
ULng32 memAdded = hashTable_->resize( enoughMem );
// if Hash-Table was resized up, then update memory use
clusterDb_->memoryUsed_ += memAdded ;
// if could not create a new HT, better pick this cluster for a flush
if ( ! memAdded ) flushMe_ = TRUE;
}
}
rowCount_++;
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// initialize the cluster's scratch file and read handler (and the clusterDB
// global scratch file, if needed). Return TRUE if error.
NABoolean Cluster::initScratch(ExeErrorCode * rc)
{
// First time -- need to create the scratch space for all the clusters
if ( ! clusterDb_->tempFile_ ) {
ExExeStmtGlobals * stmtGlobals = clusterDb_->stmtGlobals_ ;
const ExScratchFileOptions *sfo = stmtGlobals->getScratchFileOptions();
Lng32 numOfInstances = stmtGlobals->getNumOfInstances();
Lng32 myInstanceNumber = stmtGlobals->getMyInstanceNumber();
SortError * sortError = new(collHeap(), FALSE) SortError();
HashScratchSpace * tempFile = new(collHeap(), FALSE)
HashScratchSpace(collHeap(),
sortError,
clusterDb_->explainNodeId_,
clusterDb_->bufferSize_,
clusterDb_->getScratchIOVectorSize(),
clusterDb_->doLog_,
sfo->getScratchMgmtOption());
if ( ! tempFile ){
*rc = EXE_NO_MEM_TO_EXEC;
return TRUE;
};
if (sortError->getSortError() != 0) {
*rc = EXE_SORT_ERROR;
return TRUE;
};
tempFile->setScratchDirListSpec(sfo->getSpecifiedScratchDirs());
tempFile->setNumDirsSpec(sfo->getNumSpecifiedDirs());
tempFile->setNumEsps(numOfInstances);
tempFile->setEspInstance(myInstanceNumber);
tempFile->setPreallocateExtents(sfo->getScratchPreallocateExtents());
tempFile->setScratchMaxOpens(sfo->getScratchMaxOpensHash());
tempFile->setScratchDiskLogging(sfo->getScratchDiskLogging());
tempFile->setIoEventHandler(clusterDb_->ioEventHandler_);
tempFile->setCallingTcb(clusterDb_->callingTcb_);
tempFile->setIpcEnvironment(stmtGlobals->getIpcEnvironment());
tempFile->setScratchThreshold(clusterDb_->scratchThresholdPct_);
tempFile->setScratchIOVectorSize(clusterDb_->getScratchIOVectorSize());
tempFile->setScratchOverflowMode(clusterDb_->getScratchOverflowMode());
clusterDb_->tempFile_ = tempFile ;
};
// initialize for this cluster
tempFile_ = clusterDb_->tempFile_ ;
readHandle_ = new(collHeap(), FALSE) ClusterPassBack();
if ( ! readHandle_ ) {
*rc = EXE_NO_MEM_TO_EXEC;
return TRUE;
};
return FALSE;
}
//Wrapper function on flush() to populate diags area.
//Returns: FALSE - either error, or need to call again
// TRUE -- flush is done
NABoolean Cluster::flush(ComDiagsArea *&da, CollHeap *heap) {
ExeErrorCode rc = EXE_OK;
//Flush returning FALSE means either Error or IO_NOT_COMPLETE.
//if rc != EXE_OK then it is error.
if(!flush(&rc)) {
if(rc != EXE_OK) {
if(da == NULL) {
da = ComDiagsArea::allocate(heap);
}
*da << DgSqlCode(-rc);
char msg[512];
if(rc == EXE_SORT_ERROR) {
char errorMsg[100];
Lng32 scratchError = 0;
Lng32 scratchSysError = 0;
Lng32 scratchSysErrorDetail = 0;
if(clusterDb_ != NULL) {
clusterDb_->getScratchErrorDetail(scratchError,
scratchSysError,
scratchSysErrorDetail,
errorMsg);
snprintf(msg, sizeof(msg), "Scratch IO Error occurred. Scratch Error: %d, System Error: %d, System Error Detail: %d, Details: %s",
scratchError, scratchSysError, scratchSysErrorDetail, errorMsg);
}
else {
snprintf(msg, sizeof(msg), "Scratch IO Error occurred. clusterDb_ is NULL" );
}
} else {
snprintf(msg, sizeof(msg), "Cluster Flush Error occurred.");
}
*da << DgString0(msg);
}
return FALSE;
}
return TRUE;
}
// Flush the in-memory buffers of this cluster
// Returns: FALSE - either error, or need to call again
// TRUE -- flush is done
NABoolean Cluster::flush(ExeErrorCode * rc) {
// assume success
*rc = EXE_OK;
RESULT writeStatus = SCRATCH_SUCCESS;
ULng32 bufferSize = clusterDb_->bufferSize_;
// ensure that the scratch file was created
if ( ! tempFile_ )
if ( initScratch(rc) ) return FALSE; // return if there was an error
#ifdef DO_DEBUG
if ( clusterDb_->doLog_ && seqIDIndex_ > 0 ) { // DEBUG
char msg[256];
sprintf(msg,
"Cluster::flush() (%lu %lu). next buff %lu writeIOCnt %lu ",
(ULong)this & 0x0FFF,
(ULong)clusterDb_ & 0x0FFF,
(ULong)nextBufferToFlush_ & 0x0FFF,
writeIOCnt_);
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL,0,msg,clusterDb_->explainNodeId_);
}
#endif
// while there are buffers, and the IO is ready, write them to disk
// ( afterLastBufferToFlush_ is usually NULL ; it's only used by OLAP, where
// it is guaranteed to point to one of the following buffers.)
while ( nextBufferToFlush_ != afterLastBufferToFlush_ ) {
// are the previous I/Os still in flight, and we can not issue a new I/O ?
if ( IONotReady(rc) ) return FALSE; // return to scheduler (or error)
// first make sure that this buffer has rows
ex_assert( clusterDb_->hashOperator_ == ClusterDB::SEQUENCE_OLAP ||
nextBufferToFlush_->getRowCount(),
"flushed an empty buffer" );
// fire the I/O
writeStatus = tempFile_->writeThru(nextBufferToFlush_->getDataPointer(),
seqID_[seqIDIndex_] );
if ( writeStatus != SCRATCH_SUCCESS && writeStatus != IO_NOT_COMPLETE ) {
*rc = EXE_SORT_ERROR;
return FALSE;
}
// and do the remaining book-keeping
writeIOCnt_++;
clusterDb_->totalIOCnt_++;
if ( clusterDb_->hashOperStats_ ) clusterDb_->updateIOStats();
nextBufferToFlush_ = nextBufferToFlush_->getNext() ;
} // while ( nextBufferToFlush_ )
// No more buffers to flush -- ensure that all I/Os are done
if ( IONotComplete(rc) ) return FALSE; // return to scheduler (or error)
state_ = FLUSHED;
// For OLAP -- do not deallocate buffers (anyway bufferPool is not used).
if ( clusterDb_->hashOperator_ == ClusterDB::SEQUENCE_OLAP ) return TRUE;
// All writes completed -- remove the written buffers
while ( bufferPool_->getNext() ) { // remove all but the last buffer
delete bufferPool_;
}
// if the recent buffer was kept, then the last written buffer can be removed
// and the kept recent buffer would be used instead
if ( keepRecentBuffer_ ) { // make the kept buffer to be the new list
delete bufferPool_;
bufferPool_ = keepRecentBuffer_;
keepRecentBuffer_ = NULL ;
}
else { // the last buffer was flushed; reuse it as the new buffer list
// we are done with the cluster flush. reset the last buffer
bufferPool_->castToSerial()->clearRowCount();
// increase totalClusterSize_ because bufferPool_ is now empty but
// will be reused when inserting new rows.
totalClusterSize_ += bufferSize;
}
numInMemBuffers_ = 1; // only 1 in-memory buffer now
// Check if CLUSTER-SPLIT is needed, and perform the split if possible
// return FALSE if error ( *rc != 0 ) or if still processing the most
// recent (not full) buffer (the schedule would return us here later)
if ( checkAndSplit( rc ) ) return FALSE;
return TRUE; // Done writing this list of buffers.
}; // Cluster::flush()
/////////////////////////////////////////////////////////////////////////////
NABoolean Cluster::spill(ExeErrorCode * rc, NABoolean noAggregates) {
// assume success
*rc = EXE_OK;
NABoolean firstFlushDistinctGroupby = state_ == CHAINED && noAggregates ;
if ( firstFlushDistinctGroupby && keepRecentBuffer_ ) {
// first spill for distinct must flush that remaining not-full buffer
// because it contains groups that were already returned !!
// So re-chain the recent buffer into the buffer pool to be flushed
keepRecentBuffer_->setNext(bufferPool_);
bufferPool_ = keepRecentBuffer_;
keepRecentBuffer_ = NULL;
// start with the (just restored) first buffer in chain
nextBufferToFlush_ = bufferPool_ ;
}
if ( flush(rc) ) {
// the flush is done; reinitialize/renew the hash-table
if ( hashTable_->originalSize() ) {
// the old HT is at the original size; just re-initialize it
hashTable_->init();
}
else {
// Reallocate a (smaller) hash table.
removeHashTable();
// after a flush, a cluster starts with the minimal hash table
hashTable_ = createHashTable(clusterDb_->initialHashTableSize_, rc);
if (!hashTable_) return FALSE;
}
// If last buffer was kept, add its rows to the new hash-table
if ( keepRecentBuffer_ ) {
HashBuffer *hb = bufferPool_;
HashRow *dataPointer = hb->castToSerial()->getFirstRow();
for ( ULng32 rowIndex = 0 ;
rowIndex < hb->getRowCount() ;
rowIndex++ ) {
hashTable_->insert(dataPointer); // no resize
dataPointer = hb->castToSerial()->getNextRow(dataPointer);
}
}
if ( firstFlushDistinctGroupby ) {
ex_assert( 0 == maxSeqIDIndex_ ,"First time spill, index should be 0");
// For non-blocking, rows up to here were returned up, while the
// following rows would only be returned when the overflowed cluster
// is read from file, hence we keep the two lists seperate
// start a new sequence for the current cluster -- but at same index 0
// while the previous sequence-num is pushed to index 1 (because later
// we read first the buffers from index 1)
maxSeqIDIndex_++ ; // update the max
seqID_[1 + seqIDIndex_] = seqID_[seqIDIndex_] ; // push up
seqID_[seqIDIndex_] = clusterDb_->generateSequenceID();
}
return TRUE;
}
else
return FALSE;
};
// internal method: Set HL, create bitmap, return TRUE if no memory error
NABoolean Cluster::setHashLoop(ExeErrorCode * rc) {
if ( clusterDb_->doLog_ && ! clusterDb_->hashLoop_ ) { // first time
char msg[256];
sprintf(msg,
"HASH LOOP started (%lu %lu). Total memory used %u, cluster size " PF64 " ",
(ULong)this & 0x0FFF, (ULong)clusterDb_ & 0x0FFF,
clusterDb_->memoryUsed_, totalClusterSize_ );
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL, 0, msg, clusterDb_->explainNodeId_);
}
clusterDb_->hashLoop_ = TRUE ;
// we might have to allocate the bitmap for the outer cluster;
// this is only done if the outer cluster doesn't have a
// bitmap already
Cluster * oCluster = getOuterCluster();
if ( oCluster && // right-HJ may have an empty outer cluster
oCluster->bitMapEnable_ &&
!oCluster->outerBitMap_ ) {
oCluster->outerBitMap_ =
new(collHeap(), FALSE) ClusterBitMap(oCluster->rowCount_, rc);
if (!oCluster->outerBitMap_ || *rc) {
*rc = EXE_NO_MEM_TO_EXEC;
return FALSE;
};
}
completeCurrentRead_ = TRUE; // End of a loop is like an end of cluster
state_ = IN_MEMORY; // the (read part of the) cluster is IN_MEMORY
if ( IONotComplete(rc) ) return FALSE; // return to scheduler (or error)
// squeeze out rows of other clusters (not needed for the first sequence)
if ( seqIDIndex_ < maxSeqIDIndex_ ) // if beyond the first sequence
if ( squeezeOutRowsOfOtherClusters(rc) ) return FALSE; // return if error
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// internal method: If cluster contains variable length rows, move
// rows belonging to this cluster from original buffers new
// buffers. All rows of this cluster must be moved. Can reuse buffers
// after they have been processed.
//
// If cluster contains fixed length rows, move rows from last read
// buffer(s) into locations of rows that belong to other clusters
//
// (used only after a cluster split) Works with _multiple_ mixed
// buffers !! return TRUE if error
/////////////////////////////////////////////////////////////////////////////
NABoolean Cluster::squeezeOutRowsOfOtherClusters(ExeErrorCode * rc)
{
if(bufferPool_->isVariableLength()) {
// If the rows in these buffers are variable length, then we
// cannot do this squeeze operation in place. We must copy each
// row from the existing buffers to the new buffers. However, we
// can reuse the buffers that we have already processed.
// The source data
HashBuffer *oldBuffs = bufferPool_;
// The destination. Only rows that belong to this cluster will be
// moved here.
HashBuffer *newBuffs = NULL;
// Keep track of the buffers that have been processed. They can
// be reused.
HashBuffer *freeBuffs = NULL;
// Process all the buffers
while(oldBuffs) {
HashBuffer *oldBuff = oldBuffs;
oldBuff->castToSerial()->fixup();
// Check each row of the current buffer
HashRow *row = oldBuff->castToSerial()->getFirstRow();
for(UInt32 i = 0; i < oldBuff->getRowCount(); i++) {
ULng32 bucketId = row->hashValue() % clusterDb_->bucketCount_;
// If this row belongs to this cluster, copy it to the
// destination. Otherwise, ignore it.
if ( clusterDb_->buckets_[bucketId].getInnerCluster() == this ) {
// If we need a new buffer, allocate one or take one off of
// the free list.
if(!newBuffs || !newBuffs->castToSerial()->notFull()) {
HashBuffer *newBuff = NULL;
// If there are free buffers, use one
if(freeBuffs) {
newBuff = freeBuffs;
freeBuffs = freeBuffs->getNext();
newBuff->setNext(NULL);
} else {
// Otherwise, we must allocate a new one.
newBuff = new(collHeap(), FALSE) HashBuffer(this);
if ( ! newBuff || ! newBuff->getDataPointer() ) {
*rc = EXE_NO_MEM_TO_EXEC;
return TRUE;
}
}
// Place new buffer at the head of the new buffers list.
newBuff->setNext(newBuffs);
newBuffs = newBuff;
}
// Copy the row from the source (oldBuff) to the destination
// (newBuffs). Resize the row based on the size of the source row.
HashRow *dstRow = newBuffs->castToSerial()->getFreeRow();
UInt32 len = oldBuff->castToSerial()->getRowLength(row);
memcpy((char *)dstRow, (char *)row, len + sizeof(HashRow));
newBuffs->castToSerial()->resizeLastRow(len, dstRow);
}
// Move to the next row of the source.
row = oldBuff->castToSerial()->getNextRow(row);
}
// Move to the next buffer of the source.
// Move the buffer we just finished onto the free list.
oldBuffs = oldBuff->getNext();
oldBuff->setNext(freeBuffs);
freeBuffs = oldBuff;
freeBuffs->init(this);
}
// If there are any remaining free buffers, delete them.
while (freeBuffs) {
HashBuffer *freeBuff = freeBuffs;
freeBuffs = freeBuffs->getNext();
delete freeBuff;
}
bufferPool_ = newBuffs;
lastSqueezedBuffer_ = bufferPool_;
return FALSE;
} else {
// If this cluster contains fixed length rows, then we can move
// rows from the source into vacant slots in the destination.
// assume lastSqueezedBuffer_ points to the last squeezed buffer in the
// buffer list, and the buffers ahead have mixed rows (incl other clusters)
// lastSqueezedBuffer_
// |
// V
// ---- ---- ---- ---- ---------------
// bufferPool_ -> | | -> | | -> | | -> | | --> | RRRRRRR| -> ...
// ---- ---- ---- ---- ---------------
// When no lastSqueezedBuffer_ exists (e.g., with hash-loop, or if no input
// rows came after the split), then create an empty one and chain it at the
// end of the buffers list.
if ( ! lastSqueezedBuffer_ ) {
// no memory pressure check
lastSqueezedBuffer_ = new(collHeap(), FALSE) HashBuffer(this);
if ( ! lastSqueezedBuffer_ || ! lastSqueezedBuffer_->getDataPointer() ) {
*rc = EXE_NO_MEM_TO_EXEC;
return TRUE;
};
// chain the new buffer at the end of the buffer pool list
HashBuffer * checkBuff = bufferPool_;
HashBuffer * nextBuff = checkBuff->getNext() ;
while ( nextBuff != NULL ) {
checkBuff = nextBuff;
nextBuff = nextBuff->getNext() ;
}
checkBuff->setNext(lastSqueezedBuffer_) ;
}
// ========================================================================
// The squeeze algorithm: First find the bottom most slot for the row (either
// in the lastSqueezedBuffer_, or if full, in the buffer above it), then
// find the top most row (of this cluster) to move to that slot.
// If both are found -- move that row to that slot. If not (e.g., reached
// the end of the buffer) then rectify and try again.
// Invariants to keep:
// 1. lastSqueezedBuffer_ is always in a complete state (i.e., its row count
// is correct; no rows in theat buffer above that count).
// 2. When returning, bufferPool_ equals lastSqueezedBuffer_ .
// ========================================================================
// Rows that belong to this cluster are moved from the fromBuff to the
// toBuff, and when fromBuff gets empty, it is deallocated.
HashBuffer * toBuff = lastSqueezedBuffer_ ;
HashBuffer * fromBuff = bufferPool_ ; // fromBuff is always == bufferPool_
// invariant - when toSlot/fromRow is NULL, then toRowPos/fromRowPos has
// the position to check next; when not null, then they have the
// current position of that slot/row.
char * toSlot = NULL, * fromRow = NULL;
UInt32 numConfirmedRowsInBuff = lastSqueezedBuffer_->getRowCount() ;
Int32 toRowPos = (Int32) toBuff->getRowCount(),
fromRowPos = (Int32) fromBuff->getRowCount() - 1;
const UInt32 rowLength = lastSqueezedBuffer_->getMaxRowLength() ;
const UInt32 maxRowsInBuffer = lastSqueezedBuffer_->castToSerial()->getMaxNumFullRows();
//
// Search for a slot, then for a row to move, then is possible move that
// row down.
//
while ( TRUE ) { // while there are still rows to move
// ******* find a free toSlot in toBuff *******
while ( ! toSlot ) {
// update toBuff to next buffer, if needed
if ( toRowPos >= (Int32) maxRowsInBuffer ) { // is this "to" buffer full?
lastSqueezedBuffer_ = toBuff ; // toBuff is all squeezed
lastSqueezedBuffer_->castToSerial()->setRowCount(maxRowsInBuffer);
// in some rare case ...
if ( bufferPool_ == lastSqueezedBuffer_ ) return FALSE;
HashBuffer * checkBuff = bufferPool_;
HashBuffer * nextBuff = checkBuff->getNext() ;
while ( nextBuff != lastSqueezedBuffer_ ) {
checkBuff = nextBuff;
nextBuff = nextBuff->getNext() ;
}
toBuff = checkBuff;
toRowPos = 0; // start from row position zero
numConfirmedRowsInBuff = 0;
} // if ( toRowPos >= maxRowsInBuffer ) // is this "to" buffer full
char * toDataPointer = toBuff->getFirstRow() + toRowPos * rowLength ;
HashRow * row = (HashRow *) toDataPointer;
ULng32 bucketId = row->hashValue() % clusterDb_->bucketCount_;
// Are we done ? If end of this batch -- finish up and return
if ( toBuff == fromBuff && // only check when "to" and "from" are same
( row->bitSet() || // was this new row already checked by "from" ?
toRowPos >= fromRowPos ) ) { // "from" hasn't checked this row yet
// handle case of a row not yet checked by "from"
if ( ! row->bitSet() &&
clusterDb_->buckets_[bucketId].getInnerCluster() == this )
++numConfirmedRowsInBuff;
if ( numConfirmedRowsInBuff ) { // there are rows in this buffer
lastSqueezedBuffer_ = toBuff ; // toBuff is all squeezed
lastSqueezedBuffer_->castToSerial()->setRowCount(numConfirmedRowsInBuff);
}
else { // another rare case: just crossed over to an empty bufferPool
delete bufferPool_ ;
}
ex_assert ( bufferPool_ == lastSqueezedBuffer_ ,
"bufferPool is not the last squeezed buffer");
return FALSE;
} else { // find an available slot
if ( toRowPos >= (Int32) toBuff->getRowCount()
// this buffer was not full, and we reached over the top row
|| // or
clusterDb_->buckets_[bucketId].getInnerCluster() != this
// This slot was held by another cluster's row; reuse it
)
toSlot = toDataPointer;
else {
++toRowPos; // prepare for the next one
++numConfirmedRowsInBuff;
}
}
} // while ( ! toSlot )
// **** find the last row (of this cluster) in fromBuff and move it ****
while ( ! fromRow ) {
// if no more rows in this buffer, deallocate and use next buffer
if ( fromRowPos < 0 ) {
ex_assert ( bufferPool_ != lastSqueezedBuffer_ ,
"Empty bufferPool is the last squeezed buffer");
delete bufferPool_; // the dtor removes the first buffer in list
fromBuff = bufferPool_;
fromRowPos = (Int32) fromBuff->getRowCount() - 1;
// just in case ...
if ( fromBuff == lastSqueezedBuffer_ ) return FALSE;
}
// If row at from-pos belongs to this cluster -- use it !
char * fromDataPointer = fromBuff->getFirstRow() + fromRowPos * rowLength ;
HashRow * row = (HashRow *) fromDataPointer;
ULng32 bucketId = row->hashValue() % clusterDb_->bucketCount_;
if ( clusterDb_->buckets_[bucketId].getInnerCluster() == this )
fromRow = fromDataPointer;
else
--fromRowPos; // prepare for the next one
// in case the "from" just crossed the "to", in the same buffer
if ( toBuff == fromBuff && toRowPos >= fromRowPos ) {
// mark this buffer as last squeezed and return
if ( numConfirmedRowsInBuff ) { // there are rows in this buffer
lastSqueezedBuffer_ = toBuff ; // toBuff is all squeezed
lastSqueezedBuffer_->castToSerial()->setRowCount(numConfirmedRowsInBuff);
}
else { // another rare case: just crossed over to an empty bufferPool
delete bufferPool_ ;
}
ex_assert ( bufferPool_ == lastSqueezedBuffer_ ,
"bufferPool is not the last squeezed buffer");
return FALSE;
}
// mark this row to make the "to" stop if needed
// (this row is either skipped or would be moved)
row->setBit(TRUE);
} // while ( ! fromRow )
// ***** Move the row into the slot **********
memcpy(toSlot, fromRow, rowLength );
// in case the toBuff is the last squeezed, or incomplete
// - then update its row count
if ( toBuff == lastSqueezedBuffer_ ||
toRowPos == toBuff->getRowCount() )
toBuff->castToSerial()->setRowCount(toBuff->getRowCount()+1);
HashRow * row = (HashRow *) toSlot;
row->setBit(FALSE); // erase the mark in the moved row
toSlot = fromRow = NULL ; // both were used; reset them
++toRowPos; // prepare for the next one
--fromRowPos; // prepare for the next one
++numConfirmedRowsInBuff; // one more row of this cluster in this buffer
} // while ( TRUE )
}
} // Cluster::squeezeOutRowsOfOtherClusters()
/////////////////////////////////////////////////////////////////////////////
// Read a cluster. If it is an inner Cluster, read as many buffers as
// possible. If it is an inner and we couldn't read all buffers, set
// hashLoop_ == TRUE (this is for inner Clusters during PHASE_3).
// If it in an outer Cluster, read a batch of buffers (this is for outer
// clusters during PHASE_3).
/////////////////////////////////////////////////////////////////////////////
NABoolean Cluster::read(ExeErrorCode * rc) {
// assume success
*rc = EXE_OK;
RESULT readStatus = SCRATCH_SUCCESS;
char * dataPtr = NULL;
// FIRST -- handle end of (batch) read
if ( completeCurrentRead_ ) {
// Synchronize with previously issued READs - ensure that all I/Os are done
if ( IONotComplete(rc) ) return FALSE; // return to scheduler (or error)
completeCurrentRead_ = FALSE ; // prepare for next time, if needed
// this is a regular flushed cluster (i.e., not
// -- an (inner) cluster that was split
// or -- an (outer) cluster from HGB Distinct
if ( ! maxSeqIDIndex_ ) {
if ( readHandle_->endOfSequence() )
state_ = IN_MEMORY; // mark the cluster as IN_MEMORY
return TRUE; // this read is done !!
}
// Handle an (outer) cluster from HGB Distinct
if ( ! isInner_ ) {
// once we finished the first sequence, return all the new groups
if ( seqIDIndex_ < maxSeqIDIndex_ )
returnOverflowRows_ = TRUE;
if ( readHandle_->endOfSequence() ) {
if ( seqIDIndex_ ) {
--seqIDIndex_ ; // end of first sequence; go to 2nd/last
readHandle_->initCPB(); // start reading from begining of sequence
}
else state_ = IN_MEMORY; // 2nd sequence: mark the cluster as IN_MEMORY
}
return TRUE;
}
// code below: only for handling an inner cluster that had a split
// squeeze out rows of other clusters (not needed for the first sequence)
if ( seqIDIndex_ < maxSeqIDIndex_ ) // if beyond the first sequence
if ( squeezeOutRowsOfOtherClusters(rc) ) return FALSE; // return if error
// if reached end of sequence (and there was a split)
if ( readHandle_->endOfSequence() ) {
if ( ! seqIDIndex_ ) { // was that the last sequence ?
state_ = IN_MEMORY; // mark the cluster as IN_MEMORY
return TRUE;
}
if ( seqIDIndex_ == maxSeqIDIndex_ ) // if this was the first sequence
lastSqueezedBuffer_ = bufferPool_ ; // initialize
ex_assert( lastSqueezedBuffer_ == bufferPool_,
"Last squeezed buffer must be the first in the buffer pool");
// prepare for next sequence
--seqIDIndex_;
readHandle_->initCPB(); // start reading from begining of sequence
} // if ( readHandle_->endOfSequence() ) and there was a split
} // if ( completeCurrentRead_ )
// **** read several buffers ********
while ( TRUE ) { // there are more buffers to read
HashBuffer * newBuffer = NULL;
// are all previous I/Os still in flight, and we can not issue a new I/O ?
if ( IONotReady(rc, (UInt32) seqID_[seqIDIndex_]) )
return FALSE; // return to scheduler (or error)
if ( isInner_ ) { // get a buffer, or if can't then switch to hash-loop
// If this is not the first buffer, check if we're out of memory and
// need to switch to a Hash-Loop. For the first buffer the check is
// skipped, and we try and allocate that buffer.
if ( buffersRead_ ) {
// We need enough space for another buffer (we might need memory for
// two buffers, because we need one buffer for the outer cluster)
ULng32 requiredMem = clusterDb_->bufferSize_;
if ( getOuterCluster() && // avoid case of right join without an outer
! getOuterCluster()->bufferPool_ ) requiredMem *= 2 ;
// we also need memory to build the hash table for the rows already
// read plus the potential rows in the next buffer
requiredMem += getMemorySizeForHashTable(readCount_ +
bufferPool_ ? bufferPool_->getRowCount() : 0);
if ( !clusterDb_->enoughMemory(requiredMem)
// For debugging only !! Force HL after reading so many buffers
|| clusterDb_->forceHashLoopAfterNumBuffers_ == buffersRead_
)
// Not enough memory -- we have to use Hash-Loop for this cluster
return ( setHashLoop(rc) ); // return FALSE if no-mem error
} // if ( buffersRead_ )
newBuffer = new(collHeap(), FALSE) HashBuffer(this);
if ( !newBuffer || !newBuffer->getDataPointer() ) {
if ( ! buffersRead_ ) { // no buffers read yet -- can't even hash loop
*rc = EXE_NO_MEM_TO_EXEC;
return FALSE;
};
// reset rc in case it was set by the constructor of HashBuffer
*rc = EXE_OK;
state_ = IN_MEMORY; // mark the cluster as IN_MEMORY for the hash loop
// Inner and No memory ==> calls for a Hash Loop
return ( setHashLoop(rc) );
};
// we got a new buffer. Chain it into the bufferlist
newBuffer->setNext(bufferPool_);
bufferPool_ = newBuffer;
dataPtr = newBuffer->getDataPointer() ;
// if this cluster had a split, and reading its 2nd or 3rd sequence
// then only read a batch of buffers, not all at once
if ( seqIDIndex_ < maxSeqIDIndex_ ) {
if ( 0 == --batchCountDown_ ) { // only one more left in this batch
batchCountDown_ = clusterDb_->numReadOuterBatch_ ; // for next batch
// the next read would be the last for this batch
completeCurrentRead_ = TRUE ;
}
}
} // if ( isInner_ )
else { // *** outer ***
// if no more read buffers are available, then complete this batch
if ( nextBufferToRead_ == afterLastBufferToRead_ ) {
completeCurrentRead_ = TRUE;
return read(rc); // to also check if IO happened to complete
}
// only for the case of OLAP with "bounded following" -- need to
// continue cyclically to the first buffer in the list.
if ( NULL == nextBufferToRead_ ) {
ex_assert(firstBufferInList_,"first buffer not set for OLAP");
nextBufferToRead_ = firstBufferInList_;
}
dataPtr = nextBufferToRead_->getDataPointer() ;
nextBufferToRead_ = nextBufferToRead_->getNext();
}
// ****** ISSUE THE READ ********
readStatus = tempFile_->readThru( dataPtr ,
seqID_[seqIDIndex_],
readHandle_ );
if ( readStatus == SCRATCH_SUCCESS || readStatus == IO_NOT_COMPLETE ) {
// update counters; likely ahead of the actual read but that's OK
buffersRead_++;
readIOCnt_++;
clusterDb_->totalIOCnt_++;
if ( clusterDb_->hashOperStats_ ) clusterDb_->updateIOStats();
}
else { // probably SCRATCH_FAILURE
NABoolean realFailure = TRUE;
// check for a special case -- nothing was written to that sequence
// (e.g., when no more input came immediately after a cluster split)
// this case is benign -- just complete the read below.
SortError *sortError = tempFile_->getSortError();
if ( sortError && readHandle_->endOfSequence() )
realFailure = EInvScrBlockNum != - sortError->getSortError();
if ( realFailure ) {
*rc = EXE_SORT_ERROR;
return FALSE;
}
}
// At end of a sequence
if ( readHandle_->endOfSequence() ) {
if ( isInner_ ) {
ex_assert( maxSeqIDIndex_ /* split */ || readIOCnt_ == writeIOCnt_ ,
"Inner cluster did not read as many buffers as written!");
// in case we were in a hash-loop (and if split, the last sequence)
if ( ! seqIDIndex_ ) clusterDb_->hashLoop_ = FALSE ;
}
completeCurrentRead_ = TRUE;
}
if ( completeCurrentRead_ )
return read(rc); // to also check if IO happened to complete
} // WHILE ( TRUE )
};
//Wrapper function on read() to populate diags area.
//Returns: FALSE - either error, or need to call again
// TRUE -- flush is done
NABoolean Cluster::read(ComDiagsArea *&da, CollHeap *heap) {
ExeErrorCode rc = EXE_OK;
//read returning FALSE means either Error or IO_NOT_COMPLETE.
//if rc != EXE_OK then it is error.
if(!read(&rc)) {
if(rc != EXE_OK) {
if(da == NULL) {
da = ComDiagsArea::allocate(heap);
}
*da << DgSqlCode(-rc);
char msg[512];
if(rc == EXE_SORT_ERROR) {
char errorMsg[100];
Lng32 scratchError = 0;
Lng32 scratchSysError = 0;
Lng32 scratchSysErrorDetail = 0;
if(clusterDb_ != NULL) {
clusterDb_->getScratchErrorDetail(scratchError,
scratchSysError,
scratchSysErrorDetail,
errorMsg);
snprintf(msg, sizeof(msg), "Cluster::read Scratch IO Error occurred. Scratch Error: %d, System Error: %d, System Error Detail: %d, Details: %s",
scratchError, scratchSysError, scratchSysErrorDetail, errorMsg);
}
else {
snprintf(msg, sizeof(msg), "Cluster::read Scratch IO Error occurred. clusterDb_ is NULL" );
}
} else {
snprintf(msg, sizeof(msg), "Cluster::read Error occurred.");
}
*da << DgString0(msg);
}
return FALSE;
}
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// Return: FALSE - No split needed, or split was done successfully
// TRUE -- there was an error
NABoolean Cluster::checkAndSplit(ExeErrorCode * rc)
{
* rc = EXE_OK;
if ( ! isInner_ ||
bucketCount_ <= 1 ||
dontSplit_ ) return FALSE; // then do not split
// Check if a Cluster-Split is needed
// total memory needed == inner cluster + outer cluster buffer + hash table
Int64 requiredMem = totalClusterSize_ + clusterDb_->bufferSize_ +
getMemorySizeForHashTable(rowCount_);
if ( ( requiredMem <= clusterDb_->maxClusterSize_ // need more than max ?
|| clusterDb_->earlyOverflowStarted_ ) // can't tell max cluster size
&& ( ! clusterDb_->forceClusterSplitAfterMB_ // testing CQD was set ?
|| requiredMem <= clusterDb_->forceClusterSplitAfterMB_* ONE_MEG ))
return FALSE ; // split is not needed
// do not split if data is significantly skewed (i.e., mostly in 1 bucket)
for ( UInt32 ib = 0; ib < bucketCount_; ib++)
// does some single bucket hold more than %80 of the cluster's rows ?
if ( buckets_[ib].getRowCount() * 5 >= 4 * getRowCount() ) {
if ( clusterDb_->doLog_ ) { // report that skew
char msg[256];
sprintf(msg,
"Skewed data; no cluster split (%lu %lu). Cluster size " PF64 " ",
(ULong)this & 0x0FFF,
(ULong)clusterDb_ & 0x0FFF,
totalClusterSize_ );
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL,0,msg,clusterDb_->explainNodeId_);
}
dontSplit_ = TRUE;
return FALSE;
} // if more than %80
// Can not split if most recent (not full) buffer was kept in memory !
if ( bufferPool_->getRowCount() > 0 ) { // that was keepRecentBuffer_
// set the next buffer to be flushed to be that remaining kept buffer
nextBufferToFlush_ = bufferPool_ ;
// flush that last buffer (note: this is a recursive call!) and return
return ! flush(rc);
}
// the cluster has only half as many buckets left
bucketCount_ /= 2;
// now create a new cluster and chain it into the chain after the
// current cluster
next_ = new(collHeap(), FALSE) Cluster(Cluster::FLUSHED,
clusterDb_,
&buckets_[bucketCount_],
bucketCount_,
rowLength_,
useVariableLength_,
considerBufferDefrag_,
insertAtpIndex_,
isInner_,
bitMapEnable_,
next_,
rc);
if ( !next_ || (*rc != EXE_OK) ) {
if (EXE_OK == *rc) *rc = EXE_NO_MEM_TO_EXEC;
return TRUE;
}
// Update the number of rows in the current cluster: Subtract the rows
// taken by the new cluster.
rowCount_ -= next_->rowCount_ ;
// Calculate the total size of the new cluster based on the ratio of
// rows in the new cluster to total rows. Assume that the ratio of
// rows will reflect the ratio of total size.
next_->totalClusterSize_ =
(next_->rowCount_/(rowCount_ + next_->rowCount_)) * totalClusterSize_;
// Update the total size of the current cluster: subtract the new's size
totalClusterSize_ -= next_->totalClusterSize_ ;
// and add the size of the current buffer (which was flushed and now is empty)
totalClusterSize_ += clusterDb_->bufferSize_;
numInMemBuffers_ = 1; // only 1 in-memory buffer now
// Allocate a buffer for the new cluster. This allocation happens
// unconditionally, i.e., we don't care if there is enough memory.
HashBuffer * newBuffer = new(collHeap(), FALSE) HashBuffer(next_);
if (!newBuffer || !newBuffer->getDataPointer() ) {
if (newBuffer) delete newBuffer;
*rc = EXE_NO_MEM_TO_EXEC;
return TRUE;
};
next_->bufferPool_ = newBuffer;
next_->numInMemBuffers_ = 1; // only 1 in-memory buffer
// and add the size of the new buffer
next_->totalClusterSize_ += clusterDb_->bufferSize_;
//
// Now set the overflow sequences, for both clusters
//
// Update the new cluster to have the same previous sequences as the current
for ( next_->seqIDIndex_ = 0 ;
next_->seqIDIndex_ <= seqIDIndex_ ;
next_->seqIDIndex_++ )
next_->seqID_[next_->seqIDIndex_] = seqID_[next_->seqIDIndex_] ;
next_->maxSeqIDIndex_ = next_->seqIDIndex_ ; // update the max idx
// A new sequence for the new cluster
next_->seqID_[next_->seqIDIndex_] = clusterDb_->generateSequenceID();
// start a new sequence for the current cluster
maxSeqIDIndex_ = ++seqIDIndex_ ; // increment, and update the max
seqID_[seqIDIndex_] = clusterDb_->generateSequenceID();
// Just in case the new cluster gets no more rows, initialize its scratch
if ( next_->initScratch(rc) ) return TRUE;
if ( clusterDb_->doLog_ ) { // report that a split happened
char msg[256];
sprintf(msg,
"Cluster-Split: New/old (%lu/%lu %lu): sizes " PF64 "/" PF64 " rowCount %u/%u seqIDindex %hu",
(ULong)next_ & 0x0FFF,
(ULong)this & 0x0FFF,
(ULong)clusterDb_ & 0x0FFF,
next_->totalClusterSize_, totalClusterSize_,
next_->rowCount_, rowCount_,
seqIDIndex_ );
// log an EMS event and continue
SQLMXLoggingArea::logExecRtInfo(NULL,0,msg,clusterDb_->explainNodeId_);
}
if ( clusterDb_->hashOperStats_ && clusterDb_->hashOperStats_->castToExHashJoinStats() ) // keep stats about splits (HJ only)
((ExHashJoinStats*)clusterDb_->hashOperStats_)->incrClusterSplits();
return FALSE;
};
/////////////////////////////////////////////////////////////////////////////
NABoolean Cluster::chain(NABoolean forceChaining, ExeErrorCode * rc) {
// assume success
*rc = EXE_OK;
// we can only chain clusters in memory
ex_assert((state_ == Cluster::IN_MEMORY),
"tried to chain a unchainable cluster");
// if we can't get enough space for the hash table, don't chain
// the hash table has rowCount_ * 1.5 entries.
// if we have a readCount_, we are in a hash loop, thus, we don't
// allocate hash chain headers for all row in the inner table
// (rowCount_). Instead, we use readCount_ which tells us how many
// rows we have read in this loop.
ULng32 hashTableEntryCount = ( readCount_ ? readCount_ : rowCount_ );
hashTable_ = createHashTable( getMemorySizeForHashTable(hashTableEntryCount),
rc,
! forceChaining ); // force? -> no mem check
if (!hashTable_) return FALSE;
HashBuffer *hb = bufferPool_;
// If performing a CROSS_PRODUCT operation, reverse the list of
// buffers to keep the rows in order.
if (clusterDb_->hashOperator_ == ClusterDB::CROSS_PRODUCT && hb != NULL) {
HashBuffer *revList = hb;
hb = hb->getNext();
revList->setNext(NULL);
while(hb) {
HashBuffer *next = hb->getNext();
hb->setNext(revList);
revList = hb;
hb = next;
}
hb = revList;
}
// scan through all the rows in the bufferPool_ and chain them into the HT
tupp tupp1 =clusterDb_->workAtp_->getTupp(clusterDb_->hashTableRowAtpIndex1_);
tupp tupp2 =clusterDb_->workAtp_->getTupp(clusterDb_->hashTableRowAtpIndex2_);
while (hb) {
hb->castToSerial()->fixup();
HashRow *dataPointer = hb->castToSerial()->getFirstRow();
for ( ULng32 rowIndex = 0 ;
rowIndex < hb->getRowCount() ;
rowIndex++)
{
if (clusterDb_->hashOperator_ == ClusterDB::CROSS_PRODUCT) {
hashTable_->insertSingleChain(dataPointer);
} else {
// insert row into hash table
hashTable_->insert(clusterDb_->workAtp_,
dataPointer,
tupp1,
tupp2,
clusterDb_->searchExpr_);
}
dataPointer = hb->castToSerial()->getNextRow(dataPointer);
}
hb = hb->getNext();
} // while (hb)
// the cluster is chained now
state_ = CHAINED;
return TRUE;
};
/////////////////////////////////////////////////////////////////////////////
ExeErrorCode Cluster::setUpOuter(ULng32 rowLength,
short atpIndex,
NABoolean bitMapEnable) {
// assume success
ExeErrorCode rc = EXE_OK;
ex_assert(state_ == FLUSHED, "Only a FLUSHED inner cluster gets an outer");
ex_assert(isInner_, "can't set up outer Cluster for an outer Cluster");
ex_assert(bufferPool_->getNext() == NULL, "cluster has too many buffers");
ex_assert(!bufferPool_->getRowCount(), "empty buffer has positive rowCount");
// when the last buffer in the cluster is flushed, bufferPool_ is empty
// but it still counts as part of totalClusterSize_. so we need to subtract
// the empty buffer.
totalClusterSize_ -= clusterDb_->bufferSize_;
// the inner cluster is flushed and contains rows (all rows on temporary
// file). We need an outer cluster for it.
Cluster * oCluster = new(collHeap(), FALSE) Cluster(FLUSHED,
clusterDb_,
buckets_,
bucketCount_,
rowLength,
useVariableLength_,
considerBufferDefrag_,
atpIndex,
FALSE, // outer cluster
bitMapEnable,
NULL, // no next ptr
&rc,
bufferPool_);
if (!oCluster) return EXE_NO_MEM_TO_EXEC;
if (rc) return rc;
bufferPool_ = NULL;
for (ULng32 i = 0; i < bucketCount_; i++)
buckets_[i].setOuterCluster(oCluster);
return rc;
};
/////////////////////////////////////////////////////////////////////////////
void Cluster::resetForHashLoop() {
numLoops_++; // finished another iteration
if ( clusterDb_->hashOperStats_ && clusterDb_->hashOperStats_->castToExHashJoinStats()) // keep stats about hash loops (HJ only)
((ExHashJoinStats*)clusterDb_->hashOperStats_)->incrHashLoops();
// delete all buffers of the inner cluster. It would be nice
// to keep one buffer, but Cluster::read() always allocates a buffer
// for inner, i.e. it is not aware of this special case.
releaseAllHashBuffers();
// reset the readCount_ of the inner cluster. This is used to
// determine the size of the hash table in a hash loop.
readCount_ = 0;
// clear lastSqueezedBuffer_ after each hash loop
lastSqueezedBuffer_ = NULL;
// remove the hash table
removeHashTable();
completeCurrentRead_ = FALSE; // Beginning of a loop is like a new cluster
state_ = FLUSHED; // now the cluster is not IN_MEMORY
buffersRead_ = 0;
// get the outer cluster
Cluster * oCluster = getOuterCluster();
if ( oCluster ) { // if not a right HJ with an empty outer
// reset the outer cluster so that it is read again
oCluster->readCount_ = 0;
// reset the file position
oCluster->readHandle_->initCPB();
}
// we don't release the buffer of the outer, since we need it
};
/////////////////////////////////////////////////////////////////////////////
ExClusterStats* Cluster::getStats(CollHeap* heap) {
ExStatsCounter hashChains;
if (hashTable_)
for (ULng32 i = 0; i < hashTable_->getHeaderCount(); i++) {
ULng32 value = hashTable_->getChainSize(i);
if (value != 0)
hashChains.addEntry(value);
};
ExClusterStats* stats = new(heap)ExClusterStats(isInner_,
bucketCount_,
rowCount_,
totalClusterSize_,
hashChains,
writeIOCnt_,
readIOCnt_);
return stats;
};
/////////////////////////////////////////////////////////////////////////////
void Cluster::releaseAllHashBuffers() {
// release all hashbuffers of this cluster
while (bufferPool_)
delete bufferPool_;
bufferPool_ = NULL;
};
/////////////////////////////////////////////////////////////////////////////
// get the next row in main memory
HashRow * Cluster::advance() {
ex_assert(scanPosition_, "tried to advance on a non-existent hash buffer");
HashRow * dataPointer = scanPosition_->castToSerial()->getCurrentRowAndAdvance();
// If finished this outer buffer, try the next buffer in the list
if ( !dataPointer && scanPosition_->getNext()
&& scanPosition_->getNext()->getRowCount() ) {
scanPosition_ = scanPosition_->getNext();
scanPosition_->castToSerial()->positionOnFirstRow();
dataPointer = scanPosition_->castToSerial()->getCurrentRowAndAdvance();
};
return dataPointer;
};
HashRow * Cluster::getCurrentRow() {
ex_assert(scanPosition_, "tried to advance on a non-existent hash buffer");
HashRow * dataPointer = scanPosition_->castToSerial()->getCurrentRow();
if ( !dataPointer && scanPosition_->getNext()
&& scanPosition_->getNext()->getRowCount() ) {
scanPosition_ = scanPosition_->getNext();
scanPosition_->castToSerial()->positionOnFirstRow();
dataPointer = scanPosition_->castToSerial()->getCurrentRow();
};
return dataPointer;
};
ULng32 Cluster::getMemorySizeForHashTable(ULng32 entryCount)
{
// see constraints in hash_table.h
entryCount = MINOF(entryCount, MAX_HEADER_COUNT);
entryCount = MAXOF(entryCount, MIN_HEADER_COUNT); // just a sanity
// + %50 for hash chains
return (entryCount * sizeof(HashTableHeader) * 3 / 2);
}
void Cluster::updateBitMap() {
ex_assert(outerBitMap_, "no bitmap to update");
outerBitMap_->setBit(readCount_);
};
NABoolean Cluster::testBitMap() {
ex_assert(outerBitMap_, "no bitmap to test");
return (outerBitMap_->testBit(readCount_));
};
#include "ComCextdecs.h"
void IOTimer::resetTimer()
{
ioStarted_ = FALSE;
accumTime_ = 0;
};
NABoolean IOTimer::startTimer()
{
if (ioStarted_)
return FALSE;
else
{
startTime_ = NA_JulianTimestamp();
ioStarted_ = TRUE;
return TRUE;
}
};
Int64 IOTimer::endTimer()
{
if (ioStarted_)
{
ioStarted_ = FALSE;
accumTime_ += NA_JulianTimestamp() - startTime_;
}
return accumTime_;
};
void ClusterDB::getScratchErrorDetail(Lng32 &scratchError,
Lng32 &scratchSysError,
Lng32 &scratchSysErrorDetail,
char *errorMsg)
{
SortError *sError = NULL;
if(tempFile_)
sError = tempFile_->getSortError();
if(sError)
{
scratchError = (Lng32)sError->getSortError();
scratchSysError = (Lng32)sError->getSysError();
scratchSysErrorDetail = (Lng32)sError->getErrorDetail();
strcpy(errorMsg, sError->getSortErrorMsg());
}
}
// Every time totalIOCnt_ grows, update the stats for this operator
void ClusterDB::updateIOStats()
{
Int64 ioSize = (Int64) bufferSize_ * (Int64) totalIOCnt_ ;
if (hashOperStats_->castToExHashGroupByStats())
hashOperStats_->castToExHashGroupByStats()->updIoSize(ioSize);
else
if (hashOperStats_->castToExHashJoinStats())
hashOperStats_->castToExHashJoinStats()->updIoSize(ioSize);
}
// Every time memoryUsed_ grows, update the stats for max memory used by this operator
void ClusterDB::updateMemoryStats()
{
if (hashOperStats_->castToExHashGroupByStats())
hashOperStats_->castToExHashGroupByStats()->updMemorySize(memoryUsed_);
else
if (hashOperStats_->castToExHashJoinStats())
hashOperStats_->castToExHashJoinStats()->updMemorySize(memoryUsed_);
}
| 35.541783 | 154 | 0.638906 | CoderSong2015 |
e986e6e516b91e5a862174b3c1cfefcddd86ebfd | 625 | cpp | C++ | ims/src/v2/model/BatchAddOrDeleteTagsResponse.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 5 | 2021-03-03T08:23:43.000Z | 2022-02-16T02:16:39.000Z | ims/src/v2/model/BatchAddOrDeleteTagsResponse.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | null | null | null | ims/src/v2/model/BatchAddOrDeleteTagsResponse.cpp | yangzhaofeng/huaweicloud-sdk-cpp-v3 | 4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23 | [
"Apache-2.0"
] | 7 | 2021-02-26T13:53:35.000Z | 2022-03-18T02:36:43.000Z |
#include "huaweicloud/ims/v2/model/BatchAddOrDeleteTagsResponse.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Ims {
namespace V2 {
namespace Model {
BatchAddOrDeleteTagsResponse::BatchAddOrDeleteTagsResponse()
{
}
BatchAddOrDeleteTagsResponse::~BatchAddOrDeleteTagsResponse() = default;
void BatchAddOrDeleteTagsResponse::validate()
{
}
web::json::value BatchAddOrDeleteTagsResponse::toJson() const
{
web::json::value val = web::json::value::object();
return val;
}
bool BatchAddOrDeleteTagsResponse::fromJson(const web::json::value& val)
{
bool ok = true;
return ok;
}
}
}
}
}
}
| 13.297872 | 72 | 0.7296 | yangzhaofeng |
e99118ff9f0ba42e66e1309f734c6140d8c1e89c | 481 | hpp | C++ | Engine/src/Engpch.hpp | Niels04/Engine | 2bc0f8d65ffb0f29035edc16958c60826da7f535 | [
"Apache-2.0"
] | null | null | null | Engine/src/Engpch.hpp | Niels04/Engine | 2bc0f8d65ffb0f29035edc16958c60826da7f535 | [
"Apache-2.0"
] | null | null | null | Engine/src/Engpch.hpp | Niels04/Engine | 2bc0f8d65ffb0f29035edc16958c60826da7f535 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <iostream>
#include <utility>
#include <functional>
#include <memory>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <sstream>
#include <fstream>
#include <charconv>
#include <stdarg.h>
#include "Engine/Log.hpp"
#include "Engine/datatypes/include.hpp"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#ifdef ENG_PLATFORM_WINDOWS
#include <windows.h>
#endif | 18.5 | 39 | 0.752599 | Niels04 |
e9911a14829fb3f0971ba2f42b74ada70355319b | 542 | cpp | C++ | dmoj/ecoo/13r1p1-take-a-number.cpp | ruar18/competitive-programming | f264675fab92bf27dce184dd65eb81e302381f96 | [
"MIT"
] | null | null | null | dmoj/ecoo/13r1p1-take-a-number.cpp | ruar18/competitive-programming | f264675fab92bf27dce184dd65eb81e302381f96 | [
"MIT"
] | null | null | null | dmoj/ecoo/13r1p1-take-a-number.cpp | ruar18/competitive-programming | f264675fab92bf27dce184dd65eb81e302381f96 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int N;
cin >> N;
string a;
cin >> a;
int late = 0, served = 0, nextN = N;
while(a != "EOF")
{
if(a == "TAKE")
{
nextN = nextN == 999? 1 : nextN+1;
late++;
}
else if(a == "SERVE")
{
served++;
}
else if(a == "CLOSE")
{
printf("%d %d %d\n", late, late-served, nextN);
late = served = 0;
}
cin >> a;
}
return 0;
} | 17.483871 | 59 | 0.369004 | ruar18 |
e994016064ae4dbd0beb089a5c48321369715214 | 5,975 | cpp | C++ | src/chapter_12_networking_and_services/imap_connection.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | src/chapter_12_networking_and_services/imap_connection.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | src/chapter_12_networking_and_services/imap_connection.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | #include "Chapter12_NetworkingAndServices/ImapConnection.h"
#include "curlcpp/master/include/curl_easy.h"
#include <algorithm> // transform
#include <boost/algorithm/string.hpp>
#include <iostream> // cout
#include <iterator> // back_inserter
#include <optional>
#include <regex> // regex_match, smatch, sregex_iterator
#include <sstream> // istringstream, ostringstream
#include <string> // getline, stoull
#include <string_view>
#include <unordered_map>
#include <vector>
namespace rtc::imap
{
void imap_connection::setup_easy(curl::curl_easy& easy) const
{
easy.add<CURLOPT_PORT>(email_server_port);
easy.add<CURLOPT_USERNAME>(username_.c_str());
easy.add<CURLOPT_PASSWORD>(password_.c_str());
easy.add<CURLOPT_USE_SSL>(CURLUSESSL_ALL);
easy.add<CURLOPT_SSL_VERIFYPEER>(0L);
easy.add<CURLOPT_SSL_VERIFYHOST>(0L);
easy.add<CURLOPT_USERAGENT>("libcurl-agent/1.0");
}
[[nodiscard]] auto imap_connection::parse_get_mailbox_folders_response(const std::string& response) const -> std::vector<std::string>
{
std::vector<std::string> ret{};
std::istringstream iss{ response };
std::string line{};
std::smatch matches{};
const std::regex pattern{ R"(\* LIST \([^\)]+\) \"[^"]+\" \"([^\\]+)\".*)" };
while (std::getline(iss, line))
{
boost::algorithm::trim_right(line);
if (std::regex_match(line, matches, pattern))
{
ret.push_back(matches[1]);
}
}
return ret;
}
[[nodiscard]] auto imap_connection::parse_get_unread_email_ids_response(std::string response) const -> std::vector<std::size_t>
{
std::vector<std::size_t> ret{};
std::smatch matches{};
boost::algorithm::trim_right(response);
const std::regex response_pattern{ R"(\* SEARCH(?: \d+)+)" };
if (std::regex_match(response, matches, response_pattern))
{
const std::regex id_pattern{ R"(\d+)" };
std::transform(
std::sregex_iterator{ std::cbegin(response), std::cend(response), id_pattern },
std::sregex_iterator{},
std::back_inserter(ret),
[](const std::smatch match) { return static_cast<size_t>(std::stoull(match.str())); }
);
}
return ret;
}
[[nodiscard]] auto imap_connection::parse_email_subject(const std::string& email) const -> std::optional<std::string>
{
std::optional<std::string> ret{};
std::istringstream iss{ email };
std::string line{};
std::smatch matches{};
const std::regex pattern{ R"(^Subject: .*$)" };
while (std::getline(iss, line))
{
boost::algorithm::trim_right(line);
if (std::regex_match(line, matches, pattern))
{
ret = matches[0].str();
break;
}
}
return ret;
}
imap_connection::imap_connection(email_server_provider_t provider, std::string_view username, std::string_view password)
: provider_{ provider }
, url_{ email_server_provider_to_url.at(provider_) }
, username_{ username }
, password_{ password }
{}
[[nodiscard]] auto imap_connection::get_mailbox_folders() const -> std::optional<std::vector<std::string>>
{
std::optional<std::vector<std::string>> ret{};
try
{
std::ostringstream oss{};
curl::curl_ios<std::ostringstream> writer{ oss };
curl::curl_easy easy{ writer };
setup_easy(easy);
easy.add<CURLOPT_URL>(url_.c_str());
easy.perform();
ret = parse_get_mailbox_folders_response(oss.str());
}
catch (const curl::curl_easy_exception& ex) {
std::cout << "\tError: " << ex.what() << "\n";
}
return ret;
}
[[nodiscard]] auto imap_connection::get_unread_email_ids(std::string_view folder) const -> std::optional<std::vector<size_t>>
{
std::optional<std::vector<size_t>> ret{};
try
{
std::ostringstream oss{};
curl::curl_ios<std::ostringstream> writer{ oss };
curl::curl_easy easy{ writer };
setup_easy(easy);
std::ostringstream url_oss{};
url_oss << url_ << "/" << folder.data() << "/";
easy.add<CURLOPT_URL>(url_oss.str().c_str());
easy.add<CURLOPT_CUSTOMREQUEST>("SEARCH UNSEEN");
easy.perform();
ret = parse_get_unread_email_ids_response(oss.str());
}
catch (const curl::curl_easy_exception& ex) {
std::cout << "\tError: " << ex.what() << "\n";
}
return ret;
}
[[nodiscard]] auto imap_connection::get_email(std::string_view folder, size_t id) const -> std::optional<std::string>
{
std::optional<std::string> ret{};
try
{
std::ostringstream oss{};
curl::curl_ios<std::ostringstream> writer{ oss };
curl::curl_easy easy{ writer };
setup_easy(easy);
std::ostringstream url_oss{};
url_oss << url_ << "/" << folder.data() << "/;UID=" << id;
easy.add<CURLOPT_URL>(url_oss.str().c_str());
easy.perform();
ret = oss.str();
}
catch (const curl::curl_easy_exception& ex) {
std::cout << "\tError: " << ex.what() << "\n";
}
return ret;
}
[[nodiscard]] auto imap_connection::get_email_subject(std::string_view folder, size_t id) const -> std::optional<std::string>
{
std::optional<std::string> ret{};
auto email_opt{ get_email(folder, id) };
if (email_opt.has_value()) {
ret = parse_email_subject(email_opt.value());
}
return ret;
}
} // namespace rtc::imap
| 34.142857 | 137 | 0.567029 | rturrado |
e99406905a708a47b303ff1f7363b44ab92bfab5 | 17,508 | cpp | C++ | av/media/libstagefright/OMXClient.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 10 | 2020-04-17T04:02:36.000Z | 2021-11-23T11:38:42.000Z | av/media/libstagefright/OMXClient.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 3 | 2020-02-19T16:53:25.000Z | 2021-04-29T07:28:40.000Z | av/media/libstagefright/OMXClient.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 5 | 2019-12-25T04:05:02.000Z | 2022-01-14T16:57:55.000Z | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "OMXClient"
#ifdef __LP64__
#define OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS
#endif
#include <utils/Log.h>
#include <binder/IServiceManager.h>
#include <media/IMediaPlayerService.h>
#include <media/IMediaCodecService.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/OMXClient.h>
#include <cutils/properties.h>
#include <utils/KeyedVector.h>
#include "include/OMX.h"
namespace android {
static bool sCodecProcessEnabled = true;
struct MuxOMX : public IOMX {
MuxOMX(const sp<IOMX> &mediaServerOMX, const sp<IOMX> &mediaCodecOMX);
virtual ~MuxOMX();
// Nobody should be calling this. In case someone does anyway, just
// return the media server IOMX.
// TODO: return NULL
virtual IBinder *onAsBinder() {
ALOGE("MuxOMX::onAsBinder should not be called");
return IInterface::asBinder(mMediaServerOMX).get();
}
virtual bool livesLocally(node_id node, pid_t pid);
virtual status_t listNodes(List<ComponentInfo> *list);
virtual status_t allocateNode(
const char *name, const sp<IOMXObserver> &observer,
sp<IBinder> *nodeBinder,
node_id *node);
virtual status_t freeNode(node_id node);
virtual status_t sendCommand(
node_id node, OMX_COMMANDTYPE cmd, OMX_S32 param);
virtual status_t getParameter(
node_id node, OMX_INDEXTYPE index,
void *params, size_t size);
virtual status_t setParameter(
node_id node, OMX_INDEXTYPE index,
const void *params, size_t size);
virtual status_t getConfig(
node_id node, OMX_INDEXTYPE index,
void *params, size_t size);
virtual status_t setConfig(
node_id node, OMX_INDEXTYPE index,
const void *params, size_t size);
virtual status_t getState(
node_id node, OMX_STATETYPE* state);
virtual status_t storeMetaDataInBuffers(
node_id node, OMX_U32 port_index, OMX_BOOL enable, MetadataBufferType *type);
virtual status_t prepareForAdaptivePlayback(
node_id node, OMX_U32 port_index, OMX_BOOL enable,
OMX_U32 maxFrameWidth, OMX_U32 maxFrameHeight);
virtual status_t configureVideoTunnelMode(
node_id node, OMX_U32 portIndex, OMX_BOOL tunneled,
OMX_U32 audioHwSync, native_handle_t **sidebandHandle);
virtual status_t enableNativeBuffers(
node_id node, OMX_U32 port_index, OMX_BOOL graphic, OMX_BOOL enable);
virtual status_t getGraphicBufferUsage(
node_id node, OMX_U32 port_index, OMX_U32* usage);
virtual status_t useBuffer(
node_id node, OMX_U32 port_index, const sp<IMemory> ¶ms,
buffer_id *buffer, OMX_U32 allottedSize);
virtual status_t useGraphicBuffer(
node_id node, OMX_U32 port_index,
const sp<GraphicBuffer> &graphicBuffer, buffer_id *buffer);
virtual status_t updateGraphicBufferInMeta(
node_id node, OMX_U32 port_index,
const sp<GraphicBuffer> &graphicBuffer, buffer_id buffer);
virtual status_t updateNativeHandleInMeta(
node_id node, OMX_U32 port_index,
const sp<NativeHandle> &nativeHandle, buffer_id buffer);
virtual status_t createInputSurface(
node_id node, OMX_U32 port_index, android_dataspace dataSpace,
sp<IGraphicBufferProducer> *bufferProducer, MetadataBufferType *type);
virtual status_t createPersistentInputSurface(
sp<IGraphicBufferProducer> *bufferProducer,
sp<IGraphicBufferConsumer> *bufferConsumer);
virtual status_t setInputSurface(
node_id node, OMX_U32 port_index,
const sp<IGraphicBufferConsumer> &bufferConsumer, MetadataBufferType *type);
virtual status_t signalEndOfInputStream(node_id node);
virtual status_t allocateSecureBuffer(
node_id node, OMX_U32 port_index, size_t size,
buffer_id *buffer, void **buffer_data, sp<NativeHandle> *native_handle);
virtual status_t allocateBufferWithBackup(
node_id node, OMX_U32 port_index, const sp<IMemory> ¶ms,
buffer_id *buffer, OMX_U32 allottedSize);
virtual status_t freeBuffer(
node_id node, OMX_U32 port_index, buffer_id buffer);
virtual status_t fillBuffer(node_id node, buffer_id buffer, int fenceFd);
virtual status_t emptyBuffer(
node_id node,
buffer_id buffer,
OMX_U32 range_offset, OMX_U32 range_length,
OMX_U32 flags, OMX_TICKS timestamp, int fenceFd);
virtual status_t getExtensionIndex(
node_id node,
const char *parameter_name,
OMX_INDEXTYPE *index);
virtual status_t setInternalOption(
node_id node,
OMX_U32 port_index,
InternalOptionType type,
const void *data,
size_t size);
private:
mutable Mutex mLock;
sp<IOMX> mMediaServerOMX;
sp<IOMX> mMediaCodecOMX;
sp<IOMX> mLocalOMX;
typedef enum {
LOCAL,
MEDIAPROCESS,
CODECPROCESS
} node_location;
KeyedVector<node_id, node_location> mNodeLocation;
bool isLocalNode(node_id node) const;
bool isLocalNode_l(node_id node) const;
const sp<IOMX> &getOMX(node_id node) const;
const sp<IOMX> &getOMX_l(node_id node) const;
static node_location getPreferredCodecLocation(const char *name);
DISALLOW_EVIL_CONSTRUCTORS(MuxOMX);
};
MuxOMX::MuxOMX(const sp<IOMX> &mediaServerOMX, const sp<IOMX> &mediaCodecOMX)
: mMediaServerOMX(mediaServerOMX),
mMediaCodecOMX(mediaCodecOMX) {
ALOGI("MuxOMX ctor");
}
MuxOMX::~MuxOMX() {
}
bool MuxOMX::isLocalNode(node_id node) const {
Mutex::Autolock autoLock(mLock);
return isLocalNode_l(node);
}
bool MuxOMX::isLocalNode_l(node_id node) const {
return mNodeLocation.valueFor(node) == LOCAL;
}
// static
MuxOMX::node_location MuxOMX::getPreferredCodecLocation(const char *name) {
if (sCodecProcessEnabled) {
// all codecs go to codec process unless excluded using system property, in which case
// all non-secure decoders, OMX.google.* codecs and encoders can go in the codec process
// (non-OMX.google.* encoders can be excluded using system property.)
if ((strcasestr(name, "decoder")
&& strcasestr(name, ".secure") != name + strlen(name) - 7)
|| (strcasestr(name, "encoder")
&& !property_get_bool("media.stagefright.legacyencoder", false))
|| !property_get_bool("media.stagefright.less-secure", false)
|| !strncasecmp(name, "OMX.google.", 11)) {
return CODECPROCESS;
}
// everything else runs in the media server
return MEDIAPROCESS;
} else {
#ifdef __LP64__
// 64 bit processes always run OMX remote on MediaServer
return MEDIAPROCESS;
#else
// 32 bit processes run only OMX.google.* components locally
if (!strncasecmp(name, "OMX.google.", 11)) {
return LOCAL;
}
return MEDIAPROCESS;
#endif
}
}
const sp<IOMX> &MuxOMX::getOMX(node_id node) const {
Mutex::Autolock autoLock(mLock);
return getOMX_l(node);
}
const sp<IOMX> &MuxOMX::getOMX_l(node_id node) const {
node_location loc = mNodeLocation.valueFor(node);
if (loc == LOCAL) {
return mLocalOMX;
} else if (loc == MEDIAPROCESS) {
return mMediaServerOMX;
} else if (loc == CODECPROCESS) {
return mMediaCodecOMX;
}
ALOGE("Couldn't determine node location for node %d: %d, using local", node, loc);
return mLocalOMX;
}
bool MuxOMX::livesLocally(node_id node, pid_t pid) {
return getOMX(node)->livesLocally(node, pid);
}
status_t MuxOMX::listNodes(List<ComponentInfo> *list) {
Mutex::Autolock autoLock(mLock);
if (mLocalOMX == NULL) {
mLocalOMX = new OMX;
}
return mLocalOMX->listNodes(list);
}
status_t MuxOMX::allocateNode(
const char *name, const sp<IOMXObserver> &observer,
sp<IBinder> *nodeBinder,
node_id *node) {
Mutex::Autolock autoLock(mLock);
sp<IOMX> omx;
node_location loc = getPreferredCodecLocation(name);
if (loc == CODECPROCESS) {
omx = mMediaCodecOMX;
} else if (loc == MEDIAPROCESS) {
omx = mMediaServerOMX;
} else {
if (mLocalOMX == NULL) {
mLocalOMX = new OMX;
}
omx = mLocalOMX;
}
status_t err = omx->allocateNode(name, observer, nodeBinder, node);
ALOGV("allocated node_id %x on %s OMX", *node, omx == mMediaCodecOMX ? "codecprocess" :
omx == mMediaServerOMX ? "mediaserver" : "local");
if (err != OK) {
return err;
}
mNodeLocation.add(*node, loc);
return OK;
}
status_t MuxOMX::freeNode(node_id node) {
Mutex::Autolock autoLock(mLock);
status_t err = getOMX_l(node)->freeNode(node);
if (err != OK) {
return err;
}
mNodeLocation.removeItem(node);
return OK;
}
status_t MuxOMX::sendCommand(
node_id node, OMX_COMMANDTYPE cmd, OMX_S32 param) {
return getOMX(node)->sendCommand(node, cmd, param);
}
status_t MuxOMX::getParameter(
node_id node, OMX_INDEXTYPE index,
void *params, size_t size) {
return getOMX(node)->getParameter(node, index, params, size);
}
status_t MuxOMX::setParameter(
node_id node, OMX_INDEXTYPE index,
const void *params, size_t size) {
return getOMX(node)->setParameter(node, index, params, size);
}
status_t MuxOMX::getConfig(
node_id node, OMX_INDEXTYPE index,
void *params, size_t size) {
return getOMX(node)->getConfig(node, index, params, size);
}
status_t MuxOMX::setConfig(
node_id node, OMX_INDEXTYPE index,
const void *params, size_t size) {
return getOMX(node)->setConfig(node, index, params, size);
}
status_t MuxOMX::getState(
node_id node, OMX_STATETYPE* state) {
return getOMX(node)->getState(node, state);
}
status_t MuxOMX::storeMetaDataInBuffers(
node_id node, OMX_U32 port_index, OMX_BOOL enable, MetadataBufferType *type) {
return getOMX(node)->storeMetaDataInBuffers(node, port_index, enable, type);
}
status_t MuxOMX::prepareForAdaptivePlayback(
node_id node, OMX_U32 port_index, OMX_BOOL enable,
OMX_U32 maxFrameWidth, OMX_U32 maxFrameHeight) {
return getOMX(node)->prepareForAdaptivePlayback(
node, port_index, enable, maxFrameWidth, maxFrameHeight);
}
status_t MuxOMX::configureVideoTunnelMode(
node_id node, OMX_U32 portIndex, OMX_BOOL enable,
OMX_U32 audioHwSync, native_handle_t **sidebandHandle) {
return getOMX(node)->configureVideoTunnelMode(
node, portIndex, enable, audioHwSync, sidebandHandle);
}
status_t MuxOMX::enableNativeBuffers(
node_id node, OMX_U32 port_index, OMX_BOOL graphic, OMX_BOOL enable) {
return getOMX(node)->enableNativeBuffers(node, port_index, graphic, enable);
}
status_t MuxOMX::getGraphicBufferUsage(
node_id node, OMX_U32 port_index, OMX_U32* usage) {
return getOMX(node)->getGraphicBufferUsage(node, port_index, usage);
}
status_t MuxOMX::useBuffer(
node_id node, OMX_U32 port_index, const sp<IMemory> ¶ms,
buffer_id *buffer, OMX_U32 allottedSize) {
return getOMX(node)->useBuffer(node, port_index, params, buffer, allottedSize);
}
status_t MuxOMX::useGraphicBuffer(
node_id node, OMX_U32 port_index,
const sp<GraphicBuffer> &graphicBuffer, buffer_id *buffer) {
return getOMX(node)->useGraphicBuffer(
node, port_index, graphicBuffer, buffer);
}
status_t MuxOMX::updateGraphicBufferInMeta(
node_id node, OMX_U32 port_index,
const sp<GraphicBuffer> &graphicBuffer, buffer_id buffer) {
return getOMX(node)->updateGraphicBufferInMeta(
node, port_index, graphicBuffer, buffer);
}
status_t MuxOMX::updateNativeHandleInMeta(
node_id node, OMX_U32 port_index,
const sp<NativeHandle> &nativeHandle, buffer_id buffer) {
return getOMX(node)->updateNativeHandleInMeta(
node, port_index, nativeHandle, buffer);
}
status_t MuxOMX::createInputSurface(
node_id node, OMX_U32 port_index, android_dataspace dataSpace,
sp<IGraphicBufferProducer> *bufferProducer, MetadataBufferType *type) {
status_t err = getOMX(node)->createInputSurface(
node, port_index, dataSpace, bufferProducer, type);
return err;
}
status_t MuxOMX::createPersistentInputSurface(
sp<IGraphicBufferProducer> *bufferProducer,
sp<IGraphicBufferConsumer> *bufferConsumer) {
sp<IOMX> omx;
{
Mutex::Autolock autoLock(mLock);
if (property_get_bool("media.stagefright.legacyencoder", false)) {
omx = mMediaServerOMX;
} else {
omx = mMediaCodecOMX;
}
}
return omx->createPersistentInputSurface(
bufferProducer, bufferConsumer);
}
status_t MuxOMX::setInputSurface(
node_id node, OMX_U32 port_index,
const sp<IGraphicBufferConsumer> &bufferConsumer, MetadataBufferType *type) {
return getOMX(node)->setInputSurface(node, port_index, bufferConsumer, type);
}
status_t MuxOMX::signalEndOfInputStream(node_id node) {
return getOMX(node)->signalEndOfInputStream(node);
}
status_t MuxOMX::allocateSecureBuffer(
node_id node, OMX_U32 port_index, size_t size,
buffer_id *buffer, void **buffer_data, sp<NativeHandle> *native_handle) {
return getOMX(node)->allocateSecureBuffer(
node, port_index, size, buffer, buffer_data, native_handle);
}
status_t MuxOMX::allocateBufferWithBackup(
node_id node, OMX_U32 port_index, const sp<IMemory> ¶ms,
buffer_id *buffer, OMX_U32 allottedSize) {
return getOMX(node)->allocateBufferWithBackup(
node, port_index, params, buffer, allottedSize);
}
status_t MuxOMX::freeBuffer(
node_id node, OMX_U32 port_index, buffer_id buffer) {
return getOMX(node)->freeBuffer(node, port_index, buffer);
}
status_t MuxOMX::fillBuffer(node_id node, buffer_id buffer, int fenceFd) {
return getOMX(node)->fillBuffer(node, buffer, fenceFd);
}
status_t MuxOMX::emptyBuffer(
node_id node,
buffer_id buffer,
OMX_U32 range_offset, OMX_U32 range_length,
OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) {
return getOMX(node)->emptyBuffer(
node, buffer, range_offset, range_length, flags, timestamp, fenceFd);
}
status_t MuxOMX::getExtensionIndex(
node_id node,
const char *parameter_name,
OMX_INDEXTYPE *index) {
return getOMX(node)->getExtensionIndex(node, parameter_name, index);
}
status_t MuxOMX::setInternalOption(
node_id node,
OMX_U32 port_index,
InternalOptionType type,
const void *data,
size_t size) {
return getOMX(node)->setInternalOption(node, port_index, type, data, size);
}
OMXClient::OMXClient() {
char value[PROPERTY_VALUE_MAX];
if (property_get("media.stagefright.codecremote", value, NULL)
&& (!strcmp("0", value) || !strcasecmp("false", value))) {
sCodecProcessEnabled = false;
}
}
status_t OMXClient::connect() {
sp<IServiceManager> sm = defaultServiceManager();
sp<IBinder> playerbinder = sm->getService(String16("media.player"));
sp<IMediaPlayerService> mediaservice = interface_cast<IMediaPlayerService>(playerbinder);
if (mediaservice.get() == NULL) {
ALOGE("Cannot obtain IMediaPlayerService");
return NO_INIT;
}
sp<IOMX> mediaServerOMX = mediaservice->getOMX();
if (mediaServerOMX.get() == NULL) {
ALOGE("Cannot obtain mediaserver IOMX");
return NO_INIT;
}
// If we don't want to use the codec process, and the media server OMX
// is local, use it directly instead of going through MuxOMX
if (!sCodecProcessEnabled &&
mediaServerOMX->livesLocally(0 /* node */, getpid())) {
mOMX = mediaServerOMX;
return OK;
}
sp<IBinder> codecbinder = sm->getService(String16("media.codec"));
sp<IMediaCodecService> codecservice = interface_cast<IMediaCodecService>(codecbinder);
if (codecservice.get() == NULL) {
ALOGE("Cannot obtain IMediaCodecService");
return NO_INIT;
}
sp<IOMX> mediaCodecOMX = codecservice->getOMX();
if (mediaCodecOMX.get() == NULL) {
ALOGE("Cannot obtain mediacodec IOMX");
return NO_INIT;
}
mOMX = new MuxOMX(mediaServerOMX, mediaCodecOMX);
return OK;
}
void OMXClient::disconnect() {
if (mOMX.get() != NULL) {
mOMX.clear();
mOMX = NULL;
}
}
} // namespace android
| 31.948905 | 96 | 0.677405 | Keneral |
e994fce4832b5e16f91fafc14f68612e7a2e253d | 1,500 | cpp | C++ | GameModel.cpp | zubrim/monty_hall_problem | 6e6dbdf4cddad4c84b81bd250fcfccc5d44bf35c | [
"MIT"
] | null | null | null | GameModel.cpp | zubrim/monty_hall_problem | 6e6dbdf4cddad4c84b81bd250fcfccc5d44bf35c | [
"MIT"
] | null | null | null | GameModel.cpp | zubrim/monty_hall_problem | 6e6dbdf4cddad4c84b81bd250fcfccc5d44bf35c | [
"MIT"
] | null | null | null | #include "GameModel.h"
GameModel::GameModel() : gameEngine_(GameEngine()){
}
GameModel::~GameModel(){}
void GameModel::changeStateTo(GameEngineState state) {
switch (state) {
case GameEngineState::READY: gameEngine_.reset(); break;
case GameEngineState::DOOR_ELIMINATED: gameEngine_.eliminateDoor(); break;
case GameEngineState::QUIT: gameEngine_.quit(); break;
}
gameEngine_.print();
notifyUpdate();
}
void GameModel::changeStateTo(GameEngineState state, int index) {
switch (state) {
case GameEngineState::FIRST_TRY_DONE: gameEngine_.doFirstTry(index); break;
case GameEngineState::SECOND_TRY_DONE: gameEngine_.doSecondTry(index); break;
}
gameEngine_.print();
notifyUpdate();
}
GameEngineState GameModel::getState() {
return gameEngine_.getState();
}
int GameModel::getNumberOfDoors() {
return gameEngine_.getNumberOfDoors();
}
std::string GameModel::getDoorContentText(int index) {
switch (gameEngine_.getDoorContentByIndex(index)) {
case Prize::CAR : return "CAR";
case Prize::GOAT : return "GOAT";
default: return "ERROR";
}
};
std::string GameModel::getDoorStateText(int index) {
switch (gameEngine_.getDoorStateByIndex(index)) {
case DoorState::INITIAL: return "CLOSED";
case DoorState::PICKED: return "PICKED";
case DoorState::ELIMINATED: return "ELIMINATED";
default: return "ERROR";
}
};
DoorState GameModel::getDoorState(int index) { return gameEngine_.getDoorStateByIndex(index); };
bool GameModel::isCarWon() {
return gameEngine_.isCarWon();
}
| 25.423729 | 96 | 0.752 | zubrim |
e99692369475fcd5d2311bf59772848f22a2bf8e | 2,305 | cpp | C++ | Libs/AudioFile/libaudiofile/compression.cpp | drunkfly/retrotoolkit | 38fc08ce931339948d697a4dcf6f2441bccef7d6 | [
"MIT",
"Unlicense"
] | 3 | 2021-04-17T11:32:36.000Z | 2022-01-03T17:51:27.000Z | Libs/AudioFile/libaudiofile/compression.cpp | drunkfly/retrotoolkit | 38fc08ce931339948d697a4dcf6f2441bccef7d6 | [
"MIT",
"Unlicense"
] | null | null | null | Libs/AudioFile/libaudiofile/compression.cpp | drunkfly/retrotoolkit | 38fc08ce931339948d697a4dcf6f2441bccef7d6 | [
"MIT",
"Unlicense"
] | null | null | null | /*
Audio File Library
Copyright (C) 1999-2000, Michael Pruett <michael@68k.org>
Copyright (C) 2000, Silicon Graphics, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301 USA
*/
/*
compression.cpp
This file contains routines for configuring compressed audio.
*/
#include "config.h"
#include <assert.h>
#include "FileHandle.h"
#include "Setup.h"
#include "Track.h"
#include "audiofile.h"
#include "aupvlist.h"
#include "units.h"
#include "util.h"
const CompressionUnit *_af_compression_unit_from_id (int compressionid)
{
for (int i=0; i<_AF_NUM_COMPRESSION; i++)
if (_af_compression[i].compressionID == compressionid)
return &_af_compression[i];
_af_error(AF_BAD_COMPTYPE, "compression type %d not available", compressionid);
return NULL;
}
int afGetCompression (AFfilehandle file, int trackid)
{
if (!_af_filehandle_ok(file))
return -1;
Track *track = file->getTrack(trackid);
if (!track)
return -1;
return track->f.compressionType;
}
void afInitCompression (AFfilesetup setup, int trackid, int compression)
{
if (!_af_filesetup_ok(setup))
return;
TrackSetup *track = setup->getTrack(trackid);
if (!track)
return;
if (!_af_compression_unit_from_id(compression))
return;
track->compressionSet = true;
track->f.compressionType = compression;
}
#if 0
int afGetCompressionParams (AFfilehandle file, int trackid,
int *compression, AUpvlist pvlist, int numitems)
{
assert(file);
assert(trackid == AF_DEFAULT_TRACK);
}
void afInitCompressionParams (AFfilesetup setup, int trackid,
int compression, AUpvlist pvlist, int numitems)
{
assert(setup);
assert(trackid == AF_DEFAULT_TRACK);
}
#endif
| 24.784946 | 80 | 0.754447 | drunkfly |
e9974b685fae6c0a3373555682a1971540cfed66 | 7,507 | cpp | C++ | src/core/SBWCore/SBWException.cpp | copasi/copasi-dependencies | c01dd455c843522375c32c2989aa8675f59bb810 | [
"Unlicense"
] | 5 | 2015-04-16T14:27:38.000Z | 2021-11-30T14:54:39.000Z | src/core/SBWCore/SBWException.cpp | copasi/copasi-dependencies | c01dd455c843522375c32c2989aa8675f59bb810 | [
"Unlicense"
] | 8 | 2017-05-30T16:58:39.000Z | 2022-02-22T16:51:34.000Z | src/core/SBWCore/SBWException.cpp | copasi/copasi-dependencies | c01dd455c843522375c32c2989aa8675f59bb810 | [
"Unlicense"
] | 7 | 2016-05-29T08:12:59.000Z | 2019-05-02T13:39:25.000Z | /**
* @file SBWException.cpp
* @brief implementation of SBWException class - abstract base class for all SBW Exceptions
*
* This file is part of SBW. Please visit http://sbw.sf.org for more
* information about SBW, and the latest version of libSBW.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the New BSD license.
*
* Copyright (c) 2010-2014, Frank T. Bergmann and
* University of Washington
* Copyright (c) 2008-2010, University of Washington and
* Keck Graduate Institute.
* Copyright (c) 2005-2008, Keck Graduate Institute.
* Copyright (c) 2001-2004, California Institute of Technology and
* Japan Science and Technology Corporation.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 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.
*
* The original code contained here was initially developed by:
*
* Andrew Finney, Herbert Sauro, Michael Hucka, Hamid Bolouri
* The Systems Biology Workbench Development Group
* ERATO Kitano Systems Biology Project
* Control and Dynamical Systems, MC 107-81
* California Institute of Technology
* Pasadena, CA, 91125, USA
*
*
* Contributor(s):
*
*/
// SBWException.cpp: implementation of the SBWException class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sbwplusbasictypes.h"
#include "SBWException.h"
#include <SBW/SBWOSMutexLock.h>
using namespace SystemsBiologyWorkbench ;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
/**
* mapping between thread identifier and pending exception
*/
std::map<long, SBWException *> SBWException::exceptionMap ;
/**
* mutex to protect access to exceptionMap
*/
SBWOSMutex SBWException::threadStoreMutex("exception store") ;
/**
* creates an exception with a user message but no detailed message.
* @param c user message
*/
SBWException::SBWException(const std::string& c) : m_szMessage(c), m_szDetailedMessage()
{
}
/**
* creates an exception with user and detailed messages.
* @param c user message.
* @param d detailed message.
*/
SBWException::SBWException(const std::string& c, const std::string& d)
: m_szMessage(c), m_szDetailedMessage(d)
{
}
/**
* recover memory used by exception
*/
SBWException::~SBWException()
{
}
std::string SBWException::getMessage() const
{
return m_szMessage;
}
std::string SBWException::getDetailedMessage() const
{
return m_szDetailedMessage;
}
/**
* output to standard output the user and detailed messages.
*/
void SBWException::log() const
{
try
{
printf("%s", m_szMessage.c_str());
printf("\n");
if (!m_szDetailedMessage.empty())
{
printf("%s", m_szDetailedMessage.c_str());
printf("\n");
}
} catch(...) {}
}
/**
* output to standard output the given string.
* @param c string to be output
*/
void SBWException::log(const std::string& c)
{
try
{
printf("%s", c.c_str());
printf("\n");
}catch (...) {}
}
/**
* output to standard output the 2 given strings.
* @param c first string to be output
* @param d 2nd string to be output
*/
void SBWException::log(const std::string& c, const std::string& d)
{
try
{
printf("%s", c.c_str());
printf("\n");
printf("%s", d.c_str());
printf("\n");
} catch(...) {}
}
/**
* overload allocation operator to use C heap
* method needs to be removed.
*/
void *SBWException::operator new(size_t size)
{
return malloc(size);
}
/**
* overload deallocation operator to use C heap
* method needs to be removed.
*/
void SBWException::operator delete(void *x)
{
free(x);
}
/**
* returns the pending exception for this thread.
* @return the pending exception for this thread.
*/
SBWException *SBWException::getStoredException()
{
try
{
#ifdef WIN32
DWORD threadId = GetCurrentThreadId();
#elif defined(HAVE_LIBPTHREAD)
long threadId = (long)pthread_self();
#endif
SBWOSMutexLock ml(threadStoreMutex);
std::map<long, SBWException *>::iterator itr = exceptionMap.find(threadId);
if (itr == exceptionMap.end())
return NULL ;
else
return (*itr).second ;
} catch (...) { return NULL; }
}
/**
* removes and deallocates the pending exception for this thread.
* Assumes there is a stored exception for this thread.
*/
void SBWException::clearStoredException()
{
#ifdef WIN32
DWORD threadId = GetCurrentThreadId();
#elif defined(HAVE_LIBPTHREAD)
long threadId = (long)pthread_self();
#endif
SBWOSMutexLock ml(threadStoreMutex);
SBWException *exception = SBWException::getStoredException();
delete exception ;
exceptionMap.erase(threadId);
}
/**
* stores this exception as the pending exception for this thread
*/
void SBWException::storeException()
{
#ifdef WIN32
DWORD threadId = GetCurrentThreadId();
#elif defined(HAVE_LIBPTHREAD)
long threadId = (long)pthread_self();
#endif
SBWOSMutexLock ml(threadStoreMutex);
SBWException *exception = SBWException::getStoredException();
delete exception ;
exceptionMap[threadId] = this ;
}
/**
* throws the stored exception for this thread.
* Assumes there is a stored exception for this thread.
* The exception will no longer be the pending exception for this thread.
*/
void SBWException::throwStoredException()
{
#ifdef WIN32
DWORD threadId = GetCurrentThreadId();
#elif defined(HAVE_LIBPTHREAD)
long threadId = (long)pthread_self();
#endif
SBWOSMutexLock ml(threadStoreMutex);
SBWException *exception = SBWException::getStoredException();
exceptionMap.erase(threadId);
throw exception ;
}
/**
* clears all exceptions, on all threads.
* Added to support the SBW-MATLAB interface
* (the nefarious tricky-sticky-error problem ).
*/
void SBWException::clearAllExceptions()
{
SBWOSMutexLock ml(threadStoreMutex);
exceptionMap.clear();
}
| 26.715302 | 91 | 0.691088 | copasi |
e99992d4399dec01b531f4f57c1d46846f3305a6 | 401 | hpp | C++ | src/supermarx/data/karluser.hpp | Supermarx/common | bb1aaaef4486d6c1089193824fde4533de150b4d | [
"MIT"
] | null | null | null | src/supermarx/data/karluser.hpp | Supermarx/common | bb1aaaef4486d6c1089193824fde4533de150b4d | [
"MIT"
] | null | null | null | src/supermarx/data/karluser.hpp | Supermarx/common | bb1aaaef4486d6c1089193824fde4533de150b4d | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <supermarx/token.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
namespace supermarx
{
namespace data
{
struct karluser
{
std::string name;
token password_salt;
token password_hashed;
};
}
}
BOOST_FUSION_ADAPT_STRUCT(
supermarx::data::karluser,
(std::string, name)
(supermarx::token, password_salt)
(supermarx::token, password_hashed)
)
| 13.366667 | 48 | 0.743142 | Supermarx |
e999dfe4c99873548ae45fe6a597d0375102cb71 | 252 | cpp | C++ | Maths/7_lcm.cpp | Simran2000-jpg/CPP-Programming | cad4f362252f8bde4afadf455ddd67a85aa70dba | [
"MIT"
] | 30 | 2020-09-30T19:16:04.000Z | 2022-02-20T14:28:13.000Z | Maths/7_lcm.cpp | Simran2000-jpg/CPP-Programming | cad4f362252f8bde4afadf455ddd67a85aa70dba | [
"MIT"
] | 168 | 2020-09-30T19:52:42.000Z | 2021-10-22T03:55:57.000Z | Maths/7_lcm.cpp | Simran2000-jpg/CPP-Programming | cad4f362252f8bde4afadf455ddd67a85aa70dba | [
"MIT"
] | 123 | 2020-09-30T19:16:12.000Z | 2021-11-12T18:49:18.000Z | // LCM of two numbers a and b is equal to (a*b)/gcd(a,b);
#include <iostream>
#include <algorithm>
using namespace std;
int lcm(int a, int b){
return a * b/(__gcd(a,b));
}
int main(){
int a,b;
cin>>a>>b;
cout<<lcm(a,b)<<endl;
} | 14.823529 | 57 | 0.56746 | Simran2000-jpg |
e99fdfc22ec9dff53c79b8ec87e1d3dd07c00867 | 2,799 | cxx | C++ | source/code/core/tasks/private/task_thread_pool_win32.cxx | iceshard-engine/engine | 4f2092af8d2d389ea72addc729d0c2c8d944c95c | [
"BSD-3-Clause-Clear"
] | 39 | 2019-08-17T09:08:51.000Z | 2022-02-13T10:14:19.000Z | source/code/core/tasks/private/task_thread_pool_win32.cxx | iceshard-engine/engine | 4f2092af8d2d389ea72addc729d0c2c8d944c95c | [
"BSD-3-Clause-Clear"
] | 63 | 2020-05-22T16:09:30.000Z | 2022-01-21T14:24:05.000Z | source/code/core/tasks/private/task_thread_pool_win32.cxx | iceshard-engine/engine | 4f2092af8d2d389ea72addc729d0c2c8d944c95c | [
"BSD-3-Clause-Clear"
] | null | null | null | #include <ice/task_thread_pool.hxx>
#include <ice/os/windows.hxx>
#if ISP_WINDOWS
namespace ice
{
namespace detail
{
void threadpool_coroutine_work_callback(
PTP_CALLBACK_INSTANCE instance,
PVOID context,
PTP_WORK work
) noexcept
{
ice::detail::ScheduleOperationData const* operation_data = reinterpret_cast<ice::detail::ScheduleOperationData*>(context);
operation_data->_coroutine.resume();
CloseThreadpoolWork(work);
}
} // namespace detail
class IceTaskThreadPool : public ice::TaskThreadPool
{
public:
IceTaskThreadPool(ice::u32 thread_count) noexcept
: _thread_count{ thread_count }
, _native_threadpool{ }
, _native_tp_callback{ }
, _native_tp_group_cleanup{ }
{
_native_threadpool = CreateThreadpool(nullptr);
SetThreadpoolThreadMinimum(_native_threadpool, ice::min(_thread_count, 2u));
SetThreadpoolThreadMaximum(_native_threadpool, _thread_count);
InitializeThreadpoolEnvironment(&_native_tp_callback);
SetThreadpoolCallbackPool(&_native_tp_callback, _native_threadpool);
_native_tp_group_cleanup = CreateThreadpoolCleanupGroup();
SetThreadpoolCallbackCleanupGroup(&_native_tp_callback, _native_tp_group_cleanup, nullptr);
}
~IceTaskThreadPool() noexcept override
{
//CloseThreadpoolTimer(_native_tp_timer);
CloseThreadpoolCleanupGroupMembers(_native_tp_group_cleanup, true, nullptr);
CloseThreadpoolCleanupGroup(_native_tp_group_cleanup);
CloseThreadpool(_native_threadpool);
}
void schedule_internal(
ScheduleOperation* op,
ScheduleOperation::DataMemberType data_member
) noexcept override
{
ice::detail::ScheduleOperationData& data = op->*data_member;
SubmitThreadpoolWork(
CreateThreadpoolWork(
detail::threadpool_coroutine_work_callback,
&data,
&_native_tp_callback
)
);
}
private:
ice::u32 const _thread_count;
PTP_POOL _native_threadpool;
TP_CALLBACK_ENVIRON _native_tp_callback;
PTP_CLEANUP_GROUP _native_tp_group_cleanup;
std::atomic<ice::detail::ScheduleOperationData*> _head = nullptr;
};
auto create_simple_threadpool(
ice::Allocator& alloc,
ice::u32 thread_count
) noexcept -> ice::UniquePtr<ice::TaskThreadPool>
{
return ice::make_unique<ice::TaskThreadPool, ice::IceTaskThreadPool>(alloc, thread_count);
}
} // namespace ice
#endif
| 31.806818 | 134 | 0.642372 | iceshard-engine |
e9a0d3bba2720cb3bc93ac1ad81121afb5dc90bd | 1,518 | cpp | C++ | Algorithm/Problem48/main.cpp | et16kr/ModernCppChallengeStudy | 089cbfa2ef43f81001c986b569c4122793fcd268 | [
"MIT"
] | null | null | null | Algorithm/Problem48/main.cpp | et16kr/ModernCppChallengeStudy | 089cbfa2ef43f81001c986b569c4122793fcd268 | [
"MIT"
] | null | null | null | Algorithm/Problem48/main.cpp | et16kr/ModernCppChallengeStudy | 089cbfa2ef43f81001c986b569c4122793fcd268 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstring>
using namespace std;
void quickSort( int arr[], int left, int right )
{
int i = left, j = right;
int pivot = arr[(left + right) / 2];
int temp;
do
{
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i<= j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
} while (i<= j);
/* recursion */
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
struct node
{
int num;
int count;
};
void solve( int * start, int size )
{
int max = 1;
node * num = new node [size];
int idx = 0;
quickSort( start, 0, size - 1);
num[idx].num = start[0];
num[idx].count = 1;
for(int i = 1 ; i < size ; i++)
{
if ( num[idx].num == start[i] )
{
num[idx].count++;
if( num[idx].count > max )
{
max = num[idx].count;
}
}
else
{
num[++idx].num = start[i];
num[idx].count = 1;
}
}
for(int i = 0 ; i <= idx ; i++ )
{
if ( num[i].count == max )
{
cout << "{" << num[i].num << ", " << num[i].count << "}" << endl;
}
}
}
int main(int argc, char* argv[])
{
int arr[] = {1,1,3,5,8,13,3,5,8,8,5};
solve(arr,11);
return 0;
}
| 18.071429 | 77 | 0.387352 | et16kr |
e9a4cb96c8f548432507409740524c201692143a | 3,144 | hpp | C++ | src/pca9685/pca9685.hpp | daniel-blake/piio-server | fc0d9306343518c865c9bd1fb96fd70b693aaab1 | [
"MIT"
] | null | null | null | src/pca9685/pca9685.hpp | daniel-blake/piio-server | fc0d9306343518c865c9bd1fb96fd70b693aaab1 | [
"MIT"
] | null | null | null | src/pca9685/pca9685.hpp | daniel-blake/piio-server | fc0d9306343518c865c9bd1fb96fd70b693aaab1 | [
"MIT"
] | null | null | null | #ifndef __PCA9685_H_
#define __PCA9685_H_
#include "../exception/baseexceptions.hpp"
#include "../thread/thread.hpp"
#include <stdint.h>
/*! \file MCP23017 interface functions. Header file.
*/
/************************************
* *
* MAIN CLASS *
* *
*************************************/
class Pca9685 : Thread
{
public:
// Structure for IO Configuration
//! \typedef Pca9685Config Structure containing hardware configuration for the MCP23017
class Pca9685Config
{
friend class Pca9685; // Allow
public:
enum OutNotEnabledMode { OutputLow = 0, OutputHigh = 1, OutputHighZ = 2 };
enum OutputDriveType { OpenDrain = 0, TotemPole = 1};
public:
// Mode2
bool Invert; /*!< Invert output logic state, Default: false*/
bool OutputChangeOnAck; /*!< Change outputs on Ack instead of stop command, Default: false */
OutputDriveType OutputDrive; /*!< Type of output driver, Default: TotemPole*/
OutNotEnabledMode OutNotEnabled; /*!< Status of ouputs when /OE = 1, Default: OutputLow */
// Mode1
bool ExtClk;
// Prescale
uint32_t OscillatorClock;
uint16_t Frequency;
Pca9685Config();
uint8_t getMode1(); /*!< parse into usable uint8_t */
uint8_t getMode2(); /*!< parse into usable uint8_t */
uint8_t getPrescaler(); /*!< parse into usable uint8_t prescaler value */
uint16_t getActualFrequency(); /*!< return actual frequency used */
void setMode1(uint8_t); /*!< parse from read uint8_t */
void setMode2(uint8_t);/*!< parse from read uint8_t */
private:
// Allow this only to be set by friend class Pca9685
// Mode1
bool Restart;
bool AutoIncrement;
bool Sleep;
// Mode 2
bool Sub1;
bool Sub2;
bool Sub3;
bool AllCall;
double round(double number);
};
private:
uint8_t adr; // I2C Address of the IO expander chip
int fp; // File pointer for the I2C connection
Pca9685Config config; // Initial configuration of the chip
uint8_t tryI2CRead8 (uint8_t reg);
void tryI2CWrite8(uint8_t reg, uint8_t value);
void tryI2CMaskedWrite8(uint8_t reg, uint8_t value, uint8_t mask);
uint16_t tryI2CRead16(uint8_t reg);
void tryI2CWrite16(uint8_t reg, uint16_t value);
void tryI2CMaskedWrite16(uint8_t reg, uint16_t value, uint16_t mask);
void muteI2CMaskedWrite16(uint8_t reg, uint16_t value, uint16_t mask);
public:
//! Open a new connection to the PCA9685 device, and initialize it.
/*!
\param adr The I2C address of the IC to connect to
\param config Configuration for the IC
*/
Pca9685( uint8_t adr, Pca9685Config config);
~Pca9685();
/************************************
* *
* REGULAR I/O FUNCTIONS *
* *
************************************/
//! Set set new
void setValue(uint8_t pin, uint16_t off, uint16_t on);
//! Get current on time of the PWM
uint16_t getOnValue(uint8_t pin);
//! Get current off time of the PWM
uint16_t getOffValue(uint8_t pin);
};
#endif
| 28.071429 | 95 | 0.619275 | daniel-blake |
e9a7d2df484de4d8079fc656362f8832b5e21645 | 5,432 | cpp | C++ | SDK/ARKSurvivalEvolved_ProjSpaceDolphinChargedLaser0_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_ProjSpaceDolphinChargedLaser0_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_ProjSpaceDolphinChargedLaser0_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | // ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_ProjSpaceDolphinChargedLaser0_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.GetExtraTriggerExplosionOffsetForTarget
// ()
// Parameters:
// float Return (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void AProjSpaceDolphinChargedLaser0_C::GetExtraTriggerExplosionOffsetForTarget(float* Return)
{
static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.GetExtraTriggerExplosionOffsetForTarget");
AProjSpaceDolphinChargedLaser0_C_GetExtraTriggerExplosionOffsetForTarget_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Return != nullptr)
*Return = params.Return;
}
// Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ReceiveDestroyed
// ()
void AProjSpaceDolphinChargedLaser0_C::ReceiveDestroyed()
{
static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ReceiveDestroyed");
AProjSpaceDolphinChargedLaser0_C_ReceiveDestroyed_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.OnExplode
// ()
// Parameters:
// struct FHitResult Result (Parm, OutParm, ReferenceParm)
void AProjSpaceDolphinChargedLaser0_C::OnExplode(struct FHitResult* Result)
{
static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.OnExplode");
AProjSpaceDolphinChargedLaser0_C_OnExplode_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Result != nullptr)
*Result = params.Result;
}
// Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.BPIgnoreRadialDamageVictim
// ()
// Parameters:
// class AActor** Victim (Parm, ZeroConstructor, IsPlainOldData)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool AProjSpaceDolphinChargedLaser0_C::BPIgnoreRadialDamageVictim(class AActor** Victim)
{
static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.BPIgnoreRadialDamageVictim");
AProjSpaceDolphinChargedLaser0_C_BPIgnoreRadialDamageVictim_Params params;
params.Victim = Victim;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.UserConstructionScript
// ()
void AProjSpaceDolphinChargedLaser0_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.UserConstructionScript");
AProjSpaceDolphinChargedLaser0_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ReceiveTick
// ()
// Parameters:
// float* DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData)
void AProjSpaceDolphinChargedLaser0_C::ReceiveTick(float* DeltaSeconds)
{
static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ReceiveTick");
AProjSpaceDolphinChargedLaser0_C_ReceiveTick_Params params;
params.DeltaSeconds = DeltaSeconds;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ReceiveBeginPlay
// ()
void AProjSpaceDolphinChargedLaser0_C::ReceiveBeginPlay()
{
static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ReceiveBeginPlay");
AProjSpaceDolphinChargedLaser0_C_ReceiveBeginPlay_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ExecuteUbergraph_ProjSpaceDolphinChargedLaser0
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void AProjSpaceDolphinChargedLaser0_C::ExecuteUbergraph_ProjSpaceDolphinChargedLaser0(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ExecuteUbergraph_ProjSpaceDolphinChargedLaser0");
AProjSpaceDolphinChargedLaser0_C_ExecuteUbergraph_ProjSpaceDolphinChargedLaser0_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 30.516854 | 170 | 0.761782 | 2bite |
e9b32308ae95f3d9ac19aa2790083d365d7dd523 | 2,114 | cpp | C++ | app-assist-efl/base/src/WServiceApp.cpp | Samsung/tizen-app-assist | 8ea75cd9bc7161b137af71be657d1c1ac76bf083 | [
"Apache-2.0"
] | 13 | 2016-12-13T23:10:44.000Z | 2019-10-03T21:45:35.000Z | app-assist-efl/base/src/WServiceApp.cpp | Samsung/tizen-app-assist | 8ea75cd9bc7161b137af71be657d1c1ac76bf083 | [
"Apache-2.0"
] | 2 | 2017-05-25T11:42:36.000Z | 2018-06-14T05:50:18.000Z | app-assist-efl/base/src/WServiceApp.cpp | Samsung/tizen-app-assist | 8ea75cd9bc7161b137af71be657d1c1ac76bf083 | [
"Apache-2.0"
] | 8 | 2016-08-20T12:44:04.000Z | 2020-01-20T19:03:17.000Z | /*
* Copyright (c) 2014-2016 Samsung Electronics Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "WServiceApp.h"
#include <memory.h>
#include "WDebugInternal.h"
using namespace app_assist;
namespace app_assist {
class _WServiceAppImpl {
public:
_WServiceAppImpl() : _firstLaunch(true) {}
~_WServiceAppImpl();
public:
bool _firstLaunch;
static bool _onCreate(void* data);
static void _onTerminate(void* data);
static void _onAppControl(app_control_h request, void* data);
};
}
_WServiceAppImpl::~_WServiceAppImpl() {
}
bool _WServiceAppImpl::_onCreate(void* data) {
WHIT();
auto app = (WServiceApp*)data;
return app->onCreate();
}
void _WServiceAppImpl::_onTerminate(void* data) {
WHIT();
auto app = (WServiceApp*)data;
app->onTerminate();
}
void _WServiceAppImpl::_onAppControl(app_control_h request, void* data) {
WHIT();
auto app = (WServiceApp*)data;
app->onAppControl(request, app->_pv->_firstLaunch);
app->_pv->_firstLaunch = false;
}
WServiceApp::WServiceApp() {
_pv = new _WServiceAppImpl();
}
WServiceApp::~WServiceApp() {
WHIT();
delete _pv;
}
int WServiceApp::start(int argc, char* argv[]) {
return onStart(argc, argv);
}
void WServiceApp::onAppControl(app_control_h request, bool firstLaunch) {
}
int WServiceApp::onStart(int argc, char* argv[]) {
service_app_lifecycle_callback_s cb;
memset(&cb, 0, sizeof(cb));
cb.create = _WServiceAppImpl::_onCreate;
cb.terminate = _WServiceAppImpl::_onTerminate;
cb.app_control = _WServiceAppImpl::_onAppControl;
return service_app_main(argc, argv, &cb, this);
}
| 22.731183 | 77 | 0.734153 | Samsung |
e9baff43b229dcc8683620a787ec5dd30b5cec20 | 5,101 | hpp | C++ | include/seqan3/alignment/pairwise/align_pairwise.hpp | FirstLoveLife/seqan3 | ac2e983e0a576515c13ebb2c851c43c1eba1ece1 | [
"BSD-3-Clause"
] | null | null | null | include/seqan3/alignment/pairwise/align_pairwise.hpp | FirstLoveLife/seqan3 | ac2e983e0a576515c13ebb2c851c43c1eba1ece1 | [
"BSD-3-Clause"
] | null | null | null | include/seqan3/alignment/pairwise/align_pairwise.hpp | FirstLoveLife/seqan3 | ac2e983e0a576515c13ebb2c851c43c1eba1ece1 | [
"BSD-3-Clause"
] | null | null | null | // ============================================================================
// SeqAn - The Library for Sequence Analysis
// ============================================================================
//
// Copyright (c) 2006-2018, Knut Reinert & Freie Universitaet Berlin
// Copyright (c) 2016-2018, Knut Reinert & MPI Molekulare Genetik
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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.
//
// ============================================================================
/*!\file
* \brief Provides pairwise alignment function.
* \author Rene Rahn <rene.rahn AT fu-berlin.de>
*/
#pragma once
#include <functional>
#include <iostream>
#include <tuple>
#include <type_traits>
#include <meta/meta.hpp>
#include <range/v3/view/bounded.hpp>
#include <range/v3/view/transform.hpp>
#include <range/v3/view/single.hpp>
#include <seqan3/alignment/configuration/all.hpp>
#include <seqan3/alignment/pairwise/align_result.hpp>
#include <seqan3/alignment/pairwise/alignment_selector.hpp>
#include <seqan3/alignment/pairwise/execution/all.hpp>
#include <seqan3/alphabet/gap/gapped.hpp>
#include <seqan3/core/algorithm/all.hpp>
#include <seqan3/core/metafunction/basic.hpp>
#include <seqan3/range/view/persist.hpp>
#include <seqan3/std/concepts>
#include <seqan3/std/ranges>
namespace seqan3
{
//!\cond
template <std::ranges::InputRange sequence_t, typename alignment_config_t>
requires detail::is_algorithm_configuration_v<remove_cvref_t<alignment_config_t>> &&
tuple_like_concept<value_type_t<std::ranges::iterator_t<std::remove_reference_t<sequence_t>>>>
constexpr auto align_pairwise(sequence_t && seq, alignment_config_t && config)
{
static_assert(std::tuple_size_v<value_type_t<std::ranges::iterator_t<std::remove_reference_t<sequence_t>>>> == 2,
"Expects exactly two sequences for pairwise alignments.");
auto dispatch_execution = [tpl = std::forward_as_tuple(std::forward<sequence_t>(seq))](auto && cfg)
{
// if constexpr (detail::has_align_cfg_v<align_cfg::id::on_hit, remove_cvref_t<decltype(cfg)>>)
// {
// throw std::invalid_argument{"The delegation option is yet not supported."};
// }
// else // continue with two-way executor.
// {
//TODO (rrahn): Extend with execution handler.
auto align_rng = std::forward<std::tuple_element_t<0, decltype(tpl)>>(std::get<0>(tpl)) | view::persist;
detail::alignment_selector<value_type_t<decltype(align_rng)>,
std::remove_reference_t<decltype(cfg)>> selector{cfg};
using exec_type = detail::alignment_executor_two_way<decltype(align_rng), decltype(selector)>;
return alignment_range<exec_type>{align_rng, selector};
// }
};
// TODO: replaces the default arguments.
return detail::apply_deferred_configs(dispatch_execution, std::forward<alignment_config_t>(config));
}
//
template <tuple_like_concept seq_t,
typename alignment_config_t>
requires detail::is_algorithm_configuration_v<remove_cvref_t<alignment_config_t>>
constexpr auto align_pairwise(seq_t && seq, alignment_config_t && config)
{
static_assert(std::tuple_size_v<std::remove_reference_t<seq_t>> == 2,
"Expects exactly two sequences for pairwise alignments.");
//TODO: Check the problem here.
return align_pairwise(ranges::view::single(std::forward<seq_t>(seq)) | ranges::view::bounded,
std::forward<alignment_config_t>(config));
}
//!\endcond
} // namespace seqan3
| 44.356522 | 117 | 0.685356 | FirstLoveLife |
e9be7fc767e8537d66c0aa0b4fc2a22efeb9ad38 | 2,911 | hpp | C++ | src/cpu/cpu.hpp | Tunacan427/FishOS | 86a173e8c423e96e70dfc624b5738e1313b0b130 | [
"MIT"
] | null | null | null | src/cpu/cpu.hpp | Tunacan427/FishOS | 86a173e8c423e96e70dfc624b5738e1313b0b130 | [
"MIT"
] | null | null | null | src/cpu/cpu.hpp | Tunacan427/FishOS | 86a173e8c423e96e70dfc624b5738e1313b0b130 | [
"MIT"
] | null | null | null | #pragma once
#include <kstd/types.hpp>
#include <panic.hpp>
namespace cpu {
static inline void cli() {
asm volatile("cli");
}
static inline void sti() {
asm volatile("sti");
}
static inline void cpuid(u32 leaf, u32 subleaf, u32 *eax, u32 *ebx, u32 *ecx, u32 *edx) {
asm volatile("cpuid" : "=a" (*eax), "=b" (*ebx), "=c" (*ecx), "=d" (*edx) : "a" (leaf), "c" (subleaf));
}
static inline u64 read_msr(u32 msr) {
volatile u32 lo, hi;
asm volatile("rdmsr" : "=a" (lo), "=d" (hi) : "c" (msr));
return ((u64)hi << 32) | lo;
}
static inline void write_msr(u32 msr, u64 val) {
volatile u32 lo = val & 0xFFFFFFFF;
volatile u32 hi = val >> 32;
asm volatile("wrmsr" : : "a" (lo), "d" (hi), "c" (msr));
}
static inline void write_cr3(u64 cr3) {
asm volatile("mov %0, %%cr3" : : "r" (cr3));
}
static inline void write_cr4(u64 cr4) {
asm volatile("mov %0, %%cr4" : : "r" (cr4));
}
static inline u64 read_cr4() {
volatile u64 cr4;
asm volatile("mov %%cr4, %0" : "=r" (cr4));
return cr4;
}
static inline u64 read_cr2() {
volatile u64 cr2;
asm volatile("mov %%cr2, %0" : "=r" (cr2));
return cr2;
}
static inline void invlpg(void *m) {
asm volatile("invlpg (%0)" : : "r" (m) : "memory");
}
template<kstd::Integral T>
static inline T bswap(T val) {
volatile T result;
asm volatile("bswap %0" : "=r" (result) : "r" (val));
return result;
}
template<kstd::Integral T> static inline void out(const u16 port, const T val) {
panic("cpu::out must be used with u8, u16, or u32");
}
template<>
inline void out<u8>(const u16 port, const u8 val) {
asm volatile("outb %0, %1" : : "a" (val), "Nd" (port));
}
template<>
inline void out<u16>(const u16 port, const u16 val) {
asm volatile("outw %0, %1" : : "a" (val), "Nd" (port));
}
template<>
inline void out<u32>(const u16 port, const u32 val) {
asm volatile("outl %0, %1" : : "a" (val), "Nd" (port));
}
template<kstd::Integral T> static inline T in(const u16 port) {
panic("cpu::in must be used with u8, u16, or u32");
}
template<>
inline u8 in<u8>(const u16 port) {
volatile u8 ret;
asm volatile("inb %1, %0" : "=a" (ret) : "Nd" (port));
return ret;
}
template<>
inline u16 in<u16>(const u16 port) {
volatile u16 ret;
asm volatile("inw %1, %0" : "=a" (ret) : "Nd" (port));
return ret;
}
template<>
inline u32 in<u32>(const u16 port) {
volatile u32 ret;
asm volatile("inl %1, %0" : "=a" (ret) : "Nd" (port));
return ret;
}
static inline void io_wait() {
out<u8>(0x80, 0);
}
}
| 26.463636 | 111 | 0.512195 | Tunacan427 |
e9bec75635144916bf45b1af8a1e92da21459531 | 3,891 | cc | C++ | Calibration/EcalCalibAlgos/src/miscalibExample.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | Calibration/EcalCalibAlgos/src/miscalibExample.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | Calibration/EcalCalibAlgos/src/miscalibExample.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | // -*- C++ -*-
//
// Package: miscalibExample
// Class: miscalibExample
//
/**\class miscalibExample miscalibExample.cc Calibration/EcalCalibAlgos/src/miscalibExample.cc
Description: Perform single electron calibration (tested on TB data only).
Implementation:
<Notes on implementation>
*/
//
// Original Author: Lorenzo AGOSTINO
// Created: Tue Jul 18 12:17:01 CEST 2006
//
//
// system include files
// user include files
#include "Calibration/EcalCalibAlgos/interface/miscalibExample.h"
//
#include "DataFormats/EgammaReco/interface/SuperCluster.h"
#include "DataFormats/EgammaReco/interface/SuperClusterFwd.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include <iostream>
#include <stdexcept>
#include <vector>
// class declaration
//
/*
class miscalibExample : public edm::EDAnalyzer {
public:
explicit miscalibExample(const edm::ParameterSet&);
~miscalibExample();
virtual void analyze(const edm::Event&, const edm::EventSetup&);
virtual void beginJob();
virtual void endJob();
private:
// ----------member data ---------------------------
std::string rootfile_;
std::string correctedHybridSuperClusterProducer_;
std::string correctedHybridSuperClusterCollection_;
std::string BarrelHitsCollection_;
std::string ecalHitsProducer_ ;
int read_events;
TH1F* scEnergy;
};
*/
miscalibExample::miscalibExample(const edm::ParameterSet& iConfig) {
rootfile_ = iConfig.getUntrackedParameter<std::string>("rootfile", "ecalSimpleTBanalysis.root");
correctedHybridSuperClusterProducer_ = iConfig.getParameter<std::string>("correctedHybridSuperClusterProducer");
correctedHybridSuperClusterCollection_ = iConfig.getParameter<std::string>("correctedHybridSuperClusterCollection");
}
miscalibExample::~miscalibExample() {}
//========================================================================
void miscalibExample::beginJob() {
//========================================================================
// Book histograms
scEnergy = new TH1F("scEnergy", "SuperCluster energy", 100, 20., 80.);
read_events = 0;
}
//========================================================================
void miscalibExample::endJob() {
//========================================================================
std::cout << "************* STATISTICS **************" << std::endl;
std::cout << "Read Events: " << read_events << std::endl;
/////////////////////////////////////////////////////////////////////////////
TFile f(rootfile_.c_str(), "RECREATE");
scEnergy->Write();
f.Close();
}
//=================================================================================
void miscalibExample::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
//=================================================================================
using namespace edm;
using namespace std;
read_events++;
// Get hybrid super clusters after energy correction
Handle<reco::SuperClusterCollection> pCorrectedHybridSuperClusters;
iEvent.getByLabel(
correctedHybridSuperClusterProducer_, correctedHybridSuperClusterCollection_, pCorrectedHybridSuperClusters);
if (!pCorrectedHybridSuperClusters.isValid()) {
LogError("EgammaSimpleAnalyzer") << "Error! can't get collection with label "
<< correctedHybridSuperClusterCollection_.c_str();
}
const reco::SuperClusterCollection* correctedHybridSuperClusters = pCorrectedHybridSuperClusters.product();
reco::SuperClusterCollection::const_iterator superClusterIt;
for (superClusterIt = correctedHybridSuperClusters->begin(); superClusterIt != correctedHybridSuperClusters->end();
superClusterIt++) {
scEnergy->Fill(superClusterIt->energy());
}
}
//define this as a plug-in
//DEFINE_FWK_MODULE(miscalibExample);
| 32.425 | 118 | 0.61578 | ckamtsikis |
e9bfe0e1cdcc67bd5f54185f2f9641299ab6d5ed | 3,424 | cpp | C++ | buildexe/src/toolchain_setup.cpp | coder137/build_in_cpp | 296b0312eb0f4773fb2d40b01ed302f74f26f7a8 | [
"Apache-2.0"
] | 48 | 2021-06-15T08:34:42.000Z | 2022-03-24T20:35:54.000Z | buildexe/src/toolchain_setup.cpp | coder137/build_in_cpp | 296b0312eb0f4773fb2d40b01ed302f74f26f7a8 | [
"Apache-2.0"
] | 100 | 2021-06-14T00:21:49.000Z | 2022-03-29T03:59:42.000Z | buildexe/src/toolchain_setup.cpp | coder137/build_in_cpp | 296b0312eb0f4773fb2d40b01ed302f74f26f7a8 | [
"Apache-2.0"
] | 1 | 2021-06-17T01:03:36.000Z | 2021-06-17T01:03:36.000Z | /*
* Copyright 2021-2022 Niket Naidu. 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.
*/
namespace {
constexpr const char *const kTag = "BuildExe";
}
namespace buildcc {
void find_toolchain_verify(BaseToolchain &toolchain) {
auto verified_toolchains = toolchain.Verify();
env::assert_fatal(!verified_toolchains.empty(),
"Toolchain could not be verified. Please input correct "
"Gcc, Msvc, Clang or MinGW toolchain executable names");
if (verified_toolchains.size() > 1) {
env::log_info(
kTag,
fmt::format(
"Found {} toolchains. By default using the first added"
"toolchain. Modify your environment `PATH` information if you "
"would like compiler precedence when similar compilers are "
"detected in different folders",
verified_toolchains.size()));
}
// Print
int counter = 1;
for (const auto &vt : verified_toolchains) {
std::string info = fmt::format("{}. : {}", counter, vt.ToString());
env::log_info("Host Toolchain", info);
counter++;
}
}
void host_toolchain_verify(const BaseToolchain &toolchain) {
env::log_info(kTag, "*** Starting Toolchain verification ***");
fs::path file = env::get_project_build_dir() / "verify_host_toolchain" /
"verify_host_toolchain.cpp";
fs::create_directories(file.parent_path());
std::string file_data = R"(// Generated by BuildExe
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
std::cout << "********************" << std::endl;
std::cout << "Verifying host toolchain" << std::endl;
std::cout << "Current Path: " << fs::current_path() << std::endl;
std::cout << "********************" << std::endl;
return 0;
})";
env::save_file(path_as_string(file).c_str(), file_data, false);
ExecutableTarget_generic target(
"verify", toolchain, TargetEnv(file.parent_path(), file.parent_path()));
target.AddSource(file);
switch (toolchain.GetId()) {
case ToolchainId::Gcc:
case ToolchainId::MinGW:
target.AddCppCompileFlag("-std=c++17");
break;
case ToolchainId::Msvc:
target.AddCppCompileFlag("/std:c++17");
break;
default:
env::assert_fatal<false>("Invalid Compiler Id");
}
target.Build();
// Build
tf::Executor executor;
executor.run(target.GetTaskflow());
executor.wait_for_all();
env::assert_fatal(env::get_task_state() == env::TaskState::SUCCESS,
"Input toolchain could not compile host program. "
"Requires HOST toolchain");
// Run
bool execute = env::Command::Execute(fmt::format(
"{executable}", fmt::arg("executable", target.GetTargetPath().string())));
env::assert_fatal(execute, "Could not execute verification target");
env::log_info(kTag, "*** Toolchain verification done ***");
}
} // namespace buildcc
| 32.609524 | 80 | 0.658294 | coder137 |
e9c44d780609a6b5ea7a921e72bf1d3dab9d2620 | 5,333 | cc | C++ | src/AMOS/msgtest.cc | sagrudd/amos | 47643a1d238bff83421892cb74daaf6fff8d9548 | [
"Artistic-1.0"
] | 10 | 2015-03-20T18:25:56.000Z | 2020-06-02T22:00:08.000Z | src/AMOS/msgtest.cc | sagrudd/amos | 47643a1d238bff83421892cb74daaf6fff8d9548 | [
"Artistic-1.0"
] | 5 | 2015-05-14T17:51:20.000Z | 2020-07-19T04:17:47.000Z | src/AMOS/msgtest.cc | sagrudd/amos | 47643a1d238bff83421892cb74daaf6fff8d9548 | [
"Artistic-1.0"
] | 10 | 2015-05-17T16:01:23.000Z | 2020-05-20T08:13:43.000Z | #include "foundation_AMOS.hh"
#include <fstream>
#include <ctime>
using namespace std;
using namespace AMOS;
#define ITERS 500000
int main (int argc, char ** argv)
{
Message_t msg;
Read_t red;
Contig_t ctg;
double loopa = 0;
double loopb = 0;
clock_t clocka, clockb;
vector<Tile_t> tlevec;
Tile_t tle;
tle . source = 33396;
tle . offset = 512;
tle . range = Range_t (12,832);
tle . gaps . push_back (12);
tle . gaps . push_back (30);
tle . gaps . push_back (337);
tle . gaps . push_back (508);
tle . gaps . push_back (514);
tle . gaps . push_back (789);
for ( int j = 0; j < 200; j ++ )
tlevec . push_back (tle);
try {
red . setIID (1);
red . setEID ("str2");
red . setComment ("GBRAA01TF");
red . setSequence
("CCTTTGTGCTGGAAGGTGAATGCGGTGCGGCTGGTAACGGGCCGCGCGGGCGCAATCGGCGTCGTGATGGGCCGCAACAGCGAGTTTCACTTTGCCGAATTCATGCGCGGCATGGCCGAACGGCTGGGGCAGGACGAAGTGGACATTCTCGTCAGCCCCACCTCGCCGACCGGCAATGACGACGAGGTGCAGCTTTGTCACCGGCTGGCAACGAGCGGACGGGTGGATGCCGTTATCGTCACTTCCCCCAGGCCGAATGATGAACGCATCCGCATGTTGCACAAGCTCGGCATGCCGTTTCTGGTCCACGGGCGTTCGCAGATCGACATTCCCCATGCATGGCTTGATATCGACAATGAGAGCGCGGTCTATCATTCCACCGCACATCTGCTCGATCTTGGCCACAAGCGGATTGCGATGATCAACGGGCGCCATGGCTTCACCTTCTCGCTGCACCGCGACGCTGGCTATCGTAAGGCGCTTGAAAGCCGGGGAATCGACTTTGATCCCGACCTGGTGGAACATGGCGATTTCACCGATGAAATCGGCTATTGCCTCGCCCGCAAGCTTCTGGAACGCAATCCACGTCCAACGGCATTCGTCGCAGGCTCCATGATGACCGCGCTCGGCATCTACCGTGCCGCCCGCTCCTTCGGCCTTACGATCGGCAAGGATATTTCCGTCATCGCCCATGACGACGTGATCTCGTTCCTCAGCGCCGGTAATATGGGTGCCGTCGCTGACTGCGACACGCTCTTCAATGCGCGCGGCTGGCAAGCGATGCGCCGACCTTTTGATGGATATCCTCGATGGGCGCGCGCCCACCGAAATCCA",
"9878<?JQONBB77:=EGMPDOHRNSTSTSTRSSSREMRSSRSSRSQSSLQLLLLMPPPRRSSSRRRRSSSRSSSRRSRRRRSRIJJJONLTTTTRRROLLLLLLTTTTTTTRRRRPPPSRRSTTTRSRRRSPOLOOLOSSSSRSSRSRPRPPPSPSTSTSQSQTRURSSSSSTTTTRRRSRRSRSSSURRRRSWSSRRRSSTSRRTTTTTTTTTPPSRPPSTTTTRSRUSSSSUSPPPPRSQRTTTTSSSRRRRRTRRSTRTTTRTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTPSPPPPPRRRTTTTTRSSSSRRSRRSTSTTTTTTTTRTTRSSSTRSRSRRSSSTTTRSSRSSSUSSQSSRSSSSRRRRRSRRTRTSRTSURTTTTTRSSSSSSTRTRRRSSRSSRTSPSPPPRTRRSSRRSTRRRSSRRRRTTTRRRUSRSSSTRSSSSRRLLLLOLNOTTTSRRRRSSSTTTTTTTTTTTWRRPPPPPPSTTTTWPPMSTPTTTTTTTTSTSRSRSSTTRSSSSTTTTTTTTPPPPKPPSRSSSTSSSSTSSRRSSSTTTTTRRSSTTSSRSSSSSTTTTTTTTTTTRTTTSRSSSSSTTTTRRRSSPPSPPPTTTTSRRPORSRPPPPLPPSSSSTTSSRSSSRPPNSSQRTTTTTSSPKKGMNPSSQSSRSSSSQLLIL?HSTQPSSPLRSQSSRSUQSMRSSUPRLLPGEPPSNMRPTYRRQPMMGGPMLQE?CENRNCRSLQRNTTKTKLQTXSRSRTTPRQXISRCONK<?IDTPPPDDIR?B<LALBDL@;LQQLCH?E=@IC<9F9?I;9;=8");
red . setFragment (1);
red . setClearRange (Range_t(16,823));
red . setVectorClearRange (Range_t(16,823));
red . setQualityClearRange (Range_t(16,823));
ctg . setIID (1);
ctg . setEID ("str2");
ctg . setComment ("big contig");
ctg . setSequence
("CCTTTGTGCTGGAAGGTGAATGCGGTGCGGCTGGTAACGGGCCGCGCGGGCGCAATCGGCGTCGTGATGGGCCGCAACAGCGAGTTTCACTTTGCCGAATTCATGCGCGGCATGGCCGAACGGCTGGGGCAGGACGAAGTGGACATTCTCGTCAGCCCCACCTCGCCGACCGGCAATGACGACGAGGTGCAGCTTTGTCACCGGCTGGCAACGAGCGGACGGGTGGATGCCGTTATCGTCACTTCCCCCAGGCCGAATGATGAACGCATCCGCATGTTGCACAAGCTCGGCATGCCGTTTCTGGTCCACGGGCGTTCGCAGATCGACATTCCCCATGCATGGCTTGATATCGACAATGAGAGCGCGGTCTATCATTCCACCGCACATCTGCTCGATCTTGGCCACAAGCGGATTGCGATGATCAACGGGCGCCATGGCTTCACCTTCTCGCTGCACCGCGACGCTGGCTATCGTAAGGCGCTTGAAAGCCGGGGAATCGACTTTGATCCCGACCTGGTGGAACATGGCGATTTCACCGATGAAATCGGCTATTGCCTCGCCCGCAAGCTTCTGGAACGCAATCCACGTCCAACGGCATTCGTCGCAGGCTCCATGATGACCGCGCTCGGCATCTACCGTGCCGCCCGCTCCTTCGGCCTTACGATCGGCAAGGATATTTCCGTCATCGCCCATGACGACGTGATCTCGTTCCTCAGCGCCGGTAATATGGGTGCCGTCGCTGACTGCGACACGCTCTTCAATGCGCGCGGCTGGCAAGCGATGCGCCGACCTTTTGATGGATATCCTCGATGGGCGCGCGCCCACCGAAATCCA",
"9878<?JQONBB77:=EGMPDOHRNSTSTSTRSSSREMRSSRSSRSQSSLQLLLLMPPPRRSSSRRRRSSSRSSSRRSRRRRSRIJJJONLTTTTRRROLLLLLLTTTTTTTRRRRPPPSRRSTTTRSRRRSPOLOOLOSSSSRSSRSRPRPPPSPSTSTSQSQTRURSSSSSTTTTRRRSRRSRSSSURRRRSWSSRRRSSTSRRTTTTTTTTTPPSRPPSTTTTRSRUSSSSUSPPPPRSQRTTTTSSSRRRRRTRRSTRTTTRTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTPSPPPPPRRRTTTTTRSSSSRRSRRSTSTTTTTTTTRTTRSSSTRSRSRRSSSTTTRSSRSSSUSSQSSRSSSSRRRRRSRRTRTSRTSURTTTTTRSSSSSSTRTRRRSSRSSRTSPSPPPRTRRSSRRSTRRRSSRRRRTTTRRRUSRSSSTRSSSSRRLLLLOLNOTTTSRRRRSSSTTTTTTTTTTTWRRPPPPPPSTTTTWPPMSTPTTTTTTTTSTSRSRSSTTRSSSSTTTTTTTTPPPPKPPSRSSSTSSSSTSSRRSSSTTTTTRRSSTTSSRSSSSSTTTTTTTTTTTRTTTSRSSSSSTTTTRRRSSPPSPPPTTTTSRRPORSRPPPPLPPSSSSTTSSRSSSRPPNSSQRTTTTTSSPKKGMNPSSQSSRSSSSQLLIL?HSTQPSSPLRSQSSRSUQSMRSSUPRLLPGEPPSNMRPTYRRQPMMGGPMLQE?CENRNCRSLQRNTTKTKLQTXSRSRTTPRQXISRCONK<?IDTPPPDDIR?B<LALBDL@;LQQLCH?E=@IC<9F9?I;9;=8");
ctg . setReadTiling (tlevec);
clocka = clock( );
for ( int i = 0; i < ITERS; i ++ )
red . writeMessage (msg);
clockb = clock( );
loopa = (double)(clockb - clocka);
clocka = clock( );
for ( int i = 0; i < ITERS; i ++ )
red . readMessage (msg);
clockb = clock( );
loopb = (double)(clockb - clocka);
msg . setField ("eid", "hello");
msg . setField ("bla", "foo");
msg . write (cerr);
Message_t::const_iterator mi;
cerr << "\nField List\n";
for ( mi = msg . begin( ); mi != msg . end( ); ++ mi )
cerr << Decode (mi -> first) << endl;
cerr << endl
<< "loopa: " << (double)loopa / CLOCKS_PER_SEC << " sec.\n"
<< "loopb: " << (double)loopb / CLOCKS_PER_SEC << " sec.\n"
<< "granu: " << CLOCKS_PER_SEC << " of a sec.\n";
}
catch (Exception_t & e) {
cerr << "ERROR: exception\n" << e;
}
return 0;
}
| 59.921348 | 845 | 0.824864 | sagrudd |
e9c5d6019ab160363cb2b39eff1dc70a39db1525 | 1,078 | hpp | C++ | bnl/base/include/bnl/http3/event.hpp | DaanDeMeyer/h3c | 5fe5705afeebda94eb2fc8483dac6846b2deb85f | [
"MIT"
] | 4 | 2019-07-29T07:54:20.000Z | 2020-05-14T10:12:59.000Z | bnl/base/include/bnl/http3/event.hpp | DaanDeMeyer/h3c | 5fe5705afeebda94eb2fc8483dac6846b2deb85f | [
"MIT"
] | null | null | null | bnl/base/include/bnl/http3/event.hpp | DaanDeMeyer/h3c | 5fe5705afeebda94eb2fc8483dac6846b2deb85f | [
"MIT"
] | 1 | 2020-05-14T10:12:58.000Z | 2020-05-14T10:12:58.000Z | #pragma once
#include <bnl/base/buffer.hpp>
#include <bnl/base/export.hpp>
#include <bnl/http3/header.hpp>
#include <bnl/http3/settings.hpp>
#include <bnl/quic/event.hpp>
namespace bnl {
namespace http3 {
class BNL_BASE_EXPORT event {
public:
enum class type { settings, header, body, finished };
struct payload {
using settings = http3::settings;
struct header {
uint64_t id;
bool fin;
http3::header header;
};
using body = quic::data;
struct finished {
uint64_t id;
};
};
event(payload::settings settings) noexcept; // NOLINT
event(payload::header header) noexcept; // NOLINT
event(payload::body body) noexcept; // NOLINT
event(payload::finished finished) noexcept; // NOLINT
event(event &&other) noexcept;
event &operator=(event &&) = delete;
~event() noexcept;
operator type() const noexcept; // NOLINT
private:
const type type_;
public:
union {
payload::settings settings;
payload::header header;
payload::body body;
payload::finished finished;
};
};
}
}
| 18.586207 | 55 | 0.657699 | DaanDeMeyer |
8397256bd2d0a925f0e6c1a29152e1582cd95868 | 761 | cpp | C++ | stacks/Recursion/Factorial1.cpp | InamulRehman/DataStructures_and_Algorithms_Cplusplus | 7fb5ca3e9313ef302c7ce9bac3bb9ec9016ab906 | [
"MIT"
] | null | null | null | stacks/Recursion/Factorial1.cpp | InamulRehman/DataStructures_and_Algorithms_Cplusplus | 7fb5ca3e9313ef302c7ce9bac3bb9ec9016ab906 | [
"MIT"
] | null | null | null | stacks/Recursion/Factorial1.cpp | InamulRehman/DataStructures_and_Algorithms_Cplusplus | 7fb5ca3e9313ef302c7ce9bac3bb9ec9016ab906 | [
"MIT"
] | null | null | null | // calculating factorial using loop
#include <iostream>
using namespace std;
class factorial
{
private:
int fac;
public:
// function to calculate factorial
int fact (int val)
{
fac = 1;
if (val == 0)
{
return fac;
}
else
{
for(int i = fac; i <= val; i++ )
{
fac = fac * i;
}
return fac;
}
}
};
int main ()
{
factorial obj;
int val , result;
cout << "Enter value to calculate factorial: "<< flush;
cin >> val ;
result = obj.fact(val);
cout << "Factorial of " << val << " is " << result;
return 0;
}
| 15.530612 | 59 | 0.412615 | InamulRehman |
8398274554f23e9cb7aa54ac70e963a4059f5510 | 1,620 | cpp | C++ | src/ThreadPool.cpp | CaptainUnitaco/Clustered-Deferred-shading-in-Vulkan | 08803777a20a010015958af8bd841147fc6b7fd6 | [
"MIT"
] | 3 | 2020-06-24T07:13:59.000Z | 2020-10-22T03:49:15.000Z | src/ThreadPool.cpp | CaptainUnitaco/Clustered-Deferred-shading-in-Vulkan | 08803777a20a010015958af8bd841147fc6b7fd6 | [
"MIT"
] | null | null | null | src/ThreadPool.cpp | CaptainUnitaco/Clustered-Deferred-shading-in-Vulkan | 08803777a20a010015958af8bd841147fc6b7fd6 | [
"MIT"
] | null | null | null | /**
* @file 'ThreadPool.cpp'
* @brief Implementation of thread pool design pattern
* @copyright The MIT license
* @author Matej Karas
*/
#include "ThreadPool.h"
Thread::Thread(size_t id)
: mID(id)
{
mThread = std::thread(&Thread::run, this);
}
Thread::~Thread()
{
mDestroy = true;
if (mThread.joinable())
{
{
std::lock_guard<std::mutex> lock(mWorkMutex);
mWorkCondition.notify_one();
}
mThread.join();
}
}
void Thread::run()
{
while(true)
{
{
std::unique_lock<std::mutex> lock(mWorkMutex);
mWorkCondition.wait(lock, [this]() { return mWork != nullptr || mDestroy; });
if (mDestroy)
break;
auto work = std::move(mWork);
work(mID);
}
{
std::lock_guard<std::mutex> lock(mWorkMutex);
mFinished = true;
mWorkCondition.notify_one();
}
}
}
void Thread::addWork(ThreadFuncPtr work)
{
std::lock_guard<std::mutex> lock(mWorkMutex);
mWork = std::move(work);
mWorkCondition.notify_one();
}
void Thread::wait()
{
std::unique_lock<std::mutex> lock(mWorkMutex);
mWorkCondition.wait(lock, [this]() { return mFinished; });
mFinished = false;
}
ThreadPool::ThreadPool()
{
for (size_t i = 0; i < std::thread::hardware_concurrency(); i++)
mThreads.emplace_back(std::make_unique<Thread>(i));
}
void ThreadPool::addWorkMultiplex(const ThreadFuncPtr& work)
{
for (auto& thread : mThreads)
thread->addWork(work);
}
void ThreadPool::addWork(std::vector<ThreadFuncPtr>&& work)
{
for (size_t i = 0; i < work.size(); i++)
mThreads[i % mThreads.size()]->addWork(work[i]);
}
void ThreadPool::wait()
{
for (auto& thread : mThreads)
thread->wait();
}
| 17.802198 | 80 | 0.656173 | CaptainUnitaco |
839af6896db8dbaf433d9779630bd4ea41bf8a25 | 8,537 | cpp | C++ | src/apps/mediaplayer/interface/SubtitleBitmap.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/apps/mediaplayer/interface/SubtitleBitmap.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/apps/mediaplayer/interface/SubtitleBitmap.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* Copyright 2010, Stephan Aßmus <superstippi@gmx.de>.
* Distributed under the terms of the MIT License.
*/
#include "SubtitleBitmap.h"
#include <stdio.h>
#include <Bitmap.h>
#include <TextView.h>
#include "StackBlurFilter.h"
SubtitleBitmap::SubtitleBitmap()
:
fBitmap(NULL),
fTextView(new BTextView("offscreen text")),
fShadowTextView(new BTextView("offscreen text shadow")),
fCharsPerLine(36),
fUseSoftShadow(true),
fOverlayMode(false)
{
fTextView->SetStylable(true);
fTextView->MakeEditable(false);
fTextView->SetWordWrap(false);
fTextView->SetAlignment(B_ALIGN_CENTER);
fShadowTextView->SetStylable(true);
fShadowTextView->MakeEditable(false);
fShadowTextView->SetWordWrap(false);
fShadowTextView->SetAlignment(B_ALIGN_CENTER);
}
SubtitleBitmap::~SubtitleBitmap()
{
delete fBitmap;
delete fTextView;
delete fShadowTextView;
}
bool
SubtitleBitmap::SetText(const char* text)
{
if (text == fText)
return false;
fText = text;
_GenerateBitmap();
return true;
}
void
SubtitleBitmap::SetVideoBounds(BRect bounds)
{
if (bounds == fVideoBounds)
return;
fVideoBounds = bounds;
fUseSoftShadow = true;
_GenerateBitmap();
}
void
SubtitleBitmap::SetOverlayMode(bool overlayMode)
{
if (overlayMode == fOverlayMode)
return;
fOverlayMode = overlayMode;
_GenerateBitmap();
}
void
SubtitleBitmap::SetCharsPerLine(float charsPerLine)
{
if (charsPerLine == fCharsPerLine)
return;
fCharsPerLine = charsPerLine;
fUseSoftShadow = true;
_GenerateBitmap();
}
const BBitmap*
SubtitleBitmap::Bitmap() const
{
return fBitmap;
}
void
SubtitleBitmap::_GenerateBitmap()
{
if (!fVideoBounds.IsValid())
return;
delete fBitmap;
BRect bounds;
float outlineRadius;
_InsertText(bounds, outlineRadius, fOverlayMode);
bigtime_t startTime = 0;
if (!fOverlayMode && fUseSoftShadow)
startTime = system_time();
fBitmap = new BBitmap(bounds, B_BITMAP_ACCEPTS_VIEWS, B_RGBA32);
memset(fBitmap->Bits(), 0, fBitmap->BitsLength());
if (fBitmap->Lock()) {
fBitmap->AddChild(fShadowTextView);
fShadowTextView->ResizeTo(bounds.Width(), bounds.Height());
fShadowTextView->SetViewColor(0, 0, 0, 0);
fShadowTextView->SetDrawingMode(B_OP_ALPHA);
fShadowTextView->SetBlendingMode(B_PIXEL_ALPHA, B_ALPHA_COMPOSITE);
fShadowTextView->PushState();
fShadowTextView->Draw(bounds);
fShadowTextView->PopState();
if (!fOverlayMode && fUseSoftShadow) {
fShadowTextView->Sync();
StackBlurFilter filter;
filter.Filter(fBitmap, outlineRadius * 2);
}
fShadowTextView->RemoveSelf();
fBitmap->AddChild(fTextView);
fTextView->ResizeTo(bounds.Width(), bounds.Height());
if (!fOverlayMode && fUseSoftShadow)
fTextView->MoveTo(-outlineRadius / 2, -outlineRadius / 2);
else
fTextView->MoveTo(0, 0);
fTextView->SetViewColor(0, 0, 0, 0);
fTextView->SetDrawingMode(B_OP_ALPHA);
fTextView->SetBlendingMode(B_PIXEL_ALPHA, B_ALPHA_COMPOSITE);
fTextView->PushState();
fTextView->Draw(bounds);
fTextView->PopState();
fTextView->Sync();
fTextView->RemoveSelf();
fBitmap->Unlock();
}
if (!fOverlayMode && fUseSoftShadow && system_time() - startTime > 10000)
fUseSoftShadow = false;
}
struct ParseState {
ParseState(rgb_color color)
:
color(color),
bold(false),
italic(false),
underlined(false),
previous(NULL)
{
}
ParseState(ParseState* previous)
:
color(previous->color),
bold(previous->bold),
italic(previous->italic),
underlined(previous->underlined),
previous(previous)
{
}
rgb_color color;
bool bold;
bool italic;
bool underlined;
ParseState* previous;
};
static bool
find_next_tag(const BString& string, int32& tagPos, int32& tagLength,
ParseState*& state)
{
static const char* kTags[] = {
"<b>", "</b>",
"<i>", "</i>",
"<u>", "</u>",
"<font color=\"#", "</font>"
};
static const int32 kTagCount = sizeof(kTags) / sizeof(const char*);
int32 startPos = tagPos;
tagPos = string.Length();
tagLength = 0;
// Find the next tag closest from the current position
// This way of doing it allows broken input with overlapping tags even.
BString tag;
for (int32 i = 0; i < kTagCount; i++) {
int32 nextTag = string.IFindFirst(kTags[i], startPos);
if (nextTag >= startPos && nextTag < tagPos) {
tagPos = nextTag;
tag = kTags[i];
}
}
if (tag.Length() == 0)
return false;
// Tag found, ParseState will change.
tagLength = tag.Length();
if (tag == "<b>") {
state = new ParseState(state);
state->bold = true;
} else if (tag == "<i>") {
state = new ParseState(state);
state->italic = true;
} else if (tag == "<u>") {
state = new ParseState(state);
state->underlined = true;
} else if (tag == "<font color=\"#") {
state = new ParseState(state);
char number[16];
snprintf(number, sizeof(number), "0x%.6s",
string.String() + tagPos + tag.Length());
int colorInt;
if (sscanf(number, "%x", &colorInt) == 1) {
state->color.red = (colorInt & 0xff0000) >> 16;
state->color.green = (colorInt & 0x00ff00) >> 8;
state->color.blue = (colorInt & 0x0000ff);
// skip 'RRGGBB">' part, too
tagLength += 8;
}
} else if (tag == "</b>" || tag == "</i>" || tag == "</u>"
|| tag == "</font>") {
// Closing tag, pop state
if (state->previous != NULL) {
ParseState* oldState = state;
state = state->previous;
delete oldState;
}
}
return true;
}
static void
apply_state(BTextView* textView, const ParseState* state, BFont font,
bool changeColor)
{
uint16 face = 0;
if (state->bold || state->italic || state->underlined) {
if (state->bold)
face |= B_BOLD_FACE;
if (state->italic)
face |= B_ITALIC_FACE;
// NOTE: This is probably not supported by the app_server (perhaps
// it is if the font contains a specific underline face).
if (state->underlined)
face |= B_UNDERSCORE_FACE;
} else
face = B_REGULAR_FACE;
font.SetFace(face);
if (changeColor)
textView->SetFontAndColor(&font, B_FONT_ALL, &state->color);
else
textView->SetFontAndColor(&font, B_FONT_ALL, NULL);
}
static void
parse_text(const BString& string, BTextView* textView, const BFont& font,
const rgb_color& color, bool changeColor)
{
ParseState rootState(color);
// Colors may change, but alpha channel will be preserved
ParseState* state = &rootState;
int32 pos = 0;
while (pos < string.Length()) {
int32 nextPos = pos;
int32 tagLength;
bool stateChanged = find_next_tag(string, nextPos, tagLength, state);
if (nextPos > pos) {
// Insert text between last and next tags
BString subString;
string.CopyInto(subString, pos, nextPos - pos);
textView->Insert(subString.String());
}
pos = nextPos + tagLength;
if (stateChanged)
apply_state(textView, state, font, changeColor);
}
// Cleanup states in case the input text had non-matching tags.
while (state->previous != NULL) {
ParseState* oldState = state;
state = state->previous;
delete oldState;
}
}
void
SubtitleBitmap::_InsertText(BRect& textRect, float& outlineRadius,
bool overlayMode)
{
BFont font(be_plain_font);
float fontSize = ceilf((fVideoBounds.Width() * 0.9) / fCharsPerLine);
outlineRadius = ceilf(fontSize / 28.0);
font.SetSize(fontSize);
rgb_color shadow;
shadow.red = 0;
shadow.green = 0;
shadow.blue = 0;
shadow.alpha = 200;
rgb_color color;
color.red = 255;
color.green = 255;
color.blue = 255;
color.alpha = 240;
textRect = fVideoBounds;
textRect.OffsetBy(outlineRadius, outlineRadius);
fTextView->SetText(NULL);
fTextView->SetFontAndColor(&font, B_FONT_ALL, &color);
fTextView->Insert(" ");
parse_text(fText, fTextView, font, color, true);
font.SetFalseBoldWidth(outlineRadius);
fShadowTextView->ForceFontAliasing(overlayMode);
fShadowTextView->SetText(NULL);
fShadowTextView->SetFontAndColor(&font, B_FONT_ALL, &shadow);
fShadowTextView->Insert(" ");
parse_text(fText, fShadowTextView, font, shadow, false);
// This causes the BTextView to calculate the layout of the text
fTextView->SetTextRect(BRect(0, 0, 0, 0));
fTextView->SetTextRect(textRect);
fShadowTextView->SetTextRect(BRect(0, 0, 0, 0));
fShadowTextView->SetTextRect(textRect);
textRect = fTextView->TextRect();
textRect.InsetBy(-outlineRadius, -outlineRadius);
textRect.OffsetTo(B_ORIGIN);
// Make sure the text rect really finishes behind the last line.
// We don't want any accidental extra space.
textRect.bottom = outlineRadius;
int32 lineCount = fTextView->CountLines();
for (int32 i = 0; i < lineCount; i++)
textRect.bottom += fTextView->LineHeight(i);
textRect.bottom += outlineRadius;
}
| 22.174026 | 74 | 0.699075 | Kirishikesan |
839c75e18a6aeab381fee29142df80c268967d3b | 4,977 | cpp | C++ | ID3v2/source/ID3v2-Version.cpp | macmade/ID3v2 | be8022a5ee94197a58710a55931aea7d89ae3f71 | [
"MIT"
] | 2 | 2018-12-15T22:30:58.000Z | 2019-11-24T21:25:02.000Z | ID3v2/source/ID3v2-Version.cpp | macmade/ID3v2 | be8022a5ee94197a58710a55931aea7d89ae3f71 | [
"MIT"
] | null | null | null | ID3v2/source/ID3v2-Version.cpp | macmade/ID3v2 | be8022a5ee94197a58710a55931aea7d89ae3f71 | [
"MIT"
] | 1 | 2018-01-22T13:09:06.000Z | 2018-01-22T13:09:06.000Z | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2014 Jean-David Gadina - www.xs-labs.com / www.digidna.net
*
* 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.
******************************************************************************/
/*!
* @header ID3v2-Tag.cpp
* @copyright (c) 2014 - Jean-David Gadina - www.xs-labs.com / www.digidna.net
* @abstract ID3v2 version
*/
#include <ID3v2.h>
#include <sstream>
namespace ID3v2
{
class Version::IMPL
{
public:
IMPL( void );
unsigned int major;
unsigned int minor;
unsigned int revision;
};
Version::Version( unsigned int major, unsigned int minor, unsigned int revision ): impl( new IMPL )
{
this->impl->major = major;
this->impl->minor = minor;
this->impl->revision = revision;
}
Version::Version( const Version & version ): impl( new IMPL )
{
this->impl->major = version.impl->major;
this->impl->minor = version.impl->minor;
this->impl->revision = version.impl->revision;
}
Version::~Version( void )
{
delete this->impl;
}
Version & Version::operator =( const Version & version )
{
this->impl->major = version.impl->major;
this->impl->minor = version.impl->minor;
this->impl->revision = version.impl->revision;
return *( this );
}
bool Version::operator ==( const Version & version ) const
{
return this->GetMajor() == version.GetMajor() && this->GetMinor() == version.GetMinor() && this->GetRevision() == version.GetRevision();
}
bool Version::operator !=( const Version & version ) const
{
return ( this->operator ==( version ) ) ? false : true;
}
bool Version::operator >=( const Version & version ) const
{
if( this->operator ==( version ) )
{
return true;
}
return this->operator >( version );
}
bool Version::operator <=( const Version & version ) const
{
if( this->operator ==( version ) )
{
return true;
}
return this->operator <( version );
}
bool Version::operator >( const Version & version ) const
{
if( this->GetMajor() > version.GetMajor() )
{
return true;
}
if( this->GetMinor() > version.GetMinor() )
{
return true;
}
if( this->GetRevision() > version.GetRevision() )
{
return true;
}
return false;
}
bool Version::operator <( const Version & version ) const
{
if( this->GetMajor() < version.GetMajor() )
{
return true;
}
if( this->GetMinor() < version.GetMinor() )
{
return true;
}
if( this->GetRevision() < version.GetRevision() )
{
return true;
}
return false;
}
std::string Version::GetStringValue( void ) const
{
std::stringstream ss;
ss << this->impl->major;
ss << ".";
ss << this->impl->minor;
ss << ".";
ss << this->impl->revision;
return ss.str();
}
unsigned int Version::GetMajor( void ) const
{
return this->impl->major;
}
unsigned int Version::GetMinor( void ) const
{
return this->impl->minor;
}
unsigned int Version::GetRevision( void ) const
{
return this->impl->revision;
}
Version::IMPL::IMPL( void )
{
this->major = 0;
this->minor = 0;
this->revision = 0;
}
}
| 27.65 | 144 | 0.53486 | macmade |
839dfc1a40407c2bde02e2811a617d92b9282ae5 | 15,383 | cpp | C++ | modules/core/jobsystem/jobsystem.cpp | maoxiezhao/Vulkan-Test | 620f3aa420e7995c3428ed2856896a9e5f5c8b5a | [
"MIT"
] | 3 | 2022-03-02T08:55:54.000Z | 2022-03-23T05:56:43.000Z | modules/core/jobsystem/jobsystem.cpp | maoxiezhao/Vulkan-Test | 620f3aa420e7995c3428ed2856896a9e5f5c8b5a | [
"MIT"
] | null | null | null | modules/core/jobsystem/jobsystem.cpp | maoxiezhao/Vulkan-Test | 620f3aa420e7995c3428ed2856896a9e5f5c8b5a | [
"MIT"
] | null | null | null | #include "jobsystem.h"
#include "core\memory\memory.h"
#include "core\platform\fiber.h"
#include "core\platform\platform.h"
#include "core\platform\sync.h"
#include "core\platform\atomic.h"
#pragma warning( push )
#pragma warning (disable : 6385)
namespace VulkanTest
{
namespace Jobsystem
{
//////////////////////////////////////////////////////////////
// Definition
const U32 MAX_FIBER_COUNT = 512;
const U32 MAX_JOB_HANDLE_COUNT = 4096;
const U32 HANDLE_ID_MASK = 0x0000ffff;
const U32 HANDLE_GENERATION_MASK = 0xffff0000;
#ifdef _WIN32
static void __stdcall FiberFunc(void* data);
#else
static void FiberFunc(void* data);
#endif
struct ManagerImpl;
struct WorkerThread;
struct JobImpl
{
JobFunc task = nullptr;
void* data = nullptr;
JobHandle finishHandle;
JobHandle precondition;
U8 workerIndex;
};
struct JobCounter
{
volatile I32 value = 0;
JobImpl nextJob;
JobHandle sibling = INVALID_HANDLE;
U32 generation = 0; // use for check
};
struct WorkerFiber
{
U32 index = 0;
Fiber::Handle handle = Fiber::INVALID_HANDLE;
JobImpl currentJob;
};
struct ManagerImpl
{
public:
Mutex sync;
ConditionMutex jobQueueLock;
JobCounter handleCounters[MAX_JOB_HANDLE_COUNT];
std::vector<U32> handlePool;
std::vector<WorkerFiber*> readyFibers;
std::vector<WorkerFiber*> freeFibers;
WorkerFiber fiberPool[MAX_FIBER_COUNT];
std::vector<WorkerThread*> workers;
std::vector<JobImpl> jobQueue;
public:
ManagerImpl();
JobHandle AllocateHandle();
void IncHandle(JobHandle* jobHandle);
void DecHandle(JobHandle jobHandle);
bool IsHandleValid(JobHandle jobHandle)const;
bool IsHandleZero(JobHandle jobHandle, bool isLock);
void ReleaseHandle(JobHandle jobHandle, bool isLock);
void PushJob(JobImpl job);
};
static LocalPtr<ManagerImpl> gManager;
static thread_local WorkerThread* gWorker = nullptr;
WorkerThread* GetWorker()
{
return gWorker;
}
struct WorkerThread : Thread
{
public:
U32 workderIndex;
ManagerImpl& manager;
bool isFinished = false;
Fiber::Handle primaryFiber = Fiber::INVALID_HANDLE;
WorkerFiber* currentFiber = nullptr;
std::vector<WorkerFiber*> readyFibers;
std::vector<JobImpl> jobQueue;
#ifdef JOB_SYSTEM_DEBUG
volatile I32 numFinishedJob = 0;
#endif // JOB_SYSTEM_DEBUG
public:
WorkerThread(ManagerImpl& manager_, U32 workerIndex_) :
manager(manager_),
workderIndex(workerIndex_)
{
}
~WorkerThread()
{
}
int Task() override
{
Platform::SetCurrentThreadIndex(workderIndex + 1);
gWorker = this;
primaryFiber = Fiber::Create(Fiber::THIS_THREAD);
gManager->sync.Lock();
WorkerFiber* fiber = gManager->freeFibers.back();
gManager->freeFibers.pop_back();
if (!Fiber::IsValid(fiber->handle))
fiber->handle = Fiber::Create(64 * 1024, FiberFunc, fiber);
gWorker->currentFiber = fiber;
Fiber::SwitchTo(gWorker->primaryFiber, fiber->handle);
return 0;
}
};
ManagerImpl::ManagerImpl()
{
handlePool.resize(MAX_JOB_HANDLE_COUNT);
for (int i = 0; i < MAX_JOB_HANDLE_COUNT; i++)
{
handleCounters[i].sibling = INVALID_HANDLE;
handlePool[i] = i;;
}
}
JobHandle ManagerImpl::AllocateHandle()
{
if (handlePool.empty())
return INVALID_HANDLE;
U32 handle = handlePool.back();
handlePool.pop_back();
JobCounter& counter = handleCounters[handle & HANDLE_ID_MASK];
counter.value = 1;
counter.sibling = INVALID_HANDLE;
counter.nextJob.task = nullptr;
return (handle & HANDLE_ID_MASK) | counter.generation;
}
void ManagerImpl::IncHandle(JobHandle* jobHandle)
{
ASSERT(jobHandle != nullptr);
ScopedMutex lock(sync);
if (IsHandleValid(*jobHandle) && !IsHandleZero(*jobHandle, false))
handleCounters[*jobHandle & HANDLE_ID_MASK].value++;
else
*jobHandle = AllocateHandle();
}
void ManagerImpl::DecHandle(JobHandle jobHandle)
{
ScopedMutex lock(sync);
JobCounter& counter = handleCounters[jobHandle & HANDLE_ID_MASK];
counter.value--;
if (counter.value > 0)
return;
ReleaseHandle(jobHandle, false);
}
bool ManagerImpl::IsHandleValid(JobHandle jobHandle)const
{
return jobHandle != INVALID_HANDLE;
}
bool ManagerImpl::IsHandleZero(JobHandle jobHandle, bool isLock)
{
if (!IsHandleValid(jobHandle))
return false;
const U32 id = jobHandle & HANDLE_ID_MASK;
const U32 generation = jobHandle & HANDLE_GENERATION_MASK;
if (isLock) sync.Lock();
bool ret = handleCounters[id].value == 0 || handleCounters[id].generation != generation;
if (isLock) sync.Unlock();
return ret;
}
void ManagerImpl::ReleaseHandle(JobHandle jobHandle, bool isLock)
{
if (isLock) sync.Lock();
JobHandle iter = jobHandle;
while (IsHandleValid(iter))
{
JobCounter& counter = handleCounters[iter & HANDLE_ID_MASK];
if (counter.nextJob.task != nullptr)
{
ScopedConditionMutex lock(jobQueueLock);
PushJob(counter.nextJob);
}
counter.generation = (((counter.generation >> 16) + 1) & 0xffff) << 16;
handlePool.push_back(iter & HANDLE_ID_MASK | counter.generation);
counter.nextJob.task = nullptr;
iter = counter.sibling;
}
if (isLock) sync.Unlock();
}
void ManagerImpl::PushJob(JobImpl job)
{
if (job.workerIndex == ANY_WORKER)
{
jobQueue.push_back(job);
for (auto worker : workers)
worker->Wakeup();
}
else
{
WorkerThread* worker = gManager->workers[job.workerIndex % gManager->workers.size()];
worker->jobQueue.push_back(job);
worker->Wakeup();
}
}
//////////////////////////////////////////////////////////////
// Methods
bool Initialize(U32 numWorkers)
{
Platform::SetCurrentThreadIndex(0);
gManager.Create();
for (int i = 0; i < MAX_FIBER_COUNT; i++)
{
WorkerFiber* fiber = &gManager->fiberPool[i];
fiber->index = i;
fiber->handle = Fiber::INVALID_HANDLE;
gManager->freeFibers.push_back(fiber);
}
numWorkers = std::min(64u, numWorkers);
gManager->workers.reserve(numWorkers);
for (U32 i = 0; i < numWorkers; i++)
{
WorkerThread* worker = CJING_NEW(WorkerThread)(*gManager, i);
if (worker->Create("Worker"))
{
gManager->workers.push_back(worker);
worker->SetAffinity((U64)1u << i);
}
}
return !gManager->workers.empty();
}
void Uninitialize()
{
// Clear workers
for (auto worker : gManager->workers)
{
worker->isFinished = true;
worker->Wakeup();
}
for (auto worker : gManager->workers)
{
while (!worker->IsFinished())
worker->Wakeup();
worker->Destroy();
CJING_SAFE_DELETE(worker);
}
gManager->workers.clear();
// Clear fibers
for (auto& fiber : gManager->fiberPool)
{
if (Fiber::IsValid(fiber.handle))
Fiber::Destroy(fiber.handle);
}
gManager.Destroy();
}
void RunInternal(JobFunc task, void* data, bool doLock, JobHandle precondition, JobHandle* handle, int workerIndex)
{
JobImpl job = {};
job.data = data;
job.task = task;
job.precondition = precondition;
job.workerIndex = workerIndex != ANY_WORKER ? workerIndex % gManager->workers.size() : ANY_WORKER;
if (doLock) gManager->sync.Lock();
job.finishHandle = [&]() {
if (handle == nullptr)
{
return INVALID_HANDLE;
}
if (gManager->IsHandleValid(*handle) && !gManager->IsHandleZero(*handle, false))
{
gManager->handleCounters[*handle & HANDLE_ID_MASK].value++;
return *handle;
}
return gManager->AllocateHandle();
}();
if (handle != nullptr)
*handle = job.finishHandle;
if (!gManager->IsHandleValid(precondition) || gManager->IsHandleZero(precondition, false))
{
ScopedConditionMutex lock(gManager->jobQueueLock);
gManager->PushJob(job);
}
else
{
auto& preCounter = gManager->handleCounters[precondition & HANDLE_ID_MASK];
if (preCounter.nextJob.task != nullptr)
{
auto slibingHandle = gManager->AllocateHandle();
auto& slibingCounter = gManager->handleCounters[slibingHandle & HANDLE_ID_MASK];
slibingCounter.nextJob = job;
slibingCounter.sibling = preCounter.sibling;
preCounter.sibling = slibingHandle;
}
else
{
preCounter.nextJob = job;
}
}
if (doLock) gManager->sync.Unlock();
}
void Run(const JobInfo& jobInfo, JobHandle* handle)
{
RunInternal(
jobInfo.jobFunc,
jobInfo.data,
true,
jobInfo.precondition,
handle,
ANY_WORKER
);
}
void Run(void*data, JobFunc func, JobHandle* handle)
{
RunInternal(
func,
data,
true,
INVALID_HANDLE,
handle,
ANY_WORKER
);
}
void RunEx(void* data, JobFunc func, JobHandle* handle, JobHandle precondition)
{
RunInternal(
func,
data,
true,
precondition,
handle,
ANY_WORKER
);
}
void Wait(JobHandle handle)
{
gManager->sync.Lock();
if (gManager->IsHandleZero(handle, false))
{
gManager->sync.Unlock();
return;
}
if (GetWorker() == nullptr)
{
while (!gManager->IsHandleZero(handle, false))
{
gManager->sync.Unlock();
Platform::Sleep(1);
gManager->sync.Lock();
}
gManager->sync.Unlock();
}
else
{
WorkerFiber* currentFiber = GetWorker()->currentFiber;
RunInternal([](void* data) {
ScopedConditionMutex lock(gManager->jobQueueLock);
WorkerFiber* fiber = (WorkerFiber*)data;
if (fiber->currentJob.workerIndex == ANY_WORKER)
{
gManager->readyFibers.push_back(fiber);
for (auto worker : gManager->workers)
worker->Wakeup();
}
else
{
WorkerThread* worker = gManager->workers[fiber->currentJob.workerIndex % gManager->workers.size()];
worker->readyFibers.push_back(fiber);
worker->Wakeup();
}
}, currentFiber, false, handle, nullptr, 0); // currentFiber->currentJob.workerIndex);
WorkerFiber* newFiber = gManager->freeFibers.back();
gManager->freeFibers.pop_back();
if (!Fiber::IsValid(newFiber->handle))
newFiber->handle = Fiber::Create(64 * 1024, FiberFunc, newFiber);
GetWorker()->currentFiber = newFiber;
Fiber::SwitchTo(currentFiber->handle, newFiber->handle);
GetWorker()->currentFiber = currentFiber;
gManager->sync.Unlock();
}
}
#ifdef _WIN32
static void __stdcall FiberFunc(void* data)
#else
static void FiberFunc(void* data);
#endif
{
gManager->sync.Unlock();
WorkerFiber* currentFiber = (WorkerFiber*)(data);
WorkerThread* worker = GetWorker();
while (!worker->isFinished)
{
WorkerFiber* readyFiber = nullptr;
JobImpl job;
while (!worker->isFinished)
{
ScopedConditionMutex lock(gManager->jobQueueLock);
// Local
if (!worker->readyFibers.empty())
{
readyFiber = worker->readyFibers.back();
worker->readyFibers.pop_back();
break;
}
if (!worker->jobQueue.empty())
{
job = worker->jobQueue.back();
worker->jobQueue.pop_back();
break;
}
// Global
if (!gManager->readyFibers.empty())
{
readyFiber = gManager->readyFibers.back();
gManager->readyFibers.pop_back();
break;
}
if (!gManager->jobQueue.empty())
{
job = gManager->jobQueue.back();
gManager->jobQueue.pop_back();
break;
}
worker->Sleep(gManager->jobQueueLock);
}
if (worker->isFinished)
break;
if (readyFiber != nullptr)
{
worker->currentFiber = readyFiber;
gManager->sync.Lock();
gManager->freeFibers.push_back(currentFiber);
Fiber::SwitchTo(currentFiber->handle, readyFiber->handle);
gManager->sync.Unlock();
worker = GetWorker();
worker->currentFiber = currentFiber;
}
else if (job.task != nullptr)
{
#ifdef JOB_SYSTEM_DEBUG
AtomicIncrement(&worker->numFinishedJob);
#endif
currentFiber->currentJob = job;
job.task(job.data);
currentFiber->currentJob.task = nullptr;
if (gManager->IsHandleValid(job.finishHandle))
gManager->DecHandle(job.finishHandle);
worker = GetWorker();
}
}
Fiber::SwitchTo(currentFiber->handle, worker->primaryFiber);
}
#ifdef JOB_SYSTEM_DEBUG
void ShowDebugInfo()
{
std::cout << "Worker infos:" << std::endl;
for (auto& worker : gManager->workers)
{
std::cout << worker->workderIndex << "; numFinishedJob:";
std::cout << worker->numFinishedJob;
std::cout << std::endl;
}
}
#endif
}
}
#pragma warning (pop) | 28.861163 | 119 | 0.533251 | maoxiezhao |
83a08cbb6a38c6b2cfbb6753f79b8600bc12c77e | 1,737 | cpp | C++ | src/Receiver.cpp | NassimEzz/Projet_2A_SeriousGameAlgorithme | 588eda6049d732f5908e2c0876b7363c9ff1fee3 | [
"Unlicense",
"MIT"
] | null | null | null | src/Receiver.cpp | NassimEzz/Projet_2A_SeriousGameAlgorithme | 588eda6049d732f5908e2c0876b7363c9ff1fee3 | [
"Unlicense",
"MIT"
] | null | null | null | src/Receiver.cpp | NassimEzz/Projet_2A_SeriousGameAlgorithme | 588eda6049d732f5908e2c0876b7363c9ff1fee3 | [
"Unlicense",
"MIT"
] | null | null | null | #include "Receiver.h"
#include "Utils.h"
Receiver::Receiver(const Point &position, const PictureInformer &emptyReceiverInformer,
const std::string &wrongAnswerPicture, const std::string &lockedReceiverPicture) {
_emptyReceiverPicture = emptyReceiverInformer.picturePath;
_wrongAnswerPicture = wrongAnswerPicture;
_lockedReceiverPicture = lockedReceiverPicture;
_rect = {position.x, position.y, emptyReceiverInformer.getPictureWidth(), emptyReceiverInformer.getPictureHeight()};
_uniqIDDrag = 0;
}
void Receiver::drawMe(Window *window, bool isRCorrect) const {
if (!isRCorrect) {
window->drawPng(_rect.x, _rect.y, _wrongAnswerPicture);
} else if (_uniqIDDrag != 0) {
window->drawPng(_rect.x, _rect.y, _lockedReceiverPicture);
} else {
window->drawPng(_rect.x, _rect.y, _emptyReceiverPicture);
}
}
bool Receiver::isAvailable(long dragUniqueId, int x, int y) {
return ((isEmpty()) || (dragUniqueId == _uniqIDDrag)) && (_rect.isInRectangle(x, y));
}
void Receiver::setReceiverContent(DraggableRectangle *instruction, unsigned int x, unsigned int y) {
if (_rect.isInRectangle((int) x, (int) y)) {
instruction->setMeInReceiver(_rect.x, _rect.y);
_uniqIDDrag = instruction->getUniqueID();
_logicIDDrag = instruction->getLogicID();
}
}
bool Receiver::isOutOfReceiver(long dragUniqueId, unsigned int x, unsigned int y) {
return (!(_rect.isInRectangle((int) x, (int) y)) && (dragUniqueId == _uniqIDDrag));
}
int Receiver::getCurrentDragLogicID() const {
return _logicIDDrag;
}
bool Receiver::isEmpty() const {
return _uniqIDDrag == 0;
}
void Receiver::resetDrag() {
_logicIDDrag = 0;
_uniqIDDrag = 0;
}
| 33.403846 | 120 | 0.699482 | NassimEzz |
83a3c20c09aff9310973b4abefa826acbbe78412 | 3,994 | cpp | C++ | test/integration/ttl.cpp | sptrakesh/config-db | 583ef3a3b636b2d56283194ff2b183bac2a36f21 | [
"Apache-2.0"
] | null | null | null | test/integration/ttl.cpp | sptrakesh/config-db | 583ef3a3b636b2d56283194ff2b183bac2a36f21 | [
"Apache-2.0"
] | null | null | null | test/integration/ttl.cpp | sptrakesh/config-db | 583ef3a3b636b2d56283194ff2b183bac2a36f21 | [
"Apache-2.0"
] | null | null | null | //
// Created by Rakesh on 11/01/2022.
//
#include <catch2/catch.hpp>
#include <iostream>
#include <thread>
#include "../../src/api/api.h"
using namespace spt::configdb::api;
using namespace spt::configdb::model;
using namespace std::string_literals;
using namespace std::string_view_literals;
SCENARIO( "TTL test", "[ttl]" )
{
GIVEN( "Given a batch of keys" )
{
const auto key1 = "/akey1"sv;
const auto key2 = "/akey2"sv;
const auto dest1 = "/bkey1"sv;
const auto dest2 = "/bkey2"sv;
WHEN( "Creating keys" )
{
const auto kvs = std::vector<Pair>{ { key1, "value"sv }, { key2, "value"sv } };
const auto status = set( kvs );
REQUIRE( status );
}
AND_WHEN( "Retrieving the keys" )
{
const auto keys = std::vector<std::string_view>{ key1, key2 };
const auto results = get( keys );
REQUIRE_FALSE( results.empty() );
REQUIRE( results.size() == keys.size() );
for ( auto i = 0; i < 2; ++i )
{
REQUIRE( results[i].first == keys[i] );
REQUIRE( results[i].second );
REQUIRE( *results[i].second == "value"s );
}
}
AND_WHEN( "Retrieving non-existent TTL" )
{
const auto keys = std::vector<std::string_view>{ key1, key2 };
const auto results = ttl( keys );
REQUIRE_FALSE( results.empty() );
REQUIRE( results.size() == keys.size() );
for ( auto i = 0; i < 2; ++i )
{
REQUIRE( results[i].first == keys[i] );
REQUIRE( results[i].second.count() == 0 );
}
}
AND_WHEN( "Setting a TTL for the keys" )
{
auto opts = RequestData::Options{ 2u };
auto kvs = std::vector<RequestData>{};
kvs.reserve( 2 );
kvs.emplace_back( key1, "value"sv, opts );
kvs.emplace_back( key2, "value"sv, opts );
const auto status = set( kvs );
REQUIRE( status );
}
AND_WHEN( "Retrieving the TTL values" )
{
const auto keys = std::vector<std::string_view>{ key1, key2 };
const auto results = ttl( keys );
REQUIRE_FALSE( results.empty() );
REQUIRE( results.size() == keys.size() );
for ( auto i = 0; i < 2; ++i )
{
REQUIRE( results[i].first == keys[i] );
REQUIRE( results[i].second.count() > 0 );
}
}
AND_WHEN( "Moving the keys" )
{
auto opts = RequestData::Options{ 4u };
auto kvs = std::vector<RequestData>{};
kvs.reserve( 2 );
kvs.emplace_back( key1, dest1, opts );
kvs.emplace_back( key2, dest2, opts );
const auto status = spt::configdb::api::move( kvs );
REQUIRE( status );
}
AND_WHEN( "Retrieving the TTL for destinations" )
{
const auto keys = std::vector<std::string_view>{ dest1, dest2 };
const auto results = ttl( keys );
REQUIRE_FALSE( results.empty() );
REQUIRE( results.size() == keys.size() );
for ( auto i = 0; i < 2; ++i )
{
REQUIRE( results[i].first == keys[i] );
REQUIRE( results[i].second.count() > 2 );
}
}
AND_WHEN( "Reading the auto deleted keys" )
{
std::cout << "Sleeping 5s to expire key\n";
std::this_thread::sleep_for( std::chrono::seconds{ 5 } );
const auto keys = std::vector<std::string_view>{ dest1, dest2 };
const auto results = get( keys );
REQUIRE_FALSE( results.empty() );
REQUIRE( results.size() == keys.size() );
for ( auto i = 0; i < 2; ++i )
{
REQUIRE( results[i].first == keys[i] );
REQUIRE_FALSE( results[i].second );
}
}
AND_WHEN( "Retrieving the TTL for auto deleted destination" )
{
const auto keys = std::vector<std::string_view>{ dest1, dest2 };
const auto results = ttl( keys );
REQUIRE_FALSE( results.empty() );
REQUIRE( results.size() == keys.size() );
for ( auto i = 0; i < 2; ++i )
{
REQUIRE( results[i].first == keys[i] );
REQUIRE( results[i].second.count() == 0 );
}
}
}
}
| 28.942029 | 85 | 0.554331 | sptrakesh |
83a6351c3132b0ff81025ea256c6c9c2b8150f9c | 1,306 | hpp | C++ | bench/tests/std/file_exception.hpp | bureau14/qdb-benchmark | 1839d7ac04417de56b7a7fb2b7deff50756b3048 | [
"BSD-2-Clause"
] | 5 | 2017-01-19T09:35:40.000Z | 2021-02-26T07:31:38.000Z | bench/tests/std/file_exception.hpp | bureau14/qdb-benchmark | 1839d7ac04417de56b7a7fb2b7deff50756b3048 | [
"BSD-2-Clause"
] | 1 | 2015-11-09T15:38:28.000Z | 2015-11-12T11:14:58.000Z | bench/tests/std/file_exception.hpp | bureau14/qdb-benchmark | 1839d7ac04417de56b7a7fb2b7deff50756b3048 | [
"BSD-2-Clause"
] | 3 | 2015-11-02T09:37:09.000Z | 2017-05-05T06:38:49.000Z | #pragma once
#include <stdexcept>
#include <string>
namespace bench
{
namespace tests
{
namespace std_
{
class file_exception : public std::exception
{
public:
file_exception(const std::string & action, const std::string & filename, int error)
{
_message = "Failed to " + action + " " + filename + " (error " + std::to_string(error) + ")";
}
virtual const char * what() const throw()
{
return _message.c_str();
}
private:
std::string _message;
};
class create_file_exception : public file_exception
{
public:
create_file_exception(const std::string & filename, int error) : file_exception("create", filename, error)
{
}
};
class open_file_exception : public file_exception
{
public:
open_file_exception(const std::string & filename, int error) : file_exception("open", filename, error)
{
}
};
class read_file_exception : public file_exception
{
public:
read_file_exception(const std::string & filename, int error) : file_exception("read to", filename, error)
{
}
};
class write_file_exception : public file_exception
{
public:
write_file_exception(const std::string & filename, int error) : file_exception("write to", filename, error)
{
}
};
} // namespace std_
} // namespace tests
} // namespace bench
| 20.092308 | 111 | 0.678407 | bureau14 |
83a7b6bc8549888e1ab9a7ce2cf9981399d770cc | 811 | hpp | C++ | Include/PanelCandidate.hpp | Andres6936/QT-Elecciones-CPP | ab401c89d35d497fe4ba7d32aa086c8a25b66d48 | [
"Unlicense"
] | null | null | null | Include/PanelCandidate.hpp | Andres6936/QT-Elecciones-CPP | ab401c89d35d497fe4ba7d32aa086c8a25b66d48 | [
"Unlicense"
] | null | null | null | Include/PanelCandidate.hpp | Andres6936/QT-Elecciones-CPP | ab401c89d35d497fe4ba7d32aa086c8a25b66d48 | [
"Unlicense"
] | null | null | null | #ifndef PANELCANDIDATE_HPP
#define PANELCANDIDATE_HPP
#include <QtWidgets/QFrame>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QVBoxLayout>
#include "Candidate.h"
class PanelCandidate : public QFrame
{
Q_OBJECT
private:
Candidate *candidate;
QVBoxLayout *layout;
QLabel *labelImage;
QLabel *labelNombre;
QLabel *labelApellido;
QLabel *labelEdad;
QLabel *labelPartidoPolitico;
QLabel *labelCostoCampanha;
QLabel *labelNumeroVotos;
QPushButton *buttonPorcentajeVotos;
QPushButton *buttonVotar;
public:
PanelCandidate(QWidget *nParent, Candidate *nCandidate);
virtual ~PanelCandidate() override;
void updateLabel();
private slots:
void handleButtonPressed();
};
#endif // PANELCANDIDATE_HPP
| 15.018519 | 60 | 0.729963 | Andres6936 |
83ade35d7e1ab4bb53e7f0f0b5dfe46bb771a59d | 7,965 | cpp | C++ | repos/plywood/src/reflect/ply-reflect/PersistReadSchema.cpp | boldsort/plywood | ab85a187e9e9d42d55cd3bd24be000898fd50234 | [
"MIT"
] | 742 | 2020-05-26T12:34:24.000Z | 2022-03-14T07:22:36.000Z | repos/plywood/src/reflect/ply-reflect/PersistReadSchema.cpp | boldsort/plywood | ab85a187e9e9d42d55cd3bd24be000898fd50234 | [
"MIT"
] | 18 | 2020-05-27T20:29:15.000Z | 2022-01-17T00:19:45.000Z | repos/plywood/src/reflect/ply-reflect/PersistReadSchema.cpp | boldsort/plywood | ab85a187e9e9d42d55cd3bd24be000898fd50234 | [
"MIT"
] | 51 | 2020-05-26T15:30:00.000Z | 2021-12-15T01:02:25.000Z | /*------------------------------------
///\ Plywood C++ Framework
\\\/ https://plywood.arc80.com/
------------------------------------*/
#include <ply-reflect/Core.h>
#include <ply-reflect/PersistRead.h>
#include <ply-reflect/FormatDescriptor.h>
#include <ply-runtime/container/Boxed.h>
namespace ply {
struct BuiltInFormatPair {
FormatKey key;
FormatDescriptor* formatDesc;
};
Array<BuiltInFormatPair> BuiltInFormats = {{FormatKey::None, nullptr},
{FormatKey::Indirect, nullptr},
{FormatKey::Bool, &FormatDescriptor_Bool},
{FormatKey::S8, &FormatDescriptor_S8},
{FormatKey::S16, &FormatDescriptor_S16},
{FormatKey::S32, &FormatDescriptor_S32},
{FormatKey::S64, &FormatDescriptor_S64},
{FormatKey::U8, &FormatDescriptor_U8},
{FormatKey::U16, &FormatDescriptor_U16},
{FormatKey::U32, &FormatDescriptor_U32},
{FormatKey::U64, &FormatDescriptor_U64},
{FormatKey::Float, &FormatDescriptor_Float},
{FormatKey::Double, &FormatDescriptor_Double},
{FormatKey::String, &FormatDescriptor_String},
{FormatKey::TypedArray, &FormatDescriptor_TypedArray},
{FormatKey::Typed, &FormatDescriptor_Typed}};
class SchemaLoader {
public:
Schema* m_schema;
NativeEndianReader m_in;
SchemaLoader(Schema* schema, InStream* in) : m_schema(schema), m_in(in) {
PLY_ASSERT(BuiltInFormats.numItems() == int(FormatKey::StartUserKeyRange));
}
FormatDescriptor* readFormatDescriptor(bool topLevel = false) {
u8 formatKey = m_in.read<u8>();
if (formatKey == (u8) FormatKey::None) {
PLY_ASSERT(topLevel);
return nullptr;
}
if (formatKey == (u8) FormatKey::Indirect) {
u32 formatID = m_in.read<u32>();
if (formatID < FormatID_StartUserRange) {
PLY_ASSERT(formatID < (u32) FormatKey::StartUserKeyRange);
BuiltInFormatPair& pair = BuiltInFormats[formatID];
PLY_ASSERT((u32) pair.key == formatID);
PLY_ASSERT(pair.formatDesc);
return pair.formatDesc;
} else {
return m_schema->userFormatDescs[formatID - FormatID_StartUserRange];
}
}
if (formatKey < (u8) FormatKey::StartUserKeyRange) {
PLY_ASSERT(!topLevel);
BuiltInFormatPair& pair = BuiltInFormats[formatKey];
PLY_ASSERT((u8) pair.key == formatKey);
return pair.formatDesc;
}
FormatDescriptor* newFormat = nullptr;
u32 userFormatIndex =
m_schema->userFormatDescs
.numItems(); // actual formatID is FormatID_StartUserRange + userFormatIndex
m_schema->userFormatDescs.append(nullptr);
if (formatKey == (u8) FormatKey::FixedArray) {
u32 numItems = m_in.read<u32>();
FormatDescriptor* itemFormat = readFormatDescriptor();
newFormat = new FormatDescriptor_FixedArray{numItems, itemFormat};
} else if (formatKey == (u8) FormatKey::Array) {
FormatDescriptor* itemFormat = readFormatDescriptor();
newFormat = new FormatDescriptor_Array{itemFormat};
} else if (formatKey == (u8) FormatKey::Owned) {
FormatDescriptor* childFormat = readFormatDescriptor();
newFormat = new FormatDescriptor_Owned{childFormat};
} else if (formatKey == (u8) FormatKey::WeakPtr) {
FormatDescriptor* childFormat = readFormatDescriptor();
newFormat = new FormatDescriptor_WeakPtr{childFormat};
} else if (formatKey == (u8) FormatKey::Struct) {
FormatDescriptor_Struct* structFormat = new FormatDescriptor_Struct;
structFormat->name = Boxed<String>::read(m_in);
u16 numTemplateParams = m_in.read<u16>();
u16 numMembers = m_in.read<u16>();
structFormat->templateParams.resize(numTemplateParams);
for (FormatDescriptor_Struct::Member& templateParam : structFormat->templateParams) {
templateParam.name = Boxed<String>::read(m_in);
templateParam.formatDesc = readFormatDescriptor();
}
structFormat->members.resize(numMembers);
for (FormatDescriptor_Struct::Member& member : structFormat->members) {
member.name = Boxed<String>::read(m_in);
member.formatDesc = readFormatDescriptor();
}
newFormat = structFormat;
} else if (formatKey == (u8) FormatKey::Enum) {
FormatDescriptor_Enum* enumFormat = new FormatDescriptor_Enum;
enumFormat->name = Boxed<String>::read(m_in);
enumFormat->fixedSize = m_in.read<u8>();
u32 numEntries = m_in.read<u32>();
enumFormat->identifiers.resize(numEntries);
for (String& name : enumFormat->identifiers) {
name = Boxed<String>::read(m_in);
}
newFormat = enumFormat;
} else if (formatKey == (u8) FormatKey::EnumIndexedArray) {
FormatDescriptor_EnumIndexedArray* arrFormat = new FormatDescriptor_EnumIndexedArray;
arrFormat->itemFormat = readFormatDescriptor();
FormatDescriptor* enumFormat = readFormatDescriptor();
PLY_ASSERT(enumFormat->formatKey == (u8) FormatKey::Enum);
arrFormat->enumFormat = static_cast<FormatDescriptor_Enum*>(enumFormat);
newFormat = arrFormat;
} else if (formatKey == (u8) FormatKey::Switch) {
FormatDescriptor_Switch* switchFormat = new FormatDescriptor_Switch;
switchFormat->name = Boxed<String>::read(m_in);
u16 numStates = m_in.read<u16>();
switchFormat->states.resize(numStates);
for (FormatDescriptor_Switch::State& state : switchFormat->states) {
state.name = Boxed<String>::read(m_in);
FormatDescriptor* stateFormat = readFormatDescriptor();
PLY_ASSERT(stateFormat->formatKey == (u8) FormatKey::Struct);
state.structFormat = static_cast<FormatDescriptor_Struct*>(stateFormat);
}
newFormat = switchFormat;
} else {
PLY_ASSERT(0);
}
m_schema->userFormatDescs[userFormatIndex] = newFormat;
return newFormat;
}
void readSchema() {
// Read all the user FormatDescriptors
for (;;) {
if (!readFormatDescriptor(true))
break;
}
}
};
void readSchema(Schema& schema, InStream* in) {
SchemaLoader loader{&schema, in};
loader.readSchema();
}
FormatDescriptor* Schema::getFormatDesc(u32 formatID) const {
if (formatID < FormatID_StartUserRange) {
// To avoid this assert, and make the serialization system forward-compatible and easy
// to merge across different branches, perhaps we could add a plugin system that allows
// arbitrary strings to serve as format keys, instead of limiting it to integers.
// Format keys are not added very often, but still worth thinking about.
PLY_ASSERT(formatID <
(u32) FormatKey::StartUserKeyRange); // Unrecognized FormatKey in the data
return BuiltInFormats[formatID].formatDesc;
} else {
return userFormatDescs[formatID - FormatID_StartUserRange];
}
}
} // namespace ply
| 47.130178 | 97 | 0.580917 | boldsort |
83b2054ffda44c4fe78d01b862a24bde1ec71f02 | 3,821 | cpp | C++ | source/ContratException.cpp | fantome3/test1 | 6b28cbbe87110baa68ef22ed7aeba13f538fcaef | [
"MIT"
] | null | null | null | source/ContratException.cpp | fantome3/test1 | 6b28cbbe87110baa68ef22ed7aeba13f538fcaef | [
"MIT"
] | null | null | null | source/ContratException.cpp | fantome3/test1 | 6b28cbbe87110baa68ef22ed7aeba13f538fcaef | [
"MIT"
] | null | null | null | /**
* \file ContratException.cpp
* \brief Implantation de la classe ContratException et de ses héritiers
* \author administrateur
* \date 16 janvier 2014
* \version révisée balises Doxygen C++ normes H2014
*/
#include "ContratException.h"
#include <sstream>
using namespace std;
/**
* \brief Constructeur de la classe de base ContratException
* \param p_fichP chaîne de caractères représentant le fichier source dans lequel a eu lieu l'erreur
* \param p_prmLigne un entier représentant la ligne où a eu lieu l'erreur
* \param p_msgP Message décrivant l'erreur
* \param p_exprP Test logique qui a échoué
*/
ContratException::ContratException(std::string p_fichP, unsigned int p_prmLigne,
std::string p_exprP, std::string p_msgP) :
logic_error(p_msgP), m_expression(p_exprP), m_fichier(p_fichP), m_ligne(p_prmLigne)
{
}
/**
* \brief Construit le texte complet relié à l'exception de contrat
* \return une chaîne de caractères correspondant à l'exception
*/
std::string ContratException::reqTexteException() const
{
// --- Prépare le message
ostringstream os;
os << "Message : " << what() << endl;
os << "Fichier : " << m_fichier << endl;
os << "Ligne : " << m_ligne << endl;
os << "Test : " << m_expression << endl;
return os.str();
}
/**
* \brief Constructeur de la classe AssertionException \n
* Le constructeur public AssertionException(...)initialise
* sa classe de base ContratException. On n'a pas d'attribut local. Cette
* classe est intéressante pour son TYPE lors du traitement des exceptions.
* \param p_fichP chaîne de caractères représentant le fichier source dans lequel a eu lieu l'erreur
* \param p_prmLigne un entier représentant la ligne où a eu lieu l'erreur
* \param p_exprP Test logique qui a échoué
*
*/
AssertionException::AssertionException(std::string p_fichP, unsigned int p_prmLigne,
std::string p_exprP)
: ContratException(p_fichP, p_prmLigne, p_exprP, "ERREUR D'ASSERTION")
{
}
/**
* \brief Constructeur de la classe PreconditionException en initialisant la classe de base ContratException.
* La classe représente l'erreur de précondition dans la théorie du contrat.
* \param p_fichP chaîne de caractères représentant le fichier source dans lequel a eu lieu l'erreur
* \param p_prmLigne un entier représentant la ligne où a eu lieu l'erreur
* \param p_exprP Test logique qui a échoué
*/
PreconditionException::PreconditionException(std::string p_fichP, unsigned int p_prmLigne,
std::string p_exprP)
: ContratException(p_fichP, p_prmLigne, p_exprP, "ERREUR DE PRECONDITION")
{
}
/**
* \brief Constructeur de la classe PostconditionException en initialisant la classe de base ContratException.
* La classe représente des erreurs de postcondition dans la théorie du contrat.
* \param p_fichP chaîne de caractères représentant le fichier source dans lequel a eu lieu l'erreur
* \param p_prmLigne un entier représentant la ligne où a eu lieu l'erreur
* \param p_exprP Test logique qui a échoué
*/
PostconditionException::PostconditionException(std::string p_fichP, unsigned int p_prmLigne,
std::string p_exprP)
: ContratException(p_fichP, p_prmLigne, p_exprP, "ERREUR DE POSTCONDITION")
{
}
/**
* \brief Constructeur de la classe InvariantException en initialisant la classe de base ContratException.
* La classe représente des erreurs d'invariant dans la théorie du contrat.
* \param p_fichP chaîne de caractères représentant le fichier source dans lequel a eu lieu l'erreur
* \param p_prmLigne un entier représentant la ligne où a eu lieu l'erreur
* \param p_exprP Test logique qui a échoué
*/
InvariantException::InvariantException(std::string p_fichP, unsigned int p_prmLigne,
std::string p_exprP)
: ContratException(p_fichP, p_prmLigne, p_exprP, "ERREUR D'INVARIANT")
{
}
| 41.086022 | 110 | 0.751636 | fantome3 |
83b2ab4de7b7d92fb74840afe2843d4df7585395 | 290 | cpp | C++ | 2000/60/2066.cpp | actium/timus | 6231d9e7fd325cae36daf5ee2ec7e61381f04003 | [
"Unlicense"
] | null | null | null | 2000/60/2066.cpp | actium/timus | 6231d9e7fd325cae36daf5ee2ec7e61381f04003 | [
"Unlicense"
] | null | null | null | 2000/60/2066.cpp | actium/timus | 6231d9e7fd325cae36daf5ee2ec7e61381f04003 | [
"Unlicense"
] | null | null | null | #include <algorithm>
#include <iostream>
int main()
{
int a, b, c;
std::cin >> a >> b >> c;
if (a > b) std::swap(a, b);
if (b > c) std::swap(b, c);
if (a > b) std::swap(a, b);
std::cout << std::min({ a*b*c, a+b*c, a-b*c, a+b+c, a-b-c }) << '\n';
return 0;
}
| 17.058824 | 73 | 0.441379 | actium |
83b6121603228e73887b4e38f9a403ee6c35057c | 635 | cpp | C++ | books/tech/cpp/std-11/b_sutherland-cpp_recipes/ch_08-the_stl_algorithms/recipe_8.3-finding_the_maximum_and_minimum_values/02-using_the_min_element_with_a_user-defined_class/main.cpp | ordinary-developer/education | 1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58 | [
"MIT"
] | 1 | 2017-05-04T08:23:46.000Z | 2017-05-04T08:23:46.000Z | books/techno/cpp/__intermediate/cpp_recipes_a_problem_solution_approach_b_shutherland/code/ch_8-THE_STL_ALGORITHMS/recipe_8.3-finding_the_maximum_and_minimum_values/02-using_the_min_element_with_a_user-defined_class/main.cpp | ordinary-developer/lin_education | 13d65b20cdbc3e5467b2383e5c09c73bbcdcb227 | [
"MIT"
] | null | null | null | books/techno/cpp/__intermediate/cpp_recipes_a_problem_solution_approach_b_shutherland/code/ch_8-THE_STL_ALGORITHMS/recipe_8.3-finding_the_maximum_and_minimum_values/02-using_the_min_element_with_a_user-defined_class/main.cpp | ordinary-developer/lin_education | 13d65b20cdbc3e5467b2383e5c09c73bbcdcb227 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <vector>
class MyClass {
public:
MyClass(const int value) : m_Value{ value } { }
int GetValue() const { return m_Value; }
bool operator <(const MyClass& other) const {
return m_Value < other.m_Value;
}
private:
int m_Value;
};
int main() {
std::vector<MyClass> myVector{ 4, 10, 6, 9, 1 };
auto minimum = std::min_element(myVector.begin(), myVector.end());
if (myVector.end() != minimum)
std::cout << "Minimum value: " << (*minimum).GetValue()
<< std::endl;
return 0;
}
| 21.166667 | 70 | 0.555906 | ordinary-developer |
83b73441173877043778c6261001f3c77b71ed1a | 254 | cpp | C++ | Dataset/Leetcode/train/53/51.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/53/51.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/53/51.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
int XXX(vector<int>& nums) {
int n = nums.size();
for(int i = 1; i < n; i++){
if(nums[i - 1] > 0) nums[i] += nums[i - 1];
}
return *max_element(nums.begin(), nums.end());
}
};
| 21.166667 | 55 | 0.448819 | kkcookies99 |
83b8f3a485f00073195f9764c1e4982926097be8 | 2,992 | hpp | C++ | rap_kvv.hpp | linkdata/crap | 1062cc4b42ae2a3dc4e7d61c19f2102f1557e180 | [
"MIT"
] | null | null | null | rap_kvv.hpp | linkdata/crap | 1062cc4b42ae2a3dc4e7d61c19f2102f1557e180 | [
"MIT"
] | null | null | null | rap_kvv.hpp | linkdata/crap | 1062cc4b42ae2a3dc4e7d61c19f2102f1557e180 | [
"MIT"
] | null | null | null | #ifndef RAP_KVV_HPP
#define RAP_KVV_HPP
#include "rap.hpp"
#include "rap_frame.h"
#include "rap_reader.hpp"
#include "rap_text.hpp"
#include "rap_writer.hpp"
#include <cassert>
#include <cstdint>
#include <string>
#include <vector>
namespace rap {
class kvv {
public:
kvv() {}
kvv(const kvv& other)
: data_(other.data_)
{
}
kvv(reader& r)
{
for (;;) {
text key(r.read_text());
if (key.is_null())
break;
data_.push_back(key);
for (;;) {
text val(r.read_text());
data_.push_back(val);
if (val.is_null())
break;
}
}
}
size_t size() const { return data_.size(); }
text at(size_t n) const { return data_.at(n); }
size_t find(const char* key) const
{
size_t i = 0;
while (i < data_.size()) {
if (data_.at(i).is_null())
break;
if (data_.at(i) == key)
return i + 1;
while (!data_.at(i).is_null())
++i;
}
return 0;
}
const rap::writer& operator>>(const rap::writer& w) const
{
for (size_t i = 0; i < size(); ++i)
w << at(i);
w << text();
return w;
}
protected:
std::vector<text> data_;
};
class query : public kvv {
public:
query()
: kvv()
{
}
query(reader& r)
: kvv(r)
{
}
void render(string_t& out) const
{
char prefix = '?';
for (size_t i = 0; i < size(); ++i) {
text key(at(i));
if (key.is_null())
break;
for (;;) {
if (++i >= size())
break;
text val(at(i));
if (val.is_null())
break;
out += prefix;
key.render(out);
prefix = '&';
if (!val.empty()) {
out += '=';
val.render(out);
}
}
}
}
};
class headers : public kvv {
public:
headers()
: kvv()
{
}
headers(reader& r)
: kvv(r)
{
}
void render(string_t& out) const
{
for (size_t i = 0; i < size(); ++i) {
text key(at(i));
if (key.is_null())
break;
for (;;) {
if (++i >= size())
break;
text val(at(i));
if (val.is_null())
break;
if (!val.empty()) {
key.render(out);
out += ": ";
val.render(out);
out += '\n';
}
}
}
}
};
inline const rap::writer& operator<<(const rap::writer& w,
const rap::kvv& kvv)
{
return kvv >> w;
}
} // namespace rap
#endif // RAP_KVV_HPP
| 20.353741 | 61 | 0.389372 | linkdata |
83b905ae548cea507540063f5574333cca9bc799 | 909 | cpp | C++ | IssueTest/test.cpp | vvck/QXlsx | 281fcb41ec186167ee3bbbe57572746f3c9c09be | [
"MIT"
] | 547 | 2019-01-14T18:38:08.000Z | 2022-03-31T07:30:00.000Z | IssueTest/test.cpp | vvck/QXlsx | 281fcb41ec186167ee3bbbe57572746f3c9c09be | [
"MIT"
] | 136 | 2019-01-07T05:44:21.000Z | 2022-03-29T08:41:18.000Z | IssueTest/test.cpp | vvck/QXlsx | 281fcb41ec186167ee3bbbe57572746f3c9c09be | [
"MIT"
] | 201 | 2019-03-02T09:59:02.000Z | 2022-03-25T17:43:13.000Z | // test.cpp
#include <QtGlobal>
#include <QCoreApplication>
#include <QtCore>
#include <QVector>
#include <QVariant>
#include <QDebug>
#include <QDir>
#include <QColor>
#include <QImage>
#include <QRgb>
#include <QRandomGenerator>
#include <iostream>
using namespace std;
#include "xlsxdocument.h"
#include "xlsxchartsheet.h"
#include "xlsxcellrange.h"
#include "xlsxchart.h"
#include "xlsxrichstring.h"
#include "xlsxworkbook.h"
int test162( QVector<QVariant> params );
int test( QVector<QVariant> params )
{
qDebug() << "[debug] current path : " << QDir::currentPath();
return test162( params );
}
int test162( QVector<QVariant> params )
{
using namespace QXlsx;
Document xlsx;
xlsx.saveAs("image1.xlsx");
Document xlsx2("image1.xlsx");
qDebug() << "xlsx2" ;
qDebug() << " image count : " << xlsx.getImageCount();
xlsx2.saveAs("image2.xlsx");
return 0;
}
| 18.55102 | 65 | 0.678768 | vvck |
83b9107f67fe4998cb60ce665677862afc9de7cb | 1,943 | cpp | C++ | vision/src/detect/motion_simple.cpp | robotalks/analytics | fede843601cba39370e77804a78bb704b32414f1 | [
"MIT"
] | null | null | null | vision/src/detect/motion_simple.cpp | robotalks/analytics | fede843601cba39370e77804a78bb704b32414f1 | [
"MIT"
] | null | null | null | vision/src/detect/motion_simple.cpp | robotalks/analytics | fede843601cba39370e77804a78bb704b32414f1 | [
"MIT"
] | null | null | null | #include <vector>
#include "vision/detect/motion.h"
namespace vision {
using namespace std;
using namespace cv;
SimpleMotionDetector::SimpleMotionDetector(const Size &blurSize, double areaMin, double threshold)
: m_blurSize(blurSize), m_areaMin(areaMin), m_threshold(threshold) {
}
void SimpleMotionDetector::detect(const Mat& image, DetectedObjectList& objects) {
Mat gray;
cvtColor(image, gray, CV_BGR2GRAY);
GaussianBlur(gray, gray, m_blurSize, 0);
if (m_prev.empty()) {
m_prev = gray;
return;
}
Mat thresh;
absdiff(m_prev, gray, thresh);
m_prev = gray;
threshold(thresh, thresh, m_threshold, 255, THRESH_BINARY);
dilate(thresh, thresh, Mat());
vector<vector<Point>> contours;
findContours(thresh.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
for (auto& c : contours) {
if (contourArea(c) >= m_areaMin) {
objects.push_back(DetectedObject(boundingRect(c), "motion"));
}
}
}
void SimpleMotionDetector::reg(App* app, const ::std::string& name) {
app->options().add_options()
("motion-min-area", "minimum motion area", cxxopts::value<double>())
("motion-blur", "size of gaussian blur", cxxopts::value<int>())
("motion-threshold", "threshold for diff", cxxopts::value<double>())
;
app->pipeline()->addFactory(name, [app] {
auto blurSize = app->opt("motion-blur").as<int>();
if (blurSize <= 0) {
blurSize = 11;
}
auto threshold = app->opt("motion-threshold").as<double>();
if (threshold <= 0) {
threshold = 25;
}
return new SimpleMotionDetector(
Size(blurSize, blurSize),
app->opt("motion-min-area").as<double>(),
threshold);
});
}
void SimpleMotionDetector::reg(App* app, ::cv::Scalar color, const ::std::string& name) {
reg(app, name);
app->objectColor("motion", color);
}
}
| 29.439394 | 98 | 0.630468 | robotalks |
83be419f9aceb2831ae6e5dc1ea825a8b084692b | 888 | hh | C++ | advent/utils/timer.hh | tamaroth/AdventOfCode2017 | 0c0f93590068b6b8fa6ed7f5d53c9fecede632bb | [
"MIT"
] | 2 | 2017-12-01T09:18:03.000Z | 2017-12-13T12:59:40.000Z | advent/utils/timer.hh | tamaroth/AdventOfCode2017 | 0c0f93590068b6b8fa6ed7f5d53c9fecede632bb | [
"MIT"
] | null | null | null | advent/utils/timer.hh | tamaroth/AdventOfCode2017 | 0c0f93590068b6b8fa6ed7f5d53c9fecede632bb | [
"MIT"
] | null | null | null | /// @file
///
/// Time measuring.
///
#pragma once
#include <chrono>
#include <iostream>
#include <string>
#include <sstream>
namespace advent {
using ms = std::chrono::milliseconds;
using us = std::chrono::microseconds;
template<typename Timepoint>
std::string duration_to_string(Timepoint start, Timepoint end) {
std::ostringstream os;
if (auto elapsed = std::chrono::duration_cast<ms>(end-start); elapsed.count()) {
os << elapsed.count() << "ms.";
} else {
os << std::chrono::duration_cast<us>(end-start).count() << "µs.";;
}
return os.str();
}
template<typename Block, typename ...Args>
void measure_execution_time(std::string_view task, Block block) {
auto start = std::chrono::high_resolution_clock::now();
block();
auto end = std::chrono::high_resolution_clock::now();
std::cout << task << "executed in " << duration_to_string(start, end) << std::endl;
}
}
| 23.368421 | 85 | 0.682432 | tamaroth |
83c9c10687defc7f9fb38ed9fa2dfd64d7f2cfda | 732 | cxx | C++ | test/cmp.cxx | Caltech-IPAC/libtinyhtm | abc3394f3d37b3729a625989d2fc144f14a7d208 | [
"BSD-3-Clause"
] | 1 | 2019-06-17T21:56:31.000Z | 2019-06-17T21:56:31.000Z | test/cmp.cxx | Caltech-IPAC/libtinyhtm | abc3394f3d37b3729a625989d2fc144f14a7d208 | [
"BSD-3-Clause"
] | null | null | null | test/cmp.cxx | Caltech-IPAC/libtinyhtm | abc3394f3d37b3729a625989d2fc144f14a7d208 | [
"BSD-3-Clause"
] | null | null | null | /** \file
\brief floating point comparison implementation.
\authors Serge Monkewitz
\copyright IPAC/Caltech
*/
#include "cmp.h"
#include <float.h>
#ifdef __cplusplus
extern "C" {
#endif
static double safe_div(double n, double d)
{
if (d < 1.0 && n > d * DBL_MAX) {
return DBL_MAX; /* overflow to DBL_MAX */
}
if (n == 0.0 || (d > 1.0 && n < d * DBL_MIN)) {
return 0.0; /* underflow to zero */
}
return n / d;
}
int almost_equal(double u, double v, double tolerance)
{
double delta = fabs(u - v);
double eps = fabs(tolerance);
u = safe_div(delta, fabs(u));
v = safe_div(delta, fabs(v));
return u <= eps && v <= eps;
}
#ifdef __cplusplus
}
#endif
| 18.3 | 57 | 0.575137 | Caltech-IPAC |
83caaaa81636c1efbbdb0c8fdaa3d6b9e215e601 | 14,599 | cpp | C++ | VarCalc/GdaParser.cpp | chenyoujie/GeoDa | 87504344512bd0da2ccadfb160ecd1e918a52f06 | [
"BSL-1.0"
] | null | null | null | VarCalc/GdaParser.cpp | chenyoujie/GeoDa | 87504344512bd0da2ccadfb160ecd1e918a52f06 | [
"BSL-1.0"
] | null | null | null | VarCalc/GdaParser.cpp | chenyoujie/GeoDa | 87504344512bd0da2ccadfb160ecd1e918a52f06 | [
"BSL-1.0"
] | null | null | null | /**
* GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved
*
* This file is part of GeoDa.
*
* GeoDa is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GeoDa is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <limits>
#include <math.h>
#include "../logger.h"
#include "GdaParser.h"
GdaParser::GdaParser()
: data_table(0), w_man_int(0)
{
}
bool GdaParser::eval(const std::vector<GdaTokenDetails>& tokens_,
std::map<wxString, GdaFVSmtPtr>* data_table_,
WeightsManInterface* w_man_int_)
{
tokens = tokens_;
data_table = data_table_;
w_man_int = w_man_int_;
tok_i = 0;
bool success = false;
eval_toks.clear();
try {
error_msg = "";
eval_val = expression();
success = true;
}
catch (GdaParserException e) {
error_msg = e.what();
}
catch (GdaFVException e) {
error_msg = e.what();
}
catch (std::exception e) {
error_msg = e.what();
}
return success;
}
GdaFVSmtPtr GdaParser::expression()
{
return logical_xor_expr();
}
GdaFVSmtPtr GdaParser::logical_xor_expr()
{
using namespace std;
GdaFVSmtPtr left = logical_or_expr();
for (;;) {
if (curr_token() == Gda::XOR) {
inc_token(); // consume XOR
GdaFVSmtPtr right = logical_or_expr();
left->ApplyBinarySelf(&Gda::logical_xor, *right);
} else {
return left;
}
}
}
GdaFVSmtPtr GdaParser::logical_or_expr()
{
using namespace std;
GdaFVSmtPtr left = logical_and_expr();
for (;;) {
if (curr_token() == Gda::OR) {
inc_token(); // consume OR
GdaFVSmtPtr right = logical_and_expr();
left->ApplyBinarySelf(&Gda::logical_or, *right);
} else {
return left;
}
}
}
GdaFVSmtPtr GdaParser::logical_and_expr()
{
using namespace std;
GdaFVSmtPtr left = logical_not_expr();
for (;;) {
if (curr_token() == Gda::AND) {
inc_token(); // consume AND
GdaFVSmtPtr right = logical_not_expr();
left->ApplyBinarySelf(&Gda::logical_and, *right);
} else {
return left;
}
}
}
GdaFVSmtPtr GdaParser::logical_not_expr()
{
if (curr_token() == Gda::NOT) {
inc_token(); // consume NOT
GdaFVSmtPtr p(expression());
p->ApplyUniSelf(&Gda::logical_not);
return p;
}
return comp_expr();
}
GdaFVSmtPtr GdaParser::comp_expr()
{
GdaFVSmtPtr left = add_expr();
for (;;) {
if (curr_token() == Gda::LT) {
inc_token(); // consume <
GdaFVSmtPtr right = add_expr();
left->ApplyBinarySelf(&Gda::lt, *right);
} else if (curr_token() == Gda::LE) {
inc_token(); // consume <=
GdaFVSmtPtr right = add_expr();
left->ApplyBinarySelf(&Gda::le, *right);
} else if (curr_token() == Gda::GT) {
inc_token(); // consume >
GdaFVSmtPtr right = add_expr();
left->ApplyBinarySelf(&Gda::gt, *right);
} else if (curr_token() == Gda::GE) {
inc_token(); // consume >=
GdaFVSmtPtr right = add_expr();
left->ApplyBinarySelf(&Gda::ge, *right);
} else if (curr_token() == Gda::EQ) {
inc_token(); // consume =
GdaFVSmtPtr right = add_expr();
left->ApplyBinarySelf(&Gda::eq, *right);
} else if (curr_token() == Gda::NE) {
inc_token(); // consume <>
GdaFVSmtPtr right = add_expr();
left->ApplyBinarySelf(&Gda::ne, *right);
} else {
return left;
}
}
}
GdaFVSmtPtr GdaParser::add_expr()
{
using namespace std;
GdaFVSmtPtr left = mult_expr();
for (;;) {
if (curr_token() == Gda::PLUS) {
inc_token(); // consume '+'
GdaFVSmtPtr right = mult_expr();
wxString ss;
ss << "GdaParser + op: operand " << (*left).ToStr();
ss << ", operand " << (*right).ToStr();
(*left) += (*right);
} else if (curr_token() == Gda::MINUS) {
inc_token(); // consume '-'
(*left) -= (*mult_expr());
} else {
return left;
}
}
}
GdaFVSmtPtr GdaParser::mult_expr()
{
GdaFVSmtPtr left = pow_expr();
for (;;) {
if (curr_token() == Gda::MUL) {
inc_token(); // consume '*'
(*left) *= (*pow_expr());
} else if (curr_token() == Gda::DIV) {
inc_token(); // consume '/'
(*left) /= (*pow_expr());
} else {
return left;
}
}
}
GdaFVSmtPtr GdaParser::pow_expr()
{
GdaFVSmtPtr left = func_expr();
if (curr_token() == Gda::POW) {
inc_token(); // consume '^'
GdaFVSmtPtr right = expression();
(*left) ^= (*right);
return left;
} else {
return left;
}
}
GdaFVSmtPtr GdaParser::func_expr()
{
if (curr_token() != Gda::NAME ||
(curr_token() == Gda::NAME && next_token() != Gda::LP)) {
return primary();
}
wxString func_name = curr_tok_str_val();
mark_curr_token_func();
inc_token(); // consume NAME token
inc_token(); // consume '('
if (curr_token() == Gda::RP) {
inc_token(); // consume ')'
// return 0-ary function NAME () value
LOG(func_name);
if (func_name.CmpNoCase("rook") == 0 ||
func_name.CmpNoCase("queen") == 0) {
throw GdaParserException("automatic weights creation "
"not yet supported");
if (!w_man_int) {
throw GdaParserException("no weights available.");
}
WeightsMetaInfo wmi;
if (func_name.CmpNoCase("rook") == 0) {
wmi.SetToRook("");
} else {
wmi.SetToQueen("");
}
boost::uuids::uuid u = w_man_int->RequestWeights(wmi);
GdaFVSmtPtr p(new GdaFlexValue(u));
return p;
}
throw GdaParserException("unknown function \"" + func_name + "\"");
}
GdaFVSmtPtr arg1(expression()); // evaluate first argument
if (curr_token() == Gda::RP) {
inc_token(); // consume ')'
// evaluate unary function NAME ( arg1 )
LOG(func_name);
if (func_name.CmpNoCase("sqrt") == 0) {
arg1->ApplyUniSelf(&sqrt);
} else if (func_name.CmpNoCase("cos") == 0) {
arg1->ApplyUniSelf(&cos);
} else if (func_name.CmpNoCase("sin") == 0) {
arg1->ApplyUniSelf(&sin);
} else if (func_name.CmpNoCase("tan") == 0) {
arg1->ApplyUniSelf(&tan);
} else if (func_name.CmpNoCase("acos") == 0) {
arg1->ApplyUniSelf(&acos);
} else if (func_name.CmpNoCase("asin") == 0) {
arg1->ApplyUniSelf(&asin);
} else if (func_name.CmpNoCase("atan") == 0) {
arg1->ApplyUniSelf(&atan);
} else if (func_name.CmpNoCase("abs") == 0 ||
func_name.CmpNoCase("fabs") == 0) {
arg1->ApplyUniSelf(&fabs);
} else if (func_name.CmpNoCase("ceil") == 0) {
arg1->ApplyUniSelf(&ceil);
} else if (func_name.CmpNoCase("floor") == 0) {
arg1->ApplyUniSelf(&floor);
} else if (func_name.CmpNoCase("round") == 0) {
arg1->Round();
} else if (func_name.CmpNoCase("log") == 0 ||
func_name.CmpNoCase("ln") == 0) {
arg1->ApplyUniSelf(&log);
} else if (func_name.CmpNoCase("log10") == 0) {
arg1->ApplyUniSelf(&log10);
} else if (func_name.CmpNoCase("sum") == 0) {
arg1->Sum();
} else if (func_name.CmpNoCase("mean") == 0 ||
func_name.CmpNoCase("avg") == 0) {
arg1->Mean();
} else if (func_name.CmpNoCase("sum") == 0) {
arg1->Sum();
} else if (func_name.CmpNoCase("stddev") == 0) {
arg1->StdDev();
} else if (func_name.CmpNoCase("dev_fr_mean") == 0) {
arg1->DevFromMean();
} else if (func_name.CmpNoCase("standardize") == 0) {
arg1->Standardize();
} else if (func_name.CmpNoCase("shuffle") == 0) {
arg1->Shuffle();
} else if (func_name.CmpNoCase("rot_down") == 0) {
arg1->Rotate(-1);
} else if (func_name.CmpNoCase("rot_up") == 0) {
arg1->Rotate(1);
} else if (func_name.CmpNoCase("unif_dist") == 0) {
arg1->UniformDist();
} else if (func_name.CmpNoCase("norm_dist") == 0) {
arg1->GaussianDist(0,1);
} else if (func_name.CmpNoCase("enumerate") == 0) {
arg1->Enumerate(1, 1);
} else if (func_name.CmpNoCase("max") == 0) {
arg1->Max();
} else if (func_name.CmpNoCase("min") == 0) {
arg1->Min();
} else if (func_name.CmpNoCase("is_defined") == 0) {
arg1->ApplyUniSelf(&Gda::is_defined);
} else if (func_name.CmpNoCase("is_finite") == 0) {
arg1->ApplyUniSelf(&Gda::is_finite);
} else if (func_name.CmpNoCase("is_nan") == 0) {
arg1->ApplyUniSelf(&Gda::is_nan);
} else if (func_name.CmpNoCase("is_pos_inf") == 0) {
arg1->ApplyUniSelf(&Gda::is_pos_inf);
} else if (func_name.CmpNoCase("is_neg_inf") == 0) {
arg1->ApplyUniSelf(&Gda::is_neg_inf);
} else if (func_name.CmpNoCase("is_inf") == 0) {
arg1->ApplyUniSelf(&Gda::is_inf);
} else if (func_name.CmpNoCase("counts") == 0) {
if (!w_man_int) {
throw GdaParserException("no weights available.");
}
if (!arg1->IsWeights()) {
throw GdaParserException("first argument of counts must be weights");
}
std::vector<long> counts;
if (!w_man_int->GetCounts(arg1->GetWUuid(), counts)) {
throw GdaParserException("could not find neighbor counts");
}
GdaFVSmtPtr p(new GdaFlexValue(counts));
return p;
} else {
throw GdaParserException("unknown function \"" + func_name + "\"");
}
return arg1;
}
if (curr_token() != Gda::COMMA) {
throw GdaParserException("',' or ')' expected");
}
inc_token(); // consume ','
GdaFVSmtPtr arg2(expression()); // evaluate second argument
if (curr_token() == Gda::RP) {
inc_token(); // consume ')'
// evaluate binary function NAME ( arg1 , arg2 )
LOG(func_name);
if (func_name.CmpNoCase("pow") == 0) {
arg1->ApplyBinarySelf(&pow, *arg2);
} else if (func_name.CmpNoCase("lag") == 0) {
if (!w_man_int) {
throw GdaParserException("no weights available.");
}
if (!arg1->IsWeights()) {
throw GdaParserException("first argument of lag must be weights.");
}
if (!arg2->IsData()) {
throw GdaParserException("second argument of lag must be data.");
}
if (!w_man_int->WeightsExists(arg1->GetWUuid())) {
throw GdaParserException("invalid weights.");
}
LOG(arg1->ToStr());
GdaFVSmtPtr p(new GdaFlexValue());
if (!w_man_int->Lag(arg1->GetWUuid(), *arg2, *p)) {
throw GdaParserException("error computing spatial lag");
}
return p;
} else {
throw GdaParserException("unknown function \"" + func_name + "\"");
}
return arg1;
}
if (curr_token() != Gda::COMMA) {
throw GdaParserException("',' or ')' expected");
}
inc_token(); // consume ','
GdaFVSmtPtr arg3(expression()); // evaluate third argument
if (curr_token() == Gda::RP) {
// mark as function token.
inc_token(); // consume ')'
// evaluate binary function NAME ( arg1 , arg2, arg3 )
LOG(func_name);
if (func_name.CmpNoCase("enumerate") == 0 ||
func_name.CmpNoCase("norm_dist") == 0) {
if (arg2->GetObs() != 1 || arg2->GetTms() != 1) {
throw GdaParserException("second argument of " + func_name
+ " must be a constant.");
}
if (arg3->GetObs() != 1 || arg3->GetTms() != 1) {
throw GdaParserException("third argument of " + func_name
+ " must be a constant.");
}
}
if (func_name.CmpNoCase("enumerate") == 0) {
arg1->Enumerate(arg2->GetDouble(), arg3->GetDouble());
} else if (func_name.CmpNoCase("norm_dist") == 0) {
double sd = arg3->GetDouble();
if (sd-sd != 0 || sd < 0) {
// x-x == 0 is a reliable test for double being finite
throw GdaParserException("third argument of " + func_name
+ " must be a non-negative finite real.");
}
arg1->GaussianDist(arg2->GetDouble(), sd);
} else {
throw GdaParserException("unknown function \"" + func_name + "\"");
}
return arg1;
}
throw GdaParserException("')' expected");
}
GdaFVSmtPtr GdaParser::primary()
{
if (curr_token() == Gda::STRING) {
GdaFVSmtPtr p(new GdaFlexValue(curr_tok_str_val()));
inc_token(); // consume STRING token
return p;
}
if (curr_token() == Gda::NUMBER) {
GdaFVSmtPtr p(new GdaFlexValue(curr_tok_num_val()));
//double v = curr_tok_num_val();
inc_token(); // consume NUMBER token
return p;
} else if (curr_token() == Gda::NAME) {
wxString key(curr_tok_str_val());
//if (next_token() == Gda::ASSIGN) {
// (*data_table)[key] = expression(true);
//}
// check for existence in data_table and in weights if w_man_int exists
if (data_table->find(key) == data_table->end() &&
(!w_man_int ||
(w_man_int && w_man_int->FindIdByTitle(key).is_nil()))) {
mark_curr_token_ident();
mark_curr_token_problem();
inc_token();
throw GdaParserException(key + " not a known identifier");
}
mark_curr_token_ident();
inc_token(); // consume NAME token
if (data_table->find(key) != data_table->end()) {
GdaFVSmtPtr p(new GdaFlexValue((*(*data_table)[key])));
return p;
} else {
GdaFVSmtPtr p(new GdaFlexValue(w_man_int->FindIdByTitle(key)));
return p;
}
} else if (curr_token() == Gda::MINUS) { // unary minus
inc_token(); // consume '-'
GdaFVSmtPtr p(primary());
p->NegateSelf();
return p;
} else if (curr_token() == Gda::LP) {
inc_token(); // consume '('
GdaFVSmtPtr e(expression());
if (curr_token() != Gda::RP) {
throw GdaParserException("')' expected");
}
inc_token(); // consume ')'
return e;
}
throw GdaParserException("primary expected");
}
Gda::TokenEnum GdaParser::curr_token()
{
if (tok_i >= tokens.size()) return Gda::END;
return tokens[tok_i].token;
}
double GdaParser::curr_tok_num_val()
{
if (tok_i >= tokens.size() ||
curr_token() != Gda::NUMBER) return 0;
return tokens[tok_i].number_value;
}
wxString GdaParser::curr_tok_str_val()
{
if (tok_i >= tokens.size() ||
(curr_token() != Gda::NAME &&
curr_token() != Gda::STRING)) return "";
return tokens[tok_i].string_value;
}
Gda::TokenEnum GdaParser::next_token()
{
int ii = tok_i + 1;
if (ii >= tokens.size()) return Gda::END;
return tokens[ii].token;
}
void GdaParser::inc_token()
{
if (tok_i < tokens.size()) {
eval_toks.push_back(tokens[tok_i]);
}
++tok_i;
}
void GdaParser::mark_curr_token_func()
{
if (tok_i < tokens.size()) {
tokens[tok_i].is_func = true;
tokens[tok_i].is_ident = false;
}
}
void GdaParser::mark_curr_token_ident()
{
if (tok_i < tokens.size()) {
tokens[tok_i].is_func = false;
tokens[tok_i].is_ident = true;
}
}
void GdaParser::mark_curr_token_problem()
{
if (tok_i < tokens.size()) tokens[tok_i].problem_token = true;
}
void GdaParser::exception_if_not_data(const GdaFVSmtPtr x)
{
if (!x->IsData()) {
throw GdaParserException("parser expected data expression");
}
}
void GdaParser::exception_if_not_weights(const GdaFVSmtPtr x)
{
if (!x->IsWeights()) {
throw GdaParserException("parser expected weights expression");
}
}
| 27.545283 | 73 | 0.635728 | chenyoujie |
83cb0529ee57a1d92b412f121439c8fe82250b6f | 52,728 | cc | C++ | ge/single_op/task/op_task.cc | mindspore-ai/graphengine | 460406cbd691b963d125837f022be5d8abd1a637 | [
"Apache-2.0"
] | 207 | 2020-03-28T02:12:50.000Z | 2021-11-23T18:27:45.000Z | ge/single_op/task/op_task.cc | mindspore-ai/graphengine | 460406cbd691b963d125837f022be5d8abd1a637 | [
"Apache-2.0"
] | 4 | 2020-04-17T07:32:44.000Z | 2021-06-26T04:55:03.000Z | ge/single_op/task/op_task.cc | mindspore-ai/graphengine | 460406cbd691b963d125837f022be5d8abd1a637 | [
"Apache-2.0"
] | 13 | 2020-03-28T02:52:26.000Z | 2021-07-03T23:12:54.000Z | /**
* Copyright 2019-2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "single_op/task/op_task.h"
#include <google/protobuf/extension_set.h>
#include <chrono>
#include <thread>
#include "aicpu/common/aicpu_task_struct.h"
#include "common/dump/dump_manager.h"
#include "common/dump/dump_op.h"
#include "common/profiling/profiling_manager.h"
#include "common/formats/formats.h"
#include "common/math/math_util.h"
#include "framework/common/debug/log.h"
#include "runtime/rt.h"
#include "single_op/task/build_task_utils.h"
namespace ge {
namespace {
constexpr int kLaunchRetryTimes = 1000;
constexpr size_t kMemcpyArgCount = 2;
constexpr int kSleepTime = 10;
constexpr uint64_t kReleaseFlag = 1;
constexpr int kCopyNum = 2;
constexpr uint64_t kInferSessionId = 0;
void FreeHbm(void *var) {
if (var) {
(void)rtFree(var);
}
}
} // namespace
Status OpTask::OpenDump(rtStream_t stream) {
if (DumpManager::GetInstance().GetDumpProperties(kInferSessionId).IsSingleOpNeedDump()) {
GELOGI("Dump is open in single op, start to set dump info");
std::vector<uint64_t> input_addrs;
std::vector<uint64_t> output_adds;
auto input_size = op_desc_->GetInputsSize();
auto output_size = op_desc_->GetOutputsSize();
uintptr_t *arg_base = nullptr;
size_t arg_num = 0;
GetIoAddr(arg_base, arg_num);
if (arg_num < input_size + output_size) {
GELOGE(ACL_ERROR_GE_INTERNAL_ERROR,
"[Check][Size]io_addrs_for_dump_ size %zu is not equal input and output size %zu",
arg_num, input_size + output_size);
REPORT_INNER_ERROR("E19999", "io_addrs_for_dump_ size %zu is not equal input and output size %zu",
arg_num, input_size + output_size);
return ACL_ERROR_GE_INTERNAL_ERROR;
}
for (size_t i = 0; i < input_size; i++) {
uint64_t input_addr = arg_base[i];
input_addrs.emplace_back(input_addr);
}
for (size_t j = 0; j < output_size; j++) {
uint64_t output_addr = arg_base[input_size + j];
output_adds.emplace_back(output_addr);
}
dump_op_.SetDumpInfo(DumpManager::GetInstance().GetDumpProperties(kInferSessionId),
op_desc_, input_addrs, output_adds, stream);
auto status = dump_op_.LaunchDumpOp();
if (status != SUCCESS) {
GELOGE(status, "[Launch][DumpOp] failed in single op.");
return status;
}
return SUCCESS;
}
GELOGI("Dump is not open in single op");
return SUCCESS;
}
void TbeOpTask::SetStubFunc(const std::string &name, const void *stub_func) {
this->stub_name_ = name;
this->stub_func_ = stub_func;
this->task_name_ = name;
}
void TbeOpTask::SetKernelArgs(std::unique_ptr<uint8_t[]> &&args, size_t arg_size, uint32_t block_dim,
const OpDescPtr &op_desc) {
args_ = std::move(args);
arg_size_ = arg_size;
block_dim_ = block_dim;
op_desc_ = op_desc;
}
void TbeOpTask::SetKernelWithHandleArgs(std::unique_ptr<uint8_t[]> &&args, size_t arg_size, uint32_t block_dim,
const OpDescPtr &op_desc,
const domi::KernelDefWithHandle &kernel_def_with_handle) {
SetKernelArgs(std::move(args), arg_size, block_dim, op_desc);
original_kernel_key_ = kernel_def_with_handle.original_kernel_key();
node_info_ = kernel_def_with_handle.node_info();
}
void TbeOpTask::SetSmDesc(void *sm_desc) { sm_desc_ = sm_desc; }
void OpTask::SetModelArgs(std::string model_name, uint32_t model_id) {
model_name_ = model_name;
model_id_ = model_id;
}
Status OpTask::GetProfilingArgs(TaskDescInfo &task_desc_info, uint32_t &model_id) {
uint32_t task_id = 0;
uint32_t stream_id = 0;
auto rt_ret = rtGetTaskIdAndStreamID(&task_id, &stream_id);
if (rt_ret != RT_ERROR_NONE) {
GELOGE(RT_FAILED, "[Get][TaskIdAndStreamID] failed, ret: 0x%X.", rt_ret);
REPORT_CALL_ERROR("E19999", "rtGetTaskIdAndStreamID failed, ret: 0x%X.", rt_ret);
return RT_ERROR_TO_GE_STATUS(rt_ret);
}
GE_CHECK_NOTNULL(op_desc_);
string op_name = op_desc_->GetName();
GELOGD("Get profiling args of op [%s] end, task_id[%u], stream_id[%u].", op_name.c_str(), task_id, stream_id);
model_id = model_id_;
task_desc_info.model_name = model_name_;
task_desc_info.block_dim = block_dim_;
task_desc_info.task_id = task_id;
task_desc_info.stream_id = stream_id;
task_desc_info.op_name = op_name;
task_desc_info.op_type = op_desc_->GetType();
auto &prof_mgr = ProfilingManager::Instance();
prof_mgr.GetOpInputOutputInfo(op_desc_, task_desc_info);
return SUCCESS;
}
Status OpTask::UpdateRunInfo() {
return UNSUPPORTED;
}
Status OpTask::DoUpdateArgTable(const SingleOpModelParam ¶m, bool keep_workspace) {
auto addresses = BuildTaskUtils::GetAddresses(op_desc_, param, keep_workspace);
auto all_addresses = BuildTaskUtils::JoinAddresses(addresses);
uintptr_t *arg_base = nullptr;
size_t arg_num = 0;
GetIoAddr(arg_base, arg_num);
if (arg_num < all_addresses.size()) {
GELOGE(ACL_ERROR_GE_INTERNAL_ERROR,
"[Check][Size][%s] arg number mismatches, expect at least = %zu, but got = %zu.",
op_desc_->GetName().c_str(), all_addresses.size(), arg_num);
REPORT_INNER_ERROR("E19999", "%s arg number mismatches, expect at least = %zu, but got = %zu.",
op_desc_->GetName().c_str(), all_addresses.size(), arg_num);
return ACL_ERROR_GE_INTERNAL_ERROR;
}
for (void *addr : all_addresses) {
*arg_base++ = reinterpret_cast<uintptr_t >(addr);
}
return SUCCESS;
}
Status OpTask::UpdateArgTable(const SingleOpModelParam ¶m) {
return DoUpdateArgTable(param, true);
}
Status OpTask::LaunchKernel(const vector<GeTensorDesc> &input_desc,
const vector<DataBuffer> &input_buffers,
vector<GeTensorDesc> &output_desc,
vector<DataBuffer> &output_buffers,
rtStream_t stream) {
return UNSUPPORTED;
}
const std::string &OpTask::GetTaskType() const { return kTaskTypeInvalid; }
TbeOpTask::~TbeOpTask() {
if (sm_desc_ != nullptr) {
(void)rtMemFreeManaged(sm_desc_);
}
if (tiling_buffer_ != nullptr) {
(void)rtFree(tiling_buffer_);
}
}
const void *TbeOpTask::GetArgs() const { return args_.get(); }
size_t TbeOpTask::GetArgSize() const { return arg_size_; }
const std::string &TbeOpTask::GetStubName() const { return stub_name_; }
const std::string &TbeOpTask::GetTaskType() const { return kTaskTypeAicore; }
void TbeOpTask::SetHandle(void *handle) {
this->handle_ = handle;
}
Status TbeOpTask::LaunchKernel(rtStream_t stream) {
GELOGD("To invoke rtKernelLaunch. task = %s, block_dim = %u", this->stub_name_.c_str(), block_dim_);
auto ret = DoLaunchKernel(stream);
int retry_times = 0;
while (ret != RT_ERROR_NONE && retry_times < kLaunchRetryTimes) {
retry_times++;
GELOGW("Retry after %d ms, retry_times: %d", kSleepTime, retry_times);
std::this_thread::sleep_for(std::chrono::milliseconds(kSleepTime));
ret = DoLaunchKernel(stream);
}
if (ret != RT_ERROR_NONE) {
GELOGE(ret, "[Invoke][RtKernelLaunch] failed. ret = %d, task = %s", ret, this->stub_name_.c_str());
REPORT_INNER_ERROR("E19999", "invoke rtKernelLaunch failed, ret = %d, task = %s", ret, this->stub_name_.c_str());
return RT_ERROR_TO_GE_STATUS(ret);
}
GELOGI("[TASK_INFO] %s", this->stub_name_.c_str());
return SUCCESS;
}
Status TbeOpTask::CalcTilingInfo(optiling::utils::OpRunInfo &run_info) {
auto ret = optiling::OpParaCalculateV2(*node_, run_info);
if (ret != GRAPH_SUCCESS) {
GELOGE(ACL_ERROR_GE_INTERNAL_ERROR, "[Invoke][OpParaCalculate] failed, ret = %u.", ret);
REPORT_INNER_ERROR("E19999", "invoke OpParaCalculate failed, ret = %u.", ret);
return ACL_ERROR_GE_INTERNAL_ERROR;
}
return SUCCESS;
}
Status TbeOpTask::UpdateRunInfo() {
// invoke OpParaCalculate
GELOGD("Start to invoke OpParaCalculate.");
optiling::utils::OpRunInfo run_info(0, true, 0);
GE_CHK_STATUS_RET(CalcTilingInfo(run_info), "[Calc][TilingInfo]failed.");
block_dim_ = run_info.GetBlockDim();
tiling_data_ = run_info.GetAllTilingData().str();
tiling_key_ = run_info.GetTilingKey();
clear_atomic_ = run_info.GetClearAtomic();
run_info.GetAllWorkspaces(run_info_workspaces_);
GELOGD("Done invoking OpParaCalculate successfully. block_dim = %u, tiling size = %zu, tiling_key = %u", block_dim_,
tiling_data_.size(), tiling_key_);
return SUCCESS;
}
Status TbeOpTask::UpdateTensorDesc(const GeTensorDesc &src_tensor, GeTensorDesc &dst_tensor) {
int64_t storage_format_val = static_cast<Format>(FORMAT_RESERVED);
(void)AttrUtils::GetInt(src_tensor, ge::ATTR_NAME_STORAGE_FORMAT, storage_format_val);
auto storage_format = static_cast<Format>(storage_format_val);
if (storage_format == FORMAT_RESERVED) {
GELOGD("Storage format not set. update shape to [%s], and original shape to [%s]",
src_tensor.GetShape().ToString().c_str(), src_tensor.GetOriginShape().ToString().c_str());
dst_tensor.SetShape(src_tensor.GetShape());
dst_tensor.SetOriginShape(src_tensor.GetOriginShape());
} else {
std::vector<int64_t> storage_shape;
if (!AttrUtils::GetListInt(src_tensor, ge::ATTR_NAME_STORAGE_SHAPE, storage_shape)) {
GELOGE(ACL_ERROR_GE_INTERNAL_ERROR, "[Get][ListInt]failed while storage_format was set.");
return ACL_ERROR_GE_INTERNAL_ERROR;
}
GELOGD("Storage format set. update shape to [%s], and original shape to [%s]",
GeShape(storage_shape).ToString().c_str(), src_tensor.GetShape().ToString().c_str());
dst_tensor.SetShape(GeShape(std::move(storage_shape)));
dst_tensor.SetOriginShape(src_tensor.GetShape());
}
return SUCCESS;
}
Status TbeOpTask::UpdateNodeByShape(const vector<GeTensorDesc> &input_desc, const vector<GeTensorDesc> &output_desc) {
auto op_desc = node_->GetOpDesc();
GE_CHECK_NOTNULL(op_desc);
// Set runtime shape to node
for (size_t i = 0; i < input_desc.size(); ++i) {
auto tensor_desc = op_desc->MutableInputDesc(i);
auto &runtime_tensor_desc = input_desc[i];
GE_CHECK_NOTNULL(tensor_desc);
GE_CHK_STATUS_RET(UpdateTensorDesc(runtime_tensor_desc, *tensor_desc));
}
for (size_t i = 0; i < output_desc.size(); ++i) {
auto tensor_desc = op_desc->MutableOutputDesc(i);
auto &runtime_tensor_desc = output_desc[i];
GE_CHECK_NOTNULL(tensor_desc);
GE_CHK_STATUS_RET(UpdateTensorDesc(runtime_tensor_desc, *tensor_desc));
}
return SUCCESS;
}
Status TbeOpTask::EnableDynamicSupport(const NodePtr &node, void *tiling_buffer, uint32_t max_tiling_size) {
if (tiling_buffer != nullptr) {
uintptr_t *arg_base = nullptr;
size_t arg_num = 0;
GetIoAddr(arg_base, arg_num);
GE_CHECK_NOTNULL(node);
GE_CHECK_NOTNULL(node->GetOpDesc());
uint32_t inputs_num = node->GetOpDesc()->GetInputsSize();
uint32_t outputs_num = node->GetOpDesc()->GetOutputsSize();
uint32_t workspace_nums = node->GetOpDesc()->GetWorkspace().size();
uint32_t tiling_index = inputs_num + outputs_num + workspace_nums;
if (arg_num == 0 || arg_num < tiling_index) {
GELOGE(ACL_ERROR_GE_INTERNAL_ERROR, "[Check][Size]Tiling index %u, arg number %zu is invalid.",
tiling_index, arg_num);
return ACL_ERROR_GE_INTERNAL_ERROR;
}
arg_base[tiling_index] = reinterpret_cast<uintptr_t>(tiling_buffer);
}
node_ = node;
tiling_buffer_ = tiling_buffer;
max_tiling_size_ = max_tiling_size;
return SUCCESS;
}
Status TbeOpTask::AllocateWorkspaces(const vector<int64_t> &workspace_sizes) {
static const std::string kPurpose("malloc workspace memory for dynamic op.");
workspaces_.clear();
if (workspace_sizes.empty()) {
GELOGD("No need to allocate workspace.");
return SUCCESS;
}
int64_t total_size = 0;
std::vector<int64_t> ws_offsets;
for (auto ws_size : workspace_sizes) {
// alignment and padding should be done in OpParaCalculate
if (CheckInt64AddOverflow(total_size, ws_size) != SUCCESS) {
return ACL_ERROR_GE_INTERNAL_ERROR;
}
ws_offsets.emplace_back(total_size);
total_size += ws_size;
}
GELOGD("Total workspace size is %ld", total_size);
GE_CHECK_NOTNULL(stream_resource_);
auto ws_base = stream_resource_->MallocMemory(kPurpose, static_cast<size_t>(total_size));
if (ws_base == nullptr) {
GELOGE(ACL_ERROR_GE_MEMORY_ALLOCATION, "[Malloc][Memory] failed, size: %ld", total_size);
REPORT_INNER_ERROR("E19999", "MallocMemory failed, size: %ld", total_size);
return ACL_ERROR_GE_MEMORY_ALLOCATION;
}
GELOGD("Done allocating workspace memory successfully.");
for (auto ws_offset : ws_offsets) {
workspaces_.emplace_back(ws_base + ws_offset);
}
return SUCCESS;
}
Status TbeOpTask::CheckAndExecuteAtomic(const vector<GeTensorDesc> &input_desc,
const vector<DataBuffer> &input_buffers,
vector<GeTensorDesc> &output_desc,
vector<DataBuffer> &output_buffers,
rtStream_t stream) {
if (clear_atomic_ && atomic_task_ != nullptr) {
return atomic_task_->LaunchKernel(input_desc, input_buffers, output_desc, output_buffers, stream);
}
return SUCCESS;
}
Status TbeOpTask::UpdateTilingArgs(rtStream_t stream) {
size_t args_size = input_num_ + output_num_ + workspaces_.size();
if (tiling_buffer_ != nullptr) {
args_size++;
}
size_t temp_size = args_size * sizeof(void *);
if (arg_size_ < temp_size) {
GELOGD("Need to reset size of args_ from %zu to %zu.", arg_size_, temp_size);
std::unique_ptr<uint8_t[]> args(new (std::nothrow) uint8_t[temp_size]());
GE_CHECK_NOTNULL(args);
if (memcpy_s(args.get(), temp_size, args_.get(), arg_size_) != EOK) {
GELOGE(ACL_ERROR_GE_MEMORY_OPERATE_FAILED, "[Update][KernelArgs] failed for [%s].", node_->GetName().c_str());
REPORT_INNER_ERROR("E19999", "update kernel args failed for %s.", node_->GetName().c_str());
return ACL_ERROR_GE_MEMORY_OPERATE_FAILED;
}
args_ = std::move(args);
arg_size_ = temp_size;
}
uintptr_t *arg_base = reinterpret_cast<uintptr_t *>(args_.get());
size_t arg_index = input_num_ + output_num_;
for (size_t i = 0; i < workspaces_.size(); ++i) {
arg_base[arg_index++] = reinterpret_cast<uintptr_t>(workspaces_[i]);
}
if (tiling_buffer_ != nullptr) {
GELOGD("[%s] Start to copy tiling info. size = %zu", node_->GetName().c_str(), tiling_data_.size());
GE_CHK_RT_RET(rtMemcpyAsync(tiling_buffer_, max_tiling_size_, tiling_data_.data(), tiling_data_.size(),
RT_MEMCPY_HOST_TO_DEVICE_EX, stream));
arg_base[arg_index] = reinterpret_cast<uintptr_t>(tiling_buffer_);
}
return SUCCESS;
}
Status TbeOpTask::SetArgIndex() {
const vector<bool> v_is_input_const = op_desc_->GetIsInputConst();
size_t input_index = 0;
for (size_t i = 0; i < op_desc_->GetAllInputsSize(); ++i) {
const GeTensorDescPtr tensor_desc = op_desc_->MutableInputDesc(static_cast<uint32_t>(i));
if (tensor_desc == nullptr) {
GELOGD("SingleOp: %s, Index: %zu, has no input", op_desc_->GetName().c_str(), i);
continue;
}
if (i < v_is_input_const.size() && v_is_input_const[i]) {
GELOGD("SingleOp: %s, Index: %zu, input is const", op_desc_->GetName().c_str(), i);
input_index++;
continue;
}
arg_index_.emplace_back(input_index);
input_index++;
}
return SUCCESS;
}
Status TbeOpTask::UpdateIoAddr(const vector<DataBuffer> &inputs, const vector<DataBuffer> &outputs) {
if (arg_index_.size() != inputs.size()) {
GELOGE(ACL_ERROR_GE_PARAM_INVALID, "[Check][Size] Args size is %zu, but get input size is %zu.",
arg_index_.size(), inputs.size());
REPORT_INNER_ERROR("E19999", "[Check][Size] Args size is %zu, but get input size is %zu.",
arg_index_.size(), inputs.size());
return ACL_ERROR_GE_PARAM_INVALID;
}
uintptr_t *arg_base = reinterpret_cast<uintptr_t *>(args_.get());
for (size_t i = 0; i < arg_index_.size(); ++i) {
arg_base[arg_index_[i]] = reinterpret_cast<uintptr_t>(inputs[i].data);
}
for (size_t i = 0; i < op_desc_->GetOutputsSize(); ++i) {
arg_base[input_num_ + i] = reinterpret_cast<uintptr_t>(outputs[i].data);
}
return SUCCESS;
}
Status TbeOpTask::LaunchKernel(const vector<GeTensorDesc> &input_desc,
const vector<DataBuffer> &input_buffers,
vector<GeTensorDesc> &output_desc,
vector<DataBuffer> &output_buffers,
rtStream_t stream) {
GELOGD("[%s] Start to launch kernel", node_->GetName().c_str());
GE_CHK_STATUS_RET(UpdateIoAddr(input_buffers, output_buffers), "[Update][IoAddr] failed.");
GE_CHK_STATUS_RET_NOLOG(UpdateNodeByShape(input_desc, output_desc));
GE_CHK_STATUS_RET_NOLOG(UpdateRunInfo());
GE_CHK_STATUS_RET(AllocateWorkspaces(run_info_workspaces_), "[Allocate][Workspaces] failed.");
GE_CHK_STATUS_RET(CheckAndExecuteAtomic(input_desc, input_buffers, output_desc, output_buffers, stream),
"[Execute][AtomicTask] failed.");
GE_CHK_STATUS_RET(UpdateTilingArgs(stream), "[Update][TilingArgs] failed.");
GELOGD("[%s] Start to invoke rtKernelLaunch", node_->GetName().c_str());
GE_CHK_STATUS_RET(DoLaunchKernel(stream), "Failed to do launch kernel.");
return SUCCESS;
}
Status TbeOpTask::DoLaunchKernel(rtStream_t stream) {
auto *sm_desc = reinterpret_cast<rtSmDesc_t *>(sm_desc_);
if (handle_ == nullptr) {
GE_CHK_RT_RET(rtKernelLaunch(stub_func_, block_dim_, args_.get(), static_cast<uint32_t>(arg_size_),
sm_desc, stream));
} else {
std::string dev_func = original_kernel_key_ + "_" + std::to_string(tiling_key_);
std::string kernel_info = node_info_ + "/" + std::to_string(tiling_key_);
GE_CHK_RT_RET(rtKernelLaunchWithHandle(handle_, dev_func.c_str(), block_dim_, args_.get(),
static_cast<uint32_t>(arg_size_), sm_desc, stream, kernel_info.c_str()));
}
return SUCCESS;
}
void TbeOpTask::GetIoAddr(uintptr_t *&arg_base, size_t &arg_count) {
arg_base = reinterpret_cast<uintptr_t *>(args_.get());
arg_count = arg_size_ / sizeof(void *);
if (tiling_buffer_ != nullptr) {
--arg_count;
}
}
Status AtomicAddrCleanOpTask::UpdateNodeByShape(const vector<GeTensorDesc> &input_desc,
const vector<GeTensorDesc> &output_desc) {
return SUCCESS;
}
Status AtomicAddrCleanOpTask::UpdateIoAddr(const vector<DataBuffer> &inputs, const vector<DataBuffer> &outputs) {
uintptr_t *arg_base = reinterpret_cast<uintptr_t *>(args_.get());
for (auto atomic_output_index : atomic_output_indices_) {
if (atomic_output_index >= static_cast<int>(outputs.size())) {
GELOGE(ACL_ERROR_GE_PARAM_INVALID, "[Update][Args] failed, atomic index must smaller then data size.");
REPORT_INNER_ERROR("E19999", "[Update][Args] failed, atomic index must smaller then data size.");
return ACL_ERROR_GE_PARAM_INVALID;
}
auto &output_buffer = outputs[atomic_output_index];
*arg_base++ = reinterpret_cast<uintptr_t>(output_buffer.data);
auto tensor_desc = op_desc_->MutableOutputDesc(atomic_output_index);
int64_t size = 0;
graphStatus graph_status = TensorUtils::GetTensorMemorySizeInBytes(*tensor_desc, size);
if (graph_status != GRAPH_SUCCESS) {
REPORT_CALL_ERROR("E19999", "Get tensor size in bytes failed!");
GELOGE(graph_status, "[Get][TensorMemorySize] In Bytes failed!");
return FAILED;
}
TensorUtils::SetSize(*tensor_desc, size);
}
return SUCCESS;
}
Status AtomicAddrCleanOpTask::UpdateTilingArgs(rtStream_t stream) {
if (tiling_buffer_ != nullptr) {
GELOGD("[%s] Start to copy tiling info. size = %zu", node_->GetName().c_str(), tiling_data_.size());
GE_CHK_RT_RET(rtMemcpyAsync(tiling_buffer_, max_tiling_size_, tiling_data_.data(), tiling_data_.size(),
RT_MEMCPY_HOST_TO_DEVICE_EX, stream));
uintptr_t *arg_base = reinterpret_cast<uintptr_t *>(args_.get());
size_t idx = atomic_output_indices_.size();
arg_base[idx] = reinterpret_cast<uintptr_t>(tiling_buffer_);
}
return SUCCESS;
}
Status AtomicAddrCleanOpTask::CalcTilingInfo(optiling::utils::OpRunInfo &run_info) {
auto ret = optiling::OpAtomicCalculateV2(*node_, run_info);
if (ret != GRAPH_SUCCESS) {
GELOGE(ACL_ERROR_GE_INTERNAL_ERROR, "[Invoke][OpAtomicCalculate] failed, ret = %u.", ret);
REPORT_INNER_ERROR("E19999", "invoke OpAtomicCalculate failed, ret = %u.", ret);
return ACL_ERROR_GE_INTERNAL_ERROR;
}
return SUCCESS;
}
Status AtomicAddrCleanOpTask::InitAtomicAddrCleanIndices() {
GELOGD("[%s] Start to setup AtomicAddrClean task.", op_desc_->GetName().c_str());
std::vector<int64_t> atomic_output_indices;
(void) ge::AttrUtils::GetListInt(op_desc_, ATOMIC_ATTR_OUTPUT_INDEX, atomic_output_indices);
if (atomic_output_indices.empty()) {
GELOGE(INTERNAL_ERROR, "[Check][Size][%s] atomic_output_indices must not be empty.", op_desc_->GetName().c_str());
REPORT_INNER_ERROR("E19999", "[%s] atomic_output_indices must not be empty.", op_desc_->GetName().c_str());
return INTERNAL_ERROR;
}
size_t max_arg_size = tiling_buffer_ == nullptr ? arg_size_ : arg_size_ - 1;
if (atomic_output_indices.size() > max_arg_size) {
GELOGE(INTERNAL_ERROR, "[Check][Size][%s] atomic_output_indices invalid. atomic_output_indices size is %zu,"
"arg size is %zu.", op_desc_->GetName().c_str(), atomic_output_indices.size(), arg_size_);
REPORT_INNER_ERROR("E19999", "[%s] atomic_output_indices invalid. atomic_output_indices size is %zu,"
"arg size is %zu.", op_desc_->GetName().c_str(), atomic_output_indices.size(), arg_size_);
return INTERNAL_ERROR;
}
for (auto output_index : atomic_output_indices) {
GELOGD("[%s] Adding output index [%ld]", op_desc_->GetName().c_str(), output_index);
GE_CHECK_GE(output_index, 0);
GE_CHECK_LE(output_index, INT32_MAX);
atomic_output_indices_.emplace_back(static_cast<int>(output_index));
}
return SUCCESS;
}
AiCpuBaseTask::~AiCpuBaseTask() {
if (ext_info_addr_dev_ != nullptr) {
(void)rtFree(ext_info_addr_dev_);
}
if (rt_event_ != nullptr) {
(void)rtEventDestroy(rt_event_);
}
}
Status AiCpuBaseTask::UpdateEventIdForBlockingAicpuOp() {
bool is_support = false;
if (CheckDeviceSupportBlockingAicpuOpProcess(is_support) != SUCCESS) {
GELOGE(FAILED, "[Call][CheckDeviceSupportBlockingAicpuOpProcess] Call CheckDeviceSupportBlockingAicpuOpProcess failed");
return FAILED;
}
if (!is_support) {
GELOGD("Device not support blocking aicpu op process");
return SUCCESS;
}
uint32_t event_id = 0;
auto rt_ret = rtEventCreateWithFlag(&rt_event_, RT_EVENT_WITH_FLAG);
if (rt_ret != RT_ERROR_NONE) {
REPORT_CALL_ERROR("E19999", "Call rtEventCreateWithFlag failed, ret:0x%X", rt_ret);
GELOGE(RT_FAILED, "[Call][rtEventCreateWithFlag] failed, ret:0x%X", rt_ret);
return RT_ERROR_TO_GE_STATUS(rt_ret);
}
rt_ret = rtGetEventID(rt_event_, &event_id);
if (rt_ret != RT_ERROR_NONE) {
REPORT_CALL_ERROR("E19999", "Call rtGetEventID failed, ret:0x%X", rt_ret);
GELOGE(RT_FAILED, "[Call][rtGetEventID] failed, ret:0x%X", rt_ret);
return RT_ERROR_TO_GE_STATUS(rt_ret);
}
if (aicpu_ext_handle_->UpdateEventId(event_id) != SUCCESS) {
REPORT_CALL_ERROR("E19999", "Update event id=%u failed.", event_id);
GELOGE(FAILED, "[Update][EventId] Update event id failed", event_id);
return FAILED;
}
GELOGI("Update event_id=%u success", event_id);
return SUCCESS;
}
Status AiCpuBaseTask::SetExtInfoAndType(const std::string &kernel_ext_info, uint64_t kernel_id) {
if (kernel_ext_info.empty()) {
GELOGI("Kernel_ext_info is empty, no need copy to device.");
return SUCCESS;
}
int32_t unknown_shape_type_val = 0;
(void) AttrUtils::GetInt(op_desc_, ::ge::ATTR_NAME_UNKNOWN_SHAPE_TYPE, unknown_shape_type_val);
GELOGD("Get unknown_type is %d.", unknown_shape_type_val);
unknown_type_ = static_cast<UnknowShapeOpType>(unknown_shape_type_val);
AttrUtils::GetBool(op_desc_, ATTR_NAME_IS_BLOCKING_OP, is_blocking_aicpu_op_);
GELOGD("Get op:%s attribute(is_blocking_op), value:%d", op_desc_->GetName().c_str(), is_blocking_aicpu_op_);
aicpu_ext_handle_.reset(new(std::nothrow) ::ge::hybrid::AicpuExtInfoHandler(op_desc_->GetName(),
num_inputs_,
num_outputs_,
unknown_type_));
GE_CHK_BOOL_RET_STATUS(aicpu_ext_handle_ != nullptr, ACL_ERROR_GE_MEMORY_ALLOCATION,
"[Malloc][Memory] failed for aicpu_ext_handle!");
Status ret = aicpu_ext_handle_->Parse(kernel_ext_info);
if (ret != SUCCESS) {
GELOGE(ret, "[Parse][Param:kernel_ext_info] failed, kernel_ext_info_size=%zu.", kernel_ext_info.size());
REPORT_INNER_ERROR("E19999",
"Parse Param:kernel_ext_info failed, kernel_ext_info_size=%zu.", kernel_ext_info.size());
return ret;
}
GE_CHK_STATUS_RET(aicpu_ext_handle_->UpdateSessionInfo(ULLONG_MAX, kernel_id, false),
"[Update][SessionInfo] failed.");
if (is_blocking_aicpu_op_) {
if (UpdateEventIdForBlockingAicpuOp() != SUCCESS) {
GELOGE(FAILED, "[Call][UpdateEventIdForBlockingAicpuOp] Call UpdateEventIdForBlockingAicpuOp failed");
return FAILED;
}
}
GE_CHK_RT_RET(rtMalloc(&ext_info_addr_dev_, aicpu_ext_handle_->GetExtInfoLen(), RT_MEMORY_HBM));
GE_CHK_RT_RET(rtMemcpy(ext_info_addr_dev_, aicpu_ext_handle_->GetExtInfoLen(),
aicpu_ext_handle_->GetExtInfo(), aicpu_ext_handle_->GetExtInfoLen(),
RT_MEMCPY_HOST_TO_DEVICE));
return SUCCESS;
}
Status AiCpuBaseTask::SetInputConst() {
input_is_const_.clear();
const vector<bool> v_is_input_const = op_desc_->GetIsInputConst();
for (size_t i = 0; i < op_desc_->GetAllInputsSize(); ++i) {
const GeTensorDescPtr tensor_desc = op_desc_->MutableInputDesc(static_cast<uint32_t>(i));
if (tensor_desc == nullptr) {
GELOGD("SingleOp: %s, Index: %zu, has no input", op_desc_->GetName().c_str(), i);
continue;
}
if (i < v_is_input_const.size() && v_is_input_const[i]) {
GELOGD("SingleOp: %s, Index: %zu, input is const", op_desc_->GetName().c_str(), i);
input_is_const_.push_back(true);
continue;
}
input_is_const_.push_back(false);
}
return SUCCESS;
}
Status AiCpuBaseTask::UpdateExtInfo(const std::vector<GeTensorDesc> &input_desc,
std::vector<GeTensorDesc> &output_desc,
rtStream_t stream) {
GELOGI("Update ext info begin, unknown_type=%d.", unknown_type_);
GE_CHECK_NOTNULL(aicpu_ext_handle_);
GE_CHK_STATUS_RET(aicpu_ext_handle_->UpdateExecuteMode(false), "[Update][ExecuteMode] failed.");
if (num_inputs_ == 0 && num_outputs_ == 0) {
GELOGI("No input and output, no need update ext info.");
return SUCCESS;
}
size_t non_const_index = 0;
for (size_t input_index = 0; input_index < num_inputs_; input_index++) {
if (input_index < input_is_const_.size() && input_is_const_[input_index]) {
// get input_desc from op_desc if const input, num_inputs_ is op_desc_ input_size
auto const_input_desc = op_desc_->MutableInputDesc(static_cast<uint32_t>(input_index));
GE_CHECK_NOTNULL(const_input_desc);
GE_CHK_STATUS_RET(aicpu_ext_handle_->UpdateInputShapeAndType(input_index, *const_input_desc),
"[Update][InputShapeAndType] failed, input_index:%zu.", input_index);
continue;
}
GE_CHK_BOOL_RET_STATUS(non_const_index < input_desc.size(), ACL_ERROR_GE_PARAM_INVALID,
"[Check][Size]Input_desc size is %zu, but get non_const_index is %zu", input_desc.size(), non_const_index);
GE_CHK_STATUS_RET(aicpu_ext_handle_->UpdateInputShapeAndType(input_index, input_desc[non_const_index]),
"[Update][InputShapeAndType]failed, input_index:%zu.", input_index);
if (DumpManager::GetInstance().GetDumpProperties(kInferSessionId).IsSingleOpNeedDump()) {
GE_CHK_STATUS_RET(op_desc_->UpdateInputDesc(input_index, input_desc[non_const_index]),
"AiCpuTask Update [%zu]th input desc failed.",input_index);
}
non_const_index++;
}
if (unknown_type_ != DEPEND_COMPUTE) {
for (size_t j = 0; j < num_outputs_; ++j) {
GE_CHK_STATUS_RET(aicpu_ext_handle_->UpdateOutputShapeAndType(j, output_desc[j]),
"[Update][OutputShapeAndType] failed, Output:%zu.", j);
if (DumpManager::GetInstance().GetDumpProperties(kInferSessionId).IsSingleOpNeedDump()) {
GE_CHK_STATUS_RET(op_desc_->UpdateOutputDesc(j, output_desc[j]),
"AiCpuTask Update [%zu]th output desc failed.",j);
}
}
}
GE_CHK_RT_RET(rtMemcpyAsync(ext_info_addr_dev_,
aicpu_ext_handle_->GetExtInfoLen(), // check size
aicpu_ext_handle_->GetExtInfo(),
aicpu_ext_handle_->GetExtInfoLen(),
RT_MEMCPY_HOST_TO_DEVICE_EX,
stream));
GELOGI("Update ext info end.");
return SUCCESS;
}
Status AiCpuBaseTask::UpdateOutputShape(vector<GeTensorDesc> &output_desc) {
if (num_outputs_ == 0) {
GELOGD("AiCpuBaseTask output_num is 0, no need update output shape.");
return SUCCESS;
}
GELOGD("Start to update DEPEND_SHAPE_RANGE AiCpuBaseTask outputshape.");
GE_CHK_RT_RET(rtMemcpy(aicpu_ext_handle_->GetExtInfo(), aicpu_ext_handle_->GetExtInfoLen(), ext_info_addr_dev_,
aicpu_ext_handle_->GetExtInfoLen(), RT_MEMCPY_DEVICE_TO_HOST));
for (size_t i = 0; i < num_outputs_; ++i) {
GeShape shape;
DataType data_type;
aicpu_ext_handle_->GetOutputShapeAndType(i, shape, data_type);
GE_CHK_STATUS_RET(UpdateShapeToOutputDesc(shape, output_desc[i]),
"[Update][ShapeToOutputDesc] failed, output:%zu.", i);
if (DumpManager::GetInstance().GetDumpProperties(kInferSessionId).IsSingleOpNeedDump()) {
GE_CHK_STATUS_RET(op_desc_->UpdateOutputDesc(i, output_desc[i]), "[Update][OutputDesc] failed, output:%zu.", i);
}
}
GELOGD("Update DEPEND_SHAPE_RANGE AiCpuBaseTask outputshape finished.");
return SUCCESS;
}
Status AiCpuBaseTask::UpdateShapeToOutputDesc(const GeShape &shape_new, GeTensorDesc &output_desc) {
auto shape_old = output_desc.GetShape();
output_desc.SetShape(shape_new);
GELOGD("Update AiCpuBaseTask shape from %s to %s", shape_old.ToString().c_str(), shape_new.ToString().c_str());
auto origin_shape_old = output_desc.GetOriginShape();
auto origin_format = output_desc.GetOriginFormat();
auto format = output_desc.GetFormat();
if (origin_format == format) {
output_desc.SetOriginShape(shape_new);
return SUCCESS;
}
std::vector<int64_t> origin_dims_new;
auto trans_ret = formats::TransShape(format, shape_new.GetDims(),
output_desc.GetDataType(), origin_format, origin_dims_new);
GE_CHK_STATUS_RET(trans_ret,
"[Trans][Shape] failed, AiCpuTask originFormat[%d] is not same as format[%d], shape=%s.",
origin_format, format, shape_new.ToString().c_str());
auto origin_shape_new = GeShape(origin_dims_new);
output_desc.SetOriginShape(origin_shape_new);
GELOGD("AiCpuTask originFormat[%d] is not same as format[%d], need update from %s ro %s.",
origin_format, format, origin_shape_old.ToString().c_str(), origin_shape_new.ToString().c_str());
return SUCCESS;
}
Status AiCpuBaseTask::UpdateIoAddr(const vector<DataBuffer> &inputs, const vector<DataBuffer> &outputs) {
uintptr_t *arg_base = nullptr;
size_t arg_num = 0;
GetIoAddr(arg_base, arg_num);
// input number and output number was check in ValidateParams
size_t non_const_index = 0;
for (size_t input_index = 0; input_index < num_inputs_; input_index++) {
if (input_index < input_is_const_.size() && input_is_const_[input_index]) {
// const input no need update addr
GE_CHECK_NOTNULL(arg_base);
GELOGD("AICpuTask input[%zu] addr = %lu", input_index, *arg_base);
arg_base++;
continue;
}
GE_CHK_BOOL_RET_STATUS(non_const_index < inputs.size(), ACL_ERROR_GE_PARAM_INVALID,
"[Check][Size] Input size is %zu, but get non_const_index is %zu", inputs.size(), non_const_index);
auto addr = inputs[non_const_index].data;
uint64_t length = inputs[non_const_index].length;
if (length != 0 && addr == nullptr) {
GELOGE(PARAM_INVALID, "[Check][Addr]AiCpuTask input[%zu] addr is nullptr, length = %lu", input_index, length);
return PARAM_INVALID;
}
GELOGD("AICpuTask input[%zu] addr = %p, length = %lu.", input_index, addr, length);
*arg_base++ = reinterpret_cast<uintptr_t>(addr);
non_const_index++;
}
for (size_t i = 0; i < outputs.size(); ++i) {
auto addr = outputs[i].data;
uint64_t length = outputs[i].length;
if (length != 0 && addr == nullptr) {
GELOGE(PARAM_INVALID, "[Check][Addr]AiCpuTask output[%zu] addr is nullptr, length = %lu", i, length);
return PARAM_INVALID;
}
GELOGD("AICpuTask output[%zu] addr = %p, length = %lu.", i, addr, length);
*arg_base++ = reinterpret_cast<uintptr_t>(addr);
}
return SUCCESS;
}
Status AiCpuBaseTask::CheckDeviceSupportBlockingAicpuOpProcess(bool &is_support) {
int32_t device_id = 0;
auto rt_ret = rtGetDevice(&device_id);
if (rt_ret != RT_ERROR_NONE) {
REPORT_CALL_ERROR("E19999", "Call rtGetDevice failed, ret:0x%X", rt_ret);
GELOGE(RT_FAILED, "[Call][rtGetDevice] failed, ret:0x%X", rt_ret);
return RT_ERROR_TO_GE_STATUS(rt_ret);
}
int32_t value = 0;
rt_ret = rtGetDeviceCapability(device_id, FEATURE_TYPE_BLOCKING_OPERATOR, RT_MODULE_TYPE_AICPU, &value);
if (rt_ret != RT_ERROR_NONE) {
REPORT_CALL_ERROR("E19999", "Call rtGetDeviceCapability failed, ret:0x%X", rt_ret);
GELOGE(RT_FAILED, "[Call][rtGetDeviceCapability] failed, ret:0x%X", rt_ret);
return RT_ERROR_TO_GE_STATUS(rt_ret);
}
if (value != RT_AICPU_BLOCKING_OP_NOT_SUPPORT && value != RT_AICPU_BLOCKING_OP_SUPPORT) {
REPORT_INNER_ERROR("E19999", "Value should be %d or %d but %d",
RT_AICPU_BLOCKING_OP_NOT_SUPPORT, RT_AICPU_BLOCKING_OP_SUPPORT, value);
GELOGE(FAILED, "[Check][Value] Value should be %d or %d but %d",
RT_AICPU_BLOCKING_OP_NOT_SUPPORT, RT_AICPU_BLOCKING_OP_SUPPORT, value);
return FAILED;
}
is_support = (value == RT_AICPU_BLOCKING_OP_SUPPORT ? true : false);
return SUCCESS;
}
Status AiCpuBaseTask::DistributeWaitTaskForAicpuBlockingOp(rtStream_t stream) {
bool is_support = false;
if (CheckDeviceSupportBlockingAicpuOpProcess(is_support) != SUCCESS) {
GELOGE(FAILED, "[Call][CheckDeviceSupportBlockingAicpuOpProcess] Call CheckDeviceSupportBlockingAicpuOpProcess failed");
return FAILED;
}
if (!is_support) {
GELOGD("Device not support blocking aicpu op process.");
return SUCCESS;
}
GELOGI("Distribute queue task begin");
if (rt_event_ == nullptr) {
REPORT_INNER_ERROR("E19999", "rt_event_ is nullptr");
GELOGE(FAILED, "[Check][rt_event_] rt_event_ is nullptr");
return FAILED;
}
auto rt_ret = rtStreamWaitEvent(stream, rt_event_);
if (rt_ret != RT_ERROR_NONE) {
REPORT_CALL_ERROR("E19999", "Call rtStreamWaitEvent failed, ret:0x%X", rt_ret);
GELOGE(RT_FAILED, "[Call][RtApi] failed, ret:0x%X", rt_ret);
return RT_ERROR_TO_GE_STATUS(rt_ret);
}
rt_ret = rtEventReset(rt_event_, stream);
if (rt_ret != RT_ERROR_NONE) {
REPORT_CALL_ERROR("E19999", "Call rtEventReset failed, ret:0x%X", rt_ret);
GELOGE(RT_FAILED, "[Call][RtApi] failed, ret:0x%X", rt_ret);
return RT_ERROR_TO_GE_STATUS(rt_ret);
}
return SUCCESS;
}
AiCpuTask::~AiCpuTask() {
FreeHbm(args_);
FreeHbm(io_addr_);
FreeHbm(workspace_addr_);
FreeHbm(copy_workspace_buf_);
FreeHbm(copy_ioaddr_dev_);
FreeHbm(copy_input_release_flag_dev_);
FreeHbm(copy_input_data_size_dev_);
FreeHbm(copy_input_src_dev_);
FreeHbm(copy_input_dst_dev_);
FreeHbm(copy_task_args_buf_);
for (auto summary : output_summary_) {
FreeHbm(summary);
}
for (auto out_shape : out_shape_hbm_) {
FreeHbm(out_shape);
}
}
Status AiCpuTask::LaunchKernel(rtStream_t stream) {
GELOGD("Start to launch kernel. task = %s", this->op_type_.c_str());
auto ret = rtMemcpyAsync(io_addr_,
io_addr_size_,
io_addr_host_.data(),
io_addr_host_.size() * sizeof(void *),
RT_MEMCPY_HOST_TO_DEVICE_EX,
stream);
if (ret != RT_ERROR_NONE) {
GELOGE(ret, "[MemcpyAsync][Date] failed. ret = %d, task = %s", ret, this->op_type_.c_str());
REPORT_CALL_ERROR("E19999", "rtMemcpyAsync data failed, ret = %d, task = %s", ret, this->op_type_.c_str());
return RT_ERROR_TO_GE_STATUS(ret);
}
GELOGI("To invoke rtKernelLaunchEx. task = %s", this->op_type_.c_str());
ret = rtKernelLaunchEx(args_, arg_size_, 0, stream);
if (ret != RT_ERROR_NONE) {
GELOGE(ret, "[Invoke][rtKernelLaunch] failed. ret = %d, task = %s", ret, this->op_type_.c_str());
REPORT_CALL_ERROR("E19999", "invoke rtKernelLaunchEx failed, ret = %d, task = %s", ret, this->op_type_.c_str());
return RT_ERROR_TO_GE_STATUS(ret);
}
GELOGI("[TASK_INFO] %lu/%s", kernel_id_, op_type_.c_str());
GELOGD("Done launch kernel successfully. task = %s", this->op_type_.c_str());
if (is_blocking_aicpu_op_) {
if (DistributeWaitTaskForAicpuBlockingOp(stream) != SUCCESS) {
GELOGE(FAILED, "[Call][DistributeWaitTaskForAicpuBlockingOp] Call DistributeWaitTaskForAicpuBlockingOp failed");
return FAILED;
}
}
return SUCCESS;
}
Status AiCpuTask::PrepareCopyInputs(vector<DataBuffer> &outputs) {
std::vector<uint64_t> copy_input_release_flag;
std::vector<uint64_t> copy_input_data_size;
std::vector<uint64_t> copy_input_src;
std::vector<uint64_t> copy_input_dst;
for (size_t i = 0; i < num_outputs_; ++i) {
const auto &summary = output_summary_host_[i];
GELOGI("Node out[%zu] summary, shape data=0x%lx, shape data size=%lu, raw data=0x%lx, raw data size=%lu.",
i, summary.shape_data_ptr, summary.shape_data_size,
summary.raw_data_ptr, summary.raw_data_size);
auto output = outputs[i];
copy_input_release_flag.emplace_back(kReleaseFlag);
if (summary.raw_data_size > 0) {
copy_input_data_size.emplace_back(output.length);
} else {
copy_input_data_size.emplace_back(summary.raw_data_size);
}
copy_input_src.emplace_back(summary.raw_data_ptr);
copy_input_dst.emplace_back(reinterpret_cast<uintptr_t>(output.data));
const auto &shape_buffer = out_shape_hbm_[i];
copy_input_release_flag.emplace_back(kReleaseFlag);
copy_input_data_size.emplace_back(summary.shape_data_size);
copy_input_src.emplace_back(summary.shape_data_ptr);
copy_input_dst.emplace_back(reinterpret_cast<uintptr_t>(shape_buffer));
}
const size_t copy_input_buf_len = num_outputs_ * kCopyNum * sizeof(uint64_t);
GE_CHK_RT_RET(rtMemcpy(copy_input_release_flag_dev_, copy_input_buf_len,
copy_input_release_flag.data(), copy_input_buf_len, RT_MEMCPY_HOST_TO_DEVICE));
GE_CHK_RT_RET(rtMemcpy(copy_input_data_size_dev_, copy_input_buf_len,
copy_input_data_size.data(), copy_input_buf_len, RT_MEMCPY_HOST_TO_DEVICE));
GE_CHK_RT_RET(rtMemcpy(copy_input_src_dev_, copy_input_buf_len,
copy_input_src.data(), copy_input_buf_len, RT_MEMCPY_HOST_TO_DEVICE));
GE_CHK_RT_RET(rtMemcpy(copy_input_dst_dev_, copy_input_buf_len,
copy_input_dst.data(), copy_input_buf_len, RT_MEMCPY_HOST_TO_DEVICE));
return SUCCESS;
}
Status AiCpuTask::ReadResultSummaryAndPrepareMemory() {
for (size_t i = 0; i < num_outputs_; ++i) {
auto &result_summary = output_summary_host_[i];
GE_CHK_RT_RET(rtMemcpy(&result_summary, sizeof(aicpu::FWKAdapter::ResultSummary),
output_summary_[i], sizeof(aicpu::FWKAdapter::ResultSummary),
RT_MEMCPY_DEVICE_TO_HOST));
auto shape_data_size = result_summary.shape_data_size;
void *shape_buffer = nullptr;
if (shape_data_size > 0) {
GE_CHK_RT_RET(rtMalloc(&shape_buffer, shape_data_size, RT_MEMORY_HBM));
}
out_shape_hbm_.emplace_back(shape_buffer);
}
return SUCCESS;
}
Status AiCpuTask::CopyDataToHbm(vector<DataBuffer> &outputs,
rtStream_t stream) {
GE_CHK_STATUS_RET_NOLOG(PrepareCopyInputs(outputs));
GE_CHK_RT_RET(rtKernelLaunchEx(copy_task_args_buf_, sizeof(STR_FWK_OP_KERNEL),
RT_KERNEL_DEFAULT, stream));
GE_CHK_RT_RET(rtStreamSynchronize(stream));
return SUCCESS;
}
Status AiCpuTask::UpdateShapeByHbmBuffer(vector<GeTensorDesc> &output_desc) {
for (size_t i = 0; i < num_outputs_; ++i) {
const auto &result_summary = output_summary_host_[i];
std::vector<int64_t> shape_dims;
if (result_summary.shape_data_size > 0) {
const auto &shape_hbm = out_shape_hbm_[i];
uint32_t dim_num = result_summary.shape_data_size / sizeof(int64_t);
std::unique_ptr<int64_t[]> shape_addr(new (std::nothrow) int64_t[dim_num]());
GE_CHECK_NOTNULL(shape_addr);
GE_CHK_RT_RET(rtMemcpy(shape_addr.get(), result_summary.shape_data_size, shape_hbm,
result_summary.shape_data_size, RT_MEMCPY_DEVICE_TO_HOST));
for (uint32_t dim_idx = 0; dim_idx < dim_num; ++dim_idx) {
shape_dims.emplace_back(shape_addr[dim_idx]);
GELOGD("Node [%zu]th output dim[%u]=%ld.", i, dim_idx, shape_addr[dim_idx]);
}
}
GE_CHK_STATUS_RET(UpdateShapeToOutputDesc(GeShape(shape_dims), output_desc[i]),
"[Update][ShapeToOutputDesc] failed , output:%zu.", i);
if (DumpManager::GetInstance().GetDumpProperties(kInferSessionId).IsSingleOpNeedDump()) {
GE_CHK_STATUS_RET(op_desc_->UpdateOutputDesc(i, output_desc[i]), "[Update][OutputDesc] failed, output:%zu.", i);
}
}
return SUCCESS;
}
Status AiCpuTask::UpdateShapeAndDataByResultSummary(vector<GeTensorDesc> &output_desc,
vector<DataBuffer> &outputs,
rtStream_t stream) {
if (num_outputs_ == 0) {
GELOGI("Output num is 0, there is no need to update the output and size.");
return SUCCESS;
}
GELOGI("Update shape and data by result summary begin.");
for (auto out_shape : out_shape_hbm_) {
FreeHbm(out_shape);
}
out_shape_hbm_.clear();
GE_CHK_STATUS_RET(ReadResultSummaryAndPrepareMemory(),
"[Read][ResultSummaryAndPrepareMemory] failed.");
GE_CHK_STATUS_RET(CopyDataToHbm(outputs, stream),
"[Copy][DataToHbm] failed.");
GE_CHK_STATUS_RET(UpdateShapeByHbmBuffer(output_desc),
"[Update][ShapeByHbmBuffer] failed.");
for (auto out_shape : out_shape_hbm_) {
FreeHbm(out_shape);
}
out_shape_hbm_.clear();
GELOGI("Update shape and data by result summary end.");
return SUCCESS;
}
Status AiCpuTask::InitForSummaryAndCopy() {
if (unknown_type_ != DEPEND_COMPUTE || num_outputs_ == 0) {
GELOGI("Unknown_type is %d, output num is %zu.", unknown_type_, num_outputs_);
return SUCCESS;
}
output_summary_.resize(num_outputs_);
constexpr auto result_summary_size = sizeof(aicpu::FWKAdapter::ResultSummary);
for (size_t i = 0; i < num_outputs_; ++i) {
GE_CHK_RT_RET(rtMalloc(&output_summary_[i], result_summary_size, RT_MEMORY_HBM));
}
output_summary_host_.resize(num_outputs_);
const size_t copy_input_buf_len = num_outputs_ * kCopyNum * sizeof(uint64_t);
GE_CHK_RT_RET(rtMalloc(©_input_release_flag_dev_, copy_input_buf_len, RT_MEMORY_HBM));
GE_CHK_RT_RET(rtMalloc(©_input_data_size_dev_, copy_input_buf_len, RT_MEMORY_HBM));
GE_CHK_RT_RET(rtMalloc(©_input_src_dev_, copy_input_buf_len, RT_MEMORY_HBM));
GE_CHK_RT_RET(rtMalloc(©_input_dst_dev_, copy_input_buf_len, RT_MEMORY_HBM));
GE_CHK_RT_RET(rtMalloc(©_task_args_buf_, sizeof(STR_FWK_OP_KERNEL), RT_MEMORY_HBM));
std::vector<uint64_t> copy_io_addr;
copy_io_addr.emplace_back(reinterpret_cast<uintptr_t>(copy_input_release_flag_dev_));
copy_io_addr.emplace_back(reinterpret_cast<uintptr_t>(copy_input_data_size_dev_));
copy_io_addr.emplace_back(reinterpret_cast<uintptr_t>(copy_input_src_dev_));
copy_io_addr.emplace_back(reinterpret_cast<uintptr_t>(copy_input_dst_dev_));
const auto copy_io_addr_size = sizeof(uint64_t) * copy_io_addr.size();
GE_CHK_RT_RET(rtMalloc(©_ioaddr_dev_, copy_io_addr_size, RT_MEMORY_HBM));
GE_CHK_RT_RET(rtMemcpy(copy_ioaddr_dev_, copy_io_addr_size,
copy_io_addr.data(), copy_io_addr_size, RT_MEMCPY_HOST_TO_DEVICE));
return SUCCESS;
}
Status AiCpuTask::SetMemCopyTask(const domi::KernelExDef &kernel_def) {
if (kernel_def.args_size() > sizeof(STR_FWK_OP_KERNEL)) {
GELOGE(ACL_ERROR_GE_PARAM_INVALID, "[Check][Size]sizeof STR_FWK_OP_KERNEL is: %lu, but args_size is: %d",
sizeof(STR_FWK_OP_KERNEL), kernel_def.args_size());
REPORT_INNER_ERROR("E19999", "[sizeof STR_FWK_OP_KERNEL is: %lu, but args_size is: %d",
sizeof(STR_FWK_OP_KERNEL), kernel_def.args_size());
return ACL_ERROR_GE_PARAM_INVALID;
}
GE_CHK_RT_RET(rtMalloc(©_workspace_buf_, kernel_def.task_info_size(), RT_MEMORY_HBM));
GE_CHK_RT_RET(rtMemcpy(copy_workspace_buf_, kernel_def.task_info_size(),
kernel_def.task_info().data(), kernel_def.task_info_size(), RT_MEMCPY_HOST_TO_DEVICE));
STR_FWK_OP_KERNEL aicpu_task = {0};
auto sec_ret = memcpy_s(&aicpu_task, sizeof(STR_FWK_OP_KERNEL),
kernel_def.args().data(), kernel_def.args().size());
if (sec_ret != EOK) {
GELOGE(ACL_ERROR_GE_MEMORY_OPERATE_FAILED, "[Update][TaskArgs] failed, ret: %d", sec_ret);
REPORT_INNER_ERROR("E19999", "update STR_FWK_OP_KERNEL args failed because memcpy_s return %d.", sec_ret);
return ACL_ERROR_GE_MEMORY_OPERATE_FAILED;
}
aicpu_task.fwkKernelBase.fwk_kernel.inputOutputAddr = reinterpret_cast<uintptr_t>(copy_ioaddr_dev_);
aicpu_task.fwkKernelBase.fwk_kernel.workspaceBaseAddr = reinterpret_cast<uintptr_t>(copy_workspace_buf_);
aicpu_task.fwkKernelBase.fwk_kernel.extInfoAddr = 0;
aicpu_task.fwkKernelBase.fwk_kernel.extInfoLen = 0;
GE_CHK_RT_RET(rtMemcpy(copy_task_args_buf_, sizeof(STR_FWK_OP_KERNEL),
&aicpu_task, sizeof(STR_FWK_OP_KERNEL), RT_MEMCPY_HOST_TO_DEVICE));
return SUCCESS;
}
Status AiCpuTask::LaunchKernel(const std::vector<GeTensorDesc> &input_desc,
const std::vector<DataBuffer> &input_buffers,
std::vector<GeTensorDesc> &output_desc,
std::vector<DataBuffer> &output_buffers,
rtStream_t stream) {
GE_CHK_STATUS_RET_NOLOG(UpdateExtInfo(input_desc, output_desc, stream));
if (unknown_type_ == DEPEND_COMPUTE) {
std::vector<DataBuffer> summary_buffers;
for (size_t i = 0; i < num_outputs_; ++i) {
summary_buffers.emplace_back(output_summary_[i], sizeof(aicpu::FWKAdapter::ResultSummary), false);
}
GE_CHK_STATUS_RET_NOLOG(UpdateIoAddr(input_buffers, summary_buffers));
} else {
GE_CHK_STATUS_RET_NOLOG(UpdateIoAddr(input_buffers, output_buffers));
}
GE_CHK_STATUS_RET_NOLOG(LaunchKernel(stream));
if (unknown_type_ == DEPEND_SHAPE_RANGE) {
GE_CHK_RT_RET(rtStreamSynchronize(stream));
GE_CHK_STATUS_RET_NOLOG(UpdateOutputShape(output_desc));
} else if (unknown_type_ == DEPEND_COMPUTE) {
GE_CHK_RT_RET(rtStreamSynchronize(stream));
GE_CHK_STATUS_RET_NOLOG(UpdateShapeAndDataByResultSummary(output_desc, output_buffers, stream));
}
return SUCCESS;
}
Status AiCpuBaseTask::UpdateArgTable(const SingleOpModelParam ¶m) {
// aicpu do not have workspace, for now
return DoUpdateArgTable(param, false);
}
const std::string &AiCpuBaseTask::GetTaskType() const { return kTaskTypeAicpu; }
void AiCpuTask::GetIoAddr(uintptr_t *&arg_base, size_t &arg_count) {
arg_base = reinterpret_cast<uintptr_t *>(io_addr_host_.data());
arg_count = io_addr_host_.size();
}
void AiCpuCCTask::SetKernelArgs(std::unique_ptr<uint8_t[]> args, size_t arg_size) {
args_ = std::move(args);
arg_size_ = arg_size;
// The blockdim value is defult "1" for rtCpuKernelLaunch
block_dim_ = 1;
}
void AiCpuCCTask::SetSoName(const std::string &so_name) { so_name_ = so_name; }
void AiCpuCCTask::SetkernelName(const std::string &kernel_Name) { kernel_name_ = kernel_Name; }
void AiCpuCCTask::SetIoAddr(uintptr_t *io_addr) { io_addr_ = io_addr; }
const void *AiCpuCCTask::GetArgs() const { return args_.get(); }
size_t AiCpuCCTask::GetArgSize() const { return arg_size_; }
AiCpuCCTask::~AiCpuCCTask() {
}
Status AiCpuCCTask::LaunchKernel(rtStream_t stream) {
GELOGI("To invoke rtCpuKernelLaunch. block_dim = %u, so_name is %s, kernel_name is %s", block_dim_, so_name_.data(),
kernel_name_.data());
// sm_desc is nullptr, because l2 buffer does not support
auto *sm_desc = reinterpret_cast<rtSmDesc_t *>(sm_desc_);
auto ret = rtCpuKernelLaunchWithFlag(static_cast<const void *>(so_name_.data()),
static_cast<const void *>(kernel_name_.data()),
block_dim_, args_.get(), static_cast<uint32_t>(arg_size_),
sm_desc, stream, dump_flag_);
if (ret != RT_ERROR_NONE) {
GELOGE(ret, "[Invoke][rtCpuKernelLaunchWithFlag] failed. ret = %d.", ret);
REPORT_CALL_ERROR("E19999", "invoke rtCpuKernelLaunchWithFlag failed, ret:%d.", ret);
return RT_ERROR_TO_GE_STATUS(ret);
}
GELOGI("[TASK_INFO] %lu/%s", kernel_id_, op_type_.c_str());
GELOGD("Invoke rtCpuKernelLaunch succeeded");
if (is_blocking_aicpu_op_) {
if (DistributeWaitTaskForAicpuBlockingOp(stream) != SUCCESS) {
GELOGE(FAILED, "[Call][DistributeWaitTaskForAicpuBlockingOp] Call DistributeWaitTaskForAicpuBlockingOp failed");
return FAILED;
}
}
return SUCCESS;
}
Status AiCpuCCTask::LaunchKernel(const std::vector<GeTensorDesc> &input_desc,
const std::vector<DataBuffer> &input_buffers,
std::vector<GeTensorDesc> &output_desc,
std::vector<DataBuffer> &output_buffers,
rtStream_t stream) {
GE_CHK_STATUS_RET_NOLOG(UpdateExtInfo(input_desc, output_desc, stream));
GE_CHK_STATUS_RET_NOLOG(UpdateIoAddr(input_buffers, output_buffers));
GE_CHK_STATUS_RET_NOLOG(LaunchKernel(stream));
if (unknown_type_ == DEPEND_SHAPE_RANGE) {
GE_CHK_RT_RET(rtStreamSynchronize(stream));
GE_CHK_STATUS_RET_NOLOG(UpdateOutputShape(output_desc));
}
return SUCCESS;
}
void AiCpuCCTask::GetIoAddr(uintptr_t *&arg_base, size_t &arg_count) {
arg_base = io_addr_;
arg_count = io_addr_num_;
}
Status MemcpyAsyncTask::LaunchKernel(rtStream_t stream) {
auto src_addr = reinterpret_cast<void *>(addresses_[0]);
auto dst_addr = reinterpret_cast<void *>(addresses_[1]);
kind_ = (kind_ == RT_MEMCPY_ADDR_DEVICE_TO_DEVICE) ? RT_MEMCPY_DEVICE_TO_DEVICE : kind_;
GE_CHK_RT_RET(rtMemcpyAsync(dst_addr, dst_max_, src_addr, count_, kind_, stream));
return SUCCESS;
}
void MemcpyAsyncTask::GetIoAddr(uintptr_t *&arg_base, size_t &arg_count) {
arg_base = addresses_;
arg_count = kMemcpyArgCount;
}
} // namespace ge
| 42.317817 | 124 | 0.700311 | mindspore-ai |
83cddb5172e0b6e734866af702d84efa2a26e143 | 10,804 | cpp | C++ | NVIDIA/benchmarks/transformer/implementations/pytorch/fairseq/data/csrc/make_batches_v0p6.cpp | mengkai94/training_results_v0.6 | 43dc3e250f8da47b5f8833197d74cb8cf1004fc9 | [
"Apache-2.0"
] | 42 | 2019-07-11T18:23:52.000Z | 2021-09-14T08:21:09.000Z | NVIDIA/benchmarks/transformer/implementations/pytorch/fairseq/data/csrc/make_batches_v0p6.cpp | mengkai94/training_results_v0.6 | 43dc3e250f8da47b5f8833197d74cb8cf1004fc9 | [
"Apache-2.0"
] | 23 | 2019-07-29T05:21:52.000Z | 2020-08-31T18:51:42.000Z | NVIDIA/benchmarks/transformer/implementations/pytorch/fairseq/data/csrc/make_batches_v0p6.cpp | mengkai94/training_results_v0.6 | 43dc3e250f8da47b5f8833197d74cb8cf1004fc9 | [
"Apache-2.0"
] | 51 | 2019-07-12T05:10:25.000Z | 2021-07-28T16:19:06.000Z | #include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <torch/extension.h>
namespace at {
namespace native {
namespace {
int64_t roundup(int64_t x, int64_t multiple)
{
return (x + multiple - 1) / multiple * multiple;
} // roundup
int64_t rounddown(int64_t x, int64_t multiple)
{
return x / multiple * multiple;
} // rounddown
std::pair<std::vector<int64_t>, std::vector<int64_t>> create_bucket_bounds_lists(
int64_t max_allowable_seq_length,
int64_t bucket_specify_min_boundary,
float bucket_specify_growth_scale,
bool use_efficient_last_pack)
{
std::vector<int64_t> bucket_boundaries;
auto x = bucket_specify_min_boundary;
while (x < max_allowable_seq_length)
{
bucket_boundaries.emplace_back(x);
x = std::max(x + 1, static_cast<int64_t>(x * bucket_specify_growth_scale));
}
std::vector<int64_t> buckets_min_list;
buckets_min_list.emplace_back(0);
std::vector<int64_t> buckets_max_list;
if (use_efficient_last_pack)
{
for (auto && bound : bucket_boundaries)
{
buckets_min_list.emplace_back(bound + 1);
buckets_max_list.emplace_back(bound);
}
buckets_max_list.push_back(max_allowable_seq_length);
}
else
{
for (auto && bound : bucket_boundaries)
{
buckets_min_list.emplace_back(bound);
buckets_max_list.emplace_back(bound);
}
buckets_max_list.emplace_back(max_allowable_seq_length + 1);
}
return std::make_pair(buckets_min_list, buckets_max_list);
} // create_bucket_bounds_lists
int64_t seq_len_to_bucket_idx(
int64_t seq_length,
int64_t max_seq_length,
std::vector<int64_t> buckets_min_list,
std::vector<int64_t> buckets_max_list)
{
int64_t idx = 0;
// TODO: Update to bisection if execution time actually matters (avoiding premature optimization)
// TODO: Alternate is to make lookup table keys = [0...256] and values are the buckets (this loop just indexes in to avoid repeated traversals)
if (seq_length <= max_seq_length)
{
while (idx < static_cast<int64_t>(buckets_min_list.size()) && !(buckets_min_list[idx] <= seq_length && seq_length < buckets_max_list[idx]))
{
++idx;
}
}
else
{
idx = -1;
}
return idx;
} // seq_len_to_bucket_idx
int64_t seq_len_to_bucket_idx_improved_pack(
int64_t seq_length,
int64_t max_seq_length,
std::vector<int64_t> buckets_min_list,
std::vector<int64_t> buckets_max_list)
{
int64_t idx = 0;
// TODO: Update to bisection if execution time actually matters (avoiding premature optimization)
// TODO: Alternate is to make lookup table keys = [0...256] and values are the buckets (this loop just indexes in to avoid repeated traversals)
if (seq_length <= max_seq_length)
{
while (idx < static_cast<int64_t>(buckets_min_list.size()) && !(buckets_min_list[idx] <= seq_length && seq_length <= buckets_max_list[idx]))
{
++idx;
}
}
else
{
idx = -1;
}
return idx;
} // seq_len_to_bucket_idx_improved_pack
std::pair<std::vector<int64_t>, std::vector<int64_t>> create_seq_to_bucket_id_list_and_n_seq_per_batch(
std::vector<int64_t> n_tok_per_seq, // Number of tokens per sequence
int64_t max_allowable_seq_length, // Maximum sequence length to be considered (rejected if over)
int64_t max_tokens, // Maximum number of tokens allowed in the batch
int64_t pad_seq_per_batch_to_multiple_of, // Padding multiple required, for number of sequences in batch
int64_t pad_tok_per_seq_to_multiple_of, // Padding multiple required, for number of tokens for sequence
int64_t bucket_specify_min_boundary, // This is the first non-zero beginning of a bucket (zero implicitly added)
float bucket_specify_growth_scale, // The next bucket bound is determined from the previous based on this factor
bool do_seq_len_padding_to_multiple, // Switch, enables padding sequence length to multiple
bool do_batch_size_rounding_down_to_multiple, // Switch, enables making other dimension of batch a multiple, based on number of sequences
bool do_dynamic_batch_size_choice, // Switch, enables choosing between methods on a batch-by-batch basis for efficiency
bool use_efficient_last_pack) // Switch, modifies bucket bounds logic to improve batching
{
const auto min_max_bounds = create_bucket_bounds_lists(
max_allowable_seq_length,
bucket_specify_min_boundary,
bucket_specify_growth_scale,
use_efficient_last_pack);
std::vector<int64_t> n_seq_per_batch;
std::vector<int64_t> bucket_idx_list;
const auto bucket_interval_min = min_max_bounds.first;
const auto bucket_interval_max = min_max_bounds.second;
// Choose method
if (do_seq_len_padding_to_multiple)
{
for (auto && item : bucket_interval_max)
{
n_seq_per_batch.emplace_back(max_tokens / roundup(item, pad_tok_per_seq_to_multiple_of));
}
}
else if (do_batch_size_rounding_down_to_multiple)
{
for (auto && item : bucket_interval_max)
{
n_seq_per_batch.emplace_back(rounddown(max_tokens / item, pad_seq_per_batch_to_multiple_of));
}
}
else if (do_dynamic_batch_size_choice)
{
for (auto && item : bucket_interval_max)
{
auto option1 = max_tokens / roundup(item, pad_tok_per_seq_to_multiple_of);
auto option2 = rounddown(max_tokens / item, pad_seq_per_batch_to_multiple_of);
n_seq_per_batch.emplace_back(std::max(option1, option2));
}
}
else
{
for (auto && item : bucket_interval_max)
{
n_seq_per_batch.emplace_back(max_tokens / item);
}
}
// Choose more efficient bounds
if (use_efficient_last_pack)
{
for (auto && seq_length : n_tok_per_seq)
{
int64_t bucket_idx = seq_len_to_bucket_idx_improved_pack(seq_length, max_allowable_seq_length, bucket_interval_min, bucket_interval_max);
bucket_idx_list.push_back(bucket_idx);
}
}
else
{
for (auto && seq_length : n_tok_per_seq)
{
auto bucket_idx = seq_len_to_bucket_idx(seq_length, max_allowable_seq_length, bucket_interval_min, bucket_interval_max);
bucket_idx_list.emplace_back(bucket_idx);
}
}
return std::make_pair(bucket_idx_list, n_seq_per_batch);
} // create_seq_to_bucket_id_list_and_n_seq_per_batch
std::vector<std::vector<int64_t> > make_batches_v0p6(
py::array_t<int64_t> src_lengths,
py::array_t<int64_t> tgt_lengths,
py::array_t<int64_t> idx_list,
int64_t max_tokens,
int64_t max_sentences,
int64_t bsz_mult,
int64_t max_len,
int64_t bucket_specify_min_boundary,
float bucket_specify_growth_scale,
int64_t batch_strategy,
bool use_efficient_last_pack)
{
auto src_l = src_lengths.unchecked<1>();
auto tgt_l = tgt_lengths.unchecked<1>();
auto idx_l = idx_list.unchecked<1>();
std::vector<std::vector<int64_t> > batches(1);
std::vector<int64_t> n_tok_per_seq;
for (int64_t i = 0; i < src_l.shape(0); ++i)
{
const int64_t src_len = src_l(i);
const int64_t tgt_len = tgt_l(i);
n_tok_per_seq.emplace_back(std::max(src_len, tgt_len));
}
const bool do_seq_len_padding_to_multiple = batch_strategy == 1;
const bool do_batch_size_rounding_down_to_multiple = batch_strategy == 0;
const bool do_dynamic_batch_size_choice = batch_strategy == 2;
// Get vector of bucket ids (one per seq)
const auto bucket_ids_and_n_seq_per_batch = create_seq_to_bucket_id_list_and_n_seq_per_batch(
n_tok_per_seq,
max_len,
max_tokens,
bsz_mult,
bsz_mult, // TODO: Make this independently varied (for now assumed to be 8 for both anyways)
bucket_specify_min_boundary,
bucket_specify_growth_scale,
do_seq_len_padding_to_multiple,
do_batch_size_rounding_down_to_multiple,
do_dynamic_batch_size_choice,
use_efficient_last_pack);
const auto bucket_ids = bucket_ids_and_n_seq_per_batch.first;
const auto n_seq_per_batch = bucket_ids_and_n_seq_per_batch.second;
// Get buckets
const auto min_max_bounds = create_bucket_bounds_lists(
max_len,
bucket_specify_min_boundary,
bucket_specify_growth_scale,
use_efficient_last_pack);
const auto bucket_interval_min = min_max_bounds.first;
const auto bucket_interval_max = min_max_bounds.second;
// Fill buckets
std::vector<std::vector<int64_t> > buckets(bucket_interval_min.size(), std::vector<int64_t>());
int64_t id_cnt = 0;
for (auto && id : bucket_ids)
{
if (id == -1)
{
id_cnt += 1;
}
}
int64_t reject_count = 0;
int64_t dummy = 0;
for (int64_t i = 0; i < static_cast<int64_t>(bucket_ids.size()); ++i)
{
if (bucket_ids[i] >= 0)
{
const auto bidx = bucket_ids[i];
buckets[bidx].emplace_back(i);
}
else
{
++reject_count;
}
}
// Get number sequences rejected due to sequence length
std::cout << reject_count << " sequences were omitted due to containing over " << max_len << " tokens." << std::endl;
int64_t batch_n_seq = 0;
for (int64_t i = 0; i < static_cast<int64_t>(buckets.size()); ++i)
{
const auto bucket = buckets[i];
const auto nspb = n_seq_per_batch[i];
for (auto && item : bucket)
{
if (batch_n_seq < nspb)
{
batches.back().emplace_back(item);
++batch_n_seq;
}
else
{
std::vector<int64_t> new_batch;
new_batch.emplace_back(item);
batches.emplace_back(new_batch);
batch_n_seq = 1;
}
}
batches.emplace_back(std::vector<int64_t>());
batch_n_seq = 0;
}
if (batches.back().empty())
{
batches.pop_back();
}
auto i = std::begin(batches);
while (i != std::end(batches))
{
if ((*i).empty())
{
i = batches.erase(i);
}
else
{
++i;
}
}
return batches;
}
} // namespace
} // namespace at
} // namespace native
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m){
m.def("make_batches_v0p6", &at::native::make_batches_v0p6);
}
| 31.776471 | 149 | 0.653277 | mengkai94 |
83d284ff83da1c52a3e20d49c50879f0340a3e11 | 192 | cpp | C++ | src/JSEUIMenuLeafImpl.cpp | imzcy/JavaScriptExecutable | 723a13f433aafad84faa609f62955ce826063c66 | [
"MIT"
] | 3 | 2015-03-18T03:12:27.000Z | 2020-11-19T10:40:12.000Z | src/JSEUIMenuLeafImpl.cpp | imzcy/JavaScriptExecutable | 723a13f433aafad84faa609f62955ce826063c66 | [
"MIT"
] | null | null | null | src/JSEUIMenuLeafImpl.cpp | imzcy/JavaScriptExecutable | 723a13f433aafad84faa609f62955ce826063c66 | [
"MIT"
] | null | null | null | #include "JSEUIMenuLeafImpl.h"
namespace JSE { namespace UI {
JSEUIMenuLeafImpl::JSEUIMenuLeafImpl(QWidget *parent)
: QAction(parent)
{
}
JSEUIMenuLeafImpl::~JSEUIMenuLeafImpl()
{}
}} | 13.714286 | 53 | 0.739583 | imzcy |
83d4bd29208359d57a0680654dc43ad268cfb655 | 1,936 | hpp | C++ | game_files/game_order/game_order.hpp | sakumo7/zpr | 7b9cdbec1ff8d8179a96bb6e1e88f54ee84d138e | [
"MIT"
] | null | null | null | game_files/game_order/game_order.hpp | sakumo7/zpr | 7b9cdbec1ff8d8179a96bb6e1e88f54ee84d138e | [
"MIT"
] | null | null | null | game_files/game_order/game_order.hpp | sakumo7/zpr | 7b9cdbec1ff8d8179a96bb6e1e88f54ee84d138e | [
"MIT"
] | null | null | null | #ifndef GAME_ORDER_HPP
#define GAME_ORDER_HPP
#include "../typedefs.hpp"
#include <vector>
#include <memory>
#include "../game_engine/game_engine.hpp"
typedef std::unique_ptr<std::vector<unsigned int>> ship_vector_uptr;
class GameOrder{
public:
virtual std::string toString() const=0;
virtual int type() const = 0;
};
class MoveOrder : public GameOrder{
public:
enum {type_id = 1};
MoveOrder():start_point_id_(0), destination_id_(0) {ship_id_vector_ = std::make_unique<std::vector<unsigned int>>();}
MoveOrder(unsigned int start_point_id, unsigned int destination_id, const std::vector<unsigned int>& ship_id_vector):
start_point_id_(start_point_id), destination_id_(destination_id){ship_id_vector_ = std::make_unique<std::vector<unsigned int>> (ship_id_vector);}
MoveOrder(std::string data);
std::string toString() const;
unsigned int getStartPoint() const {return start_point_id_;}
unsigned int getDestination() const {return destination_id_;}
const ship_vector_uptr& getShipVector() const {return ship_id_vector_;}
int type() const{return MoveOrder::type_id;}
private:
unsigned int start_point_id_;
unsigned int destination_id_;
ship_vector_uptr ship_id_vector_;
};
class BuildOrder : public GameOrder{
public:
BuildOrder(unsigned int point_id = 0): point_id_(point_id){}
BuildOrder(std::string data);
enum {type_id= 2};
unsigned int getPointId() const {return point_id_;}
std::string toString() const;
int type() const {return BuildOrder::type_id;}
private:
unsigned int point_id_;
};
class CreateShipOrder: public GameOrder{
public:
enum {type_id=3};
CreateShipOrder(unsigned int point_id = 0): point_id_(point_id){}
std::string toString() const;
CreateShipOrder(std::string data);
unsigned int getPointId() const {return point_id_;}
int type() const {return CreateShipOrder::type_id;}
private:
unsigned int point_id_;
};
#endif //GAME_ORDER_HPP
| 31.225806 | 146 | 0.75 | sakumo7 |
83d987d24bfb176ca10c8132e11da65f1009d534 | 2,715 | cpp | C++ | session-manager/common/call/CallInGetUserSession.cpp | Syamsuri227/FreeRDS | 933f43a9f2dfd254d825e6687c8ca536ec2bf569 | [
"Apache-2.0"
] | 14 | 2015-02-17T15:43:46.000Z | 2022-02-17T07:11:46.000Z | session-manager/common/call/CallInGetUserSession.cpp | Syamsuri227/FreeRDS | 933f43a9f2dfd254d825e6687c8ca536ec2bf569 | [
"Apache-2.0"
] | 4 | 2015-03-22T10:26:38.000Z | 2020-07-07T13:35:56.000Z | session-manager/common/call/CallInGetUserSession.cpp | Syamsuri227/FreeRDS | 933f43a9f2dfd254d825e6687c8ca536ec2bf569 | [
"Apache-2.0"
] | 58 | 2015-04-08T02:24:17.000Z | 2022-03-29T15:59:15.000Z | /**
* Class for rpc call GetUserSession (freerds to session manager)
*
* Copyright 2013 Thinstuff Technologies GmbH
* Copyright 2013 DI (FH) Martin Haimberger <martin.haimberger@thinstuff.at>
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "CallInGetUserSession.h"
#include <appcontext/ApplicationContext.h>
using freerds::icp::GetUserSessionRequest;
using freerds::icp::GetUserSessionResponse;
namespace freerds{
namespace sessionmanager{
namespace call{
CallInGetUserSession::CallInGetUserSession() {
};
CallInGetUserSession::~CallInGetUserSession() {
};
unsigned long CallInGetUserSession::getCallType() {
return freerds::icp::GetUserSession;
};
int CallInGetUserSession::decodeRequest() {
// decode protocol buffers
GetUserSessionRequest req;
if (!req.ParseFromString(mEncodedRequest)) {
// failed to parse
mResult = 1;// will report error with answer
return -1;
}
mUserName = req.username();
if (req.has_domainname()) {
mDomainName = req.domainname();
}
return 0;
};
int CallInGetUserSession::encodeResponse() {
// encode protocol buffers
GetUserSessionResponse resp;
// stup do stuff here
resp.set_sessionid(mSessionID);
resp.set_serviceendpoint(mPipeName);
if (!resp.SerializeToString(&mEncodedResponse)) {
// failed to serialize
mResult = 1;
return -1;
}
return 0;
};
int CallInGetUserSession::doStuff() {
std::string pipeName;
sessionNS::Session * currentSession = APP_CONTEXT.getSessionStore()->createSession();
currentSession->setUserName(mUserName);
currentSession->setDomain(mDomainName);
if (!currentSession->generateUserToken()) {
mResult = 1;// will report error with answer
return 1;
}
if (!currentSession->generateEnvBlockAndModify() ){
mResult = 1;// will report error with answer
return 1;
}
currentSession->setModuleName("x11module");
if (!currentSession->startModule(pipeName)) {
mResult = 1;// will report error with answer
return 1;
}
mSessionID = currentSession->getSessionID();
mPipeName = pipeName;
return 0;
}
}
}
}
| 24.908257 | 88 | 0.710497 | Syamsuri227 |
83dbec132ac763ab5b591eecaf876cad502393b0 | 2,108 | cpp | C++ | MemSpy/MemSpy/Sources/CommandLine.cpp | piskunovdenis/MemSpy | 84c4994a5c3a0f7a9379f64609a6eff4a3d7985f | [
"MIT"
] | null | null | null | MemSpy/MemSpy/Sources/CommandLine.cpp | piskunovdenis/MemSpy | 84c4994a5c3a0f7a9379f64609a6eff4a3d7985f | [
"MIT"
] | null | null | null | MemSpy/MemSpy/Sources/CommandLine.cpp | piskunovdenis/MemSpy | 84c4994a5c3a0f7a9379f64609a6eff4a3d7985f | [
"MIT"
] | null | null | null | #include <algorithm>
#include <windows.h>
#include <stdexcept>
#include "CommandLine.hpp"
#include "WideString.hpp"
namespace memspy
{
const std::vector<wchar_t> CommandLine::kParamSeparators = { L'-', L'/' };
const std::vector<wchar_t> CommandLine::kNameValueSeparators = { L':', L'=' };
CommandLine::CommandLine(int argc, _TCHAR* argv[]) :
m_Arguments(argv + 1, argv + argc)
{
}
bool CommandLine::FindParam(const std::wstring& searchingParamName) const
{
if (!searchingParamName.empty())
{
for (const auto& i : m_Arguments)
{
std::wstring paramName;
std::wstring paramValue;
ParseParam(i, paramName, paramValue);
if (memspy::WideString::Compare(paramName, searchingParamName) ||
memspy::WideString::Compare(L"-" + paramName, searchingParamName) ||
memspy::WideString::Compare(L"/" + paramName, searchingParamName))
{
return true;
}
}
}
return false;
}
std::wstring CommandLine::GetParamValue(const std::wstring& searchingParamName) const
{
if (!searchingParamName.empty())
{
for (const auto& i : m_Arguments)
{
std::wstring paramName;
std::wstring paramValue;
ParseParam(i, paramName, paramValue);
if (memspy::WideString::Compare(paramName, searchingParamName))
{
return paramValue;
}
}
}
return L"";
}
void CommandLine::ParseParam(const std::wstring& param, std::wstring& rParamName, std::wstring& rParamValue) const
{
rParamName = L"";
rParamValue = L"";
if (param.empty())
return;
for (auto i : kParamSeparators)
{
if (param[0] == i)
{
rParamName = param.substr(1, param.length());
break;
}
}
size_t firstSeparatorPos{ std::wstring::npos };
for (auto i : kNameValueSeparators)
{
size_t separatorPos = rParamName.find(i);
if (separatorPos != std::wstring::npos)
{
firstSeparatorPos = min(separatorPos, firstSeparatorPos);
}
}
if (firstSeparatorPos != std::wstring::npos)
{
rParamValue = rParamName.substr(firstSeparatorPos + 1, std::wstring::npos);
}
rParamName = rParamName.substr(0, firstSeparatorPos);
}
} | 23.685393 | 115 | 0.666034 | piskunovdenis |
83dc85e75596c3bcee21afa8ca606de437c7467a | 4,045 | cpp | C++ | src/blocksigner.cpp | jazy510/XSN | 6ea74506573c6253c2ce933aafce9ad8b2d95659 | [
"MIT"
] | 1 | 2021-04-04T20:38:41.000Z | 2021-04-04T20:38:41.000Z | src/blocksigner.cpp | jazy510/XSN | 6ea74506573c6253c2ce933aafce9ad8b2d95659 | [
"MIT"
] | null | null | null | src/blocksigner.cpp | jazy510/XSN | 6ea74506573c6253c2ce933aafce9ad8b2d95659 | [
"MIT"
] | null | null | null | #include "blocksigner.h"
#include "tpos/tposutils.h"
#include "tpos/activemerchantnode.h"
#include "keystore.h"
#include "primitives/block.h"
#include "utilstrencodings.h"
CBlockSigner::CBlockSigner(CBlock &block, const CKeyStore &keystore, const TPoSContract &contract) :
refBlock(block),
refKeystore(keystore),
refContract(contract)
{
}
bool CBlockSigner::SignBlock()
{
std::vector<std::vector<unsigned char>> vSolutions;
txnouttype whichType;
CKey keySecret;
if(refBlock.IsProofOfStake())
{
const CTxOut& txout = refBlock.vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if(refBlock.IsTPoSBlock())
{
CKeyID merchantKeyID;
if(!refContract.merchantAddress.GetKeyID(merchantKeyID))
return error("CBlockSigner::SignBlock() : merchant address is not P2PKH, critical error, can't accept.");
if(merchantKeyID != activeMerchantnode.pubKeyMerchantnode.GetID())
return error("CBlockSigner::SignBlock() : contract address is different from merchantnode address, won't sign.");
keySecret = activeMerchantnode.keyMerchantnode;
}
else
{
CKeyID keyID;
if (whichType == TX_PUBKEYHASH)
{
keyID = CKeyID(uint160(vSolutions[0]));
}
else if(whichType == TX_PUBKEY)
{
keyID = CPubKey(vSolutions[0]).GetID();
}
if (!refKeystore.GetKey(keyID, keySecret))
return false;
}
}
else
{
const CTxOut& txout = refBlock.vtx[0].vout[0];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
CKeyID keyID;
if (whichType == TX_PUBKEYHASH)
{
keyID = CKeyID(uint160(vSolutions[0]));
}
else if(whichType == TX_PUBKEY)
{
keyID = CPubKey(vSolutions[0]).GetID();
}
if (!refKeystore.GetKey(keyID, keySecret))
return false;
}
return keySecret.SignCompact(refBlock.IsTPoSBlock() ? refBlock.GetTPoSHash() : refBlock.GetHash(), refBlock.vchBlockSig);
}
bool CBlockSigner::CheckBlockSignature() const
{
if(refBlock.IsProofOfWork())
return true;
if(refBlock.vchBlockSig.empty())
return false;
std::vector<std::vector<unsigned char>> vSolutions;
txnouttype whichType;
const CTxOut& txout = refBlock.vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
CKeyID signatureKeyID;
CPubKey recoveredKey;
auto hashMessage = refBlock.IsTPoSBlock() ? refBlock.GetTPoSHash() : refBlock.GetHash();
if(!recoveredKey.RecoverCompact(hashMessage, refBlock.vchBlockSig))
return error("CBlockSigner::CheckBlockSignature() : failed to recover public key from signature");
if(refBlock.IsProofOfStake())
{
if(refBlock.IsTPoSBlock())
{
if(!refContract.merchantAddress.GetKeyID(signatureKeyID))
return error("CBlockSigner::CheckBlockSignature() : merchant address is not P2PKH, critical error, can't accept.");
}
else
{
if (whichType == TX_PUBKEYHASH)
{
signatureKeyID = CKeyID(uint160(vSolutions[0]));
}
else if(whichType == TX_PUBKEY)
{
signatureKeyID = CPubKey(vSolutions[0]).GetID();
}
}
}
else
{
const CTxOut& txout = refBlock.vtx[0].vout[0];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEYHASH)
{
signatureKeyID = CKeyID(uint160(vSolutions[0]));
}
else if(whichType == TX_PUBKEY)
{
signatureKeyID = CPubKey(vSolutions[0]).GetID();
}
}
return recoveredKey.GetID() == signatureKeyID;
}
| 27.705479 | 131 | 0.595797 | jazy510 |
83e058a2001fcf61af5b1aa8f04a126b1cb30ba7 | 459 | hpp | C++ | include/rive/constraints/targeted_constraint.hpp | kariem2k/rive-cpp | f58c3b3d48ea03947a76971bce17e7f567cf0de0 | [
"MIT"
] | 139 | 2020-08-17T20:10:24.000Z | 2022-03-28T12:22:44.000Z | include/rive/constraints/targeted_constraint.hpp | kariem2k/rive-cpp | f58c3b3d48ea03947a76971bce17e7f567cf0de0 | [
"MIT"
] | 89 | 2020-08-28T16:41:01.000Z | 2022-03-28T19:10:49.000Z | include/rive/constraints/targeted_constraint.hpp | kariem2k/rive-cpp | f58c3b3d48ea03947a76971bce17e7f567cf0de0 | [
"MIT"
] | 19 | 2020-10-19T00:54:40.000Z | 2022-02-28T05:34:17.000Z | #ifndef _RIVE_TARGETED_CONSTRAINT_HPP_
#define _RIVE_TARGETED_CONSTRAINT_HPP_
#include "rive/generated/constraints/targeted_constraint_base.hpp"
#include <stdio.h>
namespace rive
{
class TransformComponent;
class TargetedConstraint : public TargetedConstraintBase
{
protected:
TransformComponent* m_Target = nullptr;
public:
void buildDependencies() override;
StatusCode onAddedDirty(CoreContext* context) override;
};
} // namespace rive
#endif | 24.157895 | 66 | 0.812636 | kariem2k |
83e0eb15225bda6935122b0f804610d14d20a668 | 3,597 | cpp | C++ | src/material/deferredMaterial.cpp | mfirmin/audio-demo | 767e2fc1b7afb53cd5aafad90ae562661a154373 | [
"MIT"
] | 1 | 2021-09-13T20:22:29.000Z | 2021-09-13T20:22:29.000Z | src/material/deferredMaterial.cpp | mfirmin/audio-demo | 767e2fc1b7afb53cd5aafad90ae562661a154373 | [
"MIT"
] | null | null | null | src/material/deferredMaterial.cpp | mfirmin/audio-demo | 767e2fc1b7afb53cd5aafad90ae562661a154373 | [
"MIT"
] | 1 | 2021-09-13T20:22:31.000Z | 2021-09-13T20:22:31.000Z | #include "deferredMaterial.hpp"
#include "gl/shaderUtils.hpp"
#include "light/light.hpp"
#include <GL/glew.h>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <string>
#include <sstream>
DeferredMaterial::DeferredMaterial(glm::vec3 color, float specularCoefficient, float shininess) : Material(color, specularCoefficient, shininess) {
}
void DeferredMaterial::create() {
if (getProgram() != 0) {
// already initialized
return;
}
std::string vertexShaderSource = R"(
#version 330
layout(location = 0) in vec3 position;
layout(location = 1) in vec3 normal;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;
out vec3 vNormalEyespace;
out vec4 vPositionEyespace;
void main() {
vNormalEyespace = (transpose(inverse(viewMatrix * modelMatrix)) * vec4(normal, 0.0)).xyz;
vPositionEyespace = viewMatrix * modelMatrix * vec4(position, 1.0);
gl_Position = projectionMatrix * vPositionEyespace;
}
)";
std::string fragmentShaderSource = R"(
#version 330
layout(location = 0) out vec4 position;
layout(location = 1) out vec3 normal;
layout(location = 2) out vec4 albedo;
layout(location = 3) out vec4 emissive;
uniform mat4 viewMatrix;
uniform vec3 color;
uniform float specularCoefficient;
// todo: shininess?
// uniform float shininess;
uniform vec3 emissiveColor;
uniform float emissiveStrength;
uniform float emissiveEnabled;
in vec3 vNormalEyespace;
in vec4 vPositionEyespace;
void main() {
vec3 N = normalize(vNormalEyespace);
vec3 E = normalize(-vPositionEyespace.xyz);
if (dot(N, E) < 0.0) {
N = -N;
}
position = vPositionEyespace;
normal = N;
albedo = vec4(color, specularCoefficient);
if (emissiveEnabled > 0.5) {
emissive = vec4(emissiveColor, emissiveStrength);
}
}
)";
if (!compile(vertexShaderSource, fragmentShaderSource)) {
return;
}
GLuint shader = getProgram();
glUseProgram(shader);
auto projectionMatrixLocation = glGetUniformLocation(shader, "projectionMatrix");
auto viewMatrixLocation = glGetUniformLocation(shader, "viewMatrix");
auto modelMatrixLocation = glGetUniformLocation(shader, "modelMatrix");
auto colorLocation = glGetUniformLocation(shader, "color");
auto specularCoefficientLocation = glGetUniformLocation(shader, "specularCoefficient");
auto emissiveColorLocation = glGetUniformLocation(shader, "emissiveColor");
auto emissiveStrengthLocation = glGetUniformLocation(shader, "emissiveStrength");
auto emissiveEnabledLocation = glGetUniformLocation(shader, "emissiveEnabled");
glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(glm::mat4(1.0)));
glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, glm::value_ptr(glm::mat4(1.0)));
glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, glm::value_ptr(glm::mat4(1.0)));
glUniform3fv(colorLocation, 1, glm::value_ptr(getColor()));
glUniform1f(specularCoefficientLocation, getSpecularCoefficient());
glUniform3fv(emissiveColorLocation, 1, glm::value_ptr(getColor()));
glUniform1f(emissiveStrengthLocation, 0.0f);
glUniform1f(emissiveEnabledLocation, 0.0f);
glUseProgram(0);
}
DeferredMaterial::~DeferredMaterial() {}
| 33 | 147 | 0.666389 | mfirmin |
83e104455c56eff23af6d81cacb374c026a45e40 | 29,189 | cpp | C++ | src/app/qgsbookmarks.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/app/qgsbookmarks.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/app/qgsbookmarks.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | 1 | 2021-12-25T08:40:30.000Z | 2021-12-25T08:40:30.000Z | /***************************************************************************
QgsBookmarks.cpp - Spatial Bookmarks
-------------------
begin : 2005-04-23
copyright : (C) 2005 Gary Sherman
email : sherman at mrcc dot com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgisapp.h"
#include "qgsapplication.h"
#include "qgsbookmarks.h"
#include "qgsmapcanvas.h"
#include "qgsproject.h"
#include "qgsmessagelog.h"
#include "qgslogger.h"
#include "qgssettings.h"
#include "qgsgui.h"
#include <QFileDialog>
#include <QFileInfo>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QModelIndex>
#include <QDoubleSpinBox>
#include <QAbstractTableModel>
#include <QToolButton>
const int QgsDoubleSpinBoxBookmarksDelegate::DECIMAL_PLACES = 6;
QgsBookmarks::QgsBookmarks( QWidget *parent )
: QgsDockWidget( parent )
{
setupUi( this );
QgsGui::enableAutoGeometryRestore( this );
connect( lstBookmarks, &QTreeView::doubleClicked, this, &QgsBookmarks::lstBookmarks_doubleClicked );
bookmarksDockContents->layout()->setMargin( 0 );
bookmarksDockContents->layout()->setContentsMargins( 0, 0, 0, 0 );
static_cast< QGridLayout * >( bookmarksDockContents->layout() )->setVerticalSpacing( 0 );
QToolButton *btnImpExp = new QToolButton;
btnImpExp->setAutoRaise( true );
btnImpExp->setToolTip( tr( "Import/Export Bookmarks" ) );
btnImpExp->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSharing.svg" ) ) );
btnImpExp->setPopupMode( QToolButton::InstantPopup );
QMenu *share = new QMenu( this );
QAction *btnExport = share->addAction( tr( "&Export" ) );
QAction *btnImport = share->addAction( tr( "&Import" ) );
btnExport->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSharingExport.svg" ) ) );
btnImport->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSharingImport.svg" ) ) );
connect( btnExport, &QAction::triggered, this, &QgsBookmarks::exportToXml );
connect( btnImport, &QAction::triggered, this, &QgsBookmarks::importFromXml );
btnImpExp->setMenu( share );
connect( actionAdd, &QAction::triggered, this, &QgsBookmarks::addClicked );
connect( actionDelete, &QAction::triggered, this, &QgsBookmarks::deleteClicked );
connect( actionZoomTo, &QAction::triggered, this, &QgsBookmarks::zoomToBookmark );
mBookmarkToolbar->addWidget( btnImpExp );
// open the database
QSqlDatabase db = QSqlDatabase::addDatabase( QStringLiteral( "QSQLITE" ), QStringLiteral( "bookmarks" ) );
db.setDatabaseName( QgsApplication::qgisUserDatabaseFilePath() );
if ( ! db.open() )
{
QMessageBox::warning( this, tr( "Spatial Bookmarks" ),
tr( "Unable to open bookmarks database.\nDatabase: %1\nDriver: %2\nDatabase: %3" )
.arg( QgsApplication::qgisUserDatabaseFilePath(),
db.lastError().driverText(),
db.lastError().databaseText() )
);
deleteLater();
return;
}
// Do not set parent or the destructor will try to write on the log viewer (and crash QGIS)
mQgisModel = new QSqlTableModel( nullptr, db );
mQgisModel->setTable( QStringLiteral( "tbl_bookmarks" ) );
mQgisModel->setSort( 0, Qt::AscendingOrder );
mQgisModel->select();
mQgisModel->setEditStrategy( QSqlTableModel::OnFieldChange );
// set better headers then column names from table
mQgisModel->setHeaderData( 0, Qt::Horizontal, tr( "ID" ) );
mQgisModel->setHeaderData( 1, Qt::Horizontal, tr( "Name" ) );
mQgisModel->setHeaderData( 2, Qt::Horizontal, tr( "Project" ) );
mQgisModel->setHeaderData( 3, Qt::Horizontal, tr( "xMin" ) );
mQgisModel->setHeaderData( 4, Qt::Horizontal, tr( "yMin" ) );
mQgisModel->setHeaderData( 5, Qt::Horizontal, tr( "xMax" ) );
mQgisModel->setHeaderData( 6, Qt::Horizontal, tr( "yMax" ) );
mQgisModel->setHeaderData( 7, Qt::Horizontal, tr( "SRID" ) );
mProjectModel = new QgsProjectBookmarksTableModel( this );
mMergedModel = new QgsMergedBookmarksTableModel( *mQgisModel, *mProjectModel, lstBookmarks, this );
mProxyModel = new QgsBookmarksProxyModel( );
mProxyModel->setSourceModel( mMergedModel );
mProxyModel->setSortCaseSensitivity( Qt::CaseInsensitive );
lstBookmarks->setModel( mProxyModel );
lstBookmarks->setItemDelegate( new QgsDoubleSpinBoxBookmarksDelegate( this ) );
lstBookmarks->setSortingEnabled( true );
lstBookmarks->sortByColumn( 1, Qt::AscendingOrder );
connect( mMergedModel, &QgsMergedBookmarksTableModel::selectItem, this, [ = ]( const QModelIndex & index )
{
QModelIndex proxyIndex( mProxyModel->mapFromSource( index ) );
lstBookmarks->scrollTo( proxyIndex );
lstBookmarks->setCurrentIndex( proxyIndex );
} );
connect( mMergedModel, &QgsMergedBookmarksTableModel::layoutChanged, mProxyModel, &QgsBookmarksProxyModel::_resetModel );
QgsSettings settings;
lstBookmarks->header()->restoreState( settings.value( QStringLiteral( "Windows/Bookmarks/headerstate" ) ).toByteArray() );
#ifndef QGISDEBUG
lstBookmarks->setColumnHidden( 0, true );
#endif
}
QgsBookmarks::~QgsBookmarks()
{
delete mQgisModel;
delete mProxyModel;
QSqlDatabase::removeDatabase( QStringLiteral( "bookmarks" ) );
saveWindowLocation();
}
void QgsBookmarks::saveWindowLocation()
{
QgsSettings settings;
settings.setValue( QStringLiteral( "Windows/Bookmarks/headerstate" ), lstBookmarks->header()->saveState() );
}
void QgsBookmarks::addClicked()
{
Q_ASSERT( mMergedModel );
Q_ASSERT( mQgisModel );
QgsMapCanvas *canvas = QgisApp::instance()->mapCanvas();
Q_ASSERT( canvas );
QString projStr;
if ( QgsProject::instance() )
{
if ( !QgsProject::instance()->title().isEmpty() )
{
projStr = QgsProject::instance()->title();
}
else if ( !QgsProject::instance()->fileName().isEmpty() )
{
QFileInfo fi( QgsProject::instance()->fileName() );
projStr = fi.exists() ? fi.fileName() : QString();
}
}
QSqlRecord record = mQgisModel->record();
record.setValue( 1, QVariant( tr( "New bookmark" ) ) );
record.setValue( 2, QVariant( projStr ) );
record.setValue( 3, QVariant( canvas->extent().xMinimum() ) );
record.setValue( 4, QVariant( canvas->extent().yMinimum() ) );
record.setValue( 5, QVariant( canvas->extent().xMaximum() ) );
record.setValue( 6, QVariant( canvas->extent().yMaximum() ) );
record.setValue( 7, QVariant::fromValue( canvas->mapSettings().destinationCrs().srsid() ) );
if ( mQgisModel->insertRecord( -1, record ) )
{
mQgisModel->setSort( 0, Qt::AscendingOrder );
mQgisModel->select();
QModelIndex newIdx = mProxyModel->mapFromSource( mMergedModel->index( mQgisModel->rowCount() - 1, 1 ) );
// Edit new bookmark title
lstBookmarks->scrollTo( newIdx );
lstBookmarks->setCurrentIndex( newIdx );
lstBookmarks->edit( newIdx );
}
else
{
QMessageBox::warning( this, tr( "Add Bookmark" ), tr( "Unable to create the bookmark.\nDriver: %1\nDatabase: %2" )
.arg( mQgisModel->database().lastError().driverText(),
mQgisModel->database().lastError().databaseText() ) );
}
}
void QgsBookmarks::deleteClicked()
{
QItemSelection selection( mProxyModel->mapSelectionToSource( lstBookmarks->selectionModel()->selection() ) );
std::vector<int> rows;
for ( const auto &selectedIdx : selection.indexes() )
{
if ( selectedIdx.column() == 1 )
rows.push_back( selectedIdx.row() );
}
if ( rows.size() == 0 )
return;
// make sure the user really wants to delete these bookmarks
if ( QMessageBox::No == QMessageBox::question( this, tr( "Delete Bookmarks" ),
tr( "Are you sure you want to delete %n bookmark(s)?", "number of rows", rows.size() ),
QMessageBox::Yes | QMessageBox::No ) )
return;
// Remove in reverse order to keep the merged model indexes
std::sort( rows.begin(), rows.end(), std::greater<int>() );
for ( const auto &row : rows )
{
mMergedModel->removeRow( row );
}
mProxyModel->_resetModel();
}
void QgsBookmarks::lstBookmarks_doubleClicked( const QModelIndex &index )
{
Q_UNUSED( index );
zoomToBookmark();
}
void QgsBookmarks::zoomToBookmark()
{
QModelIndex index = lstBookmarks->currentIndex();
if ( !index.isValid() )
return;
zoomToBookmarkIndex( index );
}
void QgsBookmarks::zoomToBookmarkIndex( const QModelIndex &index )
{
double xmin = index.sibling( index.row(), 3 ).data().toDouble();
double ymin = index.sibling( index.row(), 4 ).data().toDouble();
double xmax = index.sibling( index.row(), 5 ).data().toDouble();
double ymax = index.sibling( index.row(), 6 ).data().toDouble();
QString authid = index.sibling( index.row(), 7 ).data().toString();
QgsRectangle rect = QgsRectangle( xmin, ymin, xmax, ymax );
// backwards compatibility, older version had -1 in the srid column
if ( ! authid.isEmpty( ) &&
authid != QgisApp::instance()->mapCanvas()->mapSettings().destinationCrs().authid() )
{
QgsCoordinateTransform ct( QgsCoordinateReferenceSystem::fromOgcWmsCrs( authid ),
QgisApp::instance()->mapCanvas()->mapSettings().destinationCrs(), QgsProject::instance() );
rect = ct.transform( rect );
if ( rect.isEmpty() )
{
QMessageBox::warning( this, tr( "Empty Extent" ), tr( "Reprojected extent is empty." ) );
return;
}
}
// set the extent to the bookmark and refresh
QgisApp::instance()->setExtent( rect );
QgisApp::instance()->mapCanvas()->refresh();
}
void QgsBookmarks::importFromXml()
{
QgsSettings settings;
QString lastUsedDir = settings.value( QStringLiteral( "Windows/Bookmarks/LastUsedDirectory" ), QDir::homePath() ).toString();
QString fileName = QFileDialog::getOpenFileName( this, tr( "Import Bookmarks" ), lastUsedDir,
tr( "XML files (*.xml *.XML)" ) );
if ( fileName.isEmpty() )
{
return;
}
QFile f( fileName );
if ( !f.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
return;
}
QDomDocument doc;
if ( !doc.setContent( &f ) )
{
return;
}
f.close();
QDomElement docElem = doc.documentElement();
QDomNodeList nodeList = docElem.elementsByTagName( QStringLiteral( "bookmark" ) );
Q_ASSERT( mMergedModel );
QString queries;
for ( int i = 0; i < nodeList.count(); i++ )
{
QDomNode bookmark = nodeList.at( i );
QDomElement name = bookmark.firstChildElement( QStringLiteral( "name" ) );
QDomElement prjname = bookmark.firstChildElement( QStringLiteral( "project" ) );
QDomElement xmin = bookmark.firstChildElement( QStringLiteral( "xmin" ) );
QDomElement ymin = bookmark.firstChildElement( QStringLiteral( "ymin" ) );
QDomElement xmax = bookmark.firstChildElement( QStringLiteral( "xmax" ) );
QDomElement ymax = bookmark.firstChildElement( QStringLiteral( "ymax" ) );
QDomElement srid = bookmark.firstChildElement( QStringLiteral( "sr_id" ) );
queries += "INSERT INTO tbl_bookmarks(bookmark_id,name,project_name,xmin,ymin,xmax,ymax,projection_srid)"
" VALUES (NULL,"
"'" + name.text() + "',"
"'" + prjname.text() + "',"
+ xmin.text() + ','
+ ymin.text() + ','
+ xmax.text() + ','
+ ymax.text() + ','
+ srid.text() + ");";
}
QStringList queriesList = queries.split( ';' );
QSqlQuery query( mQgisModel->database() );
const auto constQueriesList = queriesList;
for ( const QString &queryTxt : constQueriesList )
{
if ( queryTxt.trimmed().isEmpty() )
{
continue;
}
if ( !query.exec( queryTxt ) )
{
QMessageBox::warning( this, tr( "Import Bookmarks" ), tr( "Unable to create the bookmark.\nDriver: %1\nDatabase: %2" )
.arg( query.lastError().driverText(),
query.lastError().databaseText() ) );
}
query.finish();
}
mQgisModel->setSort( 0, Qt::AscendingOrder );
mQgisModel->select();
mProxyModel->_resetModel();
}
QMap<QString, QModelIndex> QgsBookmarks::getIndexMap()
{
QMap<QString, QModelIndex> map;
int rowCount = mMergedModel->rowCount();
for ( int i = 0; i < rowCount; ++i )
{
QModelIndex idx = mMergedModel->index( i, 1 ); //Name col
if ( idx.isValid() )
{
QString name = idx.data( Qt::DisplayRole ).toString();
QString project = idx.sibling( idx.row(), 2 ).data().toString();
if ( !project.isEmpty() )
{
name = name + " (" + project + ")";
}
map.insert( name, idx ); //Duplicate name/project pairs are overwritten by subsequent bookmarks
}
}
return map;
}
void QgsBookmarks::exportToXml()
{
QgsSettings settings;
QString lastUsedDir = settings.value( QStringLiteral( "Windows/Bookmarks/LastUsedDirectory" ), QDir::homePath() ).toString();
QString fileName = QFileDialog::getSaveFileName( this, tr( "Export Bookmarks" ), lastUsedDir,
tr( "XML files (*.xml *.XML)" ) );
if ( fileName.isEmpty() )
{
return;
}
// ensure the user never omitted the extension from the file name
if ( !fileName.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) )
{
fileName += QLatin1String( ".xml" );
}
QDomDocument doc( QStringLiteral( "qgis_bookmarks" ) );
QDomElement root = doc.createElement( QStringLiteral( "qgis_bookmarks" ) );
doc.appendChild( root );
int rowCount = mMergedModel->rowCount();
int colCount = mMergedModel->columnCount() - 1; // exclude virtual "In project" column
QList<QString> headerList;
headerList
<< QStringLiteral( "id" )
<< QStringLiteral( "name" )
<< QStringLiteral( "project" )
<< QStringLiteral( "xmin" )
<< QStringLiteral( "ymin" )
<< QStringLiteral( "xmax" )
<< QStringLiteral( "ymax" )
<< QStringLiteral( "sr_id" );
for ( int i = 0; i < rowCount; ++i )
{
QDomElement bookmark = doc.createElement( QStringLiteral( "bookmark" ) );
root.appendChild( bookmark );
for ( int j = 0; j < colCount; j++ )
{
QModelIndex idx = mMergedModel->index( i, j );
if ( idx.isValid() )
{
QString value = idx.data( Qt::DisplayRole ).toString();
QString header = headerList.at( j );
// If it's the EPSG code, convert it to internal srid
if ( header == QStringLiteral( "sr_id" ) )
{
QgsCoordinateReferenceSystem crs;
if ( crs.createFromOgcWmsCrs( value ) )
value = QString::number( QgsCoordinateReferenceSystem::fromOgcWmsCrs( value ).srsid( ) );
else
value = QString();
}
QDomText idText = doc.createTextNode( value );
QDomElement id = doc.createElement( header );
id.appendChild( idText );
bookmark.appendChild( id );
}
}
}
QFile f( fileName );
if ( !f.open( QFile::WriteOnly | QIODevice::Truncate ) )
{
f.close();
return;
}
QTextStream out( &f );
out.setCodec( "UTF - 8" );
doc.save( out, 2 );
f.close();
settings.setValue( QStringLiteral( "Windows/Bookmarks/LastUsedDirectory" ), QFileInfo( fileName ).path() );
}
QgsProjectBookmarksTableModel::QgsProjectBookmarksTableModel( QObject *parent )
: QAbstractTableModel( parent )
{
connect(
QgisApp::instance(), &QgisApp::projectRead,
this, &QgsProjectBookmarksTableModel::projectRead );
connect(
QgisApp::instance(), &QgisApp::newProject,
this, &QgsProjectBookmarksTableModel::projectRead );
}
int QgsProjectBookmarksTableModel::rowCount( const QModelIndex &parent ) const
{
Q_UNUSED( parent );
return QgsProject::instance()->readNumEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/count" ) );
}
int QgsProjectBookmarksTableModel::columnCount( const QModelIndex &parent ) const
{
Q_UNUSED( parent );
return 8;
}
QVariant QgsProjectBookmarksTableModel::data( const QModelIndex &index, int role ) const
{
if ( role != Qt::DisplayRole && role != Qt::EditRole )
{
return QVariant();
}
switch ( index.column() )
{
case 1:
return QgsProject::instance()->readEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/Name" ).arg( index.row() ) );
case 2:
return QgsProject::instance()->readEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/Project" ).arg( index.row() ) );
case 3:
return QgsProject::instance()->readDoubleEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MinX" ).arg( index.row() ) );
case 4:
return QgsProject::instance()->readDoubleEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MinY" ).arg( index.row() ) );
case 5:
return QgsProject::instance()->readDoubleEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MaxX" ).arg( index.row() ) );
case 6:
return QgsProject::instance()->readDoubleEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MaxY" ).arg( index.row() ) );
case 7:
return QgsProject::instance()->readNumEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/SRID" ).arg( index.row() ) );
default:
return QVariant();
}
}
bool QgsProjectBookmarksTableModel::setData( const QModelIndex &index, const QVariant &value, int role )
{
Q_UNUSED( role );
Q_ASSERT( role == Qt::EditRole );
switch ( index.column() )
{
case 1:
QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/Name" ).arg( index.row() ), value.toString() );
return true;
case 2:
QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/Project" ).arg( index.row() ), value.toString() );
return true;
case 3:
QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MinX" ).arg( index.row() ), value.toDouble() );
return true;
case 4:
QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MinY" ).arg( index.row() ), value.toDouble() );
return true;
case 5:
QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MaxX" ).arg( index.row() ), value.toDouble() );
return true;
case 6:
QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MaxY" ).arg( index.row() ), value.toDouble() );
return true;
case 7:
QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/SRID" ).arg( index.row() ), value.toInt() );
return true;
default:
return false;
}
}
bool QgsProjectBookmarksTableModel::insertRows( int row, int count, const QModelIndex &parent )
{
Q_UNUSED( parent );
Q_UNUSED( row );
// append
int oldCount = QgsProject::instance()->readNumEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/count" ) );
beginInsertRows( parent, oldCount, oldCount + count );
bool result = QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/count" ), oldCount + count );
endInsertRows();
return result;
}
bool QgsProjectBookmarksTableModel::removeRows( int row, int count, const QModelIndex &parent )
{
Q_UNUSED( parent );
beginRemoveRows( parent, row, row + count );
for ( int newRow = row ; newRow < rowCount() - count ; newRow++ )
{
for ( int column = 0; column < columnCount() ; column++ )
{
setData( index( newRow, column ), data( index( newRow + count, column ) ) );
}
}
for ( int newRow = rowCount() - count ; newRow < rowCount() ; newRow++ )
{
QgsProject::instance()->removeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1" ).arg( newRow ) );
}
QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/count" ), QgsProject::instance()->readNumEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/count" ) ) - count );
endRemoveRows();
return true;
}
void QgsProjectBookmarksTableModel::projectRead()
{
emit layoutChanged();
}
QgsMergedBookmarksTableModel::QgsMergedBookmarksTableModel( QAbstractTableModel &qgisTableModel, QAbstractTableModel &projectTableModel, QTreeView *treeView, QObject *parent )
: QAbstractTableModel( parent )
, mQgisTableModel( qgisTableModel )
, mProjectTableModel( projectTableModel )
, mTreeView( treeView )
{
connect(
&mQgisTableModel, &QAbstractTableModel::layoutChanged,
this, &QgsMergedBookmarksTableModel::allLayoutChanged );
connect(
&mQgisTableModel, &QAbstractTableModel::rowsInserted,
this, &QgsMergedBookmarksTableModel::allLayoutChanged );
connect(
&mQgisTableModel, &QAbstractTableModel::rowsRemoved,
this, &QgsMergedBookmarksTableModel::allLayoutChanged );
connect(
&projectTableModel, &QAbstractTableModel::layoutChanged,
this, &QgsMergedBookmarksTableModel::allLayoutChanged );
connect(
&projectTableModel, &QAbstractTableModel::rowsInserted,
this, &QgsMergedBookmarksTableModel::allLayoutChanged );
connect(
&projectTableModel, &QAbstractTableModel::rowsRemoved,
this, &QgsMergedBookmarksTableModel::allLayoutChanged );
}
int QgsMergedBookmarksTableModel::rowCount( const QModelIndex &parent ) const
{
return mQgisTableModel.rowCount( parent ) + mProjectTableModel.rowCount( parent );
}
int QgsMergedBookmarksTableModel::columnCount( const QModelIndex &parent ) const
{
return mQgisTableModel.columnCount( parent ) + 1;
}
QVariant QgsMergedBookmarksTableModel::data( const QModelIndex &index, int role ) const
{
QVariant value;
// Is it checkbox column?
if ( index.column() == mQgisTableModel.columnCount() && role == Qt::CheckStateRole )
{
value = index.row() < mQgisTableModel.rowCount() ? Qt::Unchecked : Qt::Checked;
}
else
{
// Is it a SQLite stored entry ?
if ( index.row() < mQgisTableModel.rowCount() )
{
value = mQgisTableModel.data( index, role );
}
else // ... it is a project stored bookmark
{
if ( role == Qt::DisplayRole || role == Qt::EditRole )
{
value = mProjectTableModel.data( this->index( index.row() - mQgisTableModel.rowCount(), index.column() ), role );
}
else // Default roles from base model
{
value = mQgisTableModel.data( this->index( 0, index.column() ), role );
}
}
// Is it the projection column ?
if ( ( role == Qt::DisplayRole || role == Qt::EditRole ) && index.column( ) == mQgisTableModel.columnCount() - 1 )
{
value = QgsCoordinateReferenceSystem::fromSrsId( value.toInt( ) ).authid( );
}
}
return value;
}
bool QgsMergedBookmarksTableModel::setData( const QModelIndex &index, const QVariant &value, int role )
{
bool result = false;
// last column triggers a move from QGIS to project bookmark
if ( index.column() == mQgisTableModel.columnCount() )
{
if ( index.row() < mQgisTableModel.rowCount() )
{
// Move from SQLite storage to project
moveBookmark( mQgisTableModel, mProjectTableModel, index.row() );
emit selectItem( this->index( rowCount() - 1, 1 ) );
}
else
{
//Move from project to SQLite storage
moveBookmark( mProjectTableModel, mQgisTableModel, index.row() - mQgisTableModel.rowCount() );
emit selectItem( this->index( mQgisTableModel.rowCount() - 1, 1 ) );
}
result = true;
}
else
{
if ( index.row() < mQgisTableModel.rowCount() )
{
result = mQgisTableModel.setData( index, value, role );
}
else
{
result = mProjectTableModel.setData( this->index( index.row() - mQgisTableModel.rowCount(), index.column() ), value, role );
}
}
if ( result )
emit dataChanged( index, index );
return result;
}
Qt::ItemFlags QgsMergedBookmarksTableModel::flags( const QModelIndex &index ) const
{
Qt::ItemFlags flags = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
if ( index.column() == mQgisTableModel.columnCount() )
{
if ( !projectAvailable() )
{
return Qt::ItemIsSelectable;
}
flags |= Qt::ItemIsUserCheckable;
}
else
{
// Skip projection: not editable!
if ( index.column() != mQgisTableModel.columnCount() - 1 )
flags |= Qt::ItemIsEditable;
}
return flags;
}
bool QgsMergedBookmarksTableModel::removeRows( int row, int count, const QModelIndex &parent )
{
Q_ASSERT( count == 1 );
bool result;
if ( row < mQgisTableModel.rowCount() )
{
QSqlTableModel *qgisModel = static_cast<QSqlTableModel *>( &mQgisTableModel );
Q_ASSERT( qgisModel );
result = qgisModel->removeRows( row, count, parent );
qgisModel->select(); // This updates row count in the model!
}
else
{
result = mProjectTableModel.removeRows( row - mQgisTableModel.rowCount(), count, parent );
}
allLayoutChanged();
return result;
}
QVariant QgsMergedBookmarksTableModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if ( section == mQgisTableModel.columnCount() )
{
if ( role == Qt::DisplayRole )
{
return QVariant( tr( "In Project" ) );
}
else
{
return mQgisTableModel.headerData( 0, orientation, role );
}
}
else
{
return mQgisTableModel.headerData( section, orientation, role );
}
}
QAbstractTableModel *QgsMergedBookmarksTableModel::qgisModel()
{
return &mQgisTableModel;
}
bool QgsMergedBookmarksTableModel::projectAvailable() const
{
return ! QgsProject::instance()->fileName().isEmpty();
}
void QgsMergedBookmarksTableModel::moveBookmark( QAbstractTableModel &modelFrom, QAbstractTableModel &modelTo, int row )
{
beginResetModel();
QSqlTableModel *qgisModel = dynamic_cast<QSqlTableModel *>( &modelTo );
if ( !qgisModel )
{
modelTo.insertRow( -1 );
for ( int column = 1 ; column < modelFrom.columnCount() ; column++ )
{
Q_ASSERT( modelTo.index( modelTo.rowCount() - 1, column ).isValid( ) );
modelTo.setData(
modelTo.index( modelTo.rowCount() - 1, column ),
modelFrom.data( modelFrom.index( row, column ) ) );
}
qgisModel = dynamic_cast<QSqlTableModel *>( &modelFrom );
Q_ASSERT( qgisModel );
qgisModel->removeRows( row, 1 );
qgisModel->select();
}
else
{
QSqlRecord record = qgisModel->record();
record.setValue( 1, modelFrom.data( modelFrom.index( row, 1 ) ).toString() );
record.setValue( 2, modelFrom.data( modelFrom.index( row, 2 ) ).toString() );
record.setValue( 3, modelFrom.data( modelFrom.index( row, 3 ) ).toDouble() );
record.setValue( 4, modelFrom.data( modelFrom.index( row, 4 ) ).toDouble() );
record.setValue( 5, modelFrom.data( modelFrom.index( row, 5 ) ).toDouble() );
record.setValue( 6, modelFrom.data( modelFrom.index( row, 6 ) ).toDouble() );
record.setValue( 7, modelFrom.data( modelFrom.index( row, 7 ) ).toInt() );
if ( ! qgisModel->insertRecord( -1, record ) )
{
QgsDebugMsg( QStringLiteral( "Could not move bookmark: %1" )
.arg( qgisModel->database().lastError().text() ) );
return;
}
qgisModel->setSort( 0, Qt::AscendingOrder );
qgisModel->select();
modelFrom.removeRows( row, 1 );
}
endResetModel();
emit layoutChanged();
}
QgsBookmarksProxyModel::QgsBookmarksProxyModel( QObject *parent ):
QSortFilterProxyModel( parent )
{
}
QVariant QgsBookmarksProxyModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
return sourceModel()->headerData( section, orientation, role );
}
QgsDoubleSpinBoxBookmarksDelegate::QgsDoubleSpinBoxBookmarksDelegate( QObject *parent )
: QStyledItemDelegate( parent )
{
}
QString QgsDoubleSpinBoxBookmarksDelegate::displayText( const QVariant &value, const QLocale &locale ) const
{
if ( value.userType() == QVariant::Double )
{
return locale.toString( value.toDouble(), 'f', QgsDoubleSpinBoxBookmarksDelegate::DECIMAL_PLACES );
}
else
{
return QStyledItemDelegate::displayText( value, locale );
}
}
QWidget *QgsDoubleSpinBoxBookmarksDelegate::createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
QWidget *widget = QStyledItemDelegate::createEditor( parent, option, index );
QDoubleSpinBox *spinbox = qobject_cast<QDoubleSpinBox *>( widget );
if ( spinbox )
spinbox->setDecimals( QgsDoubleSpinBoxBookmarksDelegate::DECIMAL_PLACES );
return widget;
}
| 34.790226 | 205 | 0.652232 | dyna-mis |
83e893e9f021dbd7327ca9ac7bed37ba91434a57 | 7,862 | cpp | C++ | kbar.cpp | ridgeware/dekaf2 | b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33 | [
"MIT"
] | null | null | null | kbar.cpp | ridgeware/dekaf2 | b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33 | [
"MIT"
] | null | null | null | kbar.cpp | ridgeware/dekaf2 | b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33 | [
"MIT"
] | 1 | 2021-08-20T16:15:01.000Z | 2021-08-20T16:15:01.000Z | //
// DEKAF(tm): Lighter, Faster, Smarter(tm)
//
// Copyright (c) 2000-2003, Ridgeware, Inc.
//
// +-------------------------------------------------------------------------+
// | /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\|
// |/+---------------------------------------------------------------------+/|
// |/| |/|
// |\| ** THIS NOTICE MUST NOT BE REMOVED FROM THE SOURCE CODE MODULE ** |\|
// |/| |/|
// |\| OPEN SOURCE LICENSE |\|
// |/| |/|
// |\| Permission is hereby granted, free of charge, to any person |\|
// |/| obtaining a copy of this software and associated |/|
// |\| documentation files (the "Software"), to deal in the |\|
// |/| Software without restriction, including without limitation |/|
// |\| the rights to use, copy, modify, merge, publish, |\|
// |/| distribute, sublicense, and/or sell copies of the Software, |/|
// |\| and to permit persons to whom the Software is furnished to |\|
// |/| do so, subject to the following conditions: |/|
// |\| |\|
// |/| The above copyright notice and this permission notice shall |/|
// |\| be included in all copies or substantial portions of the |\|
// |/| Software. |/|
// |\| |\|
// |/| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY |/|
// |\| KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE |\|
// |/| WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR |/|
// |\| PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS |\|
// |/| OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR |/|
// |\| OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR |\|
// |/| OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |/|
// |\| SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |\|
// |/| |/|
// |/+---------------------------------------------------------------------+/|
// |\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ |
// +-------------------------------------------------------------------------+
//
#include "kstring.h"
#include "kbar.h"
#include "kwriter.h"
#include "klog.h"
namespace dekaf2 {
//-----------------------------------------------------------------------------
KBAR::KBAR (uint64_t iExpected/*=0*/, uint32_t iWidth/*=DEFAULT_WIDTH*/, uint64_t iFlags/*=SLIDER*/, int chDone/*='%'*/, KOutStream& Out/*=KOut*/)
//-----------------------------------------------------------------------------
: m_iFlags(iFlags)
, m_iWidth(iWidth)
, m_iExpected(iExpected)
, m_iSoFar(0)
, m_chDone(chDone)
, m_Out(Out)
, m_bSliding(false)
{
if (m_iExpected && (m_iFlags & SLIDER))
{
_SliderAction (KPS_START, 0, 0);
m_bSliding = true;
}
} // constructor
//-----------------------------------------------------------------------------
KBAR::~KBAR()
//-----------------------------------------------------------------------------
{
Finish();
}
//-----------------------------------------------------------------------------
bool KBAR::Start (uint64_t iExpected)
//-----------------------------------------------------------------------------
{
m_iExpected = iExpected;
if (m_iExpected && (m_iFlags & SLIDER))
{
m_iSoFar = 0;
_SliderAction (KPS_START, 0, 0);
m_bSliding = true;
}
return (true);
} // Start
//-----------------------------------------------------------------------------
bool KBAR::Adjust (uint64_t iExpected)
//-----------------------------------------------------------------------------
{
if (iExpected > m_iSoFar)
{
m_iExpected = iExpected;
return (true);
}
else
{
return (false);
}
} // Adjust
//-----------------------------------------------------------------------------
bool KBAR::Move (int64_t iDelta)
//-----------------------------------------------------------------------------
{
uint64_t iWant = m_iSoFar + iDelta;
bool fOK = true;
if (iWant > m_iExpected)
{
iWant = m_iExpected;
fOK = false;
}
if ((iWant < m_iSoFar) && (m_iFlags & SLIDER))
{
iWant = m_iSoFar; // cannot go backwards
fOK = false;
}
iDelta = iWant - m_iSoFar;
if (m_bSliding)
{
if (KLog::getInstance().GetLevel())
{
kDebugLog (1, "kbar: {:3}%, {} of {}", ((m_iSoFar+iDelta))*100/m_iExpected, m_iSoFar+iDelta, m_iExpected);
}
else {
_SliderAction (KPS_ADD, m_iSoFar, m_iSoFar+iDelta);
}
}
m_iSoFar += iDelta;
return (fOK);
} // Move
//-----------------------------------------------------------------------------
KString KBAR::GetBar (int chBlank/*=' '*/)
//-----------------------------------------------------------------------------
{
KString sBar;
if (!m_iExpected)
{
return sBar;
}
double nPercentNow = ((double)m_iSoFar / (double)m_iExpected);
if (nPercentNow > 100.0)
{
nPercentNow = 100.0;
}
uint32_t iNumBarsNow = (int) (nPercentNow * (double)(m_iWidth));
kDebug (1, "{} out of {}, {}%, {} out of {} bars", m_iSoFar, m_iExpected, nPercentNow, iNumBarsNow, m_iWidth);
for (uint32_t ii=1; ii<=m_iWidth; ++ii)
{
if (ii <= iNumBarsNow)
{
sBar += m_chDone;
}
else
{
sBar += chBlank;
}
}
return (sBar);
} // GetBar
//-----------------------------------------------------------------------------
void KBAR::RepaintSlider ()
//-----------------------------------------------------------------------------
{
if (m_iFlags & SLIDER)
{
_SliderAction (KPS_START, 0, 0);
_SliderAction (KPS_ADD, 0, m_iSoFar);
}
} // RepaintSlider
//-----------------------------------------------------------------------------
void KBAR::Finish ()
//-----------------------------------------------------------------------------
{
if (m_bSliding)
{
_SliderAction (KPS_END, m_iSoFar, m_iExpected);
m_bSliding = false;
}
m_iExpected = m_iSoFar;
} // Finish
//-----------------------------------------------------------------------------
void KBAR::Break (KStringView sMsg/*="!!!"*/)
//-----------------------------------------------------------------------------
{
if (m_bSliding)
{
m_Out.WriteLine (sMsg);
m_bSliding = false;
}
} // Break
//-----------------------------------------------------------------------------
void KBAR::_SliderAction (int iAction, uint64_t iSoFarLast, uint64_t iSoFarNow)
//-----------------------------------------------------------------------------
{
if (KLog::getInstance().GetLevel()) // progress bar only makes sense when NOT klogging
{
return;
}
double nPercentLast = ((double)iSoFarLast / (double)m_iExpected);
if (nPercentLast > 100.0)
{
nPercentLast = 100.0;
}
double nPercentNow = ((double)iSoFarNow / (double)m_iExpected);
if (nPercentNow > 100.0)
{
nPercentNow = 100.0;
}
uint32_t iNumBarsLast = (int) (nPercentLast * (double)(m_iWidth));
uint32_t iNumBarsNow = (int) (nPercentNow * (double)(m_iWidth));
uint32_t ii;
switch (iAction)
{
case KPS_START:
m_Out.Write('v');
for (ii=0; ii<m_iWidth; ++ii)
{
m_Out.Write('_');
}
m_Out.Write("v\n|");
break;
case KPS_ADD:
for (ii=iNumBarsLast; ii<iNumBarsNow; ++ii)
{
m_Out.Write(m_chDone);
}
break;
case KPS_END:
for (ii=iNumBarsLast; ii<m_iWidth; ++ii)
{
m_Out.Write(' ');
}
m_Out.Write("|\n");
}
m_Out.Flush();
} // _SliderAction
} // of namespace dekaf2
| 28.078571 | 146 | 0.407148 | ridgeware |
83e9e5ea9685835e4e4eda625d867263e125b035 | 7,332 | cpp | C++ | src/libraries/core/meshTools/coordinateSystems/coordinateRotation/localAxesRotation.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/core/meshTools/coordinateSystems/coordinateRotation/localAxesRotation.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/core/meshTools/coordinateSystems/coordinateRotation/localAxesRotation.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011-2015 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "localAxesRotation.hpp"
#include "axesRotation.hpp"
#include "addToRunTimeSelectionTable.hpp"
#include "polyMesh.hpp"
#include "tensorIOField.hpp"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace CML
{
defineTypeNameAndDebug(localAxesRotation, 0);
addToRunTimeSelectionTable
(
coordinateRotation,
localAxesRotation,
dictionary
);
addToRunTimeSelectionTable
(
coordinateRotation,
localAxesRotation,
objectRegistry
);
}
// * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * * //
void CML::localAxesRotation::init
(
const objectRegistry& obr,
const List<label>& cells
)
{
const polyMesh& mesh = refCast<const polyMesh>(obr);
const vectorField& cc = mesh.cellCentres();
if (cells.size())
{
Rptr_.reset(new tensorField(cells.size()));
tensorField& R = Rptr_();
forAll(cells, i)
{
label cellI = cells[i];
vector dir = cc[cellI] - origin_;
dir /= mag(dir) + VSMALL;
R[i] = axesRotation(e3_, dir).R();
}
}
else
{
Rptr_.reset(new tensorField(mesh.nCells()));
tensorField& R = Rptr_();
forAll(cc, cellI)
{
vector dir = cc[cellI] - origin_;
dir /= mag(dir) + VSMALL;
R[cellI] = axesRotation(e3_, dir).R();
}
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
CML::localAxesRotation::localAxesRotation
(
const dictionary& dict,
const objectRegistry& obr
)
:
Rptr_(),
origin_(point::zero),
e3_(vector::zero)
{
// If origin is specified in the coordinateSystem
if (dict.parent().found("origin"))
{
dict.parent().lookup("origin") >> origin_;
}
// rotation axis
dict.lookup("e3") >> e3_;
init(obr);
}
CML::localAxesRotation::localAxesRotation
(
const objectRegistry& obr,
const vector& axis,
const point& origin
)
:
Rptr_(),
origin_(origin),
e3_(axis)
{
init(obr);
}
CML::localAxesRotation::localAxesRotation
(
const objectRegistry& obr,
const vector& axis,
const point& origin,
const List<label>& cells
)
:
Rptr_(),
origin_(origin),
e3_(axis)
{
init(obr, cells);
}
CML::localAxesRotation::localAxesRotation(const dictionary& dict)
:
Rptr_(),
origin_(),
e3_()
{
FatalErrorInFunction
<< " localAxesRotation can not be constructed from dictionary "
<< " use the construtctor : "
"("
" const dictionary&, const objectRegistry&"
")"
<< exit(FatalIOError);
}
CML::localAxesRotation::localAxesRotation(const tensorField& R)
:
Rptr_(),
origin_(vector::zero),
e3_(vector::zero)
{
Rptr_() = R;
}
// * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * * //
void CML::localAxesRotation::clear()
{
if (!Rptr_.empty())
{
Rptr_.clear();
}
}
void CML::localAxesRotation::updateCells
(
const polyMesh& mesh,
const labelList& cells
)
{
const vectorField& cc = mesh.cellCentres();
tensorField& R = Rptr_();
forAll(cells, i)
{
label cellI = cells[i];
vector dir = cc[cellI] - origin_;
dir /= mag(dir) + VSMALL;
R[cellI] = axesRotation(e3_, dir).R();
}
}
CML::tmp<CML::vectorField> CML::localAxesRotation::transform
(
const vectorField& vf
) const
{
if (Rptr_->size() != vf.size())
{
FatalErrorInFunction
<< "vectorField st has different size to tensorField "
<< abort(FatalError);
}
return (Rptr_() & vf);
}
CML::vector CML::localAxesRotation::transform(const vector& v) const
{
NotImplemented;
return vector::zero;
}
CML::vector CML::localAxesRotation::transform
(
const vector& v,
const label cmptI
) const
{
return (Rptr_()[cmptI] & v);
}
CML::tmp<CML::vectorField> CML::localAxesRotation::invTransform
(
const vectorField& vf
) const
{
return (Rptr_().T() & vf);
}
CML::vector CML::localAxesRotation::invTransform(const vector& v) const
{
NotImplemented;
return vector::zero;
}
CML::vector CML::localAxesRotation::invTransform
(
const vector& v,
const label cmptI
) const
{
return (Rptr_()[cmptI].T() & v);
}
CML::tmp<CML::tensorField> CML::localAxesRotation::transformTensor
(
const tensorField& tf
) const
{
if (Rptr_->size() != tf.size())
{
FatalErrorInFunction
<< "tensorField st has different size to tensorField Tr"
<< abort(FatalError);
}
return (Rptr_() & tf & Rptr_().T());
}
CML::tensor CML::localAxesRotation::transformTensor
(
const tensor& t
) const
{
NotImplemented;
return tensor::zero;
}
CML::tmp<CML::tensorField> CML::localAxesRotation::transformTensor
(
const tensorField& tf,
const labelList& cellMap
) const
{
if (cellMap.size() != tf.size())
{
FatalErrorInFunction
<< "tensorField tf has different size to tensorField Tr"
<< abort(FatalError);
}
const tensorField& R = Rptr_();
const tensorField Rtr(R.T());
tmp<tensorField> tt(new tensorField(cellMap.size()));
tensorField& t = tt();
forAll(cellMap, i)
{
const label cellI = cellMap[i];
t[i] = R[cellI] & tf[i] & Rtr[cellI];
}
return tt;
}
CML::tmp<CML::symmTensorField> CML::localAxesRotation::transformVector
(
const vectorField& vf
) const
{
if (Rptr_->size() != vf.size())
{
FatalErrorInFunction
<< "tensorField vf has different size to tensorField Tr"
<< abort(FatalError);
}
tmp<symmTensorField> tfld(new symmTensorField(Rptr_->size()));
symmTensorField& fld = tfld();
const tensorField& R = Rptr_();
forAll(fld, i)
{
fld[i] = transformPrincipal(R[i], vf[i]);
}
return tfld;
}
CML::symmTensor CML::localAxesRotation::transformVector
(
const vector& v
) const
{
NotImplemented;
return symmTensor::zero;
}
void CML::localAxesRotation::write(Ostream& os) const
{
os.writeKeyword("e3") << e3() << token::END_STATEMENT << nl;
}
// ************************************************************************* //
| 20.653521 | 79 | 0.570104 | MrAwesomeRocks |
83ea2428af336f95fb2326f096ec03a630611643 | 5,743 | cpp | C++ | src/programs/advection.cpp | pedrospeixoto/sweet | 224248181e92615467c94b4e163596017811b5eb | [
"MIT"
] | null | null | null | src/programs/advection.cpp | pedrospeixoto/sweet | 224248181e92615467c94b4e163596017811b5eb | [
"MIT"
] | null | null | null | src/programs/advection.cpp | pedrospeixoto/sweet | 224248181e92615467c94b4e163596017811b5eb | [
"MIT"
] | 1 | 2019-03-27T01:17:59.000Z | 2019-03-27T01:17:59.000Z |
#include <sweet/DataArray.hpp>
#if SWEET_GUI
#include "sweet/VisSweet.hpp"
#endif
#include <sweet/SimulationVariables.hpp>
#include "sweet/Operators2D.hpp"
#include <unistd.h>
#include <stdio.h>
SimulationVariables simVars;
class SimulationSWE
{
public:
DataArray<2> h;
DataArray<2> u;
DataArray<2> v;
DataArray<2> hu;
DataArray<2> hv;
DataArray<2> h_t;
Operators2D op;
public:
SimulationSWE() :
h(simVars.disc.res),
u(simVars.disc.res),
v(simVars.disc.res),
hu(simVars.disc.res),
hv(simVars.disc.res),
h_t(simVars.disc.res),
op(simVars.disc.res, simVars.sim.domain_size, simVars.disc.use_spectral_basis_diffs)
{
reset();
}
void reset()
{
simVars.timecontrol.current_timestep_nr = 0;
h.set_all(simVars.setup.h0);
if (std::isinf(simVars.bogus.var[0]))
{
u.set_all(0);
v.set_all(0);
}
else
{
u.set_all(simVars.bogus.var[0]);
v.set_all(simVars.bogus.var[1]);
}
double center_x = 0.7;
double center_y = 0.6;
if (simVars.setup.scenario == 0)
{
/*
* radial dam break
*/
double radius = 0.2;
for (std::size_t j = 0; j < simVars.disc.res[1]; j++)
{
for (std::size_t i = 0; i < simVars.disc.res[0]; i++)
{
double x = ((double)i+0.5)/(double)simVars.disc.res[0];
double y = ((double)j+0.5)/(double)simVars.disc.res[1];
double dx = x-center_x;
double dy = y-center_y;
if (radius*radius >= dx*dx+dy*dy)
h.set(j,i, simVars.setup.h0+1.0);
}
}
}
if (simVars.setup.scenario == 1)
{
/*
* fun with Gaussian
*/
for (std::size_t j = 0; j < simVars.disc.res[1]; j++)
{
for (std::size_t i = 0; i < simVars.disc.res[0]; i++)
{
double x = ((double)i+0.5)/(double)simVars.disc.res[0];
double y = ((double)j+0.5)/(double)simVars.disc.res[1];
double dx = x-center_x;
double dy = y-center_y;
h.set(j,i, simVars.setup.h0+std::exp(-50.0*(dx*dx + dy*dy)));
}
}
}
}
void run_timestep()
{
double dt = simVars.sim.CFL*std::min(simVars.disc.cell_size[0]/u.reduce_maxAbs(), simVars.disc.cell_size[1]/v.reduce_maxAbs());
if (std::isinf(dt))
dt = simVars.sim.CFL*simVars.disc.cell_size[0]/0.000001;
simVars.timecontrol.current_timestep_size = dt;
// 0: staggered
// 1: non-staggered
// 2: up/downwinding
#define GRID_LAYOUT_AND_ADVECTION 2
#if ADVECTION_METHOD == 0
// staggered
h -= dt*(
op.diff_b_x(op.avg_f_x(h)*u) +
op.diff_b_y(op.avg_f_y(h)*v)
);
#endif
#if ADVECTION_METHOD == 1
// non-staggered
h = h - dt*(
op.diff_c_x(h*u) +
op.diff_c_y(h*v)
);
#endif
#if ADVECTION_METHOD == 2
h += dt*
(
(
// u is positive
op.shift_right(h)*u.return_value_if_positive() // inflow
-h*op.shift_left(u.return_value_if_positive()) // outflow
// u is negative
+(h*u.return_value_if_negative()) // outflow
-op.shift_left(h*u.return_value_if_negative()) // inflow
)*(1.0/simVars.disc.cell_size[0]) // here we see a finite-difference-like formulation
+
(
// v is positive
op.shift_up(h)*v.return_value_if_positive() // inflow
-h*op.shift_down(v.return_value_if_positive()) // outflow
// v is negative
+(h*v.return_value_if_negative()) // outflow
-op.shift_down(h*v.return_value_if_negative()) // inflow
)*(1.0/simVars.disc.cell_size[1])
);
#endif
simVars.timecontrol.current_timestep_nr++;
}
bool should_quit()
{
return false;
}
/**
* postprocessing of frame: do time stepping
*/
void vis_post_frame_processing(int i_num_iterations)
{
if (simVars.timecontrol.run_simulation_timesteps)
for (int i = 0; i < i_num_iterations; i++)
run_timestep();
}
void vis_get_vis_data_array(
const DataArray<2> **o_dataArray,
double *o_aspect_ratio
)
{
switch (simVars.misc.vis_id)
{
case 0:
*o_dataArray = &h;
break;
case 1:
*o_dataArray = &u;
break;
case 2:
*o_dataArray = &v;
break;
}
*o_aspect_ratio = simVars.sim.domain_size[1] / simVars.sim.domain_size[0];
}
const char* vis_get_status_string()
{
static char title_string[1024];
sprintf(title_string, "Timestep: %i, timestep size: %e", simVars.timecontrol.current_timestep_nr, simVars.timecontrol.current_timestep_size);
return title_string;
}
void vis_pause()
{
simVars.timecontrol.run_simulation_timesteps = !simVars.timecontrol.run_simulation_timesteps;
}
void vis_keypress(int i_key)
{
switch(i_key)
{
case 'v':
simVars.misc.vis_id++;
break;
case 'V':
simVars.misc.vis_id--;
break;
}
}
};
int main(int i_argc, char *i_argv[])
{
const char *bogus_var_names[] = {
"velocity-u",
"velocity-v",
nullptr
};
if (!simVars.setupFromMainParameters(i_argc, i_argv, bogus_var_names))
{
std::cout << std::endl;
std::cout << "Program-specific options:" << std::endl;
std::cout << " --velocity-u [advection velocity u]" << std::endl;
std::cout << " --velocity-v [advection velocity v]" << std::endl;
return -1;
}
if (std::isinf(simVars.bogus.var[0]) || std::isinf(simVars.bogus.var[1]))
{
std::cout << "Both velocities have to be set, see parameters --velocity-u, --velocity-v" << std::endl;
return -1;
}
SimulationSWE *simulationSWE = new SimulationSWE;
#if SWEET_GUI
VisSweet<SimulationSWE> visSweet(simulationSWE);
#else
simulationSWE->reset();
while (!simulationSWE->should_quit())
{
simulationSWE->run_timestep();
if (simVars.misc.verbosity > 2)
std::cout << simVars.timecontrol.current_simulation_time << std::endl;
if (simVars.timecontrol.current_simulation_time > simVars.timecontrol.max_simulation_time)
break;
}
#endif
delete simulationSWE;
return 0;
}
| 19.940972 | 143 | 0.640432 | pedrospeixoto |
83ec4d6f63c2476238bc4eb8701c2d307a2ee4c5 | 46,974 | cpp | C++ | DESIRE-Modules/Script-AngelScript/src/API/CoreAPI_Math_AngelScript.cpp | nyaki-HUN/DESIRE | dd579bffa77bc6999266c8011bc389bb96dee01d | [
"BSD-2-Clause"
] | 1 | 2020-10-04T18:50:01.000Z | 2020-10-04T18:50:01.000Z | DESIRE-Modules/Script-AngelScript/src/API/CoreAPI_Math_AngelScript.cpp | nyaki-HUN/DESIRE | dd579bffa77bc6999266c8011bc389bb96dee01d | [
"BSD-2-Clause"
] | null | null | null | DESIRE-Modules/Script-AngelScript/src/API/CoreAPI_Math_AngelScript.cpp | nyaki-HUN/DESIRE | dd579bffa77bc6999266c8011bc389bb96dee01d | [
"BSD-2-Clause"
] | 1 | 2018-09-18T08:03:33.000Z | 2018-09-18T08:03:33.000Z | #include "stdafx_AngelScript.h"
#include "API/AngelScriptAPI.h"
#include "Engine/Core/Math/Math.h"
#include "Engine/Core/Math/Matrix4.h"
#include "Engine/Core/Math/Rand.h"
#include "Engine/Core/Math/Transform.h"
static Vector3* Vector3_Cross(const Vector3& vec0, const Vector3& vec1) { return new Vector3(vec0.Cross(vec1)); }
static Vector3* Transform_GetPosition(const Transform& transform) { return new Vector3(transform.GetPosition()); }
static Quat* Transform_GetRotation(const Transform& transform) { return new Quat(transform.GetRotation()); }
static Vector3* Transform_GetScale(const Transform& transform) { return new Vector3(transform.GetScale()); }
void RegisterCoreAPI_Math_AngelScript(asIScriptEngine& engine)
{
int32_t result = asSUCCESS;
// Vector3
result = engine.RegisterObjectType("Vector3", 0, asOBJ_REF | asOBJ_SCOPED); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Vector3", asBEHAVE_RELEASE, "void f()", asFUNCTION(AngelScriptAPI<Vector3>::Release), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Vector3", asBEHAVE_FACTORY, "Vector3@ f()", asFUNCTION(AngelScriptAPI<Vector3>::Factory), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Vector3", asBEHAVE_FACTORY, "Vector3@ f(const Vector3& in)", asFUNCTION(AngelScriptAPI<Vector3>::FactoryWithArgs<const Vector3&>), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Vector3", asBEHAVE_FACTORY, "Vector3@ f(float, float, float)", asFUNCTION((AngelScriptAPI<Vector3>::FactoryWithArgs<float, float, float>)), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "void SetX(float)", asMETHOD(Vector3, SetX), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "void SetY(float)", asMETHOD(Vector3, SetY), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "void SetZ(float)", asMETHOD(Vector3, SetZ), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "float GetX() const", asMETHOD(Vector3, GetX), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "float GetY() const", asMETHOD(Vector3, GetY), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "float GetZ() const", asMETHOD(Vector3, GetZ), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "void opAssign(const Vector3& in)", asFUNCTION(AngelScriptAPI<Vector3>::OpAssign<Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "Vector3@ opNeg()", asFUNCTION(AngelScriptAPI<Vector3>::OpNeg), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "Vector3@ opAdd(const Vector3& in) const", asFUNCTION(AngelScriptAPI<Vector3>::OpAdd<const Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "Vector3@ opSub(const Vector3& in) const", asFUNCTION(AngelScriptAPI<Vector3>::OpSub<const Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "Vector3@ opMul(const Vector3& in) const", asFUNCTION(AngelScriptAPI<Vector3>::OpMul<const Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "Vector3@ opMul(float) const", asFUNCTION(AngelScriptAPI<Vector3>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "Vector3@ opMul_r(float) const", asFUNCTION(AngelScriptAPI<Vector3>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "Vector3@ opDiv(const Vector3& in) const", asFUNCTION(AngelScriptAPI<Vector3>::OpDiv<const Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "Vector3@ opDiv(float) const", asFUNCTION(AngelScriptAPI<Vector3>::OpDiv<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "void opAddAssign(const Vector3& in)", asFUNCTION(AngelScriptAPI<Vector3>::OpAddAssign<const Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "void subAssign(const Vector3& in)", asFUNCTION(AngelScriptAPI<Vector3>::OpSubAssign<const Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "void opMulAssign(float)", asFUNCTION(AngelScriptAPI<Vector3>::OpMulAssign<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "void opDivAssign(float)", asFUNCTION(AngelScriptAPI<Vector3>::OpDivAssign<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "float Dot(const Vector3& in) const", asMETHOD(Vector3, Dot), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "Vector3@ Cross(const Vector3& in) const", asFUNCTION(Vector3_Cross), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "float LengthSqr() const", asMETHOD(Vector3, LengthSqr), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "float Length() const", asMETHOD(Vector3, Length), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "void Normalize()", asMETHOD(Vector3, Normalize), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
// result = engine.RegisterObjectMethod("Vector3", "Vector3@ Normalized() const", asMETHOD(Vector3, Normalized), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
// Vector3 Abs() const; ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "float GetMaxElement() const", asMETHOD(Vector3, GetMaxElement), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector3", "float GetMinElement() const", asMETHOD(Vector3, GetMinElement), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.SetDefaultNamespace("Vector3"); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector3@ Max(const Vector3& in, const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Vector3>::StaticFunc<const Vector3&, const Vector3&, &Vector3::Max>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector3@ Min(const Vector3& in, const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Vector3>::StaticFunc<const Vector3&, const Vector3&, &Vector3::Min>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector3@ Zero()", asFUNCTION(AngelScriptGenericAPI<Vector3>::StaticFunc<&Vector3::Zero>), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector3@ One()", asFUNCTION(AngelScriptGenericAPI<Vector3>::StaticFunc<&Vector3::One>), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector3@ AxisX()", asFUNCTION(AngelScriptGenericAPI<Vector3>::StaticFunc<&Vector3::AxisX>), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector3@ AxisY()", asFUNCTION(AngelScriptGenericAPI<Vector3>::StaticFunc<&Vector3::AxisY>), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector3@ AxisZ()", asFUNCTION(AngelScriptGenericAPI<Vector3>::StaticFunc<&Vector3::AxisZ>), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.SetDefaultNamespace(""); ASSERT(result >= asSUCCESS);
// Vector4
result = engine.RegisterObjectType("Vector4", 0, asOBJ_REF | asOBJ_SCOPED); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Vector4", asBEHAVE_RELEASE, "void f()", asFUNCTION(AngelScriptAPI<Vector4>::Release), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Vector4", asBEHAVE_FACTORY, "Vector4@ f()", asFUNCTION(AngelScriptAPI<Vector4>::Factory), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Vector4", asBEHAVE_FACTORY, "Vector4@ f(const Vector4& in)", asFUNCTION(AngelScriptAPI<Vector4>::FactoryWithArgs<const Vector4&>), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Vector4", asBEHAVE_FACTORY, "Vector4@ f(float, float, float, float)", asFUNCTION((AngelScriptAPI<Vector4>::FactoryWithArgs<float, float, float, float>)), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Vector4", asBEHAVE_FACTORY, "Vector4@ f(const Vector3& in, float)", asFUNCTION((AngelScriptAPI<Vector4>::FactoryWithArgs<const Vector3&, float>)), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Vector4", asBEHAVE_FACTORY, "Vector4@ f(const Vector3& in)", asFUNCTION(AngelScriptAPI<Vector4>::FactoryWithArgs<const Vector3&>), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "void SetXYZ(const Vector3& in)", asMETHOD(Vector4, SetXYZ), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
// Vector3 GetXYZ() const ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "void SetX(float)", asMETHOD(Vector4, SetX), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "void SetY(float)", asMETHOD(Vector4, SetY), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "void SetZ(float)", asMETHOD(Vector4, SetZ), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "void SetW(float)", asMETHOD(Vector4, SetW), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "float GetX() const", asMETHOD(Vector4, GetX), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "float GetY() const", asMETHOD(Vector4, GetY), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "float GetZ() const", asMETHOD(Vector4, GetZ), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "float GetW() const", asMETHOD(Vector4, GetW), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "void opAssign(const Vector4& in)", asFUNCTION(AngelScriptAPI<Vector4>::OpAssign<Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "Vector4@ opNeg()", asFUNCTION(AngelScriptAPI<Vector4>::OpNeg), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "Vector4@ opAdd(const Vector4& in) const", asFUNCTION(AngelScriptAPI<Vector4>::OpAdd<const Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "Vector4@ opSub(const Vector4& in) const", asFUNCTION(AngelScriptAPI<Vector4>::OpSub<const Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "Vector4@ opMul(const Vector4& in) const", asFUNCTION(AngelScriptAPI<Vector4>::OpMul<const Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "Vector4@ opMul(float) const", asFUNCTION(AngelScriptAPI<Vector4>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "Vector4@ opMul_r(float) const", asFUNCTION(AngelScriptAPI<Vector4>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "Vector4@ opDiv(const Vector4& in) const", asFUNCTION(AngelScriptAPI<Vector4>::OpDiv<const Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "Vector4@ opDiv(float) const", asFUNCTION(AngelScriptAPI<Vector4>::OpDiv<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "void opAddAssign(const Vector4& in)", asFUNCTION(AngelScriptAPI<Vector4>::OpAddAssign<const Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "void subAssign(const Vector4& in)", asFUNCTION(AngelScriptAPI<Vector4>::OpSubAssign<const Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "void opMulAssign(float)", asFUNCTION(AngelScriptAPI<Vector4>::OpMulAssign<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "void opDivAssign(float)", asFUNCTION(AngelScriptAPI<Vector4>::OpDivAssign<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "float GetMaxElement() const", asMETHOD(Vector4, GetMaxElement), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "float GetMinElement() const", asMETHOD(Vector4, GetMinElement), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "float Dot(const Vector4& in) const", asMETHOD(Vector4, Dot), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "float LengthSqr() const", asMETHOD(Vector4, LengthSqr), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "float Length() const", asMETHOD(Vector4, Length), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Vector4", "void Normalize()", asMETHOD(Vector4, Normalize), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
// result = engine.RegisterObjectMethod("Vector4", "Vector4@ Normalized() const", asMETHOD(Vector4, Normalized), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
// Vector4 Abs() const ASSERT(result >= asSUCCESS);
result = engine.SetDefaultNamespace("Vector4"); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector4@ Max(const Vector4& in, const Vector4& in)", asFUNCTION((AngelScriptGenericAPI<Vector4>::StaticFunc<const Vector4&, const Vector4&, &Vector4::Max>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector4@ Min(const Vector4& in, const Vector4& in)", asFUNCTION((AngelScriptGenericAPI<Vector4>::StaticFunc<const Vector4&, const Vector4&, &Vector4::Min>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector4@ AxisX()", asFUNCTION(AngelScriptGenericAPI<Vector4>::StaticFunc<&Vector4::AxisX>), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector4@ AxisY()", asFUNCTION(AngelScriptGenericAPI<Vector4>::StaticFunc<&Vector4::AxisY>), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector4@ AxisZ()", asFUNCTION(AngelScriptGenericAPI<Vector4>::StaticFunc<&Vector4::AxisZ>), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Vector4@ AxisW()", asFUNCTION(AngelScriptGenericAPI<Vector4>::StaticFunc<&Vector4::AxisW>), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.SetDefaultNamespace(""); ASSERT(result >= asSUCCESS);
// Quat
result = engine.RegisterObjectType("Quat", 0, asOBJ_REF | asOBJ_SCOPED); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Quat", asBEHAVE_RELEASE, "void f()", asFUNCTION(AngelScriptAPI<Quat>::Release), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Quat", asBEHAVE_FACTORY, "Quat@ f()", asFUNCTION(AngelScriptAPI<Quat>::Factory), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Quat", asBEHAVE_FACTORY, "Quat@ f(const Quat& in)", asFUNCTION(AngelScriptAPI<Quat>::FactoryWithArgs<const Quat&>), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Quat", asBEHAVE_FACTORY, "Quat@ f(float, float, float, float)", asFUNCTION((AngelScriptAPI<Quat>::FactoryWithArgs<float, float, float, float>)), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Quat", "void opAssign(const Quat& in)", asFUNCTION(AngelScriptAPI<Quat>::OpAssign<Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Quat", "Quat@ opNeg()", asFUNCTION(AngelScriptAPI<Quat>::OpNeg), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Quat", "Quat@ opAdd(const Quat& in) const", asFUNCTION(AngelScriptAPI<Quat>::OpAdd<const Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Quat", "Quat@ opSub(const Quat& in) const", asFUNCTION(AngelScriptAPI<Quat>::OpSub<const Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Quat", "Quat@ opMul(const Quat& in) const", asFUNCTION(AngelScriptAPI<Quat>::OpMul<const Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Quat", "void opAddAssign(const Quat& in)", asFUNCTION(AngelScriptAPI<Quat>::OpAddAssign<const Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Quat", "void subAssign(const Quat& in)", asFUNCTION(AngelScriptAPI<Quat>::OpSubAssign<const Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Quat", "void opMulAssign(const Quat& in)", asFUNCTION(AngelScriptAPI<Quat>::OpMulAssign<const Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Quat", "float Dot(const Quat& in) const", asMETHOD(Quat, Dot), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Quat", "float Norm()", asMETHOD(Quat, Norm), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Quat", "float Length() const", asMETHOD(Quat, Length), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
// Quat Conjugate() const; ASSERT(result >= asSUCCESS);
// Vector3 EulerAngles() const; ASSERT(result >= asSUCCESS);
// Vector3 RotateVec(const Vector3& vec) const; ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Quat", "void Normalize()", asMETHOD(Quat, Normalize), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
// result = engine.RegisterObjectMethod("Quat", "Quat@ Normalized() const", asMETHOD(Quat, Normalized), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.SetDefaultNamespace("Quat"); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Quat@ Identity()", asFUNCTION(AngelScriptGenericAPI<Quat>::StaticFunc<&Quat::Identity>), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Quat@ CreateRotation(float, const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Quat>::StaticFunc<float, const Vector3&, &Quat::CreateRotation>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Quat@ CreateRotationX(float)", asFUNCTION((AngelScriptGenericAPI<Quat>::StaticFunc<float, &Quat::CreateRotationX>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Quat@ CreateRotationY(float)", asFUNCTION((AngelScriptGenericAPI<Quat>::StaticFunc<float, &Quat::CreateRotationY>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Quat@ CreateRotationZ(float)", asFUNCTION((AngelScriptGenericAPI<Quat>::StaticFunc<float, &Quat::CreateRotationZ>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Quat@ CreateRotationFromEulerAngles(const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Quat>::StaticFunc<const Vector3&, &Quat::CreateRotationFromEulerAngles>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.SetDefaultNamespace(""); ASSERT(result >= asSUCCESS);
// Matrix3
result = engine.RegisterObjectType("Matrix3", 0, asOBJ_REF | asOBJ_SCOPED); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Matrix3", asBEHAVE_RELEASE, "void f()", asFUNCTION(AngelScriptAPI<Matrix3>::Release), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Matrix3", asBEHAVE_FACTORY, "Matrix3@ f()", asFUNCTION(AngelScriptAPI<Matrix3>::Factory), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Matrix3", asBEHAVE_FACTORY, "Matrix3@ f(const Matrix3& in)", asFUNCTION(AngelScriptAPI<Matrix3>::FactoryWithArgs<const Matrix3&>), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Matrix3", asBEHAVE_FACTORY, "Matrix3@ f(const Vector3& in, const Vector3& in, const Vector3& in)", asFUNCTION((AngelScriptAPI<Matrix3>::FactoryWithArgs<const Vector3&, const Vector3&, const Vector3&>)), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Matrix3", asBEHAVE_FACTORY, "Matrix3@ f(const Quat& in)", asFUNCTION(AngelScriptAPI<Matrix3>::FactoryWithArgs<const Quat&>), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectProperty("Matrix3", "Vector3& m_col0", asOFFSET(Matrix3, m_col0)); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectProperty("Matrix3", "Vector3& m_col1", asOFFSET(Matrix3, m_col1)); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectProperty("Matrix3", "Vector3& m_col2", asOFFSET(Matrix3, m_col2)); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "void SetCol(int, const Vector3& in)", asMETHOD(Matrix3, SetCol), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "Vector3& GetCol(int) const", asMETHOD(Matrix3, GetCol), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "void SetRow0(const Vector3& in)", asMETHOD(Matrix3, SetRow0), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
// Vector3 GetRow0() const ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "void opAssign(const Matrix3& in)", asFUNCTION(AngelScriptAPI<Matrix3>::OpAssign<Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "Matrix3@ opNeg()", asFUNCTION(AngelScriptAPI<Matrix3>::OpNeg), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "Matrix3@ opAdd(const Matrix3& in) const", asFUNCTION(AngelScriptAPI<Matrix3>::OpAdd<const Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "Matrix3@ opSub(const Matrix3& in) const", asFUNCTION(AngelScriptAPI<Matrix3>::OpSub<const Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "Matrix3@ opMul(float) const", asFUNCTION(AngelScriptAPI<Matrix3>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "Matrix3@ opMul_r(float) const", asFUNCTION(AngelScriptAPI<Matrix3>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "Vector3@ opMul(const Vector3& in) const", asFUNCTION(AngelScriptAPI<Matrix3>::OpMul_2<Vector3>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "Matrix3@ opMul(const Matrix3& in) const", asFUNCTION(AngelScriptAPI<Matrix3>::OpMul<const Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "void opAddAssign(const Matrix3& in)", asFUNCTION(AngelScriptAPI<Matrix3>::OpAddAssign<const Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "void subAssign(const Matrix3& in)", asFUNCTION(AngelScriptAPI<Matrix3>::OpSubAssign<const Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "void opMulAssign(float)", asFUNCTION(AngelScriptAPI<Matrix3>::OpMulAssign<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "void opMulAssign(const Matrix3& in)", asFUNCTION(AngelScriptAPI<Matrix3>::OpMulAssign<const Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "void AppendScale(const Vector3& in)", asMETHOD(Matrix3, AppendScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "void PrependScale(const Vector3& in)", asMETHOD(Matrix3, PrependScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "void Transpose()", asMETHOD(Matrix3, Transpose), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "void Invert()", asMETHOD(Matrix3, Invert), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix3", "float CalculateDeterminant() const", asMETHOD(Matrix3, CalculateDeterminant), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.SetDefaultNamespace("Matrix3"); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix3@ Identity()", asFUNCTION(AngelScriptGenericAPI<Matrix3>::StaticFunc<&Matrix3::Identity>), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix3@ CreateRotationX(float)", asFUNCTION((AngelScriptGenericAPI<Matrix3>::StaticFunc<float, &Matrix3::CreateRotationX>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix3@ CreateRotationY(float)", asFUNCTION((AngelScriptGenericAPI<Matrix3>::StaticFunc<float, &Matrix3::CreateRotationY>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix3@ CreateRotationZ(float)", asFUNCTION((AngelScriptGenericAPI<Matrix3>::StaticFunc<float, &Matrix3::CreateRotationZ>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix3@ CreateRotationZYX(const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix3>::StaticFunc<const Vector3&, &Matrix3::CreateRotationZYX>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix3@ CreateRotation(float, const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix3>::StaticFunc<float, const Vector3&, &Matrix3::CreateRotation>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix3@ CreateScale(const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix3>::StaticFunc<const Vector3&, &Matrix3::CreateScale>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.SetDefaultNamespace(""); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Quat", asBEHAVE_FACTORY, "Quat@ f(const Matrix3& in)", asFUNCTION((AngelScriptAPI<Quat>::FactoryWithArgs<const Matrix3&>)), asCALL_CDECL); ASSERT(result >= asSUCCESS);
// Matrix4
result = engine.RegisterObjectType("Matrix4", 0, asOBJ_REF | asOBJ_SCOPED); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Matrix4", asBEHAVE_RELEASE, "void f()", asFUNCTION(AngelScriptAPI<Matrix4>::Release), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Matrix4", asBEHAVE_FACTORY, "Matrix4@ f()", asFUNCTION(AngelScriptAPI<Matrix4>::Factory), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Matrix4", asBEHAVE_FACTORY, "Matrix4@ f(const Matrix4& in)", asFUNCTION(AngelScriptAPI<Matrix4>::FactoryWithArgs<const Matrix4&>), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Matrix4", asBEHAVE_FACTORY, "Matrix4@ f(const Vector4& in, const Vector4& in, const Vector4& in, const Vector4& in)", asFUNCTION((AngelScriptAPI<Matrix4>::FactoryWithArgs<const Vector4&, const Vector4&, const Vector4&, const Vector4&>)), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Matrix4", asBEHAVE_FACTORY, "Matrix4@ f(const Matrix3& in, const Vector3& in)", asFUNCTION((AngelScriptAPI<Matrix4>::FactoryWithArgs<const Matrix3&, const Vector3&>)), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectBehaviour("Matrix4", asBEHAVE_FACTORY, "Matrix4@ f(const Quat& in, const Vector3& in)", asFUNCTION((AngelScriptAPI<Matrix4>::FactoryWithArgs<const Quat&, const Vector3&>)), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void SetUpper3x3(const Matrix3& in)", asMETHOD(Matrix4, SetUpper3x3), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
// Matrix3 GetUpper3x3() const ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void SetTranslation(const Vector3& in)", asMETHOD(Matrix4, SetTranslation), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
// Vector3 GetTranslation() const ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectProperty("Matrix4", "Vector4& m_col0", asOFFSET(Matrix4, m_col0)); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectProperty("Matrix4", "Vector4& m_col1", asOFFSET(Matrix4, m_col1)); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectProperty("Matrix4", "Vector4& m_col2", asOFFSET(Matrix4, m_col2)); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectProperty("Matrix4", "Vector4& m_col3", asOFFSET(Matrix4, m_col3)); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void SetCol(int, const Vector4& in)", asMETHOD(Matrix4, SetCol), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "Vector4& GetCol(int) const", asMETHOD(Matrix4, GetCol), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void SetRow0(const Vector4& in)", asMETHOD(Matrix4, SetRow0), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
// Vector4 GetRow0() const ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void opAssign(const Matrix4& in)", asFUNCTION(AngelScriptAPI<Matrix4>::OpAssign<Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "Matrix4@ opNeg()", asFUNCTION(AngelScriptAPI<Matrix4>::OpNeg), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "Matrix4@ opAdd(const Matrix4& in) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpAdd<const Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "Matrix4@ opSub(const Matrix4& in) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpSub<const Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "Matrix4@ opMul(float) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "Matrix4@ opMul_r(float) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "Vector4@ opMul(const Vector4& in) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpMul_2<Vector4>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "Vector4@ opMul(const Vector3& in) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpMul_2<Vector3>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "Matrix4@ opMul(const Matrix4& in) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpMul<const Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void opAddAssign(const Matrix4& in)", asFUNCTION(AngelScriptAPI<Matrix4>::OpAddAssign<const Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void subAssign(const Matrix4& in)", asFUNCTION(AngelScriptAPI<Matrix4>::OpSubAssign<const Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void opMulAssign(float)", asFUNCTION(AngelScriptAPI<Matrix4>::OpMulAssign<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void opMulAssign(const Matrix4& in)", asFUNCTION(AngelScriptAPI<Matrix4>::OpMulAssign<const Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void AppendScale(const Vector3& in)", asMETHOD(Matrix4, AppendScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void PrependScale(const Vector3& in)", asMETHOD(Matrix4, PrependScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void Transpose()", asMETHOD(Matrix4, Transpose), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void Invert()", asMETHOD(Matrix4, Invert), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void AffineInvert()", asMETHOD(Matrix4, AffineInvert), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "void OrthoInvert()", asMETHOD(Matrix4, OrthoInvert), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Matrix4", "float CalculateDeterminant() const", asMETHOD(Matrix4, CalculateDeterminant), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.SetDefaultNamespace("Matrix4"); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix4@ Identity()", asFUNCTION(AngelScriptGenericAPI<Matrix4>::StaticFunc<&Matrix4::Identity>), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix4@ CreateTranslation(const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<const Vector3&, &Matrix4::CreateTranslation>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix4@ CreateRotationX(float)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<float, &Matrix4::CreateRotationX>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix4@ CreateRotationY(float)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<float, &Matrix4::CreateRotationY>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix4@ CreateRotationZ(float)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<float, &Matrix4::CreateRotationZ>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix4@ CreateRotationZYX(const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<const Vector3&, &Matrix4::CreateRotationZYX>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix4@ CreateRotation(float, const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<float, const Vector3&, &Matrix4::CreateRotation>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("Matrix4@ CreateScale(const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<const Vector3&, &Matrix4::CreateScale>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS);
result = engine.SetDefaultNamespace(""); ASSERT(result >= asSUCCESS);
// Transform
result = engine.RegisterObjectType("Transform", 0, asOBJ_REF | asOBJ_NOHANDLE); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Transform", "void SetLocalPosition(const Vector3& in)", asMETHOD(Transform, SetLocalPosition), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Transform", "const Vector3& GetLocalPosition() const", asMETHOD(Transform, GetLocalPosition), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Transform", "void SetLocalRotation(const Quat& in)", asMETHOD(Transform, SetLocalRotation), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Transform", "const Quat& GetLocalRotation() const", asMETHOD(Transform, GetLocalRotation), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Transform", "void SetLocalScale(const Vector3& in)", asMETHOD(Transform, SetLocalScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Transform", "const Vector3& GetLocalScale() const", asMETHOD(Transform, GetLocalScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Transform", "void SetPosition(const Vector3& in)", asMETHOD(Transform, SetPosition), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Transform", "Vector3@ GetPosition() const", asFUNCTION(Transform_GetPosition), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Transform", "void SetRotation(const Quat& in)", asMETHOD(Transform, SetRotation), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Transform", "Quat@ GetRotation() const", asFUNCTION(Transform_GetRotation), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Transform", "void SetScale(const Vector3& in)", asMETHOD(Transform, SetScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Transform", "Vector3@ GetScale() const", asFUNCTION(Transform_GetScale), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS);
// Rand
result = engine.RegisterObjectType("Rand", 0, asOBJ_REF | asOBJ_NOHANDLE); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Rand", "int GetInt32()", asMETHOD(Rand, GetInt32), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Rand", "uint GetUint32()", asMETHOD(Rand, GetUint32), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Rand", "float GetFloat()", asMETHOD(Rand, GetFloat), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Rand", "double GetDouble()", asMETHOD(Rand, GetDouble), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterObjectMethod("Rand", "bool GetBool()", asMETHOD(Rand, GetBool), asCALL_THISCALL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalProperty("Rand s_globalRand", &Rand::s_globalRand); ASSERT(result >= asSUCCESS);
// Math
result = engine.SetDefaultNamespace("Math"); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("int Round32(float)", asFUNCTION(Math::Round32), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("int RoundUp(float, int)", asFUNCTION(Math::RoundUp), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.SetDefaultNamespace(""); ASSERT(result >= asSUCCESS);
// Trigonometric functions
result = engine.RegisterGlobalFunction("float cos(float)", asFUNCTION(std::cosf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("float sin(float)", asFUNCTION(std::sinf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("float tan(float)", asFUNCTION(std::tanf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("float acos(float)", asFUNCTION(std::acosf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("float asin(float)", asFUNCTION(std::asinf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("float atan(float)", asFUNCTION(std::atanf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("float atan2(float, float)", asFUNCTION(std::atan2f), asCALL_CDECL); ASSERT(result >= asSUCCESS);
// Hyberbolic functions
result = engine.RegisterGlobalFunction("float cosh(float)", asFUNCTION(std::coshf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("float sinh(float)", asFUNCTION(std::sinhf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("float tanh(float)", asFUNCTION(std::tanhf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
// Exponential and logarithmic functions
result = engine.RegisterGlobalFunction("float log(float)", asFUNCTION(std::logf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("float log10(float)", asFUNCTION(std::log10f), asCALL_CDECL); ASSERT(result >= asSUCCESS);
// Power functions
result = engine.RegisterGlobalFunction("float pow(float, float)", asFUNCTION(std::powf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("float sqrt(float)", asFUNCTION(std::sqrtf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
// Absolute value functions
result = engine.RegisterGlobalFunction("float fabsf(float)", asFUNCTION(std::fabsf), asCALL_CDECL); ASSERT(result >= asSUCCESS);
result = engine.RegisterGlobalFunction("int64 abs(int64)", asFUNCTION(std::llabs), asCALL_CDECL); ASSERT(result >= asSUCCESS);
}
| 163.672474 | 323 | 0.691404 | nyaki-HUN |