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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923beef145545c26f17f30f2201265e5540f3851 | 9,760 | cpp | C++ | hackathon/XuanZhao/compare_swc2/n_class.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | hackathon/XuanZhao/compare_swc2/n_class.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | hackathon/XuanZhao/compare_swc2/n_class.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | #include "n_class.h"
bool Comp(const int &a,const int &b)
{
return a>b;
}
bool Branch::get_r_points_of_branch(vector<NeuronSWC> &r_points, NeuronTree &nt)
{
NeuronSWC tmp=end_point;
r_points.push_back(end_point);
while(tmp.n!=head_point.n)
{
tmp=nt.listNeuron[nt.hashNeuron.value(tmp.parent)];
r_points.push_back(tmp);
}
return true;
}
bool Branch::get_points_of_branch(vector<NeuronSWC> &points, NeuronTree &nt)
{
vector<NeuronSWC> r_points;
this->get_r_points_of_branch(r_points,nt);
while(!r_points.empty())
{
NeuronSWC tmp=r_points.back();
r_points.pop_back();
points.push_back(tmp);
}
return true;
}
bool SwcTree::initialize(NeuronTree t)
{
nt.deepCopy(t);
NeuronSWC ori;
V3DLONG num_p=nt.listNeuron.size();
vector<vector<V3DLONG> > children=vector<vector<V3DLONG> >(num_p,vector<V3DLONG>());
for(V3DLONG i=0;i<num_p;++i)
{
V3DLONG par=nt.listNeuron[i].parent;
if(par<0)
{
ori=nt.listNeuron[i];
continue;
}
children[nt.hashNeuron.value(par)].push_back(i);
}
vector<NeuronSWC> queue;
queue.push_back(ori);
//initial head_point,end_point,distance,length
cout<<"initial head_point,end_point,distance,length"<<endl;
while(!queue.empty())
{
NeuronSWC tmp=queue.front();
queue.erase(queue.begin());
for(int i=0;i<children[nt.hashNeuron.value(tmp.n)].size();++i)
{
Branch branch;
branch.head_point=tmp;
NeuronSWC child=nt.listNeuron[children[nt.hashNeuron.value(branch.head_point.n)][i]];
branch.length+=distance_two_point(tmp,child);
Angle near_point_angle = Angle(child.x-tmp.x,child.y-tmp.y,child.z-tmp.z);
near_point_angle.norm_angle();
double sum_angle = 0;
while(children[nt.hashNeuron.value(child.n)].size()==1)
{
NeuronSWC par=child;
child=nt.listNeuron[children[nt.hashNeuron.value(par.n)][0]];
branch.length+=distance_two_point(par,child);
Angle next_point_angle = Angle(child.x-par.x,child.y-par.y,child.z-par.z);
next_point_angle.norm_angle();
sum_angle += acos(near_point_angle*next_point_angle);
}
if(children[nt.hashNeuron.value(child.n)].size()>=1)
{
queue.push_back(child);
}
branch.end_point=child;
branch.distance=branch.get_distance();
branch.sum_angle = sum_angle;
branchs.push_back(branch);
}
}
//initial head_angle,end_angle
cout<<"initial head_angle,end_angle"<<endl;
for(int i=0;i<branchs.size();++i)
{
vector<NeuronSWC> points;
branchs[i].get_points_of_branch(points,nt);
double length=0;
NeuronSWC par0=points[0];
for(int j=1;j<points.size();++j)
{
NeuronSWC child0=points[j];
length+=distance_two_point(par0,child0);
if(length>5)
{
branchs[i].head_angle.x=child0.x-points[0].x;
branchs[i].head_angle.y=child0.y-points[0].y;
branchs[i].head_angle.z=child0.z-points[0].z;
double d=norm_v(branchs[i].head_angle);
branchs[i].head_angle.x/=d;
branchs[i].head_angle.y/=d;
branchs[i].head_angle.z/=d;
break;
}
par0=child0;
}
if(length<=5)
{
branchs[i].head_angle.x=par0.x-points[0].x;
branchs[i].head_angle.y=par0.y-points[0].y;
branchs[i].head_angle.z=par0.z-points[0].z;
double d=norm_v(branchs[i].head_angle);
branchs[i].head_angle.x/=d;
branchs[i].head_angle.y/=d;
branchs[i].head_angle.z/=d;
}
length=0;
points.clear();
branchs[i].get_r_points_of_branch(points,nt);
NeuronSWC child1=points[0];
for(int j=1;j<points.size();++j)
{
NeuronSWC par1=points[j];
length+=distance_two_point(par1,child1);
if(length>5)
{
branchs[i].end_angle.x=par1.x-points[0].x;
branchs[i].end_angle.y=par1.y-points[0].y;
branchs[i].end_angle.z=par1.z-points[0].z;
double d=norm_v(branchs[i].end_angle);
branchs[i].end_angle.x/=d;
branchs[i].end_angle.y/=d;
branchs[i].end_angle.z/=d;
break;
}
child1=par1;
}
if(length<=5)
{
branchs[i].end_angle.x=child1.x-points[0].x;
branchs[i].end_angle.y=child1.y-points[0].y;
branchs[i].end_angle.z=child1.z-points[0].z;
double d=norm_v(branchs[i].end_angle);
branchs[i].end_angle.x/=d;
branchs[i].end_angle.y/=d;
branchs[i].end_angle.z/=d;
}
}
//initial parent
cout<<"initial parent"<<endl;
for(int i=0;i<branchs.size();++i)
{
if(branchs[i].head_point.parent<0)
{
branchs[i].parent=0;
}
else
{
for(int j=0;j<branchs.size();++j)
{
if(branchs[i].head_point==branchs[j].end_point)
{
branchs[i].parent=&branchs[j];
}
}
}
}
//initial level
for(int i=0;i<branchs.size();++i)
{
Branch* tmp;
tmp=&branchs[i];
int level=0;
while(tmp->parent!=0)
{
level++;
tmp=tmp->parent;
}
branchs[i].level=level;
}
return true;
}
bool SwcTree::get_level_index(vector<int> &level_index,int level)
{
for(int i=0;i<branchs.size();++i)
{
if(branchs[i].level==level)
{
level_index.push_back(i);
}
}
return true;
}
bool SwcTree::get_points_of_branchs(vector<Branch> &b,vector<NeuronSWC> &points,NeuronTree &ntb)
{
for(int i=0;i<(b.size()-1);++i)
{
b[i].get_points_of_branch(points,ntb);
points.pop_back();
}
b[(b.size()-1)].get_points_of_branch(points,ntb);
return true;
}
int SwcTree::get_max_level()
{
int max_level;
for(int i=0;i<branchs.size();++i)
{
max_level=(max_level>branchs[i].level)?max_level:branchs[i].level;
}
return max_level;
}
bool SwcTree::get_bifurcation_image(QString dir, int resolutionX, int resolutionY, int resolutionZ, bool all, QString braindir, V3DPluginCallback2 &callback)
{
int num_b = branchs.size();
map<Branch,int> mapbranch;
for(int i=0; i<num_b ;++i)
{
mapbranch[branchs[i]] = i;
}
vector<vector<int> > branch_children=vector<vector<int> >(num_b,vector<int>());
for(int i=0; i<num_b; ++i)
{
if(branchs[i].parent==0) continue;
branch_children[mapbranch[*(branchs[i].parent)]].push_back(i);
}
vector<int> queue;
get_level_index(queue,0);
int num = 0;
while(!queue.empty()){
int bi = queue.front();//branch_index
queue.erase(queue.begin());
if(branch_children[bi].size()>0){
int level = branchs[bi].level;
num++;
if(all || branchs[bi].level>2){
QString filename = dir+"/b_level"+QString::number(level)
+"_x"+QString::number(branchs[bi].end_point.x)
+"_y"+QString::number(branchs[bi].end_point.y)
+"_z"+QString::number(branchs[bi].end_point.z)+QString::number(num)+".tif";
get3DImageBasedPoint(filename.toStdString().c_str(),branchs[bi].end_point,resolutionX,resolutionY,resolutionZ,braindir,callback);
}
for(int i=0; i<branch_children[bi].size(); ++i){
queue.push_back(branch_children[bi][i]);
}
}
}
return true;
}
bool SwcTree::get_un_bifurcation_image(QString dir, int resolutionX, int resolutionY, int resolutionZ, bool all, QString braindir, V3DPluginCallback2 &callback)
{
const int distance_to_bifurcation = 20;
int num_b = branchs.size();
int num = 0;
for(int i=0; i<num_b; ++i){
if(all||branchs[i].length<200){
if(branchs[i].length>2*distance_to_bifurcation){
vector<NeuronSWC> points;
branchs[i].get_points_of_branch(points,nt);
int level = branchs[i].level;
int num_p = points.size();
if(num_p>10){
int k;
if(all)
k = 1;
else
k = 3;
for(int j=5; j<num_p-5; j+=k){
if(distance_two_point(points[j],points[0])>distance_to_bifurcation
&& distance_two_point(points[j],points[num_p-1])>distance_to_bifurcation)
{
num++;
QString filename = dir+"/level"+QString::number(level)+"_j"+QString::number(j)+"_"
+QString::number(num)+"_x"+QString::number(points[j].x)
+"_y"+QString::number(points[j].y)+"_z"+QString::number(points[j].z)+".tif";
get3DImageBasedPoint(filename.toStdString().c_str(),points[j],resolutionX,resolutionY,resolutionZ,braindir,callback);
}
}
}
}
}
}
return true;
}
| 30.030769 | 160 | 0.534836 | zzhmark |
923c947f3f73180e470c109103abeb14f7b60a45 | 527 | hpp | C++ | include/util/any.hpp | BaroboRobotics/cxx-util | 624813d244ac5a3e6e4ffb16b7e0ac96b5c200cd | [
"BSL-1.0"
] | null | null | null | include/util/any.hpp | BaroboRobotics/cxx-util | 624813d244ac5a3e6e4ffb16b7e0ac96b5c200cd | [
"BSL-1.0"
] | null | null | null | include/util/any.hpp | BaroboRobotics/cxx-util | 624813d244ac5a3e6e4ffb16b7e0ac96b5c200cd | [
"BSL-1.0"
] | 1 | 2018-11-13T15:02:23.000Z | 2018-11-13T15:02:23.000Z | // Copyright (c) 2014-2016 Barobo, Inc.
//
// 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 UTIL_ANY_HPP
#define UTIL_ANY_HPP
#include <utility>
namespace util {
template <class T>
constexpr bool any (T&& x) {
return std::forward<T>(x);
}
template <class T, class... Ts>
constexpr bool any (T&& x, Ts&&... xs) {
return std::forward<T>(x) || any(std::forward<Ts>(xs)...);
}
} // namespace util
#endif
| 20.269231 | 79 | 0.671727 | BaroboRobotics |
923dce66fe2a31a0efe4eb5249b0ae605820ffa0 | 5,904 | hpp | C++ | code/jsbind/v8/convert.hpp | Chobolabs/jsbind | 874b41df6bbc9a3b756e828c64e43e1b6cbd4386 | [
"MIT"
] | 57 | 2019-03-30T21:26:08.000Z | 2022-03-11T02:22:09.000Z | code/jsbind/v8/convert.hpp | Chobolabs/jsbind | 874b41df6bbc9a3b756e828c64e43e1b6cbd4386 | [
"MIT"
] | null | null | null | code/jsbind/v8/convert.hpp | Chobolabs/jsbind | 874b41df6bbc9a3b756e828c64e43e1b6cbd4386 | [
"MIT"
] | 3 | 2020-04-11T09:19:44.000Z | 2021-09-30T07:30:45.000Z | // jsbind
// Copyright (c) 2019 Chobolabs Inc.
// http://www.chobolabs.com/
//
// Distributed under the MIT Software License
// See accompanying file LICENSE.txt or copy at
// http://opensource.org/licenses/MIT
//
#pragma once
#include "global.hpp"
#include "jsbind/common/wrapped_class.hpp"
#include <string>
#include <type_traits>
#include <climits>
namespace jsbind
{
class local;
namespace internal
{
template <typename T, typename Enable = void> // enable used by enable_if specializations
struct convert;
template <>
struct convert<std::string>
{
using from_type = std::string;
using to_type = v8::Local<v8::String>;
static from_type from_v8(v8::Local<v8::Value> val)
{
const v8::String::Utf8Value str(isolate, val);
return from_type(*str, str.length());
}
static to_type to_v8(const from_type& val)
{
return v8::String::NewFromUtf8(isolate, val.c_str(),
v8::String::kNormalString, int(val.length()));
}
};
template <>
struct convert<const char*>
{
using from_type = const char*;
using to_type = v8::Local<v8::String>;
// raw pointer converion not supported
// it could be supported but emscripten doesn't do it, so we'll follow
static from_type from_v8(v8::Local<v8::Value> val) = delete;
static to_type to_v8(const char* val)
{
return v8::String::NewFromUtf8(isolate, val);
}
};
template<>
struct convert<bool>
{
using from_type = bool;
using to_type = v8::Local<v8::Boolean>;
static from_type from_v8(v8::Local<v8::Value> value)
{
return value->ToBoolean(isolate)->Value();
}
static to_type to_v8(bool value)
{
return v8::Boolean::New(isolate, value);
}
};
template<typename T>
struct convert<T, typename std::enable_if<std::is_integral<T>::value>::type>
{
using from_type = T;
using to_type = v8::Local<v8::Number>;
enum { bits = sizeof(T) * CHAR_BIT, is_signed = std::is_signed<T>::value };
static from_type from_v8(v8::Local<v8::Value> value)
{
auto& v8ctx = *reinterpret_cast<v8::Local<v8::Context>*>(&internal::ctx.v8ctx);
if (bits <= 32)
{
if (is_signed)
{
return static_cast<T>(value->Int32Value(v8ctx).FromMaybe(0));
}
else
{
return static_cast<T>(value->Uint32Value(v8ctx).FromMaybe(0));
}
}
else
{
return static_cast<T>(value->IntegerValue(v8ctx).FromMaybe(0));
}
}
static to_type to_v8(from_type value)
{
if (bits <= 32)
{
if (is_signed)
{
return v8::Integer::New(isolate, static_cast<int32_t>(value));
}
else
{
return v8::Integer::NewFromUnsigned(isolate, static_cast<uint32_t>(value));
}
}
else
{
// check value < (1<<57) to fit in double?
return v8::Number::New(isolate, static_cast<double>(value));
}
}
};
template<typename T>
struct convert<T, typename std::enable_if<std::is_floating_point<T>::value>::type>
{
using from_type = T;
using to_type = v8::Local<v8::Number>;
static from_type from_v8(v8::Local<v8::Value> value)
{
auto& v8ctx = *reinterpret_cast<v8::Local<v8::Context>*>(&internal::ctx.v8ctx);
return static_cast<T>(value->NumberValue(v8ctx).FromMaybe(0));
}
static to_type to_v8(T value)
{
return v8::Number::New(isolate, value);
}
};
template <>
struct convert<void>
{
using from_type = void;
using to_type = v8::Local<v8::Primitive>;
static from_type from_v8(v8::Local<v8::Value>) {}
static to_type to_v8() { return v8::Undefined(isolate); }
};
template <>
struct convert<local>
{
using from_type = local;
using to_type = v8::Local<v8::Value>;
static from_type from_v8(v8::Local<v8::Value>);
static to_type to_v8(const from_type&);
};
template<typename T>
struct convert<T&> : convert<T>{};
template<typename T>
struct convert<const T&> : convert<T>{};
///////////////////////////////////////////////////////////////////////////
template <typename T>
T convert_wrapped_class_from_v8(v8::Local<v8::Value> value);
template <typename T>
v8::Local<v8::Object> convert_wrapped_class_to_v8(const T& t);
template <typename T>
struct convert<T, typename std::enable_if<is_wrapped_class<T>::value>::type>
{
using from_type = T;
using to_type = v8::Local<v8::Object>;
static from_type from_v8(v8::Local<v8::Value> value)
{
return convert_wrapped_class_from_v8<from_type>(value);
}
static to_type to_v8(const from_type& value)
{
return convert_wrapped_class_to_v8(value);
}
};
///////////////////////////////////////////////////////////////////////////
template<typename T>
typename convert<T>::from_type from_v8(v8::Local<v8::Value> value)
{
return convert<T>::from_v8(value);
}
template<size_t N>
v8::Local<v8::String> to_v8(const char (&str)[N])
{
return convert<const char*>::to_v8(str);
}
template<typename T>
typename convert<T>::to_type to_v8(const T& value)
{
return convert<T>::to_v8(value);
}
}
}
| 26.594595 | 95 | 0.54065 | Chobolabs |
92404c1d3c0ab2222f506e2b240dd972433768a4 | 657 | cpp | C++ | OrionUO/GUI/GUIHTMLButton.cpp | SirGlorg/OrionUO | 42209bd144392fddff9e910562ccec1bf5704049 | [
"MIT"
] | 1 | 2019-04-27T22:20:34.000Z | 2019-04-27T22:20:34.000Z | OrionUO/GUI/GUIHTMLButton.cpp | SirGlorg/OrionUO | 42209bd144392fddff9e910562ccec1bf5704049 | [
"MIT"
] | 1 | 2018-12-28T13:45:08.000Z | 2018-12-28T13:45:08.000Z | OrionUO/GUI/GUIHTMLButton.cpp | heppcatt/Siebenwind-Beta-Client | ba25683f37f9bb7496d12aa2b2117cba397370e2 | [
"MIT"
] | null | null | null | // MIT License
// Copyright (C) August 2016 Hotride
CGUIHTMLButton::CGUIHTMLButton(
CGUIHTMLGump *htmlGump,
int serial,
uint16_t graphic,
uint16_t graphicSelected,
uint16_t graphicPressed,
int x,
int y)
: CGUIButton(serial, graphic, graphicSelected, graphicPressed, x, y)
, m_HTMLGump(htmlGump)
{
}
CGUIHTMLButton::~CGUIHTMLButton()
{
}
void CGUIHTMLButton::SetShaderMode()
{
DEBUG_TRACE_FUNCTION;
glUniform1iARB(g_ShaderDrawMode, SDM_NO_COLOR);
}
void CGUIHTMLButton::Scroll(bool up, int delay)
{
DEBUG_TRACE_FUNCTION;
if (m_HTMLGump != nullptr)
{
m_HTMLGump->Scroll(up, delay);
}
}
| 18.771429 | 72 | 0.692542 | SirGlorg |
924c0db79b8f383d8dc3d30eed312be6cd6580ba | 777 | hpp | C++ | Runtime/World/CScriptBeam.hpp | Jcw87/urde | fb9ea9092ad00facfe957ece282a86c194e9cbda | [
"MIT"
] | null | null | null | Runtime/World/CScriptBeam.hpp | Jcw87/urde | fb9ea9092ad00facfe957ece282a86c194e9cbda | [
"MIT"
] | null | null | null | Runtime/World/CScriptBeam.hpp | Jcw87/urde | fb9ea9092ad00facfe957ece282a86c194e9cbda | [
"MIT"
] | null | null | null | #pragma once
#include <string_view>
#include "Runtime/Weapon/CBeamInfo.hpp"
#include "Runtime/World/CActor.hpp"
#include "Runtime/World/CDamageInfo.hpp"
namespace metaforce {
class CWeaponDescription;
class CScriptBeam : public CActor {
TCachedToken<CWeaponDescription> xe8_weaponDescription;
CBeamInfo xf4_beamInfo;
CDamageInfo x138_damageInfo;
TUniqueId x154_projectileId;
public:
CScriptBeam(TUniqueId, std::string_view, const CEntityInfo&, const zeus::CTransform&, bool,
const TToken<CWeaponDescription>&, const CBeamInfo&, const CDamageInfo&);
void Accept(IVisitor& visitor) override;
void Think(float, CStateManager&) override;
void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override;
};
} // namespace metaforce
| 29.884615 | 93 | 0.78121 | Jcw87 |
924d63d5f43ad2567313e7584a5941997b3a6580 | 3,321 | cpp | C++ | test/unit-modcc/test_kinetic_rewriter.cpp | kanzl/arbor | 86b1eb065ac252bf0026de7cf7cbc6748a528254 | [
"BSD-3-Clause"
] | 53 | 2018-10-18T12:08:21.000Z | 2022-03-26T22:03:51.000Z | test/unit-modcc/test_kinetic_rewriter.cpp | kanzl/arbor | 86b1eb065ac252bf0026de7cf7cbc6748a528254 | [
"BSD-3-Clause"
] | 864 | 2018-10-01T08:06:00.000Z | 2022-03-31T08:06:48.000Z | test/unit-modcc/test_kinetic_rewriter.cpp | kanzl/arbor | 86b1eb065ac252bf0026de7cf7cbc6748a528254 | [
"BSD-3-Clause"
] | 37 | 2019-03-03T16:18:49.000Z | 2022-03-24T10:39:51.000Z | #include <iostream>
#include <string>
#include "expression.hpp"
#include "kineticrewriter.hpp"
#include "parser.hpp"
#include "alg_collect.hpp"
#include "common.hpp"
#include "expr_expand.hpp"
expr_list_type& statements(Expression *e) {
if (e) {
if (auto block = e->is_block()) {
return block->statements();
}
if (auto sym = e->is_symbol()) {
if (auto proc = sym->is_procedure()) {
return proc->body()->statements();
}
if (auto proc = sym->is_procedure()) {
return proc->body()->statements();
}
}
}
throw std::runtime_error("not a block, function or procedure");
}
inline symbol_ptr state_var(const char* name) {
auto v = make_symbol<VariableExpression>(Location(), name);
v->is_variable()->state(true);
return v;
}
inline symbol_ptr assigned_var(const char* name) {
return make_symbol<VariableExpression>(Location(), name);
}
static const char* kinetic_abc =
"KINETIC kin { \n"
" u = 3 \n"
" ~ a <-> b (u, v) \n"
" u = 4 \n"
" v = sin(u) \n"
" ~ b <-> 3b + c (u, v) \n"
"} \n";
static const char* derivative_abc =
"DERIVATIVE deriv { \n"
" a' = -3*a + b*v \n"
" LOCAL rev2 \n"
" rev2 = c*b^3*sin(4) \n"
" b' = 3*a - v*b + 8*b - 2*rev2\n"
" c' = 4*b - rev2 \n"
"} \n";
TEST(KineticRewriter, equiv) {
auto kin = Parser(kinetic_abc).parse_procedure();
auto deriv = Parser(derivative_abc).parse_procedure();
auto kin_ptr = kin.get();
auto deriv_ptr = deriv.get();
ASSERT_NE(nullptr, kin);
ASSERT_NE(nullptr, deriv);
ASSERT_TRUE(kin->is_symbol() && kin->is_symbol()->is_procedure());
ASSERT_TRUE(deriv->is_symbol() && deriv->is_symbol()->is_procedure());
scope_type::symbol_map globals;
globals["kin"] = std::move(kin);
globals["deriv"] = std::move(deriv);
globals["a"] = state_var("a");
globals["b"] = state_var("b");
globals["c"] = state_var("c");
globals["u"] = assigned_var("u");
globals["v"] = assigned_var("v");
deriv_ptr->semantic(globals);
auto kin_body = kin_ptr->is_procedure()->body();
scope_ptr scope = std::make_shared<scope_type>(globals);
kin_body->semantic(scope);
auto kin_deriv = kinetic_rewrite(kin_body);
verbose_print("derivative procedure:\n", deriv_ptr);
verbose_print("kin procedure:\n", kin_ptr);
verbose_print("rewritten kin body:\n", kin_deriv);
auto deriv_map = expand_assignments(statements(deriv_ptr));
auto kin_map = expand_assignments(statements(kin_deriv.get()));
if (g_verbose_flag) {
std::cout << "derivative assignments (canonical):\n";
for (const auto&p: deriv_map) {
std::cout << p.first << ": " << p.second << "\n";
}
std::cout << "rewritten kin assignments (canonical):\n";
for (const auto&p: kin_map) {
std::cout << p.first << ": " << p.second << "\n";
}
}
EXPECT_EQ(deriv_map["a'"], kin_map["a'"]);
EXPECT_EQ(deriv_map["b'"], kin_map["b'"]);
EXPECT_EQ(deriv_map["c'"], kin_map["c'"]);
}
| 29.651786 | 74 | 0.552243 | kanzl |
924eb6611f6d5a383f9a0e27dada734eb9ee7b17 | 713 | cpp | C++ | sauce/core/collections/abstractions/strange__queue_a.cpp | oneish/strange | e6c47eca5738dd98f4e09ee5c0bb820146e8b48f | [
"Apache-2.0"
] | null | null | null | sauce/core/collections/abstractions/strange__queue_a.cpp | oneish/strange | e6c47eca5738dd98f4e09ee5c0bb820146e8b48f | [
"Apache-2.0"
] | null | null | null | sauce/core/collections/abstractions/strange__queue_a.cpp | oneish/strange | e6c47eca5738dd98f4e09ee5c0bb820146e8b48f | [
"Apache-2.0"
] | null | null | null | #include "../../strange__core.h"
namespace strange
{
template <typename element_d>
var<symbol_a> queue_a<element_d>::cat(con<> const& me)
{
static auto r = sym("<strange::queue>"); //TODO cat
return r;
}
template <typename element_d>
typename queue_a<element_d>::creator_fp queue_a<element_d>::creator(con<symbol_a> const& scope,
con<symbol_a> const& thing,
con<symbol_a> const& function)
{
if (scope == "strange")
{
if (thing == "queue")
{
if (function == "create_from_range")
{
// return thing_t::create_from_range;
}
}
}
return nullptr;
}
// instantiation
template struct queue_a<>;
template struct queue_a<int64_t>;
template struct queue_a<uint8_t>;
}
| 20.371429 | 96 | 0.667602 | oneish |
924f78caafafaacfd4d8d9a754dfce0594908a0a | 596 | hpp | C++ | test/src/Algorithm/NoneOf.hpp | changjurhee/CppML | 6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5 | [
"MIT"
] | 48 | 2019-05-14T10:07:08.000Z | 2021-04-08T08:26:20.000Z | test/src/Algorithm/NoneOf.hpp | changjurhee/CppML | 6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5 | [
"MIT"
] | null | null | null | test/src/Algorithm/NoneOf.hpp | changjurhee/CppML | 6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5 | [
"MIT"
] | 4 | 2019-11-18T15:35:32.000Z | 2021-12-02T05:23:04.000Z | #include "CppML/CppML.hpp"
namespace NoneOfTest {
template <typename T> using Predicate = std::is_class<T>;
template <typename T> struct R {};
struct Type0 {};
struct Type1 {};
void run() {
{
using T = ml::f<ml::NoneOf<ml::F<Predicate>, ml::F<R>>, int, char, Type0>;
static_assert(std::is_same<T, R<ml::Bool<false>>>::value,
"NoneOf with a non-empty pack 1");
}
{
using T = ml::f<ml::NoneOf<ml::F<Predicate>, ml::F<R>>>;
static_assert(std::is_same<T, R<ml::Bool<true>>>::value,
"NoneOf with empty pack");
}
}
} // namespace NoneOfTest
| 28.380952 | 78 | 0.597315 | changjurhee |
9251f04cb4db1dc0d87200a90ab7c19d98b94fac | 2,281 | cc | C++ | content/browser/attribution_reporting/storable_source.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/attribution_reporting/storable_source.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-03-13T10:32:53.000Z | 2019-03-13T11:05:30.000Z | content/browser/attribution_reporting/storable_source.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/attribution_reporting/storable_source.h"
#include "base/check_op.h"
#include "net/base/schemeful_site.h"
namespace content {
StorableSource::StorableSource(uint64_t impression_data,
url::Origin impression_origin,
url::Origin conversion_origin,
url::Origin reporting_origin,
base::Time impression_time,
base::Time expiry_time,
SourceType source_type,
int64_t priority,
AttributionLogic attribution_logic,
absl::optional<Id> impression_id)
: impression_data_(impression_data),
impression_origin_(std::move(impression_origin)),
conversion_origin_(std::move(conversion_origin)),
reporting_origin_(std::move(reporting_origin)),
impression_time_(impression_time),
expiry_time_(expiry_time),
source_type_(source_type),
priority_(priority),
attribution_logic_(attribution_logic),
impression_id_(impression_id) {
// 30 days is the max allowed expiry for an impression.
DCHECK_GE(base::Days(30), expiry_time - impression_time);
// The impression must expire strictly after it occurred.
DCHECK_GT(expiry_time, impression_time);
DCHECK(!impression_origin.opaque());
DCHECK(!reporting_origin.opaque());
DCHECK(!conversion_origin.opaque());
}
StorableSource::StorableSource(const StorableSource& other) = default;
StorableSource& StorableSource::operator=(const StorableSource& other) =
default;
StorableSource::StorableSource(StorableSource&& other) = default;
StorableSource& StorableSource::operator=(StorableSource&& other) = default;
StorableSource::~StorableSource() = default;
net::SchemefulSite StorableSource::ConversionDestination() const {
return net::SchemefulSite(conversion_origin_);
}
net::SchemefulSite StorableSource::ImpressionSite() const {
return net::SchemefulSite(impression_origin_);
}
} // namespace content
| 37.393443 | 76 | 0.682595 | Yannic |
9254c035c212013bc6916d0a329190d8981cec1a | 1,287 | cpp | C++ | Flims 2019/Flims Contest Friday/Icebreaker/main.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | Flims 2019/Flims Contest Friday/Icebreaker/main.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | Flims 2019/Flims Contest Friday/Icebreaker/main.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define int long long
using namespace std;
signed main() {
// Turn off synchronization between cin/cout and scanf/printf
ios_base::sync_with_stdio(false);
// Disable automatic flush of cout when reading from cin cin.tie(0);
cin.tie(0);
int n, groups;
cin >> n >> groups;
vector<vector<bool>>con(n, vector<bool>(n));
vector<vector<int>>E(n);
for (int i = 0; i < n; ++i) {
int k;
cin >> k;
for (int j = 0; j < k; ++j) {
int x;
cin >> x;
con[i][x]=true;
con[x][i]=true;
E[x].push_back(i);
}
}
vector<int>first, second;
vector<int>cols(n,-1);
vector<vector<int>>g(groups);
for (int i = 0; i < n; ++i) {
vector<bool>used(groups);
for (int w : E[i]) {
if(cols[w]==-1){ continue;}
used[cols[w]]=true;
}
for (int j = 0; j < groups; ++j) {
if(used[j]){ continue;}
cols[i]=j;
g[j].push_back(i);
break;
}
}
for (int i = 0; i < groups; ++i) {
cout << g[i].size() << " ";
for (int j = 0; j < g[i].size(); ++j) {
cout << g[i][j] << " ";
}
cout << "\n";
}
} | 25.235294 | 72 | 0.440559 | wdjpng |
92553a8f958ed44a6481a91f1184e2bc0f73d132 | 3,014 | cpp | C++ | lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp | jessicadavies-intel/llvm | 4236bbba4c562a1355e75fa6d237b7c6b15a3193 | [
"Apache-2.0"
] | 1 | 2022-01-06T15:44:48.000Z | 2022-01-06T15:44:48.000Z | lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp | jessicadavies-intel/llvm | 4236bbba4c562a1355e75fa6d237b7c6b15a3193 | [
"Apache-2.0"
] | 2 | 2019-06-27T00:36:28.000Z | 2021-06-29T20:05:03.000Z | lldb/source/Plugins/Process/Utility/RegisterContextPOSIX_arm.cpp | kbobrovs/llvm | b57c6bf3b16e6d3f6c052ba9ba3616a24e0beae5 | [
"Apache-2.0"
] | null | null | null | //===-- RegisterContextPOSIX_arm.cpp --------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <cerrno>
#include <cstdint>
#include <cstring>
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Endian.h"
#include "lldb/Utility/RegisterValue.h"
#include "lldb/Utility/Scalar.h"
#include "llvm/Support/Compiler.h"
#include "RegisterContextPOSIX_arm.h"
using namespace lldb;
using namespace lldb_private;
bool RegisterContextPOSIX_arm::IsGPR(unsigned reg) {
if (m_register_info_up->GetRegisterSetFromRegisterIndex(reg) ==
RegisterInfoPOSIX_arm::GPRegSet)
return true;
return false;
}
bool RegisterContextPOSIX_arm::IsFPR(unsigned reg) {
if (m_register_info_up->GetRegisterSetFromRegisterIndex(reg) ==
RegisterInfoPOSIX_arm::FPRegSet)
return true;
return false;
}
RegisterContextPOSIX_arm::RegisterContextPOSIX_arm(
lldb_private::Thread &thread,
std::unique_ptr<RegisterInfoPOSIX_arm> register_info)
: lldb_private::RegisterContext(thread, 0),
m_register_info_up(std::move(register_info)) {}
RegisterContextPOSIX_arm::~RegisterContextPOSIX_arm() {}
void RegisterContextPOSIX_arm::Invalidate() {}
void RegisterContextPOSIX_arm::InvalidateAllRegisters() {}
unsigned RegisterContextPOSIX_arm::GetRegisterOffset(unsigned reg) {
return m_register_info_up->GetRegisterInfo()[reg].byte_offset;
}
unsigned RegisterContextPOSIX_arm::GetRegisterSize(unsigned reg) {
return m_register_info_up->GetRegisterInfo()[reg].byte_size;
}
size_t RegisterContextPOSIX_arm::GetRegisterCount() {
return m_register_info_up->GetRegisterCount();
}
size_t RegisterContextPOSIX_arm::GetGPRSize() {
return m_register_info_up->GetGPRSize();
}
const lldb_private::RegisterInfo *RegisterContextPOSIX_arm::GetRegisterInfo() {
// Commonly, this method is overridden and g_register_infos is copied and
// specialized. So, use GetRegisterInfo() rather than g_register_infos in
// this scope.
return m_register_info_up->GetRegisterInfo();
}
const lldb_private::RegisterInfo *
RegisterContextPOSIX_arm::GetRegisterInfoAtIndex(size_t reg) {
if (reg < GetRegisterCount())
return &GetRegisterInfo()[reg];
return nullptr;
}
size_t RegisterContextPOSIX_arm::GetRegisterSetCount() {
return m_register_info_up->GetRegisterSetCount();
}
const lldb_private::RegisterSet *
RegisterContextPOSIX_arm::GetRegisterSet(size_t set) {
return m_register_info_up->GetRegisterSet(set);
}
const char *RegisterContextPOSIX_arm::GetRegisterName(unsigned reg) {
if (reg < GetRegisterCount())
return GetRegisterInfo()[reg].name;
return nullptr;
}
| 30.444444 | 80 | 0.748507 | jessicadavies-intel |
9256d552a8fc7886c210b2b48a985722d598b601 | 666 | hpp | C++ | z/util/regex/rgx.hpp | ZacharyWesterman/zLibraries | cbc6a5f4a6cce7d382906eb1754f627b5df1cc1d | [
"MIT"
] | null | null | null | z/util/regex/rgx.hpp | ZacharyWesterman/zLibraries | cbc6a5f4a6cce7d382906eb1754f627b5df1cc1d | [
"MIT"
] | 12 | 2022-01-09T04:05:56.000Z | 2022-01-16T04:50:52.000Z | z/util/regex/rgx.hpp | ZacharyWesterman/zLibraries | cbc6a5f4a6cce7d382906eb1754f627b5df1cc1d | [
"MIT"
] | 1 | 2021-01-30T01:19:02.000Z | 2021-01-30T01:19:02.000Z | #pragma once
/**
* \file z/util/regex/rgx.hpp
* \namespace z::util::rgx
* \brief Namespace containing all regex rules for the sake of organization.
**/
#include "rules/alpha.hpp"
#include "rules/alnum.hpp"
#include "rules/andlist.hpp"
#include "rules/anything.hpp"
#include "rules/begin.hpp"
#include "rules/boundary.hpp"
#include "rules/character.hpp"
#include "rules/compound.hpp"
#include "rules/digit.hpp"
#include "rules/end.hpp"
#include "rules/lookahead.hpp"
#include "rules/lookbehind.hpp"
#include "rules/newline.hpp"
#include "rules/orlist.hpp"
#include "rules/punct.hpp"
#include "rules/range.hpp"
#include "rules/space.hpp"
#include "rules/word.hpp"
| 25.615385 | 76 | 0.738739 | ZacharyWesterman |
925be2325232508739c27e2f3f2acdb423c2d297 | 517 | cpp | C++ | perm/remoteExec.cpp | cationstudio/arma-3-life-management | e74aa843222e612d7b2435cc9a37d0c515d82b47 | [
"MIT"
] | null | null | null | perm/remoteExec.cpp | cationstudio/arma-3-life-management | e74aa843222e612d7b2435cc9a37d0c515d82b47 | [
"MIT"
] | null | null | null | perm/remoteExec.cpp | cationstudio/arma-3-life-management | e74aa843222e612d7b2435cc9a37d0c515d82b47 | [
"MIT"
] | null | null | null | /*
File: remoteExec.cpp
Author: Julian Bauer (julian.bauer@cationstudio.com)
Description:
Remote exec config file for management system.
*/
class cat_perm_fnc_getInfos {
allowedTargets=2;
};
class cat_perm_fnc_updateRank {
allowedTargets=2;
};
class cat_perm_fnc_getInfosHC {
allowedTargets=HC_Life;
};
class cat_perm_fnc_updateRankHC {
allowedTargets=HC_Life;
};
class cat_perm_fnc_updatePlayer {
allowedTargets=1;
}
class cat_perm_fnc_updatePermDialog {
allowedTargets=1;
} | 20.68 | 56 | 0.750484 | cationstudio |
925ca1c942da4971f72c6c38f301070e283e4934 | 614 | hpp | C++ | include/lsfml/resource_text.hpp | Oberon00/lsfml | c5440216c408234a856e59044addc7e6f6bd99b3 | [
"BSD-2-Clause"
] | 5 | 2015-02-21T23:28:39.000Z | 2017-01-04T10:04:45.000Z | include/lsfml/resource_text.hpp | Oberon00/lsfml | c5440216c408234a856e59044addc7e6f6bd99b3 | [
"BSD-2-Clause"
] | null | null | null | include/lsfml/resource_text.hpp | Oberon00/lsfml | c5440216c408234a856e59044addc7e6f6bd99b3 | [
"BSD-2-Clause"
] | null | null | null | // Part of the LSFML library -- Copyright (c) Christian Neumüller 2015
// This file is subject to the terms of the BSD 2-Clause License.
// See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause
#ifndef LSFML_RESOURCE_TEXT_HPP_INCLUDED
#define LSFML_RESOURCE_TEXT_HPP_INCLUDED
#include <lsfml/resource_media.hpp>
#include <SFML/Graphics/Text.hpp>
namespace lsfml {
using resource_text = resource_media<sf::Text, sf::Font>;
inline void update_resource_media(
sf::Text& s, resource_text::res_ptr const& fnt)
{
s.setFont(*fnt);
}
} // namespace lsfml
#endif // LSFML_RESOURCE_TEXT_HPP_INCLUDED
| 25.583333 | 70 | 0.763844 | Oberon00 |
17827204f3a382c341700dffd4dc3f93a11b042c | 2,031 | cpp | C++ | src/sensors/temperature/TMP006.cpp | waterloop/goose-sensors | 16e56132408724a55a49bca96af2f28c1720fc03 | [
"MIT"
] | null | null | null | src/sensors/temperature/TMP006.cpp | waterloop/goose-sensors | 16e56132408724a55a49bca96af2f28c1720fc03 | [
"MIT"
] | null | null | null | src/sensors/temperature/TMP006.cpp | waterloop/goose-sensors | 16e56132408724a55a49bca96af2f28c1720fc03 | [
"MIT"
] | 4 | 2018-02-06T19:07:09.000Z | 2018-04-07T17:16:19.000Z | #include <math.h>
#include "TMP006.h"
#include "../../register/ByteInvert.h"
using namespace wlp;
TMP006::TMP006(uint8_t address, uint16_t sample_rate)
: m_sample_rate(sample_rate),
m_register(address) {}
bool TMP006::begin() {
m_register.write16(TMP006::CONFIG, TMP006::CFG_MODEON | TMP006::CFG_DRDYEN | m_sample_rate);
auto man_id = byte_invert<uint16_t>(m_register.read16(TMP006::MAN_ID));
auto dev_id = byte_invert<uint16_t>(m_register.read16(TMP006::DEV_ID));
return man_id == TMP006_MAN_ID && dev_id == TMP006_DEV_ID;
}
void TMP006::sleep() {
uint16_t config = m_register.read16(TMP006::CONFIG);
config &= ~TMP006::CFG_MODEON;
m_register.write16(TMP006::CONFIG, config);
}
void TMP006::wake() {
uint16_t config = m_register.read16(TMP006::CONFIG);
config |= TMP006::CFG_MODEON;
m_register.write16(TMP006::CONFIG, config);
}
int16_t TMP006::read_raw_die_temperature() {
auto raw_value = static_cast<int16_t>(byte_invert<uint16_t>(m_register.read16(TMP006::TAMB)));
raw_value >>= 2;
return raw_value;
}
int16_t TMP006::read_raw_voltage() {
return static_cast<int16_t>(byte_invert<uint16_t>(m_register.read16(TMP006::VOBJ)));
}
double TMP006::read_die_temperature() {
return read_raw_die_temperature() * 0.03125;
}
double TMP006::read_obj_temperature() {
double die_temp = read_die_temperature() + 273.15;
double vobj = read_raw_voltage() * 1.5625e-7;
double die_ref_temp = die_temp - TMP006_TREF;
double die_ref_temp_sq = die_ref_temp * die_ref_temp;
double S =
1 +
TMP006_A1 * die_ref_temp +
TMP006_A2 * die_ref_temp_sq;
S *= TMP006_S0 * 1e-14;
double vos =
TMP006_B0 +
TMP006_B1 * die_ref_temp +
TMP006_B2 * die_ref_temp_sq;
double vdiff = vobj - vos;
double f_vobj = vdiff + TMP006_C2 * vdiff * vdiff;
double die_temp_sq = die_temp * die_temp;
double temperature = sqrt(sqrt(die_temp_sq * die_temp_sq + f_vobj / S));
return temperature - 273.15;
}
| 31.246154 | 98 | 0.695224 | waterloop |
17842829d72c556d2d571a1e3b7839b8fd5bb4fd | 3,679 | hxx | C++ | src/freertos_drivers/ti/CC32xxEEPROMFlushFlow.hxx | balazsracz/openmrn | 338f5dcbafeff6d171b2787b291d1904f2c45965 | [
"BSD-2-Clause"
] | 34 | 2015-05-23T03:57:56.000Z | 2022-03-27T03:48:48.000Z | src/freertos_drivers/ti/CC32xxEEPROMFlushFlow.hxx | balazsracz/openmrn | 338f5dcbafeff6d171b2787b291d1904f2c45965 | [
"BSD-2-Clause"
] | 214 | 2015-07-05T05:06:55.000Z | 2022-02-06T14:53:14.000Z | src/freertos_drivers/ti/CC32xxEEPROMFlushFlow.hxx | balazsracz/openmrn | 338f5dcbafeff6d171b2787b291d1904f2c45965 | [
"BSD-2-Clause"
] | 38 | 2015-08-28T05:32:07.000Z | 2021-07-06T16:47:23.000Z | /** \copyright
* Copyright (c) 2016, Balazs Racz
* 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.
*
* 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.
*
* \file CC32xxEEPROMFlushFlow.hxx
* Helper state flow for flushing the CC32xx EEPROM emulation automatically.
*
* @author Balazs Racz
* @date 24 June 2017
*/
#ifndef FREERTOS_DRIVERS_TI_CC32XXEEPROMFLUSHFLOW_HXX_
#define FREERTOS_DRIVERS_TI_CC32XXEEPROMFLUSHFLOW_HXX_
#include "executor/StateFlow.hxx"
extern "C" {
void eeprom_flush();
}
class EepromTimerFlow : public StateFlowBase, protected Atomic
{
public:
EepromTimerFlow(Service* s)
: StateFlowBase(s)
, isWaiting_(0)
, isDirty_(0)
{
start_flow(STATE(test_and_sleep));
}
void wakeup() {
AtomicHolder h(this);
isDirty_ = 1;
if (isWaiting_) {
isWaiting_ = 0;
notify();
}
}
private:
Action test_and_sleep()
{
bool need_sleep = false;
{
AtomicHolder h(this);
if (isDirty_)
{
isDirty_ = 0;
need_sleep = true;
}
else
{
isWaiting_ = 1;
}
}
if (need_sleep)
{
return sleep_and_call(
&timer_, MSEC_TO_NSEC(1000), STATE(test_and_flush));
}
else
{
return wait();
}
}
Action test_and_flush()
{
bool need_sleep = false;
{
AtomicHolder h(this);
if (isDirty_)
{
// we received another write during the sleep. Go back to sleep.
isDirty_ = 0;
need_sleep = true;
}
}
if (need_sleep)
{
return sleep_and_call(
&timer_, MSEC_TO_NSEC(1000), STATE(test_and_flush));
}
eeprom_flush();
return call_immediately(STATE(test_and_sleep));
}
StateFlowTimer timer_{this};
// 1 if the flow is sleeping and needs to be notified to wake up.
unsigned isWaiting_ : 1;
// 1 if we received a notification from the eeprom handler.
unsigned isDirty_ : 1;
};
extern EepromTimerFlow eepromTimerFlow_;
#ifndef SKIP_UPDATED_CALLBACK
extern "C" {
void eeprom_updated_notification() {
eepromTimerFlow_.wakeup();
}
}
#endif
#endif // FREERTOS_DRIVERS_TI_CC32XXEEPROMFLUSHFLOW_HXX_
| 28.51938 | 80 | 0.636586 | balazsracz |
1785ad878ad66144dcdc56bf2f53cbed3e7be01d | 538 | cpp | C++ | campion-era/seif1.cpp/seif1.cpp | GeorgianBadita/algorithmic-problems | 6b260050b7a1768b5e47a1d7d4ef7138a52db210 | [
"MIT"
] | 1 | 2021-07-05T16:32:14.000Z | 2021-07-05T16:32:14.000Z | campion-era/seif1.cpp/seif1.cpp | GeorgianBadita/algorithmic-problems | 6b260050b7a1768b5e47a1d7d4ef7138a52db210 | [
"MIT"
] | null | null | null | campion-era/seif1.cpp/seif1.cpp | GeorgianBadita/algorithmic-problems | 6b260050b7a1768b5e47a1d7d4ef7138a52db210 | [
"MIT"
] | 1 | 2021-05-14T15:40:09.000Z | 2021-05-14T15:40:09.000Z | #include<fstream>
using namespace std;
int a[101][101],v[1001];
int main()
{
ifstream f("seif1.in");
ofstream g("seif1.out");
int n,k,i,j,x=0,p=0,l=1;
f>>n>>k;
k=k%(n*2);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
f>>a[i][j];
for(i=1;i<=n/2;i++) x++,v[x]=a[i][n/2-i+1];
for(i=1;i<=n/2;i++) x++,v[x]=a[n/2+i][i];
for(i=1;i<=n/2;i++) x++,v[x]=a[n-i+1][n/2+i];
for(i=1;i<=n/2;i++) x++,v[x]=a[n/2-i+1][n-i+1];
for(i=k+1;i<=x;i++) g<<v[i]<<' ';
for(i=1;i<=k;i++) g<<v[i]<<' ';
return 0;
}
| 24.454545 | 51 | 0.427509 | GeorgianBadita |
1787ed14d3818441f867030aca7213c26cfd5fb6 | 2,634 | hpp | C++ | Transport-Guide-CPP/Guide/Route/RoutesMap.hpp | Cheshulko/Transport-Guide-CPP | 84d8e447ecf45d1f6f7598ef773b70d6611413e8 | [
"MIT"
] | null | null | null | Transport-Guide-CPP/Guide/Route/RoutesMap.hpp | Cheshulko/Transport-Guide-CPP | 84d8e447ecf45d1f6f7598ef773b70d6611413e8 | [
"MIT"
] | null | null | null | Transport-Guide-CPP/Guide/Route/RoutesMap.hpp | Cheshulko/Transport-Guide-CPP | 84d8e447ecf45d1f6f7598ef773b70d6611413e8 | [
"MIT"
] | null | null | null | //
// RoutesMap.hpp
// transportnyi-spravochnik
//
// Created by Mykyta Cheshulko on 02.07.2020.
// Copyright © 2020 Mykyta Cheshulko. All rights reserved.
//
#ifndef RoutesMap_hpp
#define RoutesMap_hpp
#include "Route.hpp"
#include "Stop.hpp"
#include "DirectedWeightedGraph.hpp"
#include "Router.hpp"
#include <optional>
#include <set>
#include <unordered_map>
#include <map>
#include <tuple>
namespace guide::route {
class RoutesMap
{
public:
class Settings final
{
public:
Settings(size_t busWaitTime, size_t busVelocity);
size_t GetBusWaitTime() const;
size_t GetBusVelocity() const;
private:
size_t busWaitTime_;
size_t busVelocity_;
};
public:
RoutesMap();
RoutesMap(std::vector<std::shared_ptr<Route>> routes, std::vector<std::shared_ptr<Stop>> stops);
bool AddStop(std::shared_ptr<Stop> stop);
bool AddRoute(std::shared_ptr<Route> route);
std::optional<std::weak_ptr<Stop>> FindStop(const std::string& name) const;
std::optional<std::weak_ptr<Stop>> FindStop(std::shared_ptr<Stop> stop) const;
std::optional<std::weak_ptr<Route>> FindRoute(const std::string& name) const;
void SetSettings(std::shared_ptr<Settings> settings_);
size_t GetStopsCount() const;
const Settings& GetSettings() const;
std::optional<size_t> GetStopId(std::shared_ptr<Stop> stop) const;
std::optional<std::weak_ptr<Stop>> GetStop(size_t stopId) const;
std::optional<std::weak_ptr<Route>> GetRoute(size_t routeId) const;
std::optional<
std::vector<std::tuple<
std::weak_ptr<Stop>, /* From stop */
std::weak_ptr<Stop>, /* To stop */
double, /* Time, minutes */
std::weak_ptr<Route>, /* Using route */
size_t /* Stops count */
>>> GetOptimalRoute(std::shared_ptr<Stop> fromStop, std::shared_ptr<Stop> toStop);
void BuildGraph();
private:
std::shared_ptr<Settings> settings_;
private:
std::set<std::shared_ptr<Route>, Route::SharedComparator> routes_;
std::set<std::shared_ptr<Stop>, Stop::SharedComparator> stops_;
private: /* These for graph */
std::map<
std::weak_ptr<Stop>,
size_t,
Stop::WeakComparator
> stopsId_;
std::vector<std::weak_ptr<Stop>> idStops_;
std::vector<std::weak_ptr<Route>> idRoutes_;
private:
std::unique_ptr<structure::graph::Router<double>> router_;
std::unique_ptr<structure::graph::DirectedWeightedGraph<double>> graph_;
};
}
#endif /* RoutesMap_hpp */
| 27.4375 | 100 | 0.645406 | Cheshulko |
178a079ef29b48b91917e258e8cfed96fc43ff03 | 9,323 | cpp | C++ | src/GafferImage/VectorWarp.cpp | Tuftux/gaffer | 5acaf7cbfadbae841dc06854121ca85dcc5c338c | [
"BSD-3-Clause"
] | 31 | 2017-07-10T10:02:07.000Z | 2022-02-08T13:54:14.000Z | src/GafferImage/VectorWarp.cpp | Tuftux/gaffer | 5acaf7cbfadbae841dc06854121ca85dcc5c338c | [
"BSD-3-Clause"
] | null | null | null | src/GafferImage/VectorWarp.cpp | Tuftux/gaffer | 5acaf7cbfadbae841dc06854121ca85dcc5c338c | [
"BSD-3-Clause"
] | 3 | 2017-11-04T15:30:11.000Z | 2018-09-25T18:36:11.000Z | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2016, Image Engine Design Inc. 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 Image Engine Design nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "GafferImage/VectorWarp.h"
#include "GafferImage/FilterAlgo.h"
#include "GafferImage/ImageAlgo.h"
#include "Gaffer/Context.h"
#include "OpenEXR/ImathFun.h"
#include <cmath>
using namespace Imath;
using namespace IECore;
using namespace Gaffer;
using namespace GafferImage;
//////////////////////////////////////////////////////////////////////////
// Engine implementation
//////////////////////////////////////////////////////////////////////////
struct VectorWarp::Engine : public Warp::Engine
{
Engine( const Box2i &displayWindow, const Box2i &tileBound, const Box2i &validTileBound, ConstFloatVectorDataPtr xData, ConstFloatVectorDataPtr yData, ConstFloatVectorDataPtr aData, VectorMode vectorMode, VectorUnits vectorUnits )
: m_displayWindow( displayWindow ),
m_tileBound( tileBound ),
m_xData( xData ),
m_yData( yData ),
m_aData( aData ),
m_x( xData->readable() ),
m_y( yData->readable() ),
m_a( aData->readable() ),
m_vectorMode( vectorMode ),
m_vectorUnits( vectorUnits )
{
}
Imath::V2f inputPixel( const Imath::V2f &outputPixel ) const override
{
const V2i outputPixelI( (int)floorf( outputPixel.x ), (int)floorf( outputPixel.y ) );
const size_t i = BufferAlgo::index( outputPixelI, m_tileBound );
if( m_a[i] == 0.0f )
{
return black;
}
else
{
V2f result = m_vectorMode == Relative ? outputPixel : V2f( 0.0f );
result += m_vectorUnits == Screen ?
screenToPixel( V2f( m_x[i], m_y[i] ) ) :
V2f( m_x[i], m_y[i] );
if( !std::isfinite( result[0] ) || !std::isfinite( result[1] ) )
{
return black;
}
return result;
}
}
private :
inline V2f screenToPixel( const V2f &vector ) const
{
return V2f(
lerp<float>( m_displayWindow.min.x, m_displayWindow.max.x, vector.x ),
lerp<float>( m_displayWindow.min.y, m_displayWindow.max.y, vector.y )
);
}
const Box2i m_displayWindow;
const Box2i m_tileBound;
ConstFloatVectorDataPtr m_xData;
ConstFloatVectorDataPtr m_yData;
ConstFloatVectorDataPtr m_aData;
const std::vector<float> &m_x;
const std::vector<float> &m_y;
const std::vector<float> &m_a;
const VectorMode m_vectorMode;
const VectorUnits m_vectorUnits;
};
//////////////////////////////////////////////////////////////////////////
// VectorWarp implementation
//////////////////////////////////////////////////////////////////////////
GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( VectorWarp );
size_t VectorWarp::g_firstPlugIndex = 0;
VectorWarp::VectorWarp( const std::string &name )
: Warp( name )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new ImagePlug( "vector" ) );
addChild( new IntPlug( "vectorMode", Gaffer::Plug::In, (int)Absolute, (int)Relative, (int)Absolute ) );
addChild( new IntPlug( "vectorUnits", Gaffer::Plug::In, (int)Screen, (int)Pixels, (int)Screen ) );
outPlug()->formatPlug()->setInput( vectorPlug()->formatPlug() );
outPlug()->dataWindowPlug()->setInput( vectorPlug()->dataWindowPlug() );
}
VectorWarp::~VectorWarp()
{
}
ImagePlug *VectorWarp::vectorPlug()
{
return getChild<ImagePlug>( g_firstPlugIndex );
}
const ImagePlug *VectorWarp::vectorPlug() const
{
return getChild<ImagePlug>( g_firstPlugIndex );
}
IntPlug *VectorWarp::vectorModePlug()
{
return getChild<IntPlug>( g_firstPlugIndex + 1 );
}
const IntPlug *VectorWarp::vectorModePlug() const
{
return getChild<IntPlug>( g_firstPlugIndex + 1 );
}
IntPlug *VectorWarp::vectorUnitsPlug()
{
return getChild<IntPlug>( g_firstPlugIndex + 2 );
}
const IntPlug *VectorWarp::vectorUnitsPlug() const
{
return getChild<IntPlug>( g_firstPlugIndex + 2 );
}
void VectorWarp::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
Warp::affects( input, outputs );
if( input == vectorPlug()->deepPlug() )
{
outputs.push_back( outPlug()->deepPlug() );
}
}
bool VectorWarp::affectsEngine( const Gaffer::Plug *input ) const
{
return
Warp::affectsEngine( input ) ||
input == inPlug()->formatPlug() ||
input == vectorPlug()->channelNamesPlug() ||
input == vectorPlug()->channelDataPlug() ||
input == vectorModePlug() ||
input == vectorUnitsPlug();
}
void VectorWarp::hashEngine( const Imath::V2i &tileOrigin, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
Warp::hashEngine( tileOrigin, context, h );
h.append( tileOrigin );
ConstStringVectorDataPtr channelNames;
{
ImagePlug::GlobalScope c( context );
channelNames = vectorPlug()->channelNamesPlug()->getValue();
vectorPlug()->dataWindowPlug()->hash( h );
inPlug()->formatPlug()->hash( h );
}
ImagePlug::ChannelDataScope channelDataScope( context );
if( ImageAlgo::channelExists( channelNames->readable(), "R" ) )
{
channelDataScope.setChannelName( "R" );
vectorPlug()->channelDataPlug()->hash( h );
}
if( ImageAlgo::channelExists( channelNames->readable(), "G" ) )
{
channelDataScope.setChannelName( "G" );
vectorPlug()->channelDataPlug()->hash( h );
}
if( ImageAlgo::channelExists( channelNames->readable(), "A" ) )
{
channelDataScope.setChannelName( "A" );
vectorPlug()->channelDataPlug()->hash( h );
}
vectorModePlug()->hash( h );
vectorUnitsPlug()->hash( h );
}
const Warp::Engine *VectorWarp::computeEngine( const Imath::V2i &tileOrigin, const Gaffer::Context *context ) const
{
const Box2i tileBound( tileOrigin, tileOrigin + V2i( ImagePlug::tileSize() ) );
Box2i validTileBound;
ConstStringVectorDataPtr channelNames;
Box2i displayWindow;
{
ImagePlug::GlobalScope c( context );
validTileBound = BufferAlgo::intersection( tileBound, vectorPlug()->dataWindowPlug()->getValue() );
channelNames = vectorPlug()->channelNamesPlug()->getValue();
displayWindow = inPlug()->formatPlug()->getValue().getDisplayWindow();
}
ImagePlug::ChannelDataScope channelDataScope( context );
ConstFloatVectorDataPtr xData = ImagePlug::blackTile();
if( ImageAlgo::channelExists( channelNames->readable(), "R" ) )
{
channelDataScope.setChannelName( "R" );
xData = vectorPlug()->channelDataPlug()->getValue();
}
ConstFloatVectorDataPtr yData = ImagePlug::blackTile();
if( ImageAlgo::channelExists( channelNames->readable(), "G" ) )
{
channelDataScope.setChannelName( "G" );
yData = vectorPlug()->channelDataPlug()->getValue();
}
ConstFloatVectorDataPtr aData = ImagePlug::whiteTile();
if( ImageAlgo::channelExists( channelNames->readable(), "A" ) )
{
channelDataScope.setChannelName( "A" );
aData = vectorPlug()->channelDataPlug()->getValue();
}
if( xData->readable().size() != (unsigned int)ImagePlug::tilePixels() ||
yData->readable().size() != (unsigned int)ImagePlug::tilePixels() ||
aData->readable().size() != (unsigned int)ImagePlug::tilePixels() )
{
throw IECore::Exception( "VectorWarp::computeEngine : Bad channel data size on vector plug. Maybe it's deep?" );
}
return new Engine(
displayWindow,
tileBound,
validTileBound,
xData,
yData,
aData,
(VectorMode)vectorModePlug()->getValue(),
(VectorUnits)vectorUnitsPlug()->getValue()
);
}
void VectorWarp::hashDeep( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
FlatImageProcessor::hashDeep( parent, context, h );
h.append( vectorPlug()->deepPlug()->hash() );
}
bool VectorWarp::computeDeep( const Gaffer::Context *context, const ImagePlug *parent ) const
{
if( vectorPlug()->deepPlug()->getValue() )
{
throw IECore::Exception( "Deep data not supported in input \"vector\"" );
}
return false;
}
| 29.785942 | 231 | 0.675963 | Tuftux |
178c38f61c269ad1478fec9e3d90deaffab6112c | 4,329 | cpp | C++ | data/train/cpp/e2cec176136b0c4a05a60447da174f8d480243b0dumps.cpp | harshp8l/deep-learning-lang-detection | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | [
"MIT"
] | 84 | 2017-10-25T15:49:21.000Z | 2021-11-28T21:25:54.000Z | data/train/cpp/e2cec176136b0c4a05a60447da174f8d480243b0dumps.cpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 5 | 2018-03-29T11:50:46.000Z | 2021-04-26T13:33:18.000Z | data/train/cpp/e2cec176136b0c4a05a60447da174f8d480243b0dumps.cpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 24 | 2017-11-22T08:31:00.000Z | 2022-03-27T01:22:31.000Z | #include "dumps.h"
#include "solver.h"
dump_manager_class :: dump_manager_class()
{
}
dump_manager_class :: ~dump_manager_class()
{
for (int i=0; i<dumpN; i++) delete (dump_slaves[i]);
free(dump_slaves);
}
dump_manager_class :: dump_manager_class(FILE* optfid)
{
dumpN = load_namedint(optfid, "DUMPS_N", true, 0);
dump_slaves = (dump_type_empty_class**)malloc_ch(sizeof(dump_type_empty_class*)*dumpN);
for (int i=0; i<dumpN; i++)
{
char cbuf[100];
load_namednumstringn(optfid, "DUMPTYPE", cbuf, i, 100, false);
if (strcmp(cbuf, "full")==0) dump_slaves[i] = new dump_type_full_class (optfid,i);
else if (strcmp(cbuf, "maxI")==0) dump_slaves[i] = new dump_type_maxI_class (optfid,i);
else if (strcmp(cbuf, "flux")==0) dump_slaves[i] = new dump_type_flux_class (optfid,i);
else if (strcmp(cbuf, "ysection")==0) dump_slaves[i] = new dump_type_ysection_class (optfid,i);
else if (strcmp(cbuf, "ysection_maxI")==0) dump_slaves[i] = new dump_type_ysection_maxI_class (optfid,i);
else if (strcmp(cbuf, "ysection_flux")==0) dump_slaves[i] = new dump_type_ysection_flux_class (optfid,i);
else if (strcmp(cbuf, "plasma_full")==0) dump_slaves[i] = new dump_type_full_plasma_class (optfid,i);
else if (strcmp(cbuf, "plasma_max")==0) dump_slaves[i] = new dump_type_plasma_max_class (optfid,i);
else if (strcmp(cbuf, "plasma_ysection")==0) dump_slaves[i] = new dump_type_ysection_plasma_class (optfid,i);
else if (strcmp(cbuf, "plasma_ysection_max")==0) dump_slaves[i] = new dump_type_ysection_plasma_max_class (optfid,i);
else if (strcmp(cbuf, "youngy")==0) dump_slaves[i] = new dump_type_youngy_class(optfid, i);
else if (strcmp(cbuf, "fluxk") ==0) dump_slaves[i] = new dump_type_fluxk_class(optfid, i);
else if (strcmp(cbuf, "ysectionk")==0) dump_slaves[i] = new dump_type_ysectionk_class(optfid,i);
else if (strcmp(cbuf, "field_axis") ==0) dump_slaves[i] = new dump_type_field_axis_class(optfid,i);
else if (strcmp(cbuf, "plasma_axis")==0) dump_slaves[i] = new dump_type_plasma_axis_class(optfid,i);
else if (strcmp(cbuf, "Z_axis")==0) dump_slaves[i] = new dump_type_Z_axis_class(optfid,i);
else if (strcmp(cbuf, "average_spectrum")==0) dump_slaves[i] = new dump_type_average_spectrum_class(optfid,i);
else if (strcmp(cbuf, "duration")==0) dump_slaves[i] = new dump_type_duration_class(optfid, i);
else throw "dump_manager_class :: dump_manager_class(FILE* fid) >>> Error! Unknown dump type specified! Revise DUMPTYPE values";
}
}
void dump_manager_class :: dump()
{
if (ISMASTER) printf("\nDumping (n_Z=%d, Z=%f)...", n_Z, CURRENT_Z);
for (int i=0; i<dumpN; i++) dump_slaves[i]->dump_noflush();
if (ISMASTER) printf("Done.");
}
void create_wfilter(f_complex* wfilter, const char* name)
{
//TODO: Other filters
if (strncmp(name, "longpass",8)==0) {float_type lambda=(float_type)atof(name+8); create_longpass_filter(wfilter,lambda);}
else if (strncmp(name, "lp",2)==0) {float_type lambda=(float_type)atof(name+2); create_longpass_filter(wfilter,lambda);}
else if (strncmp(name, "shortpass",9)==0) {float_type lambda=(float_type)atof(name+9); create_shortpass_filter(wfilter,lambda);}
else if (strncmp(name, "sp",2)==0) {float_type lambda=(float_type)atof(name+2); create_shortpass_filter(wfilter,lambda);}
else if (strncmp(name, "NO",2)==0) {for (int nw=0; nw<N_T; nw++) wfilter[nw]=1.0; }
else if (strncmp(name, "file_",5)==0) {load_spectrum_fromfile(wfilter, OMEGA, N_T, name+5, "text_lambdanm");}
else throw "create_wfilter: Unknown filter shape!";
}
void create_longpass_filter(f_complex* wfilter, float_type lambda)
{
float_type omega = 2*M_PI*LIGHT_VELOCITY/lambda;
for (int nw=0; nw<N_T; nw++) if (OMEGA[nw]<omega) wfilter[nw]=1.0; else wfilter[nw]=0.0;
}
void create_shortpass_filter(f_complex* wfilter, float_type lambda)
{
float_type omega = 2*M_PI*LIGHT_VELOCITY/lambda;
for (int nw=0; nw<N_T; nw++) if (OMEGA[nw]>omega) wfilter[nw]=1.0; else wfilter[nw]=0.0;
}
void create_filter_fromfile(f_complex* wfilter, char* filename)
{
FILE* fid = fopen(filename, "rt");
}
| 50.929412 | 131 | 0.675445 | harshp8l |
179080c68c15949a425f9f9180208acc3a9785c0 | 9,988 | cxx | C++ | CORRFW/AliCFAcceptanceCuts.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 114 | 2017-03-03T09:12:23.000Z | 2022-03-03T20:29:42.000Z | CORRFW/AliCFAcceptanceCuts.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 19,637 | 2017-01-16T12:34:41.000Z | 2022-03-31T22:02:40.000Z | CORRFW/AliCFAcceptanceCuts.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 1,021 | 2016-07-14T22:41:16.000Z | 2022-03-31T05:15:51.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////
// ---- CORRECTION FRAMEWORK ----
// AliCFAcceptanceCuts implementation
// Class to cut on the number of AliTrackReference's
// for each detector
///////////////////////////////////////////////////////////////////////////
// author : R. Vernet (renaud.vernet@cern.ch)
///////////////////////////////////////////////////////////////////////////
#include "AliLog.h"
#include "AliMCParticle.h"
#include "AliCFAcceptanceCuts.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TList.h"
#include "TBits.h"
ClassImp(AliCFAcceptanceCuts)
//______________________________
AliCFAcceptanceCuts::AliCFAcceptanceCuts() :
AliCFCutBase(),
fMCInfo(0x0),
fMinNHitITS(0),
fMinNHitTPC(0),
fMinNHitTRD(0),
fMinNHitTOF(0),
fMinNHitMUON(0),
fhCutStatistics(0x0),
fhCutCorrelation(0x0),
fBitmap(new TBits(0))
{
//
//ctor
//
for (int i=0; i<kNCuts; i++) for (int j=0; j<kNStepQA; j++) fhQA[i][j]=0x0;
}
//______________________________
AliCFAcceptanceCuts::AliCFAcceptanceCuts(const Char_t* name, const Char_t* title) :
AliCFCutBase(name,title),
fMCInfo(0x0),
fMinNHitITS(0),
fMinNHitTPC(0),
fMinNHitTRD(0),
fMinNHitTOF(0),
fMinNHitMUON(0),
fhCutStatistics(0x0),
fhCutCorrelation(0x0),
fBitmap(new TBits(0))
{
//
//ctor
//
for (int i=0; i<kNCuts; i++) for (int j=0; j<kNStepQA; j++) fhQA[i][j]=0x0;
}
//______________________________
AliCFAcceptanceCuts::AliCFAcceptanceCuts(const AliCFAcceptanceCuts& c) :
AliCFCutBase(c),
fMCInfo(c.fMCInfo),
fMinNHitITS(c.fMinNHitITS),
fMinNHitTPC(c.fMinNHitTPC),
fMinNHitTRD(c.fMinNHitTRD),
fMinNHitTOF(c.fMinNHitTOF),
fMinNHitMUON(c.fMinNHitMUON),
fhCutStatistics(c.fhCutStatistics),
fhCutCorrelation(c.fhCutCorrelation),
fBitmap(c.fBitmap)
{
//
//copy ctor
//
for (int i=0; i<kNCuts; i++) for (int j=0; j<kNStepQA; j++) fhQA[i][j]=c.fhQA[i][j];
}
//______________________________
AliCFAcceptanceCuts& AliCFAcceptanceCuts::operator=(const AliCFAcceptanceCuts& c)
{
//
// Assignment operator
//
if (this != &c) {
AliCFCutBase::operator=(c) ;
fMCInfo=c.fMCInfo;
fMinNHitITS=c.fMinNHitITS;
fMinNHitTPC=c.fMinNHitTPC;
fMinNHitTRD=c.fMinNHitTRD;
fMinNHitTOF=c.fMinNHitTOF;
fMinNHitMUON=c.fMinNHitMUON;
fhCutStatistics = c.fhCutStatistics ;
fhCutCorrelation = c.fhCutCorrelation ;
fBitmap = c.fBitmap ;
for (int i=0; i<kNCuts; i++) for (int j=0; j<kNStepQA; j++) fhQA[i][j]=c.fhQA[i][j];
}
return *this ;
}
//______________________________________________________________
Bool_t AliCFAcceptanceCuts::IsSelected(TObject *obj) {
//
// check if selections on 'obj' are passed
// 'obj' must be an AliMCParticle
//
SelectionBitMap(obj);
if (fIsQAOn) FillHistograms(obj,kFALSE);
for (UInt_t icut=0; icut<fBitmap->GetNbits(); icut++)
if (!fBitmap->TestBitNumber(icut)) return kFALSE ;
if (fIsQAOn) FillHistograms(obj,kTRUE);
return kTRUE;
}
//______________________________
void AliCFAcceptanceCuts::SelectionBitMap(TObject* obj) {
//
// checks the number of track references associated to 'obj'
// 'obj' must be an AliMCParticle
//
for (UInt_t i=0; i<kNCuts; i++) fBitmap->SetBitNumber(i,kFALSE);
if (!obj) return;
TString className(obj->ClassName());
if (className.CompareTo("AliMCParticle") != 0) {
AliError("obj must point to an AliMCParticle !");
return ;
}
AliMCParticle * part = dynamic_cast<AliMCParticle*>(obj);
if(!part) return ;
Int_t nHitsITS=0, nHitsTPC=0, nHitsTRD=0, nHitsTOF=0, nHitsMUON=0 ;
for (Int_t iTrackRef=0; iTrackRef<part->GetNumberOfTrackReferences(); iTrackRef++) {
AliTrackReference * trackRef = part->GetTrackReference(iTrackRef);
if(trackRef){
Int_t detectorId = trackRef->DetectorId();
switch(detectorId) {
case AliTrackReference::kITS : nHitsITS++ ; break ;
case AliTrackReference::kTPC : nHitsTPC++ ; break ;
case AliTrackReference::kTRD : nHitsTRD++ ; break ;
case AliTrackReference::kTOF : nHitsTOF++ ; break ;
case AliTrackReference::kMUON : nHitsMUON++ ; break ;
default : break ;
}
}
}
Int_t iCutBit = 0;
if (nHitsITS >= fMinNHitITS ) fBitmap->SetBitNumber(iCutBit,kTRUE);
iCutBit++;
if (nHitsTPC >= fMinNHitTPC ) fBitmap->SetBitNumber(iCutBit,kTRUE);
iCutBit++;
if (nHitsTRD >= fMinNHitTRD ) fBitmap->SetBitNumber(iCutBit,kTRUE);
iCutBit++;
if (nHitsTOF >= fMinNHitTOF ) fBitmap->SetBitNumber(iCutBit,kTRUE);
iCutBit++;
if (nHitsMUON >= fMinNHitMUON) fBitmap->SetBitNumber(iCutBit,kTRUE);
}
void AliCFAcceptanceCuts::SetMCEventInfo(const TObject* mcInfo) {
//
// Sets pointer to MC event information (AliMCEvent)
//
if (!mcInfo) {
AliError("Pointer to AliMCEvent !");
return;
}
TString className(mcInfo->ClassName());
if (className.CompareTo("AliMCEvent") != 0) {
AliError("argument must point to an AliMCEvent !");
return ;
}
fMCInfo = (AliMCEvent*) mcInfo ;
}
//__________________________________________________________________________________
void AliCFAcceptanceCuts::AddQAHistograms(TList *qaList) {
//
// saves the histograms in a TList
//
DefineHistograms();
qaList->Add(fhCutStatistics);
qaList->Add(fhCutCorrelation);
for (Int_t j=0; j<kNStepQA; j++) {
for(Int_t i=0; i<kNCuts; i++)
qaList->Add(fhQA[i][j]);
}
}
//__________________________________________________________________________________
void AliCFAcceptanceCuts::DefineHistograms() {
//
// histograms for cut variables, cut statistics and cut correlations
//
Int_t color = 2;
// book cut statistics and cut correlation histograms
fhCutStatistics = new TH1F(Form("%s_cut_statistics",GetName()),"",kNCuts,0.5,kNCuts+0.5);
fhCutStatistics->SetLineWidth(2);
int k = 1;
fhCutStatistics->GetXaxis()->SetBinLabel(k,"hits ITS") ; k++;
fhCutStatistics->GetXaxis()->SetBinLabel(k,"hits TPC") ; k++;
fhCutStatistics->GetXaxis()->SetBinLabel(k,"hits TRD") ; k++;
fhCutStatistics->GetXaxis()->SetBinLabel(k,"hits TOF") ; k++;
fhCutStatistics->GetXaxis()->SetBinLabel(k,"hits MUON"); k++;
fhCutCorrelation = new TH2F(Form("%s_cut_correlation",GetName()),"",kNCuts,0.5,kNCuts+0.5,kNCuts,0.5,kNCuts+0.5);
fhCutCorrelation->SetLineWidth(2);
for (k=1; k<=kNCuts; k++) {
fhCutCorrelation->GetXaxis()->SetBinLabel(k,fhCutStatistics->GetXaxis()->GetBinLabel(k));
fhCutCorrelation->GetYaxis()->SetBinLabel(k,fhCutStatistics->GetXaxis()->GetBinLabel(k));
}
Char_t str[5];
for (int i=0; i<kNStepQA; i++) {
if (i==0) snprintf(str,5," ");
else snprintf(str,5,"_cut");
fhQA[kCutHitsITS] [i] = new TH1F(Form("%s_HitsITS%s" ,GetName(),str),"",10,0,10);
fhQA[kCutHitsTPC] [i] = new TH1F(Form("%s_HitsTPC%s" ,GetName(),str),"",5,0,5);
fhQA[kCutHitsTRD] [i] = new TH1F(Form("%s_HitsTRD%s" ,GetName(),str),"",20,0,20);
fhQA[kCutHitsTOF] [i] = new TH1F(Form("%s_HitsTOF%s" ,GetName(),str),"",5,0,5);
fhQA[kCutHitsMUON][i] = new TH1F(Form("%s_HitsMUON%s" ,GetName(),str),"",5,0,5);
}
for(Int_t i=0; i<kNCuts; i++) fhQA[i][1]->SetLineColor(color);
}
//__________________________________________________________________________________
void AliCFAcceptanceCuts::FillHistograms(TObject* obj, Bool_t afterCuts)
{
//
// fill the QA histograms
//
AliMCParticle* part = dynamic_cast<AliMCParticle *>(obj);
if (!part) {
AliError("casting failed");
return;
}
Int_t nHitsITS=0, nHitsTPC=0, nHitsTRD=0, nHitsTOF=0, nHitsMUON=0 ;
for (Int_t iTrackRef=0; iTrackRef<part->GetNumberOfTrackReferences(); iTrackRef++) {
AliTrackReference * trackRef = part->GetTrackReference(iTrackRef);
if(trackRef){
Int_t detectorId = trackRef->DetectorId();
switch(detectorId) {
case AliTrackReference::kITS : nHitsITS++ ; break ;
case AliTrackReference::kTPC : nHitsTPC++ ; break ;
case AliTrackReference::kTRD : nHitsTRD++ ; break ;
case AliTrackReference::kTOF : nHitsTOF++ ; break ;
case AliTrackReference::kMUON : nHitsMUON++ ; break ;
default : break ;
}
}
}
fhQA[kCutHitsITS ][afterCuts]->Fill(nHitsITS );
fhQA[kCutHitsTPC ][afterCuts]->Fill(nHitsTPC );
fhQA[kCutHitsTRD ][afterCuts]->Fill(nHitsTRD );
fhQA[kCutHitsTOF ][afterCuts]->Fill(nHitsTOF );
fhQA[kCutHitsMUON][afterCuts]->Fill(nHitsMUON);
// fill cut statistics and cut correlation histograms with information from the bitmap
if (afterCuts) return;
// Number of single cuts in this class
UInt_t ncuts = fBitmap->GetNbits();
for(UInt_t bit=0; bit<ncuts;bit++) {
if (!fBitmap->TestBitNumber(bit)) {
fhCutStatistics->Fill(bit+1);
for (UInt_t bit2=bit; bit2<ncuts;bit2++) {
if (!fBitmap->TestBitNumber(bit2))
fhCutCorrelation->Fill(bit+1,bit2+1);
}
}
}
}
| 32.747541 | 115 | 0.643572 | maroozm |
179109de25b0bdc5132f048f43c72caf09e40f4f | 2,864 | cc | C++ | src/test/libcephfs/multiclient.cc | rpratap-bot/ceph | 9834961a66927ae856935591f2fd51082e2ee484 | [
"MIT"
] | 4 | 2020-04-08T03:42:02.000Z | 2020-10-01T20:34:48.000Z | src/test/libcephfs/multiclient.cc | rpratap-bot/ceph | 9834961a66927ae856935591f2fd51082e2ee484 | [
"MIT"
] | 93 | 2020-03-26T14:29:14.000Z | 2020-11-12T05:54:55.000Z | src/test/libcephfs/multiclient.cc | rpratap-bot/ceph | 9834961a66927ae856935591f2fd51082e2ee484 | [
"MIT"
] | 23 | 2020-03-24T10:28:44.000Z | 2020-09-24T09:42:19.000Z | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "gtest/gtest.h"
#include "include/cephfs/libcephfs.h"
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <sys/xattr.h>
TEST(LibCephFS, MulticlientSimple) {
struct ceph_mount_info *ca, *cb;
ASSERT_EQ(ceph_create(&ca, NULL), 0);
ASSERT_EQ(ceph_conf_read_file(ca, NULL), 0);
ASSERT_EQ(0, ceph_conf_parse_env(ca, NULL));
ASSERT_EQ(ceph_mount(ca, NULL), 0);
ASSERT_EQ(ceph_create(&cb, NULL), 0);
ASSERT_EQ(ceph_conf_read_file(cb, NULL), 0);
ASSERT_EQ(0, ceph_conf_parse_env(cb, NULL));
ASSERT_EQ(ceph_mount(cb, NULL), 0);
char name[20];
snprintf(name, sizeof(name), "foo.%d", getpid());
int fda = ceph_open(ca, name, O_CREAT|O_RDWR, 0644);
ASSERT_LE(0, fda);
int fdb = ceph_open(cb, name, O_CREAT|O_RDWR, 0644);
ASSERT_LE(0, fdb);
char bufa[4] = "foo";
char bufb[4];
for (int i=0; i<10; i++) {
strcpy(bufa, "foo");
ASSERT_EQ((int)sizeof(bufa), ceph_write(ca, fda, bufa, sizeof(bufa), i*6));
ASSERT_EQ((int)sizeof(bufa), ceph_read(cb, fdb, bufb, sizeof(bufa), i*6));
ASSERT_EQ(0, memcmp(bufa, bufb, sizeof(bufa)));
strcpy(bufb, "bar");
ASSERT_EQ((int)sizeof(bufb), ceph_write(cb, fdb, bufb, sizeof(bufb), i*6+3));
ASSERT_EQ((int)sizeof(bufb), ceph_read(ca, fda, bufa, sizeof(bufb), i*6+3));
ASSERT_EQ(0, memcmp(bufa, bufb, sizeof(bufa)));
}
ceph_close(ca, fda);
ceph_close(cb, fdb);
ceph_shutdown(ca);
ceph_shutdown(cb);
}
TEST(LibCephFS, MulticlientHoleEOF) {
struct ceph_mount_info *ca, *cb;
ASSERT_EQ(ceph_create(&ca, NULL), 0);
ASSERT_EQ(ceph_conf_read_file(ca, NULL), 0);
ASSERT_EQ(0, ceph_conf_parse_env(ca, NULL));
ASSERT_EQ(ceph_mount(ca, NULL), 0);
ASSERT_EQ(ceph_create(&cb, NULL), 0);
ASSERT_EQ(ceph_conf_read_file(cb, NULL), 0);
ASSERT_EQ(0, ceph_conf_parse_env(cb, NULL));
ASSERT_EQ(ceph_mount(cb, NULL), 0);
char name[20];
snprintf(name, sizeof(name), "foo.%d", getpid());
int fda = ceph_open(ca, name, O_CREAT|O_RDWR, 0644);
ASSERT_LE(0, fda);
int fdb = ceph_open(cb, name, O_CREAT|O_RDWR, 0644);
ASSERT_LE(0, fdb);
ASSERT_EQ(3, ceph_write(ca, fda, "foo", 3, 0));
ASSERT_EQ(0, ceph_ftruncate(ca, fda, 1000000));
char buf[4];
ASSERT_EQ(2, ceph_read(cb, fdb, buf, sizeof(buf), 1000000-2));
ASSERT_EQ(0, buf[0]);
ASSERT_EQ(0, buf[1]);
ceph_close(ca, fda);
ceph_close(cb, fdb);
ceph_shutdown(ca);
ceph_shutdown(cb);
}
| 29.22449 | 81 | 0.672137 | rpratap-bot |
1792a2942c1006e4f638184028c56fd9ae344738 | 4,557 | cpp | C++ | modules/jlv2_host/host/PortBuffer.cpp | atsushieno/jlv2 | 01dfa44e248f31fed1a076d8351b516da9547a22 | [
"ISC"
] | 11 | 2019-10-29T18:30:56.000Z | 2021-09-15T08:20:53.000Z | modules/jlv2_host/host/PortBuffer.cpp | atsushieno/jlv2 | 01dfa44e248f31fed1a076d8351b516da9547a22 | [
"ISC"
] | 8 | 2019-10-29T12:46:56.000Z | 2022-02-03T14:11:10.000Z | modules/jlv2_host/host/PortBuffer.cpp | atsushieno/jlv2 | 01dfa44e248f31fed1a076d8351b516da9547a22 | [
"ISC"
] | 2 | 2020-10-15T11:41:21.000Z | 2020-11-24T15:21:48.000Z | /*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
namespace jlv2 {
static uint32 portBufferPadSize (uint32 size)
{
return (size + 7) & (~7);
}
PortBuffer::PortBuffer (bool inputPort, uint32 portType, uint32 dataType, uint32 bufferSize)
: type (portType),
capacity (std::max (sizeof (float), (size_t) bufferSize)),
bufferType (dataType),
input (inputPort)
{
data.reset (new uint8 [capacity]);
if (type == PortType::Atom)
{
buffer.atom = (LV2_Atom*) data.get();
}
else if (type == PortType::Event)
{
buffer.event = (LV2_Event_Buffer*) data.get();
}
else if (type == PortType::Audio)
{
buffer.audio = (float*) data.get();
}
else if (type == PortType::Control)
{
buffer.control = (float*) data.get();
}
else
{
// trying to use an unsupported buffer type
jassertfalse;
}
reset();
}
PortBuffer::~PortBuffer()
{
buffer.atom = nullptr;
data.reset();
}
float PortBuffer::getValue() const
{
jassert (type == PortType::Control);
jassert (buffer.control != nullptr);
return *buffer.control;
}
void PortBuffer::setValue (float newValue)
{
jassert (type == PortType::Control);
jassert (buffer.control != nullptr);
*buffer.control = newValue;
}
bool PortBuffer::addEvent (int64 frames, uint32 size, uint32 bodyType, const uint8* data)
{
if (isSequence())
{
if (sizeof(LV2_Atom) + buffer.atom->size + lv2_atom_pad_size(size) > capacity)
return false;
LV2_Atom_Sequence* seq = (LV2_Atom_Sequence*) buffer.atom;
LV2_Atom_Event* ev = (LV2_Atom_Event*) ((uint8*)seq + lv2_atom_total_size (&seq->atom));
ev->time.frames = frames;
ev->body.size = size;
ev->body.type = bodyType;
memcpy (ev + 1, data, size);
buffer.atom->size += sizeof (LV2_Atom_Event) + lv2_atom_pad_size (size);
return true;
}
else if (isEvent())
{
if (buffer.event->capacity - buffer.event->size < sizeof(LV2_Event) + size)
return false;
LV2_Event* ev = (LV2_Event*)(buffer.event->data + buffer.event->size);
ev->frames = static_cast<uint32> (frames);
ev->subframes = 0;
ev->type = type;
ev->size = size;
memcpy ((uint8*)ev + sizeof(LV2_Event), data, size);
buffer.event->size += portBufferPadSize (sizeof (LV2_Event) + size);
buffer.event->event_count += 1;
return true;
}
return false;
}
void PortBuffer::clear()
{
if (isAudio() || isControl())
{
}
else if (isSequence())
{
buffer.atom->size = sizeof (LV2_Atom_Sequence_Body);
}
else if (isEvent())
{
buffer.event->event_count = 0;
buffer.event->size = 0;
}
}
void PortBuffer::reset()
{
if (isAudio())
{
buffer.atom->size = capacity - sizeof (LV2_Atom);
}
else if (isControl())
{
buffer.atom->size = sizeof (float);
buffer.atom->type = bufferType;
}
else if (isSequence())
{
buffer.atom->size = input ? sizeof (LV2_Atom_Sequence_Body)
: capacity - sizeof (LV2_Atom_Sequence_Body);
buffer.atom->type = bufferType;
LV2_Atom_Sequence* seq = (LV2_Atom_Sequence*) buffer.atom;
seq->body.unit = 0;
seq->body.pad = 0;
}
else if (isEvent())
{
buffer.event->capacity = capacity - sizeof (LV2_Event_Buffer);
buffer.event->header_size = sizeof (LV2_Event_Buffer);
buffer.event->stamp_type = LV2_EVENT_AUDIO_STAMP;
buffer.event->event_count = 0;
buffer.event->size = 0;
buffer.event->data = data.get() + sizeof (LV2_Event_Buffer);
}
}
void* PortBuffer::getPortData() const
{
return referenced ? buffer.referred : data.get();
}
}
| 26.964497 | 100 | 0.607417 | atsushieno |
17971ac9b543b8d878817783d80d200a9d41c8f9 | 11,146 | hpp | C++ | CaWE/MapEditor/ObserverPattern.hpp | dns/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 3 | 2020-04-11T13:00:31.000Z | 2020-12-07T03:19:10.000Z | CaWE/MapEditor/ObserverPattern.hpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | null | null | null | CaWE/MapEditor/ObserverPattern.hpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 1 | 2020-04-11T13:00:04.000Z | 2020-04-11T13:00:04.000Z | /*
Cafu Engine, http://www.cafu.de/
Copyright (c) Carsten Fuchs and other contributors.
This project is licensed under the terms of the MIT license.
*/
#ifndef CAFU_OBSERVER_PATTERN_HPP_INCLUDED
#define CAFU_OBSERVER_PATTERN_HPP_INCLUDED
/// \file
/// This file provides the classes for the Observer pattern as described in the book by the GoF.
/// Note that implementations of ObserverT normally maintain a pointer to the subject(s) that they observe,
/// e.g. in order to be able to redraw themselves also outside of and independent from the NotifySubjectChanged() method.
/// This however in turn creates problems when the life of the observer begins before or ends after the life of the observed subject(s).
/// In fact, it seems that the observers have to maintain lists of valid, observed subjects as the subjects maintain lists of observers.
/// Fortunately, these possibly tough problems can (and apparently must) be addressed by the concrete implementation classes of
/// observers and subjects, not by the base classes that the Observer pattern describes and provided herein.
#include "Math3D/BoundingBox.hpp"
#include "Templates/Array.hpp"
#include "Templates/Pointer.hpp"
#include "wx/string.h"
namespace cf { namespace GameSys { class EntityT; } }
namespace cf { namespace TypeSys { class VarBaseT; } }
namespace MapEditor { class CompMapEntityT; }
class SubjectT;
class MapElementT;
class MapPrimitiveT;
//#####################################
//# New observer notifications hints. #
//#####################################
enum MapElemModDetailE
{
MEMD_GENERIC, ///< Generic change of map elements (useful if the subject doesn't know what exactly has been changed).
MEMD_TRANSFORM, ///< A map element has been transformed.
MEMD_PRIMITIVE_PROPS_CHANGED, ///< The properties of a map primitive have been modified.
MEMD_SURFACE_INFO_CHANGED, ///< The surface info of a map element has changed. Note that surface info changes also include the selection of faces.
MEMD_ASSIGN_PRIM_TO_ENTITY, ///< A map primitive has been assigned to another entity (the world or any custom entity).
MEMD_VISIBILITY ///< The visibility of a map element has changed.
};
enum EntityModDetailE
{
EMD_COMPONENTS, ///< The set of components has changed (e.g. added, deleted, order changed).
EMD_HIERARCHY ///< The position of an entity in the entity hierarchy has changed.
};
enum MapDocOtherDetailT
{
UPDATE_GRID,
UPDATE_POINTFILE,
UPDATE_GLOBALOPTIONS
};
//############################################
//# End of new observer notifications hints. #
//############################################
class ObserverT
{
public:
//###################################################################################################################################
//# New observer notifications methods. These methods differ from the basic observer pattern from the GoF and are CaWE specific! #
//# Note that the new methods are NOT pure virtual since a concrete observer might not be interested in some of these notifications #
//###################################################################################################################################
/// Notifies the observer that some other detail than those specifically addressed below has changed.
virtual void NotifySubjectChanged(SubjectT* Subject, MapDocOtherDetailT OtherDetail) { }
/// Notifies the observer that the selection in the current subject has been changed.
/// @param Subject The map document in which the selection has been changed.
/// @param OldSelection Array of the previously selected objects.
/// @param NewSelection Array of the new selected objects.
virtual void NotifySubjectChanged_Selection(SubjectT* Subject, const ArrayT<MapElementT*>& OldSelection, const ArrayT<MapElementT*>& NewSelection) { }
/// Notifies the observer that the groups in the current subject have been changed (new group added, group deleted, visibility changed, anything).
/// @param Subject The map document in which the group inventory has been changed.
virtual void NotifySubjectChanged_Groups(SubjectT* Subject) { }
/// Notifies the observer that one or more entities have been created.
/// @param Subject The map document in which the entities have been created.
/// @param Entities List of created entities.
virtual void NotifySubjectChanged_Created(SubjectT* Subject, const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entities) { }
/// Notifies the observer that one or more map primitives have been created.
/// @param Subject The map document in which the primitives have been created.
/// @param Primitives List of created map primitives.
virtual void NotifySubjectChanged_Created(SubjectT* Subject, const ArrayT<MapPrimitiveT*>& Primitives) { }
/// Notifies the observer that one or more entities have been deleted.
/// @param Subject The map document in which the entities have been deleted.
/// @param Entities List of deleted entities.
virtual void NotifySubjectChanged_Deleted(SubjectT* Subject, const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entities) { }
/// Notifies the observer that one or more map primitives have been deleted.
/// @param Subject The map document in which the primitives have been deleted.
/// @param Primitives List of deleted map primitives.
virtual void NotifySubjectChanged_Deleted(SubjectT* Subject, const ArrayT<MapPrimitiveT*>& Primitives) { }
/// @name Modification notification method and overloads.
/// These methods notify the observer that one or more map elements have been modified.
/// The first 3 parameters are common to all of these methods since they are the basic information needed to communicate
/// an object modification.
//@{
/// @param Subject The map document in which the elements have been modified.
/// @param MapElements List of modified map elements.
/// @param Detail Information about what has been modified:
/// Can be one of MEMD_PRIMITIVE_PROPS_CHANGED, MEMD_GENERIC, MEMD_ASSIGN_PRIM_TO_ENTITY and MEMD_MATERIAL_CHANGED.
virtual void NotifySubjectChanged_Modified(SubjectT* Subject, const ArrayT<MapElementT*>& MapElements, MapElemModDetailE Detail) { }
/// @param Subject The map document in which the elements have been modified.
/// @param MapElements List of modified map elements.
/// @param Detail Information about what has been modified:
/// Can be MEMD_TRANSFORM or MEMD_PRIMITIVE_PROPS_CHANGED.
/// In the case of MEMD_PRIMITIVE_PROPS_CHANGED one can assume that
/// only map primitives (no entities) are in the MapElements array.
/// @param OldBounds Holds the bounds of each objects BEFORE the modification (has the same size as MapElements).
virtual void NotifySubjectChanged_Modified(SubjectT* Subject, const ArrayT<MapElementT*>& MapElements, MapElemModDetailE Detail, const ArrayT<BoundingBox3fT>& OldBounds) { }
/// @param Subject The map document in which the entities have been modified.
/// @param Entities List of modified map entities.
/// @param Detail Information about what has been modified.
virtual void Notify_EntChanged(SubjectT* Subject, const ArrayT< IntrusivePtrT<MapEditor::CompMapEntityT> >& Entities, EntityModDetailE Detail) { }
/// Notifies the observer that a variable has changed.
/// @param Subject The map document in which a variable has changed.
/// @param Var The variable whose value has changed.
virtual void Notify_VarChanged(SubjectT* Subject, const cf::TypeSys::VarBaseT& Var) { }
//@}
//############################################
//# End of new observer notification methods #
//############################################
/// This method is called whenever a subject is about the be destroyed (and become unavailable).
/// \param dyingSubject The subject that is being destroyed.
virtual void NotifySubjectDies(SubjectT* dyingSubject)=0;
/// The virtual destructor.
virtual ~ObserverT();
protected:
/// The constructor. It is protected so that only derived classes can create instances of this class.
ObserverT();
};
class SubjectT
{
public:
/// Registers the observer Obs for notification on updates of this class.
/// \param Obs The observer that is to be registered.
void RegisterObserver(ObserverT* Obs);
/// Unregisters the observer Obs from further notification on updates of this class.
/// \param Obs The observer that is to be unregistered.
void UnregisterObserver(ObserverT* Obs);
//###################################################################################################################################
//# New observer notifications methods. These methods differ from the basic observer pattern from the GoF and are CaWE specific! #
//# For detailed comments on the parameters, see the equivalent methods in ObserverT #
//###################################################################################################################################
void UpdateAllObservers(MapDocOtherDetailT OtherDetail);
void UpdateAllObservers_SelectionChanged(const ArrayT<MapElementT*>& OldSelection, const ArrayT<MapElementT*>& NewSelection);
void UpdateAllObservers_GroupsChanged();
void UpdateAllObservers_Created(const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entities);
void UpdateAllObservers_Created(const ArrayT<MapPrimitiveT*>& Primitives);
void UpdateAllObservers_Deleted(const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entites);
void UpdateAllObservers_Deleted(const ArrayT<MapPrimitiveT*>& Primitives);
void UpdateAllObservers_Modified(const ArrayT<MapElementT*>& MapElements, MapElemModDetailE Detail);
void UpdateAllObservers_Modified(const ArrayT<MapElementT*>& MapElements, MapElemModDetailE Detail, const ArrayT<BoundingBox3fT>& OldBounds);
void UpdateAllObservers_EntChanged(const ArrayT< IntrusivePtrT<MapEditor::CompMapEntityT> >& Entities, EntityModDetailE Detail);
void UpdateAllObservers_EntChanged(const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entities, EntityModDetailE Detail);
void UpdateAllObservers_EntChanged(IntrusivePtrT<cf::GameSys::EntityT> Entity, EntityModDetailE Detail);
void UpdateAllObservers_VarChanged(const cf::TypeSys::VarBaseT& Var);
void UpdateAllObservers_SubjectDies();
/// The virtual destructor.
virtual ~SubjectT();
protected:
/// The constructor. It is protected so that only derived classes can create instances of this class.
SubjectT();
private:
/// The list of the observers that have registered for notification on updates of this class.
ArrayT<ObserverT*> m_Observers;
};
#endif
| 53.845411 | 177 | 0.679795 | dns |
179a3912a5ee10485fb2b720edeb71cc6cbdce99 | 5,354 | cpp | C++ | src/rfx/application/Window.cpp | rfruesmer/rfx | 96c15a11ee8e2192c9d2ff233924eee884835f17 | [
"MIT"
] | null | null | null | src/rfx/application/Window.cpp | rfruesmer/rfx | 96c15a11ee8e2192c9d2ff233924eee884835f17 | [
"MIT"
] | null | null | null | src/rfx/application/Window.cpp | rfruesmer/rfx | 96c15a11ee8e2192c9d2ff233924eee884835f17 | [
"MIT"
] | null | null | null | #include "rfx/pch.h"
#include "rfx/application/Window.h"
#include <rfx/common/Algorithm.h>
#ifdef _WINDOWS
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h>
#endif // _WINDOWS
using namespace rfx;
using namespace std;
// ---------------------------------------------------------------------------------------------------------------------
void Window::create(const string& title, int width, int height)
{
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
window = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr);
if (!window) {
RFX_THROW("Failed to create window");
}
glfwGetFramebufferSize(window, &width_, &height_);
glfwSetWindowUserPointer(window, this);
glfwSetKeyCallback(window, onKeyEvent);
glfwSetFramebufferSizeCallback(window, onResize);
glfwSetCursorEnterCallback(window, onCursorEntered);
glfwSetCursorPosCallback(window, onCursorPos);
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::show()
{
glfwShowWindow(window);
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::onResize(GLFWwindow* window, int width, int height)
{
auto rfxWindow = reinterpret_cast<Window*>(glfwGetWindowUserPointer(window));
rfxWindow->onResize(width, height);
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::onResize(int width, int height)
{
width_ = width;
height_ = height;
ranges::for_each(listeners,
[this, width, height](const weak_ptr<WindowListener>& weakListener) {
if (auto listener = weakListener.lock()) {
listener->onResized(*this, width, height);
}
});
}
// ---------------------------------------------------------------------------------------------------------------------
GLFWwindow* Window::getGlfwWindow() const
{
return window;
}
// ---------------------------------------------------------------------------------------------------------------------
void* Window::getHandle() const
{
return glfwGetWin32Window(window);
}
// ---------------------------------------------------------------------------------------------------------------------
uint32_t Window::getClientWidth() const
{
return width_;
}
// ---------------------------------------------------------------------------------------------------------------------
uint32_t Window::getClientHeight() const
{
return height_;
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::addListener(const shared_ptr<WindowListener>& listener)
{
if (!contains(listeners, listener)) {
listeners.push_back(listener);
}
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::onKeyEvent(GLFWwindow* window, int key, int scancode, int action, int mods)
{
auto rfxWindow = reinterpret_cast<Window*>(glfwGetWindowUserPointer(window));
rfxWindow->onKeyEvent(key, scancode, action, mods);
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::onKeyEvent(int key, int scancode, int action, int mods)
{
ranges::for_each(listeners,
[this, key, scancode, action, mods](const weak_ptr<WindowListener>& weakListener) {
if (auto listener = weakListener.lock()) {
listener->onKeyEvent(*this, key, scancode, action, mods);
}
});
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::onCursorPos(GLFWwindow* window, double x, double y)
{
auto rfxWindow = reinterpret_cast<Window*>(glfwGetWindowUserPointer(window));
rfxWindow->onCursorPos(static_cast<float>(x), static_cast<float>(y));
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::onCursorPos(float x, float y)
{
ranges::for_each(listeners,
[this, x, y](const weak_ptr<WindowListener>& weakListener) {
if (auto listener = weakListener.lock()) {
listener->onCursorPos(*this, x, y);
}
});
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::onCursorEntered(GLFWwindow* window, int entered)
{
auto rfxWindow = reinterpret_cast<Window*>(glfwGetWindowUserPointer(window));
rfxWindow->onCursorEntered(entered);
}
// ---------------------------------------------------------------------------------------------------------------------
void Window::onCursorEntered(bool entered)
{
ranges::for_each(listeners,
[this, entered](const weak_ptr<WindowListener>& weakListener) {
if (auto listener = weakListener.lock()) {
listener->onCursorEntered(*this, entered);
}
});
}
// ---------------------------------------------------------------------------------------------------------------------
| 33.254658 | 120 | 0.432013 | rfruesmer |
179ad258773967d439cbe264428f9d2ffa1620f5 | 18,781 | cpp | C++ | clang-tools-extra/unittests/clang-include-fixer/find-all-symbols/FindAllSymbolsTests.cpp | dan-zheng/llvm-project | 6b792850da0345274758c9260fda5df5e57ab486 | [
"Apache-2.0"
] | 409 | 2015-01-03T23:52:34.000Z | 2022-03-09T11:32:18.000Z | clang-tools-extra/unittests/clang-include-fixer/find-all-symbols/FindAllSymbolsTests.cpp | dan-zheng/llvm-project | 6b792850da0345274758c9260fda5df5e57ab486 | [
"Apache-2.0"
] | 15 | 2015-08-31T13:35:00.000Z | 2018-11-23T12:34:50.000Z | clang-tools-extra/unittests/clang-include-fixer/find-all-symbols/FindAllSymbolsTests.cpp | dan-zheng/llvm-project | 6b792850da0345274758c9260fda5df5e57ab486 | [
"Apache-2.0"
] | 374 | 2015-02-02T05:23:26.000Z | 2022-03-31T10:53:25.000Z | //===-- FindAllSymbolsTests.cpp - find all symbols unit tests ---*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "FindAllSymbolsAction.h"
#include "HeaderMapCollector.h"
#include "SymbolInfo.h"
#include "SymbolReporter.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/PCHContainerOperations.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "gtest/gtest.h"
#include <memory>
#include <string>
#include <vector>
namespace clang {
namespace find_all_symbols {
static const char HeaderName[] = "symbols.h";
class TestSymbolReporter : public SymbolReporter {
public:
~TestSymbolReporter() override {}
void reportSymbols(llvm::StringRef FileName,
const SymbolInfo::SignalMap &NewSymbols) override {
for (const auto &Entry : NewSymbols)
Symbols[Entry.first] += Entry.second;
}
int seen(const SymbolInfo &Symbol) const {
auto it = Symbols.find(Symbol);
return it == Symbols.end() ? 0 : it->second.Seen;
}
int used(const SymbolInfo &Symbol) const {
auto it = Symbols.find(Symbol);
return it == Symbols.end() ? 0 : it->second.Used;
}
private:
SymbolInfo::SignalMap Symbols;
};
class FindAllSymbolsTest : public ::testing::Test {
public:
int seen(const SymbolInfo &Symbol) { return Reporter.seen(Symbol); }
int used(const SymbolInfo &Symbol) { return Reporter.used(Symbol); }
bool runFindAllSymbols(StringRef HeaderCode, StringRef MainCode) {
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
new llvm::vfs::InMemoryFileSystem);
llvm::IntrusiveRefCntPtr<FileManager> Files(
new FileManager(FileSystemOptions(), InMemoryFileSystem));
std::string FileName = "symbol.cc";
const std::string InternalHeader = "internal/internal_header.h";
const std::string TopHeader = "<top>";
// Test .inc header path. The header for `IncHeaderClass` should be
// internal.h, which will eventually be mapped to <top>.
std::string IncHeader = "internal/private.inc";
std::string IncHeaderCode = "class IncHeaderClass {};";
HeaderMapCollector::RegexHeaderMap RegexMap = {
{R"(internal_.*\.h$)", TopHeader.c_str()},
};
std::string InternalCode =
"#include \"private.inc\"\nclass Internal {};";
SymbolInfo InternalSymbol("Internal", SymbolInfo::SymbolKind::Class,
TopHeader, {});
SymbolInfo IncSymbol("IncHeaderClass", SymbolInfo::SymbolKind::Class,
TopHeader, {});
InMemoryFileSystem->addFile(
IncHeader, 0, llvm::MemoryBuffer::getMemBuffer(IncHeaderCode));
InMemoryFileSystem->addFile(InternalHeader, 0,
llvm::MemoryBuffer::getMemBuffer(InternalCode));
std::unique_ptr<tooling::FrontendActionFactory> Factory(
new FindAllSymbolsActionFactory(&Reporter, &RegexMap));
tooling::ToolInvocation Invocation(
{std::string("find_all_symbols"), std::string("-fsyntax-only"),
std::string("-std=c++11"), FileName},
Factory->create(), Files.get(),
std::make_shared<PCHContainerOperations>());
InMemoryFileSystem->addFile(HeaderName, 0,
llvm::MemoryBuffer::getMemBuffer(HeaderCode));
std::string Content = "#include\"" + std::string(HeaderName) +
"\"\n"
"#include \"" +
InternalHeader + "\"";
#if !defined(_MSC_VER) && !defined(__MINGW32__)
// Test path cleaning for both decls and macros.
const std::string DirtyHeader = "./internal/./a/b.h";
Content += "\n#include \"" + DirtyHeader + "\"";
const std::string CleanHeader = "internal/a/b.h";
const std::string DirtyHeaderContent =
"#define INTERNAL 1\nclass ExtraInternal {};";
InMemoryFileSystem->addFile(
DirtyHeader, 0, llvm::MemoryBuffer::getMemBuffer(DirtyHeaderContent));
SymbolInfo DirtyMacro("INTERNAL", SymbolInfo::SymbolKind::Macro,
CleanHeader, {});
SymbolInfo DirtySymbol("ExtraInternal", SymbolInfo::SymbolKind::Class,
CleanHeader, {});
#endif // _MSC_VER && __MINGW32__
Content += "\n" + MainCode.str();
InMemoryFileSystem->addFile(FileName, 0,
llvm::MemoryBuffer::getMemBuffer(Content));
Invocation.run();
EXPECT_EQ(1, seen(InternalSymbol));
EXPECT_EQ(1, seen(IncSymbol));
#if !defined(_MSC_VER) && !defined(__MINGW32__)
EXPECT_EQ(1, seen(DirtySymbol));
EXPECT_EQ(1, seen(DirtyMacro));
#endif // _MSC_VER && __MINGW32__
return true;
}
protected:
TestSymbolReporter Reporter;
};
TEST_F(FindAllSymbolsTest, VariableSymbols) {
static const char Header[] = R"(
extern int xargc;
namespace na {
static bool SSSS = false;
namespace nb { const long long *XXXX; }
})";
static const char Main[] = R"(
auto y = &na::nb::XXXX;
int main() { if (na::SSSS) return xargc; }
)";
runFindAllSymbols(Header, Main);
SymbolInfo Symbol =
SymbolInfo("xargc", SymbolInfo::SymbolKind::Variable, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("SSSS", SymbolInfo::SymbolKind::Variable, HeaderName,
{{SymbolInfo::ContextType::Namespace, "na"}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("XXXX", SymbolInfo::SymbolKind::Variable, HeaderName,
{{SymbolInfo::ContextType::Namespace, "nb"},
{SymbolInfo::ContextType::Namespace, "na"}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
}
TEST_F(FindAllSymbolsTest, ExternCSymbols) {
static const char Header[] = R"(
extern "C" {
int C_Func() { return 0; }
struct C_struct {
int Member;
};
})";
static const char Main[] = R"(
C_struct q() {
int(*ptr)() = C_Func;
return {0};
}
)";
runFindAllSymbols(Header, Main);
SymbolInfo Symbol =
SymbolInfo("C_Func", SymbolInfo::SymbolKind::Function, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol =
SymbolInfo("C_struct", SymbolInfo::SymbolKind::Class, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
}
TEST_F(FindAllSymbolsTest, CXXRecordSymbols) {
static const char Header[] = R"(
struct Glob {};
struct A; // Not a defintion, ignored.
class NOP; // Not a defintion, ignored
namespace na {
struct A {
struct AAAA {};
int x;
int y;
void f() {}
};
}; //
)";
static const char Main[] = R"(
static Glob glob;
static na::A::AAAA* a;
)";
runFindAllSymbols(Header, Main);
SymbolInfo Symbol =
SymbolInfo("Glob", SymbolInfo::SymbolKind::Class, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("A", SymbolInfo::SymbolKind::Class, HeaderName,
{{SymbolInfo::ContextType::Namespace, "na"}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("AAA", SymbolInfo::SymbolKind::Class, HeaderName,
{{SymbolInfo::ContextType::Record, "A"},
{SymbolInfo::ContextType::Namespace, "na"}});
EXPECT_EQ(0, seen(Symbol));
EXPECT_EQ(0, used(Symbol));
}
TEST_F(FindAllSymbolsTest, CXXRecordSymbolsTemplate) {
static const char Header[] = R"(
template <typename T>
struct T_TEMP {
template <typename _Tp1>
struct rebind { typedef T_TEMP<_Tp1> other; };
};
// Ignore specialization.
template class T_TEMP<char>;
template <typename T>
class Observer {
};
// Ignore specialization.
template <> class Observer<int> {};
)";
static const char Main[] = R"(
extern T_TEMP<int>::rebind<char> weirdo;
)";
runFindAllSymbols(Header, Main);
SymbolInfo Symbol =
SymbolInfo("T_TEMP", SymbolInfo::SymbolKind::Class, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
}
TEST_F(FindAllSymbolsTest, DontIgnoreTemplatePartialSpecialization) {
static const char Code[] = R"(
template<class> class Class; // undefined
template<class R, class... ArgTypes>
class Class<R(ArgTypes...)> {
};
template<class T> void f() {};
template<> void f<int>() {};
)";
runFindAllSymbols(Code, "");
SymbolInfo Symbol =
SymbolInfo("Class", SymbolInfo::SymbolKind::Class, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
Symbol = SymbolInfo("f", SymbolInfo::SymbolKind::Function, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
}
TEST_F(FindAllSymbolsTest, FunctionSymbols) {
static const char Header[] = R"(
namespace na {
int gg(int);
int f(const int &a) { int Local; static int StaticLocal; return 0; }
static void SSSFFF() {}
} // namespace na
namespace na {
namespace nb {
template<typename T>
void fun(T t) {};
} // namespace nb
} // namespace na";
)";
static const char Main[] = R"(
int(*gg)(int) = &na::gg;
int main() {
(void)na::SSSFFF;
na::nb::fun(0);
return na::f(gg(0));
}
)";
runFindAllSymbols(Header, Main);
SymbolInfo Symbol =
SymbolInfo("gg", SymbolInfo::SymbolKind::Function, HeaderName,
{{SymbolInfo::ContextType::Namespace, "na"}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("f", SymbolInfo::SymbolKind::Function, HeaderName,
{{SymbolInfo::ContextType::Namespace, "na"}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("SSSFFF", SymbolInfo::SymbolKind::Function, HeaderName,
{{SymbolInfo::ContextType::Namespace, "na"}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("fun", SymbolInfo::SymbolKind::Function, HeaderName,
{{SymbolInfo::ContextType::Namespace, "nb"},
{SymbolInfo::ContextType::Namespace, "na"}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
}
TEST_F(FindAllSymbolsTest, NamespaceTest) {
static const char Header[] = R"(
int X1;
namespace { int X2; }
namespace { namespace { int X3; } }
namespace { namespace nb { int X4; } }
namespace na { inline namespace __1 { int X5; } }
)";
static const char Main[] = R"(
using namespace nb;
int main() {
X1 = X2;
X3 = X4;
(void)na::X5;
}
)";
runFindAllSymbols(Header, Main);
SymbolInfo Symbol =
SymbolInfo("X1", SymbolInfo::SymbolKind::Variable, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("X2", SymbolInfo::SymbolKind::Variable, HeaderName,
{{SymbolInfo::ContextType::Namespace, ""}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("X3", SymbolInfo::SymbolKind::Variable, HeaderName,
{{SymbolInfo::ContextType::Namespace, ""},
{SymbolInfo::ContextType::Namespace, ""}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("X4", SymbolInfo::SymbolKind::Variable, HeaderName,
{{SymbolInfo::ContextType::Namespace, "nb"},
{SymbolInfo::ContextType::Namespace, ""}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("X5", SymbolInfo::SymbolKind::Variable, HeaderName,
{{SymbolInfo::ContextType::Namespace, "na"}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
}
TEST_F(FindAllSymbolsTest, DecayedTypeTest) {
static const char Header[] = "void DecayedFunc(int x[], int y[10]) {}";
static const char Main[] = R"(int main() { DecayedFunc(nullptr, nullptr); })";
runFindAllSymbols(Header, Main);
SymbolInfo Symbol = SymbolInfo(
"DecayedFunc", SymbolInfo::SymbolKind::Function, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
}
TEST_F(FindAllSymbolsTest, CTypedefTest) {
static const char Header[] = R"(
typedef unsigned size_t_;
typedef struct { int x; } X;
using XX = X;
)";
static const char Main[] = R"(
size_t_ f;
template<typename T> struct vector{};
vector<X> list;
void foo(const XX&){}
)";
runFindAllSymbols(Header, Main);
SymbolInfo Symbol = SymbolInfo("size_t_", SymbolInfo::SymbolKind::TypedefName,
HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("X", SymbolInfo::SymbolKind::TypedefName, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol =
SymbolInfo("XX", SymbolInfo::SymbolKind::TypedefName, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
}
TEST_F(FindAllSymbolsTest, EnumTest) {
static const char Header[] = R"(
enum Glob_E { G1, G2 };
enum class Altitude { high='h', low='l'};
enum { A1, A2 };
class A {
public:
enum A_ENUM { X1, X2 };
};
enum DECL : int;
)";
static const char Main[] = R"(
static auto flags = G1 | G2;
static auto alt = Altitude::high;
static auto nested = A::X1;
extern DECL whatever;
static auto flags2 = A1 | A2;
)";
runFindAllSymbols(Header, Main);
SymbolInfo Symbol =
SymbolInfo("Glob_E", SymbolInfo::SymbolKind::EnumDecl, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(0, used(Symbol));
Symbol =
SymbolInfo("G1", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName,
{{SymbolInfo::ContextType::EnumDecl, "Glob_E"}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol =
SymbolInfo("G2", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName,
{{SymbolInfo::ContextType::EnumDecl, "Glob_E"}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol =
SymbolInfo("Altitude", SymbolInfo::SymbolKind::EnumDecl, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol =
SymbolInfo("high", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName,
{{SymbolInfo::ContextType::EnumDecl, "Altitude"}});
EXPECT_EQ(0, seen(Symbol));
EXPECT_EQ(0, used(Symbol));
Symbol = SymbolInfo("A1", SymbolInfo::SymbolKind::EnumConstantDecl,
HeaderName, {{SymbolInfo::ContextType::EnumDecl, ""}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("A2", SymbolInfo::SymbolKind::EnumConstantDecl,
HeaderName, {{SymbolInfo::ContextType::EnumDecl, ""}});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("", SymbolInfo::SymbolKind::EnumDecl, HeaderName, {});
EXPECT_EQ(0, seen(Symbol));
EXPECT_EQ(0, used(Symbol));
Symbol = SymbolInfo("A_ENUM", SymbolInfo::SymbolKind::EnumDecl, HeaderName,
{{SymbolInfo::ContextType::Record, "A"}});
EXPECT_EQ(0, seen(Symbol));
EXPECT_EQ(0, used(Symbol));
Symbol = SymbolInfo("X1", SymbolInfo::SymbolKind::EnumDecl, HeaderName,
{{SymbolInfo::ContextType::EnumDecl, "A_ENUM"},
{SymbolInfo::ContextType::Record, "A"}});
EXPECT_EQ(0, seen(Symbol));
Symbol = SymbolInfo("DECL", SymbolInfo::SymbolKind::EnumDecl, HeaderName, {});
EXPECT_EQ(0, seen(Symbol));
}
TEST_F(FindAllSymbolsTest, IWYUPrivatePragmaTest) {
static const char Header[] = R"(
// IWYU pragma: private, include "bar.h"
struct Bar {
};
)";
static const char Main[] = R"(
Bar bar;
)";
runFindAllSymbols(Header, Main);
SymbolInfo Symbol =
SymbolInfo("Bar", SymbolInfo::SymbolKind::Class, "bar.h", {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
}
TEST_F(FindAllSymbolsTest, MacroTest) {
static const char Header[] = R"(
#define X
#define Y 1
#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
)";
static const char Main[] = R"(
#ifdef X
int main() { return MAX(0,Y); }
#endif
)";
runFindAllSymbols(Header, Main);
SymbolInfo Symbol =
SymbolInfo("X", SymbolInfo::SymbolKind::Macro, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("Y", SymbolInfo::SymbolKind::Macro, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("MAX", SymbolInfo::SymbolKind::Macro, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
}
TEST_F(FindAllSymbolsTest, MacroTestWithIWYU) {
static const char Header[] = R"(
// IWYU pragma: private, include "bar.h"
#define X 1
#define Y 1
#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
)";
static const char Main[] = R"(
#ifdef X
int main() { return MAX(0,Y); }
#endif
)";
runFindAllSymbols(Header, Main);
SymbolInfo Symbol =
SymbolInfo("X", SymbolInfo::SymbolKind::Macro, "bar.h", {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("Y", SymbolInfo::SymbolKind::Macro, "bar.h", {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
Symbol = SymbolInfo("MAX", SymbolInfo::SymbolKind::Macro, "bar.h", {});
EXPECT_EQ(1, seen(Symbol));
EXPECT_EQ(1, used(Symbol));
}
TEST_F(FindAllSymbolsTest, NoFriendTest) {
static const char Header[] = R"(
class WorstFriend {
friend void Friend();
friend class BestFriend;
};
)";
runFindAllSymbols(Header, "");
SymbolInfo Symbol =
SymbolInfo("WorstFriend", SymbolInfo::SymbolKind::Class, HeaderName, {});
EXPECT_EQ(1, seen(Symbol));
Symbol =
SymbolInfo("Friend", SymbolInfo::SymbolKind::Function, HeaderName, {});
EXPECT_EQ(0, seen(Symbol));
Symbol =
SymbolInfo("BestFriend", SymbolInfo::SymbolKind::Class, HeaderName, {});
EXPECT_EQ(0, seen(Symbol));
}
} // namespace find_all_symbols
} // namespace clang
| 32.49308 | 80 | 0.624567 | dan-zheng |
179d24ecf183dab489c1eb0f50bda30091244204 | 54,032 | cpp | C++ | src/imaging/ossimImageChain.cpp | vladislav-horbatiuk/ossim | 82417ad868fac022672335e1684bdd91d662c18c | [
"MIT"
] | 251 | 2015-10-20T09:08:11.000Z | 2022-03-22T18:16:38.000Z | src/imaging/ossimImageChain.cpp | vladislav-horbatiuk/ossim | 82417ad868fac022672335e1684bdd91d662c18c | [
"MIT"
] | 73 | 2015-11-02T17:12:36.000Z | 2021-11-15T17:41:47.000Z | src/imaging/ossimImageChain.cpp | vladislav-horbatiuk/ossim | 82417ad868fac022672335e1684bdd91d662c18c | [
"MIT"
] | 146 | 2015-10-15T16:00:15.000Z | 2022-03-22T12:37:14.000Z | //*******************************************************************
// Copyright (C) 2000 ImageLinks Inc.
//
// License: LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
// Author: Garrett Potts
//
//*************************************************************************
// $Id: ossimImageChain.cpp 21850 2012-10-21 20:09:55Z dburken $
#include <ossim/imaging/ossimImageChain.h>
#include <ossim/base/ossimCommon.h>
#include <ossim/base/ossimConnectableContainer.h>
#include <ossim/base/ossimDrect.h>
#include <ossim/base/ossimNotifyContext.h>
#include <ossim/base/ossimObjectFactoryRegistry.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimTrace.h>
#include <ossim/base/ossimEventIds.h>
#include <ossim/base/ossimObjectEvents.h>
#include <ossim/base/ossimIdManager.h>
#include <ossim/base/ossimVisitor.h>
#include <ossim/imaging/ossimImageData.h>
#include <ossim/imaging/ossimImageGeometry.h>
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
static ossimTrace traceDebug("ossimImageChain");
RTTI_DEF3(ossimImageChain, "ossimImageChain", ossimImageSource,
ossimConnectableObjectListener, ossimConnectableContainerInterface);
void ossimImageChain::processEvent(ossimEvent& event)
{
ossimConnectableObjectListener::processEvent(event);
ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject, event.getCurrentObject());
if((ossimConnectableObject*)getFirstSource() == obj)
{
if(event.isPropagatingToOutputs())
{
ossimConnectableObject::ConnectableObjectList& outputList = getOutputList();
ossim_uint32 idx = 0;
for(idx = 0; idx < outputList.size();++idx)
{
if(outputList[idx].valid())
{
outputList[idx]->fireEvent(event);
outputList[idx]->propagateEventToOutputs(event);
}
}
}
}
}
ossimImageChain::ossimImageChain()
:ossimImageSource(0,
0, // number of inputs
0, // number of outputs
false, // input's fixed
false), // outputs are not fixed
ossimConnectableContainerInterface((ossimObject*)NULL),
theBlankTile(NULL),
theLoadStateFlag(false)
{
ossimConnectableContainerInterface::theBaseObject = this;
//thePropagateEventFlag = false;
addListener((ossimConnectableObjectListener*)this);
}
ossimImageChain::~ossimImageChain()
{
removeListener((ossimConnectableObjectListener*)this);
deleteList();
}
bool ossimImageChain::addFirst(ossimConnectableObject* obj)
{
ossimConnectableObject* rightOfThisObj =
(ossimConnectableObject*)getFirstObject();
return insertRight(obj, rightOfThisObj);
}
bool ossimImageChain::addLast(ossimConnectableObject* obj)
{
if(imageChainList().size() > 0)
{
ossimConnectableObject* lastSource = imageChainList()[ imageChainList().size() -1].get();
// if(dynamic_cast<ossimImageSource*>(obj)&&lastSource)
if(lastSource)
{
// obj->disconnect();
ossimConnectableObject::ConnectableObjectList tempIn = getInputList();
lastSource->disconnectAllInputs();
lastSource->connectMyInputTo(obj);
obj->changeOwner(this);
obj->connectInputList(tempIn);
tempIn = obj->getInputList();
theInputListIsFixedFlag = obj->getInputListIsFixedFlag();
setNumberOfInputs(obj->getNumberOfInputs());
imageChainList().push_back(obj);
obj->addListener((ossimConnectableObjectListener*)this);
// Send an event to any listeners.
ossimContainerEvent event((ossimObject*)this,
OSSIM_EVENT_ADD_OBJECT_ID);
event.setObjectList(obj);
fireEvent(event);
return true;
}
}
else
{
return add(obj);
}
return false;;
}
ossimImageSource* ossimImageChain::getFirstSource()
{
if(imageChainList().size()>0)
{
return dynamic_cast<ossimImageSource*>(imageChainList()[0].get());
}
return 0;
}
const ossimImageSource* ossimImageChain::getFirstSource() const
{
if(imageChainList().size()>0)
return dynamic_cast<const ossimImageSource*>(imageChainList()[0].get());
return 0;
}
ossimObject* ossimImageChain::getFirstObject()
{
if(imageChainList().size()>0)
{
return dynamic_cast<ossimImageSource*>(imageChainList()[0].get());
}
return 0;
}
ossimImageSource* ossimImageChain::getLastSource()
{
if(imageChainList().size()>0)
{
return dynamic_cast<ossimImageSource*>((*(imageChainList().end()-1)).get());
}
return NULL;
}
const ossimImageSource* ossimImageChain::getLastSource() const
{
if(imageChainList().size()>0)
return dynamic_cast<const ossimImageSource*>((*(imageChainList().end()-1)).get());
return NULL;
}
ossimObject* ossimImageChain::getLastObject()
{
if(imageChainList().size()>0)
{
return dynamic_cast<ossimImageSource*>((*(imageChainList().end()-1)).get());
}
return 0;
}
ossimConnectableObject* ossimImageChain::findObject(const ossimId& id,
bool /* recurse */)
{
std::vector<ossimRefPtr<ossimConnectableObject> >::iterator current = imageChainList().begin();
while(current != imageChainList().end())
{
if((*current).get())
{
if(id == (*current)->getId())
{
return (*current).get();
}
}
++current;
}
current = imageChainList().begin();
while(current != imageChainList().end())
{
ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface,
(*current).get());
if(child)
{
ossimConnectableObject* object = child->findObject(id, true);
if(object) return object;
}
++current;
}
return NULL;
}
ossimConnectableObject* ossimImageChain::findObject(const ossimConnectableObject* obj,
bool /* recurse */)
{
std::vector<ossimRefPtr<ossimConnectableObject> >::iterator current = imageChainList().begin();
while(current != imageChainList().end())
{
if((*current).valid())
{
if(obj == (*current).get())
{
return (*current).get();
}
}
++current;
}
current = imageChainList().begin();
while(current != imageChainList().end())
{
ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get());
if(child)
{
ossimConnectableObject* object = child->findObject(obj, true);
if(object) return object;
}
++current;
}
return 0;
}
ossimConnectableObject* ossimImageChain::findFirstObjectOfType(const RTTItypeid& typeInfo,
bool recurse)
{
vector<ossimRefPtr<ossimConnectableObject> >::iterator current = imageChainList().begin();
while(current != imageChainList().end())
{
if((*current).valid()&&
(*current)->canCastTo(typeInfo))
{
return (*current).get();
}
++current;
}
if(recurse)
{
current = imageChainList().begin();
while(current != imageChainList().end())
{
ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface,
(*current).get());
if(child)
{
ossimConnectableObject* temp = child->findFirstObjectOfType(typeInfo, recurse);
if(temp)
{
return temp;
}
}
++current;
}
}
return (ossimConnectableObject*)NULL;
}
ossimConnectableObject* ossimImageChain::findFirstObjectOfType(const ossimString& className,
bool recurse)
{
vector<ossimRefPtr<ossimConnectableObject> >::iterator current = imageChainList().begin();
while(current != imageChainList().end())
{
if((*current).valid()&&
(*current)->canCastTo(className) )
{
return (*current).get();
}
++current;
}
if(recurse)
{
current = imageChainList().begin();
while(current != imageChainList().end())
{
ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get());
if(child)
{
ossimConnectableObject* temp = child->findFirstObjectOfType(className, recurse);
if(temp)
{
return temp;
}
}
++current;
}
}
return (ossimConnectableObject*)0;
}
ossimConnectableObject::ConnectableObjectList ossimImageChain::findAllObjectsOfType(const RTTItypeid& typeInfo,
bool recurse)
{
ossimConnectableObject::ConnectableObjectList result;
ossimConnectableObject::ConnectableObjectList::iterator current = imageChainList().begin();
while(current != imageChainList().end())
{
if((*current).valid()&&
(*current)->canCastTo(typeInfo))
{
ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(),
result.end(),
(*current).get());
if(iter == result.end())
{
result.push_back((*current).get());
}
}
++current;
}
if(recurse)
{
current = imageChainList().begin();
while(current != imageChainList().end())
{
ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get());
if(child)
{
ossimConnectableObject::ConnectableObjectList temp;
temp = child->findAllObjectsOfType(typeInfo, recurse);
for(long index=0; index < (long)temp.size();++index)
{
ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), temp[index]);
if(iter == result.end())
{
result.push_back(temp[index]);
}
}
}
++current;
}
}
return result;
}
ossimConnectableObject::ConnectableObjectList ossimImageChain::findAllObjectsOfType(const ossimString& className,
bool recurse)
{
ossimConnectableObject::ConnectableObjectList result;
ossimConnectableObject::ConnectableObjectList::iterator current = imageChainList().begin();
while(current != imageChainList().end())
{
if((*current).valid()&&
(*current)->canCastTo(className))
{
ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(),
result.end(),
(*current).get());
if(iter == result.end())
{
result.push_back((*current).get());
}
}
++current;
}
if(recurse)
{
current = imageChainList().begin();
while(current != imageChainList().end())
{
ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get());
if(child)
{
ossimConnectableObject::ConnectableObjectList temp;
temp = child->findAllObjectsOfType(className, recurse);
for(long index=0; index < (long)temp.size();++index)
{
ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), temp[index]);
if(iter == result.end())
{
result.push_back(temp[index]);
}
}
}
++current;
}
}
return result;
}
void ossimImageChain::makeUniqueIds()
{
setId(ossimIdManager::instance()->generateId());
for(long index = 0; index < (long)imageChainList().size(); ++index)
{
ossimConnectableContainerInterface* container = PTR_CAST(ossimConnectableContainerInterface,
imageChainList()[index].get());
if(container)
{
container->makeUniqueIds();
}
else
{
if(imageChainList()[index].valid())
{
imageChainList()[index]->setId(ossimIdManager::instance()->generateId());
}
}
}
}
ossim_uint32 ossimImageChain::getNumberOfObjects(bool recurse)const
{
ossim_uint32 result = (ossim_uint32)imageChainList().size();
if(recurse)
{
for(ossim_uint32 i = 0; i < imageChainList().size(); ++i)
{
ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, imageChainList()[i].get());
if(child)
{
result += child->getNumberOfObjects(true);
}
}
}
return result;
}
ossim_uint32 ossimImageChain::getNumberOfSources() const
{
ossimNotify(ossimNotifyLevel_NOTICE)
<< "ossimImageChain::getNumberOfSources is deprecated!"
<< "\nUse: ossimImageChain::getNumberOfObjects(false)"
<< std::endl;
return getNumberOfObjects(false);
}
bool ossimImageChain::addChild(ossimConnectableObject* object)
{
return add(object);
}
bool ossimImageChain::removeChild(ossimConnectableObject* object)
{
bool result = false;
vector<ossimRefPtr<ossimConnectableObject> >::iterator current = std::find(imageChainList().begin(), imageChainList().end(), object);
if(current!=imageChainList().end())
{
result = true;
object->removeListener((ossimConnectableObjectListener*)this);
if(current == imageChainList().begin())
{
object->removeListener((ossimConnectableObjectListener*)this);
}
if(imageChainList().size() == 1)
{
object->changeOwner(0);
current = imageChainList().erase(current);
}
else
{
ossimConnectableObject::ConnectableObjectList input = object->getInputList();
ossimConnectableObject::ConnectableObjectList output = object->getOutputList();
object->changeOwner(0);// set the owner to 0
bool erasingBeginning = (current == imageChainList().begin());
// bool erasingEnd = (current+1) == imageChainList().end();
current = imageChainList().erase(current);
object->disconnect();
if(!imageChainList().empty())
{
if(erasingBeginning) // the one that receives the first getTile
{
(*imageChainList().begin())->addListener(this);
}
else if(current==imageChainList().end()) // one that receives the last getTIle
{
current = imageChainList().begin()+(imageChainList().size()-1);
(*current)->connectInputList(input);
theInputObjectList = (*current)->getInputList();
theInputListIsFixedFlag = (*current)->getInputListIsFixedFlag();
}
else
{
// prepare interior setup and removal and connect surrounding nodes
// take the outputs of the node we are removing and connect them to the old inputs
ossim_uint32 outIndex = 0;
for(outIndex = 0; outIndex < output.size();++outIndex)
{
output[outIndex]->connectInputList(input);
}
}
}
}
// Send an event to any listeners.
ossimContainerEvent event((ossimObject*)this,
OSSIM_EVENT_REMOVE_OBJECT_ID);
event.setObjectList(object);
fireEvent(event);
}
return result;
}
ossimConnectableObject* ossimImageChain::removeChild(const ossimId& id)
{
ossimIdVisitor visitor( id,
(ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS ) );
accept( visitor );
ossimConnectableObject* obj = visitor.getObject();
if ( obj )
{
removeChild(obj);
}
return obj;
}
void ossimImageChain::getChildren(vector<ossimConnectableObject*>& children,
bool immediateChildrenOnlyFlag)
{
ossim_uint32 i = 0;
vector<ossimConnectableObject*> temp;
for(i = 0; i < imageChainList().size();++i)
{
temp.push_back(imageChainList()[i].get());
}
for(i = 0; i < temp.size();++i)
{
ossimConnectableContainerInterface* interface = PTR_CAST(ossimConnectableContainerInterface,
temp[i]);
if(immediateChildrenOnlyFlag)
{
children.push_back(temp[i]);
}
else if(!interface)
{
children.push_back(temp[i]);
}
}
if(!immediateChildrenOnlyFlag)
{
for(i = 0; i < temp.size();++i)
{
ossimConnectableContainerInterface* interface = PTR_CAST(ossimConnectableContainerInterface,
temp[i]);
if(interface)
{
interface->getChildren(children, false);
}
}
}
}
bool ossimImageChain::add(ossimConnectableObject* source)
{
bool result = false;
// if(PTR_CAST(ossimImageSource, source))
{
source->changeOwner(this);
if(imageChainList().size() > 0)
{
source->disconnectAllOutputs();
theOutputListIsFixedFlag = source->getOutputListIsFixedFlag();
imageChainList()[0]->removeListener(this);
imageChainList().insert(imageChainList().begin(), source);
imageChainList()[0]->addListener(this);
source->addListener((ossimConnectableObjectListener*)this);
imageChainList()[0]->connectMyInputTo(imageChainList()[1].get());
result = true;
}
else
{
theInputListIsFixedFlag = false;
theOutputListIsFixedFlag = false;
if(!theInputObjectList.empty())
{
source->connectInputList(getInputList());
}
theInputObjectList = source->getInputList();
theInputListIsFixedFlag = source->getInputListIsFixedFlag();
// theOutputObjectList = source->getOutputList();
// theOutputListIsFixedFlag= source->getOutputListIsFixedFlag();
imageChainList().push_back(source);
source->addListener((ossimConnectableObjectListener*)this);
source->addListener(this);
result = true;
}
}
if (result && source)
{
ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID);
event.setObjectList(source);
fireEvent(event);
}
return result;
}
bool ossimImageChain::insertRight(ossimConnectableObject* newObj,
ossimConnectableObject* rightOfThisObj)
{
if(!newObj&&!rightOfThisObj) return false;
if(!imageChainList().size())
{
return add(newObj);
}
std::vector<ossimRefPtr<ossimConnectableObject> >::iterator iter = std::find(imageChainList().begin(), imageChainList().end(), rightOfThisObj);
if(iter!=imageChainList().end())
{
if(iter == imageChainList().begin())
{
return add(newObj);
}
else //if(PTR_CAST(ossimImageSource, newObj))
{
ossimConnectableObject::ConnectableObjectList outputList = rightOfThisObj->getOutputList();
rightOfThisObj->disconnectAllOutputs();
// Core dump fix. Connect input prior to outputs. (drb)
newObj->connectMyInputTo(rightOfThisObj);
newObj->connectOutputList(outputList);
newObj->changeOwner(this);
newObj->addListener((ossimConnectableObjectListener*)this);
imageChainList().insert(iter, newObj);
// Send event to any listeners.
ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID);
event.setObjectList(newObj);
fireEvent(event);
return true;
}
}
return false;
}
bool ossimImageChain::insertRight(ossimConnectableObject* newObj,
const ossimId& id)
{
#if 1
ossimIdVisitor visitor( id, ossimVisitor::VISIT_CHILDREN );
accept( visitor );
ossimConnectableObject* obj = visitor.getObject();
if ( obj )
{
return insertRight(newObj, obj);
}
return false;
#else
ossimConnectableObject* obj = findObject(id, false);
if(obj)
{
return insertRight(newObj, obj);
}
return false;
#endif
}
bool ossimImageChain::insertLeft(ossimConnectableObject* newObj,
ossimConnectableObject* leftOfThisObj)
{
if(!newObj&&!leftOfThisObj) return false;
if(!imageChainList().size())
{
return add(newObj);
}
std::vector<ossimRefPtr<ossimConnectableObject> >::iterator iter = std::find(imageChainList().begin(), imageChainList().end(), leftOfThisObj);
if(iter!=imageChainList().end())
{
if((iter+1)==imageChainList().end())
{
return addLast(newObj);
}
else
{
ossimConnectableObject::ConnectableObjectList inputList = leftOfThisObj->getInputList();
newObj->connectInputList(inputList);
leftOfThisObj->disconnectAllInputs();
leftOfThisObj->connectMyInputTo(newObj);
newObj->changeOwner(this);
newObj->addListener((ossimConnectableObjectListener*)this);
imageChainList().insert(iter+1, newObj);
// Send an event to any listeners.
ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID);
event.setObjectList(newObj);
fireEvent(event);
return true;
}
}
return false;
}
bool ossimImageChain::insertLeft(ossimConnectableObject* newObj,
const ossimId& id)
{
#if 1
ossimIdVisitor visitor( id,
ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS);
accept( visitor );
ossimConnectableObject* obj = visitor.getObject();
if ( obj )
{
return insertLeft(newObj, obj);
}
return false;
#else
ossimConnectableObject* obj = findObject(id, false);
if(obj)
{
return insertLeft(newObj, obj);
}
return false;
#endif
}
bool ossimImageChain::replace(ossimConnectableObject* newObj,
ossimConnectableObject* oldObj)
{
ossim_int32 idx = indexOf(oldObj);
if(idx >= 0)
{
ossimConnectableObject::ConnectableObjectList& inputList = oldObj->getInputList();
ossimConnectableObject::ConnectableObjectList& outputList = oldObj->getOutputList();
oldObj->removeListener((ossimConnectableObjectListener*)this);
oldObj->removeListener(this);
oldObj->changeOwner(0);
imageChainList()[idx] = newObj;
newObj->connectInputList(inputList);
newObj->connectOutputList(outputList);
newObj->changeOwner(this);
newObj->addListener((ossimConnectableObjectListener*)this);
if(idx == 0)
{
newObj->addListener(this);
}
}
return (idx >= 0);
}
ossimRefPtr<ossimImageData> ossimImageChain::getTile(
const ossimIrect& tileRect,
ossim_uint32 resLevel)
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* inputSource = PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(inputSource)
{
// make sure we initialize in reverse order.
// some source may depend on the initialization of
// its inputs
return inputSource->getTile(tileRect, resLevel);
}
}
else
{
if(getInput(0))
{
ossimImageSource* inputSource = PTR_CAST(ossimImageSource, getInput(0));
if(inputSource)
{
ossimRefPtr<ossimImageData> inputTile = inputSource->getTile(tileRect, resLevel);
// if(inputTile.valid())
// {
// std::cout << *(inputTile.get()) << std::endl;
// }
return inputTile.get();
}
}
}
// std::cout << "RETURNING A BLANK TILE!!!!" << std::endl;
/*
if(theBlankTile.get())
{
theBlankTile->setImageRectangle(tileRect);
}
return theBlankTile;
*/
return 0;
}
ossim_uint32 ossimImageChain::getNumberOfInputBands() const
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(interface)
{
return interface->getNumberOfOutputBands();
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
getInput(0));
if(interface)
{
return interface->getNumberOfOutputBands();
}
}
}
return 0;
}
double ossimImageChain::getNullPixelValue(ossim_uint32 band)const
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(interface)
{
return interface->getNullPixelValue(band);
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
getInput(0));
if(interface)
{
return interface->getNullPixelValue(band);
}
}
}
return ossim::defaultNull(getOutputScalarType());
}
double ossimImageChain::getMinPixelValue(ossim_uint32 band)const
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(interface)
{
return interface->getMinPixelValue(band);
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
getInput(0));
if(interface)
{
return interface->getMinPixelValue(band);
}
}
}
return ossim::defaultMin(getOutputScalarType());
}
double ossimImageChain::getMaxPixelValue(ossim_uint32 band)const
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* inter = PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(inter)
{
return inter->getMaxPixelValue(band);
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
getInput(0));
if(interface)
{
return interface->getMaxPixelValue(band);
}
}
}
return ossim::defaultMax(getOutputScalarType());
}
void ossimImageChain::getOutputBandList(std::vector<ossim_uint32>& bandList) const
{
if( (imageChainList().size() > 0) && isSourceEnabled() )
{
ossimRefPtr<const ossimImageSource> inter =
dynamic_cast<const ossimImageSource*>( imageChainList()[0].get() );
if( inter.valid() )
{
// cout << "cn: " << inter->getClassName() << endl;
inter->getOutputBandList(bandList);
}
}
}
ossimScalarType ossimImageChain::getOutputScalarType() const
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(interface)
{
return interface->getOutputScalarType();
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
getInput(0));
if(interface)
{
return interface->getOutputScalarType();
}
}
}
return OSSIM_SCALAR_UNKNOWN;
}
ossim_uint32 ossimImageChain::getTileWidth()const
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(interface)
{
return interface->getTileWidth();;
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
getInput(0));
if(interface)
{
return interface->getTileWidth();
}
}
}
return 0;
}
ossim_uint32 ossimImageChain::getTileHeight()const
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(interface)
{
return interface->getTileHeight();
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
getInput(0));
if(interface)
{
return interface->getTileHeight();
}
}
}
return 0;
}
ossimIrect ossimImageChain::getBoundingRect(ossim_uint32 resLevel)const
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(interface)
{
return interface->getBoundingRect(resLevel);
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
getInput(0));
if(interface)
{
return interface->getBoundingRect();
}
}
}
ossimDrect rect;
rect.makeNan();
return rect;
}
void ossimImageChain::getValidImageVertices(vector<ossimIpt>& validVertices,
ossimVertexOrdering ordering,
ossim_uint32 resLevel)const
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* interface =PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(interface)
{
interface->getValidImageVertices(validVertices,
ordering,
resLevel);
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
getInput(0));
if(interface)
{
interface->getValidImageVertices(validVertices,
ordering,
resLevel);
}
}
}
}
ossimRefPtr<ossimImageGeometry> ossimImageChain::getImageGeometry()
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get());
if( interface )
{
return interface->getImageGeometry();
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0));
if(interface)
{
return interface->getImageGeometry();
}
}
}
return ossimRefPtr<ossimImageGeometry>();
}
void ossimImageChain::getDecimationFactor(ossim_uint32 resLevel,
ossimDpt& result) const
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(interface)
{
interface->getDecimationFactor(resLevel,
result);
return;
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
getInput(0));
if(interface)
{
interface->getDecimationFactor(resLevel, result);
return;
}
}
}
result.makeNan();
}
void ossimImageChain::getDecimationFactors(vector<ossimDpt>& decimations) const
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(interface)
{
interface->getDecimationFactors(decimations);
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
getInput(0));
if(interface)
{
interface->getDecimationFactors(decimations);
return;
}
}
}
}
ossim_uint32 ossimImageChain::getNumberOfDecimationLevels()const
{
if((imageChainList().size() > 0)&&(isSourceEnabled()))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
imageChainList()[0].get());
if(interface)
{
return interface->getNumberOfDecimationLevels();
}
}
else
{
if(getInput(0))
{
ossimImageSource* interface = PTR_CAST(ossimImageSource,
getInput(0));
if(interface)
{
return interface->getNumberOfDecimationLevels();
}
}
}
return 1;
}
bool ossimImageChain::addAllSources(map<ossimId, vector<ossimId> >& idMapping,
const ossimKeywordlist& kwl,
const char* prefix)
{
static const char* MODULE = "ossimImageChain::addAllSources";
ossimString copyPrefix = prefix;
bool result = ossimImageSource::loadState(kwl, copyPrefix.c_str());
if(!result)
{
return result;
}
long index = 0;
// ossimSource* source = NULL;
vector<ossimId> inputConnectionIds;
ossimString regExpression = ossimString("^(") + copyPrefix + "object[0-9]+.)";
vector<ossimString> keys =
kwl.getSubstringKeyList( regExpression );
long numberOfSources = (long)keys.size();//kwl.getNumberOfSubstringKeys(regExpression);
int offset = (int)(copyPrefix+"object").size();
int idx = 0;
std::vector<int> theNumberList(numberOfSources);
for(idx = 0; idx < (int)theNumberList.size();++idx)
{
ossimString numberStr(keys[idx].begin() + offset,
keys[idx].end());
theNumberList[idx] = numberStr.toInt();
}
std::sort(theNumberList.begin(), theNumberList.end());
for(idx=0;idx < (int)theNumberList.size();++idx)
{
ossimString newPrefix = copyPrefix;
newPrefix += ossimString("object");
newPrefix += ossimString::toString(theNumberList[idx]);
newPrefix += ossimString(".");
if(traceDebug())
{
CLOG << "trying to create source with prefix: " << newPrefix
<< std::endl;
}
ossimRefPtr<ossimObject> object = ossimObjectFactoryRegistry::instance()->createObject(kwl,
newPrefix.c_str());
ossimConnectableObject* source = PTR_CAST(ossimConnectableObject, object.get());
if(source)
{
// we did find a source so include it in the count
if(traceDebug())
{
CLOG << "Created source with prefix: " << newPrefix << std::endl;
}
//if(PTR_CAST(ossimImageSource, source))
{
ossimId id = source->getId();
inputConnectionIds.clear();
findInputConnectionIds(inputConnectionIds,
kwl,
newPrefix);
if(inputConnectionIds.size() == 0)
{
// we will try to do a default connection
//
if(imageChainList().size())
{
if(traceDebug())
{
CLOG << "connecting " << source->getClassName() << " to "
<< imageChainList()[0]->getClassName() << std::endl;
}
source->connectMyInputTo(0, imageChainList()[0].get());
}
}
else
{
// we remember the connection id's so we can connect this later.
// this way we make sure all sources were actually
// allocated.
//
idMapping.insert(std::make_pair(id, inputConnectionIds));
}
add(source);
}
// else
// {
source = 0;
// }
}
else
{
object = 0;
source = 0;
}
++index;
}
if(imageChainList().size())
{
ossimConnectableObject* obj = imageChainList()[(ossim_int32)imageChainList().size()-1].get();
if(obj)
{
setNumberOfInputs(obj->getNumberOfInputs());
}
}
return result;
}
void ossimImageChain::findInputConnectionIds(vector<ossimId>& result,
const ossimKeywordlist& kwl,
const char* prefix)
{
ossimString copyPrefix = prefix;
ossim_uint32 idx = 0;
ossimString regExpression = ossimString("^") + ossimString(prefix) + "input_connection[0-9]+";
vector<ossimString> keys =
kwl.getSubstringKeyList( regExpression );
ossim_int32 offset = (ossim_int32)(copyPrefix+"input_connection").size();
ossim_uint32 numberOfKeys = (ossim_uint32)keys.size();
std::vector<int> theNumberList(numberOfKeys);
for(idx = 0; idx < theNumberList.size();++idx)
{
ossimString numberStr(keys[idx].begin() + offset,
keys[idx].end());
theNumberList[idx] = numberStr.toInt();
}
std::sort(theNumberList.begin(), theNumberList.end());
copyPrefix += ossimString("input_connection");
for(idx=0;idx < theNumberList.size();++idx)
{
const char* lookup = kwl.find(copyPrefix,ossimString::toString(theNumberList[idx]));
if(lookup)
{
long id = ossimString(lookup).toLong();
result.push_back(ossimId(id));
}
}
}
bool ossimImageChain::connectAllSources(const map<ossimId, vector<ossimId> >& idMapping)
{
// cout << "this->getId(): " << this->getId() << endl;
if(idMapping.size())
{
map<ossimId, vector<ossimId> >::const_iterator iter = idMapping.begin();
while(iter != idMapping.end())
{
// cout << "(*iter).first): " << (*iter).first << endl;
#if 0
ossimConnectableObject* currentSource = findObject((*iter).first);
#else
ossimIdVisitor visitor( (*iter).first,
(ossimVisitor::VISIT_CHILDREN ) );
// ossimVisitor::VISIT_INPUTS ) );
accept( visitor );
ossimConnectableObject* currentSource = visitor.getObject();
#endif
if(currentSource)
{
// cout << "currentSource->getClassName: " << currentSource->getClassName() << endl;
long upperBound = (long)(*iter).second.size();
for(long index = 0; index < upperBound; ++index)
{
//cout << "(*iter).second[index]: " << (*iter).second[index] << endl;
if((*iter).second[index].getId() > -1)
{
#if 0
ossimConnectableObject* inputSource =
PTR_CAST(ossimConnectableObject, findObject((*iter).second[index]));
#else
visitor.reset();
visitor.setId( (*iter).second[index] );
accept( visitor );
ossimConnectableObject* inputSource = visitor.getObject();
#endif
// cout << "inputSource is " << (inputSource?"good...":"null...") << endl;
if ( inputSource )
{
// cout << "inputSource->getClassName(): " << inputSource->getClassName() << endl;
// Check for connection to self.
if ( this != inputSource )
{
currentSource->connectMyInputTo(index, inputSource);
}
// else warning???
}
}
else // -1 id
{
currentSource->disconnectMyInput((ossim_int32)index);
}
}
}
else
{
cerr << "Could not find " << (*iter).first << " for source: ";
return false;
}
++iter;
}
}
// abort();
return true;
}
bool ossimImageChain::saveState(ossimKeywordlist& kwl,
const char* prefix)const
{
bool result = true;
result = ossimImageSource::saveState(kwl, prefix);
if(!result)
{
return result;
}
ossim_uint32 upper = (ossim_uint32)imageChainList().size();
ossim_uint32 counter = 1;
if (upper)
{
ossim_int32 idx = upper-1;
// start with the tail and go to the head fo the list.
for(;((idx >= 0)&&result);--idx, ++counter)
{
ossimString newPrefix = prefix;
newPrefix += (ossimString("object") +
ossimString::toString(counter) +
ossimString("."));
result = imageChainList()[idx]->saveState(kwl, newPrefix.c_str());
}
}
return result;
}
bool ossimImageChain::loadState(const ossimKeywordlist& kwl,
const char* prefix)
{
static const char* MODULE = "ossimImageChain::loadState(kwl, prefix)";
deleteList();
ossimImageSource::loadState(kwl, prefix);
theLoadStateFlag = true;
bool result = true;
map<ossimId, vector<ossimId> > idMapping;
result = addAllSources(idMapping, kwl, prefix);
if(!result)
{
CLOG << "problems adding sources" << std::endl;
}
result = connectAllSources(idMapping);
if(!result)
{
CLOG << "problems connecting sources" << std::endl;
}
theLoadStateFlag = false;
return result;
}
void ossimImageChain::initialize()
{
static const char* MODULE = "ossimImageChain::initialize()";
if (traceDebug()) CLOG << " Entered..." << std::endl;
long upper = (ossim_uint32)imageChainList().size();
for(long index = upper - 1; index >= 0; --index)
{
if(traceDebug())
{
CLOG << "initializing source: "
<< imageChainList()[index]->getClassName()
<< std::endl;
}
if(imageChainList()[index].valid())
{
ossimSource* interface =
PTR_CAST(ossimSource, imageChainList()[index].get());
if(interface)
{
// make sure we initialize in reverse order.
// some source may depend on the initialization of
// its inputs
interface->initialize();
}
}
}
if (traceDebug()) CLOG << " Exited..." << std::endl;
}
void ossimImageChain::enableSource()
{
ossim_int32 upper = static_cast<ossim_int32>(imageChainList().size());
ossim_int32 index = 0;
for(index = upper - 1; index >= 0; --index)
{
// make sure we initialize in reverse order.
// some source may depend on the initialization of
// its inputs
ossimSource* source = PTR_CAST(ossimSource, imageChainList()[index].get());
if(source)
{
source->enableSource();
}
}
theEnableFlag = true;
}
void ossimImageChain::disableSource()
{
long upper = (ossim_uint32)imageChainList().size();
for(long index = upper - 1; index >= 0; --index)
{
// make sure we initialize in reverse order.
// some source may depend on the initialization of
// its inputs
ossimSource* source = PTR_CAST(ossimSource, imageChainList()[index].get());
if(source)
{
source->disableSource();
}
}
theEnableFlag = false;
}
void ossimImageChain::prepareForRemoval(ossimConnectableObject* connectableObject)
{
if(connectableObject)
{
connectableObject->removeListener((ossimConnectableObjectListener*)this);
connectableObject->changeOwner(0);
connectableObject->disconnect();
}
}
bool ossimImageChain::deleteFirst()
{
if (imageChainList().size() == 0) return false;
ossimContainerEvent event(this, OSSIM_EVENT_REMOVE_OBJECT_ID);
prepareForRemoval(imageChainList()[0].get());
// Clear any listeners, memory.
event.setObjectList(imageChainList()[0].get());
imageChainList()[0] = 0;
// Remove from the vector.
std::vector<ossimRefPtr<ossimConnectableObject> >::iterator i = imageChainList().begin();
imageChainList().erase(i);
fireEvent(event);
return true;
}
bool ossimImageChain::deleteLast()
{
if (imageChainList().size() == 0) return false;
ossimContainerEvent event(this, OSSIM_EVENT_REMOVE_OBJECT_ID);
// Clear any listeners, memory.
ossim_uint32 idx = (ossim_uint32)imageChainList().size() - 1;
prepareForRemoval(imageChainList()[idx].get());
event.setObjectList(imageChainList()[idx].get());
imageChainList()[idx] = 0;
// Remove from the vector.
imageChainList().pop_back();
fireEvent(event);
return true;
}
void ossimImageChain::deleteList()
{
ossim_uint32 upper = (ossim_uint32) imageChainList().size();
ossim_uint32 idx = 0;
ossimContainerEvent event(this, OSSIM_EVENT_REMOVE_OBJECT_ID);
for(; idx < upper; ++idx)
{
if(imageChainList()[idx].valid())
{
event.getObjectList().push_back(imageChainList()[idx].get());
prepareForRemoval(imageChainList()[idx].get());
imageChainList()[idx] = 0;
}
}
imageChainList().clear();
fireEvent(event);
}
void ossimImageChain::disconnectInputEvent(ossimConnectionEvent& event)
{
if(imageChainList().size())
{
if(event.getObject()==this)
{
if(imageChainList()[imageChainList().size()-1].valid())
{
for(ossim_uint32 i = 0; i < event.getNumberOfOldObjects(); ++i)
{
imageChainList()[imageChainList().size()-1]->disconnectMyInput(event.getOldObject(i));
}
}
}
}
}
void ossimImageChain::disconnectOutputEvent(ossimConnectionEvent& /* event */)
{
}
void ossimImageChain::connectInputEvent(ossimConnectionEvent& event)
{
if(imageChainList().size())
{
if(event.getObject()==this)
{
if(imageChainList()[imageChainList().size()-1].valid())
{
for(ossim_uint32 i = 0; i < event.getNumberOfNewObjects(); ++i)
{
ossimConnectableObject* obj = event.getNewObject(i);
imageChainList()[imageChainList().size()-1]->connectMyInputTo(findInputIndex(obj),
obj,
false);
}
}
}
else if(event.getObject() == imageChainList()[0].get())
{
if(!theLoadStateFlag)
{
// theInputObjectList = imageChainList()[0]->getInputList();
}
}
initialize();
}
}
void ossimImageChain::connectOutputEvent(ossimConnectionEvent& /* event */)
{
}
// void ossimImageChain::propertyEvent(ossimPropertyEvent& event)
// {
// if(imageChainList().size())
// {
// ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject,
// event.getObject());
// if(obj)
// {
// ossimImageSource* interface = findSource(obj->getId());
// if(interface)
// {
// ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject,
// interface.getObject());
// if(obj)
// {
// }
// }
// }
// }
// }
void ossimImageChain::objectDestructingEvent(ossimObjectDestructingEvent& event)
{
if(!event.getObject()) return;
if(imageChainList().size()&&(event.getObject()!=this))
{
removeChild(PTR_CAST(ossimConnectableObject,
event.getObject()));
}
}
void ossimImageChain::propagateEventToOutputs(ossimEvent& event)
{
//if(thePropagateEventFlag) return;
//thePropagateEventFlag = true;
if(imageChainList().size())
{
if(imageChainList()[imageChainList().size()-1].valid())
{
imageChainList()[imageChainList().size()-1]->fireEvent(event);
imageChainList()[imageChainList().size()-1]->propagateEventToOutputs(event);
}
}
//ossimConnectableObject::propagateEventToOutputs(event);
// thePropagateEventFlag = false;
}
void ossimImageChain::propagateEventToInputs(ossimEvent& event)
{
// if(thePropagateEventFlag) return;
// thePropagateEventFlag = true;
if(imageChainList().size())
{
if(imageChainList()[0].valid())
{
imageChainList()[0]->fireEvent(event);
imageChainList()[0]->propagateEventToInputs(event);
}
}
// thePropagateEventFlag = false;
}
ossimConnectableObject* ossimImageChain::operator[](ossim_uint32 index)
{
return getConnectableObject(index);
}
ossimConnectableObject* ossimImageChain::getConnectableObject(
ossim_uint32 index)
{
if(imageChainList().size() && (index < imageChainList().size()))
{
return imageChainList()[index].get();
}
return 0;
}
ossim_int32 ossimImageChain::indexOf(ossimConnectableObject* obj)const
{
ossim_uint32 idx = 0;
for(idx = 0; idx < imageChainList().size();++idx)
{
if(imageChainList()[idx] == obj)
{
return (ossim_int32)idx;
}
}
return -1;
}
void ossimImageChain::accept(ossimVisitor& visitor)
{
if(!visitor.hasVisited(this))
{
visitor.visit(this);
ossimVisitor::VisitorType currentType = visitor.getVisitorType();
//---
// Lets make sure inputs and outputs are turned off for we are traversing all children
// and we should not have to have that enabled.
//---
visitor.turnOffVisitorType(ossimVisitor::VISIT_INPUTS|ossimVisitor::VISIT_OUTPUTS);
if(visitor.getVisitorType() & ossimVisitor::VISIT_CHILDREN)
{
ConnectableObjectList::reverse_iterator current = imageChainList().rbegin();
while((current != imageChainList().rend())&&!visitor.stopTraversal())
{
ossimRefPtr<ossimConnectableObject> currentObject = (*current);
if(currentObject.get() && !visitor.hasVisited(currentObject.get())) currentObject->accept(visitor);
++current;
}
}
visitor.setVisitorType(currentType);
ossimConnectableObject::accept(visitor);
}
}
//**************************************************************************************************
// Inserts all of its children and inputs into the container provided. Since ossimImageChain is
// itself a form of container, this method will consolidate this chain with the argument
// container. Therefore this chain object will not be represented in the container (but its
// children will be, with correct input and output connections to external objects).
// Returns TRUE if successful.
//**************************************************************************************************
#if 0
bool ossimImageChain::fillContainer(ossimConnectableContainer& container)
{
// Grab the first source in the chain and let it fill the container with itself and inputs. This
// will traverse down the chain and will even pick up external sources that feed this chain:
ossimRefPtr<ossimConnectableObject> first_source = getFirstSource();
if (!first_source.valid())
return false;
first_source->fillContainer(container);
// Instead of adding ourselves, make sure my first source is properly connected to my output,
// thus obviating the need for this image chain (my chain items become part of 'container':
ConnectableObjectList& obj_list = getOutputList();
ossimRefPtr<ossimConnectableObject> output_connection = 0;
while (!obj_list.empty())
{
// Always pick off the beginning of the list since it is shrinking with each disconnect:
output_connection = obj_list[0];
disconnectMyOutput(output_connection.get(), true, false);
first_source->connectMyOutputTo(output_connection.get());
}
return true;
}
#endif
| 29.397171 | 146 | 0.56548 | vladislav-horbatiuk |
17a291f71fed31824f3edf947665a1616e3b644a | 6,554 | cpp | C++ | modules/platforms/cpp/core-test/src/interop_test.cpp | vvteplygin/ignite | 876a2ca190dbd88f42bc7acecff8b7783ce7ce54 | [
"Apache-2.0"
] | 4,339 | 2015-08-21T21:13:25.000Z | 2022-03-30T09:56:44.000Z | modules/platforms/cpp/core-test/src/interop_test.cpp | vvteplygin/ignite | 876a2ca190dbd88f42bc7acecff8b7783ce7ce54 | [
"Apache-2.0"
] | 1,933 | 2015-08-24T11:37:40.000Z | 2022-03-31T08:37:08.000Z | modules/platforms/cpp/core-test/src/interop_test.cpp | vvteplygin/ignite | 876a2ca190dbd88f42bc7acecff8b7783ce7ce54 | [
"Apache-2.0"
] | 2,140 | 2015-08-21T22:09:00.000Z | 2022-03-25T07:57:34.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <boost/test/unit_test.hpp>
#include "ignite/ignition.h"
#include "ignite/test_utils.h"
using namespace ignite;
using namespace cache;
using namespace boost::unit_test;
namespace
{
/** Test put affinity key Java task. */
const std::string TEST_PUT_AFFINITY_KEY_TASK("org.apache.ignite.platform.PlatformComputePutAffinityKeyTask");
}
class InteropTestSuiteFixture
{
public:
InteropTestSuiteFixture()
{
// No-op.
}
~InteropTestSuiteFixture()
{
ignite::Ignition::StopAll(false);
}
};
/**
* Affinity key class.
*/
struct AffinityKey
{
/** Key */
int32_t key;
/** Affinity key */
int32_t aff;
/**
* Default constructor.
*/
AffinityKey() :
key(0),
aff(0)
{
// No-op.
}
/**
* Constructor.
* @param key Key.
* @param aff Affinity key.
*/
AffinityKey(int32_t key, int32_t aff) :
key(key),
aff(aff)
{
// No-op.
}
};
namespace ignite
{
namespace binary
{
template<>
struct BinaryType<AffinityKey> : BinaryTypeDefaultAll<AffinityKey>
{
static void GetTypeName(std::string& dst)
{
dst = "AffinityKey";
}
static void Write(BinaryWriter& writer, const AffinityKey& obj)
{
writer.WriteInt32("key", obj.key);
writer.WriteInt32("aff", obj.aff);
}
static void Read(BinaryReader& reader, AffinityKey& dst)
{
dst.key = reader.ReadInt32("key");
dst.aff = reader.ReadInt32("aff");
}
static void GetAffinityFieldName(std::string& dst)
{
dst = "aff";
}
};
}
}
BOOST_FIXTURE_TEST_SUITE(InteropTestSuite, InteropTestSuiteFixture)
#ifdef ENABLE_STRING_SERIALIZATION_VER_2_TESTS
BOOST_AUTO_TEST_CASE(StringUtfInvalidSequence)
{
Ignite ignite = ignite_test::StartNode("cache-test.xml");
Cache<std::string, std::string> cache = ignite.CreateCache<std::string, std::string>("Test");
std::string initialValue;
initialValue.push_back(static_cast<unsigned char>(0xD8));
initialValue.push_back(static_cast<unsigned char>(0x00));
try
{
cache.Put("key", initialValue);
std::string cachedValue = cache.Get("key");
BOOST_ERROR("Exception is expected due to invalid format.");
}
catch (const IgniteError&)
{
// Expected in this mode.
}
Ignition::StopAll(false);
}
BOOST_AUTO_TEST_CASE(StringUtfInvalidCodePoint)
{
putenv("IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2=true");
Ignite ignite = ignite_test::StartNode("cache-test.xml");
Cache<std::string, std::string> cache = ignite.CreateCache<std::string, std::string>("Test");
std::string initialValue;
// 1110xxxx 10xxxxxx 10xxxxxx |
// <= 11011000 00000000 | U+D8
// = 11101101 10100000 10000000 | ED A0 80
initialValue.push_back(static_cast<unsigned char>(0xED));
initialValue.push_back(static_cast<unsigned char>(0xA0));
initialValue.push_back(static_cast<unsigned char>(0x80));
cache.Put("key", initialValue);
std::string cachedValue = cache.Get("key");
// This is a valid case. Invalid code points are supported in this mode.
BOOST_CHECK_EQUAL(initialValue, cachedValue);
Ignition::StopAll(false);
}
#endif
BOOST_AUTO_TEST_CASE(StringUtfValid4ByteCodePoint)
{
Ignite ignite = ignite_test::StartPlatformNode("cache-test.xml", "ServerNode");
Cache<std::string, std::string> cache = ignite.CreateCache<std::string, std::string>("Test");
std::string initialValue;
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
// <= 00001 00000001 01001011 | U+1014B
// <= 000 010000 000101 001011 | U+1014B
// = 11110000 10010000 10000101 10001011 | F0 90 85 8B
initialValue.push_back(static_cast<unsigned char>(0xF0));
initialValue.push_back(static_cast<unsigned char>(0x90));
initialValue.push_back(static_cast<unsigned char>(0x85));
initialValue.push_back(static_cast<unsigned char>(0x8B));
cache.Put("key", initialValue);
std::string cachedValue = cache.Get("key");
// This is a valid UTF-8 code point. Should be supported in default mode.
BOOST_CHECK_EQUAL(initialValue, cachedValue);
Ignition::StopAll(false);
}
BOOST_AUTO_TEST_CASE(PutObjectByCppThenByJava)
{
Ignite ignite = ignite_test::StartPlatformNode("interop.xml", "ServerNode");
cache::Cache<AffinityKey, AffinityKey> cache = ignite.GetOrCreateCache<AffinityKey, AffinityKey>("default");
AffinityKey key1(2, 3);
cache.Put(key1, key1);
compute::Compute compute = ignite.GetCompute();
compute.ExecuteJavaTask<int*>(TEST_PUT_AFFINITY_KEY_TASK);
AffinityKey key2(1, 2);
AffinityKey val = cache.Get(key2);
BOOST_CHECK_EQUAL(val.key, 1);
BOOST_CHECK_EQUAL(val.aff, 2);
}
BOOST_AUTO_TEST_CASE(PutObjectPointerByCppThenByJava)
{
Ignite ignite = ignite_test::StartPlatformNode("interop.xml", "ServerNode");
cache::Cache<AffinityKey*, AffinityKey*> cache =
ignite.GetOrCreateCache<AffinityKey*, AffinityKey*>("default");
AffinityKey* key1 = new AffinityKey(2, 3);
cache.Put(key1, key1);
delete key1;
compute::Compute compute = ignite.GetCompute();
compute.ExecuteJavaTask<int*>(TEST_PUT_AFFINITY_KEY_TASK);
AffinityKey* key2 = new AffinityKey(1, 2);
AffinityKey* val = cache.Get(key2);
BOOST_CHECK_EQUAL(val->key, 1);
BOOST_CHECK_EQUAL(val->aff, 2);
delete key2;
delete val;
}
BOOST_AUTO_TEST_SUITE_END()
| 26.642276 | 113 | 0.660665 | vvteplygin |
17a3497f4476a51f14d68b4a6844f65d212f964d | 10,281 | cpp | C++ | test/image_threshold_to_zero_cts.cpp | daemyung/vps | b031151e42fb355446bb4e207b74e65eb0e4b9ac | [
"MIT"
] | null | null | null | test/image_threshold_to_zero_cts.cpp | daemyung/vps | b031151e42fb355446bb4e207b74e65eb0e4b9ac | [
"MIT"
] | null | null | null | test/image_threshold_to_zero_cts.cpp | daemyung/vps | b031151e42fb355446bb4e207b74e65eb0e4b9ac | [
"MIT"
] | null | null | null | //
// This file is part of the "vps" project
// See "LICENSE" for license information.
//
#include <doctest.h>
#include <vps.h>
#define VMA_IMPLEMENTATION
#include <vk_mem_alloc.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image_write.h>
#include <iostream>
using namespace std;
using namespace doctest;
TEST_SUITE_BEGIN("image threshold to zero test suite");
//----------------------------------------------------------------------------------------------------------------------
TEST_CASE("test image threshold to zero")
{
/*Window_desc desc;
desc.title = default_title;
desc.extent = default_extent;
auto window = make_unique<Window>(desc);
CHECK(window);
REQUIRE(window->title() == default_title);
REQUIRE(window->extent() == default_extent);*/
VkResult result;
VkInstance instance;
{
const char* layerNames = "VK_LAYER_KHRONOS_validation";
VkInstanceCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
create_info.enabledLayerCount = 1;
create_info.ppEnabledLayerNames = &layerNames;
result = vkCreateInstance(&create_info, nullptr, &instance);
}
VkPhysicalDevice physical_device;
{
uint32_t cnt = 1;
result = vkEnumeratePhysicalDevices(instance, &cnt, &physical_device);
}
VkDevice device;
{
float priority = 1.0f;
VkDeviceQueueCreateInfo queue_info {};
queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_info.queueFamilyIndex = 0;
queue_info.queueCount = 1;
queue_info.pQueuePriorities = &priority;
VkDeviceCreateInfo info {};
info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
info.queueCreateInfoCount = 1;
info.pQueueCreateInfos = &queue_info;
result = vkCreateDevice(physical_device, &info, nullptr, &device);
}
VmaAllocator allocator;
{
VmaAllocatorCreateInfo create_info {};
create_info.physicalDevice = physical_device;
create_info.device = device;
create_info.instance = instance;
vmaCreateAllocator(&create_info, &allocator);
}
int x, y, n;
unsigned char* contents;
{
contents = stbi_load(VPS_ASSET_PATH"/image/lena.bmp", &x, &y, &n, STBI_rgb_alpha);
// contents = stbi_load("C:/Users/djang/repos/vps/build/vps/src.png", &x, &y, &n, STBI_rgb_alpha);
}
VkImage src_image;
VmaAllocation src_allocation;
VkImageView src_image_view;
{
VkImageCreateInfo image_info {};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
image_info.extent.width = x;
image_info.extent.height = y;
image_info.extent.depth = 1;
image_info.mipLevels = 1;
image_info.arrayLayers = 1;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.tiling = VK_IMAGE_TILING_LINEAR;
// image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
image_info.usage = VK_IMAGE_USAGE_STORAGE_BIT;
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
VmaAllocationCreateInfo allocation_info {};
allocation_info.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
vmaCreateImage(allocator, &image_info, &allocation_info, &src_image, &src_allocation, nullptr);
VkImageViewCreateInfo view_info {};
view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
view_info.image = src_image;
view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
view_info.format = VK_FORMAT_R8G8B8A8_UNORM;
view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
view_info.subresourceRange.baseArrayLayer = 0;
view_info.subresourceRange.baseMipLevel = 0;
view_info.subresourceRange.layerCount = 1;
view_info.subresourceRange.levelCount = 1;
vkCreateImageView(device, &view_info, nullptr, &src_image_view);
}
{
void* ptr;
vmaMapMemory(allocator, src_allocation, &ptr);
memcpy(ptr, contents, x * y * 4);
stbi_image_free(contents);
}
VkImage dst_image;
VmaAllocation dst_allocation;
VkImageView dst_image_view;
VmaAllocationInfo i {};
{
VkImageCreateInfo image_info {};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
image_info.extent.width = x;
image_info.extent.height = y;
image_info.extent.depth = 1;
image_info.mipLevels = 1;
image_info.arrayLayers = 1;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.tiling = VK_IMAGE_TILING_LINEAR;
image_info.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
VmaAllocationCreateInfo allocation_info {};
allocation_info.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
vmaCreateImage(allocator, &image_info, &allocation_info, &dst_image, &dst_allocation, &i);
VkImageViewCreateInfo view_info {};
view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
view_info.image = dst_image;
view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
view_info.format = VK_FORMAT_R8G8B8A8_UNORM;
view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
view_info.subresourceRange.baseArrayLayer = 0;
view_info.subresourceRange.baseMipLevel = 0;
view_info.subresourceRange.layerCount = 1;
view_info.subresourceRange.levelCount = 1;
vkCreateImageView(device, &view_info, nullptr, &dst_image_view);
}
VkBuffer dump;
VmaAllocation dump_alloc;
{
VkBufferCreateInfo buffer_create_info {};
buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_create_info.size = x * y * 4;
buffer_create_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocation_create_info {};
allocation_create_info.usage = VMA_MEMORY_USAGE_CPU_COPY;
result = vmaCreateBuffer(allocator, &buffer_create_info, &allocation_create_info,
&dump, &dump_alloc, nullptr);
}
VkCommandPool command_pool;
{
VkCommandPoolCreateInfo create_info {};
create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
create_info.queueFamilyIndex = 0;
vkCreateCommandPool(device, &create_info, nullptr, &command_pool);
}
VkCommandBuffer cmd_buf;
{
VkCommandBufferAllocateInfo allocate_info {};
allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocate_info.commandPool = command_pool;
allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocate_info.commandBufferCount = 1;
vkAllocateCommandBuffers(device, &allocate_info, &cmd_buf);
}
VkQueue queue;
vkGetDeviceQueue(device, 0, 0, &queue);
VpsContextCreateInfo createInfo {};
createInfo.instance = instance;
createInfo.physicalDevice = physical_device;
createInfo.device = device;
VpsContext context = VK_NULL_HANDLE;
vpsCreateContext(&createInfo, &context);
VkCommandBufferBeginInfo bi {};
bi.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
vkBeginCommandBuffer(cmd_buf, &bi);
{
VkImageMemoryBarrier barriers[2];
barriers[0] = {};
barriers[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barriers[0].srcAccessMask = 0;
barriers[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
barriers[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barriers[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
barriers[0].image = src_image;
barriers[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barriers[0].subresourceRange.baseArrayLayer = 0;
barriers[0].subresourceRange.baseMipLevel = 0;
barriers[0].subresourceRange.layerCount = 1;
barriers[0].subresourceRange.levelCount = 1;
barriers[1] = {};
barriers[1].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barriers[1].srcAccessMask = 0;
barriers[1].dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
barriers[1].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barriers[1].newLayout = VK_IMAGE_LAYOUT_GENERAL;
barriers[1].image = dst_image;
barriers[1].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barriers[1].subresourceRange.baseArrayLayer = 0;
barriers[1].subresourceRange.baseMipLevel = 0;
barriers[1].subresourceRange.layerCount = 1;
barriers[1].subresourceRange.levelCount = 1;
vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 2, barriers);
}
vpsCmdImageThresholdToZero(context, cmd_buf, src_image_view, dst_image_view, 0.2, nullptr);
{
VkImageMemoryBarrier barrier;
barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.image = dst_image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.layerCount = 1;
barrier.subresourceRange.levelCount = 1;
vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
}
{
VkBufferImageCopy region {};
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageSubresource.mipLevel = 0;
region.imageExtent.width = x;
region.imageExtent.height = y;
region.imageExtent.depth = 1;
vkCmdCopyImageToBuffer(cmd_buf, dst_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dump, 1, ®ion);
}
vkEndCommandBuffer(cmd_buf);
VkSubmitInfo si {};
si.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
si.commandBufferCount = 1;
si.pCommandBuffers = &cmd_buf;
vkQueueSubmit(queue, 1, &si, VK_NULL_HANDLE);
vkDeviceWaitIdle(device);
void* p;
vmaMapMemory(allocator, dump_alloc, &p);
stbi_write_png("result.png", x, y, STBI_rgb_alpha, p, 0);
// vpsDestoryContext(context);
}
//----------------------------------------------------------------------------------------------------------------------
TEST_SUITE_END();
| 29.458453 | 146 | 0.744383 | daemyung |
17a387e83243244c68727d5b43f0490e257a98f1 | 5,425 | cpp | C++ | TileServer und Tiles/threadfilereaders.cpp | andr1312e/Russia-Tiles-Server | c1d596b84e22c170ba0f795ed6e2bfb80167eeb6 | [
"Unlicense"
] | null | null | null | TileServer und Tiles/threadfilereaders.cpp | andr1312e/Russia-Tiles-Server | c1d596b84e22c170ba0f795ed6e2bfb80167eeb6 | [
"Unlicense"
] | null | null | null | TileServer und Tiles/threadfilereaders.cpp | andr1312e/Russia-Tiles-Server | c1d596b84e22c170ba0f795ed6e2bfb80167eeb6 | [
"Unlicense"
] | null | null | null | #include "threadfilereaders.h"
ThreadImageRotator::ThreadImageRotator(const QString *pathToSourceSvg,const QString *pathToRendedImage,const QString *fileType, const QString *slash, QObject *parent)
: QObject(parent)
, m_timer(new QTimer(this))
, m_imageRotatorHash(new QHash<QThread*, ImageRotator*>())
, m_freeThreadsQueue(new std::queue<QThread*>())
, m_tilesQueue(new std::queue<TileData>())
, m_svgType(new QString(QStringLiteral(".svg")))
{
qInfo()<<"ThreadFileReader constructor";
initTimer();
createDataStructs(pathToSourceSvg, pathToRendedImage, fileType, slash);
createConnections();
}
ThreadImageRotator::~ThreadImageRotator()
{
QHashIterator<QThread*, ImageRotator*> iterator(*m_imageRotatorHash);
while (iterator.hasNext()) {
iterator.next();
delete iterator.value();
delete iterator.key();
}
delete m_tilesQueue;
delete m_imageRotatorHash;
delete m_freeThreadsQueue;
delete m_timer;
}
void ThreadImageRotator::gettingTilesToConvert(QStringList &tiles, int &numOfImages, QString &azm, QString &layer)
{
char firstParam=azm.at(0).toLatin1();
char secondParam=azm.at(1).toLatin1();
char thirdParam=azm.at(2).toLatin1();
QStringList::iterator it=tiles.begin();
if(m_freeThreadsQueue->size()>=numOfImages)
{
for (; it!=tiles.end(); ++it)
{
QThread *thread=m_freeThreadsQueue->front();
m_freeThreadsQueue->pop();
m_imageRotatorHash->value(thread)->setParams(*it, azm, layer, firstParam, secondParam, thirdParam);
thread->start();
}
}
else
{
int numImagesToQueue=numOfImages;
for (int i=0; i<m_freeThreadsQueue->size(); i++, ++it)
{
QThread *thread=m_freeThreadsQueue->front();
m_freeThreadsQueue->pop();
m_imageRotatorHash->value(thread)->setParams(*it, azm, layer, firstParam, secondParam, thirdParam);
thread->start();
numImagesToQueue--;
}
for (int i=numOfImages-1; i>numOfImages-numImagesToQueue; i--)
{
m_tilesQueue->push(TileData(tiles[i], azm , layer));
}
m_timer->start(m_timerInterval);
}
}
void ThreadImageRotator::seekAvailableThreads()
{
if (!m_tilesQueue->empty())
{
readFilesFromQueue();
}
}
void ThreadImageRotator::addThreadToQueue()
{
m_freeThreadsQueue->push(qobject_cast<QThread *>(sender()));
}
void ThreadImageRotator::readFilesFromQueue()
{
if (!m_tilesQueue->empty()&&!m_freeThreadsQueue->empty())
{
if(m_tilesQueue->size()<=m_freeThreadsQueue->size())
{
for (int i=0; i<m_tilesQueue->size(); i++)
{
TileData tile= m_tilesQueue->front();
m_tilesQueue->pop();
char firstParam=tile.azm.at(0).toLatin1();
char secondParam=tile.azm.at(1).toLatin1();
char thirdParam=tile.azm.at(2).toLatin1();
QThread *thread=m_freeThreadsQueue->front();
m_freeThreadsQueue->pop();
m_imageRotatorHash->operator [](thread)->setParams(tile.tile, tile.azm, tile.layer, firstParam, secondParam, thirdParam);
thread->start(QThread::TimeCriticalPriority);
}
}
else
{
for (int i=0; i<m_freeThreadsQueue->size(); i++)
{
TileData tile= m_tilesQueue->front();
m_tilesQueue->pop();
char firstParam=tile.azm.at(0).toLatin1();
char secondParam=tile.azm.at(1).toLatin1();
char thirdParam=tile.azm.at(2).toLatin1();
QThread *thread=m_freeThreadsQueue->front();
m_freeThreadsQueue->pop();
m_imageRotatorHash->operator [](thread)->setParams(tile.tile, tile.azm, tile.layer, firstParam, secondParam, thirdParam);
thread->start(QThread::TimeCriticalPriority);
}
m_timer->start(m_timerInterval);
}
}
}
void ThreadImageRotator::initTimer()
{
m_timer->setInterval(m_timerInterval);
m_timer->setTimerType(Qt::CoarseTimer);
m_timer->setSingleShot(true);
}
void ThreadImageRotator::createDataStructs(const QString *pathToSourceSvg,const QString *pathToRendedImage,const QString *fileType, const QString *slash)
{
for (int i=0; i<m_numOfThreads; i++)
{
m_imageRotatorHash->insert(new QThread(), new ImageRotator(pathToSourceSvg, pathToRendedImage, fileType, slash, m_svgType, nullptr));
}
QList<QThread*>keys=m_imageRotatorHash->keys();
for (QList<QThread*>::const_iterator it=keys.cbegin(), total = keys.cend(); it!=total; ++it)
{
m_freeThreadsQueue->push(*it);
}
}
void ThreadImageRotator::createConnections()
{
QHashIterator<QThread*, ImageRotator*> iterator(*m_imageRotatorHash);
while (iterator.hasNext()) {
iterator.next();
connect(iterator.key(), &QThread::started, iterator.value(), &ImageRotator::doing);
connect(iterator.value(), &ImageRotator::finished, iterator.key(), &QThread::quit);
connect(iterator.key(), &QThread::finished, this, &ThreadImageRotator::addThreadToQueue);
iterator.value()->moveToThread(iterator.key());
}
connect(m_timer, &QTimer::timeout, this, &ThreadImageRotator::seekAvailableThreads);
}
| 36.409396 | 166 | 0.634101 | andr1312e |
17a814171d3c904d198d4b9d6d67e1528c9bb81f | 10,273 | cpp | C++ | source/Core/Castor3D/Render/GlobalIllumination/VoxelConeTracing/Voxelizer.cpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 245 | 2015-10-29T14:31:45.000Z | 2022-03-31T13:04:45.000Z | source/Core/Castor3D/Render/GlobalIllumination/VoxelConeTracing/Voxelizer.cpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 64 | 2016-03-11T19:45:05.000Z | 2022-03-31T23:58:33.000Z | source/Core/Castor3D/Render/GlobalIllumination/VoxelConeTracing/Voxelizer.cpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 11 | 2018-05-24T09:07:43.000Z | 2022-03-21T21:05:20.000Z | #include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/Voxelizer.hpp"
#include "Castor3D/DebugDefines.hpp"
#include "Castor3D/Engine.hpp"
#include "Castor3D/Buffer/GpuBuffer.hpp"
#include "Castor3D/Buffer/UniformBufferPools.hpp"
#include "Castor3D/Event/Frame/GpuFunctorEvent.hpp"
#include "Castor3D/Material/Texture/Sampler.hpp"
#include "Castor3D/Material/Texture/TextureLayout.hpp"
#include "Castor3D/Miscellaneous/ProgressBar.hpp"
#include "Castor3D/Render/RenderDevice.hpp"
#include "Castor3D/Render/Technique/RenderTechniqueVisitor.hpp"
#include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelBufferToTexture.hpp"
#include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelizePass.hpp"
#include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelSceneData.hpp"
#include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelSecondaryBounce.hpp"
#include "Castor3D/Scene/Camera.hpp"
#include "Castor3D/Scene/Scene.hpp"
#include "Castor3D/Scene/SceneNode.hpp"
#include "Castor3D/Shader/ShaderBuffer.hpp"
#include "Castor3D/Shader/Shaders/GlslVoxel.hpp"
#include "Castor3D/Shader/Ubos/VoxelizerUbo.hpp"
#include <CastorUtils/Design/ResourceCache.hpp>
#include <CastorUtils/Miscellaneous/BitSize.hpp>
#include <ashespp/RenderPass/FrameBuffer.hpp>
#include <RenderGraph/FrameGraph.hpp>
#include <RenderGraph/GraphContext.hpp>
#include <RenderGraph/RunnablePasses/GenerateMipmaps.hpp>
CU_ImplementCUSmartPtr( castor3d, Voxelizer )
using namespace castor;
namespace castor3d
{
//*********************************************************************************************
namespace
{
Texture createTexture( RenderDevice const & device
, crg::ResourceHandler & handler
, String const & name
, VkExtent3D const & size )
{
return Texture{ device
, handler
, name
, VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT
, size
, 1u
, getMipLevels( size, VK_FORMAT_R16G16B16A16_SFLOAT )
, VK_FORMAT_R16G16B16A16_SFLOAT
, ( VK_IMAGE_USAGE_STORAGE_BIT
| VK_IMAGE_USAGE_TRANSFER_SRC_BIT
| VK_IMAGE_USAGE_TRANSFER_DST_BIT
| VK_IMAGE_USAGE_SAMPLED_BIT )
, VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK
, false };
}
ashes::BufferPtr< Voxel > createSsbo( Engine & engine
, RenderDevice const & device
, String const & name
, uint32_t voxelGridSize )
{
return castor3d::makeBuffer< Voxel >( device
, voxelGridSize * voxelGridSize * voxelGridSize
, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT
, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT
, name );
}
}
//*********************************************************************************************
Voxelizer::Voxelizer( crg::ResourceHandler & handler
, RenderDevice const & device
, ProgressBar * progress
, Scene & scene
, Camera & camera
, MatrixUbo & matrixUbo
, VoxelizerUbo & voxelizerUbo
, VoxelSceneData const & voxelConfig )
: m_engine{ *device.renderSystem.getEngine() }
, m_device{ device }
, m_voxelConfig{ voxelConfig }
, m_graph{ handler, "Voxelizer" }
, m_culler{ scene, &camera }
, m_matrixUbo{ device }
, m_firstBounce{ createTexture( device, handler, "VoxelizedSceneFirstBounce", { m_voxelConfig.gridSize.value(), m_voxelConfig.gridSize.value(), m_voxelConfig.gridSize.value() } ) }
, m_secondaryBounce{ createTexture( device, handler, "VoxelizedSceneSecondaryBounce", { m_voxelConfig.gridSize.value(), m_voxelConfig.gridSize.value(), m_voxelConfig.gridSize.value() } ) }
, m_voxels{ createSsbo( m_engine, device, "VoxelizedSceneBuffer", m_voxelConfig.gridSize.value() ) }
, m_voxelizerUbo{ voxelizerUbo }
, m_voxelizePassDesc{ doCreateVoxelizePass( progress ) }
, m_voxelToTextureDesc{ doCreateVoxelToTexture( m_voxelizePassDesc, progress ) }
, m_voxelMipGen{ doCreateVoxelMipGen( m_voxelToTextureDesc, "FirstBounceMip", m_firstBounce.wholeViewId, progress ) }
, m_voxelSecondaryBounceDesc{ doCreateVoxelSecondaryBounce( m_voxelMipGen, progress ) }
, m_voxelSecondaryMipGen{ doCreateVoxelMipGen( m_voxelSecondaryBounceDesc, "SecondaryBounceMip", m_secondaryBounce.wholeViewId, progress ) }
, m_runnable{ m_graph.compile( m_device.makeContext() ) }
{
m_firstBounce.create();
m_secondaryBounce.create();
auto runnable = m_runnable.get();
m_device.renderSystem.getEngine()->postEvent( makeGpuFunctorEvent( EventType::ePreRender
, [runnable]( RenderDevice const &
, QueueData const & )
{
runnable->record();
} ) );
}
Voxelizer::~Voxelizer()
{
m_runnable.reset();
m_voxels.reset();
m_engine.getSamplerCache().remove( "VoxelizedSceneSecondaryBounce" );
m_engine.getSamplerCache().remove( "VoxelizedSceneFirstBounce" );
}
void Voxelizer::update( CpuUpdater & updater )
{
if ( m_voxelizePass )
{
auto & camera = *updater.camera;
auto & aabb = camera.getScene()->getBoundingBox();
auto max = std::max( aabb.getDimensions()->x, std::max( aabb.getDimensions()->y, aabb.getDimensions()->z ) );
auto cellSize = float( m_voxelConfig.gridSize.value() ) / max;
auto voxelSize = ( cellSize * m_voxelConfig.voxelSizeFactor );
m_grid = castor::Point4f{ 0.0f
, 0.0f
, 0.0f
, voxelSize };
m_voxelizePass->update( updater );
m_voxelizerUbo.cpuUpdate( m_voxelConfig
, voxelSize
, m_voxelConfig.gridSize.value() );
}
}
void Voxelizer::update( GpuUpdater & updater )
{
if ( m_voxelizePass )
{
m_voxelizePass->update( updater );
}
}
void Voxelizer::accept( RenderTechniqueVisitor & visitor )
{
visitor.visit( "Voxelisation First Bounce"
, m_firstBounce
, m_graph.getFinalLayout( m_firstBounce.wholeViewId ).layout
, TextureFactors::tex3D( &m_grid ) );
visitor.visit( "Voxelisation Secondary Bounce"
, m_secondaryBounce
, m_graph.getFinalLayout( m_secondaryBounce.wholeViewId ).layout
, TextureFactors::tex3D( &m_grid ) );
m_voxelizePass->accept( visitor );
m_voxelToTexture->accept( visitor );
m_voxelSecondaryBounce->accept( visitor );
}
crg::SemaphoreWait Voxelizer::render( crg::SemaphoreWait const & semaphore
, ashes::Queue const & queue )
{
return m_runnable->run( semaphore, queue );
}
crg::FramePass & Voxelizer::doCreateVoxelizePass( ProgressBar * progress )
{
stepProgressBar( progress, "Creating voxelize pass" );
auto & result = m_graph.createPass( "VoxelizePass"
, [this, progress]( crg::FramePass const & framePass
, crg::GraphContext & context
, crg::RunnableGraph & runnableGraph )
{
stepProgressBar( progress, "Initialising voxelize pass" );
auto res = std::make_unique< VoxelizePass >( framePass
, context
, runnableGraph
, m_device
, m_matrixUbo
, m_culler
, m_voxelizerUbo
, *m_voxels
, m_voxelConfig );
m_voxelizePass = res.get();
m_device.renderSystem.getEngine()->registerTimer( runnableGraph.getName() + "/Voxelizer"
, res->getTimer() );
return res;
} );
result.addOutputStorageBuffer( { m_voxels->getBuffer(), "Voxels" }
, 0u
, 0u
, m_voxels->getBuffer().getSize() );
return result;
}
crg::FramePass & Voxelizer::doCreateVoxelToTexture( crg::FramePass const & previousPass
, ProgressBar * progress )
{
stepProgressBar( progress, "Creating voxel buffer to texture pass" );
auto & result = m_graph.createPass( "VoxelBufferToTexture"
, [this, progress]( crg::FramePass const & framePass
, crg::GraphContext & context
, crg::RunnableGraph & runnableGraph )
{
stepProgressBar( progress, "Initialising voxel buffer to texture pass" );
auto res = std::make_unique< VoxelBufferToTexture >( framePass
, context
, runnableGraph
, m_device
, m_voxelConfig );
m_voxelToTexture = res.get();
m_device.renderSystem.getEngine()->registerTimer( runnableGraph.getName() + "/Voxelizer"
, res->getTimer() );
return res;
} );
result.addDependency( previousPass );
result.addInputStorageBuffer( { m_voxels->getBuffer(), "Voxels" }
, 0u
, 0u
, m_voxels->getBuffer().getSize() );
result.addOutputStorageView( m_firstBounce.wholeViewId
, 1u
, VK_IMAGE_LAYOUT_UNDEFINED );
return result;
}
crg::FramePass & Voxelizer::doCreateVoxelMipGen( crg::FramePass const & previousPass
, std::string const & name
, crg::ImageViewId const & view
, ProgressBar * progress )
{
stepProgressBar( progress, "Creating voxel mipmap generation pass" );
auto & result = m_graph.createPass( name
, [this, progress]( crg::FramePass const & framePass
, crg::GraphContext & context
, crg::RunnableGraph & runnableGraph )
{
stepProgressBar( progress, "Initialising voxel mipmap generation pass" );
auto res = std::make_unique< crg::GenerateMipmaps >( framePass
, context
, runnableGraph
, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL );
m_device.renderSystem.getEngine()->registerTimer( runnableGraph.getName() + "/Voxelizer"
, res->getTimer() );
return res;
} );
result.addDependency( previousPass );
result.addTransferInOutView( view );
return result;
}
crg::FramePass & Voxelizer::doCreateVoxelSecondaryBounce( crg::FramePass const & previousPass
, ProgressBar * progress )
{
stepProgressBar( progress, "Creating voxel secondary bounce pass" );
auto & result = m_graph.createPass( "VoxelSecondaryBounce"
, [this, progress]( crg::FramePass const & framePass
, crg::GraphContext & context
, crg::RunnableGraph & runnableGraph )
{
stepProgressBar( progress, "Initialising voxel secondary bounce pass" );
auto res = std::make_unique< VoxelSecondaryBounce >( framePass
, context
, runnableGraph
, m_device
, m_voxelConfig );
m_voxelSecondaryBounce = res.get();
m_device.renderSystem.getEngine()->registerTimer( runnableGraph.getName() + "/Voxelizer"
, res->getTimer() );
return res;
} );
result.addDependency( previousPass );
result.addInOutStorageBuffer( { m_voxels->getBuffer(), "Voxels" }
, 0u
, 0u
, m_voxels->getBuffer().getSize() );
m_voxelizerUbo.createPassBinding( result
, 1u );
result.addSampledView( m_firstBounce.wholeViewId
, 2u
, VK_IMAGE_LAYOUT_UNDEFINED );
result.addOutputStorageView( m_secondaryBounce.wholeViewId
, 3u
, VK_IMAGE_LAYOUT_UNDEFINED );
return result;
}
}
| 34.942177 | 190 | 0.710698 | Mu-L |
17aab0402839379eaf08c6e9f0ef25b622ba1ae6 | 15,240 | cc | C++ | genfit/GBL/src/GblPoint.cc | Plamenna/proba | 517d7e437865c372e538f77d2242c188740f35d9 | [
"BSD-4-Clause"
] | null | null | null | genfit/GBL/src/GblPoint.cc | Plamenna/proba | 517d7e437865c372e538f77d2242c188740f35d9 | [
"BSD-4-Clause"
] | null | null | null | genfit/GBL/src/GblPoint.cc | Plamenna/proba | 517d7e437865c372e538f77d2242c188740f35d9 | [
"BSD-4-Clause"
] | null | null | null | /*
* GblPoint.cpp
*
* Created on: Aug 18, 2011
* Author: kleinwrt
*/
#include "GblPoint.h"
//! Namespace for the general broken lines package
namespace gbl {
/// Create a point.
/**
* Create point on (initial) trajectory. Needs transformation jacobian from previous point.
* \param [in] aJacobian Transformation jacobian from previous point
*/
GblPoint::GblPoint(const TMatrixD &aJacobian) :
theLabel(0), theOffset(0), measDim(0), transFlag(false), measTransformation(), scatFlag(
false), localDerivatives(), globalLabels(), globalDerivatives() {
for (unsigned int i = 0; i < 5; ++i) {
for (unsigned int j = 0; j < 5; ++j) {
p2pJacobian(i, j) = aJacobian(i, j);
}
}
}
GblPoint::GblPoint(const SMatrix55 &aJacobian) :
theLabel(0), theOffset(0), p2pJacobian(aJacobian), measDim(0), transFlag(
false), measTransformation(), scatFlag(false), localDerivatives(), globalLabels(), globalDerivatives() {
}
GblPoint::~GblPoint() {
}
/// Add a measurement to a point.
/**
* Add measurement (in meas. system) with diagonal precision (inverse covariance) matrix.
* ((up to) 2D: position, 4D: slope+position, 5D: curvature+slope+position)
* \param [in] aProjection Projection from local to measurement system
* \param [in] aResiduals Measurement residuals
* \param [in] aPrecision Measurement precision (diagonal)
* \param [in] minPrecision Minimal precision to accept measurement
*/
void GblPoint::addMeasurement(const TMatrixD &aProjection,
const TVectorD &aResiduals, const TVectorD &aPrecision,
double minPrecision) {
measDim = aResiduals.GetNrows();
unsigned int iOff = 5 - measDim;
for (unsigned int i = 0; i < measDim; ++i) {
measResiduals(iOff + i) = aResiduals[i];
measPrecision(iOff + i) = (
aPrecision[i] >= minPrecision ? aPrecision[i] : 0.);
for (unsigned int j = 0; j < measDim; ++j) {
measProjection(iOff + i, iOff + j) = aProjection(i, j);
}
}
}
/// Add a measurement to a point.
/**
* Add measurement (in meas. system) with arbitrary precision (inverse covariance) matrix.
* Will be diagonalized.
* ((up to) 2D: position, 4D: slope+position, 5D: curvature+slope+position)
* \param [in] aProjection Projection from local to measurement system
* \param [in] aResiduals Measurement residuals
* \param [in] aPrecision Measurement precision (matrix)
* \param [in] minPrecision Minimal precision to accept measurement
*/
void GblPoint::addMeasurement(const TMatrixD &aProjection,
const TVectorD &aResiduals, const TMatrixDSym &aPrecision,
double minPrecision) {
measDim = aResiduals.GetNrows();
TMatrixDSymEigen measEigen(aPrecision);
measTransformation.ResizeTo(measDim, measDim);
measTransformation = measEigen.GetEigenVectors();
measTransformation.T();
transFlag = true;
TVectorD transResiduals = measTransformation * aResiduals;
TVectorD transPrecision = measEigen.GetEigenValues();
TMatrixD transProjection = measTransformation * aProjection;
unsigned int iOff = 5 - measDim;
for (unsigned int i = 0; i < measDim; ++i) {
measResiduals(iOff + i) = transResiduals[i];
measPrecision(iOff + i) = (
transPrecision[i] >= minPrecision ? transPrecision[i] : 0.);
for (unsigned int j = 0; j < measDim; ++j) {
measProjection(iOff + i, iOff + j) = transProjection(i, j);
}
}
}
/// Add a measurement to a point.
/**
* Add measurement in local system with diagonal precision (inverse covariance) matrix.
* ((up to) 2D: position, 4D: slope+position, 5D: curvature+slope+position)
* \param [in] aResiduals Measurement residuals
* \param [in] aPrecision Measurement precision (diagonal)
* \param [in] minPrecision Minimal precision to accept measurement
*/
void GblPoint::addMeasurement(const TVectorD &aResiduals,
const TVectorD &aPrecision, double minPrecision) {
measDim = aResiduals.GetNrows();
unsigned int iOff = 5 - measDim;
for (unsigned int i = 0; i < measDim; ++i) {
measResiduals(iOff + i) = aResiduals[i];
measPrecision(iOff + i) = (
aPrecision[i] >= minPrecision ? aPrecision[i] : 0.);
}
measProjection = ROOT::Math::SMatrixIdentity();
}
/// Add a measurement to a point.
/**
* Add measurement in local system with arbitrary precision (inverse covariance) matrix.
* Will be diagonalized.
* ((up to) 2D: position, 4D: slope+position, 5D: curvature+slope+position)
* \param [in] aResiduals Measurement residuals
* \param [in] aPrecision Measurement precision (matrix)
* \param [in] minPrecision Minimal precision to accept measurement
*/
void GblPoint::addMeasurement(const TVectorD &aResiduals,
const TMatrixDSym &aPrecision, double minPrecision) {
measDim = aResiduals.GetNrows();
TMatrixDSymEigen measEigen(aPrecision);
measTransformation.ResizeTo(measDim, measDim);
measTransformation = measEigen.GetEigenVectors();
measTransformation.T();
transFlag = true;
TVectorD transResiduals = measTransformation * aResiduals;
TVectorD transPrecision = measEigen.GetEigenValues();
unsigned int iOff = 5 - measDim;
for (unsigned int i = 0; i < measDim; ++i) {
measResiduals(iOff + i) = transResiduals[i];
measPrecision(iOff + i) = (
transPrecision[i] >= minPrecision ? transPrecision[i] : 0.);
for (unsigned int j = 0; j < measDim; ++j) {
measProjection(iOff + i, iOff + j) = measTransformation(i, j);
}
}
}
/// Check for measurement at a point.
/**
* Get dimension of measurement (0 = none).
* \return measurement dimension
*/
unsigned int GblPoint::hasMeasurement() const {
return measDim;
}
/// Retrieve measurement of a point.
/**
* \param [out] aProjection Projection from (diagonalized) measurement to local system
* \param [out] aResiduals Measurement residuals
* \param [out] aPrecision Measurement precision (diagonal)
*/
void GblPoint::getMeasurement(SMatrix55 &aProjection, SVector5 &aResiduals,
SVector5 &aPrecision) const {
aProjection = measProjection;
aResiduals = measResiduals;
aPrecision = measPrecision;
}
/// Get measurement transformation (from diagonalization).
/**
* \param [out] aTransformation Transformation matrix
*/
void GblPoint::getMeasTransformation(TMatrixD &aTransformation) const {
aTransformation.ResizeTo(measDim, measDim);
if (transFlag) {
aTransformation = measTransformation;
} else {
aTransformation.UnitMatrix();
}
}
/// Add a (thin) scatterer to a point.
/**
* Add scatterer with diagonal precision (inverse covariance) matrix.
* Changes local track direction.
*
* \param [in] aResiduals Scatterer residuals
* \param [in] aPrecision Scatterer precision (diagonal of inverse covariance matrix)
*/
void GblPoint::addScatterer(const TVectorD &aResiduals,
const TVectorD &aPrecision) {
scatFlag = true;
scatResiduals(0) = aResiduals[0];
scatResiduals(1) = aResiduals[1];
scatPrecision(0) = aPrecision[0];
scatPrecision(1) = aPrecision[1];
scatTransformation = ROOT::Math::SMatrixIdentity();
}
/// Add a (thin) scatterer to a point.
/**
* Add scatterer with arbitrary precision (inverse covariance) matrix.
* Will be diagonalized. Changes local track direction.
*
* The precision matrix for the local slopes is defined by the
* angular scattering error theta_0 and the scalar products c_1, c_2 of the
* offset directions in the local frame with the track direction:
*
* (1 - c_1*c_1 - c_2*c_2) | 1 - c_1*c_1 - c_1*c_2 |
* P = ~~~~~~~~~~~~~~~~~~~~~~~ * | |
* theta_0*theta_0 | - c_1*c_2 1 - c_2*c_2 |
*
* \param [in] aResiduals Scatterer residuals
* \param [in] aPrecision Scatterer precision (matrix)
*/
void GblPoint::addScatterer(const TVectorD &aResiduals,
const TMatrixDSym &aPrecision) {
scatFlag = true;
TMatrixDSymEigen scatEigen(aPrecision);
TMatrixD aTransformation = scatEigen.GetEigenVectors();
aTransformation.T();
TVectorD transResiduals = aTransformation * aResiduals;
TVectorD transPrecision = scatEigen.GetEigenValues();
for (unsigned int i = 0; i < 2; ++i) {
scatResiduals(i) = transResiduals[i];
scatPrecision(i) = transPrecision[i];
for (unsigned int j = 0; j < 2; ++j) {
scatTransformation(i, j) = aTransformation(i, j);
}
}
}
/// Check for scatterer at a point.
bool GblPoint::hasScatterer() const {
return scatFlag;
}
/// Retrieve scatterer of a point.
/**
* \param [out] aTransformation Scatterer transformation from diagonalization
* \param [out] aResiduals Scatterer residuals
* \param [out] aPrecision Scatterer precision (diagonal)
*/
void GblPoint::getScatterer(SMatrix22 &aTransformation, SVector2 &aResiduals,
SVector2 &aPrecision) const {
aTransformation = scatTransformation;
aResiduals = scatResiduals;
aPrecision = scatPrecision;
}
/// Get scatterer transformation (from diagonalization).
/**
* \param [out] aTransformation Transformation matrix
*/
void GblPoint::getScatTransformation(TMatrixD &aTransformation) const {
aTransformation.ResizeTo(2, 2);
if (scatFlag) {
for (unsigned int i = 0; i < 2; ++i) {
for (unsigned int j = 0; j < 2; ++j) {
aTransformation(i, j) = scatTransformation(i, j);
}
}
} else {
aTransformation.UnitMatrix();
}
}
/// Add local derivatives to a point.
/**
* Point needs to have a measurement.
* \param [in] aDerivatives Local derivatives (matrix)
*/
void GblPoint::addLocals(const TMatrixD &aDerivatives) {
if (measDim) {
localDerivatives.ResizeTo(aDerivatives);
if (transFlag) {
localDerivatives = measTransformation * aDerivatives;
} else {
localDerivatives = aDerivatives;
}
}
}
/// Retrieve number of local derivatives from a point.
unsigned int GblPoint::getNumLocals() const {
return localDerivatives.GetNcols();
}
/// Retrieve local derivatives from a point.
const TMatrixD& GblPoint::getLocalDerivatives() const {
return localDerivatives;
}
/// Add global derivatives to a point.
/**
* Point needs to have a measurement.
* \param [in] aLabels Global derivatives labels
* \param [in] aDerivatives Global derivatives (matrix)
*/
void GblPoint::addGlobals(const std::vector<int> &aLabels,
const TMatrixD &aDerivatives) {
if (measDim) {
globalLabels = aLabels;
globalDerivatives.ResizeTo(aDerivatives);
if (transFlag) {
globalDerivatives = measTransformation * aDerivatives;
} else {
globalDerivatives = aDerivatives;
}
}
}
/// Retrieve number of global derivatives from a point.
unsigned int GblPoint::getNumGlobals() const {
return globalDerivatives.GetNcols();
}
/// Retrieve global derivatives labels from a point.
std::vector<int> GblPoint::getGlobalLabels() const {
return globalLabels;
}
/// Retrieve global derivatives from a point.
const TMatrixD& GblPoint::getGlobalDerivatives() const {
return globalDerivatives;
}
/// Define label of point (by GBLTrajectory constructor)
/**
* \param [in] aLabel Label identifying point
*/
void GblPoint::setLabel(unsigned int aLabel) {
theLabel = aLabel;
}
/// Retrieve label of point
unsigned int GblPoint::getLabel() const {
return theLabel;
}
/// Define offset for point (by GBLTrajectory constructor)
/**
* \param [in] anOffset Offset number
*/
void GblPoint::setOffset(int anOffset) {
theOffset = anOffset;
}
/// Retrieve offset for point
int GblPoint::getOffset() const {
return theOffset;
}
/// Retrieve point-to-(previous)point jacobian
const SMatrix55& GblPoint::getP2pJacobian() const {
return p2pJacobian;
}
/// Define jacobian to previous scatterer (by GBLTrajectory constructor)
/**
* \param [in] aJac Jacobian
*/
void GblPoint::addPrevJacobian(const SMatrix55 &aJac) {
int ifail = 0;
// to optimize: need only two last rows of inverse
// prevJacobian = aJac.InverseFast(ifail);
// block matrix algebra
SMatrix23 CA = aJac.Sub<SMatrix23>(3, 0)
* aJac.Sub<SMatrix33>(0, 0).InverseFast(ifail); // C*A^-1
SMatrix22 DCAB = aJac.Sub<SMatrix22>(3, 3) - CA * aJac.Sub<SMatrix32>(0, 3); // D - C*A^-1 *B
DCAB.InvertFast();
prevJacobian.Place_at(DCAB, 3, 3);
prevJacobian.Place_at(-DCAB * CA, 3, 0);
}
/// Define jacobian to next scatterer (by GBLTrajectory constructor)
/**
* \param [in] aJac Jacobian
*/
void GblPoint::addNextJacobian(const SMatrix55 &aJac) {
nextJacobian = aJac;
}
/// Retrieve derivatives of local track model
/**
* Linearized track model: F_u(q/p,u',u) = J*u + S*u' + d*q/p,
* W is inverse of S, negated for backward propagation.
* \param [in] aDirection Propagation direction (>0 forward, else backward)
* \param [out] matW W
* \param [out] matWJ W*J
* \param [out] vecWd W*d
* \exception std::overflow_error : matrix S is singular.
*/
void GblPoint::getDerivatives(int aDirection, SMatrix22 &matW, SMatrix22 &matWJ,
SVector2 &vecWd) const {
SMatrix22 matJ;
SVector2 vecd;
if (aDirection < 1) {
matJ = prevJacobian.Sub<SMatrix22>(3, 3);
matW = -prevJacobian.Sub<SMatrix22>(3, 1);
vecd = prevJacobian.SubCol<SVector2>(0, 3);
} else {
matJ = nextJacobian.Sub<SMatrix22>(3, 3);
matW = nextJacobian.Sub<SMatrix22>(3, 1);
vecd = nextJacobian.SubCol<SVector2>(0, 3);
}
if (!matW.InvertFast()) {
std::cout << " GblPoint::getDerivatives failed to invert matrix: "
<< matW << std::endl;
std::cout
<< " Possible reason for singular matrix: multiple GblPoints at same arc-length"
<< std::endl;
throw std::overflow_error("Singular matrix inversion exception");
}
matWJ = matW * matJ;
vecWd = matW * vecd;
}
/// Print GblPoint
/**
* \param [in] level print level (0: minimum, >0: more)
*/
void GblPoint::printPoint(unsigned int level) const {
std::cout << " GblPoint";
if (theLabel) {
std::cout << ", label " << theLabel;
if (theOffset >= 0) {
std::cout << ", offset " << theOffset;
}
}
if (measDim) {
std::cout << ", " << measDim << " measurements";
}
if (scatFlag) {
std::cout << ", scatterer";
}
if (transFlag) {
std::cout << ", diagonalized";
}
if (localDerivatives.GetNcols()) {
std::cout << ", " << localDerivatives.GetNcols()
<< " local derivatives";
}
if (globalDerivatives.GetNcols()) {
std::cout << ", " << globalDerivatives.GetNcols()
<< " global derivatives";
}
std::cout << std::endl;
if (level > 0) {
if (measDim) {
std::cout << " Measurement" << std::endl;
std::cout << " Projection: " << std::endl << measProjection
<< std::endl;
std::cout << " Residuals: " << measResiduals << std::endl;
std::cout << " Precision: " << measPrecision << std::endl;
}
if (scatFlag) {
std::cout << " Scatterer" << std::endl;
std::cout << " Residuals: " << scatResiduals << std::endl;
std::cout << " Precision: " << scatPrecision << std::endl;
}
if (localDerivatives.GetNcols()) {
std::cout << " Local Derivatives:" << std::endl;
localDerivatives.Print();
}
if (globalDerivatives.GetNcols()) {
std::cout << " Global Labels:";
for (unsigned int i = 0; i < globalLabels.size(); ++i) {
std::cout << " " << globalLabels[i];
}
std::cout << std::endl;
std::cout << " Global Derivatives:" << std::endl;
globalDerivatives.Print();
}
std::cout << " Jacobian " << std::endl;
std::cout << " Point-to-point " << std::endl << p2pJacobian
<< std::endl;
if (theLabel) {
std::cout << " To previous offset " << std::endl << prevJacobian
<< std::endl;
std::cout << " To next offset " << std::endl << nextJacobian
<< std::endl;
}
}
}
}
| 31.102041 | 108 | 0.691142 | Plamenna |
17ab7dcda5ad069ac93417ade4b86295cf14ff6c | 3,055 | cpp | C++ | code/opengl.cpp | elvismd/tanksgame | 8c2c9daa9963b9d5a5e16a8515bd4c3e7d231799 | [
"MIT"
] | null | null | null | code/opengl.cpp | elvismd/tanksgame | 8c2c9daa9963b9d5a5e16a8515bd4c3e7d231799 | [
"MIT"
] | null | null | null | code/opengl.cpp | elvismd/tanksgame | 8c2c9daa9963b9d5a5e16a8515bd4c3e7d231799 | [
"MIT"
] | null | null | null | #include "opengl.h"
#include "logger.h"
#define CHECK_GL(...) check_gl_error(__FILE__, __LINE__);
int check_gl_error(char * file, int line)
{
GLuint err = glGetError();
if (err > 0)
{
log_warning("GL Error - file:%s line: %d error: %d", file, line, err);
switch(err)
{
case GL_INVALID_ENUM: log_warning("GL_INVALID_ENUM: Given when an enumeration parameter is not a legal enumeration for that function. This is given only for local problems; if the spec allows the enumeration in certain circumstances, where other parameters or state dictate those circumstances, then GL_INVALID_OPERATION is the result instead."); break;
case GL_INVALID_VALUE: log_warning("GL_INVALID_VALUE: Given when a value parameter is not a legal value for that function. This is only given for local problems; if the spec allows the value in certain circumstances, where other parameters or state dictate those circumstances, then GL_INVALID_OPERATION is the result instead."); break;
case GL_INVALID_OPERATION: log_warning("GL_INVALID_OPERATION: Given when the set of state for a command is not legal for the parameters given to that command. It is also given for commands where combinations of parameters define what the legal parameters are."); break;
case GL_STACK_OVERFLOW: log_warning("GL_STACK_OVERFLOW: Given when a stack pushing operation cannot be done because it would overflow the limit of that stack's size."); break;
case GL_STACK_UNDERFLOW: log_warning("GL_STACK_UNDERFLOW: Given when a stack popping operation cannot be done because the stack is already at its lowest point."); break;
case GL_OUT_OF_MEMORY: log_warning("GL_OUT_OF_MEMORY: Given when performing an operation that can allocate memory, and the memory cannot be allocated. The results of OpenGL functions that return this error are undefined; it is allowable for partial operations to happen."); break;
case GL_INVALID_FRAMEBUFFER_OPERATION: log_warning("GL_INVALID_FRAMEBUFFER_OPERATION: Given when doing anything that would attempt to read from or write/render to a framebuffer that is not complete."); break;
case GL_CONTEXT_LOST: log_warning("GL_CONTEXT_LOST: Given if the OpenGL context has been lost, due to a graphics card reset."); break;
}
}
return err;
}
void init_renderer(void* data)
{
if (!gladLoadGLLoader((GLADloadproc)data))
{
printf("Failed to init GLAD. \n");
Assert(false);
}
// TODO : Print those
char* opengl_vendor = (char*)glGetString(GL_VENDOR);
char* opengl_renderer = (char*)glGetString(GL_RENDERER);
char* opengl_version = (char*)glGetString(GL_VERSION);
char* shading_language_version = (char*)glGetString(GL_SHADING_LANGUAGE_VERSION);
log_info("GL Vendor %s", opengl_vendor);
log_info("GL Renderer %s", opengl_renderer);
log_info("GL Version %s", opengl_version);
log_info("GL Shading Language Version %s", shading_language_version);
// GLint n, i;
// glGetIntegerv(GL_NUM_EXTENSIONS, &n);
// for (i = 0; i < n; i++)
// {
// char* extension = (char*)glGetStringi(GL_EXTENSIONS, i);
// }
} | 56.574074 | 356 | 0.762029 | elvismd |
17ada2e487cfb137c6cf76c9121d18e063a40fb9 | 29,878 | hpp | C++ | include/dca/phys/dca_step/cluster_solver/ctaux/accumulator/tp/accumulator_nonlocal_chi.hpp | yingwaili/DCA | 31c298a1831f90daf62ea8bb6b683229513d7c08 | [
"BSD-3-Clause"
] | null | null | null | include/dca/phys/dca_step/cluster_solver/ctaux/accumulator/tp/accumulator_nonlocal_chi.hpp | yingwaili/DCA | 31c298a1831f90daf62ea8bb6b683229513d7c08 | [
"BSD-3-Clause"
] | null | null | null | include/dca/phys/dca_step/cluster_solver/ctaux/accumulator/tp/accumulator_nonlocal_chi.hpp | yingwaili/DCA | 31c298a1831f90daf62ea8bb6b683229513d7c08 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (C) 2018 ETH Zurich
// Copyright (C) 2018 UT-Battelle, LLC
// All rights reserved.
//
// See LICENSE for terms of usage.
// See CITATION.md for citation guidelines, if DCA++ is used for scientific publications.
//
// Author: Peter Staar (taa@zurich.ibm.com)
//
// This class computes the nonlocal \f$\chi(k_1,k_2,q)\f$.
/*
* Definition of two-particle functions:
*
* \section ph particle-hole channel:
*
* The magnetic channel,
*
* \f{eqnarray*}{
* G^{II}_{ph} &=& \frac{1}{4} \sum_{\sigma_1,\sigma_2 = \pm1} (\sigma_1 \: \sigma_2) \langle
* T_\tau\{c^\dagger_{k_1+q,\sigma_1} c_{k_1,\sigma_1} c^\dagger_{k_2,\sigma_2}
* c_{k_2+q,\sigma_2} \}\rangle
* \f}
*
* The charge channel,
*
* \f{eqnarray*}{
* G^{II}_{ph} &=& \frac{1}{4} \sum_{\sigma_1,\sigma_2 = \pm1} \langle
* T_\tau\{c^\dagger_{k_1+q,\sigma_1} c_{k_1,\sigma_1} c^\dagger_{k_2,\sigma_2}
* c_{k_2+q,\sigma_2} \}\rangle
* \f}
*
* The transverse channel,
*
* \f{eqnarray*}{
* G^{II}_{ph} &=& \frac{1}{2} \sum_{\sigma = \pm1} \langle T_\tau\{c^\dagger_{k_1+q,\sigma}
* c_{k_1,-\sigma} c^\dagger_{k_2,-\sigma} c_{k_2+q,\sigma} \}\rangle
* \f}
*
* \section pp particle-hole channel:
*
* The transverse (or superconducting) channel,
*
* \f{eqnarray*}{
* G^{II}_{pp} &=& \frac{1}{2} \sum_{\sigma= \pm1} \langle T_\tau\{ c^\dagger_{q-k_1,\sigma}
* c^\dagger_{k_1,-\sigma} c_{k_2,-\sigma} c_{q-k_2,\sigma} \}
* \f}
*/
#ifndef DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_CTAUX_ACCUMULATOR_TP_ACCUMULATOR_NONLOCAL_CHI_HPP
#define DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_CTAUX_ACCUMULATOR_TP_ACCUMULATOR_NONLOCAL_CHI_HPP
#include <cassert>
#include <cmath>
#include <complex>
#include "dca/function/domains.hpp"
#include "dca/function/function.hpp"
#include "dca/phys/domains/cluster/cluster_domain.hpp"
#include "dca/phys/domains/quantum/electron_band_domain.hpp"
#include "dca/phys/domains/time_and_frequency/vertex_frequency_domain.hpp"
#include "dca/phys/four_point_type.hpp"
#include "dca/phys/domains/cluster/cluster_domain_aliases.hpp"
namespace dca {
namespace phys {
namespace solver {
namespace ctaux {
// dca::phys::solver::ctaux::
template <class parameters_type, class MOMS_type>
class accumulator_nonlocal_chi {
public:
using w_VERTEX = func::dmn_0<domains::vertex_frequency_domain<domains::COMPACT>>;
using w_VERTEX_EXTENDED = func::dmn_0<domains::vertex_frequency_domain<domains::EXTENDED>>;
using w_VERTEX_EXTENDED_POS =
func::dmn_0<domains::vertex_frequency_domain<domains::EXTENDED_POSITIVE>>;
using b = func::dmn_0<domains::electron_band_domain>;
using CDA = ClusterDomainAliases<parameters_type::lattice_type::DIMENSION>;
using RClusterDmn = typename CDA::RClusterDmn;
using KClusterDmn = typename CDA::KClusterDmn;
// This needs shifted to new aliases
typedef RClusterDmn r_dmn_t;
typedef KClusterDmn k_dmn_t;
typedef typename r_dmn_t::parameter_type r_cluster_type;
typedef typename k_dmn_t::parameter_type k_cluster_type;
typedef typename parameters_type::profiler_type profiler_t;
typedef typename parameters_type::concurrency_type concurrency_type;
typedef typename parameters_type::MC_measurement_scalar_type scalar_type;
typedef typename parameters_type::G4_w1_dmn_t w1_dmn_t;
typedef typename parameters_type::G4_w2_dmn_t w2_dmn_t;
typedef func::dmn_variadic<b, b, r_dmn_t, r_dmn_t, w1_dmn_t, w2_dmn_t> b_b_r_r_w_w_dmn_t;
typedef func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w1_dmn_t, w2_dmn_t> b_b_k_k_w_w_dmn_t;
public:
accumulator_nonlocal_chi(
parameters_type& parameters_ref, MOMS_type& MOMS_ref, int id,
func::function<std::complex<double>,
func::dmn_variadic<b, b, b, b, k_dmn_t, k_dmn_t, w_VERTEX, w_VERTEX>>& G4_ref);
void initialize();
void finalize();
template <class nonlocal_G_t>
void execute(scalar_type current_sign, nonlocal_G_t& nonlocal_G_obj);
private:
void F(
int n1, int m1, int k1, int k2, int w1, int w2,
func::function<std::complex<scalar_type>,
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2,
std::complex<scalar_type>& G2_result);
void F(int n1, int m1, int k1, int k2, int w1, int w2,
func::function<
std::complex<scalar_type>,
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2,
std::complex<scalar_type>& G2_result);
void F(
int n1, int m1, int k1, int k2, int w1, int w2,
func::function<std::complex<scalar_type>,
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2_dn,
std::complex<scalar_type>& G2_dn_result,
func::function<std::complex<scalar_type>,
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2_up,
std::complex<scalar_type>& G2_up_result);
void F(int n1, int m1, int k1, int k2, int w1, int w2,
func::function<
std::complex<scalar_type>,
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2_dn,
std::complex<scalar_type>& G2_dn_result,
func::function<
std::complex<scalar_type>,
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2_up,
std::complex<scalar_type>& G2_up_result);
void accumulate_particle_hole_transverse(
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN,
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP,
scalar_type sign);
void accumulate_particle_hole_magnetic(
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN,
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP,
scalar_type sign);
void accumulate_particle_hole_charge(
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN,
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP,
scalar_type sign);
void accumulate_particle_particle_superconducting(
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN,
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP,
scalar_type sign);
private:
parameters_type& parameters;
MOMS_type& MOMS;
concurrency_type& concurrency;
int thread_id;
func::function<std::complex<double>,
func::dmn_variadic<b, b, b, b, k_dmn_t, k_dmn_t, w_VERTEX, w_VERTEX>>& G4;
int w_VERTEX_EXTENDED_POS_dmn_size;
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED> b_b_k_k_w_full_w_full_dmn;
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED> b_b_k_k_w_pos_w_full_dmn;
func::function<int, k_dmn_t> min_k_dmn_t;
func::function<int, k_dmn_t> q_plus_;
func::function<int, k_dmn_t> q_min_;
func::function<int, w_VERTEX> min_w_vertex;
func::function<int, w_VERTEX_EXTENDED> min_w_vertex_ext;
func::function<int, w_VERTEX> w_vertex_2_w_vertex_ext;
func::function<int, w_VERTEX_EXTENDED> w_vertex_ext_2_w_vertex_ext_pos;
};
template <class parameters_type, class MOMS_type>
accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulator_nonlocal_chi(
parameters_type& parameters_ref, MOMS_type& MOMS_ref, int id,
func::function<std::complex<double>,
func::dmn_variadic<b, b, b, b, k_dmn_t, k_dmn_t, w_VERTEX, w_VERTEX>>& G4_ref)
: parameters(parameters_ref),
MOMS(MOMS_ref),
concurrency(parameters.get_concurrency()),
thread_id(id),
G4(G4_ref),
w_VERTEX_EXTENDED_POS_dmn_size(w_VERTEX_EXTENDED_POS::dmn_size()),
b_b_k_k_w_full_w_full_dmn(),
b_b_k_k_w_pos_w_full_dmn(),
min_k_dmn_t("min_k_dmn_t"),
q_plus_("q_plus_"),
q_min_("q_min_"),
min_w_vertex(" min_w_vertex"),
min_w_vertex_ext("min_w_vertex_ext"),
w_vertex_2_w_vertex_ext("w_vertex_2_w_vertex_ext"),
w_vertex_ext_2_w_vertex_ext_pos("w_vertex_ext_2_w_vertex_ext_pos") {
int q_channel = parameters.get_four_point_momentum_transfer_index();
// int k0_index = k_cluster_type::get_k_0_index();
int k0_index = k_cluster_type::origin_index();
for (int l = 0; l < k_cluster_type::get_size(); l++) {
min_k_dmn_t(l) = k_cluster_type::subtract(l, k0_index);
q_plus_(l) = k_cluster_type::add(l, q_channel);
q_min_(l) = k_cluster_type::subtract(l, q_channel);
}
{
for (int l = 0; l < w_VERTEX::dmn_size(); l++)
min_w_vertex(l) = w_VERTEX::dmn_size() - 1 - l;
for (int l = 0; l < w_VERTEX_EXTENDED::dmn_size(); l++)
min_w_vertex_ext(l) = w_VERTEX_EXTENDED::dmn_size() - 1 - l;
}
{
for (int i = 0; i < w_VERTEX::dmn_size(); i++)
for (int j = 0; j < w_VERTEX_EXTENDED::dmn_size(); j++)
if (std::fabs(w_VERTEX::get_elements()[i] - w_VERTEX_EXTENDED::get_elements()[j]) < 1.e-6)
w_vertex_2_w_vertex_ext(i) = j;
}
{
for (int l = 0; l < w_VERTEX_EXTENDED::dmn_size(); l++) {
if (l < w_VERTEX_EXTENDED_POS::dmn_size())
w_vertex_ext_2_w_vertex_ext_pos(l) = w_VERTEX_EXTENDED_POS::dmn_size() - 1 - l;
else
w_vertex_ext_2_w_vertex_ext_pos(l) = l - w_VERTEX_EXTENDED_POS::dmn_size();
// cout << l << "\t" << w_vertex_ext_2_w_vertex_ext_pos(l) << "\n";
}
}
}
template <class parameters_type, class MOMS_type>
void accumulator_nonlocal_chi<parameters_type, MOMS_type>::initialize() {
MOMS.get_G4_k_k_w_w() = 0.;
}
template <class parameters_type, class MOMS_type>
void accumulator_nonlocal_chi<parameters_type, MOMS_type>::finalize() {
// for(int i=0; i<G4.size(); i++)
// MOMS.G4_k_k_w_w(i) = G4(i);
}
template <class parameters_type, class MOMS_type>
template <class nonlocal_G_t>
void accumulator_nonlocal_chi<parameters_type, MOMS_type>::execute(scalar_type current_sign,
nonlocal_G_t& nonlocal_G_obj) {
profiler_t profiler("compute nonlocal-chi", "CT-AUX accumulator", __LINE__, thread_id);
switch (parameters.get_four_point_type()) {
case PARTICLE_HOLE_TRANSVERSE:
accumulate_particle_hole_transverse(nonlocal_G_obj.get_G_k_k_w_w_e_DN(),
nonlocal_G_obj.get_G_k_k_w_w_e_UP(), current_sign);
break;
case PARTICLE_HOLE_MAGNETIC:
accumulate_particle_hole_magnetic(nonlocal_G_obj.get_G_k_k_w_w_e_DN(),
nonlocal_G_obj.get_G_k_k_w_w_e_UP(), current_sign);
break;
case PARTICLE_HOLE_CHARGE:
accumulate_particle_hole_charge(nonlocal_G_obj.get_G_k_k_w_w_e_DN(),
nonlocal_G_obj.get_G_k_k_w_w_e_UP(), current_sign);
break;
case PARTICLE_PARTICLE_UP_DOWN:
accumulate_particle_particle_superconducting(
nonlocal_G_obj.get_G_k_k_w_w_e_DN(), nonlocal_G_obj.get_G_k_k_w_w_e_UP(), current_sign);
break;
default:
throw std::logic_error(__FUNCTION__);
}
}
template <class parameters_type, class MOMS_type>
inline void accumulator_nonlocal_chi<parameters_type, MOMS_type>::F(
int n1, int m1, int k1, int k2, int w1, int w2,
func::function<std::complex<scalar_type>,
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2,
std::complex<scalar_type>& G2_result) {
G2_result = G2(n1, m1, k1, k2, w1, w2);
}
template <class parameters_type, class MOMS_type>
inline void accumulator_nonlocal_chi<parameters_type, MOMS_type>::F(
int n1, int m1, int k1, int k2, int w1, int w2,
func::function<std::complex<scalar_type>,
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2,
std::complex<scalar_type>& G2_result) {
if (w1 < w_VERTEX_EXTENDED_POS_dmn_size) {
G2_result = conj(G2(n1, m1, min_k_dmn_t(k1), min_k_dmn_t(k2),
w_vertex_ext_2_w_vertex_ext_pos(w1), min_w_vertex_ext(w2)));
}
else {
G2_result = G2(n1, m1, k1, k2, w_vertex_ext_2_w_vertex_ext_pos(w1), w2);
}
}
template <class parameters_type, class MOMS_type>
inline void accumulator_nonlocal_chi<parameters_type, MOMS_type>::F(
int n1, int m1, int k1, int k2, int w1, int w2,
func::function<std::complex<scalar_type>,
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2_dn,
std::complex<scalar_type>& G2_dn_result,
func::function<std::complex<scalar_type>,
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2_up,
std::complex<scalar_type>& G2_up_result) {
int lin_ind = b_b_k_k_w_full_w_full_dmn(n1, m1, k1, k2, w1, w2);
G2_dn_result = G2_dn(lin_ind);
G2_up_result = G2_up(lin_ind);
}
template <class parameters_type, class MOMS_type>
inline void accumulator_nonlocal_chi<parameters_type, MOMS_type>::F(
int n1, int m1, int k1, int k2, int w1, int w2,
func::function<std::complex<scalar_type>,
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2_dn,
std::complex<scalar_type>& G2_dn_result,
func::function<std::complex<scalar_type>,
func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2_up,
std::complex<scalar_type>& G2_up_result) {
if (w1 < w_VERTEX_EXTENDED_POS_dmn_size) {
int lin_ind = b_b_k_k_w_pos_w_full_dmn(n1, m1, min_k_dmn_t(k1), min_k_dmn_t(k2),
w_vertex_ext_2_w_vertex_ext_pos(w1), min_w_vertex_ext(w2));
G2_dn_result = conj(G2_dn(lin_ind));
G2_up_result = conj(G2_up(lin_ind));
}
else {
int lin_ind = b_b_k_k_w_pos_w_full_dmn(n1, m1, k1, k2, w_vertex_ext_2_w_vertex_ext_pos(w1), w2);
G2_dn_result = G2_dn(lin_ind);
G2_up_result = G2_up(lin_ind);
}
}
template <class parameters_type, class MOMS_type>
void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_hole_magnetic(
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN,
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign) {
// n1 ------------------------ m1
// | |
// | |
// | |
// n2 ------------------------ m2
std::complex<scalar_type> G2_DN_n1_m2_k1_k2_w1_w2, G2_UP_n1_m2_k1_k2_w1_w2,
G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1,
G2_DN_n1_m1_k1_k1_plus_q_w1_w1, G2_UP_n1_m1_k1_k1_plus_q_w1_w1,
G2_DN_n2_m2_k2_plus_q_k2_w2_w2, G2_UP_n2_m2_k2_plus_q_k2_w2_w2, G4_val;
int k2_plus_q, k1_plus_q;
scalar_type sign_div_2 = scalar_type(sign) / 2.;
int w_nu = parameters.get_four_point_frequency_transfer();
for (int w2 = 0; w2 < w_VERTEX::dmn_size(); w2++) {
int w2_ext = w_vertex_2_w_vertex_ext(w2);
int w2_ext_plus_w_nu = w2_ext + w_nu;
assert(std::fabs(w_VERTEX::get_elements()[w2] - w_VERTEX_EXTENDED::get_elements()[w2_ext]) <
1.e-6);
for (int w1 = 0; w1 < w_VERTEX::dmn_size(); w1++) {
int w1_ext = w_vertex_2_w_vertex_ext(w1);
int w1_ext_plus_w_nu = w1_ext + w_nu;
for (int k2 = 0; k2 < k_dmn_t::dmn_size(); k2++) {
// int k2_plus_q = k_cluster_type::add(k2,q_channel);
k2_plus_q = q_plus_(k2);
for (int k1 = 0; k1 < k_dmn_t::dmn_size(); k1++) {
// int k1_plus_q = k_cluster_type::add(k1,q_channel);
k1_plus_q = q_plus_(k1);
for (int m1 = 0; m1 < b::dmn_size(); m1++) {
for (int m2 = 0; m2 < b::dmn_size(); m2++) {
for (int n1 = 0; n1 < b::dmn_size(); n1++) {
for (int n2 = 0; n2 < b::dmn_size(); n2++) {
F(n1, m2, k1, k2, w1_ext, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n1_m2_k1_k2_w1_w2,
G2_k_k_w_w_e_UP, G2_UP_n1_m2_k1_k2_w1_w2);
F(n2, m1, k2_plus_q, k1_plus_q, w2_ext_plus_w_nu, w1_ext_plus_w_nu,
G2_k_k_w_w_e_DN, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_k_k_w_w_e_UP,
G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1);
F(n1, m1, k1, k1_plus_q, w1_ext, w1_ext_plus_w_nu, G2_k_k_w_w_e_DN,
G2_DN_n1_m1_k1_k1_plus_q_w1_w1, G2_k_k_w_w_e_UP, G2_UP_n1_m1_k1_k1_plus_q_w1_w1);
F(n2, m2, k2_plus_q, k2, w2_ext_plus_w_nu, w2_ext, G2_k_k_w_w_e_DN,
G2_DN_n2_m2_k2_plus_q_k2_w2_w2, G2_k_k_w_w_e_UP, G2_UP_n2_m2_k2_plus_q_k2_w2_w2);
G4_val = -(G2_DN_n1_m2_k1_k2_w1_w2 * G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1 +
G2_UP_n1_m2_k1_k2_w1_w2 * G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1)
+
(G2_UP_n1_m1_k1_k1_plus_q_w1_w1 - G2_DN_n1_m1_k1_k1_plus_q_w1_w1) *
(G2_UP_n2_m2_k2_plus_q_k2_w2_w2 - G2_DN_n2_m2_k2_plus_q_k2_w2_w2);
/*
G4 = - (G2_k_k_w_w_e_DN(n1, m2, k1, k2, w1, w2) * G2_k_k_w_w_e_DN(n2, m1,
k2_plus_q, k1_plus_q, w2+w_channel, w1+w_channel)
+ G2_k_k_w_w_e_UP(n1, m2, k1, k2, w1, w2) * G2_k_k_w_w_e_UP(n2, m1, k2_plus_q,
k1_plus_q, w2+w_channel, w1+w_channel))
+ (G2_k_k_w_w_e_UP(n1, m1, k1, k1_plus_q, w1, w1+w_channel) -
G2_k_k_w_w_e_DN(n1, m1, k1, k1_plus_q, w1, w1+w_channel))
* (G2_k_k_w_w_e_UP(n2, m2, k2_plus_q, k2, w2+w_channel, w2) -
G2_k_k_w_w_e_DN(n2, m2, k2_plus_q, k2, w2+w_channel, w2));
*/
G4(n1, n2, m1, m2, k1, k2, w1, w2) += std::complex<double>(sign_div_2 * G4_val);
// MOMS.G4_k_k_w_w(n1, n2, m1, m2, k1, k2, w1, w2) +=
// std::complex<double>(sign_div_2 * G4);
}
}
}
}
}
}
}
}
}
template <class parameters_type, class MOMS_type>
void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_hole_transverse(
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN,
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign) {
// n1 ------------------------ m1
// | |
// | |
// | |
// n2 ------------------------ m2
std::complex<scalar_type> G2_DN_n1_m2_k1_k2_w1_w2, G2_UP_n1_m2_k1_k2_w1_w2,
G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G4_val;
int k2_plus_q, k1_plus_q;
scalar_type sign_div_2 = scalar_type(sign) / 2.;
int w_nu = parameters.get_four_point_frequency_transfer();
for (int w2 = 0; w2 < w_VERTEX::dmn_size(); w2++) {
int w2_ext = w_vertex_2_w_vertex_ext(w2);
int w2_ext_plus_w_nu = w2_ext + w_nu;
assert(std::fabs(w_VERTEX::get_elements()[w2] - w_VERTEX_EXTENDED::get_elements()[w2_ext]) <
1.e-6);
for (int w1 = 0; w1 < w_VERTEX::dmn_size(); w1++) {
int w1_ext = w_vertex_2_w_vertex_ext(w1);
int w1_ext_plus_w_nu = w1_ext + w_nu;
for (int k2 = 0; k2 < k_dmn_t::dmn_size(); k2++) {
k2_plus_q = q_plus_(k2);
for (int k1 = 0; k1 < k_dmn_t::dmn_size(); k1++) {
k1_plus_q = q_plus_(k1);
for (int m1 = 0; m1 < b::dmn_size(); m1++) {
for (int m2 = 0; m2 < b::dmn_size(); m2++) {
for (int n1 = 0; n1 < b::dmn_size(); n1++) {
for (int n2 = 0; n2 < b::dmn_size(); n2++) {
// F(n1, m2, k1, k2, w1, w2,
// G2_k_k_w_w_e_DN, G2_DN_n1_m2_k1_k2_w1_w2,
// G2_k_k_w_w_e_UP, G2_UP_n1_m2_k1_k2_w1_w2);
// F(n2, m1, k2_plus_q, k1_plus_q, w2+w_nu, w1+w_nu,
// G2_k_k_w_w_e_DN, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1,
// G2_k_k_w_w_e_UP, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1);
F(n1, m2, k1, k2, w1_ext, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n1_m2_k1_k2_w1_w2,
G2_k_k_w_w_e_UP, G2_UP_n1_m2_k1_k2_w1_w2);
F(n2, m1, k2_plus_q, k1_plus_q, w2_ext_plus_w_nu, w1_ext_plus_w_nu,
G2_k_k_w_w_e_DN, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_k_k_w_w_e_UP,
G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1);
G4_val = -(G2_DN_n1_m2_k1_k2_w1_w2 * G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1 +
G2_UP_n1_m2_k1_k2_w1_w2 * G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1);
G4(n1, n2, m1, m2, k1, k2, w1, w2) += std::complex<double>(sign_div_2 * G4_val);
}
}
}
}
}
}
}
}
}
/*
template<class parameters_type, class MOMS_type>
void accumulator_nonlocal_chi<parameters_type,
MOMS_type>::accumulate_particle_hole_magnetic_fast(func::function<std::complex<scalar_type>,
func::dmn_variadic<b,b,k_dmn_t,k_dmn_t,w_VERTEX,w_VERTEX> >& G2_k_k_w_w_e_DN,
func::function<std::complex<scalar_type>,
func::dmn_variadic<b,b,k_dmn_t,k_dmn_t,w_VERTEX,w_VERTEX> >&
G2_k_k_w_w_e_UP,
scalar_type sign)
{
std::complex<scalar_type> *G2_DN_n1_m2_k1_k2_w1_w2, *G2_UP_n1_m2_k1_k2_w1_w2,
*G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, *G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1,
*G2_DN_n1_m1_k1_k1_plus_q_w1_w1, *G2_UP_n1_m1_k1_k1_plus_q_w1_w1,
*G2_DN_n2_m2_k2_plus_q_k2_w2_w2, *G2_UP_n2_m2_k2_plus_q_k2_w2_w2;
std::complex<double>* G4;
int k2_plus_q, k1_plus_q;
scalar_type sign_div_2 =scalar_type(sign)/2.;
for(int w2=0; w2<w_VERTEX::dmn_size(); w2++){
for(int w1=0; w1<w_VERTEX::dmn_size(); w1++){
for(int k2=0; k2<k_dmn_t::dmn_size(); k2++){
// int k2_plus_q = k_cluster_type::add(k2,q_channel);
k2_plus_q = q_plus_(k2);
for(int k1=0; k1<k_dmn_t::dmn_size(); k1++){
// int k1_plus_q = k_cluster_type::add(k1,q_channel);
k1_plus_q = q_plus_(k1);
G2_DN_n1_m2_k1_k2_w1_w2 = &G2_k_k_w_w_e_DN(0, 0, k1, k2, w1, w2);
G2_UP_n1_m2_k1_k2_w1_w2 = &G2_k_k_w_w_e_UP(0, 0, k1, k2, w1, w2);
G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1 = &G2_k_k_w_w_e_DN(0, 0, k2_plus_q, k1_plus_q, w2, w1);
G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1 = &G2_k_k_w_w_e_UP(0, 0, k2_plus_q, k1_plus_q, w2, w1);
G2_DN_n1_m1_k1_k1_plus_q_w1_w1 = &G2_k_k_w_w_e_DN(0, 0, k1, k1_plus_q, w1, w1);
G2_UP_n1_m1_k1_k1_plus_q_w1_w1 = &G2_k_k_w_w_e_UP(0, 0, k1, k1_plus_q, w1, w1);
G2_DN_n2_m2_k2_plus_q_k2_w2_w2 = &G2_k_k_w_w_e_DN(0, 0, k2_plus_q, k2, w2, w2);
G2_UP_n2_m2_k2_plus_q_k2_w2_w2 = &G2_k_k_w_w_e_UP(0, 0, k2_plus_q, k2, w2, w2);
G4 = &MOMS.G4_k_k_w_w(0,0,0,0, k1, k2, w1, w2);
accumulator_nonlocal_chi_atomic<model, PARTICLE_HOLE_MAGNETIC>::execute(G2_DN_n1_m2_k1_k2_w1_w2
, G2_UP_n1_m2_k1_k2_w1_w2,
G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1,
G2_DN_n1_m1_k1_k1_plus_q_w1_w1 , G2_UP_n1_m1_k1_k1_plus_q_w1_w1,
G2_DN_n2_m2_k2_plus_q_k2_w2_w2 , G2_UP_n2_m2_k2_plus_q_k2_w2_w2,
G4, sign_div_2);
}
}
}
}
}
*/
template <class parameters_type, class MOMS_type>
void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_hole_charge(
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN,
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign) {
// n1 ------------------------ m1
// | |
// | |
// | |
// n2 ------------------------ m2
// int q_channel = parameters.get_q_channel();
std::complex<scalar_type> G2_DN_n1_m2_k1_k2_w1_w2, G2_UP_n1_m2_k1_k2_w1_w2,
G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1,
G2_DN_n1_m1_k1_k1_plus_q_w1_w1, G2_UP_n1_m1_k1_k1_plus_q_w1_w1,
G2_DN_n2_m2_k2_plus_q_k2_w2_w2, G2_UP_n2_m2_k2_plus_q_k2_w2_w2, G4_val;
int w_nu = parameters.get_four_point_frequency_transfer();
scalar_type sign_div_2 = scalar_type(sign) / 2.;
for (int w2 = 0; w2 < w_VERTEX::dmn_size(); w2++) {
int w2_ext = w_vertex_2_w_vertex_ext(w2);
int w2_ext_plus_w_nu = w2_ext + w_nu;
assert(std::fabs(w_VERTEX::get_elements()[w2] - w_VERTEX_EXTENDED::get_elements()[w2_ext]) <
1.e-6);
for (int w1 = 0; w1 < w_VERTEX::dmn_size(); w1++) {
int w1_ext = w_vertex_2_w_vertex_ext(w1);
int w1_ext_plus_w_nu = w1_ext + w_nu;
for (int k2 = 0; k2 < k_dmn_t::dmn_size(); k2++) {
// int k2_plus_q = k_cluster_type::add(k2,q_channel);
int k2_plus_q = q_plus_(k2);
for (int k1 = 0; k1 < k_dmn_t::dmn_size(); k1++) {
// int k1_plus_q = k_cluster_type::add(k1,q_channel);
int k1_plus_q = q_plus_(k1);
for (int m1 = 0; m1 < b::dmn_size(); m1++) {
for (int m2 = 0; m2 < b::dmn_size(); m2++) {
for (int n1 = 0; n1 < b::dmn_size(); n1++) {
for (int n2 = 0; n2 < b::dmn_size(); n2++) {
F(n1, m2, k1, k2, w1_ext, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n1_m2_k1_k2_w1_w2,
G2_k_k_w_w_e_UP, G2_UP_n1_m2_k1_k2_w1_w2);
F(n2, m1, k2_plus_q, k1_plus_q, w2_ext_plus_w_nu, w1_ext_plus_w_nu,
G2_k_k_w_w_e_DN, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_k_k_w_w_e_UP,
G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1);
F(n1, m1, k1, k1_plus_q, w1_ext, w1_ext_plus_w_nu, G2_k_k_w_w_e_DN,
G2_DN_n1_m1_k1_k1_plus_q_w1_w1, G2_k_k_w_w_e_UP, G2_UP_n1_m1_k1_k1_plus_q_w1_w1);
F(n2, m2, k2_plus_q, k2, w2_ext_plus_w_nu, w2_ext, G2_k_k_w_w_e_DN,
G2_DN_n2_m2_k2_plus_q_k2_w2_w2, G2_k_k_w_w_e_UP, G2_UP_n2_m2_k2_plus_q_k2_w2_w2);
G4_val = -(G2_DN_n1_m2_k1_k2_w1_w2 * G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1 +
G2_UP_n1_m2_k1_k2_w1_w2 * G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1)
+
(G2_UP_n1_m1_k1_k1_plus_q_w1_w1 + G2_DN_n1_m1_k1_k1_plus_q_w1_w1) *
(G2_UP_n2_m2_k2_plus_q_k2_w2_w2 + G2_DN_n2_m2_k2_plus_q_k2_w2_w2);
/*
G4 = - (G2_k_k_w_w_e_DN(n1, m2, k1, k2, w1, w2) * G2_k_k_w_w_e_DN(n2, m1,
k2_plus_q, k1_plus_q, w2+w_channel, w1+w_channel)
+ G2_k_k_w_w_e_UP(n1, m2, k1, k2, w1, w2) * G2_k_k_w_w_e_UP(n2, m1, k2_plus_q,
k1_plus_q, w2+w_channel, w1+w_channel))
+ (G2_k_k_w_w_e_UP(n1, m1, k1, k1_plus_q, w1, w1+w_channel) +
G2_k_k_w_w_e_DN(n1, m1, k1, k1_plus_q, w1, w1+w_channel))
* (G2_k_k_w_w_e_UP(n2, m2, k2_plus_q, k2, w2+w_channel, w2) +
G2_k_k_w_w_e_DN(n2, m2, k2_plus_q, k2, w2+w_channel, w2));
*/
G4(n1, n2, m1, m2, k1, k2, w1, w2) += std::complex<double>(sign_div_2 * G4_val);
// MOMS.G4_k_k_w_w(n1, n2, m1, m2, k1, k2, w1, w2) +=
// std::complex<double>(sign_div_2 * G4);
}
}
}
}
}
}
}
}
}
template <class parameters_type, class MOMS_type>
void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_particle_superconducting(
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN,
func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign) {
std::complex<scalar_type> G2_UP_n1_m1_k1_k2_w1_w2, G2_DN_n1_m1_k1_k2_w1_w2,
G2_UP_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2, G2_DN_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2,
G4_val;
int w_nu = parameters.get_four_point_frequency_transfer();
scalar_type sign_div_2 = sign / 2.;
for (int w2 = 0; w2 < w_VERTEX::dmn_size(); w2++) {
int w2_ext = w_vertex_2_w_vertex_ext(w2);
int w_nu_min_w2 = w_nu + w_vertex_2_w_vertex_ext(min_w_vertex(w2));
for (int w1 = 0; w1 < w_VERTEX::dmn_size(); w1++) {
int w1_ext = w_vertex_2_w_vertex_ext(w1);
int w_nu_min_w1 = w_nu + w_vertex_2_w_vertex_ext(min_w_vertex(w1));
for (int k1 = 0; k1 < k_dmn_t::dmn_size(); k1++) {
int q_minus_k1 = q_min_(k1);
for (int k2 = 0; k2 < k_dmn_t::dmn_size(); k2++) {
int q_minus_k2 = q_min_(k2);
for (int n1 = 0; n1 < b::dmn_size(); n1++) {
for (int n2 = 0; n2 < b::dmn_size(); n2++) {
for (int m1 = 0; m1 < b::dmn_size(); m1++) {
for (int m2 = 0; m2 < b::dmn_size(); m2++) {
F(n1, m1, k1, k2, w1_ext, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n1_m1_k1_k2_w1_w2,
G2_k_k_w_w_e_UP, G2_UP_n1_m1_k1_k2_w1_w2);
F(n2, m2, q_minus_k1, q_minus_k2, w_nu_min_w1, w_nu_min_w2, G2_k_k_w_w_e_UP,
G2_UP_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2, G2_k_k_w_w_e_DN,
G2_DN_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2);
G4_val = (G2_UP_n1_m1_k1_k2_w1_w2 * G2_DN_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2 +
G2_DN_n1_m1_k1_k2_w1_w2 * G2_UP_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2);
G4(n1, n2, m1, m2, k1, k2, w1, w2) += std::complex<double>(sign_div_2 * G4_val);
}
}
}
}
}
}
}
}
}
} // ctaux
} // solver
} // phys
} // dca
#endif // DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_CTAUX_ACCUMULATOR_TP_ACCUMULATOR_NONLOCAL_CHI_HPP
| 41.041209 | 112 | 0.651483 | yingwaili |
17af2153521afd985ec8b8a9d34f7ba5fcd12d90 | 1,240 | hpp | C++ | include/tracker/MarkerFilter.hpp | anqixu/ftag2 | f77c0c0960a1ed44cc8723fd6c5320b7bb256a68 | [
"BSD-2-Clause"
] | 5 | 2019-08-16T07:04:32.000Z | 2022-03-31T11:02:09.000Z | include/tracker/MarkerFilter.hpp | anqixu/ftag2 | f77c0c0960a1ed44cc8723fd6c5320b7bb256a68 | [
"BSD-2-Clause"
] | null | null | null | include/tracker/MarkerFilter.hpp | anqixu/ftag2 | f77c0c0960a1ed44cc8723fd6c5320b7bb256a68 | [
"BSD-2-Clause"
] | 1 | 2021-12-09T21:05:56.000Z | 2021-12-09T21:05:56.000Z | /*
* MarkerFilter.hpp
*
* Created on: Mar 4, 2014
* Author: dacocp
*/
#ifndef MARKERFILTER_HPP_
#define MARKERFILTER_HPP_
#include "common/FTag2.hpp"
#include "tracker/PayloadFilter.hpp"
#include "detector/FTag2Detector.hpp"
#include "tracker/Kalman.hpp"
using namespace std;
class MarkerFilter {
private:
FTag2Marker detectedTag;
int frames_without_detection;
PayloadFilter IF;
Kalman KF;
static int num_Markers;
int marker_id;
public:
bool active;
bool got_detection_in_current_frame;
FTag2Marker hypothesis;
MarkerFilter(int tagType) :
detectedTag(tagType),
IF(tagType),
hypothesis(tagType) { frames_without_detection = 0; active = false; got_detection_in_current_frame = false; };
MarkerFilter(FTag2Marker detection, double quadSizeM, cv::Mat cameraIntrinsic, cv::Mat cameraDistortion );
virtual ~MarkerFilter() {};
FTag2Marker getHypothesis() { return hypothesis; }
int get_frames_without_detection() { return frames_without_detection; }
void step( FTag2Marker detection, double quadSizeM, cv::Mat cameraIntrinsic, cv::Mat cameraDistortion );
void step( double quadSizeM, cv::Mat cameraIntrinsic, cv::Mat cameraDistortion );
void updateParameters();
};
#endif /* MARKERFILTER_HPP_ */
| 26.956522 | 115 | 0.762903 | anqixu |
17b1fb67d0a3acfb9257e63bafdd5fb33d5d3dca | 728 | cpp | C++ | GEARBOX/res/scripts/TestScript.cpp | AndrewRichards-Code/GEAR_CORE | 4d4e77bf643dc9b98de9f38445eae690290e1895 | [
"MIT"
] | null | null | null | GEARBOX/res/scripts/TestScript.cpp | AndrewRichards-Code/GEAR_CORE | 4d4e77bf643dc9b98de9f38445eae690290e1895 | [
"MIT"
] | null | null | null | GEARBOX/res/scripts/TestScript.cpp | AndrewRichards-Code/GEAR_CORE | 4d4e77bf643dc9b98de9f38445eae690290e1895 | [
"MIT"
] | null | null | null | #include "Scene/INativeScript.h"
using namespace gear;
using namespace scene;
class TestScript : public INativeScript
{
public:
TestScript() = default;
~TestScript() = default;
bool first = true;
mars::float3 initPos;
void OnCreate()
{
}
void OnDestroy()
{
objects::Transform& transform = GetEntity().GetComponent<TransformComponent>().transform;
transform.translation = initPos;
}
void OnUpdate(float deltaTime)
{
objects::Transform& transform = GetEntity().GetComponent<TransformComponent>().transform;
mars::float3& pos = transform.translation;
if (first)
{
initPos = pos;
first = false;
}
pos.z += 0.5f * deltaTime;
}
};
GEAR_LOAD_SCRIPT(TestScript);
GEAR_UNLOAD_SCRIPT(TestScript); | 18.666667 | 91 | 0.715659 | AndrewRichards-Code |
17b25e6a9f5d40e856515dbe7c86cc60d95665fa | 320 | cpp | C++ | tests/catch.cpp | ZeroICQ/cpp-vector | ac896b1c0fd70b2ae1e27229172de28684a85978 | [
"MIT"
] | null | null | null | tests/catch.cpp | ZeroICQ/cpp-vector | ac896b1c0fd70b2ae1e27229172de28684a85978 | [
"MIT"
] | null | null | null | tests/catch.cpp | ZeroICQ/cpp-vector | ac896b1c0fd70b2ae1e27229172de28684a85978 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in on
#define CATCH_CONFIG_FAST_COMPILE // Sacrifices some (rather minor) features for compilation speed
#define CATCH_CONFIG_DISABLE_MATCHERS // Do not compile Matchers in this compilation unit
#include "catch.hpp"
| 53.333333 | 104 | 0.746875 | ZeroICQ |
17b468aaa75a8a0bc536f24c3af4f66cfe0edc63 | 2,860 | cpp | C++ | src/vgui2/src/MessageListener.cpp | DeadZoneLuna/csso-src | 6c978ea304ee2df3796bc9c0d2916bac550050d5 | [
"Unlicense"
] | 4 | 2021-10-03T05:16:55.000Z | 2021-12-28T16:49:27.000Z | src/vgui2/src/MessageListener.cpp | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | null | null | null | src/vgui2/src/MessageListener.cpp | cafeed28/what | 08e51d077f0eae50afe3b592543ffa07538126f5 | [
"Unlicense"
] | 3 | 2022-02-02T18:09:58.000Z | 2022-03-06T18:54:39.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "IMessageListener.h"
#include "VPanel.h"
#include "vgui_internal.h"
#include <KeyValues.h>
#include "vgui/IClientPanel.h"
#include "vgui/IVGui.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
namespace vgui
{
//-----------------------------------------------------------------------------
// Implementation of the message listener
//-----------------------------------------------------------------------------
class CMessageListener : public IMessageListener
{
public:
virtual void Message( VPanel* pSender, VPanel* pReceiver, KeyValues* pKeyValues, MessageSendType_t type );
};
void CMessageListener::Message( VPanel* pSender, VPanel* pReceiver, KeyValues* pKeyValues, MessageSendType_t type )
{
char const *pSenderName = "NULL";
if (pSender)
pSenderName = pSender->Client()->GetName();
char const *pSenderClass = "NULL";
if (pSender)
pSenderClass = pSender->Client()->GetClassName();
char const *pReceiverName = "unknown name";
if (pReceiver)
pReceiverName = pReceiver->Client()->GetName();
char const *pReceiverClass = "unknown class";
if (pReceiver)
pReceiverClass = pReceiver->Client()->GetClassName();
// FIXME: Make a bunch of filters here
// filter out key focus messages
if (!strcmp (pKeyValues->GetName(), "KeyFocusTicked"))
{
return;
}
// filter out mousefocus messages
else if (!strcmp (pKeyValues->GetName(), "MouseFocusTicked"))
{
return;
}
// filter out cursor movement messages
else if (!strcmp (pKeyValues->GetName(), "CursorMoved"))
{
return;
}
// filter out cursor entered messages
else if (!strcmp (pKeyValues->GetName(), "CursorEntered"))
{
return;
}
// filter out cursor exited messages
else if (!strcmp (pKeyValues->GetName(), "CursorExited"))
{
return;
}
// filter out MouseCaptureLost messages
else if (!strcmp (pKeyValues->GetName(), "MouseCaptureLost"))
{
return;
}
// filter out MousePressed messages
else if (!strcmp (pKeyValues->GetName(), "MousePressed"))
{
return;
}
// filter out MouseReleased messages
else if (!strcmp (pKeyValues->GetName(), "MouseReleased"))
{
return;
}
// filter out Tick messages
else if (!strcmp (pKeyValues->GetName(), "Tick"))
{
return;
}
Msg( "%s : (%s (%s) - > %s (%s)) )\n",
pKeyValues->GetName(), pSenderClass, pSenderName, pReceiverClass, pReceiverName );
}
//-----------------------------------------------------------------------------
// Singleton instance
//-----------------------------------------------------------------------------
static CMessageListener s_MessageListener;
IMessageListener *MessageListener()
{
return &s_MessageListener;
}
} | 25.535714 | 115 | 0.597203 | DeadZoneLuna |
17b5f7ec7dd976b40e6f84cbfc8bff2cfbe49bfb | 21,324 | cpp | C++ | Utils/spawn-wthttpd.cpp | NuLL3rr0r/blog-subscription-service | 4458c0679229ad20ee446e1d1f7c58d1aa04b64d | [
"MIT"
] | 6 | 2016-01-30T03:25:00.000Z | 2022-01-23T23:29:22.000Z | Utils/spawn-wthttpd.cpp | NuLL3rr0r/blog-subscription-service | 4458c0679229ad20ee446e1d1f7c58d1aa04b64d | [
"MIT"
] | 1 | 2018-09-01T09:46:34.000Z | 2019-01-12T15:05:50.000Z | Utils/spawn-wthttpd.cpp | NuLL3rr0r/blog-subscription-service | 4458c0679229ad20ee446e1d1f7c58d1aa04b64d | [
"MIT"
] | 6 | 2017-01-05T14:55:02.000Z | 2021-03-30T14:05:10.000Z | /**
* @file
* @author Mamadou Babaei <info@babaei.net>
* @version 0.1.0
*
* @section LICENSE
*
* (The MIT License)
*
* Copyright (c) 2016 - 2021 Mamadou Babaei
*
* 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.
*
* @section DESCRIPTION
*
* A tiny utility program to spawn a collection of wthttpd applications if they
* won't exists in memory already. In addition to that, it monitors the
* application and does re-spawn it in case of a crash.
* You might want to run this as a cron job.
*/
#include <fstream>
#include <iostream>
#include <map>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <vector>
#include <csignal>
#include <cstdlib>
#include <boost/algorithm/string.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <CoreLib/CoreLib.hpp>
#include <CoreLib/Exception.hpp>
#include <CoreLib/FileSystem.hpp>
#include <CoreLib/Log.hpp>
#include <CoreLib/System.hpp>
#define UNKNOWN_ERROR "Unknown error!"
const std::string DATABASE_FILE_NAME = "spawn-wthttpd.db";
static boost::property_tree::ptree appsTree;
[[ noreturn ]] void Terminate(int signo);
bool ReadApps();
void ReSpawn();
int main(int argc, char **argv)
{
try {
/// Gracefully handling SIGTERM
void (*prev_fn)(int);
prev_fn = signal(SIGTERM, Terminate);
if (prev_fn == SIG_IGN)
signal(SIGTERM, SIG_IGN);
/// Extract the executable path and name
boost::filesystem::path path(boost::filesystem::initial_path<boost::filesystem::path>());
if (argc > 0 && argv[0] != NULL)
path = boost::filesystem::system_complete(boost::filesystem::path(argv[0]));
std::string appId(path.filename().string());
std::string appPath(boost::algorithm::replace_last_copy(path.string(), appId, ""));
/// Force changing the current path to executable path
boost::filesystem::current_path(appPath);
/// Initializing CoreLib
CoreLib::CoreLibInitialize(argc, argv);
#if GDPR_COMPLIANCE
CoreLib::Log::Initialize(std::cout);
#else // GDPR_COMPLIANCE
CoreLib::Log::Initialize(std::cout,
(boost::filesystem::path(appPath)
/ boost::filesystem::path("..")
/ boost::filesystem::path("log")).string(),
"SpawnWtHttpd");
#endif // GDPR_COMPLIANCE
/// Acquiring process lock
std::string lockId;
#if defined ( __unix__ )
int lock;
lockId = (boost::filesystem::path(appPath)
/ boost::filesystem::path("..")
/ boost::filesystem::path("tmp")
/ (appId + ".lock")).string();
#elif defined ( _WIN32 )
HANDLE lock;
lockId = appId;
#endif // defined ( __unix__ )
if(!CoreLib::System::GetLock(lockId, lock)) {
std::cerr << "Could not get lock!" << std::endl;
std::cerr << "Probably process is already running!" << std::endl;
return EXIT_FAILURE;
} else {
LOG_INFO("Got the process lock!");
}
if(!ReadApps()) {
return EXIT_FAILURE;
}
if (appsTree.empty()
|| appsTree.count("apps") == 0
|| appsTree.get_child("apps").count("") == 0) {
std::cerr << "There is no WtHttpd app to spawn!" << std::endl;
return EXIT_FAILURE;
}
while (true) {
ReSpawn();
sleep(1);
}
}
catch (CoreLib::Exception<std::string> &ex) {
LOG_ERROR(ex.What());
}
catch (boost::exception &ex) {
LOG_ERROR(boost::diagnostic_information(ex));
}
catch (std::exception &ex) {
LOG_ERROR(ex.what());
}
catch (...) {
LOG_ERROR(UNKNOWN_ERROR);
}
return EXIT_SUCCESS;
}
void Terminate(int signo)
{
std::clog << "Terminating...." << std::endl;
exit(signo);
}
bool ReadApps()
{
std::ifstream dbFile(
(boost::filesystem::path("..")
/ boost::filesystem::path("db")
/ DATABASE_FILE_NAME).string()
);
if (!dbFile.is_open()) {
std::cerr << "Unable to open the database file!" << std::endl;
return false;
}
try {
boost::property_tree::read_json(dbFile, appsTree);
}
catch (std::exception const &ex) {
LOG_ERROR(ex.what());
return false;
}
catch (...) {
LOG_ERROR(UNKNOWN_ERROR);
}
return true;
}
void ReSpawn()
{
try {
BOOST_FOREACH(boost::property_tree::ptree::value_type &appNode, appsTree.get_child("apps")) {
if (appNode.first.empty()) {
bool running = false;
std::vector<int> pids;
if (appNode.second.get_child_optional("pid-file")) {
if (CoreLib::FileSystem::FileExists(appNode.second.get<std::string>("pid-file"))) {
std::ifstream pidFile(appNode.second.get<std::string>("pid-file"));
if (pidFile.is_open()) {
std::string firstLine;
getline(pidFile, firstLine);
pidFile.close();
boost::algorithm::trim(firstLine);
try {
int pid = boost::lexical_cast<int>(firstLine);
// The shell way:
// To check if ${PID} exists
// kill -0 ${PID}
// Other possible ways to get process name or full-path
// ps -p ${PID} -o comm=
// or
// FreeBSD
// ps axwww -o pid,command | grep ${PID}
// GNU/Linux
// ps ax -o pid,cmd | grep ${PID}
if (CoreLib::System::GetPidsOfProcess(
CoreLib::System::GetProcessNameFromPath(appNode.second.get<std::string>("app")),
pids)) {
if (pids.size() > 0 &&
std::find(pids.begin(), pids.end(), pid) != pids.end()) {
running = true;
}
}
} catch (...) {
}
} else {
}
} else {
}
} else {
throw "No socket or port specified!";
}
if (!running) {
for (std::vector<int>::const_iterator it =
pids.begin(); it != pids.end(); ++it) {
std::string output;
std::string cmd = (boost::format("/bin/ps -p %1% | grep '%2%'")
% *it
% appNode.second.get<std::string>("app")).str();
CoreLib::System::Exec(cmd, output);
if (output.find(appNode.second.get<std::string>("app")) != std::string::npos) {
std::clog << std::endl
<< (boost::format(" * KILLING ==> %1%"
"\n\t%2%")
% *it
% appNode.second.get<std::string>("app")).str()
<< std::endl;
cmd = (boost::format("/bin/kill -SIGKILL %1%")
% *it).str();
CoreLib::System::Exec(cmd);
}
}
std::clog << std::endl
<< (boost::format(" * RESPAWNING WTHTTPD APP ==> %1%"
"\n\tWorking Directory : %2%"
"\n\tThreads : %3%"
"\n\tServer Name : %4%"
"\n\tDocument Root : %5%"
"\n\tApplication Root : %6%"
"\n\tError Root : %7%"
"\n\tAccess Log : %8%"
"\n\tCompression : %9%"
"\n\tDeploy Path : %10%"
"\n\tSession ID Prefix : %11%"
"\n\tPid File : %12%"
"\n\tConfig File : %13%"
"\n\tMax Memory Request Size : %14%"
"\n\tGDB : %15%"
"\n\tHttp Address : %16%"
"\n\tHttp Port : %17%"
"\n\tHttps Address : %18%"
"\n\tHttps Port : %19%"
"\n\tSSL Certificate : %20%"
"\n\tSSL Private Key : %21%"
"\n\tSSL Temp Diffie Hellman : %22%"
"\n\tSSL Enable v3 : %23%"
"\n\tSSL Client Verification : %24%"
"\n\tSSL Verify Depth : %25%"
"\n\tSSL CA Certificates : %26%"
"\n\tSSL Cipherlist : %27%")
% appNode.second.get<std::string>("app")
% appNode.second.get<std::string>("workdir")
% appNode.second.get<std::string>("threads")
% appNode.second.get<std::string>("servername")
% appNode.second.get<std::string>("docroot")
% appNode.second.get<std::string>("approot")
% appNode.second.get<std::string>("errroot")
% appNode.second.get<std::string>("accesslog")
% appNode.second.get<std::string>("compression")
% appNode.second.get<std::string>("deploy-path")
% appNode.second.get<std::string>("session-id-prefix")
% appNode.second.get<std::string>("pid-file")
% appNode.second.get<std::string>("config")
% appNode.second.get<std::string>("max-memory-request-size")
% appNode.second.get<std::string>("gdb")
% appNode.second.get<std::string>("http-address")
% appNode.second.get<std::string>("http-port")
% appNode.second.get<std::string>("https-address")
% appNode.second.get<std::string>("https-port")
% appNode.second.get<std::string>("ssl-certificate")
% appNode.second.get<std::string>("ssl-private-key")
% appNode.second.get<std::string>("ssl-tmp-dh")
% appNode.second.get<std::string>("ssl-enable-v3")
% appNode.second.get<std::string>("ssl-client-verification")
% appNode.second.get<std::string>("ssl-verify-depth")
% appNode.second.get<std::string>("ssl-ca-certificates")
% appNode.second.get<std::string>("ssl-cipherlist")
).str()
<< std::endl << std::endl;
std::string cmd((boost::format("cd %2% && %1%")
% appNode.second.get<std::string>("app")
% appNode.second.get<std::string>("workdir")
).str());
if (!appNode.second.get<std::string>("threads").empty()
&& appNode.second.get<std::string>("threads") != "-1") {
cmd += (boost::format(" --threads %1%")
% appNode.second.get<std::string>("threads")).str();
}
if (!appNode.second.get<std::string>("servername").empty()) {
cmd += (boost::format(" --servername %1%")
% appNode.second.get<std::string>("servername")).str();
}
if (!appNode.second.get<std::string>("docroot").empty()) {
cmd += (boost::format(" --docroot \"%1%\"")
% appNode.second.get<std::string>("docroot")).str();
}
if (!appNode.second.get<std::string>("approot").empty()) {
cmd += (boost::format(" --approot \"%1%\"")
% appNode.second.get<std::string>("approot")).str();
}
if (!appNode.second.get<std::string>("errroot").empty()) {
cmd += (boost::format(" --errroot \"%1%\"")
% appNode.second.get<std::string>("errroot")).str();
}
if (!appNode.second.get<std::string>("accesslog").empty()) {
cmd += (boost::format(" --accesslog \"%1%\"")
% appNode.second.get<std::string>("accesslog")).str();
}
if (!appNode.second.get<std::string>("compression").empty()
&& appNode.second.get<std::string>("compression") != "yes") {
cmd += " --no-compression";
}
if (!appNode.second.get<std::string>("deploy-path").empty()) {
cmd += (boost::format(" --deploy-path %1%")
% appNode.second.get<std::string>("deploy-path")).str();
}
if (!appNode.second.get<std::string>("session-id-prefix").empty()) {
cmd += (boost::format(" --session-id-prefix %1%")
% appNode.second.get<std::string>("session-id-prefix")).str();
}
if (!appNode.second.get<std::string>("pid-file").empty()) {
cmd += (boost::format(" --pid-file \"%1%\"")
% appNode.second.get<std::string>("pid-file")).str();
}
if (!appNode.second.get<std::string>("config").empty()) {
cmd += (boost::format(" --config \"%1%\"")
% appNode.second.get<std::string>("config")).str();
}
if (!appNode.second.get<std::string>("max-memory-request-size").empty()) {
cmd += (boost::format(" --max-memory-request-size %1%")
% appNode.second.get<std::string>("max-memory-request-size")).str();
}
if (!appNode.second.get<std::string>("gdb").empty()
&& appNode.second.get<std::string>("gdb") != "yes") {
cmd += " --gdb";
}
if (!appNode.second.get<std::string>("http-address").empty()) {
cmd += (boost::format(" --http-address %1%")
% appNode.second.get<std::string>("http-address")).str();
}
if (!appNode.second.get<std::string>("http-port").empty()) {
cmd += (boost::format(" --http-port %1%")
% appNode.second.get<std::string>("http-port")).str();
}
if (!appNode.second.get<std::string>("https-address").empty()) {
cmd += (boost::format(" --https-address %1%")
% appNode.second.get<std::string>("https-address")).str();
}
if (!appNode.second.get<std::string>("https-port").empty()) {
cmd += (boost::format(" --https-port %1%")
% appNode.second.get<std::string>("https-port")).str();
}
if (!appNode.second.get<std::string>("ssl-certificate").empty()) {
cmd += (boost::format(" --ssl-certificate \"%1%\"")
% appNode.second.get<std::string>("ssl-certificate")).str();
}
if (!appNode.second.get<std::string>("ssl-private-key").empty()) {
cmd += (boost::format(" --ssl-private-key \"%1%\"")
% appNode.second.get<std::string>("ssl-private-key")).str();
}
if (!appNode.second.get<std::string>("ssl-tmp-dh").empty()) {
cmd += (boost::format(" --ssl-tmp-dh \"%1%\"")
% appNode.second.get<std::string>("ssl-tmp-dh")).str();
}
if (!appNode.second.get<std::string>("ssl-enable-v3").empty()
&& appNode.second.get<std::string>("ssl-enable-v3") != "yes") {
cmd += " --ssl-enable-v3";
}
if (!appNode.second.get<std::string>("ssl-client-verification").empty()) {
cmd += (boost::format(" --ssl-client-verification %1%")
% appNode.second.get<std::string>("ssl-client-verification")).str();
}
if (!appNode.second.get<std::string>("ssl-verify-depth").empty()) {
cmd += (boost::format(" --ssl-verify-depth %1%")
% appNode.second.get<std::string>("ssl-verify-depth")).str();
}
if (!appNode.second.get<std::string>("ssl-ca-certificates").empty()) {
cmd += (boost::format(" --ssl-ca-certificates \"%1%\"")
% appNode.second.get<std::string>("ssl-ca-certificates")).str();
}
if (!appNode.second.get<std::string>("ssl-cipherlist").empty()) {
cmd += (boost::format(" --ssl-cipherlist %1%")
% appNode.second.get<std::string>("ssl-cipherlist")).str();
}
cmd += " &";
CoreLib::System::Exec(cmd);
}
}
}
}
catch (const char * const &ex) {
LOG_ERROR(ex);
}
catch (std::exception const &ex) {
LOG_ERROR(ex.what());
}
catch (...) {
LOG_ERROR(UNKNOWN_ERROR);
}
}
| 46.356522 | 124 | 0.422998 | NuLL3rr0r |
17b90207f73dcaf083a85f23ce25a62e4604a03f | 949 | cc | C++ | components/password_manager/core/browser/password_manager_constants.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/password_manager/core/browser/password_manager_constants.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | components/password_manager/core/browser/password_manager_constants.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/password_manager/core/browser/password_manager_constants.h"
namespace password_manager {
const base::FilePath::CharType kAffiliationDatabaseFileName[] =
FILE_PATH_LITERAL("Affiliation Database");
const base::FilePath::CharType kLoginDataForProfileFileName[] =
FILE_PATH_LITERAL("Login Data");
const base::FilePath::CharType kLoginDataForAccountFileName[] =
FILE_PATH_LITERAL("Login Data For Account");
const char kPasswordManagerAccountDashboardURL[] =
"https://passwords.google.com";
const char kPasswordManagerHelpCenteriOSURL[] =
"https://support.google.com/chrome/answer/95606?ios=1";
const char kPasswordManagerHelpCenterSmartLock[] =
"https://support.google.com/accounts?p=smart_lock_chrome";
} // namespace password_manager
| 36.5 | 80 | 0.783983 | chromium |
17b9a3a619dc2f0ce902205a7086ac9fd2a5d60d | 5,969 | cpp | C++ | src/mongo/db/fts/fts_search.cpp | nleite/mongo | 1a1b6b0aaeefbae06942867e4dcf55d00d42afe0 | [
"Apache-2.0"
] | 24 | 2015-10-15T00:03:57.000Z | 2021-04-25T18:21:31.000Z | src/mongo/db/fts/fts_search.cpp | nleite/mongo | 1a1b6b0aaeefbae06942867e4dcf55d00d42afe0 | [
"Apache-2.0"
] | 1 | 2015-06-02T12:19:19.000Z | 2015-06-02T12:19:19.000Z | src/mongo/db/fts/fts_search.cpp | nleite/mongo | 1a1b6b0aaeefbae06942867e4dcf55d00d42afe0 | [
"Apache-2.0"
] | 3 | 2017-07-26T11:17:11.000Z | 2021-11-30T00:11:32.000Z | // fts_search.cpp
/**
* Copyright (C) 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mongo/pch.h"
#include "mongo/db/btreecursor.h"
#include "mongo/db/fts/fts_index_format.h"
#include "mongo/db/fts/fts_search.h"
#include "mongo/db/kill_current_op.h"
#include "mongo/db/pdfile.h"
namespace mongo {
namespace fts {
/*
* Constructor generates query and term dictionaries
* @param ns, namespace
* @param idxNum, index number
* @param search, query string
* @param language, language of the query
* @param filter, filter object
*/
FTSSearch::FTSSearch( IndexDescriptor* descriptor,
const FTSSpec& ftsSpec,
const BSONObj& indexPrefix,
const FTSQuery& query,
const BSONObj& filter )
: _descriptor(descriptor),
_ftsSpec(ftsSpec),
_indexPrefix( indexPrefix ),
_query( query ),
_ftsMatcher(query, ftsSpec) {
if ( !filter.isEmpty() )
_matcher.reset( new CoveredIndexMatcher( filter, _descriptor->keyPattern() ) );
_keysLookedAt = 0;
_objectsLookedAt = 0;
}
bool FTSSearch::_ok( Record* record ) const {
if ( !_query.hasNonTermPieces() )
return true;
return _ftsMatcher.matchesNonTerm( BSONObj::make( record ) );
}
/*
* GO: sets the tree cursors on each term in terms, processes the terms by advancing
* the terms cursors and storing the partial
* results and lastly calculates the top results
* @param results, the priority queue containing the top results
* @param limit, number of results in the priority queue
*/
void FTSSearch::go(Results* results, unsigned limit ) {
vector< shared_ptr<BtreeCursor> > cursors;
for ( unsigned i = 0; i < _query.getTerms().size(); i++ ) {
const string& term = _query.getTerms()[i];
BSONObj min = FTSIndexFormat::getIndexKey( MAX_WEIGHT, term, _indexPrefix );
BSONObj max = FTSIndexFormat::getIndexKey( 0, term, _indexPrefix );
shared_ptr<BtreeCursor> c( BtreeCursor::make(
nsdetails(_descriptor->parentNS().c_str()),
_descriptor->getOnDisk(),
min, max, true, -1 ) );
cursors.push_back( c );
}
while ( !inShutdown() ) {
bool gotAny = false;
for ( unsigned i = 0; i < cursors.size(); i++ ) {
if ( cursors[i]->eof() )
continue;
gotAny = true;
_process( cursors[i].get() );
cursors[i]->advance();
}
if ( !gotAny )
break;
RARELY killCurrentOp.checkForInterrupt();
}
// priority queue using a compare that grabs the lowest of two ScoredLocations by score.
for ( Scores::iterator i = _scores.begin(); i != _scores.end(); ++i ) {
if ( i->second < 0 )
continue;
// priority queue
if ( results->size() < limit ) { // case a: queue unfilled
if ( !_ok( i->first ) )
continue;
results->push( ScoredLocation( i->first, i->second ) );
}
else if ( i->second > results->top().score ) { // case b: queue filled
if ( !_ok( i->first ) )
continue;
results->pop();
results->push( ScoredLocation( i->first, i->second ) );
}
else {
// else do nothing (case c)
}
}
}
/*
* Takes a cursor and updates the partial score for said cursor in _scores map
* @param cursor, btree cursor pointing to the current document to be scored
*/
void FTSSearch::_process( BtreeCursor* cursor ) {
_keysLookedAt++;
BSONObj key = cursor->currKey();
BSONObjIterator i( key );
for ( unsigned j = 0; j < _ftsSpec.numExtraBefore(); j++)
i.next();
i.next(); // move past indexToken
BSONElement scoreElement = i.next();
double score = scoreElement.number();
double& cur = _scores[(cursor->currLoc()).rec()];
if ( cur < 0 ) {
// already been rejected
return;
}
if ( cur == 0 && _matcher.get() ) {
// we haven't seen this before and we have a matcher
MatchDetails d;
if ( !_matcher->matchesCurrent( cursor, &d ) ) {
cur = -1;
}
if ( d.hasLoadedRecord() )
_objectsLookedAt++;
if ( cur == -1 )
return;
}
if ( cur )
cur += score * (1 + 1 / score);
else
cur += score;
}
}
}
| 32.796703 | 100 | 0.501424 | nleite |
17bab29a25e304d2904a2d4e02c7b9a8ae2c5a2b | 2,156 | cc | C++ | src/storage/blobfs/test/unit/fsck-test.cc | dahlia-os/fuchsia-pine64-pinephone | 57aace6f0b0bd75306426c98ab9eb3ff4524a61d | [
"BSD-3-Clause"
] | 14 | 2020-10-25T05:48:36.000Z | 2021-09-20T02:46:20.000Z | src/storage/blobfs/test/unit/fsck-test.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | 1 | 2022-01-14T23:38:40.000Z | 2022-01-14T23:38:40.000Z | src/storage/blobfs/test/unit/fsck-test.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | 4 | 2020-12-28T17:04:45.000Z | 2022-03-12T03:20:44.000Z | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "blobfs/fsck.h"
#include <blobfs/mkfs.h>
#include <block-client/cpp/fake-device.h>
#include <gtest/gtest.h>
#include "blobfs.h"
#include "utils.h"
namespace blobfs {
namespace {
using block_client::FakeBlockDevice;
constexpr uint32_t kBlockSize = 512;
constexpr uint32_t kNumBlocks = 400 * kBlobfsBlockSize / kBlockSize;
TEST(FsckTest, TestEmpty) {
auto device = std::make_unique<FakeBlockDevice>(kNumBlocks, kBlockSize);
ASSERT_TRUE(device);
ASSERT_EQ(FormatFilesystem(device.get()), ZX_OK);
MountOptions options;
ASSERT_EQ(Fsck(std::move(device), &options), ZX_OK);
}
TEST(FsckTest, TestUnmountable) {
auto device = std::make_unique<FakeBlockDevice>(kNumBlocks, kBlockSize);
ASSERT_TRUE(device);
MountOptions options;
ASSERT_EQ(Fsck(std::move(device), &options), ZX_ERR_INVALID_ARGS);
}
TEST(FsckTest, TestCorrupted) {
auto device = std::make_unique<FakeBlockDevice>(kNumBlocks, kBlockSize);
ASSERT_TRUE(device);
ASSERT_EQ(FormatFilesystem(device.get()), ZX_OK);
char block[kBlobfsBlockSize];
DeviceBlockRead(device.get(), block, sizeof(block), kSuperblockOffset);
Superblock* info = reinterpret_cast<Superblock*>(block);
info->alloc_inode_count++;
DeviceBlockWrite(device.get(), block, sizeof(block), kSuperblockOffset);
MountOptions options;
ASSERT_EQ(Fsck(std::move(device), &options), ZX_ERR_IO_OVERRUN);
}
TEST(FsckTest, TestOverflow) {
auto device = std::make_unique<FakeBlockDevice>(kNumBlocks, kBlockSize);
ASSERT_TRUE(device);
ASSERT_EQ(FormatFilesystem(device.get()), ZX_OK);
char block[kBlobfsBlockSize];
DeviceBlockRead(device.get(), block, sizeof(block), kSuperblockOffset);
Superblock* info = reinterpret_cast<Superblock*>(block);
info->inode_count = std::numeric_limits<uint64_t>::max();
DeviceBlockWrite(device.get(), block, sizeof(block), kSuperblockOffset);
MountOptions options;
ASSERT_EQ(Fsck(std::move(device), &options), ZX_ERR_OUT_OF_RANGE);
}
} // namespace
} // namespace blobfs
| 30.366197 | 74 | 0.752783 | dahlia-os |
17bd5ed31ba7debeab07f15da466c585475700eb | 4,364 | cpp | C++ | CalFp02-/src/Sudoku.cpp | GuilhermeJSilva/CAL-TP | 5e9dac1c56370a82d16f1633f03ec6302d81652d | [
"MIT"
] | null | null | null | CalFp02-/src/Sudoku.cpp | GuilhermeJSilva/CAL-TP | 5e9dac1c56370a82d16f1633f03ec6302d81652d | [
"MIT"
] | null | null | null | CalFp02-/src/Sudoku.cpp | GuilhermeJSilva/CAL-TP | 5e9dac1c56370a82d16f1633f03ec6302d81652d | [
"MIT"
] | null | null | null | /*
* Sudoku.cpp
*
*/
#include "Sudoku.h"
#include <vector>
#include <string.h>
#include <climits>
/** Inicia um Sudoku vazio.
*/
Sudoku::Sudoku()
{
this->initialize();
this->n_solucoes = 0;
this->countFilled = 0;
}
/**
* Inicia um Sudoku com um conte�do inicial.
* Lan�a excep��o IllegalArgumentException se os valores
* estiverem fora da gama de 1 a 9 ou se existirem n�meros repetidos
* por linha, coluna ou bloc 3x3.
*
* @param nums matriz com os valores iniciais (0 significa por preencher)
*/
Sudoku::Sudoku(int nums[9][9])
{
this->initialize();
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (nums[i][j] != 0)
{
int n = nums[i][j];
numbers[i][j] = n;
lineHasNumber[i][n] = true;
columnHasNumber[j][n] = true;
block3x3HasNumber[i / 3][j / 3][n] = true;
countFilled++;
}
}
}
this->n_solucoes = 0;
}
void Sudoku::initialize()
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
for (int n = 0; n < 10; n++)
{
numbers[i][j] = 0;
lineHasNumber[i][n] = false;
columnHasNumber[j][n] = false;
block3x3HasNumber[i / 3][j / 3][n] = false;
}
}
}
this->countFilled = 0;
}
/**
* Obtem o conte�do actual (s� para leitura!).
*/
int** Sudoku::getNumbers()
{
int** ret = new int*[9];
for (int i = 0; i < 9; i++)
{
ret[i] = new int[9];
for (int a = 0; a < 9; a++)
ret[i][a] = numbers[i][a];
}
return ret;
}
/**
* Verifica se o Sudoku j� est� completamente resolvido
*/
bool Sudoku::isComplete()
{
return countFilled == 9 * 9;
}
/**
* Resolve o Sudoku.
* Retorna indica��o de sucesso ou insucesso (sudoku imposs�vel).
*/
bool Sudoku::solve()
{
//this->print();
//cout << endl;
if(countFilled == 81)
{
this->print();
cout << endl;
n_solucoes++;
return true;
}
int x ,y;
int n_accepted = INT_MAX;
vector<bool> num_accepted;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
int tmp_n_accepted = 9;
vector<bool> acceptable_num(10,true);
if(this->numbers[i][j] != 0)
continue;
for(int k = 0; k < 10; k++)
{
acceptable_num[k] = acceptable_num[k] & !this->columnHasNumber[j][k];
acceptable_num[k] = acceptable_num[k] & !this->lineHasNumber[i][k];
acceptable_num[k] = acceptable_num[k] & !this->block3x3HasNumber[i/3][j/3][k];
if(!acceptable_num[k])
tmp_n_accepted--;
}
//cout << "x: " << i << " y: " << j << endl;
//cout << tmp_n_accepted << ' ' << n_accepted << endl;
if(tmp_n_accepted == 0)
return false;
if(tmp_n_accepted <= n_accepted)
{
n_accepted = tmp_n_accepted;
num_accepted.clear();
num_accepted.insert(num_accepted.begin(),acceptable_num.begin(), acceptable_num.end());
x = i;
y = j;
}
}
}
if(n_accepted == 1)
{
int a = 1;
while(!num_accepted[a])
a++;
//cout << "Added: " << a << " in x: " << x << " y: " << y << endl << endl;
this->numbers[x][y] = a;
this->countFilled++;
lineHasNumber[x][a] = true;
columnHasNumber[y][a] = true;
block3x3HasNumber[x / 3][y / 3][a] = true;
if(this->solve())
{
return true;
}
else
{
this->numbers[x][y] = 0;
this->countFilled--;
lineHasNumber[x][a] = false;
columnHasNumber[y][a] = false;
block3x3HasNumber[x / 3][y / 3][a] = false;
return false;
}
}
else
{
//cout << x << "\t" << y << "\n";
std::vector<int> possible_sol;
for(int i = 1; i < 10; i++)
if(num_accepted[i])
{
//cout << i << " acceptated\n";
possible_sol.push_back(i);
}
for(size_t j = 0; j < possible_sol.size(); j++)
{
//cout << "Added: " << possible_sol[j] << " in x: " << x << " y: " << y << endl << endl;
this->numbers[x][y] = possible_sol[j];
this->countFilled++;
lineHasNumber[x][possible_sol[j]] = true;
columnHasNumber[y][possible_sol[j]] = true;
block3x3HasNumber[x / 3][y / 3][possible_sol[j]] = true;
if(this->solve())
{
return true;
}
else
{
this->numbers[x][y] = 0;
this->countFilled--;
lineHasNumber[x][possible_sol[j]] = false;
columnHasNumber[y][possible_sol[j]] = false;
block3x3HasNumber[x / 3][y / 3][possible_sol[j]] = false;
}
}
}
return false;
}
/**
* Imprime o Sudoku.
*/
void Sudoku::print()
{
for (int i = 0; i < 9; i++)
{
for (int a = 0; a < 9; a++)
cout << this->numbers[i][a] << " ";
cout << endl;
}
}
| 19.056769 | 91 | 0.555454 | GuilhermeJSilva |
17c0c334c4fc80d57eac6f272f38fd439cb246f0 | 6,224 | cc | C++ | sim/uart.cc | cbiffle/brittle-kernel | 13ca6dddc910d38e6cdca8360b29b42e1fa8928a | [
"Apache-2.0"
] | 18 | 2016-04-09T09:05:43.000Z | 2021-03-31T20:52:44.000Z | sim/uart.cc | cbiffle/brittle-kernel | 13ca6dddc910d38e6cdca8360b29b42e1fa8928a | [
"Apache-2.0"
] | 1 | 2017-05-16T08:17:25.000Z | 2017-05-16T08:17:25.000Z | sim/uart.cc | cbiffle/brittle-kernel | 13ca6dddc910d38e6cdca8360b29b42e1fa8928a | [
"Apache-2.0"
] | 1 | 2021-11-23T15:17:15.000Z | 2021-11-23T15:17:15.000Z | #include <assert.h>
#include "stubs.h"
/*******************************************************************************
* Names for some of our resources.
*/
// Names for clist slots
static constexpr uintptr_t
// Where reply keys arrive.
k0 = 0,
// We move reply keys here immediately so they don't get stomped
// by subsequent operations.
k_saved_reply = 4,
// We accept one flush request and keep its reply key pending
// here across concurrent operations on other ports.
k_flush_reply = 5,
// Register access grant.
k_reg = 14,
// System access.
k_sys = 15;
// Names for our ports.
static constexpr uintptr_t
p_mon = 0,
p_tx = 1,
p_irq = 2,
p_rx = 3;
/*******************************************************************************
* Constants describing our protocols and others'. Some of this ought to move
* into header files.
*/
static constexpr uintptr_t
// mon protocol
t_mon_heartbeat = 0,
// mem protocol
t_mem_write32 = 0,
t_mem_read32 = 1,
// uart.tx protocol
t_tx_send1 = 0,
t_tx_flush = 1,
// uart.rx protocol
t_rx_recv1 = 0;
/*******************************************************************************
* Declarations of implementation factors.
*/
// Functions used in received-message port dispatching.
static void handle_mon(Message const &);
static void handle_tx(Message const &);
static void handle_irq(Message const &);
static void handle_rx(Message const &);
// Utility function for using k_saved_reply with no keys.
static void reply(uintptr_t md0 = 0,
uintptr_t md1 = 0,
uintptr_t md2 = 0,
uintptr_t md3 = 0) {
send(false, k_saved_reply, Message{{md0, md1, md2, md3}});
}
/*******************************************************************************
* Main loop
*/
int main() {
// We mask the receive port until we get evidence from the
// hardware that data is available.
// TODO: if we're restarted, the hardware may already hold
// data -- we should check.
mask(p_rx);
while (true) {
ReceivedMessage rm;
auto r = open_receive(true, &rm);
if (r != SysResult::success) continue;
move_cap(k0, k_saved_reply);
// TODO: clear transients
switch (rm.port) {
case p_mon: handle_mon(rm.m); break;
case p_tx: handle_tx(rm.m); break;
case p_irq: handle_irq(rm.m); break;
case p_rx: handle_rx(rm.m); break;
default:
// This would indicate that the kernel has handed us
// a message from a port we don't know about. This
// is either a bug in the kernel or in this dispatch
// code.
assert(false);
}
}
}
/*******************************************************************************
* Mem protocol wrappers for UART register access.
*
* These all use the register access grant kept in k_reg. Because we assume
* a simple memory grant, or something compatible with one, we handle error
* returns in a heavy-handed manner.
*/
static void write_cr1(uint32_t value) {
auto r = send(true, k_reg, Message{t_mem_write32, 0xC, value});
assert(r == SysResult::success);
}
static void write_dr(uint8_t value) {
auto r = send(true, k_reg, Message{t_mem_write32, 4, value});
assert(r == SysResult::success);
}
static uint32_t read_dr() {
ReceivedMessage response;
auto r = call(true, k_reg, Message{t_mem_read32, 4}, &response);
assert(r == SysResult::success);
return uint32_t(response.m.data[0]);
}
static uint32_t read_cr1() {
ReceivedMessage response;
auto r = call(true, k_reg, Message{t_mem_read32, 0xC}, &response);
assert(r == SysResult::success);
return uint32_t(response.m.data[0]);
}
static uint32_t read_sr() {
ReceivedMessage response;
auto r = call(true, k_reg, Message{t_mem_read32, 0}, &response);
assert(r == SysResult::success);
return uint32_t(response.m.data[0]);
}
static void enable_irq_on_txe() {
write_cr1(read_cr1() | (1 << 7));
}
static void enable_irq_on_rxne() {
write_cr1(read_cr1() | (1 << 5));
}
static void enable_irq_on_tc() {
write_cr1(read_cr1() | (1 << 6));
}
/*******************************************************************************
* Mon server implementation
*/
static void handle_mon(Message const & req) {
switch (req.data[0]) {
case t_mon_heartbeat:
reply(req.data[1], req.data[2], req.data[3]);
break;
}
}
/*******************************************************************************
* UART.TX server implementation
*/
static bool flushing;
static void do_send1(Message const & req) {
write_dr(uint8_t(req.data[1]));
mask(p_tx);
enable_irq_on_txe();
reply();
}
static void do_flush(Message const &) {
enable_irq_on_tc();
mask(p_tx);
move_cap(k_saved_reply, k_flush_reply);
flushing = true;
// Do not reply yet.
}
static void handle_tx(Message const & req) {
switch (req.data[0]) {
case t_tx_send1: do_send1(req); break;
case t_tx_flush: do_flush(req); break;
}
}
/*******************************************************************************
* IRQ server implementation
*/
static void handle_irq(Message const &) {
auto sr = read_sr();
auto cr1 = read_cr1();
if ((sr & (1 << 7)) && (cr1 & (1 << 7))) {
// TXE set and interrupt enabled.
// Disable interrupt in preparation for allowing another send.
cr1 &= ~(1 << 7);
write_cr1(cr1);
if (!flushing) unmask(p_tx);
}
if ((sr & (1 << 5)) && (cr1 & (1 << 5))) {
// RxNE set and interrupt enabled.
cr1 &= ~(1 << 5);
write_cr1(cr1);
unmask(p_rx);
}
if ((sr & (1 << 6)) && (cr1 & (1 << 6))) {
// TC set and interrupt enabled -- a flush has completed.
cr1 &= ~(1 << 6);
write_cr1(cr1);
assert(flushing);
send(false, k_flush_reply, Message{{0, 0, 0, 0}});
flushing = false;
unmask(p_tx);
}
reply(1);
}
/*******************************************************************************
* UART.RX server implementation
*/
static void do_recv1(Message const & req) {
auto b = read_dr();
mask(p_rx);
enable_irq_on_rxne();
reply(b);
}
static void handle_rx(Message const & req) {
switch (req.data[0]) {
case t_rx_recv1: do_recv1(req); break;
}
}
| 25.198381 | 80 | 0.570373 | cbiffle |
17c0db6e2c3ccbf82be67c5a1f0f9e818cd28de9 | 1,001 | hpp | C++ | Type.hpp | Racinettee/Inked | 231ba994772d0847b19df5b1da2abaed113d58d6 | [
"MIT"
] | null | null | null | Type.hpp | Racinettee/Inked | 231ba994772d0847b19df5b1da2abaed113d58d6 | [
"MIT"
] | null | null | null | Type.hpp | Racinettee/Inked | 231ba994772d0847b19df5b1da2abaed113d58d6 | [
"MIT"
] | null | null | null | #ifndef _TYPE_HPP_
#define _TYPE_HPP_
#include "ICompilerEngine.hpp"
class Type
{
std::string name;
llvm::Type* type;
public:
const std::string& Name()
{
return name;
}
const llvm::Type* Type()
{
return type;
}
std::size_t SizeBytes() const
{
// figure out the type of type of type. if its primitive just return the size, if its a struct type
// then it will have to be interated over
unsigned std::size_t sizeof_type = 0;
if(type->isFloatTy())
sizeof_type = 4;
// 32 bits
else if(type->isDoubleTy())
// 64 bits
sizeof_type = 8;
else if(type->isIntegerTy())
{
// variable width that type can report
sizeof_type = dynamic_cast<llvm::IntegerType>(type)->getBitWidth();
}
else if(type->isStructTy())
{
// iterate over all elements and sum them
}
}
};
#endif // _TYPE_HPP_
| 25.025 | 107 | 0.551449 | Racinettee |
17c2f4f24fc2ccf0616b763a9acf0ff599e21539 | 1,996 | cpp | C++ | c03/ex3_16.cpp | qzhang0/CppPrimer | 315ef879bd4d3b51d594e33b049adee0d47e4c11 | [
"MIT"
] | null | null | null | c03/ex3_16.cpp | qzhang0/CppPrimer | 315ef879bd4d3b51d594e33b049adee0d47e4c11 | [
"MIT"
] | null | null | null | c03/ex3_16.cpp | qzhang0/CppPrimer | 315ef879bd4d3b51d594e33b049adee0d47e4c11 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;
int main() {
vector<int> v1; // size:0, no values.
vector<int> v2(10); // size:10, value:0
vector<int> v3(10, 42); // size:10, value:42
vector<int> v4{ 10 }; // size:1, value:10
vector<int> v5{ 10, 42 }; // size:2, value:10, 42
vector<string> v6{ 10 }; // size:10, value:""
vector<string> v7{ 10, "hi" }; // size:10, value:"hi"
cout << "v1 has " << v1.size() << " elements: " << endl;
if (v1.size() > 0) {
for (auto a : v1) cout << a << " ";
cout << endl;
} else {
cout << "N/A" << endl;
}
cout << "v2 has " << v2.size() << " elements: " << endl;
if (v2.size() > 0) {
for (auto a : v2) cout << a << " ";
cout << endl;
} else {
cout << "N/A" << endl;
}
cout << "v3 has " << v3.size() << " elements: " << endl;
if (v3.size() > 0) {
for (auto a : v3) cout << a << " ";
cout << endl;
} else {
cout << "N/A" << endl;
}
cout << "v4 has " << v4.size() << " elements: " << endl;
if (v4.size() > 0) {
for (auto a : v4) cout << a << " ";
cout << endl;
} else {
cout << "N/A" << endl;
}
cout << "v5 has " << v5.size() << " elements: " << endl;
if (v5.size() > 0) {
for (auto a : v5) cout << a << " ";
cout << endl;
} else {
cout << "N/A" << endl;
}
cout << "v6 has " << v6.size() << " elements: " << endl;
if (v6.size() > 0) {
for (auto a : v6) cout << a << " ";
cout << endl;
} else {
cout << "N/A" << endl;
}
cout << "v7 has " << v7.size() << " elements: " << endl;
if (v7.size() > 0) {
for (auto a : v7) cout << a << " ";
cout << endl;
} else {
cout << "N/A" << endl;
}
return 0;
} | 25.589744 | 60 | 0.40982 | qzhang0 |
17c3caf5cd91fbaf56150f942457ee8336fd6118 | 27,692 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/bluetooth/BluetoothGattServer.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/bluetooth/BluetoothGattServer.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/bluetooth/BluetoothGattServer.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos 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.
//=========================================================================
#include "elastos/droid/bluetooth/BluetoothGattServer.h"
#include "elastos/droid/bluetooth/CBluetoothAdapter.h"
#include "elastos/droid/os/CParcelUuid.h"
#include "elastos/core/AutoLock.h"
#include <elastos/utility/logging/Logger.h>
using Elastos::Droid::Os::CParcelUuid;
using Elastos::Droid::Os::EIID_IBinder;
using Elastos::Core::AutoLock;
using Elastos::Utility::CArrayList;
using Elastos::Utility::IUUIDHelper;
using Elastos::Utility::CUUIDHelper;
using Elastos::Utility::Logging::Logger;
namespace Elastos {
namespace Droid {
namespace Bluetooth {
//=====================================================================
// BluetoothGattServer::BluetoothGattServerCallbackStub
//=====================================================================
CAR_INTERFACE_IMPL_2(BluetoothGattServer::BluetoothGattServerCallbackStub, Object, IIBluetoothGattServerCallback, IBinder);
BluetoothGattServer::BluetoothGattServerCallbackStub::BluetoothGattServerCallbackStub()
{
}
ECode BluetoothGattServer::BluetoothGattServerCallbackStub::constructor(
/* [in] */ IBluetoothGattServer* owner)
{
mOwner = (BluetoothGattServer*)owner;
return NOERROR;
}
ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnServerRegistered(
/* [in] */ Int32 status,
/* [in] */ Int32 serverIf)
{
if (DBG) Logger::D(TAG, "onServerRegistered() - status=%d, serverIf=%d", status, serverIf);
{
AutoLock lock(mOwner->mServerIfLock);
if (mOwner->mCallback != NULL) {
mOwner->mServerIf = serverIf;
mOwner->mServerIfLock->Notify();
} else {
// registration timeout
Logger::E(TAG, "onServerRegistered: mCallback is NULL");
}
}
return NOERROR;
}
ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnScanResult(
/* [in] */ const String& address,
/* [in] */ Int32 rssi,
/* [in] */ ArrayOf<Byte>* advData)
{
VALIDATE_NOT_NULL(advData);
if (VDBG) Logger::D(TAG, "onScanResult() - Device=%s, RSSI=%d", address.string(), rssi);
// // no op
return NOERROR;
}
ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnServerConnectionState(
/* [in] */ Int32 status,
/* [in] */ Int32 serverIf,
/* [in] */ Boolean connected,
/* [in] */ const String& address)
{
if (DBG) Logger::D(TAG, "onServerConnectionState() - status=%d, serverIf=%d, device=%s",
status, serverIf, address.string());
//try {
AutoPtr<IBluetoothDevice> device;
mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device);
mOwner->mCallback->OnConnectionStateChange(device, status,
connected ? IBluetoothProfile::STATE_CONNECTED :
IBluetoothProfile::STATE_DISCONNECTED);
//} catch (Exception ex) {
// Log.w(TAG, "Unhandled exception in callback", ex);
//}
return NOERROR;
}
ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnServiceAdded(
/* [in] */ Int32 status,
/* [in] */ Int32 srvcType,
/* [in] */ Int32 srvcInstId,
/* [in] */ IParcelUuid* srvcId)
{
VALIDATE_NOT_NULL(srvcId);
AutoPtr<IUUID> srvcUuid;
srvcId->GetUuid((IUUID**)&srvcUuid);
if (DBG) Logger::D(TAG, "onServiceAdded() - service=");// + srvcUuid + "status=" + status);
AutoPtr<IBluetoothGattService> service;
mOwner->GetService(srvcUuid, srvcInstId, srvcType, (IBluetoothGattService**)&service);
if (service == NULL) return NOERROR;
//try {
mOwner->mCallback->OnServiceAdded(status, service);
//} catch (Exception ex) {
// Log.w(TAG, "Unhandled exception in callback", ex);
//}
return NOERROR;
}
ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnCharacteristicReadRequest(
/* [in] */ const String& address,
/* [in] */ Int32 transId,
/* [in] */ Int32 offset,
/* [in] */ Boolean isLong,
/* [in] */ Int32 srvcType,
/* [in] */ Int32 srvcInstId,
/* [in] */ IParcelUuid* srvcId,
/* [in] */ Int32 charInstId,
/* [in] */ IParcelUuid* charId)
{
AutoPtr<IUUID> srvcUuid;
srvcId->GetUuid((IUUID**)&srvcUuid);
AutoPtr<IUUID> charUuid;
charId->GetUuid((IUUID**)&charUuid);
if (VDBG) Logger::D(TAG, "onCharacteristicReadRequest() - ");
//+ "service=" + srvcUuid + ", characteristic=" + charUuid);
AutoPtr<IBluetoothDevice> device;
mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device);
AutoPtr<IBluetoothGattService> service;
mOwner->GetService(srvcUuid, srvcInstId, srvcType, (IBluetoothGattService**)&service);
if (service == NULL) return NOERROR;
AutoPtr<IBluetoothGattCharacteristic> characteristic;
service->GetCharacteristic(charUuid, (IBluetoothGattCharacteristic**)&characteristic);
if (characteristic == NULL) return NOERROR;
//try {
mOwner->mCallback->OnCharacteristicReadRequest(device, transId, offset, characteristic);
//} catch (Exception ex) {
// Log.w(TAG, "Unhandled exception in callback", ex);
//}
return NOERROR;
}
ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnDescriptorReadRequest(
/* [in] */ const String& address,
/* [in] */ Int32 transId,
/* [in] */ Int32 offset,
/* [in] */ Boolean isLong,
/* [in] */ Int32 srvcType,
/* [in] */ Int32 srvcInstId,
/* [in] */ IParcelUuid* srvcId,
/* [in] */ Int32 charInstId,
/* [in] */ IParcelUuid* charId,
/* [in] */ IParcelUuid* descrId)
{
AutoPtr<IUUID> srvcUuid;
srvcId->GetUuid((IUUID**)&srvcUuid);
AutoPtr<IUUID> charUuid;
charId->GetUuid((IUUID**)&charUuid);
AutoPtr<IUUID> descrUuid;
descrId->GetUuid((IUUID**)&descrUuid);
if (VDBG) Logger::D(TAG, "onCharacteristicReadRequest() - ");
//+ "service=" + srvcUuid + ", characteristic=" + charUuid
//+ "descriptor=" + descrUuid);
AutoPtr<IBluetoothDevice> device;
mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device);
AutoPtr<IBluetoothGattService> service;
mOwner->GetService(srvcUuid, srvcInstId, srvcType, (IBluetoothGattService**)&service);
if (service == NULL) return NOERROR;
AutoPtr<IBluetoothGattCharacteristic> characteristic;
service->GetCharacteristic(charUuid, (IBluetoothGattCharacteristic**)&characteristic);
if (characteristic == NULL) return NOERROR;
AutoPtr<IBluetoothGattDescriptor> descriptor;
characteristic->GetDescriptor(descrUuid, (IBluetoothGattDescriptor**)&descriptor);
if (descriptor == NULL) return NOERROR;
//try {
mOwner->mCallback->OnDescriptorReadRequest(device, transId, offset, descriptor);
//} catch (Exception ex) {
// Log.w(TAG, "Unhandled exception in callback", ex);
//}
return NOERROR;
}
ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnCharacteristicWriteRequest(
/* [in] */ const String& address,
/* [in] */ Int32 transId,
/* [in] */ Int32 offset,
/* [in] */ Int32 length,
/* [in] */ Boolean isPrep,
/* [in] */ Boolean needRsp,
/* [in] */ Int32 srvcType,
/* [in] */ Int32 srvcInstId,
/* [in] */ IParcelUuid* srvcId,
/* [in] */ Int32 charInstId,
/* [in] */ IParcelUuid* charId,
/* [in] */ ArrayOf<Byte>* value)
{
AutoPtr<IUUID> srvcUuid;
srvcId->GetUuid((IUUID**)&srvcUuid);
AutoPtr<IUUID> charUuid;
charId->GetUuid((IUUID**)&charUuid);
if (VDBG) Logger::D(TAG, "onCharacteristicWriteRequest() - ");
//+ "service=" + srvcUuid + ", characteristic=" + charUuid);
AutoPtr<IBluetoothDevice> device;
mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device);
AutoPtr<IBluetoothGattService> service;
mOwner->GetService(srvcUuid, srvcInstId, srvcType, (IBluetoothGattService**)&service);
if (service == NULL) return NOERROR;
AutoPtr<IBluetoothGattCharacteristic> characteristic;
service->GetCharacteristic(charUuid, (IBluetoothGattCharacteristic**)&characteristic);
if (characteristic == NULL) return NOERROR;
//try {
mOwner->mCallback->OnCharacteristicWriteRequest(device, transId, characteristic,
isPrep, needRsp, offset, value);
//} catch (Exception ex) {
// Log.w(TAG, "Unhandled exception in callback", ex);
//}
return NOERROR;
}
ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnDescriptorWriteRequest(
/* [in] */ const String& address,
/* [in] */ Int32 transId,
/* [in] */ Int32 offset,
/* [in] */ Int32 length,
/* [in] */ Boolean isPrep,
/* [in] */ Boolean needRsp,
/* [in] */ Int32 srvcType,
/* [in] */ Int32 srvcInstId,
/* [in] */ IParcelUuid* srvcId,
/* [in] */ Int32 charInstId,
/* [in] */ IParcelUuid* charId,
/* [in] */ IParcelUuid* descrId,
/* [in] */ ArrayOf<Byte>* value)
{
AutoPtr<IUUID> srvcUuid;
srvcId->GetUuid((IUUID**)&srvcUuid);
AutoPtr<IUUID> charUuid;
charId->GetUuid((IUUID**)&charUuid);
AutoPtr<IUUID> descrUuid;
descrId->GetUuid((IUUID**)&descrUuid);
if (VDBG) Logger::D(TAG, "onDescriptorWriteRequest() - ");
//+ "service=" + srvcUuid + ", characteristic=" + charUuid
//+ "descriptor=" + descrUuid);
AutoPtr<IBluetoothDevice> device;
mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device);
AutoPtr<IBluetoothGattService> service;
mOwner->GetService(srvcUuid, srvcInstId, srvcType, (IBluetoothGattService**)&service);
if (service == NULL) return NOERROR;
AutoPtr<IBluetoothGattCharacteristic> characteristic;
service->GetCharacteristic(charUuid, (IBluetoothGattCharacteristic**)&characteristic);
if (characteristic == NULL) return NOERROR;
AutoPtr<IBluetoothGattDescriptor> descriptor;
characteristic->GetDescriptor(descrUuid, (IBluetoothGattDescriptor**)&descriptor);
if (descriptor == NULL) return NOERROR;
//try {
mOwner->mCallback->OnDescriptorWriteRequest(device, transId, descriptor,
isPrep, needRsp, offset, value);
//} catch (Exception ex) {
// Log.w(TAG, "Unhandled exception in callback", ex);
//}
return NOERROR;
}
ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnExecuteWrite(
/* [in] */ const String& address,
/* [in] */ Int32 transId,
/* [in] */ Boolean execWrite)
{
if (DBG) Logger::D(TAG, "onExecuteWrite() - ");
//+ "device=" + address + ", transId=" + transId
//+ "execWrite=" + execWrite);
AutoPtr<IBluetoothDevice> device;
mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device);
if (device == NULL) return NOERROR;
//try {
mOwner->mCallback->OnExecuteWrite(device, transId, execWrite);
//} catch (Exception ex) {
// Log.w(TAG, "Unhandled exception in callback", ex);
//}
return NOERROR;
}
ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnNotificationSent(
/* [in] */ const String& address,
/* [in] */ Int32 status)
{
if (VDBG) Logger::D(TAG, "onNotificationSent() - ");
//+ "device=" + address + ", status=" + status);
AutoPtr<IBluetoothDevice> device;
mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device);
if (device == NULL) return NOERROR;
//try {
mOwner->mCallback->OnNotificationSent(device, status);
//} catch (Exception ex) {
// Log.w(TAG, "Unhandled exception: " + ex);
//}
return NOERROR;
}
//=====================================================================
// BluetoothGattServer
//=====================================================================
const String BluetoothGattServer::TAG("BluetoothGattServer");
const Boolean BluetoothGattServer::DBG = TRUE;
const Boolean BluetoothGattServer::VDBG = FALSE;
const Int32 BluetoothGattServer::CALLBACK_REG_TIMEOUT;
CAR_INTERFACE_IMPL_2(BluetoothGattServer, Object, IBluetoothGattServer, IBluetoothProfile);
BluetoothGattServer::BluetoothGattServer()
{
}
BluetoothGattServer::BluetoothGattServer(
/* [in] */ IContext* context,
/* [in] */ IIBluetoothGatt* iGatt,
/* [in] */ Int32 transport)
{
mContext = context;
mService = iGatt;
//mAdapter = BluetoothAdapter.getDefaultAdapter();
mAdapter = CBluetoothAdapter::GetDefaultAdapter();
mCallback = NULL;
mServerIf = 0;
mTransport = transport;
//mServices = new ArrayList<BluetoothGattService>();
CArrayList::New((IList**)&mServices);
}
ECode BluetoothGattServer::Close()
{
if (DBG) Logger::D(TAG, "close()");
UnregisterCallback();
return NOERROR;
}
ECode BluetoothGattServer::RegisterCallback(
/* [in] */ IBluetoothGattServerCallback* callback,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
if (DBG) Logger::D(TAG, "registerCallback()");
if (mService == NULL) {
Logger::E(TAG, "GATT service not available");
*result = FALSE;
return NOERROR;
}
AutoPtr<IUUIDHelper> uuidHelper;
CUUIDHelper::AcquireSingleton((IUUIDHelper**)&uuidHelper);
AutoPtr<IUUID> uuid;
uuidHelper->RandomUUID((IUUID**)&uuid);
if (DBG) Logger::D(TAG, "registerCallback() - UUID=");// + uuid);
{
AutoLock lock(mServerIfLock);
if (mCallback != NULL) {
Logger::E(TAG, "App can register callback only once");
*result = FALSE;
return NOERROR;
}
mCallback = callback;
//try {
AutoPtr<IParcelUuid> parcelUuid;
CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid);
ECode ec = mService->RegisterServer(parcelUuid, mBluetoothGattServerCallback);
//} catch (RemoteException e) {
if (FAILED(ec)) {
//Logger::E(TAG,"",e);
mCallback = NULL;
*result = FALSE;
return NOERROR;
}
//}
//try {
ec = mServerIfLock->Wait(CALLBACK_REG_TIMEOUT);
//} catch (InterruptedException e) {
// Logger::E(TAG, "" + e);
if (FAILED(ec)) {
mCallback = NULL;
}
//}
if (mServerIf == 0) {
mCallback = NULL;
*result = FALSE;
return NOERROR;
} else {
*result = TRUE;
return NOERROR;
}
}
return NOERROR;
}
ECode BluetoothGattServer::GetService(
/* [in] */ IUUID* uuid,
/* [in] */ Int32 instanceId,
/* [in] */ Int32 type,
/* [out] */ IBluetoothGattService** result)
{
VALIDATE_NOT_NULL(result);
Int32 size;
mServices->GetSize(&size);
for(Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> obj;
mServices->Get(i, (IInterface**)&obj);
IBluetoothGattService* svc = IBluetoothGattService::Probe(obj);
Int32 sType;
Int32 sInstanceId;
AutoPtr<IUUID> sUuid;
svc->GetType(&sType);
svc->GetInstanceId(&sInstanceId);
svc->GetUuid((IUUID**)&sUuid);
Boolean eq = FALSE;
if (sType == type &&
sInstanceId == instanceId &&
(sUuid->Equals(uuid, &eq), eq)) {
*result = svc;
REFCOUNT_ADD(*result);
return NOERROR;
}
}
*result = NULL;
return NOERROR;
}
ECode BluetoothGattServer::Connect(
/* [in] */ IBluetoothDevice* device,
/* [in] */ Boolean autoConnect,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
*result = FALSE;
if (DBG) Logger::D(TAG, "connect() - device: ");// + device.getAddress() + ", auto: " + autoConnect);
if (mService == NULL || mServerIf == 0) return NOERROR;
String address;
device->GetAddress(&address);
//try {
ECode ec = mService->ServerConnect(mServerIf, address,
autoConnect ? FALSE : TRUE, mTransport); // autoConnect is inverse of "isDirect"
//} catch (RemoteException e) {
// Logger::E(TAG,"",e);
if (FAILED(ec)) {
return NOERROR;
}
//}
*result = TRUE;
return NOERROR;
}
ECode BluetoothGattServer::CancelConnection(
/* [in] */ IBluetoothDevice* device)
{
if (DBG) Logger::D(TAG, "cancelConnection() - device: ");// + device.getAddress());
if (mService == NULL || mServerIf == 0) return NOERROR;
String address;
device->GetAddress(&address);
//try {
mService->ServerDisconnect(mServerIf, address);
//} catch (RemoteException e) {
// Logger::E(TAG,"",e);
//}
return NOERROR;
}
ECode BluetoothGattServer::SendResponse(
/* [in] */ IBluetoothDevice* device,
/* [in] */ Int32 requestId,
/* [in] */ Int32 status,
/* [in] */ Int32 offset,
/* [in] */ ArrayOf<Byte>* value,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
*result = FALSE;
if (VDBG) Logger::D(TAG, "sendResponse() - device: ");// + device.getAddress());
if (mService == NULL || mServerIf == 0) return NOERROR;
String address;
device->GetAddress(&address);
//try {
ECode ec = mService->SendResponse(mServerIf, address, requestId,
status, offset, value);
//} catch (RemoteException e) {
// Logger::E(TAG,"",e);
if (FAILED(ec)) {
return FALSE;
}
//}
*result = TRUE;
return NOERROR;
}
ECode BluetoothGattServer::NotifyCharacteristicChanged(
/* [in] */ IBluetoothDevice* device,
/* [in] */ IBluetoothGattCharacteristic* characteristic,
/* [in] */ Boolean confirm,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
*result = FALSE;
if (VDBG) Logger::D(TAG, "notifyCharacteristicChanged() - device: ");// + device.getAddress());
if (mService == NULL || mServerIf == 0) return NOERROR;
AutoPtr<IBluetoothGattService> service;
characteristic->GetService((IBluetoothGattService**)&service);
if (service == NULL) return NOERROR;
AutoPtr<ArrayOf<Byte> > value;
characteristic->GetValue((ArrayOf<Byte>**)&value);
if (value == NULL) {
//throw new IllegalArgumentException("Chracteristic value is empty. Use "
// + "BluetoothGattCharacteristic#setvalue to update");
Logger::E(TAG, "Chracteristic value is empty. Use BluetoothGattCharacteristic#setvalue to update");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
//try {
String address;
device->GetAddress(&address);
Int32 type;
service->GetType(&type);
Int32 instanceId;
service->GetInstanceId(&instanceId);
AutoPtr<IUUID> uuid;
service->GetUuid((IUUID**)&uuid);
AutoPtr<IParcelUuid> parcelUuid;
CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid);
Int32 cInstanceId;
characteristic->GetInstanceId(&cInstanceId);
AutoPtr<IUUID> cuuid;
characteristic->GetUuid((IUUID**)&cuuid);
AutoPtr<IParcelUuid> pcUuid;
CParcelUuid::New(cuuid, (IParcelUuid**)&pcUuid);
ECode ec = mService->SendNotification(mServerIf, address,
type, instanceId,
parcelUuid, cInstanceId,
pcUuid, confirm,
value);
//} catch (RemoteException e) {
// Logger::E(TAG,"",e);
if (FAILED(ec)) {
return FALSE;
}
//}
*result = TRUE;
return NOERROR;
}
ECode BluetoothGattServer::AddService(
/* [in] */ IBluetoothGattService* service,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
*result = FALSE;
if (DBG) Logger::D(TAG, "addService() - service: ");// + service.getUuid());
if (mService == NULL || mServerIf == 0) return NOERROR;
mServices->Add(TO_IINTERFACE(service));
Int32 type;
service->GetType(&type);
Int32 instanceId;
service->GetInstanceId(&instanceId);
AutoPtr<IUUID> uuid;
service->GetUuid((IUUID**)&uuid);
AutoPtr<IParcelUuid> parcelUuid;
CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid);
Boolean preferred;
service->IsAdvertisePreferred(&preferred);
Int32 handles = 0;
service->GetHandles(&handles);
//try {
mService->BeginServiceDeclaration(mServerIf, type,
instanceId, handles,
parcelUuid, preferred);
//List<BluetoothGattService> includedServices = service.getIncludedServices();
AutoPtr<IList> includedServices;
service->GetIncludedServices((IList**)&includedServices);
Int32 size;
includedServices->GetSize(&size);
for(Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> obj;
includedServices->Get(i, (IInterface**)&obj);
IBluetoothGattService* includedService = IBluetoothGattService::Probe(obj);
Int32 iType, iInstanceId;
includedService->GetType(&iType);
includedService->GetInstanceId(&iInstanceId);
AutoPtr<IUUID> uuid;
includedService->GetUuid((IUUID**)&uuid);
AutoPtr<IParcelUuid> parcelUuid;
CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid);
mService->AddIncludedService(mServerIf,
iType, iInstanceId,
parcelUuid);
}
//List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
AutoPtr<IList> characteristics;
service->GetCharacteristics((IList**)&characteristics);
Int32 csize;
characteristics->GetSize(&csize);
for(Int32 i = 0; i < csize; ++i) {
AutoPtr<IInterface> obj;
characteristics->Get(i, (IInterface**)&obj);
IBluetoothGattCharacteristic* characteristic = IBluetoothGattCharacteristic::Probe(obj);
Int32 keySize = 0, permissions = 0;
characteristic->GetKeySize(&keySize);
characteristic->GetPermissions(&permissions);
Int32 permission = ((keySize - 7) << 12)
+ permissions;
AutoPtr<IUUID> uuid;
characteristic->GetUuid((IUUID**)&uuid);
AutoPtr<IParcelUuid> parcelUuid;
CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid);
Int32 properties;
characteristic->GetProperties(&properties);
mService->AddCharacteristic(mServerIf,
parcelUuid,
properties, permission);
//List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
AutoPtr<IList> descriptors;
characteristic->GetDescriptors((IList**)&descriptors);
Int32 size;
descriptors->GetSize(&size);
for(Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> obj;
IBluetoothGattDescriptor* descriptor = IBluetoothGattDescriptor::Probe(obj);
Int32 dPermissions;
descriptor->GetPermissions(&dPermissions);
permission = ((keySize - 7) << 12)
+ dPermissions;
AutoPtr<IUUID> uuid;
descriptor->GetUuid((IUUID**)&uuid);
AutoPtr<IParcelUuid> parcelUuid;
CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid);
mService->AddDescriptor(mServerIf, parcelUuid, permission);
}
}
mService->EndServiceDeclaration(mServerIf);
//} catch (RemoteException e) {
// Logger::E(TAG,"",e);
// return FALSE;
//}
*result = TRUE;
return NOERROR;
}
ECode BluetoothGattServer::RemoveService(
/* [in] */ IBluetoothGattService* service,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
*result = FALSE;
if (DBG) Logger::D(TAG, "removeService() - service: ");// + service.getUuid());
if (mService == NULL || mServerIf == 0) return NOERROR;
AutoPtr<IBluetoothGattService> intService;
AutoPtr<IUUID> uuid;
service->GetUuid((IUUID**)&uuid);
Int32 instanceId, type;
service->GetInstanceId(&instanceId);
service->GetType(&type);
GetService(uuid, instanceId, type, (IBluetoothGattService**)&intService);
if (intService == NULL) return NOERROR;
AutoPtr<IParcelUuid> parcelUuid;
CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid);
//try {
ECode ec = mService->RemoveService(mServerIf, type,
instanceId, parcelUuid);
mServices->Remove(intService);
//} catch (RemoteException e) {
// Logger::E(TAG,"",e);
if (FAILED(ec)) {
return FALSE;
}
//}
*result = TRUE;
return NOERROR;
}
ECode BluetoothGattServer::ClearServices()
{
if (DBG) Logger::D(TAG, "clearServices()");
if (mService == NULL || mServerIf == 0) return NOERROR;
//try {
mService->ClearServices(mServerIf);
mServices->Clear();
//} catch (RemoteException e) {
// Logger::E(TAG,"",e);
//}
return NOERROR;
}
ECode BluetoothGattServer::GetServices(
/* [out] */ IList** result)
{
VALIDATE_NOT_NULL(result);
*result = mServices;
REFCOUNT_ADD(*result);
return NOERROR;
}
ECode BluetoothGattServer::GetService(
/* [in] */ IUUID* uuid,
/* [out] */ IBluetoothGattService** result)
{
VALIDATE_NOT_NULL(result);
Int32 size;
mServices->GetSize(&size);
for(Int32 i = 0; i < size; ++i) {
AutoPtr<IInterface> obj;
mServices->Get(i, (IInterface**)&obj);
IBluetoothGattService* service = IBluetoothGattService::Probe(obj);
AutoPtr<IUUID> sUuid;
service->GetUuid((IUUID**)&sUuid);
Boolean eq = FALSE;
if (sUuid->Equals(uuid, &eq), eq) {
*result = service;
REFCOUNT_ADD(*result);
return NOERROR;
}
}
*result = NULL;
return NOERROR;
}
ECode BluetoothGattServer::GetConnectionState(
/* [in] */ IBluetoothDevice* device,
/* [out] */ Int32* state)
{
// throw new UnsupportedOperationException("Use BluetoothManager#getConnectionState instead.");
return E_UNSUPPORTED_OPERATION_EXCEPTION;
}
ECode BluetoothGattServer::GetConnectedDevices(
/* [out] */ IList** devices)
{
// throw new UnsupportedOperationException
// ("Use BluetoothManager#getConnectedDevices instead.");
return E_UNSUPPORTED_OPERATION_EXCEPTION;
}
ECode BluetoothGattServer::GetDevicesMatchingConnectionStates(
/* [in] */ ArrayOf<Int32>* states,
/* [out] */ IList** devices)
{
// throw new UnsupportedOperationException
// ("Use BluetoothManager#getDevicesMatchingConnectionStates instead.");
return E_UNSUPPORTED_OPERATION_EXCEPTION;
}
void BluetoothGattServer::UnregisterCallback()
{
if (DBG) Logger::D(TAG, "unregisterCallback() - mServerIf=");// + mServerIf);
if (mService == NULL || mServerIf == 0) return;
//try {
mCallback = NULL;
mService->UnregisterServer(mServerIf);
mServerIf = 0;
//} catch (RemoteException e) {
// Logger::E(TAG,"",e);
//}
}
} // namespace Bluetooth
} // namespace Droid
} // namespace Elastos
| 33.811966 | 123 | 0.61841 | jingcao80 |
17c5e1257d39c35c1542de3d5e0f8dfb670382b5 | 1,346 | hh | C++ | src/cxx/lib/layout/cppunit/testBarcodeCollisionDetector.hh | sbooeshaghi/bcl2fastq | 3f39a24cd743fa71fba9b7dcf62e5d33cea8272d | [
"BSD-3-Clause"
] | 5 | 2021-06-07T12:36:11.000Z | 2022-02-08T09:49:02.000Z | src/cxx/lib/layout/cppunit/testBarcodeCollisionDetector.hh | sbooeshaghi/bcl2fastq | 3f39a24cd743fa71fba9b7dcf62e5d33cea8272d | [
"BSD-3-Clause"
] | 1 | 2022-03-01T23:55:57.000Z | 2022-03-01T23:57:15.000Z | src/cxx/lib/layout/cppunit/testBarcodeCollisionDetector.hh | sbooeshaghi/bcl2fastq | 3f39a24cd743fa71fba9b7dcf62e5d33cea8272d | [
"BSD-3-Clause"
] | null | null | null | /**
* BCL to FASTQ file converter
* Copyright (c) 2007-2017 Illumina, Inc.
*
* This software is covered by the accompanying EULA
* and certain third party copyright/licenses, and any user of this
* source file is bound by the terms therein.
*
* \file barcodeCollisionDetector.hh
*
* \brief BarcodeCollisionDetector cppunit test declarations.
*
* \author Aaron Day
*/
#ifndef BCL2FASTQ_LAYOUT_TEST_BARCODE_COLLISION_DETECTOR_HH
#define BCL2FASTQ_LAYOUT_TEST_BARCODE_COLLISION_DETECTOR_HH
#include <cppunit/extensions/HelperMacros.h>
#include <vector>
/// \brief Test suite for BarcodeCollisionDetector.
class TestBarcodeCollisionDetector : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(TestBarcodeCollisionDetector);
CPPUNIT_TEST(testSuccess);
CPPUNIT_TEST(testMismatchLength);
CPPUNIT_TEST(testNumComponents);
CPPUNIT_TEST(testCollisionSameSample);
CPPUNIT_TEST(testCollision);
CPPUNIT_TEST_SUITE_END();
private:
std::vector<std::size_t> componentMaxMismatches_;
public:
TestBarcodeCollisionDetector() : componentMaxMismatches_() {}
void setUp();
void tearDown();
void testSuccess();
void testMismatchLength();
void testNumComponents();
void testCollisionSameSample();
void testCollision();
};
#endif // BCL2FASTQ_LAYOUT_TEST_BARCODE_COLLISION_DETECTOR_HH
| 25.884615 | 67 | 0.767459 | sbooeshaghi |
17c678ac09686e3db38bc53e3d85ba4dd27930ca | 2,536 | cc | C++ | code/arduino/lib/deskmate/arduino/input/crank.cc | rbaron/deskmate | bbbe35a04ead4acc2d65da7e75ecebdece158382 | [
"MIT"
] | 48 | 2020-11-26T09:04:14.000Z | 2022-03-21T04:28:10.000Z | code/arduino/lib/deskmate/arduino/input/crank.cc | rbaron/deskmate | bbbe35a04ead4acc2d65da7e75ecebdece158382 | [
"MIT"
] | 1 | 2021-03-22T15:17:43.000Z | 2021-04-04T12:30:12.000Z | code/arduino/lib/deskmate/arduino/input/crank.cc | rbaron/deskmate | bbbe35a04ead4acc2d65da7e75ecebdece158382 | [
"MIT"
] | 7 | 2020-11-30T00:16:34.000Z | 2022-03-02T02:02:43.000Z | #include "deskmate/arduino/input/crank.h"
#include <Arduino.h>
#include "deskmate/input/input.h"
namespace deskmate {
namespace arduino {
namespace input {
namespace {
using deskmate::input::InputEvent;
using deskmate::input::InputEventHandler;
deskmate::input::InputEventHandler *input_handler = nullptr;
struct CrankPin {
int pin_n;
volatile int pin_value;
};
CrankPin crank_a{-1, HIGH};
CrankPin crank_b{-1, HIGH};
class State {
public:
enum States {
kInitial = 0,
k1CW,
k2CW,
k3CW,
k1CCW,
k2CCW,
k3CCW,
};
};
State::States state = State::kInitial;
State::States transition_table[][4] = {
// 00 01 10 11
{State::kInitial, State::k1CCW, State::k1CW,
State::kInitial}, // State::kInitial
// Clockwise transitions.
{State::kInitial, State::kInitial, State::k1CW,
State::k2CW}, // State::k1CW
{State::kInitial, State::k3CW, State::kInitial,
State::k2CW}, // State::k2CW
{State::kInitial, State::k3CW, State::kInitial,
State::kInitial}, // State::k3CW
// Counter-clockwise transitions.
{State::kInitial, State::k1CCW, State::kInitial,
State::k2CCW}, // State::k1CCW
{State::kInitial, State::kInitial, State::k3CCW,
State::k2CCW}, // State::k2CCW
{State::kInitial, State::kInitial, State::k3CCW,
State::kInitial}, // State::k3CCW
};
void HandleStateTransition() {
int transition =
((crank_a.pin_value == LOW) << 1 | crank_b.pin_value == LOW) & 0x3;
State::States next = transition_table[state][transition];
if (state == State::k3CW && next == State::kInitial) {
input_handler->HandleInputEvent(InputEvent::kCrankCW);
} else if (state == State::k3CCW && next == State::kInitial) {
input_handler->HandleInputEvent(InputEvent::kCrankCCW);
}
state = next;
}
void ISRCrankA() {
crank_a.pin_value = digitalRead(crank_a.pin_n);
HandleStateTransition();
}
void ISRCrankB() {
crank_b.pin_value = digitalRead(crank_b.pin_n);
HandleStateTransition();
}
} // namespace
void SetupCrankInterruptHandler(uint8_t crank_a_pin, uint8_t crank_b_pin,
InputEventHandler *handler) {
input_handler = handler;
crank_a.pin_n = crank_a_pin;
crank_b.pin_n = crank_b_pin;
pinMode(crank_a.pin_n, INPUT);
pinMode(crank_b.pin_n, INPUT);
attachInterrupt(crank_a.pin_n, ISRCrankA, CHANGE);
attachInterrupt(crank_b.pin_n, ISRCrankB, CHANGE);
}
} // namespace input
} // namespace arduino
} // namespace deskmate | 25.877551 | 73 | 0.663249 | rbaron |
17c6c202fc9e8dfd7c8b4acaa44eb86759c8d544 | 74,906 | cxx | C++ | main/sc/source/filter/starcalc/scflt.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sc/source/filter/starcalc/scflt.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sc/source/filter/starcalc/scflt.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_scfilt.hxx"
// INCLUDE ---------------------------------------------------------------
#include "scitems.hxx"
#include <editeng/eeitem.hxx>
#include <svx/algitem.hxx>
#include <editeng/boxitem.hxx>
#include <editeng/brshitem.hxx>
#include <editeng/colritem.hxx>
#include <editeng/crsditem.hxx>
#include <editeng/editdata.hxx>
#include <editeng/editeng.hxx>
#include <editeng/editobj.hxx>
#include <editeng/fhgtitem.hxx>
#include <editeng/fontitem.hxx>
#include <editeng/lrspitem.hxx>
#include <svx/pageitem.hxx>
#include <editeng/postitem.hxx>
#include <editeng/sizeitem.hxx>
#include <editeng/udlnitem.hxx>
#include <editeng/ulspitem.hxx>
#include <editeng/wghtitem.hxx>
#include <svl/zforlist.hxx>
#include <svl/PasswordHelper.hxx>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "global.hxx"
#include "sc.hrc"
#include "attrib.hxx"
#include "patattr.hxx"
#include "docpool.hxx"
#include "document.hxx"
#include "collect.hxx"
#include "rangenam.hxx"
#include "dbcolect.hxx"
#include "stlsheet.hxx"
#include "stlpool.hxx"
#include "filter.hxx"
#include "scflt.hxx"
#include "cell.hxx"
#include "scfobj.hxx"
#include "docoptio.hxx"
#include "viewopti.hxx"
#include "postit.hxx"
#include "globstr.hrc"
#include "ftools.hxx"
#include "tabprotection.hxx"
#include "fprogressbar.hxx"
using namespace com::sun::star;
#define DEFCHARSET RTL_TEXTENCODING_MS_1252
#define SC10TOSTRING(p) String((p),DEFCHARSET)
const SCCOL SC10MAXCOL = 255; // #i85906# don't try to load more columns than there are in the file
/** Those strings are used with SC10TOSTRING() and strcmp() and such, hence
need to be 0-terminated. */
static void lcl_ReadFixedString( SvStream& rStream, void* pData, size_t nLen )
{
sal_Char* pBuf = static_cast<sal_Char*>(pData);
if (!nLen)
pBuf[0] = 0;
else
{
rStream.Read( pBuf, nLen);
pBuf[nLen-1] = 0;
}
}
static void lcl_ReadFileHeader(SvStream& rStream, Sc10FileHeader& rFileHeader)
{
lcl_ReadFixedString( rStream, &rFileHeader.CopyRight, sizeof(rFileHeader.CopyRight));
rStream >> rFileHeader.Version;
rStream.Read(&rFileHeader.Reserved, sizeof(rFileHeader.Reserved));
}
static void lcl_ReadTabProtect(SvStream& rStream, Sc10TableProtect& rProtect)
{
lcl_ReadFixedString( rStream, &rProtect.PassWord, sizeof(rProtect.PassWord));
rStream >> rProtect.Flags;
rStream >> rProtect.Protect;
}
static void lcl_ReadSheetProtect(SvStream& rStream, Sc10SheetProtect& rProtect)
{
lcl_ReadFixedString( rStream, &rProtect.PassWord, sizeof(rProtect.PassWord));
rStream >> rProtect.Flags;
rStream >> rProtect.Protect;
}
static void lcl_ReadRGB(SvStream& rStream, Sc10Color& rColor)
{
rStream >> rColor.Dummy;
rStream >> rColor.Blue;
rStream >> rColor.Green;
rStream >> rColor.Red;
}
static void lcl_ReadPalette(SvStream& rStream, Sc10Color* pPalette)
{
for (sal_uInt16 i = 0; i < 16; i++)
lcl_ReadRGB(rStream, pPalette[i]);
}
static void lcl_ReadValueFormat(SvStream& rStream, Sc10ValueFormat& rFormat)
{
rStream >> rFormat.Format;
rStream >> rFormat.Info;
}
static void lcl_ReadLogFont(SvStream& rStream, Sc10LogFont& rFont)
{
rStream >> rFont.lfHeight;
rStream >> rFont.lfWidth;
rStream >> rFont.lfEscapement;
rStream >> rFont.lfOrientation;
rStream >> rFont.lfWeight;
rStream >> rFont.lfItalic;
rStream >> rFont.lfUnderline;
rStream >> rFont.lfStrikeOut;
rStream >> rFont.lfCharSet;
rStream >> rFont.lfOutPrecision;
rStream >> rFont.lfClipPrecision;
rStream >> rFont.lfQuality;
rStream >> rFont.lfPitchAndFamily;
lcl_ReadFixedString( rStream, &rFont.lfFaceName, sizeof(rFont.lfFaceName));
}
static void lcl_ReadBlockRect(SvStream& rStream, Sc10BlockRect& rBlock)
{
rStream >> rBlock.x1;
rStream >> rBlock.y1;
rStream >> rBlock.x2;
rStream >> rBlock.y2;
}
static void lcl_ReadHeadFootLine(SvStream& rStream, Sc10HeadFootLine& rLine)
{
lcl_ReadFixedString( rStream, &rLine.Title, sizeof(rLine.Title));
lcl_ReadLogFont(rStream, rLine.LogFont);
rStream >> rLine.HorJustify;
rStream >> rLine.VerJustify;
rStream >> rLine.Raster;
rStream >> rLine.Frame;
lcl_ReadRGB(rStream, rLine.TextColor);
lcl_ReadRGB(rStream, rLine.BackColor);
lcl_ReadRGB(rStream, rLine.RasterColor);
rStream >> rLine.FrameColor;
rStream >> rLine.Reserved;
}
static void lcl_ReadPageFormat(SvStream& rStream, Sc10PageFormat& rFormat)
{
lcl_ReadHeadFootLine(rStream, rFormat.HeadLine);
lcl_ReadHeadFootLine(rStream, rFormat.FootLine);
rStream >> rFormat.Orientation;
rStream >> rFormat.Width;
rStream >> rFormat.Height;
rStream >> rFormat.NonPrintableX;
rStream >> rFormat.NonPrintableY;
rStream >> rFormat.Left;
rStream >> rFormat.Top;
rStream >> rFormat.Right;
rStream >> rFormat.Bottom;
rStream >> rFormat.Head;
rStream >> rFormat.Foot;
rStream >> rFormat.HorCenter;
rStream >> rFormat.VerCenter;
rStream >> rFormat.PrintGrid;
rStream >> rFormat.PrintColRow;
rStream >> rFormat.PrintNote;
rStream >> rFormat.TopBottomDir;
lcl_ReadFixedString( rStream, &rFormat.PrintAreaName, sizeof(rFormat.PrintAreaName));
lcl_ReadBlockRect(rStream, rFormat.PrintArea);
rStream.Read(&rFormat.PrnZoom, sizeof(rFormat.PrnZoom));
rStream >> rFormat.FirstPageNo;
rStream >> rFormat.RowRepeatStart;
rStream >> rFormat.RowRepeatEnd;
rStream >> rFormat.ColRepeatStart;
rStream >> rFormat.ColRepeatEnd;
rStream.Read(&rFormat.Reserved, sizeof(rFormat.Reserved));
}
static void lcl_ReadGraphHeader(SvStream& rStream, Sc10GraphHeader& rHeader)
{
rStream >> rHeader.Typ;
rStream >> rHeader.CarretX;
rStream >> rHeader.CarretY;
rStream >> rHeader.CarretZ;
rStream >> rHeader.x;
rStream >> rHeader.y;
rStream >> rHeader.w;
rStream >> rHeader.h;
rStream >> rHeader.IsRelPos;
rStream >> rHeader.DoPrint;
rStream >> rHeader.FrameType;
rStream >> rHeader.IsTransparent;
lcl_ReadRGB(rStream, rHeader.FrameColor);
lcl_ReadRGB(rStream, rHeader.BackColor);
rStream.Read(&rHeader.Reserved, sizeof(rHeader.Reserved));
}
static void lcl_ReadImageHeaer(SvStream& rStream, Sc10ImageHeader& rHeader)
{
lcl_ReadFixedString( rStream, &rHeader.FileName, sizeof(rHeader.FileName));
rStream >> rHeader.Typ;
rStream >> rHeader.Linked;
rStream >> rHeader.x1;
rStream >> rHeader.y1;
rStream >> rHeader.x2;
rStream >> rHeader.y2;
rStream >> rHeader.Size;
}
static void lcl_ReadChartHeader(SvStream& rStream, Sc10ChartHeader& rHeader)
{
rStream >> rHeader.MM;
rStream >> rHeader.xExt;
rStream >> rHeader.yExt;
rStream >> rHeader.Size;
}
static void lcl_ReadChartSheetData(SvStream& rStream, Sc10ChartSheetData& rSheetData)
{
rStream >> rSheetData.HasTitle;
rStream >> rSheetData.TitleX;
rStream >> rSheetData.TitleY;
rStream >> rSheetData.HasSubTitle;
rStream >> rSheetData.SubTitleX;
rStream >> rSheetData.SubTitleY;
rStream >> rSheetData.HasLeftTitle;
rStream >> rSheetData.LeftTitleX;
rStream >> rSheetData.LeftTitleY;
rStream >> rSheetData.HasLegend;
rStream >> rSheetData.LegendX1;
rStream >> rSheetData.LegendY1;
rStream >> rSheetData.LegendX2;
rStream >> rSheetData.LegendY2;
rStream >> rSheetData.HasLabel;
rStream >> rSheetData.LabelX1;
rStream >> rSheetData.LabelY1;
rStream >> rSheetData.LabelX2;
rStream >> rSheetData.LabelY2;
rStream >> rSheetData.DataX1;
rStream >> rSheetData.DataY1;
rStream >> rSheetData.DataX2;
rStream >> rSheetData.DataY2;
rStream.Read(&rSheetData.Reserved, sizeof(rSheetData.Reserved));
}
static void lcl_ReadChartTypeData(SvStream& rStream, Sc10ChartTypeData& rTypeData)
{
rStream >> rTypeData.NumSets;
rStream >> rTypeData.NumPoints;
rStream >> rTypeData.DrawMode;
rStream >> rTypeData.GraphType;
rStream >> rTypeData.GraphStyle;
lcl_ReadFixedString( rStream, &rTypeData.GraphTitle, sizeof(rTypeData.GraphTitle));
lcl_ReadFixedString( rStream, &rTypeData.BottomTitle, sizeof(rTypeData.BottomTitle));
sal_uInt16 i;
for (i = 0; i < 256; i++)
rStream >> rTypeData.SymbolData[i];
for (i = 0; i < 256; i++)
rStream >> rTypeData.ColorData[i];
for (i = 0; i < 256; i++)
rStream >> rTypeData.ThickLines[i];
for (i = 0; i < 256; i++)
rStream >> rTypeData.PatternData[i];
for (i = 0; i < 256; i++)
rStream >> rTypeData.LinePatternData[i];
for (i = 0; i < 11; i++)
rStream >> rTypeData.NumGraphStyles[i];
rStream >> rTypeData.ShowLegend;
for (i = 0; i < 256; i++)
lcl_ReadFixedString( rStream, &rTypeData.LegendText[i], sizeof(Sc10ChartText));
rStream >> rTypeData.ExplodePie;
rStream >> rTypeData.FontUse;
for (i = 0; i < 5; i++)
rStream >> rTypeData.FontFamily[i];
for (i = 0; i < 5; i++)
rStream >> rTypeData.FontStyle[i];
for (i = 0; i < 5; i++)
rStream >> rTypeData.FontSize[i];
rStream >> rTypeData.GridStyle;
rStream >> rTypeData.Labels;
rStream >> rTypeData.LabelEvery;
for (i = 0; i < 50; i++)
lcl_ReadFixedString( rStream, &rTypeData.LabelText[i], sizeof(Sc10ChartText));
lcl_ReadFixedString( rStream, &rTypeData.LeftTitle, sizeof(rTypeData.LeftTitle));
rStream.Read(&rTypeData.Reserved, sizeof(rTypeData.Reserved));
}
double lcl_PascalToDouble(sal_Char* tp6)
{
sal_uInt8* pnUnsigned = reinterpret_cast< sal_uInt8* >( tp6 );
// biased exponent
sal_uInt8 be = pnUnsigned[ 0 ];
// lower 16 bits of mantissa
sal_uInt16 v1 = static_cast< sal_uInt16 >( pnUnsigned[ 2 ] * 256 + pnUnsigned[ 1 ] );
// next 16 bits of mantissa
sal_uInt16 v2 = static_cast< sal_uInt16 >( pnUnsigned[ 4 ] * 256 + pnUnsigned[ 3 ] );
// upper 7 bits of mantissa
sal_uInt8 v3 = static_cast< sal_uInt8 >( pnUnsigned[ 5 ] & 0x7F );
// sign bit
bool s = (pnUnsigned[ 5 ] & 0x80) != 0;
if (be == 0)
return 0.0;
return (((((128 + v3) * 65536.0) + v2) * 65536.0 + v1) *
ldexp ((s ? -1.0 : 1.0), be - (129+39)));
}
static void lcl_ChangeColor( sal_uInt16 nIndex, Color& rColor )
{
ColorData aCol;
switch( nIndex )
{
case 1: aCol = COL_RED; break;
case 2: aCol = COL_GREEN; break;
case 3: aCol = COL_BROWN; break;
case 4: aCol = COL_BLUE; break;
case 5: aCol = COL_MAGENTA; break;
case 6: aCol = COL_CYAN; break;
case 7: aCol = COL_GRAY; break;
case 8: aCol = COL_LIGHTGRAY; break;
case 9: aCol = COL_LIGHTRED; break;
case 10: aCol = COL_LIGHTGREEN; break;
case 11: aCol = COL_YELLOW; break;
case 12: aCol = COL_LIGHTBLUE; break;
case 13: aCol = COL_LIGHTMAGENTA; break;
case 14: aCol = COL_LIGHTCYAN; break;
case 15: aCol = COL_WHITE; break;
default: aCol = COL_BLACK;
}
rColor.SetColor( aCol );
}
String lcl_MakeOldPageStyleFormatName( sal_uInt16 i )
{
String aName = ScGlobal::GetRscString( STR_PAGESTYLE );
aName.AppendAscii( " " );
aName += String::CreateFromInt32( i + 1 );
return aName;
}
template < typename T > sal_uLong insert_new( ScCollection* pCollection, SvStream& rStream )
{
T* pData = new (::std::nothrow) T( rStream);
sal_uLong nError = rStream.GetError();
if (pData)
{
if (nError)
delete pData;
else
pCollection->Insert( pData);
}
else
nError = errOutOfMemory;
return nError;
}
//--------------------------------------------
// Font
//--------------------------------------------
Sc10FontData::Sc10FontData(SvStream& rStream)
{
rStream >> Height;
rStream >> CharSet;
rStream >> PitchAndFamily;
sal_uInt16 nLen;
rStream >> nLen;
if (nLen < sizeof(FaceName))
rStream.Read(FaceName, nLen);
else
rStream.SetError(ERRCODE_IO_WRONGFORMAT);
}
Sc10FontCollection::Sc10FontCollection(SvStream& rStream) :
ScCollection (4, 4),
nError (0)
{
sal_uInt16 ID;
rStream >> ID;
if (ID == FontID)
{
sal_uInt16 nAnz;
rStream >> nAnz;
for (sal_uInt16 i=0; (i < nAnz) && (nError == 0); i++)
{
nError = insert_new<Sc10FontData>( this, rStream);
}
}
else
{
DBG_ERROR( "FontID" );
nError = errUnknownID;
}
}
//--------------------------------------------
// Benannte-Bereiche
//--------------------------------------------
Sc10NameData::Sc10NameData(SvStream& rStream)
{
sal_uInt8 nLen;
rStream >> nLen;
rStream.Read(Name, sizeof(Name) - 1);
if (nLen >= sizeof(Name))
nLen = sizeof(Name) - 1;
Name[nLen] = 0;
rStream >> nLen;
rStream.Read(Reference, sizeof(Reference) - 1);
if (nLen >= sizeof(Reference))
nLen = sizeof(Reference) - 1;
Reference[nLen] = 0;
rStream.Read(Reserved, sizeof(Reserved));
}
Sc10NameCollection::Sc10NameCollection(SvStream& rStream) :
ScCollection (4, 4),
nError (0)
{
sal_uInt16 ID;
rStream >> ID;
if (ID == NameID)
{
sal_uInt16 nAnz;
rStream >> nAnz;
for (sal_uInt16 i=0; (i < nAnz) && (nError == 0); i++)
{
nError = insert_new<Sc10NameData>( this, rStream);
}
}
else
{
DBG_ERROR( "NameID" );
nError = errUnknownID;
}
}
//--------------------------------------------
// Vorlagen
//--------------------------------------------
Sc10PatternData::Sc10PatternData(SvStream& rStream)
{
lcl_ReadFixedString( rStream, Name, sizeof(Name));
lcl_ReadValueFormat(rStream, ValueFormat);
lcl_ReadLogFont(rStream, LogFont);
rStream >> Attr;
rStream >> Justify;
rStream >> Frame;
rStream >> Raster;
rStream >> nColor;
rStream >> FrameColor;
rStream >> Flags;
rStream >> FormatFlags;
rStream.Read(Reserved, sizeof(Reserved));
}
Sc10PatternCollection::Sc10PatternCollection(SvStream& rStream) :
ScCollection (4, 4),
nError (0)
{
sal_uInt16 ID;
rStream >> ID;
if (ID == PatternID)
{
sal_uInt16 nAnz;
rStream >> nAnz;
for (sal_uInt16 i=0; (i < nAnz) && (nError == 0); i++)
{
nError = insert_new<Sc10PatternData>( this, rStream);
}
}
else
{
DBG_ERROR( "PatternID" );
nError = errUnknownID;
}
}
//--------------------------------------------
// Datenbank
//--------------------------------------------
Sc10DataBaseData::Sc10DataBaseData(SvStream& rStream)
{
lcl_ReadFixedString( rStream, &DataBaseRec.Name, sizeof(DataBaseRec.Name));
rStream >> DataBaseRec.Tab;
lcl_ReadBlockRect(rStream, DataBaseRec.Block);
rStream >> DataBaseRec.RowHeader;
rStream >> DataBaseRec.SortField0;
rStream >> DataBaseRec.SortUpOrder0;
rStream >> DataBaseRec.SortField1;
rStream >> DataBaseRec.SortUpOrder1;
rStream >> DataBaseRec.SortField2;
rStream >> DataBaseRec.SortUpOrder2;
rStream >> DataBaseRec.IncludeFormat;
rStream >> DataBaseRec.QueryField0;
rStream >> DataBaseRec.QueryOp0;
rStream >> DataBaseRec.QueryByString0;
lcl_ReadFixedString( rStream, &DataBaseRec.QueryString0, sizeof(DataBaseRec.QueryString0));
DataBaseRec.QueryValue0 = ScfTools::ReadLongDouble(rStream);
rStream >> DataBaseRec.QueryConnect1;
rStream >> DataBaseRec.QueryField1;
rStream >> DataBaseRec.QueryOp1;
rStream >> DataBaseRec.QueryByString1;
lcl_ReadFixedString( rStream, &DataBaseRec.QueryString1, sizeof(DataBaseRec.QueryString1));
DataBaseRec.QueryValue1 = ScfTools::ReadLongDouble(rStream);
rStream >> DataBaseRec.QueryConnect2;
rStream >> DataBaseRec.QueryField2;
rStream >> DataBaseRec.QueryOp2;
rStream >> DataBaseRec.QueryByString2;
lcl_ReadFixedString( rStream, &DataBaseRec.QueryString2, sizeof(DataBaseRec.QueryString2));
DataBaseRec.QueryValue2 = ScfTools::ReadLongDouble(rStream);
}
Sc10DataBaseCollection::Sc10DataBaseCollection(SvStream& rStream) :
ScCollection (4, 4),
nError (0)
{
sal_uInt16 ID;
rStream >> ID;
if (ID == DataBaseID)
{
lcl_ReadFixedString( rStream, ActName, sizeof(ActName));
sal_uInt16 nAnz;
rStream >> nAnz;
for (sal_uInt16 i=0; (i < nAnz) && (nError == 0); i++)
{
nError = insert_new<Sc10DataBaseData>( this, rStream);
}
}
else
{
DBG_ERROR( "DataBaseID" );
nError = errUnknownID;
}
}
int Sc10LogFont::operator==( const Sc10LogFont& rData ) const
{
return !strcmp( lfFaceName, rData.lfFaceName )
&& lfHeight == rData.lfHeight
&& lfWidth == rData.lfWidth
&& lfEscapement == rData.lfEscapement
&& lfOrientation == rData.lfOrientation
&& lfWeight == rData.lfWeight
&& lfItalic == rData.lfItalic
&& lfUnderline == rData.lfUnderline
&& lfStrikeOut == rData.lfStrikeOut
&& lfCharSet == rData.lfCharSet
&& lfOutPrecision == rData.lfOutPrecision
&& lfClipPrecision == rData.lfClipPrecision
&& lfQuality == rData.lfQuality
&& lfPitchAndFamily == rData.lfPitchAndFamily;
}
int Sc10Color::operator==( const Sc10Color& rColor ) const
{
return ((Red == rColor.Red) && (Green == rColor.Green) && (Blue == rColor.Blue));
}
int Sc10HeadFootLine::operator==( const Sc10HeadFootLine& rData ) const
{
return !strcmp(Title, rData.Title)
&& LogFont == rData.LogFont
&& HorJustify == rData.HorJustify
&& VerJustify == rData.VerJustify
&& Raster == rData.Raster
&& Frame == rData.Frame
&& TextColor == rData.TextColor
&& BackColor == rData.BackColor
&& RasterColor == rData.RasterColor
&& FrameColor == rData.FrameColor
&& Reserved == rData.Reserved;
}
int Sc10PageFormat::operator==( const Sc10PageFormat& rData ) const
{
return !strcmp(PrintAreaName, rData.PrintAreaName)
&& HeadLine == rData.HeadLine
&& FootLine == rData.FootLine
&& Orientation == rData.Orientation
&& Width == rData.Width
&& Height == rData.Height
&& NonPrintableX == rData.NonPrintableX
&& NonPrintableY == rData.NonPrintableY
&& Left == rData.Left
&& Top == rData.Top
&& Right == rData.Right
&& Bottom == rData.Bottom
&& Head == rData.Head
&& Foot == rData.Foot
&& HorCenter == rData.HorCenter
&& VerCenter == rData.VerCenter
&& PrintGrid == rData.PrintGrid
&& PrintColRow == rData.PrintColRow
&& PrintNote == rData.PrintNote
&& TopBottomDir == rData.TopBottomDir
&& FirstPageNo == rData.FirstPageNo
&& RowRepeatStart == rData.RowRepeatStart
&& RowRepeatEnd == rData.RowRepeatEnd
&& ColRepeatStart == rData.ColRepeatStart
&& ColRepeatEnd == rData.ColRepeatEnd
&& !memcmp( PrnZoom, rData.PrnZoom, sizeof(PrnZoom) )
&& !memcmp( &PrintArea, &rData.PrintArea, sizeof(PrintArea) );
}
sal_uInt16 Sc10PageCollection::InsertFormat( const Sc10PageFormat& rData )
{
for (sal_uInt16 i=0; i<nCount; i++)
if (At(i)->aPageFormat == rData)
return i;
Insert( new Sc10PageData(rData) );
return nCount-1;
}
static inline sal_uInt8 GetMixedCol( const sal_uInt8 nB, const sal_uInt8 nF, const sal_uInt16 nFak )
{
sal_Int32 nT = nB - nF;
nT *= ( sal_Int32 ) nFak;
nT /= 0xFFFF;
nT += nF;
return ( sal_uInt8 ) nT;
}
static inline Color GetMixedColor( const Color& rFore, const Color& rBack, sal_uInt16 nFact )
{
return Color( GetMixedCol( rBack.GetRed(), rFore.GetRed(), nFact ),
GetMixedCol( rBack.GetGreen(), rFore.GetGreen(), nFact ),
GetMixedCol( rBack.GetBlue(), rFore.GetBlue(), nFact ) );
}
void Sc10PageCollection::PutToDoc( ScDocument* pDoc )
{
ScStyleSheetPool* pStylePool = pDoc->GetStyleSheetPool();
EditEngine aEditEngine( pDoc->GetEnginePool() );
EditTextObject* pEmptyObject = aEditEngine.CreateTextObject();
for (sal_uInt16 i=0; i<nCount; i++)
{
Sc10PageFormat* pPage = &At(i)->aPageFormat;
pPage->Width = (short) ( pPage->Width * ( 72.0 / 72.27 ) + 0.5 );
pPage->Height = (short) ( pPage->Height * ( 72.0 / 72.27 ) + 0.5 );
pPage->Top = (short) ( pPage->Top * ( 72.0 / 72.27 ) + 0.5 );
pPage->Bottom = (short) ( pPage->Bottom * ( 72.0 / 72.27 ) + 0.5 );
pPage->Left = (short) ( pPage->Left * ( 72.0 / 72.27 ) + 0.5 );
pPage->Right = (short) ( pPage->Right * ( 72.0 / 72.27 ) + 0.5 );
pPage->Head = (short) ( pPage->Head * ( 72.0 / 72.27 ) + 0.5 );
pPage->Foot = (short) ( pPage->Foot * ( 72.0 / 72.27 ) + 0.5 );
String aName = lcl_MakeOldPageStyleFormatName( i );
ScStyleSheet* pSheet = (ScStyleSheet*) &pStylePool->Make( aName,
SFX_STYLE_FAMILY_PAGE,
SFXSTYLEBIT_USERDEF | SCSTYLEBIT_STANDARD );
// #i68483# set page style name at sheet...
pDoc->SetPageStyle( static_cast< SCTAB >( i ), aName );
SfxItemSet* pSet = &pSheet->GetItemSet();
for (sal_uInt16 nHeadFoot=0; nHeadFoot<2; nHeadFoot++)
{
Sc10HeadFootLine* pHeadFootLine = nHeadFoot ? &pPage->FootLine : &pPage->HeadLine;
SfxItemSet aEditAttribs(aEditEngine.GetEmptyItemSet());
FontFamily eFam = FAMILY_DONTKNOW;
switch (pPage->HeadLine.LogFont.lfPitchAndFamily & 0xF0)
{
case ffDontCare: eFam = FAMILY_DONTKNOW; break;
case ffRoman: eFam = FAMILY_ROMAN; break;
case ffSwiss: eFam = FAMILY_SWISS; break;
case ffModern: eFam = FAMILY_MODERN; break;
case ffScript: eFam = FAMILY_SCRIPT; break;
case ffDecorative: eFam = FAMILY_DECORATIVE; break;
default: eFam = FAMILY_DONTKNOW; break;
}
aEditAttribs.Put( SvxFontItem(
eFam,
SC10TOSTRING( pHeadFootLine->LogFont.lfFaceName ), EMPTY_STRING,
PITCH_DONTKNOW, RTL_TEXTENCODING_DONTKNOW, EE_CHAR_FONTINFO ),
EE_CHAR_FONTINFO );
aEditAttribs.Put( SvxFontHeightItem( Abs( pHeadFootLine->LogFont.lfHeight ), 100, EE_CHAR_FONTHEIGHT ),
EE_CHAR_FONTHEIGHT);
Sc10Color nColor = pHeadFootLine->TextColor;
Color TextColor( nColor.Red, nColor.Green, nColor.Blue );
aEditAttribs.Put(SvxColorItem(TextColor, EE_CHAR_COLOR), EE_CHAR_COLOR);
// FontAttr
if (pHeadFootLine->LogFont.lfWeight != fwNormal)
aEditAttribs.Put(SvxWeightItem(WEIGHT_BOLD, EE_CHAR_WEIGHT), EE_CHAR_WEIGHT);
if (pHeadFootLine->LogFont.lfItalic != 0)
aEditAttribs.Put(SvxPostureItem(ITALIC_NORMAL, EE_CHAR_ITALIC), EE_CHAR_ITALIC);
if (pHeadFootLine->LogFont.lfUnderline != 0)
aEditAttribs.Put(SvxUnderlineItem(UNDERLINE_SINGLE, EE_CHAR_UNDERLINE), EE_CHAR_UNDERLINE);
if (pHeadFootLine->LogFont.lfStrikeOut != 0)
aEditAttribs.Put(SvxCrossedOutItem(STRIKEOUT_SINGLE, EE_CHAR_STRIKEOUT), EE_CHAR_STRIKEOUT);
String aText( pHeadFootLine->Title, DEFCHARSET );
aEditEngine.SetText( aText );
aEditEngine.QuickSetAttribs( aEditAttribs, ESelection( 0, 0, 0, aText.Len() ) );
EditTextObject* pObject = aEditEngine.CreateTextObject();
ScPageHFItem aHeaderItem(nHeadFoot ? ATTR_PAGE_FOOTERRIGHT : ATTR_PAGE_HEADERRIGHT);
switch (pHeadFootLine->HorJustify)
{
case hjCenter:
aHeaderItem.SetLeftArea(*pEmptyObject);
aHeaderItem.SetCenterArea(*pObject);
aHeaderItem.SetRightArea(*pEmptyObject);
break;
case hjRight:
aHeaderItem.SetLeftArea(*pEmptyObject);
aHeaderItem.SetCenterArea(*pEmptyObject);
aHeaderItem.SetRightArea(*pObject);
break;
default:
aHeaderItem.SetLeftArea(*pObject);
aHeaderItem.SetCenterArea(*pEmptyObject);
aHeaderItem.SetRightArea(*pEmptyObject);
break;
}
delete pObject;
pSet->Put( aHeaderItem );
SfxItemSet aSetItemItemSet( *pDoc->GetPool(),
ATTR_BACKGROUND, ATTR_BACKGROUND,
ATTR_BORDER, ATTR_SHADOW,
ATTR_PAGE_SIZE, ATTR_PAGE_SIZE,
ATTR_LRSPACE, ATTR_ULSPACE,
ATTR_PAGE_ON, ATTR_PAGE_SHARED,
0 );
nColor = pHeadFootLine->BackColor;
Color aBColor( nColor.Red, nColor.Green, nColor.Blue );
nColor = pHeadFootLine->RasterColor;
Color aRColor( nColor.Red, nColor.Green, nColor.Blue );
sal_uInt16 nFact;
sal_Bool bSwapCol = sal_False;
switch (pHeadFootLine->Raster)
{
case raNone: nFact = 0xffff; bSwapCol = sal_True; break;
case raGray12: nFact = (0xffff / 100) * 12; break;
case raGray25: nFact = (0xffff / 100) * 25; break;
case raGray50: nFact = (0xffff / 100) * 50; break;
case raGray75: nFact = (0xffff / 100) * 75; break;
default: nFact = 0xffff;
}
if( bSwapCol )
aSetItemItemSet.Put( SvxBrushItem( GetMixedColor( aBColor, aRColor, nFact ), ATTR_BACKGROUND ) );
else
aSetItemItemSet.Put( SvxBrushItem( GetMixedColor( aRColor, aBColor, nFact ), ATTR_BACKGROUND ) );
if (pHeadFootLine->Frame != 0)
{
sal_uInt16 nLeft = 0;
sal_uInt16 nTop = 0;
sal_uInt16 nRight = 0;
sal_uInt16 nBottom = 0;
sal_uInt16 fLeft = (pHeadFootLine->Frame & 0x000F);
sal_uInt16 fTop = (pHeadFootLine->Frame & 0x00F0) / 0x0010;
sal_uInt16 fRight = (pHeadFootLine->Frame & 0x0F00) / 0x0100;
sal_uInt16 fBottom = (pHeadFootLine->Frame & 0xF000) / 0x1000;
if (fLeft > 1)
nLeft = 50;
else if (fLeft > 0)
nLeft = 20;
if (fTop > 1)
nTop = 50;
else if (fTop > 0)
nTop = 20;
if (fRight > 1)
nRight = 50;
else if (fRight > 0)
nRight = 20;
if (fBottom > 1)
nBottom = 50;
else if (fBottom > 0)
nBottom = 20;
Color ColorLeft(COL_BLACK);
Color ColorTop(COL_BLACK);
Color ColorRight(COL_BLACK);
Color ColorBottom(COL_BLACK);
sal_uInt16 cLeft = (pHeadFootLine->FrameColor & 0x000F);
sal_uInt16 cTop = (pHeadFootLine->FrameColor & 0x00F0) >> 4;
sal_uInt16 cRight = (pHeadFootLine->FrameColor & 0x0F00) >> 8;
sal_uInt16 cBottom = (pHeadFootLine->FrameColor & 0xF000) >> 12;
lcl_ChangeColor(cLeft, ColorLeft);
lcl_ChangeColor(cTop, ColorTop);
lcl_ChangeColor(cRight, ColorRight);
lcl_ChangeColor(cBottom, ColorBottom);
SvxBorderLine aLine;
SvxBoxItem aBox( ATTR_BORDER );
aLine.SetOutWidth(nLeft);
aLine.SetColor(ColorLeft);
aBox.SetLine(&aLine, BOX_LINE_LEFT);
aLine.SetOutWidth(nTop);
aLine.SetColor(ColorTop);
aBox.SetLine(&aLine, BOX_LINE_TOP);
aLine.SetOutWidth(nRight);
aLine.SetColor(ColorRight);
aBox.SetLine(&aLine, BOX_LINE_RIGHT);
aLine.SetOutWidth(nBottom);
aLine.SetColor(ColorBottom);
aBox.SetLine(&aLine, BOX_LINE_BOTTOM);
aSetItemItemSet.Put(aBox);
}
pSet->Put( SvxULSpaceItem( 0, 0, ATTR_ULSPACE ) );
if (nHeadFoot==0)
aSetItemItemSet.Put( SvxSizeItem( ATTR_PAGE_SIZE, Size( 0, pPage->Top - pPage->Head ) ) );
else
aSetItemItemSet.Put( SvxSizeItem( ATTR_PAGE_SIZE, Size( 0, pPage->Bottom - pPage->Foot ) ) );
aSetItemItemSet.Put(SfxBoolItem( ATTR_PAGE_ON, sal_True ));
aSetItemItemSet.Put(SfxBoolItem( ATTR_PAGE_DYNAMIC, sal_False ));
aSetItemItemSet.Put(SfxBoolItem( ATTR_PAGE_SHARED, sal_True ));
pSet->Put( SvxSetItem( nHeadFoot ? ATTR_PAGE_FOOTERSET : ATTR_PAGE_HEADERSET,
aSetItemItemSet ) );
}
SvxPageItem aPageItem(ATTR_PAGE);
aPageItem.SetPageUsage( SVX_PAGE_ALL );
aPageItem.SetLandscape( pPage->Orientation != 1 );
aPageItem.SetNumType( SVX_ARABIC );
pSet->Put(aPageItem);
pSet->Put(SvxLRSpaceItem( pPage->Left, pPage->Right, 0,0, ATTR_LRSPACE ));
pSet->Put(SvxULSpaceItem( pPage->Top, pPage->Bottom, ATTR_ULSPACE ));
pSet->Put(SfxBoolItem( ATTR_PAGE_HORCENTER, pPage->HorCenter ));
pSet->Put(SfxBoolItem( ATTR_PAGE_VERCENTER, pPage->VerCenter ));
//----------------
// Area-Parameter:
//----------------
{
ScRange* pRepeatRow = NULL;
ScRange* pRepeatCol = NULL;
if ( pPage->ColRepeatStart >= 0 )
pRepeatCol = new ScRange( static_cast<SCCOL> (pPage->ColRepeatStart), 0, 0 );
if ( pPage->RowRepeatStart >= 0 )
pRepeatRow = new ScRange( 0, static_cast<SCROW> (pPage->RowRepeatStart), 0 );
if ( pRepeatRow || pRepeatCol )
{
//
// an allen Tabellen setzen
//
for ( SCTAB nTab = 0, nTabCount = pDoc->GetTableCount(); nTab < nTabCount; ++nTab )
{
pDoc->SetRepeatColRange( nTab, pRepeatCol );
pDoc->SetRepeatRowRange( nTab, pRepeatRow );
}
}
delete pRepeatRow;
delete pRepeatCol;
}
//-----------------
// Table-Parameter:
//-----------------
pSet->Put( SfxBoolItem( ATTR_PAGE_NOTES, pPage->PrintNote ) );
pSet->Put( SfxBoolItem( ATTR_PAGE_GRID, pPage->PrintGrid ) );
pSet->Put( SfxBoolItem( ATTR_PAGE_HEADERS, pPage->PrintColRow ) );
pSet->Put( SfxBoolItem( ATTR_PAGE_TOPDOWN, pPage->TopBottomDir ) );
pSet->Put( ScViewObjectModeItem( ATTR_PAGE_CHARTS, VOBJ_MODE_SHOW ) );
pSet->Put( ScViewObjectModeItem( ATTR_PAGE_OBJECTS, VOBJ_MODE_SHOW ) );
pSet->Put( ScViewObjectModeItem( ATTR_PAGE_DRAWINGS, VOBJ_MODE_SHOW ) );
pSet->Put( SfxUInt16Item( ATTR_PAGE_SCALE,
(sal_uInt16)( lcl_PascalToDouble( pPage->PrnZoom ) * 100 ) ) );
pSet->Put( SfxUInt16Item( ATTR_PAGE_FIRSTPAGENO, 1 ) );
pSet->Put( SvxSizeItem( ATTR_PAGE_SIZE, Size( pPage->Width, pPage->Height ) ) );
}
delete pEmptyObject;
}
ScDataObject* Sc10PageData::Clone() const
{
return new Sc10PageData(aPageFormat);
}
//--------------------------------------------
// Import
//--------------------------------------------
Sc10Import::Sc10Import(SvStream& rStr, ScDocument* pDocument ) :
rStream (rStr),
pDoc (pDocument),
pFontCollection (NULL),
pNameCollection (NULL),
pPatternCollection (NULL),
pDataBaseCollection (NULL),
nError (0),
nShowTab (0)
{
pPrgrsBar = NULL;
}
Sc10Import::~Sc10Import()
{
pDoc->CalcAfterLoad();
pDoc->UpdateAllCharts();
delete pFontCollection;
delete pNameCollection;
delete pPatternCollection;
delete pDataBaseCollection;
DBG_ASSERT( pPrgrsBar == NULL,
"*Sc10Import::Sc10Import(): Progressbar lebt noch!?" );
}
sal_uLong Sc10Import::Import()
{
pPrgrsBar = new ScfStreamProgressBar( rStream, pDoc->GetDocumentShell() );
ScDocOptions aOpt = pDoc->GetDocOptions();
aOpt.SetDate( 1, 1, 1900 );
aOpt.SetYear2000( 18 + 1901 ); // ab SO51 src513e vierstellig
pDoc->SetDocOptions( aOpt );
pDoc->GetFormatTable()->ChangeNullDate( 1, 1, 1900 );
LoadFileHeader(); pPrgrsBar->Progress();
if (!nError) { LoadFileInfo(); pPrgrsBar->Progress(); }
if (!nError) { LoadEditStateInfo(); pPrgrsBar->Progress(); }
if (!nError) { LoadProtect(); pPrgrsBar->Progress(); }
if (!nError) { LoadViewColRowBar(); pPrgrsBar->Progress(); }
if (!nError) { LoadScrZoom(); pPrgrsBar->Progress(); }
if (!nError) { LoadPalette(); pPrgrsBar->Progress(); }
if (!nError) { LoadFontCollection(); pPrgrsBar->Progress(); }
if (!nError) { LoadNameCollection(); pPrgrsBar->Progress(); }
if (!nError) { LoadPatternCollection(); pPrgrsBar->Progress(); }
if (!nError) { LoadDataBaseCollection(); pPrgrsBar->Progress(); }
if (!nError) { LoadTables(); pPrgrsBar->Progress(); }
if (!nError) { LoadObjects(); pPrgrsBar->Progress(); }
if (!nError) { ImportNameCollection(); pPrgrsBar->Progress(); }
pDoc->SetViewOptions( aSc30ViewOpt );
#ifdef DBG_UTIL
if (nError)
{
DBG_ERROR( ByteString::CreateFromInt32( nError ).GetBuffer() );
}
#endif
delete pPrgrsBar;
#ifdef DBG_UTIL
pPrgrsBar = NULL;
#endif
return nError;
}
void Sc10Import::LoadFileHeader()
{
Sc10FileHeader FileHeader;
lcl_ReadFileHeader(rStream, FileHeader);
nError = rStream.GetError();
if ( nError == 0 )
{
sal_Char Sc10CopyRight[32];
strcpy(Sc10CopyRight, "Blaise-Tabelle"); // #100211# - checked
Sc10CopyRight[14] = 10;
Sc10CopyRight[15] = 13;
Sc10CopyRight[16] = 0;
if ((strcmp(FileHeader.CopyRight, Sc10CopyRight) != 0)
|| (FileHeader.Version < 101)
|| (FileHeader.Version > 102))
nError = errUnknownFormat;
}
}
void Sc10Import::LoadFileInfo()
{
Sc10FileInfo FileInfo;
rStream.Read(&FileInfo, sizeof(FileInfo));
nError = rStream.GetError();
// Achtung Info Uebertragen
}
void Sc10Import::LoadEditStateInfo()
{
Sc10EditStateInfo EditStateInfo;
rStream.Read(&EditStateInfo, sizeof(EditStateInfo));
nError = rStream.GetError();
nShowTab = static_cast<SCTAB>(EditStateInfo.DeltaZ);
// Achtung Cursorposition und Offset der Tabelle Uebertragen (soll man das machen??)
}
void Sc10Import::LoadProtect()
{
lcl_ReadSheetProtect(rStream, SheetProtect);
nError = rStream.GetError();
ScDocProtection aProtection;
aProtection.setProtected(static_cast<bool>(SheetProtect.Protect));
aProtection.setPassword(SC10TOSTRING(SheetProtect.PassWord));
pDoc->SetDocProtection(&aProtection);
}
void Sc10Import::LoadViewColRowBar()
{
sal_uInt8 ViewColRowBar;
rStream >> ViewColRowBar;
nError = rStream.GetError();
aSc30ViewOpt.SetOption( VOPT_HEADER, (sal_Bool)ViewColRowBar );
}
void Sc10Import::LoadScrZoom()
{
// Achtung Zoom ist leider eine 6Byte TP real Zahl (keine Ahnung wie die Umzusetzen ist)
sal_Char cZoom[6];
rStream.Read(cZoom, sizeof(cZoom));
nError = rStream.GetError();
}
void Sc10Import::LoadPalette()
{
lcl_ReadPalette(rStream, TextPalette);
lcl_ReadPalette(rStream, BackPalette);
lcl_ReadPalette(rStream, RasterPalette);
lcl_ReadPalette(rStream, FramePalette);
nError = rStream.GetError();
}
void Sc10Import::LoadFontCollection()
{
pFontCollection = new Sc10FontCollection(rStream);
if (!nError)
nError = pFontCollection->GetError();
}
void Sc10Import::LoadNameCollection()
{
pNameCollection = new Sc10NameCollection(rStream);
if (!nError)
nError = pNameCollection->GetError();
}
void Sc10Import::ImportNameCollection()
{
ScRangeName* pRN = pDoc->GetRangeName();
for (sal_uInt16 i = 0; i < pNameCollection->GetCount(); i++)
{
Sc10NameData* pName = pNameCollection->At( i );
pRN->Insert( new ScRangeData( pDoc,
SC10TOSTRING( pName->Name ),
SC10TOSTRING( pName->Reference ) ) );
}
}
void Sc10Import::LoadPatternCollection()
{
pPatternCollection = new Sc10PatternCollection( rStream );
if (!nError)
nError = pPatternCollection->GetError();
if (nError == errOutOfMemory)
return; // hopeless
ScStyleSheetPool* pStylePool = pDoc->GetStyleSheetPool();
for( sal_uInt16 i = 0 ; i < pPatternCollection->GetCount() ; i++ )
{
Sc10PatternData* pPattern = pPatternCollection->At( i );
String aName( pPattern->Name, DEFCHARSET );
SfxStyleSheetBase* pStyle = pStylePool->Find( aName, SFX_STYLE_FAMILY_PARA );
if( pStyle == NULL )
pStylePool->Make( aName, SFX_STYLE_FAMILY_PARA );
else
{
pPattern->Name[ 27 ] = 0;
strcat( pPattern->Name, "_Old" ); // #100211# - checked
aName = SC10TOSTRING( pPattern->Name );
pStylePool->Make( aName, SFX_STYLE_FAMILY_PARA );
}
pStyle = pStylePool->Find( aName, SFX_STYLE_FAMILY_PARA );
if( pStyle != NULL )
{
SfxItemSet &rItemSet = pStyle->GetItemSet();
// Font
if( ( pPattern->FormatFlags & pfFont ) == pfFont )
{
FontFamily eFam = FAMILY_DONTKNOW;
switch( pPattern->LogFont.lfPitchAndFamily & 0xF0 )
{
case ffDontCare : eFam = FAMILY_DONTKNOW; break;
case ffRoman : eFam = FAMILY_ROMAN; break;
case ffSwiss : eFam = FAMILY_SWISS; break;
case ffModern : eFam = FAMILY_MODERN; break;
case ffScript : eFam = FAMILY_SCRIPT; break;
case ffDecorative : eFam = FAMILY_DECORATIVE; break;
default: eFam = FAMILY_DONTKNOW; break;
}
rItemSet.Put( SvxFontItem( eFam, SC10TOSTRING( pPattern->LogFont.lfFaceName ), EMPTY_STRING,
PITCH_DONTKNOW, RTL_TEXTENCODING_DONTKNOW, ATTR_FONT ) );
rItemSet.Put( SvxFontHeightItem( Abs( pPattern->LogFont.lfHeight ), 100, ATTR_FONT_HEIGHT ) );
Color TextColor( COL_BLACK );
lcl_ChangeColor( ( pPattern->nColor & 0x000F ), TextColor );
rItemSet.Put( SvxColorItem( TextColor, ATTR_FONT_COLOR ) );
// FontAttr
if( pPattern->LogFont.lfWeight != fwNormal )
rItemSet.Put( SvxWeightItem( WEIGHT_BOLD, ATTR_FONT_WEIGHT ) );
if( pPattern->LogFont.lfItalic != 0 )
rItemSet.Put( SvxPostureItem( ITALIC_NORMAL, ATTR_FONT_POSTURE ) );
if( pPattern->LogFont.lfUnderline != 0 )
rItemSet.Put( SvxUnderlineItem( UNDERLINE_SINGLE, ATTR_FONT_UNDERLINE ) );
if( pPattern->LogFont.lfStrikeOut != 0 )
rItemSet.Put( SvxCrossedOutItem( STRIKEOUT_SINGLE, ATTR_FONT_CROSSEDOUT ) );
}
// Ausrichtung
if( ( pPattern->FormatFlags & pfJustify ) == pfJustify )
{
sal_uInt16 HorJustify = ( pPattern->Justify & 0x000F );
sal_uInt16 VerJustify = ( pPattern->Justify & 0x00F0 ) >> 4;
sal_uInt16 OJustify = ( pPattern->Justify & 0x0F00 ) >> 8;
sal_uInt16 EJustify = ( pPattern->Justify & 0xF000 ) >> 12;
if( HorJustify != 0 )
switch( HorJustify )
{
case hjLeft:
rItemSet.Put( SvxHorJustifyItem( SVX_HOR_JUSTIFY_LEFT, ATTR_HOR_JUSTIFY ) );
break;
case hjCenter:
rItemSet.Put( SvxHorJustifyItem( SVX_HOR_JUSTIFY_CENTER, ATTR_HOR_JUSTIFY ) );
break;
case hjRight:
rItemSet.Put( SvxHorJustifyItem( SVX_HOR_JUSTIFY_RIGHT, ATTR_HOR_JUSTIFY ) );
break;
}
if( VerJustify != 0 )
switch( VerJustify )
{
case vjTop:
rItemSet.Put( SvxVerJustifyItem( SVX_VER_JUSTIFY_TOP, ATTR_VER_JUSTIFY ) );
break;
case vjCenter:
rItemSet.Put( SvxVerJustifyItem( SVX_VER_JUSTIFY_CENTER, ATTR_VER_JUSTIFY ) );
break;
case vjBottom:
rItemSet.Put( SvxVerJustifyItem( SVX_VER_JUSTIFY_BOTTOM, ATTR_VER_JUSTIFY ) );
break;
}
if( ( OJustify & ojWordBreak ) == ojWordBreak )
rItemSet.Put( SfxBoolItem( sal_True ) );
if( ( OJustify & ojBottomTop ) == ojBottomTop )
rItemSet.Put( SfxInt32Item( ATTR_ROTATE_VALUE, 9000 ) );
else if( ( OJustify & ojTopBottom ) == ojTopBottom )
rItemSet.Put( SfxInt32Item( ATTR_ROTATE_VALUE, 27000 ) );
sal_Int16 Margin = Max( ( sal_uInt16 ) 20, ( sal_uInt16 ) ( EJustify * 20 ) );
if( ( ( OJustify & ojBottomTop ) == ojBottomTop ) )
rItemSet.Put( SvxMarginItem( 20, Margin, 20, Margin, ATTR_MARGIN ) );
else
rItemSet.Put( SvxMarginItem( Margin, 20, Margin, 20, ATTR_MARGIN ) );
}
// Frame
if( ( pPattern->FormatFlags & pfFrame ) == pfFrame )
{
if( pPattern->Frame != 0 )
{
sal_uInt16 nLeft = 0;
sal_uInt16 nTop = 0;
sal_uInt16 nRight = 0;
sal_uInt16 nBottom = 0;
sal_uInt16 fLeft = ( pPattern->Frame & 0x000F );
sal_uInt16 fTop = ( pPattern->Frame & 0x00F0 ) / 0x0010;
sal_uInt16 fRight = ( pPattern->Frame & 0x0F00 ) / 0x0100;
sal_uInt16 fBottom = ( pPattern->Frame & 0xF000 ) / 0x1000;
if( fLeft > 1 )
nLeft = 50;
else if( fLeft > 0 )
nLeft = 20;
if( fTop > 1 )
nTop = 50;
else if( fTop > 0 )
nTop = 20;
if( fRight > 1 )
nRight = 50;
else if( fRight > 0 )
nRight = 20;
if( fBottom > 1 )
nBottom = 50;
else if( fBottom > 0 )
nBottom = 20;
Color ColorLeft( COL_BLACK );
Color ColorTop( COL_BLACK );
Color ColorRight( COL_BLACK );
Color ColorBottom( COL_BLACK );
sal_uInt16 cLeft = ( pPattern->FrameColor & 0x000F );
sal_uInt16 cTop = ( pPattern->FrameColor & 0x00F0 ) >> 4;
sal_uInt16 cRight = ( pPattern->FrameColor & 0x0F00 ) >> 8;
sal_uInt16 cBottom = ( pPattern->FrameColor & 0xF000 ) >> 12;
lcl_ChangeColor( cLeft, ColorLeft );
lcl_ChangeColor( cTop, ColorTop );
lcl_ChangeColor( cRight, ColorRight );
lcl_ChangeColor( cBottom, ColorBottom );
SvxBorderLine aLine;
SvxBoxItem aBox( ATTR_BORDER );
aLine.SetOutWidth( nLeft );
aLine.SetColor( ColorLeft );
aBox.SetLine( &aLine, BOX_LINE_LEFT );
aLine.SetOutWidth( nTop );
aLine.SetColor( ColorTop );
aBox.SetLine( &aLine, BOX_LINE_TOP );
aLine.SetOutWidth( nRight );
aLine.SetColor( ColorRight );
aBox.SetLine( &aLine, BOX_LINE_RIGHT );
aLine.SetOutWidth( nBottom );
aLine.SetColor( ColorBottom );
aBox.SetLine( &aLine, BOX_LINE_BOTTOM );
rItemSet.Put( aBox );
}
}
// Raster
if( ( pPattern->FormatFlags & pfRaster ) == pfRaster )
{
if( pPattern->Raster != 0 )
{
sal_uInt16 nBColor = ( pPattern->nColor & 0x00F0 ) >> 4;
sal_uInt16 nRColor = ( pPattern->nColor & 0x0F00 ) >> 8;
Color aBColor( COL_BLACK );
lcl_ChangeColor( nBColor, aBColor );
if( nBColor == 0 )
aBColor.SetColor( COL_WHITE );
else if( nBColor == 15 )
aBColor.SetColor( COL_BLACK );
Color aRColor( COL_BLACK );
lcl_ChangeColor( nRColor, aRColor );
sal_uInt16 nFact;
sal_Bool bSwapCol = sal_False;
sal_Bool bSetItem = sal_True;
switch (pPattern->Raster)
{
case raNone: nFact = 0xffff; bSwapCol = sal_True; bSetItem = (nBColor > 0); break;
case raGray12: nFact = (0xffff / 100) * 12; break;
case raGray25: nFact = (0xffff / 100) * 25; break;
case raGray50: nFact = (0xffff / 100) * 50; break;
case raGray75: nFact = (0xffff / 100) * 75; break;
default: nFact = 0xffff; bSetItem = (nRColor < 15);
}
if ( bSetItem )
{
if( bSwapCol )
rItemSet.Put( SvxBrushItem( GetMixedColor( aBColor, aRColor, nFact ), ATTR_BACKGROUND ) );
else
rItemSet.Put( SvxBrushItem( GetMixedColor( aRColor, aBColor, nFact ), ATTR_BACKGROUND ) );
}
}
}
// ZahlenFormate
if( ( pPattern->ValueFormat.Format != 0 ) &&
( ( pPattern->FormatFlags & pfValue ) == pfValue ) )
{
sal_uLong nKey = 0;
ChangeFormat( pPattern->ValueFormat.Format, pPattern->ValueFormat.Info, nKey );
rItemSet.Put( SfxUInt32Item( ATTR_VALUE_FORMAT, ( sal_uInt32 ) nKey ) );
}
// Zellattribute (Schutz, Versteckt...)
if( ( pPattern->Flags != 0 ) &&
( ( pPattern->FormatFlags & pfProtection ) == pfProtection ) )
{
sal_Bool bProtect = ( ( pPattern->Flags & paProtect ) == paProtect );
sal_Bool bHFormula = ( ( pPattern->Flags & paHideFormula ) == paHideFormula );
sal_Bool bHCell = ( ( pPattern->Flags & paHideAll ) == paHideAll );
sal_Bool bHPrint = ( ( pPattern->Flags & paHidePrint ) == paHidePrint );
rItemSet.Put( ScProtectionAttr( bProtect, bHFormula, bHCell, bHPrint ) );
}
} // if Style != 0
} // for (i = 0; i < GetCount()
}
void Sc10Import::LoadDataBaseCollection()
{
pDataBaseCollection = new Sc10DataBaseCollection(rStream);
if (!nError)
nError = pDataBaseCollection->GetError();
if (nError == errOutOfMemory)
return; // hopeless
for( sal_uInt16 i = 0 ; i < pDataBaseCollection->GetCount() ; i++ )
{
Sc10DataBaseData* pOldData = pDataBaseCollection->At(i);
ScDBData* pNewData = new ScDBData( SC10TOSTRING( pOldData->DataBaseRec.Name ),
( SCTAB ) pOldData->DataBaseRec.Tab,
( SCCOL ) pOldData->DataBaseRec.Block.x1,
( SCROW ) pOldData->DataBaseRec.Block.y1,
( SCCOL ) pOldData->DataBaseRec.Block.x2,
( SCROW ) pOldData->DataBaseRec.Block.y2,
sal_True,
( sal_Bool) pOldData->DataBaseRec.RowHeader );
pDoc->GetDBCollection()->Insert( pNewData );
}
}
void Sc10Import::LoadTables()
{
Sc10PageCollection aPageCollection;
sal_Int16 nTabCount;
rStream >> nTabCount;
for (sal_Int16 Tab = 0; (Tab < nTabCount) && (nError == 0); Tab++)
{
Sc10PageFormat PageFormat;
sal_Int16 DataBaseIndex;
Sc10TableProtect TabProtect;
sal_Int16 TabNo;
sal_Char TabName[128];
sal_uInt16 Display;
sal_uInt8 Visible;
sal_uInt16 ID;
sal_uInt16 DataCount;
sal_uInt16 DataStart;
sal_uInt16 DataEnd;
sal_uInt16 DataValue;
sal_uInt16 Count;
sal_uInt16 i;
String aStr; // Universal-Konvertierungs-String
lcl_ReadPageFormat(rStream, PageFormat);
sal_uInt16 nAt = aPageCollection.InsertFormat(PageFormat);
String aPageName = lcl_MakeOldPageStyleFormatName( nAt );
pPrgrsBar->Progress();
rStream >> DataBaseIndex;
lcl_ReadTabProtect(rStream, TabProtect);
ScTableProtection aProtection;
aProtection.setProtected(static_cast<bool>(TabProtect.Protect));
aProtection.setPassword(SC10TOSTRING(TabProtect.PassWord));
pDoc->SetTabProtection(static_cast<SCTAB>(Tab), &aProtection);
rStream >> TabNo;
sal_uInt8 nLen;
rStream >> nLen;
rStream.Read(TabName, sizeof(TabName) - 1);
if (nLen >= sizeof(TabName))
nLen = sizeof(TabName) - 1;
TabName[nLen] = 0;
//----------------------------------------------------------
rStream >> Display;
if ( Tab == (sal_Int16)nShowTab )
{
ScVObjMode eObjMode = VOBJ_MODE_SHOW;
aSc30ViewOpt.SetOption( VOPT_FORMULAS, IS_SET(dfFormula,Display) );
aSc30ViewOpt.SetOption( VOPT_NULLVALS, IS_SET(dfZerro,Display) );
aSc30ViewOpt.SetOption( VOPT_SYNTAX, IS_SET(dfSyntax,Display) );
aSc30ViewOpt.SetOption( VOPT_NOTES, IS_SET(dfNoteMark,Display) );
aSc30ViewOpt.SetOption( VOPT_VSCROLL, sal_True );
aSc30ViewOpt.SetOption( VOPT_HSCROLL, sal_True );
aSc30ViewOpt.SetOption( VOPT_TABCONTROLS, sal_True );
aSc30ViewOpt.SetOption( VOPT_OUTLINER, sal_True );
aSc30ViewOpt.SetOption( VOPT_GRID, IS_SET(dfGrid,Display) );
// VOPT_HEADER wird in LoadViewColRowBar() gesetzt
if ( IS_SET(dfObjectAll,Display) ) // Objekte anzeigen
eObjMode = VOBJ_MODE_SHOW;
else if ( IS_SET(dfObjectFrame,Display) ) // Objekte als Platzhalter
eObjMode = VOBJ_MODE_SHOW;
else if ( IS_SET(dfObjectNone,Display) ) // Objekte nicht anzeigen
eObjMode = VOBJ_MODE_HIDE;
aSc30ViewOpt.SetObjMode( VOBJ_TYPE_OLE, eObjMode );
aSc30ViewOpt.SetObjMode( VOBJ_TYPE_CHART, eObjMode );
aSc30ViewOpt.SetObjMode( VOBJ_TYPE_DRAW, eObjMode );
}
/* wofuer wird das benoetigt? Da in SC 1.0 die Anzeigeflags pro Tabelle gelten und nicht pro View
Dieses Flag in die ViewOptions eintragen bei Gelegenheit, Sollte der Stephan Olk machen
sal_uInt16 nDisplayMask = 0xFFFF;
sal_uInt16 nDisplayValue = 0;
if (Tab == 0)
nDisplayValue = Display;
else
{
sal_uInt16 nDiff = Display ^ nDisplayValue;
nDisplayMask &= ~nDiff;
}
*/
//--------------------------------------------------------------------
rStream >> Visible;
nError = rStream.GetError();
if (nError != 0) return;
if (TabNo == 0)
pDoc->RenameTab(static_cast<SCTAB> (TabNo), SC10TOSTRING( TabName ), sal_False);
else
pDoc->InsertTab(SC_TAB_APPEND, SC10TOSTRING( TabName ) );
pDoc->SetPageStyle( static_cast<SCTAB>(Tab), aPageName );
if (Visible == 0) pDoc->SetVisible(static_cast<SCTAB> (TabNo), sal_False);
// ColWidth
rStream >> ID;
if (ID != ColWidthID)
{
DBG_ERROR( "ColWidthID" );
nError = errUnknownID;
return;
}
rStream >> DataCount;
DataStart = 0;
for (i=0; i < DataCount; i++)
{
rStream >> DataEnd;
rStream >> DataValue;
for (SCCOL j = static_cast<SCCOL>(DataStart); j <= static_cast<SCCOL>(DataEnd); j++) pDoc->SetColWidth(j, static_cast<SCTAB> (TabNo), DataValue);
DataStart = DataEnd + 1;
}
pPrgrsBar->Progress();
// ColAttr
rStream >> ID;
if (ID != ColAttrID)
{
DBG_ERROR( "ColAttrID" );
nError = errUnknownID;
return;
}
rStream >> DataCount;
DataStart = 0;
for (i=0; i < DataCount; i++)
{
rStream >> DataEnd;
rStream >> DataValue;
if (DataValue != 0)
{
bool bPageBreak = ((DataValue & crfSoftBreak) == crfSoftBreak);
bool bManualBreak = ((DataValue & crfHardBreak) == crfHardBreak);
bool bHidden = ((DataValue & crfHidden) == crfHidden);
for (SCCOL k = static_cast<SCCOL>(DataStart); k <= static_cast<SCCOL>(DataEnd); k++)
{
pDoc->SetColHidden(k, k, static_cast<SCTAB>(TabNo), bHidden);
pDoc->SetColBreak(k, static_cast<SCTAB> (TabNo), bPageBreak, bManualBreak);
}
}
DataStart = DataEnd + 1;
}
pPrgrsBar->Progress();
// RowHeight
rStream >> ID;
if (ID != RowHeightID)
{
DBG_ERROR( "RowHeightID" );
nError = errUnknownID;
return;
}
rStream >> DataCount;
DataStart = 0;
for (i=0; i < DataCount; i++)
{
rStream >> DataEnd;
rStream >> DataValue;
pDoc->SetRowHeightRange(static_cast<SCROW> (DataStart), static_cast<SCROW> (DataEnd), static_cast<SCTAB> (TabNo), DataValue);
DataStart = DataEnd + 1;
}
pPrgrsBar->Progress();
// RowAttr
rStream >> ID;
if (ID != RowAttrID)
{
DBG_ERROR( "RowAttrID" );
nError = errUnknownID;
return;
}
rStream >> DataCount;
DataStart = 0;
for (i=0; i < DataCount; i++)
{
rStream >> DataEnd;
rStream >> DataValue;
if (DataValue != 0)
{
bool bPageBreak = ((DataValue & crfSoftBreak) == crfSoftBreak);
bool bManualBreak = ((DataValue & crfHardBreak) == crfHardBreak);
bool bHidden = ((DataValue & crfHidden) == crfHidden);
for (SCROW l = static_cast<SCROW>(DataStart); l <= static_cast<SCROW>(DataEnd); l++)
{
pDoc->SetRowHidden(l, l, static_cast<SCTAB> (TabNo), bHidden);
pDoc->SetRowBreak(l, static_cast<SCTAB> (TabNo), bPageBreak, bManualBreak);
}
}
DataStart = DataEnd + 1;
}
pPrgrsBar->Progress();
// DataTable
rStream >> ID;
if (ID != TableID)
{
DBG_ERROR( "TableID" );
nError = errUnknownID;
return;
}
for (SCCOL Col = 0; (Col <= SC10MAXCOL) && (nError == 0); Col++)
{
rStream >> Count;
nError = rStream.GetError();
if ((Count != 0) && (nError == 0))
LoadCol(Col, static_cast<SCTAB> (TabNo));
}
DBG_ASSERT( nError == 0, "Stream" );
}
pPrgrsBar->Progress();
aPageCollection.PutToDoc( pDoc );
}
void Sc10Import::LoadCol(SCCOL Col, SCTAB Tab)
{
LoadColAttr(Col, Tab);
sal_uInt16 CellCount;
sal_uInt8 CellType;
sal_uInt16 Row;
rStream >> CellCount;
SCROW nScCount = static_cast< SCROW >( CellCount );
if (nScCount > MAXROW) nError = errUnknownFormat;
for (sal_uInt16 i = 0; (i < CellCount) && (nError == 0); i++)
{
rStream >> CellType;
rStream >> Row;
nError = rStream.GetError();
if (nError == 0)
{
switch (CellType)
{
case ctValue :
{
const SfxPoolItem* pValueFormat = pDoc->GetAttr(Col, static_cast<SCROW> (Row), Tab, ATTR_VALUE_FORMAT);
sal_uLong nFormat = ((SfxUInt32Item*)pValueFormat)->GetValue();
double Value = ScfTools::ReadLongDouble(rStream);
// Achtung hier ist eine Anpassung Notwendig wenn Ihr das Basisdatum aendert
// In StarCalc 1.0 entspricht 0 dem 01.01.1900
// if ((nFormat >= 30) && (nFormat <= 35))
// Value += 0;
if ((nFormat >= 40) && (nFormat <= 45))
Value /= 86400.0;
pDoc->SetValue(Col, static_cast<SCROW> (Row), Tab, Value);
break;
}
case ctString :
{
sal_uInt8 Len;
sal_Char s[256];
rStream >> Len;
rStream.Read(s, Len);
s[Len] = 0;
pDoc->SetString( Col, static_cast<SCROW> (Row), Tab, SC10TOSTRING( s ) );
break;
}
case ctFormula :
{
/*double Value =*/ ScfTools::ReadLongDouble(rStream);
sal_uInt8 Len;
sal_Char s[256+1];
rStream >> Len;
rStream.Read(&s[1], Len);
s[0] = '=';
s[Len + 1] = 0;
ScFormulaCell* pCell = new ScFormulaCell( pDoc, ScAddress( Col, static_cast<SCROW> (Row), Tab ) );
pCell->SetHybridFormula( SC10TOSTRING( s ),formula::FormulaGrammar::GRAM_NATIVE );
pDoc->PutCell( Col, static_cast<SCROW> (Row), Tab, pCell, (sal_Bool)sal_True );
break;
}
case ctNote :
break;
default :
nError = errUnknownFormat;
break;
}
sal_uInt16 NoteLen;
rStream >> NoteLen;
if (NoteLen != 0)
{
sal_Char* pNote = new sal_Char[NoteLen+1];
rStream.Read(pNote, NoteLen);
pNote[NoteLen] = 0;
String aNoteText( SC10TOSTRING(pNote));
delete [] pNote;
ScAddress aPos( Col, static_cast<SCROW>(Row), Tab );
ScNoteUtil::CreateNoteFromString( *pDoc, aPos, aNoteText, false, false );
}
}
pPrgrsBar->Progress();
}
}
void Sc10Import::LoadColAttr(SCCOL Col, SCTAB Tab)
{
Sc10ColAttr aFont;
Sc10ColAttr aAttr;
Sc10ColAttr aJustify;
Sc10ColAttr aFrame;
Sc10ColAttr aRaster;
Sc10ColAttr aValue;
Sc10ColAttr aColor;
Sc10ColAttr aFrameColor;
Sc10ColAttr aFlag;
Sc10ColAttr aPattern;
if (nError == 0) LoadAttr(aFont);
if (nError == 0) LoadAttr(aAttr);
if (nError == 0) LoadAttr(aJustify);
if (nError == 0) LoadAttr(aFrame);
if (nError == 0) LoadAttr(aRaster);
if (nError == 0) LoadAttr(aValue);
if (nError == 0) LoadAttr(aColor);
if (nError == 0) LoadAttr(aFrameColor);
if (nError == 0) LoadAttr(aFlag);
if (nError == 0) LoadAttr(aPattern);
if (nError == 0)
{
SCROW nStart;
SCROW nEnd;
sal_uInt16 i;
sal_uInt16 nLimit;
sal_uInt16 nValue1;
Sc10ColData *pColData;
// Font (Name, Groesse)
nStart = 0;
nEnd = 0;
nLimit = aFont.Count;
pColData = aFont.pData;
for( i = 0 ; i < nLimit ; i++, pColData++ )
{
nEnd = static_cast<SCROW>(pColData->Row);
if ((nStart <= nEnd) && (pColData->Value))
{
FontFamily eFam = FAMILY_DONTKNOW;
Sc10FontData* pFont = pFontCollection->At(pColData->Value);
if (pFont)
{
switch (pFont->PitchAndFamily & 0xF0)
{
case ffDontCare : eFam = FAMILY_DONTKNOW; break;
case ffRoman : eFam = FAMILY_ROMAN; break;
case ffSwiss : eFam = FAMILY_SWISS; break;
case ffModern : eFam = FAMILY_MODERN; break;
case ffScript : eFam = FAMILY_SCRIPT; break;
case ffDecorative : eFam = FAMILY_DECORATIVE; break;
default: eFam = FAMILY_DONTKNOW; break;
}
ScPatternAttr aScPattern(pDoc->GetPool());
aScPattern.GetItemSet().Put(SvxFontItem(eFam, SC10TOSTRING( pFont->FaceName ), EMPTY_STRING,
PITCH_DONTKNOW, RTL_TEXTENCODING_DONTKNOW, ATTR_FONT ));
aScPattern.GetItemSet().Put(SvxFontHeightItem(Abs(pFont->Height), 100, ATTR_FONT_HEIGHT ));
pDoc->ApplyPatternAreaTab(Col, nStart, Col, nEnd, Tab, aScPattern);
}
}
nStart = nEnd + 1;
}
// Fontfarbe
nStart = 0;
nEnd = 0;
nLimit = aColor.Count;
pColData = aColor.pData;
for( i = 0 ; i < nLimit ; i++, pColData++ )
{
nEnd = static_cast<SCROW>(pColData->Row);
if ((nStart <= nEnd) && (pColData->Value))
{
Color TextColor(COL_BLACK);
lcl_ChangeColor((pColData->Value & 0x000F), TextColor);
ScPatternAttr aScPattern(pDoc->GetPool());
aScPattern.GetItemSet().Put(SvxColorItem(TextColor, ATTR_FONT_COLOR ));
pDoc->ApplyPatternAreaTab(Col, nStart, Col, nEnd, Tab, aScPattern);
}
nStart = nEnd + 1;
}
// Fontattribute (Fett, Kursiv...)
nStart = 0;
nEnd = 0;
nLimit = aAttr.Count;
pColData = aAttr.pData;
for( i = 0 ; i < nLimit ; i++, pColData++ )
{
nEnd = static_cast<SCROW>(pColData->Row);
nValue1 = pColData->Value;
if ((nStart <= nEnd) && (nValue1))
{
ScPatternAttr aScPattern(pDoc->GetPool());
if ((nValue1 & atBold) == atBold)
aScPattern.GetItemSet().Put(SvxWeightItem(WEIGHT_BOLD, ATTR_FONT_WEIGHT));
if ((nValue1 & atItalic) == atItalic)
aScPattern.GetItemSet().Put(SvxPostureItem(ITALIC_NORMAL, ATTR_FONT_POSTURE));
if ((nValue1 & atUnderline) == atUnderline)
aScPattern.GetItemSet().Put(SvxUnderlineItem(UNDERLINE_SINGLE, ATTR_FONT_UNDERLINE));
if ((nValue1 & atStrikeOut) == atStrikeOut)
aScPattern.GetItemSet().Put(SvxCrossedOutItem(STRIKEOUT_SINGLE, ATTR_FONT_CROSSEDOUT));
pDoc->ApplyPatternAreaTab(Col, nStart, Col, nEnd, Tab, aScPattern);
}
nStart = nEnd + 1;
}
// Zellausrichtung
nStart = 0;
nEnd = 0;
nLimit = aJustify.Count;
pColData = aJustify.pData;
for( i = 0 ; i < nLimit ; i++, pColData++ )
{
nEnd = static_cast<SCROW>(pColData->Row);
nValue1 = pColData->Value;
if ((nStart <= nEnd) && (nValue1))
{
ScPatternAttr aScPattern(pDoc->GetPool());
sal_uInt16 HorJustify = (nValue1 & 0x000F);
sal_uInt16 VerJustify = (nValue1 & 0x00F0) >> 4;
sal_uInt16 OJustify = (nValue1 & 0x0F00) >> 8;
sal_uInt16 EJustify = (nValue1 & 0xF000) >> 12;
switch (HorJustify)
{
case hjLeft:
aScPattern.GetItemSet().Put(SvxHorJustifyItem(SVX_HOR_JUSTIFY_LEFT, ATTR_HOR_JUSTIFY));
break;
case hjCenter:
aScPattern.GetItemSet().Put(SvxHorJustifyItem(SVX_HOR_JUSTIFY_CENTER, ATTR_HOR_JUSTIFY));
break;
case hjRight:
aScPattern.GetItemSet().Put(SvxHorJustifyItem(SVX_HOR_JUSTIFY_RIGHT, ATTR_HOR_JUSTIFY));
break;
}
switch (VerJustify)
{
case vjTop:
aScPattern.GetItemSet().Put(SvxVerJustifyItem(SVX_VER_JUSTIFY_TOP, ATTR_VER_JUSTIFY));
break;
case vjCenter:
aScPattern.GetItemSet().Put(SvxVerJustifyItem(SVX_VER_JUSTIFY_CENTER, ATTR_VER_JUSTIFY));
break;
case vjBottom:
aScPattern.GetItemSet().Put(SvxVerJustifyItem(SVX_VER_JUSTIFY_BOTTOM, ATTR_VER_JUSTIFY));
break;
}
if (OJustify & ojWordBreak)
aScPattern.GetItemSet().Put(SfxBoolItem(sal_True));
if (OJustify & ojBottomTop)
aScPattern.GetItemSet().Put(SfxInt32Item(ATTR_ROTATE_VALUE,9000));
else if (OJustify & ojTopBottom)
aScPattern.GetItemSet().Put(SfxInt32Item(ATTR_ROTATE_VALUE,27000));
sal_Int16 Margin = Max((sal_uInt16)20, (sal_uInt16)(EJustify * 20));
if (((OJustify & ojBottomTop) == ojBottomTop) || ((OJustify & ojBottomTop) == ojBottomTop))
aScPattern.GetItemSet().Put(SvxMarginItem(20, Margin, 20, Margin, ATTR_MARGIN));
else
aScPattern.GetItemSet().Put(SvxMarginItem(Margin, 20, Margin, 20, ATTR_MARGIN));
pDoc->ApplyPatternAreaTab(Col, nStart, Col, nEnd, Tab, aScPattern);
}
nStart = nEnd + 1;
}
// Umrandung
sal_Bool bEnd = sal_False;
sal_uInt16 nColorIndex = 0;
sal_uInt16 nFrameIndex = 0;
// Special Fix...
const sal_uInt32 nHelpMeStart = 100;
sal_uInt32 nHelpMe = nHelpMeStart;
sal_uInt16 nColorIndexOld = nColorIndex;
sal_uInt16 nFrameIndexOld = nColorIndex;
nEnd = 0;
nStart = 0;
while( !bEnd && nHelpMe )
{
pColData = &aFrame.pData[ nFrameIndex ];
sal_uInt16 nValue = pColData->Value;
sal_uInt16 nLeft = 0;
sal_uInt16 nTop = 0;
sal_uInt16 nRight = 0;
sal_uInt16 nBottom = 0;
sal_uInt16 fLeft = ( nValue & 0x000F );
sal_uInt16 fTop = ( nValue & 0x00F0 ) >> 4;
sal_uInt16 fRight = ( nValue & 0x0F00 ) >> 8;
sal_uInt16 fBottom = ( nValue & 0xF000 ) >> 12;
if( fLeft > 1 )
nLeft = 50;
else if( fLeft > 0 )
nLeft = 20;
if( fTop > 1 )
nTop = 50;
else if( fTop > 0 )
nTop = 20;
if( fRight > 1 )
nRight = 50;
else if( fRight > 0 )
nRight = 20;
if( fBottom > 1 )
nBottom = 50;
else if( fBottom > 0 )
nBottom = 20;
Color ColorLeft( COL_BLACK );
Color ColorTop( COL_BLACK );
Color ColorRight( COL_BLACK );
Color ColorBottom( COL_BLACK );
sal_uInt16 nFrmColVal = aFrameColor.pData[ nColorIndex ].Value;
SCROW nFrmColRow = static_cast<SCROW>(aFrameColor.pData[ nColorIndex ].Row);
sal_uInt16 cLeft = ( nFrmColVal & 0x000F );
sal_uInt16 cTop = ( nFrmColVal & 0x00F0 ) >> 4;
sal_uInt16 cRight = ( nFrmColVal & 0x0F00 ) >> 8;
sal_uInt16 cBottom = ( nFrmColVal & 0xF000 ) >> 12;
lcl_ChangeColor( cLeft, ColorLeft );
lcl_ChangeColor( cTop, ColorTop );
lcl_ChangeColor( cRight, ColorRight );
lcl_ChangeColor( cBottom, ColorBottom );
if( static_cast<SCROW>(pColData->Row) < nFrmColRow )
{
nEnd = static_cast<SCROW>(pColData->Row);
if( nFrameIndex < ( aFrame.Count - 1 ) )
nFrameIndex++;
}
else if( static_cast<SCROW>(pColData->Row) > nFrmColRow )
{
nEnd = static_cast<SCROW>(aFrameColor.pData[ nColorIndex ].Row);
if( nColorIndex < ( aFrameColor.Count - 1 ) )
nColorIndex++;
}
else
{
nEnd = nFrmColRow;
if( nFrameIndex < (aFrame.Count - 1 ) )
nFrameIndex++;
if( nColorIndex < ( aFrameColor.Count - 1 ) )
nColorIndex++;
}
if( ( nStart <= nEnd ) && ( nValue != 0 ) )
{
ScPatternAttr aScPattern(pDoc->GetPool());
SvxBorderLine aLine;
SvxBoxItem aBox( ATTR_BORDER );
aLine.SetOutWidth( nLeft );
aLine.SetColor( ColorLeft );
aBox.SetLine( &aLine, BOX_LINE_LEFT );
aLine.SetOutWidth( nTop );
aLine.SetColor( ColorTop );
aBox.SetLine( &aLine, BOX_LINE_TOP );
aLine.SetOutWidth( nRight );
aLine.SetColor( ColorRight );
aBox.SetLine( &aLine, BOX_LINE_RIGHT );
aLine.SetOutWidth( nBottom );
aLine.SetColor( ColorBottom );
aBox.SetLine( &aLine, BOX_LINE_BOTTOM );
aScPattern.GetItemSet().Put( aBox );
pDoc->ApplyPatternAreaTab( Col, nStart, Col, nEnd, Tab, aScPattern );
}
nStart = nEnd + 1;
bEnd = ( nFrameIndex == ( aFrame.Count - 1 ) ) && ( nColorIndex == ( aFrameColor.Count - 1 ) );
if( nColorIndexOld != nColorIndex || nFrameIndexOld != nFrameIndex )
{
nColorIndexOld = nColorIndex;
nFrameIndexOld = nFrameIndex;
nHelpMe = nHelpMeStart;
}
else
nHelpMe--;
pColData++;
}
// ACHTUNG: Code bis hier ueberarbeitet ... jetzt hab' ich keinen Bock mehr! (GT)
// Hintergrund (Farbe, Raster)
sal_uInt16 nRasterIndex = 0;
bEnd = sal_False;
nColorIndex = 0;
nEnd = 0;
nStart = 0;
// Special Fix...
nHelpMe = nHelpMeStart;
sal_uInt16 nRasterIndexOld = nRasterIndex;
while( !bEnd && nHelpMe )
{
sal_uInt16 nBColor = ( aColor.pData[ nColorIndex ].Value & 0x00F0 ) >> 4;
sal_uInt16 nRColor = ( aColor.pData[ nColorIndex ].Value & 0x0F00 ) >> 8;
Color aBColor( COL_BLACK );
lcl_ChangeColor( nBColor, aBColor );
if( nBColor == 0 )
aBColor.SetColor( COL_WHITE );
else if( nBColor == 15 )
aBColor.SetColor( COL_BLACK );
Color aRColor( COL_BLACK );
lcl_ChangeColor( nRColor, aRColor );
ScPatternAttr aScPattern( pDoc->GetPool() );
sal_uInt16 nFact;
sal_Bool bSwapCol = sal_False;
sal_Bool bSetItem = sal_True;
switch ( aRaster.pData[ nRasterIndex ].Value )
{
case raNone: nFact = 0xffff; bSwapCol = sal_True; bSetItem = (nBColor > 0); break;
case raGray12: nFact = (0xffff / 100) * 12; break;
case raGray25: nFact = (0xffff / 100) * 25; break;
case raGray50: nFact = (0xffff / 100) * 50; break;
case raGray75: nFact = (0xffff / 100) * 75; break;
default: nFact = 0xffff; bSetItem = (nRColor < 15);
}
if ( bSetItem )
{
if( bSwapCol )
aScPattern.GetItemSet().Put( SvxBrushItem( GetMixedColor( aBColor, aRColor, nFact ), ATTR_BACKGROUND ) );
else
aScPattern.GetItemSet().Put( SvxBrushItem( GetMixedColor( aRColor, aBColor, nFact ), ATTR_BACKGROUND ) );
}
if( aRaster.pData[ nRasterIndex ].Row < aColor.pData[ nColorIndex ].Row )
{
nEnd = static_cast<SCROW>(aRaster.pData[ nRasterIndex ].Row);
if( nRasterIndex < ( aRaster.Count - 1 ) )
nRasterIndex++;
}
else if( aRaster.pData[ nRasterIndex ].Row > aColor.pData[ nColorIndex ].Row )
{
nEnd = static_cast<SCROW>(aColor.pData[ nColorIndex ].Row);
if( nColorIndex < ( aColor.Count - 1 ) )
nColorIndex++;
}
else
{
nEnd = static_cast<SCROW>(aColor.pData[ nColorIndex ].Row);
if( nRasterIndex < ( aRaster.Count - 1 ) )
nRasterIndex++;
if( nColorIndex < ( aColor.Count - 1 ) )
nColorIndex++;
}
if( nStart <= nEnd )
pDoc->ApplyPatternAreaTab( Col, nStart, Col, nEnd, Tab, aScPattern );
nStart = nEnd + 1;
bEnd = ( nRasterIndex == ( aRaster.Count - 1 ) ) && ( nColorIndex == ( aColor.Count - 1 ) );
if( nColorIndexOld != nColorIndex || nRasterIndexOld != nRasterIndex )
{
nColorIndexOld = nColorIndex;
nRasterIndexOld = nRasterIndex;
nHelpMe = nHelpMeStart;
}
else
nHelpMe--;
nHelpMe--;
}
// Zahlenformate
nStart = 0;
nEnd = 0;
nLimit = aValue.Count;
pColData = aValue.pData;
for (i=0; i<nLimit; i++, pColData++)
{
nEnd = static_cast<SCROW>(pColData->Row);
nValue1 = pColData->Value;
if ((nStart <= nEnd) && (nValue1))
{
sal_uLong nKey = 0;
sal_uInt16 nFormat = (nValue1 & 0x00FF);
sal_uInt16 nInfo = (nValue1 & 0xFF00) >> 8;
ChangeFormat(nFormat, nInfo, nKey);
ScPatternAttr aScPattern(pDoc->GetPool());
aScPattern.GetItemSet().Put(SfxUInt32Item(ATTR_VALUE_FORMAT, (sal_uInt32)nKey));
pDoc->ApplyPatternAreaTab(Col, nStart, Col, nEnd, Tab, aScPattern);
}
nStart = nEnd + 1;
}
// Zellattribute (Schutz, Versteckt...)
nStart = 0;
nEnd = 0;
for (i=0; i<aFlag.Count; i++)
{
nEnd = static_cast<SCROW>(aFlag.pData[i].Row);
if ((nStart <= nEnd) && (aFlag.pData[i].Value != 0))
{
sal_Bool bProtect = ((aFlag.pData[i].Value & paProtect) == paProtect);
sal_Bool bHFormula = ((aFlag.pData[i].Value & paHideFormula) == paHideFormula);
sal_Bool bHCell = ((aFlag.pData[i].Value & paHideAll) == paHideAll);
sal_Bool bHPrint = ((aFlag.pData[i].Value & paHidePrint) == paHidePrint);
ScPatternAttr aScPattern(pDoc->GetPool());
aScPattern.GetItemSet().Put(ScProtectionAttr(bProtect, bHFormula, bHCell, bHPrint));
pDoc->ApplyPatternAreaTab(Col, nStart, Col, nEnd, Tab, aScPattern);
}
nStart = nEnd + 1;
}
// ZellVorlagen
nStart = 0;
nEnd = 0;
ScStyleSheetPool* pStylePool = pDoc->GetStyleSheetPool();
for (i=0; i<aPattern.Count; i++)
{
nEnd = static_cast<SCROW>(aPattern.pData[i].Row);
if ((nStart <= nEnd) && (aPattern.pData[i].Value != 0))
{
sal_uInt16 nPatternIndex = (aPattern.pData[i].Value & 0x00FF) - 1;
Sc10PatternData* pPattern = pPatternCollection->At(nPatternIndex);
if (pPattern != NULL)
{
ScStyleSheet* pStyle = (ScStyleSheet*) pStylePool->Find(
SC10TOSTRING( pPattern->Name ), SFX_STYLE_FAMILY_PARA);
if (pStyle != NULL)
pDoc->ApplyStyleAreaTab(Col, nStart, Col, nEnd, Tab, *pStyle);
}
}
nStart = nEnd + 1;
}
}
}
void Sc10Import::LoadAttr(Sc10ColAttr& rAttr)
{
// rAttr is not reused, otherwise we'd have to delete [] rAttr.pData;
rStream >> rAttr.Count;
if (rAttr.Count)
{
rAttr.pData = new (::std::nothrow) Sc10ColData[rAttr.Count];
if (rAttr.pData != NULL)
{
for (sal_uInt16 i = 0; i < rAttr.Count; i++)
{
rStream >> rAttr.pData[i].Row;
rStream >> rAttr.pData[i].Value;
}
nError = rStream.GetError();
}
else
{
nError = errOutOfMemory;
rAttr.Count = 0;
}
}
}
void Sc10Import::ChangeFormat(sal_uInt16 nFormat, sal_uInt16 nInfo, sal_uLong& nKey)
{
// Achtung: Die Formate werden nur auf die StarCalc 3.0 internen Formate gemappt
// Korrekterweise muessten zum Teil neue Formate erzeugt werden (sollte Stephan sich ansehen)
nKey = 0;
switch (nFormat)
{
case vfStandard :
if (nInfo > 0)
nKey = 2;
break;
case vfMoney :
if (nInfo > 0)
nKey = 21;
else
nKey = 20;
break;
case vfThousend :
if (nInfo > 0)
nKey = 4;
else
nKey = 5;
break;
case vfPercent :
if (nInfo > 0)
nKey = 11;
else
nKey = 10;
break;
case vfExponent :
nKey = 60;
break;
case vfZerro :
// Achtung kein Aequivalent
break;
case vfDate :
switch (nInfo)
{
case df_NDMY_Long :
nKey = 31;
break;
case df_DMY_Long :
nKey = 30;
break;
case df_MY_Long :
nKey = 32;
break;
case df_NDM_Long :
nKey = 31;
break;
case df_DM_Long :
nKey = 33;
break;
case df_M_Long :
nKey = 34;
break;
case df_NDMY_Short :
nKey = 31;
break;
case df_DMY_Short :
nKey = 30;
break;
case df_MY_Short :
nKey = 32;
break;
case df_NDM_Short :
nKey = 31;
break;
case df_DM_Short :
nKey = 33;
break;
case df_M_Short :
nKey = 34;
break;
case df_Q_Long :
nKey = 35;
break;
case df_Q_Short :
nKey = 35;
break;
default :
nKey = 30;
break;
}
break;
case vfTime :
switch (nInfo)
{
case tf_HMS_Long :
nKey = 41;
break;
case tf_HM_Long :
nKey = 40;
break;
case tf_HMS_Short :
nKey = 43;
break;
case tf_HM_Short :
nKey = 42;
break;
default :
nKey = 41;
break;
}
break;
case vfBoolean :
nKey = 99;
break;
case vfStandardRed :
if (nInfo > 0)
nKey = 2;
break;
case vfMoneyRed :
if (nInfo > 0)
nKey = 23;
else
nKey = 22;
break;
case vfThousendRed :
if (nInfo > 0)
nKey = 4;
else
nKey = 5;
break;
case vfPercentRed :
if (nInfo > 0)
nKey = 11;
else
nKey = 10;
break;
case vfExponentRed :
nKey = 60;
break;
case vfFormula :
break;
case vfString :
break;
default :
break;
}
}
void Sc10Import::LoadObjects()
{
sal_uInt16 ID;
rStream >> ID;
if (rStream.IsEof()) return;
if (ID == ObjectID)
{
#ifdef SC10_SHOW_OBJECTS
// Achtung nur zu Debugzwecken
//-----------------------------------
pDoc->InsertTab(SC_TAB_APPEND, "GraphObjects");
SCCOL nCol = 0;
SCROW nRow = 0;
SCTAB nTab = 0;
pDoc->GetTable("GraphObjects", nTab);
pDoc->SetString(nCol++, nRow, nTab, "ObjectTyp");
pDoc->SetString(nCol++, nRow, nTab, "Col");
pDoc->SetString(nCol++, nRow, nTab, "Row");
pDoc->SetString(nCol++, nRow, nTab, "Tab");
pDoc->SetString(nCol++, nRow, nTab, "X");
pDoc->SetString(nCol++, nRow, nTab, "Y");
pDoc->SetString(nCol++, nRow, nTab, "W");
pDoc->SetString(nCol++, nRow, nTab, "H");
//-----------------------------------
#endif
sal_uInt16 nAnz;
rStream >> nAnz;
sal_Char Reserved[32];
rStream.Read(Reserved, sizeof(Reserved));
nError = rStream.GetError();
if ((nAnz > 0) && (nError == 0))
{
sal_uInt8 ObjectType;
Sc10GraphHeader GraphHeader;
sal_Bool IsOleObject = sal_False; // Achtung dies ist nur ein Notnagel
for (sal_uInt16 i = 0; (i < nAnz) && (nError == 0) && !rStream.IsEof() && !IsOleObject; i++)
{
rStream >> ObjectType;
lcl_ReadGraphHeader(rStream, GraphHeader);
double nPPTX = ScGlobal::nScreenPPTX;
double nPPTY = ScGlobal::nScreenPPTY;
long nStartX = 0;
for (SCsCOL nX=0; nX<GraphHeader.CarretX; nX++)
nStartX += pDoc->GetColWidth(nX, static_cast<SCTAB>(GraphHeader.CarretZ));
nStartX = (long) ( nStartX * HMM_PER_TWIPS );
nStartX += (long) ( GraphHeader.x / nPPTX * HMM_PER_TWIPS );
long nSizeX = (long) ( GraphHeader.w / nPPTX * HMM_PER_TWIPS );
long nStartY = pDoc->GetRowHeight( 0,
static_cast<SCsROW>(GraphHeader.CarretY) - 1,
static_cast<SCTAB>(GraphHeader.CarretZ));
nStartY = (long) ( nStartY * HMM_PER_TWIPS );
nStartY += (long) ( GraphHeader.y / nPPTY * HMM_PER_TWIPS );
long nSizeY = (long) ( GraphHeader.h / nPPTY * HMM_PER_TWIPS );
#ifdef SC10_SHOW_OBJECTS
// Achtung nur zu Debugzwecken
//-----------------------------------
nCol = 0;
nRow++;
switch (ObjectType)
{
case otOle :
pDoc->SetString(nCol++, nRow, nTab, "Ole-Object");
break;
case otImage :
pDoc->SetString(nCol++, nRow, nTab, "Image-Object");
break;
case otChart :
pDoc->SetString(nCol++, nRow, nTab, "Chart-Object");
break;
default :
pDoc->SetString(nCol++, nRow, nTab, "ERROR");
break;
}
pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.CarretX);
pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.CarretY);
pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.CarretZ);
pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.x);
pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.y);
pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.w);
pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.h);
//-----------------------------------
#endif
switch (ObjectType)
{
case otOle :
// Achtung hier muss sowas wie OleLoadFromStream passieren
IsOleObject = sal_True;
break;
case otImage :
{
Sc10ImageHeader ImageHeader;
lcl_ReadImageHeaer(rStream, ImageHeader);
// Achtung nun kommen die Daten (Bitmap oder Metafile)
// Typ = 1 Device Dependend Bitmap DIB
// Typ = 2 MetaFile
rStream.SeekRel(ImageHeader.Size);
if( ImageHeader.Typ != 1 && ImageHeader.Typ != 2 )
nError = errUnknownFormat;
break;
}
case otChart :
{
Sc10ChartHeader ChartHeader;
Sc10ChartSheetData ChartSheetData;
Sc10ChartTypeData* pTypeData = new (::std::nothrow) Sc10ChartTypeData;
if (!pTypeData)
nError = errOutOfMemory;
else
{
lcl_ReadChartHeader(rStream, ChartHeader);
//! altes Metafile verwenden ??
rStream.SeekRel(ChartHeader.Size);
lcl_ReadChartSheetData(rStream, ChartSheetData);
lcl_ReadChartTypeData(rStream, *pTypeData);
Rectangle aRect( Point(nStartX,nStartY), Size(nSizeX,nSizeY) );
Sc10InsertObject::InsertChart( pDoc, static_cast<SCTAB>(GraphHeader.CarretZ), aRect,
static_cast<SCTAB>(GraphHeader.CarretZ),
ChartSheetData.DataX1, ChartSheetData.DataY1,
ChartSheetData.DataX2, ChartSheetData.DataY2 );
delete pTypeData;
}
}
break;
default :
nError = errUnknownFormat;
break;
}
nError = rStream.GetError();
}
}
}
else
{
DBG_ERROR( "ObjectID" );
nError = errUnknownID;
}
}
//-----------------------------------------------------------------------------------------------
FltError ScFormatFilterPluginImpl::ScImportStarCalc10( SvStream& rStream, ScDocument* pDocument )
{
rStream.Seek( 0UL );
Sc10Import aImport( rStream, pDocument );
return ( FltError ) aImport.Import();
}
| 29.760032 | 148 | 0.642392 | Grosskopf |
17c84e975dc7f786a073022412fcc6f6169550d7 | 35,778 | cpp | C++ | src/RenderSystem/Vulkan/Vulkan.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | 1 | 2018-01-06T04:44:36.000Z | 2018-01-06T04:44:36.000Z | src/RenderSystem/Vulkan/Vulkan.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | null | null | null | src/RenderSystem/Vulkan/Vulkan.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | null | null | null | #include "RenderSystem/Vulkan/Vulkan.h"
#include "Core/Platform/CPlatform.h"
#include "Core/Utils/CLogger.h"
//#undef VKE_VK_FUNCTION
//#define VKE_VK_FUNCTION(_name) PFN_##_name _name
//#undef VK_EXPORTED_FUNCTION
//#undef VKE_ICD_GLOBAL
//#undef VKE_INSTANCE_ICD
//#undef VKE_DEVICE_ICD
//#define VK_EXPORTED_FUNCTION(name) PFN_##name name = 0
//#define VKE_ICD_GLOBAL(name) PFN_##name name = 0
//#define VKE_INSTANCE_ICD(name) PFN_##name name = 0
//#define VKE_DEVICE_ICD(name) PFN_##name name = 0
//#include "ThirdParty/vulkan/funclist.h"
//#undef VKE_DEVICE_ICD
//#undef VKE_INSTANCE_ICD
//#undef VKE_ICD_GLOBAL
//#undef VK_EXPORTED_FUNCTION
//#undef VKE_VK_FUNCTION
namespace VKE
{
namespace Vulkan
{
using ErrorMap = std::map< std::thread::id, VkResult >;
ErrorMap g_mErrors;
std::mutex g_ErrorMutex;
void SetLastError( VkResult err )
{
g_ErrorMutex.lock();
g_mErrors[ std::this_thread::get_id() ] = err;
g_ErrorMutex.unlock();
}
VkResult GetLastError()
{
g_ErrorMutex.lock();
auto ret = g_mErrors[ std::this_thread::get_id() ];
g_ErrorMutex.unlock();
return ret;
}
SQueue::SQueue()
{
this->m_objRefCount = 0;
Vulkan::InitInfo( &m_PresentInfo, VK_STRUCTURE_TYPE_PRESENT_INFO_KHR );
m_PresentInfo.pResults = nullptr;
}
VkResult SQueue::Submit( const VkICD::Device& ICD, const VkSubmitInfo& Info, const VkFence& vkFence )
{
Lock();
auto res = ICD.vkQueueSubmit( vkQueue, 1, &Info, vkFence );
Unlock();
return res;
}
bool SQueue::IsPresentDone()
{
return m_isPresentDone;
}
void SQueue::ReleasePresentNotify()
{
Lock();
if( m_presentCount-- < 0 )
m_presentCount = 0;
m_isPresentDone = m_presentCount == 0;
Unlock();
}
void SQueue::Wait( const VkICD::Device& ICD )
{
ICD.vkQueueWaitIdle( vkQueue );
}
Result SQueue::Present( const VkICD::Device& ICD, uint32_t imgIdx, VkSwapchainKHR vkSwpChain,
VkSemaphore vkWaitSemaphore )
{
Result res = VKE_ENOTREADY;
Lock();
m_PresentData.vImageIndices.PushBack( imgIdx );
m_PresentData.vSwapChains.PushBack( vkSwpChain );
m_PresentData.vWaitSemaphores.PushBack( vkWaitSemaphore );
m_presentCount++;
m_isPresentDone = false;
if( this->GetRefCount() == m_PresentData.vSwapChains.GetCount() )
{
m_PresentInfo.pImageIndices = &m_PresentData.vImageIndices[ 0 ];
m_PresentInfo.pSwapchains = &m_PresentData.vSwapChains[ 0 ];
m_PresentInfo.pWaitSemaphores = &m_PresentData.vWaitSemaphores[ 0 ];
m_PresentInfo.swapchainCount = m_PresentData.vSwapChains.GetCount();
m_PresentInfo.waitSemaphoreCount = m_PresentData.vWaitSemaphores.GetCount();
VK_ERR( ICD.vkQueuePresentKHR( vkQueue, &m_PresentInfo ) );
// $TID Present: q={vkQueue}, sc={m_PresentInfo.pSwapchains[0]}, imgIdx={m_PresentInfo.pImageIndices[0]}, ws={m_PresentInfo.pWaitSemaphores[0]}
m_isPresentDone = true;
m_PresentData.vImageIndices.Clear();
m_PresentData.vSwapChains.Clear();
m_PresentData.vWaitSemaphores.Clear();
res = VKE_OK;
}
Unlock();
return res;
}
bool IsColorImage( VkFormat format )
{
switch( format )
{
case VK_FORMAT_UNDEFINED:
case VK_FORMAT_D16_UNORM:
case VK_FORMAT_D16_UNORM_S8_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_D32_SFLOAT:
case VK_FORMAT_D32_SFLOAT_S8_UINT:
case VK_FORMAT_X8_D24_UNORM_PACK32:
case VK_FORMAT_S8_UINT:
return false;
}
return true;
}
bool IsDepthImage( VkFormat format )
{
switch( format )
{
case VK_FORMAT_D16_UNORM:
case VK_FORMAT_D16_UNORM_S8_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_D32_SFLOAT:
case VK_FORMAT_D32_SFLOAT_S8_UINT:
case VK_FORMAT_X8_D24_UNORM_PACK32:
case VK_FORMAT_S8_UINT:
return true;
}
return false;
}
bool IsStencilImage( VkFormat format )
{
switch( format )
{
case VK_FORMAT_D16_UNORM_S8_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_D32_SFLOAT_S8_UINT:
case VK_FORMAT_S8_UINT:
return true;
}
return false;
}
namespace Map
{
VkImageType ImageType( RenderSystem::TEXTURE_TYPE type )
{
static const VkImageType aVkImageTypes[] =
{
VK_IMAGE_TYPE_1D,
VK_IMAGE_TYPE_2D,
VK_IMAGE_TYPE_3D,
VK_IMAGE_TYPE_2D, // cube
};
return aVkImageTypes[ type ];
}
VkImageViewType ImageViewType( RenderSystem::TEXTURE_VIEW_TYPE type )
{
static const VkImageViewType aVkTypes[] =
{
VK_IMAGE_VIEW_TYPE_1D,
VK_IMAGE_VIEW_TYPE_2D,
VK_IMAGE_VIEW_TYPE_3D,
VK_IMAGE_VIEW_TYPE_1D_ARRAY,
VK_IMAGE_VIEW_TYPE_2D_ARRAY,
VK_IMAGE_VIEW_TYPE_CUBE,
VK_IMAGE_VIEW_TYPE_CUBE_ARRAY
};
return aVkTypes[ type ];
}
VkImageUsageFlags ImageUsage( RenderSystem::TEXTURE_USAGE usage )
{
/*static const VkImageUsageFlags aVkUsages[] =
{
VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
VK_IMAGE_USAGE_TRANSFER_DST_BIT,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
VK_IMAGE_USAGE_SAMPLED_BIT,
VK_IMAGE_USAGE_STORAGE_BIT,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT,
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT
};
return aVkUsages[ usage ];*/
using namespace RenderSystem;
VkImageUsageFlags flags = 0;
if( usage & TextureUsages::SAMPLED )
{
flags |= VK_IMAGE_USAGE_SAMPLED_BIT;
}
if( usage & TextureUsages::COLOR_RENDER_TARGET )
{
flags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
}
else if( usage & TextureUsages::DEPTH_STENCIL_RENDER_TARGET )
{
flags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
}
if( usage & TextureUsages::STORAGE )
{
flags |= VK_IMAGE_USAGE_STORAGE_BIT;
}
if( usage & TextureUsages::TRANSFER_DST )
{
flags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
}
if( usage & TextureUsages::TRANSFER_SRC )
{
flags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
}
return flags;
}
VkImageLayout ImageLayout( RenderSystem::TEXTURE_STATE layout )
{
static const VkImageLayout aVkLayouts[] =
{
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_GENERAL,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
};
return aVkLayouts[ layout ];
}
VkImageAspectFlags ImageAspect( RenderSystem::TEXTURE_ASPECT aspect )
{
static const VkImageAspectFlags aVkAspects[] =
{
// UNKNOWN
0,
// COLOR
VK_IMAGE_ASPECT_COLOR_BIT,
// DEPTH
VK_IMAGE_ASPECT_DEPTH_BIT,
// STENCIL
VK_IMAGE_ASPECT_STENCIL_BIT,
// DEPTH_STENCIL
VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT
};
return aVkAspects[ aspect ];
}
VkMemoryPropertyFlags MemoryPropertyFlags( RenderSystem::MEMORY_USAGE usages )
{
using namespace RenderSystem;
VkMemoryPropertyFlags flags = 0;
if( usages & MemoryUsages::CPU_ACCESS )
{
flags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
}
if( usages & MemoryUsages::CPU_CACHED )
{
flags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
}
if( usages & MemoryUsages::CPU_NO_FLUSH )
{
flags |= VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
}
if( usages & MemoryUsages::GPU_ACCESS )
{
flags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
}
return flags;
}
VkBlendOp BlendOp( const RenderSystem::BLEND_OPERATION& op )
{
static const VkBlendOp aVkOps[] =
{
VK_BLEND_OP_ADD,
VK_BLEND_OP_SUBTRACT,
VK_BLEND_OP_REVERSE_SUBTRACT,
VK_BLEND_OP_MIN,
VK_BLEND_OP_MAX
};
return aVkOps[ op ];
}
VkColorComponentFlags ColorComponent( const RenderSystem::ColorComponent& component )
{
VkColorComponentFlags vkComponent = 0;
if( component & RenderSystem::ColorComponents::ALL )
{
vkComponent = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
}
else
{
if( component & RenderSystem::ColorComponents::ALPHA )
{
vkComponent |= VK_COLOR_COMPONENT_A_BIT;
}
if( component & RenderSystem::ColorComponents::BLUE )
{
vkComponent |= VK_COLOR_COMPONENT_B_BIT;
}
if( component & RenderSystem::ColorComponents::GREEN )
{
vkComponent |= VK_COLOR_COMPONENT_G_BIT;
}
if( component & RenderSystem::ColorComponents::RED )
{
vkComponent |= VK_COLOR_COMPONENT_R_BIT;
}
}
return vkComponent;
}
VkBlendFactor BlendFactor( const RenderSystem::BLEND_FACTOR& factor )
{
static const VkBlendFactor aVkFactors[] =
{
VK_BLEND_FACTOR_ZERO,
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_SRC_COLOR,
VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR,
VK_BLEND_FACTOR_DST_COLOR,
VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR,
VK_BLEND_FACTOR_SRC_ALPHA,
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
VK_BLEND_FACTOR_DST_ALPHA,
VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA,
VK_BLEND_FACTOR_CONSTANT_COLOR,
VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR,
VK_BLEND_FACTOR_CONSTANT_ALPHA,
VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA,
VK_BLEND_FACTOR_SRC_ALPHA_SATURATE,
VK_BLEND_FACTOR_SRC1_COLOR,
VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR,
VK_BLEND_FACTOR_SRC1_ALPHA,
VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA
};
return aVkFactors[ factor ];
}
VkLogicOp LogicOperation( const RenderSystem::LOGIC_OPERATION& op )
{
static const VkLogicOp aVkOps[] =
{
VK_LOGIC_OP_CLEAR,
VK_LOGIC_OP_AND,
VK_LOGIC_OP_AND_REVERSE,
VK_LOGIC_OP_COPY,
VK_LOGIC_OP_AND_INVERTED,
VK_LOGIC_OP_NO_OP,
VK_LOGIC_OP_XOR,
VK_LOGIC_OP_OR,
VK_LOGIC_OP_NOR,
VK_LOGIC_OP_EQUIVALENT,
VK_LOGIC_OP_INVERT,
VK_LOGIC_OP_OR_REVERSE,
VK_LOGIC_OP_COPY_INVERTED,
VK_LOGIC_OP_OR_INVERTED,
VK_LOGIC_OP_NAND,
VK_LOGIC_OP_SET
};
return aVkOps[ op ];
}
VkStencilOp StencilOperation( const RenderSystem::STENCIL_FUNCTION& op )
{
static const VkStencilOp aVkOps[] =
{
VK_STENCIL_OP_KEEP,
VK_STENCIL_OP_ZERO,
VK_STENCIL_OP_REPLACE,
VK_STENCIL_OP_INCREMENT_AND_CLAMP,
VK_STENCIL_OP_DECREMENT_AND_CLAMP,
VK_STENCIL_OP_INVERT,
VK_STENCIL_OP_INCREMENT_AND_WRAP,
VK_STENCIL_OP_DECREMENT_AND_WRAP
};
return aVkOps[ op ];
}
VkCompareOp CompareOperation( const RenderSystem::COMPARE_FUNCTION& op )
{
static const VkCompareOp aVkOps[] =
{
VK_COMPARE_OP_NEVER,
VK_COMPARE_OP_LESS,
VK_COMPARE_OP_EQUAL,
VK_COMPARE_OP_LESS_OR_EQUAL,
VK_COMPARE_OP_GREATER,
VK_COMPARE_OP_NOT_EQUAL,
VK_COMPARE_OP_GREATER_OR_EQUAL,
VK_COMPARE_OP_ALWAYS
};
return aVkOps[ op ];
}
VkPrimitiveTopology PrimitiveTopology(const RenderSystem::PRIMITIVE_TOPOLOGY& topology)
{
static const VkPrimitiveTopology aVkTopologies[] =
{
VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN,
VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY,
VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY,
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY,
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY,
VK_PRIMITIVE_TOPOLOGY_PATCH_LIST
};
return aVkTopologies[ topology ];
}
VkSampleCountFlagBits SampleCount(const RenderSystem::SAMPLE_COUNT& count)
{
static const VkSampleCountFlagBits aVkSamples[] =
{
VK_SAMPLE_COUNT_1_BIT,
VK_SAMPLE_COUNT_2_BIT,
VK_SAMPLE_COUNT_4_BIT,
VK_SAMPLE_COUNT_8_BIT,
VK_SAMPLE_COUNT_16_BIT,
VK_SAMPLE_COUNT_32_BIT,
VK_SAMPLE_COUNT_64_BIT
};
return aVkSamples[ count ];
}
VkCullModeFlags CullMode( const RenderSystem::CULL_MODE& mode )
{
static const VkCullModeFlagBits aVkModes[] =
{
VK_CULL_MODE_NONE,
VK_CULL_MODE_FRONT_BIT,
VK_CULL_MODE_BACK_BIT,
VK_CULL_MODE_FRONT_AND_BACK
};
return aVkModes[ mode ];
}
VkFrontFace FrontFace( const RenderSystem::FRONT_FACE& face )
{
static const VkFrontFace aVkFaces[] =
{
VK_FRONT_FACE_COUNTER_CLOCKWISE,
VK_FRONT_FACE_CLOCKWISE
};
return aVkFaces[ face ];
}
VkPolygonMode PolygonMode( const RenderSystem::POLYGON_MODE& mode )
{
static const VkPolygonMode aVkModes[] =
{
VK_POLYGON_MODE_FILL,
VK_POLYGON_MODE_LINE,
VK_POLYGON_MODE_POINT
};
return aVkModes[ mode ];
}
VkShaderStageFlagBits ShaderStage( const RenderSystem::SHADER_TYPE& type )
{
static const VkShaderStageFlagBits aVkBits[] =
{
VK_SHADER_STAGE_VERTEX_BIT,
VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,
VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
VK_SHADER_STAGE_GEOMETRY_BIT,
VK_SHADER_STAGE_FRAGMENT_BIT,
VK_SHADER_STAGE_COMPUTE_BIT
};
return aVkBits[ type ];
}
VkVertexInputRate InputRate( const RenderSystem::VERTEX_INPUT_RATE& rate )
{
static const VkVertexInputRate aVkRates[] =
{
VK_VERTEX_INPUT_RATE_VERTEX,
VK_VERTEX_INPUT_RATE_INSTANCE
};
return aVkRates[ rate ];
}
VkDescriptorType DescriptorType(const RenderSystem::DESCRIPTOR_SET_TYPE& type)
{
static const VkDescriptorType aVkDescriptorType[] =
{
VK_DESCRIPTOR_TYPE_SAMPLER,
VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER,
VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC,
VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT
};
return aVkDescriptorType[ type ];
}
} // Map
namespace Convert
{
VkImageAspectFlags UsageToAspectMask( VkImageUsageFlags usage )
{
if( usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT )
{
return VK_IMAGE_ASPECT_COLOR_BIT;
}
if( usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT )
{
return VK_IMAGE_ASPECT_DEPTH_BIT;
}
VKE_LOG_ERR( "Invalid image usage: " << usage << " to use for aspectMask" );
assert( 0 && "Invalid image usage" );
return VK_IMAGE_ASPECT_COLOR_BIT;
}
VkImageViewType ImageTypeToViewType( VkImageType type )
{
static const VkImageViewType aTypes[] =
{
VK_IMAGE_VIEW_TYPE_1D,
VK_IMAGE_VIEW_TYPE_2D,
VK_IMAGE_VIEW_TYPE_3D
};
assert( type <= VK_IMAGE_TYPE_3D && "Invalid image type for image view type" );
return aTypes[ type ];
}
VkAttachmentLoadOp UsageToLoadOp( RenderSystem::RENDER_PASS_ATTACHMENT_USAGE usage )
{
static const VkAttachmentLoadOp aLoads[] =
{
VK_ATTACHMENT_LOAD_OP_DONT_CARE, // undefined
VK_ATTACHMENT_LOAD_OP_LOAD, // color
VK_ATTACHMENT_LOAD_OP_CLEAR, // color clear
VK_ATTACHMENT_LOAD_OP_LOAD, // color store
VK_ATTACHMENT_LOAD_OP_CLEAR, // color clear store
VK_ATTACHMENT_LOAD_OP_LOAD, // depth
VK_ATTACHMENT_LOAD_OP_CLEAR, // depth clear
VK_ATTACHMENT_LOAD_OP_LOAD, // depth store
VK_ATTACHMENT_LOAD_OP_CLEAR, // depth clear store
};
return aLoads[ usage ];
}
VkAttachmentStoreOp UsageToStoreOp( RenderSystem::RENDER_PASS_ATTACHMENT_USAGE usage )
{
static const VkAttachmentStoreOp aStores[] =
{
VK_ATTACHMENT_STORE_OP_STORE, // undefined
VK_ATTACHMENT_STORE_OP_STORE, // color
VK_ATTACHMENT_STORE_OP_STORE, // color clear
VK_ATTACHMENT_STORE_OP_STORE, // color store
VK_ATTACHMENT_STORE_OP_STORE, // color clear store
VK_ATTACHMENT_STORE_OP_STORE, // depth
VK_ATTACHMENT_STORE_OP_STORE, // depth clear
VK_ATTACHMENT_STORE_OP_STORE, // depth store
VK_ATTACHMENT_STORE_OP_STORE, // depth clear store
};
return aStores[ usage ];
}
VkImageLayout ImageUsageToLayout( VkImageUsageFlags vkFlags )
{
const auto imgSampled = vkFlags & VK_IMAGE_USAGE_SAMPLED_BIT;
const auto inputAttachment = vkFlags & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
const auto isReadOnly = imgSampled || inputAttachment;
if( vkFlags & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT )
{
return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
}
else if( vkFlags & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT )
{
if( isReadOnly )
return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
}
else if( vkFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT )
{
return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
}
else if( vkFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT )
{
return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
}
else if( isReadOnly )
{
return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
}
assert( 0 && "Invalid image usage flags" );
VKE_LOG_ERR( "Usage flags: " << vkFlags << " are invalid." );
return VK_IMAGE_LAYOUT_UNDEFINED;
}
VkImageLayout ImageUsageToInitialLayout( VkImageUsageFlags vkFlags )
{
if( vkFlags & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT )
{
return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
}
else if( vkFlags & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT )
{
return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
}
assert( 0 && "Invalid image usage flags" );
VKE_LOG_ERR( "Usage flags: " << vkFlags << " are invalid." );
return VK_IMAGE_LAYOUT_UNDEFINED;
}
VkImageLayout ImageUsageToFinalLayout( VkImageUsageFlags vkFlags )
{
const auto imgSampled = vkFlags & VK_IMAGE_USAGE_SAMPLED_BIT;
const auto inputAttachment = vkFlags & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
bool isReadOnly = imgSampled || inputAttachment;
if( vkFlags & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT )
{
if( isReadOnly )
return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
}
else if( vkFlags & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT )
{
if( isReadOnly )
return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
}
assert( 0 && "Invalid image usage flags" );
VKE_LOG_ERR( "Usage flags: " << vkFlags << " are invalid." );
return VK_IMAGE_LAYOUT_UNDEFINED;
}
VkImageLayout NextAttachmentLayoutRread( VkImageLayout currLayout )
{
if( currLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL )
{
return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
}
if( currLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL )
{
return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
}
assert( 0 && "Incorrect initial layout for attachment." );
return VK_IMAGE_LAYOUT_UNDEFINED;
}
VkImageLayout NextAttachmentLayoutOptimal( VkImageLayout currLayout )
{
if( currLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL )
{
return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
}
if( currLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL )
{
return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
}
assert( 0 && "Incorrect initial layout for attachment." );
return VK_IMAGE_LAYOUT_UNDEFINED;
}
RenderSystem::TEXTURE_FORMAT ImageFormat( VkFormat vkFormat )
{
switch( vkFormat )
{
case VK_FORMAT_B8G8R8A8_UNORM: return RenderSystem::Formats::B8G8R8A8_UNORM;
};
assert( 0 && "Cannot convert VkFormat to RenderSystem format" );
return RenderSystem::Formats::UNDEFINED;
}
VkPipelineStageFlags PipelineStages(const RenderSystem::PIPELINE_STAGES& stages)
{
VkPipelineStageFlags vkFlags = 0;
if( stages & RenderSystem::PipelineStages::COMPUTE )
{
vkFlags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
}
if( stages & RenderSystem::PipelineStages::GEOMETRY )
{
vkFlags |= VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT;
}
if( stages & RenderSystem::PipelineStages::PIXEL )
{
vkFlags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
}
if( stages & RenderSystem::PipelineStages::TS_DOMAIN )
{
vkFlags |= VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT;
}
if( stages & RenderSystem::PipelineStages::TS_HULL )
{
vkFlags |= VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT;
}
if( stages & RenderSystem::PipelineStages::VERTEX )
{
vkFlags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT;
}
return vkFlags;
}
VkBufferUsageFlags BufferUsage( const RenderSystem::BUFFER_USAGE& usage )
{
VkBufferUsageFlags vkFlags = 0;
if( usage & RenderSystem::BufferUsages::INDEX_BUFFER )
{
vkFlags |= VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
}
if( usage & RenderSystem::BufferUsages::VERTEX_BUFFER )
{
vkFlags |= VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
}
if( usage & RenderSystem::BufferUsages::CONSTANT_BUFFER )
{
vkFlags |= VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
}
if( usage & RenderSystem::BufferUsages::TRANSFER_DST )
{
vkFlags |= VK_BUFFER_USAGE_TRANSFER_DST_BIT;
}
if( usage & RenderSystem::BufferUsages::TRANSFER_SRC )
{
vkFlags |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
}
if( usage & RenderSystem::BufferUsages::INDIRECT_BUFFER )
{
vkFlags |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
}
if( usage & RenderSystem::BufferUsages::STORAGE_BUFFER )
{
vkFlags |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
}
if( usage & RenderSystem::BufferUsages::STORAGE_TEXEL_BUFFER )
{
vkFlags |= VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT;
}
if( usage & RenderSystem::BufferUsages::UNIFORM_TEXEL_BUFFER )
{
vkFlags |= VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT;
}
return vkFlags;
}
VkImageTiling ImageUsageToTiling( const RenderSystem::TEXTURE_USAGE& usage )
{
VkImageTiling vkTiling = VK_IMAGE_TILING_OPTIMAL;
if( usage & RenderSystem::TextureUsages::FILE_IO )
{
vkTiling = VK_IMAGE_TILING_LINEAR;
}
return vkTiling;
}
static const VkMemoryPropertyFlags g_aRequiredMemoryFlags[] =
{
0, // unknown
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // gpu
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, // cpu access
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT // cpu access optimal
};
VkMemoryPropertyFlags MemoryUsagesToVkMemoryPropertyFlags( const RenderSystem::MEMORY_USAGE& usages )
{
VkMemoryPropertyFlags flags = 0;
if( usages & RenderSystem::MemoryUsages::GPU_ACCESS )
{
flags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
}
else
{
if( usages & RenderSystem::MemoryUsages::CPU_ACCESS )
{
flags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
}
if( usages & RenderSystem::MemoryUsages::CPU_NO_FLUSH )
{
flags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
}
if( usages & RenderSystem::MemoryUsages::CPU_CACHED )
{
flags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
}
}
return flags;
}
} // Convert
#define VKE_EXPORT_FUNC(_name, _handle, _getProcAddr) \
pOut->_name = (PFN_##_name)(_getProcAddr((_handle), #_name)); \
if(!pOut->_name) \
{ VKE_LOG_ERR("Unable to load function: " << #_name); err = VKE_ENOTFOUND; }
#define VKE_EXPORT_EXT_FUNC(_name, _handle, _getProcAddr) \
pOut->_name = (PFN_##_name)(_getProcAddr((_handle), #_name)); \
if(!pOut->_name) \
{ VKE_LOG_ERR("Unable to load function: " << #_name); }
Result LoadGlobalFunctions( handle_t hLib, VkICD::Global* pOut )
{
Result err = VKE_OK;
#if VKE_AUTO_ICD
#define VK_EXPORTED_FUNCTION(_name) VKE_EXPORT_FUNC(_name, hLib, Platform::DynamicLibrary::GetProcAddress)
#include "ThirdParty/vulkan/VKEICD.h"
#undef VK_EXPORTED_FUNCTION
#define VKE_ICD_GLOBAL(_name) VKE_EXPORT_FUNC(_name, VK_NULL_HANDLE, pOut->vkGetInstanceProcAddr)
#include "ThirdParty/vulkan/VKEICD.h"
#undef VKE_ICD_GLOBAL
#else // VKE_AUTO_ICD
pOut->vkGetInstanceProcAddr = reinterpret_cast< PFN_vkGetInstanceProcAddr >( Platform::GetProcAddress( hLib, "vkGetInstanceProcAddr" ) );
pOut->vkCreateInstance = reinterpret_cast< PFN_vkCreateInstance >( pOut->vkGetInstanceProcAddr( VK_NULL_HANDLE, "vkCreateInstance" ) );
//pOut->vkDestroyInstance = reinterpret_cast< PFN_vkDestroyInstance >( pOut->vkGetInstanceProcAddr( VK_NULL_HANDLE, "vkDestroyInstance" ) );
pOut->vkEnumerateInstanceExtensionProperties = reinterpret_cast< PFN_vkEnumerateInstanceExtensionProperties >( pOut->vkGetInstanceProcAddr( VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties" ) );
pOut->vkEnumerateInstanceLayerProperties = reinterpret_cast< PFN_vkEnumerateInstanceLayerProperties >( pOut->vkGetInstanceProcAddr( VK_NULL_HANDLE, "vkEnumerateInstanceLayerProperties" ) );
#endif // VKE_AUTO_ICD
return err;
}
Result LoadInstanceFunctions( VkInstance vkInstance, const VkICD::Global& Global,
VkICD::Instance* pOut )
{
Result err = VKE_OK;
#if VKE_AUTO_ICD
# undef VKE_INSTANCE_ICD
# undef VKE_INSTANCE_EXT_ICD
# define VKE_INSTANCE_ICD(_name) VKE_EXPORT_FUNC(_name, vkInstance, Global.vkGetInstanceProcAddr)
# define VKE_INSTANCE_EXT_ICD(_name) VKE_EXPORT_EXT_FUNC(_name, vkInstance, Global.vkGetInstanceProcAddr)
# include "ThirdParty/vulkan/VKEICD.h"
# undef VKE_INSTANCE_ICD
# undef VKE_INSTANCE_EXT_ICD
#else // VKE_AUTO_ICD
pOut->vkDestroySurfaceKHR = reinterpret_cast< PFN_vkDestroySurfaceKHR >( Global.vkGetInstanceProcAddr( vkInstance, "vkDestroySurfaceKHR" ) );
#endif // VKE_AUTO_ICD
return err;
}
Result LoadDeviceFunctions( VkDevice vkDevice, const VkICD::Instance& Instance, VkICD::Device* pOut )
{
Result err = VKE_OK;
#if VKE_AUTO_ICD
# undef VKE_DEVICE_ICD
# undef VKE_DEVICE_EXT_ICD
# define VKE_DEVICE_ICD(_name) VKE_EXPORT_FUNC(_name, vkDevice, Instance.vkGetDeviceProcAddr)
# define VKE_DEVICE_EXT_ICD(_name) VKE_EXPORT_EXT_FUNC(_name, vkDevice, Instance.vkGetDeviceProcAddr);
# include "ThirdParty/vulkan/VKEICD.h"
# undef VKE_DEVICE_ICD
# undef VKE_DEVICE_EXT_ICD
#else // VKE_AUTO_ICD
#endif // VKE_AUTO_ICD
return err;
}
}
} | 40.656818 | 213 | 0.542764 | przemyslaw-szymanski |
17c86b1802ea9ee06842273f20e333998dd5a9b6 | 3,330 | cpp | C++ | rqt_multiplot_plugin/rqt_multiplot/src/rqt_multiplot/CurveDataVector.cpp | huying163/ros_environment | bac3343bf92e6fa2bd852baf261e80712564f990 | [
"MIT"
] | 8 | 2018-01-30T11:40:31.000Z | 2021-05-03T05:52:47.000Z | rqt_multiplot_plugin/rqt_multiplot/src/rqt_multiplot/CurveDataVector.cpp | huying163/ros_environment | bac3343bf92e6fa2bd852baf261e80712564f990 | [
"MIT"
] | null | null | null | rqt_multiplot_plugin/rqt_multiplot/src/rqt_multiplot/CurveDataVector.cpp | huying163/ros_environment | bac3343bf92e6fa2bd852baf261e80712564f990 | [
"MIT"
] | 1 | 2020-12-23T08:14:57.000Z | 2020-12-23T08:14:57.000Z | /******************************************************************************
* Copyright (C) 2015 by Ralf Kaestner *
* ralf.kaestner@gmail.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the Lesser GNU General Public License as published by*
* the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* Lesser GNU General Public License for more details. *
* *
* You should have received a copy of the Lesser GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************/
#include "rqt_multiplot/CurveDataVector.h"
namespace rqt_multiplot {
/*****************************************************************************/
/* Constructors and Destructor */
/*****************************************************************************/
CurveDataVector::CurveDataVector() {
}
CurveDataVector::~CurveDataVector() {
}
/*****************************************************************************/
/* Accessors */
/*****************************************************************************/
size_t CurveDataVector::getNumPoints() const {
return points_.count();
}
QPointF CurveDataVector::getPoint(size_t index) const {
return points_[index];
}
QVector<size_t> CurveDataVector::getPointsInDistance(double x, double
maxDistance) const {
QVector<size_t> indexes;
XCoordinateRefSet::const_iterator it = x_.lower_bound(x-maxDistance);
while (it != x_.end()) {
if (fabs(x-it->x_) <= maxDistance) {
indexes.push_back(it->index_);
++it;
}
else
break;
}
return indexes;
}
BoundingRectangle CurveDataVector::getBounds() const {
return bounds_;
}
/*****************************************************************************/
/* Methods */
/*****************************************************************************/
void CurveDataVector::appendPoint(const QPointF& point) {
bounds_ += point;
if (points_.capacity() < points_.count()+1)
points_.reserve(points_.capacity() ? 2*points_.capacity() : 1);
points_.append(point);
if (x_.capacity() < x_.size()+1)
x_.reserve(x_.capacity() ? 2*x_.capacity() : 1);
x_.insert(XCoordinateRef(point.x(), points_.size()-1));
}
void CurveDataVector::clearPoints() {
points_.clear();
x_.clear();
bounds_.clear();
}
}
| 35.806452 | 80 | 0.429429 | huying163 |
17c8b1276609b9fd159b42401ccf7f84dada58ff | 539 | cpp | C++ | Leetcode/Practice/N-Repeated Element in Size 2N Array.cpp | coderanant/Competitive-Programming | 45076af7894251080ac616c9581fbf2dc49604af | [
"MIT"
] | 4 | 2019-06-04T11:03:38.000Z | 2020-06-19T23:37:32.000Z | Leetcode/Practice/N-Repeated Element in Size 2N Array.cpp | coderanant/Competitive-Programming | 45076af7894251080ac616c9581fbf2dc49604af | [
"MIT"
] | null | null | null | Leetcode/Practice/N-Repeated Element in Size 2N Array.cpp | coderanant/Competitive-Programming | 45076af7894251080ac616c9581fbf2dc49604af | [
"MIT"
] | null | null | null | /*coderanant*/
#define ll long long
#define f1(i,a,b) for(int i=a;i<b;i++)
#define f2(i,a,b) for(int i=a;i>=b;i--)
#define endl '\n'
#define pb push_back
#define gp " "
#define ff first
#define ss second
#define mp make_pair
const int mod=1000000007;
ll temp;
class Solution {
public:
int repeatedNTimes(vector<int>& A)
{
int n = A.size();
f1(i,0,n)
{
f1(j,max(i-3,0),i)
{
if(A[i]==A[j])
return A[i];
}
}
return 0;
}
}; | 18.586207 | 39 | 0.497217 | coderanant |
17c9c617f92aa763f28cf6945f5d1206b92c5b5a | 14,580 | cc | C++ | tests/mpi_particle_test.cc | fuatfurkany/mpm | d840c91f1f6ed1d164dec30029717dcfe9d30f0c | [
"MIT"
] | null | null | null | tests/mpi_particle_test.cc | fuatfurkany/mpm | d840c91f1f6ed1d164dec30029717dcfe9d30f0c | [
"MIT"
] | null | null | null | tests/mpi_particle_test.cc | fuatfurkany/mpm | d840c91f1f6ed1d164dec30029717dcfe9d30f0c | [
"MIT"
] | null | null | null | #include <limits>
#include "catch.hpp"
#include "data_types.h"
#include "hdf5_particle.h"
#include "material/material.h"
#include "mpi_datatypes.h"
#include "particle.h"
#ifdef USE_MPI
//! \brief Check particle class for 1D case
TEST_CASE("MPI HDF5 Particle is checked", "[particle][mpi][hdf5]") {
// Dimension
const unsigned Dim = 3;
// Tolerance
const double Tolerance = 1.E-7;
// Check MPI transfer of HDF5 Particle
SECTION("MPI HDF5 Particle") {
mpm::Index id = 0;
mpm::HDF5Particle h5_particle;
h5_particle.id = 13;
h5_particle.mass = 501.5;
h5_particle.pressure = 125.75;
Eigen::Vector3d coords;
coords << 1., 2., 3.;
h5_particle.coord_x = coords[0];
h5_particle.coord_y = coords[1];
h5_particle.coord_z = coords[2];
Eigen::Vector3d displacement;
displacement << 0.01, 0.02, 0.03;
h5_particle.displacement_x = displacement[0];
h5_particle.displacement_y = displacement[1];
h5_particle.displacement_z = displacement[2];
Eigen::Vector3d lsize;
lsize << 0.25, 0.5, 0.75;
h5_particle.nsize_x = lsize[0];
h5_particle.nsize_y = lsize[1];
h5_particle.nsize_z = lsize[2];
Eigen::Vector3d velocity;
velocity << 1.5, 2.5, 3.5;
h5_particle.velocity_x = velocity[0];
h5_particle.velocity_y = velocity[1];
h5_particle.velocity_z = velocity[2];
Eigen::Matrix<double, 6, 1> stress;
stress << 11.5, -12.5, 13.5, 14.5, -15.5, 16.5;
h5_particle.stress_xx = stress[0];
h5_particle.stress_yy = stress[1];
h5_particle.stress_zz = stress[2];
h5_particle.tau_xy = stress[3];
h5_particle.tau_yz = stress[4];
h5_particle.tau_xz = stress[5];
Eigen::Matrix<double, 6, 1> strain;
strain << 0.115, -0.125, 0.135, 0.145, -0.155, 0.165;
h5_particle.strain_xx = strain[0];
h5_particle.strain_yy = strain[1];
h5_particle.strain_zz = strain[2];
h5_particle.gamma_xy = strain[3];
h5_particle.gamma_yz = strain[4];
h5_particle.gamma_xz = strain[5];
h5_particle.epsilon_v = strain.head(Dim).sum();
h5_particle.status = true;
h5_particle.cell_id = 1;
h5_particle.volume = 2.;
h5_particle.material_id = 1;
h5_particle.nstate_vars = 0;
for (unsigned i = 0; i < h5_particle.nstate_vars; ++i)
h5_particle.svars[i] = 0.;
// Check send and receive particle with HDF5
SECTION("Check send and receive particle with HDF5") {
// Get number of MPI ranks
int mpi_size;
MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
// If on same rank
int sender = 0;
int receiver = 0;
// Get rank and do the corresponding job for mpi size == 2
if (mpi_size == 2) receiver = 1;
int mpi_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
// Send particle
if (mpi_rank == sender) {
// Initialize MPI datatypes
MPI_Datatype particle_type =
mpm::register_mpi_particle_type(h5_particle);
MPI_Send(&h5_particle, 1, particle_type, receiver, 0, MPI_COMM_WORLD);
mpm::deregister_mpi_particle_type(particle_type);
}
// Receive particle
if (mpi_rank == receiver) {
// Receive the messid
struct mpm::HDF5Particle received;
MPI_Datatype particle_type = mpm::register_mpi_particle_type(received);
MPI_Recv(&received, 1, particle_type, sender, 0, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
mpm::deregister_mpi_particle_type(particle_type);
REQUIRE(h5_particle.id == received.id);
REQUIRE(h5_particle.mass == received.mass);
REQUIRE(h5_particle.pressure ==
Approx(received.pressure).epsilon(Tolerance));
REQUIRE(h5_particle.volume ==
Approx(received.volume).epsilon(Tolerance));
REQUIRE(h5_particle.coord_x ==
Approx(received.coord_x).epsilon(Tolerance));
REQUIRE(h5_particle.coord_y ==
Approx(received.coord_y).epsilon(Tolerance));
REQUIRE(h5_particle.coord_z ==
Approx(received.coord_z).epsilon(Tolerance));
REQUIRE(h5_particle.displacement_x ==
Approx(received.displacement_x).epsilon(Tolerance));
REQUIRE(h5_particle.displacement_y ==
Approx(received.displacement_y).epsilon(Tolerance));
REQUIRE(h5_particle.displacement_z ==
Approx(received.displacement_z).epsilon(Tolerance));
REQUIRE(h5_particle.nsize_x == received.nsize_x);
REQUIRE(h5_particle.nsize_y == received.nsize_y);
REQUIRE(h5_particle.nsize_z == received.nsize_z);
REQUIRE(h5_particle.velocity_x ==
Approx(received.velocity_x).epsilon(Tolerance));
REQUIRE(h5_particle.velocity_y ==
Approx(received.velocity_y).epsilon(Tolerance));
REQUIRE(h5_particle.velocity_z ==
Approx(received.velocity_z).epsilon(Tolerance));
REQUIRE(h5_particle.stress_xx ==
Approx(received.stress_xx).epsilon(Tolerance));
REQUIRE(h5_particle.stress_yy ==
Approx(received.stress_yy).epsilon(Tolerance));
REQUIRE(h5_particle.stress_zz ==
Approx(received.stress_zz).epsilon(Tolerance));
REQUIRE(h5_particle.tau_xy ==
Approx(received.tau_xy).epsilon(Tolerance));
REQUIRE(h5_particle.tau_yz ==
Approx(received.tau_yz).epsilon(Tolerance));
REQUIRE(h5_particle.tau_xz ==
Approx(received.tau_xz).epsilon(Tolerance));
REQUIRE(h5_particle.strain_xx ==
Approx(received.strain_xx).epsilon(Tolerance));
REQUIRE(h5_particle.strain_yy ==
Approx(received.strain_yy).epsilon(Tolerance));
REQUIRE(h5_particle.strain_zz ==
Approx(received.strain_zz).epsilon(Tolerance));
REQUIRE(h5_particle.gamma_xy ==
Approx(received.gamma_xy).epsilon(Tolerance));
REQUIRE(h5_particle.gamma_yz ==
Approx(received.gamma_yz).epsilon(Tolerance));
REQUIRE(h5_particle.gamma_xz ==
Approx(received.gamma_xz).epsilon(Tolerance));
REQUIRE(h5_particle.epsilon_v ==
Approx(received.epsilon_v).epsilon(Tolerance));
REQUIRE(h5_particle.status == received.status);
REQUIRE(h5_particle.cell_id == received.cell_id);
REQUIRE(h5_particle.material_id == received.cell_id);
REQUIRE(h5_particle.nstate_vars == received.nstate_vars);
for (unsigned i = 0; i < h5_particle.nstate_vars; ++i)
REQUIRE(h5_particle.svars[i] ==
Approx(h5_particle.svars[i]).epsilon(Tolerance));
}
}
// Check initialise particle from HDF5 file
SECTION("Check initialise particle with HDF5 across MPI processes") {
// Get number of MPI ranks
int mpi_size;
MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
int mpi_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
// If on same rank
int sender = 0;
int receiver = 0;
// Get rank and do the corresponding job for mpi size == 2
if (mpi_size == 2) receiver = 1;
// Initial particle coordinates
Eigen::Matrix<double, 3, 1> pcoordinates;
pcoordinates.setZero();
if (mpi_rank == sender) {
// Create and initialzie particle with HDF5 data
std::shared_ptr<mpm::ParticleBase<Dim>> particle =
std::make_shared<mpm::Particle<Dim>>(id, pcoordinates);
// Assign material
unsigned mid = 1;
// Initialise material
Json jmaterial;
jmaterial["density"] = 1000.;
jmaterial["youngs_modulus"] = 1.0E+7;
jmaterial["poisson_ratio"] = 0.3;
auto material =
Factory<mpm::Material<Dim>, unsigned, const Json&>::instance()
->create("LinearElastic3D", std::move(mid), jmaterial);
// Reinitialise particle from HDF5 data
REQUIRE(particle->initialise_particle(h5_particle, material) == true);
// Check particle id
REQUIRE(particle->id() == h5_particle.id);
// Check particle mass
REQUIRE(particle->mass() == h5_particle.mass);
// Check particle volume
REQUIRE(particle->volume() == h5_particle.volume);
// Check particle mass density
REQUIRE(particle->mass_density() ==
h5_particle.mass / h5_particle.volume);
// Check particle status
REQUIRE(particle->status() == h5_particle.status);
// Check for coordinates
auto coordinates = particle->coordinates();
REQUIRE(coordinates.size() == Dim);
for (unsigned i = 0; i < coordinates.size(); ++i)
REQUIRE(coordinates(i) == Approx(coords(i)).epsilon(Tolerance));
REQUIRE(coordinates.size() == Dim);
// Check for displacement
auto pdisplacement = particle->displacement();
REQUIRE(pdisplacement.size() == Dim);
for (unsigned i = 0; i < Dim; ++i)
REQUIRE(pdisplacement(i) ==
Approx(displacement(i)).epsilon(Tolerance));
// Check for size
auto size = particle->natural_size();
REQUIRE(size.size() == Dim);
for (unsigned i = 0; i < size.size(); ++i)
REQUIRE(size(i) == Approx(lsize(i)).epsilon(Tolerance));
// Check velocity
auto pvelocity = particle->velocity();
REQUIRE(pvelocity.size() == Dim);
for (unsigned i = 0; i < Dim; ++i)
REQUIRE(pvelocity(i) == Approx(velocity(i)).epsilon(Tolerance));
// Check stress
auto pstress = particle->stress();
REQUIRE(pstress.size() == stress.size());
for (unsigned i = 0; i < stress.size(); ++i)
REQUIRE(pstress(i) == Approx(stress(i)).epsilon(Tolerance));
// Check strain
auto pstrain = particle->strain();
REQUIRE(pstrain.size() == strain.size());
for (unsigned i = 0; i < strain.size(); ++i)
REQUIRE(pstrain(i) == Approx(strain(i)).epsilon(Tolerance));
// Check particle volumetric strain centroid
REQUIRE(particle->volumetric_strain_centroid() ==
h5_particle.epsilon_v);
// Check cell id
REQUIRE(particle->cell_id() == h5_particle.cell_id);
// Check material id
REQUIRE(particle->material_id() == h5_particle.material_id);
// Write Particle HDF5 data
const auto h5_send = particle->hdf5();
// Send MPI particle
MPI_Datatype paritcle_type = mpm::register_mpi_particle_type(h5_send);
MPI_Send(&h5_send, 1, paritcle_type, receiver, 0, MPI_COMM_WORLD);
mpm::deregister_mpi_particle_type(paritcle_type);
}
if (mpi_rank == receiver) {
// Receive the messid
struct mpm::HDF5Particle received;
MPI_Datatype paritcle_type = mpm::register_mpi_particle_type(received);
MPI_Recv(&received, 1, paritcle_type, sender, 0, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
mpm::deregister_mpi_particle_type(paritcle_type);
// Received particle
std::shared_ptr<mpm::ParticleBase<Dim>> rparticle =
std::make_shared<mpm::Particle<Dim>>(id, pcoordinates);
// Assign material
unsigned mid = 1;
// Initialise material
Json jmaterial;
jmaterial["density"] = 1000.;
jmaterial["youngs_modulus"] = 1.0E+7;
jmaterial["poisson_ratio"] = 0.3;
auto material =
Factory<mpm::Material<Dim>, unsigned, const Json&>::instance()
->create("LinearElastic3D", std::move(mid), jmaterial);
// Reinitialise particle from HDF5 data
REQUIRE(rparticle->initialise_particle(received, material) == true);
// Check particle id
REQUIRE(rparticle->id() == h5_particle.id);
// Check particle mass
REQUIRE(rparticle->mass() == h5_particle.mass);
// Check particle volume
REQUIRE(rparticle->volume() == h5_particle.volume);
// Check particle mass density
REQUIRE(rparticle->mass_density() ==
h5_particle.mass / h5_particle.volume);
// Check particle status
REQUIRE(rparticle->status() == h5_particle.status);
// Check for coordinates
auto coordinates = rparticle->coordinates();
REQUIRE(coordinates.size() == Dim);
for (unsigned i = 0; i < coordinates.size(); ++i)
REQUIRE(coordinates(i) == Approx(coords(i)).epsilon(Tolerance));
REQUIRE(coordinates.size() == Dim);
// Check for displacement
auto pdisplacement = rparticle->displacement();
REQUIRE(pdisplacement.size() == Dim);
for (unsigned i = 0; i < Dim; ++i)
REQUIRE(pdisplacement(i) ==
Approx(displacement(i)).epsilon(Tolerance));
// Check for size
auto size = rparticle->natural_size();
REQUIRE(size.size() == Dim);
for (unsigned i = 0; i < size.size(); ++i)
REQUIRE(size(i) == Approx(lsize(i)).epsilon(Tolerance));
// Check velocity
auto pvelocity = rparticle->velocity();
REQUIRE(pvelocity.size() == Dim);
for (unsigned i = 0; i < Dim; ++i)
REQUIRE(pvelocity(i) == Approx(velocity(i)).epsilon(Tolerance));
// Check stress
auto pstress = rparticle->stress();
REQUIRE(pstress.size() == stress.size());
for (unsigned i = 0; i < stress.size(); ++i)
REQUIRE(pstress(i) == Approx(stress(i)).epsilon(Tolerance));
// Check strain
auto pstrain = rparticle->strain();
REQUIRE(pstrain.size() == strain.size());
for (unsigned i = 0; i < strain.size(); ++i)
REQUIRE(pstrain(i) == Approx(strain(i)).epsilon(Tolerance));
// Check particle volumetric strain centroid
REQUIRE(rparticle->volumetric_strain_centroid() ==
h5_particle.epsilon_v);
// Check cell id
REQUIRE(rparticle->cell_id() == h5_particle.cell_id);
// Check material id
REQUIRE(rparticle->material_id() == h5_particle.material_id);
// Get Particle HDF5 data
const auto h5_received = rparticle->hdf5();
// State variables
REQUIRE(h5_received.nstate_vars == h5_particle.nstate_vars);
// State variables
for (unsigned i = 0; i < h5_particle.nstate_vars; ++i)
REQUIRE(h5_received.svars[i] ==
Approx(h5_particle.svars[i]).epsilon(Tolerance));
}
}
}
}
#endif // MPI
| 36.541353 | 79 | 0.615844 | fuatfurkany |
17ca1c483efbf06de8a215d671380faa872a772b | 1,211 | cpp | C++ | libs/vgc/graphics/idgenerator.cpp | QtOpenGL/vgc | 4c48e24884f0613cca5ff7094b7a1824cb44d97a | [
"ECL-2.0",
"Apache-2.0"
] | 218 | 2018-03-04T14:11:25.000Z | 2022-03-25T01:19:47.000Z | libs/vgc/graphics/idgenerator.cpp | QtOpenGL/vgc | 4c48e24884f0613cca5ff7094b7a1824cb44d97a | [
"ECL-2.0",
"Apache-2.0"
] | 239 | 2018-02-21T11:26:04.000Z | 2022-03-17T15:08:22.000Z | libs/vgc/graphics/idgenerator.cpp | QtOpenGL/vgc | 4c48e24884f0613cca5ff7094b7a1824cb44d97a | [
"ECL-2.0",
"Apache-2.0"
] | 21 | 2018-02-28T06:27:44.000Z | 2022-03-02T15:31:53.000Z | // Copyright 2021 The VGC Developers
// See the COPYRIGHT file at the top-level directory of this distribution
// and at https://github.com/vgc/vgc/blob/master/COPYRIGHT
//
// 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 <vgc/graphics/idgenerator.h>
// Note: we need this .cpp file because even though it doesn't define any
// function, it includes the above .h file, informing the compiler about the
// IdGenerator symbol which must be exported (despite the class being
// all-inline). Not having this *.cpp file results in a linker error on
// MSVC when trying to instanciate an IdGenerator from another DLL.
namespace vgc {
namespace graphics {
} // namespace graphics
} // namespace vgc
| 40.366667 | 76 | 0.753097 | QtOpenGL |
17cb624e664efb5046ffc4a49a003c47fda795cb | 875 | cpp | C++ | cpp/src/FindFirstAndLastPositionOfElementInSortedArray.cpp | qianbinbin/leetcode | 915cecab0c940cd13847683ec55b17b77eb0f39b | [
"MIT"
] | 4 | 2018-03-05T02:27:16.000Z | 2021-03-15T14:19:44.000Z | cpp/src/FindFirstAndLastPositionOfElementInSortedArray.cpp | qianbinbin/leetcode | 915cecab0c940cd13847683ec55b17b77eb0f39b | [
"MIT"
] | null | null | null | cpp/src/FindFirstAndLastPositionOfElementInSortedArray.cpp | qianbinbin/leetcode | 915cecab0c940cd13847683ec55b17b77eb0f39b | [
"MIT"
] | 2 | 2018-07-22T10:32:10.000Z | 2018-10-20T03:14:28.000Z | #include "FindFirstAndLastPositionOfElementInSortedArray.h"
using namespace lcpp;
static std::vector<int>::iterator binarySearch(std::vector<int>::iterator First,
std::vector<int>::iterator Last,
int Val, bool Lower) {
while (First < Last) {
auto Mid = First + (Last - First) / 2;
if (Val < *Mid || (Lower && Val == *Mid))
Last = Mid;
else
First = Mid + 1;
}
return First;
}
std::vector<int> Solution34_1::searchRange(std::vector<int> &nums, int target) {
auto I = binarySearch(nums.begin(), nums.end(), target, true);
if (I == nums.end() || *I != target)
return {-1, -1};
return {static_cast<int>(I - nums.begin()),
static_cast<int>(binarySearch(I, nums.end(), target, false) -
nums.begin() - 1)};
}
| 33.653846 | 80 | 0.540571 | qianbinbin |
17d207c505a538b0ea583e5b66e3165dd8e78138 | 186 | cxx | C++ | src/test/testmain.cxx | fermi-lat/Event | 2e9e8ee117f61c4b1abde69828a97f94ff84630a | [
"BSD-3-Clause"
] | null | null | null | src/test/testmain.cxx | fermi-lat/Event | 2e9e8ee117f61c4b1abde69828a97f94ff84630a | [
"BSD-3-Clause"
] | null | null | null | src/test/testmain.cxx | fermi-lat/Event | 2e9e8ee117f61c4b1abde69828a97f94ff84630a | [
"BSD-3-Clause"
] | null | null | null | #include "Event/TopLevel/EventModel.h"
#include "geometry/Vector.h"
#include "Event/Utilities/TimeStamp.h"
#include <iostream>
/// return non-zero on success
int main(){
return 0;
}
| 16.909091 | 38 | 0.725806 | fermi-lat |
17d34e71d4614171110adbde4c5970176be21c73 | 2,130 | hpp | C++ | embedded/src/fsw/FCCode/MissionManager_a.hpp | CornellDataScience/self-driving-car | 449044840abdeed9f547a16cd192950e23ba189c | [
"MIT"
] | 3 | 2021-09-29T21:15:25.000Z | 2021-11-11T20:57:07.000Z | embedded/src/fsw/FCCode/MissionManager_a.hpp | CornellDataScience/self-driving-car | 449044840abdeed9f547a16cd192950e23ba189c | [
"MIT"
] | 44 | 2021-09-28T05:38:43.000Z | 2022-03-31T21:29:48.000Z | embedded/src/fsw/FCCode/MissionManager_a.hpp | CornellDataScience/self-driving-car | 449044840abdeed9f547a16cd192950e23ba189c | [
"MIT"
] | 1 | 2020-12-23T03:32:11.000Z | 2020-12-23T03:32:11.000Z | #ifndef MISSION_MANAGER_A_HPP_
#define MISSION_MANAGER_A_HPP_
#include "TimedControlTask.hpp"
#include "mission_mode_t.enum"
#include "adcs_mode_t.enum"
class MissionManager_a : public TimedControlTask<void> {
public:
MissionManager_a(StateFieldRegistry& registry, unsigned int offset);
void execute() override;
protected:
void set_mission_mode(mission_mode_t mode);
void calibrate_data();
void dispatch_warmup();
void dispatch_initialization();
void pause();
void tvc();
void dispatch_landed();
// Fields that control overall mission state.
/**
* @brief Current mission mode (see mission_mode_t.enum)
*/
InternalStateField<unsigned char> mission_mode_f;
InternalStateField<lin::Vector3f> acc_error_f;
InternalStateField<lin::Vector4d> init_quat_d;
InternalStateField<lin::Vector3d> euler_deg;
InternalStateField<lin::Vector2f> init_lat_long_f;
InternalStateField<float> ground_level_f;
InternalStateField<bool> engine_on_f;
InternalStateField<bool> servo_on_f;
InternalStateField<float> agl_alt_f;
InternalStateField<int> count;
InternalStateField<double> init_global_roll;
InternalStateField<float>* alt_fp;
InternalStateField<lin::Vector3f>* acc_vec_fp;
InternalStateField<lin::Vector4d>* quat_fp;
InternalStateField<lin::Vector2f>* lat_long_fp;
InternalStateField<lin::Vector3f>* lin_acc_vec_fp;
InternalStateField<lin::Vector3f>* omega_vec_fp;
InternalStateField<lin::Vector3f>* mag_vec_fp;
InternalStateField<unsigned char>* sys_cal;
InternalStateField<unsigned char>* gyro_cal;
InternalStateField<unsigned char>* accel_cal;
InternalStateField<unsigned char>* mag_cal;
long enter_init_millis;
int enter_init_ccno;
long enter_flight_millis;
int enter_freefall_cnno;
int pause_ccno;
//long enter_bellyflop_millis;
// long enter_standby_millis;
};
#endif
| 31.791045 | 76 | 0.686385 | CornellDataScience |
17d6544d9e02d7958f2e201d0bd853b43cbbd20e | 2,818 | hpp | C++ | vendor/bela/include/bela/env.hpp | rdp-studio/baulk | 39feb4914dc1b7a572b9a80cac13a906d637046e | [
"MIT"
] | 3 | 2019-03-19T09:24:09.000Z | 2021-05-17T11:21:24.000Z | vendor/bela/include/bela/env.hpp | rdp-studio/Privexec | 472c05b808965d82151828a0ec5ee846b5ca86db | [
"MIT"
] | null | null | null | vendor/bela/include/bela/env.hpp | rdp-studio/Privexec | 472c05b808965d82151828a0ec5ee846b5ca86db | [
"MIT"
] | 1 | 2019-11-20T05:11:30.000Z | 2019-11-20T05:11:30.000Z | /// Env helper
#ifndef BELA_ENV_HPP
#define BELA_ENV_HPP
#include <string>
#include <string_view>
#include <shared_mutex>
#include "match.hpp"
#include "str_split.hpp"
#include "str_join.hpp"
#include "span.hpp"
#include "phmap.hpp"
#include "base.hpp"
namespace bela {
constexpr const wchar_t Separator = L';';
constexpr const std::wstring_view Separators = L";";
template <DWORD Len = 256> bool LookupEnv(std::wstring_view key, std::wstring &val) {
val.resize(Len);
auto len = GetEnvironmentVariableW(key.data(), val.data(), Len);
if (len == 0) {
return !(GetLastError() == ERROR_ENVVAR_NOT_FOUND);
}
if (len < Len) {
val.resize(len);
return true;
}
val.resize(len);
auto nlen = GetEnvironmentVariableW(key.data(), val.data(), len);
if (nlen < len) {
val.resize(nlen);
}
return true;
}
// GetEnv You should set the appropriate size for the initial allocation
// according to your needs.
// https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-getenvironmentvariable
template <DWORD Len = 256> std::wstring GetEnv(std::wstring_view key) {
std::wstring val;
bela::LookupEnv<Len>(key, val);
return val;
}
inline void MakePathEnv(std::vector<std::wstring> &paths) {
auto systemroot = bela::GetEnv(L"SystemRoot");
auto system32_env = bela::StringCat(systemroot, L"\\System32");
paths.emplace_back(system32_env); // C:\\Windows\\System32
paths.emplace_back(systemroot); // C:\\Windows
paths.emplace_back(bela::StringCat(system32_env, L"\\Wbem")); // C:\\Windows\\System32\\Wbem
// C:\\Windows\\System32\\WindowsPowerShell\\v1.0
paths.emplace_back(bela::StringCat(system32_env, L"\\WindowsPowerShell\\v1.0"));
}
std::wstring WindowsExpandEnv(std::wstring_view sv);
std::wstring PathUnExpand(std::wstring_view sv);
template <typename Range> std::wstring JoinEnv(const Range &range) {
return bela::strings_internal::JoinRange(range, Separators);
}
template <typename T> std::wstring JoinEnv(std::initializer_list<T> il) {
return bela::strings_internal::JoinRange(il, Separators);
}
template <typename... T> std::wstring JoinEnv(const std::tuple<T...> &value) {
return bela::strings_internal::JoinAlgorithm(value, Separators, AlphaNumFormatter());
}
template <typename... Args> std::wstring InsertEnv(std::wstring_view key, Args... arg) {
std::wstring_view svv[] = {arg...};
auto prepend = bela::JoinEnv(svv);
auto val = bela::GetEnv(key);
return bela::StringCat(prepend, Separators, val);
}
template <typename... Args> std::wstring AppendEnv(std::wstring_view key, Args... arg) {
std::wstring_view svv[] = {arg...};
auto ended = bela::JoinEnv(svv);
auto val = bela::GetEnv(key);
return bela::StringCat(val, Separators, ended);
}
} // namespace bela
#endif
| 32.390805 | 97 | 0.694819 | rdp-studio |
17d744b490831419ed1ed3326f534eb3cbe53938 | 4,712 | cc | C++ | src/automaton/examples/network/node_prototype.cc | liberatix/automaton-core | 0e36bd5b616a308ea319a791b11f68df879f4571 | [
"MIT"
] | null | null | null | src/automaton/examples/network/node_prototype.cc | liberatix/automaton-core | 0e36bd5b616a308ea319a791b11f68df879f4571 | [
"MIT"
] | null | null | null | src/automaton/examples/network/node_prototype.cc | liberatix/automaton-core | 0e36bd5b616a308ea319a791b11f68df879f4571 | [
"MIT"
] | null | null | null | #include "automaton/examples/network/node_prototype.h"
#include "automaton/core/io/io.h"
namespace acn = automaton::core::network;
/// Node's connection handler
node::handler::handler(node* n): node_(n) {}
void node::handler::on_message_received(acn::connection* c, char* buffer,
uint32_t bytes_read, uint32_t id) {
std::string message = std::string(buffer, bytes_read);
// logging("Message \"" + message + "\" received in <" + c->get_address() + ">");
if (std::stoul(message) > node_->height) {
node_->height = std::stoul(message);
node_->send_height();
}
c -> async_read(buffer, 16, 0, 0);
}
void node::handler::on_message_sent(acn::connection* c, uint32_t id,
acn::connection::error e) {
if (e) {
LOG(ERROR) << "Message with id " << std::to_string(id) << " was NOT sent to " <<
c->get_address() << "\nError " << std::to_string(e);
} else {
// logging("Message with id " + std::to_string(id) + " was successfully sent to " +
// c->get_address());
}
}
void node::handler::on_connected(acn::connection* c) {
c->async_read(node_->add_buffer(16), 16, 0, 0);
}
void node::handler::on_disconnected(acn::connection* c) {
// logging("Disconnected with: " + c->get_address());
}
void node::handler::on_error(acn::connection* c,
acn::connection::error e) {
if (e == acn::connection::no_error) {
return;
}
LOG(ERROR) << "Error: " << std::to_string(e) << " (connection " << c->get_address() << ")";
}
/// Node's acceptor handler
node::lis_handler::lis_handler(node* n):node_(n) {}
bool node::lis_handler::on_requested(acn::acceptor* a, const std::string& address) {
// EXPECT_EQ(address, address_a);
// logging("Connection request from: " + address + ". Accepting...");
return node_->accept_connection(/*address*/);
}
void node::lis_handler::on_connected(acn::acceptor* a, acn::connection* c,
const std::string& address) {
// logging("Accepted connection from: " + address);
node_->peers[node_->get_next_peer_id()] = c;
c->async_read(node_->add_buffer(16), 16, 0, 0);
}
void node::lis_handler::on_error(acn::acceptor* a, acn::connection::error e) {
LOG(ERROR) << std::to_string(e);
}
/// Node
node::node() {
height = 0;
peer_ids = 0;
handler_ = new handler(this);
lis_handler_ = new lis_handler(this);
}
node::~node() {
for (int i = 0; i < buffers.size(); ++i) {
delete [] buffers[i];
}
// TODO(kari): delete all acceptors and connections
}
char* node::add_buffer(uint32_t size) {
std::lock_guard<std::mutex> lock(buffer_mutex);
buffers.push_back(new char[size]);
return buffers[buffers.size() - 1];
}
/// This function is created because the acceptor needs ids for the connections it accepts
uint32_t node::get_next_peer_id() {
return ++peer_ids;
}
bool node::accept_connection() { return true; }
bool node::add_peer(uint32_t id, const std::string& connection_type, const std::string& address) {
auto it = peers.find(id);
if (it != peers.end()) {
// delete it->second; /// Delete existing acceptor
}
acn::connection* new_connection;
try {
new_connection = acn::connection::create(connection_type, address,
handler_);
} catch (std::exception& e) {
LOG(ERROR) << e.what();
peers[id] = nullptr;
return false;
}
if (!new_connection) {
LOG(ERROR) << "Connection was not created!"; // Possible reason: tcp_init was never called
return false;
}
peers[id] = new_connection;
new_connection->connect();
return true;
}
void node::remove_peer(uint32_t id) {
auto it = peers.find(id);
if (it != peers.end()) {
peers.erase(it);
}
}
bool node::add_acceptor(uint32_t id, const std::string& connection_type,
const std::string& address) {
auto it = acceptors.find(id);
if (it != acceptors.end()) {
// delete it->second; /// Delete existing acceptor
}
acn::acceptor* new_acceptor;
try {
new_acceptor = acn::acceptor::create(connection_type, address,
lis_handler_, handler_);
} catch (std::exception& e) {
LOG(ERROR) << e.what();
acceptors[id] = nullptr;
return false;
}
if (!new_acceptor) {
LOG(ERROR) << "Acceptor was not created!";
return false;
}
acceptors[id] = new_acceptor;
new_acceptor->start_accepting();
return true;
}
void node::remove_acceptor(uint32_t id) {
auto it = acceptors.find(id);
if (it != acceptors.end()) {
acceptors.erase(it);
}
}
void node::send_height(uint32_t connection_id) {
if (!connection_id) {
for (auto it = peers.begin(); it != peers.end(); ++it) {
// TODO(kari): if connected
it->second->async_send(std::to_string(height), 0);
}
} else {
peers[connection_id]->async_send(std::to_string(height), 0);
}
}
| 30.597403 | 98 | 0.647071 | liberatix |
17d8c4394bf3d379ec772376c3523b82b649f910 | 739 | cxx | C++ | cgv/gui/gui_creator.cxx | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | 1 | 2020-07-26T10:54:41.000Z | 2020-07-26T10:54:41.000Z | cgv/gui/gui_creator.cxx | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | null | null | null | cgv/gui/gui_creator.cxx | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | null | null | null | #include "gui_creator.h"
#include <vector>
namespace cgv {
namespace gui {
std::vector<gui_creator*>& ref_gui_creators()
{
static std::vector<gui_creator*> creators;
return creators;
}
/// register a gui creator
void register_gui_creator(gui_creator* gc, const char* creator_name)
{
ref_gui_creators().push_back(gc);
}
/// create the gui for a composed structure
bool create_gui(provider* p, const std::string& label,
void* value_ptr, const std::string& value_type,
const std::string& gui_type, const std::string& options, bool* toggles)
{
for (unsigned i=0; i<ref_gui_creators().size(); ++i)
if (ref_gui_creators()[i]->create(p,label,value_ptr,value_type,gui_type,options,toggles))
return true;
return false;
}
}
} | 23.09375 | 91 | 0.728011 | IXDdev |
17db19a3320a4362a2d43ad0289f36c0ec48cb95 | 7,345 | cpp | C++ | test/pchip_test.cpp | oleg-alexandrov/math | 2137c31eb8e52129d997a76b893f71c1da0ccc5f | [
"BSL-1.0"
] | 233 | 2015-01-12T19:26:01.000Z | 2022-03-11T09:21:47.000Z | test/pchip_test.cpp | oleg-alexandrov/math | 2137c31eb8e52129d997a76b893f71c1da0ccc5f | [
"BSL-1.0"
] | 626 | 2015-02-05T18:12:27.000Z | 2022-03-20T13:19:18.000Z | test/pchip_test.cpp | oleg-alexandrov/math | 2137c31eb8e52129d997a76b893f71c1da0ccc5f | [
"BSL-1.0"
] | 243 | 2015-01-17T17:46:32.000Z | 2022-03-07T12:56:26.000Z | /*
* Copyright Nick Thompson, 2020
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include "math_unit_test.hpp"
#include <numeric>
#include <utility>
#include <random>
#include <boost/math/interpolators/pchip.hpp>
#include <boost/circular_buffer.hpp>
#include <boost/assert.hpp>
#ifdef BOOST_HAS_FLOAT128
#include <boost/multiprecision/float128.hpp>
using boost::multiprecision::float128;
#endif
using boost::math::interpolators::pchip;
template<typename Real>
void test_constant()
{
std::vector<Real> x{0,1,2,3, 9, 22, 81};
std::vector<Real> y(x.size());
for (auto & t : y) {
t = 7;
}
auto x_copy = x;
auto y_copy = y;
auto pchip_spline = pchip(std::move(x_copy), std::move(y_copy));
//std::cout << "Constant value pchip spline = " << pchip_spline << "\n";
for (Real t = x[0]; t <= x.back(); t += 0.25) {
CHECK_ULP_CLOSE(Real(7), pchip_spline(t), 2);
CHECK_ULP_CLOSE(Real(0), pchip_spline.prime(t), 2);
}
boost::circular_buffer<Real> x_buf(x.size());
for (auto & t : x) {
x_buf.push_back(t);
}
boost::circular_buffer<Real> y_buf(x.size());
for (auto & t : y) {
y_buf.push_back(t);
}
auto circular_pchip_spline = pchip(std::move(x_buf), std::move(y_buf));
for (Real t = x[0]; t <= x.back(); t += 0.25) {
CHECK_ULP_CLOSE(Real(7), circular_pchip_spline(t), 2);
CHECK_ULP_CLOSE(Real(0), pchip_spline.prime(t), 2);
}
circular_pchip_spline.push_back(x.back() + 1, 7);
CHECK_ULP_CLOSE(Real(0), circular_pchip_spline.prime(x.back()+1), 2);
}
template<typename Real>
void test_linear()
{
std::vector<Real> x{0,1,2,3};
std::vector<Real> y{0,1,2,3};
auto x_copy = x;
auto y_copy = y;
auto pchip_spline = pchip(std::move(x_copy), std::move(y_copy));
CHECK_ULP_CLOSE(y[0], pchip_spline(x[0]), 0);
CHECK_ULP_CLOSE(Real(1)/Real(2), pchip_spline(Real(1)/Real(2)), 10);
CHECK_ULP_CLOSE(y[1], pchip_spline(x[1]), 0);
CHECK_ULP_CLOSE(Real(3)/Real(2), pchip_spline(Real(3)/Real(2)), 10);
CHECK_ULP_CLOSE(y[2], pchip_spline(x[2]), 0);
CHECK_ULP_CLOSE(Real(5)/Real(2), pchip_spline(Real(5)/Real(2)), 10);
CHECK_ULP_CLOSE(y[3], pchip_spline(x[3]), 0);
x.resize(45);
y.resize(45);
for (size_t i = 0; i < x.size(); ++i) {
x[i] = i;
y[i] = i;
}
x_copy = x;
y_copy = y;
pchip_spline = pchip(std::move(x_copy), std::move(y_copy));
for (Real t = 0; t < x.back(); t += 0.5) {
CHECK_ULP_CLOSE(t, pchip_spline(t), 0);
CHECK_ULP_CLOSE(Real(1), pchip_spline.prime(t), 0);
}
x_copy = x;
y_copy = y;
// Test endpoint derivatives:
pchip_spline = pchip(std::move(x_copy), std::move(y_copy), Real(1), Real(1));
for (Real t = 0; t < x.back(); t += 0.5) {
CHECK_ULP_CLOSE(t, pchip_spline(t), 0);
CHECK_ULP_CLOSE(Real(1), pchip_spline.prime(t), 0);
}
boost::circular_buffer<Real> x_buf(x.size());
for (auto & t : x) {
x_buf.push_back(t);
}
boost::circular_buffer<Real> y_buf(x.size());
for (auto & t : y) {
y_buf.push_back(t);
}
auto circular_pchip_spline = pchip(std::move(x_buf), std::move(y_buf));
for (Real t = x[0]; t <= x.back(); t += 0.25) {
CHECK_ULP_CLOSE(t, circular_pchip_spline(t), 2);
CHECK_ULP_CLOSE(Real(1), circular_pchip_spline.prime(t), 2);
}
circular_pchip_spline.push_back(x.back() + 1, y.back()+1);
CHECK_ULP_CLOSE(Real(y.back() + 1), circular_pchip_spline(Real(x.back()+1)), 2);
CHECK_ULP_CLOSE(Real(1), circular_pchip_spline.prime(Real(x.back()+1)), 2);
}
template<typename Real>
void test_interpolation_condition()
{
for (size_t n = 4; n < 50; ++n) {
std::vector<Real> x(n);
std::vector<Real> y(n);
std::default_random_engine rd;
std::uniform_real_distribution<Real> dis(0,1);
Real x0 = dis(rd);
x[0] = x0;
y[0] = dis(rd);
for (size_t i = 1; i < n; ++i) {
x[i] = x[i-1] + dis(rd);
y[i] = dis(rd);
}
auto x_copy = x;
auto y_copy = y;
auto s = pchip(std::move(x_copy), std::move(y_copy));
//std::cout << "s = " << s << "\n";
for (size_t i = 0; i < x.size(); ++i) {
CHECK_ULP_CLOSE(y[i], s(x[i]), 2);
}
x_copy = x;
y_copy = y;
// The interpolation condition is not affected by the endpoint derivatives, even though these derivatives might be super weird:
s = pchip(std::move(x_copy), std::move(y_copy), Real(0), Real(0));
//std::cout << "s = " << s << "\n";
for (size_t i = 0; i < x.size(); ++i) {
CHECK_ULP_CLOSE(y[i], s(x[i]), 2);
}
}
}
template<typename Real>
void test_monotonicity()
{
for (size_t n = 4; n < 50; ++n) {
std::vector<Real> x(n);
std::vector<Real> y(n);
std::default_random_engine rd;
std::uniform_real_distribution<Real> dis(0,1);
Real x0 = dis(rd);
x[0] = x0;
y[0] = dis(rd);
// Monotone increasing:
for (size_t i = 1; i < n; ++i) {
x[i] = x[i-1] + dis(rd);
y[i] = y[i-1] + dis(rd);
}
auto x_copy = x;
auto y_copy = y;
auto s = pchip(std::move(x_copy), std::move(y_copy));
//std::cout << "s = " << s << "\n";
for (size_t i = 0; i < x.size() - 1; ++i) {
Real tmin = x[i];
Real tmax = x[i+1];
Real val = y[i];
CHECK_ULP_CLOSE(y[i], s(x[i]), 2);
for (Real t = tmin; t < tmax; t += (tmax-tmin)/16) {
Real greater_val = s(t);
BOOST_ASSERT(val <= greater_val);
val = greater_val;
}
}
x[0] = dis(rd);
y[0] = dis(rd);
// Monotone decreasing:
for (size_t i = 1; i < n; ++i) {
x[i] = x[i-1] + dis(rd);
y[i] = y[i-1] - dis(rd);
}
x_copy = x;
y_copy = y;
s = pchip(std::move(x_copy), std::move(y_copy));
//std::cout << "s = " << s << "\n";
for (size_t i = 0; i < x.size() - 1; ++i) {
Real tmin = x[i];
Real tmax = x[i+1];
Real val = y[i];
CHECK_ULP_CLOSE(y[i], s(x[i]), 2);
for (Real t = tmin; t < tmax; t += (tmax-tmin)/16) {
Real lesser_val = s(t);
BOOST_ASSERT(val >= lesser_val);
val = lesser_val;
}
}
}
}
int main()
{
#if (__GNUC__ > 7) || defined(_MSC_VER) || defined(__clang__)
test_constant<float>();
test_linear<float>();
test_interpolation_condition<float>();
test_monotonicity<float>();
test_constant<double>();
test_linear<double>();
test_interpolation_condition<double>();
test_monotonicity<double>();
test_constant<long double>();
test_linear<long double>();
test_interpolation_condition<long double>();
test_monotonicity<long double>();
#ifdef BOOST_HAS_FLOAT128
test_constant<float128>();
test_linear<float128>();
#endif
#endif
return boost::math::test::report_errors();
}
| 28.803922 | 135 | 0.54663 | oleg-alexandrov |
17db4def8352c85ce6e424972c4388b60871d83f | 6,356 | cpp | C++ | src/LauncherSystem.cpp | OlivierAlgoet/angry-bricks-project | 64b368bd623eadcd814b4f27bb19e02388f8799f | [
"MIT"
] | null | null | null | src/LauncherSystem.cpp | OlivierAlgoet/angry-bricks-project | 64b368bd623eadcd814b4f27bb19e02388f8799f | [
"MIT"
] | null | null | null | src/LauncherSystem.cpp | OlivierAlgoet/angry-bricks-project | 64b368bd623eadcd814b4f27bb19e02388f8799f | [
"MIT"
] | null | null | null | #include "LauncherSystem.h"
void LauncherSystem::Update(){
std::set<Entity*> current_missile=engine_.GetEntityStream().WithTag(Component::Tag::CURRENTMISSILE); // ask for sprites, all entities containing a sprite have to use a scaled bitmap
if (current_missile.empty()){
context_.changing=true;
std::set<Entity*> missiles;
PolygonComponent * pg;
Point increment=Point((MISSILE_DST_WIDTH+MISSILE_SPACING),0);
Point new_pos;
for(int i=0;i<MISS_NR;i++){
missiles=engine_.GetEntityStream().WithTag(missile_list[i]);
std::set<Entity*>::iterator it=missiles.begin();
for(;it!=missiles.end();it++){
pg=(PolygonComponent*)(*it)->GetComponent(Component::Tag::POLYGON);
new_pos=pg->get_position()+increment;
pg->set_position(new_pos);
if(pg->get_position().x_>((MISS_NR-1)*(MISSILE_SPACING+MISSILE_DST_WIDTH))){
Point current=Point(MISSILEX,MISSILEY);
CurrentMissileComponent * curr=new CurrentMissileComponent;
(*it)->Add(curr);
engine_.UpdateEntity((*it),(*it)->GetTags(),false);
pg->set_position(current);
CircleComponent * circle =(CircleComponent*)(*it)->GetComponent(Component::Tag::CIRCLE);
if (circle!=NULL){
circle->set_pos(current);
}
}
}
}
Entity * ent=new Entity;
RandomMissile(0,Y_OFFSET,ent);
engine_.AddEntity(ent);
}
// TODO click release check & zo ja positie van muis gelijkstellen aan x,y
// als het gereleased is snelheid bepalen!
else{
std::set<Entity*>::iterator it=current_missile.begin();// onlyone missile
CurrentMissileComponent * Cm=(CurrentMissileComponent*)(*it)->GetComponent(Component::Tag::CURRENTMISSILE);
if(!Cm->fired){
PolygonComponent * pg=(PolygonComponent*)(*it)->GetComponent(Component::Tag::POLYGON);
if(!Cm->selected){
bool collision;
CircleComponent * cr=(CircleComponent*)(*it)->GetComponent(Component::Tag::CIRCLE);
// Check for collision
if (cr!=NULL){
collision=CircleCollision_(context_.mouse,cr->get_center(),cr->radius);
}else{
collision=PolyCollision_(context_.mouse,pg->get_polygon());
}
// check if we clicked
if (collision and context_.clicked){
Cm->selected=true;
Cm->ClickCorrect=context_.mouse-pg->get_position();
}
}else{
context_.changing=true;
if (context_.mouse.x_<MISSILEX){
Point current_pos=context_.mouse-Cm->ClickCorrect;
pg->set_position(current_pos); //Only set position of the polygon, the circle will only be used for the collision check so no sets are required here
}
//std::cout<<"selected!!"<<std::endl;
if(context_.released){
//std::cout<<"changing the status to fired"<<std::endl;
Cm->fired=true;
Point speed_vector=Point(MISSILEX,MISSILEY)-(context_.mouse-Cm->ClickCorrect);
Cm->speed.x_=KSPEED*speed_vector.x_;
Cm->speed.y_=KSPEED*speed_vector.y_; //KSPEED is a proportional value to play with
}
}
}
}
}
bool LauncherSystem::CircleCollision_(Point& mouse,Point& center,double radius){
double length=mouse*center;
//std::cout<<"the length is"<<length<<std::endl;
bool collision=length<radius;
//std::cout<<"collision"<<collision<<std::endl;
return collision;
}
bool LauncherSystem::PolyCollision_(Point& mouse,std::vector<Point>& poly){
/* Some ugly copy and paste was done here, not using the functions directly from TargetSystems with the goal to
keep the systems seperated for readability + future work*/
bool collision = true;
std::vector<Point> edges_poly = GetEdges(poly);
Point edge;
std::vector<Point> mouse_point{mouse}; // made a vector such that the functions don't have to be changed
// Loop through all the edges of both polygons
for (std::size_t edge_id = 0; edge_id < edges_poly.size(); edge_id++) {
edge = edges_poly[edge_id];
// Find perpendicular axis to current edge
Point axis(-edge.y_, edge.x_);
axis.Normalize();
// Find projection of polygon on current axis
double min_dotp_poly = 0;
double max_dotp_poly = 0;
double dotp_mouse = 0;
ProjectOnAxis(poly, axis, min_dotp_poly, max_dotp_poly);
ProjectOnAxis(mouse_point, axis, dotp_mouse, dotp_mouse); // dotp_mouse in twice for function compatibility
// Check if polygon projections overlap
if (DistanceBetweenPolys(min_dotp_poly, max_dotp_poly, dotp_mouse) > 0) {
collision = false;
break;
}
}
return collision;
}
std::vector<Point> LauncherSystem::GetEdges(std::vector<Point>& coordinates) {
std::vector<Point> edges;
Point prevPoint = coordinates[0];
for (std::size_t i = 1; i < coordinates.size(); i++) {
edges.push_back(coordinates[i] - prevPoint);
prevPoint = coordinates[i];
}
edges.push_back(coordinates[0] - prevPoint);
return edges;
}
void LauncherSystem::ProjectOnAxis(std::vector<Point>& coordinates, Point& axis, double& min, double& max) {
double dotp = coordinates[0] >> axis;
min = dotp;
max = dotp;
for (std::size_t i = 0; i < coordinates.size(); i++) {
dotp = coordinates[i] >> axis;
if (dotp < min) {
min = dotp;
}
else if (dotp > max) {
max = dotp;
}
}
}
double LauncherSystem::DistanceBetweenPolys(double min_dotp_poly, double max_dotp_poly, double dotp_mouse) {
if (min_dotp_poly < dotp_mouse) {
return dotp_mouse - max_dotp_poly;
}
else {
return min_dotp_poly - dotp_mouse;
}
}
| 39.234568 | 185 | 0.584172 | OlivierAlgoet |
17db87f2a2c464be293923a5e29a43225df7691c | 2,092 | cc | C++ | test/test_json/test_json.cc | MUCZ/meowings | 5c691f0a2fb606dad2ddda44f946a94ff8ba3212 | [
"Apache-2.0"
] | null | null | null | test/test_json/test_json.cc | MUCZ/meowings | 5c691f0a2fb606dad2ddda44f946a94ff8ba3212 | [
"Apache-2.0"
] | null | null | null | test/test_json/test_json.cc | MUCZ/meowings | 5c691f0a2fb606dad2ddda44f946a94ff8ba3212 | [
"Apache-2.0"
] | null | null | null | #include "json.hpp"
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <exception>
using json = nlohmann::json;
using namespace std;
int main(){
// 序列化
// 普通数据序列化
json js;
js["id"] = {1,2,3,4,5};
js["name"] = "zhang san";
js["msg"]["zhang san"] = "hello world";
js["msg"]["liu shuo"] = "hello from liu shuo";
cout << js <<endl;
// 容器序列化
json js_;
vector<int> vec{1,2,5};
js_["list"] = vec;
map<int,string> m{{1,"一"},{2,"二"},{3,"三"}};
js_["num"] = m;
cout << js_ <<endl;
// 显式dump
cout << js_.dump()<<endl;
// 反序列化
cout << endl;
string json_str = js.dump();
cout << "receive: " << json_str<<endl;
json js2_parsed = json::parse(json_str);
// 允许空格、回车等
json js3_parsed = json::parse("{\"msgid\":4,\"id\": 540000 } \n");
cout << "allow some noise like \\n and space" << js3_parsed.dump() <<endl;
// 可以使用find检查键
cout << "json above has id "<<(js3_parsed.find("id")!=js3_parsed.end() )<< endl;
cout << "json above has name "<<(js3_parsed.find("name")!=js3_parsed.end()) << endl;
// 反序列化get为string
json js_ex ;
js_ex["msg"] = "message";
string js_ex_str = js_ex.dump();
json js_ex_r = json::parse( js_ex_str);
cout <<"use [\"tag\"] directly : "<< js_ex_r["msg"] << endl;
cout <<"use get<string> : "<< js_ex_r["msg"].get<string>()<< endl;
// 单个变量
auto name = js2_parsed["name"];
cout << "name: " << name <<endl;
// 容器
auto v = js2_parsed["id"];
cout << "id : ";
for(const auto& x : v){
cout << x << " ";
}
cout << endl;
// 容器
map<string,string> name_sentence = js2_parsed["msg"];
for(const auto& x : name_sentence){
cout << x.first << " : " <<x.second<<endl;
}
cout <<endl;
// 多个json : 不行
try{
string two_js_str = js_ex.dump();
two_js_str += js_ex.dump();
cout << two_js_str <<endl;
json two_js = json::parse(two_js_str);
} catch (exception E){
cout << E.what()<<endl;
}
} | 23.244444 | 88 | 0.526769 | MUCZ |
17dfc870e343d123b3ce267aeb5897ba3c3fba06 | 9,698 | hpp | C++ | kernel/src/ext_pool_t.hpp | CrackerCat/hypervisor | d8876dd605e27a4eddcd4ff4b2d0cf23374c872a | [
"MIT"
] | null | null | null | kernel/src/ext_pool_t.hpp | CrackerCat/hypervisor | d8876dd605e27a4eddcd4ff4b2d0cf23374c872a | [
"MIT"
] | null | null | null | kernel/src/ext_pool_t.hpp | CrackerCat/hypervisor | d8876dd605e27a4eddcd4ff4b2d0cf23374c872a | [
"MIT"
] | null | null | null | /// @copyright
/// Copyright (C) 2020 Assured Information Security, Inc.
///
/// @copyright
/// 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:
///
/// @copyright
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// @copyright
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
#ifndef EXT_POOL_T_HPP
#define EXT_POOL_T_HPP
#include <bsl/array.hpp>
#include <bsl/as_const.hpp>
#include <bsl/debug.hpp>
#include <bsl/errc_type.hpp>
#include <bsl/finally.hpp>
#include <bsl/move.hpp>
#include <bsl/touch.hpp>
#include <bsl/unlikely.hpp>
namespace mk
{
/// @class mk::ext_pool_t
///
/// <!-- description -->
/// @brief TODO
///
/// <!-- template parameters -->
/// @tparam EXT_CONCEPT the type of ext_t that this class manages.
/// @tparam INTRINSIC_CONCEPT defines the type of intrinsics to use
/// @tparam PAGE_POOL_CONCEPT defines the type of page pool to use
/// @tparam ROOT_PAGE_TABLE_CONCEPT defines the type of RPT pool to use
/// @tparam MAX_EXTENSIONS the max number of extensions supported
///
template<
typename EXT_CONCEPT,
typename INTRINSIC_CONCEPT,
typename PAGE_POOL_CONCEPT,
typename ROOT_PAGE_TABLE_CONCEPT,
bsl::uintmax MAX_EXTENSIONS>
class ext_pool_t final
{
/// @brief stores a reference to the intrinsics to use
INTRINSIC_CONCEPT &m_intrinsic;
/// @brief stores a reference to the page pool to use
PAGE_POOL_CONCEPT &m_page_pool;
/// @brief stores system RPT provided by the loader
ROOT_PAGE_TABLE_CONCEPT &m_system_rpt;
/// @brief stores all of the extensions.
bsl::array<EXT_CONCEPT, MAX_EXTENSIONS> m_ext_pool;
public:
/// @brief an alias for EXT_CONCEPT
using ext_type = EXT_CONCEPT;
/// @brief an alias for INTRINSIC_CONCEPT
using intrinsic_type = INTRINSIC_CONCEPT;
/// @brief an alias for PAGE_POOL_CONCEPT
using page_pool_type = PAGE_POOL_CONCEPT;
/// @brief an alias for ROOT_PAGE_TABLE_CONCEPT
using root_page_table_type = ROOT_PAGE_TABLE_CONCEPT;
/// <!-- description -->
/// @brief Creates a ext_pool_t
///
/// <!-- inputs/outputs -->
/// @param intrinsic the intrinsics to use
/// @param page_pool the page pool to use
/// @param system_rpt the system RPT provided by the loader
///
explicit constexpr ext_pool_t(
INTRINSIC_CONCEPT &intrinsic,
PAGE_POOL_CONCEPT &page_pool,
ROOT_PAGE_TABLE_CONCEPT &system_rpt) noexcept
: m_intrinsic{intrinsic}, m_page_pool{page_pool}, m_system_rpt{system_rpt}, m_ext_pool{}
{}
/// <!-- description -->
/// @brief Initializes this ext_pool_t
///
/// <!-- inputs/outputs -->
/// @tparam EXT_ELF_FILES_CONCEPT the type of array containing the
/// ext_elf_files provided by the loader
/// @param ext_elf_files the ext_elf_files provided by the loader
/// @param online_pps the total number of PPs that are online
/// @return Returns bsl::errc_success on success, bsl::errc_failure
/// otherwise
///
template<typename EXT_ELF_FILES_CONCEPT>
[[nodiscard]] constexpr auto
initialize(EXT_ELF_FILES_CONCEPT const &ext_elf_files, bsl::safe_uint16 const &online_pps)
&noexcept -> bsl::errc_type
{
bsl::errc_type ret{};
if (bsl::unlikely(ext_elf_files.size() != m_ext_pool.size())) {
bsl::error() << "invalid ext_elf_file\n" << bsl::here();
return bsl::errc_failure;
}
bsl::finally release_on_error{[this]() noexcept -> void {
this->release();
}};
for (auto const ext : m_ext_pool) {
if (ext_elf_files.at_if(ext.index)->empty()) {
break;
}
ret = ext.data->initialize(
&m_intrinsic,
&m_page_pool,
bsl::to_u16(ext.index),
*ext_elf_files.at_if(ext.index),
online_pps,
&m_system_rpt);
if (bsl::unlikely(!ret)) {
bsl::print<bsl::V>() << bsl::here();
return bsl::errc_failure;
}
bsl::touch();
}
release_on_error.ignore();
return bsl::errc_success;
}
/// <!-- description -->
/// @brief Release the ext_pool_t
///
constexpr void
release() &noexcept
{
for (auto const ext : m_ext_pool) {
ext.data->release();
}
}
/// <!-- description -->
/// @brief Destroyes a previously created ext_pool_t
///
constexpr ~ext_pool_t() noexcept = default;
/// <!-- description -->
/// @brief copy constructor
///
/// <!-- inputs/outputs -->
/// @param o the object being copied
///
constexpr ext_pool_t(ext_pool_t const &o) noexcept = delete;
/// <!-- description -->
/// @brief move constructor
///
/// <!-- inputs/outputs -->
/// @param o the object being moved
///
constexpr ext_pool_t(ext_pool_t &&o) noexcept = default;
/// <!-- description -->
/// @brief copy assignment
///
/// <!-- inputs/outputs -->
/// @param o the object being copied
/// @return a reference to *this
///
[[maybe_unused]] constexpr auto operator=(ext_pool_t const &o) &noexcept
-> ext_pool_t & = delete;
/// <!-- description -->
/// @brief move assignment
///
/// <!-- inputs/outputs -->
/// @param o the object being moved
/// @return a reference to *this
///
[[maybe_unused]] constexpr auto operator=(ext_pool_t &&o) &noexcept
-> ext_pool_t & = default;
/// <!-- description -->
/// @brief Starts this ext_pool_t by calling all of the
/// extension's _start entry points.
///
/// <!-- inputs/outputs -->
/// @tparam TLS_CONCEPT defines the type of TLS block to use
/// @param tls the current TLS block
/// @return Returns bsl::errc_success on success, bsl::errc_failure
/// otherwise
///
template<typename TLS_CONCEPT>
[[nodiscard]] constexpr auto
start(TLS_CONCEPT &tls) &noexcept -> bsl::errc_type
{
for (auto const ext : m_ext_pool) {
if (bsl::unlikely(!ext.data->start(tls))) {
bsl::print<bsl::V>() << bsl::here();
return bsl::errc_failure;
}
bsl::touch();
}
return bsl::errc_success;
}
/// <!-- description -->
/// @brief Bootstraps this ext_pool_t by calling all of the
/// registered bootstrap callbacks for each extension.
///
/// <!-- inputs/outputs -->
/// @tparam TLS_CONCEPT defines the type of TLS block to use
/// @param tls the current TLS block
/// @return Returns bsl::errc_success on success, bsl::errc_failure
/// otherwise
///
template<typename TLS_CONCEPT>
[[nodiscard]] constexpr auto
bootstrap(TLS_CONCEPT &tls) &noexcept -> bsl::errc_type
{
for (auto const ext : m_ext_pool) {
if (bsl::unlikely(!ext.data->bootstrap(tls))) {
bsl::print<bsl::V>() << bsl::here();
return bsl::errc_failure;
}
bsl::touch();
}
if (bsl::unlikely(nullptr == tls.ext_vmexit)) {
bsl::error() << "a vmexit handler has not been registered" // --
<< bsl::endl // --
<< bsl::here(); // --
return bsl::errc_failure;
}
if (bsl::unlikely(nullptr == tls.ext_fail)) {
bsl::error() << "a fast fail handler has not been registered" // --
<< bsl::endl // --
<< bsl::here(); // --
return bsl::errc_failure;
}
return bsl::errc_success;
}
};
}
#endif
| 36.186567 | 100 | 0.543102 | CrackerCat |
17e09d95d39bcd1b148b39c9853cafe1a89aa818 | 3,361 | cpp | C++ | Source/AllProjects/Drivers/LutronHW/Client/LutronHWC_Data.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/Drivers/LutronHW/Client/LutronHWC_Data.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/Drivers/LutronHW/Client/LutronHWC_Data.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | // ----------------------------------------------------------------------------
// FILE: LutronHWC_Data.cpp
// DATE: Fri, Feb 12 21:14:17 2021 -0500
//
// This file was generated by the Charmed Quark CIDIDL compiler. Do not make
// changes by hand, because they will be lost if the file is regenerated.
// ----------------------------------------------------------------------------
#include "LutronHWC_.hpp"
const TString kLutronHWC::strAttr_Addr(L"/Attr/Addr");
const TString kLutronHWC::strAttr_Name(L"/Attr/Name");
const TString kLutronHWC::strAttr_Number(L"/Attr/Number");
static TEnumMap::TEnumValItem aeitemValues_EListCols[4] =
{
{ tCIDLib::TInt4(tLutronHWC::EListCols::Type), 0, 0, { L"", L"", L"", L"Type", L"EListCols::Type", L"" } }
, { tCIDLib::TInt4(tLutronHWC::EListCols::Name), 0, 0, { L"", L"", L"", L"Name", L"EListCols::Name", L"" } }
, { tCIDLib::TInt4(tLutronHWC::EListCols::Address), 0, 0, { L"", L"", L"", L"Address", L"EListCols::Address", L"" } }
, { tCIDLib::TInt4(tLutronHWC::EListCols::Number), 0, 0, { L"", L"", L"", L"Number", L"EListCols::Number", L"" } }
};
static TEnumMap emapEListCols
(
L"EListCols"
, 4
, kCIDLib::False
, aeitemValues_EListCols
, nullptr
, tCIDLib::TCard4(tLutronHWC::EListCols::Count)
);
const TString& tLutronHWC::strXlatEListCols(const tLutronHWC::EListCols eVal, const tCIDLib::TBoolean bThrowIfNot)
{
return emapEListCols.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::BaseName, bThrowIfNot);
}
tLutronHWC::EListCols tLutronHWC::eXlatEListCols(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot)
{
return tLutronHWC::EListCols(emapEListCols.i4MapEnumText(strVal, TEnumMap::ETextVals::BaseName, bThrowIfNot));
}
tCIDLib::TBoolean tLutronHWC::bIsValidEnum(const tLutronHWC::EListCols eVal)
{
return emapEListCols.bIsValidEnum(tCIDLib::TCard4(eVal));
}
static TEnumMap::TEnumValItem aeitemValues_EItemTypes[3] =
{
{ tCIDLib::TInt4(tLutronHWC::EItemTypes::Button), 0, 0, { L"", L"", L"", L"Button", L"EItemTypes::Button", L"" } }
, { tCIDLib::TInt4(tLutronHWC::EItemTypes::Dimmer), 0, 0, { L"", L"", L"", L"Dimmer", L"EItemTypes::Dimmer", L"" } }
, { tCIDLib::TInt4(tLutronHWC::EItemTypes::LED), 0, 0, { L"", L"", L"", L"LED", L"EItemTypes::LED", L"" } }
};
static TEnumMap emapEItemTypes
(
L"EItemTypes"
, 3
, kCIDLib::False
, aeitemValues_EItemTypes
, nullptr
, tCIDLib::TCard4(tLutronHWC::EItemTypes::Count)
);
const TString& tLutronHWC::strXlatEItemTypes(const tLutronHWC::EItemTypes eVal, const tCIDLib::TBoolean bThrowIfNot)
{
return emapEItemTypes.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::BaseName, bThrowIfNot);
}
tLutronHWC::EItemTypes tLutronHWC::eXlatEItemTypes(const TString& strVal, const tCIDLib::TBoolean bThrowIfNot)
{
return tLutronHWC::EItemTypes(emapEItemTypes.i4MapEnumText(strVal, TEnumMap::ETextVals::BaseName, bThrowIfNot));
}
TTextOutStream& tLutronHWC::operator<<(TTextOutStream& strmTar, const tLutronHWC::EItemTypes eVal)
{
strmTar << emapEItemTypes.strMapEnumVal(tCIDLib::TCard4(eVal), TEnumMap::ETextVals::BaseName, kCIDLib::False);
return strmTar;
}
tCIDLib::TBoolean tLutronHWC::bIsValidEnum(const tLutronHWC::EItemTypes eVal)
{
return emapEItemTypes.bIsValidEnum(tCIDLib::TCard4(eVal));
}
| 36.532609 | 121 | 0.670336 | MarkStega |
17e0f92fc682d0d6b0286805d29cbb9d30e9e58e | 2,434 | cpp | C++ | src/python/plugin.cpp | mfontanini/pirulo | 69ad5a9a9f51e1ca40fd9be4ddc560022179426c | [
"BSD-2-Clause"
] | null | null | null | src/python/plugin.cpp | mfontanini/pirulo | 69ad5a9a9f51e1ca40fd9be4ddc560022179426c | [
"BSD-2-Clause"
] | null | null | null | src/python/plugin.cpp | mfontanini/pirulo | 69ad5a9a9f51e1ca40fd9be4ddc560022179426c | [
"BSD-2-Clause"
] | null | null | null | #include <stdexcept>
#include <boost/python/object.hpp>
#include <boost/python/import.hpp>
#include <boost/python/exec.hpp>
#include <boost/python/dict.hpp>
#include "python/plugin.h"
#include "python/helpers.h"
#include "detail/logging.h"
#include "offset_store.h"
using std::string;
using std::vector;
using std::once_flag;
using std::call_once;
using std::runtime_error;
using boost::optional;
namespace python = boost::python;
namespace pirulo {
namespace api {
PIRULO_CREATE_LOGGER("p.python");
PythonPlugin::PythonPlugin(const string& modules_path, const string& file_path) {
helpers::initialize_python();
helpers::GILAcquirer _;
// Dirtiness taken from https://wiki.python.org/moin/boost.python/EmbeddingPython
python::dict locals;
python::object main_module = python::import("__main__");
python::object main_namespace = main_module.attr("__dict__");
locals["modules_path"] = modules_path;
locals["path"] = file_path;
try {
python::exec("import imp, sys, os.path\n"
"sys.path.append(os.path.abspath(modules_path))\n"
"module_name = os.path.basename(path)[:-3]\n"
"module = imp.load_module(module_name,open(path),path,('py','U',imp.PY_SOURCE))\n",
main_namespace, locals);
}
catch (const python::error_already_set& ex) {
LOG4CXX_ERROR(logger, "Failed to load module " << file_path
<< ": " << helpers::format_python_exception());
throw runtime_error("Error loading python plugin " + file_path);
}
try {
python::object plugin_factory = locals["module"].attr("create_plugin");
plugin_ = plugin_factory();
}
catch (const python::error_already_set& ex) {
LOG4CXX_ERROR(logger, "Error instantiating Plugin classs on module " << file_path
<< ": " << helpers::format_python_exception());
throw runtime_error("Error instanting python plugin " + file_path);
}
}
PythonPlugin::~PythonPlugin() {
helpers::GILAcquirer _;
plugin_ = {};
}
void PythonPlugin::initialize() {
helpers::GILAcquirer _;
try {
const StorePtr& store = get_store();
plugin_.attr("initialize")(store);
}
catch (const python::error_already_set& ex) {
LOG4CXX_ERROR(logger, "Error initializing plugin: "
<< helpers::format_python_exception());
}
}
} // api
} // pirulo
| 30.049383 | 96 | 0.653246 | mfontanini |
17e1f15ef95a3e3cf40db72888252bcd8342fe47 | 5,686 | cc | C++ | tools/baulk/context.cc | dandycheung/baulk | f0ea046bf19e494510ae61cc4633fc38877c53e4 | [
"MIT"
] | null | null | null | tools/baulk/context.cc | dandycheung/baulk | f0ea046bf19e494510ae61cc4633fc38877c53e4 | [
"MIT"
] | null | null | null | tools/baulk/context.cc | dandycheung/baulk | f0ea046bf19e494510ae61cc4633fc38877c53e4 | [
"MIT"
] | null | null | null | // baulk context
#include <version.hpp>
#include <bela/io.hpp>
#include <baulk/vfs.hpp>
#include <baulk/json_utils.hpp>
#include <baulk/fs.hpp>
#include "baulk.hpp"
namespace baulk {
namespace baulk_internal {
inline std::wstring path_expand(std::wstring_view p) {
if (p.find(L'$') != std::wstring_view::npos) {
return bela::env::PathExpand(p);
}
return bela::WindowsExpandEnv(p);
}
inline std::wstring default_locale_name() {
std::wstring s;
s.resize(64);
if (auto n = GetUserDefaultLocaleName(s.data(), 64); n != 0 && n < 64) {
s.resize(n);
return s;
}
return L"";
}
// https://github.com/baulk/bucket/commits/master.atom
constexpr std::wstring_view DefaultBucket = L"https://github.com/baulk/bucket";
} // namespace baulk_internal
class Context {
public:
Context(const Context &) = delete;
Context &operator=(const Context &) = delete;
static Context &Instance() {
static Context inst;
return inst;
}
bool Initialize(std::wstring_view profile_, bela::error_code &ec);
bool InitializeExecutor(bela::error_code &ec);
bool IsFrozenedPackage(std::wstring_view pkgName) const {
return std::find(pkgs.begin(), pkgs.end(), pkgName) != pkgs.end();
}
std::wstring_view LocaleName() const { return localeName; }
std::wstring_view Profile() const { return profile; }
auto &LoadedBuckets() { return buckets; }
auto &LinkExecutor() { return executor; }
private:
bool initializeInternal(const std::wstring &profile_, bela::error_code &ec);
Context() = default;
std::wstring localeName; // mirrors
std::wstring profile;
Buckets buckets;
std::vector<std::wstring> pkgs;
compiler::Executor executor;
};
constexpr std::wstring_view default_content = LR"({
"bucket": [
{
"description": "Baulk official bucket",
"name": "baulk",
"url": "https://github.com/baulk/bucket",
"weights": 100
}
],
"freeze": [],
"channel": "insider"
})";
bool Context::initializeInternal(const std::wstring &profile_, bela::error_code &ec) {
profile = profile_;
DbgPrint(L"Baulk use profile '%s'", profile);
auto jo = baulk::json::parse_file(profile, ec);
if (!jo) {
buckets.emplace_back(L"Baulk default bucket", L"Baulk", baulk_internal::DefaultBucket);
bela::FPrintF(stderr, L"baulk: \x1b[31m%s\x1b[0m\nprofile path %s\n", ec, profile_);
if (ec.code == ERROR_FILE_NOT_FOUND) {
baulk::fs::MakeParentDirectories(profile, ec);
bela::io::WriteText(default_content, profile, ec);
}
return true;
}
auto jv = jo->view();
localeName = jv.fetch("locale", localeName);
auto svs = jv.subviews("bucket");
for (auto sv : svs) {
buckets.emplace_back(
sv.fetch("description"), sv.fetch("name"), sv.fetch("url"), sv.fetch_as_integer("weights", 100),
static_cast<BucketObserveMode>(sv.fetch_as_integer("mode", static_cast<int>(BucketObserveMode::Github))),
static_cast<BucketVariant>(sv.fetch_as_integer("variant", static_cast<int>(BucketVariant::Native))));
if (IsDebugMode) {
auto bk = buckets.back();
DbgPrint(L"Add bucket '%s': %s", bk.name, bk.description);
DbgPrint(L" url: %s", bk.url);
DbgPrint(L" mode: %s", BucketObserveModeName(bk.mode));
DbgPrint(L" variant: %s", BucketVariantName(bk.variant));
}
}
if (jv.fetch_strings_checked("freeze", pkgs) && !pkgs.empty() && IsDebugMode) {
for (const auto &p : pkgs) {
DbgPrint(L"Freeze package %s", p);
}
}
return true;
}
bool Context::Initialize(std::wstring_view profile_, bela::error_code &ec) {
if (!baulk::vfs::InitializePathFs(ec)) {
return false;
}
localeName = baulk_internal::default_locale_name();
if (IsDebugMode) {
DbgPrint(L"Baulk %s [%s] time: %s", BAULK_VERSION, vfs::AppMode(), BAULK_BUILD_TIME);
DbgPrint(L"Baulk Location '%s'", vfs::AppLocation());
DbgPrint(L"Baulk baulk.exe '%s'", vfs::AppLocationPath(L"baulk.exe"));
DbgPrint(L"Baulk BasePath '%s'", vfs::AppBasePath());
DbgPrint(L"Baulk AppData '%s'", vfs::AppData());
DbgPrint(L"Baulk etc '%s'", vfs::AppEtc());
DbgPrint(L"Baulk AppTemp '%s'", vfs::AppTemp());
DbgPrint(L"Baulk AppPackages '%s'", vfs::AppPackages());
DbgPrint(L"Baulk AppLocks '%s'", vfs::AppLocks());
DbgPrint(L"Baulk AppBuckets '%s'", vfs::AppBuckets());
DbgPrint(L"Baulk AppLinks '%s'", vfs::AppLinks());
DbgPrint(L"Baulk Locale Name '%s'", localeName);
}
if (profile_.empty()) {
return initializeInternal(baulk::vfs::AppDefaultProfile(), ec);
}
return initializeInternal(baulk_internal::path_expand(profile_), ec);
}
bool Context::InitializeExecutor(bela::error_code &ec) { return executor.Initialize(ec); }
// global functions
bool InitializeContext(std::wstring_view profile, bela::error_code &ec) {
return Context::Instance().Initialize(profile, ec);
}
bool InitializeExecutor(bela::error_code &ec) { return Context::Instance().InitializeExecutor(ec); }
std::wstring_view LocaleName() { return Context::Instance().LocaleName(); }
std::wstring_view Profile() { return Context::Instance().Profile(); }
Buckets &LoadedBuckets() { return Context::Instance().LoadedBuckets(); }
compiler::Executor &LinkExecutor() { return Context::Instance().LinkExecutor(); }
bool IsFrozenedPackage(std::wstring_view pkgName) { return Context::Instance().IsFrozenedPackage(pkgName); }
int BucketWeights(std::wstring_view bucket) {
for (const auto &bucket_ : Context::Instance().LoadedBuckets()) {
if (bela::EqualsIgnoreCase(bucket_.name, bucket)) {
return bucket_.weights;
}
}
return 0;
}
} // namespace baulk | 35.761006 | 113 | 0.666725 | dandycheung |
17e23fd60070009ef647e04a73074839c68147a6 | 534 | cpp | C++ | pool_and_pad/padding.cpp | navneel99/image_processing_library | c4a13be8a9c7b2d7b1f6373bc6b3707d0d01be76 | [
"MIT"
] | null | null | null | pool_and_pad/padding.cpp | navneel99/image_processing_library | c4a13be8a9c7b2d7b1f6373bc6b3707d0d01be76 | [
"MIT"
] | null | null | null | pool_and_pad/padding.cpp | navneel99/image_processing_library | c4a13be8a9c7b2d7b1f6373bc6b3707d0d01be76 | [
"MIT"
] | null | null | null | #include "padding.hpp"
vector<vector<float> > Padding(vector<vector<float> > mat, int pad){
for (int j = 0;j<mat.size();j++){
vector<float> row = mat.at(j);
for (int i = 0; i<pad;i++){
row.push_back(0);
row.emplace(row.begin(),0);
}
mat[j] = row;
}
int new_row_length = mat.size() + 2 * pad;
vector<float> zero_row(new_row_length);
for (int i = 0;i<pad;i++){
mat.push_back(zero_row);
mat.emplace(mat.begin(),zero_row);
}
return mat;
} | 29.666667 | 68 | 0.533708 | navneel99 |
17e76ea19d231662c315ed05eda23231adf26c86 | 1,191 | hpp | C++ | core/test/lib/libledger-test/CppHttpLibClient.hpp | Manny27nyc/lib-ledger-core | fc9d762b83fc2b269d072b662065747a64ab2816 | [
"MIT"
] | 92 | 2016-11-13T01:28:34.000Z | 2022-03-25T01:11:37.000Z | core/test/lib/libledger-test/CppHttpLibClient.hpp | Manny27nyc/lib-ledger-core | fc9d762b83fc2b269d072b662065747a64ab2816 | [
"MIT"
] | 242 | 2016-11-28T11:13:09.000Z | 2022-03-04T13:02:53.000Z | core/test/lib/libledger-test/CppHttpLibClient.hpp | Manny27nyc/lib-ledger-core | fc9d762b83fc2b269d072b662065747a64ab2816 | [
"MIT"
] | 91 | 2017-06-20T10:35:28.000Z | 2022-03-09T14:15:40.000Z | #pragma once
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include <functional>
#include <api/HttpClient.hpp>
#include <api/HttpRequest.hpp>
#include <api/ExecutionContext.hpp>
#include <spdlog/logger.h>
#include <httplib.h>
namespace ledger {
namespace core {
namespace test {
class CppHttpLibClient : public core::api::HttpClient {
public:
CppHttpLibClient(const std::shared_ptr<core::api::ExecutionContext>& context) :
_context(context), _logger(nullptr), _generateCacheFile(false)
{};
void execute(const std::shared_ptr<core::api::HttpRequest> &request) override;
void setLogger(const std::shared_ptr<spdlog::logger>& logger) {
_logger = logger;
}
void setGenerateCacheFile(bool generateCacheFile) {
_generateCacheFile = generateCacheFile;
}
private:
std::shared_ptr<core::api::ExecutionContext> _context;
std::shared_ptr<spdlog::logger> _logger;
bool _generateCacheFile;
};
}
}
} | 28.357143 | 96 | 0.575987 | Manny27nyc |
17ebe2608250381839b77ac8344ca576667f996b | 127 | cpp | C++ | Sources/Game/Application/main.cpp | vit3k/entity_system | 5b00804bb772229cab90ea7de589faced98bc001 | [
"MIT"
] | null | null | null | Sources/Game/Application/main.cpp | vit3k/entity_system | 5b00804bb772229cab90ea7de589faced98bc001 | [
"MIT"
] | null | null | null | Sources/Game/Application/main.cpp | vit3k/entity_system | 5b00804bb772229cab90ea7de589faced98bc001 | [
"MIT"
] | null | null | null | #include "Application.h"
int main()
{
Application& app = Application::Instance();
app.Init();
app.Loop();
return 0;
} | 12.7 | 44 | 0.629921 | vit3k |
17f1536e10412892a011263ed09a218538630109 | 24,531 | cpp | C++ | tket/src/Circuit/macro_manipulation.cpp | CQCL/tket | 3f3d7c24d9a6c9cfd85966c13dcccc8a13f92adb | [
"Apache-2.0"
] | 104 | 2021-09-15T08:16:25.000Z | 2022-03-28T21:19:00.000Z | tket/src/Circuit/macro_manipulation.cpp | CQCL/tket | 3f3d7c24d9a6c9cfd85966c13dcccc8a13f92adb | [
"Apache-2.0"
] | 109 | 2021-09-16T17:14:22.000Z | 2022-03-29T06:48:40.000Z | tket/src/Circuit/macro_manipulation.cpp | CQCL/tket | 3f3d7c24d9a6c9cfd85966c13dcccc8a13f92adb | [
"Apache-2.0"
] | 8 | 2021-10-02T13:47:34.000Z | 2022-03-17T15:36:56.000Z | // Copyright 2019-2022 Cambridge Quantum Computing
//
// 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.
/////////////////////////////////////////////////////
// ALL METHODS TO PERFORM COMPLEX CIRCUIT MANIPULATION//
/////////////////////////////////////////////////////
#include <memory>
#include "Circuit.hpp"
#include "Gate/Gate.hpp"
#include "Ops/ClassicalOps.hpp"
#include "Utils/TketLog.hpp"
#include "Utils/UnitID.hpp"
namespace tket {
vertex_map_t Circuit::copy_graph(
const Circuit& c2, BoundaryMerge boundary_merge,
OpGroupTransfer opgroup_transfer) {
switch (opgroup_transfer) {
case OpGroupTransfer::Preserve:
// Fail if any collisions.
for (const auto& opgroupsig : c2.opgroupsigs) {
if (opgroupsigs.find(opgroupsig.first) != opgroupsigs.end()) {
throw CircuitInvalidity("Name collision in inserted circuit");
}
}
// Add inserted opgroups to circuit.
opgroupsigs.insert(c2.opgroupsigs.begin(), c2.opgroupsigs.end());
break;
case OpGroupTransfer::Disallow:
// Fail if any opgroups.
if (!c2.opgroupsigs.empty()) {
throw CircuitInvalidity("Named op groups in inserted circuit");
}
break;
case OpGroupTransfer::Merge:
// Fail if any mismatched signatures
for (const auto& opgroupsig : c2.opgroupsigs) {
if (opgroupsigs.find(opgroupsig.first) != opgroupsigs.end()) {
if (opgroupsigs[opgroupsig.first] != opgroupsig.second) {
throw CircuitInvalidity(
"Name signature mismatch in inserted circuit");
}
}
}
// Add inserted opgroups to circuit.
opgroupsigs.insert(c2.opgroupsigs.begin(), c2.opgroupsigs.end());
break;
default:
TKET_ASSERT(opgroup_transfer == OpGroupTransfer::Remove);
// Ignore inserted opgroups
break;
}
vertex_map_t isomap;
if (&c2 == this) {
throw Unsupported(
"Circuit Cannot currently copy itself using this method. Use * "
"instead\n");
}
BGL_FORALL_VERTICES(v, c2.dag, DAG) {
Vertex v0 = boost::add_vertex(this->dag);
this->dag[v0].op = c2.get_Op_ptr_from_Vertex(v);
if (opgroup_transfer == OpGroupTransfer::Preserve ||
opgroup_transfer == OpGroupTransfer::Merge) {
this->dag[v0].opgroup = c2.get_opgroup_from_Vertex(v);
}
isomap.insert({v, v0});
}
BGL_FORALL_VERTICES(v, c2.dag, DAG) {
EdgeVec edges = c2.get_in_edges(v);
Vertex target_v = isomap.find(v)->second;
for (EdgeVec::iterator e1 = edges.begin(); e1 != edges.end(); ++e1) {
Vertex old_source_v = c2.source(*e1);
Vertex source_v = isomap.find(old_source_v)->second;
add_edge(
{source_v, get_source_port(*e1)}, {target_v, get_target_port(*e1)},
c2.dag[*e1].type);
}
}
if (boundary_merge == BoundaryMerge::Yes) {
for (const BoundaryElement& el : c2.boundary.get<TagID>()) {
std::string reg_name = el.id_.reg_name();
register_info_t reg_type = el.reg_info();
opt_reg_info_t reg_found = get_reg_info(reg_name);
if (reg_found) {
if (reg_found.value() != reg_type) {
throw Unsupported(
"Cannot merge circuits with different types for "
"register with name: " +
reg_name);
}
boundary_t::iterator unit_found = boundary.get<TagID>().find(el.id_);
if (unit_found != boundary.get<TagID>().end()) {
throw Unsupported(
"Cannot merge circuits as both contain unit: " + el.id_.repr());
}
}
Vertex new_in = isomap[el.in_];
Vertex new_out = isomap[el.out_];
boundary.insert({el.id_, new_in, new_out});
}
}
return isomap;
}
// given two circuits, adds second circuit to first circuit object in parallel
Circuit operator*(const Circuit& c1, const Circuit& c2) {
// preliminary method to add circuit objects together
Circuit new_circ;
new_circ.copy_graph(c1);
new_circ.copy_graph(c2);
new_circ.add_phase(c1.get_phase() + c2.get_phase());
return new_circ;
}
void Circuit::append(const Circuit& c2) { append_with_map(c2, {}); }
// qm is from the units on the second (appended) circuit to the units on the
// first (this) circuit
void Circuit::append_with_map(const Circuit& c2, const unit_map_t& qm) {
Circuit copy = c2;
copy.rename_units(qm);
// Check what we need to do at the joins:
// Output --- Input ==> -------------
// Output --- Create ==> --- Reset ---
// Discard --- Input ==> [not allowed]
// Discard --- Create ==> --- Reset ---
qubit_vector_t qbs = copy.all_qubits();
std::set<Qubit> qbs_set(qbs.begin(), qbs.end());
std::set<Qubit> reset_qbs;
for (auto qb : all_qubits()) {
if (qbs_set.find(qb) != qbs_set.end()) {
if (copy.is_created(qb)) {
reset_qbs.insert(qb);
} else if (is_discarded(qb)) {
throw CircuitInvalidity("Cannot append input qubit to discarded qubit");
}
}
}
// Copy c2 into c1 but do not merge boundaries
vertex_map_t vm = copy_graph(copy, BoundaryMerge::No);
const Op_ptr noop = get_op_ptr(OpType::noop);
// Connect each matching qubit and bit, merging remainder
for (const BoundaryElement& el : copy.boundary.get<TagID>()) {
std::string reg_name = el.reg_name();
register_info_t reg_type = el.reg_info();
opt_reg_info_t reg_found = get_reg_info(reg_name);
if (reg_found) {
if (reg_found.value() != reg_type) {
throw Unsupported(
"Cannot append circuits with different types for "
"register with name: " +
reg_name);
}
boundary_t::iterator unit_found = boundary.get<TagID>().find(el.id_);
if (unit_found != boundary.get<TagID>().end()) {
Vertex out = unit_found->out_;
Vertex in = vm[el.in_];
// Update map
BoundaryElement new_elem = *unit_found;
new_elem.out_ = vm[el.out_];
boundary.replace(unit_found, new_elem);
// Tie together
if (reg_type.first == UnitType::Qubit)
add_edge({out, 0}, {in, 0}, EdgeType::Quantum);
else
add_edge({out, 0}, {in, 0}, EdgeType::Classical);
dag[out].op = noop;
dag[in].op = noop;
remove_vertex(out, GraphRewiring::Yes, VertexDeletion::Yes);
if (el.type() != UnitType::Qubit ||
reset_qbs.find(Qubit(el.id_)) == reset_qbs.end()) {
remove_vertex(in, GraphRewiring::Yes, VertexDeletion::Yes);
} else {
dag[in].op = std::make_shared<const Gate>(OpType::Reset);
}
} else {
Vertex new_in = vm[el.in_];
Vertex new_out = vm[el.out_];
boundary.insert({el.id_, new_in, new_out});
}
} else {
Vertex new_in = vm[el.in_];
Vertex new_out = vm[el.out_];
boundary.insert({el.id_, new_in, new_out});
}
}
add_phase(c2.get_phase());
}
void Circuit::append_qubits(
const Circuit& c2, const std::vector<unsigned>& qubits,
const std::vector<unsigned>& bits) {
unit_map_t qm;
for (unsigned i = 0; i < qubits.size(); i++) {
qm.insert({Qubit(i), Qubit(qubits[i])});
}
for (unsigned i = 0; i < bits.size(); i++) {
qm.insert({Bit(i), Bit(bits[i])});
}
append_with_map(c2, qm);
}
// given two circuits, adds second circuit to first sequentially by tying qubits
// together and returns a copy of this (to prevent destruction of initial
// circuits)
Circuit operator>>(const Circuit& ci1, const Circuit& ci2) {
Circuit new_circ = ci1;
new_circ.append(ci2);
return new_circ;
}
// Important substitute method. Requires knowledge of the boundary to insert
// into, and the vertices inside which are to be removed when substitution is
// performed. Gives the option to isolate the removed vertices but not delete
// them.
void Circuit::substitute(
const Circuit& to_insert, const Subcircuit& to_replace,
VertexDeletion vertex_deletion, OpGroupTransfer opgroup_transfer) {
if (!to_insert.is_simple()) throw SimpleOnly();
if (to_insert.n_qubits() != to_replace.q_in_hole.size() ||
to_insert.n_bits() != to_replace.c_in_hole.size())
throw CircuitInvalidity("Subcircuit boundary mismatch to hole");
vertex_map_t vm = copy_graph(to_insert, BoundaryMerge::No, opgroup_transfer);
VertexList bin;
EdgeSet ebin; // Needs to be a set since subcircuit to replace could be
// trivial, essentially rewiring on a cut
std::map<Edge, Vertex> c_out_map;
const Op_ptr noop = get_op_ptr(OpType::noop);
for (unsigned i = 0; i < to_replace.q_in_hole.size(); i++) {
Edge edge = to_replace.q_in_hole[i];
Vertex pred_v = source(edge);
port_t port1 = get_source_port(edge);
ebin.insert(edge);
Vertex inp = vm[to_insert.get_in(Qubit(i))];
add_edge({pred_v, port1}, {inp, 0}, EdgeType::Quantum);
dag[inp].op = noop;
bin.push_back(inp);
}
for (unsigned i = 0; i < to_replace.q_out_hole.size(); i++) {
Edge edge = to_replace.q_out_hole[i];
Vertex succ_v = target(edge);
port_t port2 = get_target_port(edge);
ebin.insert(edge);
Vertex outp = vm[to_insert.get_out(Qubit(i))];
add_edge({outp, 0}, {succ_v, port2}, EdgeType::Quantum);
dag[outp].op = noop;
bin.push_back(outp);
}
for (unsigned i = 0; i < to_replace.c_in_hole.size(); i++) {
Edge edge = to_replace.c_in_hole[i];
Vertex pred_v = source(edge);
port_t port1 = get_source_port(edge);
ebin.insert(edge);
Vertex inp = vm[to_insert.get_in(Bit(i))];
add_edge({pred_v, port1}, {inp, 0}, EdgeType::Classical);
dag[inp].op = noop;
bin.push_back(inp);
}
for (unsigned i = 0; i < to_replace.c_out_hole.size(); i++) {
Edge edge = to_replace.c_out_hole[i];
Vertex succ_v = target(edge);
port_t port2 = get_target_port(edge);
ebin.insert(edge);
Vertex outp = vm[to_insert.get_out(Bit(i))];
add_edge({outp, 0}, {succ_v, port2}, EdgeType::Classical);
dag[outp].op = noop;
bin.push_back(outp);
c_out_map.insert({edge, outp});
}
for (const Edge& e : to_replace.b_future) {
Edge c_out = get_nth_out_edge(source(e), get_source_port(e));
Vertex outp = c_out_map[c_out];
add_edge({outp, 0}, {target(e), get_target_port(e)}, EdgeType::Boolean);
ebin.insert(e);
}
for (const Edge& e : ebin) {
remove_edge(e);
}
// automatically rewire these canned vertices
remove_vertices(bin, GraphRewiring::Yes, VertexDeletion::Yes);
remove_vertices(to_replace.verts, GraphRewiring::No, vertex_deletion);
add_phase(to_insert.get_phase());
}
void Circuit::substitute(
const Circuit& to_insert, const Vertex& to_replace,
VertexDeletion vertex_deletion, OpGroupTransfer opgroup_transfer) {
Subcircuit sub = {
get_in_edges_of_type(to_replace, EdgeType::Quantum),
get_out_edges_of_type(to_replace, EdgeType::Quantum),
get_in_edges_of_type(to_replace, EdgeType::Classical),
get_out_edges_of_type(to_replace, EdgeType::Classical),
get_out_edges_of_type(to_replace, EdgeType::Boolean),
{to_replace}};
substitute(to_insert, sub, vertex_deletion, opgroup_transfer);
}
void Circuit::substitute_conditional(
Circuit to_insert, const Vertex& to_replace, VertexDeletion vertex_deletion,
OpGroupTransfer opgroup_transfer) {
Op_ptr op = get_Op_ptr_from_Vertex(to_replace);
if (op->get_type() != OpType::Conditional)
throw CircuitInvalidity(
"substitute_conditional called with an unconditional gate");
Subcircuit sub = {
get_in_edges_of_type(to_replace, EdgeType::Quantum),
get_out_edges_of_type(to_replace, EdgeType::Quantum),
get_in_edges_of_type(to_replace, EdgeType::Classical),
get_out_edges_of_type(to_replace, EdgeType::Classical),
get_out_edges_of_type(to_replace, EdgeType::Boolean),
{to_replace}};
const Conditional& cond = static_cast<const Conditional&>(*op);
unsigned width = cond.get_width();
// Conditions are first few args, so increase index of all others
bit_map_t rename_map;
for (unsigned i = 0; i < to_insert.n_bits(); ++i) {
rename_map[Bit(i)] = Bit(i + width);
}
to_insert.rename_units(rename_map);
// Extend subcircuit hole with space for condition bits
bit_vector_t cond_bits(width);
EdgeVec cond_sources;
for (unsigned i = 0; i < width; ++i) {
cond_bits[i] = Bit(i);
Edge read_in = get_nth_in_edge(to_replace, i);
Edge source_write =
get_nth_out_edge(source(read_in), get_source_port(read_in));
cond_sources.push_back(source_write);
}
sub.c_in_hole.insert(
sub.c_in_hole.begin(), cond_sources.begin(), cond_sources.end());
sub.c_out_hole.insert(
sub.c_out_hole.begin(), cond_sources.begin(), cond_sources.end());
to_insert = to_insert.conditional_circuit(cond_bits, cond.get_value());
substitute(to_insert, sub, vertex_deletion, opgroup_transfer);
}
// given the edges to be broken and new
// circuit, implants circuit into old circuit
void Circuit::cut_insert(
const Circuit& incirc, const EdgeVec& q_preds, const EdgeVec& c_preds,
const EdgeVec& b_future) {
Subcircuit sub = {q_preds, q_preds, c_preds, c_preds, b_future};
substitute(incirc, sub, VertexDeletion::No);
}
void Circuit::replace_SWAPs() {
VertexList bin;
BGL_FORALL_VERTICES(v, dag, DAG) {
if (get_Op_ptr_from_Vertex(v)->get_type() == OpType::SWAP) {
Vertex swap = v;
EdgeVec outs = get_all_out_edges(v);
Edge out1 = outs[0];
dag[out1].ports.first = 1;
Edge out2 = outs[1];
dag[out2].ports.first = 0;
remove_vertex(swap, GraphRewiring::Yes, VertexDeletion::No);
bin.push_back(swap);
}
}
remove_vertices(bin, GraphRewiring::No, VertexDeletion::Yes);
}
void Circuit::replace_implicit_wire_swap(
const Qubit first, const Qubit second) {
add_op<UnitID>(OpType::CX, {first, second});
add_op<UnitID>(OpType::CX, {second, first});
Vertex cxvertex = add_op<UnitID>(OpType::CX, {first, second});
EdgeVec outs = get_all_out_edges(cxvertex);
Edge out1 = outs[0];
dag[out1].ports.first = 1;
Edge out2 = outs[1];
dag[out2].ports.first = 0;
}
// helper functions for the dagger and transpose
void Circuit::_handle_boundaries(Circuit& circ, vertex_map_t& vmap) const {
// Handle boundaries
for (const BoundaryElement& el : this->boundary.get<TagID>()) {
Vertex new_in;
Vertex new_out;
if (el.id_.type() == UnitType::Bit) {
tket_log()->warn(
"The circuit contains classical data for which the dagger/transpose "
"might not be defined.");
new_in = circ.add_vertex(OpType::ClInput);
new_out = circ.add_vertex(OpType::ClOutput);
} else {
new_in = circ.add_vertex(OpType::Input);
new_out = circ.add_vertex(OpType::Output);
}
Vertex old_in = el.in_;
Vertex old_out = el.out_;
vmap[old_in] = new_out;
vmap[old_out] = new_in;
circ.boundary.insert({el.id_, new_in, new_out});
}
}
void Circuit::_handle_interior(
Circuit& circ, vertex_map_t& vmap, V_iterator& vi, V_iterator& vend,
ReverseType reverse_op) const {
// Handle interior
for (std::tie(vi, vend) = boost::vertices(this->dag); vi != vend; vi++) {
const Op_ptr op = get_Op_ptr_from_Vertex(*vi);
OpDesc desc = op->get_desc();
if (is_boundary_q_type(desc.type())) {
continue;
} else if ((desc.is_gate() || desc.is_box()) && !desc.is_oneway()) {
Op_ptr op_type_ptr;
switch (reverse_op) {
case ReverseType::dagger: {
op_type_ptr = op->dagger();
break;
}
case ReverseType::transpose: {
op_type_ptr = op->transpose();
break;
}
default: {
throw std::logic_error(
"Error in the definition of the dagger or transpose.");
}
}
Vertex v = circ.add_vertex(op_type_ptr);
vmap[*vi] = v;
} else {
throw CircuitInvalidity(
"Cannot dagger or transpose op: " + op->get_name());
}
}
}
void Circuit::_handle_edges(
Circuit& circ, vertex_map_t& vmap, E_iterator& ei, E_iterator& eend) const {
for (std::tie(ei, eend) = boost::edges(this->dag); ei != eend; ei++) {
Vertex s = source(*ei);
port_t sp = get_source_port(*ei);
Vertex t = target(*ei);
port_t tp = get_target_port(*ei);
circ.add_edge({vmap[t], tp}, {vmap[s], sp}, get_edgetype(*ei));
}
}
// returns Hermitian conjugate of circuit, ie its inverse
Circuit Circuit::dagger() const {
Circuit c;
vertex_map_t vmap;
_handle_boundaries(c, vmap);
V_iterator vi, vend;
ReverseType dagger = ReverseType::dagger;
_handle_interior(c, vmap, vi, vend, dagger);
E_iterator ei, eend;
_handle_edges(c, vmap, ei, eend);
c.add_phase(-get_phase());
return c;
}
// returns transpose of circuit
Circuit Circuit::transpose() const {
Circuit c;
vertex_map_t vmap;
_handle_boundaries(c, vmap);
V_iterator vi, vend;
ReverseType transpose = ReverseType::transpose;
_handle_interior(c, vmap, vi, vend, transpose);
E_iterator ei, eend;
_handle_edges(c, vmap, ei, eend);
c.add_phase(get_phase());
return c;
}
bool Circuit::substitute_all(const Circuit& to_insert, const Op_ptr op) {
if (!to_insert.is_simple()) throw SimpleOnly();
if (op->n_qubits() != to_insert.n_qubits())
throw CircuitInvalidity(
"Cannot substitute all on mismatching arity between Vertex "
"and inserted Circuit");
VertexVec to_replace;
VertexVec conditional_to_replace;
BGL_FORALL_VERTICES(v, dag, DAG) {
Op_ptr v_op = get_Op_ptr_from_Vertex(v);
if (*v_op == *op)
to_replace.push_back(v);
else if (v_op->get_type() == OpType::Conditional) {
const Conditional& cond = static_cast<const Conditional&>(*v_op);
if (*cond.get_op() == *op) conditional_to_replace.push_back(v);
}
}
for (const Vertex& v : to_replace) {
substitute(to_insert, v, VertexDeletion::Yes);
}
for (const Vertex& v : conditional_to_replace) {
substitute_conditional(to_insert, v, VertexDeletion::Yes);
}
return !(to_replace.empty() && conditional_to_replace.empty());
}
bool Circuit::substitute_named(
const Circuit& to_insert, const std::string opname) {
if (!to_insert.is_simple()) throw SimpleOnly();
// Check that no op group names are in common
for (const auto& opgroupsig : to_insert.opgroupsigs) {
if (opgroupsigs.find(opgroupsig.first) != opgroupsigs.end()) {
throw CircuitInvalidity("Name collision in replacement circuit");
}
}
// Do nothing if opname not present
if (opgroupsigs.find(opname) == opgroupsigs.end()) {
return false;
}
// Check signatures match
op_signature_t sig = opgroupsigs[opname];
unsigned sig_n_q = std::count(sig.begin(), sig.end(), EdgeType::Quantum);
unsigned sig_n_c = std::count(sig.begin(), sig.end(), EdgeType::Classical);
unsigned sig_n_b = std::count(sig.begin(), sig.end(), EdgeType::Boolean);
if (to_insert.n_qubits() != sig_n_q || to_insert.n_bits() != sig_n_c ||
sig_n_b != 0) {
throw CircuitInvalidity("Signature mismatch");
}
VertexVec to_replace;
BGL_FORALL_VERTICES(v, dag, DAG) {
std::optional<std::string> v_opgroup = get_opgroup_from_Vertex(v);
if (v_opgroup && v_opgroup.value() == opname) {
to_replace.push_back(v);
}
}
for (const Vertex& v : to_replace) {
substitute(to_insert, v, VertexDeletion::Yes, OpGroupTransfer::Merge);
}
return !to_replace.empty();
}
bool Circuit::substitute_named(Op_ptr to_insert, const std::string opname) {
// Do nothing if opname not present
if (opgroupsigs.find(opname) == opgroupsigs.end()) {
return false;
}
// Check signatures match
op_signature_t sig = opgroupsigs[opname];
if (to_insert->get_signature() != sig) {
throw CircuitInvalidity("Signature mismatch");
}
VertexVec to_replace;
BGL_FORALL_VERTICES(v, dag, DAG) {
std::optional<std::string> v_opgroup = get_opgroup_from_Vertex(v);
if (v_opgroup && v_opgroup.value() == opname) {
to_replace.push_back(v);
}
}
unsigned sig_n_q = std::count(sig.begin(), sig.end(), EdgeType::Quantum);
unsigned sig_n_c = std::count(sig.begin(), sig.end(), EdgeType::Classical);
Circuit c(sig_n_q, sig_n_c);
unit_vector_t args(sig_n_q + sig_n_c);
for (unsigned i = 0; i < sig_n_q; i++) args[i] = Qubit(i);
for (unsigned i = 0; i < sig_n_c; i++) args[sig_n_q + i] = Bit(i);
c.add_op(to_insert, args, opname);
for (const Vertex& v : to_replace) {
substitute(c, v, VertexDeletion::Yes, OpGroupTransfer::Merge);
}
return !to_replace.empty();
}
Circuit Circuit::conditional_circuit(
const bit_vector_t& bits, unsigned value) const {
if (has_implicit_wireswaps()) {
throw CircuitInvalidity("Cannot add conditions to an implicit wireswap");
}
Circuit cond_circ(all_qubits(), all_bits());
for (const Bit& b : bits) {
if (contains_unit(b)) {
Vertex in = get_in(b);
Vertex out = get_out(b);
if (get_successors_of_type(in, EdgeType::Classical).front() != out) {
throw CircuitInvalidity(
"Cannot add condition. Circuit has non-trivial "
"actions on bit " +
b.repr());
}
} else {
cond_circ.add_bit(b);
}
}
unsigned width = bits.size();
for (const Command& com : *this) {
const Op_ptr op = com.get_op_ptr();
Op_ptr cond_op = std::make_shared<Conditional>(op, width, value);
unit_vector_t args = com.get_args();
args.insert(args.begin(), bits.begin(), bits.end());
cond_circ.add_op(cond_op, args);
}
cond_circ.add_phase(get_phase());
return cond_circ;
}
bool Circuit::substitute_box_vertex(
Vertex& vert, VertexDeletion vertex_deletion) {
Op_ptr op = get_Op_ptr_from_Vertex(vert);
bool conditional = op->get_type() == OpType::Conditional;
if (conditional) {
const Conditional& cond = static_cast<const Conditional&>(*op);
op = cond.get_op();
}
if (!op->get_desc().is_box()) return false;
const Box& b = static_cast<const Box&>(*op);
Circuit replacement = *b.to_circuit();
if (conditional) {
substitute_conditional(
replacement, vert, vertex_deletion, OpGroupTransfer::Merge);
} else {
substitute(replacement, vert, vertex_deletion, OpGroupTransfer::Merge);
}
return true;
}
bool Circuit::decompose_boxes() {
bool success = false;
VertexList bin;
BGL_FORALL_VERTICES(v, dag, DAG) {
if (substitute_box_vertex(v, VertexDeletion::No)) {
bin.push_back(v);
success = true;
}
}
remove_vertices(bin, GraphRewiring::No, VertexDeletion::Yes);
return success;
}
void Circuit::decompose_boxes_recursively() {
while (decompose_boxes()) {
}
}
std::map<Bit, bool> Circuit::classical_eval(
const std::map<Bit, bool>& values) const {
std::map<Bit, bool> v(values);
for (CommandIterator it = begin(); it != end(); ++it) {
Op_ptr op = it->get_op_ptr();
OpType optype = op->get_type();
if (!is_classical_type(optype)) {
throw CircuitInvalidity("Non-classical operation");
}
std::shared_ptr<const ClassicalEvalOp> cop =
std::dynamic_pointer_cast<const ClassicalEvalOp>(op);
unit_vector_t args = it->get_args();
unsigned n_args = args.size();
switch (optype) {
case OpType::ClassicalTransform: {
std::vector<bool> input(n_args);
for (unsigned i = 0; i < n_args; i++) {
input[i] = v[Bit(args[i])];
}
std::vector<bool> output = cop->eval(input);
TKET_ASSERT(output.size() == n_args);
for (unsigned i = 0; i < n_args; i++) {
v[Bit(args[i])] = output[i];
}
break;
}
case OpType::SetBits: {
std::vector<bool> output = cop->eval({});
TKET_ASSERT(output.size() == n_args);
for (unsigned i = 0; i < n_args; i++) {
v[Bit(args[i])] = output[i];
}
break;
}
default:
throw CircuitInvalidity("Unexpected operation in circuit");
}
}
return v;
}
} // namespace tket
| 34.453652 | 80 | 0.65244 | CQCL |
17f1e8102065c9709a2510fd02afb31c828e9ec4 | 24,718 | cpp | C++ | services/hilogtool/log_controller.cpp | chaoyangcui/hiviewdfx_hilog | 19a1aab702b9038e00fe4b751d122f42065d5c95 | [
"Apache-2.0"
] | null | null | null | services/hilogtool/log_controller.cpp | chaoyangcui/hiviewdfx_hilog | 19a1aab702b9038e00fe4b751d122f42065d5c95 | [
"Apache-2.0"
] | null | null | null | services/hilogtool/log_controller.cpp | chaoyangcui/hiviewdfx_hilog | 19a1aab702b9038e00fe4b751d122f42065d5c95 | [
"Apache-2.0"
] | 1 | 2021-09-13T12:06:47.000Z | 2021-09-13T12:06:47.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "log_controller.h"
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <securec.h>
#include <stdio.h>
#include <regex>
#include "hilog/log.h"
#include "hilog_common.h"
#include "hilogtool_msg.h"
#include "seq_packet_socket_client.h"
#include "properties.h"
#include "log_display.h"
namespace OHOS {
namespace HiviewDFX {
using namespace std;
const int LOG_PERSIST_FILE_SIZE = 4 * ONE_MB;
const int LOG_PERSIST_FILE_NUM = 10;
const uint32_t DEFAULT_JOBID = 1;
void SetMsgHead(MessageHeader* msgHeader, const uint8_t msgCmd, const uint16_t msgLen)
{
if (!msgHeader) {
return;
}
msgHeader->version = 0;
msgHeader->msgType = msgCmd;
msgHeader->msgLen = msgLen;
}
void Split(const std::string& src, const std::string& separator, std::vector<std::string>& dest)
{
string str = src;
string substring;
string::size_type start = 0;
string::size_type index;
dest.clear();
index = str.find_first_of(separator, start);
if (index == string::npos) {
dest.push_back(str);
return;
}
do {
substring = str.substr(start, index - start);
dest.push_back(substring);
start = index + separator.size();
index = str.find(separator, start);
if (start == string::npos) {
break;
}
} while (index != string::npos);
substring = str.substr(start);
dest.emplace_back(substring);
}
uint16_t GetLogType(const string& logTypeStr)
{
uint16_t logType;
if (logTypeStr == "init") {
logType = LOG_INIT;
} else if (logTypeStr == "core") {
logType = LOG_CORE;
} else if (logTypeStr == "app") {
logType = LOG_APP;
} else {
return 0xffff;
}
return logType;
}
uint64_t GetBuffSize(const string& buffSizeStr)
{
uint64_t index = buffSizeStr.size() - 1;
uint64_t buffSize;
std::regex reg("[0-9]+[bBkKmMgGtT]?");
if (!std::regex_match(buffSizeStr, reg)) {
std::cout << ParseErrorCode(ERR_BUFF_SIZE_INVALID) << std::endl;
exit(-1);
}
if (buffSizeStr[index] == 'b' || buffSizeStr[index] == 'B') {
buffSize = stol(buffSizeStr.substr(0, index));
} else if (buffSizeStr[index] == 'k' || buffSizeStr[index] == 'K') {
buffSize = stol(buffSizeStr.substr(0, index)) * ONE_KB;
} else if (buffSizeStr[index] == 'm' || buffSizeStr[index] == 'M') {
buffSize = stol(buffSizeStr.substr(0, index)) * ONE_MB;
} else if (buffSizeStr[index] == 'g' || buffSizeStr[index] == 'G') {
buffSize = stol(buffSizeStr.substr(0, index)) * ONE_GB;
} else if (buffSizeStr[index] == 't' || buffSizeStr[index] == 'T') {
buffSize = stol(buffSizeStr.substr(0, index)) * ONE_TB;
} else {
buffSize = stol(buffSizeStr.substr(0, index + 1));
}
return buffSize;
}
uint16_t GetCompressAlg(const std::string& pressAlg)
{
if (pressAlg == "none") {
return COMPRESS_TYPE_NONE;
} else if (pressAlg == "zlib") {
return COMPRESS_TYPE_ZLIB;
} else if (pressAlg == "zstd") {
return COMPRESS_TYPE_ZSTD;
}
return COMPRESS_TYPE_ZLIB;
}
uint16_t GetLogLevel(const std::string& logLevelStr, std::string& logLevel)
{
if (logLevelStr == "debug" || logLevelStr == "DEBUG" || logLevelStr == "d" || logLevelStr == "D") {
logLevel = "D";
return LOG_DEBUG;
} else if (logLevelStr == "info" || logLevelStr == "INFO" || logLevelStr == "i" || logLevelStr == "I") {
logLevel = "I";
return LOG_INFO;
} else if (logLevelStr == "warn" || logLevelStr == "WARN" || logLevelStr == "w" || logLevelStr == "W") {
logLevel = "W";
return LOG_WARN;
} else if (logLevelStr == "error" || logLevelStr == "ERROR" || logLevelStr == "e" || logLevelStr == "E") {
logLevel = "E";
return LOG_ERROR;
} else if (logLevelStr == "fatal" || logLevelStr == "FATAL" || logLevelStr == "f" || logLevelStr == "F") {
logLevel = "F";
return LOG_FATAL;
}
return 0xffff;
}
string SetDefaultLogType(const std::string& logTypeStr)
{
string logType;
if (logTypeStr == "") {
logType = "core app";
} else if (logTypeStr == "all") {
logType = "core app init";
} else {
logType = logTypeStr;
}
return logType;
}
void NextRequestOp(SeqPacketSocketClient& controller, uint16_t sendId)
{
NextRequest nextRequest;
memset_s(&nextRequest, sizeof(nextRequest), 0, sizeof(nextRequest));
SetMsgHead(&nextRequest.header, NEXT_REQUEST, sizeof(NextRequest)-sizeof(MessageHeader));
nextRequest.sendId = sendId;
controller.WriteAll((char*)&nextRequest, sizeof(NextRequest));
}
void LogQueryRequestOp(SeqPacketSocketClient& controller, const HilogArgs* context)
{
LogQueryRequest logQueryRequest;
memset_s(&logQueryRequest, sizeof(LogQueryRequest), 0, sizeof(LogQueryRequest));
logQueryRequest.levels = context->levels;
logQueryRequest.types = context->types;
logQueryRequest.nPid = context->nPid;
logQueryRequest.nDomain = context->nDomain;
logQueryRequest.nTag = context->nTag;
for (int i = 0; i < context->nPid; i++) {
std::istringstream(context->pids[i]) >> std::dec >> logQueryRequest.pids[i];
}
for (int i = 0; i < context->nDomain; i++) {
std::istringstream(context->domains[i]) >> std::hex >> logQueryRequest.domains[i];
}
for (int i = 0; i < context->nTag; i++) {
if (strncpy_s(logQueryRequest.tags[i], MAX_TAG_LEN,
context->tags[i].c_str(), context->tags[i].length())) {
continue;
}
}
logQueryRequest.noLevels = context->noLevels;
logQueryRequest.noTypes = context->noTypes;
logQueryRequest.nNoPid = context->nNoPid;
logQueryRequest.nNoDomain = context->nNoDomain;
logQueryRequest.nNoTag = context->nNoTag;
for (int i = 0; i < context->nNoPid; i++) {
std::istringstream(context->noPids[i]) >> std::dec >> logQueryRequest.noPids[i];
}
for (int i = 0; i < context->nNoDomain; i++) {
std::istringstream(context->noDomains[i]) >> std::hex >> logQueryRequest.noDomains[i];
}
for (int i = 0; i < context->nNoTag; i++) {
if (strncpy_s(logQueryRequest.noTags[i], MAX_TAG_LEN,
context->noTags[i].c_str(), context->noTags[i].length())) {
continue;
}
}
SetMsgHead(&logQueryRequest.header, LOG_QUERY_REQUEST, sizeof(LogQueryRequest)-sizeof(MessageHeader));
logQueryRequest.header.version = 0;
controller.WriteAll((char*)&logQueryRequest, sizeof(LogQueryRequest));
}
void LogQueryResponseOp(SeqPacketSocketClient& controller, char* recvBuffer, uint32_t bufLen,
HilogArgs* context, HilogShowFormat format)
{
static std::vector<string> tailBuffer;
LogQueryResponse* rsp = reinterpret_cast<LogQueryResponse*>(recvBuffer);
HilogDataMessage* data = &(rsp->data);
if (data->sendId != SENDIDN) {
HilogShowLog(format, data, context, tailBuffer);
}
NextRequestOp(controller, SENDIDA);
while(1) {
memset_s(recvBuffer, bufLen, 0, bufLen);
if (controller.RecvMsg(recvBuffer, bufLen) == 0) {
fprintf(stderr, "Unexpected EOF %s\n", strerror(errno));
exit(1);
return;
}
MessageHeader* msgHeader = &(rsp->header);
if (msgHeader->msgType == NEXT_RESPONSE) {
switch (data->sendId) {
case SENDIDN:
if (context->noBlockMode) {
if (context->tailLines) {
while (context->tailLines-- && !tailBuffer.empty()) {
cout << tailBuffer.back() << endl;
tailBuffer.pop_back();
}
}
NextRequestOp(controller, SENDIDN);
exit(1);
}
break;
case SENDIDA:
HilogShowLog(format, data, context, tailBuffer);
NextRequestOp(controller, SENDIDA);
break;
default:
NextRequestOp(controller, SENDIDA);
break;
}
}
}
}
int32_t BufferSizeOp(SeqPacketSocketClient& controller, uint8_t msgCmd, const std::string& logTypeStr,
const std::string& buffSizeStr)
{
char msgToSend[MSG_MAX_LEN] = {0};
vector<string> vecLogType;
uint32_t logTypeNum;
uint32_t iter;
string logType = SetDefaultLogType(logTypeStr);
Split(logType, " ", vecLogType);
logTypeNum = vecLogType.size();
switch (msgCmd) {
case MC_REQ_BUFFER_SIZE: {
BufferSizeRequest* pBuffSizeReq = reinterpret_cast<BufferSizeRequest*>(msgToSend);
BuffSizeMsg* pBuffSizeMsg = reinterpret_cast<BuffSizeMsg*>(&pBuffSizeReq->buffSizeMsg);
if (logTypeNum * sizeof(BuffSizeMsg) + sizeof(MessageHeader) > MSG_MAX_LEN) {
return RET_FAIL;
}
for (iter = 0; iter < logTypeNum; iter++) {
pBuffSizeMsg->logType = GetLogType(vecLogType[iter]);
if (pBuffSizeMsg->logType == 0xffff) {
cout << ParseErrorCode(ERR_LOG_TYPE_INVALID) << endl;
return RET_FAIL;
}
pBuffSizeMsg++;
}
SetMsgHead(&pBuffSizeReq->msgHeader, msgCmd, sizeof(BuffSizeMsg) * logTypeNum);
controller.WriteAll(msgToSend, sizeof(MessageHeader) + sizeof(BuffSizeMsg) * logTypeNum);
break;
}
case MC_REQ_BUFFER_RESIZE: {
BufferResizeRequest* pBuffResizeReq = reinterpret_cast<BufferResizeRequest*>(msgToSend);
BuffResizeMsg* pBuffResizeMsg = reinterpret_cast<BuffResizeMsg*>(&pBuffResizeReq->buffResizeMsg);
if (logTypeNum * sizeof(BuffResizeMsg) + sizeof(MessageHeader) > MSG_MAX_LEN) {
return RET_FAIL;
}
for (iter = 0; iter < logTypeNum; iter++) {
pBuffResizeMsg->logType = GetLogType(vecLogType[iter]);
if (pBuffResizeMsg->logType == 0xffff) {
cout << ParseErrorCode(ERR_LOG_TYPE_INVALID) << endl;
return RET_FAIL;
}
pBuffResizeMsg->buffSize = GetBuffSize(buffSizeStr);
pBuffResizeMsg++;
}
SetMsgHead(&pBuffResizeReq->msgHeader, msgCmd, sizeof(BuffResizeMsg) * logTypeNum);
controller.WriteAll(msgToSend, sizeof(MessageHeader) + sizeof(BuffResizeMsg) * logTypeNum);
break;
}
default:
break;
}
return RET_SUCCESS;
}
int32_t StatisticInfoOp(SeqPacketSocketClient& controller, uint8_t msgCmd,
const std::string& logTypeStr, const std::string& domainStr)
{
if ((logTypeStr != "" && domainStr != "") || (logTypeStr == "" && domainStr == "")) {
return RET_FAIL;
}
uint16_t logType = GetLogType(logTypeStr);
uint32_t domain;
if (domainStr == "") {
domain = 0xffffffff;
if (logType == 0xffff) {
cout << ParseErrorCode(ERR_LOG_TYPE_INVALID) << endl;
return RET_FAIL;
}
} else {
std::istringstream(domainStr) >> domain;
if (domain == 0 || domain > DOMAIN_MAX_SCOPE) {
cout << ParseErrorCode(ERR_DOMAIN_INVALID) << endl;
return RET_FAIL;
}
}
switch (msgCmd) {
case MC_REQ_STATISTIC_INFO_QUERY:
StatisticInfoQueryRequest staInfoQueryReq;
memset_s(&staInfoQueryReq, sizeof(StatisticInfoQueryRequest), 0, sizeof(StatisticInfoQueryRequest));
staInfoQueryReq.logType = logType;
staInfoQueryReq.domain = domain;
SetMsgHead(&staInfoQueryReq.msgHeader, msgCmd, sizeof(StatisticInfoQueryRequest) - sizeof(MessageHeader));
controller.WriteAll((char*)&staInfoQueryReq, sizeof(StatisticInfoQueryRequest));
break;
case MC_REQ_STATISTIC_INFO_CLEAR:
StatisticInfoClearRequest staInfoClearReq;
memset_s(&staInfoClearReq, sizeof(StatisticInfoClearRequest), 0, sizeof(StatisticInfoClearRequest));
staInfoClearReq.logType = logType;
staInfoClearReq.domain = domain;
SetMsgHead(&staInfoClearReq.msgHeader, msgCmd, sizeof(StatisticInfoClearRequest) - sizeof(MessageHeader));
controller.WriteAll((char*)&staInfoClearReq, sizeof(StatisticInfoClearRequest));
break;
default:
break;
}
return RET_SUCCESS;
}
int32_t LogClearOp(SeqPacketSocketClient& controller, uint8_t msgCmd, const std::string& logTypeStr)
{
char msgToSend[MSG_MAX_LEN] = {0};
vector<string> vecLogType;
uint32_t logTypeNum;
uint32_t iter;
string logType = SetDefaultLogType(logTypeStr);
Split(logType, " ", vecLogType);
logTypeNum = vecLogType.size();
LogClearRequest* pLogClearReq = reinterpret_cast<LogClearRequest*>(msgToSend);
LogClearMsg* pLogClearMsg = reinterpret_cast<LogClearMsg*>(&pLogClearReq->logClearMsg);
if (!pLogClearMsg) {
cout << ParseErrorCode(ERR_MEM_ALLOC_FAIL) << endl;
return RET_FAIL;
}
if (logTypeNum * sizeof(LogClearMsg) + sizeof(MessageHeader) > MSG_MAX_LEN) {
cout << ParseErrorCode(ERR_MSG_LEN_INVALID) << endl;
return RET_FAIL;
}
for (iter = 0; iter < logTypeNum; iter++) {
pLogClearMsg->logType = GetLogType(vecLogType[iter]);
if (pLogClearMsg->logType == 0xffff) {
cout << ParseErrorCode(ERR_LOG_TYPE_INVALID) << endl;
return RET_FAIL;
}
pLogClearMsg++;
}
SetMsgHead(&pLogClearReq->msgHeader, msgCmd, sizeof(LogClearMsg) * logTypeNum);
controller.WriteAll(msgToSend, sizeof(LogClearMsg) * logTypeNum + sizeof(MessageHeader));
return RET_SUCCESS;
}
int32_t LogPersistOp(SeqPacketSocketClient& controller, uint8_t msgCmd, LogPersistParam* logPersistParam)
{
char msgToSend[MSG_MAX_LEN] = {0};
vector<string> vecLogType;
vector<string> vecJobId;
uint32_t logTypeNum;
uint32_t jobIdNum;
uint32_t iter;
int ret = 0;
uint32_t fileSizeDefault = LOG_PERSIST_FILE_SIZE;
uint32_t fileNumDefault = LOG_PERSIST_FILE_NUM;
string logType = SetDefaultLogType(logPersistParam->logTypeStr);
Split(logType, " ", vecLogType);
Split(logPersistParam->jobIdStr, " ", vecJobId);
logTypeNum = vecLogType.size();
jobIdNum = vecJobId.size();
switch (msgCmd) {
case MC_REQ_LOG_PERSIST_START: {
LogPersistStartRequest* pLogPersistStartReq = reinterpret_cast<LogPersistStartRequest*>(msgToSend);
LogPersistStartMsg* pLogPersistStartMsg =
reinterpret_cast<LogPersistStartMsg*>(&pLogPersistStartReq->logPersistStartMsg);
if (sizeof(LogPersistStartRequest) > MSG_MAX_LEN) {
cout << ParseErrorCode(ERR_MSG_LEN_INVALID) << endl;
return RET_FAIL;
}
for (iter = 0; iter < logTypeNum; iter++) {
uint16_t tmpType = GetLogType(vecLogType[iter]);
if (tmpType == 0xffff) {
cout << ParseErrorCode(ERR_LOG_TYPE_INVALID) << endl;
return RET_FAIL;
}
pLogPersistStartMsg->logType = (0b01 << tmpType) | pLogPersistStartMsg->logType;
}
pLogPersistStartMsg->jobId = (logPersistParam->jobIdStr == "") ? DEFAULT_JOBID
: stoi(logPersistParam->jobIdStr);
if (pLogPersistStartMsg->jobId <= 0) {
cout << ParseErrorCode(ERR_LOG_PERSIST_JOBID_INVALID) << endl;
return RET_FAIL;
}
pLogPersistStartMsg->compressAlg = (logPersistParam->compressAlgStr == "") ? COMPRESS_TYPE_ZLIB :
GetCompressAlg(logPersistParam->compressAlgStr);
pLogPersistStartMsg->fileSize = (logPersistParam->fileSizeStr == "") ? fileSizeDefault : GetBuffSize(
logPersistParam->fileSizeStr);
pLogPersistStartMsg->fileNum = (logPersistParam->fileNumStr == "") ? fileNumDefault
: stoi(logPersistParam->fileNumStr);
if (logPersistParam->fileNameStr.size() > FILE_PATH_MAX_LEN) {
cout << ParseErrorCode(ERR_LOG_PERSIST_FILE_NAME_INVALID) << endl;
return RET_FAIL;
}
if (logPersistParam->fileNameStr != " ") {
ret += strcpy_s(pLogPersistStartMsg->filePath, FILE_PATH_MAX_LEN, logPersistParam->fileNameStr.c_str());
}
SetMsgHead(&pLogPersistStartReq->msgHeader, msgCmd, sizeof(LogPersistStartRequest));
controller.WriteAll(msgToSend, sizeof(LogPersistStartRequest));
break;
}
case MC_REQ_LOG_PERSIST_STOP: {
LogPersistStopRequest* pLogPersistStopReq =
reinterpret_cast<LogPersistStopRequest*>(msgToSend);
LogPersistStopMsg* pLogPersistStopMsg =
reinterpret_cast<LogPersistStopMsg*>(&pLogPersistStopReq->logPersistStopMsg);
if (logPersistParam->jobIdStr == "") {
pLogPersistStopMsg->jobId = JOB_ID_ALL;
SetMsgHead(&pLogPersistStopReq->msgHeader, msgCmd, sizeof(LogPersistStopMsg));
controller.WriteAll(msgToSend, sizeof(LogPersistStopMsg) + sizeof(MessageHeader));
break;
}
if (jobIdNum * sizeof(LogPersistStopMsg) + sizeof(MessageHeader) > MSG_MAX_LEN) {
cout << ParseErrorCode(ERR_MSG_LEN_INVALID) << endl;
return RET_FAIL;
}
for (iter = 0; iter < jobIdNum; iter++) {
pLogPersistStopMsg->jobId = stoi(vecJobId[iter]);
pLogPersistStopMsg++;
}
SetMsgHead(&pLogPersistStopReq->msgHeader, msgCmd, sizeof(LogPersistStopMsg) * jobIdNum);
controller.WriteAll(msgToSend, sizeof(LogPersistStopMsg) * jobIdNum + sizeof(MessageHeader));
break;
}
case MC_REQ_LOG_PERSIST_QUERY: {
LogPersistQueryRequest* pLogPersistQueryReq =
reinterpret_cast<LogPersistQueryRequest*>(msgToSend);
LogPersistQueryMsg* pLogPersistQueryMsg =
reinterpret_cast<LogPersistQueryMsg*>(&pLogPersistQueryReq->logPersistQueryMsg);
for (iter = 0; iter < logTypeNum; iter++) {
uint16_t tmpType = GetLogType(vecLogType[iter]);
if (tmpType == 0xffff) {
cout << ParseErrorCode(ERR_LOG_TYPE_INVALID) << endl;
return RET_FAIL;
}
pLogPersistQueryMsg->logType = (0b01 << tmpType) | pLogPersistQueryMsg->logType;
}
SetMsgHead(&pLogPersistQueryReq->msgHeader, msgCmd, sizeof(LogPersistQueryMsg));
controller.WriteAll(msgToSend, sizeof(LogPersistQueryRequest));
break;
}
default:
break;
}
if (ret) {
return RET_FAIL;
}
return RET_SUCCESS;
}
int32_t SetPropertiesOp(SeqPacketSocketClient& controller, uint8_t operationType, SetPropertyParam* propertyParm)
{
vector<string> vecDomain;
vector<string> vecTag;
uint32_t domainNum, tagNum;
uint32_t iter;
string key, value;
Split(propertyParm->domainStr, " ", vecDomain);
Split(propertyParm->tagStr, " ", vecTag);
domainNum = vecDomain.size();
tagNum = vecTag.size();
switch (operationType) {
case OT_PRIVATE_SWITCH:
key = GetPropertyName(PROP_PRIVATE);
if (propertyParm->privateSwitchStr == "on") {
PropertySet(key.c_str(), "true");
cout << "hilog private formatter is enabled" << endl;
} else if (propertyParm->privateSwitchStr == "off") {
PropertySet(key.c_str(), "false");
cout << "hilog private formatter is disabled" << endl;
} else {
cout << ParseErrorCode(ERR_PRIVATE_SWITCH_VALUE_INVALID) << endl;
return RET_FAIL;
}
break;
case OT_LOG_LEVEL:
if (propertyParm->tagStr != "" && propertyParm->domainStr != "") {
return RET_FAIL;
} else if (propertyParm->domainStr != "") { // by domain
std::string keyPre = GetPropertyName(PROP_DOMAIN_LOG_LEVEL);
for (iter = 0; iter < domainNum; iter++) {
key = keyPre + vecDomain[iter];
if (GetLogLevel(propertyParm->logLevelStr, value) == 0xffff) {
continue;
}
PropertySet(key.c_str(), value.c_str());
cout << "domain " << vecDomain[iter] << " level is set to " << propertyParm->logLevelStr << endl;
}
} else if (propertyParm->tagStr != "") { // by tag
std::string keyPre = GetPropertyName(PROP_TAG_LOG_LEVEL);
for (iter = 0; iter < tagNum; iter++) {
key = keyPre + vecTag[iter];
if (GetLogLevel(propertyParm->logLevelStr, value) == 0xffff) {
continue;
}
PropertySet(key.c_str(), value.c_str());
cout << "tag " << vecTag[iter] << " level is set to " << propertyParm->logLevelStr << endl;
}
} else {
key = GetPropertyName(PROP_GLOBAL_LOG_LEVEL);
if (GetLogLevel(propertyParm->logLevelStr, value) == 0xffff) {
return RET_FAIL;
}
PropertySet(key.c_str(), value.c_str());
cout << "global log level is set to " << propertyParm->logLevelStr << endl;
}
break;
case OT_FLOW_SWITCH:
if (propertyParm->flowSwitchStr == "pidon") {
key = GetPropertyName(PROP_PROCESS_FLOWCTRL);
PropertySet(key.c_str(), "true");
cout << "flow control by process is enabled" << endl;
} else if (propertyParm->flowSwitchStr == "pidoff") {
key = GetPropertyName(PROP_PROCESS_FLOWCTRL);
PropertySet(key.c_str(), "false");
cout << "flow control by process is disabled" << endl;
} else if (propertyParm->flowSwitchStr == "domainon") {
key = GetPropertyName(PROP_DOMAIN_FLOWCTRL);
PropertySet(key.c_str(), "true");
cout << "flow control by domain is enabled" << endl;
} else if (propertyParm->flowSwitchStr == "domainoff") {
key = GetPropertyName(PROP_DOMAIN_FLOWCTRL);
PropertySet(key.c_str(), "false");
cout << "flow control by domain is disabled" << endl;
} else {
cout << ParseErrorCode(ERR_FLOWCTRL_SWITCH_VALUE_INVALID) << endl;
return RET_FAIL;
}
break;
default:
break;
}
return RET_SUCCESS;
}
int MultiQuerySplit(const std::string& src, const char& delim, std::vector<std::string>& vecSplit)
{
int srcSize = src.length();
int findPos = 0;
int getPos = 0;
vecSplit.clear();
while (getPos < srcSize) {
findPos = src.find(delim, findPos);
if (-1 == findPos) {
if (getPos < srcSize) {
vecSplit.push_back(src.substr(getPos, srcSize - getPos));
return 0;
}
} else if (findPos == getPos) {
vecSplit.push_back(std::string(""));
} else {
vecSplit.push_back(src.substr(getPos, findPos - getPos));
}
getPos = ++findPos;
if (getPos == srcSize) {
vecSplit.push_back(std::string(""));
return 0;
}
}
return 0;
}
} // namespace HiviewDFX
} // namespace OHOS
| 40.061588 | 120 | 0.597702 | chaoyangcui |
17f3ace54a63874f93bdd24a51fa2a1b27862747 | 1,461 | cpp | C++ | hdu/hdu1560.cpp | jiegec/oj | 492117a5e275487d49b16ec3249a2412e896682d | [
"MIT"
] | 1 | 2021-08-02T03:04:28.000Z | 2021-08-02T03:04:28.000Z | hdu/hdu1560.cpp | jiegec/oj | 492117a5e275487d49b16ec3249a2412e896682d | [
"MIT"
] | null | null | null | hdu/hdu1560.cpp | jiegec/oj | 492117a5e275487d49b16ec3249a2412e896682d | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
int bound;
bool flag;
char ch[4]={'A','C','G','T'};
int map[128];
inline int min(int a,int b){
return a>b?b:a;
}
inline int max(int a,int b){
return a>b?a:b;
}
struct D{
int k;
char s[10][10];
int cur[10];
int len[10];
int H() {
int n[4]={0};
for(int i=0;i<k;i++){
int tmp[4]={0};
for(int j=cur[i];j<len[i];j++){
tmp[map[s[i][j]]]++;
}
n[0]=max(n[0],tmp[0]);
n[1]=max(n[1],tmp[1]);
n[2]=max(n[2],tmp[2]);
n[3]=max(n[3],tmp[3]);
}
return n[0]+n[1]+n[2]+n[3];
}
}s;
int dfs(int x){
int hv=s.H();
if(x+hv>bound)
return x+hv;
if(hv==0)
return flag=true,x;
int nxt=0x7FFF,tmp;
int old[10];
memcpy(old, s.cur, sizeof(old));
for(int i=0;i<4;i++){
bool flag2=false;
for(int j=0;j<s.k;j++){
if(s.s[j][s.cur[j]]==ch[i]) {
s.cur[j]++;
flag2=true;
}
}
if(!flag2)
continue;
tmp = dfs(x+1);
if(flag)
return tmp;
if(nxt>tmp)
nxt=tmp;
memcpy(s.cur,old,sizeof(old));
}
return nxt;
}
int main() {
map['A']=0;
map['C']=1;
map['G']=2;
map['T']=3;
int N;
scanf("%d",&N);
while(N--){
flag=false;
scanf("%d",&s.k);
for(int i=0;i<s.k;i++){
scanf("%s",s.s[i]);
s.cur[i]=0;
s.len[i]=strlen(s.s[i]);
}
for(bound=s.H();!flag;bound=dfs(0));
printf("%d\n",bound);
}
}
| 16.988372 | 40 | 0.451061 | jiegec |
17f626e19eef7556be05079d97a3bcc9c7d1c7cf | 1,215 | cc | C++ | gdb/testsuite/gdb.compile/compile-cplus-nested.cc | greyblue9/binutils-gdb | 05377632b124fe7600eea7f4ee0e9a35d1b0cbdc | [
"BSD-3-Clause"
] | 1 | 2020-10-14T03:24:35.000Z | 2020-10-14T03:24:35.000Z | gdb/testsuite/gdb.compile/compile-cplus-nested.cc | greyblue9/binutils-gdb | 05377632b124fe7600eea7f4ee0e9a35d1b0cbdc | [
"BSD-3-Clause"
] | null | null | null | gdb/testsuite/gdb.compile/compile-cplus-nested.cc | greyblue9/binutils-gdb | 05377632b124fe7600eea7f4ee0e9a35d1b0cbdc | [
"BSD-3-Clause"
] | null | null | null | /* Copyright 2015-2021 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
class A
{
public:
A () : a_ (1) {}
int get ();
protected:
int a_;
private:
/* It is important to not /not/ use the nested class definition in A.
This exercises a different path through the code. */
struct Inner1
{
int a_;
Inner1 () : a_ (2) {}
struct Inner2
{
int a_;
Inner2 () : a_ (3) {}
};
};
};
int
A::get ()
{
A::Inner1 i1;
A::Inner1::Inner2 i2;
return i1.a_ + i2.a_; // break here
}
int var = 1234;
int
main ()
{
A a;
return a.get ();
}
| 20.59322 | 76 | 0.65679 | greyblue9 |
17f64fcd3b96498b8ddec8fa3dd529e46acdaba5 | 3,308 | cpp | C++ | frameworks/kits/content/cpp/src/ohos/aafwk/content/intent_filter.cpp | openharmony-gitee-mirror/aafwk_standard | 59761a67f4ebc5ea4c3282cd1262bd4a2b66faa7 | [
"Apache-2.0"
] | null | null | null | frameworks/kits/content/cpp/src/ohos/aafwk/content/intent_filter.cpp | openharmony-gitee-mirror/aafwk_standard | 59761a67f4ebc5ea4c3282cd1262bd4a2b66faa7 | [
"Apache-2.0"
] | null | null | null | frameworks/kits/content/cpp/src/ohos/aafwk/content/intent_filter.cpp | openharmony-gitee-mirror/aafwk_standard | 59761a67f4ebc5ea4c3282cd1262bd4a2b66faa7 | [
"Apache-2.0"
] | 1 | 2021-09-13T12:07:39.000Z | 2021-09-13T12:07:39.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ohos/aafwk/content/intent_filter.h"
#include "string_ex.h"
#include "ohos/aafwk/content/intent.h"
namespace OHOS {
namespace AAFwk {
IntentFilter::IntentFilter()
{}
std::string IntentFilter::GetEntity() const
{
return entity_;
}
void IntentFilter::SetEntity(const std::string &entity)
{
entity_ = entity;
}
void IntentFilter::AddAction(const std::string &action)
{
auto it = std::find(actions_.cbegin(), actions_.cend(), action);
if (it == actions_.cend()) {
actions_.push_back(action);
}
}
int IntentFilter::CountAction() const
{
return actions_.size();
}
std::string IntentFilter::GetAction(int index) const
{
std::string action;
if (index < static_cast<int>(actions_.size())) {
action = actions_[index];
}
return action;
}
void IntentFilter::RemoveAction(const std::string &action)
{
auto it = std::find(actions_.cbegin(), actions_.cend(), action);
if (it != actions_.cend()) {
actions_.erase(it);
}
}
bool IntentFilter::HasAction(const std::string &action) const
{
return std::find(actions_.cbegin(), actions_.cend(), action) != actions_.cend();
}
bool IntentFilter::Marshalling(Parcel &parcel) const
{
// write entity
if (!parcel.WriteString16(Str8ToStr16(entity_))) {
return false;
}
// write actions
std::vector<std::u16string> actionU16;
for (std::vector<std::string>::size_type i = 0; i < actions_.size(); i++) {
actionU16.push_back(Str8ToStr16(actions_[i]));
}
if (!parcel.WriteString16Vector(actionU16)) {
return false;
}
return true;
}
bool IntentFilter::ReadFromParcel(Parcel &parcel)
{
// read entity
entity_ = Str16ToStr8(parcel.ReadString16());
// read actions
std::vector<std::u16string> actionU16;
if (!parcel.ReadString16Vector(&actionU16)) {
return false;
}
actions_.clear();
for (std::vector<std::u16string>::size_type i = 0; i < actionU16.size(); i++) {
actions_.push_back(Str16ToStr8(actionU16[i]));
}
return true;
}
IntentFilter *IntentFilter::Unmarshalling(Parcel &parcel)
{
IntentFilter *filter = new (std::nothrow) IntentFilter();
if (filter && !filter->ReadFromParcel(parcel)) {
delete filter;
filter = nullptr;
}
return filter;
}
bool IntentFilter::MatchAction(const std::string &action) const
{
return HasAction(action);
}
bool IntentFilter::MatchEntity(const std::string &entity) const
{
return entity_ == entity;
}
bool IntentFilter::Match(const Intent &intent) const
{
return MatchAction(intent.GetAction()) && MatchEntity(intent.GetEntity());
}
} // namespace AAFwk
} // namespace OHOS
| 23.971014 | 84 | 0.673519 | openharmony-gitee-mirror |
17fd471e10483d78274657e2999449917ac836c3 | 4,653 | cpp | C++ | patterns/mytreeFragmentLinux.cpp | bruennijs/ise.cppworkshop | c54a60ad3468f83aeb45b347657b3f246d7190cc | [
"MIT"
] | null | null | null | patterns/mytreeFragmentLinux.cpp | bruennijs/ise.cppworkshop | c54a60ad3468f83aeb45b347657b3f246d7190cc | [
"MIT"
] | null | null | null | patterns/mytreeFragmentLinux.cpp | bruennijs/ise.cppworkshop | c54a60ad3468f83aeb45b347657b3f246d7190cc | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////
// MYTREE Linuxvariante
#include <sys/types.h>
#include <dirent.h>
#include <string>
#include <list>
#include <iostream>
#include <algorithm>
using namespace std;
////////////////////////////////////////////
class Visitor
{
public:
Visitor() {};
~Visitor() {};
virtual void visit(class Verzeichnis& v) = 0;
virtual void visit(class Datei& d) = 0;
};
// Kompositstruktur
class Datei // Komponente
{
public:
Datei( const string &n ) : name( n ) {}
virtual ~Datei();
const string & GibName() const { return name; }
virtual void accept(Visitor& visitor)
{
}
protected:
string name;
};
class Verzeichnis : public Datei // Komposite
{
public:
Verzeichnis( const string &n );
~Verzeichnis();
typedef std::list<Datei *> Dateiliste;
Dateiliste liste;
void accept(Visitor& visitor) override;
};
///////////////////////
class RegulaereDatei : public Datei // Leaf
{
public:
RegulaereDatei( const string &n ) : Datei( n ) {}
};
class GeraeteDatei : public Datei // Leaf
{
public:
GeraeteDatei( const string &n ) : Datei( n ) {}
};
class KommunikationsDatei : public Datei // Leaf
{
public:
KommunikationsDatei( const string &n ) : Datei( n ) {}
};
class SonstigeDatei : public Datei // Leaf
{
public:
SonstigeDatei( const string &n ) : Datei( n ) {}
};
////////////////////////////////////////////////////////////////////////////////
Datei::~Datei() {}
Verzeichnis::Verzeichnis( const string &n ) : Datei( n )
{
struct dirent *pde;
DIR *dirp = opendir( n.c_str() );
if( dirp != NULL )
{
while( (pde = readdir( dirp )) != NULL )
{
std::string dname( pde->d_name );
if( dname != "." && dname != ".." )
{
Datei *pd = 0;
switch( pde->d_type )
{
case DT_REG:
pd = new RegulaereDatei( dname );
break;
case DT_DIR:
{
std::string vn( n );
if( vn[vn.size() - 1] != '/' )
vn += "/";
vn += dname;
pd = new Verzeichnis( vn );
}
break;
case DT_FIFO:
case DT_SOCK:
pd = new KommunikationsDatei( dname );
break;
case DT_CHR:
case DT_BLK:
pd = new GeraeteDatei( dname );
break;
case DT_UNKNOWN:
default:
pd = new SonstigeDatei( dname );
break;
}
if( pd )
liste.push_back( pd );
}
}
closedir(dirp);
}
}
Verzeichnis::~Verzeichnis()
{
for( Dateiliste::iterator it = liste.begin(); it != liste.end(); ++it )
delete *it;
}
void Verzeichnis::accept(Visitor& visitor)
{
visitor.visit(*this);
for (auto& d : liste)
d->accept(visitor);
}
///////////////////////////////////////////////////////////////////////////////
template<typename T>
bool IsInstanceOf(const Datei* obj) noexcept {
return dynamic_cast< const T* >( obj ) != nullptr;
}
//////////////////////////
class VisitorPrintFiles : public Visitor
{
public:
VisitorPrintFiles() {};
~VisitorPrintFiles() {};
VisitorPrintFiles(VisitorPrintFiles&& rv) = delete;
void visit(Verzeichnis& v) override
{
std::cout << "verz:" << v.GibName() << std::endl;
}
void visit(Datei& d) override
{
std::cout << "datei:" << d.GibName() << std::endl;
}
};
class VisitorCountFiles : public Visitor
{
public:
VisitorCountFiles() {};
~VisitorCountFiles() {};
VisitorCountFiles(VisitorCountFiles&& rv) = delete;
void visit(Verzeichnis& v) override
{
std::cout << v.GibName() << ":" << v.liste.size() << std::endl;
}
void visit(Datei& d) override
{
std::cout << "visit.datei" << std::endl;
}
};
class VisitorRecursiveCountVerzeichnisse : public Visitor
{
public:
VisitorRecursiveCountVerzeichnisse() {};
~VisitorRecursiveCountVerzeichnisse() {};
void visit(Verzeichnis& v) override
{
//m_countFiles += std::count_if(v.liste.begin(), v.liste.end(), [](Datei* d) { return IsInstanceOf<Verzeichnis>(d); });
m_countFiles++;
}
void visit(Datei& d) override
{
}
int getCount() {
return m_countFiles;
}
private:
int m_countFiles = 0;
};
///////////////////////////////
int main( int argc, char *argv[] )
{
using namespace std;
string verz( argc > 1 ? argv[1] : "." );
VisitorPrintFiles v;
VisitorCountFiles vcf;
VisitorRecursiveCountVerzeichnisse vrcf;
Verzeichnis root( verz );
//root.accept(v);
//root.accept(vcf);
root.accept(vrcf);
std::cout << "count of all files=" << vrcf.getCount() << std::endl;
return 0;
}
| 19.227273 | 122 | 0.54395 | bruennijs |
17fe91610e2bbb02caa8236a9718cbece2f06806 | 3,164 | hpp | C++ | src/Xi-Core/include/Xi/Blob.hpp | ElSamaritan/blockchain-OLD | ca3422c8873613226db99b7e6735c5ea1fac9f1a | [
"Apache-2.0"
] | null | null | null | src/Xi-Core/include/Xi/Blob.hpp | ElSamaritan/blockchain-OLD | ca3422c8873613226db99b7e6735c5ea1fac9f1a | [
"Apache-2.0"
] | null | null | null | src/Xi-Core/include/Xi/Blob.hpp | ElSamaritan/blockchain-OLD | ca3422c8873613226db99b7e6735c5ea1fac9f1a | [
"Apache-2.0"
] | null | null | null | /* ============================================================================================== *
* *
* Galaxia Blockchain *
* *
* ---------------------------------------------------------------------------------------------- *
* This file is part of the Xi framework. *
* ---------------------------------------------------------------------------------------------- *
* *
* Copyright 2018-2019 Xi Project Developers <support.xiproject.io> *
* *
* This program is free software: you can redistribute it and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; *
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with this program. *
* If not, see <https://www.gnu.org/licenses/>. *
* *
* ============================================================================================== */
#pragma once
#include <cstring>
#include "Xi/Span.hpp"
#include "Xi/Byte.hh"
namespace Xi {
template <typename _T, size_t _Bytes>
struct enable_blob_from_this : protected ByteArray<_Bytes> {
using value_type = _T;
using array_type = ByteArray<_Bytes>;
static inline constexpr size_t bytes() { return _Bytes; }
enable_blob_from_this() { this->fill(0); }
explicit enable_blob_from_this(array_type raw) : array_type(std::move(raw)) {}
using array_type::data;
using array_type::fill;
using array_type::size;
using array_type::operator[];
ByteSpan span() { return ByteSpan{this->data(), this->size()}; }
ConstByteSpan span() const { return ConstByteSpan{this->data(), this->size()}; }
inline bool operator==(const value_type &rhs) { return ::std::memcmp(this->data(), rhs.data(), bytes()) == 0; }
inline bool operator!=(const value_type &rhs) { return ::std::memcmp(this->data(), rhs.data(), bytes()) != 0; }
};
} // namespace Xi
| 56.5 | 113 | 0.395702 | ElSamaritan |
aa05d2501398c889ec0090075642b4fa59d4b7a7 | 2,082 | cpp | C++ | Game/src/game/BulletManager.cpp | franticsoftware/vlad-heavy-strike | a4da4df617e9ccd6ebd9819ad166d892924638ce | [
"MIT"
] | 3 | 2019-10-04T19:44:44.000Z | 2021-07-27T15:59:39.000Z | Game/src/game/BulletManager.cpp | franticsoftware/vlad-heavy-strike | a4da4df617e9ccd6ebd9819ad166d892924638ce | [
"MIT"
] | 1 | 2019-07-20T05:36:31.000Z | 2019-07-20T22:22:49.000Z | Game/src/game/BulletManager.cpp | aminere/vlad-heavy-strike | a4da4df617e9ccd6ebd9819ad166d892924638ce | [
"MIT"
] | null | null | null | /*
Amine Rehioui
Created: November 18th 2011
*/
#include "ShootTest.h"
#include "BulletManager.h"
#include "GameManager.h"
namespace shoot
{
DEFINE_OBJECT(BulletManager);
//! Constructor
BulletManager::BulletManager()
// properties
: m_BulletPoolSize(4096)
{
}
//! serializes the entity to/from a PropertyStream
void BulletManager::Serialize(PropertyStream& stream)
{
super::Serialize(stream);
if(stream.Serialize(PT_UInt, "BulletPoolSize", &m_BulletPoolSize))
{
if(IsInitialized())
{
m_Pool = snew MemoryPool(m_BulletPoolSize);
m_Bullets.clear();
}
}
}
//! called during the initialization of the entity
void BulletManager::Init()
{
m_Pool = snew MemoryPool(m_BulletPoolSize);
GraphicComponent* pGraphic = GetComponent<GraphicComponent>();
if(!pGraphic)
{
pGraphic = snew GraphicComponent();
pGraphic->SetRenderingPass(GraphicComponent::RP_Transparent3D);
AddComponent(pGraphic, true);
}
super::Init();
}
//! called during the update of the entity
void BulletManager::Update()
{
VertexBuffer* pVB = GetComponent<GraphicComponent>()->GetVertexBuffer();
pVB->SetNumVertices(0);
if(m_Bullets.size())
{
u32 bulletIndex = 0;
for(std::list<Bullet*>::iterator it = m_Bullets.begin(); it != m_Bullets.end();)
{
if((*it)->fLife > 0.0f && !GameManager::Instance()->IsOutOfPlayfield((*it)->vPosition))
{
(*it)->vPosition += (*it)->vDirection*(*it)->fSpeed*g_fDeltaTime;
SetupRendering((*it), bulletIndex++, pVB);
(*it)->fLife -= g_fDeltaTime;
++it;
}
else
{
m_Pool->Free((*it));
it = m_Bullets.erase(it);
}
}
pVB->SetDirty(true);
}
}
//! Adds a bullet
void BulletManager::AddBullet(const Bullet::BulletParams& params)
{
if(Bullet* pBullet = m_Pool->Alloc<Bullet>())
{
pBullet->Init(params);
m_Bullets.push_back(pBullet);
}
}
//! clears the bullets
void BulletManager::Clear()
{
for(std::list<Bullet*>::iterator it = m_Bullets.begin(); it != m_Bullets.end(); ++it)
{
(*it)->fLife = 0.0f;
}
}
}
| 19.457944 | 91 | 0.653218 | franticsoftware |
aa0774141d71bc5d073660e069b33fb38c5f08f8 | 687 | hpp | C++ | src/util/handle.hpp | marvinwilliams/rantanplan | aadb4109a443a75881f610f45b710cd0532079fe | [
"MIT"
] | 3 | 2021-09-07T08:45:30.000Z | 2021-09-15T08:16:41.000Z | src/util/handle.hpp | marvinwilliams/rantanplan | aadb4109a443a75881f610f45b710cd0532079fe | [
"MIT"
] | null | null | null | src/util/handle.hpp | marvinwilliams/rantanplan | aadb4109a443a75881f610f45b710cd0532079fe | [
"MIT"
] | null | null | null | #ifndef HANDLE_HPP
#define HANDLE_HPP
namespace util {
/* This class is intended to only be instantiatable by the base and represents a
* pointer */
template <typename T, typename Base> class Handle {
public:
friend Base;
Handle() = default;
const T *get() { return p_; }
const Base *get_base() { return base_; }
const T &operator*() { return *p_; }
const T *operator->() { return p_; }
bool operator==(const Handle<T, Base> &other) const {
return p_ == other.p_ && base_ == other.base_;
}
private:
Handle(T *p, const Base *base) : p_{p}, base_{base} {}
T *p_ = nullptr;
const Base *base_ = nullptr;
};
}
#endif /* end of include guard: HANDLE_HPP */
| 20.818182 | 80 | 0.647744 | marvinwilliams |
aa07d67bc651b590684bdbab8917927c41c8514a | 452 | cpp | C++ | server/TracyFilesystem.cpp | benvanik/tracy | a3a7183293793003e5c20748dca7c7f430c11c20 | [
"BSD-3-Clause"
] | 3,609 | 2020-03-17T20:53:24.000Z | 2022-03-31T21:32:51.000Z | server/TracyFilesystem.cpp | benvanik/tracy | a3a7183293793003e5c20748dca7c7f430c11c20 | [
"BSD-3-Clause"
] | 312 | 2019-06-13T19:39:25.000Z | 2022-03-02T18:37:22.000Z | server/TracyFilesystem.cpp | benvanik/tracy | a3a7183293793003e5c20748dca7c7f430c11c20 | [
"BSD-3-Clause"
] | 273 | 2020-04-07T18:14:36.000Z | 2022-03-31T12:48:01.000Z | #include "TracyFilesystem.hpp"
#include "TracyView.hpp"
namespace tracy
{
bool SourceFileValid( const char* fn, uint64_t olderThan, const View& view, const Worker& worker )
{
if( worker.GetSourceFileFromCache( fn ).data != nullptr ) return true;
struct stat buf;
if( stat( view.SourceSubstitution( fn ), &buf ) == 0 && ( buf.st_mode & S_IFREG ) != 0 )
{
return (uint64_t)buf.st_mtime < olderThan;
}
return false;
}
}
| 23.789474 | 98 | 0.659292 | benvanik |
aa07d6df8e385e4f4363a3ba4aa696a69f4c56b3 | 548 | cpp | C++ | 080. Remove Duplicates from Sorted Array II/solution.cpp | zlsun/leetcode | 438d0020a701d7aa6a82eee0e46e5b11305abfda | [
"MIT"
] | null | null | null | 080. Remove Duplicates from Sorted Array II/solution.cpp | zlsun/leetcode | 438d0020a701d7aa6a82eee0e46e5b11305abfda | [
"MIT"
] | null | null | null | 080. Remove Duplicates from Sorted Array II/solution.cpp | zlsun/leetcode | 438d0020a701d7aa6a82eee0e46e5b11305abfda | [
"MIT"
] | null | null | null | /** 080. Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
**/
#include <iostream>
#include "../utils.h"
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
}
};
int main() {
Solution s;
return 0;
}
| 19.571429 | 156 | 0.680657 | zlsun |
aa0af1f55eed5220f2f2fef8acb2cf94c82cad9e | 8,602 | cc | C++ | src/aligner/aligner_edlib.cc | isovic/raptor | 171e0f1b94366f20250a00389400a2fcd267bcc6 | [
"BSD-3-Clause-Clear"
] | 60 | 2019-07-09T14:57:48.000Z | 2022-03-29T06:53:39.000Z | src/aligner/aligner_edlib.cc | isovic/raptor | 171e0f1b94366f20250a00389400a2fcd267bcc6 | [
"BSD-3-Clause-Clear"
] | 2 | 2019-05-28T01:59:50.000Z | 2021-05-18T13:15:10.000Z | src/aligner/aligner_edlib.cc | isovic/raptor | 171e0f1b94366f20250a00389400a2fcd267bcc6 | [
"BSD-3-Clause-Clear"
] | 4 | 2019-05-25T15:41:56.000Z | 2019-07-10T11:44:22.000Z | #include <aligner/aligner_edlib.h>
// #include "libs/edlibcigar.h"
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <zlib.h>
#include <aligner/aligner_util.hpp>
namespace raptor {
std::shared_ptr<AlignerBase> createAlignerEdlib(const raptor::AlignmentOptions& opt) {
return std::shared_ptr<AlignerBase>(new AlignerEdlib(opt));
}
AlignerEdlib::AlignerEdlib(const raptor::AlignmentOptions& opt) : opt_(opt) {}
AlignerEdlib::~AlignerEdlib() {}
std::vector<raptor::CigarOp> EdlibAlignmentToCigar(unsigned char* aln, int aln_len) {
std::vector<raptor::CigarOp> ret;
if (aln_len <= 0) {
return ret;
}
// Maps move code from alignment to char in cigar.
// 0 1 2 3
char op_to_cigar[] = {'=', 'I', 'D', 'X'};
char prev_op = 0; // Char of last move. 0 if there was no previous move.
int count = 0;
for (int i = 0; i <= aln_len; i++) {
if (i == aln_len || (op_to_cigar[aln[i]] != prev_op && prev_op != 0)) {
ret.emplace_back(raptor::CigarOp(prev_op, count));
count = 0;
}
if (i < aln_len) {
prev_op = op_to_cigar[aln[i]];
count += 1;
}
}
return ret;
}
std::shared_ptr<raptor::AlignmentResult> AlignerEdlib::Global(const char* qseq, int64_t qlen,
const char* tseq, int64_t tlen) {
return RunEdlib(qseq, qlen, tseq, tlen, opt_, EDLIB_MODE_NW, EDLIB_TASK_PATH);
}
std::shared_ptr<raptor::AlignmentResult> AlignerEdlib::Extend(const char* qseq, int64_t qlen,
const char* tseq, int64_t tlen) {
auto result = raptor::createAlignmentResult();
if (qseq == NULL || tseq == NULL || qlen <= 0 || tlen <= 0) {
result->status(raptor::AlignmentReturnValue::InvalidOptions);
return result;
}
result = RunEdlib(qseq, qlen, tseq, tlen, opt_, EDLIB_MODE_SHW, EDLIB_TASK_PATH);
auto aln_vec = CigarToAlignmentArray(result->cigar());
int64_t score = (opt_.end_bonus >= 0) ? opt_.end_bonus : 0;
// bool stop_ext_on_zero_score = (opt_.zdrop == -99912345) ? false : true; // Emulates local alignment if true. This might prevent end-to-end extensions, so allow a hidden feature to enable end-to-end extensions. These can severely reduce alignment score / identity.
int64_t max_score = -1000000000; // Large negative value;
int64_t max_q = 0;
int64_t max_t = 0;
int64_t drop_q = 0, drop_t = 0, drop_score = 0;
int64_t qpos = 0, tpos = 0;
size_t final_i = 0;
int64_t edit_dist = 0;
bool stop_loop = false;
char prev_op = 'Z';
int32_t streak = 1;
for (size_t i = 0; i < aln_vec.size(); ++i) {
char op = aln_vec[i];
streak = (op == prev_op) ? (streak + 1) : 1;
// int32_t count = 1; // streak;
final_i = i;
// std::cerr << "op = " << op << ", prev_op = " << prev_op << ", count = " << 1 << ", i = " << i << ", score = " << score << "\n";
prev_op = op;
switch (op) {
case '=':
score += opt_.p.match;
qpos += 1;
tpos += 1;
break;
case 'X':
score += opt_.p.mismatch;
qpos += 1;
tpos += 1;
edit_dist += 1;
break;
case 'I':
if (streak == 1) {
score += opt_.p.w[0].open; // Gap open only if a new streak is found.
}
score += opt_.p.w[0].ext; // This is the gap extend penalty.
qpos += 1;
edit_dist += 1;
break;
case 'D':
if (streak == 1) {
score += opt_.p.w[0].open; // Gap open only if a new streak is found.
}
score += opt_.p.w[0].ext; // This is the gap extend penalty.
tpos += 1;
edit_dist += 1;
break;
default:
// If an unknown op is found, don't do zdrop.
max_score = -1000000000;
qpos = qlen;
tpos = tlen;
score = result->score();
final_i = result->cigar().size();
stop_loop = true;
break;
}
if (score > max_score) {
max_score = score;
max_q = qpos;
max_t = tpos;
}
if (qpos >= qlen || tpos >= tlen) {
// std::cerr << "Break 1!\n";
break;
}
if (opt_.stop_ext_on_zero_score && score < 0) {
// std::cerr << "Break 2!\n";
break;
}
if (stop_loop == true) {
// std::cerr << "Break 3!\n";
break;
}
if (opt_.zdrop >= 0 && score < (max_score - opt_.zdrop)) {
// std::cerr << "Break 4!\n";
break;
}
}
if (final_i == aln_vec.size()) {
return result;
}
// std::cerr << "max_score = " << max_score << ", score = " << score << "\n";
// std::cerr << "cigar = " << raptor::CigarToString(result->cigar(), false) << "\n";
std::vector<raptor::CigarOp> new_cigar =
AlignmentArrayToCigar((const unsigned char*)&aln_vec[0], final_i + 1);
result->cigar(new_cigar);
result->score(score);
result->position(raptor::AlignmentPosition(0, qpos, 0, tpos));
result->max_score(max_score);
result->max_q_pos(max_q);
result->max_t_pos(max_t);
result->edit_dist(edit_dist);
result->final_band(-1);
result->status(raptor::AlignmentReturnValue::OK);
return result;
}
std::shared_ptr<raptor::AlignmentResult> AlignerEdlib::Local(const char* qseq, int64_t qlen,
const char* tseq, int64_t tlen) {
auto result = raptor::createAlignmentResult();
if (qseq == NULL || tseq == NULL || qlen <= 0 || tlen <= 0) {
result->status(raptor::AlignmentReturnValue::InvalidOptions);
return result;
}
result->status(raptor::AlignmentReturnValue::NotImplementedYet);
return result;
}
std::shared_ptr<raptor::AlignmentResult> AlignerEdlib::Semiglobal(const char* qseq, int64_t qlen,
const char* tseq, int64_t tlen) {
auto result = raptor::createAlignmentResult();
if (qseq == NULL || tseq == NULL || qlen <= 0 || tlen <= 0) {
result->status(raptor::AlignmentReturnValue::InvalidOptions);
return result;
}
result->status(raptor::AlignmentReturnValue::NotImplementedYet);
return result;
}
std::shared_ptr<raptor::AlignmentResult> AlignerEdlib::RunEdlib(const char* qseq, int64_t qlen,
const char* tseq, int64_t tlen,
const raptor::AlignmentOptions& opt,
EdlibAlignMode edlib_mode,
EdlibAlignTask edlib_task) {
auto result = raptor::createAlignmentResult();
if (qseq == NULL || tseq == NULL || qlen <= 0 || tlen <= 0) {
result->status(raptor::AlignmentReturnValue::InvalidOptions);
return result;
}
result->status(raptor::AlignmentReturnValue::AlignerFailure);
EdlibAlignResult edlib_result =
edlibAlign((const char*)qseq, qlen, (const char*)tseq, tlen,
edlibNewAlignConfig(opt.bandwidth, edlib_mode, edlib_task));
if (edlib_result.numLocations == 0) {
edlibFreeAlignResult(edlib_result);
result->status(raptor::AlignmentReturnValue::AlignerFailure);
return result;
}
// result->score(-edlib_result.editDistance);
result->edit_dist(edlib_result.editDistance);
result->position(raptor::AlignmentPosition(0, qlen, 0, tlen));
result->final_band(-1);
result->status(raptor::AlignmentReturnValue::OK);
result->max_q_pos(qlen);
result->max_t_pos(tlen);
result->cigar(EdlibAlignmentToCigar(edlib_result.alignment, edlib_result.alignmentLength));
int64_t score = ScoreCigarAlignment(result->cigar(), opt.p.match, opt.p.mismatch, opt.p.w[0].open, opt.p.w[0].ext);
result->score(score);
result->max_score(result->score());
edlibFreeAlignResult(edlib_result);
return result;
}
} // namespace raptor
| 35.991632 | 278 | 0.538596 | isovic |
aa0bd6d0f47af4c95f7f42945fb34176141d5494 | 4,413 | hpp | C++ | include/pcp/traits/point_traits.hpp | Q-Minh/octree | 0c3fd5a791d660b37461daf968a68ffb1c80b965 | [
"BSL-1.0"
] | 2 | 2021-03-10T09:57:45.000Z | 2021-04-13T21:19:57.000Z | include/pcp/traits/point_traits.hpp | Q-Minh/octree | 0c3fd5a791d660b37461daf968a68ffb1c80b965 | [
"BSL-1.0"
] | 22 | 2020-12-07T20:09:39.000Z | 2021-04-12T20:42:59.000Z | include/pcp/traits/point_traits.hpp | Q-Minh/octree | 0c3fd5a791d660b37461daf968a68ffb1c80b965 | [
"BSL-1.0"
] | null | null | null | #ifndef PCP_TRAITS_POINT_TRAITS_HPP
#define PCP_TRAITS_POINT_TRAITS_HPP
/**
* @file
* @ingroup traits
*/
#include <type_traits>
namespace pcp {
namespace traits {
/**
* @ingroup traits-geometry
* @brief
* PointView requirements:
* - coordinate_type type member
* - copy constructible
* - copy assignable
* - move constructible
* - move assignable
* - x,y,z getters
* - x,y,z setters
* - equality/inequality operator
* @tparam PointView Type to inspect
*/
template <class PointView, class = void>
struct is_point_view : std::false_type
{
};
template <class PointView>
struct is_point_view<
PointView,
std::void_t<
typename PointView::coordinate_type,
decltype(std::declval<PointView&>().x()),
decltype(std::declval<PointView&>().y()),
decltype(std::declval<PointView&>().z()),
decltype(std::declval<PointView&>().x(std::declval<typename PointView::coordinate_type>())),
decltype(std::declval<PointView&>().y(std::declval<typename PointView::coordinate_type>())),
decltype(std::declval<PointView&>().z(
std::declval<typename PointView::coordinate_type>()))>> : std::true_type
{
static_assert(std::is_copy_constructible_v<PointView>, "PointView must be copy constructible");
static_assert(std::is_copy_assignable_v<PointView>, "PointView must be copy assignable");
};
/**
* @ingroup traits-geometry
* @brief
* Compile-time check for PointView concept
* @tparam PointView
*/
template <class PointView>
static constexpr bool is_point_view_v = is_point_view<PointView>::value;
/**
* @ingroup traits-geometry
* @brief
* Point requirements (refines PointView):
* - default constructible
* - parameter constructor from x,y,z
* - *,/,+,- operators
*/
template <class Point, class = void>
struct is_point : std::false_type
{
};
template <class Point>
struct is_point<
Point,
std::void_t<
decltype(std::declval<typename Point::coordinate_type>() * std::declval<Point&>()),
decltype(std::declval<Point&>() / std::declval<typename Point::coordinate_type>()),
decltype(std::declval<Point&>() + std::declval<Point&>()),
decltype(std::declval<Point&>() - std::declval<Point&>()),
decltype(-std::declval<Point&>())>> : is_point_view<Point>
{
static_assert(std::is_default_constructible_v<Point>, "Point must be default constructible");
static_assert(
std::is_constructible_v<
Point,
typename Point::coordinate_type,
typename Point::coordinate_type,
typename Point::coordinate_type>,
"Point must be constructible from (x,y,z) coordinates");
};
/**
* @ingroup traits-geometry
* @brief
* Compile-time check for Point concept
* @tparam Point
*/
template <class Point>
static constexpr bool is_point_v = is_point<Point>::value;
template <class PointView1, class PointView2, class = void>
struct is_point_view_equality_comparable_to : std::false_type
{
};
template <class PointView1, class PointView2>
struct is_point_view_equality_comparable_to<
PointView1,
PointView2,
std::void_t<
decltype(std::declval<PointView1&>() == std::declval<PointView2&>()),
decltype(std::declval<PointView1&>() != std::declval<PointView2&>())>> : std::true_type
{
};
/**
* @ingroup traits
* @brief
* Compile-time check to verify if PointView1 is equality/inequality comparable to PointView2
* @tparam PointView1
* @tparam PointView2
*/
template <class PointView1, class PointView2>
static constexpr bool is_point_view_equality_comparable_to_v =
is_point_view_equality_comparable_to<PointView1, PointView2>::value;
template <class PointView1, class PointView2, class = void>
struct is_point_view_assignable_from : std::false_type
{
};
template <class PointView1, class PointView2>
struct is_point_view_assignable_from<
PointView1,
PointView2,
std::void_t<decltype(std::declval<PointView1&>() = std::declval<PointView2&>())>>
: std::true_type
{
};
/**
* @ingroup traits
* @brief
* Compile-time check to verify is PointView1 is assignable from PointView2
* @tparam PointView1
* @tparam PointView2
*/
template <class PointView1, class PointView2>
static constexpr bool is_point_view_assignable_from_v =
is_point_view_assignable_from<PointView1, PointView2>::value;
} // namespace traits
} // namespace pcp
#endif // PCP_TRAITS_POINT_TRAITS_HPP | 28.470968 | 100 | 0.705189 | Q-Minh |
aa0c7e6891cfc4be9ee61d0bf1b89cdb595959cd | 5,952 | cpp | C++ | QuadratureAnalyserAnalyzer.cpp | Marcus10110/Quadrature-Saleae-Analyser | 384ae08811864ac80fd207e28e6de41fc52b8386 | [
"Apache-2.0"
] | 9 | 2015-03-23T20:05:22.000Z | 2020-12-06T04:50:53.000Z | QuadratureAnalyserAnalyzer.cpp | Marcus10110/Quadrature-Saleae-Analyser | 384ae08811864ac80fd207e28e6de41fc52b8386 | [
"Apache-2.0"
] | 1 | 2018-12-06T08:57:13.000Z | 2018-12-06T19:10:45.000Z | QuadratureAnalyserAnalyzer.cpp | Marcus10110/Quadrature-Saleae-Analyser | 384ae08811864ac80fd207e28e6de41fc52b8386 | [
"Apache-2.0"
] | 2 | 2018-12-05T22:17:40.000Z | 2019-11-03T12:11:33.000Z | /* Copyright 2011 Dirk-Willem van Gulik, All Rights Reserved.
* dirkx(at)webweaving(dot)org
*
* 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.
*
* $Id: QuadratureAnalyserAnalyzer.cpp 1037 2011-09-12 09:49:58Z dirkx $
*/
#include "QuadratureAnalyserAnalyzer.h"
#include "QuadratureAnalyserAnalyzerSettings.h"
#include <AnalyzerChannelData.h>
static change_t qe_decode(unsigned char olda, unsigned char oldb, unsigned char newa, unsigned char newb)
{
change_t oldnew[16] = { // AB -> AB which is (old state) --> (new state)
STANDSTILL , // 00 -> 00
CLOCKWISE , // 00 -> 01 -1
COUNTERCW , // 00 -> 10 +1
GLITCH , // 00 -> 11
COUNTERCW , // 01 -> 00 +1
STANDSTILL , // 01 -> 01
GLITCH , // 01 -> 10
CLOCKWISE , // 01 -> 11 -1
CLOCKWISE , // 10 -> 00 -1
GLITCH , // 10 -> 01
STANDSTILL , // 10 -> 10
COUNTERCW , // 10 -> 11 +1
GLITCH , // 11 -> 00
COUNTERCW , // 11 -> 01 +1
CLOCKWISE , // 11 -> 10 -1
STANDSTILL , // 11 -> 11
};
unsigned char state = 0;
state += olda ? 1 : 0;
state += oldb ? 2 : 0;
state += newa ? 4 : 0;
state += newb ? 8 : 0;
return oldnew[state];
}
QuadratureAnalyserAnalyzer::QuadratureAnalyserAnalyzer()
: Analyzer(),
mSettings( new QuadratureAnalyserAnalyzerSettings() )
{
SetAnalyzerSettings( mSettings.get() );
}
QuadratureAnalyserAnalyzer::~QuadratureAnalyserAnalyzer()
{
KillThread();
}
void QuadratureAnalyserAnalyzer::WorkerThread()
{
mResults.reset( new QuadratureAnalyserAnalyzerResults( this, mSettings.get() ) );
SetAnalyzerResults( mResults.get() );
if (mSettings->mInputChannelA != UNDEFINED_CHANNEL)
mResults->AddChannelBubblesWillAppearOn( mSettings->mInputChannelA );
if (mSettings->mInputChannelB != UNDEFINED_CHANNEL)
mResults->AddChannelBubblesWillAppearOn( mSettings->mInputChannelB );
AnalyzerChannelData * mChannelA = GetAnalyzerChannelData( mSettings->mInputChannelA );
AnalyzerChannelData * mChannelB = GetAnalyzerChannelData( mSettings->mInputChannelB );
U8 mLastA = mChannelA->GetBitState() == BIT_HIGH ? 1 : 0;
U8 mLastB = mChannelB->GetBitState() == BIT_HIGH ? 1 : 0;
change_t lastDir = GLITCH;
U64 lastStart = mChannelA->GetSampleNumber();
U64 lastEnd = mChannelA->GetSampleNumber();
U64 curEnd = mChannelA->GetSampleNumber();
U32 glitchCount = 0;
U32 tickCount = 0;
int64_t posCount = 0;
for( ; ; )
{
AnalyzerResults::MarkerType m;
int result = 0;
U64 a,b,c;
#if 0
mChannelA->Advance(1);
mChannelB->Advance(1);
U8 mNewA = mChannelA->GetBitState() == BIT_HIGH ? 1 : 0;
U8 mNewB = mChannelB->GetBitState() == BIT_HIGH ? 1 : 0;
#else
a = mChannelA->GetSampleNumber();
b = mChannelB->GetSampleNumber();
if (a<=b) {
mChannelA->AdvanceToNextEdge();
};
if (b<=a) {
mChannelB->AdvanceToNextEdge();
};
a = mChannelA->GetSampleNumber();
b = mChannelB->GetSampleNumber();
U8 mNewA = mLastA;
U8 mNewB = mLastB;
if (a<=b) {
mNewA = mChannelA->GetBitState() == BIT_HIGH ? 1 : 0;
c = a;
};
if (b<=a) {
mNewB = mChannelB->GetBitState() == BIT_HIGH ? 1 : 0;
c = b;
};
#endif
change_t dir = qe_decode(mLastA, mLastB, mNewA, mNewB);
mLastA = mNewA;
mLastB = mNewB;
if (dir == STANDSTILL)
continue;
switch(dir) {
case CLOCKWISE:
case COUNTERCW:
m = (dir == CLOCKWISE) ? AnalyzerResults::DownArrow : AnalyzerResults::UpArrow;
mResults->AddMarker( c, m, mSettings->mInputChannelA );
mResults->AddMarker( c, m, mSettings->mInputChannelB );
result ++;
tickCount++;
posCount += (m == CLOCKWISE) ? -1 : 1;
lastEnd = curEnd;
curEnd = c;
break;
default:
glitchCount++;
break;
};
if (dir != lastDir) {
// skip any initial glitches. We're not sure what they are anyway.
//
if (glitchCount != 0 || lastDir != GLITCH) {
Frame frame;
frame.mData1 = (posCount << 32) | lastDir;
frame.mData2 = ((U64)tickCount << 32) | (glitchCount << 0);
frame.mFlags = 0;
frame.mStartingSampleInclusive = lastStart;
frame.mEndingSampleInclusive = lastEnd;
mResults->AddFrame( frame );
}
lastStart = curEnd;
lastDir = dir;
result ++;
tickCount = 0;
glitchCount = 0;
};
if (result) {
mResults->CommitResults();
ReportProgress(c);
};
}
}
bool QuadratureAnalyserAnalyzer::NeedsRerun()
{
return false;
}
U32 QuadratureAnalyserAnalyzer::GenerateSimulationData( U64 minimum_sample_index, U32 device_sample_rate, SimulationChannelDescriptor** simulation_channels )
{
mSimulationDataGenerator.Initialize( GetSimulationSampleRate(), mSettings.get() );
return mSimulationDataGenerator.GenerateSimulationData( minimum_sample_index,
device_sample_rate, simulation_channels );
}
U32 QuadratureAnalyserAnalyzer::GetMinimumSampleRateHz()
{
return SCANRATE;
}
const char* QuadratureAnalyserAnalyzer::GetAnalyzerName() const
{
return "Quadrature Decoder";
}
const char* GetAnalyzerName()
{
// return MYVERSION;
return "Quadrature Decoder";
}
Analyzer* CreateAnalyzer()
{
return new QuadratureAnalyserAnalyzer();
}
void DestroyAnalyzer( Analyzer* analyzer )
{
delete analyzer;
}
| 28.075472 | 158 | 0.641633 | Marcus10110 |
aa0e1c32db5c42e74b17ec2cda84e729012eaff8 | 263 | hpp | C++ | server/api/include/rsDataObjOpenAndStat.hpp | JustinKyleJames/irods | 59e9db75200e95796ec51ec20eb3b185d9e4b5f5 | [
"BSD-3-Clause"
] | 333 | 2015-01-15T15:42:29.000Z | 2022-03-19T19:16:15.000Z | server/api/include/rsDataObjOpenAndStat.hpp | JustinKyleJames/irods | 59e9db75200e95796ec51ec20eb3b185d9e4b5f5 | [
"BSD-3-Clause"
] | 3,551 | 2015-01-02T19:55:40.000Z | 2022-03-31T21:24:56.000Z | server/api/include/rsDataObjOpenAndStat.hpp | JustinKyleJames/irods | 59e9db75200e95796ec51ec20eb3b185d9e4b5f5 | [
"BSD-3-Clause"
] | 148 | 2015-01-31T16:13:46.000Z | 2022-03-23T20:23:43.000Z | #ifndef RS_DATA_OBJ_OPEN_AND_STAT_HPP
#define RS_DATA_OBJ_OPEN_AND_STAT_HPP
#include "rcConnect.h"
#include "dataObjInpOut.h"
#include "dataObjOpenAndStat.h"
int rsDataObjOpenAndStat( rsComm_t *rsComm, dataObjInp_t *dataObjInp, openStat_t **openStat );
#endif
| 23.909091 | 94 | 0.821293 | JustinKyleJames |
aa0e1c65fc53317f11367b9bf07e292b5e09f68c | 16,656 | cc | C++ | cc/blimp/layer_tree_host_unittest_serialization.cc | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | cc/blimp/layer_tree_host_unittest_serialization.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cc/blimp/layer_tree_host_unittest_serialization.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "cc/animation/animation_host.h"
#include "cc/blimp/layer_tree_host_remote.h"
#include "cc/layers/empty_content_layer_client.h"
#include "cc/layers/layer.h"
#include "cc/layers/solid_color_scrollbar_layer.h"
#include "cc/proto/layer.pb.h"
#include "cc/proto/layer_tree_host.pb.h"
#include "cc/test/fake_image_serialization_processor.h"
#include "cc/test/fake_layer_tree_host.h"
#include "cc/test/fake_layer_tree_host_client.h"
#include "cc/test/fake_picture_layer.h"
#include "cc/test/fake_recording_source.h"
#include "cc/test/remote_client_layer_factory.h"
#include "cc/test/remote_compositor_test.h"
#include "cc/test/serialization_test_utils.h"
#include "cc/trees/layer_tree.h"
#include "cc/trees/layer_tree_host_common.h"
#include "cc/trees/layer_tree_settings.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/vector2d_f.h"
namespace cc {
#define EXPECT_CLIENT_LAYER_DIRTY(engine_layer) \
do { \
Layer* client_layer = compositor_state_deserializer_->GetLayerForEngineId( \
engine_layer->id()); \
LayerTree* client_tree = client_layer->GetLayerTree(); \
EXPECT_TRUE( \
client_tree->LayerNeedsPushPropertiesForTesting(client_layer)); \
} while (false)
class LayerTreeHostSerializationTest : public RemoteCompositorTest {
protected:
void VerifySerializationAndDeserialization() {
// Synchronize state.
CHECK(HasPendingUpdate());
base::RunLoop().RunUntilIdle();
VerifySerializedTreesAreIdentical(
layer_tree_host_remote_->GetLayerTree(),
layer_tree_host_in_process_->GetLayerTree(),
compositor_state_deserializer_.get());
}
void SetUpViewportLayers(LayerTree* engine_layer_tree) {
scoped_refptr<Layer> overscroll_elasticity_layer = Layer::Create();
scoped_refptr<Layer> page_scale_layer = Layer::Create();
scoped_refptr<Layer> inner_viewport_scroll_layer = Layer::Create();
scoped_refptr<Layer> outer_viewport_scroll_layer = Layer::Create();
engine_layer_tree->root_layer()->AddChild(overscroll_elasticity_layer);
engine_layer_tree->root_layer()->AddChild(page_scale_layer);
engine_layer_tree->root_layer()->AddChild(inner_viewport_scroll_layer);
engine_layer_tree->root_layer()->AddChild(outer_viewport_scroll_layer);
engine_layer_tree->RegisterViewportLayers(
overscroll_elasticity_layer, page_scale_layer,
inner_viewport_scroll_layer, outer_viewport_scroll_layer);
}
};
TEST_F(LayerTreeHostSerializationTest, AllMembersChanged) {
LayerTree* engine_layer_tree = layer_tree_host_remote_->GetLayerTree();
engine_layer_tree->SetRootLayer(Layer::Create());
scoped_refptr<Layer> mask_layer = Layer::Create();
engine_layer_tree->root_layer()->SetMaskLayer(mask_layer.get());
SetUpViewportLayers(engine_layer_tree);
engine_layer_tree->SetViewportSize(gfx::Size(3, 14));
engine_layer_tree->SetDeviceScaleFactor(4.f);
engine_layer_tree->SetPaintedDeviceScaleFactor(2.f);
engine_layer_tree->SetPageScaleFactorAndLimits(2.f, 0.5f, 3.f);
engine_layer_tree->set_background_color(SK_ColorMAGENTA);
engine_layer_tree->set_has_transparent_background(true);
LayerSelectionBound sel_bound;
sel_bound.edge_top = gfx::Point(14, 3);
LayerSelection selection;
selection.start = sel_bound;
engine_layer_tree->RegisterSelection(selection);
VerifySerializationAndDeserialization();
}
TEST_F(LayerTreeHostSerializationTest, LayersChangedMultipleSerializations) {
LayerTree* engine_layer_tree = layer_tree_host_remote_->GetLayerTree();
engine_layer_tree->SetRootLayer(Layer::Create());
SetUpViewportLayers(engine_layer_tree);
VerifySerializationAndDeserialization();
scoped_refptr<Layer> new_child = Layer::Create();
engine_layer_tree->root_layer()->AddChild(new_child);
engine_layer_tree->RegisterViewportLayers(nullptr, nullptr, nullptr, nullptr);
VerifySerializationAndDeserialization();
engine_layer_tree->SetRootLayer(nullptr);
VerifySerializationAndDeserialization();
}
TEST_F(LayerTreeHostSerializationTest, AddAndRemoveNodeFromLayerTree) {
/* Testing serialization when the tree hierarchy changes like this:
root root
/ \ / \
a b => a c
\ \
c d
*/
LayerTree* engine_layer_tree = layer_tree_host_remote_->GetLayerTree();
scoped_refptr<Layer> layer_src_root = Layer::Create();
engine_layer_tree->SetRootLayer(layer_src_root);
scoped_refptr<Layer> layer_src_a = Layer::Create();
scoped_refptr<Layer> layer_src_b = Layer::Create();
scoped_refptr<Layer> layer_src_c = Layer::Create();
scoped_refptr<Layer> layer_src_d = Layer::Create();
layer_src_root->AddChild(layer_src_a);
layer_src_root->AddChild(layer_src_b);
layer_src_b->AddChild(layer_src_c);
VerifySerializationAndDeserialization();
// Now change the Layer Hierarchy
layer_src_c->RemoveFromParent();
layer_src_b->RemoveFromParent();
layer_src_root->AddChild(layer_src_c);
layer_src_c->AddChild(layer_src_d);
VerifySerializationAndDeserialization();
}
TEST_F(LayerTreeHostSerializationTest, TestNoExistingRoot) {
/* Test deserialization of a tree that looks like:
root
/ \
a b
\
c
There is no existing root node before serialization.
*/
scoped_refptr<Layer> old_root_layer = Layer::Create();
scoped_refptr<Layer> layer_a = Layer::Create();
scoped_refptr<Layer> layer_b = Layer::Create();
scoped_refptr<Layer> layer_c = Layer::Create();
old_root_layer->AddChild(layer_a);
old_root_layer->AddChild(layer_b);
layer_b->AddChild(layer_c);
layer_tree_host_remote_->GetLayerTree()->SetRootLayer(old_root_layer);
VerifySerializationAndDeserialization();
// Swap the root node.
scoped_refptr<Layer> new_root_layer = Layer::Create();
new_root_layer->AddChild(layer_a);
new_root_layer->AddChild(layer_b);
layer_tree_host_remote_->GetLayerTree()->SetRootLayer(old_root_layer);
VerifySerializationAndDeserialization();
}
TEST_F(LayerTreeHostSerializationTest, RecursivePropertiesSerialization) {
/* Testing serialization of properties for a tree that looks like this:
root+
/ \
a* b+[mask:*]
/ \
c d
Layers marked with * have changed properties.
Layers marked with + have descendants with changed properties.
Layer b also has a mask layer.
*/
scoped_refptr<Layer> layer_src_root = Layer::Create();
scoped_refptr<Layer> layer_src_a = Layer::Create();
scoped_refptr<Layer> layer_src_b = Layer::Create();
scoped_refptr<Layer> layer_src_b_mask = Layer::Create();
scoped_refptr<Layer> layer_src_c = Layer::Create();
scoped_refptr<Layer> layer_src_d = Layer::Create();
layer_src_root->AddChild(layer_src_a);
layer_src_root->AddChild(layer_src_b);
layer_src_a->AddChild(layer_src_c);
layer_src_b->AddChild(layer_src_d);
layer_src_b->SetMaskLayer(layer_src_b_mask.get());
layer_tree_host_remote_->GetLayerTree()->SetRootLayer(layer_src_root);
VerifySerializationAndDeserialization();
EXPECT_EQ(layer_tree_host_remote_->GetLayerTree()
->LayersThatShouldPushProperties()
.size(),
0u);
EXPECT_EQ(layer_tree_host_in_process_->GetLayerTree()
->LayersThatShouldPushProperties()
.size(),
6u);
}
TEST_F(LayerTreeHostSerializationTest, ChildrenOrderChange) {
/* Testing serialization and deserialization of a tree that initially looks
like this:
root
/ \
a b
The children are then re-ordered and changed to:
root
/ \
b a
\
c
*/
scoped_refptr<Layer> layer_src_root = Layer::Create();
layer_tree_host_remote_->GetLayerTree()->SetRootLayer(layer_src_root);
scoped_refptr<Layer> layer_src_a = Layer::Create();
scoped_refptr<Layer> layer_src_b = Layer::Create();
layer_src_root->AddChild(layer_src_b);
layer_src_root->AddChild(layer_src_a);
VerifySerializationAndDeserialization();
Layer* client_root =
compositor_state_deserializer_->GetLayerForEngineId(layer_src_root->id());
Layer* client_a =
compositor_state_deserializer_->GetLayerForEngineId(layer_src_a->id());
Layer* client_b =
compositor_state_deserializer_->GetLayerForEngineId(layer_src_b->id());
// Swap the children.
layer_src_root->RemoveAllChildren();
layer_src_root->AddChild(layer_src_a);
layer_src_root->AddChild(layer_src_b);
layer_src_a->AddChild(Layer::Create());
VerifySerializationAndDeserialization();
// Verify all old layers are re-used.
Layer* new_client_root =
compositor_state_deserializer_->GetLayerForEngineId(layer_src_root->id());
Layer* new_client_a =
compositor_state_deserializer_->GetLayerForEngineId(layer_src_a->id());
Layer* new_client_b =
compositor_state_deserializer_->GetLayerForEngineId(layer_src_b->id());
EXPECT_EQ(client_root, new_client_root);
EXPECT_EQ(client_a, new_client_a);
EXPECT_EQ(client_b, new_client_b);
}
TEST_F(LayerTreeHostSerializationTest, DeletingLayers) {
/* Testing serialization and deserialization of a tree that initially
looks like this:
root
/ \
a b
\
c+[mask:*]
First the mask layer is deleted.
Then the subtree from node |b| is deleted in the next update.
*/
scoped_refptr<Layer> layer_src_root = Layer::Create();
layer_tree_host_remote_->GetLayerTree()->SetRootLayer(layer_src_root);
scoped_refptr<Layer> layer_src_a = Layer::Create();
scoped_refptr<Layer> layer_src_b = Layer::Create();
scoped_refptr<Layer> layer_src_c = Layer::Create();
scoped_refptr<Layer> layer_src_c_mask = Layer::Create();
layer_src_root->AddChild(layer_src_a);
layer_src_root->AddChild(layer_src_b);
layer_src_b->AddChild(layer_src_c);
layer_src_c->SetMaskLayer(layer_src_c_mask.get());
VerifySerializationAndDeserialization();
// Delete the mask layer.
layer_src_c->SetMaskLayer(nullptr);
VerifySerializationAndDeserialization();
// Remove child b.
layer_src_b->RemoveFromParent();
VerifySerializationAndDeserialization();
}
TEST_F(LayerTreeHostSerializationTest, LayerDataSerialization) {
scoped_refptr<Layer> layer = Layer::Create();
layer_tree_host_remote_->GetLayerTree()->SetRootLayer(layer);
VerifySerializationAndDeserialization();
// Change all the fields.
layer->SetTransformOrigin(gfx::Point3F(3.0f, 1.0f, 4.0f));
layer->SetBackgroundColor(SK_ColorRED);
layer->SetBounds(gfx::Size(3, 14));
layer->SetDoubleSided(!layer->double_sided());
layer->SetHideLayerAndSubtree(!layer->hide_layer_and_subtree());
layer->SetMasksToBounds(!layer->masks_to_bounds());
layer->AddMainThreadScrollingReasons(
MainThreadScrollingReason::kHasBackgroundAttachmentFixedObjects);
layer->SetNonFastScrollableRegion(Region(gfx::Rect(5, 1, 14, 3)));
layer->SetNonFastScrollableRegion(Region(gfx::Rect(3, 14, 1, 5)));
layer->SetContentsOpaque(!layer->contents_opaque());
layer->SetOpacity(0.4f);
layer->SetBlendMode(SkXfermode::kOverlay_Mode);
layer->SetIsRootForIsolatedGroup(!layer->is_root_for_isolated_group());
layer->SetPosition(gfx::PointF(3.14f, 6.28f));
layer->SetIsContainerForFixedPositionLayers(
!layer->IsContainerForFixedPositionLayers());
LayerPositionConstraint pos_con;
pos_con.set_is_fixed_to_bottom_edge(true);
layer->SetPositionConstraint(pos_con);
layer->SetShouldFlattenTransform(!layer->should_flatten_transform());
layer->SetUseParentBackfaceVisibility(
!layer->use_parent_backface_visibility());
gfx::Transform transform;
transform.Rotate(90);
layer->SetTransform(transform);
layer->Set3dSortingContextId(42);
layer->SetUserScrollable(layer->user_scrollable_horizontal(),
layer->user_scrollable_vertical());
layer->SetScrollOffset(gfx::ScrollOffset(3, 14));
gfx::Rect update_rect(14, 15);
layer->SetNeedsDisplayRect(update_rect);
VerifySerializationAndDeserialization();
Layer* client_layer =
compositor_state_deserializer_->GetLayerForEngineId(layer->id());
EXPECT_EQ(update_rect, client_layer->update_rect());
}
TEST_F(LayerTreeHostSerializationTest, SolidColorScrollbarLayer) {
scoped_refptr<Layer> root_layer = Layer::Create();
layer_tree_host_remote_->GetLayerTree()->SetRootLayer(root_layer);
scoped_refptr<Layer> child_layer = Layer::Create();
root_layer->AddChild(child_layer);
std::vector<scoped_refptr<SolidColorScrollbarLayer>> scrollbar_layers;
scrollbar_layers.push_back(SolidColorScrollbarLayer::Create(
ScrollbarOrientation::HORIZONTAL, 20, 5, true, root_layer->id()));
scrollbar_layers.push_back(SolidColorScrollbarLayer::Create(
ScrollbarOrientation::VERTICAL, 20, 5, false, child_layer->id()));
scrollbar_layers.push_back(SolidColorScrollbarLayer::Create(
ScrollbarOrientation::HORIZONTAL, 0, 0, true, root_layer->id()));
scrollbar_layers.push_back(SolidColorScrollbarLayer::Create(
ScrollbarOrientation::VERTICAL, 10, 35, true, child_layer->id()));
for (const auto& layer : scrollbar_layers) {
root_layer->AddChild(layer);
}
VerifySerializationAndDeserialization();
for (const auto& engine_layer : scrollbar_layers) {
VerifySerializedScrollbarLayersAreIdentical(
engine_layer.get(), compositor_state_deserializer_.get());
}
}
TEST_F(LayerTreeHostSerializationTest, PictureLayerSerialization) {
// Override the layer factor to create FakePictureLayers in the deserializer.
compositor_state_deserializer_->SetLayerFactoryForTesting(
base::MakeUnique<RemoteClientLayerFactory>());
LayerTree* engine_layer_tree = layer_tree_host_remote_->GetLayerTree();
scoped_refptr<Layer> root_layer_src = Layer::Create();
engine_layer_tree->SetRootLayer(root_layer_src);
// Ensure that a PictureLayer work correctly for multiple rounds of
// serialization and deserialization.
FakeContentLayerClient content_client;
gfx::Size bounds(256, 256);
content_client.set_bounds(bounds);
SkPaint simple_paint;
simple_paint.setColor(SkColorSetARGB(255, 12, 23, 34));
content_client.add_draw_rect(gfx::Rect(bounds), simple_paint);
scoped_refptr<FakePictureLayer> picture_layer_src =
FakePictureLayer::Create(&content_client);
root_layer_src->AddChild(picture_layer_src);
picture_layer_src->SetNearestNeighbor(!picture_layer_src->nearest_neighbor());
picture_layer_src->SetNeedsDisplay();
VerifySerializationAndDeserialization();
layer_tree_host_in_process_->UpdateLayers();
VerifySerializedPictureLayersAreIdentical(
picture_layer_src.get(), compositor_state_deserializer_.get());
// Another round.
picture_layer_src->SetNeedsDisplay();
SkPaint new_paint;
new_paint.setColor(SkColorSetARGB(255, 12, 32, 44));
content_client.add_draw_rect(gfx::Rect(bounds), new_paint);
VerifySerializationAndDeserialization();
layer_tree_host_in_process_->UpdateLayers();
VerifySerializedPictureLayersAreIdentical(
picture_layer_src.get(), compositor_state_deserializer_.get());
}
TEST_F(LayerTreeHostSerializationTest, EmptyPictureLayerSerialization) {
// Override the layer factor to create FakePictureLayers in the deserializer.
compositor_state_deserializer_->SetLayerFactoryForTesting(
base::MakeUnique<RemoteClientLayerFactory>());
LayerTree* engine_layer_tree = layer_tree_host_remote_->GetLayerTree();
scoped_refptr<Layer> root_layer_src = Layer::Create();
engine_layer_tree->SetRootLayer(root_layer_src);
scoped_refptr<FakePictureLayer> picture_layer_src =
FakePictureLayer::Create(EmptyContentLayerClient::GetInstance());
root_layer_src->AddChild(picture_layer_src);
picture_layer_src->SetNeedsDisplay();
VerifySerializationAndDeserialization();
layer_tree_host_in_process_->UpdateLayers();
VerifySerializedPictureLayersAreIdentical(
picture_layer_src.get(), compositor_state_deserializer_.get());
}
} // namespace cc
| 40.329298 | 80 | 0.742315 | xzhan96 |
aa0ed280387e135370d559b9ead9bb90c26b7b6a | 678 | cc | C++ | brightray/common/application_info_win.cc | SeanMercy/Pro1 | 43aa555d647d181265bde59570e2fdd7704cf83f | [
"MIT"
] | 7 | 2018-02-05T11:43:49.000Z | 2022-02-09T20:28:20.000Z | brightray/common/application_info_win.cc | SeanMercy/Pro1 | 43aa555d647d181265bde59570e2fdd7704cf83f | [
"MIT"
] | null | null | null | brightray/common/application_info_win.cc | SeanMercy/Pro1 | 43aa555d647d181265bde59570e2fdd7704cf83f | [
"MIT"
] | 2 | 2017-08-25T18:58:44.000Z | 2019-10-22T14:59:04.000Z | #include "brightray/common/application_info.h"
#include <memory>
#include "base/file_version_info.h"
#include "base/strings/utf_string_conversions.h"
namespace brightray {
std::string GetApplicationName() {
auto module = GetModuleHandle(nullptr);
std::unique_ptr<FileVersionInfo> info(
FileVersionInfo::CreateFileVersionInfoForModule(module));
return base::UTF16ToUTF8(info->product_name());
}
std::string GetApplicationVersion() {
auto module = GetModuleHandle(nullptr);
std::unique_ptr<FileVersionInfo> info(
FileVersionInfo::CreateFileVersionInfoForModule(module));
return base::UTF16ToUTF8(info->product_version());
}
} // namespace brightray
| 27.12 | 63 | 0.769912 | SeanMercy |
aa10fa15812e90565409cc49a77918ccadec35b7 | 11,309 | cc | C++ | Controllers/Flatground/utils/funcs/kin/mex/LeftToeJoint_mex.cc | EngineeringIV/CASSIE_MPC | fcbf5559bfd11dbdbb241565585fa22ccdaa5499 | [
"BSD-3-Clause"
] | 61 | 2019-02-21T09:32:55.000Z | 2022-03-29T02:30:18.000Z | Controllers/Flatground/utils/funcs/kin/mex/LeftToeJoint_mex.cc | EngineeringIV/CASSIE_MPC | fcbf5559bfd11dbdbb241565585fa22ccdaa5499 | [
"BSD-3-Clause"
] | 3 | 2019-02-22T08:01:40.000Z | 2022-01-20T09:16:40.000Z | Controllers/Flatground/utils/funcs/kin/mex/LeftToeJoint_mex.cc | EngineeringIV/CASSIE_MPC | fcbf5559bfd11dbdbb241565585fa22ccdaa5499 | [
"BSD-3-Clause"
] | 28 | 2019-02-04T19:47:35.000Z | 2022-02-23T08:28:23.000Z | /*
* Automatically Generated from Mathematica.
* Mon 25 Jun 2018 14:53:24 GMT-04:00
*/
#ifdef MATLAB_MEX_FILE
#include <stdexcept>
#include <cmath>
/**
* Copied from Wolfram Mathematica C Definitions file mdefs.hpp
* Changed marcos to inline functions (Eric Cousineau)
*/
inline double Power(double x, double y) { return pow(x, y); }
inline double Sqrt(double x) { return sqrt(x); }
inline double Abs(double x) { return fabs(x); }
inline double Exp(double x) { return exp(x); }
inline double Log(double x) { return log(x); }
inline double Sin(double x) { return sin(x); }
inline double Cos(double x) { return cos(x); }
inline double Tan(double x) { return tan(x); }
inline double ArcSin(double x) { return asin(x); }
inline double ArcCos(double x) { return acos(x); }
inline double ArcTan(double x) { return atan(x); }
/* update ArcTan function to use atan2 instead. */
inline double ArcTan(double x, double y) { return atan2(y,x); }
inline double Sinh(double x) { return sinh(x); }
inline double Cosh(double x) { return cosh(x); }
inline double Tanh(double x) { return tanh(x); }
const double E = 2.71828182845904523536029;
const double Pi = 3.14159265358979323846264;
const double Degree = 0.01745329251994329576924;
#endif
/*
* Sub functions
*/
static void output1(double *p_output1,const double *var1)
{
double t2124;
double t2089;
double t2134;
double t2101;
double t2138;
double t328;
double t2109;
double t2149;
double t2160;
double t2181;
double t2185;
double t2186;
double t2213;
double t2244;
double t2249;
double t2251;
double t2258;
double t2238;
double t2240;
double t2243;
double t2324;
double t2413;
double t2416;
double t2421;
double t2426;
double t2393;
double t2395;
double t2406;
double t2435;
double t2439;
double t2442;
double t2492;
double t2496;
double t2510;
double t2528;
double t2555;
double t2557;
double t2566;
double t2605;
double t2610;
double t2613;
double t2621;
double t2625;
double t2627;
double t2635;
double t2645;
double t2647;
double t2652;
double t2674;
double t2681;
double t2689;
double t2691;
double t2705;
double t2710;
double t2721;
double t2741;
double t2750;
double t2755;
double t2820;
double t2824;
double t2828;
double t2837;
double t2839;
double t2842;
double t2846;
double t2871;
double t2872;
double t2878;
double t2903;
double t2906;
double t2919;
double t1962;
double t2015;
double t2028;
double t2050;
double t2219;
double t2223;
double t2963;
double t2967;
double t2969;
double t2982;
double t2985;
double t2990;
double t2255;
double t2262;
double t2272;
double t2338;
double t2344;
double t2345;
double t2998;
double t3000;
double t3003;
double t2424;
double t2428;
double t2432;
double t2454;
double t2465;
double t2481;
double t2514;
double t2531;
double t2545;
double t3030;
double t3031;
double t3035;
double t3049;
double t3051;
double t3056;
double t2583;
double t2594;
double t2599;
double t2631;
double t2640;
double t2642;
double t3064;
double t3069;
double t3072;
double t3080;
double t3093;
double t3102;
double t2661;
double t2664;
double t2670;
double t2717;
double t2736;
double t2737;
double t3115;
double t3116;
double t3123;
double t3137;
double t3138;
double t3142;
double t2773;
double t2779;
double t2802;
double t2845;
double t2852;
double t2866;
double t3150;
double t3151;
double t3154;
double t3158;
double t3159;
double t3160;
double t2890;
double t2892;
double t2896;
double t3169;
double t3172;
double t3176;
double t3182;
double t3186;
double t3195;
double t3239;
double t3242;
double t3248;
double t3280;
double t3284;
double t3287;
double t3296;
double t3299;
double t3303;
double t3308;
double t3310;
double t3312;
double t3316;
double t3317;
double t3325;
double t3334;
double t3335;
double t3337;
double t3341;
double t3343;
double t3344;
double t3354;
double t3355;
double t3359;
double t3365;
double t3370;
double t3371;
double t3378;
double t3379;
double t3382;
double t3386;
double t3389;
double t3392;
t2124 = Cos(var1[3]);
t2089 = Cos(var1[5]);
t2134 = Sin(var1[4]);
t2101 = Sin(var1[3]);
t2138 = Sin(var1[5]);
t328 = Cos(var1[6]);
t2109 = -1.*t2089*t2101;
t2149 = t2124*t2134*t2138;
t2160 = t2109 + t2149;
t2181 = t2124*t2089*t2134;
t2185 = t2101*t2138;
t2186 = t2181 + t2185;
t2213 = Sin(var1[6]);
t2244 = Cos(var1[7]);
t2249 = -1.*t2244;
t2251 = 1. + t2249;
t2258 = Sin(var1[7]);
t2238 = t328*t2160;
t2240 = t2186*t2213;
t2243 = t2238 + t2240;
t2324 = Cos(var1[4]);
t2413 = Cos(var1[8]);
t2416 = -1.*t2413;
t2421 = 1. + t2416;
t2426 = Sin(var1[8]);
t2393 = t2124*t2324*t2244;
t2395 = t2243*t2258;
t2406 = t2393 + t2395;
t2435 = t328*t2186;
t2439 = -1.*t2160*t2213;
t2442 = t2435 + t2439;
t2492 = Cos(var1[9]);
t2496 = -1.*t2492;
t2510 = 1. + t2496;
t2528 = Sin(var1[9]);
t2555 = t2413*t2406;
t2557 = t2442*t2426;
t2566 = t2555 + t2557;
t2605 = t2413*t2442;
t2610 = -1.*t2406*t2426;
t2613 = t2605 + t2610;
t2621 = Cos(var1[10]);
t2625 = -1.*t2621;
t2627 = 1. + t2625;
t2635 = Sin(var1[10]);
t2645 = -1.*t2528*t2566;
t2647 = t2492*t2613;
t2652 = t2645 + t2647;
t2674 = t2492*t2566;
t2681 = t2528*t2613;
t2689 = t2674 + t2681;
t2691 = Cos(var1[11]);
t2705 = -1.*t2691;
t2710 = 1. + t2705;
t2721 = Sin(var1[11]);
t2741 = t2635*t2652;
t2750 = t2621*t2689;
t2755 = t2741 + t2750;
t2820 = t2621*t2652;
t2824 = -1.*t2635*t2689;
t2828 = t2820 + t2824;
t2837 = Cos(var1[12]);
t2839 = -1.*t2837;
t2842 = 1. + t2839;
t2846 = Sin(var1[12]);
t2871 = -1.*t2721*t2755;
t2872 = t2691*t2828;
t2878 = t2871 + t2872;
t2903 = t2691*t2755;
t2906 = t2721*t2828;
t2919 = t2903 + t2906;
t1962 = -1.*t328;
t2015 = 1. + t1962;
t2028 = 0.135*t2015;
t2050 = 0. + t2028;
t2219 = -0.135*t2213;
t2223 = 0. + t2219;
t2963 = t2124*t2089;
t2967 = t2101*t2134*t2138;
t2969 = t2963 + t2967;
t2982 = t2089*t2101*t2134;
t2985 = -1.*t2124*t2138;
t2990 = t2982 + t2985;
t2255 = 0.135*t2251;
t2262 = 0.049*t2258;
t2272 = 0. + t2255 + t2262;
t2338 = -0.049*t2251;
t2344 = 0.135*t2258;
t2345 = 0. + t2338 + t2344;
t2998 = t328*t2969;
t3000 = t2990*t2213;
t3003 = t2998 + t3000;
t2424 = -0.049*t2421;
t2428 = -0.09*t2426;
t2432 = 0. + t2424 + t2428;
t2454 = -0.09*t2421;
t2465 = 0.049*t2426;
t2481 = 0. + t2454 + t2465;
t2514 = -0.049*t2510;
t2531 = -0.21*t2528;
t2545 = 0. + t2514 + t2531;
t3030 = t2324*t2244*t2101;
t3031 = t3003*t2258;
t3035 = t3030 + t3031;
t3049 = t328*t2990;
t3051 = -1.*t2969*t2213;
t3056 = t3049 + t3051;
t2583 = -0.21*t2510;
t2594 = 0.049*t2528;
t2599 = 0. + t2583 + t2594;
t2631 = -0.2707*t2627;
t2640 = 0.0016*t2635;
t2642 = 0. + t2631 + t2640;
t3064 = t2413*t3035;
t3069 = t3056*t2426;
t3072 = t3064 + t3069;
t3080 = t2413*t3056;
t3093 = -1.*t3035*t2426;
t3102 = t3080 + t3093;
t2661 = -0.0016*t2627;
t2664 = -0.2707*t2635;
t2670 = 0. + t2661 + t2664;
t2717 = 0.0184*t2710;
t2736 = -0.7055*t2721;
t2737 = 0. + t2717 + t2736;
t3115 = -1.*t2528*t3072;
t3116 = t2492*t3102;
t3123 = t3115 + t3116;
t3137 = t2492*t3072;
t3138 = t2528*t3102;
t3142 = t3137 + t3138;
t2773 = -0.7055*t2710;
t2779 = -0.0184*t2721;
t2802 = 0. + t2773 + t2779;
t2845 = -1.1135*t2842;
t2852 = 0.0216*t2846;
t2866 = 0. + t2845 + t2852;
t3150 = t2635*t3123;
t3151 = t2621*t3142;
t3154 = t3150 + t3151;
t3158 = t2621*t3123;
t3159 = -1.*t2635*t3142;
t3160 = t3158 + t3159;
t2890 = -0.0216*t2842;
t2892 = -1.1135*t2846;
t2896 = 0. + t2890 + t2892;
t3169 = -1.*t2721*t3154;
t3172 = t2691*t3160;
t3176 = t3169 + t3172;
t3182 = t2691*t3154;
t3186 = t2721*t3160;
t3195 = t3182 + t3186;
t3239 = t2324*t328*t2138;
t3242 = t2324*t2089*t2213;
t3248 = t3239 + t3242;
t3280 = -1.*t2244*t2134;
t3284 = t3248*t2258;
t3287 = t3280 + t3284;
t3296 = t2324*t2089*t328;
t3299 = -1.*t2324*t2138*t2213;
t3303 = t3296 + t3299;
t3308 = t2413*t3287;
t3310 = t3303*t2426;
t3312 = t3308 + t3310;
t3316 = t2413*t3303;
t3317 = -1.*t3287*t2426;
t3325 = t3316 + t3317;
t3334 = -1.*t2528*t3312;
t3335 = t2492*t3325;
t3337 = t3334 + t3335;
t3341 = t2492*t3312;
t3343 = t2528*t3325;
t3344 = t3341 + t3343;
t3354 = t2635*t3337;
t3355 = t2621*t3344;
t3359 = t3354 + t3355;
t3365 = t2621*t3337;
t3370 = -1.*t2635*t3344;
t3371 = t3365 + t3370;
t3378 = -1.*t2721*t3359;
t3379 = t2691*t3371;
t3382 = t3378 + t3379;
t3386 = t2691*t3359;
t3389 = t2721*t3371;
t3392 = t3386 + t3389;
p_output1[0]=0. + t2050*t2160 + t2186*t2223 + t2243*t2272 + 0.1305*(t2243*t2244 - 1.*t2124*t2258*t2324) + t2124*t2324*t2345 + t2406*t2432 + t2442*t2481 + t2545*t2566 + t2599*t2613 + t2642*t2652 + t2670*t2689 + t2737*t2755 + t2802*t2828 + t2866*t2878 + t2896*t2919 - 0.0216*(t2846*t2878 + t2837*t2919) - 1.1135*(t2837*t2878 - 1.*t2846*t2919) + var1[0];
p_output1[1]=0. + t2101*t2324*t2345 + t2050*t2969 + t2223*t2990 + t2272*t3003 + 0.1305*(-1.*t2101*t2258*t2324 + t2244*t3003) + t2432*t3035 + t2481*t3056 + t2545*t3072 + t2599*t3102 + t2642*t3123 + t2670*t3142 + t2737*t3154 + t2802*t3160 + t2866*t3176 + t2896*t3195 - 0.0216*(t2846*t3176 + t2837*t3195) - 1.1135*(t2837*t3176 - 1.*t2846*t3195) + var1[1];
p_output1[2]=0. + t2050*t2138*t2324 + t2089*t2223*t2324 - 1.*t2134*t2345 + t2272*t3248 + 0.1305*(t2134*t2258 + t2244*t3248) + t2432*t3287 + t2481*t3303 + t2545*t3312 + t2599*t3325 + t2642*t3337 + t2670*t3344 + t2737*t3359 + t2802*t3371 + t2866*t3382 + t2896*t3392 - 0.0216*(t2846*t3382 + t2837*t3392) - 1.1135*(t2837*t3382 - 1.*t2846*t3392) + var1[2];
}
#ifdef MATLAB_MEX_FILE
#include "mex.h"
/*
* Main function
*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
size_t mrows, ncols;
double *var1;
double *p_output1;
/* Check for proper number of arguments. */
if( nrhs != 1)
{
mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "One input(s) required (var1).");
}
else if( nlhs > 1)
{
mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments.");
}
/* The input must be a noncomplex double vector or scaler. */
mrows = mxGetM(prhs[0]);
ncols = mxGetN(prhs[0]);
if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) ||
( !(mrows == 20 && ncols == 1) &&
!(mrows == 1 && ncols == 20)))
{
mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong.");
}
/* Assign pointers to each input. */
var1 = mxGetPr(prhs[0]);
/* Create matrices for return arguments. */
plhs[0] = mxCreateDoubleMatrix((mwSize) 3, (mwSize) 1, mxREAL);
p_output1 = mxGetPr(plhs[0]);
/* Call the calculation subroutine. */
output1(p_output1,var1);
}
#else // MATLAB_MEX_FILE
#include "LeftToeJoint_mex.hh"
namespace SymExpression
{
void LeftToeJoint_mex_raw(double *p_output1, const double *var1)
{
// Call Subroutines
output1(p_output1, var1);
}
}
#endif // MATLAB_MEX_FILE
| 22.939148 | 354 | 0.646299 | EngineeringIV |
aa13e698baea8aaa85d1688784209c652df80ef9 | 1,517 | cpp | C++ | gwen/UnitTest/ComboBox.cpp | Oipo/GWork | 3dd70c090bf8708dd3e7b9cfbcb67163bb7166db | [
"MIT"
] | null | null | null | gwen/UnitTest/ComboBox.cpp | Oipo/GWork | 3dd70c090bf8708dd3e7b9cfbcb67163bb7166db | [
"MIT"
] | null | null | null | gwen/UnitTest/ComboBox.cpp | Oipo/GWork | 3dd70c090bf8708dd3e7b9cfbcb67163bb7166db | [
"MIT"
] | null | null | null | #include "Gwen/UnitTest/UnitTest.h"
#include "Gwen/Controls/ComboBox.h"
using namespace Gwen;
class ComboBox : public GUnit
{
public:
GWEN_CONTROL_INLINE(ComboBox, GUnit)
{
{
Gwen::Controls::ComboBox* combo = new Gwen::Controls::ComboBox(this);
combo->SetPos(50, 50);
combo->SetWidth(200);
combo->AddItem("Option One", "one");
combo->AddItem("Number Two", "two");
combo->AddItem("Door Three", "three");
combo->AddItem("Four Legs", "four");
combo->AddItem("Five Birds", "five");
combo->onSelection.Add(this, &ComboBox::OnComboSelect);
}
{
// Empty..
Gwen::Controls::ComboBox* combo = new Gwen::Controls::ComboBox(this);
combo->SetPos(50, 80);
combo->SetWidth(200);
}
{
// Empty..
Gwen::Controls::ComboBox* combo = new Gwen::Controls::ComboBox(this);
combo->SetPos(50, 110);
combo->SetWidth(200);
for (int i = 0; i < 500; i++)
{
combo->AddItem("Lots Of Options");
}
}
}
void OnComboSelect(Gwen::Controls::Base* pControl)
{
Gwen::Controls::ComboBox* combo = (Gwen::Controls::ComboBox*)pControl;
UnitPrint(Utility::Format("Combo Changed: %s",
combo->GetSelectedItem()->GetText().c_str()));
}
};
DEFINE_UNIT_TEST(ComboBox, "ComboBox");
| 28.622642 | 81 | 0.523401 | Oipo |
aa15517695317103d3e2df47b1b5a140a8422a4b | 5,061 | cpp | C++ | urdf_transform/src/process_model_node.cpp | tjdalsckd/urdf-tools-pkgs | dba0458489aef8d64d59821c47d661e348a9fdf9 | [
"BSD-3-Clause"
] | 6 | 2017-01-17T01:55:39.000Z | 2020-04-24T02:03:30.000Z | urdf_transform/src/process_model_node.cpp | tjdalsckd/urdf-tools-pkgs | dba0458489aef8d64d59821c47d661e348a9fdf9 | [
"BSD-3-Clause"
] | 10 | 2016-06-16T19:38:38.000Z | 2020-12-11T12:13:05.000Z | urdf_transform/src/process_model_node.cpp | tjdalsckd/urdf-tools-pkgs | dba0458489aef8d64d59821c47d661e348a9fdf9 | [
"BSD-3-Clause"
] | 7 | 2017-12-12T17:21:19.000Z | 2021-02-10T05:51:25.000Z | /**
* <ORGANIZATION> = Jennifer Buehler
* <COPYRIGHT HOLDER> = Jennifer Buehler
*
* Copyright (c) 2016 Jennifer Buehler
* 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 <ORGANIZATION> 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 <COPYRIGHT HOLDER> 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 <ros/ros.h>
#include <urdf_traverser/UrdfTraverser.h>
#include <urdf_traverser/PrintModel.h>
#include <urdf_transform/ScaleModel.h>
#include <urdf_transform/JoinFixedLinks.h>
#include <urdf_transform/AlignRotationAxis.h>
#include <string>
using urdf_traverser::UrdfTraverser;
void printHelp(char * progName)
{
ROS_INFO_STREAM("Test tool for urdf transform.");
ROS_INFO_STREAM("Usage: " << progName << " <OP> <input-file> [<from-link>]");
ROS_INFO_STREAM("<OP>: The operation to perform. <print|scale|join|zaxis>");
ROS_INFO_STREAM("If <from-link> is specified, the URDF is processed from this link down instead of the root link.");
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "urdf_traverser_scale_model", ros::init_options::AnonymousName);
if (argc < 3)
{
printHelp(argv[0]);
return 0;
}
enum Operation {PRINT, SCALE, JOIN, ZAXIS};
Operation op;
std::string opArg = argv[1];
if (opArg == "print")
{
op = PRINT;
}
else if (opArg == "scale")
{
op = SCALE;
}
else if (opArg == "join")
{
op = JOIN;
}
else if (opArg == "zaxis")
{
op = ZAXIS;
}
else
{
printHelp(argv[0]);
ROS_ERROR_STREAM("Unkown operation: " << opArg);
return 1;
}
std::string inputFile = argv[2];
std::string fromLink;
if (argc > 3)
{
fromLink = argv[3];
}
ROS_INFO_STREAM("Traversing model from file " << inputFile << "...");
if (!fromLink.empty()) ROS_INFO_STREAM("Starting from link " << fromLink);
bool verbose = false;
ROS_INFO("Loading file...");
UrdfTraverser traverser;
if (!traverser.loadModelFromFile(inputFile))
{
ROS_ERROR_STREAM("Could not load file " << inputFile);
return 0;
}
switch (op)
{
case PRINT:
{
ROS_INFO("###### MODEL #####");
verbose = true;
traverser.printModel(verbose);
ROS_INFO("###### JOINT NAMES #####");
traverser.printJointNames(fromLink);
break;
}
case SCALE:
{
ROS_INFO("###### MODEL BEFORE #####");
verbose = true;
traverser.printModel(verbose);
urdf_transform::scaleModel(traverser, 2);
break;
}
case JOIN:
{
ROS_INFO("Join fixed links...");
if (!urdf_transform::joinFixedLinks(traverser, fromLink))
{
ROS_ERROR_STREAM("Could not join fixed links");
return 0;
}
ROS_INFO("$$$--- Joint names after fixed linked joining:");
traverser.printJointNames(fromLink);
break;
}
case ZAXIS:
{
verbose = true;
ROS_INFO("Align rotation axis...");
ROS_INFO("###### MODEL BEFORE #####");
traverser.printModel(verbose);
Eigen::Vector3d axis(0, 0, 1);
if (!urdf_transform::allRotationsToAxis(traverser, fromLink, axis))
{
ROS_ERROR_STREAM("Could not rotate axes");
return 0;
}
break;
}
default:
{
ROS_ERROR("Unknown operation.");
return 1;
}
}
if (op != PRINT)
{
ROS_INFO("### Model after processing:");
traverser.printModel(verbose);
}
return 0;
}
| 29.770588 | 120 | 0.616084 | tjdalsckd |
aa15ddb1f5fab1254d31980991e9c27d436ac9b5 | 3,822 | cpp | C++ | client/client_query.cpp | RubenAGSilva/deneva | 538f18d296e926055e50cf819c6988a340105476 | [
"Apache-2.0"
] | 1 | 2021-12-15T12:31:18.000Z | 2021-12-15T12:31:18.000Z | client/client_query.cpp | RubenAGSilva/deneva | 538f18d296e926055e50cf819c6988a340105476 | [
"Apache-2.0"
] | null | null | null | client/client_query.cpp | RubenAGSilva/deneva | 538f18d296e926055e50cf819c6988a340105476 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2016 Massachusetts Institute of Technology
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 "client_query.h"
#include "mem_alloc.h"
#include "wl.h"
#include "table.h"
#include "ycsb_query.h"
#include "tpcc_query.h"
#include "pps_query.h"
/*************************************************/
// class Query_queue
/*************************************************/
void
Client_query_queue::init(Workload * h_wl) {
_wl = h_wl;
#if SERVER_GENERATE_QUERIES
if(ISCLIENT)
return;
size = g_thread_cnt;
#else
size = g_servers_per_client;
#endif
query_cnt = new uint64_t * [size];
for ( UInt32 id = 0; id < size; id ++) {
std::vector<BaseQuery*> new_queries(g_max_txn_per_part+4,NULL);
queries.push_back(new_queries);
query_cnt[id] = (uint64_t*)mem_allocator.align_alloc(sizeof(uint64_t));
}
next_tid = 0;
pthread_t * p_thds = new pthread_t[g_init_parallelism - 1];
for (UInt32 i = 0; i < g_init_parallelism - 1; i++) {
pthread_create(&p_thds[i], NULL, initQueriesHelper, this);
}
initQueriesHelper(this);
for (uint32_t i = 0; i < g_init_parallelism - 1; i++) {
pthread_join(p_thds[i], NULL);
}
}
void *
Client_query_queue::initQueriesHelper(void * context) {
((Client_query_queue*)context)->initQueriesParallel();
return NULL;
}
void
Client_query_queue::initQueriesParallel() {
UInt32 tid = ATOM_FETCH_ADD(next_tid, 1);
uint64_t request_cnt;
request_cnt = g_max_txn_per_part + 4;
uint32_t final_request;
if (tid == g_init_parallelism-1) {
final_request = request_cnt;
} else {
final_request = request_cnt / g_init_parallelism * (tid+1);
}
#if WORKLOAD == YCSB
YCSBQueryGenerator * gen = new YCSBQueryGenerator;
gen->init();
#elif WORKLOAD == TPCC
TPCCQueryGenerator * gen = new TPCCQueryGenerator;
#elif WORKLOAD == PPS
PPSQueryGenerator * gen = new PPSQueryGenerator;
#endif
#if SERVER_GENERATE_QUERIES
for ( UInt32 thread_id = 0; thread_id < g_thread_cnt; thread_id ++) {
for (UInt32 query_id = request_cnt / g_init_parallelism * tid; query_id < final_request; query_id ++) {
queries[thread_id][query_id] = gen->create_query(_wl,g_node_id);
}
}
#else
for ( UInt32 server_id = 0; server_id < g_servers_per_client; server_id ++) {
for (UInt32 query_id = request_cnt / g_init_parallelism * tid; query_id < final_request; query_id ++) {
queries[server_id][query_id] = gen->create_query(_wl,server_id+g_server_start_node); // --- test
// if((query_id + server_id) % 2 == 0){
// queries[server_id][query_id] = gen->gen_requests_zipf(server_id+g_server_start_node, _wl, RD);
// }else{
// queries[server_id][query_id] = gen->gen_requests_zipf(server_id+g_server_start_node, _wl, WR);
// }
}
}
#endif
}
bool
Client_query_queue::done() {
return false;
}
BaseQuery *
Client_query_queue::get_next_query(uint64_t server_id,uint64_t thread_id) {
assert(server_id < size);
uint64_t query_id = __sync_fetch_and_add(query_cnt[server_id], 1);
if(query_id > g_max_txn_per_part) {
__sync_bool_compare_and_swap(query_cnt[server_id],query_id+1,0);
query_id = __sync_fetch_and_add(query_cnt[server_id], 1);
}
BaseQuery * query = queries[server_id][query_id];
return query;
}
| 29.627907 | 107 | 0.682889 | RubenAGSilva |
aa17c9640e398bf244ec15b8347076acc6d681d9 | 60,623 | cpp | C++ | src/inst_riscv_bit.cpp | msyksphinz/swimmer_riscv | 065cf3e0dcdcd00cd9bd976285a307d371253ba9 | [
"BSD-3-Clause"
] | 33 | 2015-08-23T02:45:07.000Z | 2019-11-06T23:34:51.000Z | src/inst_riscv_bit.cpp | msyksphinz-self/swimmer_riscv | 065cf3e0dcdcd00cd9bd976285a307d371253ba9 | [
"BSD-3-Clause"
] | 11 | 2015-10-11T15:52:42.000Z | 2019-09-20T14:30:35.000Z | src/inst_riscv_bit.cpp | msyksphinz/swimmer_riscv | 065cf3e0dcdcd00cd9bd976285a307d371253ba9 | [
"BSD-3-Clause"
] | 5 | 2015-02-14T10:07:44.000Z | 2019-09-20T06:37:38.000Z | /*
* Copyright (c) 2015, msyksphinz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
#include <gmpxx.h>
#include <iostream>
#include <iomanip>
#include "inst_list_riscv.hpp"
#include "dec_utils_riscv.hpp"
#include "softfloat.h"
#include "riscv_pe_thread.hpp"
#include "inst_riscv.hpp"
#include "riscv_sysreg_impl.hpp"
#include "inst_ops.hpp"
#include "riscv_sysreg_bitdef.hpp"
uint32_t shuffle32_stage(uint32_t src, uint32_t maskL, uint32_t maskR, int N)
{
uint32_t x = src & ~(maskL | maskR);
x |= ((src << N) & maskL) | ((src >> N) & maskR);
return x;
}
uint32_t shfl32(uint32_t rs1, uint32_t rs2)
{
uint32_t x = rs1;
int shamt = rs2 & 15;
if (shamt & 8) x = shuffle32_stage(x, 0x00ff0000, 0x0000ff00, 8);
if (shamt & 4) x = shuffle32_stage(x, 0x0f000f00, 0x00f000f0, 4);
if (shamt & 2) x = shuffle32_stage(x, 0x30303030, 0x0c0c0c0c, 2);
if (shamt & 1) x = shuffle32_stage(x, 0x44444444, 0x22222222, 1);
return x;
}
uint32_t unshfl32(uint32_t rs1, uint32_t rs2)
{
uint32_t x = rs1;
int shamt = rs2 & 15;
if (shamt & 1) x = shuffle32_stage(x, 0x44444444, 0x22222222, 1);
if (shamt & 2) x = shuffle32_stage(x, 0x30303030, 0x0c0c0c0c, 2);
if (shamt & 4) x = shuffle32_stage(x, 0x0f000f00, 0x00f000f0, 4);
if (shamt & 8) x = shuffle32_stage(x, 0x00ff0000, 0x0000ff00, 8);
return x;
}
UDWord_t shuffle64_stage(UDWord_t src, UDWord_t maskL, UDWord_t maskR, int N)
{
UDWord_t x = src & ~(maskL | maskR);
x |= ((src << N) & maskL) | ((src >> N) & maskR);
return x;
}
UDWord_t shfl64(UDWord_t rs1_val, UDWord_t rs2_val)
{
UDWord_t x = rs1_val;
int shamt = rs2_val & 31;
if (shamt & 16) x = shuffle64_stage(x, 0x0000ffff00000000LL,
0x00000000ffff0000LL, 16);
if (shamt & 8) x = shuffle64_stage(x, 0x00ff000000ff0000LL,
0x0000ff000000ff00LL, 8);
if (shamt & 4) x = shuffle64_stage(x, 0x0f000f000f000f00LL,
0x00f000f000f000f0LL, 4);
if (shamt & 2) x = shuffle64_stage(x, 0x3030303030303030LL,
0x0c0c0c0c0c0c0c0cLL, 2);
if (shamt & 1) x = shuffle64_stage(x, 0x4444444444444444LL,
0x2222222222222222LL, 1);
return x;
}
UDWord_t unshfl64(UDWord_t rs1_val, UDWord_t rs2_val)
{
UDWord_t x = rs1_val;
int shamt = rs2_val & 31;
if (shamt & 1) x = shuffle64_stage(x, 0x4444444444444444LL,
0x2222222222222222LL, 1);
if (shamt & 2) x = shuffle64_stage(x, 0x3030303030303030LL,
0x0c0c0c0c0c0c0c0cLL, 2);
if (shamt & 4) x = shuffle64_stage(x, 0x0f000f000f000f00LL,
0x00f000f000f000f0LL, 4);
if (shamt & 8) x = shuffle64_stage(x, 0x00ff000000ff0000LL,
0x0000ff000000ff00LL, 8);
if (shamt & 16) x = shuffle64_stage(x, 0x0000ffff00000000LL,
0x00000000ffff0000LL, 16);
return x;
}
UDWord_t slo(UDWord_t rs1, UDWord_t rs2, int xlen)
{
int shamt = rs2 & (xlen - 1);
return ~(~rs1 << shamt);
}
void InstEnv::RISCV_INST_SLO (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = ~(~rs1_val << shamt);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SRO (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = ~(~rs1_val >> shamt);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_ROL (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = (rs1_val << shamt) | (rs1_val >> ((m_pe_thread->GetBitModeInt() - shamt) & (m_pe_thread->GetBitModeInt() - 1)));
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_ROR (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = (rs1_val >> shamt) | (rs1_val << ((m_pe_thread->GetBitModeInt() - shamt) & (m_pe_thread->GetBitModeInt() - 1)));
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBCLR (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
int shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = rs1_val & ~(UDWord_t(1) << shamt);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBSET (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
int shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = rs1_val | (UDWord_t(1) << shamt);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBINV (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
int shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = rs1_val ^ (UDWord_t(1) << shamt);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBEXT (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
int shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = 1 & (rs1_val >> shamt);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_GORC (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
DWord_t res = 0;
if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit32) {
UWord_t x = rs1_val;
int shamt = rs2_val & 31;
if (shamt & 1) x |= ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1);
if (shamt & 2) x |= ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2);
if (shamt & 4) x |= ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4);
if (shamt & 8) x |= ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8);
if (shamt & 16) x |= ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16);
res = x;
} else if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit64) {
UDWord_t x = rs1_val;
int shamt = rs2_val & 63;
if (shamt & 1) x |= ((x & 0x5555555555555555LL) << 1) |
((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
if (shamt & 2) x |= ((x & 0x3333333333333333LL) << 2) |
((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
if (shamt & 4) x |= ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) |
((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
if (shamt & 8) x |= ((x & 0x00FF00FF00FF00FFLL) << 8) |
((x & 0xFF00FF00FF00FF00LL) >> 8);
if (shamt & 16) x |= ((x & 0x0000FFFF0000FFFFLL) << 16) |
((x & 0xFFFF0000FFFF0000LL) >> 16);
if (shamt & 32) x |= ((x & 0x00000000FFFFFFFFLL) << 32) |
((x & 0xFFFFFFFF00000000LL) >> 32);
res = x;
}
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_GREV (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t res = 0;
for (uint32_t i = 0; i < m_pe_thread->GetBitModeInt(); i++) {
int j = (i ^ rs2_val) & (m_pe_thread->GetBitModeInt()-1);
res |= ((rs1_val >> i) & 1) << j;
}
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SLOI (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t imm = ExtractBitField (inst_hex, 26, 20);
uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = ~(~rs1_val << shamt);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SROI (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t imm = ExtractBitField (inst_hex, 26, 20);
uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
UDWord_t res = ~(~rs1_val >> shamt);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_RORI (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t imm = ExtractBitField (inst_hex, 26, 20);
uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = (rs1_val >> shamt) | (rs1_val << ((m_pe_thread->GetBitModeInt() - shamt) & (m_pe_thread->GetBitModeInt() - 1)));
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBCLRI (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t imm = ExtractBitField (inst_hex, 26, 20);
int shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = rs1_val & ~(UDWord_t(1) << shamt);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBSETI (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t imm = ExtractBitField (inst_hex, 26, 20);
int shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = rs1_val | (UDWord_t(1) << shamt);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBINVI (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t imm = ExtractBitField (inst_hex, 26, 20);
int shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = rs1_val ^ (UDWord_t(1) << shamt);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBEXTI (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t imm = ExtractBitField (inst_hex, 26, 20);
int shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = 1 & (rs1_val >> shamt);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_GORCI (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t imm = ExtractBitField (inst_hex, 26, 20);
// int shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
DWord_t res = 0;
if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit32) {
UWord_t x = rs1_val;
int shamt = imm & 31;
if (shamt & 1) x |= ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1);
if (shamt & 2) x |= ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2);
if (shamt & 4) x |= ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4);
if (shamt & 8) x |= ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8);
if (shamt & 16) x |= ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16);
res = x;
} else if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit64) {
UDWord_t x = rs1_val;
int shamt = imm & 63;
if (shamt & 1) x |= ((x & 0x5555555555555555LL) << 1) |
((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
if (shamt & 2) x |= ((x & 0x3333333333333333LL) << 2) |
((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
if (shamt & 4) x |= ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) |
((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
if (shamt & 8) x |= ((x & 0x00FF00FF00FF00FFLL) << 8) |
((x & 0xFF00FF00FF00FF00LL) >> 8);
if (shamt & 16) x |= ((x & 0x0000FFFF0000FFFFLL) << 16) |
((x & 0xFFFF0000FFFF0000LL) >> 16);
if (shamt & 32) x |= ((x & 0x00000000FFFFFFFFLL) << 32) |
((x & 0xFFFFFFFF00000000LL) >> 32);
res = x;
}
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_GREVI (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t imm = ExtractBitField (inst_hex, 26, 20);
UDWord_t res = 0;
for (uint32_t i = 0; i < m_pe_thread->GetBitModeInt(); i++) {
int j = (i ^ imm) & (m_pe_thread->GetBitModeInt()-1);
res |= ((rs1_val >> i) & 1) << j;
}
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CMIX (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rs3_addr = ExtractR3Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t rs3_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs3_addr));
UDWord_t res = (rs1_val & rs2_val) | (rs3_val & ~rs2_val);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CMOV (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rs3_addr = ExtractR3Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t rs3_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs3_addr));
UDWord_t res = rs2_val ? rs1_val : rs3_val;
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_FSL (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rs3_addr = ExtractR3Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t rs3_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs3_addr));
uint32_t shamt = rs2_val & (2*m_pe_thread->GetBitModeInt() - 1);
UDWord_t A = rs1_val, B = rs3_val;
if (shamt >= m_pe_thread->GetBitModeInt()) {
shamt -= m_pe_thread->GetBitModeInt();
A = rs3_val;
B = rs1_val;
}
UDWord_t res = shamt ? (A << shamt) | (B >> (m_pe_thread->GetBitModeInt()-shamt)) : A;
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_FSR (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rs3_addr = ExtractR3Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t rs3_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs3_addr));
uint32_t shamt = rs2_val & (2*m_pe_thread->GetBitModeInt() - 1);
UDWord_t A = rs1_val, B = rs3_val;
if (shamt >= m_pe_thread->GetBitModeInt()) {
shamt -= m_pe_thread->GetBitModeInt();
A = rs3_val;
B = rs1_val;
}
UDWord_t res = shamt ? (A >> shamt) | (B << (m_pe_thread->GetBitModeInt()-shamt)) : A;
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_FSRI (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs3_addr = ExtractR3Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs3_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs3_addr));
UDWord_t imm = ExtractBitField (inst_hex, 25, 20);
uint32_t shamt = imm & (2 * m_pe_thread->GetBitModeInt() - 1);
UDWord_t A = rs1_val, B = rs3_val;
if (shamt >= m_pe_thread->GetBitModeInt()) {
shamt -= m_pe_thread->GetBitModeInt();
A = rs3_val;
B = rs1_val;
}
UDWord_t res = shamt ? (A >> shamt) | (B << (m_pe_thread->GetBitModeInt()-shamt)) : A;
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CLZ (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t res = m_pe_thread->GetBitModeInt();
for (uint32_t count = 0; count < m_pe_thread->GetBitModeInt(); count++) {
if ((rs1_val << count) >> (m_pe_thread->GetBitModeInt() - 1)) {
res = count;
break;
}
}
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CTZ (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t res = m_pe_thread->GetBitModeInt();
for (uint32_t count = 0; count < m_pe_thread->GetBitModeInt(); count++) {
if ((rs1_val >> count) & 1) {
res = count;
break;
}
}
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_PCNT (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
int count = 0;
for (uint32_t index = 0; index < m_pe_thread->GetBitModeInt(); index++)
count += (rs1_val >> index) & 1;
DWord_t res = count;
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_BMATFLIP (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t x = rs1_val;
x = shfl64(x, 31);
x = shfl64(x, 31);
x = shfl64(x, 31);
DWord_t res = x;
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SEXT_B (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t res = DWord_t(rs1_val << (m_pe_thread->GetBitModeInt()-8)) >> (m_pe_thread->GetBitModeInt()-8);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SEXT_H (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t res = DWord_t(rs1_val << (m_pe_thread->GetBitModeInt()-16)) >> (m_pe_thread->GetBitModeInt()-16);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CRC32_B (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr);
UDWord_t res = m_pe_thread->crc32(rs1_val, 8);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CRC32_H (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr);
UDWord_t res = m_pe_thread->crc32(rs1_val, 16);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CRC32_W (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
DWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr);
UDWord_t res = m_pe_thread->crc32(rs1_val, 32);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CRC32_D (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
DWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr);
DWord_t res = m_pe_thread->crc32(rs1_val, 64);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CRC32C_B (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr);
UDWord_t res = m_pe_thread->crc32_c(rs1_val, 8);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CRC32C_H (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr);
UDWord_t res = m_pe_thread->crc32_c(rs1_val, 16);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CRC32C_W (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->ReadGReg<DWord_t> (rs1_addr);
UDWord_t res = m_pe_thread->crc32_c(rs1_val, 32);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CRC32C_D (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->ReadGReg<UDWord_t> (rs1_addr);
UDWord_t res = m_pe_thread->crc32_c(rs1_val, 64);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CLMUL (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t res = 0;
for (uint32_t i = 0; i < m_pe_thread->GetBitModeInt(); i++)
if ((rs2_val >> i) & 1)
res ^= rs1_val << i;
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CLMULR (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t res = 0;
for (uint32_t i = 0; i < m_pe_thread->GetBitModeInt(); i++)
if ((rs2_val >> i) & 1)
res ^= rs1_val >> (m_pe_thread->GetBitModeInt()-i-1);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CLMULH (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t res = 0;
for (uint32_t i = 1; i < m_pe_thread->GetBitModeInt(); i++)
if ((rs2_val >> i) & 1)
res ^= rs1_val >> (m_pe_thread->GetBitModeInt()-i);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SHFL (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit32) {
UDWord_t res = shfl32(rs1_val, rs2_val);
m_pe_thread->WriteGReg<Word_t> (rd_addr, res);
} else {
UDWord_t res = shfl64(rs1_val, rs2_val);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
}
void InstEnv::RISCV_INST_UNSHFL (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit32) {
UDWord_t res = unshfl32(rs1_val, rs2_val);
m_pe_thread->WriteGReg<Word_t> (rd_addr, res);
} else {
UDWord_t res = unshfl64(rs1_val, rs2_val);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
}
void InstEnv::RISCV_INST_BDEP (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t res = 0;
for (uint32_t i = 0, j = 0; i < m_pe_thread->GetBitModeInt(); i++)
if ((rs2_val >> i) & 1) {
if ((rs1_val >> j) & 1)
res |= UDWord_t(1) << i;
j++;
}
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_BEXT (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t res = 0;
for (uint32_t i = 0, j = 0; i < m_pe_thread->GetBitModeInt(); i++)
if ((rs2_val >> i) & 1) {
if ((rs1_val >> i) & 1)
res |= UDWord_t(1) << j;
j++;
}
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_PACK (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t lower = (rs1_val << m_pe_thread->GetBitModeInt()/2) >> m_pe_thread->GetBitModeInt()/2;
UDWord_t upper = rs2_val << m_pe_thread->GetBitModeInt()/2;
UDWord_t res = lower | upper;
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_PACKU (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t lower = rs1_val >> m_pe_thread->GetBitModeInt()/2;
UDWord_t upper = (rs2_val >> m_pe_thread->GetBitModeInt()/2) << m_pe_thread->GetBitModeInt()/2;
UDWord_t res = lower | upper;
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
UDWord_t bmatflip(UDWord_t rs1)
{
UDWord_t x = rs1;
x = shfl64(x, 31);
x = shfl64(x, 31);
x = shfl64(x, 31);
return x;
}
void InstEnv::RISCV_INST_BMATOR (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
// transpose of rs2
UDWord_t rs2t = bmatflip(rs2_val);
uint8_t u[8]; // rows of rs1
uint8_t v[8]; // cols of rs2
for (int i = 0; i < 8; i++) {
u[i] = rs1_val >> (i*8);
v[i] = rs2t >> (i*8);
}
UDWord_t res = 0;
for (int i = 0; i < 64; i++) {
if ((u[i / 8] & v[i % 8]) != 0)
res |= 1LL << i;
}
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
UDWord_t pcnt(UDWord_t rs1, unsigned int xlen)
{
int count = 0;
for (uint32_t index = 0; index < xlen; index++)
count += (rs1 >> index) & 1;
return count;
}
void InstEnv::RISCV_INST_BMATXOR (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
// transpose of rs2
UDWord_t rs2t = bmatflip(rs2_val);
uint8_t u[8]; // rows of rs1
uint8_t v[8]; // cols of rs2
for (int i = 0; i < 8; i++) {
u[i] = rs1_val >> (i*8);
v[i] = rs2t >> (i*8);
}
UDWord_t res = 0;
for (int i = 0; i < 64; i++) {
if (pcnt(u[i / 8] & v[i % 8], m_pe_thread->GetBitModeInt()) & 1)
res |= 1LL << i;
}
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_PACKH (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t lower = rs1_val & 255;
UDWord_t upper = (rs2_val & 255) << 8;
UDWord_t res = lower | upper;
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_BFP (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t cfg = rs2_val >> (m_pe_thread->GetBitModeInt()/2);
if ((cfg >> 30) == 2)
cfg = cfg >> 16;
int len = (cfg >> 8) & (m_pe_thread->GetBitModeInt()/2-1);
int off = cfg & (m_pe_thread->GetBitModeInt()-1);
len = len ? len : m_pe_thread->GetBitModeInt()/2;
UDWord_t mask = slo(0, len, m_pe_thread->GetBitModeInt()) << off;
UDWord_t data = rs2_val << off;
DWord_t res = (data & mask) | (rs1_val & ~mask);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SHFLI (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t imm = ExtractBitField (inst_hex, 25, 20);
if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit32) {
UDWord_t res = shfl32(rs1_val, imm);
m_pe_thread->WriteGReg<Word_t> (rd_addr, res);
} else {
UDWord_t res = shfl64(rs1_val, imm);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
}
void InstEnv::RISCV_INST_UNSHFLI (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t imm = ExtractBitField (inst_hex, 25, 20);
if (m_pe_thread->GetBitMode() == RiscvBitMode_t::Bit32) {
UDWord_t res = unshfl32(rs1_val, imm);
m_pe_thread->WriteGReg<Word_t> (rd_addr, res);
} else {
UDWord_t res = unshfl64(rs1_val, imm);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
}
void InstEnv::RISCV_INST_ADDIWU (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t imm = ExtractBitField (inst_hex, 25, 20);
UDWord_t result64 = rs1_val + imm;
UWord_t res = (uint32_t)result64;
m_pe_thread->WriteGReg<Word_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_ADDWU (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t result64 = rs1_val + rs2_val;
UWord_t res = (uint32_t)result64;
m_pe_thread->WriteGReg<Word_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SUBWU (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t result64 = rs1_val - rs2_val;
UWord_t res = (uint32_t)result64;
m_pe_thread->WriteGReg<Word_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_ADDU_W (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t rs2u = (uint32_t)rs2_val;
UDWord_t res = rs1_val + rs2u;
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SUBU_W (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
UDWord_t rs2_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs2_addr));
UDWord_t rs2u = (uint32_t)rs2_val;
UDWord_t res = rs1_val - rs2u;
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SLOW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
Word_t res_32 = ~(~rs1_val << shamt);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SROW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
UWord_t res_32 = ~(~rs1_val >> shamt);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_ROLW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
UWord_t res_32 = (rs1_val << shamt) | (rs1_val >> ((m_pe_thread->GetBitModeInt() - shamt) & (m_pe_thread->GetBitModeInt() - 1)));
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_RORW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
UWord_t res_32 = (rs1_val >> shamt) | (rs1_val << ((m_pe_thread->GetBitModeInt() - shamt) & (m_pe_thread->GetBitModeInt() - 1)));
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SH1ADDU_W (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t res_32 = (rs1_val << 1) + rs2_val;
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SH2ADDU_W (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
Word_t res_32 = (rs1_val << 2) + rs2_val;
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SH3ADDU_W (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
Word_t res_32 = (rs1_val << 3) + rs2_val;
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBCLRW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
Word_t res_32 = rs1_val & ~(UWord_t(1) << shamt);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBSETW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
Word_t res_32 = rs1_val | (UWord_t(1) << shamt);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBINVW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
Word_t res_32 = rs1_val ^ (UWord_t(1) << shamt);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBEXTW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
Word_t res_32 = 1 & (rs1_val >> shamt);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_GORCW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
Word_t res_32 = 0;
uint32_t x = rs1_val;
uint32_t shamt = rs2_val & (m_pe_thread->GetBitModeInt() - 1);
if (shamt & 1) x |= ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1);
if (shamt & 2) x |= ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2);
if (shamt & 4) x |= ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4);
if (shamt & 8) x |= ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8);
if (shamt & 16) x |= ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16);
res_32 = x;
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_GREVW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t res_32 = 0;
for (uint32_t i = 0; i < m_pe_thread->GetBitModeInt(); i++) {
int j = (i ^ rs2_val) & (m_pe_thread->GetBitModeInt()-1);
res_32 |= ((rs1_val >> i) & 1) << j;
}
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SLOIW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UDWord_t rs1_val = m_pe_thread->SExtXlen (m_pe_thread->ReadGReg<UDWord_t> (rs1_addr));
DWord_t imm = ExtractBitField (inst_hex, 24, 20);
uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
Word_t res_32 = ~(~rs1_val << shamt);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SROIW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
DWord_t imm = ExtractBitField (inst_hex, 24, 20);
uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
UWord_t res_32 = ~(~rs1_val >> shamt);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_RORIW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
DWord_t imm = ExtractBitField (inst_hex, 24, 20);
uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
UWord_t res_32 = (rs1_val >> shamt) | (rs1_val << ((m_pe_thread->GetBitModeInt() - shamt) & (m_pe_thread->GetBitModeInt() - 1)));
DWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBCLRIW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<Word_t> (rs1_addr);
DWord_t imm = ExtractBitField (inst_hex, 26, 20);
int shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
UWord_t res_32 = rs1_val & ~(UWord_t(1) << shamt);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBSETIW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<Word_t> (rs1_addr);
DWord_t imm = ExtractBitField (inst_hex, 24, 20);
uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
UWord_t res_32 = rs1_val | (UWord_t(1) << shamt);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SBINVIW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<Word_t> (rs1_addr);
DWord_t imm = ExtractBitField (inst_hex, 24, 20);
uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
UWord_t res_32 = rs1_val ^ (UWord_t(1) << shamt);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_GORCIW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<Word_t> (rs1_addr);
DWord_t imm = ExtractBitField (inst_hex, 24, 20);
uint32_t shamt = imm & (m_pe_thread->GetBitModeInt() - 1);
UWord_t res_32 = 0;
UWord_t x = rs1_val;
if (shamt & 1) x |= ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1);
if (shamt & 2) x |= ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2);
if (shamt & 4) x |= ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4);
if (shamt & 8) x |= ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8);
if (shamt & 16) x |= ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16);
res_32 = x;
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_GREVIW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<Word_t> (rs1_addr);
DWord_t imm = ExtractBitField (inst_hex, 24, 20);
UWord_t res_32 = 0;
for (uint32_t i = 0; i < m_pe_thread->GetBitModeInt(); i++) {
int j = (i ^ imm) & (m_pe_thread->GetBitModeInt()-1);
res_32 |= ((rs1_val >> i) & 1) << j;
}
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_FSLW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rs3_addr = ExtractR3Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t rs3_val = m_pe_thread->ReadGReg<UWord_t> (rs3_addr);
uint32_t actual_xlen = 32;
uint32_t shamt = rs2_val & (2 * actual_xlen - 1);
UWord_t A = rs1_val, B = rs3_val;
if (shamt >= actual_xlen) {
shamt -= actual_xlen;
A = rs3_val;
B = rs1_val;
}
UWord_t res_32 = shamt ? (A << shamt) | (B >> (actual_xlen-shamt)) : A;
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_FSRW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rs3_addr = ExtractR3Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs3_val = m_pe_thread->ReadGReg<UWord_t> (rs3_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
uint32_t actual_xlen = 32;
uint32_t shamt = rs2_val & ( 2 *actual_xlen - 1);
UDWord_t A = rs1_val, B = rs3_val;
if (shamt >= actual_xlen) {
shamt -= actual_xlen;
A = rs3_val;
B = rs1_val;
}
UWord_t res_32 = shamt ? (A >> shamt) | (B << (32-shamt)) : A;
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_FSRIW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs3_addr = ExtractR3Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs3_val = m_pe_thread->ReadGReg<UWord_t> (rs3_addr);
UWord_t imm = ExtractBitField (inst_hex, 24, 20);
uint32_t actual_xlen = 32;
uint32_t shamt = imm & (2*actual_xlen - 1);
UWord_t A = rs1_val, B = rs3_val;
if (shamt >= actual_xlen) {
shamt -= actual_xlen;
A = rs3_val;
B = rs1_val;
}
UWord_t res_32 = shamt ? (A >> shamt) | (B << (32-shamt)) : A;
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CLZW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t res_32 = 32;
for (int count = 0; count < 32; count++) {
if ((rs1_val << count) >> 31) {
res_32 = count;
break;
}
}
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CTZW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
Word_t res_32 = 32;
for (int count = 0; count < 32; count++) {
if ((rs1_val >> count) & 1) {
res_32 = count;
break;
}
}
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_PCNTW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
int count = 0;
for (int index = 0; index < 32; index++)
count += (rs1_val >> index) & 1;
Word_t res_32 = count;
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CLMULW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t res_32 = 0;
for (int i = 0; i < 32; i++)
if ((rs2_val >> i) & 1)
res_32 ^= rs1_val << i;
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CLMULRW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t res_32 = 0;
for (int i = 0; i < 32; i++)
if ((rs2_val >> i) & 1)
res_32 ^= rs1_val >> (32-i-1);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_CLMULHW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t res_32 = 0;
for (int i = 1; i < 32; i++)
if ((rs2_val >> i) & 1)
res_32 ^= rs1_val >> (32-i);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_SHFLW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t res_32 = shfl32(rs1_val, rs2_val);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_UNSHFLW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t res_32 = unshfl32(rs1_val, rs2_val);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_BDEPW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t res_32 = 0;
for (int i = 0, j = 0; i < 32; i++)
if ((rs2_val >> i) & 1) {
if ((rs1_val >> j) & 1)
res_32 |= UWord_t(1) << i;
j++;
}
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_BEXTW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t res_32 = 0;
for (int i = 0, j = 0; i < 32; i++)
if ((rs2_val >> i) & 1) {
if ((rs1_val >> i) & 1)
res_32 |= UWord_t(1) << j;
j++;
}
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_PACKW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t lower = (rs1_val << 32/2) >> 32/2;
UWord_t upper = rs2_val << 32/2;
UWord_t res_32 = lower | upper;
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_PACKUW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t lower = rs1_val >> 32/2;
UWord_t upper = (rs2_val >> 32/2) << 32/2;
UWord_t res_32 = lower | upper;
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
void InstEnv::RISCV_INST_BFPW (InstWord_t inst_hex)
{
RegAddr_t rs1_addr = ExtractR1Field (inst_hex);
RegAddr_t rs2_addr = ExtractR2Field (inst_hex);
RegAddr_t rd_addr = ExtractRDField (inst_hex);
UWord_t rs1_val = m_pe_thread->ReadGReg<UWord_t> (rs1_addr);
UWord_t rs2_val = m_pe_thread->ReadGReg<UWord_t> (rs2_addr);
UWord_t cfg = rs2_val >> (32/2);
if ((cfg >> 30) == 2)
cfg = cfg >> 16;
int len = (cfg >> 8) & (32/2-1);
int off = cfg & (32-1);
len = len ? len : 32/2;
UWord_t mask = slo(0, len, 32) << off;
UWord_t data = rs2_val << off;
Word_t res_32 = (data & mask) | (rs1_val & ~mask);
UDWord_t res = ExtendSign(res_32, 31);
m_pe_thread->WriteGReg<UDWord_t> (rd_addr, res);
}
| 32.418717 | 132 | 0.693994 | msyksphinz |
aa17ee08bdaa5f094a09f0682a73a05f8fca7537 | 1,153 | hpp | C++ | addons/modules/includes/moduleDeleteMarkerAttributes.hpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 1 | 2020-06-07T00:45:49.000Z | 2020-06-07T00:45:49.000Z | addons/modules/includes/moduleDeleteMarkerAttributes.hpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 27 | 2020-05-24T11:09:56.000Z | 2020-05-25T12:28:10.000Z | addons/modules/includes/moduleDeleteMarkerAttributes.hpp | Krzyciu/A3CS | b7144fc9089b5ded6e37cc1fad79b1c2879521be | [
"MIT"
] | 2 | 2020-05-31T08:52:45.000Z | 2021-04-16T23:16:37.000Z |
class GVAR(deleteMarkerSettingsSubCategory): GVAR(moduleSubCategory) {
displayName = CSTRING(Attributes_deleteMarkerSettingsSubCategory);
property = QGVAR(deleteMarkerSettingsSubCategory);
};
#ifndef MODULE_DELETEMARKER
#define DELETEMARKER_COND ((_this getVariable QQGVAR(deleteMarker)) isEqualTo true)
class GVAR(deleteMarker): GVAR(dynamicCheckbox) {
displayName = CSTRING(Attributes_deleteMarker);
tooltip = CSTRING(Attributes_deleteMarker_tooltip);
property = QGVAR(deleteMarker);
defaultValue = "false";
ATTRIBUTE_LOCAL;
};
#else
#define DELETEMARKER_COND (true)
#endif
class GVAR(deleteMarkerName): GVAR(dynamicEdit) {
displayName = CSTRING(Attributes_deleteMarkerName);
tooltip = CSTRING(Attributes_deleteMarkerName_tooltip);
GVAR(description) = CSTRING(Attributes_deleteMarkerName_desc);
property = QGVAR(deleteMarkerName);
defaultValue = "''";
#ifndef MODULE_DELETEMARKER
GVAR(conditionActive) = QUOTE(DELETEMARKER_COND);
#endif
ATTRIBUTE_LOCAL;
};
#undef DELETEMARKER_COND
#ifdef MODULE_DELETEMARKER
#undef MODULE_DELETEMARKER
#endif
| 32.027778 | 87 | 0.753686 | Krzyciu |
aa181775b5bccd5cde843b3a4a8797f84b199527 | 1,006 | cpp | C++ | versions/Flower-Mail(no combine with jiachen)/getbackpwd.cpp | SecretMG/Flower-Mail | 8f9104b11e2a6380355010ebe7e085a6383dd094 | [
"MIT"
] | 2 | 2020-09-20T14:48:58.000Z | 2020-10-21T15:55:41.000Z | work dialog/Alison/sources/getbackpwd.cpp | SecretMG/Flower-Mail | 8f9104b11e2a6380355010ebe7e085a6383dd094 | [
"MIT"
] | null | null | null | work dialog/Alison/sources/getbackpwd.cpp | SecretMG/Flower-Mail | 8f9104b11e2a6380355010ebe7e085a6383dd094 | [
"MIT"
] | 3 | 2020-09-10T00:18:41.000Z | 2020-09-10T02:44:18.000Z | #include "getbackpwd.h"
#include "ui_getbackpwd.h"
#include <QMessageBox>
QString userNameGet;
Getbackpwd::Getbackpwd(QWidget *parent) :
QWidget(parent),
ui(new Ui::Getbackpwd)
{
ui->setupUi(this);
setWindowTitle("找回密码");
connect( ui ->yes_btn, SIGNAL(clicked()), this,SLOT( judgeEmpty() ) );
}
Getbackpwd::~Getbackpwd()
{
delete ui;
}
void Getbackpwd::toReset(){
qDebug() << "in toReset" << endl;
resetPassword = new Resetpassword();
resetPassword -> show();
hide();
}
void Getbackpwd::judgeEmpty(){
userNameGet = ui -> mail_le -> text();
if( userNameGet.isEmpty() ){
QMessageBox::warning(this, tr("警告"),tr("输入为空"),tr("关闭"));
}
else{
if ( judgeExist() == true)
toReset();
}
}
bool Getbackpwd::judgeExist(){
//数据库:判断userGet用户名是否存在,userNameNew
bool isExist = true;
if (isExist == true){
return true;
}
else{
ui ->mail_le->setToolTip(tr("用户名不存在"));
return false;
}
}
| 18.981132 | 74 | 0.595427 | SecretMG |
aa186fba4b7066a011e587db99253983e1b1cb0c | 3,630 | cpp | C++ | examples_oldgl_glfw/129_CubeGridEdit/main.cpp | mmer547/delfem2 | 4f4b28931c96467ac30948e6b3f83150ea530c92 | [
"MIT"
] | 1 | 2020-07-18T17:03:36.000Z | 2020-07-18T17:03:36.000Z | examples_oldgl_glfw/129_CubeGridEdit/main.cpp | mmer547/delfem2 | 4f4b28931c96467ac30948e6b3f83150ea530c92 | [
"MIT"
] | null | null | null | examples_oldgl_glfw/129_CubeGridEdit/main.cpp | mmer547/delfem2 | 4f4b28931c96467ac30948e6b3f83150ea530c92 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2019 Nobuyuki Umetani
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <cmath>
#include <climits>
#if defined(_WIN32) // windows
# define NOMINMAX // to remove min,max macro
# include <windows.h> // should be before glfw3.h
#endif
#define GL_SILENCE_DEPRECATION
#include <GLFW/glfw3.h>
#include "delfem2/cam_projection.h"
#include "delfem2/cam_modelview.h"
#include "delfem2/vec3.h"
#include "delfem2/mshmisc.h"
#include "delfem2/gridcube.h"
#include "delfem2/glfw/viewer3.h"
#include "delfem2/glfw/util.h"
#include "delfem2/opengl/old/funcs.h"
#include "delfem2/opengl/old/gridcube.h"
#ifndef M_PI
# define M_PI 3.141592653589793
#endif
namespace dfm2 = delfem2;
// -----------------------------------------
int main() {
// -------------
class CViewer_CubeGrid : public dfm2::glfw::CViewer3 {
public:
CViewer_CubeGrid() : CViewer3(2.0) {
aCubeGrid.emplace_back(0, 0, 0);
org = dfm2::CVec3d(0, 0, 0);
}
void mouse_press(const float src[3], const float dir[3]) override {
dfm2::CVec3d offsym(0, 0, 0);
if (imode_sym == 2) { offsym.p[2] = -elen * 0.5; }
double src_pick0[3] = {src[0], src[1], src[2]};
double dir_pick0[3] = {dir[0], dir[1], dir[2]};
double offsym0[3];
offsym.CopyTo(offsym0);
Pick_CubeGrid(
icube_picked, iface_picked,
src_pick0, dir_pick0, elen, offsym0, aCubeGrid);
if (edit_mode == EDIT_ADD) {
int ivx1, ivy1, ivz1;
Adj_CubeGrid(
ivx1, ivy1, ivz1,
icube_picked, iface_picked, aCubeGrid);
Add_CubeGrid(aCubeGrid, ivx1, ivy1, ivz1);
if (imode_sym == 1) { Add_CubeGrid(aCubeGrid, ivx1, ivy1, -ivz1 - 1); }
if (imode_sym == 2) { Add_CubeGrid(aCubeGrid, ivx1, ivy1, -ivz1); }
}
if (edit_mode == EDIT_DELETE) {
int ivx1 = aCubeGrid[icube_picked].ivx;
int ivy1 = aCubeGrid[icube_picked].ivy;
int ivz1 = aCubeGrid[icube_picked].ivz;
Del_CubeGrid(aCubeGrid, ivx1, ivy1, ivz1);
if (imode_sym == 1) { Del_CubeGrid(aCubeGrid, ivx1, ivy1, -ivz1 - 1); }
if (imode_sym == 2) { Del_CubeGrid(aCubeGrid, ivx1, ivy1, -ivz1); }
}
}
void key_press(
int key,
[[maybe_unused]] int mods) override {
if (key == GLFW_KEY_A) {
glfwSetWindowTitle(this->window, "Edit Mode: Add");
edit_mode = EDIT_ADD;
}
if (key == GLFW_KEY_D) {
glfwSetWindowTitle(this->window, "Edit Mode: Delete");
edit_mode = EDIT_DELETE;
}
}
void Draw() const {
dfm2::CVec3d offsym(0, 0, 0);
if (imode_sym == 2) { offsym.p[2] = -elen * 0.5; }
for (unsigned int ic = 0; ic < aCubeGrid.size(); ++ic) {
delfem2::opengl::Draw_CubeGrid(
ic == icube_picked, iface_picked,
elen, org + offsym, aCubeGrid[ic]);
}
}
public:
int imode_sym = 2;
std::vector<dfm2::CCubeGrid> aCubeGrid;
const double elen = 1.0;
dfm2::CVec3d org;
unsigned int icube_picked = UINT_MAX;
int iface_picked = -1;
enum EDIT_MODE {
EDIT_NONE,
EDIT_ADD,
EDIT_DELETE,
};
EDIT_MODE edit_mode = EDIT_ADD;
} viewer;
//
dfm2::glfw::InitGLOld();
viewer.OpenWindow();
delfem2::opengl::setSomeLighting();
while (!glfwWindowShouldClose(viewer.window)) {
viewer.DrawBegin_oldGL();
viewer.Draw();
glfwSwapBuffers(viewer.window);
glfwPollEvents();
}
glfwDestroyWindow(viewer.window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| 29.754098 | 79 | 0.609091 | mmer547 |
aa1af73e2354a53447dcd2651873b45b7a1d1b2f | 3,394 | cpp | C++ | classnote/HomeworkReferenceCode/HW1.cpp | Alex-Lin5/cpp_practice | c249362d6bbe932dc1eb4a4b8c51728d58db2aa7 | [
"MIT"
] | null | null | null | classnote/HomeworkReferenceCode/HW1.cpp | Alex-Lin5/cpp_practice | c249362d6bbe932dc1eb4a4b8c51728d58db2aa7 | [
"MIT"
] | null | null | null | classnote/HomeworkReferenceCode/HW1.cpp | Alex-Lin5/cpp_practice | c249362d6bbe932dc1eb4a4b8c51728d58db2aa7 | [
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
class Node {
public:
int value;
Node* next;
Node(int i) { value = i; next = nullptr; }
Node() { next = nullptr; }
};
class LinkedList {
public:
Node* head;
//Node* tail;
LinkedList() { head = nullptr; }
LinkedList(int m, int n);//You can use code from class lectures for this constructor.
void print();//You can use code from class lecture for print.
//***************************************************************************************************
//implement the following member functions group and bubbleSort:
void group();
/*
Group all occurrences of the same numbers together according to the order of appearance.
For a list with values
7 6 12 4 33 12 6 6 7 ,
after grouping, it becomes
7 7 6 6 6 12 12 4 33
Note that in the original sequence, 7 appears before 6 before 12 before 4 before 33.
You are only allowed to change "next" of a node, but not "value."
Do not introduce additional functions.
In-place implementation is required. External structures, such as arrays, are not allowed.
For example, you are not allowed to copy linked list values to outside, and then process the data and copy them
back to linked list.
*/
void bubbleSort();
//you are allowed change both value and next for bubbleSort.
//Like function group, you are not allowed to use any external structures, such as arrays, to help.
//No extra functions allowed
};
LinkedList::LinkedList(int n, int m) {
head = nullptr;
for (int i = 0; i < n; ++i) {
Node* p1 = new Node{ rand() % m };
p1->next = head;
head = p1;
}
}
void LinkedList::print() {
Node* p1{ head };
while (p1) {//while (p1 != nullptr)
cout << p1->value << " ";
p1 = p1->next;
}
}
void LinkedList::group() {
if (!head || !head->next || !head->next->next) {
return;
}
/*Node* pre = head->next->next, *p4 = pre->next, *p4nx = p4->next, *cur = head->next;
head->next = p4;
p4->next = cur;
pre->next = p4nx;*/
Node* p = head;
int num = p->value;
do{
Node* cur = p->next;
while (cur != nullptr && cur->value == p->value) {
p = p->next;
cur = cur->next;
}
Node* change = cur;
if (cur == nullptr) {
break;
}
while ( cur->next != nullptr) {
if (cur->next->value == num) {
Node* last = cur->next->next;
p ->next = cur->next;
cur->next->next = change;
cur->next = last;
p = p ->next;
}
else {
cur = cur->next;
}
}
p = change;
num = p ->value;
if (p ->next == nullptr) {
break;
}
} while (p ->next->next != nullptr || p ->next != nullptr);
}
void LinkedList::bubbleSort() {
if (!head || !head->next) {
return;
}
Node* cur{ head }, * last{ nullptr };
while (last != head->next) {
while (cur->next != last) {
if (cur->value > cur->next->value) {
swap(cur->value, cur->next->value);
}
cur = cur->next;
}
last = cur;
cur = head;
}
/*int swaped =1;
while (swaped) {
Node* p1 = head;
swaped = 0;
while (p1->next != nullptr) {
if (p1 -> value > p1->next->value) {
swap(p1->value, p1->next->value);
swaped = 1;
}
p1 = p1->next;
}
}
*/
}
int main() {//During grading, different cases will be used.
LinkedList L1(50,20);
L1.print();
cout << endl;
L1.group();
L1.print();
cout << endl;
LinkedList L2(50, 25);
L2.print();
cout << endl;
L2.bubbleSort();
L2.print();
return 0;
} | 20.08284 | 112 | 0.581615 | Alex-Lin5 |
aa1c4237ef52ee74da62534aedd97ea8b4d55f77 | 2,108 | cpp | C++ | src/optimizer/pushdown/pushdown_get.cpp | shenyunlong/duckdb | ecb90f22b36a50b051fdd8e0d681bade3365c430 | [
"MIT"
] | null | null | null | src/optimizer/pushdown/pushdown_get.cpp | shenyunlong/duckdb | ecb90f22b36a50b051fdd8e0d681bade3365c430 | [
"MIT"
] | 7 | 2020-08-25T22:24:16.000Z | 2020-09-06T00:16:49.000Z | src/optimizer/pushdown/pushdown_get.cpp | shenyunlong/duckdb | ecb90f22b36a50b051fdd8e0d681bade3365c430 | [
"MIT"
] | null | null | null | #include "duckdb/optimizer/filter_pushdown.hpp"
#include "duckdb/planner/operator/logical_filter.hpp"
#include "duckdb/planner/operator/logical_get.hpp"
#include "duckdb/storage/data_table.hpp"
namespace duckdb {
using namespace std;
unique_ptr<LogicalOperator> FilterPushdown::PushdownGet(unique_ptr<LogicalOperator> op) {
assert(op->type == LogicalOperatorType::GET);
auto &get = (LogicalGet &)*op;
if (!get.tableFilters.empty()) {
if (!filters.empty()) {
//! We didn't managed to push down all filters to table scan
auto logicalFilter = make_unique<LogicalFilter>();
for (auto &f : filters) {
logicalFilter->expressions.push_back(move(f->filter));
}
logicalFilter->children.push_back(move(op));
return move(logicalFilter);
} else {
return op;
}
}
//! FIXME: We only need to skip if the index is in the column being filtered
if (!get.table || !get.table->storage->info->indexes.empty()) {
//! now push any existing filters
if (filters.empty()) {
//! no filters to push
return op;
}
auto filter = make_unique<LogicalFilter>();
for (auto &f : filters) {
filter->expressions.push_back(move(f->filter));
}
filter->children.push_back(move(op));
return move(filter);
}
PushFilters();
vector<unique_ptr<Filter>> filtersToPushDown;
get.tableFilters = combiner.GenerateTableScanFilters(
[&](unique_ptr<Expression> filter) {
auto f = make_unique<Filter>();
f->filter = move(filter);
f->ExtractBindings();
filtersToPushDown.push_back(move(f));
},
get.column_ids);
for (auto &f : get.tableFilters) {
f.column_index = get.column_ids[f.column_index];
}
GenerateFilters();
for (auto &f : filtersToPushDown) {
get.expressions.push_back(move(f->filter));
}
if (!filters.empty()) {
//! We didn't managed to push down all filters to table scan
auto logicalFilter = make_unique<LogicalFilter>();
for (auto &f : filters) {
logicalFilter->expressions.push_back(move(f->filter));
}
logicalFilter->children.push_back(move(op));
return move(logicalFilter);
}
return op;
}
} // namespace duckdb
| 29.690141 | 89 | 0.694497 | shenyunlong |
aa20c13771497d03c19f6317876b9bc0f26d3e3b | 22,987 | cpp | C++ | word2vec/word2vec.cpp | uphere-co/nlp-prototype | c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3 | [
"BSD-3-Clause"
] | null | null | null | word2vec/word2vec.cpp | uphere-co/nlp-prototype | c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3 | [
"BSD-3-Clause"
] | null | null | null | word2vec/word2vec.cpp | uphere-co/nlp-prototype | c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3 | [
"BSD-3-Clause"
] | null | null | null | #include <stdlib.h>
#include <iostream>
#include <thread>
#include <string>
#include <cmath>
#include <inttypes.h>
#include <boost/tr1/random.hpp>
#include "utils.h"
#include "WordEmbed.h"
#define EXP_TABLE_SIZE 1000
#define MAX_EXP 6
#define MAX_CODE_LENGTH 40
#define MAX_SENTENCE_LENGTH 1000
class Word2Vec : public WordEmbed {
private:
unsigned int layer1_size;
int window;
real sample;
int hs, negative;
unsigned int num_threads;
unsigned int iter;
real alpha;
unsigned int classes;
int cbow;
std::string wordvector_file;
int64_t word_count_actual;
real starting_alpha;
std::array<real,(EXP_TABLE_SIZE + 1)> expTable;
clock_t start;
std::vector<real> syn0, syn1, syn1neg;
// Tables
std::array<int, table_size> table;
public:
Word2Vec (
std::string train_file, //Use text data from <file> to train the model
std::string output_file = "", //Use <file> to save the resulting word vectors / word clusters
unsigned int min_count = 5, //This will discard words that appear less than <int> times; default is 5
int debug_mode = 2, //Set the debug mode (default = 2 = more info during training)
int binary = 0, //Save the resulting vectors in binary moded; default is 0 (off)
std::string save_vocab_file = "", //The vocabulary will be saved to <file>
std::string read_vocab_file = "", //The vocabulary will be read from <file>, not constructed from the training data
unsigned int layer1_size = 100, //Set size of word vectors; default is 100
unsigned int window = 5, //Set max skip length between words; default is 5
real sample = 1e-3, //Set threshold for occurrence of words. Those that appear with higher frequency in the training data will be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)
int hs = 0, //Use Hierarchical Softmax; default is 0 (not used)
int negative = 5, //Number of negative examples; default is 5, common values are 3 - 10 (0 = not used)
unsigned int num_threads = 12, //Use <int> threads (default 12)
int iter = 5, //Run more training iterations (default 5)
real alpha = 0.05, //Set the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW
unsigned int classes = 0,//Output word classes rather than word vectors; default number of classes is 0 (vectors are written)
int cbow = 0, //Use the continuous bag of words model; default is 1 (use 0 for skip-gram model)
std::string wordvector_file = "" //Read the trained word vector file
):
WordEmbed (train_file, output_file, min_count, debug_mode, binary,save_vocab_file,read_vocab_file),
layer1_size (layer1_size),
window (window),
sample (sample),
hs (hs),
negative (negative),
num_threads (num_threads),
iter (iter),
alpha (alpha),
classes (classes),
cbow (cbow),
wordvector_file (wordvector_file)
{
min_reduce = 1,
vocab_size = 0;
train_words = 0;
word_count_actual=0;
file_size = 0;
ready_to_train = false;
if( CheckReady() ) ready_to_train = true;
};
void TrainModel ();
void CreateBinaryTree ();
void InitUnigramTable ();
void InitNet ();
void TrainModelThread (int tid);
};
//vocab cn word codelen point code
// Create binary Huffman tree using the word counts
// Frequent words will have short unique binary codes
void Word2Vec::CreateBinaryTree() {
// Words are not sorted at the beginning
int64_t a, b, i, min1i, min2i, pos1, pos2;
int64_t point[MAX_CODE_LENGTH];
char code[MAX_CODE_LENGTH];
std::vector<int64_t> count;
std::vector<int64_t> binary;
std::vector<int64_t> parent_node;
count.reserve(vocab_size * 2 + 1);
binary.reserve(vocab_size * 2 + 1);
parent_node.reserve(vocab_size * 2 +1);
for(a = 0; a < vocab_size; a++) count[a] = vocab[a].cn; // count word frequency
for(a = vocab_size; a < 2 * vocab_size; a++) count[a] = 1e15; // should be larger than any number in the vocabulary count
pos1 = vocab_size - 1;
pos2 = vocab_size; //
// following algorithm constructs the Huffman tree by adding one node at a time
for(a = 0; a < vocab_size - 1; a++) {
// First, find two smallest nodes 'min1, min2'
if(pos1 >= 0) {
if(count[pos1] < count[pos2]) {
min1i = pos1;
pos1--;
} else {
min1i = pos2;
pos2++;
}
} else {
min1i = pos2;
pos2++;
}
if(pos1 >= 0) {
if(count[pos1] < count[pos2]) {
min2i = pos1;
pos1--;
} else {
min2i = pos2;
pos2++;
}
} else {
min2i = pos2;
pos2++;
}
count[vocab_size + a] = count[min1i] + count[min2i]; // Creating parent node with summed frequency
parent_node[min1i] = vocab_size + a;
parent_node[min2i] = vocab_size + a; // Note that having a common parent node
binary[min2i] = 1; // min2i will point to root node at the final state
}
// Now assign binary code to each vocabulary word
for(a = 0; a < vocab_size; a++) {
b = a;
i = 0;
while(1) {
code[i] = binary[b];
point[i] = b;
i++;
b = parent_node[b];
if(b == vocab_size * 2 - 2) break;
}
vocab[a].codelen = i;
vocab[a].point[0] = vocab_size - 2;
for(b = 0; b < i; b++) {
vocab[a].code[i - b - 1] = code[b];
vocab[a].point[i - b] = point[b] - vocab_size;
}
}
}
// Begin of Learning Net
void Word2Vec::InitUnigramTable() {
unsigned int i;
double train_words_pow = 0;
double d1, power = 0.75;
int64_t sum = 0;
for (unsigned int a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power);
for (unsigned int a = 0; a < vocab_size; a++) sum += vocab[a].cn;
std::cout << sum << std::endl;
i = 0;
d1 = pow(vocab[i].cn, power) / train_words_pow;
for (unsigned int a = 0; a < table_size; a++) {
table[a] = i;
if (a / (double)table_size > d1) {
i++;
d1 += pow(vocab[i].cn, power) / train_words_pow;
}
if (i >= vocab_size) i = vocab_size - 1;
}
}
void Word2Vec::InitNet() {
// The name EXP_TABLE is totally mis-guiding.
for (int i = 0; i < EXP_TABLE_SIZE; i++) {
expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP);
expTable[i] = expTable[i] / (expTable[i] + 1);
}
syn0.reserve((int64_t)vocab_size * layer1_size);
if(hs) {
syn1.reserve((int64_t)vocab_size * layer1_size);
for(unsigned int a = 0; a < vocab_size; a++)
for(unsigned int b = 0; b < layer1_size; b++)
syn1[a * layer1_size + b] = 0;
}
if(negative > 0) {
syn1neg.reserve((int64_t)vocab_size * layer1_size);
for(unsigned int a = 0; a < vocab_size; a++)
for(unsigned int b = 0; b < layer1_size; b++)
syn1neg[a * layer1_size + b] = 0;
}
for(unsigned int a = 0; a < vocab_size; a++)
for(unsigned int b = 0; b < layer1_size; b++)
syn0[a * layer1_size + b] = (rand()/(double)RAND_MAX - 0.5) / layer1_size;
//CreateBinaryTree();
}
void Word2Vec::TrainModelThread(int tid){
int64_t a, b, d, word, last_word, sentence_length = 0, sentence_position = 0;
int64_t word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1];
int64_t l1, l2, c, target, label, local_iter = iter;
uint64_t next_random;
real f, g;
clock_t now;
boost::mt19937 rand_engine_int; // rand engine
boost::uniform_int<> rand_int(0, table_size); // set range.
boost::variate_generator<boost::mt19937, boost::uniform_int<>> rand_gen_int(rand_engine_int, rand_int);
boost::mt19937 rand_engine_double; // rand engine
boost::uniform_real<> rand_double(0.0, 1.0);
boost::variate_generator<boost::mt19937, boost::uniform_real<>> rand_gen_double(rand_engine_double, rand_double);
std::vector<real> neu1;
std::vector<real> neu1e;
neu1.reserve(layer1_size);
neu1e.reserve(layer1_size);
std::ifstream inFile(train_file, std::ifstream::in | std::ifstream::binary);
inFile.seekg(file_size / (int64_t)num_threads * (int64_t)tid);
while(1) {
if(word_count - last_word_count > 10000) {
word_count_actual += word_count - last_word_count;
last_word_count = word_count;
if((debug_mode > 1)) {
now = clock();
printf("%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha,
word_count_actual / (real)(iter * train_words + 1) * 100,
word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));
fflush(stdout);
}
alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1));
if(alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;
}
if(sentence_length == 0) {
while(1) {
word = ReadWordIndex(inFile);
if(inFile.eof()) break;
if(word == -1) continue;
word_count++;
if(word == 0) break;
// The subsampling randomly discards frequent words while keeping the ranking same
if(sample > 0) {
real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn;
if(ran < rand_gen_double()) continue;
}
sen[sentence_length] = word;
sentence_length++;
if(sentence_length >= MAX_SENTENCE_LENGTH) break;
}
sentence_position = 0;
}
if(inFile.eof() || (word_count > train_words / num_threads )) {
word_count_actual += word_count - last_word_count;
local_iter--;
if(local_iter == 0) break;
word_count = 0;
last_word_count = 0;
sentence_length = 0;
if(inFile.eof()) {
inFile.clear();
inFile.seekg(file_size / (int64_t)num_threads * (int64_t)tid);
}
else {
inFile.seekg(file_size / (int64_t)num_threads * (int64_t)tid);
}
continue;
}
word = sen[sentence_position];
if(word == -1) continue;
// Network Initialization
for(c = 0; c < layer1_size; c++) neu1[c] = 0;
for(c = 0; c < layer1_size; c++) neu1e[c] = 0;
b = rand_gen_int() % window;
// Skip-gram
{
for(a = b; a < window * 2 + 1 - b; a++) if(a != window) {
c = sentence_position - window + a;
if(c < 0) continue;
if(c >= sentence_length) continue;
last_word = sen[c];
if(last_word == -1) continue;
l1 = last_word * layer1_size;
// Hierarchical Softmax
if(hs) for(d = 0; d < vocab[word].codelen; d++) {
f = 0;
l2 = vocab[word].point[d] * layer1_size;
// Propagate hidden -> output
for(c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1[c + l2];
if(f <= -MAX_EXP) continue;
else if(f >= MAX_EXP) continue;
else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
// g is the gradient multiplied by the learning rate
g = (1 - vocab[word].code[d] - f) * alpha;
// Backpropagate errors output -> hidden
for(c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2];
// Learn weights hidden -> output
for(c = 0; c < layer1_size; c++) syn1[c + l2] += g * syn0[c +l1];
}
// Negative Sampling
if(negative > 0) for (d = 0; d < negative + 1 ; d++) {
if(d == 0) {
target = word;
label = 1;
} else {
next_random = rand_gen_int();
target = table[next_random % table_size];
if(target == 0) target = next_random % (vocab_size - 1) + 1;
if(target == word) continue;
label = 0;
}
l2 = target * layer1_size;
f = 0;
for(c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg[c + l2];
if(f > MAX_EXP) g = (label - 1) * alpha;
else if(f < -MAX_EXP) g = (label - 0) * alpha;
else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;
for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];
for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn0[c + l1];
}
// Learn weights input -> hidden
for(c = 0; c < layer1_size; c++) syn0[c + l1] += neu1e[c];
}
}
sentence_position++;
if(sentence_position >= sentence_length) {
sentence_length = 0;
continue;
}
}
inFile.close();
}
void Word2Vec::TrainModel() {
std::ofstream outFile;
std::vector<std::thread> th;
starting_alpha = alpha;
std::cout << "Starting training using file " << train_file << std::endl;
if(read_vocab_file != "") ReadVocab();
else ExtractVocabFromTrainFile();
if(save_vocab_file != "") SaveVocab();
if(output_file[0] == 0) return;
// Initialization
InitNet();
if(negative > 0)
InitUnigramTable();
start = clock(); // start to measure time
for(int i = 0; i < num_threads; i++) {
th.push_back(std::thread(&Word2Vec::TrainModelThread, this, i));
}
for(auto &t : th) {
t.join();
}
//TrainModelThread(); // For the single thread
outFile.open(output_file, std::ofstream::out | std::ofstream::binary);
if(classes == 0) {
outFile << vocab_size << " " << layer1_size << std::endl;
for(unsigned int a = 0; a < vocab_size; a++) {
outFile << vocab[a].word << " ";
if(binary) for(unsigned int b = 0; b < layer1_size; b++) outFile << syn0[a * layer1_size + b] << " ";
else for(unsigned int b = 0; b < layer1_size; b++) outFile << syn0[a * layer1_size + b] << " ";
outFile << std::endl;
}
} else {
// Run K-means on the word vectors
unsigned int clcn = classes, iter = 10, closeid;
real closev, x;
std::vector<int> centcn, cl;
std::vector<real> cent;
centcn.reserve(classes);
cl.reserve(vocab_size);
cent.reserve(classes * layer1_size);
for (unsigned int a = 0; a < vocab_size; a++) cl[a] = a % clcn;
for (unsigned int a = 0; a < iter; a++) {
for (unsigned int b = 0; b < clcn * layer1_size; b++) cent[b] = 0;
for (unsigned int b = 0; b < clcn; b++) centcn[b] = 1;
for (unsigned int c = 0; c < vocab_size; c++) {
for (unsigned int d = 0; d < layer1_size; d++) cent[layer1_size * cl[c] + d] += syn0[c * layer1_size + d];
centcn[cl[c]]++;
}
for (unsigned int b = 0; b < clcn; b++) {
closev = 0;
for (unsigned int c = 0; c < layer1_size; c++) {
cent[layer1_size * b + c] /= centcn[b];
closev += cent[layer1_size * b + c] * cent[layer1_size * b + c];
}
closev = sqrt(closev);
for (unsigned int c = 0; c < layer1_size; c++) cent[layer1_size * b + c] /= closev;
}
for (unsigned int c = 0; c < vocab_size; c++) {
closev = -10;
closeid = 0;
for (unsigned int d = 0; d < clcn; d++) {
x = 0;
for (unsigned int b = 0; b < layer1_size; b++) x += cent[layer1_size * d + b] * syn0[c * layer1_size + b];
if (x > closev) {
closev = x;
closeid = d;
}
}
cl[c] = closeid;
}
}
// Save the K-means classes
for (unsigned int a = 0; a < vocab_size; a++) outFile << vocab[a].word << " " << cl[a] << std::endl;
}
outFile.close();
}
// End of Learning Net
// main function arguments
void printHelp() {
std::cout << "c++ word2vector implementation \n\n";
std::cout << "Options:\n";
std::cout << "Parameters for training:\n";
std::cout << "\t-train <file>\n";
std::cout << "\t\tUse text data from <file> to train the model\n";
std::cout << "\t-output <file>\n";
std::cout << "\t\tUse <file> to save the resulting word vectors / word clusters\n";
std::cout << "\t-size <int>\n";
std::cout << "\t\tSet size of word vectors; default is 100\n";
std::cout << "\t-window <int>\n";
std::cout << "\t\tSet max skip length between words; default is 5\n";
std::cout << "\t-sample <float>\n";
std::cout << "\t\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\n";
std::cout << "\t\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\n";
std::cout << "\t-hs <int>\n";
std::cout << "\t\tUse Hierarchical Softmax; default is 0 (not used)\n";
std::cout << "\t-negative <int>\n";
std::cout << "\t\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n";
std::cout << "\t-threads <int>\n";
std::cout << "\t\tUse <int> threads (default 12)\n";
std::cout << "\t-iter <int>\n";
std::cout << "\t\tRun more training iterations (default 5)\n";
std::cout << "\t-min-count <int>\n";
std::cout << "\t\tThis will discard words that appear less than <int> times; default is 5\n";
std::cout << "\t-alpha <float>\n";
std::cout << "\t\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n";
std::cout << "\t-classes <int>\n";
std::cout << "\t\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\n";
std::cout << "\t-debug <int>\n";
std::cout << "\t\tSet the debug mode (default = 2 = more info during training)\n";
std::cout << "\t-binary <int>\n";
std::cout << "\t\tSave the resulting vectors in binary moded; default is 0 (off)\n";
std::cout << "\t-save-vocab <file>\n";
std::cout << "\t\tThe vocabulary will be saved to <file>\n";
std::cout << "\t-read-vocab <file>\n";
std::cout << "\t\tThe vocabulary will be read from <file>, not constructed from the training data\n";
std::cout << "\t-cbow <int>\n";
std::cout << "\t\tUse the continuous bag of words model; default is 1 (use 0 for skip-gram model)\n";
std::cout << "\t-wordvector <file>\n";
std::cout << "\t\tRead the trained word vector file\n";
std::cout << "\nExamples:\n";
std::cout << "./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -cbow 1 -iter 3\n\n";
}
int argpos(const char *str, int argc, char **argv) {
std::string s_str(str);
std::vector<std::string> s_argv(argv,argv+argc);
int i=0;
while (i<argc) {
if(s_str == s_argv[i]) break;
i++;
}
if(i == argc) i=0;
return i;
}
Word2Vec *arg_to_w2v(int argc, char **argv) {
int i;
int layer1_size = 100;
std::string train_file ="", save_vocab_file = "", read_vocab_file = "";
int debug_mode =2, binary = 0, cbow = 0;
real alpha = 0.05;
std::string output_file = "";
int window = 5;
real sample = 1e-3;
int hs = 0, negative = 5, num_threads = 12;
int64_t iter = 5;
int min_count = 5;
int64_t classes = 0;
std::string wordvector_file = "";
if ((i = argpos("-size", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]);
if ((i = argpos("-train", argc, argv)) > 0) train_file = argv[i + 1];
if ((i = argpos("-save-vocab", argc, argv)) > 0) save_vocab_file = argv[i + 1];
if ((i = argpos("-read-vocab", argc, argv)) > 0) read_vocab_file = argv[i + 1];
if ((i = argpos("-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]);
if ((i = argpos("-binary", argc, argv)) > 0) binary = atoi(argv[i + 1]);
if ((i = argpos("-cbow", argc, argv)) > 0) cbow = atoi(argv[i + 1]);
if (cbow) alpha = 0.05; else alpha = 0.025;
if ((i = argpos("-alpha", argc, argv)) > 0) alpha = atof(argv[i + 1]);
if ((i = argpos("-output", argc, argv)) > 0) output_file = argv[i + 1];
if ((i = argpos("-window", argc, argv)) > 0) window = atoi(argv[i + 1]);
if ((i = argpos("-sample", argc, argv)) > 0) sample = atof(argv[i + 1]);
if ((i = argpos("-hs", argc, argv)) > 0) hs = atoi(argv[i + 1]);
if ((i = argpos("-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]);
if ((i = argpos("-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]);
if ((i = argpos("-iter", argc, argv)) > 0) iter = atoi(argv[i + 1]);
if ((i = argpos("-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]);
if ((i = argpos("-classes", argc, argv)) > 0) classes = atoi(argv[i + 1]);
if ((i = argpos("-wordvector", argc, argv)) > 0) wordvector_file = argv[i + 1];
Word2Vec *w2v = new Word2Vec (
train_file,
output_file,
min_count,
debug_mode,
binary,
save_vocab_file,
read_vocab_file,
layer1_size,
window,
sample,
hs,
negative,
num_threads,
iter,
alpha,
classes,
cbow,
wordvector_file );
return w2v;
}
int main(int argc, char **argv) {
std::srand(11596521);
Word2Vec *w2v;
if(argc < 2) { printHelp(); return 1; }
else {
w2v = arg_to_w2v(argc, argv);
}
w2v->TrainModel();
return 0;
}
| 39.160136 | 212 | 0.52869 | uphere-co |
aa20dff7223c47adb81663ebfe9fc2b3d2f82be3 | 867 | cpp | C++ | mainwindow2.cpp | casey-c/spiretool | eaeeb1fb3b5d47b307e45f4f20b55b4cf7dfb6f3 | [
"MIT"
] | 5 | 2020-04-22T17:48:10.000Z | 2021-01-20T17:47:15.000Z | mainwindow2.cpp | casey-c/spiretool | eaeeb1fb3b5d47b307e45f4f20b55b4cf7dfb6f3 | [
"MIT"
] | null | null | null | mainwindow2.cpp | casey-c/spiretool | eaeeb1fb3b5d47b307e45f4f20b55b4cf7dfb6f3 | [
"MIT"
] | 2 | 2020-04-23T14:26:33.000Z | 2021-03-29T07:51:35.000Z | #include "mainwindow2.h"
#include "ui_mainwindow2.h"
#include "potiondisplay.h"
#include "carddisplay.h"
MainWindow2::MainWindow2(QWidget *parent) :
QWidget(parent),
ui(new Ui::MainWindow2)
{
ui->setupUi(this);
// CustomButton* button = new CustomButton(this, "Runs");
// this->ui->layout_options->addWidget(button);
// this->ui->layout_options->addWidget(new CustomButton(this, "statistics"));
// this->ui->layout_options->addWidget(new CustomButton(this, "help"));
// this->ui->layout_options->addWidget(new CustomButton(this, "options"));
// this->ui->layout_options->addStretch(1);
// this->ui->layout_potions->addWidget(new PotionDisplay());
// this->ui->layout_cards->addWidget(new CardDisplay());
//this->ui->gridLayout->addItem(new QSpacerItem(Qt::Horizontal));
}
MainWindow2::~MainWindow2()
{
delete ui;
}
| 27.09375 | 80 | 0.688581 | casey-c |