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 float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 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 float64 1 77k ⌀ | 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 float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
80c24b7d826a1b034e18ffa62ce8661006267914 | 5,300 | cpp | C++ | PersistentDSU.cpp | RohitTheBoss007/CodeforcesSolutions | 4025270fb22a6c5c5276569b42e839f35b9ce09b | [
"MIT"
] | 2 | 2020-06-15T09:20:26.000Z | 2020-10-01T19:24:07.000Z | PersistentDSU.cpp | RohitTheBoss007/Coding-Algorithms | 4025270fb22a6c5c5276569b42e839f35b9ce09b | [
"MIT"
] | null | null | null | PersistentDSU.cpp | RohitTheBoss007/Coding-Algorithms | 4025270fb22a6c5c5276569b42e839f35b9ce09b | [
"MIT"
] | null | null | null | // Problem: Persistent UnionFind (https://judge.yosupo.jp/problem/persistent_unionfind)
// Contest: Library Checker
// Time: 2020-12-16 23:45:07
// 私に忍び寄るのをやめてください、ありがとう
#include<bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define ll long long
#define int long long
#define mod 1000000007 //998244353
#define fast ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define f(i,n) for(ll i=0;i<n;i++)
#define fore(i, a, b) for (ll i = (ll)(a); i <= (ll)(b); ++i)
#define nl "\n"
#define trace(x) cerr<<#x<<": "<<x<<" "<<endl
#define trace2(x, y) cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl
#define trace3(x, y, z) cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl
#define trace4(a, b, c, d) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl
#define x first
#define y second
#define vc vector
#define pb push_back
#define ar array
#define all(a) (a).begin(), (a).end()
#define rall(x) (x).rbegin(), (x).rend()
#define ms(v,n,x) fill(v,v+n,x);
#define init(c,a) memset(c,a,sizeof(c))
#define pll pair<ll,ll>
#define mll map<ll,ll>
#define sll set<ll>
#define vll vector<ll>
#define vpll vector<pll>
#define inf 9e18
#define cases ll T;cin>>T;while(T--)
#define BLOCK 500
//const double PI = 3.141592653589793238460;
template<typename T> bool mmax(T &m, const T q) { if (m < q) {m = q; return true;} else return false; }
template<typename T> bool mmin(T &m, const T q) { if (m > q) {m = q; return true;} else return false; }
typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
// void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif
mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());
template< typename T, int LOG >
struct PersistentArray {
struct Node {
T data;
Node *child[1 << LOG] = {};
Node() {}
Node(const T &data) : data(data) {}
};
Node *root;
PersistentArray() : root(nullptr) {}
T get(Node *t, int k) {
if(k == 0) return t->data;
return get(t->child[k & ((1 << LOG) - 1)], k >> LOG);
}
T get(const int &k) {
return get(root, k);
}
pair< Node *, T * > mutable_get(Node *t, int k) {
t = t ? new Node(*t) : new Node();
if(k == 0) return {t, &t->data};
auto p = mutable_get(t->child[k & ((1 << LOG) - 1)], k >> LOG);
t->child[k & ((1 << LOG) - 1)] = p.first;
return {t, p.second};
}
T *mutable_get(const int &k) {
auto ret = mutable_get(root, k);
root = ret.first;
return ret.second;
}
Node *build(Node *t, const T &data, int k) {
if(!t) t = new Node();
if(k == 0) {
t->data = data;
return t;
}
auto p = build(t->child[k & ((1 << LOG) - 1)], data, k >> LOG);
t->child[k & ((1 << LOG) - 1)] = p;
return t;
}
void build(const vector< T > &v) {
root = nullptr;
for(int i = 0; i < v.size(); i++) {
root = build(root, v[i], i);
}
}
};
/*
* @brief Persistent-Union-Find(永続Union-Find)
*/
struct PersistentUnionFind {
PersistentArray< int, 3 > data;
PersistentUnionFind() {}
PersistentUnionFind(int sz) {
data.build(vector< int >(sz, -1));
}
int find(int k) {
int p = data.get(k);
return p >= 0 ? find(p) : k;
}
int size(int k) {
return (-data.get(find(k)));
}
bool unite(int x, int y) {
x = find(x);
y = find(y);
if(x == y) return false;
auto u = data.get(x);
auto v = data.get(y);
if(u < v) {
auto a = data.mutable_get(x);
*a += v;
auto b = data.mutable_get(y);
*b = x;
} else {
auto a = data.mutable_get(y);
*a += u;
auto b = data.mutable_get(x);
*b = y;
}
return true;
}
};
int32_t main()
{
fast
cout << fixed << setprecision(12);
ll n,q;
cin>>n>>q;
vc<PersistentUnionFind> uf(q+1);
uf[0]= PersistentUnionFind(n);
fore(i,1,q){
ll t,k,u,v;
cin>>t>>k>>u>>v;k++;
if(t==0){
uf[i]=uf[k];
uf[i].unite(u,v);
}
else{
if(uf[k].find(u)==uf[k].find(v))cout<<1<<nl;
else cout<<0<<nl;
}
}
return 0;
}
| 25.603865 | 118 | 0.558113 |
80c432c7b4ad76f4f3a2e9fda75cd363145327f3 | 1,833 | cpp | C++ | test812/videocapturethread.cpp | LangleyChang/GoProMultiSreen | 0ef2dd766f5dc2df047182dd906c55b8cbee4163 | [
"Apache-2.0"
] | 1 | 2020-01-01T20:04:47.000Z | 2020-01-01T20:04:47.000Z | test812/videocapturethread.cpp | LangleyChang/GoProMultiSreen | 0ef2dd766f5dc2df047182dd906c55b8cbee4163 | [
"Apache-2.0"
] | null | null | null | test812/videocapturethread.cpp | LangleyChang/GoProMultiSreen | 0ef2dd766f5dc2df047182dd906c55b8cbee4163 | [
"Apache-2.0"
] | null | null | null | #include "videocapturethread.h"
#include <QDebug>
#include <opencv2/highgui/highgui.hpp>
VideoCaptureThread::VideoCaptureThread(int cameraNum = 0) : cameraNum(cameraNum)
{
isRecording = false;
camera = NULL;
vWriter = NULL;
//connect(this, SIGNAL(finished()), this, SLOT(deleteLater()));
}
VideoCaptureThread::~VideoCaptureThread()
{
if(camera != NULL)
delete camera;
if(vWriter != NULL)
delete vWriter;
}
void VideoCaptureThread::run()
{
camera = new VideoCapture(cameraNum);
if(camera != NULL && camera -> isOpened())
{
cameraIsOpen(cameraNum);
cv::Mat src;
//int k = 100;
while(!this->isInterruptionRequested() )
{
for(int i = 0;i < 5;i ++)
{
*camera >> src;
}
if(!src.empty())
{
updateFrame(src, cameraNum);
if(isRecording)
vWriter->write(src);
src.release();
}
//qDebug() << k;
QThread::usleep(0);
}
}
qDebug() << "completed";
}
void VideoCaptureThread::startRecording()
{
isRecording = true;
stringstream temp;
temp << cameraNum;
QDateTime current_date_time = QDateTime::currentDateTime();
QString timestr = current_date_time.toString("yyyy-MM-dd hh.mm.ss");
const string NAME = "result " + temp.str() + timestr.toStdString() +".avi";
if(camera->isOpened())
{
vWriter = new VideoWriter(NAME, CV_FOURCC('i', 'Y', 'U', 'V'), 15.,
Size(camera->get(CAP_PROP_FRAME_WIDTH), camera->get(CAP_PROP_FRAME_HEIGHT)), true);
}
}
void VideoCaptureThread::stopRecording()
{
isRecording = false;
if(camera->isOpened())
{
vWriter->release();
}
}
| 23.202532 | 113 | 0.554283 |
80c5a2a27d50f3aa69dc4866d2f39309eece010a | 3,440 | hpp | C++ | include/tao/json/events/debug.hpp | mallexxx/json | da7ae64ef1af13949a9983a92fddac44390c4951 | [
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | null | null | null | include/tao/json/events/debug.hpp | mallexxx/json | da7ae64ef1af13949a9983a92fddac44390c4951 | [
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | null | null | null | include/tao/json/events/debug.hpp | mallexxx/json | da7ae64ef1af13949a9983a92fddac44390c4951 | [
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | null | null | null | // Copyright (c) 2016-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/json/
#ifndef TAO_JSON_EVENTS_DEBUG_HPP
#define TAO_JSON_EVENTS_DEBUG_HPP
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <ostream>
#include <string>
#include "../binary_view.hpp"
#include "../external/ryu.hpp"
#include "../internal/escape.hpp"
#include "../internal/hexdump.hpp"
namespace tao
{
namespace json
{
namespace events
{
// Events consumer that writes the events to a stream for debug purposes.
class debug
{
private:
std::ostream& os;
public:
explicit debug( std::ostream& in_os ) noexcept
: os( in_os )
{
}
void null()
{
os << "null\n";
}
void boolean( const bool v )
{
if( v ) {
os << "boolean: true\n";
}
else {
os << "boolean: false\n";
}
}
void number( const std::int64_t v )
{
os << "std::int64_t: " << v << '\n';
}
void number( const std::uint64_t v )
{
os << "std::uint64_t: " << v << '\n';
}
void number( const double v )
{
os << "double: ";
if( !std::isfinite( v ) ) {
os << v;
}
else {
ryu::d2s_stream( os, v );
}
os << '\n';
}
void string( const std::string_view v )
{
os << "string: \"";
internal::escape( os, v );
os << "\"\n";
}
void binary( const tao::binary_view v )
{
os << "binary: ";
internal::hexdump( os, v );
os << '\n';
}
void begin_array()
{
os << "begin array\n";
}
void begin_array( const std::size_t size )
{
os << "begin array " << size << '\n';
}
void element()
{
os << "element\n";
}
void end_array()
{
os << "end array\n";
}
void end_array( const std::size_t size )
{
os << "end array " << size << '\n';
}
void begin_object()
{
os << "begin object\n";
}
void begin_object( const std::size_t size )
{
os << "begin object " << size << '\n';
}
void key( const std::string_view v )
{
os << "key: \"";
internal::escape( os, v );
os << "\"\n";
}
void member()
{
os << "member\n";
}
void end_object()
{
os << "end object\n";
}
void end_object( const std::size_t size )
{
os << "end object " << size << '\n';
}
};
} // namespace events
} // namespace json
} // namespace tao
#endif
| 22.193548 | 82 | 0.371802 |
80c73e13996af716a05b3761f690bd9a902903d4 | 9,090 | cpp | C++ | src/translation_unit_base.cpp | achreto/fm-translation-framework | a46afcc43f94c8a224f32fcad988a830689a9256 | [
"MIT"
] | null | null | null | src/translation_unit_base.cpp | achreto/fm-translation-framework | a46afcc43f94c8a224f32fcad988a830689a9256 | [
"MIT"
] | null | null | null | src/translation_unit_base.cpp | achreto/fm-translation-framework | a46afcc43f94c8a224f32fcad988a830689a9256 | [
"MIT"
] | null | null | null | /**
* Translation Unit Base class implementation
*
* SPDX-License-Identifier: MIT
*
* Copyright (C) 2022, Reto Achermann (The University of British Columbia)
*/
#include "pv/PVBusMaster.h"
#include "pv/PVAccessWidth.h"
#include <framework/translation_unit_base.hpp>
#include <framework/interface_base.hpp>
#include <framework/logging.hpp>
/*
* -------------------------------------------------------------------------------------------
* Reset
* -------------------------------------------------------------------------------------------
*/
void TranslationUnitBase::reset(void)
{
Logging::info("resetting translation unit '%s'", this->_name.c_str());
this->get_state()->reset();
this->get_interface()->reset();
Logging::info("reset completed");
}
void TranslationUnitBase::set_reset(bool signal_level) { }
/*
* -------------------------------------------------------------------------------------------
* Printing Functionality
* -------------------------------------------------------------------------------------------
*/
// prints the global state
std::ostream &TranslationUnitBase::print_global_state(std::ostream &os)
{
return os;
}
// prints the translation steps for an address
std::ostream &TranslationUnitBase::print_translation(std::ostream &os, lvaddr_t addr)
{
return os;
}
/*
* -------------------------------------------------------------------------------------------------
* Configuration Space
* -------------------------------------------------------------------------------------------------
*/
pv::Tx_Result TranslationUnitBase::control_read(pv::ReadTransaction tx)
{
access_mode_t mode;
uint64_t value;
Logging::debug("TranslationUnit::control_read([%lx..%lx])", tx.getAddress(),
tx.getAddressEndIncl());
// we want only to support aligned accesses to the configuration space
if (!tx.isAligned()) {
Logging::info("TranslationUnit::control_read(): unaligned data access.");
return pv::Tx_Result(pv::Tx_Data::TX_ALIGNMENTABORT);
}
if (tx.isNonSecure()) {
if (tx.isPrivileged()) {
mode = ACCESS_MODE_NOSEC_READ;
} else {
mode = ACCESS_MODE_USER_READ;
}
} else {
mode = ACCESS_MODE_SEC_READ;
}
auto iface = this->get_interface();
bool r = iface->handle_register_read(tx.getAddress(), tx.getTransactionByteSize(), mode,
&value);
if (!r) {
Logging::debug("TranslationUnit::control_write(): read failed.");
return pv::Tx_Result(pv::Tx_Data::TX_TRANSFAULT);
}
switch (tx.getTransactionByteSize()) {
case 1: {
return tx.setReturnData8(value);
}
case 2: {
// XXX: work around,as the following statement somehow causes issues...
// return tx.setReturnData16(value);
*static_cast<uint16_t *>(tx.referenceDataValue()) = value;
return pv::Tx_Result(pv::Tx_Data::TX_OK);
}
case 4: {
return tx.setReturnData32(value);
}
case 8: {
return tx.setReturnData64(value);
}
default:
return pv::Tx_Result(pv::Tx_Data::TX_ALIGNMENTABORT);
}
}
pv::Tx_Result TranslationUnitBase::control_write(pv::WriteTransaction tx)
{
access_mode_t mode;
uint64_t value;
Logging::debug("TranslationUnitBase::control_write([%lx..%lx])", tx.getAddress(),
tx.getAddressEndIncl());
// we want only to support aligned accesses to the configuration space
if (!tx.isAligned()) {
Logging::debug("TranslationUnitBase::control_write(): unaligned data access.");
return pv::Tx_Result(pv::Tx_Data::TX_ALIGNMENTABORT);
}
if (tx.isNonSecure()) {
if (tx.isPrivileged()) {
mode = ACCESS_MODE_NOSEC_READ;
} else {
mode = ACCESS_MODE_USER_READ;
}
} else {
mode = ACCESS_MODE_SEC_READ;
}
switch (tx.getTransactionByteSize()) {
case 1:
value = tx.getData8();
break;
case 2:
value = tx.getData16();
break;
case 4:
value = tx.getData32();
break;
case 8:
value = tx.getData64();
break;
default:
Logging::info("TranslationUnitBase::control_write(): unsupported transaction size.");
return pv::Tx_Result(pv::Tx_Data::TX_ALIGNMENTABORT);
}
auto iface = this->get_interface();
bool r = iface->handle_register_write(tx.getAddress(), tx.getTransactionByteSize(), mode,
value);
if (!r) {
Logging::debug("TranslationUnitBase::control_write(): write failed.");
return pv::Tx_Result(pv::Tx_Data::TX_TRANSFAULT);
}
return pv::Tx_Result(pv::Tx_Data::TX_OK);
}
pv::Tx_Result TranslationUnitBase::control_debug_read(pv::ReadTransaction tx)
{
Logging::debug("TranslationUnitBase::control_debug_read([%lx..%lx])", tx.getAddress(),
tx.getAddressEndIncl());
return this->control_read(tx);
}
pv::Tx_Result TranslationUnitBase::control_debug_write(pv::WriteTransaction tx)
{
Logging::debug("TranslationUnitBase::control_debug_write([%lx..%lx])", tx.getAddress(),
tx.getAddressEndIncl());
return this->control_write(tx);
}
/*
* -------------------------------------------------------------------------------------------
* Translations
* -------------------------------------------------------------------------------------------
*/
#include "pv/RemapRequest.h"
#define BASE_PAGE_SIZE 4096
/// basic translate functionality. This doesn't change anything in the remap request
/// the specific translation unit needs to override this function to provide the actual
/// remapping/translatino function here.
unsigned TranslationUnitBase::handle_remap(pv::RemapRequest &req, unsigned *unpredictable)
{
Logging::debug("TranslationUnitBase::handle_remap()");
lpaddr_t addr = req.getOriginalTransactionAddress();
size_t size = 1; // can we get the size somehow?
// check the supported ranges
if (addr < this->_inaddr_range_min || addr + size > this->_inaddr_range_max) {
Logging::error("TranslationUnitBase::handle_remap - request 0x%lx out of supported range "
"0x%lx..0x%lx",
addr, this->_inaddr_range_min, this->_inaddr_range_max);
return 1;
}
const pv::TransactionAttributes *attr = req.getTransactionAttributes();
access_mode_t mode;
if (attr->isNormalWorld()) {
if (attr->isPrivileged()) {
if (req.isRead()) {
mode = ACCESS_MODE_NOSEC_READ;
} else {
mode = ACCESS_MODE_NOSEC_WRITE;
}
} else {
if (req.isRead()) {
mode = ACCESS_MODE_USER_READ;
} else {
mode = ACCESS_MODE_USER_WRITE;
}
}
} else {
if (req.isRead()) {
mode = ACCESS_MODE_SEC_READ;
} else {
mode = ACCESS_MODE_SEC_WRITE;
}
}
// set the translation to be valid only once, to get retriggered
req.setOnceOnly();
lpaddr_t dst;
bool r = this->do_translate(addr, size, mode, &dst);
if (!r) {
Logging::info("TranslationUnitBase::handle_remap() - translation failed");
return 1;
}
Logging::debug("TranslationUnitBase::handle_remap() - translated 0x%lx -> 0x%lx", addr, dst);
// set the remap base
req.setRemapPageBase(dst & ~(BASE_PAGE_SIZE - 1));
return 0;
}
DVM::error_response_t TranslationUnitBase::handle_dvm_msg(DVM::Message *msg, bool ptw)
{
return DVM::error_response_t(DVM::error_response_t::ok);
}
/*
* -------------------------------------------------------------------------------------------
* Translation table walk
* -------------------------------------------------------------------------------------------
*/
bool TranslationUnitBase::translation_table_walk(lpaddr_t addr, uint8_t width, uint64_t *data)
{
pv::AccessWidth access_width;
Logging::debug("TranslationUnitBase::translation_table_walk(0x%lx, %u)", addr, width);
if (this->_ttw_pvbus == nullptr) {
Logging::error("TranslationUnitBase::translation_table_walk - no page walker set!");
return false;
}
if (width == 64) {
access_width = pv::ACCESS_64_BITS;
} else if (width == 32) {
access_width = pv::ACCESS_32_BITS;
} else {
return false;
}
// setup the buffer descriptor
pv::RandomContextTransactionGenerator::buffer_t bt
= pv::RandomContextTransactionGenerator::buffer_t(access_width, data, 1);
// setup the transaction attributes
pv::TransactionAttributes ta = pv::TransactionAttributes();
ta.setPTW(true);
// a new ACE request
pv::ACERequest req = pv::ACERequest();
// do the translaction
pv::Tx_Result res = this->_ttw_pvbus->read(&ta, &req, (pv::bus_addr_t)addr, &bt);
// return success
return res.isOK();
} | 30.199336 | 100 | 0.562376 |
80c7e24023da4a49c724c3ff8c1fd74df3d9528b | 5,459 | cpp | C++ | cppLib/code/dep/G3D/source/UprightFrame.cpp | DrYaling/ProcedureContentGenerationForUnity | 3c4f1e70b01e4fe2b9f847324b60b15016b9a740 | [
"MIT"
] | 3 | 2019-05-14T07:19:59.000Z | 2019-05-14T08:08:25.000Z | cppLib/code/dep/G3D/source/UprightFrame.cpp | DrYaling/ProcedureContentGenerationForUnity | 3c4f1e70b01e4fe2b9f847324b60b15016b9a740 | [
"MIT"
] | null | null | null | cppLib/code/dep/G3D/source/UprightFrame.cpp | DrYaling/ProcedureContentGenerationForUnity | 3c4f1e70b01e4fe2b9f847324b60b15016b9a740 | [
"MIT"
] | 1 | 2018-08-08T07:39:16.000Z | 2018-08-08T07:39:16.000Z | /**
\file UprightFrame.cpp
\maintainer Morgan McGuire, http://graphics.cs.williams.edu
*/
#include "G3D/UprightFrame.h"
#include "G3D/BinaryInput.h"
#include "G3D/BinaryOutput.h"
namespace G3D {
UprightFrame::UprightFrame(const CoordinateFrame& cframe) {
Vector3 look = cframe.lookVector();
yaw = (float)(G3D::pi() + atan2(look.x, look.z));
pitch = asin(look.y);
translation = cframe.translation;
}
UprightFrame::UprightFrame(const Any& any) {
any.verifyName("UprightFrame");
any.verifyType(Any::TABLE);
translation = any["translation"];
pitch = any["pitch"];
yaw = any["yaw"];
}
Any UprightFrame::toAny() const {
Any any(Any::TABLE, "UprightFrame");
any["translation"] = translation;
any["pitch"] = pitch;
any["yaw"] = yaw;
return any;
}
UprightFrame& UprightFrame::operator=(const Any& any) {
*this = UprightFrame(any);
return *this;
}
CoordinateFrame UprightFrame::toCoordinateFrame() const {
CoordinateFrame cframe;
Matrix3 P(Matrix3::fromAxisAngle(Vector3::unitX(), pitch));
Matrix3 Y(Matrix3::fromAxisAngle(Vector3::unitY(), yaw));
cframe.rotation = Y * P;
cframe.translation = translation;
return cframe;
}
UprightFrame UprightFrame::operator+(const UprightFrame& other) const {
return UprightFrame(translation + other.translation, pitch + other.pitch, yaw + other.yaw);
}
UprightFrame UprightFrame::operator*(const float k) const {
return UprightFrame(translation * k, pitch * k, yaw * k);
}
void UprightFrame::unwrapYaw(UprightFrame* a, int N) {
// Use the first point to establish the wrapping convention
for (int i = 1; i < N; ++i) {
const float prev = a[i - 1].yaw;
float& cur = a[i].yaw;
// No two angles should be more than pi (i.e., 180-degrees) apart.
if (abs(cur - prev) > G3D::pi()) {
// These angles must have wrapped at zero, causing them
// to be interpolated the long way.
// Find canonical [0, 2pi] versions of these numbers
float p = (float)wrap(prev, twoPi());
float c = (float)wrap(cur, twoPi());
// Find the difference -pi < diff < pi between the current and previous values
float diff = c - p;
if (diff < -G3D::pi()) {
diff += (float)twoPi();
} else if (diff > G3D::pi()) {
diff -= (float)twoPi();
}
// Offset the current from the previous by the difference
// between them.
cur = prev + diff;
}
}
}
void UprightFrame::serialize(class BinaryOutput& b) const {
translation.serialize(b);
b.writeFloat32(pitch);
b.writeFloat32(yaw);
}
void UprightFrame::deserialize(class BinaryInput& b) {
translation.deserialize(b);
pitch = b.readFloat32();
yaw = b.readFloat32();
}
///////////////////////////////////////////////////////////////////////////////////////////
UprightSpline::UprightSpline() : Spline<UprightFrame>() {
}
UprightSpline::UprightSpline(const Any& any) {
any.verifyName("UprightSpline");
any.verifyType(Any::TABLE);
extrapolationMode = any["extrapolationMode"];
const Any& controlsAny = any["control"];
controlsAny.verifyType(Any::ARRAY);
control.resize(controlsAny.length());
for (int controlIndex = 0; controlIndex < control.length(); ++controlIndex) {
control[controlIndex] = controlsAny[controlIndex];
}
const Any& timesAny = any["time"];
timesAny.verifyType(Any::ARRAY);
time.resize(timesAny.length());
for (int timeIndex = 0; timeIndex < time.length(); ++timeIndex) {
time[timeIndex] = timesAny[timeIndex];
}
}
Any UprightSpline::toAny(const std::string& myName) const {
Any any(Any::TABLE, myName);
any["extrapolationMode"] = extrapolationMode;
Any controlsAny(Any::ARRAY);
for (int controlIndex = 0; controlIndex < control.length(); ++controlIndex) {
controlsAny.append(control[controlIndex]);
}
any["control"] = controlsAny;
Any timesAny(Any::ARRAY);
for (int timeIndex = 0; timeIndex < time.length(); ++timeIndex) {
timesAny.append(Any(time[timeIndex]));
}
any["time"] = timesAny;
return any;
}
Any UprightSpline::toAny() const {
return toAny("UprightSpline");
}
UprightSpline& UprightSpline::operator=(const Any& any) {
*this = UprightSpline(any);
return *this;
}
void UprightSpline::serialize(class BinaryOutput& b) const {
b.writeInt32(extrapolationMode);
b.writeInt32(control.size());
for (int i = 0; i < control.size(); ++i) {
control[i].serialize(b);
}
b.writeInt32(time.size());
for (int i = 0; i < time.size(); ++i) {
b.writeFloat32(time[i]);
}
}
void UprightSpline::deserialize(class BinaryInput& b) {
extrapolationMode = SplineExtrapolationMode(b.readInt32());
control.resize(b.readInt32());
for (int i = 0; i < control.size(); ++i) {
control[i].deserialize(b);
}
if (b.hasMore()) {
time.resize(b.readInt32());
for (int i = 0; i < time.size(); ++i) {
time[i] = b.readFloat32();
}
debugAssert(time.size() == control.size());
} else {
// Import legacy path
time.resize(control.size());
for (int i = 0; i < time.size(); ++i) {
time[i] = (float)i;
}
}
}
}
| 25.390698 | 95 | 0.599744 |
80c7ebb1fcac1999f8ba5ef57dd73c1c11ecc57f | 68,985 | cpp | C++ | src/drivers/mcr3.cpp | pierrelouys/PSP-MAME4ALL | 54374b0579b7e2377f015ac155d8f519addfaa1a | [
"Unlicense"
] | 1 | 2021-01-25T20:16:33.000Z | 2021-01-25T20:16:33.000Z | src/drivers/mcr3.cpp | pierrelouys/PSP-MAME4ALL | 54374b0579b7e2377f015ac155d8f519addfaa1a | [
"Unlicense"
] | 1 | 2021-05-24T20:28:35.000Z | 2021-05-25T14:44:54.000Z | src/drivers/mcr3.cpp | PSP-Archive/PSP-MAME4ALL | 54374b0579b7e2377f015ac155d8f519addfaa1a | [
"Unlicense"
] | null | null | null | /***************************************************************************
MCR/III memory map (preliminary)
0000-3fff ROM 0
4000-7fff ROM 1
8000-cfff ROM 2
c000-dfff ROM 3
e000-e7ff RAM
e800-e9ff spriteram
f000-f7ff tiles
f800-f8ff palette ram
IN0
bit 0 : left coin
bit 1 : right coin
bit 2 : 1 player
bit 3 : 2 player
bit 4 : ?
bit 5 : tilt
bit 6 : ?
bit 7 : service
IN1,IN2
joystick, sometimes spinner
IN3
Usually dipswitches. Most game configuration is really done by holding down
the service key (F2) during the startup self-test.
IN4
extra inputs; also used to control sound for external boards
The MCR/III games used a plethora of sound boards; all of them seem to do
roughly the same thing. We have:
* Chip Squeak Deluxe (CSD) - used for music on Spy Hunter
* Turbo Chip Squeak (TCS) - used for all sound effects on Sarge
* Sounds Good (SG) - used for all sound effects on Rampage and Xenophobe
* Squawk & Talk (SNT) - used for speech on Discs of Tron
Known issues:
* Destruction Derby has no sound
* Destruction Derby player 3 and 4 steering wheels are not properly muxed
***************************************************************************/
#include "driver.h"
#include "vidhrdw/generic.h"
#include "machine/6821pia.h"
void mcr3_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
void mcr3_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
void mcr3_videoram_w(int offset,int data);
void mcr3_paletteram_w(int offset,int data);
void rampage_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
void spyhunt_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
int spyhunt_vh_start(void);
void spyhunt_vh_stop(void);
void spyhunt_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
extern unsigned char *spyhunt_alpharam;
extern int spyhunt_alpharam_size;
int crater_vh_start(void);
void mcr_init_machine(void);
int mcr_interrupt(void);
int dotron_interrupt(void);
extern int mcr_loadnvram;
void mcr_writeport(int port,int value);
int mcr_readport(int port);
void mcr_soundstatus_w (int offset,int data);
int mcr_soundlatch_r (int offset);
void mcr_pia_1_w (int offset, int data);
int mcr_pia_1_r (int offset);
int destderb_port_r(int offset);
void spyhunt_init_machine(void);
int spyhunt_port_1_r(int offset);
int spyhunt_port_2_r(int offset);
void spyhunt_writeport(int port,int value);
void rampage_init_machine(void);
void rampage_writeport(int port,int value);
void maxrpm_writeport(int port,int value);
int maxrpm_IN1_r(int offset);
int maxrpm_IN2_r(int offset);
void sarge_init_machine(void);
int sarge_IN1_r(int offset);
int sarge_IN2_r(int offset);
void sarge_writeport(int port,int value);
int dotron_vh_start(void);
void dotron_vh_stop(void);
int dotron_IN2_r(int offset);
void dotron_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
void dotron_init_machine(void);
void dotron_writeport(int port,int value);
void crater_writeport(int port,int value);
/***************************************************************************
Memory maps
***************************************************************************/
static struct MemoryReadAddress readmem[] =
{
{ 0x0000, 0xdfff, MRA_ROM },
{ 0xe000, 0xe9ff, MRA_RAM },
{ 0xf000, 0xf7ff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress writemem[] =
{
{ 0xe000, 0xe7ff, MWA_RAM },
{ 0x0000, 0xdfff, MWA_ROM },
{ 0xe800, 0xe9ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xf000, 0xf7ff, mcr3_videoram_w, &videoram, &videoram_size },
{ 0xf800, 0xf8ff, mcr3_paletteram_w, &paletteram },
{ -1 } /* end of table */
};
static struct MemoryReadAddress rampage_readmem[] =
{
{ 0x0000, 0xdfff, MRA_ROM },
{ 0xe000, 0xebff, MRA_RAM },
{ 0xf000, 0xf7ff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress rampage_writemem[] =
{
{ 0xe000, 0xe7ff, MWA_RAM },
{ 0x0000, 0xdfff, MWA_ROM },
{ 0xe800, 0xebff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xf000, 0xf7ff, mcr3_videoram_w, &videoram, &videoram_size },
{ 0xec00, 0xecff, mcr3_paletteram_w, &paletteram },
{ -1 } /* end of table */
};
static struct MemoryReadAddress spyhunt_readmem[] =
{
{ 0x0000, 0xdfff, MRA_ROM },
{ 0xe000, 0xebff, MRA_RAM },
{ 0xf000, 0xffff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress spyhunt_writemem[] =
{
{ 0xf000, 0xf7ff, MWA_RAM },
{ 0xe800, 0xebff, MWA_RAM, &spyhunt_alpharam, &spyhunt_alpharam_size },
{ 0xe000, 0xe7ff, videoram_w, &videoram, &videoram_size },
{ 0xf800, 0xf9ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xfa00, 0xfaff, mcr3_paletteram_w, &paletteram },
{ 0x0000, 0xdfff, MWA_ROM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress sound_readmem[] =
{
{ 0x8000, 0x83ff, MRA_RAM },
{ 0x9000, 0x9003, mcr_soundlatch_r },
{ 0xa001, 0xa001, AY8910_read_port_0_r },
{ 0xb001, 0xb001, AY8910_read_port_1_r },
{ 0xf000, 0xf000, input_port_5_r },
{ 0xe000, 0xe000, MRA_NOP },
{ 0x0000, 0x3fff, MRA_ROM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress sound_writemem[] =
{
{ 0x8000, 0x83ff, MWA_RAM },
{ 0xa000, 0xa000, AY8910_control_port_0_w },
{ 0xa002, 0xa002, AY8910_write_port_0_w },
{ 0xb000, 0xb000, AY8910_control_port_1_w },
{ 0xb002, 0xb002, AY8910_write_port_1_w },
{ 0xc000, 0xc000, mcr_soundstatus_w },
{ 0xe000, 0xe000, MWA_NOP },
{ 0x0000, 0x3fff, MWA_ROM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress timber_sound_readmem[] =
{
{ 0x3000, 0x3fff, MRA_RAM },
{ 0x8000, 0x83ff, MRA_RAM },
{ 0x9000, 0x9003, mcr_soundlatch_r },
{ 0xa001, 0xa001, AY8910_read_port_0_r },
{ 0xb001, 0xb001, AY8910_read_port_1_r },
{ 0xf000, 0xf000, input_port_5_r },
{ 0xe000, 0xe000, MRA_NOP },
{ 0x0000, 0x2fff, MRA_ROM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress timber_sound_writemem[] =
{
{ 0x3000, 0x3fff, MWA_RAM },
{ 0x8000, 0x83ff, MWA_RAM },
{ 0xa000, 0xa000, AY8910_control_port_0_w },
{ 0xa002, 0xa002, AY8910_write_port_0_w },
{ 0xb000, 0xb000, AY8910_control_port_1_w },
{ 0xb002, 0xb002, AY8910_write_port_1_w },
{ 0xc000, 0xc000, mcr_soundstatus_w },
{ 0xe000, 0xe000, MWA_NOP },
{ 0x0000, 0x2fff, MWA_ROM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress csd_readmem[] =
{
{ 0x000000, 0x007fff, MRA_ROM },
{ 0x018000, 0x018007, mcr_pia_1_r },
{ 0x01c000, 0x01cfff, MRA_BANK1 },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress csd_writemem[] =
{
{ 0x000000, 0x007fff, MWA_ROM },
{ 0x018000, 0x018007, mcr_pia_1_w },
{ 0x01c000, 0x01cfff, MWA_BANK1 },
{ -1 } /* end of table */
};
static struct MemoryReadAddress sg_readmem[] =
{
{ 0x000000, 0x01ffff, MRA_ROM },
{ 0x060000, 0x060007, mcr_pia_1_r },
{ 0x070000, 0x070fff, MRA_BANK1 },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress sg_writemem[] =
{
{ 0x000000, 0x01ffff, MWA_ROM },
{ 0x060000, 0x060007, mcr_pia_1_w },
{ 0x070000, 0x070fff, MWA_BANK1 },
{ -1 } /* end of table */
};
static struct MemoryReadAddress snt_readmem[] =
{
{ 0x0000, 0x007f, MRA_RAM },
{ 0x0080, 0x0083, pia_1_r },
{ 0x0090, 0x0093, pia_2_r },
{ 0xd000, 0xffff, MRA_ROM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress snt_writemem[] =
{
{ 0x0000, 0x007f, MWA_RAM },
{ 0x0080, 0x0083, pia_1_w },
{ 0x0090, 0x0093, pia_2_w },
{ 0xd000, 0xffff, MWA_ROM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress tcs_readmem[] =
{
{ 0x0000, 0x03ff, MRA_RAM },
{ 0x6000, 0x6003, pia_1_r },
{ 0xc000, 0xffff, MRA_ROM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress tcs_writemem[] =
{
{ 0x0000, 0x03ff, MWA_RAM },
{ 0x6000, 0x6003, pia_1_w },
{ 0xc000, 0xffff, MWA_ROM },
{ -1 } /* end of table */
};
/***************************************************************************
Input port definitions
***************************************************************************/
INPUT_PORTS_START( tapper_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0xe0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY | IPF_COCKTAIL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0xe0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x04, 0x04, "Demo Sounds", IP_KEY_NONE )
PORT_DIPSETTING( 0x04, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_DIPNAME( 0x40, 0x40, "Cabinet", IP_KEY_NONE )
PORT_DIPSETTING( 0x40, "Upright" )
PORT_DIPSETTING( 0x00, "Cocktail" )
PORT_BIT( 0xbb, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
INPUT_PORTS_START( dotron_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN3 )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN1 */
#ifdef GP2X
PORT_ANALOGX( 0xff, 0x00, IPT_DIAL | IPF_REVERSE, 5, 0, 0, 0, 0, 0, OSD_JOY_FIRE5, OSD_JOY_FIRE6, 16 )
#else
PORT_ANALOGX( 0xff, 0x00, IPT_DIAL | IPF_REVERSE, 50, 0, 0, 0, OSD_KEY_Z, OSD_KEY_X, 0, 0, 4 )
#endif
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY )
PORT_BITX(0x10, IP_ACTIVE_LOW, IPT_BUTTON3, "Aim Down", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BITX(0x20, IP_ACTIVE_LOW, IPT_BUTTON4, "Aim Up", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON2 )
/* we default to Environmental otherwise speech is disabled */
PORT_DIPNAME( 0x80, 0x00, "Cabinet", IP_KEY_NONE )
PORT_DIPSETTING( 0x80, "Upright" )
PORT_DIPSETTING( 0x00, "Environmental" )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x01, 0x01, "Coin Meters", IP_KEY_NONE )
PORT_DIPSETTING( 0x01, "1" )
PORT_DIPSETTING( 0x00, "2" )
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* fake port to make aiming up & down easier */
PORT_ANALOG ( 0xff, 0x00, IPT_TRACKBALL_Y, 100, 0, 0, 0 )
INPUT_PORTS_END
INPUT_PORTS_START( destderb_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BITX( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x20, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN1 -- the high 6 bits contain the sterring wheel value */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 )
PORT_ANALOG ( 0xfc, 0x00, IPT_DIAL | IPF_REVERSE, 50, 0, 0, 0 )
PORT_START /* IN2 -- the high 6 bits contain the sterring wheel value */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_ANALOG ( 0xfc, 0x00, IPT_DIAL | IPF_REVERSE, 50, 0, 0, 0 )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x01, 0x01, "Cabinet", IP_KEY_NONE )
PORT_DIPSETTING( 0x01, "2P Upright" )
PORT_DIPSETTING( 0x00, "4P Upright" )
PORT_DIPNAME( 0x02, 0x02, "Difficulty", IP_KEY_NONE )
PORT_DIPSETTING( 0x02, "Normal" )
PORT_DIPSETTING( 0x00, "Harder" )
PORT_DIPNAME( 0x04, 0x04, "Free Play", IP_KEY_NONE )
PORT_DIPSETTING( 0x04, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_DIPNAME( 0x08, 0x08, "Reward Screen", IP_KEY_NONE )
PORT_DIPSETTING( 0x08, "Expanded" )
PORT_DIPSETTING( 0x00, "Limited" )
PORT_DIPNAME( 0x30, 0x30, "Coinage", IP_KEY_NONE )
PORT_DIPSETTING( 0x20, "2 Coins/1 Credit" )
PORT_DIPSETTING( 0x00, "2 Coins/2 Credits" )
PORT_DIPSETTING( 0x30, "1 Coin/1 Credit" )
PORT_DIPSETTING( 0x10, "1 Coin/2 Credits" )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN3 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN4 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START3 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START4 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER3 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER3 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER4 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER4 )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
INPUT_PORTS_START( timber_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY | IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY | IPF_PLAYER1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY | IPF_PLAYER1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY | IPF_PLAYER2 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY | IPF_PLAYER2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY | IPF_PLAYER2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY | IPF_PLAYER2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x04, 0x04, "Demo Sounds", IP_KEY_NONE )
PORT_DIPSETTING( 0x04, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_BIT( 0xfb, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
INPUT_PORTS_START( rampage_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_TILT )
PORT_BITX( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x20, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x03, 0x03, "Difficulty", IP_KEY_NONE )
PORT_DIPSETTING( 0x02, "Easy" )
PORT_DIPSETTING( 0x03, "Normal" )
PORT_DIPSETTING( 0x01, "Hard" )
PORT_DIPSETTING( 0x00, "Free Play" )
PORT_DIPNAME( 0x04, 0x04, "Score Option", IP_KEY_NONE )
PORT_DIPSETTING( 0x04, "Keep score when continuing" )
PORT_DIPSETTING( 0x00, "Lose score when continuing" )
PORT_DIPNAME( 0x08, 0x08, "Coin A", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "2 Coins/1 Credit" )
PORT_DIPSETTING( 0x08, "1 Coin/1 Credit" )
PORT_DIPNAME( 0x70, 0x70, "Coin B", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "3 Coins/1 Credit" )
PORT_DIPSETTING( 0x10, "2 Coins/1 Credit" )
PORT_DIPSETTING( 0x70, "1 Coin/1 Credit" )
PORT_DIPSETTING( 0x60, "1 Coin/2 Credits" )
PORT_DIPSETTING( 0x50, "1 Coin/3 Credits" )
PORT_DIPSETTING( 0x40, "1 Coin/4 Credits" )
PORT_DIPSETTING( 0x30, "1 Coin/5 Credits" )
PORT_DIPSETTING( 0x20, "1 Coin/6 Credits" )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Rack Advance", OSD_KEY_F1, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN4 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY | IPF_PLAYER3 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY | IPF_PLAYER3 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY | IPF_PLAYER3 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY | IPF_PLAYER3 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER3 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER3 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
INPUT_PORTS_START( maxrpm_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN1 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON4 | IPF_PLAYER1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON4 | IPF_PLAYER2 )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x08, 0x08, "Free Play", IP_KEY_NONE )
PORT_DIPSETTING( 0x08, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_DIPNAME( 0x30, 0x30, "Coinage", IP_KEY_NONE )
PORT_DIPSETTING( 0x20, "2 Coins/1 Credit" )
PORT_DIPSETTING( 0x30, "1 Coin/1 Credit" )
PORT_DIPSETTING( 0x10, "1 Coin/2 Credits" )
/* 0x00 says 2 Coins/2 Credits in service mode, but gives 1 Coin/1 Credit */
PORT_BIT( 0xc7, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* new fake for acceleration */
PORT_ANALOGX( 0xff, 0x30, IPT_AD_STICK_Y | IPF_PLAYER2, 100, 0, 0x30, 0xff, OSD_KEY_UP, OSD_KEY_DOWN, IPT_JOYSTICK_UP, IPT_JOYSTICK_DOWN, 1 )
PORT_START /* new fake for acceleration */
PORT_ANALOGX( 0xff, 0x30, IPT_AD_STICK_Y | IPF_PLAYER1, 100, 0, 0x30, 0xff, OSD_KEY_UP, OSD_KEY_DOWN, IPT_JOYSTICK_UP, IPT_JOYSTICK_DOWN, 1 )
PORT_START /* new fake for steering */
PORT_ANALOGX( 0xff, 0x74, IPT_AD_STICK_X | IPF_PLAYER2 | IPF_REVERSE, 80, 0, 0x34, 0xb4, OSD_KEY_LEFT, OSD_KEY_RIGHT, IPT_JOYSTICK_LEFT, IPT_JOYSTICK_RIGHT, 2 )
PORT_START /* new fake for steering */
PORT_ANALOGX( 0xff, 0x74, IPT_AD_STICK_X | IPF_PLAYER1 | IPF_REVERSE, 80, 0, 0x34, 0xb4, OSD_KEY_LEFT, OSD_KEY_RIGHT, IPT_JOYSTICK_LEFT, IPT_JOYSTICK_RIGHT, 2 )
PORT_START /* fake for shifting */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
INPUT_PORTS_START( sarge_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_TILT )
PORT_BITX( 0x20, 0x20, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x20, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN1 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_UP | IPF_2WAY | IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_DOWN | IPF_2WAY | IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_UP | IPF_2WAY | IPF_PLAYER1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_DOWN | IPF_2WAY | IPF_PLAYER1 )
PORT_BIT( 0x30, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER1 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER1 )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_UP | IPF_2WAY | IPF_PLAYER2 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_DOWN | IPF_2WAY | IPF_PLAYER2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_UP | IPF_2WAY | IPF_PLAYER2 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_DOWN | IPF_2WAY | IPF_PLAYER2 )
PORT_BIT( 0x30, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 )
PORT_START /* IN3 -- dipswitches */
PORT_DIPNAME( 0x08, 0x08, "Free Play", IP_KEY_NONE )
PORT_DIPSETTING( 0x08, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_DIPNAME( 0x30, 0x30, "Coinage", IP_KEY_NONE )
PORT_DIPSETTING( 0x20, "2 Coins/1 Credit" )
PORT_DIPSETTING( 0x30, "1 Coin/1 Credit" )
PORT_DIPSETTING( 0x10, "1 Coin/2 Credits" )
/* 0x00 says 2 Coins/2 Credits in service mode, but gives 1 Coin/1 Credit */
PORT_BIT( 0xc7, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* fake port for single joystick control */
/* This fake port is handled via sarge_IN1_r and sarge_IN2_r */
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER1 )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER1 )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER1 )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER1 )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER2 )
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER2 )
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER2 )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT | IPF_8WAY | /* IPF_CHEAT |*/ IPF_PLAYER2 )
INPUT_PORTS_END
INPUT_PORTS_START( spyhunt_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BITX( 0x10, IP_ACTIVE_LOW, IPT_BUTTON6 | IPF_TOGGLE, "Gear Shift", OSD_KEY_ENTER, IP_JOY_DEFAULT, 0 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_SERVICE )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_KEY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN1 -- various buttons, low 5 bits */
PORT_BITX( 0x01, IP_ACTIVE_LOW, IPT_BUTTON4, "Oil Slick", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BITX( 0x02, IP_ACTIVE_LOW, IPT_BUTTON5, "Missiles", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BITX( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3, "Weapon Truck", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BITX( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2, "Smoke Screen", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BITX( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1, "Machine Guns", IP_KEY_DEFAULT, IP_JOY_DEFAULT, 0 )
PORT_BIT( 0x60, IP_ACTIVE_HIGH, IPT_UNUSED ) /* CSD status bits */
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN2 -- actually not used at all, but read as a trakport */
PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START /* IN3 -- dipswitches -- low 4 bits only */
PORT_DIPNAME( 0x01, 0x01, "Game Timer", IP_KEY_NONE )
PORT_DIPSETTING( 0x00, "1:00" )
PORT_DIPSETTING( 0x01, "1:30" )
PORT_DIPNAME( 0x02, 0x02, "Demo Sounds", IP_KEY_NONE )
PORT_DIPSETTING( 0x02, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* new fake for acceleration */
PORT_ANALOGX( 0xff, 0x30, IPT_AD_STICK_Y | IPF_REVERSE, 100, 0, 0x30, 0xff, OSD_KEY_UP, OSD_KEY_DOWN, OSD_JOY_UP, OSD_JOY_DOWN, 1 )
PORT_START /* new fake for steering */
PORT_ANALOGX( 0xff, 0x74, IPT_AD_STICK_X | IPF_CENTER, 80, 0, 0x34, 0xb4, OSD_KEY_LEFT, OSD_KEY_RIGHT, OSD_JOY_LEFT, OSD_JOY_RIGHT, 2 )
INPUT_PORTS_END
INPUT_PORTS_START( crater_input_ports )
PORT_START /* IN0 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_TILT )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 )
PORT_DIPSETTING( 0x80, "Off" )
PORT_DIPSETTING( 0x00, "On" )
PORT_START /* IN1 */
PORT_ANALOGX( 0xff, 0x00, IPT_DIAL | IPF_REVERSE, 25, 0, 0, 0, OSD_KEY_Z, OSD_KEY_X, 0, 0, 4 )
PORT_START /* IN2 */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON3 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* IN3 -- dipswitches */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* IN4 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* AIN0 */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNKNOWN )
INPUT_PORTS_END
static struct IOReadPort readport[] =
{
{ 0x00, 0x00, input_port_0_r },
{ 0x01, 0x01, input_port_1_r },
{ 0x02, 0x02, input_port_2_r },
{ 0x03, 0x03, input_port_3_r },
{ 0x04, 0x04, input_port_4_r },
{ 0x05, 0xff, mcr_readport },
{ -1 }
};
static struct IOReadPort dt_readport[] =
{
{ 0x00, 0x00, input_port_0_r },
{ 0x01, 0x01, input_port_1_r },
{ 0x02, 0x02, dotron_IN2_r },
{ 0x03, 0x03, input_port_3_r },
{ 0x04, 0x04, input_port_4_r },
{ 0x05, 0xff, mcr_readport },
{ -1 }
};
static struct IOReadPort destderb_readport[] =
{
{ 0x00, 0x00, input_port_0_r },
{ 0x01, 0x02, destderb_port_r },
{ 0x03, 0x03, input_port_3_r },
{ 0x04, 0x04, input_port_4_r },
{ 0x05, 0xff, mcr_readport },
{ -1 }
};
static struct IOReadPort maxrpm_readport[] =
{
{ 0x00, 0x00, input_port_0_r },
{ 0x01, 0x01, maxrpm_IN1_r },
{ 0x02, 0x02, maxrpm_IN2_r },
{ 0x03, 0x03, input_port_3_r },
{ 0x04, 0x04, input_port_4_r },
{ 0x05, 0xff, mcr_readport },
{ -1 }
};
static struct IOReadPort sarge_readport[] =
{
{ 0x00, 0x00, input_port_0_r },
{ 0x01, 0x01, sarge_IN1_r },
{ 0x02, 0x02, sarge_IN2_r },
{ 0x03, 0x03, input_port_3_r },
{ 0x04, 0x04, input_port_4_r },
{ 0x05, 0xff, mcr_readport },
{ -1 }
};
static struct IOReadPort spyhunt_readport[] =
{
{ 0x00, 0x00, input_port_0_r },
{ 0x01, 0x01, spyhunt_port_1_r },
{ 0x02, 0x02, spyhunt_port_2_r },
{ 0x03, 0x03, input_port_3_r },
{ 0x04, 0x04, input_port_4_r },
{ 0x05, 0xff, mcr_readport },
{ -1 }
};
static struct IOWritePort writeport[] =
{
{ 0, 0xff, mcr_writeport },
{ -1 } /* end of table */
};
static struct IOWritePort sh_writeport[] =
{
{ 0, 0xff, spyhunt_writeport },
{ -1 } /* end of table */
};
static struct IOWritePort cr_writeport[] =
{
{ 0, 0xff, crater_writeport },
{ -1 } /* end of table */
};
static struct IOWritePort rm_writeport[] =
{
{ 0, 0xff, rampage_writeport },
{ -1 } /* end of table */
};
static struct IOWritePort mr_writeport[] =
{
{ 0, 0xff, maxrpm_writeport },
{ -1 } /* end of table */
};
static struct IOWritePort sa_writeport[] =
{
{ 0, 0xff, sarge_writeport },
{ -1 } /* end of table */
};
static struct IOWritePort dt_writeport[] =
{
{ 0, 0xff, dotron_writeport },
{ -1 } /* end of table */
};
/***************************************************************************
Graphics layouts
***************************************************************************/
/* generic character layouts */
/* note that characters are half the resolution of sprites in each direction, so we generate
them at double size */
/* 1024 characters; used by tapper, timber, rampage */
static struct GfxLayout mcr3_charlayout_1024 =
{
16, 16,
1024,
4,
{ 1024*16*8, 1024*16*8+1, 0, 1 },
{ 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14 },
{ 0, 0, 2*8, 2*8, 4*8, 4*8, 6*8, 6*8, 8*8, 8*8, 10*8, 10*8, 12*8, 12*8, 14*8, 14*8 },
16*8
};
/* 512 characters; used by dotron, destderb */
static struct GfxLayout mcr3_charlayout_512 =
{
16, 16,
512,
4,
{ 512*16*8, 512*16*8+1, 0, 1 },
{ 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14 },
{ 0, 0, 2*8, 2*8, 4*8, 4*8, 6*8, 6*8, 8*8, 8*8, 10*8, 10*8, 12*8, 12*8, 14*8, 14*8 },
16*8
};
/* generic sprite layouts */
/* 512 sprites; used by rampage */
#define X (512*128*8)
#define Y (2*X)
#define Z (3*X)
static struct GfxLayout mcr3_spritelayout_512 =
{
32,32,
512,
4,
{ 0, 1, 2, 3 },
{ Z+0, Z+4, Y+0, Y+4, X+0, X+4, 0, 4, Z+8, Z+12, Y+8, Y+12, X+8, X+12, 8, 12,
Z+16, Z+20, Y+16, Y+20, X+16, X+20, 16, 20, Z+24, Z+28, Y+24, Y+28,
X+24, X+28, 24, 28 },
{ 0, 32, 32*2, 32*3, 32*4, 32*5, 32*6, 32*7, 32*8, 32*9, 32*10, 32*11,
32*12, 32*13, 32*14, 32*15, 32*16, 32*17, 32*18, 32*19, 32*20, 32*21,
32*22, 32*23, 32*24, 32*25, 32*26, 32*27, 32*28, 32*29, 32*30, 32*31 },
128*8
};
#undef X
#undef Y
#undef Z
/* 256 sprites; used by tapper, timber, destderb, spyhunt */
#define X (256*128*8)
#define Y (2*X)
#define Z (3*X)
static struct GfxLayout mcr3_spritelayout_256 =
{
32,32,
256,
4,
{ 0, 1, 2, 3 },
{ Z+0, Z+4, Y+0, Y+4, X+0, X+4, 0, 4, Z+8, Z+12, Y+8, Y+12, X+8, X+12, 8, 12,
Z+16, Z+20, Y+16, Y+20, X+16, X+20, 16, 20, Z+24, Z+28, Y+24, Y+28,
X+24, X+28, 24, 28 },
{ 0, 32, 32*2, 32*3, 32*4, 32*5, 32*6, 32*7, 32*8, 32*9, 32*10, 32*11,
32*12, 32*13, 32*14, 32*15, 32*16, 32*17, 32*18, 32*19, 32*20, 32*21,
32*22, 32*23, 32*24, 32*25, 32*26, 32*27, 32*28, 32*29, 32*30, 32*31 },
128*8
};
#undef X
#undef Y
#undef Z
/* 128 sprites; used by dotron */
#define X (128*128*8)
#define Y (2*X)
#define Z (3*X)
static struct GfxLayout mcr3_spritelayout_128 =
{
32,32,
128,
4,
{ 0, 1, 2, 3 },
{ Z+0, Z+4, Y+0, Y+4, X+0, X+4, 0, 4, Z+8, Z+12, Y+8, Y+12, X+8, X+12, 8, 12,
Z+16, Z+20, Y+16, Y+20, X+16, X+20, 16, 20, Z+24, Z+28, Y+24, Y+28,
X+24, X+28, 24, 28 },
{ 0, 32, 32*2, 32*3, 32*4, 32*5, 32*6, 32*7, 32*8, 32*9, 32*10, 32*11,
32*12, 32*13, 32*14, 32*15, 32*16, 32*17, 32*18, 32*19, 32*20, 32*21,
32*22, 32*23, 32*24, 32*25, 32*26, 32*27, 32*28, 32*29, 32*30, 32*31 },
128*8
};
#undef X
#undef Y
#undef Z
/***************************** spyhunt layouts **********************************/
/* 128 32x16 characters; used by spyhunt */
static struct GfxLayout spyhunt_charlayout_128 =
{
32, 32, /* we pixel double and split in half */
128,
4,
{ 0, 1, 128*128*8, 128*128*8+1 },
{ 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14, 16, 16, 18, 18, 20, 20, 22, 22, 24, 24, 26, 26, 28, 28, 30, 30 },
{ 0, 0, 8*8, 8*8, 16*8, 16*8, 24*8, 24*8, 32*8, 32*8, 40*8, 40*8, 48*8, 48*8, 56*8, 56*8,
64*8, 64*8, 72*8, 72*8, 80*8, 80*8, 88*8, 88*8, 96*8, 96*8, 104*8, 104*8, 112*8, 112*8, 120*8, 120*8 },
128*8
};
/* of course, Spy Hunter just *had* to be different than everyone else... */
static struct GfxLayout spyhunt_alphalayout =
{
16, 16,
256,
2,
{ 0, 1 },
{ 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14 },
{ 0, 0, 2*8, 2*8, 4*8, 4*8, 6*8, 6*8, 8*8, 8*8, 10*8, 10*8, 12*8, 12*8, 14*8, 14*8 },
16*8
};
static struct GfxDecodeInfo tapper_gfxdecodeinfo[] =
{
{ 1, 0x0000, &mcr3_charlayout_1024, 0, 4 },
{ 1, 0x8000, &mcr3_spritelayout_256, 0, 4 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo dotron_gfxdecodeinfo[] =
{
{ 1, 0x0000, &mcr3_charlayout_512, 0, 4 },
{ 1, 0x4000, &mcr3_spritelayout_128, 0, 4 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo destderb_gfxdecodeinfo[] =
{
{ 1, 0x0000, &mcr3_charlayout_512, 0, 4 },
{ 1, 0x4000, &mcr3_spritelayout_256, 0, 4 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo timber_gfxdecodeinfo[] =
{
{ 1, 0x0000, &mcr3_charlayout_1024, 0, 4 },
{ 1, 0x8000, &mcr3_spritelayout_256, 0, 4 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo rampage_gfxdecodeinfo[] =
{
{ 1, 0x0000, &mcr3_charlayout_1024, 0, 4 },
{ 1, 0x8000, &mcr3_spritelayout_512, 0, 4 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo sarge_gfxdecodeinfo[] =
{
{ 1, 0x0000, &mcr3_charlayout_512, 0, 4 },
{ 1, 0x4000, &mcr3_spritelayout_256, 0, 4 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo spyhunt_gfxdecodeinfo[] =
{
{ 1, 0x0000, &spyhunt_charlayout_128, 1*16, 1 }, /* top half */
{ 1, 0x0004, &spyhunt_charlayout_128, 1*16, 1 }, /* bottom half */
{ 1, 0x8000, &mcr3_spritelayout_256, 0*16, 1 },
{ 1, 0x28000, &spyhunt_alphalayout, 8*16, 1 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo crater_gfxdecodeinfo[] =
{
{ 1, 0x0000, &spyhunt_charlayout_128, 3*16, 1 }, /* top half */
{ 1, 0x0004, &spyhunt_charlayout_128, 3*16, 1 }, /* bottom half */
{ 1, 0x8000, &mcr3_spritelayout_256, 0*16, 4 },
{ 1, 0x28000, &spyhunt_alphalayout, 8*16, 1 },
{ -1 } /* end of array */
};
/***************************************************************************
Sound interfaces
***************************************************************************/
static struct AY8910interface ay8910_interface =
{
2, /* 2 chips */
2000000, /* 2 MHz ?? */
{ 255, 255 },
{ 0 },
{ 0 },
{ 0 },
{ 0 }
};
static struct DACinterface dac_interface =
{
1,
{ 255 }
};
static struct TMS5220interface tms5220_interface =
{
640000,
192,
0
};
/***************************************************************************
Machine drivers
***************************************************************************/
static struct MachineDriver tapper_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
readmem,writemem,readport,writeport,
mcr_interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
2000000, /* 2 Mhz */
2,
sound_readmem,sound_writemem,0,0,
interrupt,26
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU has enough interrupts to handle synchronization */
mcr_init_machine,
/* video hardware */
32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 },
tapper_gfxdecodeinfo,
8*16, 8*16,
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
mcr3_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
}
}
};
static struct MachineDriver dotron_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
readmem,writemem,dt_readport,dt_writeport,
dotron_interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
2000000, /* 2 Mhz */
2,
sound_readmem,sound_writemem,0,0,
interrupt,26
},
{
CPU_M6802 | CPU_AUDIO_CPU,
3580000/4, /* .8 Mhz */
3,
snt_readmem,snt_writemem,0,0,
ignore_interrupt,1
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU has enough interrupts to handle synchronization */
dotron_init_machine,
/* video hardware */
/* 32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 }, - MAB 09/30/98, changed the screen size for the backdrop */
800, 600, { 0, 800-1, 0, 600-1 },
dotron_gfxdecodeinfo,
254, 4*16, /* The extra colors are for the backdrop */
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
dotron_vh_start,
dotron_vh_stop,
dotron_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
},
{
SOUND_TMS5220,
&tms5220_interface
}
}
};
static struct MachineDriver destderb_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
readmem,writemem,destderb_readport,writeport,
mcr_interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
2000000, /* 2 Mhz */
2,
sound_readmem,sound_writemem,0,0,
interrupt,26
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU has enough interrupts to handle synchronization */
mcr_init_machine,
/* video hardware */
32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 },
destderb_gfxdecodeinfo,
8*16, 8*16,
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
mcr3_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
}
}
};
static struct MachineDriver timber_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
readmem,writemem,readport,writeport,
mcr_interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
2000000, /* 2 Mhz */
2,
timber_sound_readmem,timber_sound_writemem,0,0,
interrupt,26
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU has enough interrupts to handle synchronization */
mcr_init_machine,
/* video hardware */
32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 },
timber_gfxdecodeinfo,
8*16, 8*16,
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
mcr3_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
}
}
};
static struct MachineDriver rampage_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
rampage_readmem,rampage_writemem,readport,rm_writeport,
mcr_interrupt,1
},
{
CPU_M68000 | CPU_AUDIO_CPU,
7500000, /* 7.5 Mhz */
2,
sg_readmem,sg_writemem,0,0,
ignore_interrupt,1
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU synchronization is done via timers */
rampage_init_machine,
/* video hardware */
32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 },
rampage_gfxdecodeinfo,
8*16, 8*16,
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
rampage_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_DAC,
&dac_interface
}
}
};
static struct MachineDriver maxrpm_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
rampage_readmem,rampage_writemem,maxrpm_readport,mr_writeport,
mcr_interrupt,1
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU synchronization is done via timers */
rampage_init_machine,
/* video hardware */
32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 },
rampage_gfxdecodeinfo,
8*16, 8*16,
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
rampage_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_DAC,
&dac_interface
}
}
};
static struct MachineDriver sarge_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
rampage_readmem,rampage_writemem,sarge_readport,sa_writeport,
mcr_interrupt,1
},
{
CPU_M6809 | CPU_AUDIO_CPU,
2250000, /* 2.25 Mhz??? */
2,
tcs_readmem,tcs_writemem,0,0,
ignore_interrupt,1
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU synchronization is done via timers */
sarge_init_machine,
/* video hardware */
32*16, 30*16, { 0, 32*16-1, 0, 30*16-1 },
sarge_gfxdecodeinfo,
8*16, 8*16,
mcr3_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE,
0,
generic_vh_start,
generic_vh_stop,
rampage_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_DAC,
&dac_interface
}
}
};
static struct MachineDriver spyhunt_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
spyhunt_readmem,spyhunt_writemem,spyhunt_readport,sh_writeport,
mcr_interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
2000000, /* 2 Mhz */
2,
sound_readmem,sound_writemem,0,0,
interrupt,26
},
{
CPU_M68000 | CPU_AUDIO_CPU,
7500000, /* Actually 7.5 Mhz, but the 68000 emulator isn't accurate */
3,
csd_readmem,csd_writemem,0,0,
ignore_interrupt,1
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU has enough interrupts to handle synchronization */
spyhunt_init_machine,
/* video hardware */
31*16, 30*16, { 0, 31*16-1, 0, 30*16-1 },
spyhunt_gfxdecodeinfo,
8*16+4, 8*16+4,
spyhunt_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_MODIFIES_PALETTE,
0,
spyhunt_vh_start,
spyhunt_vh_stop,
spyhunt_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
},
{
SOUND_DAC,
&dac_interface
}
}
};
static struct MachineDriver crater_machine_driver =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 Mhz */
0,
spyhunt_readmem,spyhunt_writemem,readport,cr_writeport,
mcr_interrupt,1
},
{
CPU_Z80 | CPU_AUDIO_CPU,
2000000, /* 2 Mhz */
2,
sound_readmem,sound_writemem,0,0,
interrupt,26
}
},
30, DEFAULT_30HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* 1 CPU slice per frame - sound CPU has enough interrupts to handle synchronization */
mcr_init_machine,
/* video hardware */
30*16, 30*16, { 0, 30*16-1, 0, 30*16-1 },
crater_gfxdecodeinfo,
8*16+4, 8*16+4,
spyhunt_vh_convert_color_prom,
VIDEO_TYPE_RASTER|VIDEO_MODIFIES_PALETTE,
0,
crater_vh_start,
spyhunt_vh_stop,
spyhunt_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
}
}
};
/***************************************************************************
High score save/load
***************************************************************************/
static int mcr3_hiload(int addr, int len)
{
unsigned char *RAM = Machine->memory_region[0];
/* see if it's okay to load */
if (mcr_loadnvram)
{
void *f;
f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,0);
if (f)
{
osd_fread(f,&RAM[addr],len);
osd_fclose (f);
}
return 1;
}
else return 0; /* we can't load the hi scores yet */
}
static void mcr3_hisave(int addr, int len)
{
unsigned char *RAM = Machine->memory_region[0];
void *f;
f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,1);
if (f)
{
osd_fwrite(f,&RAM[addr],len);
osd_fclose (f);
}
}
static int tapper_hiload(void) { return mcr3_hiload(0xe000, 0x9d); }
static void tapper_hisave(void) { mcr3_hisave(0xe000, 0x9d); }
static int dotron_hiload(void) { return mcr3_hiload(0xe543, 0xac); }
static void dotron_hisave(void) { mcr3_hisave(0xe543, 0xac); }
static int destderb_hiload(void) { return mcr3_hiload(0xe4e6, 0x153); }
static void destderb_hisave(void) { mcr3_hisave(0xe4e6, 0x153); }
static int timber_hiload(void) { return mcr3_hiload(0xe000, 0x9f); }
static void timber_hisave(void) { mcr3_hisave(0xe000, 0x9f); }
static int rampage_hiload(void) { return mcr3_hiload(0xe631, 0x3f); }
static void rampage_hisave(void) { mcr3_hisave(0xe631, 0x3f); }
static int spyhunt_hiload(void) { return mcr3_hiload(0xf42b, 0xfb); }
static void spyhunt_hisave(void) { mcr3_hisave(0xf42b, 0xfb); }
static int crater_hiload(void) { return mcr3_hiload(0xf5fb, 0xa3); }
static void crater_hisave(void) { mcr3_hisave(0xf5fb, 0xa3); }
/***************************************************************************
ROM decoding
***************************************************************************/
static void spyhunt_decode (void)
{
unsigned char *RAM = Machine->memory_region[0];
/* some versions of rom 11d have the top and bottom 8k swapped; to enable us to work with either
a correct set or a swapped set (both of which pass the checksum!), we swap them here */
if (RAM[0xa000] != 0x0c)
{
int i;
unsigned char temp;
for (i = 0;i < 0x2000;i++)
{
temp = RAM[0xa000 + i];
RAM[0xa000 + i] = RAM[0xc000 + i];
RAM[0xc000 + i] = temp;
}
}
}
/***************************************************************************
Game driver(s)
***************************************************************************/
ROM_START( tapper_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "tappg0.bin", 0x0000, 0x4000, 0x127171d1 )
ROM_LOAD( "tappg1.bin", 0x4000, 0x4000, 0x9d6a47f7 )
ROM_LOAD( "tappg2.bin", 0x8000, 0x4000, 0x3a1f8778 )
ROM_LOAD( "tappg3.bin", 0xc000, 0x2000, 0xe8dcdaa4 )
ROM_REGION_DISPOSE(0x28000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "tapbg1.bin", 0x00000, 0x4000, 0x2a30238c )
ROM_LOAD( "tapbg0.bin", 0x04000, 0x4000, 0x394ab576 )
ROM_LOAD( "tapfg7.bin", 0x08000, 0x4000, 0x070b4c81 )
ROM_LOAD( "tapfg6.bin", 0x0c000, 0x4000, 0xa37aef36 )
ROM_LOAD( "tapfg5.bin", 0x10000, 0x4000, 0x800f7c8a )
ROM_LOAD( "tapfg4.bin", 0x14000, 0x4000, 0x32674ee6 )
ROM_LOAD( "tapfg3.bin", 0x18000, 0x4000, 0x818fffd4 )
ROM_LOAD( "tapfg2.bin", 0x1c000, 0x4000, 0x67e37690 )
ROM_LOAD( "tapfg1.bin", 0x20000, 0x4000, 0x32509011 )
ROM_LOAD( "tapfg0.bin", 0x24000, 0x4000, 0x8412c808 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "tapsnda7.bin", 0x0000, 0x1000, 0x0e8bb9d5 )
ROM_LOAD( "tapsnda8.bin", 0x1000, 0x1000, 0x0cf0e29b )
ROM_LOAD( "tapsnda9.bin", 0x2000, 0x1000, 0x31eb6dc6 )
ROM_LOAD( "tapsda10.bin", 0x3000, 0x1000, 0x01a9be6a )
ROM_END
ROM_START( sutapper_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "5791", 0x0000, 0x4000, 0x87119cc4 )
ROM_LOAD( "5792", 0x4000, 0x4000, 0x4c23ad89 )
ROM_LOAD( "5793", 0x8000, 0x4000, 0xfecbf683 )
ROM_LOAD( "5794", 0xc000, 0x2000, 0x5bdc1916 )
ROM_REGION_DISPOSE(0x28000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "5790", 0x00000, 0x4000, 0xac1558c1 )
ROM_LOAD( "5789", 0x04000, 0x4000, 0xfa66cab5 )
ROM_LOAD( "5801", 0x08000, 0x4000, 0xd70defa7 )
ROM_LOAD( "5802", 0x0c000, 0x4000, 0xd4f114b9 )
ROM_LOAD( "5799", 0x10000, 0x4000, 0x02c69432 )
ROM_LOAD( "5800", 0x14000, 0x4000, 0xebf1f948 )
ROM_LOAD( "5797", 0x18000, 0x4000, 0xf10a1d05 )
ROM_LOAD( "5798", 0x1c000, 0x4000, 0x614990cd )
ROM_LOAD( "5795", 0x20000, 0x4000, 0x5d987c92 )
ROM_LOAD( "5796", 0x24000, 0x4000, 0xde5700b4 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "5788", 0x0000, 0x1000, 0x5c1d0982 )
ROM_LOAD( "5787", 0x1000, 0x1000, 0x09e74ed8 )
ROM_LOAD( "5786", 0x2000, 0x1000, 0xc3e98284 )
ROM_LOAD( "5785", 0x3000, 0x1000, 0xced2fd47 )
ROM_END
ROM_START( rbtapper_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "rbtpg0.bin", 0x0000, 0x4000, 0x20b9adf4 )
ROM_LOAD( "rbtpg1.bin", 0x4000, 0x4000, 0x87e616c2 )
ROM_LOAD( "rbtpg2.bin", 0x8000, 0x4000, 0x0b332c97 )
ROM_LOAD( "rbtpg3.bin", 0xc000, 0x2000, 0x698c06f2 )
ROM_REGION_DISPOSE(0x28000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "rbtbg1.bin", 0x00000, 0x4000, 0x44dfa483 )
ROM_LOAD( "rbtbg0.bin", 0x04000, 0x4000, 0x510b13de )
ROM_LOAD( "rbtfg7.bin", 0x08000, 0x4000, 0x8dbf0c36 )
ROM_LOAD( "rbtfg6.bin", 0x0c000, 0x4000, 0x441201a0 )
ROM_LOAD( "rbtfg5.bin", 0x10000, 0x4000, 0x9eeca46e )
ROM_LOAD( "rbtfg4.bin", 0x14000, 0x4000, 0x8c79e7d7 )
ROM_LOAD( "rbtfg3.bin", 0x18000, 0x4000, 0x3e725e77 )
ROM_LOAD( "rbtfg2.bin", 0x1c000, 0x4000, 0x4ee8b624 )
ROM_LOAD( "rbtfg1.bin", 0x20000, 0x4000, 0x1c0b8791 )
ROM_LOAD( "rbtfg0.bin", 0x24000, 0x4000, 0xe99f6018 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "rbtsnda7.bin", 0x0000, 0x1000, 0x5c1d0982 )
ROM_LOAD( "rbtsnda8.bin", 0x1000, 0x1000, 0x09e74ed8 )
ROM_LOAD( "rbtsnda9.bin", 0x2000, 0x1000, 0xc3e98284 )
ROM_LOAD( "rbtsda10.bin", 0x3000, 0x1000, 0xced2fd47 )
ROM_END
struct GameDriver tapper_driver =
{
__FILE__,
0,
"tapper",
"Tapper (Budweiser)",
"1983",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria",
0,
&tapper_machine_driver,
0,
tapper_rom,
0, 0,
0,
0, /* sound_prom */
tapper_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
tapper_hiload, tapper_hisave
};
struct GameDriver sutapper_driver =
{
__FILE__,
&tapper_driver,
"sutapper",
"Tapper (Suntory)",
"1983",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria",
0,
&tapper_machine_driver,
0,
sutapper_rom,
0, 0,
0,
0, /* sound_prom */
tapper_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
tapper_hiload, tapper_hisave
};
struct GameDriver rbtapper_driver =
{
__FILE__,
&tapper_driver,
"rbtapper",
"Tapper (Root Beer)",
"1984",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria",
0,
&tapper_machine_driver,
0,
rbtapper_rom,
0, 0,
0,
0, /* sound_prom */
tapper_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
tapper_hiload, tapper_hisave
};
ROM_START( dotron_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "loc-pg0.1c", 0x0000, 0x4000, 0xba0da15f )
ROM_LOAD( "loc-pg1.2c", 0x4000, 0x4000, 0xdc300191 )
ROM_LOAD( "loc-pg2.3c", 0x8000, 0x4000, 0xab0b3800 )
ROM_LOAD( "loc-pg1.4c", 0xc000, 0x2000, 0xf98c9f8e )
ROM_REGION_DISPOSE(0x14000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "loc-bg2.6f", 0x00000, 0x2000, 0x40167124 )
ROM_LOAD( "loc-bg1.5f", 0x02000, 0x2000, 0xbb2d7a5d )
ROM_LOAD( "loc-a.cp0", 0x04000, 0x2000, 0xb35f5374 )
ROM_LOAD( "loc-b.cp9", 0x06000, 0x2000, 0x565a5c48 )
ROM_LOAD( "loc-c.cp8", 0x08000, 0x2000, 0xef45d146 )
ROM_LOAD( "loc-d.cp7", 0x0a000, 0x2000, 0x5e8a3ef3 )
ROM_LOAD( "loc-e.cp6", 0x0c000, 0x2000, 0xce957f1a )
ROM_LOAD( "loc-f.cp5", 0x0e000, 0x2000, 0xd26053ce )
ROM_LOAD( "loc-g.cp4", 0x10000, 0x2000, 0x57a2b1ff )
ROM_LOAD( "loc-h.cp3", 0x12000, 0x2000, 0x3bb4d475 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "sound0.a7", 0x0000, 0x1000, 0x6d39bf19 )
ROM_LOAD( "sound1.a8", 0x1000, 0x1000, 0xac872e1d )
ROM_LOAD( "sound2.a9", 0x2000, 0x1000, 0xe8ef6519 )
ROM_LOAD( "sound3.a10", 0x3000, 0x1000, 0x6b5aeb02 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "pre.u3", 0xd000, 0x1000, 0xc3d0f762 )
ROM_LOAD( "pre.u4", 0xe000, 0x1000, 0x7ca79b43 )
ROM_LOAD( "pre.u5", 0xf000, 0x1000, 0x24e9618e )
ROM_END
ROM_START( dotrone_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "loc-cpu1", 0x0000, 0x4000, 0xeee31b8c )
ROM_LOAD( "loc-cpu2", 0x4000, 0x4000, 0x75ba6ad3 )
ROM_LOAD( "loc-cpu3", 0x8000, 0x4000, 0x94bb1a0e )
ROM_LOAD( "loc-cpu4", 0xc000, 0x2000, 0xc137383c )
ROM_REGION_DISPOSE(0x14000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "loc-bg2.6f", 0x00000, 0x2000, 0x40167124 )
ROM_LOAD( "loc-bg1.5f", 0x02000, 0x2000, 0xbb2d7a5d )
ROM_LOAD( "loc-a.cp0", 0x04000, 0x2000, 0xb35f5374 )
ROM_LOAD( "loc-b.cp9", 0x06000, 0x2000, 0x565a5c48 )
ROM_LOAD( "loc-c.cp8", 0x08000, 0x2000, 0xef45d146 )
ROM_LOAD( "loc-d.cp7", 0x0a000, 0x2000, 0x5e8a3ef3 )
ROM_LOAD( "loc-e.cp6", 0x0c000, 0x2000, 0xce957f1a )
ROM_LOAD( "loc-f.cp5", 0x0e000, 0x2000, 0xd26053ce )
ROM_LOAD( "loc-g.cp4", 0x10000, 0x2000, 0x57a2b1ff )
ROM_LOAD( "loc-h.cp3", 0x12000, 0x2000, 0x3bb4d475 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "loc-a", 0x0000, 0x1000, 0x2de6a8a8 )
ROM_LOAD( "loc-b", 0x1000, 0x1000, 0x4097663e )
ROM_LOAD( "loc-c", 0x2000, 0x1000, 0xf576b9e7 )
ROM_LOAD( "loc-d", 0x3000, 0x1000, 0x74b0059e )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "pre.u3", 0xd000, 0x1000, 0xc3d0f762 )
ROM_LOAD( "pre.u4", 0xe000, 0x1000, 0x7ca79b43 )
ROM_LOAD( "pre.u5", 0xf000, 0x1000, 0x24e9618e )
ROM_END
struct GameDriver dotron_driver =
{
__FILE__,
0,
"dotron",
"Discs of Tron (Upright)",
"1983",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria\nAlan J. McCormick (speech info)\nMathis Rosenhauer(backdrop support)\nMike Balfour(backdrop support)\nBrandon Kirkpatrick (backdrop)",
0,
&dotron_machine_driver,
0,
dotron_rom,
0, 0,
0,
0, /* sound_prom */
dotron_input_ports,
0, 0,0,
ORIENTATION_FLIP_X,
dotron_hiload, dotron_hisave
};
struct GameDriver dotrone_driver =
{
__FILE__,
&dotron_driver,
"dotrone",
"Discs of Tron (Environmental)",
"1983",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria\nAlan J. McCormick (speech info)\nMathis Rosenhauer(backdrop support)\nMike Balfour(backdrop support)\nBrandon Kirkpatrick (backdrop)",
0,
&dotron_machine_driver,
0,
dotrone_rom,
0, 0,
0,
0, /* sound_prom */
dotron_input_ports,
0, 0,0,
ORIENTATION_FLIP_X,
dotron_hiload, dotron_hisave
};
ROM_START( destderb_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "dd_pro", 0x0000, 0x4000, 0x8781b367 )
ROM_LOAD( "dd_pro1", 0x4000, 0x4000, 0x4c713bfe )
ROM_LOAD( "dd_pro2", 0x8000, 0x4000, 0xc2cbd2a4 )
ROM_REGION_DISPOSE(0x24000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "dd_bg0.6f", 0x00000, 0x2000, 0xcf80be19 )
ROM_LOAD( "dd_bg1.5f", 0x02000, 0x2000, 0x4e173e52 )
ROM_LOAD( "dd_fg-3.a10", 0x04000, 0x4000, 0x801d9b86 )
ROM_LOAD( "dd_fg-7.a9", 0x08000, 0x4000, 0x0ec3f60a )
ROM_LOAD( "dd_fg-2.a8", 0x0c000, 0x4000, 0x6cab7b95 )
ROM_LOAD( "dd_fg-6.a7", 0x10000, 0x4000, 0xabfb9a8b )
ROM_LOAD( "dd_fg-1.a6", 0x14000, 0x4000, 0x70259651 )
ROM_LOAD( "dd_fg-5.a5", 0x18000, 0x4000, 0x5fe99007 )
ROM_LOAD( "dd_fg-0.a4", 0x1c000, 0x4000, 0xe57a4de6 )
ROM_LOAD( "dd_fg-4.a3", 0x20000, 0x4000, 0x55aa667f )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "dd_ssio.a7", 0x0000, 0x1000, 0xc95cf31e )
ROM_LOAD( "dd_ssio.a8", 0x1000, 0x1000, 0x12aaa48e )
ROM_END
struct GameDriver destderb_driver =
{
__FILE__,
0,
"destderb",
"Demolition Derby",
"1984",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria\nBrad Oliver",
0,
&destderb_machine_driver,
0,
destderb_rom,
0, 0,
0,
0, /* sound_prom */
destderb_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
destderb_hiload, destderb_hisave
};
ROM_START( timber_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "timpg0.bin", 0x0000, 0x4000, 0x377032ab )
ROM_LOAD( "timpg1.bin", 0x4000, 0x4000, 0xfd772836 )
ROM_LOAD( "timpg2.bin", 0x8000, 0x4000, 0x632989f9 )
ROM_LOAD( "timpg3.bin", 0xc000, 0x2000, 0xdae8a0dc )
ROM_REGION_DISPOSE(0x28000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "timbg1.bin", 0x00000, 0x4000, 0xb1cb2651 )
ROM_LOAD( "timbg0.bin", 0x04000, 0x4000, 0x2ae352c4 )
ROM_LOAD( "timfg7.bin", 0x08000, 0x4000, 0xd9c27475 )
ROM_LOAD( "timfg6.bin", 0x0c000, 0x4000, 0x244778e8 )
ROM_LOAD( "timfg5.bin", 0x10000, 0x4000, 0xeb636216 )
ROM_LOAD( "timfg4.bin", 0x14000, 0x4000, 0xb7105eb7 )
ROM_LOAD( "timfg3.bin", 0x18000, 0x4000, 0x37c03272 )
ROM_LOAD( "timfg2.bin", 0x1c000, 0x4000, 0xe2c2885c )
ROM_LOAD( "timfg1.bin", 0x20000, 0x4000, 0x81de4a73 )
ROM_LOAD( "timfg0.bin", 0x24000, 0x4000, 0x7f3a4f59 )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "tima7.bin", 0x0000, 0x1000, 0xc615dc3e )
ROM_LOAD( "tima8.bin", 0x1000, 0x1000, 0x83841c87 )
ROM_LOAD( "tima9.bin", 0x2000, 0x1000, 0x22bcdcd3 )
ROM_END
struct GameDriver timber_driver =
{
__FILE__,
0,
"timber",
"Timber",
"1984",
"Bally Midway",
"Christopher Kirmse\nAaron Giles\nNicola Salmoria\nBrad Oliver",
0,
&timber_machine_driver,
0,
timber_rom,
0, 0,
0,
0, /* sound_prom */
timber_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
timber_hiload, timber_hisave
};
ROM_START( rampage_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "pro-0.rv3", 0x0000, 0x8000, 0x2f7ca03c )
ROM_LOAD( "pro-1.rv3", 0x8000, 0x8000, 0xd89bd9a4 )
ROM_REGION_DISPOSE(0x48000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "bg-0", 0x00000, 0x04000, 0xc0d8b7a5 )
ROM_LOAD( "bg-1", 0x04000, 0x04000, 0x2f6e3aa1 )
ROM_LOAD( "fg-3", 0x08000, 0x10000, 0x81e1de40 )
ROM_LOAD( "fg-2", 0x18000, 0x10000, 0x9489f714 )
ROM_LOAD( "fg-1", 0x28000, 0x10000, 0x8728532b )
ROM_LOAD( "fg-0", 0x38000, 0x10000, 0x0974be5d )
ROM_REGION(0x20000) /* 128k for the Sounds Good board */
ROM_LOAD_EVEN( "ramp_u7.snd", 0x00000, 0x8000, 0xcffd7fa5 )
ROM_LOAD_ODD ( "ramp_u17.snd", 0x00000, 0x8000, 0xe92c596b )
ROM_LOAD_EVEN( "ramp_u8.snd", 0x10000, 0x8000, 0x11f787e4 )
ROM_LOAD_ODD ( "ramp_u18.snd", 0x10000, 0x8000, 0x6b8bf5e1 )
ROM_END
void rampage_rom_decode (void)
{
int i;
/* Rampage tile graphics are inverted */
for (i = 0; i < 0x8000; i++)
Machine->memory_region[1][i] ^= 0xff;
}
struct GameDriver rampage_driver =
{
__FILE__,
0,
"rampage",
"Rampage",
"1986",
"Bally Midway",
"Aaron Giles\nChristopher Kirmse\nNicola Salmoria\nBrad Oliver",
0,
&rampage_machine_driver,
0,
rampage_rom,
rampage_rom_decode, 0,
0,
0, /* sound_prom */
rampage_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
rampage_hiload, rampage_hisave
};
ROM_START( powerdrv_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "pdrv3b.bin", 0x0000, 0x8000, 0xd870b704 )
ROM_LOAD( "pdrv5b.bin", 0x8000, 0x8000, 0xfa0544ad )
ROM_REGION_DISPOSE(0x48000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "pdrv15a.bin", 0x00000, 0x04000, 0xb858b5a8 )
ROM_LOAD( "pdrv14b.bin", 0x04000, 0x04000, 0x12ee7fc2 )
ROM_LOAD( "pdrv4e.bin", 0x08000, 0x10000, 0xde400335 )
ROM_LOAD( "pdrv5e.bin", 0x18000, 0x10000, 0x4cb4780e )
ROM_LOAD( "pdrv6e.bin", 0x28000, 0x10000, 0x1a1f7f81 )
ROM_LOAD( "pdrv8e.bin", 0x38000, 0x10000, 0xdd3a2adc )
ROM_REGION(0x20000) /* 128k for the Sounds Good board */
ROM_LOAD_EVEN( "pdsndu7.bin", 0x00000, 0x8000, 0x78713e78 )
ROM_LOAD_ODD ( "pdsndu17.bin", 0x00000, 0x8000, 0xc41de6e4 )
ROM_LOAD_EVEN( "pdsndu8.bin", 0x10000, 0x8000, 0x15714036 )
ROM_LOAD_ODD ( "pdsndu18.bin", 0x10000, 0x8000, 0xcae14c70 )
ROM_END
struct GameDriver powerdrv_driver =
{
__FILE__,
0,
"powerdrv",
"Power Drive",
"????",
"Bally Midway",
"Aaron Giles\nChristopher Kirmse\nNicola Salmoria\nBrad Oliver",
0,
&rampage_machine_driver,
0,
powerdrv_rom,
rampage_rom_decode, 0,
0,
0, /* sound_prom */
rampage_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
0, 0
};
ROM_START( maxrpm_rom )
ROM_REGION(0x12000) /* 64k for code */
ROM_LOAD( "pro.0", 0x00000, 0x8000, 0x3f9ec35f )
ROM_LOAD( "pro.1", 0x08000, 0x6000, 0xf628bb30 )
ROM_CONTINUE( 0x10000, 0x2000 ) /* unused? but there seems to be stuff in here */
/* loading it at e000 causes rogue sprites to appear on screen */
ROM_REGION_DISPOSE(0x48000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "bg-0", 0x00000, 0x4000, 0xe3fb693a )
ROM_LOAD( "bg-1", 0x04000, 0x4000, 0x50d1db6c )
ROM_LOAD( "fg-3", 0x08000, 0x8000, 0x9ae3eb52 )
ROM_LOAD( "fg-2", 0x18000, 0x8000, 0x38be8505 )
ROM_LOAD( "fg-1", 0x28000, 0x8000, 0xe54b7f2a )
ROM_LOAD( "fg-0", 0x38000, 0x8000, 0x1d1435c1 )
ROM_END
struct GameDriver maxrpm_driver =
{
__FILE__,
0,
"maxrpm",
"Max RPM",
"1986",
"Bally Midway",
"Aaron Giles\nChristopher Kirmse\nNicola Salmoria\nBrad Oliver",
0,
&maxrpm_machine_driver,
0,
maxrpm_rom,
rampage_rom_decode, 0,
0,
0, /* sound_prom */
maxrpm_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
rampage_hiload, rampage_hisave
};
ROM_START( sarge_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "cpu_3b.bin", 0x0000, 0x8000, 0xda31a58f )
ROM_LOAD( "cpu_5b.bin", 0x8000, 0x8000, 0x6800e746 )
ROM_REGION_DISPOSE(0x24000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "til_15a.bin", 0x00000, 0x2000, 0x685001b8 )
ROM_LOAD( "til_14b.bin", 0x02000, 0x2000, 0x8449eb45 )
ROM_LOAD( "spr_4e.bin", 0x04000, 0x8000, 0xc382267d )
ROM_LOAD( "spr_5e.bin", 0x0c000, 0x8000, 0xc832375c )
ROM_LOAD( "spr_6e.bin", 0x14000, 0x8000, 0x7cc6fb28 )
ROM_LOAD( "spr_8e.bin", 0x1c000, 0x8000, 0x93fac29d )
ROM_REGION(0x10000) /* 64k for the Turbo Cheap Squeak */
ROM_LOAD( "tcs_u5.bin", 0xc000, 0x2000, 0xa894ef8a )
ROM_LOAD( "tcs_u4.bin", 0xe000, 0x2000, 0x6ca6faf3 )
ROM_END
void sarge_rom_decode (void)
{
int i;
/* Sarge tile graphics are inverted */
for (i = 0; i < 0x4000; i++)
Machine->memory_region[1][i] ^= 0xff;
}
struct GameDriver sarge_driver =
{
__FILE__,
0,
"sarge",
"Sarge",
"1985",
"Bally Midway",
"Aaron Giles\nChristopher Kirmse\nNicola Salmoria\nBrad Oliver",
0,
&sarge_machine_driver,
0,
sarge_rom,
sarge_rom_decode, 0,
0,
0, /* sound_prom */
sarge_input_ports,
0, 0,0,
ORIENTATION_DEFAULT,
0, 0
};
ROM_START( spyhunt_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "cpu_pg0.6d", 0x0000, 0x2000, 0x1721b88f )
ROM_LOAD( "cpu_pg1.7d", 0x2000, 0x2000, 0x909d044f )
ROM_LOAD( "cpu_pg2.8d", 0x4000, 0x2000, 0xafeeb8bd )
ROM_LOAD( "cpu_pg3.9d", 0x6000, 0x2000, 0x5e744381 )
ROM_LOAD( "cpu_pg4.10d", 0x8000, 0x2000, 0xa3033c15 )
ROM_LOAD( "cpu_pg5.11d", 0xA000, 0x4000, 0x88aa1e99 )
ROM_REGION_DISPOSE(0x29000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "cpu_bg2.5a", 0x0000, 0x2000, 0xba0fd626 )
ROM_LOAD( "cpu_bg3.6a", 0x2000, 0x2000, 0x7b482d61 )
ROM_LOAD( "cpu_bg0.3a", 0x4000, 0x2000, 0xdea34fed )
ROM_LOAD( "cpu_bg1.4a", 0x6000, 0x2000, 0x8f64525f )
ROM_LOAD( "vid_6fg.a2", 0x8000, 0x4000, 0x8cb8a066 )
ROM_LOAD( "vid_7fg.a1", 0xc000, 0x4000, 0x940fe17e )
ROM_LOAD( "vid_4fg.a4", 0x10000, 0x4000, 0x7ca4941b )
ROM_LOAD( "vid_5fg.a3", 0x14000, 0x4000, 0x2d9fbcec )
ROM_LOAD( "vid_2fg.a6", 0x18000, 0x4000, 0x62c8bfa5 )
ROM_LOAD( "vid_3fg.a5", 0x1c000, 0x4000, 0xb894934d )
ROM_LOAD( "vid_0fg.a8", 0x20000, 0x4000, 0x292c5466 )
ROM_LOAD( "vid_1fg.a7", 0x24000, 0x4000, 0x9fe286ec )
ROM_LOAD( "cpu_alph.10g", 0x28000, 0x1000, 0x936dc87f )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "snd_0sd.a8", 0x0000, 0x1000, 0xc95cf31e )
ROM_LOAD( "snd_1sd.a7", 0x1000, 0x1000, 0x12aaa48e )
ROM_REGION(0x8000) /* 32k for the Chip Squeak Deluxe */
ROM_LOAD_EVEN( "csd_u7a.u7", 0x00000, 0x2000, 0x6e689fe7 )
ROM_LOAD_ODD ( "csd_u17b.u17", 0x00000, 0x2000, 0x0d9ddce6 )
ROM_LOAD_EVEN( "csd_u8c.u8", 0x04000, 0x2000, 0x35563cd0 )
ROM_LOAD_ODD ( "csd_u18d.u18", 0x04000, 0x2000, 0x63d3f5b1 )
ROM_END
struct GameDriver spyhunt_driver =
{
__FILE__,
0,
"spyhunt",
"Spy Hunter",
"1983",
"Bally Midway",
"Aaron Giles\nChristopher Kirmse\nNicola Salmoria\nBrad Oliver\nLawnmower Man",
0,
&spyhunt_machine_driver,
0,
spyhunt_rom,
spyhunt_decode, 0,
0,
0, /* sound_prom */
spyhunt_input_ports,
0, 0,0,
ORIENTATION_ROTATE_90,
spyhunt_hiload, spyhunt_hisave
};
ROM_START( crater_rom )
ROM_REGION(0x10000) /* 64k for code */
ROM_LOAD( "crcpu.6d", 0x0000, 0x2000, 0xad31f127 )
ROM_LOAD( "crcpu.7d", 0x2000, 0x2000, 0x3743c78f )
ROM_LOAD( "crcpu.8d", 0x4000, 0x2000, 0xc95f9088 )
ROM_LOAD( "crcpu.9d", 0x6000, 0x2000, 0xa03c4b11 )
ROM_LOAD( "crcpu.10d", 0x8000, 0x2000, 0x44ae4cbd )
ROM_REGION_DISPOSE(0x29000) /* temporary space for graphics (disposed after conversion) */
ROM_LOAD( "crcpu.5a", 0x00000, 0x2000, 0x2fe4a6e1 )
ROM_LOAD( "crcpu.6a", 0x02000, 0x2000, 0xd0659042 )
ROM_LOAD( "crcpu.3a", 0x04000, 0x2000, 0x9d73504a )
ROM_LOAD( "crcpu.4a", 0x06000, 0x2000, 0x42a47dff )
ROM_LOAD( "crvid.a9", 0x08000, 0x4000, 0x811f152d )
ROM_LOAD( "crvid.a10", 0x0c000, 0x4000, 0x7a22d6bc )
ROM_LOAD( "crvid.a7", 0x10000, 0x4000, 0x9fa307d5 )
ROM_LOAD( "crvid.a8", 0x14000, 0x4000, 0x4b913498 )
ROM_LOAD( "crvid.a5", 0x18000, 0x4000, 0x9bdec312 )
ROM_LOAD( "crvid.a6", 0x1c000, 0x4000, 0x5bf954e0 )
ROM_LOAD( "crvid.a3", 0x20000, 0x4000, 0x2c2f5b29 )
ROM_LOAD( "crvid.a4", 0x24000, 0x4000, 0x579a8e36 )
ROM_LOAD( "crcpu.10g", 0x28000, 0x1000, 0x6fe53c8d )
ROM_REGION(0x10000) /* 64k for the audio CPU */
ROM_LOAD( "crsnd4.a7", 0x0000, 0x1000, 0xfd666cb5 )
ROM_LOAD( "crsnd1.a8", 0x1000, 0x1000, 0x90bf2c4c )
ROM_LOAD( "crsnd2.a9", 0x2000, 0x1000, 0x3b8deef1 )
ROM_LOAD( "crsnd3.a10", 0x3000, 0x1000, 0x05803453 )
ROM_END
struct GameDriver crater_driver =
{
__FILE__,
0,
"crater",
"Crater Raider",
"1984",
"Bally Midway",
"Aaron Giles\nChristopher Kirmse\nNicola Salmoria\nBrad Oliver\nLawnmower Man",
0,
&crater_machine_driver,
0,
crater_rom,
0, 0,
0,
0, /* sound_prom */
crater_input_ports,
0, 0,0,
ORIENTATION_FLIP_X,
crater_hiload, crater_hisave
};
| 29.543897 | 186 | 0.681757 |
80c98983d664cca7b9dc656ae9f59552415a5233 | 118 | cpp | C++ | project653/src/component723/cpp/lib2.cpp | gradle/perf-native-large | af00fd258fbe9c7d274f386e46847fe12062cc71 | [
"Apache-2.0"
] | 2 | 2016-11-23T17:25:24.000Z | 2016-11-23T17:25:27.000Z | project653/src/component723/cpp/lib2.cpp | gradle/perf-native-large | af00fd258fbe9c7d274f386e46847fe12062cc71 | [
"Apache-2.0"
] | 15 | 2016-09-15T03:19:32.000Z | 2016-09-17T09:15:32.000Z | project653/src/component723/cpp/lib2.cpp | gradle/perf-native-large | af00fd258fbe9c7d274f386e46847fe12062cc71 | [
"Apache-2.0"
] | 2 | 2019-11-09T16:26:55.000Z | 2021-01-13T10:51:09.000Z | #include <stdio.h>
#include <component723/lib1.h>
int component723_2 () {
printf("Hello world!\n");
return 0;
}
| 13.111111 | 30 | 0.661017 |
80ca1ab3449e46af8d331c9fade430d018de3345 | 17,343 | cc | C++ | third_party/incubator-tvm/nnvm/src/top/nn/pooling.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | 286 | 2020-06-23T06:40:44.000Z | 2022-03-30T01:27:49.000Z | third_party/incubator-tvm/nnvm/src/top/nn/pooling.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | 10 | 2020-07-31T03:26:59.000Z | 2021-12-27T15:00:54.000Z | third_party/incubator-tvm/nnvm/src/top/nn/pooling.cc | KnowingNothing/akg-test | 114d8626b824b9a31af50a482afc07ab7121862b | [
"Apache-2.0"
] | 30 | 2020-07-17T01:04:14.000Z | 2021-12-27T14:05:19.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.
*/
/*!
* \file pooling.cc
* \brief Property def of pooling operators.
*/
#include <nnvm/op.h>
#include <nnvm/node.h>
#include <nnvm/op_attr_types.h>
#include <nnvm/compiler/op_attr_types.h>
#include <nnvm/compiler/util.h>
#include <nnvm/top/nn.h>
#include "nn_common.h"
#include "../op_common.h"
#include "../elemwise_op_common.h"
#include "topi/nn/pooling.h"
namespace nnvm {
namespace top {
using namespace air;
using namespace nnvm::compiler;
DMLC_REGISTER_PARAMETER(MaxPool2DParam);
template <typename T>
inline bool Pool2DInferShape(const nnvm::NodeAttrs& attrs,
std::vector<TShape>* in_shape,
std::vector<TShape>* out_shape) {
const T& param = nnvm::get<T>(attrs.parsed);
CHECK_EQ(in_shape->size(), 1U);
CHECK_EQ(out_shape->size(), 1U);
TShape dshape = (*in_shape)[0];
if (dshape.ndim() == 0) return false;
CHECK_GE(dshape.ndim(), 2U)
<< "Pool2D only support input >= 2-D: input must have height and width";
Layout layout(param.layout);
CHECK(layout.contains('H') && layout.contains('W') &&
!layout.contains('h') && !layout.contains('w'))
<< "Invalid layout " << layout
<< ". Pool2D layout must have H and W, which cannot be split";
const auto hidx = layout.indexof('H');
const auto widx = layout.indexof('W');
dim_t pad_h, pad_w;
if (param.padding.ndim() == 1) {
pad_h = param.padding[0] * 2;
pad_w = param.padding[0] * 2;
} else if (param.padding.ndim() == 2) {
// (top, left)
pad_h = param.padding[0] * 2;
pad_w = param.padding[1] * 2;
} else if (param.padding.ndim() == 4) {
// (top, left, bottom, right)
pad_h = param.padding[0] + param.padding[2];
pad_w = param.padding[1] + param.padding[3];
} else {
return false;
}
TShape oshape = dshape;
CHECK(param.pool_size[0] <= dshape[hidx] + pad_h)
<< "pool size (" << param.pool_size[0] << ") exceeds input (" << dshape[hidx]
<< " padded to " << (dshape[hidx] + pad_h) << ")";
CHECK(param.pool_size[1] <= dshape[widx] + pad_w)
<< "pool size (" << param.pool_size[1] << ") exceeds input (" << dshape[widx]
<< " padded to " << (dshape[widx] + pad_w) << ")";
if (!param.ceil_mode) {
oshape[hidx] = ((dshape[hidx] + pad_h - param.pool_size[0]) /
param.strides[0]) + 1;
oshape[widx] = ((dshape[widx] + pad_w - param.pool_size[1]) /
param.strides[1]) + 1;
} else {
oshape[hidx] = ((dshape[hidx] + pad_h - param.pool_size[0] +
param.strides[0] - 1) / param.strides[0]) + 1;
oshape[widx] = ((dshape[widx] + pad_w - param.pool_size[1] +
param.strides[1] - 1) / param.strides[1]) + 1;
}
NNVM_ASSIGN_OUTPUT_SHAPE(attrs, *out_shape, 0, oshape);
return true;
}
template <typename T>
inline bool Pool2DCorrectLayout(const NodeAttrs& attrs,
std::vector<Layout> *ilayouts,
const std::vector<Layout> *last_ilayouts,
std::vector<Layout> *olayouts) {
const T ¶m = nnvm::get<T>(attrs.parsed);
CHECK_EQ(ilayouts->size(), 1);
CHECK_EQ(last_ilayouts->size(), 1);
CHECK_EQ(olayouts->size(), 1);
Layout input = (*ilayouts)[0];
const Layout layout(param.layout);
if (input.defined()) {
CHECK(input.convertible(layout)) << "Invalid input layout " << input;
if (input.indexof('W') != layout.indexof('W') ||
input.indexof('H') != layout.indexof('H') ||
input.contains('w') || input.contains('h')) {
// as long as the index doesn't change for width and height
// pool2d can keep the input layout.
input = layout;
}
} else {
input = layout;
}
NNVM_ASSIGN_LAYOUT(*ilayouts, 0, input);
NNVM_ASSIGN_LAYOUT(*olayouts, 0, input);
return true;
}
NNVM_REGISTER_OP(max_pool2d)
.describe(R"code(Max pooling operation for one dimensional data.
- **data**: This depends on the `layout` parameter. Input is 4D array of shape
(batch_size, channels, height, width) if `layout` is `NCHW`.
- **out**: This depends on the `layout` parameter. Output is 4D array of shape
(batch_size, channels, out_height, out_width) if `layout` is `NCHW`.
out_height and out_width are calculated as::
out_height = floor((height+padding[0]+padding[2]-pool_size[0])/strides[0])+1
out_width = floor((width+padding[1]+padding[3]-pool_size[1])/strides[1])+1
where padding will be an expanded array based on number of values passed as::
one int : all sides same padding used.
two int : bottom, right use same as top and left.
four int: padding width in the order of (top, left, bottom, right).
When `ceil_mode` is `True`, ceil will be used instead of floor in this
equation.
)code" NNVM_ADD_FILELINE)
.add_argument("data", "4D Tensor", "Input data.")
.add_arguments(MaxPool2DParam::__FIELDS__())
.set_attr_parser(ParamParser<MaxPool2DParam>)
.set_attr<FGetAttrDict>("FGetAttrDict", ParamGetAttrDict<MaxPool2DParam>)
.set_num_outputs(1)
.set_num_inputs(1)
.set_attr<FInferShape>("FInferShape", Pool2DInferShape<MaxPool2DParam>)
.set_attr<FInferType>("FInferType", ElemwiseType<1, 1>)
.set_attr<FCorrectLayout>("FCorrectLayout", Pool2DCorrectLayout<MaxPool2DParam>)
.set_attr<FTVMCompute>("FTVMCompute", [](const NodeAttrs& attrs,
const Array<Tensor>& inputs,
const Array<Tensor>& out_info) {
const MaxPool2DParam& param = nnvm::get<MaxPool2DParam>(attrs.parsed);
auto pool_size = ShapeToArray(param.pool_size);
auto strides = ShapeToArray(param.strides);
auto padding = ShapeToArray(param.padding);
auto ceil_mode = param.ceil_mode;
Layout layout(param.layout);
CHECK(layout.convertible(Layout("NCHW")))
<< "max_pool2d currently only supports layouts that are convertible from NCHW";
CHECK_EQ(layout.indexof('h'), -1) << "max_pool2d does not support input split on height";
CHECK_EQ(layout.indexof('w'), -1) << "max_pool2d does not support input split on width";
CHECK(inputs[0].ndim() == 4U || inputs[0].ndim() == 5U)
<< "Pool2D only support 4-D input (e.g., NCHW)"
<< " or 5-D input (last dimension is a split of channel)";
if (param.padding.ndim() == 1) {
padding.push_back(padding[0]);
padding.push_back(padding[0]);
padding.push_back(padding[0]);
} else if (param.padding.ndim() == 2) {
padding.push_back(padding[0]);
padding.push_back(padding[1]);
}
return Array<Tensor>{
topi::nn::pool(inputs[0], pool_size, strides, padding,
topi::nn::kMaxPool, ceil_mode, layout.name())};
})
.set_attr<FGradient>(
"FGradient", [](const NodePtr& n,
const std::vector<NodeEntry>& ograds) {
return MakeGradNode("_max_pool2d_grad", n,
{ograds[0], n->inputs[0], NodeEntry{n, 0, 0}},
n->attrs.dict);
})
.set_support_level(2);
NNVM_REGISTER_OP(_max_pool2d_grad)
.describe(R"code(Max pooling 2D grad.
)code" NNVM_ADD_FILELINE)
.add_argument("ograd", "4D Tensor", "Output grad.")
.add_argument("input", "4D Tensor", "Input data of max_pool2d grad.")
.add_argument("output", "4D Tensor", "Output data of max_pool2d grad.")
.set_num_inputs(3)
.set_num_outputs(1)
.set_attr_parser(ParamParser<MaxPool2DParam>)
.set_attr<FGetAttrDict>("FGetAttrDict", ParamGetAttrDict<MaxPool2DParam>)
.set_attr<FInferShape>("FInferShape", AssignOutputAttr<TShape, 1, 0>)
.set_attr<FInferType>("FInferType", ElemwiseType<3, 1>)
.set_attr<TIsBackward>("TIsBackward", true);
DMLC_REGISTER_PARAMETER(AvgPool2DParam);
NNVM_REGISTER_OP(avg_pool2d)
.describe(R"code(Average pooling operation for one dimensional data.
- **data**: This depends on the `layout` parameter. Input is 4D array of shape
(batch_size, channels, height, width) if `layout` is `NCHW`.
- **out**: This depends on the `layout` parameter. Output is 4D array of shape
(batch_size, channels, out_height, out_width) if `layout` is `NCHW`.
out_height and out_width are calculated as::
out_height = floor((height+padding[0]+padding[2]-pool_size[0])/strides[0])+1
out_width = floor((width+padding[1]+padding[3]-pool_size[1])/strides[1])+1
where padding will be an expanded array based on number of values passed as::
one int : all sides same padding used.
two int : bottom, right use same as top and left.
four int: padding width in the order of (top, left, bottom, right).
When `ceil_mode` is `True`, ceil will be used instead of floor in this
equation.
)code" NNVM_ADD_FILELINE)
.add_argument("data", "4D Tensor", "Input data.")
.add_arguments(AvgPool2DParam::__FIELDS__())
.set_attr_parser(ParamParser<AvgPool2DParam>)
.set_attr<FGetAttrDict>("FGetAttrDict", ParamGetAttrDict<AvgPool2DParam>)
.set_attr<FInferShape>("FInferShape", Pool2DInferShape<AvgPool2DParam>)
.set_attr<FInferType>("FInferType", ElemwiseType<1, 1>)
.set_attr<FCorrectLayout>("FCorrectLayout", Pool2DCorrectLayout<AvgPool2DParam>)
.set_attr<FTVMCompute>("FTVMCompute", [](const NodeAttrs& attrs,
const Array<Tensor>& inputs,
const Array<Tensor>& out_info) {
const AvgPool2DParam& param = nnvm::get<AvgPool2DParam>(attrs.parsed);
auto pool_size = ShapeToArray(param.pool_size);
auto strides = ShapeToArray(param.strides);
auto padding = ShapeToArray(param.padding);
auto ceil_mode = param.ceil_mode;
auto count_include_pad = param.count_include_pad;
Layout layout(param.layout);
CHECK(layout.convertible(Layout("NCHW")))
<< "avg_pool2d currently only supports layouts that are convertible from NCHW";
CHECK_EQ(layout.indexof('h'), -1) << "avg_pool2d does not support input split on height";
CHECK_EQ(layout.indexof('w'), -1) << "avg_pool2d does not support input split on width";
CHECK(inputs[0].ndim() == 4U || inputs[0].ndim() == 5U)
<< "Pool2D only support 4-D input (e.g., NCHW)"
<< " or 5-D input (last dimension is a split of channel)";
if (param.padding.ndim() == 1) {
padding.push_back(padding[0]);
padding.push_back(padding[0]);
padding.push_back(padding[0]);
} else if (param.padding.ndim() == 2) {
padding.push_back(padding[0]);
padding.push_back(padding[1]);
}
return Array<Tensor>{
topi::nn::pool(inputs[0], pool_size, strides, padding,
topi::nn::kAvgPool, ceil_mode, layout.name(), count_include_pad)};
})
.set_num_outputs(1)
.set_num_inputs(1)
.set_support_level(2);
DMLC_REGISTER_PARAMETER(GlobalPool2DParam);
inline bool GlobalPool2DInferShape(const nnvm::NodeAttrs& attrs,
std::vector<TShape>* in_shape,
std::vector<TShape>* out_shape) {
static const Layout kNCHW("NCHW");
const GlobalPool2DParam& param = nnvm::get<GlobalPool2DParam>(attrs.parsed);
CHECK_EQ(in_shape->size(), 1U);
CHECK_EQ(out_shape->size(), 1U);
TShape dshape = (*in_shape)[0];
if (dshape.ndim() == 0) return false;
CHECK_GE(dshape.ndim(), 2U)
<< "Pool2D only support input >= 2-D: input must have height and width";
Layout layout(param.layout);
CHECK(layout.contains('H') && layout.contains('W') &&
!layout.contains('h') && !layout.contains('w'))
<< "Invalid layout " << layout
<< ". Pool2D layout must have H and W, which cannot be split";
const auto hidx = layout.indexof('H');
const auto widx = layout.indexof('W');
TShape oshape = dshape;
oshape[hidx] = oshape[widx] = 1;
NNVM_ASSIGN_OUTPUT_SHAPE(attrs, *out_shape, 0, oshape);
return true;
}
inline bool GlobalPool2DCorrectLayout(const NodeAttrs& attrs,
std::vector<Layout> *ilayouts,
const std::vector<Layout> *last_ilayouts,
std::vector<Layout> *olayouts) {
const GlobalPool2DParam ¶m = nnvm::get<GlobalPool2DParam>(attrs.parsed);
CHECK_EQ(ilayouts->size(), 1);
CHECK_EQ(last_ilayouts->size(), 1);
CHECK_EQ(olayouts->size(), 1);
Layout input = (*ilayouts)[0];
const Layout layout(param.layout);
if (input.defined()) {
CHECK(input.convertible(layout)) << "Invalid input layout " << input;
if (input.indexof('W') != layout.indexof('W') ||
input.indexof('H') != layout.indexof('H') ||
input.contains('w') || input.contains('h')) {
// as long as the index doesn't change for width and height
// pool2d can keep the input layout.
input = layout;
}
} else {
input = layout;
}
NNVM_ASSIGN_LAYOUT(*ilayouts, 0, input);
NNVM_ASSIGN_LAYOUT(*olayouts, 0, input);
return true;
}
NNVM_REGISTER_OP(global_max_pool2d)
.describe(R"code(Global max pooling operation for 2D data.
- **data**: This depends on the `layout` parameter. Input is 4D array of shape
(batch_size, channels, height, width) if `layout` is `NCHW`.
- **out**: This depends on the `layout` parameter. Output is 4D array of shape
(batch_size, channels, 1, 1) if `layout` is `NCHW`.
)code" NNVM_ADD_FILELINE)
.add_argument("data", "4D Tensor", "Input data.")
.add_arguments(GlobalPool2DParam::__FIELDS__())
.set_attr_parser(ParamParser<GlobalPool2DParam>)
.set_attr<FGetAttrDict>("FGetAttrDict", ParamGetAttrDict<GlobalPool2DParam>)
.set_attr<FInferShape>("FInferShape", GlobalPool2DInferShape)
.set_attr<FInferType>("FInferType", ElemwiseType<1, 1>)
.set_attr<FCorrectLayout>("FCorrectLayout", GlobalPool2DCorrectLayout)
.set_attr<FTVMCompute>(
"FTVMCompute", [](const NodeAttrs& attrs,
const Array<Tensor>& inputs,
const Array<Tensor>& out_info) {
const GlobalPool2DParam& param = nnvm::get<GlobalPool2DParam>(attrs.parsed);
Layout layout(param.layout);
CHECK(layout.convertible(Layout("NCHW")))
<< "global_max_pool2d currently only supports layouts that are convertible from NCHW";
CHECK_EQ(layout.indexof('h'), -1)
<< "global_max_pool2d does not support input split on height";
CHECK_EQ(layout.indexof('w'), -1)
<< "global_max_pool2d does not support input split on width";
CHECK(inputs[0].ndim() == 4U || inputs[0].ndim() == 5U)
<< "Pool2D only support 4-D input (e.g., NCHW)"
<< " or 5-D input (last dimension is a split of channel)";
return Array<Tensor>{
topi::nn::global_pool(inputs[0], topi::nn::kMaxPool, layout.name()) };
})
.set_num_outputs(1)
.set_num_inputs(1)
.set_support_level(2);
NNVM_REGISTER_OP(global_avg_pool2d)
.describe(R"code(Global average pooling operation for 2D data.
- **data**: This depends on the `layout` parameter. Input is 4D array of shape
(batch_size, channels, height, width) if `layout` is `NCHW`.
- **out**: This depends on the `layout` parameter. Output is 4D array of shape
(batch_size, channels, 1, 1) if `layout` is `NCHW`.
)code" NNVM_ADD_FILELINE)
.add_argument("data", "4D Tensor", "Input data.")
.add_arguments(GlobalPool2DParam::__FIELDS__())
.set_attr_parser(ParamParser<GlobalPool2DParam>)
.set_attr<FGetAttrDict>("FGetAttrDict", ParamGetAttrDict<GlobalPool2DParam>)
.set_attr<FInferShape>("FInferShape", GlobalPool2DInferShape)
.set_attr<FInferType>("FInferType", ElemwiseType<1, 1>)
.set_attr<FCorrectLayout>("FCorrectLayout", GlobalPool2DCorrectLayout)
.set_attr<FTVMCompute>(
"FTVMCompute", [](const NodeAttrs& attrs,
const Array<Tensor>& inputs,
const Array<Tensor>& out_info) {
const GlobalPool2DParam& param = nnvm::get<GlobalPool2DParam>(attrs.parsed);
Layout layout(param.layout);
CHECK(layout.convertible(Layout("NCHW")))
<< "global_avg_pool2d currently only supports layouts that are convertible from NCHW";
CHECK_EQ(layout.indexof('h'), -1)
<< "global_avg_pool2d does not support input split on height";
CHECK_EQ(layout.indexof('w'), -1)
<< "global_avg_pool2d does not support input split on width";
CHECK(inputs[0].ndim() == 4U || inputs[0].ndim() == 5U)
<< "Pool2D only support 4-D input (e.g., NCHW)"
<< " or 5-D input (last dimension is a split of channel)";
return Array<Tensor>{
topi::nn::global_pool(inputs[0], topi::nn::kAvgPool, layout.name()) };
})
.set_num_outputs(1)
.set_num_inputs(1)
.set_support_level(2);
} // namespace top
} // namespace nnvm
| 39.777523 | 91 | 0.659056 |
80ca4c1fac04ac410563ed7d8aa939c84589ad08 | 7,349 | cpp | C++ | libs/settings/tests/unit/setting_tests.cpp | jinmannwong/ledger | f3b129c127e107603e08bb192eb695d23eb17dbc | [
"Apache-2.0"
] | null | null | null | libs/settings/tests/unit/setting_tests.cpp | jinmannwong/ledger | f3b129c127e107603e08bb192eb695d23eb17dbc | [
"Apache-2.0"
] | null | null | null | libs/settings/tests/unit/setting_tests.cpp | jinmannwong/ledger | f3b129c127e107603e08bb192eb695d23eb17dbc | [
"Apache-2.0"
] | 2 | 2019-11-13T10:55:24.000Z | 2019-11-13T11:37:09.000Z | //------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include "settings/setting.hpp"
#include "settings/setting_collection.hpp"
#include "gtest/gtest.h"
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
namespace {
using fetch::settings::Setting;
using fetch::settings::SettingCollection;
TEST(SettingTests, CheckUInt32)
{
SettingCollection collection{};
Setting<uint32_t> setting{collection, "foo", 0, "A sample setting"};
EXPECT_EQ(setting.name(), "foo");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 0);
EXPECT_EQ(setting.value(), 0u);
std::istringstream iss{"401"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "foo");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 0u);
EXPECT_EQ(setting.value(), 401u);
}
TEST(SettingTests, CheckSizet)
{
SettingCollection collection{};
Setting<std::size_t> setting{collection, "block-interval", 250u, "A sample setting"};
EXPECT_EQ(setting.name(), "block-interval");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 250u);
EXPECT_EQ(setting.value(), 250u);
std::istringstream iss{"40100"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "block-interval");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 250u);
EXPECT_EQ(setting.value(), 40100u);
}
TEST(SettingTests, CheckDouble)
{
SettingCollection collection{};
Setting<double> setting{collection, "threshold", 10.0, "A sample setting"};
EXPECT_EQ(setting.name(), "threshold");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_DOUBLE_EQ(setting.default_value(), 10.0);
EXPECT_DOUBLE_EQ(setting.value(), 10.0);
std::istringstream iss{"3.145"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "threshold");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_DOUBLE_EQ(setting.default_value(), 10.0);
EXPECT_DOUBLE_EQ(setting.value(), 3.145);
}
TEST(SettingTests, CheckBool)
{
SettingCollection collection{};
Setting<bool> setting{collection, "flag", false, "A sample setting"};
EXPECT_EQ(setting.name(), "flag");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), false);
EXPECT_EQ(setting.value(), false);
for (auto const &on_value : {"true", "1", "on", "enabled"})
{
setting.Update(false);
std::istringstream iss{on_value};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "flag");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), false);
EXPECT_EQ(setting.value(), true);
}
for (auto const &off_value : {"false", "0", "off", "disabled"})
{
setting.Update(true);
std::istringstream iss{off_value};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "flag");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), false);
EXPECT_EQ(setting.value(), false);
}
}
TEST(SettingTests, CheckStringList)
{
using StringArray = std::vector<std::string>;
SettingCollection collection{};
Setting<StringArray> setting{collection, "peers", {}, "A sample setting"};
EXPECT_EQ(setting.name(), "peers");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), StringArray{});
EXPECT_EQ(setting.value(), StringArray{});
{
setting.Update(StringArray{});
std::istringstream iss{"foo"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "peers");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), StringArray{});
EXPECT_EQ(setting.value(), StringArray({"foo"}));
}
{
setting.Update(StringArray{});
std::istringstream iss{"foo,bar,baz"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "peers");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), StringArray{});
EXPECT_EQ(setting.value(), StringArray({"foo", "bar", "baz"}));
}
}
TEST(SettingTests, CheckUInt32Invalid)
{
SettingCollection collection{};
Setting<uint32_t> setting{collection, "foo", 0, "A sample setting"};
EXPECT_EQ(setting.name(), "foo");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 0);
EXPECT_EQ(setting.value(), 0u);
std::istringstream iss{"blah blah blah"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "foo");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 0u);
EXPECT_EQ(setting.value(), 0u);
}
TEST(SettingTests, CheckBoolInvalid)
{
SettingCollection collection{};
Setting<bool> setting{collection, "flag", false, "A sample setting"};
EXPECT_EQ(setting.name(), "flag");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), false);
EXPECT_EQ(setting.value(), false);
for (auto const &on_value : {"blah", "please", "gogogo", "launch"})
{
setting.Update(false);
std::istringstream iss{on_value};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "flag");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), false);
EXPECT_EQ(setting.value(), false);
}
}
TEST(SettingTests, CheckSizetInvalid)
{
SettingCollection collection{};
Setting<std::size_t> setting{collection, "block-interval", 250u, "A sample setting"};
EXPECT_EQ(setting.name(), "block-interval");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 250u);
EXPECT_EQ(setting.value(), 250u);
std::istringstream iss{"twenty-four"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "block-interval");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_EQ(setting.default_value(), 250u);
EXPECT_EQ(setting.value(), 250u);
}
TEST(SettingTests, CheckDoubleInvalid)
{
SettingCollection collection{};
Setting<double> setting{collection, "threshold", 10.0, "A sample setting"};
EXPECT_EQ(setting.name(), "threshold");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_DOUBLE_EQ(setting.default_value(), 10.0);
EXPECT_DOUBLE_EQ(setting.value(), 10.0);
std::istringstream iss{"very-small-number"};
setting.FromStream(iss);
EXPECT_EQ(setting.name(), "threshold");
EXPECT_EQ(setting.description(), "A sample setting");
EXPECT_DOUBLE_EQ(setting.default_value(), 10.0);
EXPECT_DOUBLE_EQ(setting.value(), 10.0);
}
} // namespace
| 29.753036 | 87 | 0.68608 |
80ccef118362e7a49e597bc41752dd6e1eba9513 | 1,022 | cpp | C++ | Solutions/Construct Binary Tree from Preorder and Inorder/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | 1 | 2015-04-13T10:58:30.000Z | 2015-04-13T10:58:30.000Z | Solutions/Construct Binary Tree from Preorder and Inorder/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | null | null | null | Solutions/Construct Binary Tree from Preorder and Inorder/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x): val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
return f(preorder, 0, preorder.size(), inorder, 0, inorder.size());
}
TreeNode *f(vector<int> &preorder, int pre_start, int pre_end, vector<int> &inorder, int in_start, int in_end) {
if (pre_start >= pre_end || in_start >= in_end) {
return NULL;
}
int root_val = preorder[pre_start];
TreeNode *root = new TreeNode(root_val);
int i = in_start;
for(; inorder[i] != root_val; i++);
int left_dis = i - in_start;
root->left = f(preorder, pre_start+1, pre_start + 1 + left_dis, inorder, in_start, i);
root->right = f(preorder, pre_start+1+left_dis, pre_end, inorder, i+1, in_end);
return root;
}
};
int main()
{
return 0;
}
| 29.2 | 116 | 0.605675 |
80ce767867f6a8ab050934ab193ba2fbeb6723d4 | 8,124 | hpp | C++ | response_cv.hpp | 56059943/hlcinatra | de57b35a85cfc77d9c2f9645bbfbe9051ae8d068 | [
"MIT"
] | 2 | 2018-07-23T01:48:48.000Z | 2020-05-25T09:40:47.000Z | response_cv.hpp | xiaoK0726/cinatra | 438bf3accbcbebfd585a899c2c079f950769f946 | [
"MIT"
] | null | null | null | response_cv.hpp | xiaoK0726/cinatra | 438bf3accbcbebfd585a899c2c079f950769f946 | [
"MIT"
] | 1 | 2018-12-13T07:15:54.000Z | 2018-12-13T07:15:54.000Z | #pragma once
#include "use_asio.hpp"
#include <string_view>
namespace cinatra {
enum class status_type {
init,
switching_protocols = 101,
ok = 200,
created = 201,
accepted = 202,
no_content = 204,
partial_content = 206,
multiple_choices = 300,
moved_permanently = 301,
moved_temporarily = 302,
not_modified = 304,
bad_request = 400,
unauthorized = 401,
forbidden = 403,
not_found = 404,
internal_server_error = 500,
not_implemented = 501,
bad_gateway = 502,
service_unavailable = 503
};
enum class content_encoding {
gzip,
none
};
inline std::string_view ok = "OK";
inline std::string_view created = "<html>"
"<head><title>Created</title></head>"
"<body><h1>201 Created</h1></body>"
"</html>";
inline std::string_view accepted =
"<html>"
"<head><title>Accepted</title></head>"
"<body><h1>202 Accepted</h1></body>"
"</html>";
inline std::string_view no_content =
"<html>"
"<head><title>No Content</title></head>"
"<body><h1>204 Content</h1></body>"
"</html>";
inline std::string_view multiple_choices =
"<html>"
"<head><title>Multiple Choices</title></head>"
"<body><h1>300 Multiple Choices</h1></body>"
"</html>";
inline std::string_view moved_permanently =
"<html>"
"<head><title>Moved Permanently</title></head>"
"<body><h1>301 Moved Permanently</h1></body>"
"</html>";
inline std::string_view moved_temporarily =
"<html>"
"<head><title>Moved Temporarily</title></head>"
"<body><h1>302 Moved Temporarily</h1></body>"
"</html>";
inline std::string_view not_modified =
"<html>"
"<head><title>Not Modified</title></head>"
"<body><h1>304 Not Modified</h1></body>"
"</html>";
inline std::string_view bad_request =
"<html>"
"<head><title>Bad Request</title></head>"
"<body><h1>400 Bad Request</h1></body>"
"</html>";
inline std::string_view unauthorized =
"<html>"
"<head><title>Unauthorized</title></head>"
"<body><h1>401 Unauthorized</h1></body>"
"</html>";
inline std::string_view forbidden =
"<html>"
"<head><title>Forbidden</title></head>"
"<body><h1>403 Forbidden</h1></body>"
"</html>";
inline std::string_view not_found =
"<html>"
"<head><title>Not Found</title></head>"
"<body><h1>404 Not Found</h1></body>"
"</html>";
inline std::string_view internal_server_error =
"<html>"
"<head><title>Internal Server Error</title></head>"
"<body><h1>500 Internal Server Error</h1></body>"
"</html>";
inline std::string_view not_implemented =
"<html>"
"<head><title>Not Implemented</title></head>"
"<body><h1>501 Not Implemented</h1></body>"
"</html>";
inline std::string_view bad_gateway =
"<html>"
"<head><title>Bad Gateway</title></head>"
"<body><h1>502 Bad Gateway</h1></body>"
"</html>";
inline std::string_view service_unavailable =
"<html>"
"<head><title>Service Unavailable</title></head>"
"<body><h1>503 Service Unavailable</h1></body>"
"</html>";
inline std::string_view switching_protocols = "HTTP/1.1 101 Switching Protocals\r\n";
inline std::string_view rep_ok = "HTTP/1.1 200 OK\r\n";
inline std::string_view rep_created = "HTTP/1.1 201 Created\r\n";
inline std::string_view rep_accepted = "HTTP/1.1 202 Accepted\r\n";
inline std::string_view rep_no_content = "HTTP/1.1 204 No Content\r\n";
inline std::string_view rep_partial_content = "HTTP/1.1 206 Partial Content\r\n";
inline std::string_view rep_multiple_choices = "HTTP/1.1 300 Multiple Choices\r\n";
inline std::string_view rep_moved_permanently = "HTTP/1.1 301 Moved Permanently\r\n";
inline std::string_view rep_moved_temporarily = "HTTP/1.1 302 Moved Temporarily\r\n";
inline std::string_view rep_not_modified = "HTTP/1.1 304 Not Modified\r\n";
inline std::string_view rep_bad_request = "HTTP/1.1 400 Bad Request\r\n";
inline std::string_view rep_unauthorized = "HTTP/1.1 401 Unauthorized\r\n";
inline std::string_view rep_forbidden = "HTTP/1.1 403 Forbidden\r\n";
inline std::string_view rep_not_found = "HTTP/1.1 404 Not Found\r\n";
inline std::string_view rep_internal_server_error = "HTTP/1.1 500 Internal Server Error\r\n";
inline std::string_view rep_not_implemented = "HTTP/1.1 501 Not Implemented\r\n";
inline std::string_view rep_bad_gateway = "HTTP/1.1 502 Bad Gateway\r\n";
inline std::string_view rep_service_unavailable = "HTTP/1.1 503 Service Unavailable\r\n";
inline const char name_value_separator[] = { ':', ' ' };
//inline std::string_view crlf = "\r\n";
inline const char crlf[] = { '\r', '\n' };
inline const char last_chunk[] = { '0', '\r', '\n' };
inline const std::string http_chunk_header =
"HTTP/1.1 200 OK\r\n"
"Transfer-Encoding: chunked\r\n";
/*"Content-Type: video/mp4\r\n"
"\r\n";*/
inline boost::asio::const_buffer to_buffer(status_type status) {
switch (status) {
case status_type::switching_protocols:
return boost::asio::buffer(switching_protocols.data(), switching_protocols.length());
case status_type::ok:
return boost::asio::buffer(rep_ok.data(), rep_ok.length());
case status_type::created:
return boost::asio::buffer(rep_created.data(), rep_created.length());
case status_type::accepted:
return boost::asio::buffer(rep_accepted.data(), rep_created.length());
case status_type::no_content:
return boost::asio::buffer(rep_no_content.data(), rep_no_content.length());
case status_type::partial_content:
return boost::asio::buffer(rep_partial_content.data(), rep_partial_content.length());
case status_type::multiple_choices:
return boost::asio::buffer(rep_multiple_choices.data(), rep_multiple_choices.length());
case status_type::moved_permanently:
return boost::asio::buffer(rep_moved_permanently.data(), rep_moved_permanently.length());
case status_type::moved_temporarily:
return boost::asio::buffer(rep_moved_temporarily.data(), rep_moved_temporarily.length());
case status_type::not_modified:
return boost::asio::buffer(rep_not_modified.data(), rep_not_modified.length());
case status_type::bad_request:
return boost::asio::buffer(rep_bad_request.data(), rep_bad_request.length());
case status_type::unauthorized:
return boost::asio::buffer(rep_unauthorized.data(), rep_unauthorized.length());
case status_type::forbidden:
return boost::asio::buffer(rep_forbidden.data(), rep_forbidden.length());
case status_type::not_found:
return boost::asio::buffer(rep_not_found.data(), rep_not_found.length());
case status_type::internal_server_error:
return boost::asio::buffer(rep_internal_server_error.data(), rep_internal_server_error.length());
case status_type::not_implemented:
return boost::asio::buffer(rep_not_implemented.data(), rep_not_implemented.length());
case status_type::bad_gateway:
return boost::asio::buffer(rep_bad_gateway.data(), rep_bad_gateway.length());
case status_type::service_unavailable:
return boost::asio::buffer(rep_service_unavailable.data(), rep_service_unavailable.length());
default:
return boost::asio::buffer(rep_internal_server_error.data(), rep_internal_server_error.length());
}
}
inline std::string_view to_string(status_type status) {
switch (status) {
case status_type::ok:
return ok;
case status_type::created:
return created;
case status_type::accepted:
return accepted;
case status_type::no_content:
return no_content;
case status_type::multiple_choices:
return multiple_choices;
case status_type::moved_permanently:
return moved_permanently;
case status_type::moved_temporarily:
return moved_temporarily;
case status_type::not_modified:
return not_modified;
case status_type::bad_request:
return bad_request;
case status_type::unauthorized:
return unauthorized;
case status_type::forbidden:
return forbidden;
case status_type::not_found:
return not_found;
case status_type::internal_server_error:
return internal_server_error;
case status_type::not_implemented:
return not_implemented;
case status_type::bad_gateway:
return bad_gateway;
case status_type::service_unavailable:
return service_unavailable;
default:
return internal_server_error;
}
}
}
| 34.423729 | 100 | 0.714426 |
80cfaf2424afefc32430d5f4d5443d473de4894f | 2,922 | cpp | C++ | generator/opentable_dataset.cpp | ToshUxanoff/omim | a8acb5821c72bd78847d1c49968b14d15b1e06ee | [
"Apache-2.0"
] | 1 | 2019-03-13T08:21:40.000Z | 2019-03-13T08:21:40.000Z | generator/opentable_dataset.cpp | MohammadMoeinfar/omim | 7b7d1990143bc3cbe218ea14b5428d0fc02d78fc | [
"Apache-2.0"
] | null | null | null | generator/opentable_dataset.cpp | MohammadMoeinfar/omim | 7b7d1990143bc3cbe218ea14b5428d0fc02d78fc | [
"Apache-2.0"
] | null | null | null | #include "generator/opentable_dataset.hpp"
#include "generator/feature_builder.hpp"
#include "generator/sponsored_scoring.hpp"
#include "indexer/classificator.hpp"
#include "indexer/ftypes_matcher.hpp"
#include "base/logging.hpp"
#include "base/string_utils.hpp"
#include <iomanip>
#include <iostream>
#include "boost/algorithm/string/replace.hpp"
namespace generator
{
// OpentableRestaurant ------------------------------------------------------------------------------
OpentableRestaurant::OpentableRestaurant(std::string const & src)
{
vector<std::string> rec;
strings::ParseCSVRow(src, '\t', rec);
CHECK_EQUAL(rec.size(), FieldsCount(), ("Error parsing restaurants.tsv line:",
boost::replace_all_copy(src, "\t", "\\t")));
CLOG(LDEBUG, strings::to_uint(rec[FieldIndex(Fields::Id)], m_id.Get()), ());
CLOG(LDEBUG, strings::to_double(rec[FieldIndex(Fields::Latitude)], m_latLon.lat), ());
CLOG(LDEBUG, strings::to_double(rec[FieldIndex(Fields::Longtitude)], m_latLon.lon), ());
m_name = rec[FieldIndex(Fields::Name)];
m_address = rec[FieldIndex(Fields::Address)];
m_descUrl = rec[FieldIndex(Fields::DescUrl)];
}
// OpentableDataset ---------------------------------------------------------------------------------
template <>
bool OpentableDataset::NecessaryMatchingConditionHolds(FeatureBuilder1 const & fb) const
{
if (fb.GetName(StringUtf8Multilang::kDefaultCode).empty())
return false;
return ftypes::IsEatChecker::Instance()(fb.GetTypes());
}
template <>
void OpentableDataset::PreprocessMatchedOsmObject(ObjectId const matchedObjId, FeatureBuilder1 & fb,
function<void(FeatureBuilder1 &)> const fn) const
{
auto const & restaurant = m_storage.GetObjectById(matchedObjId);
auto & metadata = fb.GetMetadata();
metadata.Set(feature::Metadata::FMD_SPONSORED_ID, strings::to_string(restaurant.m_id.Get()));
FeatureParams & params = fb.GetParams();
// params.AddAddress(restaurant.address);
// TODO(mgsergio): addr:full ???
params.AddName(StringUtf8Multilang::GetLangByCode(StringUtf8Multilang::kDefaultCode),
restaurant.m_name);
auto const & clf = classif();
params.AddType(clf.GetTypeByPath({"sponsored", "opentable"}));
fn(fb);
}
template <>
OpentableDataset::ObjectId OpentableDataset::FindMatchingObjectIdImpl(FeatureBuilder1 const & fb) const
{
auto const name = fb.GetName(StringUtf8Multilang::kDefaultCode);
if (name.empty())
return Object::InvalidObjectId();
// Find |kMaxSelectedElements| nearest values to a point.
auto const nearbyIds = m_storage.GetNearestObjects(MercatorBounds::ToLatLon(fb.GetKeyPoint()));
for (auto const objId : nearbyIds)
{
if (sponsored_scoring::Match(m_storage.GetObjectById(objId), fb).IsMatched())
return objId;
}
return Object::InvalidObjectId();
}
} // namespace generator
| 33.586207 | 103 | 0.675565 |
80d0265eea34fb6d29f59358db1b032017bedec2 | 539 | cc | C++ | net/http/http_status_code.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-05-03T06:33:56.000Z | 2021-11-14T18:39:42.000Z | net/http/http_status_code.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | net/http/http_status_code.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/http/http_status_code.h"
#include "base/logging.h"
namespace net {
const char* GetHttpReasonPhrase(HttpStatusCode code) {
switch (code) {
#define HTTP_STATUS(label, code, reason) case HTTP_ ## label: return reason;
#include "net/http/http_status_code_list.h"
#undef HTTP_STATUS
default:
NOTREACHED();
}
return "";
}
} // namespace net
| 20.730769 | 76 | 0.719852 |
80d0dc49bf7c748cde25fa9974b35878fe8d6bde | 10,047 | hpp | C++ | src/3rd party/boost/boost/spirit/debug/debug_node.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 8 | 2016-01-25T20:18:51.000Z | 2019-03-06T07:00:04.000Z | src/3rd party/boost/boost/spirit/debug/debug_node.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | null | null | null | src/3rd party/boost/boost/spirit/debug/debug_node.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 3 | 2016-02-14T01:20:43.000Z | 2021-02-03T11:19:11.000Z | /*=============================================================================
Spirit v1.6.0
Copyright (c) 2001-2003 Joel de Guzman
Copyright (c) 2002-2003 Hartmut Kaiser
Copyright (c) 2003 Gustavo Guerra
http://spirit.sourceforge.net/
Permission to copy, use, modify, sell and distribute this software is
granted provided this copyright notice appears in all copies. This
software is provided "as is" without express or implied warranty, and
with no claim as to its suitability for any purpose.
=============================================================================*/
#if !defined(BOOST_SPIRIT_DEBUG_NODE_HPP)
#define BOOST_SPIRIT_DEBUG_NODE_HPP
#if !defined(BOOST_SPIRIT_DEBUG_MAIN_HPP)
#error "You must include boost/spirit/debug.hpp, not boost/spirit/debug/debug_node.hpp"
#endif
#if defined(BOOST_SPIRIT_DEBUG)
#include <string>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/and.hpp>
#include <boost/spirit/core/primitives/primitives.hpp> // for iscntrl_
namespace boost { namespace spirit {
///////////////////////////////////////////////////////////////////////////////
//
// Debug helper classes for rules, which ensure maximum non-intrusiveness of
// the Spirit debug support
//
///////////////////////////////////////////////////////////////////////////////
namespace impl {
struct token_printer_aux_for_chars
{
template<typename CharT>
static void print(CharT c)
{
if (c == static_cast<CharT>('\a'))
BOOST_SPIRIT_DEBUG_OUT << "\\a";
else if (c == static_cast<CharT>('\b'))
BOOST_SPIRIT_DEBUG_OUT << "\\b";
else if (c == static_cast<CharT>('\f'))
BOOST_SPIRIT_DEBUG_OUT << "\\f";
else if (c == static_cast<CharT>('\n'))
BOOST_SPIRIT_DEBUG_OUT << "\\n";
else if (c == static_cast<CharT>('\r'))
BOOST_SPIRIT_DEBUG_OUT << "\\r";
else if (c == static_cast<CharT>('\t'))
BOOST_SPIRIT_DEBUG_OUT << "\\t";
else if (c == static_cast<CharT>('\v'))
BOOST_SPIRIT_DEBUG_OUT << "\\v";
else if (iscntrl_(c))
BOOST_SPIRIT_DEBUG_OUT << "\\" << static_cast<int>(c);
else
BOOST_SPIRIT_DEBUG_OUT << static_cast<char>(c);
}
};
// for token types where the comparison with char constants wouldn't work
struct token_printer_aux_for_other_types
{
template<typename CharT>
static void print(CharT c)
{
BOOST_SPIRIT_DEBUG_OUT << c;
}
};
template <typename CharT>
struct token_printer_aux
: mpl::if_<
mpl::and_<
is_convertible<CharT, char>,
is_convertible<char, CharT> >,
token_printer_aux_for_chars,
token_printer_aux_for_other_types
>::type
{
};
template<typename CharT>
inline void token_printer(CharT c)
{
#if !defined(BOOST_SPIRIT_DEBUG_TOKEN_PRINTER)
token_printer_aux<CharT>::print(c);
#else
BOOST_SPIRIT_DEBUG_TOKEN_PRINTER(BOOST_SPIRIT_DEBUG_OUT, c);
#endif
}
///////////////////////////////////////////////////////////////////////////////
//
// Dump infos about the parsing state of a rule
//
///////////////////////////////////////////////////////////////////////////////
#if BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_NODES
template <typename IteratorT>
inline void
print_node_info(bool hit, int level, bool close, std::string const& name,
IteratorT first, IteratorT last)
{
if (!name.empty())
{
for (int i = 0; i < level; ++i)
BOOST_SPIRIT_DEBUG_OUT << " ";
if (close)
{
if (hit)
BOOST_SPIRIT_DEBUG_OUT << "/";
else
BOOST_SPIRIT_DEBUG_OUT << "#";
}
BOOST_SPIRIT_DEBUG_OUT << name << ":\t\"";
IteratorT iter = first;
IteratorT ilast = last;
for (int j = 0; j < BOOST_SPIRIT_DEBUG_PRINT_SOME; ++j)
{
if (iter == ilast)
break;
token_printer(*iter);
++iter;
}
BOOST_SPIRIT_DEBUG_OUT << "\"\n";
}
}
#endif // BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_NODES
#if BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_CLOSURES
template <typename ResultT>
inline ResultT &
print_closure_info(ResultT &hit, int level, std::string const& name)
{
if (!name.empty()) {
for (int i = 0; i < level-1; ++i)
BOOST_SPIRIT_DEBUG_OUT << " ";
// for now, print out the return value only
BOOST_SPIRIT_DEBUG_OUT
<< "^" << name << ":\t" << hit.value() << "\n";
}
return hit;
}
#endif // BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_CLOSURES
}
///////////////////////////////////////////////////////////////////////////////
//
// Implementation note: The parser_context_linker, parser_scanner_linker and
// closure_context_linker classes are wrapped by a PP constant to allow
// redefinition of this classes outside of Spirit
//
///////////////////////////////////////////////////////////////////////////////
#if !defined(BOOST_SPIRIT_PARSER_CONTEXT_LINKER_DEFINED)
#define BOOST_SPIRIT_PARSER_CONTEXT_LINKER_DEFINED
///////////////////////////////////////////////////////////////////////////
//
// parser_context_linker is a debug wrapper for the ContextT template
// parameter of the rule<>, subrule<> and the grammar<> classes
//
///////////////////////////////////////////////////////////////////////////
template<typename ContextT>
struct parser_context_linker : public ContextT
{
typedef ContextT base_t;
template <typename ParserT>
parser_context_linker(ParserT const& p)
: ContextT(p) {}
template <typename ParserT, typename ScannerT>
void pre_parse(ParserT const& p, ScannerT &scan)
{
this->base_t::pre_parse(p, scan);
#if BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_NODES
if (trace_parser(p)) {
impl::print_node_info(
false,
scan.get_level(),
false,
parser_name(p),
scan.first,
scan.last);
}
scan.get_level()++;
#endif // BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_NODES
}
template <typename ResultT, typename ParserT, typename ScannerT>
ResultT& post_parse(ResultT& hit, ParserT const& p, ScannerT &scan)
{
#if BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_NODES
--scan.get_level();
if (trace_parser(p)) {
impl::print_node_info(
hit,
scan.get_level(),
true,
parser_name(p),
scan.first,
scan.last);
}
#endif // BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_NODES
return this->base_t::post_parse(hit, p, scan);
}
};
#endif // !defined(BOOST_SPIRIT_PARSER_CONTEXT_LINKER_DEFINED)
#if !defined(BOOST_SPIRIT_PARSER_SCANNER_LINKER_DEFINED)
#define BOOST_SPIRIT_PARSER_SCANNER_LINKER_DEFINED
///////////////////////////////////////////////////////////////////////////////
// This class is to avoid linker problems and to ensure a real singleton
// 'level' variable
struct debug_support
{
int& get_level()
{
static int level = 0;
return level;
}
};
template<typename ScannerT>
struct parser_scanner_linker : public ScannerT
{
parser_scanner_linker(ScannerT const &scan_) : ScannerT(scan_)
{}
int &get_level()
{ return debug.get_level(); }
private: debug_support debug;
};
#endif // !defined(BOOST_SPIRIT_PARSER_SCANNER_LINKER_DEFINED)
#if !defined(BOOST_SPIRIT_CLOSURE_CONTEXT_LINKER_DEFINED)
#define BOOST_SPIRIT_CLOSURE_CONTEXT_LINKER_DEFINED
///////////////////////////////////////////////////////////////////////////
//
// closure_context_linker is a debug wrapper for the closure template
// parameter of the rule<>, subrule<> and grammar classes
//
///////////////////////////////////////////////////////////////////////////
template<typename ContextT>
struct closure_context_linker : public parser_context_linker<ContextT>
{
typedef parser_context_linker<ContextT> base_t;
template <typename ParserT>
closure_context_linker(ParserT const& p)
: parser_context_linker<ContextT>(p) {}
template <typename ParserT, typename ScannerT>
void pre_parse(ParserT const& p, ScannerT &scan)
{ this->base_t::pre_parse(p, scan); }
template <typename ResultT, typename ParserT, typename ScannerT>
ResultT&
post_parse(ResultT& hit, ParserT const& p, ScannerT &scan)
{
#if BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_CLOSURES
if (hit && trace_parser(p)) {
// for now, print out the return value only
return impl::print_closure_info(
this->base_t::post_parse(hit, p, scan),
scan.get_level(),
parser_name(p)
);
}
#endif // BOOST_SPIRIT_DEBUG_FLAGS & BOOST_SPIRIT_DEBUG_FLAGS_CLOSURES
return this->base_t::post_parse(hit, p, scan);
}
};
#endif // !defined(BOOST_SPIRIT_CLOSURE_CONTEXT_LINKER_DEFINED)
}} // namespace boost::spirit
#endif // defined(BOOST_SPIRIT_DEBUG)
#endif // !defined(BOOST_SPIRIT_DEBUG_NODE_HPP)
| 32.099042 | 87 | 0.542052 |
80d1daf65975d4ba1be7f6e8b285cceed09f71e9 | 1,605 | cpp | C++ | logger.cpp | chenyoujie/GeoDa | 87504344512bd0da2ccadfb160ecd1e918a52f06 | [
"BSL-1.0"
] | null | null | null | logger.cpp | chenyoujie/GeoDa | 87504344512bd0da2ccadfb160ecd1e918a52f06 | [
"BSL-1.0"
] | null | null | null | logger.cpp | chenyoujie/GeoDa | 87504344512bd0da2ccadfb160ecd1e918a52f06 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2005, 2006
// Seweryn Habdank-Wojewodzki
// Distributed under the Boost Software License,
// Version 1.0.
// (copy at http://www.boost.org/LICENSE_1_0.txt)
#include "logger.h"
#if !defined(CLEANLOG)
#define FTLOG
#if !defined(DEBUG)
#undef FTLOG
#undef TLOG
#endif
//#if defined (FTLOG)
//#include <fstream>
//#else
#include <iostream>
// http://www.msobczak.com/prog/bin/nullstream.zip
#include "nullstream.h"
//#endif
logger_t::logger_t()
{}
bool logger_t::is_activated = true;
#if defined(TLOG)
std::auto_ptr<std::ostream> logger_t::outstream_helper_ptr
= std::auto_ptr<std::ostream>( new NullStream );
std::ostream * logger_t::outstream = &std::cout;
#elif defined (ETLOG)
std::auto_ptr<std::ostream> logger_t::outstream_helper_ptr
= std::auto_ptr <std::ostream>( new NullStream );
std::ostream * logger_t::outstream = &std::cerr;
#elif defined (FTLOG)
//std::auto_ptr <std::ostream> logger_t::outstream_helper_ptr
//= std::auto_ptr<std::ostream>( new std::ofstream ("oldlogger.txt"));
//std::ostream * logger_t::outstream = outstream_helper_ptr.get();
std::auto_ptr<std::ostream> logger_t::outstream_helper_ptr
= std::auto_ptr <std::ostream>( new NullStream );
std::ostream * logger_t::outstream = &std::cout;
// here is a place for user defined output stream
// and compiler flag
#else
std::auto_ptr<std::ostream> logger_t::outstream_helper_ptr
= std::auto_ptr<std::ostream>( new NullStream );
std::ostream* logger_t::outstream = outstream_helper_ptr.get();
#endif
logger_t & logger()
{
static logger_t* ans = new logger_t();
return *ans;
}
#endif
// !CLEANLOG
| 24.692308 | 70 | 0.721495 |
80d25aae65572a296eec5063154ff3838cf4b360 | 7,058 | cpp | C++ | shared/test/unit_test/helpers/bit_helpers_tests.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 778 | 2017-09-29T20:02:43.000Z | 2022-03-31T15:35:28.000Z | shared/test/unit_test/helpers/bit_helpers_tests.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 478 | 2018-01-26T16:06:45.000Z | 2022-03-30T10:19:10.000Z | shared/test/unit_test/helpers/bit_helpers_tests.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 215 | 2018-01-30T08:39:32.000Z | 2022-03-29T11:08:51.000Z | /*
* Copyright (C) 2019-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/helpers/bit_helpers.h"
#include "gtest/gtest.h"
using namespace NEO;
TEST(IsBitSetTests, givenDifferentValuesWhenTestingIsBitSetThenCorrectValueIsReturned) {
size_t field1 = 0;
size_t field2 = 0b1;
size_t field3 = 0b1000;
size_t field4 = 0b1010;
EXPECT_FALSE(isBitSet(field1, 0));
EXPECT_FALSE(isBitSet(field1, 1));
EXPECT_FALSE(isBitSet(field1, 2));
EXPECT_FALSE(isBitSet(field1, 3));
EXPECT_TRUE(isBitSet(field2, 0));
EXPECT_FALSE(isBitSet(field2, 1));
EXPECT_FALSE(isBitSet(field2, 2));
EXPECT_FALSE(isBitSet(field2, 3));
EXPECT_FALSE(isBitSet(field3, 0));
EXPECT_FALSE(isBitSet(field3, 1));
EXPECT_FALSE(isBitSet(field3, 2));
EXPECT_TRUE(isBitSet(field3, 3));
EXPECT_FALSE(isBitSet(field4, 0));
EXPECT_TRUE(isBitSet(field4, 1));
EXPECT_FALSE(isBitSet(field4, 2));
EXPECT_TRUE(isBitSet(field4, 3));
}
TEST(IsAnyBitSetTests, givenDifferentValuesWhenTestingIsAnyBitSetThenCorrectValueIsReturned) {
EXPECT_FALSE(isAnyBitSet(0, 0));
EXPECT_FALSE(isAnyBitSet(0, 0b1));
EXPECT_FALSE(isAnyBitSet(0, 0b10));
EXPECT_FALSE(isAnyBitSet(0, 0b1000));
EXPECT_FALSE(isAnyBitSet(0, 0b1010));
EXPECT_FALSE(isAnyBitSet(0, 0b1111));
EXPECT_FALSE(isAnyBitSet(0b1, 0));
EXPECT_TRUE(isAnyBitSet(0b1, 0b1));
EXPECT_FALSE(isAnyBitSet(0b1, 0b10));
EXPECT_FALSE(isAnyBitSet(0b1, 0b1000));
EXPECT_FALSE(isAnyBitSet(0b1, 0b1010));
EXPECT_TRUE(isAnyBitSet(0b1, 0b1111));
EXPECT_FALSE(isAnyBitSet(0b10, 0));
EXPECT_FALSE(isAnyBitSet(0b10, 0b1));
EXPECT_TRUE(isAnyBitSet(0b10, 0b10));
EXPECT_FALSE(isAnyBitSet(0b10, 0b1000));
EXPECT_TRUE(isAnyBitSet(0b10, 0b1010));
EXPECT_TRUE(isAnyBitSet(0b10, 0b1111));
EXPECT_FALSE(isAnyBitSet(0b1000, 0));
EXPECT_FALSE(isAnyBitSet(0b1000, 0b1));
EXPECT_FALSE(isAnyBitSet(0b1000, 0b10));
EXPECT_TRUE(isAnyBitSet(0b1000, 0b1000));
EXPECT_TRUE(isAnyBitSet(0b1000, 0b1010));
EXPECT_TRUE(isAnyBitSet(0b1000, 0b1111));
EXPECT_FALSE(isAnyBitSet(0b1010, 0));
EXPECT_FALSE(isAnyBitSet(0b1010, 0b1));
EXPECT_TRUE(isAnyBitSet(0b1010, 0b10));
EXPECT_TRUE(isAnyBitSet(0b1010, 0b1000));
EXPECT_TRUE(isAnyBitSet(0b1010, 0b1010));
EXPECT_TRUE(isAnyBitSet(0b1010, 0b1111));
EXPECT_FALSE(isAnyBitSet(0b1111, 0));
EXPECT_TRUE(isAnyBitSet(0b1111, 0b1));
EXPECT_TRUE(isAnyBitSet(0b1111, 0b10));
EXPECT_TRUE(isAnyBitSet(0b1111, 0b1000));
EXPECT_TRUE(isAnyBitSet(0b1111, 0b1010));
EXPECT_TRUE(isAnyBitSet(0b1111, 0b1111));
}
TEST(IsValueSetTests, givenDifferentValuesWhenTestingIsValueSetThenCorrectValueIsReturned) {
size_t field1 = 0;
size_t field2 = 0b1;
size_t field3 = 0b10;
size_t field4 = 0b1000;
size_t field5 = 0b1010;
size_t field6 = 0b1111;
EXPECT_FALSE(isValueSet(field1, field2));
EXPECT_FALSE(isValueSet(field1, field3));
EXPECT_FALSE(isValueSet(field1, field4));
EXPECT_FALSE(isValueSet(field1, field5));
EXPECT_FALSE(isValueSet(field1, field6));
EXPECT_TRUE(isValueSet(field2, field2));
EXPECT_FALSE(isValueSet(field2, field3));
EXPECT_FALSE(isValueSet(field2, field4));
EXPECT_FALSE(isValueSet(field2, field5));
EXPECT_FALSE(isValueSet(field2, field6));
EXPECT_FALSE(isValueSet(field3, field2));
EXPECT_TRUE(isValueSet(field3, field3));
EXPECT_FALSE(isValueSet(field3, field4));
EXPECT_FALSE(isValueSet(field3, field5));
EXPECT_FALSE(isValueSet(field3, field6));
EXPECT_FALSE(isValueSet(field4, field2));
EXPECT_FALSE(isValueSet(field4, field3));
EXPECT_TRUE(isValueSet(field4, field4));
EXPECT_FALSE(isValueSet(field4, field5));
EXPECT_FALSE(isValueSet(field4, field6));
EXPECT_FALSE(isValueSet(field5, field2));
EXPECT_TRUE(isValueSet(field5, field3));
EXPECT_TRUE(isValueSet(field5, field4));
EXPECT_TRUE(isValueSet(field5, field5));
EXPECT_FALSE(isValueSet(field5, field6));
EXPECT_TRUE(isValueSet(field6, field2));
EXPECT_TRUE(isValueSet(field6, field3));
EXPECT_TRUE(isValueSet(field6, field4));
EXPECT_TRUE(isValueSet(field6, field5));
EXPECT_TRUE(isValueSet(field6, field6));
}
TEST(IsFieldValidTests, givenDifferentValuesWhenTestingIsFieldValidThenCorrectValueIsReturned) {
size_t field1 = 0;
size_t field2 = 0b1;
size_t field3 = 0b10;
size_t field4 = 0b1000;
size_t field5 = 0b1010;
size_t field6 = 0b1111;
EXPECT_TRUE(isFieldValid(field1, field1));
EXPECT_TRUE(isFieldValid(field1, field2));
EXPECT_TRUE(isFieldValid(field1, field3));
EXPECT_TRUE(isFieldValid(field1, field4));
EXPECT_TRUE(isFieldValid(field1, field5));
EXPECT_TRUE(isFieldValid(field1, field6));
EXPECT_FALSE(isFieldValid(field2, field1));
EXPECT_TRUE(isFieldValid(field2, field2));
EXPECT_FALSE(isFieldValid(field2, field3));
EXPECT_FALSE(isFieldValid(field2, field4));
EXPECT_FALSE(isFieldValid(field2, field5));
EXPECT_TRUE(isFieldValid(field2, field6));
EXPECT_FALSE(isFieldValid(field3, field1));
EXPECT_FALSE(isFieldValid(field3, field2));
EXPECT_TRUE(isFieldValid(field3, field3));
EXPECT_FALSE(isFieldValid(field3, field4));
EXPECT_TRUE(isFieldValid(field3, field5));
EXPECT_TRUE(isFieldValid(field3, field6));
EXPECT_FALSE(isFieldValid(field4, field1));
EXPECT_FALSE(isFieldValid(field4, field2));
EXPECT_FALSE(isFieldValid(field4, field3));
EXPECT_TRUE(isFieldValid(field4, field4));
EXPECT_TRUE(isFieldValid(field4, field5));
EXPECT_TRUE(isFieldValid(field4, field6));
EXPECT_FALSE(isFieldValid(field5, field1));
EXPECT_FALSE(isFieldValid(field5, field2));
EXPECT_FALSE(isFieldValid(field5, field3));
EXPECT_FALSE(isFieldValid(field5, field4));
EXPECT_TRUE(isFieldValid(field5, field5));
EXPECT_TRUE(isFieldValid(field5, field6));
EXPECT_FALSE(isFieldValid(field6, field1));
EXPECT_FALSE(isFieldValid(field6, field2));
EXPECT_FALSE(isFieldValid(field6, field3));
EXPECT_FALSE(isFieldValid(field6, field4));
EXPECT_FALSE(isFieldValid(field6, field5));
EXPECT_TRUE(isFieldValid(field6, field6));
}
TEST(SetBitsTests, givenDifferentValuesWhenTestingSetBitsThenCorrectValueIsReturned) {
EXPECT_EQ(0b0u, setBits(0b0, false, 0b0));
EXPECT_EQ(0b0u, setBits(0b0, false, 0b1));
EXPECT_EQ(0b1u, setBits(0b1, false, 0b0));
EXPECT_EQ(0b0u, setBits(0b1, false, 0b1));
EXPECT_EQ(0b0u, setBits(0b0, true, 0b0));
EXPECT_EQ(0b1u, setBits(0b0, true, 0b1));
EXPECT_EQ(0b1u, setBits(0b1, true, 0b0));
EXPECT_EQ(0b1u, setBits(0b1, true, 0b1));
EXPECT_EQ(0b1010u, setBits(0b1010, false, 0b101));
EXPECT_EQ(0b1111u, setBits(0b1010, true, 0b101));
EXPECT_EQ(0b101u, setBits(0b101, false, 0b1010));
EXPECT_EQ(0b1111u, setBits(0b101, true, 0b1010));
EXPECT_EQ(0b0u, setBits(0b1010, false, 0b1010));
EXPECT_EQ(0b1010u, setBits(0b1010, true, 0b1010));
}
| 35.29 | 96 | 0.726693 |
80d44a51c750cbd6805e532bfbf036a23be0346d | 4,283 | cpp | C++ | src/qt/qtbase/tests/manual/gestures/graphicsview/gestures.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | src/qt/qtbase/tests/manual/gestures/graphicsview/gestures.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/tests/manual/gestures/graphicsview/gestures.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "gestures.h"
#include <QTouchEvent>
Qt::GestureType ThreeFingerSlideGesture::Type = Qt::CustomGesture;
QGesture *ThreeFingerSlideGestureRecognizer::create(QObject *)
{
return new ThreeFingerSlideGesture;
}
QGestureRecognizer::Result ThreeFingerSlideGestureRecognizer::recognize(QGesture *state, QObject *, QEvent *event)
{
ThreeFingerSlideGesture *d = static_cast<ThreeFingerSlideGesture *>(state);
QGestureRecognizer::Result result;
switch (event->type()) {
case QEvent::TouchBegin:
result = QGestureRecognizer::MayBeGesture;
case QEvent::TouchEnd:
if (d->gestureFired)
result = QGestureRecognizer::FinishGesture;
else
result = QGestureRecognizer::CancelGesture;
case QEvent::TouchUpdate:
if (d->state() != Qt::NoGesture) {
QTouchEvent *ev = static_cast<QTouchEvent*>(event);
if (ev->touchPoints().size() == 3) {
d->gestureFired = true;
result = QGestureRecognizer::TriggerGesture;
} else {
result = QGestureRecognizer::MayBeGesture;
for (int i = 0; i < ev->touchPoints().size(); ++i) {
const QTouchEvent::TouchPoint &pt = ev->touchPoints().at(i);
const int distance = (pt.pos().toPoint() - pt.startPos().toPoint()).manhattanLength();
if (distance > 20) {
result = QGestureRecognizer::CancelGesture;
}
}
}
} else {
result = QGestureRecognizer::CancelGesture;
}
break;
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseMove:
if (d->state() != Qt::NoGesture)
result = QGestureRecognizer::Ignore;
else
result = QGestureRecognizer::CancelGesture;
break;
default:
result = QGestureRecognizer::Ignore;
break;
}
return result;
}
void ThreeFingerSlideGestureRecognizer::reset(QGesture *state)
{
static_cast<ThreeFingerSlideGesture *>(state)->gestureFired = false;
QGestureRecognizer::reset(state);
}
QGesture *RotateGestureRecognizer::create(QObject *)
{
return new QGesture;
}
QGestureRecognizer::Result RotateGestureRecognizer::recognize(QGesture *, QObject *, QEvent *event)
{
switch (event->type()) {
case QEvent::TouchBegin:
case QEvent::TouchEnd:
case QEvent::TouchUpdate:
break;
default:
break;
}
return QGestureRecognizer::Ignore;
}
void RotateGestureRecognizer::reset(QGesture *state)
{
QGestureRecognizer::reset(state);
}
#include "moc_gestures.cpp"
| 34.540323 | 114 | 0.646276 |
80d62f7474f6918680b328a909d7424fc487703b | 47,022 | cxx | C++ | swig-2.0.4/Source/Modules/chicken.cxx | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | swig-2.0.4/Source/Modules/chicken.cxx | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | swig-2.0.4/Source/Modules/chicken.cxx | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | /* -----------------------------------------------------------------------------
* This file is part of SWIG, which is licensed as a whole under version 3
* (or any later version) of the GNU General Public License. Some additional
* terms also apply to certain portions of SWIG. The full details of the SWIG
* license and copyrights can be found in the LICENSE and COPYRIGHT files
* included with the SWIG source code as distributed by the SWIG developers
* and at http://www.swig.org/legal.html.
*
* chicken.cxx
*
* CHICKEN language module for SWIG.
* ----------------------------------------------------------------------------- */
char cvsroot_chicken_cxx[] = "$Id: chicken.cxx 12558 2011-03-26 23:25:14Z wsfulton $";
#include "swigmod.h"
#include <ctype.h>
static const char *usage = (char *) "\
\
CHICKEN Options (available with -chicken)\n\
-closprefix <prefix> - Prepend <prefix> to all clos identifiers\n\
-noclosuses - Do not (declare (uses ...)) in scheme file\n\
-nocollection - Do not register pointers with chicken garbage\n\
collector and export destructors\n\
-nounit - Do not (declare (unit ...)) in scheme file\n\
-proxy - Export TinyCLOS class definitions\n\
-unhideprimitive - Unhide the primitive: symbols\n\
-useclassprefix - Prepend the class name to all clos identifiers\n\
\n";
static char *module = 0;
static char *chicken_path = (char *) "chicken";
static int num_methods = 0;
static File *f_begin = 0;
static File *f_runtime = 0;
static File *f_header = 0;
static File *f_wrappers = 0;
static File *f_init = 0;
static String *chickentext = 0;
static String *closprefix = 0;
static String *swigtype_ptr = 0;
static String *f_sym_size = 0;
/* some options */
static int declare_unit = 1;
static int no_collection = 0;
static int clos_uses = 1;
/* C++ Support + Clos Classes */
static int clos = 0;
static String *c_class_name = 0;
static String *class_name = 0;
static String *short_class_name = 0;
static int in_class = 0;
static int have_constructor = 0;
static bool exporting_destructor = false;
static bool exporting_constructor = false;
static String *constructor_name = 0;
static String *member_name = 0;
/* sections of the .scm code */
static String *scm_const_defs = 0;
static String *clos_class_defines = 0;
static String *clos_methods = 0;
/* Some clos options */
static int useclassprefix = 0;
static String *clossymnameprefix = 0;
static int hide_primitive = 1;
static Hash *primitive_names = 0;
/* Used for overloading constructors */
static int has_constructor_args = 0;
static List *constructor_arg_types = 0;
static String *constructor_dispatch = 0;
static Hash *overload_parameter_lists = 0;
class CHICKEN:public Language {
public:
virtual void main(int argc, char *argv[]);
virtual int top(Node *n);
virtual int functionWrapper(Node *n);
virtual int variableWrapper(Node *n);
virtual int constantWrapper(Node *n);
virtual int classHandler(Node *n);
virtual int memberfunctionHandler(Node *n);
virtual int membervariableHandler(Node *n);
virtual int constructorHandler(Node *n);
virtual int destructorHandler(Node *n);
virtual int validIdentifier(String *s);
virtual int staticmembervariableHandler(Node *n);
virtual int staticmemberfunctionHandler(Node *n);
virtual int importDirective(Node *n);
protected:
void addMethod(String *scheme_name, String *function);
/* Return true iff T is a pointer type */
int isPointer(SwigType *t);
void dispatchFunction(Node *n);
String *chickenNameMapping(String *, const_String_or_char_ptr );
String *chickenPrimitiveName(String *);
String *runtimeCode();
String *defaultExternalRuntimeFilename();
String *buildClosFunctionCall(List *types, const_String_or_char_ptr closname, const_String_or_char_ptr funcname);
};
/* -----------------------------------------------------------------------
* swig_chicken() - Instantiate module
* ----------------------------------------------------------------------- */
static Language *new_swig_chicken() {
return new CHICKEN();
}
extern "C" {
Language *swig_chicken(void) {
return new_swig_chicken();
}
}
void CHICKEN::main(int argc, char *argv[]) {
int i;
SWIG_library_directory(chicken_path);
// Look for certain command line options
for (i = 1; i < argc; i++) {
if (argv[i]) {
if (strcmp(argv[i], "-help") == 0) {
fputs(usage, stdout);
SWIG_exit(0);
} else if (strcmp(argv[i], "-proxy") == 0) {
clos = 1;
Swig_mark_arg(i);
} else if (strcmp(argv[i], "-closprefix") == 0) {
if (argv[i + 1]) {
clossymnameprefix = NewString(argv[i + 1]);
Swig_mark_arg(i);
Swig_mark_arg(i + 1);
i++;
} else {
Swig_arg_error();
}
} else if (strcmp(argv[i], "-useclassprefix") == 0) {
useclassprefix = 1;
Swig_mark_arg(i);
} else if (strcmp(argv[i], "-unhideprimitive") == 0) {
hide_primitive = 0;
Swig_mark_arg(i);
} else if (strcmp(argv[i], "-nounit") == 0) {
declare_unit = 0;
Swig_mark_arg(i);
} else if (strcmp(argv[i], "-noclosuses") == 0) {
clos_uses = 0;
Swig_mark_arg(i);
} else if (strcmp(argv[i], "-nocollection") == 0) {
no_collection = 1;
Swig_mark_arg(i);
}
}
}
if (!clos)
hide_primitive = 0;
// Add a symbol for this module
Preprocessor_define("SWIGCHICKEN 1", 0);
// Set name of typemaps
SWIG_typemap_lang("chicken");
// Read in default typemaps */
SWIG_config_file("chicken.swg");
allow_overloading();
}
int CHICKEN::top(Node *n) {
String *chicken_filename = NewString("");
File *f_scm;
String *scmmodule;
/* Initialize all of the output files */
String *outfile = Getattr(n, "outfile");
f_begin = NewFile(outfile, "w", SWIG_output_files());
if (!f_begin) {
FileErrorDisplay(outfile);
SWIG_exit(EXIT_FAILURE);
}
f_runtime = NewString("");
f_init = NewString("");
f_header = NewString("");
f_wrappers = NewString("");
chickentext = NewString("");
closprefix = NewString("");
f_sym_size = NewString("");
primitive_names = NewHash();
overload_parameter_lists = NewHash();
/* Register file targets with the SWIG file handler */
Swig_register_filebyname("header", f_header);
Swig_register_filebyname("wrapper", f_wrappers);
Swig_register_filebyname("begin", f_begin);
Swig_register_filebyname("runtime", f_runtime);
Swig_register_filebyname("init", f_init);
Swig_register_filebyname("chicken", chickentext);
Swig_register_filebyname("closprefix", closprefix);
clos_class_defines = NewString("");
clos_methods = NewString("");
scm_const_defs = NewString("");
Swig_banner(f_begin);
Printf(f_runtime, "\n");
Printf(f_runtime, "#define SWIGCHICKEN\n");
if (no_collection)
Printf(f_runtime, "#define SWIG_CHICKEN_NO_COLLECTION 1\n");
Printf(f_runtime, "\n");
/* Set module name */
module = Swig_copy_string(Char(Getattr(n, "name")));
scmmodule = NewString(module);
Replaceall(scmmodule, "_", "-");
Printf(f_header, "#define SWIG_init swig_%s_init\n", module);
Printf(f_header, "#define SWIG_name \"%s\"\n", scmmodule);
Printf(f_wrappers, "#ifdef __cplusplus\n");
Printf(f_wrappers, "extern \"C\" {\n");
Printf(f_wrappers, "#endif\n\n");
Language::top(n);
SwigType_emit_type_table(f_runtime, f_wrappers);
Printf(f_wrappers, "#ifdef __cplusplus\n");
Printf(f_wrappers, "}\n");
Printf(f_wrappers, "#endif\n");
Printf(f_init, "C_kontinue (continuation, ret);\n");
Printf(f_init, "}\n\n");
Printf(f_init, "#ifdef __cplusplus\n");
Printf(f_init, "}\n");
Printf(f_init, "#endif\n");
Printf(chicken_filename, "%s%s.scm", SWIG_output_directory(), module);
if ((f_scm = NewFile(chicken_filename, "w", SWIG_output_files())) == 0) {
FileErrorDisplay(chicken_filename);
SWIG_exit(EXIT_FAILURE);
}
Swig_banner_target_lang(f_scm, ";;");
Printf(f_scm, "\n");
if (declare_unit)
Printv(f_scm, "(declare (unit ", scmmodule, "))\n\n", NIL);
Printv(f_scm, "(declare \n",
tab4, "(hide swig-init swig-init-return)\n",
tab4, "(foreign-declare \"C_extern void swig_", module, "_init(C_word,C_word,C_word) C_noret;\"))\n", NIL);
Printv(f_scm, "(define swig-init (##core#primitive \"swig_", module, "_init\"))\n", NIL);
Printv(f_scm, "(define swig-init-return (swig-init))\n\n", NIL);
if (clos) {
//Printf (f_scm, "(declare (uses tinyclos))\n");
//New chicken versions have tinyclos as an egg
Printf(f_scm, "(require-extension tinyclos)\n");
Replaceall(closprefix, "$module", scmmodule);
Printf(f_scm, "%s\n", closprefix);
Printf(f_scm, "%s\n", clos_class_defines);
Printf(f_scm, "%s\n", clos_methods);
} else {
Printf(f_scm, "%s\n", scm_const_defs);
}
Printf(f_scm, "%s\n", chickentext);
Close(f_scm);
Delete(f_scm);
char buftmp[20];
sprintf(buftmp, "%d", num_methods);
Replaceall(f_init, "$nummethods", buftmp);
Replaceall(f_init, "$symsize", f_sym_size);
if (hide_primitive)
Replaceall(f_init, "$veclength", buftmp);
else
Replaceall(f_init, "$veclength", "0");
Delete(chicken_filename);
Delete(chickentext);
Delete(closprefix);
Delete(overload_parameter_lists);
Delete(clos_class_defines);
Delete(clos_methods);
Delete(scm_const_defs);
/* Close all of the files */
Delete(primitive_names);
Delete(scmmodule);
Dump(f_runtime, f_begin);
Dump(f_header, f_begin);
Dump(f_wrappers, f_begin);
Wrapper_pretty_print(f_init, f_begin);
Delete(f_header);
Delete(f_wrappers);
Delete(f_sym_size);
Delete(f_init);
Close(f_begin);
Delete(f_runtime);
Delete(f_begin);
return SWIG_OK;
}
int CHICKEN::functionWrapper(Node *n) {
String *name = Getattr(n, "name");
String *iname = Getattr(n, "sym:name");
SwigType *d = Getattr(n, "type");
ParmList *l = Getattr(n, "parms");
Parm *p;
int i;
String *wname;
Wrapper *f;
String *mangle = NewString("");
String *get_pointers;
String *cleanup;
String *argout;
String *tm;
String *overname = 0;
String *declfunc = 0;
String *scmname;
bool any_specialized_arg = false;
List *function_arg_types = NewList();
int num_required;
int num_arguments;
int have_argout;
Printf(mangle, "\"%s\"", SwigType_manglestr(d));
if (Getattr(n, "sym:overloaded")) {
overname = Getattr(n, "sym:overname");
} else {
if (!addSymbol(iname, n))
return SWIG_ERROR;
}
f = NewWrapper();
wname = NewString("");
get_pointers = NewString("");
cleanup = NewString("");
argout = NewString("");
declfunc = NewString("");
scmname = NewString(iname);
Replaceall(scmname, "_", "-");
/* Local vars */
Wrapper_add_local(f, "resultobj", "C_word resultobj");
/* Write code to extract function parameters. */
emit_parameter_variables(l, f);
/* Attach the standard typemaps */
emit_attach_parmmaps(l, f);
Setattr(n, "wrap:parms", l);
/* Get number of required and total arguments */
num_arguments = emit_num_arguments(l);
num_required = emit_num_required(l);
Append(wname, Swig_name_wrapper(iname));
if (overname) {
Append(wname, overname);
}
// Check for interrupts
Printv(f->code, "C_trace(\"", scmname, "\");\n", NIL);
Printv(f->def, "static ", "void ", wname, " (C_word argc, C_word closure, C_word continuation", NIL);
Printv(declfunc, "void ", wname, "(C_word,C_word,C_word", NIL);
/* Generate code for argument marshalling */
for (i = 0, p = l; i < num_arguments; i++) {
while (checkAttribute(p, "tmap:in:numinputs", "0")) {
p = Getattr(p, "tmap:in:next");
}
SwigType *pt = Getattr(p, "type");
String *ln = Getattr(p, "lname");
Printf(f->def, ", C_word scm%d", i + 1);
Printf(declfunc, ",C_word");
/* Look for an input typemap */
if ((tm = Getattr(p, "tmap:in"))) {
String *parse = Getattr(p, "tmap:in:parse");
if (!parse) {
String *source = NewStringf("scm%d", i + 1);
Replaceall(tm, "$source", source);
Replaceall(tm, "$target", ln);
Replaceall(tm, "$input", source);
Setattr(p, "emit:input", source); /* Save the location of
the object */
if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
} else {
Replaceall(tm, "$disown", "0");
}
if (i >= num_required)
Printf(get_pointers, "if (argc-2>%i && (%s)) {\n", i, source);
Printv(get_pointers, tm, "\n", NIL);
if (i >= num_required)
Printv(get_pointers, "}\n", NIL);
if (clos) {
if (i < num_required) {
if (strcmp("void", Char(pt)) != 0) {
Node *class_node = 0;
String *clos_code = Getattr(p, "tmap:in:closcode");
class_node = classLookup(pt);
if (clos_code && class_node) {
String *class_name = NewStringf("<%s>", Getattr(class_node, "sym:name"));
Replaceall(class_name, "_", "-");
Append(function_arg_types, class_name);
Append(function_arg_types, Copy(clos_code));
any_specialized_arg = true;
Delete(class_name);
} else {
Append(function_arg_types, "<top>");
Append(function_arg_types, "$input");
}
}
}
}
Delete(source);
}
p = Getattr(p, "tmap:in:next");
continue;
} else {
Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
break;
}
}
/* finish argument marshalling */
Printf(f->def, ") {");
Printf(declfunc, ")");
if (num_required != num_arguments) {
Append(function_arg_types, "^^##optional$$");
}
/* First check the number of arguments is correct */
if (num_arguments != num_required)
Printf(f->code, "if (argc-2<%i || argc-2>%i) C_bad_argc(argc,%i);\n", num_required, num_arguments, num_required + 2);
else
Printf(f->code, "if (argc!=%i) C_bad_argc(argc,%i);\n", num_arguments + 2, num_arguments + 2);
/* Now piece together the first part of the wrapper function */
Printv(f->code, get_pointers, NIL);
/* Insert constraint checking code */
for (p = l; p;) {
if ((tm = Getattr(p, "tmap:check"))) {
Replaceall(tm, "$target", Getattr(p, "lname"));
Printv(f->code, tm, "\n", NIL);
p = Getattr(p, "tmap:check:next");
} else {
p = nextSibling(p);
}
}
/* Insert cleanup code */
for (p = l; p;) {
if ((tm = Getattr(p, "tmap:freearg"))) {
Replaceall(tm, "$source", Getattr(p, "lname"));
Printv(cleanup, tm, "\n", NIL);
p = Getattr(p, "tmap:freearg:next");
} else {
p = nextSibling(p);
}
}
/* Insert argument output code */
have_argout = 0;
for (p = l; p;) {
if ((tm = Getattr(p, "tmap:argout"))) {
if (!have_argout) {
have_argout = 1;
// Print initial argument output code
Printf(argout, "SWIG_Chicken_SetupArgout\n");
}
Replaceall(tm, "$source", Getattr(p, "lname"));
Replaceall(tm, "$target", "resultobj");
Replaceall(tm, "$arg", Getattr(p, "emit:input"));
Replaceall(tm, "$input", Getattr(p, "emit:input"));
Printf(argout, "%s", tm);
p = Getattr(p, "tmap:argout:next");
} else {
p = nextSibling(p);
}
}
Setattr(n, "wrap:name", wname);
/* Emit the function call */
String *actioncode = emit_action(n);
/* Return the function value */
if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) {
Replaceall(tm, "$source", "result");
Replaceall(tm, "$target", "resultobj");
Replaceall(tm, "$result", "resultobj");
if (GetFlag(n, "feature:new")) {
Replaceall(tm, "$owner", "1");
} else {
Replaceall(tm, "$owner", "0");
}
Printf(f->code, "%s", tm);
if (have_argout)
Printf(f->code, "\nSWIG_APPEND_VALUE(resultobj);\n");
} else {
Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name);
}
emit_return_variable(n, d, f);
/* Insert the argumetn output code */
Printv(f->code, argout, NIL);
/* Output cleanup code */
Printv(f->code, cleanup, NIL);
/* Look to see if there is any newfree cleanup code */
if (GetFlag(n, "feature:new")) {
if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) {
Replaceall(tm, "$source", "result");
Printf(f->code, "%s\n", tm);
}
}
/* See if there is any return cleanup code */
if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) {
Replaceall(tm, "$source", "result");
Printf(f->code, "%s\n", tm);
}
if (have_argout) {
Printf(f->code, "C_kontinue(continuation,C_SCHEME_END_OF_LIST);\n");
} else {
if (exporting_constructor && clos && hide_primitive) {
/* Don't return a proxy, the wrapped CLOS class is the proxy */
Printf(f->code, "C_kontinue(continuation,resultobj);\n");
} else {
// make the continuation the proxy creation function, if one exists
Printv(f->code, "{\n",
"C_word func;\n",
"SWIG_Chicken_FindCreateProxy(func, resultobj)\n",
"if (C_swig_is_closurep(func))\n",
" ((C_proc4)(void *)C_block_item(func, 0))(4,func,continuation,resultobj,C_SCHEME_FALSE);\n",
"else\n", " C_kontinue(continuation, resultobj);\n", "}\n", NIL);
}
}
/* Error handling code */
#ifdef USE_FAIL
Printf(f->code, "fail:\n");
Printv(f->code, cleanup, NIL);
Printf(f->code, "swig_panic (\"failure in " "'$symname' SWIG function wrapper\");\n");
#endif
Printf(f->code, "}\n");
/* Substitute the cleanup code */
Replaceall(f->code, "$cleanup", cleanup);
/* Substitute the function name */
Replaceall(f->code, "$symname", iname);
Replaceall(f->code, "$result", "resultobj");
/* Dump the function out */
Printv(f_wrappers, "static ", declfunc, " C_noret;\n", NIL);
Wrapper_print(f, f_wrappers);
/* Now register the function with the interpreter. */
if (!Getattr(n, "sym:overloaded")) {
if (exporting_destructor && !no_collection) {
Printf(f_init, "((swig_chicken_clientdata *)(SWIGTYPE%s->clientdata))->destroy = (swig_chicken_destructor) %s;\n", swigtype_ptr, wname);
} else {
addMethod(scmname, wname);
}
/* Only export if we are not in a class, or if in a class memberfunction */
if (!in_class || member_name) {
String *method_def;
String *clos_name;
if (in_class)
clos_name = NewString(member_name);
else
clos_name = chickenNameMapping(scmname, (char *) "");
if (!any_specialized_arg) {
method_def = NewString("");
Printv(method_def, "(define ", clos_name, " ", chickenPrimitiveName(scmname), ")", NIL);
} else {
method_def = buildClosFunctionCall(function_arg_types, clos_name, chickenPrimitiveName(scmname));
}
Printv(clos_methods, method_def, "\n", NIL);
Delete(clos_name);
Delete(method_def);
}
if (have_constructor && !has_constructor_args && any_specialized_arg) {
has_constructor_args = 1;
constructor_arg_types = Copy(function_arg_types);
}
} else {
/* add function_arg_types to overload hash */
List *flist = Getattr(overload_parameter_lists, scmname);
if (!flist) {
flist = NewList();
Setattr(overload_parameter_lists, scmname, flist);
}
Append(flist, Copy(function_arg_types));
if (!Getattr(n, "sym:nextSibling")) {
dispatchFunction(n);
}
}
Delete(wname);
Delete(get_pointers);
Delete(cleanup);
Delete(declfunc);
Delete(mangle);
Delete(function_arg_types);
DelWrapper(f);
return SWIG_OK;
}
int CHICKEN::variableWrapper(Node *n) {
char *name = GetChar(n, "name");
char *iname = GetChar(n, "sym:name");
SwigType *t = Getattr(n, "type");
ParmList *l = Getattr(n, "parms");
String *wname = NewString("");
String *mangle = NewString("");
String *tm;
String *tm2 = NewString("");
String *argnum = NewString("0");
String *arg = NewString("argv[0]");
Wrapper *f;
String *overname = 0;
String *scmname;
scmname = NewString(iname);
Replaceall(scmname, "_", "-");
Printf(mangle, "\"%s\"", SwigType_manglestr(t));
if (Getattr(n, "sym:overloaded")) {
overname = Getattr(n, "sym:overname");
} else {
if (!addSymbol(iname, n))
return SWIG_ERROR;
}
f = NewWrapper();
/* Attach the standard typemaps */
emit_attach_parmmaps(l, f);
Setattr(n, "wrap:parms", l);
// evaluation function names
Append(wname, Swig_name_wrapper(iname));
if (overname) {
Append(wname, overname);
}
Setattr(n, "wrap:name", wname);
// Check for interrupts
Printv(f->code, "C_trace(\"", scmname, "\");\n", NIL);
if (1 || (SwigType_type(t) != T_USER) || (isPointer(t))) {
Printv(f->def, "static ", "void ", wname, "(C_word, C_word, C_word, C_word) C_noret;\n", NIL);
Printv(f->def, "static " "void ", wname, "(C_word argc, C_word closure, " "C_word continuation, C_word value) {\n", NIL);
Wrapper_add_local(f, "resultobj", "C_word resultobj");
Printf(f->code, "if (argc!=2 && argc!=3) C_bad_argc(argc,2);\n");
/* Check for a setting of the variable value */
if (!GetFlag(n, "feature:immutable")) {
Printf(f->code, "if (argc > 2) {\n");
if ((tm = Swig_typemap_lookup("varin", n, name, 0))) {
Replaceall(tm, "$source", "value");
Replaceall(tm, "$target", name);
Replaceall(tm, "$input", "value");
/* Printv(f->code, tm, "\n",NIL); */
emit_action_code(n, f->code, tm);
} else {
Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(t, 0));
}
Printf(f->code, "}\n");
}
String *varname;
if (SwigType_istemplate((char *) name)) {
varname = SwigType_namestr((char *) name);
} else {
varname = name;
}
// Now return the value of the variable - regardless
// of evaluating or setting.
if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
Replaceall(tm, "$source", varname);
Replaceall(tm, "$varname", varname);
Replaceall(tm, "$target", "resultobj");
Replaceall(tm, "$result", "resultobj");
/* Printf(f->code, "%s\n", tm); */
emit_action_code(n, f->code, tm);
} else {
Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0));
}
Printv(f->code, "{\n",
"C_word func;\n",
"SWIG_Chicken_FindCreateProxy(func, resultobj)\n",
"if (C_swig_is_closurep(func))\n",
" ((C_proc4)(void *)C_block_item(func, 0))(4,func,continuation,resultobj,C_SCHEME_FALSE);\n",
"else\n", " C_kontinue(continuation, resultobj);\n", "}\n", NIL);
/* Error handling code */
#ifdef USE_FAIL
Printf(f->code, "fail:\n");
Printf(f->code, "swig_panic (\"failure in " "'%s' SWIG wrapper\");\n", proc_name);
#endif
Printf(f->code, "}\n");
Wrapper_print(f, f_wrappers);
/* Now register the variable with the interpreter. */
addMethod(scmname, wname);
if (!in_class || member_name) {
String *clos_name;
if (in_class)
clos_name = NewString(member_name);
else
clos_name = chickenNameMapping(scmname, (char *) "");
Node *class_node = classLookup(t);
String *clos_code = Getattr(n, "tmap:varin:closcode");
if (class_node && clos_code && !GetFlag(n, "feature:immutable")) {
Replaceall(clos_code, "$input", "(car lst)");
Printv(clos_methods, "(define (", clos_name, " . lst) (if (null? lst) (", chickenPrimitiveName(scmname), ") (",
chickenPrimitiveName(scmname), " ", clos_code, ")))\n", NIL);
} else {
/* Simply re-export the procedure */
if (GetFlag(n, "feature:immutable") && GetFlag(n, "feature:constasvar")) {
Printv(clos_methods, "(define ", clos_name, " (", chickenPrimitiveName(scmname), "))\n", NIL);
Printv(scm_const_defs, "(set! ", scmname, " (", scmname, "))\n", NIL);
} else {
Printv(clos_methods, "(define ", clos_name, " ", chickenPrimitiveName(scmname), ")\n", NIL);
}
}
Delete(clos_name);
}
} else {
Swig_warning(WARN_TYPEMAP_VAR_UNDEF, input_file, line_number, "Unsupported variable type %s (ignored).\n", SwigType_str(t, 0));
}
Delete(wname);
Delete(argnum);
Delete(arg);
Delete(tm2);
Delete(mangle);
DelWrapper(f);
return SWIG_OK;
}
/* ------------------------------------------------------------
* constantWrapper()
* ------------------------------------------------------------ */
int CHICKEN::constantWrapper(Node *n) {
char *name = GetChar(n, "name");
char *iname = GetChar(n, "sym:name");
SwigType *t = Getattr(n, "type");
ParmList *l = Getattr(n, "parms");
String *value = Getattr(n, "value");
String *proc_name = NewString("");
String *wname = NewString("");
String *mangle = NewString("");
String *tm;
String *tm2 = NewString("");
String *source = NewString("");
String *argnum = NewString("0");
String *arg = NewString("argv[0]");
Wrapper *f;
String *overname = 0;
String *scmname;
String *rvalue;
SwigType *nctype;
scmname = NewString(iname);
Replaceall(scmname, "_", "-");
Printf(source, "swig_const_%s", iname);
Replaceall(source, "::", "__");
Printf(mangle, "\"%s\"", SwigType_manglestr(t));
if (Getattr(n, "sym:overloaded")) {
overname = Getattr(n, "sym:overname");
} else {
if (!addSymbol(iname, n))
return SWIG_ERROR;
}
Append(wname, Swig_name_wrapper(iname));
if (overname) {
Append(wname, overname);
}
nctype = NewString(t);
if (SwigType_isconst(nctype)) {
Delete(SwigType_pop(nctype));
}
bool is_enum_item = (Cmp(nodeType(n), "enumitem") == 0);
if (SwigType_type(nctype) == T_STRING) {
rvalue = NewStringf("\"%s\"", value);
} else if (SwigType_type(nctype) == T_CHAR && !is_enum_item) {
rvalue = NewStringf("\'%s\'", value);
} else {
rvalue = NewString(value);
}
/* Special hook for member pointer */
if (SwigType_type(t) == T_MPOINTER) {
Printf(f_header, "static %s = %s;\n", SwigType_str(t, source), rvalue);
} else {
if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) {
Replaceall(tm, "$source", rvalue);
Replaceall(tm, "$target", source);
Replaceall(tm, "$result", source);
Replaceall(tm, "$value", rvalue);
Printf(f_header, "%s\n", tm);
} else {
Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n");
return SWIG_NOWRAP;
}
}
f = NewWrapper();
/* Attach the standard typemaps */
emit_attach_parmmaps(l, f);
Setattr(n, "wrap:parms", l);
// evaluation function names
// Check for interrupts
Printv(f->code, "C_trace(\"", scmname, "\");\n", NIL);
if (1 || (SwigType_type(t) != T_USER) || (isPointer(t))) {
Setattr(n, "wrap:name", wname);
Printv(f->def, "static ", "void ", wname, "(C_word, C_word, C_word) C_noret;\n", NIL);
Printv(f->def, "static ", "void ", wname, "(C_word argc, C_word closure, " "C_word continuation) {\n", NIL);
Wrapper_add_local(f, "resultobj", "C_word resultobj");
Printf(f->code, "if (argc!=2) C_bad_argc(argc,2);\n");
// Return the value of the variable
if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
Replaceall(tm, "$source", source);
Replaceall(tm, "$varname", source);
Replaceall(tm, "$target", "resultobj");
Replaceall(tm, "$result", "resultobj");
/* Printf(f->code, "%s\n", tm); */
emit_action_code(n, f->code, tm);
} else {
Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0));
}
Printv(f->code, "{\n",
"C_word func;\n",
"SWIG_Chicken_FindCreateProxy(func, resultobj)\n",
"if (C_swig_is_closurep(func))\n",
" ((C_proc4)(void *)C_block_item(func, 0))(4,func,continuation,resultobj,C_SCHEME_FALSE);\n",
"else\n", " C_kontinue(continuation, resultobj);\n", "}\n", NIL);
/* Error handling code */
#ifdef USE_FAIL
Printf(f->code, "fail:\n");
Printf(f->code, "swig_panic (\"failure in " "'%s' SWIG wrapper\");\n", proc_name);
#endif
Printf(f->code, "}\n");
Wrapper_print(f, f_wrappers);
/* Now register the variable with the interpreter. */
addMethod(scmname, wname);
if (!in_class || member_name) {
String *clos_name;
if (in_class)
clos_name = NewString(member_name);
else
clos_name = chickenNameMapping(scmname, (char *) "");
if (GetFlag(n, "feature:constasvar")) {
Printv(clos_methods, "(define ", clos_name, " (", chickenPrimitiveName(scmname), "))\n", NIL);
Printv(scm_const_defs, "(set! ", scmname, " (", scmname, "))\n", NIL);
} else {
Printv(clos_methods, "(define ", clos_name, " ", chickenPrimitiveName(scmname), ")\n", NIL);
}
Delete(clos_name);
}
} else {
Swig_warning(WARN_TYPEMAP_VAR_UNDEF, input_file, line_number, "Unsupported variable type %s (ignored).\n", SwigType_str(t, 0));
}
Delete(wname);
Delete(nctype);
Delete(proc_name);
Delete(argnum);
Delete(arg);
Delete(tm2);
Delete(mangle);
Delete(source);
Delete(rvalue);
DelWrapper(f);
return SWIG_OK;
}
int CHICKEN::classHandler(Node *n) {
/* Create new strings for building up a wrapper function */
have_constructor = 0;
constructor_dispatch = 0;
constructor_name = 0;
c_class_name = NewString(Getattr(n, "sym:name"));
class_name = NewString("");
short_class_name = NewString("");
Printv(class_name, "<", c_class_name, ">", NIL);
Printv(short_class_name, c_class_name, NIL);
Replaceall(class_name, "_", "-");
Replaceall(short_class_name, "_", "-");
if (!addSymbol(class_name, n))
return SWIG_ERROR;
/* Handle inheritance */
String *base_class = NewString("");
List *baselist = Getattr(n, "bases");
if (baselist && Len(baselist)) {
Iterator base = First(baselist);
while (base.item) {
if (!Getattr(base.item, "feature:ignore"))
Printv(base_class, "<", Getattr(base.item, "sym:name"), "> ", NIL);
base = Next(base);
}
}
Replaceall(base_class, "_", "-");
String *scmmod = NewString(module);
Replaceall(scmmod, "_", "-");
Printv(clos_class_defines, "(define ", class_name, "\n", " (make <swig-metaclass-", scmmod, "> 'name \"", short_class_name, "\"\n", NIL);
Delete(scmmod);
if (Len(base_class)) {
Printv(clos_class_defines, " 'direct-supers (list ", base_class, ")\n", NIL);
} else {
Printv(clos_class_defines, " 'direct-supers (list <object>)\n", NIL);
}
Printf(clos_class_defines, " 'direct-slots (list 'swig-this\n");
String *mangled_classname = Swig_name_mangle(Getattr(n, "sym:name"));
SwigType *ct = NewStringf("p.%s", Getattr(n, "name"));
swigtype_ptr = SwigType_manglestr(ct);
Printf(f_runtime, "static swig_chicken_clientdata _swig_chicken_clientdata%s = { 0 };\n", mangled_classname);
Printv(f_init, "SWIG_TypeClientData(SWIGTYPE", swigtype_ptr, ", (void *) &_swig_chicken_clientdata", mangled_classname, ");\n", NIL);
SwigType_remember(ct);
/* Emit all of the members */
in_class = 1;
Language::classHandler(n);
in_class = 0;
Printf(clos_class_defines, ")))\n\n");
if (have_constructor) {
Printv(clos_methods, "(define-method (initialize (obj ", class_name, ") initargs)\n", " (swig-initialize obj initargs ", NIL);
if (constructor_arg_types) {
String *initfunc_name = NewStringf("%s@@SWIG@initmethod", class_name);
String *func_call = buildClosFunctionCall(constructor_arg_types, initfunc_name, chickenPrimitiveName(constructor_name));
Printf(clos_methods, "%s)\n)\n", initfunc_name);
Printf(clos_methods, "(declare (hide %s))\n", initfunc_name);
Printf(clos_methods, "%s\n", func_call);
Delete(func_call);
Delete(initfunc_name);
Delete(constructor_arg_types);
constructor_arg_types = 0;
} else if (constructor_dispatch) {
Printf(clos_methods, "%s)\n)\n", constructor_dispatch);
Delete(constructor_dispatch);
constructor_dispatch = 0;
} else {
Printf(clos_methods, "%s)\n)\n", chickenPrimitiveName(constructor_name));
}
Delete(constructor_name);
constructor_name = 0;
} else {
Printv(clos_methods, "(define-method (initialize (obj ", class_name, ") initargs)\n", " (swig-initialize obj initargs (lambda x #f)))\n", NIL);
}
/* export class initialization function */
if (clos) {
String *funcname = NewString(mangled_classname);
Printf(funcname, "_swig_chicken_setclosclass");
String *closfuncname = NewString(funcname);
Replaceall(closfuncname, "_", "-");
Printv(f_wrappers, "static void ", funcname, "(C_word,C_word,C_word,C_word) C_noret;\n",
"static void ", funcname, "(C_word argc, C_word closure, C_word continuation, C_word cl) {\n",
" C_trace(\"", funcname, "\");\n",
" if (argc!=3) C_bad_argc(argc,3);\n",
" swig_chicken_clientdata *cdata = (swig_chicken_clientdata *) SWIGTYPE", swigtype_ptr, "->clientdata;\n",
" cdata->gc_proxy_create = CHICKEN_new_gc_root();\n",
" CHICKEN_gc_root_set(cdata->gc_proxy_create, cl);\n", " C_kontinue(continuation, C_SCHEME_UNDEFINED);\n", "}\n", NIL);
addMethod(closfuncname, funcname);
Printv(clos_methods, "(", chickenPrimitiveName(closfuncname), " (lambda (x lst) (if lst ",
"(cons (make ", class_name, " 'swig-this x) lst) ", "(make ", class_name, " 'swig-this x))))\n\n", NIL);
Delete(closfuncname);
Delete(funcname);
}
Delete(mangled_classname);
Delete(swigtype_ptr);
swigtype_ptr = 0;
Delete(class_name);
Delete(short_class_name);
Delete(c_class_name);
class_name = 0;
short_class_name = 0;
c_class_name = 0;
return SWIG_OK;
}
int CHICKEN::memberfunctionHandler(Node *n) {
String *iname = Getattr(n, "sym:name");
String *proc = NewString(iname);
Replaceall(proc, "_", "-");
member_name = chickenNameMapping(proc, short_class_name);
Language::memberfunctionHandler(n);
Delete(member_name);
member_name = NULL;
Delete(proc);
return SWIG_OK;
}
int CHICKEN::staticmemberfunctionHandler(Node *n) {
String *iname = Getattr(n, "sym:name");
String *proc = NewString(iname);
Replaceall(proc, "_", "-");
member_name = NewStringf("%s-%s", short_class_name, proc);
Language::staticmemberfunctionHandler(n);
Delete(member_name);
member_name = NULL;
Delete(proc);
return SWIG_OK;
}
int CHICKEN::membervariableHandler(Node *n) {
String *iname = Getattr(n, "sym:name");
//String *pb = SwigType_typedef_resolve_all(SwigType_base(Getattr(n, "type")));
Language::membervariableHandler(n);
String *proc = NewString(iname);
Replaceall(proc, "_", "-");
//Node *class_node = Swig_symbol_clookup(pb, Getattr(n, "sym:symtab"));
Node *class_node = classLookup(Getattr(n, "type"));
//String *getfunc = NewStringf("%s-%s-get", short_class_name, proc);
//String *setfunc = NewStringf("%s-%s-set", short_class_name, proc);
String *getfunc = Swig_name_get(NSPACE_TODO, Swig_name_member(NSPACE_TODO, c_class_name, iname));
Replaceall(getfunc, "_", "-");
String *setfunc = Swig_name_set(NSPACE_TODO, Swig_name_member(NSPACE_TODO, c_class_name, iname));
Replaceall(setfunc, "_", "-");
Printv(clos_class_defines, " (list '", proc, " ':swig-virtual ':swig-get ", chickenPrimitiveName(getfunc), NIL);
if (!GetFlag(n, "feature:immutable")) {
if (class_node) {
Printv(clos_class_defines, " ':swig-set (lambda (x y) (", chickenPrimitiveName(setfunc), " x (slot-ref y 'swig-this))))\n", NIL);
} else {
Printv(clos_class_defines, " ':swig-set ", chickenPrimitiveName(setfunc), ")\n", NIL);
}
} else {
Printf(clos_class_defines, ")\n");
}
Delete(proc);
Delete(setfunc);
Delete(getfunc);
return SWIG_OK;
}
int CHICKEN::staticmembervariableHandler(Node *n) {
String *iname = Getattr(n, "sym:name");
String *proc = NewString(iname);
Replaceall(proc, "_", "-");
member_name = NewStringf("%s-%s", short_class_name, proc);
Language::staticmembervariableHandler(n);
Delete(member_name);
member_name = NULL;
Delete(proc);
return SWIG_OK;
}
int CHICKEN::constructorHandler(Node *n) {
have_constructor = 1;
has_constructor_args = 0;
exporting_constructor = true;
Language::constructorHandler(n);
exporting_constructor = false;
has_constructor_args = 1;
String *iname = Getattr(n, "sym:name");
constructor_name = Swig_name_construct(NSPACE_TODO, iname);
Replaceall(constructor_name, "_", "-");
return SWIG_OK;
}
int CHICKEN::destructorHandler(Node *n) {
if (no_collection)
member_name = NewStringf("delete-%s", short_class_name);
exporting_destructor = true;
Language::destructorHandler(n);
exporting_destructor = false;
if (no_collection) {
Delete(member_name);
member_name = NULL;
}
return SWIG_OK;
}
int CHICKEN::importDirective(Node *n) {
String *modname = Getattr(n, "module");
if (modname && clos_uses) {
// Find the module node for this imported module. It should be the
// first child but search just in case.
Node *mod = firstChild(n);
while (mod && Strcmp(nodeType(mod), "module") != 0)
mod = nextSibling(mod);
if (mod) {
String *name = Getattr(mod, "name");
if (name) {
Printf(closprefix, "(declare (uses %s))\n", name);
}
}
}
return Language::importDirective(n);
}
String *CHICKEN::buildClosFunctionCall(List *types, const_String_or_char_ptr closname, const_String_or_char_ptr funcname) {
String *method_signature = NewString("");
String *func_args = NewString("");
String *func_call = NewString("");
Iterator arg_type;
int arg_count = 0;
int optional_arguments = 0;
for (arg_type = First(types); arg_type.item; arg_type = Next(arg_type)) {
if (Strcmp(arg_type.item, "^^##optional$$") == 0) {
optional_arguments = 1;
} else {
Printf(method_signature, " (arg%i %s)", arg_count, arg_type.item);
arg_type = Next(arg_type);
if (!arg_type.item)
break;
String *arg = NewStringf("arg%i", arg_count);
String *access_arg = Copy(arg_type.item);
Replaceall(access_arg, "$input", arg);
Printf(func_args, " %s", access_arg);
Delete(arg);
Delete(access_arg);
}
arg_count++;
}
if (optional_arguments) {
Printf(func_call, "(define-method (%s %s . args) (apply %s %s args))", closname, method_signature, funcname, func_args);
} else {
Printf(func_call, "(define-method (%s %s) (%s %s))", closname, method_signature, funcname, func_args);
}
Delete(method_signature);
Delete(func_args);
return func_call;
}
extern "C" {
/* compares based on non-primitive names */
static int compareTypeListsHelper(const DOH *a, const DOH *b, int opt_equal) {
List *la = (List *) a;
List *lb = (List *) b;
Iterator ia = First(la);
Iterator ib = First(lb);
while (ia.item && ib.item) {
int ret = Strcmp(ia.item, ib.item);
if (ret)
return ret;
ia = Next(Next(ia));
ib = Next(Next(ib));
} if (opt_equal && ia.item && Strcmp(ia.item, "^^##optional$$") == 0)
return 0;
if (ia.item)
return -1;
if (opt_equal && ib.item && Strcmp(ib.item, "^^##optional$$") == 0)
return 0;
if (ib.item)
return 1;
return 0;
}
static int compareTypeLists(const DOH *a, const DOH *b) {
return compareTypeListsHelper(a, b, 0);
}
}
void CHICKEN::dispatchFunction(Node *n) {
/* Last node in overloaded chain */
int maxargs;
String *tmp = NewString("");
String *dispatch = Swig_overload_dispatch(n, "%s (2+$numargs,closure," "continuation$commaargs);", &maxargs);
/* Generate a dispatch wrapper for all overloaded functions */
Wrapper *f = NewWrapper();
String *iname = Getattr(n, "sym:name");
String *wname = NewString("");
String *scmname = NewString(iname);
Replaceall(scmname, "_", "-");
Append(wname, Swig_name_wrapper(iname));
Printv(f->def, "static void real_", wname, "(C_word, C_word, C_word, C_word) C_noret;\n", NIL);
Printv(f->def, "static void real_", wname, "(C_word oldargc, C_word closure, C_word continuation, C_word args) {", NIL);
Wrapper_add_local(f, "argc", "int argc");
Printf(tmp, "C_word argv[%d]", maxargs + 1);
Wrapper_add_local(f, "argv", tmp);
Wrapper_add_local(f, "ii", "int ii");
Wrapper_add_local(f, "t", "C_word t = args");
Printf(f->code, "if (!C_swig_is_list (args)) {\n");
Printf(f->code, " swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE, " "\"Argument #1 must be a list of overloaded arguments\");\n");
Printf(f->code, "}\n");
Printf(f->code, "argc = C_unfix (C_i_length (args));\n");
Printf(f->code, "for (ii = 0; (ii < argc) && (ii < %d); ii++, t = C_block_item (t, 1)) {\n", maxargs);
Printf(f->code, "argv[ii] = C_block_item (t, 0);\n");
Printf(f->code, "}\n");
Printv(f->code, dispatch, "\n", NIL);
Printf(f->code, "swig_barf (SWIG_BARF1_BAD_ARGUMENT_TYPE," "\"No matching function for overloaded '%s'\");\n", iname);
Printv(f->code, "}\n", NIL);
Wrapper_print(f, f_wrappers);
addMethod(scmname, wname);
DelWrapper(f);
f = NewWrapper();
/* varargs */
Printv(f->def, "void ", wname, "(C_word, C_word, C_word, ...) C_noret;\n", NIL);
Printv(f->def, "void ", wname, "(C_word c, C_word t0, C_word t1, ...) {", NIL);
Printv(f->code,
"C_word t2;\n",
"va_list v;\n",
"C_word *a, c2 = c;\n",
"C_save_rest (t1, c2, 2);\n", "a = C_alloc((c-2)*3);\n", "t2 = C_restore_rest (a, C_rest_count (0));\n", "real_", wname, " (3, t0, t1, t2);\n", NIL);
Printv(f->code, "}\n", NIL);
Wrapper_print(f, f_wrappers);
/* Now deal with overloaded function when exporting clos */
if (clos) {
List *flist = Getattr(overload_parameter_lists, scmname);
if (flist) {
Delattr(overload_parameter_lists, scmname);
SortList(flist, compareTypeLists);
String *clos_name;
if (have_constructor && !has_constructor_args) {
has_constructor_args = 1;
constructor_dispatch = NewStringf("%s@SWIG@new@dispatch", short_class_name);
clos_name = Copy(constructor_dispatch);
Printf(clos_methods, "(declare (hide %s))\n", clos_name);
} else if (in_class)
clos_name = NewString(member_name);
else
clos_name = chickenNameMapping(scmname, (char *) "");
Iterator f;
List *prev = 0;
int all_primitive = 1;
/* first check for duplicates and an empty call */
String *newlist = NewList();
for (f = First(flist); f.item; f = Next(f)) {
/* check if cur is a duplicate of prev */
if (prev && compareTypeListsHelper(f.item, prev, 1) == 0) {
Delete(f.item);
} else {
Append(newlist, f.item);
prev = f.item;
Iterator j;
for (j = First(f.item); j.item; j = Next(j)) {
if (Strcmp(j.item, "^^##optional$$") != 0 && Strcmp(j.item, "<top>") != 0)
all_primitive = 0;
}
}
}
Delete(flist);
flist = newlist;
if (all_primitive) {
Printf(clos_methods, "(define %s %s)\n", clos_name, chickenPrimitiveName(scmname));
} else {
for (f = First(flist); f.item; f = Next(f)) {
/* now export clos code for argument */
String *func_call = buildClosFunctionCall(f.item, clos_name, chickenPrimitiveName(scmname));
Printf(clos_methods, "%s\n", func_call);
Delete(f.item);
Delete(func_call);
}
}
Delete(clos_name);
Delete(flist);
}
}
DelWrapper(f);
Delete(dispatch);
Delete(tmp);
Delete(wname);
}
int CHICKEN::isPointer(SwigType *t) {
return SwigType_ispointer(SwigType_typedef_resolve_all(t));
}
void CHICKEN::addMethod(String *scheme_name, String *function) {
String *sym = NewString("");
if (clos) {
Append(sym, "primitive:");
}
Append(sym, scheme_name);
/* add symbol to Chicken internal symbol table */
if (hide_primitive) {
Printv(f_init, "{\n",
" C_word *p0 = a;\n", " *(a++)=C_CLOSURE_TYPE|1;\n", " *(a++)=(C_word)", function, ";\n", " C_mutate(return_vec++, (C_word)p0);\n", "}\n", NIL);
} else {
Printf(f_sym_size, "+C_SIZEOF_INTERNED_SYMBOL(%d)", Len(sym));
Printf(f_init, "sym = C_intern (&a, %d, \"%s\");\n", Len(sym), sym);
Printv(f_init, "C_mutate ((C_word*)sym+1, (*a=C_CLOSURE_TYPE|1, a[1]=(C_word)", function, ", tmp=(C_word)a, a+=2, tmp));\n", NIL);
}
if (hide_primitive) {
Setattr(primitive_names, scheme_name, NewStringf("(vector-ref swig-init-return %i)", num_methods));
} else {
Setattr(primitive_names, scheme_name, Copy(sym));
}
num_methods++;
Delete(sym);
}
String *CHICKEN::chickenPrimitiveName(String *name) {
String *value = Getattr(primitive_names, name);
if (value)
return value;
else {
Swig_error(input_file, line_number, "Internal Error: attempting to reference non-existant primitive name %s\n", name);
return NewString("#f");
}
}
int CHICKEN::validIdentifier(String *s) {
char *c = Char(s);
/* Check whether we have an R5RS identifier. */
/* <identifier> --> <initial> <subsequent>* | <peculiar identifier> */
/* <initial> --> <letter> | <special initial> */
if (!(isalpha(*c) || (*c == '!') || (*c == '$') || (*c == '%')
|| (*c == '&') || (*c == '*') || (*c == '/') || (*c == ':')
|| (*c == '<') || (*c == '=') || (*c == '>') || (*c == '?')
|| (*c == '^') || (*c == '_') || (*c == '~'))) {
/* <peculiar identifier> --> + | - | ... */
if ((strcmp(c, "+") == 0)
|| strcmp(c, "-") == 0 || strcmp(c, "...") == 0)
return 1;
else
return 0;
}
/* <subsequent> --> <initial> | <digit> | <special subsequent> */
while (*c) {
if (!(isalnum(*c) || (*c == '!') || (*c == '$') || (*c == '%')
|| (*c == '&') || (*c == '*') || (*c == '/') || (*c == ':')
|| (*c == '<') || (*c == '=') || (*c == '>') || (*c == '?')
|| (*c == '^') || (*c == '_') || (*c == '~') || (*c == '+')
|| (*c == '-') || (*c == '.') || (*c == '@')))
return 0;
c++;
}
return 1;
}
/* ------------------------------------------------------------
* closNameMapping()
* Maps the identifier from C++ to the CLOS based on command
* line parameters and such.
* If class_name = "" that means the mapping is for a function or
* variable not attached to any class.
* ------------------------------------------------------------ */
String *CHICKEN::chickenNameMapping(String *name, const_String_or_char_ptr class_name) {
String *n = NewString("");
if (Strcmp(class_name, "") == 0) {
// not part of a class, so no class name to prefix
if (clossymnameprefix) {
Printf(n, "%s%s", clossymnameprefix, name);
} else {
Printf(n, "%s", name);
}
} else {
if (useclassprefix) {
Printf(n, "%s-%s", class_name, name);
} else {
if (clossymnameprefix) {
Printf(n, "%s%s", clossymnameprefix, name);
} else {
Printf(n, "%s", name);
}
}
}
return n;
}
String *CHICKEN::runtimeCode() {
String *s = Swig_include_sys("chickenrun.swg");
if (!s) {
Printf(stderr, "*** Unable to open 'chickenrun.swg'\n");
s = NewString("");
}
return s;
}
String *CHICKEN::defaultExternalRuntimeFilename() {
return NewString("swigchickenrun.h");
}
| 30.494163 | 152 | 0.624304 |
80d88d4fa9985eeb6a8132df0ff0bd361615a33b | 1,966 | hpp | C++ | include/solaire/parallel/thread_pool_executor.hpp | SolaireLibrary/solaire_parallel | eed82815215e1eb60b7ca29e19720f6707966383 | [
"Apache-2.0"
] | null | null | null | include/solaire/parallel/thread_pool_executor.hpp | SolaireLibrary/solaire_parallel | eed82815215e1eb60b7ca29e19720f6707966383 | [
"Apache-2.0"
] | null | null | null | include/solaire/parallel/thread_pool_executor.hpp | SolaireLibrary/solaire_parallel | eed82815215e1eb60b7ca29e19720f6707966383 | [
"Apache-2.0"
] | null | null | null | #ifndef SOLAIRE_PARALEL_THREAD_POOL_EXECUTOR_HPP
#define SOLAIRE_PARALEL_THREAD_POOL_EXECUTOR_HPP
//Copyright 2016 Adam G. Smith
//
//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 <vector>
#include "solaire/parallel/task_executor.hpp"
namespace solaire {
class thread_pool_executor : public task_executor {
private:
std::thread* const mWorkerThreads;
std::vector<std::function<void()>> mTasks;
std::mutex mTasksLock;
std::condition_variable mTaskAdded;
const uint32_t mThreadCount;
bool mExit;
protected:
// inherited from task_executor
void _schedule(std::function<void()> aTask) override {
mTasksLock.lock();
mTasks.push_back(aTask);
mTasksLock.unlock();
mTaskAdded.notify_one();
}
public:
thread_pool_executor(uint32_t aThreadCount) :
mWorkerThreads(new std::thread[aThreadCount]),
mThreadCount(aThreadCount),
mExit(false)
{
const auto threadFn = [this]() {
while(! mExit) {
std::unique_lock<std::mutex> lock(mTasksLock);
mTaskAdded.wait(lock);
if(! mTasks.empty()) {
std::function<void()> task = mTasks.back();
mTasks.pop_back();
lock.unlock();
task();
}
}
};
for(uint32_t i = 0; i < aThreadCount; ++i) mWorkerThreads[i] = std::thread(threadFn);
}
~thread_pool_executor() {
mExit = true;
mTaskAdded.notify_all();
for (uint32_t i = 0; i < mThreadCount; ++i) mWorkerThreads[i].join();
delete[] mWorkerThreads;
}
};
}
#endif
| 26.931507 | 88 | 0.706002 |
80d950eacccf88a798578ce38845f2308be757aa | 757 | hpp | C++ | src/include/duckdb/planner/operator/logical_copy_to_file.hpp | RelationalAI-oss/duckdb | a4908ae17de3ac62d42633ada03077b8c3ead7a5 | [
"MIT"
] | 2 | 2020-01-07T17:19:02.000Z | 2020-01-09T22:04:04.000Z | src/include/duckdb/planner/operator/logical_copy_to_file.hpp | RelationalAI-oss/duckdb | a4908ae17de3ac62d42633ada03077b8c3ead7a5 | [
"MIT"
] | null | null | null | src/include/duckdb/planner/operator/logical_copy_to_file.hpp | RelationalAI-oss/duckdb | a4908ae17de3ac62d42633ada03077b8c3ead7a5 | [
"MIT"
] | null | null | null | //===----------------------------------------------------------------------===//
// DuckDB
//
// planner/operator/logical_copy_to_file.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/parser/parsed_data/copy_info.hpp"
#include "duckdb/planner/logical_operator.hpp"
namespace duckdb {
class LogicalCopyToFile : public LogicalOperator {
public:
LogicalCopyToFile(unique_ptr<CopyInfo> info)
: LogicalOperator(LogicalOperatorType::COPY_TO_FILE), info(move(info)) {
}
unique_ptr<CopyInfo> info;
vector<string> names;
vector<SQLType> sql_types;
protected:
void ResolveTypes() override {
types.push_back(TypeId::BIGINT);
}
};
} // namespace duckdb
| 23.65625 | 80 | 0.569353 |
80dac28b65282292b53ef42d11aebcca5f92f82d | 1,664 | cpp | C++ | implementations/ugene/src/corelibs/U2Lang/src/library/BaseThroughWorker.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/corelibs/U2Lang/src/library/BaseThroughWorker.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/corelibs/U2Lang/src/library/BaseThroughWorker.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2020 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "BaseThroughWorker.h"
#include <U2Core/U2OpStatusUtils.h>
namespace U2 {
namespace LocalWorkflow {
BaseThroughWorker::BaseThroughWorker(Actor *a, const QString &inPortId, const QString &outPortId)
: BaseOneOneWorker(a, /* autoTransitBus= */ true, inPortId, outPortId) {
}
void BaseThroughWorker::cleanup() {
}
Task *BaseThroughWorker::processNextInputMessage() {
const Message message = getMessageAndSetupScriptValues(input);
U2OpStatusImpl os;
Task *task = createTask(message, os);
if (os.hasError()) {
reportError(os.getError());
}
return task;
}
Task *BaseThroughWorker::onInputEnded() {
return NULL;
}
Message BaseThroughWorker::composeMessage(const QVariantMap &data) {
return Message(output->getBusType(), data);
}
} // namespace LocalWorkflow
} // namespace U2
| 29.714286 | 97 | 0.736178 |
80db0115de030b7e18548330d48487d3542a06e7 | 3,336 | cpp | C++ | vnext/Desktop.UnitTests/WebSocketMocks.cpp | harinikmsft/react-native-windows | c73ecd0ffb8fb4ee5205ec610ab4b6dbc7f6ee21 | [
"MIT"
] | null | null | null | vnext/Desktop.UnitTests/WebSocketMocks.cpp | harinikmsft/react-native-windows | c73ecd0ffb8fb4ee5205ec610ab4b6dbc7f6ee21 | [
"MIT"
] | null | null | null | vnext/Desktop.UnitTests/WebSocketMocks.cpp | harinikmsft/react-native-windows | c73ecd0ffb8fb4ee5205ec610ab4b6dbc7f6ee21 | [
"MIT"
] | null | null | null | #include "WebSocketMocks.h"
using std::exception;
using std::function;
using std::string;
namespace Microsoft::React::Test {
MockWebSocketResource::~MockWebSocketResource() {}
#pragma region IWebSocketResource overrides
void MockWebSocketResource::Connect(const Protocols &protocols, const Options &options) noexcept /*override*/
{
if (Mocks.Connect)
return Mocks.Connect(protocols, options);
}
void MockWebSocketResource::Ping() noexcept /*override*/
{
if (Mocks.Connect)
return Mocks.Ping();
}
void MockWebSocketResource::Send(const string &message) noexcept /*override*/
{
if (Mocks.Send)
return Mocks.Send(message);
}
void MockWebSocketResource::SendBinary(const string &message) noexcept /*override*/
{
if (Mocks.SendBinary)
return Mocks.SendBinary(message);
}
void MockWebSocketResource::Close(CloseCode code, const string &reason) noexcept /*override*/
{
if (Mocks.Close)
return Mocks.Close(code, reason);
}
IWebSocketResource::ReadyState MockWebSocketResource::GetReadyState() const noexcept /*override*/
{
if (Mocks.GetReadyState)
return Mocks.GetReadyState();
return ReadyState::Connecting;
}
void MockWebSocketResource::SetOnConnect(function<void()> &&handler) noexcept /*override*/
{
if (Mocks.SetOnConnect)
return SetOnConnect(std::move(handler));
m_connectHandler = std::move(handler);
}
void MockWebSocketResource::SetOnPing(function<void()> &&handler) noexcept /*override*/
{
if (Mocks.SetOnPing)
return Mocks.SetOnPing(std::move(handler));
m_pingHandler = std::move(handler);
}
void MockWebSocketResource::SetOnSend(function<void(size_t)> &&handler) noexcept /*override*/
{
if (Mocks.SetOnSend)
return Mocks.SetOnSend(std::move(handler));
m_writeHandler = std::move(handler);
}
void MockWebSocketResource::SetOnMessage(function<void(size_t, const string &)> &&handler) noexcept /*override*/
{
if (Mocks.SetOnMessage)
return Mocks.SetOnMessage(std::move(handler));
m_readHandler = std::move(handler);
}
void MockWebSocketResource::SetOnClose(function<void(CloseCode, const string &)> &&handler) noexcept /*override*/
{
if (Mocks.SetOnClose)
return Mocks.SetOnClose(std::move(handler));
m_closeHandler = std::move(handler);
}
void MockWebSocketResource::SetOnError(function<void(Error &&)> &&handler) noexcept /*override*/
{
if (Mocks.SetOnError)
return Mocks.SetOnError(std::move(handler));
m_errorHandler = std::move(handler);
}
#pragma endregion IWebSocketResource overrides
void MockWebSocketResource::OnConnect() {
if (m_connectHandler)
m_connectHandler();
}
void MockWebSocketResource::OnPing() {
if (m_pingHandler)
m_pingHandler();
}
void MockWebSocketResource::OnSend(size_t size) {
if (m_writeHandler)
m_writeHandler(size);
}
void MockWebSocketResource::OnMessage(size_t size, const string &message) {
if (m_readHandler)
m_readHandler(size, message);
}
void MockWebSocketResource::OnClose(CloseCode code, const string &reason) {
if (m_closeHandler)
m_closeHandler(code, reason);
}
void MockWebSocketResource::OnError(Error &&error) {
if (m_errorHandler)
m_errorHandler(std::move(error));
}
} // namespace Microsoft::React::Test
| 25.272727 | 114 | 0.711331 |
80dbdafa854a5fc9ea6377dadef58a78acdda782 | 1,299 | cpp | C++ | level_zero/tools/source/sysman/engine/linux/os_engine_imp.cpp | 8tab/compute-runtime | 71bd96ad7184df83c7af04ffa8e0d6678ab26f99 | [
"MIT"
] | null | null | null | level_zero/tools/source/sysman/engine/linux/os_engine_imp.cpp | 8tab/compute-runtime | 71bd96ad7184df83c7af04ffa8e0d6678ab26f99 | [
"MIT"
] | null | null | null | level_zero/tools/source/sysman/engine/linux/os_engine_imp.cpp | 8tab/compute-runtime | 71bd96ad7184df83c7af04ffa8e0d6678ab26f99 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "level_zero/tools/source/sysman/engine/linux/os_engine_imp.h"
namespace L0 {
const std::string LinuxEngineImp::computeEngineGroupFile("engine/rcs0/name");
const std::string LinuxEngineImp::computeEngineGroupName("rcs0");
ze_result_t LinuxEngineImp::getActiveTime(uint64_t &activeTime) {
return ZE_RESULT_ERROR_UNSUPPORTED_FEATURE;
}
ze_result_t LinuxEngineImp::getEngineGroup(zet_engine_group_t &engineGroup) {
std::string strVal;
ze_result_t result = pSysfsAccess->read(computeEngineGroupFile, strVal);
if (ZE_RESULT_SUCCESS != result) {
return result;
}
if (strVal.compare(computeEngineGroupName) == 0) {
engineGroup = ZET_ENGINE_GROUP_COMPUTE_ALL;
} else {
engineGroup = ZET_ENGINE_GROUP_ALL;
return ZE_RESULT_ERROR_UNKNOWN;
}
return result;
}
LinuxEngineImp::LinuxEngineImp(OsSysman *pOsSysman) {
LinuxSysmanImp *pLinuxSysmanImp = static_cast<LinuxSysmanImp *>(pOsSysman);
pSysfsAccess = &pLinuxSysmanImp->getSysfsAccess();
}
OsEngine *OsEngine::create(OsSysman *pOsSysman) {
LinuxEngineImp *pLinuxEngineImp = new LinuxEngineImp(pOsSysman);
return static_cast<OsEngine *>(pLinuxEngineImp);
}
} // namespace L0
| 29.522727 | 79 | 0.744419 |
80def142bb58b6c555024ff734b0fbd06536ef52 | 484 | cpp | C++ | test/lib/BookmarkSerializer_test.cpp | alepez/bmrk | 04db2646b42662b976b4f4a1a5fb414ca73df163 | [
"MIT"
] | null | null | null | test/lib/BookmarkSerializer_test.cpp | alepez/bmrk | 04db2646b42662b976b4f4a1a5fb414ca73df163 | [
"MIT"
] | null | null | null | test/lib/BookmarkSerializer_test.cpp | alepez/bmrk | 04db2646b42662b976b4f4a1a5fb414ca73df163 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <BookmarkSerializer.hpp>
#include "helpers.hpp"
namespace bmrk {
struct BookmarkSerializerTest: public testing::Test {
BookmarkSerializer bs;
};
TEST_F(BookmarkSerializerTest, CanSerialize) {
auto bookmark = createMockBookmark(
"http://pezzato.net", "one", Tags({"foo", "bar"}), "two");
std::stringstream stream;
bs.serialize(&stream, bookmark);
ASSERT_EQ("http://pezzato.net\none\nfoo,bar\ntwo\n", stream.str());
}
} /* bmrk */
| 22 | 69 | 0.700413 |
80dfc33806b5444b247ee40f6440363cfa8dcb1e | 2,948 | cpp | C++ | examples/text/text.cpp | ntwyman/32blit-beta | 56d1e6c964dbf39dee09dd939e52d7d5ef75d762 | [
"MIT"
] | null | null | null | examples/text/text.cpp | ntwyman/32blit-beta | 56d1e6c964dbf39dee09dd939e52d7d5ef75d762 | [
"MIT"
] | null | null | null | examples/text/text.cpp | ntwyman/32blit-beta | 56d1e6c964dbf39dee09dd939e52d7d5ef75d762 | [
"MIT"
] | null | null | null | #include "text.hpp"
using namespace blit;
bool variable_width = true;
TextAlign alignment = TextAlign::top_left;
std::string alignment_to_string(TextAlign alignment) {
switch (alignment) {
case TextAlign::bottom_left:
return "align: bottom_left";
case TextAlign::bottom_right:
return "align: bottom_right";
case TextAlign::top_left:
return "align: top_left";
case TextAlign::top_right:
return "align: top_right";
case TextAlign::center_center:
return "align: center_center";
case TextAlign::center_left:
return "align: center_left";
case TextAlign::center_right:
return "align: center_right";
case TextAlign::top_center:
return "align: top_center";
case TextAlign::bottom_center:
return "align: bottom_center";
}
return "";
}
void init() {
set_screen_mode(ScreenMode::hires);
}
void render(uint32_t time) {
screen.pen = Pen(0, 0, 0);
screen.clear();
screen.alpha = 255;
screen.pen = Pen(255, 255, 255);
screen.rectangle(Rect(0, 0, 320, 14));
screen.pen = Pen(0, 0, 0);
screen.text("Text Rendering", minimal_font, Point(5, 4));
// alignment
Rect text_rect(20, 20, 120, 80);
screen.pen = Pen(64, 64, 64);
screen.rectangle(text_rect);
screen.pen = Pen(255, 255, 255);
std::string text = "This is some aligned text!\nUse the dpad to change the alignment\nand A to toggle variable-width.";
text = screen.wrap_text(text, text_rect.w, minimal_font, variable_width);
screen.pen = Pen(0xFF, 0xFF, 0xFF);
screen.text(text, minimal_font, text_rect, variable_width, alignment);
screen.text(alignment_to_string(alignment), minimal_font, Point(80, 102), true, TextAlign::center_h);
auto size = screen.measure_text(text, minimal_font, variable_width);
screen.text("bounds: " + std::to_string(size.w) + "x" + std::to_string(size.h), minimal_font, Point(80, 110), true, TextAlign::center_h);
text_rect.x += 160;
// clipping
Rect clip(text_rect.x + 30 + 30 * cosf(time / 1000.0f), text_rect.y, 60, 80);
screen.pen = Pen(64, 64, 64);
screen.rectangle(text_rect);
text = "This text is clipped!\nIt's slightly hard to read since half of it is missing.";
text = screen.wrap_text(text, text_rect.w, minimal_font, variable_width);
screen.pen = Pen(0xFF, 0xFF, 0xFF);
screen.text(text, minimal_font, text_rect, variable_width, TextAlign::center_center, clip);
}
void update(uint32_t time) {
if (buttons.released & Button::A)
variable_width = !variable_width;
alignment = TextAlign::top_left;
if (buttons & Button::DPAD_DOWN) {
alignment = (TextAlign)(alignment | TextAlign::bottom);
}
else if (!(buttons & Button::DPAD_UP)) {
alignment = (TextAlign)(alignment | TextAlign::center_v);
}
if (buttons & Button::DPAD_RIGHT) {
alignment = (TextAlign)(alignment | TextAlign::right);
}
else if (!(buttons & Button::DPAD_LEFT)) {
alignment = (TextAlign)(alignment | TextAlign::center_h);
}
}
| 30.081633 | 141 | 0.692334 |
80e113e820b3058dd2e1b49d6c010ebe45526857 | 7,582 | cc | C++ | src/net/third_party/quiche/src/http2/adapter/test_utils.cc | kvmb/naiveproxy | 8bbb7526b927cbaa82870a4c81a08ccf5e8e9c1d | [
"BSD-3-Clause"
] | 3 | 2020-05-31T16:20:21.000Z | 2021-09-05T20:39:50.000Z | src/net/third_party/quiche/src/http2/adapter/test_utils.cc | LImboing/naiveproxy | 8bbb7526b927cbaa82870a4c81a08ccf5e8e9c1d | [
"BSD-3-Clause"
] | 11 | 2019-10-15T23:03:57.000Z | 2020-06-14T16:10:12.000Z | src/net/third_party/quiche/src/http2/adapter/test_utils.cc | LImboing/naiveproxy | 8bbb7526b927cbaa82870a4c81a08ccf5e8e9c1d | [
"BSD-3-Clause"
] | 7 | 2019-07-04T14:23:54.000Z | 2020-04-27T08:52:51.000Z | #include "http2/adapter/test_utils.h"
#include <ostream>
#include "absl/strings/str_format.h"
#include "common/quiche_endian.h"
#include "spdy/core/hpack/hpack_encoder.h"
#include "spdy/core/spdy_frame_reader.h"
namespace http2 {
namespace adapter {
namespace test {
TestDataFrameSource::TestDataFrameSource(Http2VisitorInterface& visitor,
bool has_fin)
: visitor_(visitor), has_fin_(has_fin) {}
void TestDataFrameSource::AppendPayload(absl::string_view payload) {
QUICHE_CHECK(!end_data_);
if (!payload.empty()) {
payload_fragments_.push_back(std::string(payload));
current_fragment_ = payload_fragments_.front();
}
}
void TestDataFrameSource::EndData() { end_data_ = true; }
std::pair<int64_t, bool> TestDataFrameSource::SelectPayloadLength(
size_t max_length) {
// The stream is done if there's no more data, or if |max_length| is at least
// as large as the remaining data.
const bool end_data = end_data_ && (current_fragment_.empty() ||
(payload_fragments_.size() == 1 &&
max_length >= current_fragment_.size()));
const int64_t length = std::min(max_length, current_fragment_.size());
return {length, end_data};
}
bool TestDataFrameSource::Send(absl::string_view frame_header,
size_t payload_length) {
QUICHE_LOG_IF(DFATAL, payload_length > current_fragment_.size())
<< "payload_length: " << payload_length
<< " current_fragment_size: " << current_fragment_.size();
const std::string concatenated =
absl::StrCat(frame_header, current_fragment_.substr(0, payload_length));
const int64_t result = visitor_.OnReadyToSend(concatenated);
if (result < 0) {
// Write encountered error.
visitor_.OnConnectionError();
current_fragment_ = {};
payload_fragments_.clear();
return false;
} else if (result == 0) {
// Write blocked.
return false;
} else if (static_cast<const size_t>(result) < concatenated.size()) {
// Probably need to handle this better within this test class.
QUICHE_LOG(DFATAL)
<< "DATA frame not fully flushed. Connection will be corrupt!";
visitor_.OnConnectionError();
current_fragment_ = {};
payload_fragments_.clear();
return false;
}
if (payload_length > 0) {
current_fragment_.remove_prefix(payload_length);
}
if (current_fragment_.empty() && !payload_fragments_.empty()) {
payload_fragments_.erase(payload_fragments_.begin());
if (!payload_fragments_.empty()) {
current_fragment_ = payload_fragments_.front();
}
}
return true;
}
std::string EncodeHeaders(const spdy::SpdyHeaderBlock& entries) {
spdy::HpackEncoder encoder;
encoder.DisableCompression();
return encoder.EncodeHeaderBlock(entries);
}
TestMetadataSource::TestMetadataSource(const spdy::SpdyHeaderBlock& entries)
: encoded_entries_(EncodeHeaders(entries)) {
remaining_ = encoded_entries_;
}
std::pair<int64_t, bool> TestMetadataSource::Pack(uint8_t* dest,
size_t dest_len) {
const size_t copied = std::min(dest_len, remaining_.size());
std::memcpy(dest, remaining_.data(), copied);
remaining_.remove_prefix(copied);
return std::make_pair(copied, remaining_.empty());
}
namespace {
using TypeAndOptionalLength =
std::pair<spdy::SpdyFrameType, absl::optional<size_t>>;
std::ostream& operator<<(
std::ostream& os,
const std::vector<TypeAndOptionalLength>& types_and_lengths) {
for (const auto& type_and_length : types_and_lengths) {
os << "(" << spdy::FrameTypeToString(type_and_length.first) << ", "
<< (type_and_length.second ? absl::StrCat(type_and_length.second.value())
: "<unspecified>")
<< ") ";
}
return os;
}
std::string FrameTypeToString(uint8_t frame_type) {
if (spdy::IsDefinedFrameType(frame_type)) {
return spdy::FrameTypeToString(spdy::ParseFrameType(frame_type));
} else {
return absl::StrFormat("0x%x", static_cast<int>(frame_type));
}
}
// Custom gMock matcher, used to implement EqualsFrames().
class SpdyControlFrameMatcher
: public testing::MatcherInterface<absl::string_view> {
public:
explicit SpdyControlFrameMatcher(
std::vector<TypeAndOptionalLength> types_and_lengths)
: expected_types_and_lengths_(std::move(types_and_lengths)) {}
bool MatchAndExplain(absl::string_view s,
testing::MatchResultListener* listener) const override {
spdy::SpdyFrameReader reader(s.data(), s.size());
for (TypeAndOptionalLength expected : expected_types_and_lengths_) {
if (!MatchAndExplainOneFrame(expected.first, expected.second, &reader,
listener)) {
return false;
}
}
if (!reader.IsDoneReading()) {
size_t bytes_remaining = s.size() - reader.GetBytesConsumed();
*listener << "; " << bytes_remaining << " bytes left to read!";
return false;
}
return true;
}
bool MatchAndExplainOneFrame(spdy::SpdyFrameType expected_type,
absl::optional<size_t> expected_length,
spdy::SpdyFrameReader* reader,
testing::MatchResultListener* listener) const {
uint32_t payload_length;
if (!reader->ReadUInt24(&payload_length)) {
*listener << "; unable to read length field for expected_type "
<< FrameTypeToString(expected_type) << ". data too short!";
return false;
}
if (expected_length && payload_length != expected_length.value()) {
*listener << "; actual length: " << payload_length
<< " but expected length: " << expected_length.value();
return false;
}
uint8_t raw_type;
if (!reader->ReadUInt8(&raw_type)) {
*listener << "; unable to read type field for expected_type "
<< FrameTypeToString(expected_type) << ". data too short!";
return false;
}
if (raw_type != static_cast<uint8_t>(expected_type)) {
*listener << "; actual type: " << FrameTypeToString(raw_type)
<< " but expected type: " << FrameTypeToString(expected_type);
return false;
}
// Seek past flags (1B), stream ID (4B), and payload. Reach the next frame.
reader->Seek(5 + payload_length);
return true;
}
void DescribeTo(std::ostream* os) const override {
*os << "Data contains frames of types in sequence "
<< expected_types_and_lengths_;
}
void DescribeNegationTo(std::ostream* os) const override {
*os << "Data does not contain frames of types in sequence "
<< expected_types_and_lengths_;
}
private:
const std::vector<TypeAndOptionalLength> expected_types_and_lengths_;
};
} // namespace
testing::Matcher<absl::string_view> EqualsFrames(
std::vector<std::pair<spdy::SpdyFrameType, absl::optional<size_t>>>
types_and_lengths) {
return MakeMatcher(new SpdyControlFrameMatcher(std::move(types_and_lengths)));
}
testing::Matcher<absl::string_view> EqualsFrames(
std::vector<spdy::SpdyFrameType> types) {
std::vector<std::pair<spdy::SpdyFrameType, absl::optional<size_t>>>
types_and_lengths;
types_and_lengths.reserve(types.size());
for (spdy::SpdyFrameType type : types) {
types_and_lengths.push_back({type, absl::nullopt});
}
return MakeMatcher(new SpdyControlFrameMatcher(std::move(types_and_lengths)));
}
} // namespace test
} // namespace adapter
} // namespace http2
| 34.779817 | 80 | 0.667106 |
80e2abd0223a3786643b9a2322a3e8e55291ed23 | 9,383 | cpp | C++ | drv/sd/sd_spi.cpp | yhsb2k/omef | 7425b62dd4b5d0af4e320816293f69d16d39f57a | [
"MIT"
] | null | null | null | drv/sd/sd_spi.cpp | yhsb2k/omef | 7425b62dd4b5d0af4e320816293f69d16d39f57a | [
"MIT"
] | null | null | null | drv/sd/sd_spi.cpp | yhsb2k/omef | 7425b62dd4b5d0af4e320816293f69d16d39f57a | [
"MIT"
] | null | null | null | #include <stddef.h>
#include <cstring>
#include <assert.h>
#include "sd_spi.hpp"
#include "FreeRTOS.h"
#include "task.h"
using namespace drv;
using namespace hal;
#define WAIT_RESPONSE_CNT 10
#define TRANSMITTER_BIT 6
#define END_BIT 0
#define DATA_TOKEN_CMD17_18_24 0xFE
#define DATA_TOKEN_CMD25 0xFC
#define STOP_TOKEN_CMD25 0xFD
#define ERR_TOKEN_MASK 0x1F /* 7, 6, 5 bits are not used */
#define ERR_TOKEN_ERR (1 << 0)
#define ERR_TOKEN_CC_ERR (1 << 1)
#define ERR_TOKEN_ECC_FAIL (1 << 2)
#define ERR_TOKEN_OUT_OF_RANGE_ERR (1 << 3)
#define ERR_TOKEN_CARD_LOCKED (1 << 4)
#define DATA_RESP_MASK 0x1F /* 7, 6, 5 bits are not used */
#define DATA_RESP_START_BIT (1 << 0) /* Should be 1 */
#define DATA_RESP_END_BIT (1 << 4) /* Should be 0 */
#define DATA_RESP_ACCEPTED 0x05 /* Data accepted */
#define DATA_RESP_CRC_ERR 0x0B /* Data rejected due to a CRC erro */
#define DATA_RESP_WRITE_ERR 0x0D /* Data rejected due to a write error */
#define R1_START_BIT 0x80
#define CRC7_CID_CSD_MASK 0xFE
/* crc7 table (crc8 table shifted left by 1 bit ) */
static const uint8_t crc7_table[256] =
{
0x00, 0x12, 0x24, 0x36, 0x48, 0x5A, 0x6C, 0x7E,
0x90, 0x82, 0xB4, 0xA6, 0xD8, 0xCA, 0xFC, 0xEE,
0x32, 0x20, 0x16, 0x04, 0x7A, 0x68, 0x5E, 0x4C,
0xA2, 0xB0, 0x86, 0x94, 0xEA, 0xF8, 0xCE, 0xDC,
0x64, 0x76, 0x40, 0x52, 0x2C, 0x3E, 0x08, 0x1A,
0xF4, 0xE6, 0xD0, 0xC2, 0xBC, 0xAE, 0x98, 0x8A,
0x56, 0x44, 0x72, 0x60, 0x1E, 0x0C, 0x3A, 0x28,
0xC6, 0xD4, 0xE2, 0xF0, 0x8E, 0x9C, 0xAA, 0xB8,
0xC8, 0xDA, 0xEC, 0xFE, 0x80, 0x92, 0xA4, 0xB6,
0x58, 0x4A, 0x7C, 0x6E, 0x10, 0x02, 0x34, 0x26,
0xFA, 0xE8, 0xDE, 0xCC, 0xB2, 0xA0, 0x96, 0x84,
0x6A, 0x78, 0x4E, 0x58, 0x22, 0x30, 0x06, 0x14,
0xAC, 0xBE, 0x88, 0x9A, 0xE4, 0xF6, 0xC0, 0xD2,
0x3C, 0x2E, 0x18, 0x0A, 0x74, 0x66, 0x50, 0x42,
0x9E, 0x8C, 0xBA, 0xA8, 0xD6, 0xC4, 0xF2, 0xE0,
0x0E, 0x1C, 0x2A, 0x38, 0x46, 0x54, 0x62, 0x70,
0x82, 0x90, 0xA6, 0xB4, 0xCA, 0xD8, 0xEE, 0xFC,
0x12, 0x00, 0x36, 0x24, 0x5A, 0x48, 0x7E, 0x6C,
0xB0, 0xA2, 0x94, 0x86, 0xF8, 0xEA, 0xDC, 0xCE,
0x20, 0x32, 0x04, 0x16, 0x68, 0x7A, 0x4C, 0x5E,
0xE6, 0xF4, 0xC2, 0xD0, 0xAE, 0xBC, 0x8A, 0x98,
0x76, 0x64, 0x52, 0x40, 0x3E, 0x2C, 0x1A, 0x08,
0xD4, 0xC6, 0xF0, 0xE2, 0x9C, 0x8E, 0xB8, 0xAA,
0x44, 0x56, 0x60, 0x72, 0x0C, 0x1E, 0x28, 0x3A,
0x4A, 0x58, 0x6E, 0x7C, 0x02, 0x10, 0x26, 0x34,
0xDA, 0xC8, 0xFE, 0xEC, 0x92, 0x80, 0xB6, 0xA4,
0x78, 0x6A, 0x5C, 0x4E, 0x30, 0x22, 0x14, 0x06,
0xE8, 0xFA, 0xCC, 0xDE, 0xA0, 0xB2, 0x84, 0x96,
0x2E, 0x3C, 0x0A, 0x18, 0x66, 0x74, 0x42, 0x50,
0xBE, 0xAC, 0x9A, 0x88, 0xF6, 0xE4, 0xD2, 0xC0,
0x1C, 0x0E, 0x38, 0x2A, 0x54, 0x46, 0x70, 0x62,
0x8C, 0x9C, 0xA8, 0xBA, 0xC4, 0xD6, 0xE0, 0xF2
};
static const uint16_t crc16_ccitt_table[256] =
{
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
};
static uint8_t calc_crc7(uint8_t *buff, uint8_t size);
static uint16_t calc_crc16(uint8_t *buff, uint16_t size);
sd_spi::sd_spi(hal::spi &spi, hal::gpio &cs, hal::gpio *cd):
sd(cd),
_spi(spi),
_cs(cs)
{
assert(_spi.cpol() == spi::CPOL_0);
assert(_spi.cpha() == spi::CPHA_0);
assert(_spi.bit_order() == spi::BIT_ORDER_MSB);
assert(_cs.mode() == gpio::mode::DO && cs.get());
}
sd_spi::~sd_spi()
{
}
void sd_spi::select(bool is_selected)
{
_cs.set(is_selected ? 0 : 1);
}
int8_t sd_spi::init_sd()
{
/* Send 80 pulses without cs */
uint8_t init_buff[8];
memset(init_buff, 0xFF, sizeof(init_buff));
if(_spi.write(init_buff, sizeof(init_buff)))
return RES_SPI_ERR;
return RES_OK;
}
void sd_spi::set_speed(uint32_t speed)
{
_spi.baud(speed);
}
int8_t sd_spi::send_cmd(cmd_t cmd, uint32_t arg, resp_t resp_type, uint8_t *resp)
{
int8_t res;
if(cmd != CMD12_STOP_TRANSMISSION)
{
res = wait_ready();
if(res)
return res;
}
uint8_t cmd_buff[6];
cmd_buff[0] = (cmd | (1 << TRANSMITTER_BIT)) & ~R1_START_BIT;
cmd_buff[1] = arg >> 24;
cmd_buff[2] = arg >> 16;
cmd_buff[3] = arg >> 8;
cmd_buff[4] = arg;
cmd_buff[5] = calc_crc7(cmd_buff, sizeof(cmd_buff) - 1);
if(_spi.write(cmd_buff, sizeof(cmd_buff)))
return RES_SPI_ERR;
uint8_t retry_cnt = WAIT_RESPONSE_CNT;
while(retry_cnt--)
{
resp[0] = 0xFF;
if(_spi.read(resp, 1))
return RES_SPI_ERR;
if(!(resp[0] & R1_START_BIT))
break;
}
if(!retry_cnt)
return RES_NO_RESPONSE;
switch(resp_type)
{
case R1:
break;
case R2:
res = read_data(&resp[1], 16);
if(res)
return res;
// Check the CSD or CID CRC7 (last byte):
// Raw CID CRC7 always has LSB set to 1,
//so fix it with CRC7_CID_CSD_MASK
if(calc_crc7(&resp[1], 15) != (resp[16] & CRC7_CID_CSD_MASK))
return RES_CRC_ERR;
break;
case R3:
case R6:
case R7:
memset(&resp[1], 0xFF, 4);
if(_spi.read(&resp[1], 4))
return RES_SPI_ERR;
}
return RES_OK;
}
int8_t sd_spi::read_data(void *data, uint16_t size)
{
uint8_t data_token;
uint8_t wait_cnt = 10;
while(wait_cnt--)
{
data_token = 0xFF;
if(_spi.read(&data_token, 1))
return RES_SPI_ERR;
if(data_token == DATA_TOKEN_CMD17_18_24)
break;
/* Check for error token */
if(!(data_token & ~ERR_TOKEN_MASK))
{
if(data_token & ERR_TOKEN_CARD_LOCKED)
return RES_LOCKED;
else if(data_token & ERR_TOKEN_OUT_OF_RANGE_ERR)
return RES_PARAM_ERR;
else if(data_token & ERR_TOKEN_ECC_FAIL)
return RES_READ_ERR;
else if(data_token & ERR_TOKEN_CC_ERR)
return RES_READ_ERR;
else if(data_token & ERR_TOKEN_ERR)
return RES_READ_ERR;
else
return RES_READ_ERR;
}
vTaskDelay(1);
}
if(!wait_cnt)
return RES_NO_RESPONSE;
memset(data, 0xFF, size);
if(_spi.read(data, size))
return RES_SPI_ERR;
uint8_t crc16[2] = {0xFF, 0xFF};
if(_spi.read(crc16, sizeof(crc16)))
return RES_SPI_ERR;
if(calc_crc16((uint8_t *)data, size) != ((crc16[0] << 8) | crc16[1]))
return RES_CRC_ERR;
return RES_OK;
}
int8_t sd_spi::write_data(void *data, uint16_t size)
{
if(_spi.write(DATA_TOKEN_CMD17_18_24))
return RES_SPI_ERR;
if(_spi.write(data, size))
return RES_SPI_ERR;
uint16_t crc16_tmp = calc_crc16((uint8_t *)data, size);
uint8_t crc16[2] = {(uint8_t)crc16_tmp, (uint8_t)(crc16_tmp << 8)};
if(_spi.write(crc16, sizeof(crc16)))
return RES_SPI_ERR;
/* Check data response */
uint8_t data_resp;
data_resp = 0xFF;
if(_spi.read(&data_resp, sizeof(data_resp)))
return RES_SPI_ERR;
if(!(data_resp & DATA_RESP_START_BIT) || (data_resp & DATA_RESP_END_BIT))
{
/* Data response is not valid */
return RES_WRITE_ERR;
}
switch(data_resp & DATA_RESP_MASK)
{
case DATA_RESP_ACCEPTED: break;
case DATA_RESP_CRC_ERR: return RES_CRC_ERR;
case DATA_RESP_WRITE_ERR:
default: return RES_WRITE_ERR;
}
return wait_ready();
}
int8_t sd_spi::wait_ready()
{
uint8_t busy_flag = 0;
uint16_t wait_cnt = 500;
while(wait_cnt--)
{
busy_flag = 0xFF;
if(_spi.read(&busy_flag, 1))
return RES_SPI_ERR;
if(busy_flag == 0xFF)
break;
vTaskDelay(1);
};
return wait_cnt ? RES_OK : RES_NO_RESPONSE;
}
static uint8_t calc_crc7(uint8_t *buff, uint8_t size)
{
uint8_t crc = 0;
while(size--)
crc = crc7_table[crc ^ *buff++];
return crc;
}
static uint16_t calc_crc16(uint8_t *buff, uint16_t size)
{
uint16_t crc = 0;
while(size--)
crc = (crc << 8) ^ crc16_ccitt_table[(crc >> 8) ^ *buff++];
return crc;
}
| 27.925595 | 81 | 0.685175 |
80e393e0915fb4f27ac5d70395ba2130857a7d8e | 261 | cpp | C++ | c++/factorial.cpp | ujwal475/Data-Structures-And-Algorithms | eab5d4b4011effac409cccde486280d8f8cebd32 | [
"MIT"
] | 26 | 2021-05-26T04:20:09.000Z | 2022-03-06T15:26:56.000Z | c++/factorial.cpp | ujwal475/Data-Structures-And-Algorithms | eab5d4b4011effac409cccde486280d8f8cebd32 | [
"MIT"
] | 47 | 2021-10-06T07:22:48.000Z | 2021-10-21T10:57:15.000Z | c++/factorial.cpp | ujwal475/Data-Structures-And-Algorithms | eab5d4b4011effac409cccde486280d8f8cebd32 | [
"MIT"
] | 61 | 2021-10-06T07:33:59.000Z | 2021-11-27T15:54:25.000Z | #include <iostream>
using namespace std;
int fact(int n){
int i=n;
while(n>1){
i = i*(n-1);
--n;
}
return i;
}
int main(){
int n;
cout << "Please enter a number:";
cin >> n;
cout << fact(n) << endl;
return 0;
} | 13.05 | 37 | 0.475096 |
80e3ea2d47c9b4227e4937d7cdcf9a6c8886b16c | 9,278 | cxx | C++ | panda/src/putil/typedWritable_ext.cxx | kestred/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | panda/src/putil/typedWritable_ext.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | panda/src/putil/typedWritable_ext.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | // Filename: typedWritable_ext.cxx
// Created by: rdb (10Dec13)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "typedWritable_ext.h"
#ifdef HAVE_PYTHON
#ifndef CPPPARSER
extern Dtool_PyTypedObject Dtool_BamWriter;
#endif // CPPPARSER
////////////////////////////////////////////////////////////////////
// Function: TypedWritable::__reduce__
// Access: Published
// Description: This special Python method is implement to provide
// support for the pickle module.
//
// This hooks into the native pickle and cPickle
// modules, but it cannot properly handle
// self-referential BAM objects.
////////////////////////////////////////////////////////////////////
PyObject *Extension<TypedWritable>::
__reduce__(PyObject *self) const {
return __reduce_persist__(self, NULL);
}
////////////////////////////////////////////////////////////////////
// Function: TypedWritable::__reduce_persist__
// Access: Published
// Description: This special Python method is implement to provide
// support for the pickle module.
//
// This is similar to __reduce__, but it provides
// additional support for the missing persistent-state
// object needed to properly support self-referential
// BAM objects written to the pickle stream. This hooks
// into the pickle and cPickle modules implemented in
// direct/src/stdpy.
////////////////////////////////////////////////////////////////////
PyObject *Extension<TypedWritable>::
__reduce_persist__(PyObject *self, PyObject *pickler) const {
// We should return at least a 2-tuple, (Class, (args)): the
// necessary class object whose constructor we should call
// (e.g. this), and the arguments necessary to reconstruct this
// object.
// Check that we have a decode_from_bam_stream python method. If not,
// we can't use this interface.
PyObject *method = PyObject_GetAttrString(self, "decode_from_bam_stream");
if (method == NULL) {
ostringstream stream;
stream << "Cannot pickle objects of type " << _this->get_type() << "\n";
string message = stream.str();
PyErr_SetString(PyExc_TypeError, message.c_str());
return NULL;
}
Py_DECREF(method);
BamWriter *writer = NULL;
if (pickler != NULL) {
PyObject *py_writer = PyObject_GetAttrString(pickler, "bamWriter");
if (py_writer == NULL) {
// It's OK if there's no bamWriter.
PyErr_Clear();
} else {
DTOOL_Call_ExtractThisPointerForType(py_writer, &Dtool_BamWriter, (void **)&writer);
Py_DECREF(py_writer);
}
}
// First, streamify the object, if possible.
string bam_stream;
if (!_this->encode_to_bam_stream(bam_stream, writer)) {
ostringstream stream;
stream << "Could not bamify object of type " << _this->get_type() << "\n";
string message = stream.str();
PyErr_SetString(PyExc_TypeError, message.c_str());
return NULL;
}
// Start by getting this class object.
PyObject *this_class = PyObject_Type(self);
if (this_class == NULL) {
return NULL;
}
PyObject *func;
if (writer != NULL) {
// The modified pickle support: call the "persistent" version of
// this function, which receives the unpickler itself as an
// additional parameter.
func = find_global_decode(this_class, "py_decode_TypedWritable_from_bam_stream_persist");
if (func == NULL) {
PyErr_SetString(PyExc_TypeError, "Couldn't find py_decode_TypedWritable_from_bam_stream_persist()");
Py_DECREF(this_class);
return NULL;
}
} else {
// The traditional pickle support: call the non-persistent version
// of this function.
func = find_global_decode(this_class, "py_decode_TypedWritable_from_bam_stream");
if (func == NULL) {
PyErr_SetString(PyExc_TypeError, "Couldn't find py_decode_TypedWritable_from_bam_stream()");
Py_DECREF(this_class);
return NULL;
}
}
PyObject *result = Py_BuildValue("(O(Os#))", func, this_class, bam_stream.data(), (Py_ssize_t) bam_stream.size());
Py_DECREF(func);
Py_DECREF(this_class);
return result;
}
////////////////////////////////////////////////////////////////////
// Function: TypedWritable::find_global_decode
// Access: Public, Static
// Description: This is a support function for __reduce__(). It
// searches for the global function
// py_decode_TypedWritable_from_bam_stream() in this
// class's module, or in the module for any base class.
// (It's really looking for the libpanda module, but we
// can't be sure what name that module was loaded under,
// so we search upwards this way.)
//
// Returns: new reference on success, or NULL on failure.
////////////////////////////////////////////////////////////////////
PyObject *Extension<TypedWritable>::
find_global_decode(PyObject *this_class, const char *func_name) {
PyObject *module_name = PyObject_GetAttrString(this_class, "__module__");
if (module_name != NULL) {
// borrowed reference
PyObject *sys_modules = PyImport_GetModuleDict();
if (sys_modules != NULL) {
// borrowed reference
PyObject *module = PyDict_GetItem(sys_modules, module_name);
if (module != NULL) {
PyObject *func = PyObject_GetAttrString(module, (char *)func_name);
if (func != NULL) {
Py_DECREF(module_name);
return func;
}
}
}
}
Py_DECREF(module_name);
PyObject *bases = PyObject_GetAttrString(this_class, "__bases__");
if (bases != NULL) {
if (PySequence_Check(bases)) {
Py_ssize_t size = PySequence_Size(bases);
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject *base = PySequence_GetItem(bases, i);
if (base != NULL) {
PyObject *func = find_global_decode(base, func_name);
Py_DECREF(base);
if (func != NULL) {
Py_DECREF(bases);
return func;
}
}
}
}
Py_DECREF(bases);
}
return NULL;
}
////////////////////////////////////////////////////////////////////
// Function: py_decode_TypedWritable_from_bam_stream
// Access: Published
// Description: This wrapper is defined as a global function to suit
// pickle's needs.
//
// This hooks into the native pickle and cPickle
// modules, but it cannot properly handle
// self-referential BAM objects.
////////////////////////////////////////////////////////////////////
PyObject *
py_decode_TypedWritable_from_bam_stream(PyObject *this_class, const string &data) {
return py_decode_TypedWritable_from_bam_stream_persist(NULL, this_class, data);
}
////////////////////////////////////////////////////////////////////
// Function: py_decode_TypedWritable_from_bam_stream_persist
// Access: Published
// Description: This wrapper is defined as a global function to suit
// pickle's needs.
//
// This is similar to
// py_decode_TypedWritable_from_bam_stream, but it
// provides additional support for the missing
// persistent-state object needed to properly support
// self-referential BAM objects written to the pickle
// stream. This hooks into the pickle and cPickle
// modules implemented in direct/src/stdpy.
////////////////////////////////////////////////////////////////////
PyObject *
py_decode_TypedWritable_from_bam_stream_persist(PyObject *pickler, PyObject *this_class, const string &data) {
PyObject *py_reader = NULL;
if (pickler != NULL) {
py_reader = PyObject_GetAttrString(pickler, "bamReader");
if (py_reader == NULL) {
// It's OK if there's no bamReader.
PyErr_Clear();
}
}
// We need the function PandaNode::decode_from_bam_stream or
// TypedWritableReferenceCount::decode_from_bam_stream, which
// invokes the BamReader to reconstruct this object. Since we use
// the specific object's class as the pointer, we get the particular
// instance of decode_from_bam_stream appropriate to this class.
PyObject *func = PyObject_GetAttrString(this_class, "decode_from_bam_stream");
if (func == NULL) {
return NULL;
}
PyObject *result;
if (py_reader != NULL){
result = PyObject_CallFunction(func, (char *)"(s#O)", data.data(), (Py_ssize_t) data.size(), py_reader);
Py_DECREF(py_reader);
} else {
result = PyObject_CallFunction(func, (char *)"(s#)", data.data(), (Py_ssize_t) data.size());
}
if (result == NULL) {
return NULL;
}
if (result == Py_None) {
Py_DECREF(result);
PyErr_SetString(PyExc_ValueError, "Could not unpack bam stream");
return NULL;
}
return result;
}
#endif
| 36.101167 | 116 | 0.604656 |
80e4db6830eb49c5da5e145f6b0ede663193c0df | 1,688 | cpp | C++ | tests/graph/traversal/discovered_flag.cpp | AlCash07/ACTL | 15de4e2783d8e39dbd8e10cd635aaab328ca4f5b | [
"BSL-1.0"
] | 17 | 2018-08-22T06:48:20.000Z | 2022-02-22T21:20:09.000Z | tests/graph/traversal/discovered_flag.cpp | AlCash07/ACTL | 15de4e2783d8e39dbd8e10cd635aaab328ca4f5b | [
"BSL-1.0"
] | null | null | null | tests/graph/traversal/discovered_flag.cpp | AlCash07/ACTL | 15de4e2783d8e39dbd8e10cd635aaab328ca4f5b | [
"BSL-1.0"
] | null | null | null | // Copyright 2018 Oleksandr Bacherikov.
//
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#include <actl/graph/default_map.hpp>
#include <actl/graph/traversal/breadth_first_search.hpp>
#include <actl/graph/traversal/depth_first_search.hpp>
#include <actl/graph/traversal/discovered_flag.hpp>
#include "graph/sample_graphs.hpp"
#include "map/logging_map.hpp"
#include "test.hpp"
using Log = std::vector<std::pair<int, bool>>;
TEST_CASE("discovered_flag bfs")
{
auto graph = sample_undirected_graph();
Log log;
auto map = logging_map{
make_default_vertex_map<bool>(graph), std::back_inserter(log)};
breadth_first_search{discovered_flag{map}}(graph, 0);
CHECK(
Log{
{0, false},
{1, false},
{2, false},
{3, false},
{4, false},
{5, false},
{0, true},
{1, true},
{3, true},
{2, true},
{4, true},
{5, true},
} == log);
}
TEST_CASE("discovered_flag dfs")
{
auto graph = sample_undirected_graph();
Log log;
auto map = logging_map{
make_default_vertex_map<bool>(graph), std::back_inserter(log)};
depth_first_search{discovered_flag{map}}(graph, 0);
CHECK(
Log{
{0, false},
{1, false},
{2, false},
{3, false},
{4, false},
{5, false},
{0, true},
{1, true},
{2, true},
{3, true},
{4, true},
{5, true},
} == log);
}
| 26.375 | 71 | 0.543839 |
80e670f7c00b65cb090fa7cd8b7eb8eed5df787c | 33,813 | cpp | C++ | indires_macro_actions/src/Indires_macro_actions.cpp | Tutorgaming/indires_navigation | 830097ac0a3e3a64da9026518419939b509bbe71 | [
"BSD-3-Clause"
] | 90 | 2019-07-19T13:44:35.000Z | 2022-02-17T21:39:15.000Z | indires_macro_actions/src/Indires_macro_actions.cpp | Tutorgaming/indires_navigation | 830097ac0a3e3a64da9026518419939b509bbe71 | [
"BSD-3-Clause"
] | 13 | 2019-12-02T07:32:18.000Z | 2021-08-10T09:38:44.000Z | indires_macro_actions/src/Indires_macro_actions.cpp | Tutorgaming/indires_navigation | 830097ac0a3e3a64da9026518419939b509bbe71 | [
"BSD-3-Clause"
] | 26 | 2019-05-27T14:43:43.000Z | 2022-02-17T21:39:19.000Z | #include <indires_macro_actions/Indires_macro_actions.h>
/*
Status can take this values:
uint8 PENDING = 0 # The goal has yet to be processed by the action server
uint8 ACTIVE = 1 # The goal is currently being processed by the action server
uint8 PREEMPTED = 2 # The goal received a cancel request after it started
executing
# and has since completed its execution (Terminal State)
uint8 SUCCEEDED = 3 # The goal was achieved successfully by the action server
(Terminal State)
uint8 ABORTED = 4 # The goal was aborted during execution by the action server
due
# to some failure (Terminal State)
uint8 REJECTED = 5 # The goal was rejected by the action server without being
processed,
# because the goal was unattainable or invalid (Terminal
State)
uint8 PREEMPTING = 6 # The goal received a cancel request after it started
executing
# and has not yet completed execution
uint8 RECALLING = 7 # The goal received a cancel request before it started
executing,
# but the action server has not yet confirmed that the goal
is canceled
uint8 RECALLED = 8 # The goal received a cancel request before it started
executing
# and was successfully cancelled (Terminal State)
uint8 LOST = 9 # An action client can determine that a goal is LOST. This
should not be
# sent over the wire by an action server
*/
// namespace macroactions {
Indires_macro_actions::Indires_macro_actions(tf2_ros::Buffer* tf)
{
tf_ = tf;
// UpoNav_ = nav;
ros::NodeHandle n("~");
// Dynamic reconfigure
// dsrv_ = new
// dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig>(n);
// dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig>::CallbackType
// cb = boost::bind(&Upo_navigation_macro_actions::reconfigureCB, this, _1, _2);
// dsrv_->setCallback(cb);
n.param<double>("secs_to_check_block", secs_to_check_block_, 5.0); // seconds
n.param<double>("block_dist", block_dist_, 0.4); // meters
// n.param<double>("secs_to_wait", secs_to_wait_, 8.0); //seconds
n.param<double>("control_frequency", control_frequency_, 15.0);
std::string odom_topic = "";
n.param<std::string>("odom_topic", odom_topic, "odom");
manual_control_ = false;
// Dynamic reconfigure
// dsrv_ = new
// dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig>(n);
// dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig>::CallbackType
// cb = boost::bind(&Upo_navigation_macro_actions::reconfigureCB, this, _1, _2);
// dsrv_->setCallback(cb);
ros::NodeHandle nh;
rrtgoal_sub_ = nh.subscribe<geometry_msgs::PoseStamped>(
"/rrt_goal", 1, &Indires_macro_actions::rrtGoalCallback, this);
pose_sub_ = nh.subscribe<nav_msgs::Odometry>(
odom_topic.c_str(), 1, &Indires_macro_actions::robotPoseCallback, this);
// Services for walking side by side
// start_client_ = nh.serviceClient<teresa_wsbs::start>("/wsbs/start");
// stop_client_ = nh.serviceClient<teresa_wsbs::stop>("/wsbs/stop");
// wsbs_status_sub_ = nh.subscribe<std_msgs::UInt8>("/wsbs/status", 1,
// &Upo_navigation_macro_actions::wsbsCallback, this);
moveBaseClient_ =
new moveBaseClient("move_base", true); // true-> do not need ros::spin()
ROS_INFO("Waiting for action server to start...");
moveBaseClient_->waitForServer();
ROS_INFO("Action server connected!");
// Initialize action servers
NWActionServer_ = new NWActionServer(
nh1_, "NavigateWaypoint",
boost::bind(&Indires_macro_actions::navigateWaypointCB, this, _1), false);
NHActionServer_ = new NHActionServer(
nh2_, "NavigateHome", boost::bind(&Indires_macro_actions::navigateHomeCB, this, _1), false);
ExActionServer_ = new ExActionServer(
nh3_, "Exploration", boost::bind(&Indires_macro_actions::explorationCB, this, _1), false);
TOActionServer_ =
new TOActionServer(nh4_, "Teleoperation",
boost::bind(&Indires_macro_actions::teleoperationCB, this, _1), false);
NWActionServer_->start();
NHActionServer_->start();
ExActionServer_->start();
TOActionServer_->start();
// ros::NodeHandle nodeh("~/RRT_ros_wrapper");
// nodeh.getParam("full_path_stddev", initial_stddev_);
}
Indires_macro_actions::~Indires_macro_actions()
{
if (NWActionServer_)
delete NWActionServer_;
if (NHActionServer_)
delete NHActionServer_;
if (ExActionServer_)
delete ExActionServer_;
if (TOActionServer_)
delete TOActionServer_;
// if(UpoNav_)
// delete UpoNav_;
// if(dsrv_)
// delete dsrv_;
}
/*
void
Upo_navigation_macro_actions::reconfigureCB(upo_navigation_macro_actions::NavigationMacroActionsConfig
&config, uint32_t level){
boost::recursive_mutex::scoped_lock l(configuration_mutex_);
control_frequency_ = config.control_frequency;
secs_to_check_block_ = config.secs_to_check_block;
block_dist_ = config.block_dist;
secs_to_wait_ = config.secs_to_wait;
social_approaching_type_ = config.social_approaching_type;
secs_to_yield_ = config.secs_to_yield;
//use_leds_ = config.use_leds;
//leds_number_ = config.leds_number;
}*/
/*
//Receive feedback messages from upo_navigation
void Upo_navigation_macro_actions::feedbackReceived(const
move_base_msgs::MoveBaseActionFeedback::ConstPtr& msg) {
pose_mutex_.lock();
robot_pose_ = msg->feedback.base_position;
pose_mutex_.unlock();
if((unsigned int)(std::string(robot_pose_.header.frame_id).size()) < 3)
robot_pose_.header.frame_id = "map";
}
//Receive status messages from upo_navigation
void Upo_navigation_macro_actions::statusReceived(const
actionlib_msgs::GoalStatusArray::ConstPtr& msg)
{
unsigned int actions = msg->status_list.size();
if(actions != 0)
{
status_mutex_.lock();
nav_status_ = msg->status_list.at(0).status;
nav_text_ = msg->status_list.at(0).text;
goal_id_ = msg->status_list.at(0).goal_id.id;
status_mutex_.unlock();
} else {
status_mutex_.lock();
nav_status_ = -1;
nav_text_ = " ";
goal_id_ = " ";
status_mutex_.unlock();
}
}
//This topic publishes only when the action finishes (because of reaching the goal or
cancelation)
void Upo_navigation_macro_actions::resultReceived(const
move_base_msgs::MoveBaseActionResult::ConstPtr& msg)
{
action_end_ = true;
}*/
/*
MoveBase server:
-----------------
Action Subscribed topics:
move_base/goal [move_base_msgs::MoveBaseActionGoal]
move_base/cancel [actionlib_msgs::GoalID]
Action Published topcis:
move_base/feedback [move_base_msgs::MoveBaseActionFeedback]
move_base/status [actionlib_msgs::GoalStatusArray]
move_base/result [move_base_msgs::MoveBaseAcionResult]
*/
void Indires_macro_actions::navigateWaypointCB(
const indires_macro_actions::NavigateWaypointGoal::ConstPtr& goal)
{
printf("¡¡¡¡¡¡¡MacroAction navigatetoWaypoint --> started!!!!!!\n");
// printf("Goal x: %.2f, y: %.2f frame: %s\n", goal->target_pose.pose.position.x,
// goal->target_pose.pose.position.y, goal->target_pose.header.frame_id.c_str());
// UpoNav_->stopRRTPlanning();
move_base_msgs::MoveBaseGoal g;
g.target_pose = goal->target_pose;
moveBaseClient_->sendGoal(g);
// moveBaseClient_->waitForResult();
actionlib::SimpleClientGoalState state = moveBaseClient_->getState();
// moveBaseClient_->cancelAllGoals()
// moveBaseClient_->cancelGoal()
// moveBaseClient_->getResult()
if (moveBaseClient_->getState() == actionlib::SimpleClientGoalState::SUCCEEDED)
{
ROS_INFO("Success!!!");
} /*else {
ROS_INFO("Failed!");
}*/
/*bool ok = UpoNav_->executeNavigation(goal->target_pose);
if(!ok)
{
ROS_INFO("Setting ABORTED state 1");
nwresult_.result = "Aborted. Navigation error";
nwresult_.value = 2;
NWActionServer_->setAborted(nwresult_, "Navigation aborted");
//UpoNav_->stopRRTPlanning();
return;
}*/
ros::Rate r(control_frequency_);
// int pursue_status = 0;
bool exit = false;
ros::Time time_init = ros::Time::now();
bool first = true;
nav_msgs::Odometry pose_init;
// ros::WallTime startt;
while (nh1_.ok())
{
// startt = ros::WallTime::now();
if (NWActionServer_->isPreemptRequested())
{
if (NWActionServer_->isNewGoalAvailable())
{
indires_macro_actions::NavigateWaypointGoal new_goal =
*NWActionServer_->acceptNewGoal();
g.target_pose = new_goal.target_pose;
moveBaseClient_->sendGoal(g);
/*bool ok = UpoNav_->executeNavigation(new_goal.target_pose);
if(!ok) {
ROS_INFO("Setting ABORTED state 1");
nwresult_.result = "Aborted. Navigation error";
nwresult_.value = 2;
NWActionServer_->setAborted(nwresult_, "Navigation aborted");
UpoNav_->stopRRTPlanning();
if(use_leds_)
setLedColor(WHITE);
return;
}*/
first = true;
}
else
{
// if we've been preempted explicitly we need to shut things down
// UpoNav_->resetState();
// Cancel?????
// notify the ActionServer that we've successfully preempted
nwresult_.result = "Preempted";
nwresult_.value = 1;
ROS_DEBUG_NAMED("indires_macro_actions", "indires_navigation preempting the current goal");
NWActionServer_->setPreempted(nwresult_, "Navigation preempted");
// we'll actually return from execute after preempting
return;
}
}
pose_mutex_.lock();
nav_msgs::Odometry new_pose = odom_pose_;
pose_mutex_.unlock();
// pursue_status = UpoNav_->pathFollow(new_pose);
// Posible states:
// PENDING, ACTIVE, RECALLED, REJECTED, PREEMPTED, ABORTED, SUCCEEDED, LOST
actionlib::SimpleClientGoalState state = moveBaseClient_->getState();
if (first)
{
pose_init = new_pose;
time_init = ros::Time::now();
first = false;
}
if (state == actionlib::SimpleClientGoalState::SUCCEEDED)
{
// Goal reached
ROS_INFO("Setting SUCCEEDED state");
nwresult_.result = "Navigation succeeded";
nwresult_.value = 0;
NWActionServer_->setSucceeded(nwresult_, "Goal Reached");
nwfeedback_.text = "Succeeded";
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::ACTIVE)
{
// Goal not reached, continue navigating
nwfeedback_.text = "Navigating";
}
else if (state == actionlib::SimpleClientGoalState::ABORTED)
{
// Aborted
nwfeedback_.text = "Aborted";
ROS_INFO("Setting ABORTED state");
nwresult_.result = "Aborted";
nwresult_.value = 3;
NWActionServer_->setAborted(nwresult_, "Navigation aborted");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::PENDING)
{
nwfeedback_.text = "Pending";
// ROS_INFO("Setting ABORTED state");
// nwresult_.result = "";
// nwresult_.value = 3;
// NWActionServer_->setAborted(nwresult_, "Navigation aborted");
// exit = true;
}
else if (state == actionlib::SimpleClientGoalState::RECALLED)
{
nwfeedback_.text = "Recalled";
}
else if (state == actionlib::SimpleClientGoalState::REJECTED)
{
// Rejected
nwfeedback_.text = "Rejected";
ROS_INFO("Setting ABORTED (rejected) state");
nwresult_.result = "Rejected";
nwresult_.value = 3;
NWActionServer_->setAborted(nwresult_, "Navigation aborted(rejected)");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::LOST)
{
// Rejected
nwfeedback_.text = "Lost";
ROS_INFO("Setting ABORTED (lost) state");
nwresult_.result = "Lost";
nwresult_.value = 3;
NWActionServer_->setAborted(nwresult_, "Navigation aborted(lost)");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::PREEMPTED)
{
nwfeedback_.text = "Preempted";
}
// push the feedback out
geometry_msgs::PoseStamped aux;
aux.header = new_pose.header;
aux.pose.position = new_pose.pose.pose.position;
aux.pose.orientation = new_pose.pose.pose.orientation;
nwfeedback_.base_position = aux;
NWActionServer_->publishFeedback(nwfeedback_);
if (exit)
{
// UpoNav_->stopRRTPlanning();
return;
}
// check the blocked situation.
double time = (ros::Time::now() - time_init).toSec();
// printf("now: %.2f, init: %.2f, time: %.2f secs\n", ros::Time::now().toSec(),
// time_init.toSec(), time);
if (time > secs_to_check_block_)
{
double xinit = pose_init.pose.pose.position.x;
double yinit = pose_init.pose.pose.position.y;
double hinit = tf::getYaw(pose_init.pose.pose.orientation);
double xnow = new_pose.pose.pose.position.x;
double ynow = new_pose.pose.pose.position.y;
double hnow = tf::getYaw(new_pose.pose.pose.orientation);
double dist = sqrt(pow((xinit - xnow), 2) + pow((yinit - ynow), 2));
double yaw_diff = fabs(angles::shortest_angular_distance(hnow, hinit));
// printf("dist: %.2f, yaw_diff: %.2f\n", dist, yaw_diff);
if (dist <= block_dist_ && yaw_diff < 0.79)
{ // 0.79 = 45º
ROS_INFO("Setting ABORTED state because of blocked situation");
nwresult_.result = "Aborted. Blocked situation";
nwresult_.value = 5;
NWActionServer_->setAborted(nwresult_, "Navigation aborted. blocked");
nwfeedback_.text = "Blocked";
NWActionServer_->publishFeedback(nwfeedback_);
// UpoNav_->stopRRTPlanning();
return;
}
else
{
pose_init = new_pose;
time_init = ros::Time::now();
}
}
// ros::WallDuration dur = ros::WallTime::now() - startt;
// printf("Loop time: %.4f secs\n", dur.toSec());
r.sleep();
}
ROS_INFO("Setting ABORTED state");
nwresult_.result = "Aborted. System is shuting down";
nwresult_.value = 6;
NWActionServer_->setAborted(nwresult_, "Navigation aborted because the node has been killed");
}
void Indires_macro_actions::navigateHomeCB(const indires_macro_actions::NavigateHomeGoal::ConstPtr& goal)
{
printf("¡¡¡¡¡¡¡MacroAction NavigateHome --> started!!!!!!\n");
// printf("Goal x: %.2f, y: %.2f frame: %s\n", goal->home_pose.pose.position.x,
// goal->home_pose.pose.position.y, goal->home_pose.header.frame_id.c_str());
// UpoNav_->stopRRTPlanning();
// boost::recursive_mutex::scoped_lock l(configuration_mutex_);
// Put the goal to map origin???
move_base_msgs::MoveBaseGoal g;
g.target_pose = goal->home_pose;
moveBaseClient_->sendGoal(g);
ros::Rate r(control_frequency_);
// int pursue_status = 0;
bool exit = false;
ros::Time time_init = ros::Time::now();
bool first = true;
nav_msgs::Odometry pose_init;
while (nh2_.ok())
{
// startt = ros::WallTime::now();
if (NHActionServer_->isPreemptRequested())
{
if (NHActionServer_->isNewGoalAvailable())
{
indires_macro_actions::NavigateHomeGoal new_goal = *NHActionServer_->acceptNewGoal();
g.target_pose = new_goal.home_pose;
moveBaseClient_->sendGoal(g);
first = true;
}
else
{
// if we've been preempted explicitly we need to shut things down
// UpoNav_->resetState();
// notify the ActionServer that we've successfully preempted
ROS_DEBUG_NAMED("indires_macro_actions", "indires_navigation preempting the current goal");
nhresult_.result = "Preempted";
nhresult_.value = 1;
NHActionServer_->setPreempted(nhresult_, "Navigation preempted");
// we'll actually return from execute after preempting
return;
}
}
pose_mutex_.lock();
nav_msgs::Odometry new_pose = odom_pose_;
pose_mutex_.unlock();
// pursue_status = UpoNav_->pathFollow(new_pose);
// Posible states:
// PENDING, ACTIVE, RECALLED, REJECTED, PREEMPTED, ABORTED, SUCCEEDED, LOST
actionlib::SimpleClientGoalState state = moveBaseClient_->getState();
if (first)
{
pose_init = new_pose;
time_init = ros::Time::now();
first = false;
}
if (state == actionlib::SimpleClientGoalState::SUCCEEDED)
{
// Goal reached
ROS_INFO("Setting SUCCEEDED state");
nhresult_.result = "Navigation succeeded";
nhresult_.value = 0;
NHActionServer_->setSucceeded(nhresult_, "Goal Reached");
nhfeedback_.text = "Succeeded";
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::ACTIVE)
{
// Goal not reached, continue navigating
nhfeedback_.text = "Navigating";
}
else if (state == actionlib::SimpleClientGoalState::ABORTED)
{
// Aborted
nhfeedback_.text = "Aborted";
ROS_INFO("Setting ABORTED state");
nhresult_.result = "Aborted";
nhresult_.value = 3;
NHActionServer_->setAborted(nhresult_, "Navigation aborted");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::PENDING)
{
nhfeedback_.text = "Pending";
// ROS_INFO("Setting ABORTED state");
// nwresult_.result = "";
// nwresult_.value = 3;
// NWActionServer_->setAborted(nwresult_, "Navigation aborted");
// exit = true;
}
else if (state == actionlib::SimpleClientGoalState::RECALLED)
{
nhfeedback_.text = "Recalled";
}
else if (state == actionlib::SimpleClientGoalState::REJECTED)
{
// Rejected
nhfeedback_.text = "Rejected";
ROS_INFO("Setting ABORTED (rejected) state");
nhresult_.result = "Rejected";
nhresult_.value = 3;
NHActionServer_->setAborted(nhresult_, "Navigation aborted(rejected)");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::LOST)
{
// Rejected
nhfeedback_.text = "Lost";
ROS_INFO("Setting ABORTED (lost) state");
nhresult_.result = "Lost";
nhresult_.value = 3;
NHActionServer_->setAborted(nhresult_, "Navigation aborted(lost)");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::PREEMPTED)
{
nhfeedback_.text = "Preempted";
}
// push the feedback out
geometry_msgs::PoseStamped aux;
aux.header = new_pose.header;
aux.pose.position = new_pose.pose.pose.position;
aux.pose.orientation = new_pose.pose.pose.orientation;
nhfeedback_.base_position = aux;
NHActionServer_->publishFeedback(nhfeedback_);
if (exit)
{
// UpoNav_->stopRRTPlanning();
return;
}
// check the blocked situation.
double time = (ros::Time::now() - time_init).toSec();
// printf("now: %.2f, init: %.2f, time: %.2f secs\n", ros::Time::now().toSec(),
// time_init.toSec(), time);
if (time > secs_to_check_block_)
{
double xinit = pose_init.pose.pose.position.x;
double yinit = pose_init.pose.pose.position.y;
double hinit = tf::getYaw(pose_init.pose.pose.orientation);
double xnow = new_pose.pose.pose.position.x;
double ynow = new_pose.pose.pose.position.y;
double hnow = tf::getYaw(new_pose.pose.pose.orientation);
double dist = sqrt(pow((xinit - xnow), 2) + pow((yinit - ynow), 2));
double yaw_diff = fabs(angles::shortest_angular_distance(hnow, hinit));
// printf("dist: %.2f, yaw_diff: %.2f\n", dist, yaw_diff);
if (dist <= block_dist_ && yaw_diff < 0.79)
{ // 0.79 = 45º
ROS_INFO("Setting ABORTED state because of blocked situation");
nhresult_.result = "Aborted. Blocked situation";
nhresult_.value = 5;
NHActionServer_->setAborted(nhresult_, "Navigation aborted. blocked");
nhfeedback_.text = "Blocked";
NHActionServer_->publishFeedback(nhfeedback_);
// UpoNav_->stopRRTPlanning();
return;
}
else
{
pose_init = new_pose;
time_init = ros::Time::now();
}
}
// ros::WallDuration dur = ros::WallTime::now() - startt;
// printf("Loop time: %.4f secs\n", dur.toSec());
r.sleep();
}
ROS_INFO("Setting ABORTED state");
nhresult_.result = "Aborted. system is shuting down";
nhresult_.value = 6;
NHActionServer_->setAborted(nhresult_, "Navigation aborted because the node has been killed");
}
void Indires_macro_actions::explorationCB(const indires_macro_actions::ExplorationGoal::ConstPtr& goal)
{
printf("¡¡¡¡¡¡¡MacroAction Exploration --> started!!!!!!\n");
// printf("Goal x: %.2f, y: %.2f frame: %s\n", goal->target_pose.pose.position.x,
// goal->target_pose.pose.position.y, goal->target_pose.header.frame_id.c_str());
// UpoNav_->stopRRTPlanning();
move_base_msgs::MoveBaseGoal g;
g.target_pose = goal->empty;
g.target_pose.header.frame_id = "";
g.target_pose.pose.orientation.x = 0.0;
g.target_pose.pose.orientation.y = 0.0;
g.target_pose.pose.orientation.z = 0.0;
g.target_pose.pose.orientation.w = 1.0;
moveBaseClient_->sendGoal(g);
// moveBaseClient_->waitForResult();
actionlib::SimpleClientGoalState state = moveBaseClient_->getState();
// moveBaseClient_->cancelAllGoals()
// moveBaseClient_->cancelGoal()
// moveBaseClient_->getResult()
if (moveBaseClient_->getState() == actionlib::SimpleClientGoalState::SUCCEEDED)
{
ROS_INFO("Success!!!");
} /*else {
ROS_INFO("Failed!");
}*/
/*bool ok = UpoNav_->executeNavigation(goal->target_pose);
if(!ok)
{
ROS_INFO("Setting ABORTED state 1");
nwresult_.result = "Aborted. Navigation error";
nwresult_.value = 2;
NWActionServer_->setAborted(nwresult_, "Navigation aborted");
//UpoNav_->stopRRTPlanning();
return;
}*/
ros::Rate r(control_frequency_);
// int pursue_status = 0;
bool exit = false;
ros::Time time_init = ros::Time::now();
bool first = true;
nav_msgs::Odometry pose_init;
// ros::WallTime startt;
while (nh3_.ok())
{
// startt = ros::WallTime::now();
if (ExActionServer_->isPreemptRequested())
{
if (ExActionServer_->isNewGoalAvailable())
{
indires_macro_actions::ExplorationGoal new_goal = *ExActionServer_->acceptNewGoal();
g.target_pose = new_goal.empty;
moveBaseClient_->sendGoal(g);
/*bool ok = UpoNav_->executeNavigation(new_goal.target_pose);
if(!ok) {
ROS_INFO("Setting ABORTED state 1");
nwresult_.result = "Aborted. Navigation error";
nwresult_.value = 2;
NWActionServer_->setAborted(nwresult_, "Navigation aborted");
UpoNav_->stopRRTPlanning();
if(use_leds_)
setLedColor(WHITE);
return;
}*/
first = true;
}
else
{
// if we've been preempted explicitly we need to shut things down
// UpoNav_->resetState();
// Cancel?????
// notify the ActionServer that we've successfully preempted
exresult_.result = "Preempted";
exresult_.value = 1;
ROS_DEBUG_NAMED("indires_macro_actions", "indires_exploration preempting the current goal");
ExActionServer_->setPreempted(exresult_, "Exploration preempted");
// we'll actually return from execute after preempting
return;
}
}
pose_mutex_.lock();
nav_msgs::Odometry new_pose = odom_pose_;
pose_mutex_.unlock();
// pursue_status = UpoNav_->pathFollow(new_pose);
// Posible states:
// PENDING, ACTIVE, RECALLED, REJECTED, PREEMPTED, ABORTED, SUCCEEDED, LOST
state = moveBaseClient_->getState();
if (first)
{
pose_init = new_pose;
time_init = ros::Time::now();
first = false;
}
if (state == actionlib::SimpleClientGoalState::SUCCEEDED)
{
// Goal reached
// WE MUST TO CONTINUE THE EXPLORATION
ROS_INFO("Goal reached. Exploration continues...");
// exresult_.result = "Exploration succeeded";
// exresult_.value = 0;
// ExActionServer_->setSucceeded(exresult_, "Goal Reached");
// exfeedback_.text = "Succeeded";
// exit = true;
exfeedback_.text = "goal reached. Exploration continues";
moveBaseClient_->sendGoal(g);
}
else if (state == actionlib::SimpleClientGoalState::ACTIVE)
{
// Goal not reached, continue navigating
exfeedback_.text = "Navigating";
}
else if (state == actionlib::SimpleClientGoalState::ABORTED)
{
// Aborted
exfeedback_.text = "Aborted";
ROS_INFO("Setting ABORTED state");
exresult_.result = "Aborted";
exresult_.value = 3;
ExActionServer_->setAborted(exresult_, "Exploration aborted");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::PENDING)
{
exfeedback_.text = "Pending";
// ROS_INFO("Setting ABORTED state");
// nwresult_.result = "";
// nwresult_.value = 3;
// NWActionServer_->setAborted(nwresult_, "Navigation aborted");
// exit = true;
}
else if (state == actionlib::SimpleClientGoalState::RECALLED)
{
exfeedback_.text = "Recalled";
}
else if (state == actionlib::SimpleClientGoalState::REJECTED)
{
// Rejected
exfeedback_.text = "Rejected";
ROS_INFO("Setting ABORTED (rejected) state");
exresult_.result = "Rejected";
exresult_.value = 3;
ExActionServer_->setAborted(exresult_, "Exploration aborted(rejected)");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::LOST)
{
// Rejected
exfeedback_.text = "Lost";
ROS_INFO("Setting ABORTED (lost) state");
exresult_.result = "Lost";
exresult_.value = 3;
ExActionServer_->setAborted(exresult_, "Exploration aborted(lost)");
exit = true;
}
else if (state == actionlib::SimpleClientGoalState::PREEMPTED)
{
nwfeedback_.text = "Preempted";
}
// push the feedback out
geometry_msgs::PoseStamped aux;
aux.header = new_pose.header;
aux.pose.position = new_pose.pose.pose.position;
aux.pose.orientation = new_pose.pose.pose.orientation;
exfeedback_.base_position = aux;
ExActionServer_->publishFeedback(exfeedback_);
if (exit)
{
// UpoNav_->stopRRTPlanning();
return;
}
// check the blocked situation.
double time = (ros::Time::now() - time_init).toSec();
// printf("now: %.2f, init: %.2f, time: %.2f secs\n", ros::Time::now().toSec(),
// time_init.toSec(), time);
if (time > secs_to_check_block_)
{
double xinit = pose_init.pose.pose.position.x;
double yinit = pose_init.pose.pose.position.y;
double hinit = tf::getYaw(pose_init.pose.pose.orientation);
double xnow = new_pose.pose.pose.position.x;
double ynow = new_pose.pose.pose.position.y;
double hnow = tf::getYaw(new_pose.pose.pose.orientation);
double dist = sqrt(pow((xinit - xnow), 2) + pow((yinit - ynow), 2));
double yaw_diff = fabs(angles::shortest_angular_distance(hnow, hinit));
// printf("dist: %.2f, yaw_diff: %.2f\n", dist, yaw_diff);
if (dist <= block_dist_ && yaw_diff < 0.79)
{ // 0.79 = 45º
ROS_INFO("Setting ABORTED state because of blocked situation");
exresult_.result = "Aborted. Blocked situation";
exresult_.value = 5;
ExActionServer_->setAborted(exresult_, "Exploration aborted. blocked");
exfeedback_.text = "Blocked";
ExActionServer_->publishFeedback(exfeedback_);
// UpoNav_->stopRRTPlanning();
return;
}
else
{
pose_init = new_pose;
time_init = ros::Time::now();
}
}
// ros::WallDuration dur = ros::WallTime::now() - startt;
// printf("Loop time: %.4f secs\n", dur.toSec());
r.sleep();
}
ROS_INFO("Setting ABORTED state");
exresult_.result = "Aborted. System is shuting down";
exresult_.value = 6;
ExActionServer_->setAborted(exresult_, "Exploration aborted because the node has been killed");
}
/*
bool Indires_macro_actions::reconfigureParameters(std::string node, std::string
param_name, std::string value, const datatype type)
{
//printf("RECONFIGURE PARAMETERS METHOD\n");
dynamic_reconfigure::ReconfigureRequest srv_req;
dynamic_reconfigure::ReconfigureResponse srv_resp;
dynamic_reconfigure::IntParameter param1;
dynamic_reconfigure::BoolParameter param2;
dynamic_reconfigure::DoubleParameter param3;
dynamic_reconfigure::StrParameter param4;
dynamic_reconfigure::Config conf;
switch(type)
{
case INT_TYPE:
param1.name = param_name.c_str();
param1.value = stoi(value);
conf.ints.push_back(param1);
break;
case DOUBLE_TYPE:
param3.name = param_name.c_str();
//printf("type double. Value: %s\n", param3.name.c_str());
param3.value = stod(value);
//printf("conversion to double: %.3f\n", param3.value);
conf.doubles.push_back(param3);
break;
case BOOL_TYPE:
param2.name = param_name.c_str();
param2.value = stoi(value);
conf.bools.push_back(param2);
break;
case STRING_TYPE:
param4.name = param_name.c_str();
param4.value = value;
conf.strs.push_back(param4);
break;
default:
ROS_ERROR("indires_macro_actions. ReconfigureParameters. datatype not valid!");
}
srv_req.config = conf;
std::string service = node + "/set_parameters";
if (!ros::service::call(service, srv_req, srv_resp)) {
ROS_ERROR("Could not call the service %s reconfigure the param %s to %s",
service.c_str(), param_name.c_str(), value.c_str());
return false;
}
return true;
}
*/
void Indires_macro_actions::teleoperationCB(const indires_macro_actions::TeleoperationGoal::ConstPtr& goal)
{
if (!manual_control_)
{
printf("¡¡¡¡¡¡¡MacroAction AssistedSteering --> started!!!!!!\n");
manual_control_ = true;
moveBaseClient_->cancelAllGoals();
// UpoNav_->stopRRTPlanning();
// stop the current wsbs if it is running
// teresa_wsbs::stop stop_srv;
// stop_client_.call(stop_srv);
}
ros::Time time_init;
time_init = ros::Time::now();
bool exit = false;
// boost::recursive_mutex::scoped_lock l(configuration_mutex_);
ros::Rate r(30.0);
while (nh4_.ok())
{
if (TOActionServer_->isPreemptRequested())
{
if (TOActionServer_->isNewGoalAvailable())
{
// if we're active and a new goal is available, we'll accept it, but we won't shut
// anything down
// ROS_INFO("Accepting new goal");
indires_macro_actions::TeleoperationGoal new_goal = *TOActionServer_->acceptNewGoal();
time_init = ros::Time::now();
}
else
{
TOActionServer_->setPreempted(toresult_, "Teleoperation preempted");
return;
}
}
tofeedback_.text = "Robot manually controlled";
// Check the time without receiving commands from the interface
double time = (ros::Time::now() - time_init).toSec();
if (time > 5.0)
{
tofeedback_.text = "Teleoperation finished";
toresult_.result = "Teleoperation Succeeded";
toresult_.value = 0;
TOActionServer_->setSucceeded(toresult_, "Teleoperation succeeded");
exit = true;
}
TOActionServer_->publishFeedback(tofeedback_);
if (exit)
{
manual_control_ = false;
return;
}
r.sleep();
}
manual_control_ = false;
ROS_INFO("Setting ABORTED state");
TOActionServer_->setAborted(toresult_, "Teleoperation aborted because the node has been killed");
}
// void Upo_navigation_macro_actions::poseCallback(const
// geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg)
void Indires_macro_actions::robotPoseCallback(const nav_msgs::Odometry::ConstPtr& msg)
{
pose_mutex_.lock();
odom_pose_ = *msg;
// robot_global_pose_.y = msg->pose.pose.position.y;
// robot_global_pose_.theta = tf::getYaw(msg->pose.pose.orientation);
pose_mutex_.unlock();
}
void Indires_macro_actions::rrtGoalCallback(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
/*geometry_msgs::PoseStamped out;
out = transformPoseTo(*msg, "map");
geometry_msgs::Pose2D p;
p.x = out.pose.position.x;
p.y = out.pose.position.y;
p.theta = 0.0;
*/
goal_mutex_.lock();
rrtgoal_ = *msg;
goal_mutex_.unlock();
}
geometry_msgs::PoseStamped Indires_macro_actions::transformPoseTo(geometry_msgs::PoseStamped pose_in,
std::string frame_out)
{
geometry_msgs::PoseStamped in = pose_in;
in.header.stamp = ros::Time();
geometry_msgs::PoseStamped pose_out;
try
{
pose_out = tf_->transform(in, frame_out.c_str());
}
catch (tf2::TransformException ex)
{
ROS_WARN("Macro-Action class. TransformException in method transformPoseTo: %s", ex.what());
pose_out.header = in.header;
pose_out.header.stamp = ros::Time::now();
pose_out.pose.position.x = 0.0;
pose_out.pose.position.y = 0.0;
pose_out.pose.position.z = 0.0;
pose_out.pose.orientation = tf::createQuaternionMsgFromYaw(0.0);
}
return pose_out;
}
// This method removes the initial slash from the frame names
// in order to compare the string names easily
void Indires_macro_actions::fixFrame(std::string& cad)
{
if (cad[0] == '/')
{
cad.erase(0, 1);
}
}
float Indires_macro_actions::normalizeAngle(float val, float min, float max)
{
float norm = 0.0;
if (val >= min)
norm = min + fmod((val - min), (max - min));
else
norm = max - fmod((min - val), (max - min));
return norm;
}
| 30.683303 | 107 | 0.658001 |
80e6d38c87acd8605315d45b0d400b2a3bd80526 | 49,223 | cpp | C++ | agent/agent.cpp | MatthewPowley/cppagent | fccb7794723ba71025dfd1ea633332422f99a3dd | [
"Apache-2.0"
] | null | null | null | agent/agent.cpp | MatthewPowley/cppagent | fccb7794723ba71025dfd1ea633332422f99a3dd | [
"Apache-2.0"
] | null | null | null | agent/agent.cpp | MatthewPowley/cppagent | fccb7794723ba71025dfd1ea633332422f99a3dd | [
"Apache-2.0"
] | null | null | null | /*
* Copyright Copyright 2012, System Insights, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "agent.hpp"
#include "dlib/logger.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <sstream>
#include <stdexcept>
#include <dlib/tokenizer.h>
#include <dlib/misc_api.h>
#include <dlib/array.h>
#include <dlib/dir_nav.h>
#include <dlib/config_reader.h>
#include <dlib/queue.h>
#include <functional>
using namespace std;
static const string sUnavailable("UNAVAILABLE");
static const string sConditionUnavailable("UNAVAILABLE|||");
static const string sAvailable("AVAILABLE");
static dlib::logger sLogger("agent");
/* Agent public methods */
Agent::Agent(const string& configXmlPath, int aBufferSize, int aMaxAssets, int aCheckpointFreq)
: mPutEnabled(false), mLogStreamData(false)
{
mMimeTypes["xsl"] = "text/xsl";
mMimeTypes["xml"] = "text/xml";
mMimeTypes["css"] = "text/css";
mMimeTypes["xsd"] = "text/xml";
mMimeTypes["jpg"] = "image/jpeg";
mMimeTypes["jpeg"] = "image/jpeg";
mMimeTypes["png"] = "image/png";
mMimeTypes["ico"] = "image/x-icon";
try
{
// Load the configuration for the Agent
mXmlParser = new XmlParser();
mDevices = mXmlParser->parseFile(configXmlPath);
std::vector<Device *>::iterator device;
std::set<std::string> uuids;
for (device = mDevices.begin(); device != mDevices.end(); ++device)
{
if (uuids.count((*device)->getUuid()) > 0)
throw runtime_error("Duplicate UUID: " + (*device)->getUuid());
uuids.insert((*device)->getUuid());
(*device)->resolveReferences();
}
}
catch (runtime_error & e)
{
sLogger << LFATAL << "Error loading xml configuration: " + configXmlPath;
sLogger << LFATAL << "Error detail: " << e.what();
cerr << e.what() << endl;
throw e;
}
catch (exception &f)
{
sLogger << LFATAL << "Error loading xml configuration: " + configXmlPath;
sLogger << LFATAL << "Error detail: " << f.what();
cerr << f.what() << endl;
throw f;
}
// Grab data from configuration
string time = getCurrentTime(GMT_UV_SEC);
// Unique id number for agent instance
mInstanceId = getCurrentTimeInSec();
// Sequence number and sliding buffer for data
mSequence = 1;
mSlidingBufferSize = 1 << aBufferSize;
mSlidingBuffer = new sliding_buffer_kernel_1<ComponentEventPtr>();
mSlidingBuffer->set_size(aBufferSize);
mCheckpointFreq = aCheckpointFreq;
mCheckpointCount = (mSlidingBufferSize / aCheckpointFreq) + 1;
// Asset sliding buffer
mMaxAssets = aMaxAssets;
// Create the checkpoints at a regular frequency
mCheckpoints = new Checkpoint[mCheckpointCount];
// Mutex used for synchronized access to sliding buffer and sequence number
mSequenceLock = new dlib::mutex;
mAssetLock = new dlib::mutex;
// Add the devices to the device map and create availability and
// asset changed events if they don't exist
std::vector<Device *>::iterator device;
for (device = mDevices.begin(); device != mDevices.end(); ++device)
{
mDeviceMap[(*device)->getName()] = *device;
// Make sure we have two device level data items:
// 1. Availability
// 2. AssetChanged
if ((*device)->getAvailability() == NULL)
{
// Create availability data item and add it to the device.
std::map<string,string> attrs;
attrs["type"] = "AVAILABILITY";
attrs["id"] = (*device)->getId() + "_avail";
attrs["category"] = "EVENT";
DataItem *di = new DataItem(attrs);
di->setComponent(*(*device));
(*device)->addDataItem(*di);
(*device)->addDeviceDataItem(*di);
(*device)->mAvailabilityAdded = true;
}
int major, minor;
char c;
stringstream ss(XmlPrinter::getSchemaVersion());
ss >> major >> c >> minor;
if ((*device)->getAssetChanged() == NULL && (major > 1 || (major == 1 && minor >= 2)))
{
// Create asset change data item and add it to the device.
std::map<string,string> attrs;
attrs["type"] = "ASSET_CHANGED";
attrs["id"] = (*device)->getId() + "_asset_chg";
attrs["category"] = "EVENT";
DataItem *di = new DataItem(attrs);
di->setComponent(*(*device));
(*device)->addDataItem(*di);
(*device)->addDeviceDataItem(*di);
}
if ((*device)->getAssetRemoved() == NULL && (major > 1 || (major == 1 && minor >= 3)))
{
// Create asset removed data item and add it to the device.
std::map<string,string> attrs;
attrs["type"] = "ASSET_REMOVED";
attrs["id"] = (*device)->getId() + "_asset_rem";
attrs["category"] = "EVENT";
DataItem *di = new DataItem(attrs);
di->setComponent(*(*device));
(*device)->addDataItem(*di);
(*device)->addDeviceDataItem(*di);
}
}
// Reload the document for path resolution
mXmlParser->loadDocument(XmlPrinter::printProbe(mInstanceId, mSlidingBufferSize,
mMaxAssets,
mAssets.size(),
mSequence, mDevices));
/* Initialize the id mapping for the devices and set all data items to UNAVAILABLE */
for (device = mDevices.begin(); device != mDevices.end(); ++device)
{
const std::map<string, DataItem*> &items = (*device)->getDeviceDataItems();
std::map<string, DataItem *>::const_iterator item;
for (item = items.begin(); item != items.end(); ++item)
{
// Check for single valued constrained data items.
DataItem *d = item->second;
const string *value = &sUnavailable;
if (d->isCondition()) {
value = &sConditionUnavailable;
} else if (d->hasConstantValue()) {
value = &(d->getConstrainedValues()[0]);
}
addToBuffer(d, *value, time);
if (mDataItemMap.count(d->getId()) == 0)
mDataItemMap[d->getId()] = d;
else {
sLogger << LFATAL << "Duplicate DataItem id " << d->getId() <<
" for device: " << (*device)->getName() << " and data item name: " <<
d->getName();
exit(1);
}
}
}
}
Device *Agent::findDeviceByUUIDorName(const std::string& aId)
{
Device *device = NULL;
std::vector<Device *>::iterator it;
for (it = mDevices.begin(); device == NULL && it != mDevices.end(); it++)
{
if ((*it)->getUuid() == aId || (*it)->getName() == aId)
device = *it;
}
return device;
}
Agent::~Agent()
{
delete mSlidingBuffer;
delete mSequenceLock;
delete mAssetLock;
delete mXmlParser;
delete[] mCheckpoints;
}
void Agent::start()
{
try {
// Start all the adapters
std::vector<Adapter*>::iterator iter;
for (iter = mAdapters.begin(); iter != mAdapters.end(); iter++) {
(*iter)->start();
}
// Start the server. This blocks until the server stops.
server_http::start();
}
catch (dlib::socket_error &e) {
sLogger << LFATAL << "Cannot start server: " << e.what();
exit(1);
}
}
void Agent::clear()
{
// Stop all adapter threads...
std::vector<Adapter *>::iterator iter;
sLogger << LINFO << "Shutting down adapters";
// Deletes adapter and waits for it to exit.
for (iter = mAdapters.begin(); iter != mAdapters.end(); iter++) {
(*iter)->stop();
}
sLogger << LINFO << "Shutting down server";
server::http_1a::clear();
sLogger << LINFO << "Shutting completed";
for (iter = mAdapters.begin(); iter != mAdapters.end(); iter++) {
delete (*iter);
}
mAdapters.clear();
}
// Register a file
void Agent::registerFile(const string &aUri, const string &aPath)
{
try {
directory dir(aPath);
queue<file>::kernel_1a files;
dir.get_files(files);
files.reset();
string baseUri = aUri;
if (*baseUri.rbegin() != '/') baseUri.append(1, '/');
while (files.move_next()) {
file &file = files.element();
string name = file.name();
string uri = baseUri + name;
mFileMap.insert(pair<string,string>(uri, file.full_name()));
// Check if the file name maps to a standard MTConnect schema file.
if (name.find("MTConnect") == 0 && name.substr(name.length() - 4, 4) == ".xsd" &&
XmlPrinter::getSchemaVersion() == name.substr(name.length() - 7, 3)) {
string version = name.substr(name.length() - 7, 3);
if (name.substr(9, 5) == "Error") {
string urn = "urn:mtconnect.org:MTConnectError:" + XmlPrinter::getSchemaVersion();
XmlPrinter::addErrorNamespace(urn, uri, "m");
} else if (name.substr(9, 7) == "Devices") {
string urn = "urn:mtconnect.org:MTConnectDevices:" + XmlPrinter::getSchemaVersion();
XmlPrinter::addDevicesNamespace(urn, uri, "m");
} else if (name.substr(9, 6) == "Assets") {
string urn = "urn:mtconnect.org:MTConnectAssets:" + XmlPrinter::getSchemaVersion();
XmlPrinter::addAssetsNamespace(urn, uri, "m");
} else if (name.substr(9, 7) == "Streams") {
string urn = "urn:mtconnect.org:MTConnectStreams:" + XmlPrinter::getSchemaVersion();
XmlPrinter::addStreamsNamespace(urn, uri, "m");
}
}
}
}
catch (directory::dir_not_found e) {
sLogger << LDEBUG << "registerFile: Path " << aPath << " is not a directory: "
<< e.what() << ", trying as a file";
try {
file file(aPath);
mFileMap.insert(pair<string,string>(aUri, aPath));
} catch (file::file_not_found e) {
sLogger << LERROR << "Cannot register file: " << aPath << ": " << e.what();
}
}
}
// Methods for service
const string Agent::on_request (const incoming_things& incoming,
outgoing_things& outgoing)
{
string result;
outgoing.headers["Content-Type"] = "text/xml";
try
{
sLogger << LDEBUG << "Request: " << incoming.request_type << " " <<
incoming.path << " from " << incoming.foreign_ip << ":" << incoming.foreign_port;
if (mPutEnabled)
{
if ((incoming.request_type == "PUT" || incoming.request_type == "POST") &&
!mPutAllowedHosts.empty() && mPutAllowedHosts.count(incoming.foreign_ip) == 0)
{
return printError("UNSUPPORTED",
"HTTP PUT is not allowed from " + incoming.foreign_ip);
}
if (incoming.request_type != "GET" && incoming.request_type != "PUT" &&
incoming.request_type != "POST") {
return printError("UNSUPPORTED",
"Only the HTTP GET and PUT requests are supported");
}
}
else
{
if (incoming.request_type != "GET") {
return printError("UNSUPPORTED",
"Only the HTTP GET request is supported");
}
}
// Parse the URL path looking for '/'
string path = incoming.path;
size_t qm = path.find_last_of('?');
if (qm != string::npos)
path = path.substr(0, qm);
if (isFile(path)) {
return handleFile(path, outgoing);
}
string::size_type loc1 = path.find("/", 1);
string::size_type end = (path[path.length()-1] == '/') ?
path.length() - 1 : string::npos;
string first = path.substr(1, loc1-1);
string call, device;
if (first == "assets" || first == "asset")
{
string list;
if (loc1 != string::npos)
list = path.substr(loc1 + 1);
if (incoming.request_type == "GET")
result = handleAssets(*outgoing.out, incoming.queries, list);
else
result = storeAsset(*outgoing.out, incoming.queries, list, incoming.body);
}
else
{
// If a '/' was found
if (loc1 < end)
{
// Look for another '/'
string::size_type loc2 = path.find("/", loc1+1);
if (loc2 == end)
{
device = first;
call = path.substr(loc1+1, loc2-loc1-1);
}
else
{
// Path is too long
return printError("UNSUPPORTED", "The following path is invalid: " + path);
}
}
else
{
// Try to handle the call
call = first;
}
if (incoming.request_type == "GET")
result = handleCall(*outgoing.out, path, incoming.queries, call, device);
else
result = handlePut(*outgoing.out, path, incoming.queries, call, device);
}
}
catch (exception & e)
{
printError("SERVER_EXCEPTION",(string) e.what());
}
return result;
}
Adapter * Agent::addAdapter(const string& aDeviceName,
const string& aHost,
const unsigned int aPort,
bool aStart,
int aLegacyTimeout
)
{
Adapter *adapter = new Adapter(aDeviceName, aHost, aPort, aLegacyTimeout);
adapter->setAgent(*this);
mAdapters.push_back(adapter);
Device *dev = mDeviceMap[aDeviceName];
if (dev != NULL && dev->mAvailabilityAdded)
adapter->setAutoAvailable(true);
if (aStart)
adapter->start();
return adapter;
}
unsigned int Agent::addToBuffer(DataItem *dataItem,
const string& value,
string time
)
{
if (dataItem == NULL) return 0;
dlib::auto_mutex lock(*mSequenceLock);
uint64_t seqNum = mSequence++;
ComponentEvent *event = new ComponentEvent(*dataItem, seqNum,
time, value);
(*mSlidingBuffer)[seqNum] = event;
mLatest.addComponentEvent(event);
event->unrefer();
// Special case for the first event in the series to prime the first checkpoint.
if (seqNum == 1) {
mFirst.addComponentEvent(event);
}
// Checkpoint management
int index = mSlidingBuffer->get_element_id(seqNum);
if (mCheckpointCount > 0 && index % mCheckpointFreq == 0) {
// Copy the checkpoint from the current into the slot
mCheckpoints[index / mCheckpointFreq].copy(mLatest);
}
// See if the next sequence has an event. If the event exists it
// should be added to the first checkpoint.
if ((*mSlidingBuffer)[mSequence] != NULL)
{
// Keep the last checkpoint up to date with the last.
mFirst.addComponentEvent((*mSlidingBuffer)[mSequence]);
}
dataItem->signalObservers(seqNum);
return seqNum;
}
bool Agent::addAsset(Device *aDevice, const string &aId, const string &aAsset,
const string &aType, const string &aTime)
{
// Check to make sure the values are present
if (aType.empty() || aAsset.empty() || aId.empty()) {
sLogger << LWARN << "Asset '" << aId << "' missing required type, id, or body. Asset is rejected.";
return false;
}
string time;
if (aTime.empty())
time = getCurrentTime(GMT_UV_SEC);
else
time = aTime;
AssetPtr ptr;
// Lock the asset addition to protect from multithreaded collisions. Releaes
// before we add the event so we don't cause a race condition.
{
dlib::auto_mutex lock(*mAssetLock);
try {
ptr = mXmlParser->parseAsset(aId, aType, aAsset);
}
catch (runtime_error &e) {
sLogger << LERROR << "addAsset: Error parsing asset: " << aAsset << "\n" << e.what();
return false;
}
if (ptr.getObject() == NULL)
{
sLogger << LERROR << "addAssete: Error parsing asset";
return false;
}
AssetPtr *old = &mAssetMap[aId];
if (!ptr->isRemoved())
{
if (old->getObject() != NULL)
mAssets.remove(old);
else
mAssetCounts[aType] += 1;
} else if (old->getObject() == NULL) {
sLogger << LWARN << "Cannot remove non-existent asset";
return false;
}
if (ptr.getObject() == NULL) {
sLogger << LWARN << "Asset could not be created";
return false;
} else {
ptr->setAssetId(aId);
ptr->setTimestamp(time);
ptr->setDeviceUuid(aDevice->getUuid());
}
// Check for overflow
if (mAssets.size() >= mMaxAssets)
{
AssetPtr oldref(*mAssets.front());
mAssetCounts[oldref->getType()] -= 1;
mAssets.pop_front();
mAssetMap.erase(oldref->getAssetId());
// Remove secondary keys
AssetKeys &keys = oldref->getKeys();
AssetKeys::iterator iter;
for (iter = keys.begin(); iter != keys.end(); iter++)
{
AssetIndex &index = mAssetIndices[iter->first];
index.erase(iter->second);
}
}
mAssetMap[aId] = ptr;
if (!ptr->isRemoved())
{
AssetPtr &newPtr = mAssetMap[aId];
mAssets.push_back(&newPtr);
}
// Add secondary keys
AssetKeys &keys = ptr->getKeys();
AssetKeys::iterator iter;
for (iter = keys.begin(); iter != keys.end(); iter++)
{
AssetIndex &index = mAssetIndices[iter->first];
index[iter->second] = ptr;
}
}
// Generate an asset chnaged event.
if (ptr->isRemoved())
addToBuffer(aDevice->getAssetRemoved(), aType + "|" + aId, time);
else
addToBuffer(aDevice->getAssetChanged(), aType + "|" + aId, time);
return true;
}
bool Agent::updateAsset(Device *aDevice, const std::string &aId, AssetChangeList &aList,
const string &aTime)
{
AssetPtr asset;
string time;
if (aTime.empty())
time = getCurrentTime(GMT_UV_SEC);
else
time = aTime;
{
dlib::auto_mutex lock(*mAssetLock);
asset = mAssetMap[aId];
if (asset.getObject() == NULL)
return false;
if (asset->getType() != "CuttingTool" && asset->getType() != "CuttingToolArchitype")
return false;
CuttingToolPtr tool((CuttingTool*) asset.getObject());
try {
AssetChangeList::iterator iter;
for (iter = aList.begin(); iter != aList.end(); ++iter)
{
if (iter->first == "xml") {
mXmlParser->updateAsset(asset, asset->getType(), iter->second);
} else {
tool->updateValue(iter->first, iter->second);
}
}
}
catch (runtime_error &e) {
sLogger << LERROR << "updateAsset: Error parsing asset: " << asset << "\n" << e.what();
return false;
}
// Move it to the front of the queue
mAssets.remove(&asset);
mAssets.push_back(&asset);
tool->setTimestamp(time);
tool->setDeviceUuid(aDevice->getUuid());
tool->changed();
}
addToBuffer(aDevice->getAssetChanged(), asset->getType() + "|" + aId, time);
return true;
}
bool Agent::removeAsset(Device *aDevice, const std::string &aId, const string &aTime)
{
AssetPtr asset;
string time;
if (aTime.empty())
time = getCurrentTime(GMT_UV_SEC);
else
time = aTime;
{
dlib::auto_mutex lock(*mAssetLock);
asset = mAssetMap[aId];
if (asset.getObject() == NULL)
return false;
asset->setRemoved(true);
asset->setTimestamp(time);
// Check if the asset changed id is the same as this asset.
ComponentEventPtr *ptr = mLatest.getEventPtr(aDevice->getAssetChanged()->getId());
if (ptr != NULL && (*ptr)->getValue() == aId)
{
addToBuffer(aDevice->getAssetChanged(), asset->getType() + "|UNAVAILABLE", time);
}
}
addToBuffer(aDevice->getAssetRemoved(), asset->getType() + "|" + aId, time);
return true;
}
bool Agent::removeAllAssets(Device *aDevice, const std::string &aType, const std::string &aTime)
{
string time;
if (aTime.empty())
time = getCurrentTime(GMT_UV_SEC);
else
time = aTime;
{
dlib::auto_mutex lock(*mAssetLock);
ComponentEventPtr *ptr = mLatest.getEventPtr(aDevice->getAssetChanged()->getId());
string changedId;
if (ptr != NULL)
changedId = (*ptr)->getValue();
list<AssetPtr*>::reverse_iterator iter;
for (iter = mAssets.rbegin(); iter != mAssets.rend(); ++iter)
{
AssetPtr asset = (**iter);
if (aType == asset->getType() && !asset->isRemoved()) {
asset->setRemoved(true);
asset->setTimestamp(time);
addToBuffer(aDevice->getAssetRemoved(), asset->getType() + "|" + asset->getAssetId(), time);
if (changedId == asset->getAssetId())
addToBuffer(aDevice->getAssetChanged(), asset->getType() + "|UNAVAILABLE", time);
}
}
}
return true;
}
/* Add values for related data items UNAVAILABLE */
void Agent::disconnected(Adapter *anAdapter, std::vector<Device*> aDevices)
{
string time = getCurrentTime(GMT_UV_SEC);
sLogger << LDEBUG << "Disconnected from adapter, setting all values to UNAVAILABLE";
std::vector<Device*>::iterator iter;
for (iter = aDevices.begin(); iter != aDevices.end(); ++iter) {
const std::map<std::string, DataItem *> &dataItems = (*iter)->getDeviceDataItems();
std::map<std::string, DataItem*>::const_iterator dataItemAssoc;
for (dataItemAssoc = dataItems.begin(); dataItemAssoc != dataItems.end(); ++dataItemAssoc)
{
DataItem *dataItem = (*dataItemAssoc).second;
if (dataItem != NULL && (dataItem->getDataSource() == anAdapter ||
(anAdapter->isAutoAvailable() &&
dataItem->getDataSource() == NULL &&
dataItem->getType() == "AVAILABILITY")))
{
ComponentEventPtr *ptr = mLatest.getEventPtr(dataItem->getId());
if (ptr != NULL) {
const string *value = NULL;
if (dataItem->isCondition()) {
if ((*ptr)->getLevel() != ComponentEvent::UNAVAILABLE)
value = &sConditionUnavailable;
} else if (dataItem->hasConstraints()) {
std::vector<std::string> &values = dataItem->getConstrainedValues();
if (values.size() > 1 && (*ptr)->getValue() != sUnavailable)
value = &sUnavailable;
} else if ((*ptr)->getValue() != sUnavailable) {
value = &sUnavailable;
}
if (value != NULL && !anAdapter->isDuplicate(dataItem, *value, NAN))
addToBuffer(dataItem, *value, time);
}
} else if (dataItem == NULL) {
sLogger << LWARN << "No data Item for " << (*dataItemAssoc).first;
}
}
}
}
void Agent::connected(Adapter *anAdapter, std::vector<Device*> aDevices)
{
if (anAdapter->isAutoAvailable()) {
string time = getCurrentTime(GMT_UV_SEC);
std::vector<Device*>::iterator iter;
for (iter = aDevices.begin(); iter != aDevices.end(); ++iter) {
sLogger << LDEBUG << "Connected to adapter, setting all Availability data items to AVAILABLE";
if ((*iter)->getAvailability() != NULL)
{
sLogger << LDEBUG << "Adding availabilty event for " << (*iter)->getAvailability()->getId();
addToBuffer((*iter)->getAvailability(), sAvailable, time);
}
else
{
sLogger << LDEBUG << "Cannot find availability for " << (*iter)->getName();
}
}
}
}
/* Agent protected methods */
string Agent::handleCall(ostream& out,
const string& path,
const key_value_map& queries,
const string& call,
const string& device)
{
try {
string deviceName;
if (!device.empty())
{
deviceName = device;
}
if (call == "current")
{
const string path = queries[(string) "path"];
string result;
int freq = checkAndGetParam(queries, "frequency", NO_FREQ,
FASTEST_FREQ, false,SLOWEST_FREQ);
// Check for 1.2 conversion to interval
if (freq == NO_FREQ)
freq = checkAndGetParam(queries, "interval", NO_FREQ,
FASTEST_FREQ, false, SLOWEST_FREQ);
uint64_t at = checkAndGetParam64(queries, "at", NO_START, getFirstSequence(), true,
mSequence - 1);
int heartbeat = checkAndGetParam(queries, "heartbeat", 10000, 10, true, 600000);
if (freq != NO_FREQ && at != NO_START) {
return printError("INVALID_REQUEST", "You cannot specify both the at and frequency arguments to a current request");
}
return handleStream(out, devicesAndPath(path, deviceName), true,
freq, at, 0, heartbeat);
}
else if (call == "probe" || call.empty())
{
return handleProbe(deviceName);
}
else if (call == "sample")
{
string path = queries[(string) "path"];
string result;
int count = checkAndGetParam(queries, "count", DEFAULT_COUNT,
1, true, mSlidingBufferSize);
int freq = checkAndGetParam(queries, "frequency", NO_FREQ,
FASTEST_FREQ, false, SLOWEST_FREQ);
// Check for 1.2 conversion to interval
if (freq == NO_FREQ)
freq = checkAndGetParam(queries, "interval", NO_FREQ,
FASTEST_FREQ, false, SLOWEST_FREQ);
uint64 start = checkAndGetParam64(queries, "start", NO_START, getFirstSequence(),
true, mSequence);
if (start == NO_START) // If there was no data in queries
{
start = checkAndGetParam64(queries, "from", 1,
getFirstSequence(), true, mSequence);
}
int heartbeat = checkAndGetParam(queries, "heartbeat", 10000, 10, true, 600000);
return handleStream(out, devicesAndPath(path, deviceName), false,
freq, start, count, heartbeat);
}
else if ((mDeviceMap[call] != NULL) && device.empty())
{
return handleProbe(call);
}
else
{
return printError("UNSUPPORTED",
"The following path is invalid: " + path);
}
}
catch (ParameterError &aError)
{
return printError(aError.mCode, aError.mMessage);
}
}
/* Agent protected methods */
string Agent::handlePut(
ostream& out,
const string& path,
const key_value_map& queries,
const string& adapter,
const string& deviceName
)
{
string device = deviceName;
if (device.empty() && adapter.empty())
{
return printError("UNSUPPORTED",
"Device must be specified for PUT");
} else if (device.empty()) {
device = adapter;
}
Device *dev = mDeviceMap[device];
if (dev == NULL) {
string message = ((string) "Cannot find device: ") + device;
return printError("UNSUPPORTED", message);
}
// First check if this is an adapter put or a data put...
if (queries["_type"] == "command")
{
std::vector<Adapter*>::iterator adpt;
for (adpt = dev->mAdapters.begin(); adpt != dev->mAdapters.end(); adpt++) {
key_value_map::const_iterator kv;
for (kv = queries.begin(); kv != queries.end(); kv++) {
string command = kv->first + "=" + kv->second;
sLogger << LDEBUG << "Sending command '" << command << "' to " << device;
(*adpt)->sendCommand(command);
}
}
}
else
{
string time = queries["time"];
if (time.empty())
time = getCurrentTime(GMT_UV_SEC);
key_value_map::const_iterator kv;
for (kv = queries.begin(); kv != queries.end(); kv++) {
if (kv->first != "time")
{
DataItem *di = dev->getDeviceDataItem(kv->first);
if (di != NULL)
addToBuffer(di, kv->second, time);
else
sLogger << LWARN << "(" << device << ") Could not find data item: " << kv->first;
}
}
}
return "<success/>";
}
string Agent::handleProbe(const string& name)
{
std::vector<Device *> mDeviceList;
if (!name.empty())
{
Device * device = getDeviceByName(name);
if (device == NULL)
{
return printError("NO_DEVICE",
"Could not find the device '" + name + "'");
}
else
{
mDeviceList.push_back(device);
}
}
else
{
mDeviceList = mDevices;
}
return XmlPrinter::printProbe(mInstanceId, mSlidingBufferSize, mSequence,
mMaxAssets, mAssets.size(),
mDeviceList, &mAssetCounts);
}
string Agent::handleStream(
ostream& out,
const string& path,
bool current,
unsigned int frequency,
uint64_t start,
unsigned int count,
unsigned int aHb
)
{
std::set<string> filter;
try
{
mXmlParser->getDataItems(filter, path);
}
catch (exception& e)
{
return printError("INVALID_XPATH", e.what());
}
if (filter.empty())
{
return printError("INVALID_XPATH",
"The path could not be parsed. Invalid syntax: " + path);
}
// Check if there is a frequency to stream data or not
if (frequency != (unsigned) NO_FREQ)
{
streamData(out, filter, current, frequency, start, count, aHb);
return "";
}
else
{
uint64_t end;
bool endOfBuffer;
if (current)
return fetchCurrentData(filter, start);
else
return fetchSampleData(filter, start, count, end, endOfBuffer);
}
}
std::string Agent::handleAssets(std::ostream& aOut,
const key_value_map& aQueries,
const std::string& aList)
{
using namespace dlib;
std::vector<AssetPtr> assets;
if (!aList.empty())
{
auto_mutex lock(*mAssetLock);
istringstream str(aList);
tokenizer_kernel_1 tok;
tok.set_stream(str);
tok.set_identifier_token(tok.lowercase_letters() + tok.uppercase_letters() +
tok.numbers() + "_.@$%&^:+-_=",
tok.lowercase_letters() + tok.uppercase_letters() +
tok.numbers() + "_.@$%&^:+-_=");
int type;
string token;
for (tok.get_token(type, token); type != tok.END_OF_FILE; tok.get_token(type, token))
{
if (type == tok.IDENTIFIER)
{
AssetPtr ptr = mAssetMap[token];
if (ptr.getObject() == NULL)
return XmlPrinter::printError(mInstanceId, 0, 0, "ASSET_NOT_FOUND",
(string) "Could not find asset: " + token);
assets.push_back(ptr);
}
}
}
else
{
auto_mutex lock(*mAssetLock);
// Return all asssets, first check if there is a type attribute
string type = aQueries["type"];
bool removed = (aQueries.count("removed") > 0 && aQueries["removed"] == "true");
int count = checkAndGetParam(aQueries, "count", mAssets.size(),
1, false, NO_VALUE32);
list<AssetPtr*>::reverse_iterator iter;
for (iter = mAssets.rbegin(); iter != mAssets.rend() && count > 0; ++iter, --count)
{
if ((type.empty() || type == (**iter)->getType()) && (removed || !(**iter)->isRemoved())) {
assets.push_back(**iter);
}
}
}
return XmlPrinter::printAssets(mInstanceId, mMaxAssets, mAssets.size(), assets);
}
// Store an asset in the map by asset # and use the circular buffer as
// an LRU. Check if we're removing an existing asset and clean up the
// map, and then store this asset.
std::string Agent::storeAsset(std::ostream& aOut,
const key_value_map& aQueries,
const std::string& aId,
const std::string& aBody)
{
string name = aQueries["device"];
string type = aQueries["type"];
Device *device = NULL;
if (!name.empty()) device = mDeviceMap[name];
// If the device was not found or was not provided, use the default device.
if (device == NULL) device = mDevices[0];
if (addAsset(device, aId, aBody, type))
return "<success/>";
else
return "<failure/>";
}
string Agent::handleFile(const string &aUri, outgoing_things& aOutgoing)
{
// Get the mime type for the file.
bool unknown = true;
size_t last = aUri.find_last_of("./");
string contentType;
if (last != string::npos && aUri[last] == '.')
{
string ext = aUri.substr(last + 1);
if (mMimeTypes.count(ext) > 0)
{
contentType = mMimeTypes[ext];
unknown = false;
}
}
if (unknown)
contentType = "application/octet-stream";
// Check if the file is cached
RefCountedPtr<CachedFile> cachedFile;
std::map<string, RefCountedPtr<CachedFile> >::iterator cached = mFileCache.find(aUri);
if (cached != mFileCache.end())
cachedFile = cached->second;
else
{
std::map<string,string>::iterator file = mFileMap.find(aUri);
// Should never happen
if (file == mFileMap.end()) {
aOutgoing.http_return = 404;
aOutgoing.http_return_status = "File not found";
return "";
}
const char *path = file->second.c_str();
struct stat fs;
int res = stat(path, &fs);
if (res != 0) {
aOutgoing.http_return = 404;
aOutgoing.http_return_status = "File not found";
return "";
}
int fd = open(path, O_RDONLY | O_BINARY);
if (res < 0) {
aOutgoing.http_return = 404;
aOutgoing.http_return_status = "File not found";
return "";
}
cachedFile.setObject(new CachedFile(fs.st_size), true);
int bytes = read(fd, cachedFile->mBuffer, fs.st_size);
close(fd);
if (bytes < fs.st_size) {
aOutgoing.http_return = 404;
aOutgoing.http_return_status = "File not found";
return "";
}
// If this is a small file, cache it.
if (bytes <= SMALL_FILE) {
mFileCache.insert(pair<string, RefCountedPtr<CachedFile> >(aUri, cachedFile));
}
}
(*aOutgoing.out) << "HTTP/1.1 200 OK\r\n"
"Date: " << getCurrentTime(HUM_READ) << "\r\n"
"Server: MTConnectAgent\r\n"
"Connection: close\r\n"
"Content-Length: " << cachedFile->mSize << "\r\n"
"Expires: " << getCurrentTime(time(NULL) + 60 * 60 * 24, 0, HUM_READ) << "\r\n"
"Content-Type: " << contentType << "\r\n\r\n";
aOutgoing.out->write(cachedFile->mBuffer, cachedFile->mSize);
aOutgoing.out->setstate(ios::badbit);
return "";
}
void Agent::streamData(ostream& out,
std::set<string> &aFilter,
bool current,
unsigned int aInterval,
uint64_t start,
unsigned int count,
unsigned int aHeartbeat
)
{
// Create header
string boundary = md5(intToString(time(NULL)));
ofstream log;
if (mLogStreamData)
{
string filename = "Stream_" + getCurrentTime(LOCAL) + "_" +
int64ToString((uint64_t) dlib::get_thread_id()) + ".log";
log.open(filename.c_str());
}
out << "HTTP/1.1 200 OK\r\n"
"Date: " << getCurrentTime(HUM_READ) << "\r\n"
"Server: MTConnectAgent\r\n"
"Expires: -1\r\n"
"Connection: close\r\n"
"Cache-Control: private, max-age=0\r\n"
"Content-Type: multipart/x-mixed-replace;boundary=" << boundary << "\r\n"
"Transfer-Encoding: chunked\r\n\r\n";
// This object will automatically clean up all the observer from the
// signalers in an exception proof manor.
ChangeObserver observer;
// Add observers
std::set<string>::iterator iter;
for (iter = aFilter.begin(); iter != aFilter.end(); ++iter)
mDataItemMap[*iter]->addObserver(&observer);
uint64_t interMicros = aInterval * 1000;
uint64_t firstSeq = getFirstSequence();
if (start < firstSeq)
start = firstSeq;
try {
// Loop until the user closes the connection
timestamper ts;
while (out.good())
{
// Remember when we started this grab...
uint64_t last = ts.get_timestamp();
// Fetch sample data now resets the observer while holding the sequence
// mutex to make sure that a new event will be recorded in the observer
// when it returns.
string content;
uint64_t end;
bool endOfBuffer = true;
if (current) {
content = fetchCurrentData(aFilter, NO_START);
} else {
// Check if we're falling too far behind. If we are, generate an
// MTConnectError and return.
if (start < getFirstSequence()) {
sLogger << LWARN << "Client fell too far behind, disconnecting";
throw ParameterError("OUT_OF_RANGE", "Client can't keep up with event stream, disconnecting");
} else {
// end and endOfBuffer are set during the fetch sample data while the
// mutex is held. This removed the race to check if we are at the end of
// the bufffer and setting the next start to the last sequence number
// sent.
content = fetchSampleData(aFilter, start, count, end,
endOfBuffer, &observer);
}
if (mLogStreamData)
log << content << endl;
}
ostringstream str;
// Make sure we're terminated with a <cr><nl>
content.append("\r\n");
out.setf(ios::dec, ios::basefield);
str << "--" << boundary << "\r\n"
"Content-type: text/xml\r\n"
"Content-length: " << content.length() << "\r\n\r\n"
<< content;
string chunk = str.str();
out.setf(ios::hex, ios::basefield);
out << chunk.length() << "\r\n";
out << chunk << "\r\n";
out.flush();
// Wait for up to frequency ms for something to arrive... Don't wait if
// we are not at the end of the buffer. Just put the next set after aInterval
// has elapsed. Check also if in the intervening time between the last fetch
// and now. If so, we just spin through and wait the next interval.
// Even if we are at the end of the buffer, or within range. If we are filtering,
// we will need to make sure we are not spinning when there are no valid events
// to be reported. we will waste cycles spinning on the end of the buffer when
// we should be in a heartbeat wait as well.
if (!endOfBuffer) {
// If we're not at the end of the buffer, move to the end of the previous set and
// begin filtering from where we left off.
start = end;
// For replaying of events, we will stream as fast as we can with a 1ms sleep
// to allow other threads to run.
dlib::sleep(1);
} else {
uint64 delta;
if (!current) {
// Busy wait to make sure the signal was actually signaled. We have observed that
// a signal can occur in rare conditions where there are multiple threads listening
// on separate condition variables and this pops out too soon. This will make sure
// observer was actually signaled and instead of throwing an error will wait again
// for the remaining hartbeat interval.
delta = (ts.get_timestamp() - last) / 1000;
while (delta < aHeartbeat &&
observer.wait(aHeartbeat - delta) &&
!observer.wasSignaled()) {
delta = (ts.get_timestamp() - last) / 1000;
}
{
dlib::auto_mutex lock(*mSequenceLock);
// Make sure the observer was signaled!
if (!observer.wasSignaled()) {
// If nothing came out during the last wait, we may have still have advanced
// the sequence number. We should reset the start to something closer to the
// current sequence. If we lock the sequence lock, we can check if the observer
// was signaled between the time the wait timed out and the mutex was locked.
// Otherwise, nothing has arrived and we set to the next sequence number to
// the next sequence number to be allocated and continue.
start = mSequence;
} else {
// Get the sequence # signaled in the observer when the earliest event arrived.
// This will allow the next set of data to be pulled. Any later events will have
// greater sequence numbers, so this should not cause a problem. Also, signaled
// sequence numbers can only decrease, never increase.
start = observer.getSequence();
}
}
}
// Now wait the remainder if we triggered before the timer was up.
delta = ts.get_timestamp() - last;
if (delta < interMicros) {
// Sleep the remainder
dlib::sleep((interMicros - delta) / 1000);
}
}
}
}
catch (ParameterError &aError)
{
sLogger << LINFO << "Caught a parameter error.";
if (out.good()) {
ostringstream str;
string content = printError(aError.mCode, aError.mMessage);
str << "--" << boundary << "\r\n"
"Content-type: text/xml\r\n"
"Content-length: " << content.length() << "\r\n\r\n"
<< content;
string chunk = str.str();
out.setf(ios::hex, ios::basefield);
out << chunk.length() << "\r\n";
out << chunk << "\r\n";
out.flush();
}
}
catch (...)
{
sLogger << LWARN << "Error occurred during streaming data";
if (out.good()) {
ostringstream str;
string content = printError("INTERNAL_ERROR", "Unknown error occurred during streaming");
str << "--" << boundary << "\r\n"
"Content-type: text/xml\r\n"
"Content-length: " << content.length() << "\r\n\r\n"
<< content;
string chunk = str.str();
out.setf(ios::hex, ios::basefield);
out << chunk.length() << "\r\n";
out << chunk;
out.flush();
}
}
out.setstate(ios::badbit);
// Observer is auto removed from signalers
}
string Agent::fetchCurrentData(std::set<string> &aFilter, uint64_t at)
{
ComponentEventPtrArray events;
uint64_t firstSeq, seq;
{
dlib::auto_mutex lock(*mSequenceLock);
firstSeq = getFirstSequence();
seq = mSequence;
if (at == NO_START)
{
mLatest.getComponentEvents(events, &aFilter);
}
else
{
long pos = (long) mSlidingBuffer->get_element_id(at);
long first = (long) mSlidingBuffer->get_element_id(firstSeq);
long checkIndex = pos / mCheckpointFreq;
long closestCp = checkIndex * mCheckpointFreq;
unsigned long index;
Checkpoint *ref;
// Compute the closest checkpoint. If the checkpoint is after the
// first checkpoint and before the next incremental checkpoint,
// use first.
if (first > closestCp && pos >= first)
{
ref = &mFirst;
// The checkpoint is inclusive of the "first" event. So we add one
// so we don't duplicate effort.
index = first + 1;
}
else
{
index = closestCp + 1;
ref = &mCheckpoints[checkIndex];
}
Checkpoint check(*ref, &aFilter);
// Roll forward from the checkpoint.
for (; index <= (unsigned long) pos; index++) {
check.addComponentEvent(((*mSlidingBuffer)[(unsigned long)index]).getObject());
}
check.getComponentEvents(events);
}
}
string toReturn = XmlPrinter::printSample(mInstanceId, mSlidingBufferSize,
seq, firstSeq, mSequence - 1, events);
return toReturn;
}
string Agent::fetchSampleData(std::set<string> &aFilter,
uint64_t start, unsigned int count, uint64_t &end,
bool &endOfBuffer, ChangeObserver *aObserver)
{
ComponentEventPtrArray results;
uint64_t firstSeq;
{
dlib::auto_mutex lock(*mSequenceLock);
firstSeq = (mSequence > mSlidingBufferSize) ?
mSequence - mSlidingBufferSize : 1;
// START SHOULD BE BETWEEN 0 AND SEQUENCE NUMBER
start = (start <= firstSeq) ? firstSeq : start;
uint64_t i;
for (i = start; results.size() < count && i < mSequence; i++)
{
// Filter out according to if it exists in the list
const string &dataId = (*mSlidingBuffer)[i]->getDataItem()->getId();
if (aFilter.count(dataId) > 0)
{
ComponentEventPtr event = (*mSlidingBuffer)[i];
results.push_back(event);
}
}
end = i;
if (i >= mSequence)
endOfBuffer = true;
else
endOfBuffer = false;
if (aObserver != NULL) aObserver->reset();
}
return XmlPrinter::printSample(mInstanceId, mSlidingBufferSize, end,
firstSeq, mSequence - 1, results);
}
string Agent::printError(const string& errorCode, const string& text)
{
sLogger << LDEBUG << "Returning error " << errorCode << ": " << text;
return XmlPrinter::printError(mInstanceId, mSlidingBufferSize, mSequence,
errorCode, text);
}
string Agent::devicesAndPath(const string& path, const string& device)
{
string dataPath = "";
if (!device.empty())
{
string prefix = "//Devices/Device[@name=\"" + device + "\"]";
if (!path.empty())
{
istringstream toParse(path);
string token;
// Prefix path (i.e. "path1|path2" => "{prefix}path1|{prefix}path2")
while (getline(toParse, token, '|'))
{
dataPath += prefix + token + "|";
}
dataPath.erase(dataPath.length()-1);
}
else
{
dataPath = prefix;
}
}
else
{
dataPath = (!path.empty()) ? path : "//Devices/Device";
}
return dataPath;
}
int Agent::checkAndGetParam(const key_value_map& queries,
const string& param,
const int defaultValue,
const int minValue,
bool minError,
const int maxValue)
{
if (queries.count(param) == 0)
{
return defaultValue;
}
if (queries[param].empty())
{
throw ParameterError("QUERY_ERROR", "'" + param + "' cannot be empty.");
}
if (!isNonNegativeInteger(queries[param]))
{
throw ParameterError("OUT_OF_RANGE",
"'" + param + "' must be a positive integer.");
}
long int value = strtol(queries[param].c_str(), NULL, 10);
if (minValue != NO_VALUE32 && value < minValue)
{
if (minError)
{
throw ParameterError("OUT_OF_RANGE",
"'" + param + "' must be greater than or equal to " + intToString(minValue) + ".");
}
return minValue;
}
if (maxValue != NO_VALUE32 && value > maxValue)
{
throw ParameterError("OUT_OF_RANGE",
"'" + param + "' must be less than or equal to " + intToString(maxValue) + ".");
}
return value;
}
uint64_t Agent::checkAndGetParam64(const key_value_map& queries,
const string& param,
const uint64_t defaultValue,
const uint64_t minValue,
bool minError,
const uint64_t maxValue)
{
if (queries.count(param) == 0)
{
return defaultValue;
}
if (queries[param].empty())
{
throw ParameterError("QUERY_ERROR", "'" + param + "' cannot be empty.");
}
if (!isNonNegativeInteger(queries[param]))
{
throw ParameterError("OUT_OF_RANGE",
"'" + param + "' must be a positive integer.");
}
uint64_t value = strtoull(queries[param].c_str(), NULL, 10);
if (minValue != NO_VALUE64 && value < minValue)
{
if (minError)
{
throw ParameterError("OUT_OF_RANGE",
"'" + param + "' must be greater than or equal to " + int64ToString(minValue) + ".");
}
return minValue;
}
if (maxValue != NO_VALUE64 && value > maxValue)
{
throw ParameterError("OUT_OF_RANGE",
"'" + param + "' must be less than or equal to " + int64ToString(maxValue) + ".");
}
return value;
}
DataItem * Agent::getDataItemByName(const string& device, const string& name)
{
Device *dev = mDeviceMap[device];
return (dev) ? dev->getDeviceDataItem(name) : NULL;
}
void Agent::updateDom(Device *aDevice)
{
mXmlParser->updateDevice(aDevice);
}
| 31.232868 | 124 | 0.572639 |
80eadfcfb890ab9d53fee493019fbde5087937fb | 14,756 | cc | C++ | google/cloud/bigtable/internal/logging_instance_admin_client_test.cc | utgarda/google-cloud-cpp | c4fd446d2c9e1428bcec10917f269f8e5c0a8bc0 | [
"Apache-2.0"
] | null | null | null | google/cloud/bigtable/internal/logging_instance_admin_client_test.cc | utgarda/google-cloud-cpp | c4fd446d2c9e1428bcec10917f269f8e5c0a8bc0 | [
"Apache-2.0"
] | null | null | null | google/cloud/bigtable/internal/logging_instance_admin_client_test.cc | utgarda/google-cloud-cpp | c4fd446d2c9e1428bcec10917f269f8e5c0a8bc0 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/bigtable/internal/logging_instance_admin_client.h"
#include "google/cloud/bigtable/instance_admin_client.h"
#include "google/cloud/bigtable/testing/mock_instance_admin_client.h"
#include "google/cloud/bigtable/testing/mock_response_reader.h"
#include "google/cloud/testing_util/assert_ok.h"
#include "google/cloud/testing_util/scoped_log.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace bigtable {
inline namespace BIGTABLE_CLIENT_NS {
namespace {
using ::testing::Contains;
using ::testing::HasSubstr;
using ::testing::Return;
using MockAsyncLongrunningOpReader =
::google::cloud::bigtable::testing::MockAsyncResponseReader<
google::longrunning::Operation>;
namespace btadmin = google::bigtable::admin::v2;
class LoggingInstanceAdminClientTest : public ::testing::Test {
protected:
static Status TransientError() {
return Status(StatusCode::kUnavailable, "try-again");
}
testing_util::ScopedLog log_;
};
TEST_F(LoggingInstanceAdminClientTest, ListInstances) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, ListInstances).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::ListInstancesRequest request;
btadmin::ListInstancesResponse response;
auto status = stub.ListInstances(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("ListInstances")));
}
TEST_F(LoggingInstanceAdminClientTest, CreateInstance) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, CreateInstance).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::CreateInstanceRequest request;
google::longrunning::Operation response;
auto status = stub.CreateInstance(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("CreateInstance")));
}
TEST_F(LoggingInstanceAdminClientTest, UpdateInstance) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, UpdateInstance).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::PartialUpdateInstanceRequest request;
google::longrunning::Operation response;
auto status = stub.UpdateInstance(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("UpdateInstance")));
}
TEST_F(LoggingInstanceAdminClientTest, GetOperation) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, GetOperation).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
google::longrunning::GetOperationRequest request;
google::longrunning::Operation response;
auto status = stub.GetOperation(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("GetOperation")));
}
TEST_F(LoggingInstanceAdminClientTest, GetInstance) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, GetInstance).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::GetInstanceRequest request;
btadmin::Instance response;
auto status = stub.GetInstance(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("GetInstance")));
}
TEST_F(LoggingInstanceAdminClientTest, DeleteInstance) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, DeleteInstance).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::DeleteInstanceRequest request;
google::protobuf::Empty response;
auto status = stub.DeleteInstance(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("DeleteInstance")));
}
TEST_F(LoggingInstanceAdminClientTest, ListClusters) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, ListClusters).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::ListClustersRequest request;
btadmin::ListClustersResponse response;
auto status = stub.ListClusters(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("ListClusters")));
}
TEST_F(LoggingInstanceAdminClientTest, GetCluster) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, GetCluster).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::GetClusterRequest request;
btadmin::Cluster response;
auto status = stub.GetCluster(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("GetCluster")));
}
TEST_F(LoggingInstanceAdminClientTest, DeleteCluster) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, DeleteCluster).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::DeleteClusterRequest request;
google::protobuf::Empty response;
auto status = stub.DeleteCluster(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("DeleteCluster")));
}
TEST_F(LoggingInstanceAdminClientTest, CreateCluster) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, CreateCluster).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::CreateClusterRequest request;
google::longrunning::Operation response;
auto status = stub.CreateCluster(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("CreateCluster")));
}
TEST_F(LoggingInstanceAdminClientTest, UpdateCluster) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, UpdateCluster).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::Cluster request;
google::longrunning::Operation response;
auto status = stub.UpdateCluster(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("UpdateCluster")));
}
TEST_F(LoggingInstanceAdminClientTest, CreateAppProfile) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, CreateAppProfile).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::CreateAppProfileRequest request;
btadmin::AppProfile response;
auto status = stub.CreateAppProfile(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("CreateAppProfile")));
}
TEST_F(LoggingInstanceAdminClientTest, GetAppProfile) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, GetAppProfile).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::GetAppProfileRequest request;
btadmin::AppProfile response;
auto status = stub.GetAppProfile(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("GetAppProfile")));
}
TEST_F(LoggingInstanceAdminClientTest, ListAppProfiles) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, ListAppProfiles).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::ListAppProfilesRequest request;
btadmin::ListAppProfilesResponse response;
auto status = stub.ListAppProfiles(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("ListAppProfiles")));
}
TEST_F(LoggingInstanceAdminClientTest, UpdateAppProfile) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, UpdateAppProfile).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::UpdateAppProfileRequest request;
google::longrunning::Operation response;
auto status = stub.UpdateAppProfile(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("UpdateAppProfile")));
}
TEST_F(LoggingInstanceAdminClientTest, DeleteAppProfile) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, DeleteAppProfile).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::DeleteAppProfileRequest request;
google::protobuf::Empty response;
auto status = stub.DeleteAppProfile(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("DeleteAppProfile")));
}
TEST_F(LoggingInstanceAdminClientTest, GetIamPolicy) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, GetIamPolicy).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
google::iam::v1::GetIamPolicyRequest request;
google::iam::v1::Policy response;
auto status = stub.GetIamPolicy(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("GetIamPolicy")));
}
TEST_F(LoggingInstanceAdminClientTest, SetIamPolicy) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, SetIamPolicy).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
google::iam::v1::SetIamPolicyRequest request;
google::iam::v1::Policy response;
auto status = stub.SetIamPolicy(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("SetIamPolicy")));
}
TEST_F(LoggingInstanceAdminClientTest, TestIamPermissions) {
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, TestIamPermissions).WillOnce(Return(grpc::Status()));
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
google::iam::v1::TestIamPermissionsRequest request;
google::iam::v1::TestIamPermissionsResponse response;
auto status = stub.TestIamPermissions(&context, request, &response);
EXPECT_TRUE(status.ok());
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("TestIamPermissions")));
}
TEST_F(LoggingInstanceAdminClientTest, AsyncCreateInstance) {
auto reader = absl::make_unique<MockAsyncLongrunningOpReader>();
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, AsyncCreateInstance)
.WillOnce([&reader](grpc::ClientContext*,
btadmin::CreateInstanceRequest const&,
grpc::CompletionQueue*) {
return std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<
google::longrunning::Operation>>(reader.get());
});
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::CreateInstanceRequest request;
grpc::CompletionQueue cq;
stub.AsyncCreateInstance(&context, request, &cq);
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("AsyncCreateInstance")));
}
TEST_F(LoggingInstanceAdminClientTest, AsyncUpdateInstance) {
auto reader = absl::make_unique<MockAsyncLongrunningOpReader>();
auto mock = std::make_shared<testing::MockInstanceAdminClient>();
EXPECT_CALL(*mock, AsyncUpdateInstance)
.WillOnce([&reader](grpc::ClientContext*,
btadmin::PartialUpdateInstanceRequest const&,
grpc::CompletionQueue*) {
return std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<
google::longrunning::Operation>>(reader.get());
});
internal::LoggingInstanceAdminClient stub(
mock, TracingOptions{}.SetOptions("single_line_mode"));
grpc::ClientContext context;
btadmin::PartialUpdateInstanceRequest request;
grpc::CompletionQueue cq;
stub.AsyncUpdateInstance(&context, request, &cq);
EXPECT_THAT(log_.ExtractLines(), Contains(HasSubstr("AsyncUpdateInstance")));
}
} // namespace
} // namespace BIGTABLE_CLIENT_NS
} // namespace bigtable
} // namespace cloud
} // namespace google
| 33.309255 | 79 | 0.756506 |
80eb98790843ae825cc31caf05545e7d7fc50507 | 1,382 | hpp | C++ | src/frontmatter/frontmatter.hpp | foo-dogsquared/automate-md | c278c7ab93d34da198ce409556a8e2df287f4b17 | [
"MIT"
] | 4 | 2018-09-29T17:00:16.000Z | 2022-01-23T14:53:04.000Z | src/frontmatter/frontmatter.hpp | foo-dogsquared/automate-md | c278c7ab93d34da198ce409556a8e2df287f4b17 | [
"MIT"
] | 5 | 2018-11-06T15:45:17.000Z | 2018-12-11T13:39:31.000Z | src/frontmatter/frontmatter.hpp | foo-dogsquared/automate-md | c278c7ab93d34da198ce409556a8e2df287f4b17 | [
"MIT"
] | null | null | null | #include <map>
#include <regex>
#define MAX_ARR_LENGTH 16
#define MAX_DATE_LENGTH 26
#define MAX_TITLE_LENGTH 64
#define MAX_AUTHOR_LENGTH 32
typedef struct _frontmatter
{
std::map<std::string, std::string> list;
int categories_length;
int tags_length;
std::string type;
std::string __open_divider;
std::string __close_divider;
std::string __tab;
std::string __assigner;
std::string __space;
}
frontmatter;
static void init_fm_format_data(frontmatter &__fm) {
if (__fm.type == "YAML" || __fm.type == "yaml") {
__fm.__open_divider = "---";
__fm.__close_divider = "---";
__fm.__tab = "";
__fm.__assigner = ":";
__fm.__space = "";
}
else if (__fm.type == "TOML" || __fm.type == "toml") {
__fm.__open_divider = "+++";
__fm.__close_divider = "+++";
__fm.__tab = "";
__fm.__assigner = "=";
__fm.__space = " ";
}
else if (__fm.type == "JSON" || __fm.type == "json") {
__fm.__open_divider = "{";
__fm.__close_divider = "}";
__fm.__tab = "\t";
__fm.__assigner = ":";
__fm.__space = "";
}
}
static std::string detect_type(std::string __str) {
std::regex __YAML("---\\s*"), __TOML("\\+\\+\\+\\s*"), __JSON("\\{\\s*|\\}\\s*");
if (std::regex_match(__str, __YAML))
return "YAML";
else if (std::regex_match(__str, __TOML))
return "TOML";
else if (std::regex_match(__str, __JSON))
return "JSON";
else
return nullptr;
}
| 23.827586 | 82 | 0.631693 |
80ed2ad5b3adb1be832fa47ad9ed66fd518e0574 | 4,219 | hpp | C++ | src/base/interpolator/Interpolator.hpp | rockstorm101/GMAT | 00b6b61a40560c095da3d83dab4ab1e9157f01c7 | [
"Apache-2.0"
] | 1 | 2018-09-18T07:09:36.000Z | 2018-09-18T07:09:36.000Z | src/base/interpolator/Interpolator.hpp | rockstorm101/GMAT | 00b6b61a40560c095da3d83dab4ab1e9157f01c7 | [
"Apache-2.0"
] | null | null | null | src/base/interpolator/Interpolator.hpp | rockstorm101/GMAT | 00b6b61a40560c095da3d83dab4ab1e9157f01c7 | [
"Apache-2.0"
] | 2 | 2020-06-18T04:45:30.000Z | 2021-07-20T02:11:54.000Z | //$Id$
//------------------------------------------------------------------------------
// Interpolator
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2015 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number S-67573-G
//
// Author: Darrel J. Conway
// Created: 2003/09/23
//
/**
* Definition for the Interpolator base class
*/
//------------------------------------------------------------------------------
#ifndef Interpolator_hpp
#define Interpolator_hpp
#include "GmatBase.hpp"
/**
* Base class for the GMAT Interpolators
*/
class GMAT_API Interpolator : public GmatBase
{
public:
Interpolator(const std::string &name, const std::string &typestr,
Integer dim = 1);
virtual ~Interpolator();
Interpolator(const Interpolator &i);
Interpolator& operator=(const Interpolator &i);
virtual Integer IsInterpolationFeasible(Real ind);
virtual void SetForceInterpolation(bool flag);
virtual bool GetForceInterpolation();
virtual bool AddPoint(const Real ind, const Real *data);
virtual void Clear();
virtual Integer GetBufferSize();
virtual Integer GetPointCount();
//---------------------------------------------------------------------------
// bool Interpolate(const Real ind, Real *results)
//---------------------------------------------------------------------------
/**
* Interpolate the data.
*
* Derived classes implement this method to provide the mathematics that
* perform the data interpolation, resulint in an array of interpolated data
* valid at the desired value of the independent variable.
*
* @param <ind> Value of the independent variable at which the data is
* interpolated.
* @param <results> Array of interpolated data.
*
* @return true on success, false (or throw) on failure.
*/
//---------------------------------------------------------------------------
virtual bool Interpolate(const Real ind, Real *results) = 0;
DEFAULT_TO_NO_CLONES
DEFAULT_TO_NO_REFOBJECTS
protected:
/// Data array used for the independent variable
Real *independent;
/// The data that gets interpolated
Real **dependent;
/// Previous independent value, used to determine direction data is going
Real previousX;
// Parameters
/// Number of dependent points to be interpolated
Integer dimension;
/// Number of points required to interpolate
Integer requiredPoints;
/// Number of points managed by the interpolator
Integer bufferSize;
/// Number of points fed to the interpolator
Integer pointCount;
/// Pointer to most recent point, for the ring buffer implementation
Integer latestPoint;
/// Valid range for the data points
Real range[2];
/// Flag used to detect if range has already been calculated
bool rangeCalculated;
/// Flag used to determine if independent variable increases or decreases
bool dataIncreases;
/// Flag used for additional feasiblity checking
bool forceInterpolation;
virtual void AllocateArrays();
virtual void CleanupArrays();
virtual void CopyArrays(const Interpolator &i);
void SetRange();
};
#endif // Interpolator_hpp
| 35.158333 | 81 | 0.604172 |
80ee8e5fcad8c9774fabe3dc0d0081079af6ae80 | 4,849 | cc | C++ | lite/backends/nnadapter/nnadapter/driver/huawei_ascend_npu/converter/pool2d.cc | ChinaCYong/Paddle-Lite | 8d161bd76c86445c42f00421983e389c11323797 | [
"Apache-2.0"
] | 1 | 2021-07-12T10:46:19.000Z | 2021-07-12T10:46:19.000Z | lite/backends/nnadapter/nnadapter/driver/huawei_ascend_npu/converter/pool2d.cc | fuaq/Paddle-Lite | 56e1239410d976842fc6f7792de13c9d007d253f | [
"Apache-2.0"
] | null | null | null | lite/backends/nnadapter/nnadapter/driver/huawei_ascend_npu/converter/pool2d.cc | fuaq/Paddle-Lite | 56e1239410d976842fc6f7792de13c9d007d253f | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "driver/huawei_ascend_npu/converter.h"
#include "utility/debug.h"
#include "utility/logging.h"
namespace nnadapter {
namespace huawei_ascend_npu {
int Program::ConvertPool2D(hal::Operation* operation) {
auto& input_operands = operation->input_operands;
auto& output_operands = operation->output_operands;
auto input_count = input_operands.size();
auto output_count = output_operands.size();
NNADAPTER_CHECK_EQ(input_count, 12);
NNADAPTER_CHECK_EQ(output_count, 1);
// Input
auto input_operand = input_operands[0];
NNADAPTER_VLOG(5) << "input: " << OperandToString(input_operand);
// Paddings
auto padding_width_left =
*reinterpret_cast<int32_t*>(input_operands[1]->buffer);
auto padding_width_right =
*reinterpret_cast<int32_t*>(input_operands[2]->buffer);
auto padding_height_top =
*reinterpret_cast<int32_t*>(input_operands[3]->buffer);
auto padding_height_bottom =
*reinterpret_cast<int32_t*>(input_operands[4]->buffer);
NNADAPTER_VLOG(5) << "paddings=[" << padding_width_left << ","
<< padding_width_right << "," << padding_height_top << ","
<< padding_height_bottom << "]";
// Strides
auto stride_width = *reinterpret_cast<int32_t*>(input_operands[5]->buffer);
auto stride_height = *reinterpret_cast<int32_t*>(input_operands[6]->buffer);
NNADAPTER_VLOG(5) << "strides=[" << stride_width << "," << stride_height
<< "]";
// Filter
auto filter_width = *reinterpret_cast<int32_t*>(input_operands[7]->buffer);
auto filter_height = *reinterpret_cast<int32_t*>(input_operands[8]->buffer);
NNADAPTER_VLOG(5) << "filter=[" << filter_width << "," << filter_height
<< "]";
bool global_pooling = filter_width == input_operand->type.dimensions[3] &&
filter_height == input_operand->type.dimensions[2];
NNADAPTER_VLOG(5) << "global_pooling=" << global_pooling;
// Fuse code
auto fuse_code = *reinterpret_cast<int32_t*>(input_operands[9]->buffer);
NNADAPTER_VLOG(5) << "fuse_code=" << fuse_code;
// Ceil mode
bool ceil_mode = *reinterpret_cast<int8_t*>(input_operands[10]->buffer);
NNADAPTER_VLOG(5) << "ceil_mode=" << ceil_mode;
// Count include pad
bool count_include_pad =
*reinterpret_cast<int8_t*>(input_operands[11]->buffer);
NNADAPTER_VLOG(5) << "count_include_pad=" << count_include_pad;
// Output
auto output_operand = output_operands[0];
NNADAPTER_VLOG(5) << "output: " << OperandToString(output_operand);
// Convert to GE operators
auto input_operator = GetMappedOperator(input_operand);
if (!input_operator) {
input_operator = ConvertOperand(input_operand);
}
auto pool2d_name = GetOperatorName(output_operand);
auto pool2d_op = std::make_shared<ge::op::Pooling>(pool2d_name);
if (operation->type == NNADAPTER_AVERAGE_POOL_2D) {
pool2d_op->set_attr_mode(1);
NNADAPTER_CHECK(!count_include_pad) << "Only count_include_pad=false is "
"supported for the pooling type "
"'avg' in GE";
} else if (operation->type == NNADAPTER_MAX_POOL_2D) {
pool2d_op->set_attr_mode(0);
} else {
NNADAPTER_LOG(FATAL) << "Unsupported pooling operation type "
<< OperationTypeToString(operation->type)
<< " is found.";
}
pool2d_op->set_attr_global_pooling(global_pooling);
pool2d_op->set_attr_window(
ge::Operator::OpListInt({filter_height, filter_width}));
pool2d_op->set_attr_pad(ge::Operator::OpListInt({padding_height_bottom,
padding_height_top,
padding_width_right,
padding_width_left}));
pool2d_op->set_attr_stride(
ge::Operator::OpListInt({stride_height, stride_width}));
// "0" (ceil mode) or "1" (floor mode). Defaults to "0"
if (!ceil_mode) {
pool2d_op->set_attr_ceil_mode(1);
}
SET_INPUT(pool2d_op, x, input_operator);
MAP_OUTPUT(pool2d_op, y, output_operand);
return NNADAPTER_NO_ERROR;
}
} // namespace huawei_ascend_npu
} // namespace nnadapter
| 44.081818 | 78 | 0.670241 |
80ef0d8a50449bb2b90ce59f752fc9c46bbcd66d | 4,254 | cpp | C++ | Userland/Libraries/LibWeb/Layout/Label.cpp | r00ster91/serenity | f8387dea2689d564aff612bfd4ec5086393fac35 | [
"BSD-2-Clause"
] | 19,438 | 2019-05-20T15:11:11.000Z | 2022-03-31T23:31:32.000Z | Userland/Libraries/LibWeb/Layout/Label.cpp | r00ster91/serenity | f8387dea2689d564aff612bfd4ec5086393fac35 | [
"BSD-2-Clause"
] | 7,882 | 2019-05-20T01:03:52.000Z | 2022-03-31T23:26:31.000Z | Userland/Libraries/LibWeb/Layout/Label.cpp | r00ster91/serenity | f8387dea2689d564aff612bfd4ec5086393fac35 | [
"BSD-2-Clause"
] | 2,721 | 2019-05-23T00:44:57.000Z | 2022-03-31T22:49:34.000Z | /*
* Copyright (c) 2021, Tim Flynn <trflynn89@pm.me>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibGUI/Event.h>
#include <LibGfx/Painter.h>
#include <LibGfx/StylePainter.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/HTML/BrowsingContext.h>
#include <LibWeb/Layout/InitialContainingBlock.h>
#include <LibWeb/Layout/Label.h>
#include <LibWeb/Layout/LabelableNode.h>
#include <LibWeb/Layout/TextNode.h>
namespace Web::Layout {
Label::Label(DOM::Document& document, HTML::HTMLLabelElement* element, NonnullRefPtr<CSS::StyleProperties> style)
: BlockContainer(document, element, move(style))
{
}
Label::~Label()
{
}
void Label::handle_mousedown_on_label(Badge<TextNode>, const Gfx::IntPoint&, unsigned button)
{
if (button != GUI::MouseButton::Primary)
return;
if (auto* control = control_node(); control)
control->handle_associated_label_mousedown({});
m_tracking_mouse = true;
}
void Label::handle_mouseup_on_label(Badge<TextNode>, const Gfx::IntPoint& position, unsigned button)
{
if (!m_tracking_mouse || button != GUI::MouseButton::Primary)
return;
// NOTE: Changing the checked state of the DOM node may run arbitrary JS, which could disappear this node.
NonnullRefPtr protect = *this;
if (auto* control = control_node(); control) {
bool is_inside_control = enclosing_int_rect(control->absolute_rect()).contains(position);
bool is_inside_label = enclosing_int_rect(absolute_rect()).contains(position);
if (is_inside_control || is_inside_label)
control->handle_associated_label_mouseup({});
}
m_tracking_mouse = false;
}
void Label::handle_mousemove_on_label(Badge<TextNode>, const Gfx::IntPoint& position, unsigned)
{
if (!m_tracking_mouse)
return;
if (auto* control = control_node(); control) {
bool is_inside_control = enclosing_int_rect(control->absolute_rect()).contains(position);
bool is_inside_label = enclosing_int_rect(absolute_rect()).contains(position);
control->handle_associated_label_mousemove({}, is_inside_control || is_inside_label);
}
}
bool Label::is_inside_associated_label(LabelableNode& control, const Gfx::IntPoint& position)
{
if (auto* label = label_for_control_node(control); label)
return enclosing_int_rect(label->absolute_rect()).contains(position);
return false;
}
bool Label::is_associated_label_hovered(LabelableNode& control)
{
if (auto* label = label_for_control_node(control); label) {
if (label->document().hovered_node() == &label->dom_node())
return true;
if (auto* child = label->first_child_of_type<TextNode>(); child)
return label->document().hovered_node() == &child->dom_node();
}
return false;
}
Label* Label::label_for_control_node(LabelableNode& control)
{
Label* label = nullptr;
if (!control.document().layout_node())
return label;
String id = control.dom_node().attribute(HTML::AttributeNames::id);
if (id.is_empty())
return label;
control.document().layout_node()->for_each_in_inclusive_subtree_of_type<Label>([&](auto& node) {
if (node.dom_node().for_() == id) {
label = &node;
return IterationDecision::Break;
}
return IterationDecision::Continue;
});
// FIXME: The spec also allows for associating a label with a labelable node by putting the
// labelable node inside the label.
return label;
}
LabelableNode* Label::control_node()
{
LabelableNode* control = nullptr;
if (!document().layout_node())
return control;
String for_ = dom_node().for_();
if (for_.is_empty())
return control;
document().layout_node()->for_each_in_inclusive_subtree_of_type<LabelableNode>([&](auto& node) {
if (node.dom_node().attribute(HTML::AttributeNames::id) == for_) {
control = &node;
return IterationDecision::Break;
}
return IterationDecision::Continue;
});
// FIXME: The spec also allows for associating a label with a labelable node by putting the
// labelable node inside the label.
return control;
}
}
| 30.170213 | 113 | 0.683827 |
80f1149c50a621b596022f27e1eb8c5ddc1b3b2f | 4,540 | hpp | C++ | src/mat/opr/num.hpp | Thhethssmuz/mmm | ee91a990fba3849db1fc2b6df0e89004e2df466f | [
"MIT"
] | 1 | 2017-03-14T20:45:54.000Z | 2017-03-14T20:45:54.000Z | src/mat/opr/num.hpp | Thhethssmuz/mmm | ee91a990fba3849db1fc2b6df0e89004e2df466f | [
"MIT"
] | 1 | 2017-03-08T17:14:03.000Z | 2017-03-08T23:40:35.000Z | src/mat/opr/num.hpp | Thhethssmuz/mmm | ee91a990fba3849db1fc2b6df0e89004e2df466f | [
"MIT"
] | null | null | null | #pragma once
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tmat<T, N, M> operator+(T s, const tmat<T, N, M>& m);
template <typename T, typename U, size_t N, size_t M,
typename = typefu::for_arithmetic<T, U>>
constexpr tmat<T, N, M> operator+(U s, const tmat<T, N, M>& m);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tmat<T, N, M> operator+(const tmat<T, N, M>& m, T s);
template <typename T, typename U, size_t N, size_t M,
typename = typefu::for_arithmetic<T, U>>
constexpr tmat<T, N, M> operator+(const tmat<T, N, M>& m, U s);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tmat<T, N, M> operator+(const tmat<T, N, M>& m,
const tmat<T, N, M>& n);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tmat<T, N, M> operator-(T s, const tmat<T, N, M>& m);
template <typename T, typename U, size_t N, size_t M,
typename = typefu::for_arithmetic<T, U>>
constexpr tmat<T, N, M> operator-(U s, const tmat<T, N, M>& m);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tmat<T, N, M> operator-(const tmat<T, N, M>& m, T s);
template <typename T, typename U, size_t N, size_t M,
typename = typefu::for_arithmetic<T, U>>
constexpr tmat<T, N, M> operator-(const tmat<T, N, M>& m, U s);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tmat<T, N, M> operator-(const tmat<T, N, M>& m);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tmat<T, N, M> operator-(const tmat<T, N, M>& m,
const tmat<T, N, M>& n);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tmat<T, N, M> operator*(T s, const tmat<T, N, M>& m);
template <typename T, typename U, size_t N, size_t M,
typename = typefu::for_arithmetic<T, U>>
constexpr tmat<T, N, M> operator*(U s, const tmat<T, N, M>& m);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tmat<T, N, M> operator*(const tmat<T, N, M>& m, T s);
template <typename T, typename U, size_t N, size_t M,
typename = typefu::for_arithmetic<T, U>>
constexpr tmat<T, N, M> operator*(const tmat<T, N, M>& m, U s);
template <typename T, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tvec<T, 2> operator*(const tvec<T, M>& v, const tmat<T, 2, M>& m);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tvec<T, N> operator*(const tvec<T, M>& v, const tmat<T, N, M>& m);
template <typename T, size_t N, size_t M, typename A,
typename = typefu::for_arithmetic<T>>
constexpr tvec<T, N> operator*(const vecType<T, M, A>& v,
const tmat<T, N, M>& m);
template <typename T, size_t N, typename = typefu::for_arithmetic<T>>
constexpr tvec<T, 2> operator*(const tmat<T, N, 2>& m, const tvec<T, N>& v);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tvec<T, M> operator*(const tmat<T, N, M>& m, const tvec<T, N>& v);
template <typename T, size_t N, size_t M, typename A,
typename = typefu::for_arithmetic<T>>
constexpr tvec<T, M> operator*(const tmat<T, N, M>& m,
const vecType<T, N, A>& v);
template <typename T, size_t N, size_t M, size_t O,
typename = typefu::for_arithmetic<T>>
constexpr tmat<T, O, M> operator*(const tmat<T, N, M>& m,
const tmat<T, O, N>& n);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tmat<T, N, M> operator/(T s, const tmat<T, N, M>& m);
template <typename T, typename U, size_t N, size_t M,
typename = typefu::for_arithmetic<T, U>>
constexpr tmat<T, N, M> operator/(U s, const tmat<T, N, M>& m);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tmat<T, N, M> operator/(const tmat<T, N, M>& m, T s);
template <typename T, typename U, size_t N, size_t M,
typename = typefu::for_arithmetic<T, U>>
constexpr tmat<T, N, M> operator/(const tmat<T, N, M>& m, U s);
template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>>
constexpr tmat<T, N, M> operator/(const tmat<T, N, M>& m,
const tmat<T, N, M>& n);
| 41.651376 | 79 | 0.633921 |
80f13c80ed70d799f2b000a71c7483cab558589d | 534 | cpp | C++ | src/10.cpp | wandering007/ProjectEuler | 332e1053aa8d65e764952f4133ff0f06d028136a | [
"Apache-2.0"
] | 4 | 2015-05-02T09:15:54.000Z | 2018-06-28T16:18:20.000Z | src/10.cpp | wandering007/ProjectEuler | 332e1053aa8d65e764952f4133ff0f06d028136a | [
"Apache-2.0"
] | null | null | null | src/10.cpp | wandering007/ProjectEuler | 332e1053aa8d65e764952f4133ff0f06d028136a | [
"Apache-2.0"
] | 1 | 2017-10-29T06:35:59.000Z | 2017-10-29T06:35:59.000Z | #include <iostream>
#include <vector>
int main() {
const int N = 2000000;
std::vector<int> is_prime(N, 1);
for (int k = 2; k + k < N; ++k) {
for (int j = k + k; j < N; j += k) {
is_prime[j] = 0;
}
}
long long sum_of_primes = 0; // 不能用int
for (int i = 2; i < N; ++i) {
if (1 == is_prime[i]) {
sum_of_primes += i;
}
}
std::cout << "The sum of all the primes below two million is " << sum_of_primes << std::endl;
return 0;
} | 26.7 | 98 | 0.456929 |
80f150649a995bbec45e690f159257810537b405 | 25,084 | hpp | C++ | include/RAJA/policy/hip/sort.hpp | keichi/RAJA | 8e8cc96cbccda2bfc33b14b57a8591b2cf9ca342 | [
"BSD-3-Clause"
] | null | null | null | include/RAJA/policy/hip/sort.hpp | keichi/RAJA | 8e8cc96cbccda2bfc33b14b57a8591b2cf9ca342 | [
"BSD-3-Clause"
] | null | null | null | include/RAJA/policy/hip/sort.hpp | keichi/RAJA | 8e8cc96cbccda2bfc33b14b57a8591b2cf9ca342 | [
"BSD-3-Clause"
] | null | null | null | /*!
******************************************************************************
*
* \file
*
* \brief Header file providing RAJA sort declarations.
*
******************************************************************************
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2016-22, Lawrence Livermore National Security, LLC
// and RAJA project contributors. See the RAJA/LICENSE file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#ifndef RAJA_sort_hip_HPP
#define RAJA_sort_hip_HPP
#include "RAJA/config.hpp"
#if defined(RAJA_ENABLE_HIP)
#include <climits>
#include <iterator>
#include <type_traits>
#if defined(__HIPCC__)
#define ROCPRIM_HIP_API 1
#include "rocprim/device/device_transform.hpp"
#include "rocprim/device/device_radix_sort.hpp"
#elif defined(__CUDACC__)
#include "cub/device/device_radix_sort.cuh"
#endif
#include "RAJA/util/concepts.hpp"
#include "RAJA/util/Operators.hpp"
#include "RAJA/pattern/detail/algorithm.hpp"
#include "RAJA/policy/hip/MemUtils_HIP.hpp"
#include "RAJA/policy/hip/policy.hpp"
namespace RAJA
{
namespace impl
{
namespace sort
{
namespace detail
{
#if defined(__HIPCC__)
template < typename R >
using double_buffer = ::rocprim::double_buffer<R>;
#elif defined(__CUDACC__)
template < typename R >
using double_buffer = ::cub::DoubleBuffer<R>;
#endif
template < typename R >
R* get_current(double_buffer<R>& d_bufs)
{
#if defined(__HIPCC__)
return d_bufs.current();
#elif defined(__CUDACC__)
return d_bufs.Current();
#endif
}
}
/*!
\brief static assert unimplemented stable sort
*/
template <size_t BLOCK_SIZE, bool Async, typename Iter, typename Compare>
concepts::enable_if_t<resources::EventProxy<resources::Hip>,
concepts::negate<concepts::all_of<
type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>,
std::is_pointer<Iter>,
concepts::any_of<
camp::is_same<Compare, operators::less<RAJA::detail::IterVal<Iter>>>,
camp::is_same<Compare, operators::greater<RAJA::detail::IterVal<Iter>>>>>>>
stable(
resources::Hip hip_res,
hip_exec<BLOCK_SIZE, Async>,
Iter,
Iter,
Compare)
{
static_assert(concepts::all_of<
type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>,
std::is_pointer<Iter>,
concepts::any_of<
camp::is_same<Compare, operators::less<RAJA::detail::IterVal<Iter>>>,
camp::is_same<Compare, operators::greater<RAJA::detail::IterVal<Iter>>>>>::value,
"RAJA stable_sort<hip_exec> is only implemented for pointers to arithmetic types and RAJA::operators::less and RAJA::operators::greater.");
return resources::EventProxy<resources::Hip>(hip_res);
}
/*!
\brief stable sort given range in ascending order
*/
template <size_t BLOCK_SIZE, bool Async, typename Iter>
concepts::enable_if_t<resources::EventProxy<resources::Hip>,
type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>,
std::is_pointer<Iter>>
stable(
resources::Hip hip_res,
hip_exec<BLOCK_SIZE, Async>,
Iter begin,
Iter end,
operators::less<RAJA::detail::IterVal<Iter>>)
{
hipStream_t stream = hip_res.get_stream();
using R = RAJA::detail::IterVal<Iter>;
int len = std::distance(begin, end);
int begin_bit=0;
int end_bit=sizeof(R)*CHAR_BIT;
// Allocate temporary storage for the output array
R* d_out = hip::device_mempool_type::getInstance().malloc<R>(len);
// use cub double buffer to reduce temporary memory requirements
// by allowing cub to write to the begin buffer
detail::double_buffer<R> d_keys(begin, d_out);
// Determine temporary device storage requirements
void* d_temp_storage = nullptr;
size_t temp_storage_bytes = 0;
#if defined(__HIPCC__)
hipErrchk(::rocprim::radix_sort_keys(d_temp_storage,
temp_storage_bytes,
d_keys,
len,
begin_bit,
end_bit,
stream));
#elif defined(__CUDACC__)
cudaErrchk(::cub::DeviceRadixSort::SortKeys(d_temp_storage,
temp_storage_bytes,
d_keys,
len,
begin_bit,
end_bit,
stream));
#endif
// Allocate temporary storage
d_temp_storage =
hip::device_mempool_type::getInstance().malloc<unsigned char>(
temp_storage_bytes);
// Run
#if defined(__HIPCC__)
hipErrchk(::rocprim::radix_sort_keys(d_temp_storage,
temp_storage_bytes,
d_keys,
len,
begin_bit,
end_bit,
stream));
#elif defined(__CUDACC__)
cudaErrchk(::cub::DeviceRadixSort::SortKeys(d_temp_storage,
temp_storage_bytes,
d_keys,
len,
begin_bit,
end_bit,
stream));
#endif
// Free temporary storage
hip::device_mempool_type::getInstance().free(d_temp_storage);
if (detail::get_current(d_keys) == d_out) {
// copy
hipErrchk(hipMemcpyAsync(begin, d_out, len*sizeof(R), hipMemcpyDefault, stream));
}
hip::device_mempool_type::getInstance().free(d_out);
hip::launch(hip_res, Async);
return resources::EventProxy<resources::Hip>(hip_res);
}
/*!
\brief stable sort given range in descending order
*/
template <size_t BLOCK_SIZE, bool Async, typename Iter>
concepts::enable_if_t<resources::EventProxy<resources::Hip>,
type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>,
std::is_pointer<Iter>>
stable(
resources::Hip hip_res,
hip_exec<BLOCK_SIZE, Async>,
Iter begin,
Iter end,
operators::greater<RAJA::detail::IterVal<Iter>>)
{
hipStream_t stream = hip_res.get_stream();
using R = RAJA::detail::IterVal<Iter>;
int len = std::distance(begin, end);
int begin_bit=0;
int end_bit=sizeof(R)*CHAR_BIT;
// Allocate temporary storage for the output array
R* d_out = hip::device_mempool_type::getInstance().malloc<R>(len);
// use cub double buffer to reduce temporary memory requirements
// by allowing cub to write to the begin buffer
detail::double_buffer<R> d_keys(begin, d_out);
// Determine temporary device storage requirements
void* d_temp_storage = nullptr;
size_t temp_storage_bytes = 0;
#if defined(__HIPCC__)
hipErrchk(::rocprim::radix_sort_keys_desc(d_temp_storage,
temp_storage_bytes,
d_keys,
len,
begin_bit,
end_bit,
stream));
#elif defined(__CUDACC__)
cudaErrchk(::cub::DeviceRadixSort::SortKeysDescending(d_temp_storage,
temp_storage_bytes,
d_keys,
len,
begin_bit,
end_bit,
stream));
#endif
// Allocate temporary storage
d_temp_storage =
hip::device_mempool_type::getInstance().malloc<unsigned char>(
temp_storage_bytes);
// Run
#if defined(__HIPCC__)
hipErrchk(::rocprim::radix_sort_keys_desc(d_temp_storage,
temp_storage_bytes,
d_keys,
len,
begin_bit,
end_bit,
stream));
#elif defined(__CUDACC__)
cudaErrchk(::cub::DeviceRadixSort::SortKeysDescending(d_temp_storage,
temp_storage_bytes,
d_keys,
len,
begin_bit,
end_bit,
stream));
#endif
// Free temporary storage
hip::device_mempool_type::getInstance().free(d_temp_storage);
if (detail::get_current(d_keys) == d_out) {
// copy
hipErrchk(hipMemcpyAsync(begin, d_out, len*sizeof(R), hipMemcpyDefault, stream));
}
hip::device_mempool_type::getInstance().free(d_out);
hip::launch(hip_res, Async);
return resources::EventProxy<resources::Hip>(hip_res);
}
/*!
\brief static assert unimplemented sort
*/
template <size_t BLOCK_SIZE, bool Async, typename Iter, typename Compare>
concepts::enable_if_t<resources::EventProxy<resources::Hip>,
concepts::negate<concepts::all_of<
type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>,
std::is_pointer<Iter>,
concepts::any_of<
camp::is_same<Compare, operators::less<RAJA::detail::IterVal<Iter>>>,
camp::is_same<Compare, operators::greater<RAJA::detail::IterVal<Iter>>>>>>>
unstable(
resources::Hip hip_res,
hip_exec<BLOCK_SIZE, Async>,
Iter,
Iter,
Compare)
{
static_assert(concepts::all_of<
type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>,
std::is_pointer<Iter>,
concepts::any_of<
camp::is_same<Compare, operators::less<RAJA::detail::IterVal<Iter>>>,
camp::is_same<Compare, operators::greater<RAJA::detail::IterVal<Iter>>>>>::value,
"RAJA sort<hip_exec> is only implemented for pointers to arithmetic types and RAJA::operators::less and RAJA::operators::greater.");
return resources::EventProxy<resources::Hip>(hip_res);
}
/*!
\brief sort given range in ascending order
*/
template <size_t BLOCK_SIZE, bool Async, typename Iter>
concepts::enable_if_t<resources::EventProxy<resources::Hip>,
type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>,
std::is_pointer<Iter>>
unstable(
resources::Hip hip_res,
hip_exec<BLOCK_SIZE, Async> p,
Iter begin,
Iter end,
operators::less<RAJA::detail::IterVal<Iter>> comp)
{
return stable(hip_res, p, begin, end, comp);
}
/*!
\brief sort given range in descending order
*/
template <size_t BLOCK_SIZE, bool Async, typename Iter>
concepts::enable_if_t<resources::EventProxy<resources::Hip>,
type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>,
std::is_pointer<Iter>>
unstable(
resources::Hip hip_res,
hip_exec<BLOCK_SIZE, Async> p,
Iter begin,
Iter end,
operators::greater<RAJA::detail::IterVal<Iter>> comp)
{
return stable(hip_res, p, begin, end, comp);
}
/*!
\brief static assert unimplemented stable sort pairs
*/
template <size_t BLOCK_SIZE, bool Async,
typename KeyIter, typename ValIter, typename Compare>
concepts::enable_if_t<resources::EventProxy<resources::Hip>,
concepts::negate<concepts::all_of<
type_traits::is_arithmetic<RAJA::detail::IterVal<KeyIter>>,
std::is_pointer<KeyIter>,
std::is_pointer<ValIter>,
concepts::any_of<
camp::is_same<Compare, operators::less<RAJA::detail::IterVal<KeyIter>>>,
camp::is_same<Compare, operators::greater<RAJA::detail::IterVal<KeyIter>>>>>>>
stable_pairs(
resources::Hip hip_res,
hip_exec<BLOCK_SIZE, Async>,
KeyIter,
KeyIter,
ValIter,
Compare)
{
static_assert (std::is_pointer<KeyIter>::value,
"stable_sort_pairs<hip_exec> is only implemented for pointers");
static_assert (std::is_pointer<ValIter>::value,
"stable_sort_pairs<hip_exec> is only implemented for pointers");
using K = RAJA::detail::IterVal<KeyIter>;
static_assert (type_traits::is_arithmetic<K>::value,
"stable_sort_pairs<hip_exec> is only implemented for arithmetic types");
static_assert (concepts::any_of<
camp::is_same<Compare, operators::less<K>>,
camp::is_same<Compare, operators::greater<K>>>::value,
"stable_sort_pairs<hip_exec> is only implemented for RAJA::operators::less or RAJA::operators::greater");
return resources::EventProxy<resources::Hip>(hip_res);
}
/*!
\brief stable sort given range of pairs in ascending order of keys
*/
template <size_t BLOCK_SIZE, bool Async,
typename KeyIter, typename ValIter>
concepts::enable_if_t<resources::EventProxy<resources::Hip>,
type_traits::is_arithmetic<RAJA::detail::IterVal<KeyIter>>,
std::is_pointer<KeyIter>,
std::is_pointer<ValIter>>
stable_pairs(
resources::Hip hip_res,
hip_exec<BLOCK_SIZE, Async>,
KeyIter keys_begin,
KeyIter keys_end,
ValIter vals_begin,
operators::less<RAJA::detail::IterVal<KeyIter>>)
{
hipStream_t stream = hip_res.get_stream();
using K = RAJA::detail::IterVal<KeyIter>;
using V = RAJA::detail::IterVal<ValIter>;
int len = std::distance(keys_begin, keys_end);
int begin_bit=0;
int end_bit=sizeof(K)*CHAR_BIT;
// Allocate temporary storage for the output arrays
K* d_keys_out = hip::device_mempool_type::getInstance().malloc<K>(len);
V* d_vals_out = hip::device_mempool_type::getInstance().malloc<V>(len);
// use cub double buffer to reduce temporary memory requirements
// by allowing cub to write to the keys_begin and vals_begin buffers
detail::double_buffer<K> d_keys(keys_begin, d_keys_out);
detail::double_buffer<V> d_vals(vals_begin, d_vals_out);
// Determine temporary device storage requirements
void* d_temp_storage = nullptr;
size_t temp_storage_bytes = 0;
#if defined(__HIPCC__)
hipErrchk(::rocprim::radix_sort_pairs(d_temp_storage,
temp_storage_bytes,
d_keys,
d_vals,
len,
begin_bit,
end_bit,
stream));
#elif defined(__CUDACC__)
cudaErrchk(::cub::DeviceRadixSort::SortPairs(d_temp_storage,
temp_storage_bytes,
d_keys,
d_vals,
len,
begin_bit,
end_bit,
stream));
#endif
// Allocate temporary storage
d_temp_storage =
hip::device_mempool_type::getInstance().malloc<unsigned char>(
temp_storage_bytes);
// Run
#if defined(__HIPCC__)
hipErrchk(::rocprim::radix_sort_pairs(d_temp_storage,
temp_storage_bytes,
d_keys,
d_vals,
len,
begin_bit,
end_bit,
stream));
#elif defined(__CUDACC__)
cudaErrchk(::cub::DeviceRadixSort::SortPairs(d_temp_storage,
temp_storage_bytes,
d_keys,
d_vals,
len,
begin_bit,
end_bit,
stream));
#endif
// Free temporary storage
hip::device_mempool_type::getInstance().free(d_temp_storage);
if (detail::get_current(d_keys) == d_keys_out) {
// copy keys
hipErrchk(hipMemcpyAsync(keys_begin, d_keys_out, len*sizeof(K), hipMemcpyDefault, stream));
}
if (detail::get_current(d_vals) == d_vals_out) {
// copy vals
hipErrchk(hipMemcpyAsync(vals_begin, d_vals_out, len*sizeof(V), hipMemcpyDefault, stream));
}
hip::device_mempool_type::getInstance().free(d_keys_out);
hip::device_mempool_type::getInstance().free(d_vals_out);
hip::launch(hip_res, Async);
return resources::EventProxy<resources::Hip>(hip_res);
}
/*!
\brief stable sort given range of pairs in descending order of keys
*/
template <size_t BLOCK_SIZE, bool Async,
typename KeyIter, typename ValIter>
concepts::enable_if_t<resources::EventProxy<resources::Hip>,
type_traits::is_arithmetic<RAJA::detail::IterVal<KeyIter>>,
std::is_pointer<KeyIter>,
std::is_pointer<ValIter>>
stable_pairs(
resources::Hip hip_res,
hip_exec<BLOCK_SIZE, Async>,
KeyIter keys_begin,
KeyIter keys_end,
ValIter vals_begin,
operators::greater<RAJA::detail::IterVal<KeyIter>>)
{
hipStream_t stream = hip_res.get_stream();
using K = RAJA::detail::IterVal<KeyIter>;
using V = RAJA::detail::IterVal<ValIter>;
int len = std::distance(keys_begin, keys_end);
int begin_bit=0;
int end_bit=sizeof(K)*CHAR_BIT;
// Allocate temporary storage for the output arrays
K* d_keys_out = hip::device_mempool_type::getInstance().malloc<K>(len);
V* d_vals_out = hip::device_mempool_type::getInstance().malloc<V>(len);
// use cub double buffer to reduce temporary memory requirements
// by allowing cub to write to the keys_begin and vals_begin buffers
detail::double_buffer<K> d_keys(keys_begin, d_keys_out);
detail::double_buffer<V> d_vals(vals_begin, d_vals_out);
// Determine temporary device storage requirements
void* d_temp_storage = nullptr;
size_t temp_storage_bytes = 0;
#if defined(__HIPCC__)
hipErrchk(::rocprim::radix_sort_pairs_desc(d_temp_storage,
temp_storage_bytes,
d_keys,
d_vals,
len,
begin_bit,
end_bit,
stream));
#elif defined(__CUDACC__)
cudaErrchk(::cub::DeviceRadixSort::SortPairsDescending(d_temp_storage,
temp_storage_bytes,
d_keys,
d_vals,
len,
begin_bit,
end_bit,
stream));
#endif
// Allocate temporary storage
d_temp_storage =
hip::device_mempool_type::getInstance().malloc<unsigned char>(
temp_storage_bytes);
// Run
#if defined(__HIPCC__)
hipErrchk(::rocprim::radix_sort_pairs_desc(d_temp_storage,
temp_storage_bytes,
d_keys,
d_vals,
len,
begin_bit,
end_bit,
stream));
#elif defined(__CUDACC__)
cudaErrchk(::cub::DeviceRadixSort::SortPairsDescending(d_temp_storage,
temp_storage_bytes,
d_keys,
d_vals,
len,
begin_bit,
end_bit,
stream));
#endif
// Free temporary storage
hip::device_mempool_type::getInstance().free(d_temp_storage);
if (detail::get_current(d_keys) == d_keys_out) {
// copy keys
hipErrchk(hipMemcpyAsync(keys_begin, d_keys_out, len*sizeof(K), hipMemcpyDefault, stream));
}
if (detail::get_current(d_vals) == d_vals_out) {
// copy vals
hipErrchk(hipMemcpyAsync(vals_begin, d_vals_out, len*sizeof(V), hipMemcpyDefault, stream));
}
hip::device_mempool_type::getInstance().free(d_keys_out);
hip::device_mempool_type::getInstance().free(d_vals_out);
hip::launch(hip_res, Async);
return resources::EventProxy<resources::Hip>(hip_res);
}
/*!
\brief static assert unimplemented sort pairs
*/
template <size_t BLOCK_SIZE, bool Async,
typename KeyIter, typename ValIter, typename Compare>
concepts::enable_if_t<resources::EventProxy<resources::Hip>,
concepts::negate<concepts::all_of<
type_traits::is_arithmetic<RAJA::detail::IterVal<KeyIter>>,
std::is_pointer<KeyIter>,
std::is_pointer<ValIter>,
concepts::any_of<
camp::is_same<Compare, operators::less<RAJA::detail::IterVal<KeyIter>>>,
camp::is_same<Compare, operators::greater<RAJA::detail::IterVal<KeyIter>>>>>>>
unstable_pairs(
resources::Hip hip_res,
hip_exec<BLOCK_SIZE, Async>,
KeyIter,
KeyIter,
ValIter,
Compare)
{
static_assert (std::is_pointer<KeyIter>::value,
"sort_pairs<hip_exec> is only implemented for pointers");
static_assert (std::is_pointer<ValIter>::value,
"sort_pairs<hip_exec> is only implemented for pointers");
using K = RAJA::detail::IterVal<KeyIter>;
static_assert (type_traits::is_arithmetic<K>::value,
"sort_pairs<hip_exec> is only implemented for arithmetic types");
static_assert (concepts::any_of<
camp::is_same<Compare, operators::less<K>>,
camp::is_same<Compare, operators::greater<K>>>::value,
"sort_pairs<hip_exec> is only implemented for RAJA::operators::less or RAJA::operators::greater");
return resources::EventProxy<resources::Hip>(hip_res);
}
/*!
\brief stable sort given range of pairs in ascending order of keys
*/
template <size_t BLOCK_SIZE, bool Async,
typename KeyIter, typename ValIter>
concepts::enable_if_t<resources::EventProxy<resources::Hip>,
type_traits::is_arithmetic<RAJA::detail::IterVal<KeyIter>>,
std::is_pointer<KeyIter>,
std::is_pointer<ValIter>>
unstable_pairs(
resources::Hip hip_res,
hip_exec<BLOCK_SIZE, Async> p,
KeyIter keys_begin,
KeyIter keys_end,
ValIter vals_begin,
operators::less<RAJA::detail::IterVal<KeyIter>> comp)
{
return stable_pairs(hip_res, p, keys_begin, keys_end, vals_begin, comp);
}
/*!
\brief stable sort given range of pairs in descending order of keys
*/
template <size_t BLOCK_SIZE, bool Async,
typename KeyIter, typename ValIter>
concepts::enable_if_t<resources::EventProxy<resources::Hip>,
type_traits::is_arithmetic<RAJA::detail::IterVal<KeyIter>>,
std::is_pointer<KeyIter>,
std::is_pointer<ValIter>>
unstable_pairs(
resources::Hip hip_res,
hip_exec<BLOCK_SIZE, Async> p,
KeyIter keys_begin,
KeyIter keys_end,
ValIter vals_begin,
operators::greater<RAJA::detail::IterVal<KeyIter>> comp)
{
return stable_pairs(hip_res, p, keys_begin, keys_end, vals_begin, comp);
}
} // namespace sort
} // namespace impl
} // namespace RAJA
#endif // closing endif for RAJA_ENABLE_HIP guard
#endif // closing endif for header file include guard
| 37.271917 | 155 | 0.54772 |
80f1a3fe3290d70601a0530de0edda17489931b1 | 42 | cpp | C++ | 2018/day15/day15/graph.cpp | zagura/aoc-2017 | bfd38fb6fbe4211017a306d218b32ecff741e006 | [
"MIT"
] | 2 | 2018-12-09T16:00:09.000Z | 2018-12-09T17:56:15.000Z | 2018/day15/day15/graph.cpp | zagura/aoc-2017 | bfd38fb6fbe4211017a306d218b32ecff741e006 | [
"MIT"
] | null | null | null | 2018/day15/day15/graph.cpp | zagura/aoc-2017 | bfd38fb6fbe4211017a306d218b32ecff741e006 | [
"MIT"
] | null | null | null | #include "graph.hpp"
Graph::Graph()
{
}
| 6 | 20 | 0.595238 |
80f3d98b065279779da3a4fa531dcb89099b8e50 | 14,935 | cc | C++ | modules/perception/obstacle/camera/converter/geometry_camera_converter.cc | DinnerHowe/apollo | f45b63ea2f2409dbd1b007476d816d6ec44ba06c | [
"Apache-2.0"
] | 19 | 2018-07-26T03:17:32.000Z | 2021-01-04T02:17:09.000Z | modules/perception/obstacle/camera/converter/geometry_camera_converter.cc | DinnerHowe/apollo | f45b63ea2f2409dbd1b007476d816d6ec44ba06c | [
"Apache-2.0"
] | null | null | null | modules/perception/obstacle/camera/converter/geometry_camera_converter.cc | DinnerHowe/apollo | f45b63ea2f2409dbd1b007476d816d6ec44ba06c | [
"Apache-2.0"
] | 10 | 2018-10-17T03:18:16.000Z | 2020-07-02T06:18:14.000Z | /******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
// Convert 2D detections into 3D objects
#include "modules/perception/obstacle/camera/converter/geometry_camera_converter.h"
namespace apollo {
namespace perception {
bool GeometryCameraConverter::Init() {
ConfigManager *config_manager = ConfigManager::instance();
const ModelConfig *model_config = config_manager->GetModelConfig(Name());
if (model_config == nullptr) {
AERROR << "Model config: " << Name() << " not found";
return false;
}
std::string intrinsic_file_path = "";
if (!model_config->GetValue("camera_intrinsic_file", &intrinsic_file_path)) {
AERROR << "Failed to get camera intrinsics file path: " << Name();
return false;
}
if (!LoadCameraIntrinsics(intrinsic_file_path)) {
AERROR << "Failed to get camera intrinsics: " << intrinsic_file_path;
return false;
}
return true;
}
bool GeometryCameraConverter::Convert(std::vector<VisualObjectPtr> *objects) {
if (!objects) return false;
for (auto &obj : *objects) {
Eigen::Vector2f trunc_center_pixel = Eigen::Vector2f::Zero();
CheckTruncation(obj, &trunc_center_pixel);
CheckSizeSanity(obj);
float deg_alpha = obj->alpha * 180.0f / M_PI;
Eigen::Vector2f upper_left(obj->upper_left.x(), obj->upper_left.y());
Eigen::Vector2f lower_right(obj->lower_right.x(), obj->lower_right.y());
float distance_w = 0.0;
float distance_h = 0.0;
Eigen::Vector2f mass_center_pixel = Eigen::Vector2f::Zero();
ConvertSingle(obj->height, obj->width, obj->length, deg_alpha, upper_left,
lower_right, &distance_w, &distance_h, &mass_center_pixel);
if (obj->trunc_width > 0.25f && obj->trunc_height > 0.25f) {
// Give fix values for detected box with both side and bottom truncation
distance_w = distance_h = 10.0f;
obj->distance = DecideDistance(distance_h, distance_w, obj);
// Estimation of center pixel due to unknown truncation ratio
if (obj->trunc_width > 0.25f) mass_center_pixel = trunc_center_pixel;
} else if (distance_w > 40.0f || distance_h > 40.0f
|| obj->trunc_width > 0.25f) {
// Reset alpha angle and redo again (Model dependent issue)
obj->distance = DecideDistance(distance_h, distance_w, obj);
DecideAngle(camera_model_.unproject(mass_center_pixel), obj);
deg_alpha = obj->alpha * 180.0f / M_PI;
ConvertSingle(obj->height, obj->width, obj->length, deg_alpha, upper_left,
lower_right, &distance_w, &distance_h, &mass_center_pixel);
}
obj->distance = DecideDistance(distance_h, distance_w, obj);
Eigen::Vector3f camera_ray = camera_model_.unproject(mass_center_pixel);
DecideAngle(camera_ray, obj);
// Center (3D Mass Center of 3D BBox)
float scale = obj->distance / sqrt(camera_ray.x() * camera_ray.x() +
camera_ray.y() * camera_ray.y() +
camera_ray.z() * camera_ray.z());
obj->center = camera_ray * scale;
// Set 8 corner pixels
obj->pts8.resize(16);
if (obj->trunc_width < 0.25f && obj->trunc_height < 0.25f) {
for (int i = 0; i < 8; i++) {
obj->pts8[i * 2] = pixel_corners_[i].x();
obj->pts8[i * 2 + 1] = pixel_corners_[i].y();
}
}
}
return true;
}
void GeometryCameraConverter::SetDebug(bool flag) { debug_ = flag; }
std::string GeometryCameraConverter::Name() const {
return "GeometryCameraConverter";
}
bool GeometryCameraConverter::LoadCameraIntrinsics(
const std::string &file_path) {
YAML::Node node = YAML::LoadFile(file_path);
Eigen::Matrix3f intrinsic_k;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
int index = i * 3 + j;
intrinsic_k(i, j) = node["K"][index].as<float>();
}
}
Eigen::Matrix<float, 5, 1> intrinsic_d;
for (int i = 0; i < 5; i++) {
intrinsic_d(i, 0) = node["D"][i].as<float>();
}
float height = node["height"].as<float>();
float width = node["width"].as<float>();
camera_model_.set(intrinsic_k, width, height);
camera_model_.set_distort_params(intrinsic_d);
return true;
}
bool GeometryCameraConverter::ConvertSingle(
const float &h, const float &w, const float &l, const float &alpha_deg,
const Eigen::Vector2f &upper_left, const Eigen::Vector2f &lower_right,
float *distance_w, float *distance_h, Eigen::Vector2f *mass_center_pixel) {
// Target Goals: Projection target
int pixel_width = static_cast<int>(lower_right.x() - upper_left.x());
int pixel_height = static_cast<int>(lower_right.y() - upper_left.y());
// Target Goals: Box center pixel
Eigen::Matrix<float, 2, 1> box_center_pixel;
box_center_pixel.x() = (lower_right.x() + upper_left.x()) / 2.0f;
box_center_pixel.y() = (lower_right.y() + upper_left.y()) / 2.0f;
// Generate alpha rotated 3D template here. Corners in Camera space:
// Bottom: FL, FR, RR, RL => Top: FL, FR, RR, RL
float deg_alpha = alpha_deg;
float h_half = h / 2.0f;
float w_half = w / 2.0f;
float l_half = l / 2.0f;
std::vector<Eigen::Vector3f> corners;
corners.resize(8);
corners[0] = Eigen::Vector3f(l_half, h_half, w_half);
corners[1] = Eigen::Vector3f(l_half, h_half, -w_half);
corners[2] = Eigen::Vector3f(-l_half, h_half, -w_half);
corners[3] = Eigen::Vector3f(-l_half, h_half, w_half);
corners[4] = Eigen::Vector3f(l_half, -h_half, w_half);
corners[5] = Eigen::Vector3f(l_half, -h_half, -w_half);
corners[6] = Eigen::Vector3f(-l_half, -h_half, -w_half);
corners[7] = Eigen::Vector3f(-l_half, -h_half, w_half);
Rotate(deg_alpha, &corners);
corners_ = corners;
pixel_corners_.clear();
pixel_corners_.resize(8);
// Try to get an initial Mass center pixel and vector
Eigen::Matrix<float, 3, 1> middle_v(0.0f, 0.0f, 20.0f);
Eigen::Matrix<float, 2, 1> center_pixel = camera_model_.project(middle_v);
float max_pixel_x = std::numeric_limits<float>::min();
float min_pixel_x = std::numeric_limits<float>::max();
float max_pixel_y = std::numeric_limits<float>::min();
float min_pixel_y = std::numeric_limits<float>::max();
for (size_t i = 0; i < corners.size(); ++i) {
Eigen::Vector2f point_2d = camera_model_.project(corners[i] + middle_v);
min_pixel_x = std::min(min_pixel_x, point_2d.x());
max_pixel_x = std::max(max_pixel_x, point_2d.x());
min_pixel_y = std::min(min_pixel_y, point_2d.y());
max_pixel_y = std::max(max_pixel_y, point_2d.y());
}
float relative_x =
(center_pixel.x() - min_pixel_x) / (max_pixel_x - min_pixel_x);
float relative_y =
(center_pixel.y() - min_pixel_y) / (max_pixel_y - min_pixel_y);
mass_center_pixel->x() =
(lower_right.x() - upper_left.x()) * relative_x + upper_left.x();
mass_center_pixel->y() =
(lower_right.y() - upper_left.y()) * relative_y + upper_left.y();
Eigen::Matrix<float, 3, 1> mass_center_v =
camera_model_.unproject(*mass_center_pixel);
mass_center_v = MakeUnit(mass_center_v);
// Binary search
*distance_w = SearchDistance(pixel_width, true, mass_center_v);
*distance_h = SearchDistance(pixel_height, false, mass_center_v);
for (size_t i = 0; i < 2; ++i) {
// Mass center search
SearchCenterDirection(box_center_pixel, *distance_h, &mass_center_v,
mass_center_pixel);
// Binary search
*distance_w = SearchDistance(pixel_width, true, mass_center_v);
*distance_h = SearchDistance(pixel_height, false, mass_center_v);
}
return true;
}
void GeometryCameraConverter::Rotate(
const float &alpha_deg, std::vector<Eigen::Vector3f> *corners) const {
Eigen::AngleAxisf yaw(alpha_deg / 180.0f * M_PI, Eigen::Vector3f::UnitY());
Eigen::AngleAxisf pitch(0.0, Eigen::Vector3f::UnitX());
Eigen::AngleAxisf roll(0.0, Eigen::Vector3f::UnitZ());
Eigen::Matrix3f rotation = yaw.toRotationMatrix() * pitch.toRotationMatrix() *
roll.toRotationMatrix();
Eigen::Matrix4f transform;
transform.setIdentity();
transform.block(0, 0, 3, 3) = rotation;
for (auto &corner : *corners) {
Eigen::Vector4f temp(corner.x(), corner.y(), corner.z(), 1.0f);
temp = transform * temp;
corner = Eigen::Vector3f(temp.x(), temp.y(), temp.z());
}
}
float GeometryCameraConverter::SearchDistance(
const int &pixel_length, const bool &use_width,
const Eigen::Matrix<float, 3, 1> &mass_center_v) {
float close_d = 0.1f;
float far_d = 200.0f;
float curr_d = 0.0f;
int depth = 0;
while (close_d <= far_d && depth < kMaxDistanceSearchDepth_) {
curr_d = (far_d + close_d) / 2.0f;
Eigen::Vector3f curr_p = mass_center_v * curr_d;
float min_p = std::numeric_limits<float>::max();
float max_p = 0.0f;
for (size_t i = 0; i < corners_.size(); ++i) {
Eigen::Vector2f point_2d = camera_model_.project(corners_[i] + curr_p);
pixel_corners_[i] = point_2d;
float curr_pixel = 0.0f;
if (use_width) {
curr_pixel = point_2d.x();
} else {
curr_pixel = point_2d.y();
}
min_p = std::min(min_p, curr_pixel);
max_p = std::max(max_p, curr_pixel);
}
int curr_pixel_length = static_cast<int>(max_p - min_p);
if (curr_pixel_length == pixel_length) {
break;
} else if (pixel_length < curr_pixel_length) {
close_d = curr_d + 0.01f;
} else { // pixel_length > curr_pixel_length
far_d = curr_d - 0.01f;
}
// Early break for 0.01m accuracy
float next_d = (far_d + close_d) / 2.0f;
if (std::abs(next_d - curr_d) < 0.01f) {
break;
}
++depth;
}
return curr_d;
}
void GeometryCameraConverter::SearchCenterDirection(
const Eigen::Matrix<float, 2, 1> &box_center_pixel, const float &curr_d,
Eigen::Matrix<float, 3, 1> *mass_center_v,
Eigen::Matrix<float, 2, 1> *mass_center_pixel) const {
int depth = 0;
while (depth < kMaxCenterDirectionSearchDepth_) {
Eigen::Matrix<float, 3, 1> new_center_v = *mass_center_v * curr_d;
float max_pixel_x = std::numeric_limits<float>::min();
float min_pixel_x = std::numeric_limits<float>::max();
float max_pixel_y = std::numeric_limits<float>::min();
float min_pixel_y = std::numeric_limits<float>::max();
for (size_t i = 0; i < corners_.size(); ++i) {
Eigen::Vector2f point_2d =
camera_model_.project(corners_[i] + new_center_v);
min_pixel_x = std::min(min_pixel_x, point_2d.x());
max_pixel_x = std::max(max_pixel_x, point_2d.x());
min_pixel_y = std::min(min_pixel_y, point_2d.y());
max_pixel_y = std::max(max_pixel_y, point_2d.y());
}
Eigen::Matrix<float, 2, 1> current_box_center_pixel;
current_box_center_pixel.x() = (max_pixel_x + min_pixel_x) / 2.0;
current_box_center_pixel.y() = (max_pixel_y + min_pixel_y) / 2.0;
// Update mass center
*mass_center_pixel += box_center_pixel - current_box_center_pixel;
*mass_center_v = camera_model_.unproject(*mass_center_pixel);
*mass_center_v = MakeUnit(*mass_center_v);
if (std::abs(mass_center_pixel->x() - box_center_pixel.x()) < 1.0 &&
std::abs(mass_center_pixel->y() - box_center_pixel.y()) < 1.0) {
break;
}
++depth;
}
return;
}
Eigen::Matrix<float, 3, 1> GeometryCameraConverter::MakeUnit(
const Eigen::Matrix<float, 3, 1> &v) const {
Eigen::Matrix<float, 3, 1> unit_v = v;
float to_unit_scale =
std::sqrt(unit_v.x() * unit_v.x() + unit_v.y() * unit_v.y() +
unit_v.z() * unit_v.z());
unit_v /= to_unit_scale;
return unit_v;
}
void GeometryCameraConverter::CheckSizeSanity(VisualObjectPtr obj) const {
if (obj->type == ObjectType::VEHICLE) {
obj->length = std::max(obj->length, 3.6f);
obj->width = std::max(obj->width, 1.6f);
obj->height = std::max(obj->height, 1.5f);
} else if (obj->type == ObjectType::PEDESTRIAN) {
obj->length = std::max(obj->length, 0.5f);
obj->width = std::max(obj->width, 0.5f);
obj->height = std::max(obj->height, 1.7f);
} else if (obj->type == ObjectType::BICYCLE) {
obj->length = std::max(obj->length, 1.8f);
obj->width = std::max(obj->width, 1.2f);
obj->height = std::max(obj->height, 1.5f);
} else {
obj->length = std::max(obj->length, 0.5f);
obj->width = std::max(obj->width, 0.5f);
obj->height = std::max(obj->height, 1.5f);
}
}
void GeometryCameraConverter::CheckTruncation(VisualObjectPtr obj,
Eigen::Matrix<float, 2, 1> *trunc_center_pixel) const {
auto width = camera_model_.get_width();
auto height = camera_model_.get_height();
// Ad-hoc 2D box truncation binary determination
if (obj->upper_left.x() < 30.0f || width - 30.0f < obj->lower_right.x()) {
obj->trunc_width = 0.5f;
trunc_center_pixel->y() = (obj->upper_left.y()
+ obj->lower_right.y()) / 2.0f;
if (obj->upper_left.x() < 30.0f) {
trunc_center_pixel->x() = obj->upper_left.x();
} else {
trunc_center_pixel->x() = obj->lower_right.x();
}
}
if (obj->upper_left.y() < 30.0f || height - 30.0f < obj->lower_right.y()) {
obj->trunc_height = 0.5f;
}
}
float GeometryCameraConverter::DecideDistance(const float &distance_h,
const float &distance_w,
VisualObjectPtr obj) const {
float distance = distance_h;
// TODO(later): Deal with truncation
return distance;
}
void GeometryCameraConverter::DecideAngle(const Eigen::Vector3f &camera_ray,
VisualObjectPtr obj) const {
float beta = std::atan2(camera_ray.x(), camera_ray.z());
// Orientation is not reliable in these cases (DL model specific issue)
if (obj->distance > 50.0f || obj->trunc_width > 0.25f) {
obj->theta = -1.0f * M_PI_2;
obj->alpha = obj->theta - beta;
if (obj->alpha > M_PI) {
obj->alpha -= 2 * M_PI;
} else if (obj->alpha < -M_PI) {
obj->alpha += 2 * M_PI;
}
} else { // Normal cases
float theta = obj->alpha + beta;
if (theta > M_PI) {
theta -= 2 * M_PI;
} else if (theta < -M_PI) {
theta += 2 * M_PI;
}
obj->theta = theta;
}
}
} // namespace perception
} // namespace apollo
| 36.3382 | 83 | 0.640509 |
80f457acb73146c1efd6b335b61609bd3182ebbc | 2,890 | cpp | C++ | StepEditor/RawResponseDlg.cpp | edwig/Kwatta | ce1ca2907608e65ed62d7dbafa9ab1d030caccfe | [
"MIT"
] | 1 | 2021-12-31T17:20:01.000Z | 2021-12-31T17:20:01.000Z | StepEditor/RawResponseDlg.cpp | edwig/Kwatta | ce1ca2907608e65ed62d7dbafa9ab1d030caccfe | [
"MIT"
] | 10 | 2022-01-14T13:28:32.000Z | 2022-02-13T12:46:34.000Z | StepEditor/RawResponseDlg.cpp | edwig/Kwatta | ce1ca2907608e65ed62d7dbafa9ab1d030caccfe | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
// ██╗░░██╗░██╗░░░░░░░██╗░█████╗░████████╗████████╗░█████╗░
// ██║░██╔╝░██║░░██╗░░██║██╔══██╗╚══██╔══╝╚══██╔══╝██╔══██╗
// █████═╝░░╚██╗████╗██╔╝███████║░░░██║░░░░░░██║░░░███████║
// ██╔═██╗░░░████╔═████║░██╔══██║░░░██║░░░░░░██║░░░██╔══██║
// ██║░╚██╗░░╚██╔╝░╚██╔╝░██║░░██║░░░██║░░░░░░██║░░░██║░░██║
// ╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░╚═╝░░╚═╝░░░╚═╝░░░░░░╚═╝░░░╚═╝░░╚═╝
//
//
// This product: KWATTA (KWAliTy Test API) Test suite for Command-line SOAP/JSON/HTTP internet API's
// This program: StepEditor
// This File : RawResponseDlg.cpp
// What it does: Resulting raw response of a HTTP internet test call
// Author : ir. W.E. Huisman
// License : See license.md file in the root directory
//
///////////////////////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "StepEditor.h"
#include "TestStepNET.h"
#include "StepResultNET.h"
#include "RawResponseDlg.h"
#include "StepInternetDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#define new DEBUG_NEW
#endif
// RawResponseDlg dialog
IMPLEMENT_DYNAMIC(RawResponseDlg,StyleDialog)
RawResponseDlg::RawResponseDlg(CWnd* pParent /*=nullptr*/)
:StyleDialog(IDD_RAW_RESPONSE,pParent)
{
}
RawResponseDlg::~RawResponseDlg()
{
}
void
RawResponseDlg::DoDataExchange(CDataExchange* pDX)
{
StyleDialog::DoDataExchange(pDX);
DDX_Control(pDX,IDC_RAW,m_editPayload,m_payload);
}
BEGIN_MESSAGE_MAP(RawResponseDlg,StyleDialog)
ON_EN_KILLFOCUS(IDC_RAW,&RawResponseDlg::OnEnKillfocusPayload)
END_MESSAGE_MAP()
BOOL
RawResponseDlg::OnInitDialog()
{
StyleDialog::OnInitDialog();
InitPayload();
SetCanResize();
return TRUE;
}
void
RawResponseDlg::SetupDynamicLayout()
{
StyleDialog::SetupDynamicLayout();
CMFCDynamicLayout& manager = *GetDynamicLayout();
#ifdef _DEBUG
manager.AssertValid();
#endif
manager.AddItem(IDC_RAW,CMFCDynamicLayout::MoveNone(),CMFCDynamicLayout::SizeHorizontalAndVertical(100,100));
}
void
RawResponseDlg::InitPayload()
{
m_editPayload.SetFontName("Courier new",100);
m_editPayload.SetMutable(false);
}
void
RawResponseDlg::InitTab()
{
m_payload.Empty();
UpdateData(FALSE);
}
void
RawResponseDlg::SetResult(StepResultNET* p_result)
{
m_payload = p_result->GetRawResponse();
m_payload.Replace("\n","\r\n");
UpdateData(FALSE);
}
void
RawResponseDlg::StoreVariables()
{
// Nothing to do
}
// RawResponseDlg message handlers
void
RawResponseDlg::OnEnKillfocusPayload()
{
// Getting the payload as body for the message
UpdateData();
if(m_testStep)
{
m_testStep->SetBody(m_payload);
// Check parameters
StepInternetDlg* step = reinterpret_cast<StepInternetDlg*>(GetParent()->GetParent());
step->EffectiveParameters();
}
}
| 22.403101 | 111 | 0.597924 |
80f6bc462b24e46667b580c21423f59b1e35b003 | 226 | cpp | C++ | Engine/Source/Runtime/Engine/Private/AI/Navigation/NavAreas/NavArea_Default.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Engine/Private/AI/Navigation/NavAreas/NavArea_Default.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Engine/Private/AI/Navigation/NavAreas/NavArea_Default.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "AI/Navigation/NavAreas/NavArea_Default.h"
UNavArea_Default::UNavArea_Default(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
}
| 28.25 | 106 | 0.809735 |
80f9094b2e531ee4919911441a2d788de2d55135 | 2,871 | hpp | C++ | hpx/performance_counters/parcels/count_time_stats.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/performance_counters/parcels/count_time_stats.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/performance_counters/parcels/count_time_stats.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 Katelyn Kufahl
//
// 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)
////////////////////////////////////////////////////////////////////////////////
#if !defined(HPX_05A1C29B_DB73_463A_8C9D_B8EDC3B69F5E)
#define HPX_05A1C29B_DB73_463A_8C9D_B8EDC3B69F5E
#include <boost/config.hpp>
#include <boost/assert.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/cstdint.hpp>
#include <boost/atomic.hpp>
#include <hpx/performance_counters/parcels/count_and_time_data_point.hpp>
#include <hpx/util/high_resolution_timer.hpp>
#include <hpx/util/spinlock.hpp>
namespace hpx { namespace performance_counters { namespace parcels
{
class count_time_stats
{
typedef hpx::util::spinlock mutex_type;
typedef mutex_type::scoped_lock lock;
typedef boost::accumulators::accumulator_set acc_set;
public:
count_time_stats():
count_time_stats_size(0)
{}
boost::int64_t size() const;
void push_back(data_point const& x);
double mean_time() const;
double moment_time() const;
double variance_time() const;
double total_time() const;
private:
util::high_resolution_timer timer;
boost::atomic<boost::int64_t> count_time_stats_size;
// Create mutexes for accumulator functions.
mutable mutex_type acc_mtx;
// Create accumulator sets.
acc_set < double,
boost::accumulators::features< boost::accumulators::tag::mean > >
mean_time_acc;
acc_set < double,
boost::accumulators::features< boost::accumulators::tag::moment<2> > >
moment_time_acc;
acc_set < double,
boost::accumulators::features< boost::accumulators::tag::variance> >
variance_time_acc;
};
inline void count_time_stats::push_back(count_and_time_data_point const& x)
{
lock mtx(acc_mtx)
++count_time_stats_size;
mean_time_acc(x.time);
moment_time_acc(x.time);
variance_time_acc(x.time);
}
inline boost::int64_t count_time_stats::size() const
{
return count_time_stats_size.load();
}
inline double count_time_stats::mean_time() const
{
lock mtx(acc_mtx);
return boost::accumulators::extract::mean(mean_time_acc);
}
inline double count_time_stats::moment_time() const
{
lock mtx(acc_mtx);
return boost::accumulators::extract::moment<2>(moment_time_acc);
}
inline double count_time_stats::variance_time() const
{
lock mtx(acc_mtx);
return boost::accumulators::extract::variance(variance_time_acc);
}
}}}
#endif // HPX_05A1C29B_DB73_463A_8C9D_B8EDC3B69F5E
| 26.831776 | 80 | 0.695925 |
80fc1f458a79c0de61a543dd5740af2af132a74f | 12,484 | hpp | C++ | libs/core/algorithms/include/hpx/parallel/algorithms/detail/dispatch.hpp | Andrea-MariaDB-2/hpx | e230dddce4a8783817f38e07f5a77e624f64f826 | [
"BSL-1.0"
] | 1,822 | 2015-01-03T11:22:37.000Z | 2022-03-31T14:49:59.000Z | libs/core/algorithms/include/hpx/parallel/algorithms/detail/dispatch.hpp | Andrea-MariaDB-2/hpx | e230dddce4a8783817f38e07f5a77e624f64f826 | [
"BSL-1.0"
] | 3,288 | 2015-01-05T17:00:23.000Z | 2022-03-31T18:49:41.000Z | libs/core/algorithms/include/hpx/parallel/algorithms/detail/dispatch.hpp | Andrea-MariaDB-2/hpx | e230dddce4a8783817f38e07f5a77e624f64f826 | [
"BSL-1.0"
] | 431 | 2015-01-07T06:22:14.000Z | 2022-03-31T14:50:04.000Z | // Copyright (c) 2007-2017 Hartmut Kaiser
// Copyright (c) 2021 Giannis Gonidelis
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#pragma once
#include <hpx/config.hpp>
#include <hpx/algorithms/traits/segmented_iterator_traits.hpp>
#include <hpx/concepts/concepts.hpp>
#include <hpx/datastructures/tuple.hpp>
#include <hpx/execution/executors/execution.hpp>
#include <hpx/executors/exception_list.hpp>
#include <hpx/executors/execution_policy.hpp>
#include <hpx/futures/future.hpp>
#include <hpx/modules/errors.hpp>
#include <hpx/parallel/util/detail/algorithm_result.hpp>
#include <hpx/parallel/util/detail/scoped_executor_parameters.hpp>
#include <hpx/parallel/util/result_types.hpp>
#include <hpx/serialization/serialization_fwd.hpp>
#if defined(HPX_HAVE_CXX17_STD_EXECUTION_POLICES)
#include <execution>
#endif
#include <string>
#include <type_traits>
#include <utility>
namespace hpx { namespace parallel { inline namespace v1 { namespace detail {
///////////////////////////////////////////////////////////////////////////
template <typename Result>
struct local_algorithm_result
{
using type = typename hpx::traits::segmented_local_iterator_traits<
Result>::local_raw_iterator;
};
template <typename Result1, typename Result2>
struct local_algorithm_result<std::pair<Result1, Result2>>
{
using type1 = typename hpx::traits::segmented_local_iterator_traits<
Result1>::local_raw_iterator;
using type2 = typename hpx::traits::segmented_local_iterator_traits<
Result2>::local_raw_iterator;
using type = std::pair<type1, type2>;
};
template <typename Result1, typename Result2>
struct local_algorithm_result<util::in_out_result<Result1, Result2>>
{
using type1 = typename hpx::traits::segmented_local_iterator_traits<
Result1>::local_raw_iterator;
using type2 = typename hpx::traits::segmented_local_iterator_traits<
Result2>::local_raw_iterator;
using type = util::in_out_result<type1, type2>;
};
template <typename Result1, typename Result2, typename Result3>
struct local_algorithm_result<hpx::tuple<Result1, Result2, Result3>>
{
using type1 = typename hpx::traits::segmented_local_iterator_traits<
Result1>::local_raw_iterator;
using type2 = typename hpx::traits::segmented_local_iterator_traits<
Result2>::local_raw_iterator;
using type3 = typename hpx::traits::segmented_local_iterator_traits<
Result3>::local_raw_iterator;
using type = hpx::tuple<type1, type2, type3>;
};
template <typename Result1, typename Result2, typename Result3>
struct local_algorithm_result<
util::in_in_out_result<Result1, Result2, Result3>>
{
using type1 = typename hpx::traits::segmented_local_iterator_traits<
Result1>::local_raw_iterator;
using type2 = typename hpx::traits::segmented_local_iterator_traits<
Result2>::local_raw_iterator;
using type3 = typename hpx::traits::segmented_local_iterator_traits<
Result3>::local_raw_iterator;
using type = util::in_in_out_result<type1, type2, type3>;
};
template <>
struct local_algorithm_result<void>
{
using type = void;
};
///////////////////////////////////////////////////////////////////////////
template <typename Derived, typename Result = void>
struct algorithm
{
private:
Derived const& derived() const
{
return static_cast<Derived const&>(*this);
}
public:
using result_type = Result;
using local_result_type =
typename local_algorithm_result<result_type>::type;
explicit algorithm(char const* const name)
: name_(name)
{
}
///////////////////////////////////////////////////////////////////////
// this equivalent to sequential execution
template <typename ExPolicy, typename... Args>
HPX_HOST_DEVICE
typename parallel::util::detail::algorithm_result<ExPolicy,
local_result_type>::type
operator()(ExPolicy&& policy, Args&&... args) const
{
#if !defined(__CUDA_ARCH__)
try
{
#endif
using parameters_type = typename std::decay<
ExPolicy>::type::executor_parameters_type;
using executor_type =
typename std::decay<ExPolicy>::type::executor_type;
parallel::util::detail::scoped_executor_parameters_ref<
parameters_type, executor_type>
scoped_param(policy.parameters(), policy.executor());
return parallel::util::detail::
algorithm_result<ExPolicy, local_result_type>::get(
Derived::sequential(std::forward<ExPolicy>(policy),
std::forward<Args>(args)...));
#if !defined(__CUDA_ARCH__)
}
catch (...)
{
// this does not return
return detail::handle_exception<ExPolicy,
local_result_type>::call();
}
#endif
}
protected:
///////////////////////////////////////////////////////////////////////
template <typename ExPolicy, typename... Args>
constexpr typename parallel::util::detail::algorithm_result<ExPolicy,
local_result_type>::type
call_execute(ExPolicy&& policy, std::false_type, Args&&... args) const
{
using result = parallel::util::detail::algorithm_result<ExPolicy,
local_result_type>;
return result::get(execution::sync_execute(policy.executor(),
derived(), std::forward<ExPolicy>(policy),
std::forward<Args>(args)...));
}
template <typename ExPolicy, typename... Args>
constexpr
typename parallel::util::detail::algorithm_result<ExPolicy>::type
call_execute(
ExPolicy&& policy, std::true_type, Args&&... args) const
{
execution::sync_execute(policy.executor(), derived(),
std::forward<ExPolicy>(policy), std::forward<Args>(args)...);
return parallel::util::detail::algorithm_result<ExPolicy>::get();
}
///////////////////////////////////////////////////////////////////////
template <typename ExPolicy, typename... Args>
typename parallel::util::detail::algorithm_result<ExPolicy,
local_result_type>::type
call_sequential(ExPolicy&& policy, Args&&... args) const
{
try
{
// run the launched task on the requested executor
hpx::future<local_result_type> result =
execution::async_execute(policy.executor(), derived(),
std::forward<ExPolicy>(policy),
std::forward<Args>(args)...);
return parallel::util::detail::algorithm_result<ExPolicy,
local_result_type>::get(std::move(result));
}
catch (std::bad_alloc const& ba)
{
throw ba;
}
catch (...)
{
return detail::handle_exception<ExPolicy,
local_result_type>::call();
}
}
public:
///////////////////////////////////////////////////////////////////////
// main sequential dispatch entry points
// specialization for all task-based (asynchronous) execution policies
// clang-format off
template <typename ExPolicy, typename... Args,
HPX_CONCEPT_REQUIRES_(
hpx::is_async_execution_policy_v<std::decay_t<ExPolicy>>
)>
// clang-format on
constexpr typename parallel::util::detail::algorithm_result<ExPolicy,
local_result_type>::type
call2(ExPolicy&& policy, std::true_type, Args&&... args) const
{
return call_sequential(
std::forward<ExPolicy>(policy), std::forward<Args>(args)...);
}
// clang-format off
template <typename ExPolicy, typename... Args,
HPX_CONCEPT_REQUIRES_(
!hpx::is_async_execution_policy_v<std::decay_t<ExPolicy>>
)>
// clang-format on
typename parallel::util::detail::algorithm_result<ExPolicy,
local_result_type>::type
call2(ExPolicy&& policy, std::true_type, Args&&... args) const
{
try
{
using is_void = std::is_void<local_result_type>;
return call_execute(std::forward<ExPolicy>(policy), is_void(),
std::forward<Args>(args)...);
}
catch (std::bad_alloc const& ba)
{
throw ba;
}
catch (...)
{
return detail::handle_exception<ExPolicy,
local_result_type>::call();
}
}
// main parallel dispatch entry point
template <typename ExPolicy, typename... Args>
static constexpr
typename parallel::util::detail::algorithm_result<ExPolicy,
local_result_type>::type
call2(ExPolicy&& policy, std::false_type, Args&&... args)
{
return Derived::parallel(
std::forward<ExPolicy>(policy), std::forward<Args>(args)...);
}
template <typename ExPolicy, typename... Args>
HPX_FORCEINLINE constexpr
typename parallel::util::detail::algorithm_result<ExPolicy,
local_result_type>::type
call(ExPolicy&& policy, Args&&... args)
{
using is_seq = hpx::is_sequenced_execution_policy<ExPolicy>;
return call2(std::forward<ExPolicy>(policy), is_seq(),
std::forward<Args>(args)...);
}
#if defined(HPX_HAVE_CXX17_STD_EXECUTION_POLICES)
// main dispatch entry points for std execution policies
template <typename... Args>
HPX_FORCEINLINE constexpr
typename parallel::util::detail::algorithm_result<
hpx::execution::sequenced_policy, local_result_type>::type
call(std::execution::sequenced_policy, Args&&... args)
{
return call2(hpx::execution::seq, std::true_type(),
std::forward<Args>(args)...);
}
template <typename... Args>
HPX_FORCEINLINE constexpr
typename parallel::util::detail::algorithm_result<
hpx::execution::parallel_policy, local_result_type>::type
call(std::execution::parallel_policy, Args&&... args)
{
return call2(hpx::execution::par, std::false_type(),
std::forward<Args>(args)...);
}
template <typename... Args>
HPX_FORCEINLINE constexpr
typename parallel::util::detail::algorithm_result<
hpx::execution::parallel_unsequenced_policy,
local_result_type>::type
call(std::execution::parallel_unsequenced_policy, Args&&... args)
{
return call2(hpx::execution::par_unseq, std::false_type(),
std::forward<Args>(args)...);
}
#if defined(HPX_HAVE_CXX20_STD_EXECUTION_POLICES)
template <typename... Args>
HPX_FORCEINLINE constexpr
typename parallel::util::detail::algorithm_result<
hpx::execution::unsequenced_policy, local_result_type>::type
call(std::execution::unsequenced_policy, Args&&... args)
{
return call2(hpx::execution::unseq, std::false_type(),
std::forward<Args>(args)...);
}
#endif
#endif
private:
char const* const name_;
friend class hpx::serialization::access;
template <typename Archive>
void serialize(Archive&, unsigned int)
{
// no need to serialize 'name_' as it is always initialized by the
// constructor
}
};
}}}} // namespace hpx::parallel::v1::detail
| 37.377246 | 80 | 0.577539 |
80fd9445db389266bd3811e34ba54dcf7ca678d3 | 532 | cpp | C++ | lab0/Q5.cpp | jasonsie88/Algorithm | 4d373df037aa68f4810e271d7f8488f3ded81864 | [
"MIT"
] | 1 | 2021-09-14T12:10:50.000Z | 2021-09-14T12:10:50.000Z | lab0/Q5.cpp | jasonsie88/Algorithm | 4d373df037aa68f4810e271d7f8488f3ded81864 | [
"MIT"
] | null | null | null | lab0/Q5.cpp | jasonsie88/Algorithm | 4d373df037aa68f4810e271d7f8488f3ded81864 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main(){
int ncase;
while(cin>>ncase){
if(ncase==0){
break;
}
int a1[ncase+5],a2[ncase+5];
for(int i=0;i<ncase;i++){
cin>>a1[i]>>a2[i];
}
bool flag=true;
if(ncase%2){
cout<<"NO\n";
}else{
sort(a1,a1+ncase);
sort(a2,a2+ncase);
for(int i=0;i<ncase;i++){
if(a1[i]!=a2[i]){
flag=false;
break;
}
}
if(flag){
cout<<"YES\n";
}else{
cout<<"NO\n";
}
}
}
return 0;
}
| 14 | 33 | 0.456767 |
80febcc662731b8104dbabdf1bfd52b7ff8bab4d | 25,134 | cpp | C++ | wznmcmbd/IexWznm/JobWznmIexIex.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | 3 | 2020-09-20T16:24:48.000Z | 2021-12-01T19:44:51.000Z | wznmcmbd/IexWznm/JobWznmIexIex.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | wznmcmbd/IexWznm/JobWznmIexIex.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | /**
* \file JobWznmIexIex.cpp
* job handler for job JobWznmIexIex (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 28 Nov 2020
*/
// IP header --- ABOVE
#ifdef WZNMCMBD
#include <Wznmcmbd.h>
#else
#include <Wznmd.h>
#endif
#include "JobWznmIexIex.h"
#include "JobWznmIexIex_blks.cpp"
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
// IP ns.cust --- INSERT
using namespace IexWznmIex;
/******************************************************************************
class JobWznmIexIex
******************************************************************************/
JobWznmIexIex::JobWznmIexIex(
XchgWznm* xchg
, DbsWznm* dbswznm
, const ubigint jrefSup
, const uint ixWznmVLocale
) :
JobWznm(xchg, VecWznmVJob::JOBWZNMIEXIEX, jrefSup, ixWznmVLocale)
{
jref = xchg->addJob(dbswznm, this, jrefSup);
// IP constructor.cust1 --- INSERT
// IP constructor.cust2 --- INSERT
changeStage(dbswznm, VecVSge::IDLE);
// IP constructor.cust3 --- INSERT
};
JobWznmIexIex::~JobWznmIexIex() {
// IP destructor.spec --- INSERT
// IP destructor.cust --- INSERT
xchg->removeJobByJref(jref);
};
// IP cust --- INSERT
void JobWznmIexIex::reset(
DbsWznm* dbswznm
) {
if (ixVSge != VecVSge::IDLE) changeStage(dbswznm, VecVSge::IDLE);
};
void JobWznmIexIex::parseFromFile(
DbsWznm* dbswznm
, const string& _fullpath
, const bool _xmlNotTxt
, const string& _rectpath
) {
if (ixVSge == VecVSge::IDLE) {
fullpath = _fullpath;
xmlNotTxt = _xmlNotTxt;
rectpath = _rectpath;
changeStage(dbswznm, VecVSge::PARSE);
};
};
void JobWznmIexIex::import(
DbsWznm* dbswznm
) {
if (ixVSge == VecVSge::PRSDONE) changeStage(dbswznm, VecVSge::IMPORT);
};
void JobWznmIexIex::reverse(
DbsWznm* dbswznm
) {
if (ixVSge == VecVSge::IMPERR) changeStage(dbswznm, VecVSge::REVERSE);
};
void JobWznmIexIex::collect(
DbsWznm* dbswznm
, const map<uint,uint>& _icsWznmVIop
) {
if (ixVSge == VecVSge::IDLE) {
icsWznmVIop = _icsWznmVIop;
changeStage(dbswznm, VecVSge::COLLECT);
};
};
void JobWznmIexIex::exportToFile(
DbsWznm* dbswznm
, const string& _fullpath
, const bool _xmlNotTxt
, const bool _shorttags
) {
if ((ixVSge == VecVSge::IDLE) || (ixVSge == VecVSge::CLTDONE)) {
fullpath = _fullpath;
xmlNotTxt = _xmlNotTxt;
shorttags = _shorttags;
changeStage(dbswznm, VecVSge::EXPORT);
};
};
void JobWznmIexIex::handleRequest(
DbsWznm* dbswznm
, ReqWznm* req
) {
if (req->ixVBasetype == ReqWznm::VecVBasetype::CMD) {
reqCmd = req;
if (req->cmd == "cmdset") {
} else {
cout << "\tinvalid command!" << endl;
};
if (!req->retain) reqCmd = NULL;
};
};
void JobWznmIexIex::changeStage(
DbsWznm* dbswznm
, uint _ixVSge
) {
bool reenter = true;
do {
if (ixVSge != _ixVSge) {
switch (ixVSge) {
case VecVSge::IDLE: leaveSgeIdle(dbswznm); break;
case VecVSge::PARSE: leaveSgeParse(dbswznm); break;
case VecVSge::PRSERR: leaveSgePrserr(dbswznm); break;
case VecVSge::PRSDONE: leaveSgePrsdone(dbswznm); break;
case VecVSge::IMPORT: leaveSgeImport(dbswznm); break;
case VecVSge::IMPERR: leaveSgeImperr(dbswznm); break;
case VecVSge::REVERSE: leaveSgeReverse(dbswznm); break;
case VecVSge::COLLECT: leaveSgeCollect(dbswznm); break;
case VecVSge::CLTDONE: leaveSgeCltdone(dbswznm); break;
case VecVSge::EXPORT: leaveSgeExport(dbswznm); break;
case VecVSge::DONE: leaveSgeDone(dbswznm); break;
};
setStage(dbswznm, _ixVSge);
reenter = false;
// IP changeStage.refresh1 --- INSERT
};
switch (_ixVSge) {
case VecVSge::IDLE: _ixVSge = enterSgeIdle(dbswznm, reenter); break;
case VecVSge::PARSE: _ixVSge = enterSgeParse(dbswznm, reenter); break;
case VecVSge::PRSERR: _ixVSge = enterSgePrserr(dbswznm, reenter); break;
case VecVSge::PRSDONE: _ixVSge = enterSgePrsdone(dbswznm, reenter); break;
case VecVSge::IMPORT: _ixVSge = enterSgeImport(dbswznm, reenter); break;
case VecVSge::IMPERR: _ixVSge = enterSgeImperr(dbswznm, reenter); break;
case VecVSge::REVERSE: _ixVSge = enterSgeReverse(dbswznm, reenter); break;
case VecVSge::COLLECT: _ixVSge = enterSgeCollect(dbswznm, reenter); break;
case VecVSge::CLTDONE: _ixVSge = enterSgeCltdone(dbswznm, reenter); break;
case VecVSge::EXPORT: _ixVSge = enterSgeExport(dbswznm, reenter); break;
case VecVSge::DONE: _ixVSge = enterSgeDone(dbswznm, reenter); break;
};
// IP changeStage.refresh2 --- INSERT
} while (ixVSge != _ixVSge);
};
string JobWznmIexIex::getSquawk(
DbsWznm* dbswznm
) {
string retval;
// IP getSquawk --- RBEGIN
if ( (ixVSge == VecVSge::PARSE) || (ixVSge == VecVSge::PRSDONE) || (ixVSge == VecVSge::IMPORT) || (ixVSge == VecVSge::REVERSE) || (ixVSge == VecVSge::COLLECT) || (ixVSge == VecVSge::CLTDONE) || (ixVSge == VecVSge::EXPORT) ) {
if (ixWznmVLocale == VecWznmVLocale::ENUS) {
if (ixVSge == VecVSge::PARSE) retval = "parsing import/export structure";
else if (ixVSge == VecVSge::PRSDONE) retval = "import/export structure parsed";
else if (ixVSge == VecVSge::IMPORT) retval = "importing import/export structure (" + to_string(impcnt) + " records added)";
else if (ixVSge == VecVSge::REVERSE) retval = "reversing import/export structure import";
else if (ixVSge == VecVSge::COLLECT) retval = "collecting import/export structure for export";
else if (ixVSge == VecVSge::CLTDONE) retval = "import/export structure collected for export";
else if (ixVSge == VecVSge::EXPORT) retval = "exporting import/export structure";
};
} else if ( (ixVSge == VecVSge::PRSERR) || (ixVSge == VecVSge::IMPERR) ) {
retval = lasterror;
} else {
retval = VecVSge::getSref(ixVSge);
};
// IP getSquawk --- REND
return retval;
};
uint JobWznmIexIex::enterSgeIdle(
DbsWznm* dbswznm
, const bool reenter
) {
uint retval = VecVSge::IDLE;
fullpath = "";
xmlNotTxt = false;
rectpath = "";
lineno = 0;
impcnt = 0;
icsWznmVIop.clear();
imeimimpexpcplx.clear();
return retval;
};
void JobWznmIexIex::leaveSgeIdle(
DbsWznm* dbswznm
) {
// IP leaveSgeIdle --- INSERT
};
uint JobWznmIexIex::enterSgeParse(
DbsWznm* dbswznm
, const bool reenter
) {
uint retval;
nextIxVSgeSuccess = VecVSge::PRSDONE;
retval = nextIxVSgeSuccess;
nextIxVSgeFailure = VecVSge::PRSERR;
try {
IexWznmIex::parseFromFile(fullpath, xmlNotTxt, rectpath, imeimimpexpcplx);
} catch (SbeException& e) {
if (e.ix == SbeException::PATHNF) e.vals["path"] = "<hidden>";
lasterror = e.getSquawk(VecWznmVError::getIx, VecWznmVError::getTitle, ixWznmVLocale);
retval = nextIxVSgeFailure;
};
return retval;
};
void JobWznmIexIex::leaveSgeParse(
DbsWznm* dbswznm
) {
// IP leaveSgeParse --- INSERT
};
uint JobWznmIexIex::enterSgePrserr(
DbsWznm* dbswznm
, const bool reenter
) {
uint retval = VecVSge::PRSERR;
// IP enterSgePrserr --- INSERT
return retval;
};
void JobWznmIexIex::leaveSgePrserr(
DbsWznm* dbswznm
) {
// IP leaveSgePrserr --- INSERT
};
uint JobWznmIexIex::enterSgePrsdone(
DbsWznm* dbswznm
, const bool reenter
) {
uint retval = VecVSge::PRSDONE;
// IP enterSgePrsdone --- INSERT
return retval;
};
void JobWznmIexIex::leaveSgePrsdone(
DbsWznm* dbswznm
) {
// IP leaveSgePrsdone --- INSERT
};
uint JobWznmIexIex::enterSgeImport(
DbsWznm* dbswznm
, const bool reenter
) {
uint retval;
nextIxVSgeSuccess = VecVSge::DONE;
retval = nextIxVSgeSuccess;
nextIxVSgeFailure = VecVSge::IMPERR;
ImeitemIMImpexpcplx* iex = NULL;
ImeitemIJMImpexpcplxTitle* iexJtit = NULL;
ImeitemIMImpexp* ime = NULL;
ImeitemIMImpexpcol* iel = NULL;
ImeitemIJMImpexpcolStub* ielJstb = NULL;
set<ubigint> irefs1;
uint num2;
// IP enterSgeImport.prep --- IBEGIN
ListWznmMLocale lcls;
dbswznm->tblwznmmlocale->loadRstBySQL("SELECT * FROM TblWznmMLocale", false, lcls);
ImeitemIMImpexp* ime2 = NULL;
ubigint refWznmMVersion;
string preflcl;
refWznmMVersion = xchg->getRefPreset(VecWznmVPreset::PREWZNMREFVER, jref);
Wznm::getVerlclsref(dbswznm, refWznmMVersion, preflcl);
ubigint refWznmMVector;
string Prjshort;
Prjshort = Wznm::getPrjshort(dbswznm, refWznmMVersion);
// IP enterSgeImport.prep --- IEND
try {
// IP enterSgeImport.traverse --- RBEGIN
// -- ImeIMImpexpcplx
for (unsigned int ix0 = 0; ix0 < imeimimpexpcplx.nodes.size(); ix0++) {
iex = imeimimpexpcplx.nodes[ix0];
iex->refWznmMVersion = refWznmMVersion;
//iex->sref: TBL
//iex->Short: TBL
//iex->refJTitle: SUB
//iex->Title: TBL
//iex->Minversion: TBL
//iex->Comment: TBL
dbswznm->tblwznmmimpexpcplx->insertRec(iex);
impcnt++;
if (((iex->Title != "")) && iex->imeijmimpexpcplxtitle.nodes.empty()) {
iexJtit = new ImeitemIJMImpexpcplxTitle();
iex->imeijmimpexpcplxtitle.nodes.push_back(iexJtit);
iexJtit->refWznmMImpexpcplx = iex->ref;
iexJtit->Title = iex->Title;
};
for (unsigned int ix1 = 0; ix1 < iex->imeijmimpexpcplxtitle.nodes.size(); ix1++) {
iexJtit = iex->imeijmimpexpcplxtitle.nodes[ix1];
iexJtit->refWznmMImpexpcplx = iex->ref;
//if (iexJtit->srefX1RefWznmMLocale == "") iexJtit->srefX1RefWznmMLocale: CUSTOM DEFVAL
if (iexJtit->srefX1RefWznmMLocale == "") iexJtit->srefX1RefWznmMLocale = preflcl;
//iexJtit->x1RefWznmMLocale: RST
for (unsigned int i = 0; i < lcls.nodes.size(); i++) {
if (lcls.nodes[i]->sref == iexJtit->srefX1RefWznmMLocale) {
iexJtit->x1RefWznmMLocale = lcls.nodes[i]->ref;
break;
};
};
if (iexJtit->x1RefWznmMLocale == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",iexJtit->srefX1RefWznmMLocale}, {"iel","srefX1RefWznmMLocale"}, {"lineno",to_string(iexJtit->lineno)}});
//iexJtit->Title: TBL
dbswznm->tblwznmjmimpexpcplxtitle->insertRec(iexJtit);
impcnt++;
if (ix1 == 0) {
iex->refJTitle = iexJtit->ref;
iex->Title = iexJtit->Title;
dbswznm->tblwznmmimpexpcplx->updateRec(iex);
};
};
irefs1.clear();
for (unsigned int ix1 = 0; ix1 < iex->imeimimpexp.nodes.size(); ix1++) {
ime = iex->imeimimpexp.nodes[ix1];
if (irefs1.find(ime->iref) != irefs1.end()) throw SbeException(SbeException::IEX_IDIREF, {{"idiref",to_string(ime->iref)}, {"ime","ImeIMImpexp"}, {"lineno",to_string(ime->lineno)}});
ime->refWznmMImpexpcplx = iex->ref;
//ime->supRefWznmMImpexp: IMPPP
//ime->refWznmMTable: CUSTSQL
dbswznm->tblwznmmtable->loadRefByVerSrf(refWznmMVersion, ime->srefRefWznmMTable, ime->refWznmMTable);
if (ime->refWznmMTable == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",ime->srefRefWznmMTable}, {"iel","srefRefWznmMTable"}, {"lineno",to_string(ime->lineno)}});
//ime->sref: TBL
//ime->rtrSrefsWznmMImpexpcol: TBL
ime->ixWIop = VecWznmWMImpexpIop::getIx(ime->srefsIxWIop);
//ime->Comment: TBL
dbswznm->tblwznmmimpexp->insertRec(ime);
impcnt++;
num2 = 1;
for (unsigned int ix2 = 0; ix2 < ime->imeimimpexpcol.nodes.size(); ix2++) {
iel = ime->imeimimpexpcol.nodes[ix2];
iel->ixVBasetype = VecWznmVMImpexpcolBasetype::getIx(iel->srefIxVBasetype);
if (iel->ixVBasetype == 0) throw SbeException(SbeException::IEX_VSREF, {{"vsref",iel->srefIxVBasetype}, {"iel","srefIxVBasetype"}, {"lineno",to_string(iel->lineno)}});
iel->ixWOccurrence = VecWznmWMImpexpcolOccurrence::getIx(iel->srefsIxWOccurrence);
iel->imeRefWznmMImpexp = ime->ref;
iel->imeNum = num2++;
if (iel->srefRefWznmMTablecol != "") {
//iel->refWznmMTablecol: CUSTSQL
dbswznm->loadRefBySQL("SELECT ref FROM TblWznmMTablecol WHERE tblRefWznmMTable = " + to_string(ime->refWznmMTable) + " AND sref = '" + iel->srefRefWznmMTablecol + "'", iel->refWznmMTablecol);
if (iel->refWznmMTablecol == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",iel->srefRefWznmMTablecol}, {"iel","srefRefWznmMTablecol"}, {"lineno",to_string(iel->lineno)}});
};
//iel->sref: TBL
//iel->Short: TBL
//iel->refWznmMImpexp: IMPPP
iel->ixVConvtype = VecWznmVMImpexpcolConvtype::getIx(iel->srefIxVConvtype);
if (iel->ixVConvtype == 0) throw SbeException(SbeException::IEX_VSREF, {{"vsref",iel->srefIxVConvtype}, {"iel","srefIxVConvtype"}, {"lineno",to_string(iel->lineno)}});
//iel->Defval: TBL
if (iel->srefRefWznmMPreset != "") {
//iel->refWznmMPreset: CUSTSQL
dbswznm->tblwznmmpreset->loadRefByVerSrf(refWznmMVersion, iel->srefRefWznmMPreset, iel->refWznmMPreset);
if (iel->refWznmMPreset == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",iel->srefRefWznmMPreset}, {"iel","srefRefWznmMPreset"}, {"lineno",to_string(iel->lineno)}});
};
//iel->refJStub: SUB
if (iel->srefRefWznmMStub != "") {
//iel->refWznmMStub: CUSTSQL
dbswznm->loadRefBySQL("SELECT TblWznmMStub.ref FROM TblWznmMTable, TblWznmMStub WHERE TblWznmMTable.refWznmMVersion = " + to_string(refWznmMVersion) + " AND TblWznmMStub.refWznmMTable = TblWznmMTable.ref AND TblWznmMStub.sref = '" + iel->srefRefWznmMStub + "'", iel->refWznmMStub);
if (iel->refWznmMStub == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",iel->srefRefWznmMStub}, {"iel","srefRefWznmMStub"}, {"lineno",to_string(iel->lineno)}});
};
if (iel->srefRefWznmMVectoritem != "") {
//iel->refWznmMVectoritem: CUSTSQL
dbswznm->loadRefBySQL("SELECT TblWznmMVectoritem.ref FROM TblWznmMTablecol, TblWznmMVectoritem WHERE TblWznmMVectoritem.vecRefWznmMVector = TblWznmMTablecol.fctUref AND TblWznmMTablecol.ref = " + to_string(iel->refWznmMTablecol) + " AND TblWznmMVectoritem.sref = '" + iel->srefRefWznmMVectoritem + "'", iel->refWznmMVectoritem);
if (iel->refWznmMVectoritem == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",iel->srefRefWznmMVectoritem}, {"iel","srefRefWznmMVectoritem"}, {"lineno",to_string(iel->lineno)}});
};
dbswznm->tblwznmmimpexpcol->insertRec(iel);
impcnt++;
if (((iel->srefRefWznmMStub != "")) && iel->imeijmimpexpcolstub.nodes.empty()) {
ielJstb = new ImeitemIJMImpexpcolStub();
iel->imeijmimpexpcolstub.nodes.push_back(ielJstb);
ielJstb->refWznmMImpexpcol = iel->ref;
ielJstb->srefRefWznmMStub = iel->srefRefWznmMStub;
};
if (iel->imeijmimpexpcolstub.nodes.size() > 0) {
if (dbswznm->loadRefBySQL("SELECT TblWznmMTablecol2.fctUref FROM TblWznmMTablecol AS TblWznmMTablecol1, TblWznmMTablecol AS TblWznmMTablecol2 WHERE TblWznmMTablecol1.refWznmMRelation = TblWznmMTablecol2.refWznmMRelation AND TblWznmMTablecol1.tblRefWznmMTable = TblWznmMTablecol2.tblRefWznmMTable AND TblWznmMTablecol1.ref = "
+ to_string(iel->refWznmMTablecol) + " AND TblWznmMTablecol2.ixVBasetype = " + to_string(VecWznmVMTablecolBasetype::VECREF) + " AND TblWznmMTablecol2.sref LIKE '%VTbl'", refWznmMVector)) {
for (unsigned int ix3 = 0; ix3 < iel->imeijmimpexpcolstub.nodes.size(); ix3++) {
ielJstb = iel->imeijmimpexpcolstub.nodes[ix3];
ielJstb->refWznmMImpexpcol = iel->ref;
if (ielJstb->srefX1RefWznmMVectoritem != "") {
//ielJstb->x1RefWznmMVectoritem = CUSTSQL;
dbswznm->loadRefBySQL("SELECT ref FROM TblWznmMVectoritem WHERE vecRefWznmMVector = " + to_string(refWznmMVector) + " AND sref = '" + ielJstb->srefX1RefWznmMVectoritem + "'", ielJstb->x1RefWznmMVectoritem);
if (ielJstb->x1RefWznmMVectoritem == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",ielJstb->srefX1RefWznmMVectoritem}, {"iel","srefX1RefWznmMVectoritem"}, {"lineno",to_string(ielJstb->lineno)}});
};
//ielJstb->refWznmMStub = CUSTSQL;
dbswznm->loadRefBySQL("SELECT TblWznmMStub.ref FROM TblWznmMTable, TblWznmMStub WHERE TblWznmMTable.refWznmMVersion = " + to_string(refWznmMVersion) + " AND TblWznmMStub.refWznmMTable = TblWznmMTable.ref AND TblWznmMStub.sref = '" + ielJstb->srefRefWznmMStub + "'", ielJstb->refWznmMStub);
if (ielJstb->refWznmMStub == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",ielJstb->srefRefWznmMStub}, {"iel","srefRefWznmMStub"}, {"lineno",to_string(ielJstb->lineno)}});
dbswznm->tblwznmjmimpexpcolstub->insertRec(ielJstb);
impcnt++;
if (ix3 == 0) {
iel->refJStub = ielJstb->ref;
iel->refWznmMStub = ielJstb->refWznmMStub;
dbswznm->tblwznmmimpexpcol->updateRec(iel);
};
};
};
};
};
};
};
// IP enterSgeImport.traverse --- REND
// IP enterSgeImport.ppr --- IBEGIN
for (unsigned int ix0 = 0; ix0 < imeimimpexpcplx.nodes.size(); ix0++) {
iex = imeimimpexpcplx.nodes[ix0];
for (unsigned int ix1 = 0; ix1 < iex->imeimimpexp.nodes.size(); ix1++) {
ime = iex->imeimimpexp.nodes[ix1];
if (ime->irefSupRefWznmMImpexp != 0) {
for (unsigned int ix2 = 0; ix2 < iex->imeimimpexp.nodes.size(); ix2++) {
ime2 = iex->imeimimpexp.nodes[ix2];
if (ime2->iref == ime->irefSupRefWznmMImpexp) {
ime->supRefWznmMImpexp = ime2->ref;
ime->supLvl = ime2->supLvl + 1;
break;
};
};
if (ime->irefSupRefWznmMImpexp == 0) throw SbeException(SbeException::IEX_IREF, {{"iref",to_string(ime->irefSupRefWznmMImpexp)}, {"iel","irefSupRefWznmMImpexp"}, {"lineno",to_string(ime->lineno)}});
else dbswznm->tblwznmmimpexp->updateRec(ime);
};
for (unsigned int ix2 = 0; ix2 < ime->imeimimpexpcol.nodes.size(); ix2++) {
iel = ime->imeimimpexpcol.nodes[ix2];
if (iel->irefRefWznmMImpexp != 0) {
for (unsigned int ix3 = 0; ix3 < iex->imeimimpexp.nodes.size(); ix3++) {
ime2 = iex->imeimimpexp.nodes[ix3];
if (ime2->iref == iel->irefRefWznmMImpexp) {
iel->refWznmMImpexp = ime2->ref;
break;
};
};
if (iel->irefRefWznmMImpexp == 0) throw SbeException(SbeException::IEX_IREF, {{"iref",to_string(iel->irefRefWznmMImpexp)}, {"iel","irefRefWznmMImpexp"}, {"lineno",to_string(iel->lineno)}});
else dbswznm->tblwznmmimpexpcol->updateRec(iel);
};
};
};
};
// IP enterSgeImport.ppr --- IEND
} catch (SbeException& e) {
lasterror = e.getSquawk(VecWznmVError::getIx, VecWznmVError::getTitle, ixWznmVLocale);
retval = nextIxVSgeFailure;
};
return retval;
};
void JobWznmIexIex::leaveSgeImport(
DbsWznm* dbswznm
) {
// IP leaveSgeImport --- INSERT
};
uint JobWznmIexIex::enterSgeImperr(
DbsWznm* dbswznm
, const bool reenter
) {
uint retval = VecVSge::IMPERR;
// IP enterSgeImperr --- INSERT
return retval;
};
void JobWznmIexIex::leaveSgeImperr(
DbsWznm* dbswznm
) {
// IP leaveSgeImperr --- INSERT
};
uint JobWznmIexIex::enterSgeReverse(
DbsWznm* dbswznm
, const bool reenter
) {
uint retval;
nextIxVSgeSuccess = VecVSge::IDLE;
retval = nextIxVSgeSuccess;
ImeitemIMImpexpcplx* iex = NULL;
ImeitemIJMImpexpcplxTitle* iexJtit = NULL;
ImeitemIMImpexp* ime = NULL;
ImeitemIMImpexpcol* iel = NULL;
ImeitemIJMImpexpcolStub* ielJstb = NULL;
// -- ImeIMImpexpcplx
for (unsigned int ix0 = 0; ix0 < imeimimpexpcplx.nodes.size(); ix0++) {
iex = imeimimpexpcplx.nodes[ix0];
if (iex->ref != 0) dbswznm->tblwznmmimpexpcplx->removeRecByRef(iex->ref);
for (unsigned int ix1 = 0; ix1 < iex->imeijmimpexpcplxtitle.nodes.size(); ix1++) {
iexJtit = iex->imeijmimpexpcplxtitle.nodes[ix1];
if (iexJtit->ref != 0) dbswznm->tblwznmjmimpexpcplxtitle->removeRecByRef(iexJtit->ref);
};
for (unsigned int ix1 = 0; ix1 < iex->imeimimpexp.nodes.size(); ix1++) {
ime = iex->imeimimpexp.nodes[ix1];
if (ime->ref != 0) dbswznm->tblwznmmimpexp->removeRecByRef(ime->ref);
for (unsigned int ix2 = 0; ix2 < ime->imeimimpexpcol.nodes.size(); ix2++) {
iel = ime->imeimimpexpcol.nodes[ix2];
if (iel->ref != 0) dbswznm->tblwznmmimpexpcol->removeRecByRef(iel->ref);
for (unsigned int ix3 = 0; ix3 < iel->imeijmimpexpcolstub.nodes.size(); ix3++) {
ielJstb = iel->imeijmimpexpcolstub.nodes[ix3];
if (ielJstb->ref != 0) dbswznm->tblwznmjmimpexpcolstub->removeRecByRef(ielJstb->ref);
};
};
};
};
return retval;
};
void JobWznmIexIex::leaveSgeReverse(
DbsWznm* dbswznm
) {
// IP leaveSgeReverse --- INSERT
};
uint JobWznmIexIex::enterSgeCollect(
DbsWznm* dbswznm
, const bool reenter
) {
uint retval;
nextIxVSgeSuccess = VecVSge::CLTDONE;
retval = nextIxVSgeSuccess;
ImeitemIMImpexpcplx* iex = NULL;
ImeitemIJMImpexpcplxTitle* iexJtit = NULL;
ImeitemIMImpexp* ime = NULL;
ImeitemIMImpexpcol* iel = NULL;
ImeitemIJMImpexpcolStub* ielJstb = NULL;
uint ixWznmVIop;
vector<ubigint> refs;
Stcch* stcch = new Stcch(false);
// IP enterSgeCollect.traverse --- BEGIN
// -- ImeIMImpexpcplx
for (unsigned int ix0 = 0; ix0 < imeimimpexpcplx.nodes.size(); ix0++) {
iex = imeimimpexpcplx.nodes[ix0];
if (iex->ref != 0) {
};
if (getIxWznmVIop(icsWznmVIop, VecVIme::IMEIJMIMPEXPCPLXTITLE, ixWznmVIop)) {
dbswznm->tblwznmjmimpexpcplxtitle->loadRefsByIex(iex->ref, false, refs);
for (unsigned int i = 0; i < refs.size(); i++) if (refs[i] == iex->refJTitle) {refs[i] = refs[0]; refs[0] = iex->refJTitle; break;};
for (unsigned int i = 0; i < refs.size(); i++) iex->imeijmimpexpcplxtitle.nodes.push_back(new ImeitemIJMImpexpcplxTitle(dbswznm, refs[i]));
};
for (unsigned int ix1 = 0; ix1 < iex->imeijmimpexpcplxtitle.nodes.size(); ix1++) {
iexJtit = iex->imeijmimpexpcplxtitle.nodes[ix1];
if (iexJtit->ref != 0) {
iexJtit->srefX1RefWznmMLocale = StubWznm::getStubLocSref(dbswznm, iexJtit->x1RefWznmMLocale, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch);
};
};
if (getIxWznmVIop(icsWznmVIop, VecVIme::IMEIMIMPEXP, ixWznmVIop)) {
dbswznm->tblwznmmimpexp->loadRefsByIex(iex->ref, false, refs);
for (unsigned int i = 0; i < refs.size(); i++) iex->imeimimpexp.nodes.push_back(new ImeitemIMImpexp(dbswznm, refs[i]));
};
for (unsigned int ix1 = 0; ix1 < iex->imeimimpexp.nodes.size(); ix1++) {
ime = iex->imeimimpexp.nodes[ix1];
if (ime->ref != 0) {
ime->iref = ix1+1;
//ime->irefSupRefWznmMImpexp: IREF
ime->srefRefWznmMTable = StubWznm::getStubTblStd(dbswznm, ime->refWznmMTable, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch);
};
if (getIxWznmVIop(icsWznmVIop, VecVIme::IMEIMIMPEXPCOL, ixWznmVIop)) {
dbswznm->tblwznmmimpexpcol->loadRefsByIme(ime->ref, false, refs);
for (unsigned int i = 0; i < refs.size(); i++) ime->imeimimpexpcol.nodes.push_back(new ImeitemIMImpexpcol(dbswznm, refs[i]));
};
for (unsigned int ix2 = 0; ix2 < ime->imeimimpexpcol.nodes.size(); ix2++) {
iel = ime->imeimimpexpcol.nodes[ix2];
if (iel->ref != 0) {
iel->srefRefWznmMTablecol = StubWznm::getStubTcoSref(dbswznm, iel->refWznmMTablecol, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch);
//iel->irefRefWznmMImpexp: IREF
iel->srefRefWznmMPreset = StubWznm::getStubPstStd(dbswznm, iel->refWznmMPreset, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch);
iel->srefRefWznmMStub = StubWznm::getStubStbStd(dbswznm, iel->refWznmMStub, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch);
iel->srefRefWznmMVectoritem = StubWznm::getStubVitSref(dbswznm, iel->refWznmMVectoritem, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch);
};
if (getIxWznmVIop(icsWznmVIop, VecVIme::IMEIJMIMPEXPCOLSTUB, ixWznmVIop)) {
dbswznm->tblwznmjmimpexpcolstub->loadRefsByIel(iel->ref, false, refs);
for (unsigned int i = 0; i < refs.size(); i++) iel->imeijmimpexpcolstub.nodes.push_back(new ImeitemIJMImpexpcolStub(dbswznm, refs[i]));
};
for (unsigned int ix3 = 0; ix3 < iel->imeijmimpexpcolstub.nodes.size(); ix3++) {
ielJstb = iel->imeijmimpexpcolstub.nodes[ix3];
if (ielJstb->ref != 0) {
ielJstb->srefX1RefWznmMVectoritem = StubWznm::getStubVitSref(dbswznm, ielJstb->x1RefWznmMVectoritem, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch);
ielJstb->srefRefWznmMStub = StubWznm::getStubStbStd(dbswznm, ielJstb->refWznmMStub, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch);
};
};
};
};
};
// IP enterSgeCollect.traverse --- END
// IP enterSgeCollect.ppr --- INSERT
delete stcch;
return retval;
};
void JobWznmIexIex::leaveSgeCollect(
DbsWznm* dbswznm
) {
// IP leaveSgeCollect --- INSERT
};
uint JobWznmIexIex::enterSgeCltdone(
DbsWznm* dbswznm
, const bool reenter
) {
uint retval = VecVSge::CLTDONE;
// IP enterSgeCltdone --- INSERT
return retval;
};
void JobWznmIexIex::leaveSgeCltdone(
DbsWznm* dbswznm
) {
// IP leaveSgeCltdone --- INSERT
};
uint JobWznmIexIex::enterSgeExport(
DbsWznm* dbswznm
, const bool reenter
) {
uint retval;
nextIxVSgeSuccess = VecVSge::DONE;
retval = nextIxVSgeSuccess;
IexWznmIex::exportToFile(fullpath, xmlNotTxt, shorttags, imeimimpexpcplx);
return retval;
};
void JobWznmIexIex::leaveSgeExport(
DbsWznm* dbswznm
) {
// IP leaveSgeExport --- INSERT
};
uint JobWznmIexIex::enterSgeDone(
DbsWznm* dbswznm
, const bool reenter
) {
uint retval = VecVSge::DONE;
// IP enterSgeDone --- INSERT
return retval;
};
void JobWznmIexIex::leaveSgeDone(
DbsWznm* dbswznm
) {
// IP leaveSgeDone --- INSERT
};
| 32.769231 | 334 | 0.684133 |
44005351e0d4c83cc5ca5c08aee2c529b22f4080 | 40,782 | cc | C++ | src/bin/dhcp6/json_config_parser.cc | oss-mirror/isc-kea | e7bfb8886b0312a293e73846499095e7ec9686b9 | [
"Apache-2.0"
] | 273 | 2015-01-22T14:14:42.000Z | 2022-03-13T10:27:44.000Z | src/bin/dhcp6/json_config_parser.cc | oss-mirror/isc-kea | e7bfb8886b0312a293e73846499095e7ec9686b9 | [
"Apache-2.0"
] | 104 | 2015-01-16T16:37:06.000Z | 2021-08-08T19:38:45.000Z | src/bin/dhcp6/json_config_parser.cc | oss-mirror/isc-kea | e7bfb8886b0312a293e73846499095e7ec9686b9 | [
"Apache-2.0"
] | 133 | 2015-02-21T14:06:39.000Z | 2022-02-27T08:56:40.000Z | // Copyright (C) 2012-2021 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <config.h>
#include <asiolink/io_address.h>
#include <cc/data.h>
#include <cc/command_interpreter.h>
#include <config/command_mgr.h>
#include <database/dbaccess_parser.h>
#include <dhcp/libdhcp++.h>
#include <dhcp6/json_config_parser.h>
#include <dhcp6/dhcp6_log.h>
#include <dhcp6/dhcp6_srv.h>
#include <dhcp/iface_mgr.h>
#include <dhcpsrv/cb_ctl_dhcp4.h>
#include <dhcpsrv/cfg_option.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/db_type.h>
#include <dhcpsrv/pool.h>
#include <dhcpsrv/subnet.h>
#include <dhcpsrv/timer_mgr.h>
#include <dhcpsrv/triplet.h>
#include <dhcpsrv/parsers/client_class_def_parser.h>
#include <dhcpsrv/parsers/dhcp_parsers.h>
#include <dhcpsrv/parsers/duid_config_parser.h>
#include <dhcpsrv/parsers/expiration_config_parser.h>
#include <dhcpsrv/parsers/host_reservation_parser.h>
#include <dhcpsrv/parsers/host_reservations_list_parser.h>
#include <dhcpsrv/parsers/ifaces_config_parser.h>
#include <dhcpsrv/parsers/multi_threading_config_parser.h>
#include <dhcpsrv/parsers/option_data_parser.h>
#include <dhcpsrv/parsers/dhcp_queue_control_parser.h>
#include <dhcpsrv/parsers/simple_parser6.h>
#include <dhcpsrv/parsers/shared_networks_list_parser.h>
#include <dhcpsrv/parsers/sanity_checks_parser.h>
#include <dhcpsrv/host_data_source_factory.h>
#include <hooks/hooks_parser.h>
#include <hooks/hooks_manager.h>
#include <log/logger_support.h>
#include <process/config_ctl_parser.h>
#include <util/encode/hex.h>
#include <util/strutil.h>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <limits>
#include <map>
#include <netinet/in.h>
#include <vector>
#include <stdint.h>
using namespace std;
using namespace isc;
using namespace isc::data;
using namespace isc::dhcp;
using namespace isc::asiolink;
using namespace isc::hooks;
using namespace isc::process;
namespace {
/// @brief Checks if specified directory exists.
///
/// @param dir_path Path to a directory.
/// @throw BadValue If the directory does not exist or is not a directory.
void dirExists(const string& dir_path) {
struct stat statbuf;
if (stat(dir_path.c_str(), &statbuf) < 0) {
isc_throw(BadValue, "Bad directory '" << dir_path
<< "': " << strerror(errno));
}
if ((statbuf.st_mode & S_IFMT) != S_IFDIR) {
isc_throw(BadValue, "'" << dir_path << "' is not a directory");
}
}
/// @brief Parser for list of RSOO options
///
/// This parser handles a Dhcp6/relay-supplied-options entry. It contains a
/// list of RSOO-enabled options which should be sent back to the client.
///
/// The options on this list can be specified using an option code or option
/// name. Therefore, the values on the list should always be enclosed in
/// "quotes".
class RSOOListConfigParser : public isc::data::SimpleParser {
public:
/// @brief parses parameters value
///
/// Parses configuration entry (list of sources) and adds each element
/// to the RSOO list.
///
/// @param value pointer to the content of parsed values
/// @param cfg server configuration (RSOO will be stored here)
void parse(const SrvConfigPtr& cfg, const isc::data::ConstElementPtr& value) {
try {
BOOST_FOREACH(ConstElementPtr source_elem, value->listValue()) {
std::string option_str = source_elem->stringValue();
// This option can be either code (integer) or name. Let's try code first
int64_t code = 0;
try {
code = boost::lexical_cast<int64_t>(option_str);
// Protect against the negative value and too high value.
if (code < 0) {
isc_throw(BadValue, "invalid option code value specified '"
<< option_str << "', the option code must be a"
" non-negative value");
} else if (code > std::numeric_limits<uint16_t>::max()) {
isc_throw(BadValue, "invalid option code value specified '"
<< option_str << "', the option code must not be"
" greater than '" << std::numeric_limits<uint16_t>::max()
<< "'");
}
} catch (const boost::bad_lexical_cast &) {
// Oh well, it's not a number
}
if (!code) {
const OptionDefinitionPtr def = LibDHCP::getOptionDef(DHCP6_OPTION_SPACE,
option_str);
if (def) {
code = def->getCode();
} else {
isc_throw(BadValue, "unable to find option code for the "
" specified option name '" << option_str << "'"
" while parsing the list of enabled"
" relay-supplied-options");
}
}
cfg->getCfgRSOO()->enable(code);
}
} catch (const std::exception& ex) {
// Rethrow exception with the appended position of the parsed
// element.
isc_throw(DhcpConfigError, ex.what() << " (" << value->getPosition() << ")");
}
}
};
/// @brief Parser that takes care of global DHCPv6 parameters and utility
/// functions that work on global level.
///
/// This class is a collection of utility method that either handle
/// global parameters (see @ref parse), or conducts operations on
/// global level (see @ref sanityChecks and @ref copySubnets6).
///
/// See @ref parse method for a list of supported parameters.
class Dhcp6ConfigParser : public isc::data::SimpleParser {
public:
/// @brief Sets global parameters in staging configuration
///
/// @param global global configuration scope
/// @param cfg Server configuration (parsed parameters will be stored here)
///
/// Currently this method sets the following global parameters:
///
/// - data-directory
/// - decline-probation-period
/// - dhcp4o6-port
/// - user-context
///
/// @throw DhcpConfigError if parameters are missing or
/// or having incorrect values.
void parse(const SrvConfigPtr& srv_config, const ConstElementPtr& global) {
// Set the data directory for server id file.
if (global->contains("data-directory")) {
CfgMgr::instance().setDataDir(getString(global, "data-directory"),
false);
}
// Set the probation period for decline handling.
uint32_t probation_period =
getUint32(global, "decline-probation-period");
srv_config->setDeclinePeriod(probation_period);
// Set the DHCPv4-over-DHCPv6 interserver port.
uint16_t dhcp4o6_port = getUint16(global, "dhcp4o6-port");
srv_config->setDhcp4o6Port(dhcp4o6_port);
// Set the global user context.
ConstElementPtr user_context = global->get("user-context");
if (user_context) {
srv_config->setContext(user_context);
}
// Set the server's logical name
std::string server_tag = getString(global, "server-tag");
srv_config->setServerTag(server_tag);
}
/// @brief Sets global parameters before other parameters are parsed.
///
/// This method sets selected global parameters before other parameters
/// are parsed. This is important when the behavior of the parsers
/// run later depends on these global parameters.
///
/// Currently this method sets the following global parameters:
/// - ip-reservations-unique
///
/// @param global global configuration scope
/// @param cfg Server configuration (parsed parameters will be stored here)
void parseEarly(const SrvConfigPtr& cfg, const ConstElementPtr& global) {
// Set ip-reservations-unique flag.
bool ip_reservations_unique = getBoolean(global, "ip-reservations-unique");
cfg->setIPReservationsUnique(ip_reservations_unique);
}
/// @brief Copies subnets from shared networks to regular subnets container
///
/// @param from pointer to shared networks container (copy from here)
/// @param dest pointer to cfg subnets6 (copy to here)
/// @throw BadValue if any pointer is missing
/// @throw DhcpConfigError if there are duplicates (or other subnet defects)
void
copySubnets6(const CfgSubnets6Ptr& dest, const CfgSharedNetworks6Ptr& from) {
if (!dest || !from) {
isc_throw(BadValue, "Unable to copy subnets: at least one pointer is null");
}
const SharedNetwork6Collection* networks = from->getAll();
if (!networks) {
// Nothing to copy. Technically, it should return a pointer to empty
// container, but let's handle null pointer as well.
return;
}
// Let's go through all the networks one by one
for (auto net = networks->begin(); net != networks->end(); ++net) {
// For each network go through all the subnets in it.
const Subnet6Collection* subnets = (*net)->getAllSubnets();
if (!subnets) {
// Shared network without subnets it weird, but we decided to
// accept such configurations.
continue;
}
// For each subnet, add it to a list of regular subnets.
for (auto subnet = subnets->begin(); subnet != subnets->end(); ++subnet) {
dest->add(*subnet);
}
}
}
/// @brief Conducts global sanity checks
///
/// This method is very simple now, but more sanity checks are expected
/// in the future.
///
/// @param cfg - the parsed structure
/// @param global global Dhcp4 scope
/// @throw DhcpConfigError in case of issues found
void
sanityChecks(const SrvConfigPtr& cfg, const ConstElementPtr& global) {
/// Global lifetime sanity checks
cfg->sanityChecksLifetime("preferred-lifetime");
cfg->sanityChecksLifetime("valid-lifetime");
/// Shared network sanity checks
const SharedNetwork6Collection* networks = cfg->getCfgSharedNetworks6()->getAll();
if (networks) {
sharedNetworksSanityChecks(*networks, global->get("shared-networks"));
}
}
/// @brief Sanity checks for shared networks
///
/// This method verifies if there are no issues with shared networks.
/// @param networks pointer to shared networks being checked
/// @param json shared-networks element
/// @throw DhcpConfigError if issues are encountered
void
sharedNetworksSanityChecks(const SharedNetwork6Collection& networks,
ConstElementPtr json) {
/// @todo: in case of errors, use json to extract line numbers.
if (!json) {
// No json? That means that the shared-networks was never specified
// in the config.
return;
}
// Used for names uniqueness checks.
std::set<string> names;
// Let's go through all the networks one by one
for (auto net = networks.begin(); net != networks.end(); ++net) {
string txt;
// Let's check if all subnets have either the same interface
// or don't have the interface specified at all.
string iface = (*net)->getIface();
const Subnet6Collection* subnets = (*net)->getAllSubnets();
if (subnets) {
bool rapid_commit = false;
// For each subnet, add it to a list of regular subnets.
for (auto subnet = subnets->begin(); subnet != subnets->end(); ++subnet) {
// Rapid commit must either be enabled or disabled in all subnets
// in the shared network.
if (subnet == subnets->begin()) {
// If this is the first subnet, remember the value.
rapid_commit = (*subnet)->getRapidCommit();
} else {
// Ok, this is the second or following subnets. The value
// must match what was set in the first subnet.
if (rapid_commit != (*subnet)->getRapidCommit()) {
isc_throw(DhcpConfigError, "All subnets in a shared network "
"must have the same rapid-commit value. Subnet "
<< (*subnet)->toText()
<< " has specified rapid-commit "
<< ( (*subnet)->getRapidCommit() ? "true" : "false")
<< ", but earlier subnet in the same shared-network"
<< " or the shared-network itself used rapid-commit "
<< (rapid_commit ? "true" : "false"));
}
}
if (iface.empty()) {
iface = (*subnet)->getIface();
continue;
}
if ((*subnet)->getIface().empty()) {
continue;
}
if ((*subnet)->getIface() != iface) {
isc_throw(DhcpConfigError, "Subnet " << (*subnet)->toText()
<< " has specified interface " << (*subnet)->getIface()
<< ", but earlier subnet in the same shared-network"
<< " or the shared-network itself used " << iface);
}
// Let's collect the subnets in case we later find out the
// subnet doesn't have a mandatory name.
txt += (*subnet)->toText() + " ";
}
}
// Next, let's check name of the shared network.
if ((*net)->getName().empty()) {
isc_throw(DhcpConfigError, "Shared-network with subnets "
<< txt << " is missing mandatory 'name' parameter");
}
// Is it unique?
if (names.find((*net)->getName()) != names.end()) {
isc_throw(DhcpConfigError, "A shared-network with "
"name " << (*net)->getName() << " defined twice.");
}
names.insert((*net)->getName());
}
}
};
} // anonymous namespace
namespace isc {
namespace dhcp {
/// @brief Initialize the command channel based on the staging configuration
///
/// Only close the current channel, if the new channel configuration is
/// different. This avoids disconnecting a client and hence not sending them
/// a command result, unless they specifically alter the channel configuration.
/// In that case the user simply has to accept they'll be disconnected.
///
void configureCommandChannel() {
// Get new socket configuration.
ConstElementPtr sock_cfg =
CfgMgr::instance().getStagingCfg()->getControlSocketInfo();
// Get current socket configuration.
ConstElementPtr current_sock_cfg =
CfgMgr::instance().getCurrentCfg()->getControlSocketInfo();
// Determine if the socket configuration has changed. It has if
// both old and new configuration is specified but respective
// data elements aren't equal.
bool sock_changed = (sock_cfg && current_sock_cfg &&
!sock_cfg->equals(*current_sock_cfg));
// If the previous or new socket configuration doesn't exist or
// the new configuration differs from the old configuration we
// close the existing socket and open a new socket as appropriate.
// Note that closing an existing socket means the client will not
// receive the configuration result.
if (!sock_cfg || !current_sock_cfg || sock_changed) {
// Close the existing socket (if any).
isc::config::CommandMgr::instance().closeCommandSocket();
if (sock_cfg) {
// This will create a control socket and install the external
// socket in IfaceMgr. That socket will be monitored when
// Dhcp4Srv::receivePacket() calls IfaceMgr::receive4() and
// callback in CommandMgr will be called, if necessary.
isc::config::CommandMgr::instance().openCommandSocket(sock_cfg);
}
}
}
isc::data::ConstElementPtr
configureDhcp6Server(Dhcpv6Srv& server, isc::data::ConstElementPtr config_set,
bool check_only) {
if (!config_set) {
ConstElementPtr answer = isc::config::createAnswer(1,
string("Can't parse NULL config"));
return (answer);
}
LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_CONFIG_START)
.arg(server.redactConfig(config_set)->str());
// Before starting any subnet operations, let's reset the subnet-id counter,
// so newly recreated configuration starts with first subnet-id equal 1.
Subnet::resetSubnetID();
// Close DHCP sockets and remove any existing timers.
if (!check_only) {
IfaceMgr::instance().closeSockets();
TimerMgr::instance()->unregisterTimers();
server.discardPackets();
server.getCBControl()->reset();
}
// Revert any runtime option definitions configured so far and not committed.
LibDHCP::revertRuntimeOptionDefs();
// Let's set empty container in case a user hasn't specified any configuration
// for option definitions. This is equivalent to committing empty container.
LibDHCP::setRuntimeOptionDefs(OptionDefSpaceContainer());
// Print the list of known backends.
HostDataSourceFactory::printRegistered();
// Answer will hold the result.
ConstElementPtr answer;
// Rollback informs whether error occurred and original data
// have to be restored to global storages.
bool rollback = false;
// Global parameter name in case of an error.
string parameter_name;
ElementPtr mutable_cfg;
SrvConfigPtr srv_config;
try {
// Get the staging configuration.
srv_config = CfgMgr::instance().getStagingCfg();
// This is a way to convert ConstElementPtr to ElementPtr.
// We need a config that can be edited, because we will insert
// default values and will insert derived values as well.
mutable_cfg = boost::const_pointer_cast<Element>(config_set);
// Relocate dhcp-ddns parameters that have moved to global scope.
// Rule is that a global value overrides the dhcp-ddns value, so
// we need to do this before we apply global defaults.
// Note this is done for backward compatibility.
srv_config->moveDdnsParams(mutable_cfg);
// Move from reservation mode to new reservations flags.
// @todo add warning
BaseNetworkParser::moveReservationMode(mutable_cfg);
// Set all default values if not specified by the user.
SimpleParser6::setAllDefaults(mutable_cfg);
// And now derive (inherit) global parameters to subnets, if not specified.
SimpleParser6::deriveParameters(mutable_cfg);
// In principle we could have the following code structured as a series
// of long if else if clauses. That would give a marginal performance
// boost, but would make the code less readable. We had serious issues
// with the parser code debugability, so I decided to keep it as a
// series of independent ifs.
// This parser is used in several places.
Dhcp6ConfigParser global_parser;
// Apply global options in the staging config, e.g. ip-reservations-unique
global_parser.parseEarly(srv_config, mutable_cfg);
// Specific check for this global parameter.
ConstElementPtr data_directory = mutable_cfg->get("data-directory");
if (data_directory) {
parameter_name = "data-directory";
dirExists(data_directory->stringValue());
}
// We need definitions first
ConstElementPtr option_defs = mutable_cfg->get("option-def");
if (option_defs) {
parameter_name = "option-def";
OptionDefListParser parser(AF_INET6);
CfgOptionDefPtr cfg_option_def = srv_config->getCfgOptionDef();
parser.parse(cfg_option_def, option_defs);
}
ConstElementPtr option_datas = mutable_cfg->get("option-data");
if (option_datas) {
parameter_name = "option-data";
OptionDataListParser parser(AF_INET6);
CfgOptionPtr cfg_option = srv_config->getCfgOption();
parser.parse(cfg_option, option_datas);
}
ConstElementPtr mac_sources = mutable_cfg->get("mac-sources");
if (mac_sources) {
parameter_name = "mac-sources";
MACSourcesListConfigParser parser;
CfgMACSource& mac_source = srv_config->getMACSources();
parser.parse(mac_source, mac_sources);
}
ConstElementPtr control_socket = mutable_cfg->get("control-socket");
if (control_socket) {
parameter_name = "control-socket";
ControlSocketParser parser;
parser.parse(*srv_config, control_socket);
}
ConstElementPtr multi_threading = mutable_cfg->get("multi-threading");
if (multi_threading) {
parameter_name = "multi-threading";
MultiThreadingConfigParser parser;
parser.parse(*srv_config, multi_threading);
}
ConstElementPtr queue_control = mutable_cfg->get("dhcp-queue-control");
if (queue_control) {
parameter_name = "dhcp-queue-control";
DHCPQueueControlParser parser;
srv_config->setDHCPQueueControl(parser.parse(queue_control));
}
ConstElementPtr hr_identifiers =
mutable_cfg->get("host-reservation-identifiers");
if (hr_identifiers) {
parameter_name = "host-reservation-identifiers";
HostReservationIdsParser6 parser;
parser.parse(hr_identifiers);
}
ConstElementPtr server_id = mutable_cfg->get("server-id");
if (server_id) {
parameter_name = "server-id";
DUIDConfigParser parser;
const CfgDUIDPtr& cfg = srv_config->getCfgDUID();
parser.parse(cfg, server_id);
}
ConstElementPtr ifaces_config = mutable_cfg->get("interfaces-config");
if (ifaces_config) {
parameter_name = "interfaces-config";
IfacesConfigParser parser(AF_INET6, check_only);
CfgIfacePtr cfg_iface = srv_config->getCfgIface();
parser.parse(cfg_iface, ifaces_config);
}
ConstElementPtr sanity_checks = mutable_cfg->get("sanity-checks");
if (sanity_checks) {
parameter_name = "sanity-checks";
SanityChecksParser parser;
parser.parse(*srv_config, sanity_checks);
}
ConstElementPtr expiration_cfg =
mutable_cfg->get("expired-leases-processing");
if (expiration_cfg) {
parameter_name = "expired-leases-processing";
ExpirationConfigParser parser;
parser.parse(expiration_cfg);
}
// The hooks-libraries configuration must be parsed after parsing
// multi-threading configuration so that libraries are checked
// for multi-threading compatibility.
ConstElementPtr hooks_libraries = mutable_cfg->get("hooks-libraries");
if (hooks_libraries) {
parameter_name = "hooks-libraries";
HooksLibrariesParser hooks_parser;
HooksConfig& libraries = srv_config->getHooksConfig();
hooks_parser.parse(libraries, hooks_libraries);
libraries.verifyLibraries(hooks_libraries->getPosition());
}
// D2 client configuration.
D2ClientConfigPtr d2_client_cfg;
// Legacy DhcpConfigParser stuff below.
ConstElementPtr dhcp_ddns = mutable_cfg->get("dhcp-ddns");
if (dhcp_ddns) {
parameter_name = "dhcp-ddns";
// Apply defaults
D2ClientConfigParser::setAllDefaults(dhcp_ddns);
D2ClientConfigParser parser;
d2_client_cfg = parser.parse(dhcp_ddns);
}
ConstElementPtr client_classes = mutable_cfg->get("client-classes");
if (client_classes) {
parameter_name = "client-classes";
ClientClassDefListParser parser;
ClientClassDictionaryPtr dictionary =
parser.parse(client_classes, AF_INET6);
srv_config->setClientClassDictionary(dictionary);
}
// Please move at the end when migration will be finished.
ConstElementPtr lease_database = mutable_cfg->get("lease-database");
if (lease_database) {
parameter_name = "lease-database";
db::DbAccessParser parser;
std::string access_string;
parser.parse(access_string, lease_database);
CfgDbAccessPtr cfg_db_access = srv_config->getCfgDbAccess();
cfg_db_access->setLeaseDbAccessString(access_string);
}
ConstElementPtr hosts_database = mutable_cfg->get("hosts-database");
if (hosts_database) {
parameter_name = "hosts-database";
db::DbAccessParser parser;
std::string access_string;
parser.parse(access_string, hosts_database);
CfgDbAccessPtr cfg_db_access = srv_config->getCfgDbAccess();
cfg_db_access->setHostDbAccessString(access_string);
}
ConstElementPtr hosts_databases = mutable_cfg->get("hosts-databases");
if (hosts_databases) {
parameter_name = "hosts-databases";
CfgDbAccessPtr cfg_db_access = srv_config->getCfgDbAccess();
db::DbAccessParser parser;
for (auto it : hosts_databases->listValue()) {
std::string access_string;
parser.parse(access_string, it);
cfg_db_access->setHostDbAccessString(access_string);
}
}
// Keep relative orders of shared networks and subnets.
ConstElementPtr shared_networks = mutable_cfg->get("shared-networks");
if (shared_networks) {
parameter_name = "shared-networks";
/// We need to create instance of SharedNetworks6ListParser
/// and parse the list of the shared networks into the
/// CfgSharedNetworks6 object. One additional step is then to
/// add subnets from the CfgSharedNetworks6 into CfgSubnets6
/// as well.
SharedNetworks6ListParser parser;
CfgSharedNetworks6Ptr cfg = srv_config->getCfgSharedNetworks6();
parser.parse(cfg, shared_networks);
// We also need to put the subnets it contains into normal
// subnets list.
global_parser.copySubnets6(srv_config->getCfgSubnets6(), cfg);
}
ConstElementPtr subnet6 = mutable_cfg->get("subnet6");
if (subnet6) {
parameter_name = "subnet6";
Subnets6ListConfigParser subnets_parser;
// parse() returns number of subnets parsed. We may log it one day.
subnets_parser.parse(srv_config, subnet6);
}
ConstElementPtr reservations = mutable_cfg->get("reservations");
if (reservations) {
parameter_name = "reservations";
HostCollection hosts;
HostReservationsListParser<HostReservationParser6> parser;
parser.parse(SUBNET_ID_GLOBAL, reservations, hosts);
for (auto h = hosts.begin(); h != hosts.end(); ++h) {
srv_config->getCfgHosts()->add(*h);
}
}
ConstElementPtr config_control = mutable_cfg->get("config-control");
if (config_control) {
parameter_name = "config-control";
ConfigControlParser parser;
ConfigControlInfoPtr config_ctl_info = parser.parse(config_control);
CfgMgr::instance().getStagingCfg()->setConfigControlInfo(config_ctl_info);
}
ConstElementPtr rsoo_list = mutable_cfg->get("relay-supplied-options");
if (rsoo_list) {
parameter_name = "relay-supplied-options";
RSOOListConfigParser parser;
parser.parse(srv_config, rsoo_list);
}
ConstElementPtr compatibility = mutable_cfg->get("compatibility");
if (compatibility) {
for (auto kv : compatibility->mapValue()) {
if (kv.first == "lenient-option-parsing") {
CfgMgr::instance().getStagingCfg()->setLenientOptionParsing(
kv.second->boolValue());
}
}
}
// Make parsers grouping.
ConfigPair config_pair;
const std::map<std::string, ConstElementPtr>& values_map =
mutable_cfg->mapValue();
BOOST_FOREACH(config_pair, values_map) {
parameter_name = config_pair.first;
// These are converted to SimpleParser and are handled already above.
if ((config_pair.first == "data-directory") ||
(config_pair.first == "option-def") ||
(config_pair.first == "option-data") ||
(config_pair.first == "mac-sources") ||
(config_pair.first == "control-socket") ||
(config_pair.first == "multi-threading") ||
(config_pair.first == "dhcp-queue-control") ||
(config_pair.first == "host-reservation-identifiers") ||
(config_pair.first == "server-id") ||
(config_pair.first == "interfaces-config") ||
(config_pair.first == "sanity-checks") ||
(config_pair.first == "expired-leases-processing") ||
(config_pair.first == "hooks-libraries") ||
(config_pair.first == "dhcp-ddns") ||
(config_pair.first == "client-classes") ||
(config_pair.first == "lease-database") ||
(config_pair.first == "hosts-database") ||
(config_pair.first == "hosts-databases") ||
(config_pair.first == "subnet6") ||
(config_pair.first == "shared-networks") ||
(config_pair.first == "reservations") ||
(config_pair.first == "config-control") ||
(config_pair.first == "relay-supplied-options") ||
(config_pair.first == "compatibility")) {
continue;
}
// As of Kea 1.6.0 we have two ways of inheriting the global parameters.
// The old method is used in JSON configuration parsers when the global
// parameters are derived into the subnets and shared networks and are
// being treated as explicitly specified. The new way used by the config
// backend is the dynamic inheritance whereby each subnet and shared
// network uses a callback function to return global parameter if it
// is not specified at lower level. This callback uses configured globals.
// We deliberately include both default and explicitly specified globals
// so as the callback can access the appropriate global values regardless
// whether they are set to a default or other value.
if ( (config_pair.first == "renew-timer") ||
(config_pair.first == "rebind-timer") ||
(config_pair.first == "preferred-lifetime") ||
(config_pair.first == "min-preferred-lifetime") ||
(config_pair.first == "max-preferred-lifetime") ||
(config_pair.first == "valid-lifetime") ||
(config_pair.first == "min-valid-lifetime") ||
(config_pair.first == "max-valid-lifetime") ||
(config_pair.first == "decline-probation-period") ||
(config_pair.first == "dhcp4o6-port") ||
(config_pair.first == "server-tag") ||
(config_pair.first == "reservation-mode") ||
(config_pair.first == "reservations-global") ||
(config_pair.first == "reservations-in-subnet") ||
(config_pair.first == "reservations-out-of-pool") ||
(config_pair.first == "calculate-tee-times") ||
(config_pair.first == "t1-percent") ||
(config_pair.first == "t2-percent") ||
(config_pair.first == "cache-threshold") ||
(config_pair.first == "cache-max-age") ||
(config_pair.first == "loggers") ||
(config_pair.first == "hostname-char-set") ||
(config_pair.first == "hostname-char-replacement") ||
(config_pair.first == "ddns-send-updates") ||
(config_pair.first == "ddns-override-no-update") ||
(config_pair.first == "ddns-override-client-update") ||
(config_pair.first == "ddns-replace-client-name") ||
(config_pair.first == "ddns-generated-prefix") ||
(config_pair.first == "ddns-qualifying-suffix") ||
(config_pair.first == "ddns-update-on-renew") ||
(config_pair.first == "ddns-use-conflict-resolution") ||
(config_pair.first == "store-extended-info") ||
(config_pair.first == "statistic-default-sample-count") ||
(config_pair.first == "statistic-default-sample-age") ||
(config_pair.first == "ip-reservations-unique") ||
(config_pair.first == "parked-packet-limit")) {
CfgMgr::instance().getStagingCfg()->addConfiguredGlobal(config_pair.first,
config_pair.second);
continue;
}
// Nothing to configure for the user-context.
if (config_pair.first == "user-context") {
continue;
}
// If we got here, no code handled this parameter, so we bail out.
isc_throw(DhcpConfigError,
"unsupported global configuration parameter: " << config_pair.first
<< " (" << config_pair.second->getPosition() << ")");
}
// Reset parameter name.
parameter_name = "<post parsing>";
// Apply global options in the staging config.
global_parser.parse(srv_config, mutable_cfg);
// This method conducts final sanity checks and tweaks. In particular,
// it checks that there is no conflict between plain subnets and those
// defined as part of shared networks.
global_parser.sanityChecks(srv_config, mutable_cfg);
// Validate D2 client configuration.
if (!d2_client_cfg) {
d2_client_cfg.reset(new D2ClientConfig());
}
d2_client_cfg->validateContents();
srv_config->setD2ClientConfig(d2_client_cfg);
} catch (const isc::Exception& ex) {
LOG_ERROR(dhcp6_logger, DHCP6_PARSER_FAIL)
.arg(parameter_name).arg(ex.what());
answer = isc::config::createAnswer(1, ex.what());
// An error occurred, so make sure that we restore original data.
rollback = true;
} catch (...) {
// For things like bad_cast in boost::lexical_cast
LOG_ERROR(dhcp6_logger, DHCP6_PARSER_EXCEPTION).arg(parameter_name);
answer = isc::config::createAnswer(1, "undefined configuration"
" processing error");
// An error occurred, so make sure that we restore original data.
rollback = true;
}
if (check_only) {
rollback = true;
if (!answer) {
answer = isc::config::createAnswer(0,
"Configuration seems sane. Control-socket, hook-libraries, and D2 "
"configuration were sanity checked, but not applied.");
}
}
// So far so good, there was no parsing error so let's commit the
// configuration. This will add created subnets and option values into
// the server's configuration.
// This operation should be exception safe but let's make sure.
if (!rollback) {
try {
// Setup the command channel.
configureCommandChannel();
// No need to commit interface names as this is handled by the
// CfgMgr::commit() function.
// Apply the staged D2ClientConfig, used to be done by parser commit
D2ClientConfigPtr cfg;
cfg = CfgMgr::instance().getStagingCfg()->getD2ClientConfig();
CfgMgr::instance().setD2ClientConfig(cfg);
// This occurs last as if it succeeds, there is no easy way to
// revert it. As a result, the failure to commit a subsequent
// change causes problems when trying to roll back.
HooksManager::prepareUnloadLibraries();
static_cast<void>(HooksManager::unloadLibraries());
const HooksConfig& libraries =
CfgMgr::instance().getStagingCfg()->getHooksConfig();
libraries.loadLibraries();
}
catch (const isc::Exception& ex) {
LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_FAIL).arg(ex.what());
answer = isc::config::createAnswer(2, ex.what());
// An error occurred, so make sure to restore the original data.
rollback = true;
} catch (...) {
// For things like bad_cast in boost::lexical_cast
LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_EXCEPTION);
answer = isc::config::createAnswer(2, "undefined configuration"
" parsing error");
// An error occurred, so make sure to restore the original data.
rollback = true;
}
}
// Moved from the commit block to add the config backend indication.
if (!rollback) {
try {
// If there are config backends, fetch and merge into staging config
server.getCBControl()->databaseConfigFetch(srv_config,
CBControlDHCPv6::FetchMode::FETCH_ALL);
}
catch (const isc::Exception& ex) {
std::ostringstream err;
err << "during update from config backend database: " << ex.what();
LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_FAIL).arg(err.str());
answer = isc::config::createAnswer(2, err.str());
// An error occurred, so make sure to restore the original data.
rollback = true;
} catch (...) {
// For things like bad_cast in boost::lexical_cast
std::ostringstream err;
err << "during update from config backend database: "
<< "undefined configuration parsing error";
LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_FAIL).arg(err.str());
answer = isc::config::createAnswer(2, err.str());
// An error occurred, so make sure to restore the original data.
rollback = true;
}
}
// Rollback changes as the configuration parsing failed.
if (rollback) {
// Revert to original configuration of runtime option definitions
// in the libdhcp++.
LibDHCP::revertRuntimeOptionDefs();
return (answer);
}
LOG_INFO(dhcp6_logger, DHCP6_CONFIG_COMPLETE)
.arg(CfgMgr::instance().getStagingCfg()->
getConfigSummary(SrvConfig::CFGSEL_ALL6));
// Everything was fine. Configuration is successful.
answer = isc::config::createAnswer(0, "Configuration successful.");
return (answer);
}
} // namespace dhcp
} // namespace isc
| 42.569937 | 94 | 0.597568 |
44007d6c50bd95a8ea0f81ef4a35f463cf0caffb | 2,004 | cxx | C++ | src/SimpleCalCalib/TholdCI.cxx | fermi-lat/CalUtil | 98b5b658257b5ffe2584cf786dd2e506173e2d8f | [
"BSD-3-Clause"
] | null | null | null | src/SimpleCalCalib/TholdCI.cxx | fermi-lat/CalUtil | 98b5b658257b5ffe2584cf786dd2e506173e2d8f | [
"BSD-3-Clause"
] | null | null | null | src/SimpleCalCalib/TholdCI.cxx | fermi-lat/CalUtil | 98b5b658257b5ffe2584cf786dd2e506173e2d8f | [
"BSD-3-Clause"
] | null | null | null | /** @file
@author Zachary Fewtrell
*/
// LOCAL INCLUDES
#include "CalUtil/SimpleCalCalib/TholdCI.h"
// GLAST INCLUDES
// EXTLIB INCLUDES
// STD INCLUDES
#include <sstream>
#include <string>
#include <fstream>
using namespace CalUtil;
using namespace std;
namespace CalUtil {
const short TholdCI::INVALID_THOLD = -5000;
TholdCI::TholdCI() :
m_fleThresh(FaceIdx::N_VALS, INVALID_THOLD),
m_fheThresh(FaceIdx::N_VALS, INVALID_THOLD),
m_lacThresh(FaceIdx::N_VALS, INVALID_THOLD),
m_uldThresh(RngIdx::N_VALS, INVALID_THOLD),
m_ped(RngIdx::N_VALS, INVALID_THOLD)
{
}
void TholdCI::readTXT(const std::string &filename) {
// open file
ifstream infile(filename.c_str());
if (!infile.is_open())
throw runtime_error(string("Unable to open " + filename));
// loop through each line in file
string line;
unsigned short twr,lyr,col,face;
float lac, fle, fhe;
CalVec<RngNum, float> uld, ped;
while (infile.good()) {
getline(infile, line);
if (infile.fail()) break; // bad get
// check for comments
if (line[0] == ';')
continue;
istringstream istrm(line);
istrm >> twr >> lyr >> col >> face
>> lac >> fle >> fhe
>> uld[0] >> uld[1] >> uld[2] >> uld[3]
>> ped[0] >> ped[1] >> ped[2] >> ped[3];
const FaceIdx faceIdx(twr,
LyrNum(lyr),
col,
// the parenthesis are _very_ important.
// see Scott Meyers "Effective STL" Item 6
(FaceNum(face)));
m_fleThresh[faceIdx] = fle;
m_fheThresh[faceIdx] = fhe;
m_lacThresh[faceIdx] = lac;
for (RngNum rng; rng.isValid(); rng++) {
const RngIdx rngIdx(faceIdx,rng);
m_uldThresh[rngIdx] = uld[rng];
m_ped[rngIdx] = ped[rng];
} // rng loop
} // line loop
} // readTXT()
} // namespace CalUtil
| 25.367089 | 70 | 0.56487 |
4400ac6a4b285923557ac5fb8ca4f0d259f3ca9e | 774 | cpp | C++ | 2stack_queue.cpp | xiaobinf/algorithm | 85a0cfc72daf6da91c4d0f568e31be69d4f19bd9 | [
"MIT"
] | null | null | null | 2stack_queue.cpp | xiaobinf/algorithm | 85a0cfc72daf6da91c4d0f568e31be69d4f19bd9 | [
"MIT"
] | null | null | null | 2stack_queue.cpp | xiaobinf/algorithm | 85a0cfc72daf6da91c4d0f568e31be69d4f19bd9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stack>
#include <exception>
using std::clog;
using std::endl;
/**
* 用两个栈模拟队列操作 画好过程图
* @tparam T
*/
template <class T>
class QStack{
public:
QStack(){}
~QStack(){}
T q_pop();
void q_push(T x);
private:
std::stack<T> s1;
std::stack<T> s2;
};
template <class T>
T QStack::q_pop(){
if(s1.size()<=0){
while(s2.size()>0){
T& data=s2.top();
s2.pop();
s1.push(data);
}
}
if(s1.size()==0){
clog<<"stack is empty"<<endl;
throw std::exception();
}
T head=s1.top();
s1.pop();
return head;
}
template <class T>
void QStack::q_push(T x) {
s2.push(x);
}
int main() {
return 0;
} | 16.468085 | 38 | 0.484496 |
44010427dfc62f2f560cc39530688bc9d5ee9cf0 | 478 | cc | C++ | abel/strings/internal/ostringstream.cc | Conun/abel | 485ef38c917c0df3750242cc38966a2bcb163588 | [
"BSD-3-Clause"
] | null | null | null | abel/strings/internal/ostringstream.cc | Conun/abel | 485ef38c917c0df3750242cc38966a2bcb163588 | [
"BSD-3-Clause"
] | null | null | null | abel/strings/internal/ostringstream.cc | Conun/abel | 485ef38c917c0df3750242cc38966a2bcb163588 | [
"BSD-3-Clause"
] | null | null | null | //
#include <abel/strings/internal/ostringstream.h>
namespace abel {
namespace strings_internal {
OStringStream::Buf::int_type OStringStream::overflow(int c) {
assert(s_);
if (!Buf::traits_type::eq_int_type(c, Buf::traits_type::eof()))
s_->push_back(static_cast<char>(c));
return 1;
}
std::streamsize OStringStream::xsputn(const char* s, std::streamsize n) {
assert(s_);
s_->append(s, n);
return n;
}
} // namespace strings_internal
} // namespace abel
| 19.12 | 73 | 0.696653 |
4401838fbbaf23517ca138f45a07b2e3294e7e9f | 887 | cc | C++ | netz/ether_support.cc | PariKhaleghi/BlackFish | dde6e4de00744be04848853e6f8d12cd4c54fd73 | [
"BSD-3-Clause"
] | 1 | 2022-03-03T08:47:33.000Z | 2022-03-03T08:47:33.000Z | netz/ether_support.cc | PariKhaleghi/BlackFish | dde6e4de00744be04848853e6f8d12cd4c54fd73 | [
"BSD-3-Clause"
] | null | null | null | netz/ether_support.cc | PariKhaleghi/BlackFish | dde6e4de00744be04848853e6f8d12cd4c54fd73 | [
"BSD-3-Clause"
] | null | null | null | #ifdef OS_AIX
#include <memory.h>
#endif
#ifdef OS_OPENBSD
#include <memory.h>
#endif
#ifdef OS_LINUX
#include <string.h>
#endif
#include "ether_support.h"
#include "support.h"
c_ether_header::c_ether_header(byte *ether_header)
{
header = (s_ether_header *)ether_header;
}
c_ether_header::c_ether_header(s_ether_header *ether_header)
{
header = ether_header;
}
byte *c_ether_header::get_raw()
{
return (byte *)header;
}
byte *c_ether_header::get_dst()
{
return header->dst;
}
void c_ether_header::set_dst(byte *dst)
{
memcpy(header->dst, dst, ETHER_ADDR_LEN);
}
byte *c_ether_header::get_src()
{
return header->src;
}
void c_ether_header::set_src(byte *src)
{
memcpy(header->src, src, ETHER_ADDR_LEN);
}
word c_ether_header::get_type()
{
return ntoh(header->type);
}
void c_ether_header::set_type(word type)
{
header->type = hton(type);
}
| 14.783333 | 60 | 0.706877 |
4402919f1922b8d1c7aa1b0aba90b53f65624833 | 1,803 | cpp | C++ | 2course/Programming/examples/from_study_guide/5_1.cpp | posgen/OmsuMaterials | 6132fe300154db97327667728c4cf3b0e19420e6 | [
"Unlicense"
] | 9 | 2017-04-03T08:52:58.000Z | 2020-06-05T18:25:02.000Z | 2course/Programming/examples/from_study_guide/5_1.cpp | posgen/OmsuMaterials | 6132fe300154db97327667728c4cf3b0e19420e6 | [
"Unlicense"
] | 6 | 2018-02-07T18:26:27.000Z | 2021-09-02T04:46:06.000Z | 2course/Programming/examples/from_study_guide/5_1.cpp | posgen/OmsuMaterials | 6132fe300154db97327667728c4cf3b0e19420e6 | [
"Unlicense"
] | 10 | 2018-11-12T18:18:47.000Z | 2020-06-06T06:17:01.000Z | /*
Определить функцию для вычисления по формуле Ньютона приблежённого значения
арифметического квадратного корня. В формуле Ньютона итерации определяются
по формуле r_[n+1] = (r_[n] + x / r_[n]) / 2
Версия для C++
*/
#include <iostream>
#include <cmath>
#include <clocale>
const double PRECISION = 0.000000001;
/*
Объявление функции с именем newton_root.
Она принимает один аргумент типа double и возращает значение типа double.
Объявление без описания тела функции (блок кода в фигурных скобках) - позволяет
делать вызов этой функции в любом месте, до определения самой функции.
*/
double newton_root(double );
int main()
{
std::setlocale(LC_ALL, "RUS");
double x, result;
std::cout << "Введите x: ";
std::cin >> x;
// вызываем функцию, передавая ей в качестве аргумента переменную x и сохраняя возращённый ею результат в переменной result
result = newton_root(x);
std::cout << "Корень из x: " << result;
return 0;
}
/*
Ниже производится определение функции. В отличие от объявления, здесь обязательно указание имени передаваемых аргументов.
Имя аргумента используется только в теле функции.
Стоит заметить, что отделение объявления и определения функции не является обязательным при записи всего в одном файле.
*/
double newton_root(double num)
{
double r_cur, r_next = num;
/*
Действительные числа (float, double) лучше сравнивать с некоторой заранее определённой
точностью по числу знаков после запятой.
num == 0.0 - не гарантирует, что сравнение будет истино даже если num = 0;
*/
if (num < PRECISION)
return 0.0;
do {
r_cur = r_next;
r_next = (r_cur + num / r_cur) / 2;
} while ( abs(r_cur - r_next) > PRECISION );
return r_next;
}
| 28.619048 | 127 | 0.688297 |
4403212b21171ef9dbb3bf9840fd2b8e1f3f86dc | 22,092 | cc | C++ | src/ldbrock.cc | GiantShawn/ldbrock | 4cebaacdf323018d258a99e7e22eb2052add8fae | [
"Unlicense"
] | null | null | null | src/ldbrock.cc | GiantShawn/ldbrock | 4cebaacdf323018d258a99e7e22eb2052add8fae | [
"Unlicense"
] | null | null | null | src/ldbrock.cc | GiantShawn/ldbrock | 4cebaacdf323018d258a99e7e22eb2052add8fae | [
"Unlicense"
] | null | null | null | #include <vector>
#include <string>
#include <iostream>
#include <cstdarg>
#include <unordered_map>
#include <fstream>
#include <ctype.h>
extern "C"
{
#include <linenoise/linenoise.h>
}
// LevelDB Headers
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
using namespace std;
#define SPACECHR " \t\n"
#define SPACECHR_LEN 3
class SplitArgs
{
public:
using ArgVector = vector<pair<string, string>>;
class ArgIterator
{
public:
ArgIterator(const ArgVector &av) : av(av), idx(0) {}
ArgIterator(const ArgVector &av, const int i) : av(av), idx(i) {}
bool operator== (const ArgIterator &o) const
{ return &av == &o.av && idx == o.idx; }
void next (void) { ++idx; }
bool end(void) const { return idx == av.size(); }
bool isNOption(void) const
{ return !av[idx].first.empty() && av[idx].second.empty(); }
bool isPOption(void) const
{ return !av[idx].first.empty() && !av[idx].second.empty(); }
bool isPosArg(void) const
{ return av[idx].first.empty() && !av[idx].second.empty(); }
const string& option(void) const
{ return av[idx].first; }
const string& pargument(void) const
{ return av[idx].second; }
private:
const ArgVector &av;
int idx;
};
public:
SplitArgs(const string &args);
bool good(void) const { return err.empty(); }
const string& error(void) const { return err; }
const size_t size(void) const { return split_args.size(); }
const ArgVector& args(void) const { return split_args; }
bool isNOption(const int i) const
{ return split_args.size() > i
&& !split_args[i].first.empty() && split_args[i].second.empty(); }
bool isPOption(const int i) const
{ return split_args.size() > i
&& !split_args[i].first.empty() && !split_args[i].second.empty(); }
bool isPosArg(const int i) const
{ return split_args.size() > i
&& split_args[i].first.empty() && !split_args[i].second.empty(); }
const ArgIterator operator[] (const int i) const
{ return ArgIterator(split_args, i); }
const string& option(const int i) const
{ return split_args[i].first; }
const string& pargument(const int i) const
{ return split_args[i].second; }
const ArgIterator newIterator(void) const { return ArgIterator(split_args); }
private:
string err;
ArgVector split_args;
};
SplitArgs::SplitArgs(const string &args)
{
int argi = 0;
bool opt_arg_pending = false;
while (argi < args.length()) {
auto eid = args.find_first_of(SPACECHR, argi, SPACECHR_LEN);
if (eid == string::npos)
eid = args.length();
if (args[argi] == '-' || args[argi] == '+') {
if (opt_arg_pending) {
err = "Missing parameter to argument: -" + split_args.back().first;
}
auto argname = args.substr(argi+1, eid);
if (argname.empty()) {
err = "Command arguments ends with -";
}
if (args[argi] == '-') {
typename remove_reference<decltype(split_args)>::type::value_type v{argname, ""};
split_args.push_back(v);
opt_arg_pending = true;
} else {
split_args.emplace_back(argname, "");
}
} else {
if (opt_arg_pending) {
opt_arg_pending = false;
split_args.back().second = args.substr(argi, eid);
} else {
split_args.emplace_back("", args.substr(argi, eid));
}
}
while (eid < args.length() && isspace(args[eid])) ++eid;
argi = eid;
}
if (opt_arg_pending) {
err = "Missing parameter to arguments: -" + split_args.back().first;
}
}
class REPLTerm;
class IREPLHandler
{
public:
//typedef bool (IREPLHandler::*HandlerFunc)(const char *, REPLTerm &);
//bool echo(const char *, REPLTerm &term);
virtual bool handleLine(char *, REPLTerm &) = 0;
};
class IWriter
{
public:
virtual void write(const char *data, const size_t sz) = 0;
virtual ~IWriter(void) {}
};
class LDBCommandHandler : public IREPLHandler
{
public:
using DB = leveldb::DB;
using OOptions = leveldb::Options;
using ROptions = leveldb::ReadOptions;
using WOptions = leveldb::WriteOptions;
using DBStatus = leveldb::Status;
using DBSlice = leveldb::Slice;
using DBIterator = leveldb::Iterator;
using DBWriteBatch = leveldb::WriteBatch;
LDBCommandHandler(DB *&db, const OOptions &oops,
const ROptions &rops,
const WOptions &wops);
public:
// command actions
bool openDB(const string &args, REPLTerm &term);
bool closeDB(const string &args, REPLTerm &term);
bool getData(const string &args, REPLTerm &term);
bool retrieveData(const string &args, REPLTerm &term);
bool putData(const string &args, REPLTerm &term);
bool loadData(const string &args, REPLTerm &term);
bool destroyDB(const string &args, REPLTerm &term);
bool repairDB(const string &args, REPLTerm &term);
private:
virtual bool handleLine(char *, REPLTerm &);
const string __getDBValue(const string &key) const;
void __retrieveAllData(IWriter &wt, const char kvsep, const char itsep) const;
private:
typedef bool (LDBCommandHandler::*CommandAction)(const string &args, REPLTerm &);
using CommandActions = unordered_map<string, LDBCommandHandler::CommandAction>;
static CommandActions s_actions;
DB *&db;
OOptions oops;
ROptions rops;
WOptions wops;
public:
class NoValueException : public std::exception
{
public:
NoValueException(const string &key)
: std::exception(), m_key(key)
{}
const string key(void) const { return m_key; }
private:
const string m_key;
};
};
class REPLTerm : public IREPLHandler
{
public:
class TermWriter : public IWriter
{
public:
TermWriter(REPLTerm *term) : m_pTerm(term) {}
virtual void write(const char *data, const size_t sz);
private:
REPLTerm *m_pTerm;
};
public:
REPLTerm(IREPLHandler *hdl,
const char *prompt = "> ", const char *hist_fn = "ldbrhistory.txt");
void run(void);
void print(const char *format, ...);
void println(const char *format, ...);
void printlnResult(const char *format, ...);
void write(const char *data, const size_t sz);
void flush(void);
IWriter* newWriter(void);
private:
virtual bool handleLine(char*, REPLTerm &);
private:
string prompt;
const string history_file_name;
IREPLHandler *hdl;
};
LDBCommandHandler::CommandActions LDBCommandHandler::s_actions = {
{"open", &LDBCommandHandler::openDB},
{"close", &LDBCommandHandler::closeDB},
{"get", &LDBCommandHandler::getData},
{"retrieve", &LDBCommandHandler::retrieveData},
{"put", &LDBCommandHandler::putData},
{"load", &LDBCommandHandler::loadData},
{"dropdb", &LDBCommandHandler::destroyDB},
{"repairdb", &LDBCommandHandler::repairDB},
};
LDBCommandHandler::LDBCommandHandler(DB *&db, const OOptions &oops,
const ROptions &rops,
const WOptions &wops)
: db(db), oops(oops), rops(rops), wops(wops)
{
db = NULL;
}
bool LDBCommandHandler::handleLine(char *line, REPLTerm &term)
{
string actname, args;
char *cmd_split = strchr(line, ' ');
if (cmd_split) {
*cmd_split = '\0';
actname = line;
*cmd_split = ' ';
do { ++cmd_split; } while (isspace(*cmd_split));
args = cmd_split;
} else {
actname = line;
}
if (actname.empty()) {
// empty command
return true;
}
CommandActions::const_iterator act = s_actions.find(actname);
if (act != s_actions.cend()) {
return (this->*(act->second))(args, term);
} else {
term.println("Undefined command[%s]!", line);
return true;
}
}
bool LDBCommandHandler::openDB(const string &args, REPLTerm &term)
{
if (db) {
term.println("There is opened db");
return true;
}
string dbname;
OOptions oopt = oops;
SplitArgs split_args(args);
if (!split_args.good()) {
// error happens
term.println("Error: %s", split_args.error().c_str());
return true;
}
for (auto argit = split_args.newIterator(); !argit.end(); argit.next()) {
if (argit.isPosArg()) {
// positional argument
if (!dbname.empty()) {
term.println("Multiple db name specified, override previous one");
}
dbname = argit.pargument();
} else if (argit.isNOption()) {
if (argit.option() == "c" || argit.option() == "+create_if_missing") {
oopt.create_if_missing = true;
term.println("Create database if missed");
} else {
term.println("Error: unrecognized option[%s].", argit.option().c_str());
return true;
}
} else {
term.println("Error: unrecognized parameterized option[%s]",
argit.option().c_str());
return true;
}
}
DBStatus status = DB::Open(oopt, dbname, &db);
if (!status.ok()) {
term.println("Erro: DB open error:%s", status.ToString().c_str());
return true;
}
return true;
}
bool LDBCommandHandler::closeDB(const string &args, REPLTerm &term)
{
term.println("closeDB");
if (!db) {
term.println("No opened DB");
}
delete db;
db = NULL;
return true;
}
bool LDBCommandHandler::getData(const string &args, REPLTerm &term)
{
if (!db) {
term.println("There is no opened DB to get from");
return true;
}
SplitArgs split_args(args);
if (!split_args.good()) {
term.println("Error: %s", split_args.error().c_str());
return true;
}
if (split_args.size() == 1) {
if (split_args.option(0) == "a" || split_args.option(0) == "+all") {
IWriter *pWriter = term.newWriter();
__retrieveAllData(*pWriter, ':', '\n');
delete pWriter;
return true;
} else if (split_args.isPosArg(0)) {
try {
auto v = __getDBValue(split_args.pargument(0));
term.printlnResult("%s : %s", split_args.pargument(0).c_str(), v.c_str());
} catch (const NoValueException &exc) {
term.println("No key named[%s]", exc.key().c_str());
}
return true;
}
}
term.println("Error: invalid argument for getData");
return true;
}
bool LDBCommandHandler::retrieveData(const string &args, REPLTerm &term)
{
if (!db) {
term.println("There is no opened DB to retrieve from");
return true;
}
SplitArgs split_args(args);
if (!split_args.good()) {
term.println("Error: %s", split_args.error().c_str());
return true;
}
if (split_args.size() != 1 || !split_args[0].isPosArg()) {
term.println("retrieve <out file name>");
return true;
}
string out_fname = split_args.pargument(0);
struct FSProxy : public IWriter
{
FSProxy(fstream &&fs) : fstrm(move(fs)) {}
fstream fstrm;
void write(const char *data, const size_t sz) {
fstrm.write(data, sz);
assert(!fstrm.bad());
}
} fsproxy(fstream(out_fname, ios_base::out));
__retrieveAllData(fsproxy, ':', '\n');
return true;
}
const string LDBCommandHandler::__getDBValue(const string &key) const
{
assert(db);
if (key.empty())
return string();
ROptions ropt = rops;
string val;
DBStatus rtstatus = db->Get(ropt, key, &val);
if (rtstatus.ok())
return val;
else {
throw LDBCommandHandler::NoValueException(key);
}
}
void LDBCommandHandler::__retrieveAllData(IWriter &wt, const char kvsep, const char itsep) const
{
assert(db);
ROptions ropt = rops;
DBIterator *it = db->NewIterator(ropt);
for (it->SeekToFirst(); it->Valid(); it->Next()) {
const auto &k = it->key();
const auto &v = it->value();
wt.write(k.data(), k.size());
wt.write(&kvsep, 1);
wt.write(v.data(), v.size());
wt.write(&itsep, 1);
}
}
bool LDBCommandHandler::putData(const string &args, REPLTerm &term)
{
if (!db) {
term.println("There is no opened DB to write to");
return true;
}
SplitArgs split_args(args);
if (!split_args.good()) {
term.println("Error: %s", split_args.error().c_str());
return true;
}
if (split_args.size() != 2 || !split_args.isPosArg(0) || !split_args.isPosArg(1)) {
term.println("put <key> <value>");
return true;
}
WOptions wopt = wops;
DBStatus status = db->Put(wopt, split_args.pargument(0), split_args.pargument(1));
if (!status.ok()) {
term.println("Fail to put data into DB");
return true;
}
return true;
}
bool LDBCommandHandler::loadData(const string &args, REPLTerm &term)
{
if (!db) {
term.println("There is no opened DB to write to");
return true;
}
SplitArgs split_args(args);
if (!split_args.good()) {
term.println("Error: %s", split_args.error().c_str());
return true;
}
if (split_args.size() != 1 || !split_args.isPosArg(0)) {
term.println("load <filename>");
return true;
}
fstream infl(split_args.pargument(0), ios_base::in);
if (!infl) {
term.println("Fail to open data input file");
return true;
}
DBWriteBatch wb;
string ln;
while (std::getline(infl, ln)) {
const size_t sep = ln.find(',');
if (sep == string::npos) {
term.println("Mal-formated data input file");
infl.close();
return true;
}
const string key = ln.substr(0, sep);
const string val = ln.substr(sep+1);
wb.Put(key, val);
}
WOptions wopt = wops;
db->Write(wopt, &wb);
return true;
}
bool LDBCommandHandler::destroyDB(const string &args, REPLTerm &term)
{
if (db) {
term.println("There is opened DB, close it first!");
return true;
}
SplitArgs split_args(args);
if (!split_args.good()) {
term.println("Error: %s", split_args.error().c_str());
return true;
}
if (split_args.size() != 1 || !split_args.isPosArg(0)) {
term.println("destroydb <dbname>");
return true;
}
OOptions oopt = oops;
DBStatus status = leveldb::DestroyDB(split_args.pargument(0), oopt);
if (status.ok()) {
term.println("Successfully destroy db");
return true;
} else {
term.println("Fail to destroy db");
return true;
}
}
bool LDBCommandHandler::repairDB(const string &args, REPLTerm &term)
{
if (db) {
term.println("There is opened DB, close it first!");
return true;
}
SplitArgs split_args(args);
if (!split_args.good()) {
term.println("Error: %s", split_args.error().c_str());
return true;
}
if (split_args.size() != 1 || !split_args.isPosArg(0)) {
term.println("repairdb <dbname>");
return true;
}
OOptions oopt = oops;
DBStatus status = leveldb::RepairDB(split_args.pargument(0), oopt);
if (status.ok()) {
term.println("Successfully repair db");
return true;
} else {
term.println("Fail to repair db");
return true;
}
return true;
}
void REPLTerm::TermWriter::write(const char *data, const size_t sz)
{
// add lock if neccessary
m_pTerm->write(data, sz);
m_pTerm->flush();
}
REPLTerm::REPLTerm(IREPLHandler *hdl, const char *prompt, const char *hist_fn)
:prompt(prompt),
history_file_name(hist_fn),
hdl(hdl)
{
if (!history_file_name.empty())
linenoiseHistoryLoad(history_file_name.c_str());
}
void REPLTerm::print(const char *format, ...)
{
va_list vl;
va_start(vl, format);
vprintf(format, vl);
va_end(vl);
}
void REPLTerm::println(const char *format, ...)
{
va_list vl;
va_start(vl, format);
vprintf(format, vl);
va_end(vl);
if (format[strlen(format)-1] != '\n')
printf("\n");
flush();
}
void REPLTerm::printlnResult(const char *format, ...)
{
printf("=> ");
va_list vl;
va_start(vl, format);
vprintf(format, vl);
va_end(vl);
if (format[strlen(format)-1] != '\n')
printf("\n");
flush();
}
IWriter* REPLTerm::newWriter(void)
{
return new TermWriter(this);
}
void REPLTerm::write(const char *data, const size_t sz)
{
fwrite(data, sizeof(*data), sz, stdout);
}
void REPLTerm::flush(void)
{
fflush(stdout);
}
bool REPLTerm::handleLine(char *line, REPLTerm &term)
{
term.println("Echo: %s", line);
return true;
}
void REPLTerm::run(void)
{
char *line;
while ((line = linenoise(prompt.c_str()))) {
//cout << "echo:" << line << endl;
auto cont = hdl->handleLine(line, *this);
if (cont)
linenoiseHistoryAdd(line);
linenoiseFree(line);
if (!cont)
break;
}
linenoiseHistorySave(history_file_name.c_str());
}
int main(int argc, char **argv)
{
leveldb::DB *db;
leveldb::Options oops;
leveldb::ReadOptions rops;
leveldb::WriteOptions wops;
LDBCommandHandler ldbh(db, oops, rops, wops);
REPLTerm term(&ldbh, "> ");
term.run();
return 0;
}
| 32.110465 | 113 | 0.47017 |
4403da96c1a053243a411d33ceecba44a494520e | 20,089 | hpp | C++ | src/thirdparty/stlsoft/STLSoft/include/winstl/controls/listview_sequence.hpp | nneesshh/servercore | 8aceb7c9d5b26976469645a708b4ab804864c03f | [
"MIT"
] | null | null | null | src/thirdparty/stlsoft/STLSoft/include/winstl/controls/listview_sequence.hpp | nneesshh/servercore | 8aceb7c9d5b26976469645a708b4ab804864c03f | [
"MIT"
] | null | null | null | src/thirdparty/stlsoft/STLSoft/include/winstl/controls/listview_sequence.hpp | nneesshh/servercore | 8aceb7c9d5b26976469645a708b4ab804864c03f | [
"MIT"
] | 2 | 2020-11-04T03:07:09.000Z | 2020-11-05T08:14:45.000Z | /* /////////////////////////////////////////////////////////////////////////
* File: winstl/controls/listview_sequence.hpp
*
* Purpose: Contains the listview_sequence class template.
*
* Created: 8th May 2003
* Updated: 19th February 2017
*
* Thanks: To Pablo Aguilar for making the requisite feature requests.
*
* Home: http://stlsoft.org/
*
* Copyright (c) 2003-2017, Matthew Wilson and Synesis Software
* 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(s) of Matthew Wilson and Synesis Software nor the
* names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ////////////////////////////////////////////////////////////////////// */
/** \file winstl/controls/listview_sequence.hpp
*
* \brief [C++ only] Definition of the winstl::listview_sequence class
* (\ref group__library__Windows_Control "Windows Control" Library).
*/
#ifndef WINSTL_INCL_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE
#define WINSTL_INCL_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE
#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
# define WINSTL_VER_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE_MAJOR 4
# define WINSTL_VER_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE_MINOR 3
# define WINSTL_VER_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE_REVISION 9
# define WINSTL_VER_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE_EDIT 88
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */
/* /////////////////////////////////////////////////////////////////////////
* includes
*/
#ifndef WINSTL_INCL_WINSTL_H_WINSTL
# include <winstl/winstl.h>
#endif /* !WINSTL_INCL_WINSTL_H_WINSTL */
#ifdef STLSOFT_TRACE_INCLUDE
# pragma message(__FILE__)
#endif /* STLSOFT_TRACE_INCLUDE */
#ifndef STLSOFT_INCL_STLSOFT_COLLECTIONS_UTIL_HPP_COLLECTIONS
# include <stlsoft/collections/util/collections.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_COLLECTIONS_UTIL_HPP_COLLECTIONS */
#ifndef STLSOFT_INCL_STLSOFT_MEMORY_HPP_AUTO_BUFFER
# include <stlsoft/memory/auto_buffer.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_MEMORY_HPP_AUTO_BUFFER */
#ifndef WINSTL_INCL_WINSTL_MEMORY_HPP_PROCESSHEAP_ALLOCATOR
# include <winstl/memory/processheap_allocator.hpp>
#endif /* !WINSTL_INCL_WINSTL_MEMORY_HPP_PROCESSHEAP_ALLOCATOR */
#ifndef STLSOFT_INCL_STLSOFT_STRING_HPP_SHIM_STRING
# include <stlsoft/string/shim_string.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_STRING_HPP_SHIM_STRING */
#ifndef STLSOFT_INCL_STLSOFT_STRING_HPP_SIMPLE_STRING
# include <stlsoft/string/simple_string.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_STRING_HPP_SIMPLE_STRING */
#ifndef STLSOFT_INCL_STLSOFT_UTIL_STD_HPP_ITERATOR_HELPER
# include <stlsoft/util/std/iterator_helper.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_UTIL_STD_HPP_ITERATOR_HELPER */
#ifndef WINSTL_INCL_WINSTL_CONTROLS_H_COMMCTRL_FUNCTIONS
# include <winstl/controls/commctrl_functions.h>
#endif /* !WINSTL_INCL_WINSTL_CONTROLS_H_COMMCTRL_FUNCTIONS */
#ifdef WINSTL_LISTVIEW_SEQUENCE_CUSTOM_STRING_TYPE
typedef WINSTL_LISTVIEW_SEQUENCE_CUSTOM_STRING_TYPE lvs_string_t;
#else /* ? WINSTL_LISTVIEW_SEQUENCE_CUSTOM_STRING_TYPE */
# ifdef STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_CLASS_ARGUMENT_SUPPORT
typedef STLSOFT_NS_QUAL(basic_simple_string)<TCHAR> lvs_string_t;
# else
typedef STLSOFT_NS_QUAL(basic_simple_string)< TCHAR
, STLSOFT_NS_QUAL(stlsoft_char_traits)<TCHAR>
, WINSTL_NS_QUAL(processheap_allocator)<TCHAR>
> lvs_string_t;
# endif /* STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_CLASS_ARGUMENT_SUPPORT */
#endif /* WINSTL_LISTVIEW_SEQUENCE_CUSTOM_STRING_TYPE */
#ifndef WINSTL_INCL_WINSTL_SHIMS_ACCESS_HPP_STRING
# include <winstl/shims/access/string.hpp>
#endif /* !WINSTL_INCL_WINSTL_SHIMS_ACCESS_HPP_STRING */
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
# ifndef STLSOFT_INCL_STLSOFT_CONVERSION_HPP_TRUNCATION_CAST
# include <stlsoft/conversion/truncation_cast.hpp>
# endif /* !STLSOFT_INCL_STLSOFT_CONVERSION_HPP_TRUNCATION_CAST */
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
/* /////////////////////////////////////////////////////////////////////////
* namespace
*/
#ifndef WINSTL_NO_NAMESPACE
# if defined(STLSOFT_NO_NAMESPACE) || \
defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
/* There is no stlsoft namespace, so must define ::winstl */
namespace winstl
{
# else
/* Define stlsoft::winstl_project */
namespace stlsoft
{
namespace winstl_project
{
# endif /* STLSOFT_NO_NAMESPACE */
#endif /* !WINSTL_NO_NAMESPACE */
/* /////////////////////////////////////////////////////////////////////////
* typedefs
*/
#ifndef WINSTL_NO_NAMESPACE
using ::lvs_string_t;
#endif /* !WINSTL_NO_NAMESPACE */
/* /////////////////////////////////////////////////////////////////////////
* classes
*/
/** Item class used by the listview_sequence class
*
* \ingroup group__library__Windows_Control
*/
//template<ss_typename_param_k S = lvs_string_t>
class listview_sequence_item
{
public:
// typedef S string_type;
public:
listview_sequence_item(HWND hwndListView, int iIndex)
: m_hwndListView(hwndListView)
, m_index(iIndex)
{}
public:
lvs_string_t text(int iSubItem = 0) const
{
typedef STLSOFT_NS_QUAL(auto_buffer_old)< TCHAR
, processheap_allocator<TCHAR>
, 256
> buffer_t;
ws_size_t cb = buffer_t::internal_size();
LV_ITEM item;
item.mask = LVIF_TEXT;
item.iItem = m_index;
item.iSubItem = iSubItem;
for(;; cb += buffer_t::internal_size())
{
buffer_t buffer(cb);
item.cchTextMax = static_cast<int>(cb);
item.pszText = &buffer[0];
if(!ListView_GetItem(m_hwndListView, &item))
{
item.cchTextMax = 0;
break;
}
else
{
ss_size_t len = static_cast<ss_size_t>(lstrlen(item.pszText));
if(len + 1 < cb)
{
return lvs_string_t(item.pszText, len);
}
}
}
return lvs_string_t();
}
int index() const
{
return m_index;
}
HWND hwnd() const
{
return m_hwndListView;
}
int image() const;
int selected_image() const;
ws_dword_t data() const
{
LV_ITEM item;
item.mask = LVIF_PARAM;
item.iItem = m_index;
item.iSubItem = 0;
return ListView_GetItem(m_hwndListView, &item) ? static_cast<ws_dword_t>(item.lParam) : 0;
}
/// The item's state
UINT state(UINT mask = 0xffffffff) const
{
return ListView_GetItemState(m_hwndListView, m_index, mask);
}
private:
HWND m_hwndListView;
int m_index;
};
/** Provides an STL-like sequence over the contents of a Windows List-view (<code>"SysListView32"</code>)
*
* \ingroup group__library__Windows_Control
*/
class listview_sequence
: public STLSOFT_NS_QUAL(stl_collection_tag)
{
public:
/// The value type
typedef listview_sequence_item sequence_value_type;
typedef sequence_value_type value_type;
/// The size type
typedef ss_size_t size_type;
/// The difference type
typedef ws_ptrdiff_t difference_type;
///
typedef listview_sequence sequence_class_type;
private:
typedef int internal_index_type_;
public:
ss_explicit_k listview_sequence(HWND hwndListView)
: m_hwndListView(hwndListView)
{}
public:
/// const_iterator for the listview_sequence
class const_iterator
: public STLSOFT_NS_QUAL(iterator_base)<STLSOFT_NS_QUAL_STD(random_access_iterator_tag)
, sequence_value_type
, ws_ptrdiff_t
, void // By-Value Temporary reference
, sequence_value_type // By-Value Temporary reference
>
{
typedef const_iterator class_type;
public:
typedef sequence_value_type value_type;
public:
const_iterator()
: m_hwndListView(NULL)
, m_index(-1)
{}
const_iterator(HWND hwndListView, int iIndex)
: m_hwndListView(hwndListView)
, m_index(iIndex)
{}
const_iterator(class_type const& rhs)
: m_hwndListView(rhs.m_hwndListView)
, m_index(rhs.m_index)
{}
class_type& operator =(class_type const& rhs)
{
m_hwndListView = rhs.m_hwndListView;
m_index = rhs.m_index;
return *this;
}
public:
/// Dereference operator
value_type operator *() const
{
return value_type(m_hwndListView, m_index);
}
bool operator ==(class_type const& rhs) const
{
WINSTL_MESSAGE_ASSERT("Comparing iterators from different listview_sequence instances!", m_hwndListView == rhs.m_hwndListView);
return m_index == rhs.m_index;
}
bool operator !=(class_type const& rhs) const
{
WINSTL_MESSAGE_ASSERT("Comparing iterators from different listview_sequence instances!", m_hwndListView == rhs.m_hwndListView);
return m_index != rhs.m_index;
}
/// Pre-increment operator
class_type& operator ++()
{
WINSTL_MESSAGE_ASSERT("Attempting to increment an off-the-end iterator", m_index < ListView_GetItemCount(m_hwndListView));
++m_index;
return *this;
}
/// Post-increment operator
class_type operator ++(int)
{
class_type ret(*this);
operator ++();
return ret;
}
/// Pre-decrement operator
class_type& operator --()
{
WINSTL_MESSAGE_ASSERT("Attempting to decrement an iterator at the start of the sequence", 0 < m_index);
--m_index;
return *this;
}
/// Post-decrement operator
class_type operator --(int)
{
class_type ret(*this);
operator --();
return ret;
}
// Random access operations
/// Offset
class_type& operator +=(difference_type index)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
m_index += stlsoft::truncation_cast<internal_index_type_>(index);
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
m_index += static_cast<internal_index_type_>(index);
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
return *this;
}
/// Offset
class_type& operator -=(difference_type index)
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
m_index -= stlsoft::truncation_cast<internal_index_type_>(index);
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
m_index -= static_cast<internal_index_type_>(index);
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
return *this;
}
/// Subscript operator
value_type operator [](difference_type index) const
{
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
return value_type(m_hwndListView, stlsoft::truncation_cast<internal_index_type_>(m_index + index));
#else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */
return value_type(m_hwndListView, static_cast<internal_index_type_>(m_index + index));
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
}
/// Calculate the distance between \c this and \c rhs
difference_type distance(class_type const& rhs) const
{
return m_index - rhs.m_index;
}
/// Pointer subtraction
class_type operator -(difference_type n) const
{
return class_type(*this) -= n;
}
/// Pointer addition
class_type operator +(difference_type n) const
{
return class_type(*this) += n;
}
/// Pointer difference
difference_type operator -(class_type const& rhs) const
{
return distance(rhs);
}
// Members
private:
HWND m_hwndListView;
int m_index;
};
#if defined(STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT)
/// The non-mutating (const) reverse iterator type
typedef STLSOFT_NS_QUAL(const_reverse_iterator_base)< const_iterator
, value_type
, value_type // By-Value Temporary reference category
, void // By-Value Temporary reference category
, difference_type
> const_reverse_iterator;
#endif /* STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT */
// State
public:
/// Returns the number of elements in the list-box
size_type size() const
{
return static_cast<size_type>(ListView_GetItemCount(m_hwndListView));
}
/// Indicates whether the list-box is empty
ws_bool_t empty() const
{
return 0 == size();
}
/// Returns the maximum number of items that the list-box can contain
static size_type max_size()
{
return static_cast<size_type>(-1) / sizeof(LPCTSTR);
}
// Iteration
public:
const_iterator begin() const
{
return const_iterator(m_hwndListView, 0);
}
const_iterator end() const
{
return const_iterator(m_hwndListView, static_cast<int>(size()));
}
#if defined(STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT)
/// Begins the reverse iteration
///
/// \return An iterator representing the start of the reverse sequence
const_reverse_iterator rbegin() const
{
return const_reverse_iterator(end());
}
/// Ends the reverse iteration
///
/// \return An iterator representing the end of the reverse sequence
const_reverse_iterator rend() const
{
return const_reverse_iterator(begin());
}
#endif /* STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT */
// Accessors
public:
value_type operator [](size_type index) const
{
return value_type(m_hwndListView, static_cast<int>(index));
}
private:
HWND m_hwndListView;
};
/* /////////////////////////////////////////////////////////////////////////
* shims
*/
inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_ptr_null(listview_sequence_item const& lvi)
{
return STLSOFT_NS_QUAL(c_str_ptr_null)(lvi.text());
}
#ifdef UNICODE
inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_ptr_null_w(listview_sequence_item const& lvi)
#else /* ? UNICODE */
inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_ptr_null_a(listview_sequence_item const& lvi)
#endif /* UNICODE */
{
return STLSOFT_NS_QUAL(c_str_ptr_null)(lvi.text());
}
inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, false, processheap_allocator<TCHAR> > c_str_ptr(listview_sequence_item const& lvi)
{
return STLSOFT_NS_QUAL(c_str_ptr)(lvi.text());
}
#ifdef UNICODE
inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_ptr_w(listview_sequence_item const& lvi)
#else /* ? UNICODE */
inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_ptr_a(listview_sequence_item const& lvi)
#endif /* UNICODE */
{
return STLSOFT_NS_QUAL(c_str_ptr)(lvi.text());
}
inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, false, processheap_allocator<TCHAR> > c_str_data(listview_sequence_item const& lvi)
{
return STLSOFT_NS_QUAL(c_str_data)(lvi.text());
}
#ifdef UNICODE
inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_data_w(listview_sequence_item const& lvi)
#else /* ? UNICODE */
inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_data_a(listview_sequence_item const& lvi)
#endif /* UNICODE */
{
return STLSOFT_NS_QUAL(c_str_data)(lvi.text());
}
inline ws_size_t c_str_len(listview_sequence_item const& lvi)
{
return STLSOFT_NS_QUAL(c_str_len)(lvi.text());
}
template< ss_typename_param_k S
>
inline S& operator <<(S& s, listview_sequence_item const& lvi)
{
s << lvi.text();
return s;
}
/* /////////////////////////////////////////////////////////////////////////
* namespace
*/
#ifndef WINSTL_NO_NAMESPACE
# if defined(STLSOFT_NO_NAMESPACE) || \
defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
} /* namespace winstl */
# else
} /* namespace winstl_project */
} /* namespace stlsoft */
# endif /* STLSOFT_NO_NAMESPACE */
#endif /* !WINSTL_NO_NAMESPACE */
/* /////////////////////////////////////////////////////////////////////////
* namespace
*
* The string access shims exist either in the stlsoft namespace, or in the
* global namespace. This is required by the lookup rules.
*
*/
#ifndef WINSTL_NO_NAMESPACE
# if !defined(STLSOFT_NO_NAMESPACE) && \
!defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
namespace stlsoft
{
# else /* ? STLSOFT_NO_NAMESPACE */
/* There is no stlsoft namespace, so must define in the global namespace */
# endif /* !STLSOFT_NO_NAMESPACE */
using ::winstl::c_str_ptr_null;
using ::winstl::c_str_ptr_null_a;
using ::winstl::c_str_ptr_null_w;
using ::winstl::c_str_ptr;
using ::winstl::c_str_ptr_a;
using ::winstl::c_str_ptr_w;
using ::winstl::c_str_data;
using ::winstl::c_str_data_a;
using ::winstl::c_str_data_w;
using ::winstl::c_str_len;
# if !defined(STLSOFT_NO_NAMESPACE) && \
!defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
} /* namespace stlsoft */
# else /* ? STLSOFT_NO_NAMESPACE */
/* There is no stlsoft namespace, so must define in the global namespace */
# endif /* !STLSOFT_NO_NAMESPACE */
#endif /* !WINSTL_NO_NAMESPACE */
/* /////////////////////////////////////////////////////////////////////////
* inclusion control
*/
#ifdef STLSOFT_CF_PRAGMA_ONCE_SUPPORT
# pragma once
#endif /* STLSOFT_CF_PRAGMA_ONCE_SUPPORT */
#endif /* !WINSTL_INCL_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE */
/* ///////////////////////////// end of file //////////////////////////// */
| 32.771615 | 141 | 0.636816 |
4403dfed513c5fdb39e812465f6013deb45634de | 79,067 | cpp | C++ | trunk/win/Source/BT_Camera.cpp | dyzmapl/BumpTop | 1329ea41411c7368516b942d19add694af3d602f | [
"Apache-2.0"
] | 460 | 2016-01-13T12:49:34.000Z | 2022-02-20T04:10:40.000Z | trunk/win/Source/BT_Camera.cpp | dyzmapl/BumpTop | 1329ea41411c7368516b942d19add694af3d602f | [
"Apache-2.0"
] | 24 | 2016-11-07T04:59:49.000Z | 2022-03-14T06:34:12.000Z | trunk/win/Source/BT_Camera.cpp | dyzmapl/BumpTop | 1329ea41411c7368516b942d19add694af3d602f | [
"Apache-2.0"
] | 148 | 2016-01-17T03:16:43.000Z | 2022-03-17T12:20:36.000Z | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "BT_Common.h"
#include "BT_CustomActor.h"
#include "BT_DialogManager.h"
#include "BT_AnimationManager.h"
#include "BT_AutomatedTradeshowDemo.h"
#include "BT_Camera.h"
#include "BT_EventManager.h"
#include "BT_FacebookWidgetJavaScriptAPI.h"
#include "BT_FileSystemManager.h"
#include "BT_JavaScriptAPI.h"
#ifdef DXRENDER
#include "BT_DXRender.h"
#endif
#include "BT_PbPersistenceHelpers.h"
#include "BT_PhotoFrameActor.h"
#include "BT_Pile.h"
#include "BT_RaycastReports.h"
#include "BT_RenderManager.h"
#include "BT_SceneManager.h"
#include "BT_Selection.h"
#include "BT_StatsManager.h"
#include "BT_TextManager.h"
#include "BT_Util.h"
#include "BT_WatchedObjects.h"
#include "BT_WebActor.h"
#include "BT_WindowsOS.h"
#include "BumpTop.pb.h"
#include "TwitterClient.h"
#include "FacebookClient.h"
//
// RestoreOriginalPhoto control implementation
//
RestoreOriginalPhotoControl::RestoreOriginalPhotoControl()
: _layout(NULL)
, _hLayout(NULL)
, _label(NULL)
, _enabled(false)
{}
RestoreOriginalPhotoControl::~RestoreOriginalPhotoControl()
{}
void RestoreOriginalPhotoControl::init()
{
_layout = new OverlayLayout;
_layout->getStyle().setOffset(Vec3(-0.13f, -0.05f, 0));
_label = new TextOverlay(QT_TR_NOOP("Undo Photo Crop"));
_label->setAlpha(1.0f);
_hLayout = new HorizontalOverlayLayout;
_hLayout->getStyle().setBackgroundColor(ColorVal(60, 0, 0, 0));
_hLayout->getStyle().setPadding(AllEdges, 5.0f);
_hLayout->getStyle().setPadding(RightEdge, 10.0f);
_hLayout->getStyle().setSpacing(2.0f);
_hLayout->addItem(_label);
_hLayout->addMouseEventHandler(this);
_layout->addItem(_hLayout);
scnManager->registerOverlay(_layout);
}
void RestoreOriginalPhotoControl::show()
{
if (_enabled)
return;
_enabled = true;
// If the control is not created, then create it
// This is lazy initialization.
if (!_layout)
{
init();
}
fadeIn();
return;
}
bool RestoreOriginalPhotoControl::onMouseDown( MouseOverlayEvent& mouseEvent )
{
if (!_enabled)
return false;
// Zoom to default camera position
FileSystemActor* photo = dynamic_cast<FileSystemActor*>(cam->getHighlightedWatchedActor());
restoreOriginalPhoto(photo);
return true;
}
bool RestoreOriginalPhotoControl::onMouseUp( MouseOverlayEvent& mouseEvent )
{
if (!_enabled)
return false;
return true;
}
bool RestoreOriginalPhotoControl::onMouseMove( MouseOverlayEvent& mouseEvent )
{
return false;
}
void RestoreOriginalPhotoControl::hide()
{
if (_enabled)
{
fadeOut();
_enabled = false;
}
}
void RestoreOriginalPhotoControl::fadeIn()
{
_hLayout->finishAnimation();
float alpha = _hLayout->getStyle().getAlpha();
if (alpha < 1.0f)
_hLayout->setAlphaAnim(alpha, 1.0f, 15);
}
void RestoreOriginalPhotoControl::fadeOut()
{
_hLayout->finishAnimation();
float alpha = _hLayout->getStyle().getAlpha();
if (alpha > 0.0f)
_hLayout->setAlphaAnim(alpha, 0.0f, 15);
}
//
// CameraOverlay implementation
//
void SlideShowControls::init()
{
_enabled = true;
_facebookActor = getFacebookActor(false);
if (_slideshowMenuContainer) //Already initialized
{
fadeIn();
return;
}
//Create Slideshow Menu Items
_slideshowMenuContainer = new OverlayLayout;
_slideshowMenuHLayout = new HorizontalOverlayLayout;
_twitterContainer = new OverlayLayout;
_twitterLayout = new VerticalOverlayLayout;
_twitterImage = new ImageOverlay("pui.twitter");
_twitterLabel = new TextOverlay(QT_TR_NOOP("Twitter"));
_facebookContainer = new OverlayLayout;
_facebookLayout = new VerticalOverlayLayout;
_facebookImage = new ImageOverlay("pui.facebook");
_facebookLabel = new TextOverlay(QT_TR_NOOP("Facebook"));
_emailContainer = new OverlayLayout;
_emailLayout = new VerticalOverlayLayout;
_emailImage = new ImageOverlay("pui.email");
_emailLabel = new TextOverlay(QT_TR_NOOP("Email"));
_printerContainer = new OverlayLayout;
_printerLayout = new VerticalOverlayLayout;
_printerImage = new ImageOverlay("pui.print");
_printerLabel = new TextOverlay(QT_TR_NOOP("Print"));
_editContainer = new OverlayLayout;
_editLayout = new VerticalOverlayLayout;
_editImage = new ImageOverlay("pui.edit");
_editLabel = new TextOverlay(QT_TR_NOOP("Edit"));
_dividerImage1 = new ImageOverlay("pui.divider");
_dividerImage2 = new ImageOverlay("pui.divider");
_dividerImage3 = new ImageOverlay("pui.divider");
_dividerImage4 = new ImageOverlay("pui.divider");
_dividerImage5 = new ImageOverlay("pui.divider");
_dividerImage6 = new ImageOverlay("pui.divider");
_closeContainer = new OverlayLayout;
_closeLayout = new VerticalOverlayLayout;
_closeImage = new ImageOverlay("pui.close");
_closeLabel = new TextOverlay(QT_TR_NOOP("Close"));
_nextContainer = new OverlayLayout;
_nextLayout = new VerticalOverlayLayout;
_nextImage = new ImageOverlay("pui.next");
_prevContainer = new OverlayLayout;
_prevLayout = new VerticalOverlayLayout;
_prevImage = new ImageOverlay("pui.previous");
//Initialize Slideshow Menu Items
_slideshowMenuContainer->getStyle().setOffset(Vec3(-0.5f, 0.02f, 0));
_slideshowMenuHLayout->getStyle().setBackgroundColor(ColorVal(195, 0, 0, 0));
_slideshowMenuHLayout->getStyle().setPadding(AllEdges,5.0f);
FontDescription slideShowButtonFont(QT_NT("Tahoma bold"), 10);
_twitterLabel->setFont(slideShowButtonFont);
_facebookLabel->setFont(slideShowButtonFont);
_emailLabel->setFont(slideShowButtonFont);
_printerLabel->setFont(slideShowButtonFont);
_editLabel->setFont(slideShowButtonFont);
_closeLabel->setFont(slideShowButtonFont);
_twitterLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0));
_facebookLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0));
_emailLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0));
_printerLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0));
_editLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0));
_closeLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0));
_nextLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0));
_prevLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0));
_twitterLayout->getStyle().setPadding(TopBottomEdges, 10.0f);
_twitterLayout->getStyle().setPadding(LeftRightEdges, 0.0f);
_twitterLayout->getStyle().setSpacing(0.0f);
_facebookLayout->getStyle().setPadding(TopBottomEdges, 10.0f);
_facebookLayout->getStyle().setPadding(LeftRightEdges, 0.0f);
_facebookLayout->getStyle().setSpacing(0.0f);
_emailLayout->getStyle().setPadding(TopBottomEdges, 10.0f);
_emailLayout->getStyle().setPadding(LeftRightEdges, 0.0f);
_emailLayout->getStyle().setSpacing(0.0f);
_printerLayout->getStyle().setPadding(TopBottomEdges, 10.0f);
_printerLayout->getStyle().setPadding(LeftRightEdges, 0.0f);
_printerLayout->getStyle().setSpacing(0.0f);
_editLayout->getStyle().setPadding(TopBottomEdges, 10.0f);
_editLayout->getStyle().setPadding(LeftRightEdges, 0.0f);
_editLayout->getStyle().setSpacing(0.0f);
_closeLayout->getStyle().setPadding(TopBottomEdges, 10.0f);
_closeLayout->getStyle().setPadding(LeftRightEdges, 0.0f);
_closeLayout->getStyle().setSpacing(0.0f);
_nextLayout->getStyle().setPadding(TopBottomEdges, 10.0f);
_nextLayout->getStyle().setPadding(LeftRightEdges, 0.0f);
_nextLayout->getStyle().setSpacing(0.0f);
_prevLayout->getStyle().setPadding(TopBottomEdges, 10.0f);
_prevLayout->getStyle().setPadding(LeftRightEdges, 0.0f);
_prevLayout->getStyle().setSpacing(0.0f);
_dividerImage1->getStyle().setPadding(TopBottomEdges, 10.0f);
_dividerImage1->getStyle().setPadding(LeftRightEdges, 0.0f);
_dividerImage1->getStyle().setSpacing(0.0f);
_dividerImage2->getStyle().setPadding(TopBottomEdges, 10.0f);
_dividerImage2->getStyle().setPadding(LeftRightEdges, 0.0f);
_dividerImage2->getStyle().setSpacing(0.0f);
_dividerImage3->getStyle().setPadding(TopBottomEdges, 10.0f);
_dividerImage3->getStyle().setPadding(LeftRightEdges, 0.0f);
_dividerImage3->getStyle().setSpacing(0.0f);
_dividerImage4->getStyle().setPadding(TopBottomEdges, 10.0f);
_dividerImage4->getStyle().setPadding(LeftRightEdges, 0.0f);
_dividerImage4->getStyle().setSpacing(0.0f);
_dividerImage5->getStyle().setPadding(TopBottomEdges, 10.0f);
_dividerImage5->getStyle().setPadding(LeftRightEdges, 0.0f);
_dividerImage5->getStyle().setSpacing(0.0f);
_dividerImage6->getStyle().setPadding(TopBottomEdges, 10.0f);
_dividerImage6->getStyle().setPadding(LeftRightEdges, 0.0f);
_dividerImage6->getStyle().setSpacing(0.0f);
_twitterLayout->addItem(_twitterImage);
_twitterLayout->addItem(_twitterLabel);
_twitterContainer->addMouseEventHandler(this);
_facebookLayout->addItem(_facebookImage);
_facebookLayout->addItem(_facebookLabel);
_facebookContainer->addMouseEventHandler(this);
_emailLayout->addItem(_emailImage);
_emailLayout->addItem(_emailLabel);
_emailContainer->addMouseEventHandler(this);
_printerLayout->addItem(_printerImage);
_printerLayout->addItem(_printerLabel);
_printerContainer->addMouseEventHandler(this);
_editLayout->addItem(_editImage);
_editLayout->addItem(_editLabel);
_editContainer->addMouseEventHandler(this);
_closeLayout->addItem(_closeImage);
_closeLayout->addItem(_closeLabel);
_closeContainer->addMouseEventHandler(this);
_nextLayout->addItem(_nextImage);
_nextContainer->addMouseEventHandler(this);
_prevLayout->addItem(_prevImage);
_prevContainer->addMouseEventHandler(this);
_twitterContainer->addItem(_twitterLayout);
_facebookContainer->addItem(_facebookLayout);
_emailContainer->addItem(_emailLayout);
_printerContainer->addItem(_printerLayout);
_editContainer->addItem(_editLayout);
_closeContainer->addItem(_closeLayout);
_nextContainer->addItem(_nextLayout);
_prevContainer->addItem(_prevLayout);
/* See button hit boxes
_twitterLabel->getStyle().setBackgroundColor(ColorVal(255,255,0,0));
_twitterImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0));
_twitterContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255));
_facebookLabel->getStyle().setBackgroundColor(ColorVal(255,255,0,0));
_facebookImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0));
_facebookContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255));
_emailLabel->getStyle().setBackgroundColor(ColorVal(255,255,0,0));
_emailImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0));
_emailContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255));
_prevImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0));
_prevContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255));
_nextImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0));
_nextContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255));
_printerLabel->getStyle().setBackgroundColor(ColorVal(255,255,0,0));
_printerImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0));
_printerContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255));
_editLabel->getStyle().setBackgroundColor(ColorVal(255,255,0,0));
_editImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0));
_editContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255));
_closeLabel->getStyle().setBackgroundColor(ColorVal(255,255,0,0));
_closeImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0));
_closeContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255));
/**/
_slideshowMenuHLayout->addItem(_twitterContainer);
_slideshowMenuHLayout->addItem(_dividerImage1);
_slideshowMenuHLayout->addItem(_facebookContainer);
_slideshowMenuHLayout->addItem(_dividerImage2);
_slideshowMenuHLayout->addItem(_emailContainer);
_slideshowMenuHLayout->addItem(_dividerImage3);
_slideshowMenuHLayout->addItem(_prevContainer);
_slideshowMenuHLayout->addItem(_nextContainer);
_slideshowMenuHLayout->addItem(_dividerImage4);
_slideshowMenuHLayout->addItem(_printerContainer);
_slideshowMenuHLayout->addItem(_dividerImage5);
_slideshowMenuHLayout->addItem(_editContainer);
_slideshowMenuHLayout->addItem(_dividerImage6);
_slideshowMenuHLayout->addItem(_closeContainer);
_slideshowMenuContainer->addItem(_slideshowMenuHLayout);
scnManager->registerOverlay(_slideshowMenuContainer);
// NOTE: set the size animations _after_ they have been added to the layouts
}
SlideShowControls::SlideShowControls()
{
twitterClient = NULL;
twitpicClient = NULL;
facebookClient = NULL;
_slideshowMenuContainer = NULL;
_slideshowMenuHLayout = NULL;
_twitterContainer = NULL;
_twitterLayout = NULL;
_twitterImage = NULL;
_twitterLabel = NULL;
_facebookContainer = NULL;
_facebookLayout = NULL;
_facebookImage = NULL;
_facebookLabel = NULL;
_emailContainer = NULL;
_emailLayout = NULL;
_emailImage = NULL;
_emailLabel = NULL;
_printerContainer = NULL;
_printerLayout = NULL;
_printerImage = NULL;
_printerLabel = NULL;
_editContainer = NULL;
_editLayout = NULL;
_editImage = NULL;
_editLabel = NULL;
_closeContainer = NULL;
_closeLayout = NULL;
_closeImage = NULL;
_closeLabel = NULL;
_prevContainer = NULL;
_prevLayout = NULL;
_prevImage = NULL;
_nextContainer = NULL;
_nextLayout = NULL;
_nextImage = NULL;
_dividerImage1 = NULL;
_dividerImage2 = NULL;
_dividerImage3 = NULL;
_dividerImage4 = NULL;
_dividerImage5 = NULL;
_dividerImage6 = NULL;
}
SlideShowControls::~SlideShowControls()
{
// Scene manager automatically removes all unused overlays
}
void SlideShowControls::fadeIn()
{
_slideshowMenuHLayout->setAlphaAnim(_slideshowMenuHLayout->getStyle().getAlpha(), 1.0f, 25);
}
void SlideShowControls::fadeOut()
{
_slideshowMenuHLayout->finishAnimation();
float alpha = _slideshowMenuHLayout->getStyle().getAlpha();
if (alpha > 0.0f)
_slideshowMenuHLayout->setAlphaAnim(alpha, 0.0f, 25);
if(!evtManager->getACPowerStatus()) { //Battery power
_slideshowMenuHLayout->setAlpha(0.0f);
}
SetCursor(LoadCursor(NULL, IDC_ARROW));
}
void SlideShowControls::twitterAction() {
BumpObject* currentActor = cam->getHighlightedWatchedActor();
if (!ftManager->hasInternetConnection())
{
printUniqueError("TwitterActorImpl", QT_TRANSLATE_NOOP("TwitpicClient", "No internet connection detected"));
return;
}
CustomActor * twit = scnManager->getCustomActor<TwitterActorImpl>();
if(twit) { //Twitter actor exists
std::vector<BumpObject *> currentActor;
currentActor.push_back(cam->getHighlightedWatchedActor());
twit->onDrop(currentActor);
return;
} else { //We need to open up our own connection to twitter (based on code from the onDrop event)
if(!twitterClient) twitterClient = new TwitterClient(TWITTER_SERVER);
if(!twitpicClient) twitpicClient = new TwitpicClient(TWITPIC_SERVER);
BumpObject* currentActor = cam->getHighlightedWatchedActor();
if (twitterClient->initialize() && twitpicClient->initialize()) {
if (currentActor->getObjectType() == ObjectType(BumpActor, FileSystem, Image))
{
QString photoPath = dynamic_cast<FileSystemActor *>(currentActor)->getFullPath();
twitpicClient->uploadAndPostDeferMessage(photoPath); //tweet
}
else
{
// non-files are rejected
printUniqueError("TwitterActorImpl", QT_TRANSLATE_NOOP("TwitpicClient", "Unsupported image file type"));
}
}
}
}
void SlideShowControls::facebookAction() {
if (!ftManager->hasInternetConnection())
{
printUniqueError("FacebookActorImpl", QT_TRANSLATE_NOOP("FacebookClient", "No internet connection detected"));
return;
}
bool wasOn = true;
if(!_facebookActor) {
_facebookActor = getFacebookActor(true);
wasOn = false;
}
FacebookWidgetJavaScriptAPI* fbAPI = dynamic_cast<FacebookWidgetJavaScriptAPI*>(_facebookActor->getJavaScriptAPI());
//We found the facebook widget
if(GLOBAL(settings).fbc_uid.isEmpty() && GLOBAL(settings).fbc_session.isEmpty() && GLOBAL(settings).fbc_secret.isEmpty()) { //User is not logged in
fbAPI->launchLoginPage();
fbAPI->setPersistentStoreValue(QT_NT("last-page"),QT_NT("newsfeed"));
_facebookActor->load(QT_NT("bumpwidget-facebook://newsfeed"), true);
}
//The reason we check twice is that the user could have cancelled the login process.
if(!(GLOBAL(settings).fbc_uid.isEmpty() && GLOBAL(settings).fbc_session.isEmpty() && GLOBAL(settings).fbc_secret.isEmpty())) { //User has logged in
vector<BumpObject *> watched;
watched.push_back(cam->getHighlightedWatchedActor());
fbAPI->onDropEnter(watched);
fbAPI->onDrop();
goFacebookAction();
} else {
if(!wasOn) {
FadeAndDeleteActor(_facebookActor);
}
}
}
WebActor * SlideShowControls::getFacebookActor(bool createIfNotExists) {
vector<BumpObject *> webActors = scnManager->getBumpObjects(ObjectType(BumpActor, Webpage));
for (int i = 0; i < webActors.size(); ++i)
{
WebActor * actor = (WebActor *) webActors[i];
if (actor->isFacebookWidgetUrl())
{
return actor;
}
}
if(createIfNotExists) {
Key_ToggleFacebookWidget();
vector<BumpObject *> webActors = scnManager->getBumpObjects(ObjectType(BumpActor, Webpage));
for (int i = 0; i < webActors.size(); ++i)
{
WebActor * actor = (WebActor *) webActors[i];
if (actor->isFacebookWidgetUrl())
{
return actor;
}
}
}
return NULL;
}
void SlideShowControls::goFacebookAction() {
cam->killAnimation();
Key_ToggleSlideShow();
_facebookActor->onLaunch();
}
void SlideShowControls::printerAction(){
CustomActor * prnt = scnManager->getCustomActor<PrinterActorImpl>();
if(prnt) { //Printer actor exists
std::vector<BumpObject *> currentActor;
currentActor.push_back(cam->getHighlightedWatchedActor());
prnt->onDrop(currentActor);
return;
} else { //We need to open up our own connection to the printer (based on code from the onDrop event function)
BumpObject * currentActor = cam->getHighlightedWatchedActor();
if (!(currentActor->getObjectType() == ObjectType(BumpActor, FileSystem, File)))
{
MessageClearPolicy clearPolicy;
clearPolicy.setTimeout(2);
scnManager->messages()->addMessage(new Message("PrinterActorImpl::onDrop", QT_TR_NOOP("You can only print files!"), Message::Ok, clearPolicy));
return;
}
dlgManager->clearState();
dlgManager->setPrompt(QT_TR_NOOP("Print these file(s) on your default printer?"));
if (!dlgManager->promptDialog(DialogYesNo))
{
dismiss("PrinterActorImpl::onDrop");
return;
}
QString filePath = dynamic_cast<FileSystemActor *>(currentActor)->getFullPath();
int result = (int) ShellExecute(winOS->GetWindowsHandle(), QT_NT(L"print"), (LPCTSTR) filePath.utf16(), NULL, NULL, SW_SHOWNORMAL);
if (result <= 32)
{
MessageClearPolicy clearPolicy;
clearPolicy.setTimeout(2);
scnManager->messages()->addMessage(new Message("PrinterActorImpl::onDrop", QT_TR_NOOP("Could not print this file!"), Message::Ok, clearPolicy));
return;
}
else
{
// notify the user
MessageClearPolicy clearPolicy;
clearPolicy.setTimeout(3);
Message * message = new Message("PrinterActorImpl::onDrop", QT_TR_NOOP("Printing file"), Message::Ok, clearPolicy);
scnManager->messages()->addMessage(message);
return;
}
}
}
void SlideShowControls::closeAction(){
Key_ToggleSlideShow();
}
void SlideShowControls::emailAction(){
CustomActor * mail = scnManager->getCustomActor<EmailActorImpl>();
if(mail) { //Email actor exists
std::vector<BumpObject *> currentActor;
currentActor.push_back(cam->getHighlightedWatchedActor());
mail->onDrop(currentActor);
return;
} else { //We need to open up our own connection to email (based on code from the onDrop event function)
std::vector<BumpObject *> currentActor;
currentActor.push_back(cam->getHighlightedWatchedActor());
if (!CreateEmailWithSelectionAsAttachments(currentActor))
{
MessageClearPolicy clearPolicy;
clearPolicy.setTimeout(2);
scnManager->messages()->addMessage(new Message("EmailActorImpl::onDrop", QT_TR_NOOP("Could not create email with these files\nas attachments!"), Message::Ok, clearPolicy));
}
else
{
// notify the user
MessageClearPolicy clearPolicy;
clearPolicy.setTimeout(3);
Message * message = new Message("EmailActorImpl::onDrop", QT_TR_NOOP("Creating new email"), Message::Ok, clearPolicy);
scnManager->messages()->addMessage(message);
}
}
}
void SlideShowControls::nextAction(){
cam->highlightNextWatchedActor(true);
}
void SlideShowControls::prevAction(){
cam->highlightNextWatchedActor(false);
}
void SlideShowControls::editAction(){
assert(cam->getHighlightedWatchedActor() != NULL);
BumpObject * currentActor = cam->getHighlightedWatchedActor();
if(currentActor->getObjectType() == ObjectType(BumpActor, FileSystem)) {
fsManager->launchFile(dynamic_cast<FileSystemActor *>(currentActor)->getFullPath(),L"edit");
}
}
int SlideShowControls::getHeight() {
return _slideshowMenuHLayout->getSize().y;
}
void *callbackManager(AnimationEntry *anim) {
SlideShowControls *controls = (SlideShowControls *)anim->getCustomData();
switch (controls->pressed) {
case SlideShowControls::TWITTER:
controls->twitterAction();
break;
case SlideShowControls::FACEBOOK:
controls->facebookAction();
break;
case SlideShowControls::EMAIL:
controls->emailAction();
break;
case SlideShowControls::EDIT:
controls->editAction();
break;
case SlideShowControls::CLOSE:
controls->closeAction();
break;
case SlideShowControls::NEXT:
controls->nextAction();
break;
case SlideShowControls::PREVIOUS:
controls->prevAction();
break;
case SlideShowControls::GOFACEBOOK:
controls->goFacebookAction();
break;
case SlideShowControls::PRINTER:
controls->printerAction();
break;
}
return NULL;
}
bool SlideShowControls::onMouseDown( MouseOverlayEvent& mouseEvent )
{
if (!_enabled)
return true;
//TODO: A lot of this code is parallel to the respective actors in customactor, if possible we should share these resources
OverlayComponent * button = dynamic_cast<OverlayComponent *>(mouseEvent.getTarget());
if (dynamic_cast<OverlayLayout *>(button) == _twitterContainer) {//Twitter button
pressed = TWITTER;
} else if (dynamic_cast<OverlayLayout *>(button) == _facebookContainer) {//Facebook button
pressed = FACEBOOK;
} else if (dynamic_cast<OverlayLayout *>(button) == _emailContainer) {//Email button
pressed = EMAIL;
} else if (dynamic_cast<OverlayLayout *>(button) == _printerContainer) {//Printer button
pressed = PRINTER;
} else if (dynamic_cast<OverlayLayout *>(button) == _editContainer) {//Edit button
pressed = EDIT;
} else if (dynamic_cast<OverlayLayout *>(button) == _closeContainer) {//Close button
pressed = CLOSE;
} else if (dynamic_cast<OverlayLayout *>(button) == _prevContainer) {//Previous image button
pressed = PREVIOUS;
} else if (dynamic_cast<OverlayLayout *>(button) == _nextContainer) {//Next image button
pressed = NEXT;
} else {
pressed = NOPRESS;
}
if(pressed != NOPRESS) {
if(button->isAnimating()) {
button->finishAnimation();
AnimationEntry a = AnimationEntry(button,NULL,this);
callbackManager(&a);
}
button->setAlphaAnim(0.5f,1.0f,15,(FinishedCallBack)callbackManager, this);
}
return true;
}
bool SlideShowControls::onMouseUp( MouseOverlayEvent& mouseEvent )
{
if (!_enabled)
return false;
// reset the color of the font
OverlayComponent * button = mouseEvent.getTarget();
button->getStyle().setColor(ColorVal(255, 255, 255, 255));
if (!mouseEvent.intersectsTarget())
SetCursor(LoadCursor(NULL, IDC_ARROW));
return true;
}
bool SlideShowControls::onMouseMove( MouseOverlayEvent& mouseEvent )
{
if (!_enabled)
return false;
return false;
}
void SlideShowControls::disable()
{
if (_slideshowMenuContainer)
{
fadeOut();
_enabled = false;
}
}
//
// ZoomOut control implementation
//
ZoomOutControl::ZoomOutControl()
: _layout(NULL)
, _hLayout(NULL)
, _zoomOutLabel(NULL)
, _enabled(false)
{}
ZoomOutControl::~ZoomOutControl()
{}
void ZoomOutControl::init()
{
_layout = new OverlayLayout;
_layout->getStyle().setOffset(Vec3(-0.10f, -0.05f, 0));
_defaultText = QT_TR_NOOP("Reset Camera");
_zoomOutLabel = new TextOverlay(_defaultText);
_zoomOutLabel->setAlpha(1.0f);
_zoomOutLabel->getTextBuffer().pushFlag(TextPixmapBuffer::ForceLinearFiltering);
_zoomOutLabel->getTextBuffer().pushFlag(TextPixmapBuffer::DisableClearType);
_hLayout = new HorizontalOverlayLayout;
_hLayout->getStyle().setBackgroundColor(ColorVal(60, 0, 0, 0));
_hLayout->getStyle().setPadding(AllEdges, 5.0f);
_hLayout->getStyle().setPadding(RightEdge, 10.0f);
_hLayout->getStyle().setSpacing(2.0f);
_hLayout->addItem(_zoomOutLabel);
_hLayout->addMouseEventHandler(this);
_layout->addItem(_hLayout);
scnManager->registerOverlay(_layout);
}
void ZoomOutControl::show()
{
if (_enabled)
return;
_enabled = true;
// If the control is not created, then create it
// This is lazy initialization.
if (!_layout)
{
init();
}
fadeIn();
return;
}
void ZoomOutControl::setText(QString text, Vec3 offset)
{
if (!_layout)
{
init();
_hLayout->finishAnimation();
if (!_enabled) // If not visible, set alpha to 0 since init() automatically sets alpha to 1
_hLayout->getStyle().setAlpha(0);
}
if (text == _zoomOutLabel->getText())
return;
if (text.isEmpty())
{
text = _defaultText;
offset = Vec3(-0.10f, -0.05f, 0);
}
_zoomOutLabel->setText(text, false);
_zoomOutLabel->setSize(_zoomOutLabel->getPreferredDimensions());
_hLayout->setSize(_hLayout->getPreferredDimensions());
_hLayout->reLayout();
_layout->getStyle().setOffset(offset);
_layout->reLayout();
}
bool ZoomOutControl::onMouseDown( MouseOverlayEvent& mouseEvent )
{
if (!_enabled)
return false;
if (!WebActor::zoomOutFocusedWebActor()) //zoomOutFocusedWebActor will only zoom out when there is exactly one web actor focused / zoomed
{
cam->getZoomedObjects().clear();
cam->loadCameraFromPreset(GLOBAL(settings.cameraPreset));
}
return true;
}
bool ZoomOutControl::onMouseUp( MouseOverlayEvent& mouseEvent )
{
if (!_enabled)
return false;
return true;
}
bool ZoomOutControl::onMouseMove( MouseOverlayEvent& mouseEvent )
{
return false;
}
void ZoomOutControl::hide()
{
if (_enabled)
{
cam->setTrackingWatchedActors(true);
fadeOut();
_enabled = false;
}
}
bool ZoomOutControl::isEnabled()
{
return _enabled;
}
void ZoomOutControl::fadeIn()
{
_hLayout->finishAnimation();
float alpha = _hLayout->getStyle().getAlpha();
if (alpha < 1.0f)
_hLayout->setAlphaAnim(alpha, 1.0f, 15);
}
void ZoomOutControl_restoreText(AnimationEntry & entry)
{
((ZoomOutControl *)entry.getCustomData())->setText(QString(), Vec3(0.0f)); // Restore text to "Reset Camera"
}
void ZoomOutControl::fadeOut()
{
_hLayout->finishAnimation();
float alpha = _hLayout->getStyle().getAlpha();
if (alpha > 0.0f)
_hLayout->setAlphaAnim(alpha, 0.0f, 15, &ZoomOutControl_restoreText, this);
}
//
// CornerInfoControl control implementation
//
CornerInfoControl::CornerInfoControl()
: _layout(NULL)
, _hLayout(NULL)
, _zoomOutLabel(NULL)
, _enabled(false)
{}
CornerInfoControl::~CornerInfoControl()
{}
void CornerInfoControl::init()
{
_enabled = true;
if (_layout)
{
fadeIn();
return;
}
_layout = new OverlayLayout;
_layout->getStyle().setOffset(Vec3(0.0f, -0.07f, 0));
_zoomOutLabel = new TextOverlay("");
_zoomOutLabel->getTextBuffer().pushFlag(TextPixmapBuffer::ForceLinearFiltering);
_zoomOutLabel->getTextBuffer().pushFlag(TextPixmapBuffer::DisableClearType);
_hLayout = new HorizontalOverlayLayout;
_hLayout->getStyle().setBackgroundColor(ColorVal(80, 0, 0, 0));
_hLayout->getStyle().setPadding(AllEdges, 10.0f);
_hLayout->getStyle().setPadding(TopEdge, 12.0f);
_hLayout->getStyle().setCornerRadius(TopRightCorner|BottomRightCorner, 10.0f);
_hLayout->getStyle().setCornerRadius(TopLeftCorner|BottomLeftCorner, 0.0f);
_hLayout->getStyle().setSpacing(2.0f);
_hLayout->addItem(_zoomOutLabel);
_hLayout->addMouseEventHandler(this);
_layout->addItem(_hLayout);
scnManager->registerOverlay(_layout);
}
bool CornerInfoControl::onMouseDown( MouseOverlayEvent& mouseEvent )
{
if (!_enabled)
return false;
return true;
}
bool CornerInfoControl::onMouseUp( MouseOverlayEvent& mouseEvent )
{
if (!_enabled)
return false;
// If the demo is running stop it, otherwise disable the overlay
Replayable * replay = scnManager->getReplayable();
if (replay != NULL)
{
AutomatedTradeshowDemo * demo = dynamic_cast<AutomatedTradeshowDemo *>(replay);
if (demo->getPlayState() == replay->Running)
{
demo->quickStop();
setMessageText(QT_TR_NOOP("BumpTop Demo Scene\nTo refresh the scene hit F7\nTo start the automatic demo hit CTRL + F7"));
}
else
disable();
}
else
disable();
return true;
}
bool CornerInfoControl::onMouseMove( MouseOverlayEvent& mouseEvent )
{
return false;
}
void CornerInfoControl::disable()
{
if (_layout)
{
fadeOut();
_enabled = false;
}
}
bool CornerInfoControl::isEnabled()
{
return _enabled;
}
void CornerInfoControl::fadeIn()
{
float alpha = _hLayout->getStyle().getAlpha();
if (alpha < 1.0f)
_hLayout->setAlphaAnim(alpha, 1.0f, 15);
}
void CornerInfoControl::fadeOut()
{
float alpha = _hLayout->getStyle().getAlpha();
if (alpha > 0.0f)
_hLayout->setAlphaAnim(alpha, 0.0f, 15);
}
void CornerInfoControl::setMessageText(QString text)
{
if (!_zoomOutLabel)
return;
_zoomOutLabel->setText(text);
_hLayout->setSize(_hLayout->getPreferredDimensions());
}
//
// Camera implementation
//
const float Camera::SAME_POSITION_THRESHOLD = 0.0005f;
Camera::Camera()
:
#ifndef DXRENDER
_glProjMatrix(new GLdouble[16])
, _glMVMatrix(new GLdouble[16])
, _glViewport(new GLint[4])
, _isglDataDirty(false)
,
#endif
_animationFinishData(NULL)
, _currentCameraView(DefaultView)
{
_animationFinishCallback = NULL;
// Default Values
setOrientation(Vec3(0, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1));
cameraIsFreeForm = false;
#ifndef DXRENDER
ZeroMemory(_glProjMatrix, 16 * sizeof(GLdouble));
ZeroMemory(_glMVMatrix, 16 * sizeof(GLdouble));
ZeroMemory(_glViewport, 4 * sizeof(GLint));
#endif
// init the visible bounds
visibleBounds.setEmpty();
}
Camera::~Camera()
{
#ifndef DXRENDER
SAFE_DELETE(_glProjMatrix);
SAFE_DELETE(_glMVMatrix);
SAFE_DELETE(_glViewport);
#endif
popAllWatchActors();
}
Vec3 Camera::getEye()
{
return eye;
}
Vec3 Camera::getUp()
{
return up;
}
Vec3 Camera::getDir()
{
return dir;
}
void Camera::setEye(Vec3 newEye)
{
eye = newEye;
#ifndef DXRENDER
_isglDataDirty = true;
#endif
}
void Camera::setDir(Vec3 newDir)
{
dir = newDir;
dir.normalize();
#ifndef DXRENDER
_isglDataDirty = true;
#endif
}
void Camera::setUp(Vec3 newUp)
{
up = newUp;
#ifndef DXRENDER
_isglDataDirty = true;
#endif
}
// Camera settings loaded from Scene file
Vec3 Camera::getSavedEye()
{
return savedEye;
}
Vec3 Camera::getSavedDir()
{
return savedDir;
}
Vec3 Camera::getSavedUp()
{
return savedUp;
}
void Camera::storeCameraPosition(Vec3 newEye, Vec3 newDir, Vec3 newUp)
{
savedEye = newEye;
savedDir = newDir;
savedUp = newUp;
}
bool Camera::isCameraFreeForm()
{
return cameraIsFreeForm;
}
void Camera::setIsCameraFreeForm(bool isCameraFreeForm, bool showMessage)
{
if (!cameraIsFreeForm && isCameraFreeForm)
{
setCurrentCameraView(Camera::UserDefinedView);
if (showMessage)
printTimedUnique("Camera::setIsCameraFreeForm", 7, QT_TR_NOOP("Move the camera by using scroll wheel, double-click to focus or Ctrl + Shift W, A, S, D."));
}
cameraIsFreeForm = isCameraFreeForm;
}
// This returns the camera eye when invoking ZoomToAngledBounds
// This method is used for error checking in zooming. This
// makes sure we don't fly out of the desktop box
Vec3 Camera::getDefaultEye()
{
// Find out the region where this camera will look at
Bounds bounds;
for (int i = 0; i < 4; i++)
{
Vec3 wallsPos = GLOBAL(WallsPos)[i];
wallsPos.y = 0;
bounds.include(wallsPos);
}
// Move the camera into position so it encapsulates the entire work area
Vec3 oldEye = getEye(), oldUp = getUp(), oldDir = getDir();
Vec3 newEye, newDir, extents;
bounds.getExtents(extents);
float distZ = extents.z * 0.70f;
float distX = extents.x * 0.70f;
// Move the camera to look at that location
Vec3 camView;
camView.x = bounds.getMin().x + ((bounds.getMax().x - bounds.getMin().x) / 2);
camView.z = bounds.getMin().z + ((bounds.getMax().z - bounds.getMin().z) / 2);
float aspect = float(winOS->GetWindowWidth()) / float(winOS->GetWindowHeight());
float hFoV = bounds.getMax().z - bounds.getMin().z;
float wFoV = bounds.getMax().x - bounds.getMin().x;
float FoV = CAMERA_FOVY / 2; // 60 / 2 Deg on Y-axis
float tanFoV = tan(FoV * (PI / 180));
float multiplier;
// Fix the multiplier based on the aspect ratio, if needed (aspect ratio only if width is larger)
if (wFoV / hFoV > aspect)
{
// Width is longer then the screen, use it
multiplier = wFoV / aspect;
}else{
// height is longer then the screen
multiplier = hFoV;
}
// distance form the group
camView.y = bounds.getMax().y + ((multiplier / 2) / tanFoV);
return camView + Vec3(0, 10, -distZ);
}
Camera::PredefinedCameraViews Camera::getCurrentCameraView()
{
return _currentCameraView;
}
void Camera::setCurrentCameraView(PredefinedCameraViews view, bool makePersistent)
{
_currentCameraView = view;
if (view == Camera::TopDownView)
{
zoomToTopDownView();
if (makePersistent)
GLOBAL(settings).cameraPreset = QT_NT("oh");
}
else if (view == Camera::BottomRightCornerView)
{
zoomToBottomRightCornerView();
if (makePersistent)
GLOBAL(settings).cameraPreset = QT_NT("brc");
}
else if (view == Camera::UserDefinedView)
{
// TODO: We should add code to zoom to the currently
// user defined camera position. We do not store such
// information in settings yet, so just return.
return;
}
else
{
zoomToAngledView();
if (makePersistent)
GLOBAL(settings).cameraPreset = QT_NT("def");
}
if (makePersistent)
winOS->SaveSettingsFile();
}
void Camera::setOrientation(Vec3 Eye, Vec3 Up, Vec3 Dir)
{
// Set the orientation of the camera
setEye(Eye);
setUp(Up);
setDir(Dir);
}
void Camera::unserialize(unsigned char *buf, uint &bufSz, int versionNumber)
{
Vec3 eye, dir, up;
if (versionNumber >= 11 &&
SERIALIZE_READ_VEC3(&buf, eye, bufSz) &&
SERIALIZE_READ_VEC3(&buf, dir, bufSz) &&
SERIALIZE_READ_VEC3(&buf, up, bufSz))
{
savedEye = eye;
savedDir = dir;
savedUp = up;
}
}
void Camera::update(float elapsed)
{
// if we are watching a set of actors, check their bounds to
// see if we need to update the camera
if (!watchedActors.empty())
{
WatchedObjects& watched = watchedActors.top();
if (!watched.highlightedActor)
{
// check the watched actors' bounds
Bounds bounds = getActorsBounds(watched.actors, true);
// ensure that we are not already zoomed to bounds
float minMag = (bounds.getMin() - watched.bounds.getMin()).magnitudeSquared();
float maxMag = (bounds.getMax() - watched.bounds.getMax()).magnitudeSquared();
if (minMag > 0.005f || maxMag > 0.005f)
{
// zoom to bounds
if (!GLOBAL(isBumpPhotoMode))
{
if (isTrackingWatchedActors())
{
zoomToBounds(bounds, false);
}
watched.bounds = bounds;
}
rndrManager->invalidateRenderer();
}
}
}
// Check whether or not the ZoomOutControl needs to be rendered.
if ((eye - orig).magnitude() < SAME_POSITION_THRESHOLD)
{
// Hide the ZoomOut control when the camera is at the origin
if (zoomOutControl.isEnabled())
zoomOutControl.hide();
}
else
{
if (isSlideshowModeActive() || GLOBAL(isInSharingMode) || GLOBAL(isInInfiniteDesktopMode))
{
// Hide the ZoomOut control when we're in slideshow or sharing mode
zoomOutControl.hide();
}
else if (pathEye.size() > 0 && (pathEye.back() - orig).magnitude() < SAME_POSITION_THRESHOLD)
{
// If the camera is animating towards the origin, hide the ZoomOut control
zoomOutControl.hide();
}
else
{
// Otherwise, show the zoomOut control
zoomOutControl.show();
}
}
#ifndef DXRENDER
if (_isglDataDirty)
readOGLMatrices();
#endif
}
// Bounds checking and adjusting
bool Camera::adjustPointInDesktop(Vec3& origin, Vec3& destination, NxPlane& plane)
{
Vec3 direction = destination - origin;
direction.normalize();
Ray ray(origin, direction);
Box desktopBox = GetDesktopBox(GLOBAL(ZoomBuffer));
NxPlane planes[6];
desktopBox.computePlanes(planes);
// For some reason, intersection will only work correctly if the normals of all the planes face to the inside of the desktop.
// computePlanes() gives us these two planes (floor and ceiling) with the normals facing outwards.
planes[2].normal *= -1.0f;
planes[3].normal *= -1.0f;
// Two hacks that help keep the rest of BumpTop looking as pretty as it used to be.
// The first sets the y bound as the default camera position.
// The second sets the floor y bound to be actually on the floor and not below it.
planes[2].d = -getDefaultEye().y;
planes[3].d = 5.0f;
NxReal xMin, xMax, yMin, yMax, zMin, zMax, distance;
xMin = desktopBox.GetCenter().x - desktopBox.GetExtents().x;
xMax = desktopBox.GetCenter().x + desktopBox.GetExtents().x;
yMin = desktopBox.GetCenter().y - desktopBox.GetExtents().y;
yMax = getDefaultEye().y; // desktopBox.GetCenter().y + desktopBox.GetExtents().y;
zMin = desktopBox.GetCenter().z - desktopBox.GetExtents().z;
zMax = desktopBox.GetCenter().z + desktopBox.GetExtents().z;
int index = -1;
int count = 0;
do
{
if (destination.x > xMax)
{
NxRayPlaneIntersect(ray, planes[1], distance, destination);
destination.x = xMax;
index = 1;
}
else if (destination.x < xMin)
{
NxRayPlaneIntersect(ray, planes[0], distance, destination);
destination.x = xMin;
index = 0;
}
if (destination.y > yMax)
{
NxRayPlaneIntersect(ray, planes[2], distance, destination);
destination.y = yMax;
index = 2;
}
else if (destination.y < yMin)
{
NxRayPlaneIntersect(ray, planes[3], distance, destination);
destination.y = yMin;
index = 3;
}
if (destination.z > zMax)
{
NxRayPlaneIntersect(ray, planes[5], distance, destination);
destination.z = zMax;
index = 5;
}
else if (destination.z < zMin)
{
NxRayPlaneIntersect(ray, planes[4], distance, destination);
destination.z = zMin;
index = 4;
}
count++;
} while (index != -1 && count < 2);
if (index == -1)
return false;
if (count == 2)
{
// This means we are stuck in such a position where the origin and
// destination form a ray that completely exists outside of the
// desktop box. We will need to handle this differently.
// Project the point to the wall it intersected and use that new point.
ray = Ray(destination, planes[index].normal);
NxRayPlaneIntersect(ray, planes[index], distance, destination);
}
plane = planes[index];
return true;
}
// eyeDest: the position in world space of the destination the camera eye is to animate to
// dirDest: the direction in world space of the destination the camera direction is to animate to
// upDest: the up direction in world space of the destination the camera up direction is to animate to
// timeStep: the amount of steps the animation should take to get to its destination
// easeIn: whether or not the animation should start slow and speed into the animation
// boundsCheck: whether or not to preform boundary checking
// projectTail: whether or not to preform a projection of the tail end of the vector(made from the current eye position
// and the eye destination) onto the plane it intersects. boundsCheck must be set to true for this to work.
void Camera::animateToImpl(Vec3 eyeDest, Vec3 dirDest, Vec3 upDest, int timeStep, bool easeIn, bool boundsCheck, bool projectTail)
{
EaseFunctionType easeType;
if (easeIn)
easeType = Ease;
else
easeType = NoEase;
int originalTimeStep = timeStep;
dirDest.normalize();
upDest.normalize();
deque<Vec3> projectionPath;
if (boundsCheck)
{
// Perform bounds-checking/adjusting
Vec3 newEyeDest = eyeDest;
NxPlane plane;
// If the destination is outside the desktop, move it in, and only proceed in the body
// of this if statement if we want to project the tail of the vector.
if (adjustPointInDesktop(eye, eyeDest, plane) && projectTail)
{
// Project the destination point onto the plane the vector intersected and make an animation from
// the point of intersection to this projected point
NxReal dist;
Ray ray(newEyeDest, plane.normal);
NxRayPlaneIntersect(ray, plane, dist, newEyeDest);
adjustPointInDesktop(eyeDest, newEyeDest, plane);
float percentage = eyeDest.distance(newEyeDest) / (eye.distance(eyeDest) + eyeDest.distance(newEyeDest));
int projectedTimeStep = percentage * timeStep;
timeStep -= projectedTimeStep;
if (projectedTimeStep > 0)
projectionPath = lerpRange(eyeDest, newEyeDest, projectedTimeStep, NoEase);
}
}
if (timeStep > 0)
{
// Create an animation path over [timeStep] frames
pathEye = lerpRange(eye, eyeDest, timeStep, easeType);
}
pathDir = lerpRange(dir, dirDest, originalTimeStep, easeType);
pathUp = lerpRange(up, upDest, originalTimeStep, easeType);
// Append, if necessary, the projected animation path to the normal path
for (int n = 0; n < projectionPath.size(); n++)
{
pathEye.push_back(projectionPath[n]);
}
animManager->addAnimation(AnimationEntry(this, (FinishedCallBack) ReshapeTextAfterAnim, this));
}
void Camera::animateTo(Vec3 eyeDest, Vec3 dirDest, Vec3 upDest, int timeStep, bool easeIn)
{
animateToImpl(eyeDest, dirDest, upDest, timeStep, easeIn, false, false);
}
void Camera::animateToWithBounds(Vec3 eyeDest, Vec3 dirDest, Vec3 upDest, int timeStep, bool easeIn)
{
animateToImpl(eyeDest, dirDest, upDest, timeStep, easeIn, true, false);
}
void Camera::animateToWithSliding(Vec3 eyeDest, Vec3 dirDest, Vec3 upDest, int timeStep, bool easeIn)
{
animateToImpl(eyeDest, dirDest, upDest, timeStep, easeIn, true, true);
}
void Camera::animateQuadratic(Vec3 eyeDest, Vec3 topDest, Vec3 dirDest, Vec3 upDest, int timeStep)
{
dirDest.normalize();
upDest.normalize();
// Create an animation path over [timeStep] frames
pathEye = lerpQuardaticCurve(eye, topDest, eyeDest, timeStep);
// pathEye = lerpQuardaticCurve(eye, eye + (eyeDest-eye)*1.1, eyeDest, timeStep); //quadratic overshoot animation, doesn't look that great
pathDir = lerpRange(dir, dirDest, timeStep);
pathUp = lerpRange(up, upDest, timeStep);
animManager->addAnimation(AnimationEntry(this, (FinishedCallBack) ReshapeTextAfterAnim, NULL));
}
void Camera::customAnimation(deque<Vec3> &eyeDest, deque<Vec3> &dirDest, deque<Vec3> &upDest)
{
// Set the new custom Path
pathEye = eyeDest;
pathDir = dirDest;
pathUp = upDest;
animManager->addAnimation(AnimationEntry(this, (FinishedCallBack) ReshapeTextAfterAnim, NULL));
}
void Camera::setAnimationFinishCallback(void (* animationFinishCallback)(void *), void * animationFinishData)
{
_animationFinishCallback = animationFinishCallback;
_animationFinishData = animationFinishData;
}
void Camera::animationFinishCallback()
{
if (_animationFinishCallback)
_animationFinishCallback(_animationFinishData);
_animationFinishData = NULL;
_animationFinishCallback = NULL;
}
//Jumps immediately to where the camera is currently animating too.
//Note: Leaves 1 frame of animation yet to go. Since clearing this causes a weird novodex bug (see below)
void Camera::skipAnimation()
{
animManager->finishAnimation(this);
/*
if (pathEye.size() > 0)
{
// Get the very last animation frame coordinates
setEye(pathEye.back());
setUp(pathUp.back());
setDir(pathDir.back());
//Clear all but the last frame of the animation path
pathEye.erase(pathEye.begin(), pathEye.end() - 1);
pathUp.erase(pathUp.begin(), pathUp.end() - 1);
pathDir.erase(pathDir.begin(), pathDir.end() - 1);
}
//This cleaner version causes a weird bug. On second drop of icons, icons fall through the floor and keep falling.
// Clear the animation paths
//pathEye.clear();
//pathUp.clear();
//pathDir.clear();
*/
}
void Camera::scrollToPoint(Vec3 loc)
{
// Scroll to point doesn't make much sense in infinite desktop mode
// so if a user tries to zoom in or move around we ignore those requests
if (GLOBAL(isInInfiniteDesktopMode))
return;
// Determine how far the camera is from the point we are moving to
int facingWall = cameraIsFacingWall();
Vec3 camWallOrigin = Vec3(0, 75, 0);
// update the visible bounds if necessary
updateWatchedActorVisibleBounds();
}
void Camera::scrollToOrigin()
{
if (GLOBAL(isInInfiniteDesktopMode))
{
if (isWatchingActors())
{
Vec3 center = getEyePositionToFitBounds(watchedActors.top().bounds);
orig = center;
}
}
// Scroll to the origin
if (orig.distance(getEye()) < 125.0f)
animateTo(orig, getDir(), getUp());
scrollToPoint(orig);
// dismiss the free-form camera message
dismiss("Camera::setIsCameraFreeForm");
}
void Camera::setOrigin(Vec3 newOrig)
{
orig = newOrig;
#ifndef DXRENDER
_isglDataDirty = true;
#endif
}
Vec3 Camera::getOrigin()
{
return orig;
}
void Camera::setSlideshow(bool active) {
isSlideShow = active;
}
bool Camera::inSlideshow() {
return isSlideShow;
}
void Camera::helperSetThumbnailDetail(BumpObject* actor, GLTextureDetail textureDetail, GLTextureLoadPriority priority)
{
if (hasWatchedActorHighlighted())
{
assert(isWatchedActorHighlighted(actor));
if (actor->getObjectType() == ObjectType(BumpActor, FileSystem))
{
FileSystemActor *fsActor = (FileSystemActor *)actor;
bool drawBorder = true;
if (fsActor->isFileSystemType(PhotoFrame))
{
PhotoFrameActor* pfActor = (PhotoFrameActor*)fsActor;
if (!pfActor->isSourceType(LocalImageSource))
return;
drawBorder = false;
}
if (fsActor->isThumbnailized() && !fsActor->hasAnimatedTexture())
{
QString texId = fsActor->getThumbnailID();
QString texPath = fsActor->getTargetPath();
bool isTrainingImage = texPath.startsWith(native(winOS->GetTrainingDirectory()), Qt::CaseInsensitive);
// NOTE: workaround for ensuring that training images are always hi-resolution
if (isTrainingImage)
{
dismiss("Camera::LoadingHiRes");
}
else
{
if (!texMgr->hasTextureDetail(texId, textureDetail))
{
// NOTE: we do not free the image data since that will happen when the thumbnail replaces this
// image anyways (it takes time and this is a blocking call!)
if (texMgr->loadBlockingTexture(GLTextureObject(Load|Reload, texId, texPath, textureDetail, priority, true, drawBorder), (textureDetail != HiResImage), false))
{
rndrManager->invalidateRenderer();
dismiss("Camera::LoadingHiRes");
}
else
{
printUniqueError("Camera::LoadingHiRes", QT_TR_NOOP("Could not load the full image!"));
}
}
}
}
}
}
}
void Camera::watchActor( BumpObject * object )
{
if (!watchedActors.empty())
{
WatchedObjects& watched = watchedActors.top();
vector<BumpObject *>::iterator iter =
std::find(watched.actors.begin(), watched.actors.end(), object);
if (iter == watched.actors.end())
{
watched.actors.push_back(object);
}
}
}
void Camera::unwatchActor( BumpObject * object )
{
if (!watchedActors.empty())
{
WatchedObjects& watched = watchedActors.top();
vector<BumpObject *>::iterator iter =
std::find(watched.actors.begin(), watched.actors.end(), object);
if (iter != watched.actors.end())
{
watched.actors.erase(iter);
}
}
}
void Camera::pushWatchActors( const vector<BumpObject *>& actors, bool groupPileItems)
{
// check if we are watching the exact actors aready
if (!watchedActors.empty())
{
WatchedObjects& watched = watchedActors.top();
if (watched.actors.size() == actors.size())
{
// check each actor if they are the same
bool identicalActors = true;
for (int i = 0; i < actors.size(); ++i)
{
if (watched.actors[i] != actors[i])
{
identicalActors = false;
break;
}
}
// if the same, return
if (identicalActors)
return;
}
// fade in existing items first
// watchedActors.top().fadeInAll();
}
if (!actors.empty())
{
WatchedObjects wo(actors);
orderSpatially2D(wo.actors, groupPileItems);
wo.storeCamera();
watchedActors.push(wo);
}
}
void Camera::popWatchActors()
{
if (!_onPopWatchActorsHandler.empty())
_onPopWatchActorsHandler();
if (!watchedActors.empty())
{
if (watchedActors.top().highlightedActor)
{
if (scnManager->containsObject(watchedActors.top().highlightedActor))
{
dismiss("Camera::LoadingHiRes");
assert(watchedActors.top().highlightedActor->getObjectType() == ObjectType(BumpActor, FileSystem));
FileSystemActor * fsActor = (FileSystemActor *) watchedActors.top().highlightedActor;
fsActor->setMinThumbnailDetail(SampledImage);
helperSetThumbnailDetail(watchedActors.top().highlightedActor, SampledImage, LowPriority);
}
else
{
// erase the highlight actor from the set to have their nameables restored
_prevVisibleNameables.erase(watchedActors.top().highlightedActor);
}
}
// fade in items first
// watchedActors.top().fadeInAll();
// XXX: HACKY way to get around not reseting the view angled
// `on no objects with walls down
WatchedObjects wo(watchedActors.top());
wo.restoreCamera();
if (watchedActors.size() > 1 || GLOBAL(DrawWalls))
{
watchedActors.pop();
}
else if (!watchedActors.empty())
{
watchedActors.top().highlightedActor = NULL;
}
// finish logging slideshow time if we were in slideshow at all
statsManager->finishTimer(statsManager->getStats().bt.window.slideshowTime);
// dismiss the slideshow message if there is one
dismiss("Key_ToggleSlideShow");
}
// fade in the slideshow controls
slideShowControls.disable();
}
void Camera::popAllWatchActors()
{
while (!watchedActors.empty())
{
if (watchedActors.top().highlightedActor)
{
if (scnManager->containsObject(watchedActors.top().highlightedActor))
{
dismiss("Camera::LoadingHiRes");
assert(watchedActors.top().highlightedActor->getObjectType() == ObjectType(BumpActor, FileSystem));
FileSystemActor * fsActor = (FileSystemActor *) watchedActors.top().highlightedActor;
fsActor->setMinThumbnailDetail(SampledImage);
helperSetThumbnailDetail(watchedActors.top().highlightedActor, SampledImage, LowPriority);
}
else
{
// erase the highlight actor from the set to have their nameables restored
_prevVisibleNameables.erase(watchedActors.top().highlightedActor);
}
}
watchedActors.pop();
}
// dismiss the slideshow message if there is one
dismiss("Key_ToggleSlideShow");
}
void * LoadNextHighResThumbnailAfterAnim(AnimationEntry *animEntry)
{
BumpObject * actor = (BumpObject *) animEntry->getCustomData();
if (scnManager->containsObject(actor))
{
assert(actor->getObjectType() == ObjectType(BumpActor, FileSystem));
FileSystemActor * fsActor = (FileSystemActor *) actor;
fsActor->setMinThumbnailDetail(HiResImage);
cam->helperSetThumbnailDetail(actor, HiResImage, LowPriority);
}
return NULL;
}
void * LoadHighResImageAfterAnim(AnimationEntry *animEntry)
{
BumpObject * actor = (BumpObject *) animEntry->getCustomData();
if (scnManager->containsObject(actor))
{
assert(actor->getObjectType() == ObjectType(BumpActor, FileSystem));
FileSystemActor * fsActor = (FileSystemActor *) actor;
fsActor->setMinThumbnailDetail(HiResImage);
cam->helperSetThumbnailDetail(actor, HiResImage, LowPriority);
/*
BumpObject * nextObj = cam->getNextHighlightWatchedActor(true);
nextObj->finishAnimation();
nextObj->setPoseAnim(nextObj->getGlobalPose(), nextObj->getGlobalPose(), 50);
animManager->addAnimation(AnimationEntry(cam, (FinishedCallBack) LoadNextHighResThumbnailAfterAnim, (void *) nextObj));
*/
}
return NULL;
}
void * SetupActorForSlideshow(AnimationEntry *animEntry)
{
if (!isSlideshowModeActive())
return NULL;
Vec3 newEye, newUp, newDir;
cam->zoomToOrientedActorBoundsAttributes(cam->getHighlightedWatchedActor(), newEye, newUp, newDir);
cam->setEye(newEye);
cam->setUp(newUp);
cam->setDir(newDir);
LoadHighResImageAfterAnim(animEntry);
return NULL;
}
void Camera::rehighlightWatchedActor()
{
// ensure items are being watched
if (watchedActors.empty())
return;
WatchedObjects& watched = watchedActors.top();
if (!watched.highlightedActor)
return;
// clear existing animation
pathEye.clear();
pathDir.clear();
pathUp.clear();
// get the new camera attributes
Vec3 newEye, newUp, newDir;
zoomToOrientedActorBoundsAttributes(watched.highlightedActor, newEye, newUp, newDir);
// add animation to get the movement from the previous to new actor
const int timeStep = watched.highlightedActor ? 85 : 75;
animateTo(newEye, newDir, newUp, timeStep);
}
void Camera::highlightWatchedActor( BumpObject * actor, BumpObject * nextActor )
{
static BumpObject * prevActor = NULL;
static bool prevActorWasOn = true;
// re-enable previously disabled photo frames
if (prevActor && prevActor->isObjectType(ObjectType(BumpActor, FileSystem, PhotoFrame)))
{
// When the slideshow is being ended, this function will be called with NULL,NULL. We check for this here because in certain cases
// prevActor can be a dangling pointer (zoom in on photoframe and hit delete key)
if (prevActorWasOn)
{
if (!dynamic_cast<PhotoFrameActor *>(prevActor)->isUpdating())
dynamic_cast<PhotoFrameActor *>(prevActor)->enableUpdate();
}
}
// disable photo frames from updating while
if (actor && actor->isObjectType(ObjectType(BumpActor, FileSystem, PhotoFrame)))
{
//Current actor is a photoframe
prevActorWasOn = dynamic_cast<PhotoFrameActor *>(actor)->isUpdating();
prevActor = actor;
if (dynamic_cast<PhotoFrameActor *>(actor)->isUpdating())
dynamic_cast<PhotoFrameActor *>(actor)->disableUpdate();
}
// ensure items are being watched
if (watchedActors.empty())
return;
WatchedObjects& watched = watchedActors.top();
// ensure different actor
if (actor == watched.highlightedActor)
return;
// ensure that the actor is currently being watched
vector<BumpObject *>::const_iterator actorIter =
find(watched.actors.begin(), watched.actors.end(), actor);
if (actorIter == watched.actors.end())
return;
// init the camera controls if not already
slideShowControls.init();
// get the eye position for both the previous and new actor (top of curve)
Vec3 bothActorsEye(eye);
bool bothActorsPinned = false;
if (watched.highlightedActor)
{
// animate to zoom to fit the previous and the new actor
Bounds watchedBounds;
watchedBounds.combine(watched.highlightedActor->getBoundingBox());
watchedBounds.combine(actor->getBoundingBox());
bothActorsEye = getEyePositionToFitBounds(watchedBounds);
bothActorsPinned = watched.highlightedActor->isPinned() && actor->isPinned();
}
// clear existing animation
pathEye.clear();
pathDir.clear();
pathUp.clear();
// get the new camera attributes
Vec3 newEye, newUp, newDir;
zoomToOrientedActorBoundsAttributes(actor, newEye, newUp, newDir);
// determine if we should lerp or slerp the eye (in any other context...)
// we do this by checking if the angles between the new and old up vecs differ too greatly,
// or if both items are pinned
bool lerp = bothActorsPinned;
float theta = acos(up.dot(newUp) / (up.magnitude() * newUp.magnitude()));
float maxAngleDiff = PI / 4.0f; // 45 degrees
if (theta >= maxAngleDiff)
{
lerp = true;
}
// add animation to get the movement from the previous to new actor
const int timeStep = watched.highlightedActor ? 85 : 75;
if (lerp || !watched.highlightedActor)
pathEye = lerpRange(eye, newEye, timeStep);
else
{
pathEye = lerpQuardaticFittingCurve(eye, bothActorsEye, newEye, timeStep, SoftEase);
}
pathDir = lerpRange(dir, newDir, timeStep, SoftEase);
pathUp = lerpRange(up, newUp, timeStep, SoftEase);
// update the highlighted actor
// (we must do this before we fade out the other actors)
watched.highlightedActor = actor;
// if it's a filesystem actor
if (!(actor->getObjectType() == ObjectType(BumpActor, FileSystem, PhotoFrame)))
printUnique("Camera::LoadingHiRes", QT_TR_NOOP("Loading full image"));
{
deque<Vec3> eyePath = pathEye;
deque<Vec3> dirPath = pathDir;
deque<Vec3> upPath = pathUp;
animManager->removeAnimation(this);
pathEye = eyePath;
pathDir = dirPath;
pathUp = upPath;
animManager->addAnimation(AnimationEntry(this, (FinishedCallBack) SetupActorForSlideshow, (void *) watched.highlightedActor));
}
// fade in the highlighted actor
// watched.fadeOutAllButHighlighted(timeStep);
// fade out all the nameables
// NOTE: we only do this for the first highlight, which is why we test if
// the next actor is NULL.
if (!nextActor)
{
storePreviousVisibleNameables(true);
}
if (actor->getObjectType() == ObjectType(BumpActor, FileSystem, Image) &&
actor->getObjectType() != ObjectType(BumpActor, FileSystem, PhotoFrame))
{
FileSystemActor* photo = dynamic_cast<FileSystemActor*>(actor);
if (hasOriginalPhoto(photo))
{
getRestoreOriginalPhotoControl()->show();
}
else
{
getRestoreOriginalPhotoControl()->hide();
}
}
else
{
getRestoreOriginalPhotoControl()->hide();
}
}
int Camera::cameraIsFacingWall()
{
// Check if camera is pointing to a wall
// Construct ray going through the camera eye and camera direction
Ray camRay(getEye(), getDir());
tuple<int, NxReal, Vec3, NxPlane> t = RayIntersectDesktop(camRay);
int wallIndex = t.get<0>();
return wallIndex;
}
void Camera::lookAtWall(NxActorWrapper* wall, Vec3& positionOut, Vec3& directionOut)
{
assert(wall);
positionOut = Vec3(0, 75, 0);
directionOut = wall->getGlobalPosition();
directionOut.y = 20;
directionOut -= positionOut;
directionOut.normalize();
// Move the camera back to get the entire wall
positionOut += -(directionOut * 100);
adjustPointToInsideWalls(positionOut);
_currentCameraView = WallView;
}
bool Camera::isWatchingActors() const
{
return !watchedActors.empty();
}
bool Camera::isTrackingWatchedActors() const
{
return isWatchingActors() && watchedActors.top().trackActors;
}
void Camera::setTrackingWatchedActors(bool state)
{
if (isTrackingWatchedActors())
{
watchedActors.top().trackActors = state;
}
}
bool Camera::isWatchedActorHighlighted( BumpObject * object ) const
{
return (!watchedActors.empty() && watchedActors.top().highlightedActor == object);
}
bool Camera::hasWatchedActorHighlighted() const
{
return (!watchedActors.empty() && watchedActors.top().highlightedActor);
}
BumpObject * Camera::getHighlightedWatchedActor() const
{
if (hasWatchedActorHighlighted())
{
return watchedActors.top().highlightedActor;
}
return NULL;
}
void Camera::highlightNextWatchedActor(bool forward)
{
if (!_onHighlightNextWatchedActorHandler.empty())
_onHighlightNextWatchedActorHandler(forward);
// ensure items are being watched
if (watchedActors.empty())
return;
WatchedObjects& watched = watchedActors.top();
// ensure there is an actor being highlighted
if (!watched.highlightedActor)
return;
// ensure that there are other items to highlight
int num = watched.actors.size();
if (num <= 1)
return;
// find it in the watched list
for (int i = 0; i < num; ++i)
{
if (watched.actors[i] == watched.highlightedActor)
{
int index = i;
int nextIndex = i;
int prevIndex = i;
if (forward)
{
prevIndex = (i+num-1) % num;
index = (i+1) % num;
nextIndex = (i+2) % num;
}
else
{
prevIndex = (i+1) % num;
index = (i+num-1) % num;
nextIndex = (i+num-2) % num;
}
// pop the high-res image for the currently highlighted actor
assert(watched.highlightedActor->getObjectType() == ObjectType(BumpActor, FileSystem));
FileSystemActor * fsActor = (FileSystemActor *) watched.highlightedActor;
fsActor->setMinThumbnailDetail(SampledImage);
helperSetThumbnailDetail(watched.highlightedActor, SampledImage, HighPriority);
// load the next item (and preload the next next item)
highlightWatchedActor(watched.actors[index], watched.actors[nextIndex]);
return;
}
}
}
Vec3 Camera::getEyePositionToFitBounds(const Bounds& bounds)
{
// save camera orientation
Vec3 tempEye(eye);
Vec3 tempUp(up);
Vec3 tempDir(dir);
// calculate new eye position to fit bounds
Vec3 newEye = zoomToBounds(bounds, false);
// restore camera orientation
setEye(tempEye);
setUp(tempUp);
setDir(tempDir);
return newEye;
}
void Camera::zoomToIncludeObjects(vector<BumpObject*> objs)
{
Bounds bounds = getActorsBounds(objs);
zoomToBounds(bounds);
}
Vec3 Camera::zoomToTopDownView()
{
setIsCameraFreeForm(false);
// calculate how high the camera must be to view the whole desktop
Box desktopBox = GetDesktopBox();
float aspect = desktopBox.extents.x / desktopBox.extents.z;
float invAspect = 1.0f / aspect;
float xFov = 60.0f / 2.0f;
float yFov = xFov / aspect;
int depth = desktopBox.extents.z;
int height = ((invAspect - 0.022f) * depth) / tan(yFov * (PI / 180));
Vec3 newEye(0, height, 0);
setOrigin(newEye);
animateTo(newEye, Vec3(0, -1, 0), Vec3(0, 0, 1));
return newEye;
}
Vec3 Camera::zoomToAngledView()
{
setIsCameraFreeForm(false);
// calculate how high the camera must be to view the whole desktop
Box desktopBox = GetDesktopBox();
float aspect = desktopBox.extents.x / desktopBox.extents.z;
float invAspect = 1.0f / aspect;
float xFov = 60.0f / 2.0f;
float yFov = xFov / aspect;
int depth = desktopBox.extents.z;
int height = ((invAspect - 0.022f) * depth) / tan(yFov * (PI / 180));
Vec3 newEye = Vec3(0, height, 0);
Vec3 newDir = Vec3(0, -1, 0);
Vec3 newUp = Vec3(0, 0, 1);
// get the rotated centroid point relative to the bottom wall edge
float angle = 18.0f;
Quat ori(angle, Vec3(-1,0,0));
ori.rotate(newEye);
ori.rotate(newDir);
ori.rotate(newUp);
// offset to be flush with the bottom wall edge
Vec3 bottomWallEdgePt(0, 0, -depth);
Vec3 rotatedBottomWallEdgePt(-newUp * depth);
Vec3 diff = rotatedBottomWallEdgePt - bottomWallEdgePt;
newEye -= diff;
setOrigin(newEye);
animateTo(newEye, newDir, newUp);
return newEye;
}
Vec3 Camera::zoomToBottomRightCornerView()
{
setIsCameraFreeForm(false);
Vec3 center, extents;
Vec3 newEye, direction, up;
Bounds wall;
vector<NxActorWrapper*> walls = GLOBAL(Walls);
// bottom wall
wall = walls[1]->getBoundingBox();
wall.getCenter(center);
wall.getExtents(extents);
newEye = center - Vec3(extents.x * 0.8, 0 , 0);
newEye.z = 0;
newEye.z = center.z * 0.8;
setOrigin(newEye);
// right wall
wall = walls[2]->getBoundingBox();
wall.getCenter(center);
wall.getExtents(extents);
direction = -newEye;
direction.x = center.x / -2;
up.cross(direction, Vec3(0, 1, 0));
up.cross(up, direction);
animateTo(newEye, direction, up);
return newEye;
}
void Camera::zoomToOrientedActorBoundsAttributes(BumpObject * actor, Vec3& eye, Vec3& up, Vec3& dir, float buffer, const Vec3 & screenSize)
{
// get the values
up = actor->getGlobalOrientation() * Vec3(0, 1, 0);
dir = actor->getGlobalOrientation() * Vec3(0, 0, 1);
up.normalize();
up.y = abs(up.y);
dir.normalize();
// check if the direction of the frame is aligned to the direction to the actor
// if not, it is backwards, so flip the direction. we do this in a hacky fashion
// by checking if the dot of the actor direction and the origin (offsetted high,
// so that the items on the floor are accounted for) are "opposite".
Vec3 actorWorldDir = actor->getGlobalPosition();
actorWorldDir -= Vec3(0, getEye().y, 0);
if (actorWorldDir.dot(dir) < 0)
dir.setNegative();
eye = actor->getGlobalPosition();
Box box = actor->getBox();
float width = float(winOS->GetWindowWidth());
float height = float(winOS->GetWindowHeight());
float aspect = width / height;
float hFoV = box.extents.y;
float wFoV = box.extents.x;
float zoomHeight = box.extents.y;
float zoomWidth = box.extents.x;
Vec3 effectiveScreenSize = Vec3(screenSize.x, screenSize.y, screenSize.z);
if(isSlideshowModeActive()) {
effectiveScreenSize.x = width*0.95; //leave a bit of buffer
effectiveScreenSize.y = height*0.95 - slideShowControls.getHeight();
}
if (!effectiveScreenSize.isZero())
{
#ifdef DXRENDER
wFoV *= dxr->viewport.Width / effectiveScreenSize.x;
hFoV *= dxr->viewport.Height / effectiveScreenSize.y;
#else
wFoV *= _glViewport[2] / effectiveScreenSize.x;
hFoV *= _glViewport[3] / effectiveScreenSize.y;
#endif
}
float FoV = 60.0f / 2; // 60 / 2 Deg on Y-axis
float tanFoV = tan(FoV * (PI / 180));
// Fix the multiplier based on the aspect ratio, if needed (aspect ratio only if width is larger)
float multiplier;
if (wFoV / hFoV > aspect)
{
// Width is longer then the screen, use it
multiplier = wFoV / aspect;
}else{
// height is longer then the screen
multiplier = hFoV;
}
// distance from the actor
eye -= (dir * (multiplier * NxMath::max(1.1f, buffer) / tanFoV));
// translate the camera down by the slideshow overlay height if we're in slideshow mode
if(isSlideshowModeActive()) {
//The greater of zoomHeight and zoomWidth will in effect represent the height of the screen in bumptop world units
//if we multiply this value by the ratio of the overlay to the screen, we get the real-world size of the overlay,
//and we can offset the camera accordingly
float slideShowOverlayToScreenRatio = slideShowControls.getHeight()/height;
float offsetDistance = zoomHeight * slideShowOverlayToScreenRatio;
eye -= (up * offsetDistance);
}
#ifndef DXRENDER
_isglDataDirty = true;
#endif
}
Bounds Camera::getActorsBounds( const vector<BumpObject *>& objects, bool flatten/*=False*/ )
{
Bounds bounds, aabb;
Vec3 center, extents;
float maxY = 0.0f;
for (uint i = 0; i < objects.size(); i++)
{
if (objects[i]->isBumpObjectType(BumpPile) ||
objects[i]->isBumpObjectType(BumpActor))
{
if (!scnManager->containsObject(objects[i]))
continue;
// determine the max bounds of the
if (objects[i]->isBumpObjectType(BumpPile))
{
Pile * p = (Pile *) objects[i];
if (p->getNumItems() > 0)
{
Bounds pileBounds = p->getPileBounds();
Vec3 pileCenter, pileExtents;
pileBounds.getCenter(pileCenter);
pileBounds.getExtents(pileExtents);
if (p->getPileState() == Grid)
maxY = NxMath::max(pileCenter.y, maxY);
else
maxY = NxMath::max(pileExtents.y, maxY);
}
}
else
{
maxY = NxMath::max(objects[i]->getDims().z, maxY);
}
aabb = objects[i]->getBoundingBox();
if (!objects[i]->isPinned() && flatten)
{
// flatten the bounds?
aabb.getCenter(center);
aabb.getExtents(extents);
if (!((objects[i]->isBumpObjectType(BumpPile)) &&
(((Pile *) objects[i])->getPileState() == Grid)))
{
center.y = 0;
}
extents.y = 0;
aabb.setCenterExtents(center, extents);
}
bounds.combine(aabb);
}
}
if (flatten)
{
bounds.getCenter(center);
bounds.getExtents(extents);
center.y = extents.y = maxY;
bounds.setCenterExtents(center, extents);
}
return bounds;
}
void Camera::updateWatchedActorVisibleBounds()
{
// reset the visible bounds
visibleBounds.setEmpty();
// get the view corners in world space (v/w are near/far clipping pane points)
//
// 0-------1 <----- v[] and w[] index
// | |
// 3-------2
Vec3 v[4], w[4], pt[4], dir;
window2world(0, 0, v[0], w[0]);
window2world(winOS->GetWindowWidth(), 0, v[1], w[1]);
window2world(winOS->GetWindowWidth(), winOS->GetWindowHeight(), v[2], w[2]);
window2world(0, winOS->GetWindowHeight(), v[3], w[3]);
// get the floor bounds of the corner points
float dist;
Ray r;
NxPlane floor = NxPlane(Vec3(0,0,0), Vec3(0,1,0));
for (int i = 0; i < 4; i++)
{
// Project this ray to the floor
dir = w[i]-v[i];
dir.normalize();
r = Ray(v[i], dir);
NxRayPlaneIntersect(r, floor, dist, pt[i]);
}
// when in bounded mode, use the bottom points X as the top points X
if (!GLOBAL(isInInfiniteDesktopMode))
{
pt[0].x = pt[3].x;
pt[1].x = pt[2].x;
}
for (int i = 0; i < 4; ++i)
{
// add the point to the bounds
pt[i].y = 0;
visibleBounds.include(pt[i]);
}
}
ZoomOutControl* Camera::getZoomOutControl()
{
return &zoomOutControl;
}
RestoreOriginalPhotoControl* Camera::getRestoreOriginalPhotoControl()
{
return &restoreOriginalPhotoControl;
}
void Camera::pointCameraTo(Vec3 pt)
{
pointCameraTo(pt, true);
}
// Reorient the camera to point to a location the user clicked
void Camera::pointCameraTo(Vec3 pt, bool executeWindowToWorld)
{
if (!GLOBAL(isInInfiniteDesktopMode))// || isCameraFreeForm() || GLOBAL(settings).enableDebugKeys)
{
Vec3 pointOnPlane = pt;
// Determine what point in the bumptop desktop the mouse has clicked
if (executeWindowToWorld)
{
Vec3 closePoint, farPoint, dir;
window2world(pt.x, pt.y, closePoint, farPoint);
dir = farPoint - closePoint;
dir.normalize();
Ray theRay = Ray(closePoint, dir);
// Get unbounded box and planes making up the desktop
tuple <int, NxReal, Vec3, NxPlane> t = RayIntersectDesktop(theRay);
pointOnPlane = t.get<2>();
}
// Make sure the point is inside the bumptop desktop
Box desktopBox = GetDesktopBox(0);
if (desktopBox.GetExtents().y + desktopBox.GetCenter().y < pointOnPlane.y)
{
return;
}
// Determine new camera eye
Vec3 newEye = getEye();
if (getEye().distanceSquared(getDefaultEye()) < 0.005)
newEye.y = GLOBAL(WallHeight) * 0.8;
//Determine the new direction based on the point on the plane
Vec3 newDir;
newDir = pointOnPlane - newEye;
newDir.normalize();
//Determine new up vector
Vec3 newUp;
newUp.cross(newDir, Vec3(0,1,0));
newUp.cross(newUp, newDir);
// Animate to new direction
animateTo(newEye, newDir, newUp);
storeCameraPosition(newEye, newDir, newUp);
}
else
{
}
}
// This method is used to load a camera preset.
// It is called when bumptop is initialized or whenever the
// bumptop settings are modified
void Camera::loadCameraFromPreset(QString cameraPreset)
{
// get the new preset
PredefinedCameraViews newCameraPreset = Camera::DefaultView;
if (cameraPreset.startsWith("oh"))
newCameraPreset = Camera::TopDownView;
else if (cameraPreset.startsWith(QT_NT("brc")))
newCameraPreset = Camera::BottomRightCornerView;
// don't do anything if the walls haven't been created yet?
vector<NxActorWrapper*> walls = GLOBAL(Walls);
assert(!walls.empty());
if (walls.empty())
return;
// if we are zoomed in on any object, we should zoom back out first
popAllWatchActors();
WebActor::zoomOutFocusedWebActor();
// apply the camera change
setCurrentCameraView(newCameraPreset);
}
void Camera::onAnimTick()
{
// Get the next Step
if (!pathEye.empty())
{
setEye(pathEye.front());
pathEye.pop_front();
}
if (!pathDir.empty())
{
setDir(pathDir.front());
pathDir.pop_front();
}
if (!pathUp.empty())
{
setUp(pathUp.front());
pathUp.pop_front();
}
// Force the camera to be upright, always
if (up.y < 0.0) up.y = 0.0;
// Calculate the Right vector
right.cross(up, dir);
}
void Camera::onAnimFinished()
{
#ifndef DXRENDER
// NOTE: we update the OGL matrices so that picking works and everything
// after the camera view has moved
_isglDataDirty = true;
readOGLMatrices();
#endif
// restore the visibility of the previously hidden nameables
if (!hasWatchedActorHighlighted() &&
!(getZoomedObjects().size() == 1 && getZoomedObjects().front()->getObjectType() == ObjectType(BumpActor,Webpage)))
restorePreviousVisibleNameables(false);
animationFinishCallback();
}
void Camera::killAnimation()
{
pathEye.clear();
pathDir.clear();
pathUp.clear();
// Remove ourself from the animation queue
animManager->removeAnimation(this);
setAnimationState(NoAnim);
}
void Camera::finishAnimation()
{
// Jump to the end of each animation
if (!pathEye.empty()) setEye(pathEye.back());
if (!pathDir.empty()) setDir(pathDir.back());
if (!pathUp.empty()) setUp(pathUp.back());
pathEye.clear();
pathDir.clear();
pathUp.clear();
animationFinishCallback();
}
void Camera::revertAnimation()
{
// Jump to the beginning of each animation
if (!pathEye.empty()) setEye(pathEye.front());
if (!pathDir.empty()) setDir(pathDir.front());
if (!pathUp.empty()) setUp(pathUp.front());
killAnimation();
}
bool Camera::isAnimating( uint animType /*= SizeAnim | AlphaAnim | PoseAnim*/ )
{
bool animRunning = false;
// Check the different types of anims
if (animType & PoseAnim && (!pathEye.empty() || !pathDir.empty() || !pathUp.empty())) animRunning = true;
// Check animation Paths
return animRunning;
}
#ifndef DXRENDER
void Camera::readOGLMatrices()
{
// We shouldn't have to call switchToPerspective here, but
// it's a workaround so we have the most up-to-date view matrix
switchToPerspective();
glGetDoublev (GL_PROJECTION_MATRIX, _glProjMatrix);
glGetDoublev (GL_MODELVIEW_MATRIX, _glMVMatrix);
_glViewport[2] = winOS->GetWindowWidth();
_glViewport[3] = winOS->GetWindowHeight();
_isglDataDirty = false;
}
GLdouble * Camera::glModelViewMatrix() const
{
return _glMVMatrix;
}
GLdouble * Camera::glProjectionMatrix() const
{
return _glProjMatrix;
}
GLint * Camera::glViewport() const
{
return _glViewport;
}
void Camera::markglDataDirty()
{
_isglDataDirty = true;
}
#endif
void Camera::setOnHighlightNextWatchedActorHandler( boost::function<void(bool)> onHighlightNextWatchedActorHandler )
{
_onHighlightNextWatchedActorHandler = onHighlightNextWatchedActorHandler;
}
void Camera::setOnPopWatchActorsHandler( boost::function<void()> onPopWatchActorsHandler )
{
_onPopWatchActorsHandler = onPopWatchActorsHandler;
}
// Call with temporary to temporarily hide or restore texts according to last
// call of storePreviousVisibleNameables without temporary flag
void Camera::restorePreviousVisibleNameables(bool skipAnimation, bool temporary)
{
set<BumpObject *>::iterator iter = _prevVisibleNameables.begin();
while (iter != _prevVisibleNameables.end())
{
if (scnManager->containsObject(*iter))
{
if (skipAnimation)
(*iter)->showText(true);
else
(*iter)->showTextAnimated(25);
}
iter++;
}
if (!temporary)
_prevVisibleNameables.clear();
}
void Camera::storePreviousVisibleNameables(bool skipAnimation, bool temporary)
{
if (temporary)
{
// hide text for items that were previously hidden before restorePreviousVisibleNameables called with temporary
set<BumpObject *>::iterator iter = _prevVisibleNameables.begin();
while (iter != _prevVisibleNameables.end())
{
if (scnManager->containsObject(*iter) && !(*iter)->isTextHidden())
(*iter)->hideText(skipAnimation);
iter++;
}
}
else
{
// restore the existing nameables first just in case
restorePreviousVisibleNameables(true);
assert(_prevVisibleNameables.empty());
vector<BumpObject *> objs = scnManager->getBumpObjects();
for (int i = 0; i < objs.size(); ++i)
{
if (!objs[i]->isTextHidden())
{
_prevVisibleNameables.insert(objs[i]);
objs[i]->hideText(skipAnimation);
}
}
}
}
CornerInfoControl * Camera::getCornerInfoControl()
{
return &cornerInfoControl;
}
QList<BumpObject*>& Camera::getZoomedObjects()
{
return zoomedObjects;
}
bool Camera::serializeToPb(PbCamera * pbCamera)
{
assert(pbCamera);
toPbVec3(getEye(), pbCamera->mutable_eye());
toPbVec3(getDir(), pbCamera->mutable_dir());
toPbVec3(getUp(), pbCamera->mutable_up());
return true;
}
bool Camera::deserializeFromPb(const PbCamera * pbCamera)
{
assert(pbCamera);
if (pbCamera->has_eye()) {
savedEye = fromPbVec3(pbCamera->eye());
}
if (pbCamera->has_dir()){
savedDir = fromPbVec3(pbCamera->dir());
}
if (pbCamera->has_up()) {
savedUp = fromPbVec3(pbCamera->up());
}
return true;
} | 28.441367 | 176 | 0.700634 |
4404caf10481aafdc607b1ccbd70358f2688c0a2 | 15,851 | cc | C++ | GeneratorInterface/SherpaInterface/src/SherpackUtilities.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | GeneratorInterface/SherpaInterface/src/SherpackUtilities.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | GeneratorInterface/SherpaInterface/src/SherpackUtilities.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "GeneratorInterface/SherpaInterface/interface/SherpackUtilities.h"
#include <unistd.h>
#include <cstdlib>
namespace spu {
// functions for inflating (and deflating)
//~ /* Compress from file source to file dest until EOF on source.
//~ def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
//~ allocated for processing, Z_STREAM_ERROR if an invalid compression
//~ level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
//~ version of the library linked do not match, or Z_ERRNO if there is
//~ an error reading or writing the files. */
int def(FILE *source, FILE *dest, int level) {
int ret, flush;
unsigned have;
z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
/* allocate deflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = deflateInit(&strm, level);
if (ret != Z_OK)
return ret;
/* compress until end of file */
do {
strm.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
}
flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = in;
/* run deflate() on input until output buffer not full, finish
compression if all of source has been read in */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = deflate(&strm, flush); /* no bad return value */
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
have = CHUNK - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
}
} while (strm.avail_out == 0);
assert(strm.avail_in == 0); /* all input will be used */
/* done when last data in file processed */
} while (flush != Z_FINISH);
assert(ret == Z_STREAM_END); /* stream will be complete */
/* clean up and return */
(void)deflateEnd(&strm);
return Z_OK;
}
/* Decompress from file source to file dest until stream ends or EOF.
inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
allocated for processing, Z_DATA_ERROR if the deflate data is
invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
the version of the library linked do not match, or Z_ERRNO if there
is an error reading or writing the files. */
int inf(FILE *source, FILE *dest) {
int ret;
unsigned have;
z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
/* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
//~ ret = inflateInit(&strm,15);
ret = inflateInit2(&strm, (16 + MAX_WBITS));
if (ret != Z_OK)
return ret;
/* decompress until deflate stream ends or end of file */
do {
strm.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source)) {
(void)inflateEnd(&strm);
return Z_ERRNO;
}
if (strm.avail_in == 0)
break;
strm.next_in = in;
/* run inflate() on input until output buffer not full */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = inflate(&strm, Z_NO_FLUSH);
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
switch (ret) {
case Z_NEED_DICT:
ret = Z_DATA_ERROR;
[[fallthrough]];
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
return ret;
}
have = CHUNK - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
(void)inflateEnd(&strm);
return Z_ERRNO;
}
} while (strm.avail_out == 0);
/* done when inflate() says it's done */
} while (ret != Z_STREAM_END);
/* clean up and return */
(void)inflateEnd(&strm);
return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}
/* report a zlib or i/o error */
void zerr(int ret) {
fputs("zpipe: ", stderr);
switch (ret) {
case Z_ERRNO:
if (ferror(stdin))
fputs("error reading stdin\n", stderr);
if (ferror(stdout))
fputs("error writing stdout\n", stderr);
break;
case Z_STREAM_ERROR:
fputs("invalid compression level\n", stderr);
break;
case Z_DATA_ERROR:
fputs("invalid or incomplete deflate data\n", stderr);
break;
case Z_MEM_ERROR:
fputs("out of memory\n", stderr);
break;
case Z_VERSION_ERROR:
fputs("zlib version mismatch!\n", stderr);
}
}
/* compress or decompress from stdin to stdout */
int Unzip(std::string infile, std::string outfile) {
/////////////////////////////////////////////
/////////////// BUG FIX FOR MPI /////////////
/////////////////////////////////////////////
const char *tmpdir = std::getenv("TMPDIR");
if (tmpdir && (strlen(tmpdir) > 50)) {
setenv("TMPDIR", "/tmp", true);
}
/////////////////////////////////////////////
/////////////////////////////////////////////
/////////////////////////////////////////////
int ret;
FILE *in = fopen(infile.c_str(), "r");
if (!in)
return -1;
FILE *out = fopen(outfile.c_str(), "w");
if (!out)
return -2;
/* avoid end-of-line conversions */
SET_BINARY_MODE(in);
SET_BINARY_MODE(out);
ret = inf(in, out);
if (ret != Z_OK)
zerr(ret);
fclose(in);
fclose(out);
return ret;
}
// functions for untaring Sherpacks
/* Parse an octal number, ignoring leading and trailing nonsense. */
int parseoct(const char *p, size_t n) {
int i = 0;
while (*p < '0' || *p > '7') {
++p;
--n;
}
while (*p >= '0' && *p <= '7' && n > 0) {
i *= 8;
i += *p - '0';
++p;
--n;
}
return (i);
}
/* Returns true if this is 512 zero bytes. */
int is_end_of_archive(const char *p) {
int n;
for (n = 511; n >= 0; --n)
if (p[n] != '\0')
return (0);
return (1);
}
/* Create a directory, including parent directories as necessary. */
void create_dir(char *pathname, int mode) {
char *p;
int r;
/* Strip trailing '/' */
if (pathname[strlen(pathname) - 1] == '/')
pathname[strlen(pathname) - 1] = '\0';
/* Try creating the directory. */
r = mkdir(pathname, mode);
if (r != 0) {
/* On failure, try creating parent directory. */
p = strrchr(pathname, '/');
if (p != nullptr) {
*p = '\0';
create_dir(pathname, 0755);
*p = '/';
r = mkdir(pathname, mode);
}
}
if (r != 0)
fprintf(stderr, "Could not create directory %s\n", pathname);
}
/* Create a file, including parent directory as necessary. */
FILE *create_file(char *pathname, int mode) {
FILE *f;
f = fopen(pathname, "w+");
if (f == nullptr) {
/* Try creating parent dir and then creating file. */
char *p = strrchr(pathname, '/');
if (p != nullptr) {
*p = '\0';
create_dir(pathname, 0755);
*p = '/';
f = fopen(pathname, "w+");
}
}
return (f);
}
/* Verify the tar checksum. */
int verify_checksum(const char *p) {
int n, u = 0;
for (n = 0; n < 512; ++n) {
if (n < 148 || n > 155)
/* Standard tar checksum adds unsigned bytes. */
u += ((unsigned char *)p)[n];
else
u += 0x20;
}
return (u == parseoct(p + 148, 8));
}
/* Extract a tar archive. */
void Untar(FILE *a, const char *path) {
bool longpathname = false;
bool longlinkname = false;
char newlongpathname[512];
char newlonglinkname[512];
char buff[512];
FILE *f = nullptr;
size_t bytes_read;
int filesize;
printf("Extracting from %s\n", path);
for (;;) {
bytes_read = fread(buff, 1, 512, a);
if (bytes_read < 512) {
fprintf(stderr, "Short read on %s: expected 512, got %d\n", path, (int)bytes_read);
return;
}
if (is_end_of_archive(buff)) {
printf("End of %s\n", path);
return;
}
if (!verify_checksum(buff)) {
fprintf(stderr, "Checksum failure\n");
return;
}
filesize = parseoct(buff + 124, 12);
// printf("%c %d\n",buff[156],filesize);
switch (buff[156]) {
case '1':
printf(" Ignoring hardlink %s\n", buff);
break;
case '2':
if (longpathname && longlinkname) {
longlinkname = false;
longpathname = false;
printf(" Extracting symlink %s\n", newlongpathname);
symlink(newlonglinkname, newlongpathname);
} else if (longpathname) {
longpathname = false;
printf(" Extracting symlink %s\n", newlongpathname);
symlink(buff + 157, newlongpathname);
} else if (longlinkname) {
longlinkname = false;
printf(" Extracting symlink %s\n", buff);
symlink(newlonglinkname, buff);
} else {
printf(" Extracting symlink %s\n", buff);
symlink(buff + 157, buff);
}
break;
case '3':
printf(" Ignoring character device %s\n", buff);
break;
case '4':
printf(" Ignoring block device %s\n", buff);
break;
case '5':
if (!longpathname) {
int endposition = -1;
for (int k = 99; k >= 0; k--) {
if (buff[k] == '\0')
endposition = k;
}
if (endposition == -1) {
//~ printf("OLDNAME : %s\n",buff);
longpathname = true;
for (int k = 0; k < 100; k++) {
newlongpathname[k] = buff[k];
}
newlongpathname[100] = '\0';
//~ printf("NEWNAME : %s\n",newlongpathname);
}
}
if (longpathname) {
printf(" Extracting dir %s\n", newlongpathname);
create_dir(newlongpathname, parseoct(buff + 100, 8));
longpathname = false;
} else {
printf(" Extracting dir %s\n", buff);
create_dir(buff, parseoct(buff + 100, 8));
}
//~ printf(" Extracting dir %s\n", buff);
//~ create_dir(buff, parseoct(buff + 100, 8));
filesize = 0;
break;
case '6':
printf(" Ignoring FIFO %s\n", buff);
break;
case 'L':
longpathname = true;
//~ printf(" Long Filename found 0 %s\n", buff);
//~ printf(" Long Filename found 100 %s\n", buff+100);
//~ printf(" Long Filename found 108 %s\n", buff+108);
//~ printf(" Long Filename found 116 %s\n", buff+116);
//~ printf(" Long Filename found 124 %s\n", buff+124);
//~ printf(" Long Filename found 136 %s\n", buff+136);
//~ printf(" Long Filename found 148 %s\n", buff+148);
//~ printf(" Long Filename found 156 %s\n", buff+156);
//~ printf(" Long Filename found 157 %s\n", buff+157);
//~ printf(" Long Filename found 158 %s\n", buff+158);
//~ printf(" Long Filename found 159 %s\n", buff+159);
//~ printf(" Long Filename found 257 %s\n", buff+257);
//~ printf(" Long Filename found 263 %s\n", buff+263);
//~ printf(" Long Filename found 265 %s\n", buff+265);
//~ printf(" Long Filename found 297 %s\n", buff+297);
//~ printf(" Long Filename found 329 %s\n", buff+329);
//~ printf(" Long Filename found 337 %s\n", buff+337);
//~ printf(" Long Filename found 345 %s\n", buff+345);
//~ printf(" Long Filename found 346 %s\n", buff+346);
//~ printf(" Long Filename found 347 %s\n", buff+347);
break;
case 'K':
longlinkname = true;
break;
default:
if (!longpathname) {
int endposition = -1;
for (int k = 99; k >= 0; k--) {
if (buff[k] == '\0')
endposition = k;
}
if (endposition == -1) {
//~ printf("OLDNAME : %s\n",buff);
longpathname = true;
for (int k = 0; k < 100; k++) {
newlongpathname[k] = buff[k];
}
newlongpathname[100] = '\0';
//~ printf("NEWNAME : %s\n",newlongpathname);
}
}
if (longpathname) {
printf(" Extracting file %s\n", newlongpathname);
f = create_file(newlongpathname, parseoct(buff + 100, 8));
longpathname = false;
} else {
printf(" Extracting file %s\n", buff);
f = create_file(buff, parseoct(buff + 100, 8));
}
break;
}
if (longlinkname || longpathname) {
if (buff[156] == 'K') {
for (int ll = 0; ll < 512; ll++) {
printf("%c", buff[ll]);
}
printf("\n");
bytes_read = fread(buff, 1, 512, a);
for (int ll = 0; ll < 512; ll++) {
printf("%c", buff[ll]);
}
printf("\n");
for (int k = 0; k < filesize; k++) {
newlonglinkname[k] = buff[k];
}
newlonglinkname[filesize] = '\0';
for (int k = filesize + 1; k < 512; k++) {
newlonglinkname[k] = '0';
}
//~ printf("NEW LinkNAME: %s\n",newlonglinkname);
} else if (buff[156] == 'L') {
bytes_read = fread(buff, 1, 512, a);
for (int k = 0; k < filesize; k++) {
newlongpathname[k] = buff[k];
}
newlongpathname[filesize] = '\0';
for (int k = filesize + 1; k < 512; k++) {
newlongpathname[k] = '0';
}
//~ printf("NEW FILENAME: %s\n",newlongpathname);
}
}
//~
//~ if (longpathname) {
//~ bytes_read = fread(buff, 1, 512, a);
//~ for (int k=0; k<filesize; k++){
//~ newlongpathname[k]=buff[k];
//~ }
//~ newlongpathname[filesize]='\0';
//~ for (int k=filesize+1; k<512; k++){
//~ newlongpathname[k]='0';
//~ }
//~ printf("NEW FILENAME: %s\n",newlongpathname);
//~
//~ }
//~ else if (!longpathname && !longlinkname) {
if (!longpathname && !longlinkname) {
while (filesize > 0) {
bytes_read = fread(buff, 1, 512, a);
if (bytes_read < 512) {
fprintf(stderr, "Short read on %s: Expected 512, got %d\n", path, (int)bytes_read);
return;
}
if (filesize < 512)
bytes_read = filesize;
if (f != nullptr) {
if (fwrite(buff, 1, bytes_read, f) != bytes_read) {
fprintf(stderr, "Failed write\n");
fclose(f);
f = nullptr;
}
}
filesize -= bytes_read;
}
if (f != nullptr) {
fclose(f);
f = nullptr;
}
}
}
}
// function for calculating the MD5 checksum of a file
void md5_File(std::string filename, char *result) {
char buffer[4096];
MD5_CTX md5;
MD5_Init(&md5);
//Open File
int fd = open(filename.c_str(), O_RDONLY);
int nb_read;
while ((nb_read = read(fd, buffer, 4096 - 1))) {
MD5_Update(&md5, buffer, nb_read);
memset(buffer, 0, 4096);
}
unsigned char tmp[MD5_DIGEST_LENGTH];
MD5_Final(tmp, &md5);
//Convert the result
for (int k = 0; k < MD5_DIGEST_LENGTH; ++k) {
sprintf(result + k * 2, "%02x", tmp[k]);
}
}
} // End namespace spu
| 31.202756 | 95 | 0.507854 |
4405819af9694991e962881bc68366cfcf3778a2 | 116 | cpp | C++ | src/virtual_call_in_destructor_link.cpp | geoffviola/undefined_behavior_study | c405fa766284473c5b3c9ce415c18bcc2bba227c | [
"Apache-2.0"
] | 9 | 2017-03-18T09:15:36.000Z | 2020-05-24T18:00:37.000Z | src/virtual_call_in_destructor_link.cpp | geoffviola/undefined_behavior_study | c405fa766284473c5b3c9ce415c18bcc2bba227c | [
"Apache-2.0"
] | 1 | 2018-06-19T19:36:19.000Z | 2018-10-15T16:49:29.000Z | src/virtual_call_in_destructor_link.cpp | geoffviola/undefined_behavior_study | c405fa766284473c5b3c9ce415c18bcc2bba227c | [
"Apache-2.0"
] | 3 | 2017-03-18T01:44:49.000Z | 2022-01-04T03:22:02.000Z | #include <cstdlib>
#include "virtual_call_in_destructor_lib.hpp"
int main() {
Child c;
return EXIT_SUCCESS;
}
| 12.888889 | 45 | 0.732759 |
4406e1f01d45dd7a79d75d62ab3b011c0e304b61 | 2,594 | cpp | C++ | src/context.cpp | vish3vs/SAPP | 0e6da99bc93920237c65c250848f1f46aef16647 | [
"MIT"
] | null | null | null | src/context.cpp | vish3vs/SAPP | 0e6da99bc93920237c65c250848f1f46aef16647 | [
"MIT"
] | null | null | null | src/context.cpp | vish3vs/SAPP | 0e6da99bc93920237c65c250848f1f46aef16647 | [
"MIT"
] | null | null | null | // Copyright (c) 2020 The SAPP developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "context.h"
#include "timedata.h"
#include "util.h"
#include <memory>
#include <exception>
using namespace std;
static unique_ptr<CContext> context_;
void CreateContext()
{
if (context_)
throw runtime_error("context has already been initialized, revise your code");
else
context_.reset(new CContext);
}
void ReleaseContext()
{
context_.reset();
}
CContext& GetContext()
{
if (!context_)
throw runtime_error("context is not initialized");
else
return *context_;
}
CContext::CContext()
{
banAddrConsensus_.insert("Sd2xcwvvtRH8P8sLemSiPjadTfBd9myPbW");
banAddrConsensus_.insert("STFSLXfG31Xr8Symk78aG6jCu391yp8kWD");
banAddrConsensus_.insert("SbPoXEFrMJwes3mysfgGzP2mAtw1SmrC7H");
banAddrConsensus_.insert("ScM5iV4aJEwMipWGHHcS8E1qLsarwk6DuK");
banAddrConsensus_.insert("Sfv6SUgcSgmmpwp3UypfYgnK1x97rfC9Dj");
banAddrConsensus_.insert("SY6UdUKC8yxci8vXgvQYMgeUNRDvymEhM3");
banAddrConsensus_.insert("SdaX6DR3gdpakcFrKJfCDB6GJjC4J9XJ8M");
banAddrConsensus_.insert("Sh412EAoGLvn1WnTUCZbHiUGCk2dzmdQoA");
banAddrConsensus_.insert("ST74xpmzemL4ELiBpyDmirzgahujSUiYmM");
banAddrConsensus_.insert("SaWmWbLSghhn8JAE8JQfdLQy9cvf1ADKUD");
banAddrConsensus_.insert("Sic7sZBNkijna4zNLSVgTBkfr2ebP6c9wk");
banAddrConsensus_.insert("Sh8N9R2Li5Wm5B7g3xxfEotp9Vpp38baJM");
banAddrConsensus_.insert("SVAjKY5p9NPSNwG7PLK3VzeXUdJjm2W7CY");
}
CContext::~CContext() {}
bool CContext::IsUpdateAvailable() const
{
return bUpdateAvailable_;
}
void CContext::SetUpdateAvailable(bool available)
{
bUpdateAvailable_ = available;
}
void CContext::AddAddressToBan(
const std::vector<std::string>& mempool,
const std::vector<std::string>& consensus)
{
banAddrMempool_.insert(mempool.begin(), mempool.end());
banAddrConsensus_.insert(consensus.begin(), consensus.end());
}
bool CContext::MempoolBanActive() const
{
return !banAddrMempool_.empty() || !banAddrConsensus_.empty();
}
bool CContext::MempoolBanActive(const std::string& addr) const
{
return banAddrConsensus_.find(addr) != banAddrConsensus_.end() ||
banAddrMempool_.find(addr) != banAddrMempool_.end();
}
bool CContext::ConsensusBanActive() const
{
return !banAddrConsensus_.empty();
}
bool CContext::ConsensusBanActive(const std::string& addr) const
{
return banAddrConsensus_.find(addr) != banAddrConsensus_.end();
} | 27.595745 | 86 | 0.759059 |
440766b9513511298f9600103484d10624b58b09 | 2,063 | cpp | C++ | library/src/main/jni/_onload.cpp | badpx/IndexBitmap | d940d56a31ce7f0ee717d12132c4c51c2fd6520b | [
"Apache-2.0"
] | 11 | 2015-08-24T13:29:10.000Z | 2020-07-18T08:10:55.000Z | library/src/main/jni/_onload.cpp | badpx/IndexBitmap | d940d56a31ce7f0ee717d12132c4c51c2fd6520b | [
"Apache-2.0"
] | 3 | 2016-03-28T10:23:15.000Z | 2018-11-02T02:13:00.000Z | library/src/main/jni/_onload.cpp | badpx/IndexBitmap | d940d56a31ce7f0ee717d12132c4c51c2fd6520b | [
"Apache-2.0"
] | 4 | 2016-01-09T10:42:03.000Z | 2019-05-02T03:04:37.000Z | #include <android/log.h>
#include "baseutils.h"
#include "_onload.h"
#include "skbitmap_helper.h"
#define LOCAL_DEBUG 0
static JNINativeMethod methods[] = {
{ "nativeInit", "(Landroid/graphics/Bitmap;[I)Z", (void*)Init },
{ "nativeGetBytesPerPixel", "(Landroid/graphics/Bitmap;)I", (void*)GetBytesPerPixel },
{ "nativeGetPalette", "(Landroid/graphics/Bitmap;[I)I", (void*)GetPalette },
{ "nativeChangePalette", "(Landroid/graphics/Bitmap;[I)I", (void*)ChangePalette },
{ "nativeIndex8FakeToAlpha8", "(Landroid/graphics/Bitmap;Z)I", (void*)Index8FakeToAlpha8 },
{ "nativeGetConfig", "(Landroid/graphics/Bitmap;)I", (void*)GetConfig },
{ "nativeSetConfig", "(Landroid/graphics/Bitmap;I)I", (void*)SetConfig },
{ "nativeGetIndex8Config", "()I", (void*)GetIndex8Config },
};
jint registerNativeMethods(JNIEnv* env, const char *class_name, JNINativeMethod *methods, int num_methods) {
int result = 0;
jclass clazz = env->FindClass(class_name);
if (LIKELY(clazz)) {
result = env->RegisterNatives(clazz, methods, num_methods);
if (UNLIKELY(result < 0)) {
LOGE("registerNativeMethods failed(class=%s)", class_name);
}
} else {
LOGE("registerNativeMethods: class'%s' not found", class_name);
}
return result;
}
static int register_native_methods(JNIEnv *env) {
LOGV("register native method:");
if (registerNativeMethods(env,
PACKAGE_NAME,
methods, NUM_ARRAY_ELEMENTS(methods)) < 0) {
return JNI_ERR;
}
return JNI_OK;
}
jint JNI_OnLoad(JavaVM *vm, void *) {
#if LOCAL_DEBUG
LOGI("JNI_OnLoad");
#endif
JNIEnv *env;
if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) {
return JNI_ERR;
}
if (!setupLibrary(env)) {
#if LOCAL_DEBUG
LOGF("setup library failed!");
#endif
return JNI_ERR;
}
// register native methods
if (register_native_methods(env) != JNI_OK) {
return JNI_ERR;
}
setVM(vm);
#if LOCAL_DEBUG
LOGI("JNI_OnLoad:finshed:result=%d", result);
#endif
return JNI_VERSION_1_6;
}
| 28.652778 | 108 | 0.672807 |
44076f00c9acc115ab70c1121a76857ad79248c9 | 438 | hpp | C++ | i23dSFM/matching/matcher_type.hpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | null | null | null | i23dSFM/matching/matcher_type.hpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | null | null | null | i23dSFM/matching/matcher_type.hpp | zyxrrr/GraphSfM | 1af22ec17950ffc8a5c737a6a46f4465c40aa470 | [
"BSD-3-Clause"
] | 1 | 2019-02-18T09:49:32.000Z | 2019-02-18T09:49:32.000Z |
// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#pragma once
namespace i23dSFM{
namespace matching{
enum EMatcherType
{
BRUTE_FORCE_L2,
ANN_L2,
CASCADE_HASHING_L2,
BRUTE_FORCE_HAMMING
};
} // namespace matching
} // namespace i23dSFM
| 19.909091 | 70 | 0.730594 |
44091448f0282afc5ca5f79268da2865dfb7cf86 | 2,683 | cpp | C++ | tests/IDL_Test/Double_Inherited_Component/ComponentC_exec.cpp | qinwang13/CIAO | e69add1b5da8e9602bcc85d581ecbf1bd41c49a3 | [
"DOC"
] | 10 | 2016-07-20T00:55:50.000Z | 2020-10-04T19:07:10.000Z | tests/IDL_Test/Double_Inherited_Component/ComponentC_exec.cpp | qinwang13/CIAO | e69add1b5da8e9602bcc85d581ecbf1bd41c49a3 | [
"DOC"
] | 13 | 2016-09-27T14:08:27.000Z | 2020-11-11T10:45:56.000Z | tests/IDL_Test/Double_Inherited_Component/ComponentC_exec.cpp | qinwang13/CIAO | e69add1b5da8e9602bcc85d581ecbf1bd41c49a3 | [
"DOC"
] | 12 | 2016-04-20T09:57:02.000Z | 2021-12-24T17:23:45.000Z | // -*- C++ -*-
#include "ComponentC_exec.h"
#include "ace/Log_Msg.h"
namespace CIAO_connector_test_C_Impl
{
//============================================================
// Pulse generator
//============================================================
ComponentC_exec_i::ComponentC_exec_i (void)
: topic_name_c_ (""),
topic_name_b_ (""),
topic_name_a_ (""),
topic_name_c_has_been_set_ (false),
topic_name_b_has_been_set_ (false),
topic_name_a_has_been_set_ (false)
{
}
ComponentC_exec_i::~ComponentC_exec_i (void)
{
}
// Port operations.
void
ComponentC_exec_i::topic_name_c (const char * topic_name)
{
this->topic_name_c_ = topic_name;
this->topic_name_c_has_been_set_ = true;
}
char *
ComponentC_exec_i::topic_name_c (void)
{
return CORBA::string_dup (this->topic_name_c_.in ());
}
void
ComponentC_exec_i::topic_name_b (const char * topic_name)
{
this->topic_name_b_ = topic_name;
this->topic_name_b_has_been_set_ = true;
}
char *
ComponentC_exec_i::topic_name_b (void)
{
return CORBA::string_dup (this->topic_name_b_.in ());
}
void
ComponentC_exec_i::topic_name_a (const char * topic_name)
{
this->topic_name_a_ = topic_name;
this->topic_name_a_has_been_set_ = true;
}
char *
ComponentC_exec_i::topic_name_a (void)
{
return CORBA::string_dup (this->topic_name_a_.in ());
}
// Operations from Components::SessionComponent.
void
ComponentC_exec_i::set_session_context (
::Components::SessionContext_ptr ctx)
{
this->context_ =
::connector_test::CCM_C_Context::_narrow (ctx);
if ( ::CORBA::is_nil (this->context_.in ()))
{
throw ::CORBA::INTERNAL ();
}
}
void
ComponentC_exec_i::configuration_complete (void)
{
}
void
ComponentC_exec_i::ccm_activate (void)
{
}
void
ComponentC_exec_i::ccm_passivate (void)
{
}
void
ComponentC_exec_i::ccm_remove (void)
{
if (!this->topic_name_c_has_been_set_)
ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR : Topic name C has not been set\n")));
if (!this->topic_name_b_has_been_set_)
ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR : Topic name B has not been set\n")));
if (!this->topic_name_a_has_been_set_)
ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR : Topic name A has not been set\n")));
}
extern "C" INHERITED_COMPONENTS_EXEC_Export ::Components::EnterpriseComponent_ptr
create_ComponentC_Impl (void)
{
::Components::EnterpriseComponent_ptr retval =
::Components::EnterpriseComponent::_nil ();
ACE_NEW_NORETURN (
retval,
ComponentC_exec_i );
return retval;
}
}
| 23.330435 | 83 | 0.642564 |
44092bd71c2f0ce667e15f64d5aa0e72fa9551b3 | 1,654 | cc | C++ | testPrograms/tPartialIO.cc | yahoo/Pluton | 82bbab17c0013d87063b398ec777d5977f353d0a | [
"MIT"
] | 8 | 2015-05-22T21:27:17.000Z | 2017-03-19T06:07:41.000Z | testPrograms/tPartialIO.cc | YahooArchive/Pluton | 82bbab17c0013d87063b398ec777d5977f353d0a | [
"MIT"
] | null | null | null | testPrograms/tPartialIO.cc | YahooArchive/Pluton | 82bbab17c0013d87063b398ec777d5977f353d0a | [
"MIT"
] | 6 | 2015-10-16T08:40:00.000Z | 2016-11-14T06:48:09.000Z | #include <iostream>
#include <sys/time.h>
#include <assert.h>
#include <stdlib.h>
#include <pluton/client.h>
using namespace std;
// Force a service to be left in a partially read request state, then
// send a new request to ensure that it resets properly.
const char* SK = "system.echo.0.raw";
int
main(int argc, char** argv)
{
assert(argc == 2);
const char* goodPath = argv[1];
int res;
pluton::client C;
if (!C.initialize(goodPath)) {
cout << "Failed: " << C.getFault().getMessage("Failed: C.initialize()") << endl;
exit(1);
}
C.setDebug(true);
C.setTimeoutMilliSeconds(1);
pluton::clientRequest R;
static const int bufSize = 1000 * 1000 * 60; // 60MB ought to timeout after 1MS
char* buf = new char[bufSize];
R.setRequestData(buf, bufSize);
if (!C.addRequest(SK, R)) {
cout << "Failed Addr 1: " << C.getFault().getMessage("C.addRequest() 1") << endl;
exit(2);
}
res = C.executeAndWaitAll();
if (res != 0) {
cout << "Failed: Expected T/O from executeAndWaitAll: " << res << endl;
exit(3);
}
// Now do a second request to make sure the service isn't broken
C.setTimeoutMilliSeconds(4000); // Make the t/o really small
R.setRequestData(buf, 0);
if (!C.addRequest(SK, R)) {
cout << "Failed: AddR 2: " << C.getFault().getMessage("C.addRequest() 2") << endl;
exit(4);
}
res = C.executeAndWaitAll();
if (res <= 0) {
cout << "Failed: E&W2 " << res << " " << C.getFault().getMessage("executeAndWaitAll") << endl;
exit(5);
}
if (R.hasFault()) {
cout << "Failed: request Faulted: " << R.getFaultText() << endl;
exit(6);
}
return(0);
}
| 22.657534 | 98 | 0.613664 |
440947b52022a63dc706d779cb986d0c140b6777 | 1,756 | hpp | C++ | lib/boost_1.78.0/boost/spirit/home/x3/support/traits/variant_has_substitute.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | 29 | 2021-11-19T11:28:22.000Z | 2022-03-29T00:26:51.000Z | lib/boost_1.78.0/boost/spirit/home/x3/support/traits/variant_has_substitute.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | 4 | 2020-12-07T22:56:32.000Z | 2021-07-17T22:13:37.000Z | lib/boost_1.78.0/boost/spirit/home/x3/support/traits/variant_has_substitute.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | 17 | 2018-07-30T12:45:42.000Z | 2022-01-10T11:18:30.000Z | /*=============================================================================
Copyright (c) 2001-2014 Joel de Guzman
http://spirit.sourceforge.net/
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)
=============================================================================*/
#if !defined(BOOST_SPIRIT_X3_VARIANT_HAS_SUBSTITUTE_APR_18_2014_925AM)
#define BOOST_SPIRIT_X3_VARIANT_HAS_SUBSTITUTE_APR_18_2014_925AM
#include <boost/spirit/home/x3/support/traits/is_substitute.hpp>
#include <boost/mpl/find.hpp>
namespace boost { namespace spirit { namespace x3 { namespace traits
{
template <typename Variant, typename T>
struct variant_has_substitute_impl
{
// Find a type from the Variant that can be a substitute for T.
// return true_ if one is found, else false_
typedef Variant variant_type;
typedef typename variant_type::types types;
typedef typename mpl::end<types>::type end;
typedef typename mpl::find<types, T>::type iter_1;
typedef typename
mpl::eval_if<
is_same<iter_1, end>,
mpl::find_if<types, traits::is_substitute<T, mpl::_1>>,
mpl::identity<iter_1>
>::type
iter;
typedef mpl::not_<is_same<iter, end>> type;
};
template <typename Variant, typename T>
struct variant_has_substitute
: variant_has_substitute_impl<Variant, T>::type {};
template <typename T>
struct variant_has_substitute<unused_type, T> : mpl::true_ {};
template <typename T>
struct variant_has_substitute<unused_type const, T> : mpl::true_ {};
}}}}
#endif
| 33.769231 | 80 | 0.617882 |
440c76a7e19e24f569b9e5d005423be112be567a | 12,648 | cpp | C++ | iree/compiler/Transforms/Sequencer/LowerSequencerDialect.cpp | so-man/iree | 36be189aa74d6f5bc7eb665e5a7baf3effaca12d | [
"Apache-2.0"
] | null | null | null | iree/compiler/Transforms/Sequencer/LowerSequencerDialect.cpp | so-man/iree | 36be189aa74d6f5bc7eb665e5a7baf3effaca12d | [
"Apache-2.0"
] | null | null | null | iree/compiler/Transforms/Sequencer/LowerSequencerDialect.cpp | so-man/iree | 36be189aa74d6f5bc7eb665e5a7baf3effaca12d | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Google LLC
//
// 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
//
// https://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 "iree/compiler/IR/Dialect.h"
#include "iree/compiler/IR/Ops.h"
#include "iree/compiler/IR/Sequencer/HLDialect.h"
#include "iree/compiler/IR/Sequencer/HLOps.h"
#include "iree/compiler/IR/Sequencer/LLDialect.h"
#include "iree/compiler/IR/Sequencer/LLOps.h"
#include "iree/compiler/IR/StructureOps.h"
#include "iree/compiler/Utils/TypeConversionUtils.h"
#include "third_party/llvm/llvm/include/llvm/ADT/ArrayRef.h"
#include "third_party/llvm/llvm/include/llvm/ADT/DenseMap.h"
#include "third_party/llvm/llvm/include/llvm/ADT/SmallVector.h"
#include "mlir/Dialect/StandardOps/Ops.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Module.h"
#include "mlir/IR/OperationSupport.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassRegistry.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/DialectConversion.h"
#include "mlir/Transforms/Utils.h"
namespace mlir {
namespace iree_compiler {
namespace {
template <typename SrcOp>
class SequencerLoweringPattern : public OpConversionPattern<SrcOp> {
public:
SequencerLoweringPattern(MLIRContext *context, TypeConverter &typeConverter)
: OpConversionPattern<SrcOp>(context), typeConverter_(typeConverter) {}
protected:
TypeConverter &typeConverter_;
};
// Returns an integer scalar memref containing the offset specified by |indices|
// within |type|.
Value *computeOffset(Location loc, Value *reference, Value *indices,
OpBuilder &builder) {
auto referenceType = reference->getType().cast<ShapedType>();
auto *shapeMemRef = builder
.create<IREESeq::LL::AllocHeapOp>(
loc,
MemRefType::get({referenceType.getRank()},
builder.getIntegerType(32)),
ArrayRef<Value *>{})
.getResult();
builder.create<IREESeq::LL::ShapeOp>(loc, reference, shapeMemRef);
auto *resultMemRef =
builder
.create<IREESeq::LL::AllocHeapOp>(
loc, MemRefType::get({}, builder.getIntegerType(32)),
ArrayRef<Value *>{})
.getResult();
auto elementSizeAttr = builder.getIntegerAttr(
builder.getIntegerType(8), referenceType.getElementTypeBitWidth() / 8);
builder.create<IREESeq::LL::ComputeOffsetOp>(
loc, shapeMemRef, elementSizeAttr, indices, resultMemRef);
return resultMemRef;
}
// Returns a tuple of (offset, length) integer scalar memrefs with the range
// specified by |indices| and |lengths| within |type|.
std::pair<Value *, Value *> computeRange(Location loc, Value *reference,
Value *indices, Value *lengths,
OpBuilder &builder) {
auto referenceType = reference->getType().cast<ShapedType>();
auto *shapeMemRef = builder
.create<IREESeq::LL::AllocHeapOp>(
loc,
MemRefType::get({referenceType.getRank()},
builder.getIntegerType(32)),
ArrayRef<Value *>{})
.getResult();
builder.create<IREESeq::LL::ShapeOp>(loc, reference, shapeMemRef);
auto *offsetMemRef =
builder
.create<IREESeq::LL::AllocHeapOp>(
loc, MemRefType::get({}, builder.getIntegerType(32)),
ArrayRef<Value *>{})
.getResult();
auto *lengthMemRef =
builder
.create<IREESeq::LL::AllocHeapOp>(
loc, MemRefType::get({}, builder.getIntegerType(32)),
ArrayRef<Value *>{})
.getResult();
auto elementSizeAttr = builder.getIntegerAttr(
builder.getIntegerType(8), referenceType.getElementTypeBitWidth() / 8);
builder.create<IREESeq::LL::ComputeRangeOp>(loc, shapeMemRef, elementSizeAttr,
indices, lengths, offsetMemRef,
lengthMemRef);
return {offsetMemRef, lengthMemRef};
}
struct LowerSliceOpPattern
: public SequencerLoweringPattern<IREESeq::HL::SliceOp> {
using SequencerLoweringPattern::SequencerLoweringPattern;
PatternMatchResult matchAndRewrite(
IREESeq::HL::SliceOp op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override {
OperandAdaptor<IREESeq::HL::SliceOp> operandAdaptor(operands);
auto range = computeRange(op.getLoc(), operandAdaptor.src(),
operandAdaptor.indices(),
operandAdaptor.lengths(), rewriter);
rewriter.replaceOpWithNewOp<IREESeq::LL::DynamicSliceOp>(
op, typeConverter_.convertType(op.getType()),
ArrayRef<Value *>{operandAdaptor.src(), range.first, range.second},
op.getAttrs());
return matchSuccess();
}
};
struct LowerShapeOpPattern
: public SequencerLoweringPattern<IREESeq::HL::ShapeOp> {
using SequencerLoweringPattern::SequencerLoweringPattern;
PatternMatchResult matchAndRewrite(
IREESeq::HL::ShapeOp op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override {
auto *shapeMemRef =
rewriter
.create<IREESeq::LL::AllocHeapOp>(
op.getLoc(),
MemRefType::get({op.getType().cast<ShapedType>().getRank()},
rewriter.getIntegerType(64)),
ArrayRef<Value *>{})
.getResult();
op.replaceAllUsesWith(shapeMemRef);
rewriter.replaceOpWithNewOp<IREESeq::LL::ShapeOp>(op, operands[0],
shapeMemRef);
return matchSuccess();
}
};
struct LowerCopyOpPattern
: public SequencerLoweringPattern<IREESeq::HL::CopyOp> {
using SequencerLoweringPattern::SequencerLoweringPattern;
PatternMatchResult matchAndRewrite(
IREESeq::HL::CopyOp op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override {
OperandAdaptor<IREESeq::HL::CopyOp> operandAdaptor(operands);
auto *srcOffsetMemRef =
computeOffset(op.getLoc(), operandAdaptor.src(),
operandAdaptor.srcIndices(), rewriter);
auto dstRange = computeRange(op.getLoc(), operandAdaptor.dst(),
operandAdaptor.dstIndices(),
operandAdaptor.lengths(), rewriter);
rewriter.replaceOpWithNewOp<IREESeq::LL::DynamicCopyOp>(
op, operandAdaptor.src(), srcOffsetMemRef, operandAdaptor.dst(),
dstRange.first, dstRange.second);
return matchSuccess();
}
};
struct LowerFillOpPattern
: public SequencerLoweringPattern<IREESeq::HL::FillOp> {
using SequencerLoweringPattern::SequencerLoweringPattern;
PatternMatchResult matchAndRewrite(
IREESeq::HL::FillOp op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override {
OperandAdaptor<IREESeq::HL::FillOp> operandAdaptor(operands);
auto dstRange = computeRange(op.getLoc(), operandAdaptor.dst(),
operandAdaptor.dstIndices(),
operandAdaptor.lengths(), rewriter);
rewriter.replaceOpWithNewOp<IREESeq::LL::DynamicFillOp>(
op, operandAdaptor.value(), operandAdaptor.dst(), dstRange.first,
dstRange.second);
return matchSuccess();
}
};
struct LowerBranchOpPattern
: public SequencerLoweringPattern<IREESeq::HL::BranchOp> {
using SequencerLoweringPattern<
IREESeq::HL::BranchOp>::SequencerLoweringPattern;
PatternMatchResult matchAndRewrite(
IREESeq::HL::BranchOp op, ArrayRef<Value *> properOperands,
ArrayRef<Block *> destinations, ArrayRef<ArrayRef<Value *>> operands,
ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<IREESeq::LL::BranchOp>(op, destinations[0],
operands[0]);
return matchSuccess();
}
};
struct LowerCondCondBranchOpPattern
: public SequencerLoweringPattern<IREESeq::HL::CondBranchOp> {
using SequencerLoweringPattern<
IREESeq::HL::CondBranchOp>::SequencerLoweringPattern;
PatternMatchResult matchAndRewrite(
IREESeq::HL::CondBranchOp op, ArrayRef<Value *> properOperands,
ArrayRef<Block *> destinations, ArrayRef<ArrayRef<Value *>> operands,
ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<IREESeq::LL::CondBranchOp>(
op, properOperands[0],
destinations[IREESeq::HL::CondBranchOp::trueIndex],
operands[IREESeq::HL::CondBranchOp::trueIndex],
destinations[IREESeq::HL::CondBranchOp::falseIndex],
operands[IREESeq::HL::CondBranchOp::falseIndex]);
return matchSuccess();
}
};
// Rewrites an op into one with all the same operands, results, and attributes.
// Operands and results in the ops must have the same order and attributes must
// have the same name. They must also be constructed properly by the default
// builders.
template <typename SRC, typename DST>
struct LowerIdenticalOpPattern : public SequencerLoweringPattern<SRC> {
using SequencerLoweringPattern<SRC>::SequencerLoweringPattern;
PatternMatchResult matchAndRewrite(
SRC op, ArrayRef<Value *> operands,
ConversionPatternRewriter &rewriter) const override {
SmallVector<Type, 8> originalResultTypes{
op.getOperation()->getResultTypes()};
SmallVector<Type, 8> resultTypes;
if (failed(this->typeConverter_.convertTypes(originalResultTypes,
resultTypes))) {
op.emitOpError() << "Failed to convert result types";
return this->matchFailure();
}
rewriter.replaceOpWithNewOp<DST>(op, resultTypes, operands, op.getAttrs());
return this->matchSuccess();
}
};
} // namespace
class LowerSequencerDialectPass : public ModulePass<LowerSequencerDialectPass> {
public:
void runOnModule() override {
auto *ctx = &getContext();
LLTypeConverter typeConverter(ctx);
OwningRewritePatternList patterns;
patterns.insert<
LowerIdenticalOpPattern<IREE::ConstantOp, IREESeq::LL::ConstantOp>,
LowerIdenticalOpPattern<IREESeq::HL::DispatchOp,
IREESeq::LL::DynamicDispatchOp>,
LowerShapeOpPattern, LowerCopyOpPattern, LowerSliceOpPattern,
LowerBranchOpPattern, LowerCondCondBranchOpPattern>(ctx, typeConverter);
#define IDENTICAL_OP_LOWERING(op_name) \
LowerIdenticalOpPattern<IREESeq::HL::op_name, IREESeq::LL::op_name>
patterns.insert<
IDENTICAL_OP_LOWERING(AllocHeapOp), IDENTICAL_OP_LOWERING(CloneOp),
IDENTICAL_OP_LOWERING(ReshapeOp), IDENTICAL_OP_LOWERING(CallOp),
IDENTICAL_OP_LOWERING(ReturnOp)>(ctx, typeConverter);
#undef IDENTICAL_OP_LOWERING
mlir::populateFuncOpTypeConversionPattern(patterns, ctx, typeConverter);
ConversionTarget target(*ctx);
target.addLegalDialect<IREELLSequencerDialect>();
target.addDynamicallyLegalOp<FuncOp>([&](FuncOp op) {
return typeConverter.isSignatureLegal(op.getType());
});
target.addLegalOp<ModuleOp, ModuleTerminatorOp,
IREE::MultiArchExecutableOp>();
target.markOpRecursivelyLegal<IREE::MultiArchExecutableOp>();
if (failed(applyFullConversion(getModule(), target, patterns,
&typeConverter))) {
return signalPassFailure();
}
}
};
std::unique_ptr<OpPassBase<ModuleOp>> createLowerSequencerDialectPass() {
return std::make_unique<LowerSequencerDialectPass>();
}
static PassRegistration<LowerSequencerDialectPass> pass(
"iree-lower-sequencer-dialect",
"Lowers the IREE HL sequencer dialect to the LL sequencer dialect.");
} // namespace iree_compiler
} // namespace mlir
| 41.605263 | 80 | 0.67228 |
440d7c861defadb803bd8ec0c6833afed1f8e277 | 1,165 | cpp | C++ | libraries/fc/src/crypto/openssl.cpp | SophiaTX/SophiaTx-Blockchain | c964691c020962ad1aba8263c0d8a78a9fa27e45 | [
"MIT"
] | 8 | 2018-07-25T20:42:43.000Z | 2019-03-11T03:14:09.000Z | libraries/fc/src/crypto/openssl.cpp | SophiaTX/SophiaTx-Blockchain | c964691c020962ad1aba8263c0d8a78a9fa27e45 | [
"MIT"
] | 13 | 2018-07-25T17:41:28.000Z | 2019-01-25T13:38:11.000Z | libraries/fc/src/crypto/openssl.cpp | SophiaTX/SophiaTx-Blockchain | c964691c020962ad1aba8263c0d8a78a9fa27e45 | [
"MIT"
] | 11 | 2018-07-25T14:34:13.000Z | 2019-05-03T13:29:37.000Z | #include <fc/crypto/openssl.hpp>
#include <fc/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <cstdlib>
#include <string>
#include <stdlib.h>
namespace fc
{
struct openssl_scope
{
static ENGINE* eng;
openssl_scope()
{
ENGINE_load_rdrand();
ENGINE* eng = ENGINE_by_id("rdrand");
if(NULL == eng) {
clean_up_engine();
return;
}
if(!ENGINE_init(eng)) {
clean_up_engine();
return;
}
if(!ENGINE_set_default(eng, ENGINE_METHOD_RAND)) {
clean_up_engine();
}
}
~openssl_scope()
{
FIPS_mode_set(0);
CONF_modules_unload(1);
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
clean_up_engine();
}
void clean_up_engine()
{
if(eng != NULL) {
ENGINE_finish(eng);
ENGINE_free(eng);
}
ENGINE_cleanup();
}
};
ENGINE* openssl_scope::eng;
int init_openssl()
{
static openssl_scope ossl;
return 0;
}
}
| 17.923077 | 60 | 0.498712 |
440e8c81f92ce8229a8463756046dc9995685f1b | 5,679 | cpp | C++ | build_linux/moc_addressbookpage.cpp | bitcrystal2/bitcrystal_v20_last_linux_branch | a5d759e9b5134502a28483fea3567894eec08e7f | [
"MIT"
] | null | null | null | build_linux/moc_addressbookpage.cpp | bitcrystal2/bitcrystal_v20_last_linux_branch | a5d759e9b5134502a28483fea3567894eec08e7f | [
"MIT"
] | null | null | null | build_linux/moc_addressbookpage.cpp | bitcrystal2/bitcrystal_v20_last_linux_branch | a5d759e9b5134502a28483fea3567894eec08e7f | [
"MIT"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'addressbookpage.h'
**
** Created: Thu Dec 25 23:31:32 2014
** by: The Qt Meta Object Compiler version 63 (Qt 4.8.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/qt/addressbookpage.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'addressbookpage.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_AddressBookPage[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
17, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
3, // signalCount
// signals: signature, parameters, type, tag, flags
22, 17, 16, 16, 0x05,
43, 17, 16, 16, 0x05,
66, 17, 16, 16, 0x05,
// slots: signature, parameters, type, tag, flags
92, 85, 16, 16, 0x0a,
102, 16, 16, 16, 0x08,
129, 16, 16, 16, 0x08,
153, 16, 16, 16, 0x08,
178, 16, 16, 16, 0x08,
203, 16, 16, 16, 0x08,
230, 16, 16, 16, 0x08,
250, 16, 16, 16, 0x08,
274, 16, 16, 16, 0x08,
294, 16, 16, 16, 0x08,
309, 16, 16, 16, 0x08,
335, 16, 16, 16, 0x08,
360, 354, 16, 16, 0x08,
397, 383, 16, 16, 0x08,
0 // eod
};
static const char qt_meta_stringdata_AddressBookPage[] = {
"AddressBookPage\0\0addr\0signMessage(QString)\0"
"verifyMessage(QString)\0sendCoins(QString)\0"
"retval\0done(int)\0on_deleteAddress_clicked()\0"
"on_newAddress_clicked()\0"
"on_copyAddress_clicked()\0"
"on_signMessage_clicked()\0"
"on_verifyMessage_clicked()\0"
"onSendCoinsAction()\0on_showQRCode_clicked()\0"
"onCopyLabelAction()\0onEditAction()\0"
"on_exportButton_clicked()\0selectionChanged()\0"
"point\0contextualMenu(QPoint)\0parent,begin,\0"
"selectNewAddress(QModelIndex,int,int)\0"
};
void AddressBookPage::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
AddressBookPage *_t = static_cast<AddressBookPage *>(_o);
switch (_id) {
case 0: _t->signMessage((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 1: _t->verifyMessage((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 2: _t->sendCoins((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 3: _t->done((*reinterpret_cast< int(*)>(_a[1]))); break;
case 4: _t->on_deleteAddress_clicked(); break;
case 5: _t->on_newAddress_clicked(); break;
case 6: _t->on_copyAddress_clicked(); break;
case 7: _t->on_signMessage_clicked(); break;
case 8: _t->on_verifyMessage_clicked(); break;
case 9: _t->onSendCoinsAction(); break;
case 10: _t->on_showQRCode_clicked(); break;
case 11: _t->onCopyLabelAction(); break;
case 12: _t->onEditAction(); break;
case 13: _t->on_exportButton_clicked(); break;
case 14: _t->selectionChanged(); break;
case 15: _t->contextualMenu((*reinterpret_cast< const QPoint(*)>(_a[1]))); break;
case 16: _t->selectNewAddress((*reinterpret_cast< const QModelIndex(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break;
default: ;
}
}
}
const QMetaObjectExtraData AddressBookPage::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject AddressBookPage::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_AddressBookPage,
qt_meta_data_AddressBookPage, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &AddressBookPage::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *AddressBookPage::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *AddressBookPage::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_AddressBookPage))
return static_cast<void*>(const_cast< AddressBookPage*>(this));
return QDialog::qt_metacast(_clname);
}
int AddressBookPage::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 17)
qt_static_metacall(this, _c, _id, _a);
_id -= 17;
}
return _id;
}
// SIGNAL 0
void AddressBookPage::signMessage(QString _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void AddressBookPage::verifyMessage(QString _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
// SIGNAL 2
void AddressBookPage::sendCoins(QString _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
QT_END_MOC_NAMESPACE
| 35.49375 | 168 | 0.619827 |
440eadb4249244c03db0b3fe9843fed07ecc809f | 5,964 | cpp | C++ | luogu/4463/me.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | luogu/4463/me.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | luogu/4463/me.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=530000;
const int MOD=998244353;
inline int read(){
int x=0,f=0; char ch=getchar();
while(ch<'0'||ch>'9') f|=(ch=='-'),ch=getchar();
while(ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
return f==0 ? x : -x;
}
inline void write(int x){
if(x<0) {x=~(x-1); putchar('-');}
if(x>9) write(x/10);
putchar(x%10+'0');
}
typedef vector<int> Poly;
void write_Poly(Poly A){
for(register int i=0;i<(int)A.size();++i) write(A[i]),printf(" ");
puts("");
}
int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;}
int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;}
#define mul(a,b) (ll)(a)*(b)%MOD
void Add(int &x,int y){x+=y; if(x>=MOD) x-=MOD;}
void Sub(int &x,int y){x-=y; if(x<0) x+=MOD;}
void Mul(int &x,int y){x=1ll*x*y%MOD;}
int qpow(int x,int y){
int ret=1;
while(y){
if(y&1) ret=mul(ret,x);
x=mul(x,x);
y>>=1;
}
return ret;
}
int Inv(int x){return qpow(x,MOD-2);}
int inv[N];
namespace FFT{
int rev[N<<1],G[N<<1],IG[N<<1];
int init(int n){
int len=1;
while(len<n) len<<=1;
rev[0]=0; rev[len-1]=len-1;
for(register int i=1;i<len-1;++i) rev[i]=(rev[i>>1]>>1)+(i&1 ? len>>1 : 0);
for(register int i=1;i<=len;i<<=1){
G[i]=qpow(3,(MOD-1)/i);
IG[i]=qpow(G[i],MOD-2);
}
return len;
}
void ntt(int *a,int len,int flag){
for(register int i=0;i<len;++i) if(i<rev[i]) swap(a[i],a[rev[i]]);
for(register int h=1;h<len;h<<=1){
int wn=(flag==1 ? G[h<<1] : IG[h<<1]);
for(register int i=0;i<len;i+=(h<<1)){
int W=1,tmp1,tmp2;
for(register int j=i;j<i+h;++j){
tmp1=a[j], tmp2=mul(a[j+h],W);
a[j]=add(tmp1,tmp2);
a[j+h]=sub(tmp1,tmp2);
W=mul(W,wn);
}
}
}
if(flag==-1){
int invlen=qpow(len,MOD-2);
for(register int i=0;i<len;++i) a[i]=mul(a[i],invlen);
}
}
void multi(int *a,int *b,int len)
{
ntt(a,len,1); ntt(b,len,1);
for(register int i=0;i<len;++i) a[i]=mul(a[i],b[i]);
ntt(a,len,-1);
}
}
Poly operator + (Poly A,Poly B){
int len=max((int)A.size(),(int)B.size());
A.resize(len); B.resize(len);
for(register int i=0;i<len;++i) Add(A[i],B[i]);
return A;
}
Poly operator - (Poly A,Poly B){
int len=max((int)A.size(),(int)B.size());
A.resize(len); B.resize(len);
for(register int i=0;i<len;++i) Sub(A[i],B[i]);
return A;
}
Poly operator * (Poly A,Poly B){
static int a[N<<1],b[N<<1];
int M=(int)A.size()+(int)B.size()-1;
int len=FFT::init(M);
A.resize(len); B.resize(len);
for(register int i=0;i<len;++i) a[i]=A[i],b[i]=B[i];
FFT::multi(a,b,len);
A.resize(M);
for(register int i=0;i<M;++i) A[i]=a[i];
return A;
}
void reverse(Poly &A){
for(register int i=0;i<(int)A.size()/2;++i){
swap(A[i],A[(int)A.size()-1-i]);
}
}
void Inverse(Poly A,Poly &B,int n){
static int a[N<<1],b[N<<1];
if(n==1){
B[0]=Inv(A[0]);
return;
}
int mid=(n+1)/2;
Inverse(A,B,mid);
int len=FFT::init(n<<1);
for(register int i=0;i<len;++i) a[i]=b[i]=0;
for(register int i=0;i<n;++i) a[i]=A[i];
for(register int i=0;i<mid;++i) b[i]=B[i];
FFT::ntt(a,len,1); FFT::ntt(b,len,1);
for(register int i=0;i<len;++i){
b[i]=mul(b[i],sub(2,mul(a[i],b[i])));
}
FFT::ntt(b,len,-1);
for(register int i=0;i<n;++i) B[i]=b[i];
}
Poly Polynomial_Inverse(Poly A){
Poly B; B.resize(A.size());
Inverse(A,B,(int)A.size());
return B;
}
Poly operator / (Poly A,Poly B){
reverse(A); reverse(B);
int Len=A.size()-B.size()+1;
A.resize(Len); B.resize(Len);
B=Polynomial_Inverse(B);
Poly D=A*B; D.resize(Len);
reverse(D);
return D;
}
Poly operator % (Poly A,Poly B){
Poly D=A/B; D=D*B;
Poly R=A-D;
R.resize((int)B.size()-1);
return R;
}
Poly Integral(Poly A){//jifen
A.resize(A.size()+1);
for(register int i=(int)A.size()-1;i>=1;i--) A[i]=mul(inv[i],A[i-1]);
A[0]=0;
return A;
}
Poly Derivate(Poly A){//qiudao
for(register int i=0;i<(int)A.size()-1;++i) A[i]=mul(i+1,A[i+1]);
A.resize(A.size()-1);
return A;
}
Poly Polynomial_ln(Poly A){
Poly AA=Derivate(A);
A=Polynomial_Inverse(A);
Poly B=A*AA;
B.resize(AA.size());
B=Integral(B);
return B;
}
void EXP(Poly A,Poly &B,int n){
static int a[N<<1],b[N<<1],lnb[N<<1];
if(n==1){
B.push_back(1);
return;
}
int mid=(n+1)/2;
EXP(A,B,mid);
B.resize(n); Poly lnB=Polynomial_ln(B);
int len=FFT::init(n+n);
for(register int i=0;i<len;++i) a[i]=0,b[i]=0,lnb[i]=0;
for(register int i=0;i<n;++i) a[i]=A[i],lnb[i]=lnB[i];//important!! "ln in MOD x^n"
for(register int i=0;i<mid;++i) b[i]=B[i];
FFT::ntt(a,len,1); FFT::ntt(b,len,1); FFT::ntt(lnb,len,1);
for(register int i=0;i<len;++i){
b[i]=mul(b[i],sub(a[i]+1,lnb[i]));
}
FFT::ntt(b,len,-1);
for(register int i=0;i<n;++i) B[i]=b[i];
}
Poly Polynomial_Exp(Poly A){
Poly B;
EXP(A,B,A.size());
return B;
}
int n,k,fac[N],ifac[N];
Poly f,f1;
signed main(){
inv[0]=1; inv[1]=1; for(register int i=2;i<N;++i) inv[i]=mul(MOD-MOD/i,inv[MOD%i]);
k=read(); n=read();
fac[0]=1; for(int i=1;i<=n+1;i++) fac[i]=mul(fac[i-1],i);
ifac[0]=1; for(int i=1;i<=n+1;i++) ifac[i]=mul(ifac[i-1],inv[i]);
f.resize(n+1); f1.resize(n+1);
for(int i=0,tmp=k+1;i<=n;i++,Mul(tmp,k+1)) f1[i]=ifac[i+1],f[i]=mul(ifac[i+1],tmp);
f=f*Polynomial_Inverse(f1);
f[0]=0; f.resize(n+1);
for(int i=1;i<=n;i++){
Mul(f[i],fac[i-1]);//*i!/i
if(i&1^1) f[i]=MOD-f[i];
}
f=Polynomial_Exp(f);
printf("%lld\n",mul(f[n],fac[n]));
return 0;
} | 26.986425 | 88 | 0.504359 |
440f30946cab250c0db8709e14985c206ca8c50e | 3,501 | cpp | C++ | node/silkworm/downloader/messages/InboundNewBlockHashes.cpp | elmato/silkworm | 711c73547cd1f7632ff02d5f86dfac5b0d249344 | [
"Apache-2.0"
] | null | null | null | node/silkworm/downloader/messages/InboundNewBlockHashes.cpp | elmato/silkworm | 711c73547cd1f7632ff02d5f86dfac5b0d249344 | [
"Apache-2.0"
] | null | null | null | node/silkworm/downloader/messages/InboundNewBlockHashes.cpp | elmato/silkworm | 711c73547cd1f7632ff02d5f86dfac5b0d249344 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2021 The Silkworm Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "InboundNewBlockHashes.hpp"
#include <algorithm>
#include <silkworm/common/log.hpp>
#include <silkworm/downloader/internals/random_number.hpp>
#include <silkworm/downloader/packets/RLPEth66PacketCoding.hpp>
#include <silkworm/downloader/rpc/send_message_by_id.hpp>
namespace silkworm {
InboundNewBlockHashes::InboundNewBlockHashes(const sentry::InboundMessage& msg, WorkingChain& wc, SentryClient& s)
: InboundMessage(), working_chain_(wc), sentry_(s) {
if (msg.id() != sentry::MessageId::NEW_BLOCK_HASHES_66)
throw std::logic_error("InboundNewBlockHashes received wrong InboundMessage");
reqId_ = RANDOM_NUMBER.generate_one(); // for trace purposes
peerId_ = string_from_H512(msg.peer_id());
ByteView data = string_view_to_byte_view(msg.data()); // copy for consumption
rlp::success_or_throw(rlp::decode(data, packet_));
SILK_TRACE << "Received message " << *this;
}
void InboundNewBlockHashes::execute() {
using namespace std;
SILK_TRACE << "Processing message " << *this;
// todo: Erigon apparently processes this message even if it is not in a fetching phase BUT is in request-chaining
// mode - do we need the same?
BlockNum max = working_chain_.top_seen_block_height();
for (size_t i = 0; i < packet_.size(); i++) {
Hash hash = packet_[i].hash;
// save announcement
working_chain_.save_external_announce(hash);
if (working_chain_.has_link(hash)) continue;
// request header
GetBlockHeadersPacket66 reply;
reply.requestId = RANDOM_NUMBER.generate_one();
reply.request.origin = hash;
reply.request.amount = 1;
reply.request.skip = 0;
reply.request.reverse = false;
Bytes rlp_encoding;
rlp::encode(rlp_encoding, reply);
auto msg_reply = std::make_unique<sentry::OutboundMessageData>();
msg_reply->set_id(sentry::MessageId::GET_BLOCK_HEADERS_66);
msg_reply->set_data(rlp_encoding.data(), rlp_encoding.length()); // copy
// send msg_reply
SILK_TRACE << "Replying to " << identify(*this) << " with send_message_by_id, content: " << reply;
rpc::SendMessageById rpc(peerId_, std::move(msg_reply));
rpc.do_not_throw_on_failure();
sentry_.exec_remotely(rpc);
[[maybe_unused]] sentry::SentPeers peers = rpc.reply();
SILK_TRACE << "Received rpc result of " << identify(*this) << ": "
<< std::to_string(peers.peers_size()) + " peer(s)";
// calculate top seen block height
max = std::max(max, packet_[i].number);
}
working_chain_.top_seen_block_height(max);
}
uint64_t InboundNewBlockHashes::reqId() const { return reqId_; }
std::string InboundNewBlockHashes::content() const {
std::stringstream content;
content << packet_;
return content.str();
}
} // namespace silkworm | 34.663366 | 118 | 0.690089 |
44118ee6351d2431365729ada9faca38a9a5433e | 1,036 | cpp | C++ | bitriejoin-ed/main.cpp | TsinghuaDatabaseGroup/Similarity-Search-and-Join | 0fba32f030ca9e466d1aed9d3c7dcf59ea3e88dc | [
"BSD-2-Clause"
] | 14 | 2018-01-29T06:54:06.000Z | 2021-07-09T18:18:51.000Z | bitriejoin-ed/main.cpp | TsinghuaDatabaseGroup/similarity | 0fba32f030ca9e466d1aed9d3c7dcf59ea3e88dc | [
"BSD-2-Clause"
] | null | null | null | bitriejoin-ed/main.cpp | TsinghuaDatabaseGroup/similarity | 0fba32f030ca9e466d1aed9d3c7dcf59ea3e88dc | [
"BSD-2-Clause"
] | 11 | 2018-04-11T04:56:40.000Z | 2021-12-17T04:00:22.000Z | #include <stdio.h>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include "BiTrieSelfJoin.h"
#include "common/time.h"
using namespace std;
extern long long resultNum;
void LoadStrings(vector<char*>& strings, char* filename)
{
ifstream in(filename);
if (in.fail())
{
cerr << "Can not open \"" << filename << "\"" << endl;
exit(0);
}
string line;
while (getline(in, line, '\n'))
{
int len = line.size();
while (len>0 && (line[len-1]=='\n' || line[len-1]=='\r')) --len;
char* newBuf = (char*)malloc(len+1);
memcpy(newBuf, line.c_str(), len);
newBuf[len] = 0;
strings.push_back(newBuf);
}
in.close();
}
int main(int argc, char **argv)
{
if (argc != 3) return -1;
log_start();
char* filename = argv[1];
int ed = atoi(argv[2]);
vector<char*> strings;
LoadStrings(strings,filename);
BiTrieSelfJoin triejoin;
triejoin.edjoin(strings, ed);
for (unsigned int i=0; i<strings.size(); ++i)
free(strings[i]);
cout << resultNum << endl;
cout << resultNum << endl;
return 0;
}
| 19.54717 | 66 | 0.632239 |
4413384da82d02d06b480f9a45319d7c23c375d5 | 11,826 | cpp | C++ | SwordsmanAndSpiders/Classes/common/SixCatsLogger.cpp | beardog-ukr/vigilant-couscous | 57f00950b567cb6adf2e0a06f02925ee271012fe | [
"Unlicense"
] | null | null | null | SwordsmanAndSpiders/Classes/common/SixCatsLogger.cpp | beardog-ukr/vigilant-couscous | 57f00950b567cb6adf2e0a06f02925ee271012fe | [
"Unlicense"
] | null | null | null | SwordsmanAndSpiders/Classes/common/SixCatsLogger.cpp | beardog-ukr/vigilant-couscous | 57f00950b567cb6adf2e0a06f02925ee271012fe | [
"Unlicense"
] | null | null | null | #include "SixCatsLogger.h"
#include <iostream> // cout
using namespace std;
#define LOCAL_C6_DEBUG 1
// --- ------------------------------------------------------------------------
SixCatsLogger::SixCatsLogger() {
selfSetup();
}
// --- ------------------------------------------------------------------------
SixCatsLogger::SixCatsLogger(LogLevel inLogLevel) {
selfSetup();
logLevel = inLogLevel;
}
// --- ------------------------------------------------------------------------
SixCatsLogger::~SixCatsLogger() {
#ifdef LOCAL_C6_DEBUG
cout << "SixCatsLogger obj destroyed" << endl;
#endif // ifdef LOCAL_C6_DEBUG
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::selfSetup() {
setLogLevel(SixCatsLogger::Critical);
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::setLogLevel(LogLevel inLogLevel) {
logLevel = inLogLevel; //
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::write(LogLevel messageLevel, const string str) {
if (messageLevel > logLevel) {
return;
}
cout << str << endl;
}
// --- ------------------------------------------------------------------------
string SixCatsLogger::composeLine(const string& metaInfo, const string& message) const {
const string tmps = metaInfo + " >> " + message;
return tmps;
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::c(const string& message) {
write(Critical, message);
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::c(const string& metaInfo, const string& message) {
write(Critical, composeLine(metaInfo, message));
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::w(const string& message) {
write(Warning, message);
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::w(const string& metaInfo, const string& message) {
write(Warning, composeLine(metaInfo, message));
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::i(const string& message) {
write(Info, message);
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::i(const string& metaInfo, const string& message) {
write(Info, composeLine(metaInfo, message));
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::d(const string& message) {
write(Debug, message);
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::d(const string& metaInfo, const string& message) {
write(Debug, composeLine(metaInfo, message));
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::t(const string& metaInfo, const string& message) {
write(Trace, composeLine(metaInfo, message));
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::t(const string& message) {
write(Trace, message);
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::f(const string& metaInfo, const string& message) {
write(Flood, composeLine(metaInfo, message));
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::f(const string& message) {
write(Flood, message);
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::writeL(LogLevel messageLevel,
std::function<void(std::ostringstream&)>makeMessage) {
if (messageLevel > logLevel) {
return;
}
ostringstream s;
makeMessage(s);
write(messageLevel, s.str());
}
void SixCatsLogger::writeL(LogLevel messageLevel,
const string & metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
if (messageLevel > logLevel) {
return;
}
ostringstream s;
makeMessage(s);
write(messageLevel, composeLine(metaInfo, s.str()));
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::c(std::function<void(std::ostringstream&)>makeMessage) {
writeL(Critical, makeMessage);
}
void SixCatsLogger::w(std::function<void(std::ostringstream&)>makeMessage) {
writeL(Warning, makeMessage);
}
void SixCatsLogger::i(std::function<void(std::ostringstream&)>makeMessage) {
writeL(Info, makeMessage);
}
void SixCatsLogger::d(std::function<void(std::ostringstream&)>makeMessage) {
writeL(Debug, makeMessage);
}
void SixCatsLogger::t(std::function<void(std::ostringstream&)>makeMessage) {
writeL(Trace, makeMessage);
}
void SixCatsLogger::f(std::function<void(std::ostringstream&)>makeMessage) {
writeL(Flood, makeMessage);
}
// --- ------------------------------------------------------------------------
void SixCatsLogger::c(const string & metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
writeL(Critical, metaInfo, makeMessage);
}
void SixCatsLogger::w(const string & metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
writeL(Warning, metaInfo, makeMessage);
}
void SixCatsLogger::i(const string & metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
writeL(Info, metaInfo, makeMessage);
}
void SixCatsLogger::d(const string & metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
writeL(Debug, metaInfo, makeMessage);
}
void SixCatsLogger::t(const string & metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
writeL(Trace, metaInfo, makeMessage);
}
void SixCatsLogger::f(const string & metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
writeL(Flood, metaInfo, makeMessage);
}
// --- ------------------------------------------------------------------------
void c6c(SixCatsLogger *logger, const string message) {
if (logger == 0) {
return;
}
logger->c(message);
}
// --- ------------------------------------------------------------------------
void c6c(SixCatsLogger *logger, const string metaInfo, const string message) {
if (logger == 0) {
return;
}
logger->c(metaInfo, message);
}
// --- ------------------------------------------------------------------------
void c6w(SixCatsLogger *logger, const string message) {
if (logger == 0) {
return;
}
logger->w(message);
}
// --- ------------------------------------------------------------------------
void c6w(SixCatsLogger *logger, const string metaInfo, const string message) {
if (logger == 0) {
return;
}
logger->w(metaInfo, message);
}
// --- ------------------------------------------------------------------------
void c6i(SixCatsLogger *logger, const string message) {
if (logger == 0) {
return;
}
logger->i(message);
}
// --- ------------------------------------------------------------------------
void c6i(SixCatsLogger *logger, const string metaInfo, const string message) {
if (logger == 0) {
return;
}
logger->i(metaInfo, message);
}
// --- ------------------------------------------------------------------------
void c6d(SixCatsLogger *logger, const string message) {
if (logger == 0) {
return;
}
logger->d(message);
}
// --- ------------------------------------------------------------------------
void c6d(SixCatsLogger *logger, const string metaInfo, const string message) {
if (logger == 0) {
return;
}
logger->d(metaInfo, message);
}
// --- ------------------------------------------------------------------------
void c6t(SixCatsLogger *logger, const string message) {
if (logger == 0) {
return;
}
logger->t(message);
}
// --- ------------------------------------------------------------------------
void c6t(SixCatsLogger *logger, const string metaInfo, const string message) {
if (logger == 0) {
return;
}
logger->t(metaInfo, message);
}
// --- ------------------------------------------------------------------------
void c6f(SixCatsLogger *logger, const string message) {
if (logger == 0) {
return;
}
logger->f(message);
}
// --- ------------------------------------------------------------------------
void c6f(SixCatsLogger *logger, const string metaInfo, const string message) {
if (logger == 0) {
return;
}
logger->f(metaInfo, message);
}
// --- ------------------------------------------------------------------------
void c6c(SixCatsLogger *logger,
std::function<void(std::ostringstream&)>makeMessage) {
if (logger == 0) {
return;
}
logger->c(makeMessage);
}
void c6w(SixCatsLogger *logger, std::function<void(std::ostringstream&)>makeMessage) {
if (logger == 0) {
return;
}
logger->w(makeMessage);
}
void c6i(SixCatsLogger *logger, std::function<void(std::ostringstream&)>makeMessage) {
if (logger == 0) {
return;
}
logger->i(makeMessage);
}
void c6d(SixCatsLogger *logger, std::function<void(std::ostringstream&)>makeMessage) {
if (logger == 0) {
return;
}
logger->d(makeMessage);
}
void c6t(SixCatsLogger *logger, std::function<void(std::ostringstream&)>makeMessage) {
if (logger == 0) {
return;
}
logger->t(makeMessage);
}
void c6f(SixCatsLogger *logger, std::function<void(std::ostringstream&)>makeMessage) {
if (logger == 0) {
return;
}
logger->f(makeMessage);
}
// --- ------------------------------------------------------------------------
void c6c(SixCatsLogger *logger, const string metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
if (logger == 0) {
return;
}
logger->c(metaInfo, makeMessage);
}
void c6w(SixCatsLogger *logger, const string metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
if (logger == 0) {
return;
}
logger->w(metaInfo, makeMessage);
}
void c6i(SixCatsLogger *logger, const string metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
if (logger == 0) {
return;
}
logger->i(metaInfo, makeMessage);
}
void c6d(SixCatsLogger *logger, const string metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
if (logger == 0) {
return;
}
logger->d(metaInfo, makeMessage);
}
void c6t(SixCatsLogger *logger, const string metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
if (logger == 0) {
return;
}
logger->t(metaInfo, makeMessage);
}
void c6f(SixCatsLogger *logger, const string metaInfo,
std::function<void(std::ostringstream&)>makeMessage) {
if (logger == 0) {
return;
}
logger->f(metaInfo, makeMessage);
}
// --- ------------------------------------------------------------------------
// --- ------------------------------------------------------------------------
| 26.635135 | 89 | 0.457551 |
4414cf77cd013dbe998caff4cc57ff4f5edc1b0e | 36,416 | cpp | C++ | dlib/test/matrix4.cpp | oms1226/dlib-19.13 | 0bb55d112324edb700a42a3e6baca09c03967754 | [
"MIT"
] | null | null | null | dlib/test/matrix4.cpp | oms1226/dlib-19.13 | 0bb55d112324edb700a42a3e6baca09c03967754 | [
"MIT"
] | null | null | null | dlib/test/matrix4.cpp | oms1226/dlib-19.13 | 0bb55d112324edb700a42a3e6baca09c03967754 | [
"MIT"
] | null | null | null | // Copyright (C) 2010 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#include <dlib/matrix.h>
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>
#include "../stl_checked.h"
#include "../array.h"
#include "../rand.h"
#include "tester.h"
#include <dlib/memory_manager_stateless.h>
#include <dlib/array2d.h>
namespace
{
using namespace test;
using namespace dlib;
using namespace std;
logger dlog("test.matrix4");
void matrix_test (
)
/*!
ensures
- runs tests on the matrix stuff compliance with the specs
!*/
{
print_spinner();
{
matrix<double,3,3> m = round(10*randm(3,3));
matrix<double,3,1> v = round(10*randm(3,1));
DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m ));
DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m ));
}
{
matrix<double,3,3> m = round(10*randm(3,3));
matrix<double,1,3> v = round(10*randm(1,3));
DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m ));
DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m ));
}
{
matrix<double> m = round(10*randm(3,3));
matrix<double,1,3> v = round(10*randm(1,3));
DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m ));
DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m ));
}
{
matrix<double> m = round(10*randm(3,3));
matrix<double,0,3> v = round(10*randm(1,3));
DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m ));
DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m ));
}
{
matrix<double> m = round(10*randm(3,3));
matrix<double,1,0> v = round(10*randm(1,3));
DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m ));
DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m ));
}
{
matrix<double> m = round(10*randm(3,3));
matrix<double,3,0> v = round(10*randm(3,1));
DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m ));
DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m ));
}
{
matrix<double> m = round(10*randm(3,3));
matrix<double,0,1> v = round(10*randm(3,1));
DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m ));
DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m ));
}
{
matrix<double,3,3> m = round(10*randm(3,3));
matrix<double,3,0> v = round(10*randm(3,1));
DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m ));
DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m ));
}
{
matrix<double,3,3> m = round(10*randm(3,3));
matrix<double,0,1> v = round(10*randm(3,1));
DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) ));
DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m ));
DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m ));
}
{
matrix<double,3,5> m = round(10*randm(3,5));
matrix<double,0,1> v1 = round(10*randm(5,1));
matrix<double,0,1> v2 = round(10*randm(3,1));
DLIB_TEST(equal( m*diagm(v1) , m*tmp(diagm(v1)) ));
DLIB_TEST(equal( scale_columns(m,v1) , m*tmp(diagm(v1)) ));
DLIB_TEST(equal( diagm(v2)*m , tmp(diagm(v2))*m ));
DLIB_TEST(equal( scale_rows(m,v2) , tmp(diagm(v2))*m ));
}
{
matrix<double,3,5> m = round(10*randm(3,5));
matrix<double,5,1> v1 = round(10*randm(5,1));
matrix<double,3,1> v2 = round(10*randm(3,1));
DLIB_TEST(equal( m*diagm(v1) , m*tmp(diagm(v1)) ));
DLIB_TEST(equal( scale_columns(m,v1) , m*tmp(diagm(v1)) ));
DLIB_TEST(equal( diagm(v2)*m , tmp(diagm(v2))*m ));
DLIB_TEST(equal( scale_rows(m,v2) , tmp(diagm(v2))*m ));
}
}
void test_stuff()
{
print_spinner();
{
matrix<double> m(3,3), lr(3,3), ud(3,3);
m = 1,2,3,
4,5,6,
7,8,9;
lr = 3,2,1,
6,5,4,
9,8,7;
ud = 7,8,9,
4,5,6,
1,2,3;
DLIB_TEST(lr == fliplr(m));
DLIB_TEST(ud == flipud(m));
}
{
matrix<double> m(3,2), lr(3,2), ud(3,2);
m = 1,2,
3,4,
5,6;
lr = 2,1,
4,3,
6,5;
ud = 5,6,
3,4,
1,2;
DLIB_TEST(lr == fliplr(m));
DLIB_TEST(ud == flipud(m));
}
{
matrix<int> a, b;
a = matrix_cast<int>(round(10*randm(3,3)));
b = a;
b *= b;
DLIB_TEST(b == a*a);
}
{
matrix<double> m(2,3), m2(2,3);
m = 1,2,3,
4,5,6;
m2 = 3,4,5,
6,7,8;
DLIB_TEST(m + 2 == m2);
DLIB_TEST(2 + m == m2);
m += 2;
DLIB_TEST(m == m2);
m -= 2;
m2 = 0,1,2,
3,4,5;
DLIB_TEST(m - 1 == m2);
m -= 1;
DLIB_TEST(m == m2);
m += 1;
m2 = 5,4,3,
2,1,0;
DLIB_TEST(6 - m == m2);
}
{
matrix<float> m(2,3), m2(2,3);
m = 1,2,3,
4,5,6;
m2 = 3,4,5,
6,7,8;
DLIB_TEST(m + 2 == m2);
DLIB_TEST(2 + m == m2);
m += 2;
DLIB_TEST(m == m2);
m -= 2;
m2 = 0,1,2,
3,4,5;
DLIB_TEST(m - 1 == m2);
m -= 1;
DLIB_TEST(m == m2);
m += 1;
m2 = 5,4,3,
2,1,0;
DLIB_TEST(6 - m == m2);
}
{
matrix<int> m(2,3), m2(2,3);
m = 1,2,3,
4,5,6;
m2 = 3,4,5,
6,7,8;
DLIB_TEST(m + 2 == m2);
DLIB_TEST(2 + m == m2);
m += 2;
DLIB_TEST(m == m2);
m -= 2;
m2 = 0,1,2,
3,4,5;
DLIB_TEST(m - 1 == m2);
m -= 1;
DLIB_TEST(m == m2);
m += 1;
m2 = 5,4,3,
2,1,0;
DLIB_TEST(6 - m == m2);
}
{
matrix<int,2,3> m, m2;
m = 1,2,3,
4,5,6;
m2 = 3,4,5,
6,7,8;
DLIB_TEST(m + 2 == m2);
DLIB_TEST(2 + m == m2);
m += 2;
DLIB_TEST(m == m2);
m -= 2;
m2 = 0,1,2,
3,4,5;
DLIB_TEST(m - 1 == m2);
m -= 1;
DLIB_TEST(m == m2);
m += 1;
m2 = 5,4,3,
2,1,0;
DLIB_TEST(6 - m == m2);
}
{
matrix<double> m(2,3), m2(3,2);
m = 1,2,3,
4,5,6;
m2 = 2,5,
3,6,
4,7;
DLIB_TEST(trans(m+1) == m2);
DLIB_TEST(trans(m)+1 == m2);
DLIB_TEST(1+trans(m) == m2);
DLIB_TEST(1+m-1 == m);
m = trans(m+1);
DLIB_TEST(m == m2);
m = trans(m-1);
DLIB_TEST(trans(m+1) == m2);
m = trans(m)+1;
DLIB_TEST(m == m2);
}
{
matrix<double> d(3,1), di(3,1);
matrix<double> m(3,3);
m = 1,2,3,
4,5,6,
7,8,9;
d = 1,2,3;
di = 1, 1/2.0, 1/3.0;
DLIB_TEST(inv(diagm(d)) == diagm(di));
DLIB_TEST(pinv(diagm(d)) == diagm(di));
DLIB_TEST(inv(diagm(d))*m == tmp(diagm(di))*m);
DLIB_TEST(m*inv(diagm(d)) == m*tmp(diagm(di)));
DLIB_TEST(equal(inv(diagm(d)) + m , tmp(diagm(di)) + m));
DLIB_TEST(equal(m + inv(diagm(d)) , tmp(diagm(di)) + m));
DLIB_TEST((m + identity_matrix<double>(3) == m + tmp(identity_matrix<double>(3))));
DLIB_TEST((m + identity_matrix<double,3>() == m + tmp(identity_matrix<double,3>())));
DLIB_TEST((m + 2*identity_matrix<double>(3) == m + 2*tmp(identity_matrix<double>(3))));
DLIB_TEST((m + 2*identity_matrix<double,3>() == m + 2*tmp(identity_matrix<double,3>())));
DLIB_TEST((m + identity_matrix<double>(3)*2 == m + 2*tmp(identity_matrix<double>(3))));
DLIB_TEST((m + identity_matrix<double,3>()*2 == m + 2*tmp(identity_matrix<double,3>())));
DLIB_TEST((identity_matrix<double>(3) + m == m + tmp(identity_matrix<double>(3))));
DLIB_TEST((identity_matrix<double,3>() + m == m + tmp(identity_matrix<double,3>())));
DLIB_TEST((2*identity_matrix<double>(3) + m == m + 2*tmp(identity_matrix<double>(3))));
DLIB_TEST((2*identity_matrix<double,3>() + m == m + 2*tmp(identity_matrix<double,3>())));
}
{
matrix<double,3,1> d(3,1), di(3,1);
matrix<double,3,3> m(3,3);
m = 1,2,3,
4,5,6,
7,8,9;
d = 1,2,3;
di = 1, 1/2.0, 1/3.0;
DLIB_TEST(equal(inv(diagm(d)) , diagm(di)));
DLIB_TEST(equal(inv(diagm(d)) , diagm(di)));
DLIB_TEST(equal(inv(diagm(d))*m , tmp(diagm(di))*m));
DLIB_TEST(equal(m*inv(diagm(d)) , m*tmp(diagm(di))));
DLIB_TEST_MSG(equal(inv(diagm(d)) + m , tmp(diagm(di)) + m),
(inv(diagm(d)) + m) - (tmp(diagm(di)) + m) );
DLIB_TEST(equal(m + inv(diagm(d)) , tmp(diagm(di)) + m));
DLIB_TEST((m + identity_matrix<double>(3) == m + tmp(identity_matrix<double>(3))));
DLIB_TEST((m + identity_matrix<double,3>() == m + tmp(identity_matrix<double,3>())));
DLIB_TEST((m + 2*identity_matrix<double>(3) == m + 2*tmp(identity_matrix<double>(3))));
DLIB_TEST((m + 2*identity_matrix<double,3>() == m + 2*tmp(identity_matrix<double,3>())));
DLIB_TEST((m + identity_matrix<double>(3)*2 == m + 2*tmp(identity_matrix<double>(3))));
DLIB_TEST((m + identity_matrix<double,3>()*2 == m + 2*tmp(identity_matrix<double,3>())));
DLIB_TEST((identity_matrix<double>(3) + m == m + tmp(identity_matrix<double>(3))));
DLIB_TEST((identity_matrix<double,3>() + m == m + tmp(identity_matrix<double,3>())));
DLIB_TEST((2*identity_matrix<double>(3) + m == m + 2*tmp(identity_matrix<double>(3))));
DLIB_TEST((2*identity_matrix<double,3>() + m == m + 2*tmp(identity_matrix<double,3>())));
}
{
matrix<double,1,3> d(1,3), di(1,3);
matrix<double,3,3> m(3,3);
m = 1,2,3,
4,5,6,
7,8,9;
d = 1,2,3;
di = 1, 1/2.0, 1/3.0;
DLIB_TEST(equal(inv(diagm(d)) , diagm(di)));
DLIB_TEST(equal(inv(diagm(d)) , diagm(di)));
DLIB_TEST(equal(inv(diagm(d))*m , tmp(diagm(di))*m));
DLIB_TEST(equal(m*inv(diagm(d)) , m*tmp(diagm(di))));
DLIB_TEST(equal(inv(diagm(d)) + m , tmp(diagm(di)) + m));
DLIB_TEST(equal(m + inv(diagm(d)) , tmp(diagm(di)) + m));
DLIB_TEST((m + identity_matrix<double>(3) == m + tmp(identity_matrix<double>(3))));
DLIB_TEST((m + identity_matrix<double,3>() == m + tmp(identity_matrix<double,3>())));
DLIB_TEST((m + 2*identity_matrix<double>(3) == m + 2*tmp(identity_matrix<double>(3))));
DLIB_TEST((m + 2*identity_matrix<double,3>() == m + 2*tmp(identity_matrix<double,3>())));
DLIB_TEST((m + identity_matrix<double>(3)*2 == m + 2*tmp(identity_matrix<double>(3))));
DLIB_TEST((m + identity_matrix<double,3>()*2 == m + 2*tmp(identity_matrix<double,3>())));
DLIB_TEST((identity_matrix<double>(3) + m == m + tmp(identity_matrix<double>(3))));
DLIB_TEST((identity_matrix<double,3>() + m == m + tmp(identity_matrix<double,3>())));
DLIB_TEST((2*identity_matrix<double>(3) + m == m + 2*tmp(identity_matrix<double>(3))));
DLIB_TEST((2*identity_matrix<double,3>() + m == m + 2*tmp(identity_matrix<double,3>())));
}
{
matrix<double,1,0> d(1,3), di(1,3);
matrix<double,0,3> m(3,3);
m = 1,2,3,
4,5,6,
7,8,9;
d = 1,2,3;
di = 1, 1/2.0, 1/3.0;
DLIB_TEST(equal(inv(diagm(d)) , diagm(di)));
DLIB_TEST(equal(inv(diagm(d)) , diagm(di)));
DLIB_TEST(equal(inv(diagm(d))*m , tmp(diagm(di))*m));
DLIB_TEST(equal(m*inv(diagm(d)) , m*tmp(diagm(di))));
DLIB_TEST(equal(inv(diagm(d)) + m , tmp(diagm(di)) + m));
DLIB_TEST(equal(m + inv(diagm(d)) , tmp(diagm(di)) + m));
DLIB_TEST((m + identity_matrix<double>(3) == m + tmp(identity_matrix<double>(3))));
DLIB_TEST((m + identity_matrix<double,3>() == m + tmp(identity_matrix<double,3>())));
DLIB_TEST((m + 2*identity_matrix<double>(3) == m + 2*tmp(identity_matrix<double>(3))));
DLIB_TEST((m + 2*identity_matrix<double,3>() == m + 2*tmp(identity_matrix<double,3>())));
DLIB_TEST((m + identity_matrix<double>(3)*2 == m + 2*tmp(identity_matrix<double>(3))));
DLIB_TEST((m + identity_matrix<double,3>()*2 == m + 2*tmp(identity_matrix<double,3>())));
DLIB_TEST((identity_matrix<double>(3) + m == m + tmp(identity_matrix<double>(3))));
DLIB_TEST((identity_matrix<double,3>() + m == m + tmp(identity_matrix<double,3>())));
DLIB_TEST((2*identity_matrix<double>(3) + m == m + 2*tmp(identity_matrix<double>(3))));
DLIB_TEST((2*identity_matrix<double,3>() + m == m + 2*tmp(identity_matrix<double,3>())));
}
{
matrix<double,3,1> d1, d2;
d1 = 1,2,3;
d2 = 2,3,4;
matrix<double,3,3> ans;
ans = 2, 0, 0,
0, 6, 0,
0, 0, 12;
DLIB_TEST(ans == diagm(d1)*diagm(d2));
}
dlib::rand rnd;
for (int i = 0; i < 1; ++i)
{
matrix<double> d1 = randm(4,1,rnd);
matrix<double,5,1> d2 = randm(5,1,rnd);
matrix<double,4,5> m = randm(4,5,rnd);
DLIB_TEST_MSG(equal(pointwise_multiply(d1*trans(d2), m) , diagm(d1)*m*diagm(d2)),
pointwise_multiply(d1*trans(d2), m) - diagm(d1)*m*diagm(d2)
);
DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , diagm(d1)*(m*diagm(d2))));
DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , (diagm(d1)*m)*diagm(d2)));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , inv(diagm(d1))*m*inv(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , inv(diagm(d1))*(m*inv(diagm(d2)))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , (inv(diagm(d1))*m)*inv(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , inv(diagm(d1))*m*(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , inv(diagm(d1))*(m*(diagm(d2)))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , (inv(diagm(d1))*m)*(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , (diagm(d1))*m*inv(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , (diagm(d1))*(m*inv(diagm(d2)))));
DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , ((diagm(d1))*m)*inv(diagm(d2))));
}
for (int i = 0; i < 1; ++i)
{
matrix<double,4,1> d1 = randm(4,1,rnd);
matrix<double,5,1> d2 = randm(5,1,rnd);
matrix<double,4,5> m = randm(4,5,rnd);
DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , diagm(d1)*m*diagm(d2)));
DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , diagm(d1)*(m*diagm(d2))));
DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , (diagm(d1)*m)*diagm(d2)));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , inv(diagm(d1))*m*inv(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , inv(diagm(d1))*(m*inv(diagm(d2)))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , (inv(diagm(d1))*m)*inv(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , inv(diagm(d1))*m*(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , inv(diagm(d1))*(m*(diagm(d2)))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , (inv(diagm(d1))*m)*(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , (diagm(d1))*m*inv(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , (diagm(d1))*(m*inv(diagm(d2)))));
DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , ((diagm(d1))*m)*inv(diagm(d2))));
}
for (int i = 0; i < 1; ++i)
{
matrix<double,4,1> d1 = randm(4,1,rnd);
matrix<double,5,1> d2 = randm(5,1,rnd);
matrix<double,0,0> m = randm(4,5,rnd);
DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , diagm(d1)*m*diagm(d2)));
DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , diagm(d1)*(m*diagm(d2))));
DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , (diagm(d1)*m)*diagm(d2)));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , inv(diagm(d1))*m*inv(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , inv(diagm(d1))*(m*inv(diagm(d2)))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , (inv(diagm(d1))*m)*inv(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , inv(diagm(d1))*m*(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , inv(diagm(d1))*(m*(diagm(d2)))));
DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , (inv(diagm(d1))*m)*(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , (diagm(d1))*m*inv(diagm(d2))));
DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , (diagm(d1))*(m*inv(diagm(d2)))));
DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , ((diagm(d1))*m)*inv(diagm(d2))));
}
{
for (int i = 0; i < 5; ++i)
{
matrix<double> m = randm(3,4) + 1;
DLIB_TEST(equal(1.0/m , reciprocal(m)));
DLIB_TEST(equal(0.0/m , zeros_matrix<double>(3,4)));
}
}
{
matrix<int> m(2,3);
m = 1,2,3,
4,5,6;
matrix<int> M(2,3);
M = m;
DLIB_TEST(upperbound(m,6) == M);
DLIB_TEST(upperbound(m,60) == M);
DLIB_TEST(lowerbound(m,-2) == M);
DLIB_TEST(lowerbound(m,0) == M);
M = 2,2,3,
4,5,6;
DLIB_TEST(lowerbound(m,2) == M);
M = 0,0,0,
0,0,0;
DLIB_TEST(upperbound(m,0) == M);
M = 1,2,3,
3,3,3;
DLIB_TEST(upperbound(m,3) == M);
}
{
matrix<double,9,5> A = randm(9,5);
matrix<double> B = A;
orthogonalize(A);
orthogonalize(B);
DLIB_TEST(equal(A,B));
}
}
template <
long D1,
long D2,
long D3,
long D4
>
void test_conv()
{
dlog << LINFO << D1 << " " << D2 << " " << D3 << " " << D4;
matrix<int,D1,D1> a(1,1);
matrix<int,D2,D2> b(2,2);
matrix<int,D3,D3> c(3,3);
matrix<int,D4,D1> d(4,1);
a = 4;
b = 1,2,
3,4;
c = 1,2,3,
4,5,6,
7,8,9;
d = 1,
2,
3,
4;
matrix<int> temp(4,4), temp2;
temp = 1, 4, 7, 6,
7, 23, 33, 24,
19, 53, 63, 42,
21, 52, 59, 36;
DLIB_TEST(conv(b,c) == temp);
DLIB_TEST(conv(c,b) == temp);
DLIB_TEST(xcorr(c,flip(b)) == temp);
temp.set_size(2,2);
temp = 23, 33,
53, 63;
DLIB_TEST(conv_same(b,c) == temp);
DLIB_TEST(xcorr_same(b,flip(c)) == temp);
temp2.set_size(2,2);
temp2 = 63, 53,
33, 23;
DLIB_TEST(flip(temp) == temp2);
DLIB_TEST(flip(temp) == fliplr(flipud(temp)));
DLIB_TEST(conv_valid(b,c).nr() == 0);
DLIB_TEST(conv_valid(b,c).nc() == 0);
DLIB_TEST(conv_valid(c,b) == temp);
DLIB_TEST(xcorr_valid(c,flip(b)) == temp);
temp.set_size(1,1);
temp = 16;
DLIB_TEST(conv(a,a) == temp);
DLIB_TEST(conv_same(a,a) == temp);
DLIB_TEST(conv_valid(a,a) == temp);
DLIB_TEST(xcorr(a,a) == temp);
DLIB_TEST(xcorr_same(a,a) == temp);
DLIB_TEST(xcorr_valid(a,a) == temp);
temp.set_size(0,0);
DLIB_TEST(conv(temp,temp).nr() == 0);
DLIB_TEST(conv(temp,temp).nc() == 0);
DLIB_TEST(conv_same(temp,temp).nr() == 0);
DLIB_TEST(conv_same(temp,temp).nc() == 0);
DLIB_TEST_MSG(conv_valid(temp,temp).nr() == 0, conv_valid(temp,temp).nr());
DLIB_TEST(conv_valid(temp,temp).nc() == 0);
DLIB_TEST(conv(c,temp).nr() == 0);
DLIB_TEST(conv(c,temp).nc() == 0);
DLIB_TEST(conv_same(c,temp).nr() == 0);
DLIB_TEST(conv_same(c,temp).nc() == 0);
DLIB_TEST(conv_valid(c,temp).nr() == 0);
DLIB_TEST(conv_valid(c,temp).nc() == 0);
DLIB_TEST(conv(temp,c).nr() == 0);
DLIB_TEST(conv(temp,c).nc() == 0);
DLIB_TEST(conv_same(temp,c).nr() == 0);
DLIB_TEST(conv_same(temp,c).nc() == 0);
DLIB_TEST(conv_valid(temp,c).nr() == 0);
DLIB_TEST(conv_valid(temp,c).nc() == 0);
temp.set_size(5,2);
temp = 1, 2,
5, 8,
9, 14,
13, 20,
12, 16;
DLIB_TEST(conv(b,d) == temp);
DLIB_TEST(xcorr(b,flip(d)) == temp);
temp.set_size(2,2);
temp = 9, 14,
13, 20;
DLIB_TEST(conv_same(b,d) == temp);
DLIB_TEST(xcorr_same(b,flip(d)) == temp);
DLIB_TEST(conv_valid(b,d).nr() == 0);
DLIB_TEST(xcorr_valid(b,flip(d)).nr() == 0);
DLIB_TEST_MSG(conv_valid(b,d).nc() == 0, conv_valid(b,d).nc());
DLIB_TEST(xcorr_valid(b,flip(d)).nc() == 0);
temp.set_size(5,5);
temp = 1, 4, 10, 12, 9,
8, 26, 56, 54, 36,
30, 84, 165, 144, 90,
56, 134, 236, 186, 108,
49, 112, 190, 144, 81;
DLIB_TEST(conv(c,c) == temp);
DLIB_TEST(xcorr(c,flip(c)) == temp);
matrix<int> temp3 = c;
temp3 = conv(temp3,c);
DLIB_TEST(temp3 == temp);
temp3 = c;
temp3 = conv(c,temp3);
DLIB_TEST(temp3 == temp);
temp.set_size(3,3);
temp = 26, 56, 54,
84, 165, 144,
134, 236, 186;
DLIB_TEST(conv_same(c,c) == temp);
DLIB_TEST(xcorr_same(c,flip(c)) == temp);
temp3 = c;
temp3 = conv_same(c,temp3);
DLIB_TEST(temp3 == temp);
temp3 = c;
temp3 = conv_same(temp3,c);
DLIB_TEST(temp3 == temp);
temp.set_size(1,1);
temp = 165;
DLIB_TEST(conv_valid(c,c) == temp);
DLIB_TEST(xcorr_valid(c,flip(c)) == temp);
temp3 = c;
temp3 = conv_valid(c,temp3);
DLIB_TEST(temp3 == temp);
temp3 = c;
temp3 = conv_valid(temp3,c);
DLIB_TEST(temp3 == temp);
dlib::rand rnd;
for (int i = 0; i < 3; ++i)
{
matrix<complex<int> > a, b;
a = complex_matrix(matrix_cast<int>(round(20*randm(2,7,rnd))),
matrix_cast<int>(round(20*randm(2,7,rnd))));
b = complex_matrix(matrix_cast<int>(round(20*randm(3,2,rnd))),
matrix_cast<int>(round(20*randm(3,2,rnd))));
DLIB_TEST(xcorr(a,b) == conv(a, flip(conj(b))));
DLIB_TEST(xcorr_valid(a,b) == conv_valid(a, flip(conj(b))));
DLIB_TEST(xcorr_same(a,b) == conv_same(a, flip(conj(b))));
}
for (int i = 0; i < 30; ++i)
{
auto nr1 = rnd.get_integer_in_range(1,30);
auto nc1 = rnd.get_integer_in_range(1,30);
auto nr2 = rnd.get_integer_in_range(1,30);
auto nc2 = rnd.get_integer_in_range(1,30);
matrix<double> a, b;
a = randm(nr1,nc1,rnd);
b = randm(nr2,nc2,rnd);
DLIB_TEST(max(abs(xcorr(a,b) - xcorr_fft(a,b))) < 1e-12);
}
}
void test_complex()
{
matrix<complex<double> > a, b;
a = complex_matrix(linspace(1,7,7), linspace(2,8,7));
b = complex_matrix(linspace(4,10,7), linspace(2,8,7));
DLIB_TEST(mean(a) == complex<double>(4, 5));
}
void test_setsubs()
{
{
matrix<double> m(3,3);
m = 0;
set_colm(m,0) += 1;
set_rowm(m,0) += 1;
set_subm(m,1,1,2,2) += 5;
matrix<double> m2(3,3);
m2 = 2, 1, 1,
1, 5, 5,
1, 5, 5;
DLIB_TEST(m == m2);
set_colm(m,0) -= 1;
set_rowm(m,0) -= 1;
set_subm(m,1,1,2,2) -= 5;
m2 = 0;
DLIB_TEST(m == m2);
matrix<double,1,3> r;
matrix<double,3,1> c;
matrix<double,2,2> b;
r = 1,2,3;
c = 2,
3,
4;
b = 2,3,
4,5;
set_colm(m,1) += c;
set_rowm(m,1) += r;
set_subm(m,1,1,2,2) += b;
m2 = 0, 2, 0,
1, 7, 6,
0, 8, 5;
DLIB_TEST(m2 == m);
set_colm(m,1) -= c;
set_rowm(m,1) -= r;
set_subm(m,1,1,2,2) -= b;
m2 = 0;
DLIB_TEST(m2 == m);
// check that the code path for destructive aliasing works right.
m = 2*identity_matrix<double>(3);
set_colm(m,1) += m*c;
m2 = 2, 4, 0,
0, 8, 0,
0, 8, 2;
DLIB_TEST(m == m2);
m = 2*identity_matrix<double>(3);
set_colm(m,1) -= m*c;
m2 = 2, -4, 0,
0, -4, 0,
0, -8, 2;
DLIB_TEST(m == m2);
m = 2*identity_matrix<double>(3);
set_rowm(m,1) += r*m;
m2 = 2, 0, 0,
2, 6, 6,
0, 0, 2;
DLIB_TEST(m == m2);
m = 2*identity_matrix<double>(3);
set_rowm(m,1) -= r*m;
m2 = 2, 0, 0,
-2, -2, -6,
0, 0, 2;
DLIB_TEST(m == m2);
m = identity_matrix<double>(3);
const rectangle rect(0,0,1,1);
set_subm(m,rect) += subm(m,rect)*b;
m2 = 3, 3, 0,
4, 6, 0,
0, 0, 1;
DLIB_TEST(m == m2);
m = identity_matrix<double>(3);
set_subm(m,rect) -= subm(m,rect)*b;
m2 = -1, -3, 0,
-4, -4, 0,
0, 0, 1;
DLIB_TEST(m == m2);
}
{
matrix<double,1,1> a, b;
a = 2;
b = 3;
DLIB_TEST(dot(a,b) == 6);
}
{
matrix<double,1,1> a;
matrix<double,0,1> b(1);
a = 2;
b = 3;
DLIB_TEST(dot(a,b) == 6);
DLIB_TEST(dot(b,a) == 6);
}
{
matrix<double,1,1> a;
matrix<double,1,0> b(1);
a = 2;
b = 3;
DLIB_TEST(dot(a,b) == 6);
DLIB_TEST(dot(b,a) == 6);
}
}
template <typename T>
std::vector<int> tovect1(const T& m)
{
std::vector<int> temp;
for (typename T::const_iterator i = m.begin(); i != m.end(); ++i)
{
temp.push_back(*i);
}
return temp;
}
template <typename T>
std::vector<int> tovect2(const T& m)
{
std::vector<int> temp;
for (typename T::const_iterator i = m.begin(); i != m.end(); i++)
{
temp.push_back(*i);
}
return temp;
}
template <typename T>
std::vector<int> tovect3(const T& m_)
{
matrix<int> m(m_);
std::vector<int> temp;
for (matrix<int>::iterator i = m.begin(); i != m.end(); ++i)
{
temp.push_back(*i);
}
return temp;
}
template <typename T>
std::vector<int> tovect4(const T& m_)
{
matrix<int> m(m_);
std::vector<int> temp;
for (matrix<int>::iterator i = m.begin(); i != m.end(); i++)
{
temp.push_back(*i);
}
return temp;
}
void test_iterators()
{
matrix<int> m(3,2);
m = 1,2,3,
4,5,6;
std::vector<int> v1 = tovect1(m);
std::vector<int> v2 = tovect2(m);
std::vector<int> v3 = tovect3(m);
std::vector<int> v4 = tovect4(m);
std::vector<int> v5 = tovect1(m+m);
std::vector<int> v6 = tovect2(m+m);
std::vector<int> v7 = tovect3(m+m);
std::vector<int> v8 = tovect4(m+m);
std::vector<int> a1, a2;
for (int i = 1; i <= 6; ++i)
{
a1.push_back(i);
a2.push_back(i*2);
}
DLIB_TEST(max(abs(mat(v1) - mat(a1))) == 0);
DLIB_TEST(max(abs(mat(v2) - mat(a1))) == 0);
DLIB_TEST(max(abs(mat(v3) - mat(a1))) == 0);
DLIB_TEST(max(abs(mat(v4) - mat(a1))) == 0);
DLIB_TEST(max(abs(mat(v5) - mat(a2))) == 0);
DLIB_TEST(max(abs(mat(v6) - mat(a2))) == 0);
DLIB_TEST(max(abs(mat(v7) - mat(a2))) == 0);
DLIB_TEST(max(abs(mat(v8) - mat(a2))) == 0);
}
void test_linpiece()
{
matrix<double,0,1> temp = linpiece(5, linspace(-1, 9, 2));
DLIB_CASSERT(temp.size() == 1,"");
DLIB_CASSERT(std::abs(temp(0) - 6) < 1e-13,"");
temp = linpiece(5, linspace(-1, 9, 6));
DLIB_CASSERT(temp.size() == 5,"");
DLIB_CASSERT(std::abs(temp(0) - 2) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(1) - 2) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(2) - 2) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(3) - 0) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(4) - 0) < 1e-13,"");
temp = linpiece(4, linspace(-1, 9, 6));
DLIB_CASSERT(temp.size() == 5,"");
DLIB_CASSERT(std::abs(temp(0) - 2) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(1) - 2) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(2) - 1) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(3) - 0) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(4) - 0) < 1e-13,"");
temp = linpiece(40, linspace(-1, 9, 6));
DLIB_CASSERT(temp.size() == 5,"");
DLIB_CASSERT(std::abs(temp(0) - 2) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(1) - 2) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(2) - 2) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(3) - 2) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(4) - 2) < 1e-13,"");
temp = linpiece(-40, linspace(-1, 9, 6));
DLIB_CASSERT(temp.size() == 5,"");
DLIB_CASSERT(std::abs(temp(0) - 0) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(1) - 0) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(2) - 0) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(3) - 0) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(4) - 0) < 1e-13,"");
temp = linpiece(0, linspace(-1, 9, 6));
DLIB_CASSERT(temp.size() == 5,"");
DLIB_CASSERT(std::abs(temp(0) - 1) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(1) - 0) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(2) - 0) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(3) - 0) < 1e-13,"");
DLIB_CASSERT(std::abs(temp(4) - 0) < 1e-13,"");
}
class matrix_tester : public tester
{
public:
matrix_tester (
) :
tester ("test_matrix4",
"Runs tests on the scale_rows and scale_columns functions.")
{}
void perform_test (
)
{
test_iterators();
test_setsubs();
test_conv<0,0,0,0>();
test_conv<1,2,3,4>();
test_stuff();
for (int i = 0; i < 10; ++i)
matrix_test();
test_complex();
test_linpiece();
}
} a;
}
| 32.514286 | 127 | 0.445436 |
4416385c2761b7381dc71d4febc132e85afb83a3 | 1,993 | cc | C++ | src/flpr/Stmt_Tree.cc | apthorpe/FLPR | 9620f28ad1cde553eb8ffa7f2685683763530acb | [
"BSD-3-Clause"
] | null | null | null | src/flpr/Stmt_Tree.cc | apthorpe/FLPR | 9620f28ad1cde553eb8ffa7f2685683763530acb | [
"BSD-3-Clause"
] | null | null | null | src/flpr/Stmt_Tree.cc | apthorpe/FLPR | 9620f28ad1cde553eb8ffa7f2685683763530acb | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2019, Triad National Security, LLC. All rights reserved.
This is open source software; you can redistribute it and/or modify it
under the terms of the BSD-3 License. If software is modified to produce
derivative works, such modified software should be clearly marked, so as
not to confuse it with the version available from LANL. Full text of the
BSD-3 License can be found in the LICENSE file of the repository.
*/
/*!
\file Stmt_Tree.cc
*/
#include "flpr/Stmt_Tree.hh"
#include <cassert>
#include <ostream>
namespace FLPR {
namespace Stmt {
void cover_branches(Stmt_Tree::reference st) {
// Scan to first non-empty branch
auto b1 = st.branches().begin();
while (b1 != st.branches().end() && (*b1)->token_range.empty())
++b1;
if (b1 == st.branches().end())
return; // No valid ranges to cover
st->token_range.clear();
st->token_range.set_it((*b1)->token_range.it());
st->token_range.push_back((*b1)->token_range);
for (b1 = std::next(b1); b1 != st.branches().end(); ++b1) {
st->token_range.push_back((*b1)->token_range);
}
}
void hoist_back(Stmt_Tree &t, Stmt_Tree &&donor) {
if (!donor)
return;
if ((*donor)->syntag == Syntax_Tags::HOIST) {
for (auto &&b : donor->branches()) {
auto new_loc = t->branches().emplace(t->branches().end(), std::move(b));
new_loc->link(new_loc, t.root());
}
} else {
t.graft_back(std::move(donor));
}
}
std::ostream &operator<<(std::ostream &os, ST_Node_Data const &nd) {
return Syntax_Tags::print(os, nd.syntag);
}
int get_label_do_label(Stmt_Tree const &t) {
auto c = t.ccursor();
if (FLPR::Syntax_Tags::SG_DO_STMT == c->syntag)
c.down();
if (FLPR::Syntax_Tags::SG_LABEL_DO_STMT != c->syntag) {
return 0;
}
c.down().next().down();
assert(FLPR::Syntax_Tags::SG_INT_LITERAL_CONSTANT == c->syntag);
assert(c->token_range.size() == 1);
return std::stoi(c->token_range.front().text());
}
} // namespace Stmt
} // namespace FLPR
| 29.308824 | 78 | 0.658304 |
4417d0ef2e9a7297d1318a1d2c05a48759ea1c43 | 27,908 | cpp | C++ | src/openms/source/FORMAT/IdXMLFile.cpp | liangoaix/OpenMS | cccbc5d872320f197091596db275f35b4d0458cd | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/source/FORMAT/IdXMLFile.cpp | liangoaix/OpenMS | cccbc5d872320f197091596db275f35b4d0458cd | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/source/FORMAT/IdXMLFile.cpp | liangoaix/OpenMS | cccbc5d872320f197091596db275f35b4d0458cd | [
"Zlib",
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2013.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Andreas Bertsch $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/PrecisionWrapper.h>
#include <iostream>
#include <fstream>
#include <limits>
using namespace std;
using namespace OpenMS::Internal;
namespace OpenMS
{
IdXMLFile::IdXMLFile() :
XMLHandler("", "1.2"),
XMLFile("/SCHEMAS/IdXML_1_2.xsd", "1.2"),
last_meta_(0),
document_id_(),
prot_id_in_run_(false)
{
}
void IdXMLFile::load(const String& filename, vector<ProteinIdentification>& protein_ids, vector<PeptideIdentification>& peptide_ids)
{
String document_id;
load(filename, protein_ids, peptide_ids, document_id);
}
void IdXMLFile::load(const String& filename, vector<ProteinIdentification>& protein_ids,
vector<PeptideIdentification>& peptide_ids, String& document_id)
{
//Filename for error messages in XMLHandler
file_ = filename;
protein_ids.clear();
peptide_ids.clear();
prot_ids_ = &protein_ids;
pep_ids_ = &peptide_ids;
document_id_ = &document_id;
parse_(filename, this);
//reset members
prot_ids_ = 0;
pep_ids_ = 0;
last_meta_ = 0;
parameters_.clear();
param_ = ProteinIdentification::SearchParameters();
id_ = "";
prot_id_ = ProteinIdentification();
pep_id_ = PeptideIdentification();
prot_hit_ = ProteinHit();
pep_hit_ = PeptideHit();
proteinid_to_accession_.clear();
}
void IdXMLFile::store(String filename, const vector<ProteinIdentification>& protein_ids, const vector<PeptideIdentification>& peptide_ids, const String& document_id)
{
//open stream
std::ofstream os(filename.c_str());
if (!os)
{
throw Exception::UnableToCreateFile(__FILE__, __LINE__, __PRETTY_FUNCTION__, filename);
}
os.precision(writtenDigits<double>(0.0));
//write header
os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
os << "<?xml-stylesheet type=\"text/xsl\" href=\"http://open-ms.sourceforge.net/XSL/IdXML.xsl\" ?>\n";
os << "<IdXML version=\"" << getVersion() << "\"";
if (document_id != "")
{
os << " id=\"" << document_id << "\"";
}
os << " xsi:noNamespaceSchemaLocation=\"http://open-ms.sourceforge.net/SCHEMAS/IdXML_1_2.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n";
//look up different search parameters
vector<ProteinIdentification::SearchParameters> params;
for (vector<ProteinIdentification>::const_iterator it = protein_ids.begin(); it != protein_ids.end(); ++it)
{
if (find(params.begin(), params.end(), it->getSearchParameters()) == params.end())
{
params.push_back(it->getSearchParameters());
}
}
//write search parameters
for (Size i = 0; i != params.size(); ++i)
{
os << "\t<SearchParameters "
<< "id=\"SP_" << i << "\" "
<< "db=\"" << writeXMLEscape(params[i].db) << "\" "
<< "db_version=\"" << writeXMLEscape(params[i].db_version) << "\" "
<< "taxonomy=\"" << writeXMLEscape(params[i].taxonomy) << "\" ";
if (params[i].mass_type == ProteinIdentification::MONOISOTOPIC)
{
os << "mass_type=\"monoisotopic\" ";
}
else if (params[i].mass_type == ProteinIdentification::AVERAGE)
{
os << "mass_type=\"average\" ";
}
os << "charges=\"" << params[i].charges << "\" ";
if (params[i].enzyme == ProteinIdentification::TRYPSIN)
{
os << "enzyme=\"trypsin\" ";
}
if (params[i].enzyme == ProteinIdentification::PEPSIN_A)
{
os << "enzyme=\"pepsin_a\" ";
}
if (params[i].enzyme == ProteinIdentification::PROTEASE_K)
{
os << "enzyme=\"protease_k\" ";
}
if (params[i].enzyme == ProteinIdentification::CHYMOTRYPSIN)
{
os << "enzyme=\"chymotrypsin\" ";
}
else if (params[i].enzyme == ProteinIdentification::NO_ENZYME)
{
os << "enzyme=\"no_enzyme\" ";
}
else if (params[i].enzyme == ProteinIdentification::UNKNOWN_ENZYME)
{
os << "enzyme=\"unknown_enzyme\" ";
}
os << "missed_cleavages=\"" << params[i].missed_cleavages << "\" "
<< "precursor_peak_tolerance=\"" << params[i].precursor_tolerance << "\" "
<< "peak_mass_tolerance=\"" << params[i].peak_mass_tolerance << "\" "
<< ">\n";
//modifications
for (Size j = 0; j != params[i].fixed_modifications.size(); ++j)
{
os << "\t\t<FixedModification name=\"" << writeXMLEscape(params[i].fixed_modifications[j]) << "\" />\n";
//Add MetaInfo, when modifications has it (Andreas)
}
for (Size j = 0; j != params[i].variable_modifications.size(); ++j)
{
os << "\t\t<VariableModification name=\"" << writeXMLEscape(params[i].variable_modifications[j]) << "\" />\n";
//Add MetaInfo, when modifications has it (Andreas)
}
writeUserParam_("UserParam", os, params[i], 4);
os << "\t</SearchParameters>\n";
}
//empty search parameters
if (params.empty())
{
os << "<SearchParameters charges=\"+0, +0\" id=\"ID_1\" db_version=\"0\" mass_type=\"monoisotopic\" peak_mass_tolerance=\"0.0\" precursor_peak_tolerance=\"0.0\" db=\"Unknown\"/>\n";
}
UInt prot_count = 0;
map<String, UInt> accession_to_id;
//Identifiers of protein identifications that are already written
vector<String> done_identifiers;
//write ProteinIdentification Runs
for (Size i = 0; i < protein_ids.size(); ++i)
{
done_identifiers.push_back(protein_ids[i].getIdentifier());
os << "\t<IdentificationRun ";
os << "date=\"" << protein_ids[i].getDateTime().getDate() << "T" << protein_ids[i].getDateTime().getTime() << "\" ";
os << "search_engine=\"" << writeXMLEscape(protein_ids[i].getSearchEngine()) << "\" ";
os << "search_engine_version=\"" << writeXMLEscape(protein_ids[i].getSearchEngineVersion()) << "\" ";
//identifier
for (Size j = 0; j != params.size(); ++j)
{
if (params[j] == protein_ids[i].getSearchParameters())
{
os << "search_parameters_ref=\"SP_" << j << "\" ";
break;
}
}
os << ">\n";
os << "\t\t<ProteinIdentification ";
os << "score_type=\"" << writeXMLEscape(protein_ids[i].getScoreType()) << "\" ";
if (protein_ids[i].isHigherScoreBetter())
{
os << "higher_score_better=\"true\" ";
}
else
{
os << "higher_score_better=\"false\" ";
}
os << "significance_threshold=\"" << protein_ids[i].getSignificanceThreshold() << "\" >\n";
//write protein hits
for (Size j = 0; j < protein_ids[i].getHits().size(); ++j)
{
os << "\t\t\t<ProteinHit ";
os << "id=\"PH_" << prot_count << "\" ";
accession_to_id[protein_ids[i].getHits()[j].getAccession()] = prot_count++;
os << "accession=\"" << writeXMLEscape(protein_ids[i].getHits()[j].getAccession()) << "\" ";
os << "score=\"" << protein_ids[i].getHits()[j].getScore() << "\" ";
// os << "coverage=\"" << protein_ids[i].getHits()[j].getCoverage()
// << "\" ";
os << "sequence=\"" << writeXMLEscape(protein_ids[i].getHits()[j].getSequence()) << "\" >\n";
writeUserParam_("UserParam", os, protein_ids[i].getHits()[j], 4);
os << "\t\t\t</ProteinHit>\n";
}
// add ProteinGroup info to metavalues (hack)
MetaInfoInterface meta = protein_ids[i];
addProteinGroups_(meta, protein_ids[i].getProteinGroups(),
"protein_group", accession_to_id);
addProteinGroups_(meta, protein_ids[i].getIndistinguishableProteins(),
"indistinguishable_proteins", accession_to_id);
writeUserParam_("UserParam", os, meta, 3);
os << "\t\t</ProteinIdentification>\n";
//write PeptideIdentifications
Size count_wrong_id(0);
Size count_empty(0);
for (Size l = 0; l < peptide_ids.size(); ++l)
{
if (peptide_ids[l].getIdentifier() != protein_ids[i].getIdentifier())
{
++count_wrong_id;
continue;
}
else if (peptide_ids[l].getHits().size() == 0)
{
++count_empty;
continue;
}
os << "\t\t<PeptideIdentification ";
os << "score_type=\"" << writeXMLEscape(peptide_ids[l].getScoreType()) << "\" ";
if (peptide_ids[l].isHigherScoreBetter())
{
os << "higher_score_better=\"true\" ";
}
else
{
os << "higher_score_better=\"false\" ";
}
os << "significance_threshold=\"" << peptide_ids[l].getSignificanceThreshold() << "\" ";
// mz
if (peptide_ids[l].hasMZ())
{
os << "MZ=\"" << peptide_ids[l].getMZ() << "\" ";
}
// rt
if (peptide_ids[l].hasRT())
{
os << "RT=\"" << peptide_ids[l].getRT() << "\" ";
}
// spectrum_reference
DataValue dv = peptide_ids[l].getMetaValue("spectrum_reference");
if (dv != DataValue::EMPTY)
{
os << "spectrum_reference=\"" << writeXMLEscape(dv.toString()) << "\" ";
}
os << ">\n";
// write peptide hits
for (Size j = 0; j < peptide_ids[l].getHits().size(); ++j)
{
os << "\t\t\t<PeptideHit ";
os << "score=\"" << precisionWrapper(peptide_ids[l].getHits()[j].getScore()) << "\" ";
os << "sequence=\"" << peptide_ids[l].getHits()[j].getSequence() << "\" ";
os << "charge=\"" << peptide_ids[l].getHits()[j].getCharge() << "\" ";
if (peptide_ids[l].getHits()[j].getAABefore() != ' ')
{
os << "aa_before=\"" << writeXMLEscape(peptide_ids[l].getHits()[j].getAABefore()) << "\" ";
}
if (peptide_ids[l].getHits()[j].getAAAfter() != ' ')
{
os << "aa_after=\"" << writeXMLEscape(peptide_ids[l].getHits()[j].getAAAfter()) << "\" ";
}
if (peptide_ids[l].getHits()[j].getProteinAccessions().size() != 0)
{
String accs = "";
for (Size m = 0; m < peptide_ids[l].getHits()[j].getProteinAccessions().size(); ++m)
{
if (accs != "")
{
accs = accs + " ";
}
accs = accs + "PH_" + accession_to_id[peptide_ids[l].getHits()[j].getProteinAccessions()[m]];
}
os << "protein_refs=\"" << accs << "\" ";
}
os << ">\n";
writeUserParam_("UserParam", os, peptide_ids[l].getHits()[j], 4);
os << "\t\t\t</PeptideHit>\n";
}
// do not write "spectrum_reference" since it is written as attribute already
MetaInfoInterface tmp = peptide_ids[l];
tmp.removeMetaValue("spectrum_reference");
writeUserParam_("UserParam", os, tmp, 3);
os << "\t\t</PeptideIdentification>\n";
}
os << "\t</IdentificationRun>\n";
// on more than one protein Ids (=runs) there must be wrong mappings and the message would be useless. However, a single run should not have wrong mappings!
if (count_wrong_id && protein_ids.size() == 1) LOG_WARN << "Omitted writing of " << count_wrong_id << " peptide identifications due to wrong protein mapping." << std::endl;
if (count_empty) LOG_WARN << "Omitted writing of " << count_empty << " peptide identifications due to empty hits." << std::endl;
}
//empty protein ids parameters
if (protein_ids.empty())
{
os << "<IdentificationRun date=\"1900-01-01T01:01:01.0Z\" search_engine=\"Unknown\" search_parameters_ref=\"ID_1\" search_engine_version=\"0\"/>\n";
}
for (Size i = 0; i < peptide_ids.size(); ++i)
{
if (find(done_identifiers.begin(), done_identifiers.end(), peptide_ids[i].getIdentifier()) == done_identifiers.end())
{
warning(STORE, String("Omitting peptide identification because of missing ProteinIdentification with identifier '") + peptide_ids[i].getIdentifier() + "' while writing '" + filename + "'!");
}
}
//write footer
os << "</IdXML>\n";
//close stream
os.close();
//reset members
prot_ids_ = 0;
pep_ids_ = 0;
last_meta_ = 0;
parameters_.clear();
param_ = ProteinIdentification::SearchParameters();
id_ = "";
prot_id_ = ProteinIdentification();
pep_id_ = PeptideIdentification();
prot_hit_ = ProteinHit();
pep_hit_ = PeptideHit();
proteinid_to_accession_.clear();
}
void IdXMLFile::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes)
{
String tag = sm_.convert(qname);
//START
if (tag == "IdXML")
{
//check file version against schema version
String file_version = "";
prot_id_in_run_ = false;
optionalAttributeAsString_(file_version, attributes, "version");
if (file_version == "")
file_version = "1.0"; //default version is 1.0
if (file_version.toDouble() > version_.toDouble())
{
warning(LOAD, "The XML file (" + file_version + ") is newer than the parser (" + version_ + "). This might lead to undefined program behavior.");
}
//document id
String document_id = "";
optionalAttributeAsString_(document_id, attributes, "id");
(*document_id_) = document_id;
}
//SEARCH PARAMETERS
else if (tag == "SearchParameters")
{
//store id
id_ = attributeAsString_(attributes, "id");
//reset parameters
param_ = ProteinIdentification::SearchParameters();
//load parameters
param_.db = attributeAsString_(attributes, "db");
param_.db_version = attributeAsString_(attributes, "db_version");
optionalAttributeAsString_(param_.taxonomy, attributes, "taxonomy");
param_.charges = attributeAsString_(attributes, "charges");
optionalAttributeAsUInt_(param_.missed_cleavages, attributes, "missed_cleavages");
param_.peak_mass_tolerance = attributeAsDouble_(attributes, "peak_mass_tolerance");
param_.precursor_tolerance = attributeAsDouble_(attributes, "precursor_peak_tolerance");
//mass type
String mass_type = attributeAsString_(attributes, "mass_type");
if (mass_type == "monoisotopic")
{
param_.mass_type = ProteinIdentification::MONOISOTOPIC;
}
else if (mass_type == "average")
{
param_.mass_type = ProteinIdentification::AVERAGE;
}
//enzyme
String enzyme;
optionalAttributeAsString_(enzyme, attributes, "enzyme");
if (enzyme == "trypsin")
{
param_.enzyme = ProteinIdentification::TRYPSIN;
}
else if (enzyme == "pepsin_a")
{
param_.enzyme = ProteinIdentification::PEPSIN_A;
}
else if (enzyme == "protease_k")
{
param_.enzyme = ProteinIdentification::PROTEASE_K;
}
else if (enzyme == "chymotrypsin")
{
param_.enzyme = ProteinIdentification::CHYMOTRYPSIN;
}
else if (enzyme == "no_enzyme")
{
param_.enzyme = ProteinIdentification::NO_ENZYME;
}
else if (enzyme == "unknown_enzyme")
{
param_.enzyme = ProteinIdentification::UNKNOWN_ENZYME;
}
last_meta_ = ¶m_;
}
else if (tag == "FixedModification")
{
param_.fixed_modifications.push_back(attributeAsString_(attributes, "name"));
//change this line as soon as there is a MetaInfoInterface for modifications (Andreas)
last_meta_ = 0;
}
else if (tag == "VariableModification")
{
param_.variable_modifications.push_back(attributeAsString_(attributes, "name"));
//change this line as soon as there is a MetaInfoInterface for modifications (Andreas)
last_meta_ = 0;
}
// RUN
else if (tag == "IdentificationRun")
{
pep_id_ = PeptideIdentification();
prot_id_ = ProteinIdentification();
prot_id_.setSearchEngine(attributeAsString_(attributes, "search_engine"));
prot_id_.setSearchEngineVersion(attributeAsString_(attributes, "search_engine_version"));
//search parameters
String ref = attributeAsString_(attributes, "search_parameters_ref");
if (parameters_.find(ref) == parameters_.end())
{
fatalError(LOAD, String("Invalid search parameters reference '") + ref + "'");
}
prot_id_.setSearchParameters(parameters_[ref]);
//date
prot_id_.setDateTime(DateTime::fromString(String(attributeAsString_(attributes, "date")).toQString(), "yyyy-MM-ddThh:mm:ss"));
//set identifier
prot_id_.setIdentifier(prot_id_.getSearchEngine() + '_' + attributeAsString_(attributes, "date"));
}
//PROTEINS
else if (tag == "ProteinIdentification")
{
prot_id_.setScoreType(attributeAsString_(attributes, "score_type"));
//optional significance threshold
double tmp(0.0);
optionalAttributeAsDouble_(tmp, attributes, "significance_threshold");
if (tmp != 0.0)
{
prot_id_.setSignificanceThreshold(tmp);
}
//score orientation
prot_id_.setHigherScoreBetter(asBool_(attributeAsString_(attributes, "higher_score_better")));
last_meta_ = &prot_id_;
}
else if (tag == "ProteinHit")
{
prot_hit_ = ProteinHit();
String accession = attributeAsString_(attributes, "accession");
prot_hit_.setAccession(accession);
prot_hit_.setScore(attributeAsDouble_(attributes, "score"));
//sequence
String tmp;
optionalAttributeAsString_(tmp, attributes, "sequence");
prot_hit_.setSequence(tmp);
last_meta_ = &prot_hit_;
//insert id and accession to map
proteinid_to_accession_[attributeAsString_(attributes, "id")] = accession;
}
//PEPTIDES
else if (tag == "PeptideIdentification")
{
// check whether a prot id has been given, add "empty" one to list else
if (!prot_id_in_run_)
{
prot_ids_->push_back(prot_id_);
prot_id_in_run_ = true; // set to true, cause we have created one; will be reset for next run
}
//set identifier
pep_id_.setIdentifier(prot_ids_->back().getIdentifier());
pep_id_.setScoreType(attributeAsString_(attributes, "score_type"));
//optional significance threshold
double tmp(0.0);
optionalAttributeAsDouble_(tmp, attributes, "significance_threshold");
if (tmp != 0.0)
{
pep_id_.setSignificanceThreshold(tmp);
}
//score orientation
pep_id_.setHigherScoreBetter(asBool_(attributeAsString_(attributes, "higher_score_better")));
//MZ
double tmp2 = -numeric_limits<double>::max();
optionalAttributeAsDouble_(tmp2, attributes, "MZ");
if (tmp2 != -numeric_limits<double>::max())
{
pep_id_.setMZ(tmp2);
}
//RT
tmp2 = -numeric_limits<double>::max();
optionalAttributeAsDouble_(tmp2, attributes, "RT");
if (tmp2 != -numeric_limits<double>::max())
{
pep_id_.setRT(tmp2);
}
Int tmp3 = -numeric_limits<Int>::max();
optionalAttributeAsInt_(tmp3, attributes, "spectrum_reference");
if (tmp3 != -numeric_limits<Int>::max())
{
pep_id_.setMetaValue("spectrum_reference", tmp3);
}
last_meta_ = &pep_id_;
}
else if (tag == "PeptideHit")
{
pep_hit_ = PeptideHit();
pep_hit_.setCharge(attributeAsInt_(attributes, "charge"));
pep_hit_.setScore(attributeAsDouble_(attributes, "score"));
pep_hit_.setSequence(AASequence::fromString(String(attributeAsString_(attributes, "sequence"))));
//aa_before
String tmp;
optionalAttributeAsString_(tmp, attributes, "aa_before");
if (!tmp.empty())
{
pep_hit_.setAABefore(tmp[0]);
}
//aa_after
tmp = "";
optionalAttributeAsString_(tmp, attributes, "aa_after");
if (!tmp.empty())
{
pep_hit_.setAAAfter(tmp[0]);
}
//parse optional protein ids to determine accessions
const XMLCh* refs = attributes.getValue(sm_.convert("protein_refs"));
if (refs != 0)
{
String accession_string = sm_.convert(refs);
accession_string.trim();
vector<String> accessions;
accession_string.split(' ', accessions);
if (accession_string != "" && accessions.empty())
{
accessions.push_back(accession_string);
}
for (vector<String>::const_iterator it = accessions.begin(); it != accessions.end(); ++it)
{
map<String, String>::const_iterator it2 = proteinid_to_accession_.find(*it);
if (it2 != proteinid_to_accession_.end())
{
pep_hit_.addProteinAccession(it2->second);
}
else
{
fatalError(LOAD, String("Invalid protein reference '") + *it + "'");
}
}
}
last_meta_ = &pep_hit_;
}
//USERPARAM
else if (tag == "UserParam")
{
if (last_meta_ == 0)
{
fatalError(LOAD, "Unexpected tag 'UserParam'!");
}
String name = attributeAsString_(attributes, "name");
String type = attributeAsString_(attributes, "type");
String value = attributeAsString_(attributes, "value");
if (type == "string")
{
last_meta_->setMetaValue(name, value);
}
else if (type == "float")
{
last_meta_->setMetaValue(name, value.toDouble());
}
else if (type == "int")
{
last_meta_->setMetaValue(name, value.toInt());
}
else
{
fatalError(LOAD, String("Invalid UserParam type '") + type + "' of parameter '" + name + "'");
}
}
}
void IdXMLFile::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
String tag = sm_.convert(qname);
// START
if (tag == "IdXML")
{
prot_id_in_run_ = false;
}
// SEARCH PARAMETERS
else if (tag == "SearchParameters")
{
last_meta_ = 0;
parameters_[id_] = param_;
}
else if (tag == "FixedModification")
{
last_meta_ = ¶m_;
}
else if (tag == "VariableModification")
{
last_meta_ = ¶m_;
}
// PROTEIN IDENTIFICATIONS
else if (tag == "ProteinIdentification")
{
// post processing of ProteinGroups (hack)
getProteinGroups_(prot_id_.getProteinGroups(), "protein_group");
getProteinGroups_(prot_id_.getIndistinguishableProteins(),
"indistinguishable_proteins");
prot_ids_->push_back(prot_id_);
prot_id_ = ProteinIdentification();
last_meta_ = 0;
prot_id_in_run_ = true;
}
else if (tag == "IdentificationRun")
{
if (prot_ids_->size() == 0)
prot_ids_->push_back(prot_id_); // add empty <ProteinIdentification> if there was none so far (thats where the IdentificationRun parameters are stored)
prot_id_ = ProteinIdentification();
last_meta_ = 0;
prot_id_in_run_ = false;
}
else if (tag == "ProteinHit")
{
prot_id_.insertHit(prot_hit_);
last_meta_ = &prot_id_;
}
//PEPTIDES
else if (tag == "PeptideIdentification")
{
pep_ids_->push_back(pep_id_);
pep_id_ = PeptideIdentification();
last_meta_ = 0;
}
else if (tag == "PeptideHit")
{
pep_id_.insertHit(pep_hit_);
last_meta_ = &pep_id_;
}
}
void IdXMLFile::addProteinGroups_(
MetaInfoInterface& meta, const vector<ProteinIdentification::ProteinGroup>&
groups, const String& group_name, const map<String, UInt>& accession_to_id)
{
for (Size g = 0; g < groups.size(); ++g)
{
String name = group_name + "_" + String(g);
if (meta.metaValueExists(name))
{
warning(LOAD, String("Metavalue '") + name + "' already exists. Overwriting...");
}
String accessions;
for (StringList::const_iterator acc_it = groups[g].accessions.begin();
acc_it != groups[g].accessions.end(); ++acc_it)
{
if (acc_it != groups[g].accessions.begin())
accessions += ",";
map<String, UInt>::const_iterator pos = accession_to_id.find(*acc_it);
if (pos != accession_to_id.end())
{
accessions += "PH_" + String(pos->second);
}
else
{
fatalError(LOAD, String("Invalid protein reference '") + *acc_it + "'");
}
}
String value = String(groups[g].probability) + "," + accessions;
meta.setMetaValue(name, value);
}
}
void IdXMLFile::getProteinGroups_(vector<ProteinIdentification::ProteinGroup>&
groups, const String& group_name)
{
groups.clear();
Size g_id = 0;
String current_meta = group_name + "_" + String(g_id);
while (last_meta_->metaValueExists(current_meta))
{
// convert to proper ProteinGroup
ProteinIdentification::ProteinGroup g;
StringList values;
String(last_meta_->getMetaValue(current_meta)).split(',', values);
if (values.size() < 2)
{
fatalError(LOAD, String("Invalid UserParam for ProteinGroups (not enough values)'"));
}
g.probability = values[0].toDouble();
for (Size i_ind = 1; i_ind < values.size(); ++i_ind)
{
g.accessions.push_back(proteinid_to_accession_[values[i_ind]]);
}
groups.push_back(g);
last_meta_->removeMetaValue(current_meta);
current_meta = group_name + "_" + String(++g_id);
}
}
} // namespace OpenMS
| 35.326582 | 198 | 0.597212 |
441b00f8c3305aaf2d905c922a5aa42be9464bb5 | 6,510 | cpp | C++ | src/utils.cpp | imikejackson/bingocpp | 6ba00a490c8cb46edebfd78f56b1604a76d668e9 | [
"Apache-2.0"
] | 13 | 2019-03-14T09:54:02.000Z | 2021-09-26T14:01:30.000Z | src/utils.cpp | imikejackson/bingocpp | 6ba00a490c8cb46edebfd78f56b1604a76d668e9 | [
"Apache-2.0"
] | 35 | 2019-08-29T19:12:05.000Z | 2021-07-15T22:17:53.000Z | src/utils.cpp | imikejackson/bingocpp | 6ba00a490c8cb46edebfd78f56b1604a76d668e9 | [
"Apache-2.0"
] | 9 | 2018-10-18T02:43:03.000Z | 2021-09-02T22:08:39.000Z | /*!
* \file utils.cc
*
* \author Ethan Adams
* \date
*
* This file contains utility functions for doing and testing
* sybolic regression problems in the bingo package
*/
#include <vector>
#include <numeric>
#include "BingoCpp/utils.h"
namespace bingo {
const int kPartialWindowSize = 7;
const int kPartialEdgeSize = 3;
const int kDerivativeOrder = 1;
void set_break_points(const Eigen::ArrayXXd &x,
std::vector<int> *break_points) {
for (int i = 0; i < x.rows(); ++i) {
if (std::isnan(x(i))) {
break_points->push_back(i);
}
}
break_points->push_back(x.rows());
}
void update_return_values (int start,
const Eigen::ArrayXXd &x_segment,
const Eigen::ArrayXXd &time_deriv,
Eigen::ArrayXXd *x_return,
Eigen::ArrayXXd *time_deriv_return) {
if (start == 0) {
x_return->resize(x_segment.rows(), x_segment.cols());
*x_return << x_segment;
time_deriv_return->resize(time_deriv.rows(), time_deriv.cols());
*time_deriv_return << time_deriv;
} else {
Eigen::ArrayXXd x_temp = *x_return;
x_return->resize(x_return->rows() + x_segment.rows(), x_return->cols());
*x_return << x_temp, x_segment;
Eigen::ArrayXXd deriv_temp = *time_deriv_return;
time_deriv_return->resize(time_deriv_return->rows() + time_deriv.rows(),
time_deriv_return->cols());
*time_deriv_return << deriv_temp, time_deriv;
}
}
Eigen::ArrayXXd shave_edges_and_nan_from_array (
const Eigen::ArrayXXd &filtered_data) {
return filtered_data.block(kPartialEdgeSize, 0,
filtered_data.rows() - kPartialWindowSize, filtered_data.cols());
}
InputAndDeriviative CalculatePartials(const Eigen::ArrayXXd &x) {
std::vector<int> break_points;
set_break_points(x, &break_points);
int start = 0;
int return_value_rows = (x.rows() - kPartialEdgeSize) * break_points.size();
Eigen::ArrayXXd x_return(return_value_rows, x.cols());
Eigen::ArrayXXd time_deriv_return(x_return.rows(), x_return.cols());
for (std::vector<int>::iterator break_point = break_points.begin();
break_point != break_points.end();
break_point ++) {
Eigen::ArrayXXd x_segment = x.block(start, 0,
*break_point - start,
x.cols());
Eigen::ArrayXXd time_deriv(x_segment.rows(), x_segment.cols());
for (int col = 0; col < x_segment.cols(); col ++) {
time_deriv.col(col) = SavitzkyGolay(x_segment.col(col),
kPartialWindowSize, kPartialEdgeSize, kDerivativeOrder);
}
Eigen::ArrayXXd deriv_temp = shave_edges_and_nan_from_array(time_deriv);
Eigen::ArrayXXd x_temp = shave_edges_and_nan_from_array(x_segment);
update_return_values(start, x_temp, deriv_temp, &x_return, &time_deriv_return);
start = *break_point + 1;
}
return std::make_pair(x_return, time_deriv_return);
}
double GramPoly(double eval_point,
double num_points,
double polynomial_order,
double derivative_order) {
double result = 0;
if (polynomial_order > 0) {
result = (4. * polynomial_order - 2.) /
(polynomial_order * (2. * num_points - polynomial_order + 1.)) *
(eval_point *
GramPoly(eval_point, num_points,
polynomial_order - 1.,
derivative_order)
+
derivative_order *
GramPoly(eval_point, num_points,
polynomial_order - 1.,
derivative_order - 1.))
-
((polynomial_order - 1.) * (2. * num_points + polynomial_order)) /
(polynomial_order * (2. * num_points - polynomial_order + 1.)) *
GramPoly(eval_point, num_points,
polynomial_order - 2,
derivative_order);
} else if (polynomial_order == 0 && derivative_order == 0) {
result = 1.;
} else {
result = 0.;
}
return result;
}
double GenFact(double a, double b) {
int fact = 1;
for (int i = a - b + 1; i < a + 1; ++i) {
fact *= i;
}
return fact;
}
double GramWeight(double eval_point_start,
double eval_point_end,
double num_points,
double ploynomial_order,
double derivative_order) {
double weight = 0;
for (int i = 0; i < ploynomial_order + 1; ++i) {
weight += (2. * i + 1.) * GenFact(2. * num_points, i) /
GenFact(2. * num_points + i + 1, i + 1) *
GramPoly(eval_point_start, num_points, i, 0) *
GramPoly(eval_point_end, num_points, i, derivative_order);
}
return weight;
}
Eigen::ArrayXXd convolution(const Eigen::ArrayXXd &data_points,
int half_filter_size,
const Eigen::ArrayXXd &weights) {
int data_points_center = 0;
int w_ind = 0;
int data_points_len = data_points.rows();
Eigen::ArrayXXd convolution(data_points_len, 1);
for (int i = 0; i < data_points_len; ++i) {
if (i < half_filter_size) {
data_points_center = half_filter_size;
w_ind = i;
} else if (data_points_len - i <= half_filter_size) {
data_points_center = data_points_len - half_filter_size - 1;
w_ind = 2 * half_filter_size + 1 - (data_points_len - i);
} else {
data_points_center = i;
w_ind = half_filter_size;
}
convolution(i) = 0;
for (int j = half_filter_size * -1; j < half_filter_size + 1; ++j) {
convolution(i) += data_points(data_points_center + j)
* weights(j + half_filter_size, w_ind);
}
}
return convolution;
}
Eigen::ArrayXXd SavitzkyGolay(Eigen::ArrayXXd y,
int window_size,
int polynomial_order,
int derivative_order) {
int m = (window_size - 1) / 2;
Eigen::ArrayXXd weights(2 * m + 1, 2 * m + 1);
for (int i = m * -1; i < m + 1; ++i) {
for (int j = m * -1; j < m + 1; ++j) {
weights(i + m, j + m) =
GramWeight(i, j, m, polynomial_order, derivative_order);
}
}
return convolution(y, m, weights);
}
} // namespace bingo | 34.812834 | 84 | 0.57235 |
441b4b5e949c2f83acb085cd7d0de23fc52b0032 | 4,831 | hpp | C++ | src/xalanc/XSLT/ElemVariable.hpp | ulisesten/xalanc | a722de08e61ce66965c4a828242f7d1250950621 | [
"Apache-2.0"
] | 24 | 2015-07-29T22:49:17.000Z | 2022-03-25T10:14:17.000Z | src/xalanc/XSLT/ElemVariable.hpp | ulisesten/xalanc | a722de08e61ce66965c4a828242f7d1250950621 | [
"Apache-2.0"
] | 14 | 2019-05-10T16:25:50.000Z | 2021-11-24T18:04:47.000Z | src/xalanc/XSLT/ElemVariable.hpp | ulisesten/xalanc | a722de08e61ce66965c4a828242f7d1250950621 | [
"Apache-2.0"
] | 28 | 2015-04-20T15:50:51.000Z | 2022-01-26T14:56:55.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.
*/
#if !defined(XALAN_ELEMVARIABLE_HEADER_GUARD)
#define XALAN_ELEMVARIABLE_HEADER_GUARD
// Base include file. Must be first.
#include "XSLTDefinitions.hpp"
// Base class header file.
#include "ElemTemplateElement.hpp"
#include <xalanc/XPath/XObject.hpp>
#include <xalanc/XSLT/Constants.hpp>
namespace XALAN_CPP_NAMESPACE {
class XPath;
class ElemVariable : public ElemTemplateElement
{
public:
typedef ElemTemplateElement ParentType;
/**
* Construct an object corresponding to an "xsl:variable" element
*
* @param constructionContext context for construction of object
* @param stylesheetTree stylesheet containing element
* @param atts list of attributes for element
* @param lineNumber line number in document
* @param columnNumber column number in document
*/
ElemVariable(
StylesheetConstructionContext& constructionContext,
Stylesheet& stylesheetTree,
const AttributeListType& atts,
XalanFileLoc lineNumber,
XalanFileLoc columnNumber);
virtual
~ElemVariable();
/**
* Determines if this is a top level variable.
*
* @return true if it is a top level variable
*/
bool
isTopLevel() const
{
return m_isTopLevel;
}
// These methods are inherited from ElemTemplateElement ...
virtual const XalanQName&
getNameAttribute() const;
virtual void
addToStylesheet(
StylesheetConstructionContext& constructionContext,
Stylesheet& theStylesheet);
virtual const XalanDOMString&
getElementName() const;
#if !defined(XALAN_RECURSIVE_STYLESHEET_EXECUTION)
const ElemTemplateElement*
startElement(StylesheetExecutionContext& executionContext) const;
void
endElement(StylesheetExecutionContext& executionContext) const;
#else
virtual void
execute(StylesheetExecutionContext& executionContext) const;
#endif
const XObjectPtr
getValue(
StylesheetExecutionContext& executionContext,
XalanNode* sourceNode) const;
virtual void
setParentNodeElem(ElemTemplateElement* theParent);
virtual const XPath*
getXPath(XalanSize_t index) const;
protected:
/**
* Construct an object corresponding to an "xsl:variable" element
*
* @param constructionContext context for construction of object
* @param stylesheetTree stylesheet containing element
* @param atts list of attributes for element
* @param lineNumber line number in document
* @param columnNumber column number in document
*/
ElemVariable(
StylesheetConstructionContext& constructionContext,
Stylesheet& stylesheetTree,
const AttributeListType& atts,
XalanFileLoc lineNumber,
XalanFileLoc columnNumber,
int xslToken);
/**
* Do common initialization.
*
* @param constructionContext context for construction of object
* @param stylesheetTree stylesheet containing element
* @param atts list of attributes for element
*/
void
init(
StylesheetConstructionContext& constructionContext,
Stylesheet& stylesheetTree,
const AttributeListType& atts);
const XalanQName* m_qname;
private:
// not implemented
ElemVariable(const ElemVariable &);
ElemVariable&
operator=(const ElemVariable &);
const XPath* m_selectPattern;
bool m_isTopLevel;
XObjectPtr m_value;
XalanNode* m_varContext;
};
}
#endif // XALAN_ELEMVARIABLE_HEADER_GUARD
| 27.293785 | 75 | 0.64438 |
441baafe9de38c21838a96f15a14d248a133ce2f | 289 | cc | C++ | atcoder/arc118/a.cc | kamal1316/competitive-programming | 1443fb4bd1c92c2acff64ba2828abb21b067e6e0 | [
"WTFPL"
] | 506 | 2018-08-22T10:30:38.000Z | 2022-03-31T10:01:49.000Z | atcoder/arc118/a.cc | diegordzr/competitive-programming | 1443fb4bd1c92c2acff64ba2828abb21b067e6e0 | [
"WTFPL"
] | 13 | 2019-08-07T18:31:18.000Z | 2020-12-15T21:54:41.000Z | atcoder/arc118/a.cc | diegordzr/competitive-programming | 1443fb4bd1c92c2acff64ba2828abb21b067e6e0 | [
"WTFPL"
] | 234 | 2018-08-06T17:11:41.000Z | 2022-03-26T10:56:42.000Z | // https://atcoder.jp/contests/arc118/tasks/arc118_a
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<ll>;
int main() {
cin.tie(0), ios::sync_with_stdio(0);
ll t, n;
cin >> t >> n;
ll m = (n * 100 - 1) / t + 1;
cout << m + n - 1 << '\n';
}
| 19.266667 | 52 | 0.567474 |
441ca79e12934443171f1c455f51c3b45f822afc | 33,013 | cpp | C++ | src/solvers/flattening/bv_utils.cpp | mauguignard/cbmc | 70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5 | [
"BSD-4-Clause"
] | null | null | null | src/solvers/flattening/bv_utils.cpp | mauguignard/cbmc | 70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5 | [
"BSD-4-Clause"
] | 2 | 2018-02-14T16:11:37.000Z | 2018-02-23T18:12:27.000Z | src/solvers/flattening/bv_utils.cpp | mauguignard/cbmc | 70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5 | [
"BSD-4-Clause"
] | null | null | null | /*******************************************************************\
Module:
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
#include "bv_utils.h"
#include <cassert>
#include <util/arith_tools.h>
bvt bv_utilst::build_constant(const mp_integer &n, std::size_t width)
{
std::string n_str=integer2binary(n, width);
CHECK_RETURN(n_str.size() == width);
bvt result;
result.resize(width);
for(std::size_t i=0; i<width; i++)
result[i]=const_literal(n_str[width-i-1]=='1');
return result;
}
literalt bv_utilst::is_one(const bvt &bv)
{
PRECONDITION(!bv.empty());
bvt tmp;
tmp=bv;
tmp.erase(tmp.begin(), tmp.begin()+1);
return prop.land(is_zero(tmp), bv[0]);
}
void bv_utilst::set_equal(const bvt &a, const bvt &b)
{
PRECONDITION(a.size() == b.size());
for(std::size_t i=0; i<a.size(); i++)
prop.set_equal(a[i], b[i]);
}
bvt bv_utilst::extract(const bvt &a, std::size_t first, std::size_t last)
{
// preconditions
PRECONDITION(first < a.size());
PRECONDITION(last < a.size());
PRECONDITION(first <= last);
bvt result=a;
result.resize(last+1);
if(first!=0)
result.erase(result.begin(), result.begin()+first);
POSTCONDITION(result.size() == last - first + 1);
return result;
}
bvt bv_utilst::extract_msb(const bvt &a, std::size_t n)
{
// preconditions
PRECONDITION(n <= a.size());
bvt result=a;
result.erase(result.begin(), result.begin()+(result.size()-n));
POSTCONDITION(result.size() == n);
return result;
}
bvt bv_utilst::extract_lsb(const bvt &a, std::size_t n)
{
// preconditions
PRECONDITION(n <= a.size());
bvt result=a;
result.resize(n);
return result;
}
bvt bv_utilst::concatenate(const bvt &a, const bvt &b) const
{
bvt result;
result.resize(a.size()+b.size());
for(std::size_t i=0; i<a.size(); i++)
result[i]=a[i];
for(std::size_t i=0; i<b.size(); i++)
result[i+a.size()]=b[i];
return result;
}
/// If s is true, selects a otherwise selects b
bvt bv_utilst::select(literalt s, const bvt &a, const bvt &b)
{
PRECONDITION(a.size() == b.size());
bvt result;
result.resize(a.size());
for(std::size_t i=0; i<result.size(); i++)
result[i]=prop.lselect(s, a[i], b[i]);
return result;
}
bvt bv_utilst::extension(
const bvt &bv,
std::size_t new_size,
representationt rep)
{
std::size_t old_size=bv.size();
PRECONDITION(old_size != 0);
bvt result=bv;
result.resize(new_size);
literalt extend_with=
(rep==representationt::SIGNED && !bv.empty())?bv[old_size-1]:
const_literal(false);
for(std::size_t i=old_size; i<new_size; i++)
result[i]=extend_with;
return result;
}
/// Generates the encoding of a full adder. The optimal encoding is the
/// default.
/// \par parameters: a, b, carry_in are the literals representing inputs
/// \return return value is the literal for the sum, carry_out gets the output
/// carry
// The optimal encoding is the default as it gives a reduction in space
// and small performance gains
#define OPTIMAL_FULL_ADDER
literalt bv_utilst::full_adder(
const literalt a,
const literalt b,
const literalt carry_in,
literalt &carry_out)
{
#ifdef OPTIMAL_FULL_ADDER
if(prop.has_set_to() && prop.cnf_handled_well())
{
literalt x;
literalt y;
int constantProp = -1;
if(a.is_constant())
{
x = b;
y = carry_in;
constantProp = (a.is_true()) ? 1 : 0;
}
else if(b.is_constant())
{
x = a;
y = carry_in;
constantProp = (b.is_true()) ? 1 : 0;
}
else if(carry_in.is_constant())
{
x = a;
y = b;
constantProp = (carry_in.is_true()) ? 1 : 0;
}
literalt sum;
// Rely on prop.l* to do further constant propagation
if(constantProp == 1)
{
// At least one input bit is 1
carry_out = prop.lor(x, y);
sum = prop.lequal(x, y);
}
else if(constantProp == 0)
{
// At least one input bit is 0
carry_out = prop.land(x, y);
sum = prop.lxor(x, y);
}
else
{
carry_out = prop.new_variable();
sum = prop.new_variable();
// Any two inputs 1 will set the carry_out to 1
prop.lcnf(!a, !b, carry_out);
prop.lcnf(!a, !carry_in, carry_out);
prop.lcnf(!b, !carry_in, carry_out);
// Any two inputs 0 will set the carry_out to 0
prop.lcnf(a, b, !carry_out);
prop.lcnf(a, carry_in, !carry_out);
prop.lcnf(b, carry_in, !carry_out);
// If both carry out and sum are 1 then all inputs are 1
prop.lcnf(a, !sum, !carry_out);
prop.lcnf(b, !sum, !carry_out);
prop.lcnf(carry_in, !sum, !carry_out);
// If both carry out and sum are 0 then all inputs are 0
prop.lcnf(!a, sum, carry_out);
prop.lcnf(!b, sum, carry_out);
prop.lcnf(!carry_in, sum, carry_out);
// If all of the inputs are 1 or all are 0 it sets the sum
prop.lcnf(!a, !b, !carry_in, sum);
prop.lcnf(a, b, carry_in, !sum);
}
return sum;
}
else // NOLINT(readability/braces)
#endif // OPTIMAL_FULL_ADDER
{
// trivial encoding
carry_out=carry(a, b, carry_in);
return prop.lxor(prop.lxor(a, b), carry_in);
}
}
// Daniel's carry optimisation
#define COMPACT_CARRY
literalt bv_utilst::carry(literalt a, literalt b, literalt c)
{
#ifdef COMPACT_CARRY
if(prop.has_set_to() && prop.cnf_handled_well())
{
// propagation possible?
const auto const_count =
a.is_constant() + b.is_constant() + c.is_constant();
// propagation is possible if two or three inputs are constant
if(const_count>=2)
return prop.lor(prop.lor(
prop.land(a, b),
prop.land(a, c)),
prop.land(b, c));
// it's also possible if two of a,b,c are the same
if(a==b)
return a;
else if(a==c)
return a;
else if(b==c)
return b;
// the below yields fewer clauses and variables,
// but doesn't propagate anything at all
bvt clause;
literalt x=prop.new_variable();
/*
carry_correct: LEMMA
( a OR b OR NOT x) AND
( a OR NOT b OR c OR NOT x) AND
( a OR NOT b OR NOT c OR x) AND
(NOT a OR b OR c OR NOT x) AND
(NOT a OR b OR NOT c OR x) AND
(NOT a OR NOT b OR x)
IFF
(x=((a AND b) OR (a AND c) OR (b AND c)));
*/
prop.lcnf(a, b, !x);
prop.lcnf(a, !b, c, !x);
prop.lcnf(a, !b, !c, x);
prop.lcnf(!a, b, c, !x);
prop.lcnf(!a, b, !c, x);
prop.lcnf(!a, !b, x);
return x;
}
else
#endif // COMPACT_CARRY
{
// trivial encoding
bvt tmp;
tmp.push_back(prop.land(a, b));
tmp.push_back(prop.land(a, c));
tmp.push_back(prop.land(b, c));
return prop.lor(tmp);
}
}
void bv_utilst::adder(
bvt &sum,
const bvt &op,
literalt carry_in,
literalt &carry_out)
{
PRECONDITION(sum.size() == op.size());
carry_out=carry_in;
for(std::size_t i=0; i<sum.size(); i++)
{
sum[i] = full_adder(sum[i], op[i], carry_out, carry_out);
}
}
literalt bv_utilst::carry_out(
const bvt &op0,
const bvt &op1,
literalt carry_in)
{
PRECONDITION(op0.size() == op1.size());
literalt carry_out=carry_in;
for(std::size_t i=0; i<op0.size(); i++)
carry_out=carry(op0[i], op1[i], carry_out);
return carry_out;
}
bvt bv_utilst::add_sub_no_overflow(
const bvt &op0,
const bvt &op1,
bool subtract,
representationt rep)
{
bvt sum=op0;
adder_no_overflow(sum, op1, subtract, rep);
return sum;
}
bvt bv_utilst::add_sub(const bvt &op0, const bvt &op1, bool subtract)
{
PRECONDITION(op0.size() == op1.size());
literalt carry_in=const_literal(subtract);
literalt carry_out;
bvt result=op0;
bvt tmp_op1=subtract?inverted(op1):op1;
adder(result, tmp_op1, carry_in, carry_out);
return result;
}
bvt bv_utilst::add_sub(const bvt &op0, const bvt &op1, literalt subtract)
{
const bvt op1_sign_applied=
select(subtract, inverted(op1), op1);
bvt result=op0;
literalt carry_out;
adder(result, op1_sign_applied, subtract, carry_out);
return result;
}
literalt bv_utilst::overflow_add(
const bvt &op0, const bvt &op1, representationt rep)
{
if(rep==representationt::SIGNED)
{
// An overflow occurs if the signs of the two operands are the same
// and the sign of the sum is the opposite.
literalt old_sign=op0[op0.size()-1];
literalt sign_the_same=prop.lequal(op0[op0.size()-1], op1[op1.size()-1]);
bvt result=add(op0, op1);
return
prop.land(sign_the_same, prop.lxor(result[result.size()-1], old_sign));
}
else if(rep==representationt::UNSIGNED)
{
// overflow is simply carry-out
return carry_out(op0, op1, const_literal(false));
}
else
UNREACHABLE;
}
literalt bv_utilst::overflow_sub(
const bvt &op0, const bvt &op1, representationt rep)
{
if(rep==representationt::SIGNED)
{
// We special-case x-INT_MIN, which is >=0 if
// x is negative, always representable, and
// thus not an overflow.
literalt op1_is_int_min=is_int_min(op1);
literalt op0_is_negative=op0[op0.size()-1];
return
prop.lselect(op1_is_int_min,
!op0_is_negative,
overflow_add(op0, negate(op1), representationt::SIGNED));
}
else if(rep==representationt::UNSIGNED)
{
// overflow is simply _negated_ carry-out
return !carry_out(op0, inverted(op1), const_literal(true));
}
else
UNREACHABLE;
}
void bv_utilst::adder_no_overflow(
bvt &sum,
const bvt &op,
bool subtract,
representationt rep)
{
const bvt tmp_op=subtract?inverted(op):op;
if(rep==representationt::SIGNED)
{
// an overflow occurs if the signs of the two operands are the same
// and the sign of the sum is the opposite
literalt old_sign=sum[sum.size()-1];
literalt sign_the_same=
prop.lequal(sum[sum.size()-1], tmp_op[tmp_op.size()-1]);
literalt carry;
adder(sum, tmp_op, const_literal(subtract), carry);
// result of addition in sum
prop.l_set_to_false(
prop.land(sign_the_same, prop.lxor(sum[sum.size()-1], old_sign)));
}
else
{
INVARIANT(
rep == representationt::UNSIGNED,
"representation has either value signed or unsigned");
literalt carry_out;
adder(sum, tmp_op, const_literal(subtract), carry_out);
prop.l_set_to(carry_out, subtract);
}
}
void bv_utilst::adder_no_overflow(bvt &sum, const bvt &op)
{
literalt carry_out=const_literal(false);
adder(sum, op, carry_out, carry_out);
prop.l_set_to_false(carry_out); // enforce no overflow
}
bvt bv_utilst::shift(const bvt &op, const shiftt s, const bvt &dist)
{
std::size_t d=1, width=op.size();
bvt result=op;
for(std::size_t stage=0; stage<dist.size(); stage++)
{
if(dist[stage]!=const_literal(false))
{
bvt tmp=shift(result, s, d);
for(std::size_t i=0; i<width; i++)
result[i]=prop.lselect(dist[stage], tmp[i], result[i]);
}
d=d<<1;
}
return result;
}
bvt bv_utilst::shift(const bvt &src, const shiftt s, std::size_t dist)
{
bvt result;
result.resize(src.size());
// 'dist' is user-controlled, and thus arbitary.
// We thus must guard against the case in which i+dist overflows.
// We do so by considering the case dist>=src.size().
for(std::size_t i=0; i<src.size(); i++)
{
literalt l;
switch(s)
{
case shiftt::SHIFT_LEFT:
// no underflow on i-dist because of condition dist<=i
l=(dist<=i?src[i-dist]:const_literal(false));
break;
case shiftt::SHIFT_ARIGHT:
// src.size()-i won't underflow as i<src.size()
// Then, if dist<src.size()-i, then i+dist<src.size()
l=(dist<src.size()-i?src[i+dist]:src[src.size()-1]); // sign bit
break;
case shiftt::SHIFT_LRIGHT:
// src.size()-i won't underflow as i<src.size()
// Then, if dist<src.size()-i, then i+dist<src.size()
l=(dist<src.size()-i?src[i+dist]:const_literal(false));
break;
case shiftt::ROTATE_LEFT:
// prevent overflows by using dist%src.size()
l=src[(src.size()+i-(dist%src.size()))%src.size()];
break;
case shiftt::ROTATE_RIGHT:
// prevent overflows by using dist%src.size()
l=src[(i+(dist%src.size()))%src.size()];
break;
default:
UNREACHABLE;
}
result[i]=l;
}
return result;
}
bvt bv_utilst::negate(const bvt &bv)
{
bvt result=inverted(bv);
literalt carry_out;
incrementer(result, const_literal(true), carry_out);
return result;
}
bvt bv_utilst::negate_no_overflow(const bvt &bv)
{
prop.l_set_to_false(overflow_negate(bv));
return negate(bv);
}
literalt bv_utilst::overflow_negate(const bvt &bv)
{
// a overflow on unary- can only happen with the smallest
// representable number 100....0
bvt zeros(bv);
zeros.erase(--zeros.end());
return prop.land(bv[bv.size()-1], !prop.lor(zeros));
}
void bv_utilst::incrementer(
bvt &bv,
literalt carry_in,
literalt &carry_out)
{
carry_out=carry_in;
Forall_literals(it, bv)
{
literalt new_carry=prop.land(carry_out, *it);
*it=prop.lxor(*it, carry_out);
carry_out=new_carry;
}
}
bvt bv_utilst::incrementer(const bvt &bv, literalt carry_in)
{
bvt result=bv;
literalt carry_out;
incrementer(result, carry_in, carry_out);
return result;
}
bvt bv_utilst::inverted(const bvt &bv)
{
bvt result=bv;
Forall_literals(it, result)
*it=!*it;
return result;
}
bvt bv_utilst::wallace_tree(const std::vector<bvt> &pps)
{
PRECONDITION(!pps.empty());
if(pps.size()==1)
return pps.front();
else if(pps.size()==2)
return add(pps[0], pps[1]);
else
{
std::vector<bvt> new_pps;
std::size_t no_full_adders=pps.size()/3;
// add groups of three partial products using CSA
for(std::size_t i=0; i<no_full_adders; i++)
{
const bvt &a=pps[i*3+0],
&b=pps[i*3+1],
&c=pps[i*3+2];
INVARIANT(a.size() == b.size(), "groups should be of equal size");
INVARIANT(a.size() == c.size(), "groups should be of equal size");
bvt s(a.size()), t(a.size());
for(std::size_t bit=0; bit<a.size(); bit++)
{
// \todo reformulate using full_adder
s[bit]=prop.lxor(a[bit], prop.lxor(b[bit], c[bit]));
t[bit]=(bit==0)?const_literal(false):
carry(a[bit-1], b[bit-1], c[bit-1]);
}
new_pps.push_back(s);
new_pps.push_back(t);
}
// pass onwards up to two remaining partial products
for(std::size_t i=no_full_adders*3; i<pps.size(); i++)
new_pps.push_back(pps[i]);
POSTCONDITION(new_pps.size() < pps.size());
return wallace_tree(new_pps);
}
}
bvt bv_utilst::unsigned_multiplier(const bvt &_op0, const bvt &_op1)
{
#if 1
bvt op0=_op0, op1=_op1;
if(is_constant(op1))
std::swap(op0, op1);
bvt product;
product.resize(op0.size());
for(std::size_t i=0; i<product.size(); i++)
product[i]=const_literal(false);
for(std::size_t sum=0; sum<op0.size(); sum++)
if(op0[sum]!=const_literal(false))
{
bvt tmpop;
tmpop.reserve(op0.size());
for(std::size_t idx=0; idx<sum; idx++)
tmpop.push_back(const_literal(false));
for(std::size_t idx=sum; idx<op0.size(); idx++)
tmpop.push_back(prop.land(op1[idx-sum], op0[sum]));
product=add(product, tmpop);
}
return product;
#else
// Wallace tree multiplier. This is disabled, as runtimes have
// been observed to go up by 5%-10%, and on some models even by 20%.
// build the usual quadratic number of partial products
bvt op0=_op0, op1=_op1;
if(is_constant(op1))
std::swap(op0, op1);
std::vector<bvt> pps;
pps.reserve(op0.size());
for(std::size_t bit=0; bit<op0.size(); bit++)
if(op0[bit]!=const_literal(false))
{
bvt pp;
pp.reserve(op0.size());
// zeros according to weight
for(std::size_t idx=0; idx<bit; idx++)
pp.push_back(const_literal(false));
for(std::size_t idx=bit; idx<op0.size(); idx++)
pp.push_back(prop.land(op1[idx-bit], op0[bit]));
pps.push_back(pp);
}
if(pps.empty())
return zeros(op0.size());
else
return wallace_tree(pps);
#endif
}
bvt bv_utilst::unsigned_multiplier_no_overflow(
const bvt &op0,
const bvt &op1)
{
bvt _op0=op0, _op1=op1;
PRECONDITION(_op0.size() == _op1.size());
if(is_constant(_op1))
_op0.swap(_op1);
bvt product;
product.resize(_op0.size());
for(std::size_t i=0; i<product.size(); i++)
product[i]=const_literal(false);
for(std::size_t sum=0; sum<op0.size(); sum++)
if(op0[sum]!=const_literal(false))
{
bvt tmpop;
tmpop.reserve(product.size());
for(std::size_t idx=0; idx<sum; idx++)
tmpop.push_back(const_literal(false));
for(std::size_t idx=sum; idx<product.size(); idx++)
tmpop.push_back(prop.land(op1[idx-sum], op0[sum]));
adder_no_overflow(product, tmpop);
for(std::size_t idx=op1.size()-sum; idx<op1.size(); idx++)
prop.l_set_to_false(prop.land(op1[idx], op0[sum]));
}
return product;
}
bvt bv_utilst::signed_multiplier(const bvt &op0, const bvt &op1)
{
if(op0.empty() || op1.empty())
return bvt();
literalt sign0=op0[op0.size()-1];
literalt sign1=op1[op1.size()-1];
bvt neg0=cond_negate(op0, sign0);
bvt neg1=cond_negate(op1, sign1);
bvt result=unsigned_multiplier(neg0, neg1);
literalt result_sign=prop.lxor(sign0, sign1);
return cond_negate(result, result_sign);
}
bvt bv_utilst::cond_negate(const bvt &bv, const literalt cond)
{
bvt neg_bv=negate(bv);
bvt result;
result.resize(bv.size());
for(std::size_t i=0; i<bv.size(); i++)
result[i]=prop.lselect(cond, neg_bv[i], bv[i]);
return result;
}
bvt bv_utilst::absolute_value(const bvt &bv)
{
PRECONDITION(!bv.empty());
return cond_negate(bv, bv[bv.size()-1]);
}
bvt bv_utilst::cond_negate_no_overflow(const bvt &bv, literalt cond)
{
prop.l_set_to_true(prop.limplies(cond, !overflow_negate(bv)));
return cond_negate(bv, cond);
}
bvt bv_utilst::signed_multiplier_no_overflow(
const bvt &op0,
const bvt &op1)
{
if(op0.empty() || op1.empty())
return bvt();
literalt sign0=op0[op0.size()-1];
literalt sign1=op1[op1.size()-1];
bvt neg0=cond_negate_no_overflow(op0, sign0);
bvt neg1=cond_negate_no_overflow(op1, sign1);
bvt result=unsigned_multiplier_no_overflow(neg0, neg1);
prop.l_set_to_false(result[result.size() - 1]);
literalt result_sign=prop.lxor(sign0, sign1);
return cond_negate_no_overflow(result, result_sign);
}
bvt bv_utilst::multiplier(
const bvt &op0,
const bvt &op1,
representationt rep)
{
switch(rep)
{
case representationt::SIGNED: return signed_multiplier(op0, op1);
case representationt::UNSIGNED: return unsigned_multiplier(op0, op1);
}
UNREACHABLE;
}
bvt bv_utilst::multiplier_no_overflow(
const bvt &op0,
const bvt &op1,
representationt rep)
{
switch(rep)
{
case representationt::SIGNED:
return signed_multiplier_no_overflow(op0, op1);
case representationt::UNSIGNED:
return unsigned_multiplier_no_overflow(op0, op1);
}
UNREACHABLE;
}
void bv_utilst::signed_divider(
const bvt &op0,
const bvt &op1,
bvt &res,
bvt &rem)
{
if(op0.empty() || op1.empty())
return;
bvt _op0(op0), _op1(op1);
literalt sign_0=_op0[_op0.size()-1];
literalt sign_1=_op1[_op1.size()-1];
bvt neg_0=negate(_op0), neg_1=negate(_op1);
for(std::size_t i=0; i<_op0.size(); i++)
_op0[i]=(prop.lselect(sign_0, neg_0[i], _op0[i]));
for(std::size_t i=0; i<_op1.size(); i++)
_op1[i]=(prop.lselect(sign_1, neg_1[i], _op1[i]));
unsigned_divider(_op0, _op1, res, rem);
bvt neg_res=negate(res), neg_rem=negate(rem);
literalt result_sign=prop.lxor(sign_0, sign_1);
for(std::size_t i=0; i<res.size(); i++)
res[i]=prop.lselect(result_sign, neg_res[i], res[i]);
for(std::size_t i=0; i<res.size(); i++)
rem[i]=prop.lselect(sign_0, neg_rem[i], rem[i]);
}
void bv_utilst::divider(
const bvt &op0,
const bvt &op1,
bvt &result,
bvt &remainer,
representationt rep)
{
PRECONDITION(prop.has_set_to());
switch(rep)
{
case representationt::SIGNED:
signed_divider(op0, op1, result, remainer); break;
case representationt::UNSIGNED:
unsigned_divider(op0, op1, result, remainer); break;
}
}
void bv_utilst::unsigned_divider(
const bvt &op0,
const bvt &op1,
bvt &res,
bvt &rem)
{
std::size_t width=op0.size();
// check if we divide by a power of two
#if 0
{
std::size_t one_count=0, non_const_count=0, one_pos=0;
for(std::size_t i=0; i<op1.size(); i++)
{
literalt l=op1[i];
if(l.is_true())
{
one_count++;
one_pos=i;
}
else if(!l.is_false())
non_const_count++;
}
if(non_const_count==0 && one_count==1 && one_pos!=0)
{
// it is a power of two!
res=shift(op0, LRIGHT, one_pos);
// remainder is just a mask
rem=op0;
for(std::size_t i=one_pos; i<rem.size(); i++)
rem[i]=const_literal(false);
return;
}
}
#endif
// Division by zero test.
// Note that we produce a non-deterministic result in
// case of division by zero. SMT-LIB now says the following:
// bvudiv returns a vector of all 1s if the second operand is 0
// bvurem returns its first operand if the second operand is 0
literalt is_not_zero=prop.lor(op1);
// free variables for result of division
res.resize(width);
rem.resize(width);
for(std::size_t i=0; i<width; i++)
{
res[i]=prop.new_variable();
rem[i]=prop.new_variable();
}
// add implications
bvt product=
unsigned_multiplier_no_overflow(res, op1);
// res*op1 + rem = op0
bvt sum=product;
adder_no_overflow(sum, rem);
literalt is_equal=equal(sum, op0);
prop.l_set_to_true(prop.limplies(is_not_zero, is_equal));
// op1!=0 => rem < op1
prop.l_set_to_true(
prop.limplies(
is_not_zero, lt_or_le(false, rem, op1, representationt::UNSIGNED)));
// op1!=0 => res <= op0
prop.l_set_to_true(
prop.limplies(
is_not_zero, lt_or_le(true, res, op0, representationt::UNSIGNED)));
}
#ifdef COMPACT_EQUAL_CONST
// TODO : use for lt_or_le as well
/// The equal_const optimisation will be used on this bit-vector.
/// \par parameters: A bit-vector of a variable that is to be registered.
/// \return None.
void bv_utilst::equal_const_register(const bvt &var)
{
PRECONDITION(!is_constant(var));
equal_const_registered.insert(var);
return;
}
/// The obvious recursive comparison, the interesting thing is that it is cached
/// so the literals are shared between constants.
/// \param Bit:vectors for a variable and a const to compare, note that
/// to avoid significant amounts of copying these are mutable and consumed.
/// \return The literal that is true if and only if all the bits in var and
/// const are equal.
literalt bv_utilst::equal_const_rec(bvt &var, bvt &constant)
{
std::size_t size = var.size();
PRECONDITION(size != 0);
PRECONDITION(size == constant.size());
PRECONDITION(is_constant(constant));
if(size == 1)
{
literalt comp = prop.lequal(var[size - 1], constant[size - 1]);
var.pop_back();
constant.pop_back();
return comp;
}
else
{
var_constant_pairt index(var, constant);
equal_const_cachet::iterator entry = equal_const_cache.find(index);
if(entry != equal_const_cache.end())
{
return entry->second;
}
else
{
literalt comp = prop.lequal(var[size - 1], constant[size - 1]);
var.pop_back();
constant.pop_back();
literalt rec = equal_const_rec(var, constant);
literalt compare = prop.land(rec, comp);
equal_const_cache.insert(
std::pair<var_constant_pairt, literalt>(index, compare));
return compare;
}
}
}
/// An experimental encoding, aimed primarily at variable position access to
/// constant arrays. These generate a lot of comparisons of the form var =
/// small_const . It will introduce some additional literals and for variables
/// that have only a few comparisons with constants this may result in a net
/// increase in formula size. It is hoped that a 'sufficently advanced
/// preprocessor' will remove these.
/// \param Bit:vectors for a variable and a const to compare.
/// \return The literal that is true if and only if they are equal.
literalt bv_utilst::equal_const(const bvt &var, const bvt &constant)
{
std::size_t size = constant.size();
PRECONDITION(var.size() == size);
PRECONDITION(!is_constant(var));
PRECONDITION(is_constant(constant));
PRECONDITION(size >= 2);
// These get modified : be careful!
bvt var_upper;
bvt var_lower;
bvt constant_upper;
bvt constant_lower;
/* Split the constant based on a change in parity
* This is based on the observation that most constants are small,
* so combinations of the lower bits are heavily used but the upper
* bits are almost always either all 0 or all 1.
*/
literalt top_bit = constant[size - 1];
std::size_t split = size - 1;
var_upper.push_back(var[size - 1]);
constant_upper.push_back(constant[size - 1]);
for(split = size - 2; split != 0; --split)
{
if(constant[split] != top_bit)
{
break;
}
else
{
var_upper.push_back(var[split]);
constant_upper.push_back(constant[split]);
}
}
for(std::size_t i = 0; i <= split; ++i)
{
var_lower.push_back(var[i]);
constant_lower.push_back(constant[i]);
}
// Check we have split the array correctly
INVARIANT(
var_upper.size() + var_lower.size() == size,
"lower size plus upper size should equal the total size");
INVARIANT(
constant_upper.size() + constant_lower.size() == size,
"lower size plus upper size should equal the total size");
literalt top_comparison = equal_const_rec(var_upper, constant_upper);
literalt bottom_comparison = equal_const_rec(var_lower, constant_lower);
return prop.land(top_comparison, bottom_comparison);
}
#endif
/// Bit-blasting ID_equal and use in other encodings.
/// \param op0: Lhs bitvector to compare
/// \param op1: Rhs bitvector to compare
/// \return The literal that is true if and only if they are equal.
literalt bv_utilst::equal(const bvt &op0, const bvt &op1)
{
PRECONDITION(op0.size() == op1.size());
#ifdef COMPACT_EQUAL_CONST
// simplify_expr should put the constant on the right
// but bit-level simplification may result in the other cases
if(is_constant(op0) && !is_constant(op1) && op0.size() > 2 &&
equal_const_registered.find(op1) != equal_const_registered.end())
return equal_const(op1, op0);
else if(!is_constant(op0) && is_constant(op1) && op0.size() > 2 &&
equal_const_registered.find(op0) != equal_const_registered.end())
return equal_const(op0, op1);
#endif
bvt equal_bv;
equal_bv.resize(op0.size());
for(std::size_t i=0; i<op0.size(); i++)
equal_bv[i]=prop.lequal(op0[i], op1[i]);
return prop.land(equal_bv);
}
/// To provide a bitwise model of < or <=.
/// \par parameters: bvts for each input and whether they are signed and whether
/// a model of < or <= is required.
/// \return A literalt that models the value of the comparison.
/* Some clauses are not needed for correctness but they remove
models (effectively setting "don't care" bits) and so may be worth
including.*/
// #define INCLUDE_REDUNDANT_CLAUSES
// Saves space but slows the solver
// There is a variant that uses the xor as an auxiliary that should improve both
// #define COMPACT_LT_OR_LE
literalt bv_utilst::lt_or_le(
bool or_equal,
const bvt &bv0,
const bvt &bv1,
representationt rep)
{
PRECONDITION(bv0.size() == bv1.size());
literalt top0=bv0[bv0.size()-1],
top1=bv1[bv1.size()-1];
#ifdef COMPACT_LT_OR_LE
if(prop.has_set_to() && prop.cnf_handled_well())
{
bvt compareBelow; // 1 if a compare is needed below this bit
literalt result;
size_t start;
size_t i;
compareBelow.resize(bv0.size());
Forall_literals(it, compareBelow) { (*it) = prop.new_variable(); }
result = prop.new_variable();
if(rep==SIGNED)
{
INVARIANT(
bv0.size() >= 2, "signed bitvectors should have at least two bits");
start = compareBelow.size() - 2;
literalt firstComp=compareBelow[start];
// When comparing signs we are comparing the top bit
#ifdef INCLUDE_REDUNDANT_CLAUSES
prop.l_set_to_true(compareBelow[start + 1])
#endif
// Four cases...
prop.lcnf(top0, top1, firstComp); // + + compare needed
prop.lcnf(top0, !top1, !result); // + - result false and no compare needed
prop.lcnf(!top0, top1, result); // - + result true and no compare needed
prop.lcnf(!top0, !top1, firstComp); // - - negated compare needed
#ifdef INCLUDE_REDUNDANT_CLAUSES
prop.lcnf(top0, !top1, !firstComp);
prop.lcnf(!top0, top1, !firstComp);
#endif
}
else
{
// Unsigned is much easier
start = compareBelow.size() - 1;
prop.l_set_to_true(compareBelow[start]);
}
// Determine the output
// \forall i . cb[i] & -a[i] & b[i] => result
// \forall i . cb[i] & a[i] & -b[i] => -result
i = start;
do
{
prop.lcnf(!compareBelow[i], bv0[i], !bv1[i], result);
prop.lcnf(!compareBelow[i], !bv0[i], bv1[i], !result);
}
while(i-- != 0);
// Chain the comparison bit
// \forall i != 0 . cb[i] & a[i] & b[i] => cb[i-1]
// \forall i != 0 . cb[i] & -a[i] & -b[i] => cb[i-1]
for(i = start; i > 0; i--)
{
prop.lcnf(!compareBelow[i], !bv0[i], !bv1[i], compareBelow[i-1]);
prop.lcnf(!compareBelow[i], bv0[i], bv1[i], compareBelow[i-1]);
}
#ifdef INCLUDE_REDUNDANT_CLAUSES
// Optional zeroing of the comparison bit when not needed
// \forall i != 0 . -c[i] => -c[i-1]
// \forall i != 0 . c[i] & -a[i] & b[i] => -c[i-1]
// \forall i != 0 . c[i] & a[i] & -b[i] => -c[i-1]
for(i = start; i > 0; i--)
{
prop.lcnf(compareBelow[i], !compareBelow[i-1]);
prop.lcnf(!compareBelow[i], bv0[i], !bv1[i], !compareBelow[i-1]);
prop.lcnf(!compareBelow[i], !bv0[i], bv1[i], !compareBelow[i-1]);
}
#endif
// The 'base case' of the induction is the case when they are equal
prop.lcnf(!compareBelow[0], !bv0[0], !bv1[0], (or_equal)?result:!result);
prop.lcnf(!compareBelow[0], bv0[0], bv1[0], (or_equal)?result:!result);
return result;
}
else
#endif
{
literalt carry=
carry_out(bv0, inverted(bv1), const_literal(true));
literalt result;
if(rep==representationt::SIGNED)
result=prop.lxor(prop.lequal(top0, top1), carry);
else
{
INVARIANT(
rep == representationt::UNSIGNED,
"representation has either value signed or unsigned");
result = !carry;
}
if(or_equal)
result=prop.lor(result, equal(bv0, bv1));
return result;
}
}
literalt bv_utilst::unsigned_less_than(
const bvt &op0,
const bvt &op1)
{
#ifdef COMPACT_LT_OR_LE
return lt_or_le(false, op0, op1, UNSIGNED);
#else
// A <= B iff there is an overflow on A-B
return !carry_out(op0, inverted(op1), const_literal(true));
#endif
}
literalt bv_utilst::signed_less_than(
const bvt &bv0,
const bvt &bv1)
{
return lt_or_le(false, bv0, bv1, representationt::SIGNED);
}
literalt bv_utilst::rel(
const bvt &bv0,
irep_idt id,
const bvt &bv1,
representationt rep)
{
if(id==ID_equal)
return equal(bv0, bv1);
else if(id==ID_notequal)
return !equal(bv0, bv1);
else if(id==ID_le)
return lt_or_le(true, bv0, bv1, rep);
else if(id==ID_lt)
return lt_or_le(false, bv0, bv1, rep);
else if(id==ID_ge)
return lt_or_le(true, bv1, bv0, rep); // swapped
else if(id==ID_gt)
return lt_or_le(false, bv1, bv0, rep); // swapped
else
UNREACHABLE;
}
bool bv_utilst::is_constant(const bvt &bv)
{
forall_literals(it, bv)
if(!it->is_constant())
return false;
return true;
}
void bv_utilst::cond_implies_equal(
literalt cond,
const bvt &a,
const bvt &b)
{
PRECONDITION(a.size() == b.size());
if(prop.cnf_handled_well())
{
for(std::size_t i=0; i<a.size(); i++)
{
prop.lcnf(!cond, a[i], !b[i]);
prop.lcnf(!cond, !a[i], b[i]);
}
}
else
{
prop.limplies(cond, equal(a, b));
}
return;
}
literalt bv_utilst::verilog_bv_has_x_or_z(const bvt &src)
{
bvt odd_bits;
odd_bits.reserve(src.size()/2);
// check every odd bit
for(std::size_t i=0; i<src.size(); i++)
{
if(i%2!=0)
odd_bits.push_back(src[i]);
}
return prop.lor(odd_bits);
}
bvt bv_utilst::verilog_bv_normal_bits(const bvt &src)
{
bvt even_bits;
even_bits.reserve(src.size()/2);
// get every even bit
for(std::size_t i=0; i<src.size(); i++)
{
if(i%2==0)
even_bits.push_back(src[i]);
}
return even_bits;
}
| 24.044428 | 80 | 0.635144 |
441ef84eec24ed4bd0a7a825dc092d97482d7940 | 15,080 | hpp | C++ | RZExternal/src/FitSDKRelease_20/fit_three_d_sensor_calibration_mesg.hpp | roznet/tennisstats | 6283326c0a8cadaeff98b45f8aeff1a32429fa06 | [
"MIT"
] | 1 | 2020-08-04T07:29:47.000Z | 2020-08-04T07:29:47.000Z | RZExternal/src/FitSDKRelease_20/fit_three_d_sensor_calibration_mesg.hpp | roznet/tennisstats | 6283326c0a8cadaeff98b45f8aeff1a32429fa06 | [
"MIT"
] | null | null | null | RZExternal/src/FitSDKRelease_20/fit_three_d_sensor_calibration_mesg.hpp | roznet/tennisstats | 6283326c0a8cadaeff98b45f8aeff1a32429fa06 | [
"MIT"
] | 1 | 2019-06-05T08:27:18.000Z | 2019-06-05T08:27:18.000Z | ////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Garmin Canada Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2018 Garmin Canada Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 20.80Release
// Tag = production/akw/20.80.00-0-g64ad259
////////////////////////////////////////////////////////////////////////////////
#if !defined(FIT_THREE_D_SENSOR_CALIBRATION_MESG_HPP)
#define FIT_THREE_D_SENSOR_CALIBRATION_MESG_HPP
#include "fit_mesg.hpp"
namespace fit
{
class ThreeDSensorCalibrationMesg : public Mesg
{
public:
class FieldDefNum final
{
public:
static const FIT_UINT8 Timestamp = 253;
static const FIT_UINT8 SensorType = 0;
static const FIT_UINT8 CalibrationFactor = 1;
static const FIT_UINT8 CalibrationDivisor = 2;
static const FIT_UINT8 LevelShift = 3;
static const FIT_UINT8 OffsetCal = 4;
static const FIT_UINT8 OrientationMatrix = 5;
static const FIT_UINT8 Invalid = FIT_FIELD_NUM_INVALID;
};
ThreeDSensorCalibrationMesg(void) : Mesg(Profile::MESG_THREE_D_SENSOR_CALIBRATION)
{
}
ThreeDSensorCalibrationMesg(const Mesg &mesg) : Mesg(mesg)
{
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of timestamp field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsTimestampValid() const
{
const Field* field = GetField(253);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
return field->IsValueValid();
}
///////////////////////////////////////////////////////////////////////
// Returns timestamp field
// Units: s
// Comment: Whole second part of the timestamp
///////////////////////////////////////////////////////////////////////
FIT_DATE_TIME GetTimestamp(void) const
{
return GetFieldUINT32Value(253, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Set timestamp field
// Units: s
// Comment: Whole second part of the timestamp
///////////////////////////////////////////////////////////////////////
void SetTimestamp(FIT_DATE_TIME timestamp)
{
SetFieldUINT32Value(253, timestamp, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of sensor_type field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsSensorTypeValid() const
{
const Field* field = GetField(0);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
return field->IsValueValid();
}
///////////////////////////////////////////////////////////////////////
// Returns sensor_type field
// Comment: Indicates which sensor the calibration is for
///////////////////////////////////////////////////////////////////////
FIT_SENSOR_TYPE GetSensorType(void) const
{
return GetFieldENUMValue(0, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Set sensor_type field
// Comment: Indicates which sensor the calibration is for
///////////////////////////////////////////////////////////////////////
void SetSensorType(FIT_SENSOR_TYPE sensorType)
{
SetFieldENUMValue(0, sensorType, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of calibration_factor field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsCalibrationFactorValid() const
{
const Field* field = GetField(1);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
return field->IsValueValid();
}
///////////////////////////////////////////////////////////////////////
// Returns calibration_factor field
// Comment: Calibration factor used to convert from raw ADC value to degrees, g, etc.
///////////////////////////////////////////////////////////////////////
FIT_UINT32 GetCalibrationFactor(void) const
{
return GetFieldUINT32Value(1, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Set calibration_factor field
// Comment: Calibration factor used to convert from raw ADC value to degrees, g, etc.
///////////////////////////////////////////////////////////////////////
void SetCalibrationFactor(FIT_UINT32 calibrationFactor)
{
SetFieldUINT32Value(1, calibrationFactor, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of accel_cal_factor field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsAccelCalFactorValid() const
{
const Field* field = GetField(1);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
if( !CanSupportSubField( field, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_ACCEL_CAL_FACTOR ) )
{
return FIT_FALSE;
}
return field->IsValueValid(0, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_ACCEL_CAL_FACTOR);
}
///////////////////////////////////////////////////////////////////////
// Returns accel_cal_factor field
// Units: g
// Comment: Accelerometer calibration factor
///////////////////////////////////////////////////////////////////////
FIT_UINT32 GetAccelCalFactor(void) const
{
return GetFieldUINT32Value(1, 0, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_ACCEL_CAL_FACTOR);
}
///////////////////////////////////////////////////////////////////////
// Set accel_cal_factor field
// Units: g
// Comment: Accelerometer calibration factor
///////////////////////////////////////////////////////////////////////
void SetAccelCalFactor(FIT_UINT32 accelCalFactor)
{
SetFieldUINT32Value(1, accelCalFactor, 0, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_ACCEL_CAL_FACTOR);
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of gyro_cal_factor field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsGyroCalFactorValid() const
{
const Field* field = GetField(1);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
if( !CanSupportSubField( field, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_GYRO_CAL_FACTOR ) )
{
return FIT_FALSE;
}
return field->IsValueValid(0, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_GYRO_CAL_FACTOR);
}
///////////////////////////////////////////////////////////////////////
// Returns gyro_cal_factor field
// Units: deg/s
// Comment: Gyro calibration factor
///////////////////////////////////////////////////////////////////////
FIT_UINT32 GetGyroCalFactor(void) const
{
return GetFieldUINT32Value(1, 0, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_GYRO_CAL_FACTOR);
}
///////////////////////////////////////////////////////////////////////
// Set gyro_cal_factor field
// Units: deg/s
// Comment: Gyro calibration factor
///////////////////////////////////////////////////////////////////////
void SetGyroCalFactor(FIT_UINT32 gyroCalFactor)
{
SetFieldUINT32Value(1, gyroCalFactor, 0, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_GYRO_CAL_FACTOR);
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of calibration_divisor field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsCalibrationDivisorValid() const
{
const Field* field = GetField(2);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
return field->IsValueValid();
}
///////////////////////////////////////////////////////////////////////
// Returns calibration_divisor field
// Units: counts
// Comment: Calibration factor divisor
///////////////////////////////////////////////////////////////////////
FIT_UINT32 GetCalibrationDivisor(void) const
{
return GetFieldUINT32Value(2, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Set calibration_divisor field
// Units: counts
// Comment: Calibration factor divisor
///////////////////////////////////////////////////////////////////////
void SetCalibrationDivisor(FIT_UINT32 calibrationDivisor)
{
SetFieldUINT32Value(2, calibrationDivisor, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of level_shift field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsLevelShiftValid() const
{
const Field* field = GetField(3);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
return field->IsValueValid();
}
///////////////////////////////////////////////////////////////////////
// Returns level_shift field
// Comment: Level shift value used to shift the ADC value back into range
///////////////////////////////////////////////////////////////////////
FIT_UINT32 GetLevelShift(void) const
{
return GetFieldUINT32Value(3, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Set level_shift field
// Comment: Level shift value used to shift the ADC value back into range
///////////////////////////////////////////////////////////////////////
void SetLevelShift(FIT_UINT32 levelShift)
{
SetFieldUINT32Value(3, levelShift, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Returns number of offset_cal
///////////////////////////////////////////////////////////////////////
FIT_UINT8 GetNumOffsetCal(void) const
{
return GetFieldNumValues(4, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of offset_cal field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsOffsetCalValid(FIT_UINT8 index) const
{
const Field* field = GetField(4);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
return field->IsValueValid(index);
}
///////////////////////////////////////////////////////////////////////
// Returns offset_cal field
// Comment: Internal calibration factors, one for each: xy, yx, zx
///////////////////////////////////////////////////////////////////////
FIT_SINT32 GetOffsetCal(FIT_UINT8 index) const
{
return GetFieldSINT32Value(4, index, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Set offset_cal field
// Comment: Internal calibration factors, one for each: xy, yx, zx
///////////////////////////////////////////////////////////////////////
void SetOffsetCal(FIT_UINT8 index, FIT_SINT32 offsetCal)
{
SetFieldSINT32Value(4, offsetCal, index, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Returns number of orientation_matrix
///////////////////////////////////////////////////////////////////////
FIT_UINT8 GetNumOrientationMatrix(void) const
{
return GetFieldNumValues(5, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Checks the validity of orientation_matrix field
// Returns FIT_TRUE if field is valid
///////////////////////////////////////////////////////////////////////
FIT_BOOL IsOrientationMatrixValid(FIT_UINT8 index) const
{
const Field* field = GetField(5);
if( FIT_NULL == field )
{
return FIT_FALSE;
}
return field->IsValueValid(index);
}
///////////////////////////////////////////////////////////////////////
// Returns orientation_matrix field
// Comment: 3 x 3 rotation matrix (row major)
///////////////////////////////////////////////////////////////////////
FIT_FLOAT32 GetOrientationMatrix(FIT_UINT8 index) const
{
return GetFieldFLOAT32Value(5, index, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
///////////////////////////////////////////////////////////////////////
// Set orientation_matrix field
// Comment: 3 x 3 rotation matrix (row major)
///////////////////////////////////////////////////////////////////////
void SetOrientationMatrix(FIT_UINT8 index, FIT_FLOAT32 orientationMatrix)
{
SetFieldFLOAT32Value(5, orientationMatrix, index, FIT_SUBFIELD_INDEX_MAIN_FIELD);
}
};
} // namespace fit
#endif // !defined(FIT_THREE_D_SENSOR_CALIBRATION_MESG_HPP)
| 38.865979 | 148 | 0.455504 |
441fe1eb48a9368cde796d97fb901abdda65153d | 131 | hxx | C++ | src/Providers/UNIXProviders/StatisticsService/UNIX_StatisticsService_DARWIN.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/StatisticsService/UNIX_StatisticsService_DARWIN.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/StatisticsService/UNIX_StatisticsService_DARWIN.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_DARWIN
#ifndef __UNIX_STATISTICSSERVICE_PRIVATE_H
#define __UNIX_STATISTICSSERVICE_PRIVATE_H
#endif
#endif
| 10.916667 | 42 | 0.854962 |
44257a709f843bc41bafe52d1f430e34b1949c6c | 3,097 | cpp | C++ | componentLibraries/devLibraries/SocketComponents/SocketComponents.cpp | mjfwest/hopsan | 77a0a1e69fd9588335b7e932f348972186cbdf6f | [
"Apache-2.0"
] | null | null | null | componentLibraries/devLibraries/SocketComponents/SocketComponents.cpp | mjfwest/hopsan | 77a0a1e69fd9588335b7e932f348972186cbdf6f | [
"Apache-2.0"
] | null | null | null | componentLibraries/devLibraries/SocketComponents/SocketComponents.cpp | mjfwest/hopsan | 77a0a1e69fd9588335b7e932f348972186cbdf6f | [
"Apache-2.0"
] | null | null | null | /*-----------------------------------------------------------------------------
Copyright 2017 Hopsan Group
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.
The full license is available in the file LICENSE.
For details about the 'Hopsan Group' or information about Authors and
Contributors see the HOPSANGROUP and AUTHORS files that are located in
the Hopsan source code root directory.
-----------------------------------------------------------------------------*/
// Include your component code code files here
// If you have lots of them you can include them in separate .h files and then include those files here instead.
#include "SocketIOTestComponent.hpp"
// You need to include ComponentEssentials.h in order to gain access to the register function and the Factory types
// Also use the hopsan namespace
#include "ComponentEssentials.h"
using namespace hopsan;
// When you load your model into Hopsan, the register_contents() function bellow will be called
// It will register YOUR components into the Hopsan ComponentFactory
extern "C" DLLEXPORT void register_contents(ComponentFactory* pComponentFactory, NodeFactory* /*pNodeFactory*/)
{
// ========== Register Components ==========
// Use the registerCreatorFunction(KeyValue, Function) in the component factory to register components
// The KeyValue is a text string with the TypeName of the component.
// This value must be unique for every component in Hopsan.
// If a typename is already in use, your component will not be added.
// Suggestion, let the KeyValue (TypeName) be the same as your Class name
// If that name is already in use, use something similar
pComponentFactory->registerCreatorFunction("SocketIOTestComponent", SocketIOTestComponent::Creator);
// ========== Register Custom Nodes (if any) ==========
// This is not yet supported
}
// When you load your model into Hopsan, the get_hopsan_info() function bellow will be called
// This information is used to make sure that your component and the hopsan core have the same version
extern "C" DLLEXPORT void get_hopsan_info(HopsanExternalLibInfoT *pHopsanExternalLibInfo)
{
// Change the name of the lib to something unique
// You can include numbers in your name to indicate library version (if you want)
pHopsanExternalLibInfo->libName = (char*)"HopsanExampleComponentLibrary";
// Leave these two lines as they are
pHopsanExternalLibInfo->hopsanCoreVersion = (char*)HOPSANCOREVERSION;
pHopsanExternalLibInfo->libCompiledDebugRelease = (char*)DEBUGRELEASECOMPILED;
}
| 44.242857 | 115 | 0.7165 |
4427714e79e4d907d2f904bd9bca476c91aa1681 | 2,194 | hpp | C++ | src/vec3.hpp | chrismile/reshade-grabber | 0a24c65d8699106b94ace644748e67cdb1081024 | [
"BSD-3-Clause"
] | null | null | null | src/vec3.hpp | chrismile/reshade-grabber | 0a24c65d8699106b94ace644748e67cdb1081024 | [
"BSD-3-Clause"
] | null | null | null | src/vec3.hpp | chrismile/reshade-grabber | 0a24c65d8699106b94ace644748e67cdb1081024 | [
"BSD-3-Clause"
] | null | null | null | /*
* BSD 2-Clause License
*
* Copyright (c) 2021, Christoph Neuhauser
* 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.
*/
#ifndef RESHADE_GRABBER_VEC3_HPP
#define RESHADE_GRABBER_VEC3_HPP
struct vec3 {
union{
struct { float x, y, z; };
float data[3];
};
vec3(float x, float y, float z) : x(x), y(y), z(z) {}
};
inline vec3 normalize(const vec3& p) {
float invLength = 1.0f / std::sqrt(p.x * p.x + p.y * p.y + p.z * p.z);
return vec3(invLength * p.x, invLength * p.y, invLength * p.z);
}
inline vec3 cross(const vec3& p, const vec3& q) {
return vec3(p.y * q.z - p.z * q.y, p.z * q.x - p.x * q.z, p.x * q.y - p.y * q.x);
}
inline vec3 operator+(const vec3& p, const vec3& q) {
return vec3(p.x + q.x, p.y + q.y, p.z + q.z);
}
inline vec3 operator-(const vec3& p, const vec3& q) {
return vec3(p.x - q.x, p.y - q.y, p.z - q.z);
}
#endif //RESHADE_GRABBER_VEC3_HPP
| 37.186441 | 85 | 0.696901 |
44278245c46eed251cd16bc42256d0e38cec4437 | 11,053 | hpp | C++ | include/unifex/detail/concept_macros.hpp | hnakamur/libunifex | 30e04053d90a35f277dc5ab3dc156ac75caa91da | [
"Apache-2.0"
] | null | null | null | include/unifex/detail/concept_macros.hpp | hnakamur/libunifex | 30e04053d90a35f277dc5ab3dc156ac75caa91da | [
"Apache-2.0"
] | null | null | null | include/unifex/detail/concept_macros.hpp | hnakamur/libunifex | 30e04053d90a35f277dc5ab3dc156ac75caa91da | [
"Apache-2.0"
] | 1 | 2021-07-29T13:33:13.000Z | 2021-07-29T13:33:13.000Z | /*
* Copyright 2019-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <type_traits>
#include <unifex/config.hpp>
#include <unifex/type_traits.hpp>
#if defined(_MSC_VER) && !defined(__clang__)
#define UNIFEX_WORKAROUND_MSVC_779763 // FATAL_UNREACHABLE calling constexpr function via template parameter
#define UNIFEX_WORKAROUND_MSVC_780775 // Incorrect substitution in function template return type
#endif
#define UNIFEX_PP_CAT_(X, ...) X ## __VA_ARGS__
#define UNIFEX_PP_CAT(X, ...) UNIFEX_PP_CAT_(X, __VA_ARGS__)
#define UNIFEX_PP_CAT2_(X, ...) X ## __VA_ARGS__
#define UNIFEX_PP_CAT2(X, ...) UNIFEX_PP_CAT2_(X, __VA_ARGS__)
#define UNIFEX_PP_CAT3_(X, ...) X ## __VA_ARGS__
#define UNIFEX_PP_CAT3(X, ...) UNIFEX_PP_CAT3_(X, __VA_ARGS__)
#define UNIFEX_PP_CAT4_(X, ...) X ## __VA_ARGS__
#define UNIFEX_PP_CAT4(X, ...) UNIFEX_PP_CAT4_(X, __VA_ARGS__)
#define UNIFEX_PP_EVAL_(X, ARGS) X ARGS
#define UNIFEX_PP_EVAL(X, ...) UNIFEX_PP_EVAL_(X, (__VA_ARGS__))
#define UNIFEX_PP_EVAL2_(X, ARGS) X ARGS
#define UNIFEX_PP_EVAL2(X, ...) UNIFEX_PP_EVAL2_(X, (__VA_ARGS__))
#define UNIFEX_PP_EXPAND(...) __VA_ARGS__
#define UNIFEX_PP_EAT(...)
#define UNIFEX_PP_CHECK(...) UNIFEX_PP_EXPAND(UNIFEX_PP_CHECK_N(__VA_ARGS__, 0,))
#define UNIFEX_PP_CHECK_N(x, n, ...) n
#define UNIFEX_PP_PROBE(x) x, 1,
#define UNIFEX_PP_PROBE_N(x, n) x, n,
#define UNIFEX_PP_IS_PAREN(x) UNIFEX_PP_CHECK(UNIFEX_PP_IS_PAREN_PROBE x)
#define UNIFEX_PP_IS_PAREN_PROBE(...) UNIFEX_PP_PROBE(~)
// The final UNIFEX_PP_EXPAND here is to avoid
// https://stackoverflow.com/questions/5134523/msvc-doesnt-expand-va-args-correctly
#define UNIFEX_PP_COUNT(...) \
UNIFEX_PP_EXPAND(UNIFEX_PP_COUNT_(__VA_ARGS__, \
50, 49, 48, 47, 46, 45, 44, 43, 42, 41, \
40, 39, 38, 37, 36, 35, 34, 33, 32, 31, \
30, 29, 28, 27, 26, 25, 24, 23, 22, 21, \
20, 19, 18, 17, 16, 15, 14, 13, 12, 11, \
10, 9, 8, 7, 6, 5, 4, 3, 2, 1,)) \
/**/
#define UNIFEX_PP_COUNT_( \
_01, _02, _03, _04, _05, _06, _07, _08, _09, _10, \
_11, _12, _13, _14, _15, _16, _17, _18, _19, _20, \
_21, _22, _23, _24, _25, _26, _27, _28, _29, _30, \
_31, _32, _33, _34, _35, _36, _37, _38, _39, _40, \
_41, _42, _43, _44, _45, _46, _47, _48, _49, _50, N, ...) \
N \
/**/
#define UNIFEX_PP_IIF(BIT) UNIFEX_PP_CAT_(UNIFEX_PP_IIF_, BIT)
#define UNIFEX_PP_IIF_0(TRUE, ...) __VA_ARGS__
#define UNIFEX_PP_IIF_1(TRUE, ...) TRUE
#define UNIFEX_PP_LPAREN (
#define UNIFEX_PP_NOT(BIT) UNIFEX_PP_CAT_(UNIFEX_PP_NOT_, BIT)
#define UNIFEX_PP_NOT_0 1
#define UNIFEX_PP_NOT_1 0
#define UNIFEX_PP_EMPTY()
#define UNIFEX_PP_COMMA() ,
#define UNIFEX_PP_LBRACE() {
#define UNIFEX_PP_RBRACE() }
#define UNIFEX_PP_COMMA_IIF(X) \
UNIFEX_PP_IIF(X)(UNIFEX_PP_EMPTY, UNIFEX_PP_COMMA)() \
/**/
#define UNIFEX_PP_FOR_EACH(M, ...) \
UNIFEX_PP_FOR_EACH_N(UNIFEX_PP_COUNT(__VA_ARGS__), M, __VA_ARGS__)
#define UNIFEX_PP_FOR_EACH_N(N, M, ...) \
UNIFEX_PP_CAT2(UNIFEX_PP_FOR_EACH_, N)(M, __VA_ARGS__)
#define UNIFEX_PP_FOR_EACH_1(M, _1) \
M(_1)
#define UNIFEX_PP_FOR_EACH_2(M, _1, _2) \
M(_1) M(_2)
#define UNIFEX_PP_FOR_EACH_3(M, _1, _2, _3) \
M(_1) M(_2) M(_3)
#define UNIFEX_PP_FOR_EACH_4(M, _1, _2, _3, _4) \
M(_1) M(_2) M(_3) M(_4)
#define UNIFEX_PP_FOR_EACH_5(M, _1, _2, _3, _4, _5) \
M(_1) M(_2) M(_3) M(_4) M(_5)
#define UNIFEX_PP_FOR_EACH_6(M, _1, _2, _3, _4, _5, _6) \
M(_1) M(_2) M(_3) M(_4) M(_5) M(_6)
#define UNIFEX_PP_FOR_EACH_7(M, _1, _2, _3, _4, _5, _6, _7) \
M(_1) M(_2) M(_3) M(_4) M(_5) M(_6) M(_7)
#define UNIFEX_PP_FOR_EACH_8(M, _1, _2, _3, _4, _5, _6, _7, _8) \
M(_1) M(_2) M(_3) M(_4) M(_5) M(_6) M(_7) M(_8)
#define UNIFEX_PP_PROBE_EMPTY_PROBE_UNIFEX_PP_PROBE_EMPTY \
UNIFEX_PP_PROBE(~) \
#define UNIFEX_PP_PROBE_EMPTY()
#define UNIFEX_PP_IS_NOT_EMPTY(...) \
UNIFEX_PP_EVAL( \
UNIFEX_PP_CHECK, \
UNIFEX_PP_CAT( \
UNIFEX_PP_PROBE_EMPTY_PROBE_, \
UNIFEX_PP_PROBE_EMPTY __VA_ARGS__ ())) \
/**/
#define UNIFEX_PP_TAIL(_, ...) __VA_ARGS__
#define UNIFEX_CONCEPT_FRAGMENT_REQS_M0(REQ) \
UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_(REQ)(REQ)
#define UNIFEX_CONCEPT_FRAGMENT_REQS_M1(REQ) UNIFEX_PP_EXPAND REQ
#define UNIFEX_CONCEPT_FRAGMENT_REQS_(...) \
{ UNIFEX_PP_FOR_EACH(UNIFEX_CONCEPT_FRAGMENT_REQS_M, __VA_ARGS__) }
#define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_(REQ) \
UNIFEX_PP_CAT3(UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_, \
UNIFEX_PP_EVAL(UNIFEX_PP_CHECK, UNIFEX_PP_CAT3( \
UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_PROBE_, \
REQ))) \
/**/
#define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_PROBE_requires UNIFEX_PP_PROBE_N(~, 1)
#define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_PROBE_noexcept UNIFEX_PP_PROBE_N(~, 2)
#define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_PROBE_typename UNIFEX_PP_PROBE_N(~, 3)
#define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_0 UNIFEX_PP_EXPAND
#define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_1 UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_OR_NOEXCEPT
#define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_2 UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_OR_NOEXCEPT
#define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_3 UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_OR_NOEXCEPT
#define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_OR_NOEXCEPT(REQ) \
UNIFEX_PP_CAT4( \
UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_, \
REQ)
#define UNIFEX_PP_EAT_TYPENAME_PROBE_typename UNIFEX_PP_PROBE(~)
#define UNIFEX_PP_EAT_TYPENAME_SELECT_(X,...) \
UNIFEX_PP_CAT3(UNIFEX_PP_EAT_TYPENAME_SELECT_, \
UNIFEX_PP_EVAL(UNIFEX_PP_CHECK, UNIFEX_PP_CAT3( \
UNIFEX_PP_EAT_TYPENAME_PROBE_, \
X)))
#define UNIFEX_PP_EAT_TYPENAME_(...) \
UNIFEX_PP_EVAL2(UNIFEX_PP_EAT_TYPENAME_SELECT_, __VA_ARGS__,)(__VA_ARGS__)
#define UNIFEX_PP_EAT_TYPENAME_SELECT_0(...) __VA_ARGS__
#define UNIFEX_PP_EAT_TYPENAME_SELECT_1(...) \
UNIFEX_PP_CAT3(UNIFEX_PP_EAT_TYPENAME_, __VA_ARGS__)
#define UNIFEX_PP_EAT_TYPENAME_typename
#if UNIFEX_CXX_CONCEPTS || defined(UNIFEX_DOXYGEN_INVOKED)
#define UNIFEX_CONCEPT concept
#define UNIFEX_CONCEPT_FRAGMENT(NAME, ...) \
concept NAME = UNIFEX_PP_CAT(UNIFEX_CONCEPT_FRAGMENT_REQS_, __VA_ARGS__)
#define UNIFEX_CONCEPT_FRAGMENT_REQS_requires(...) \
requires(__VA_ARGS__) UNIFEX_CONCEPT_FRAGMENT_REQS_
#define UNIFEX_CONCEPT_FRAGMENT_REQS_M(REQ) \
UNIFEX_PP_CAT2(UNIFEX_CONCEPT_FRAGMENT_REQS_M, UNIFEX_PP_IS_PAREN(REQ))(REQ);
#define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_requires(...) \
requires __VA_ARGS__
#define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_typename(...) \
typename UNIFEX_PP_EAT_TYPENAME_(__VA_ARGS__)
#define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_noexcept(...) \
{ __VA_ARGS__ } noexcept
#define UNIFEX_FRAGMENT(NAME, ...) \
NAME<__VA_ARGS__>
#else
#define UNIFEX_CONCEPT inline constexpr bool
#define UNIFEX_CONCEPT_FRAGMENT(NAME, ...) \
auto NAME ## UNIFEX_CONCEPT_FRAGMENT_impl_ \
UNIFEX_CONCEPT_FRAGMENT_REQS_ ## __VA_ARGS__> {} \
template <typename... As> \
char NAME ## UNIFEX_CONCEPT_FRAGMENT_( \
::unifex::_concept::tag<As...> *, \
decltype(&NAME ## UNIFEX_CONCEPT_FRAGMENT_impl_<As...>)); \
char (&NAME ## UNIFEX_CONCEPT_FRAGMENT_(...))[2] \
/**/
#define M(ARG) ARG,
#if defined(_MSC_VER) && !defined(__clang__)
#define UNIFEX_CONCEPT_FRAGMENT_TRUE(...) \
::unifex::_concept::true_<decltype( \
UNIFEX_PP_FOR_EACH(UNIFEX_CONCEPT_FRAGMENT_REQS_M, __VA_ARGS__) \
void())>()
#else
#define UNIFEX_CONCEPT_FRAGMENT_TRUE(...) \
!(decltype(UNIFEX_PP_FOR_EACH(UNIFEX_CONCEPT_FRAGMENT_REQS_M, __VA_ARGS__) \
void(), \
false){})
#endif
#define UNIFEX_CONCEPT_FRAGMENT_REQS_requires(...) \
(__VA_ARGS__) -> std::enable_if_t<UNIFEX_CONCEPT_FRAGMENT_REQS_2_
#define UNIFEX_CONCEPT_FRAGMENT_REQS_2_(...) \
UNIFEX_CONCEPT_FRAGMENT_TRUE(__VA_ARGS__)
#define UNIFEX_CONCEPT_FRAGMENT_REQS_M(REQ) \
UNIFEX_PP_CAT2(UNIFEX_CONCEPT_FRAGMENT_REQS_M, UNIFEX_PP_IS_PAREN(REQ))(REQ),
#define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_requires(...) \
::unifex::requires_<__VA_ARGS__>
#define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_typename(...) \
static_cast<::unifex::_concept::tag<__VA_ARGS__> *>(nullptr)
#if defined(__GNUC__) && !defined(__clang__)
// GCC can't mangle noexcept expressions, so just check that the
// expression is well-formed.
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70790
#define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_noexcept(...) \
__VA_ARGS__
#else
#define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_noexcept(...) \
::unifex::requires_<noexcept(__VA_ARGS__)>
#endif
#define UNIFEX_FRAGMENT(NAME, ...) \
(1u==sizeof(NAME ## UNIFEX_CONCEPT_FRAGMENT_( \
static_cast<::unifex::_concept::tag<__VA_ARGS__> *>(nullptr), nullptr)))
#endif
////////////////////////////////////////////////////////////////////////////////
// UNIFEX_TEMPLATE
// Usage:
// UNIFEX_TEMPLATE(typename A, typename B)
// (requires Concept1<A> UNIFEX_AND Concept2<B>)
// void foo(A a, B b)
// {}
#if UNIFEX_CXX_CONCEPTS
#define UNIFEX_TEMPLATE(...) \
template <__VA_ARGS__> UNIFEX_PP_EXPAND \
/**/
#define UNIFEX_AND && \
/**/
#else
#define UNIFEX_TEMPLATE(...) \
template <__VA_ARGS__ UNIFEX_TEMPLATE_SFINAE_AUX_ \
/**/
#define UNIFEX_AND && UNIFEX_true_, int> = 0, std::enable_if_t< \
/**/
#endif
#define UNIFEX_TEMPLATE_SFINAE(...) \
template <__VA_ARGS__ UNIFEX_TEMPLATE_SFINAE_AUX_ \
/**/
#define UNIFEX_TEMPLATE_SFINAE_AUX_(...) , \
bool UNIFEX_true_ = true, \
std::enable_if_t< \
UNIFEX_PP_CAT(UNIFEX_TEMPLATE_SFINAE_AUX_3_, __VA_ARGS__) && UNIFEX_true_, \
int> = 0> \
/**/
#define UNIFEX_TEMPLATE_SFINAE_AUX_3_requires
#include <unifex/detail/prologue.hpp>
namespace unifex {
namespace _concept {
template <typename...>
struct tag;
template <class>
inline constexpr bool true_() {
return true;
}
} // namespace _concept
#if defined(__clang__) || defined(_MSC_VER)
template <bool B>
std::enable_if_t<B> requires_() {}
#else
template <bool B>
inline constexpr std::enable_if_t<B, int> requires_ = 0;
#endif
#if UNIFEX_CXX_CONCEPTS
template <typename Fn, typename... As>
concept //
callable = //
requires (Fn&& fn, As&&... as) {
((Fn&&) fn)((As&&) as...);
};
#else
template <typename Fn, typename... As>
UNIFEX_CONCEPT //
callable = //
sizeof(decltype(_is_callable::_try_call(static_cast<Fn(*)(As...)>(nullptr)))) ==
sizeof(_is_callable::yes_type);
#endif
} // namespace unifex
#include <unifex/detail/epilogue.hpp>
| 36.003257 | 108 | 0.722157 |
4427ad39d40e59376a5945a389a38c6d6adad970 | 1,654 | hpp | C++ | include/mainMenu/CharacterSelector.hpp | LeandreBl/cautious-fiesta | 21a08135253f6fea51835d81cce4a9920113fd18 | [
"Apache-2.0"
] | 3 | 2019-10-30T16:22:54.000Z | 2020-12-10T20:23:40.000Z | include/mainMenu/CharacterSelector.hpp | LeandreBl/cautious-fiesta | 21a08135253f6fea51835d81cce4a9920113fd18 | [
"Apache-2.0"
] | 63 | 2019-10-06T12:05:11.000Z | 2019-12-09T16:22:46.000Z | include/mainMenu/CharacterSelector.hpp | LeandreBl/cautious-fiesta | 21a08135253f6fea51835d81cce4a9920113fd18 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <vector>
#include <filesystem>
#include <Vnavbar.hpp>
#include "CharacterCreator.hpp"
namespace cf {
class CharacterSelector : public sfs::GameObject {
public:
CharacterSelector(const std::string &directory, const std::string &filename) noexcept
: _navbar(nullptr)
, _image(nullptr)
, _name(nullptr)
, _creator(nullptr)
, _directory(directory)
, _filename(filename)
, _hat(nullptr){};
void start(sfs::Scene &scene) noexcept;
void update(sfs::Scene &scene) noexcept;
Character charaterSelected() noexcept
{
if (_creator != nullptr) {
auto newCharacter = _creator->createCharacter();
if (newCharacter.getName() != "noName") {
addCharacter(newCharacter);
writeCharacterInFile();
}
return newCharacter;
}
float characterSelected = _characters.size() * _navbar->getValue();
return _characters.at((int)characterSelected);
};
void addCharacter(const Character &character) noexcept
{
_characters.emplace_back(character);
};
void loadCharactersFromFile() noexcept;
void writeCharacterInFile() noexcept;
void addCharacterFromCreateButton() noexcept
{
if (_creator != nullptr) {
auto _new = _creator->createCharacter();
if (_new.getName() != "noName") {
_characters.emplace_back(_new);
writeCharacterInFile();
_creator->destroy();
_creator = nullptr;
}
}
}
protected:
std::vector<Character> _characters;
sfs::Vnavbar *_navbar;
sfs::Sprite *_image;
sfs::Text *_name;
CharacterCreation *_creator;
std::filesystem::path _directory;
std::filesystem::path _filename;
std::vector<Text *> _stats;
sfs::Sprite *_hat;
};
} // namespace cf
| 24.686567 | 86 | 0.709794 |
4429aa9c53aa7fe991c3f8ed433f72345f0c99c6 | 40,689 | cc | C++ | test/allocator/test_epoch_zone_heap.cc | LaudateCorpus1/gull | 21dde19295f1f1c65458a27729d9e241ef6e0e57 | [
"MIT"
] | 8 | 2017-01-31T21:15:37.000Z | 2021-05-26T01:10:32.000Z | test/allocator/test_epoch_zone_heap.cc | LaudateCorpus1/gull | 21dde19295f1f1c65458a27729d9e241ef6e0e57 | [
"MIT"
] | 9 | 2020-03-26T13:27:23.000Z | 2022-03-30T17:02:19.000Z | test/allocator/test_epoch_zone_heap.cc | LaudateCorpus1/gull | 21dde19295f1f1c65458a27729d9e241ef6e0e57 | [
"MIT"
] | 7 | 2019-10-11T04:43:22.000Z | 2022-02-18T05:49:53.000Z | /*
* (c) Copyright 2016-2021 Hewlett Packard Enterprise Development Company LP.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the
* GNU Lesser General Public License Version 3, or (at your option)
* later with exceptions included below, or under the terms of the
* MIT license (Expat) available in COPYING file in the source tree.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As an exception, the copyright holders of this Library grant you permission
* to (i) compile an Application with the Library, and (ii) distribute the
* Application containing code generated by the Library and added to the
* Application during this compilation process under terms of your choice,
* provided you also meet the terms and conditions of the Application license.
*
*/
#include <unistd.h> // sleep
#include <list>
#include <random>
#include <limits>
#include <vector>
#include <thread>
#include <chrono>
#include <gtest/gtest.h>
#include "nvmm/memory_manager.h"
#include "test_common/test.h"
using namespace nvmm;
// random number and string generator
std::random_device r;
std::default_random_engine e1(r());
uint64_t rand_uint64(uint64_t min = 0,
uint64_t max = std::numeric_limits<uint64_t>::max()) {
std::uniform_int_distribution<uint64_t> uniform_dist(min, max);
return uniform_dist(e1);
}
// regular free
TEST(EpochZoneHeap, Free) {
PoolId pool_id = 1;
size_t size = 128 * 1024 * 1024LLU; // 128 MB
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
// allocate & free
GlobalPtr ptr = heap->Alloc(sizeof(int));
heap->Free(ptr);
// allocate again, because of immediate free, the new ptr should be the same
// as the previous ptr
GlobalPtr ptr1 = heap->Alloc(sizeof(int));
EXPECT_EQ(ptr, ptr1);
heap->Free(ptr1);
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
// delayed free
TEST(EpochZoneHeap, DelayedFree) {
PoolId pool_id = 1;
size_t size = 128 * 1024 * 1024LLU; // 128 MB
MemoryManager *mm = MemoryManager::GetInstance();
EpochManager *em = EpochManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
EpochCounter e1;
GlobalPtr ptr1;
// allocate & delayed free
{
EpochOp op(em);
e1 = op.reported_epoch();
std::cout << "first epoch " << e1 << std::endl;
ptr1 = heap->Alloc(op, sizeof(int));
heap->Free(op, ptr1);
// allocate again, because of delayed free, the new ptr should be
// different from t he
// previous ptr
GlobalPtr ptr2 = heap->Alloc(op, sizeof(int));
EXPECT_NE(ptr1, ptr2);
heap->Free(op, ptr2);
}
// wait a few epoches and make sure the background thread picks up this
// chunk and frees it
EpochCounter e2;
while (1) {
{
// Begin epoch in a new scope block so that we exit the epoch when
// we out of scope and don't block others when we then sleep.
{
EpochOp op(em);
e2 = op.reported_epoch();
}
if (e2 - e1 >= 3 && e2 % 5 == (e1 + 3) % 5) {
std::cout << "sleeping at epoch " << e2 << std::endl;
sleep(1); // making sure the background thread wakes up in this
// epoch
break;
}
}
}
while (1) {
{
EpochOp op(em);
EpochCounter e3 = op.reported_epoch();
if (e3 > e2) {
break;
}
}
}
// now the ptr that was delayed freed must have been actually freed
{
EpochOp op(em);
std::cout << "final epoch " << op.reported_epoch() << std::endl;
GlobalPtr ptr2 = heap->Alloc(op, sizeof(int));
EXPECT_EQ(ptr1, ptr2);
heap->Free(ptr2);
}
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
//
// Simple Resize
// Test case :
// 1. Create heap
// 2. Allocate it completely. Verify if allocation is from shelf 0
// 3. Resize heap
// 4. Allocat, Verify if the allocation is from shelf 1
//
TEST(EpochZoneHeap, Resize) {
PoolId pool_id = 1;
size_t min_alloc_size = 128;
size_t heap_size = min_alloc_size * 1024 * 1024LLU; // 128 MB
size_t allocated_size = 0;
size_t alloc_size = 1024 * 1024LLU; // 1MB per alloc
GlobalPtr ptr[512];
int i = 0;
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
// You should be able allocate (allocated_size - alloc_size) from the heap.
do {
ptr[i] = heap->Alloc(alloc_size);
allocated_size += alloc_size;
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),1);
i++;
} while(allocated_size < (heap_size - alloc_size)); // Loop until last item.
// Just do one more allocation in case we are able to allocate entire heap
ptr[i] = heap->Alloc(alloc_size);
if(ptr[i] != 0)
i++;
allocated_size = heap_size;
heap_size = heap_size * 2;
EXPECT_EQ(NO_ERROR, heap->Resize(heap_size));
EXPECT_EQ(heap->Size(), heap_size);
do {
ptr[i] = heap->Alloc(alloc_size);
allocated_size += alloc_size;
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),2);
i++;
} while(allocated_size < (heap_size - alloc_size)); // Loop until last item.
ptr[i] = heap->Alloc(alloc_size);
if(ptr[i]==0)
i--;
do{
heap->Free(ptr[i--]);
}while(i>=0);
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
// Resize multiple times in a loop
TEST(EpochZoneHeap, MultipleResize) {
PoolId pool_id = 1;
size_t min_alloc_size = 128;
size_t heap_size = min_alloc_size * 1024 * 1024LLU; // 128 MB
size_t resize_size = heap_size;
size_t alloc_size = heap_size/2 ;
int total_shelfs = 96;
GlobalPtr ptr[512];
GlobalPtr ptr_fail;
int i = 0, j = 0;
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
#ifdef LFSWORKAROUND
total_shelfs = 4;
#endif
for(i=0;i<total_shelfs;i++) {
ptr[i] = heap->Alloc(alloc_size);
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),i+1);
ptr_fail = heap->Alloc(alloc_size);
EXPECT_EQ(ptr_fail,(GlobalPtr)0);
heap_size += resize_size;
EXPECT_EQ(heap->Resize(heap_size), NO_ERROR);
EXPECT_EQ(heap->Size(), heap_size);
}
ptr[i] = heap->Alloc(alloc_size);
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),i+1);
ptr_fail = heap->Alloc(alloc_size);
EXPECT_EQ(ptr_fail,(GlobalPtr)0);
heap->Free(ptr[i]);
ptr[i] = heap->Alloc(alloc_size);
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),i+1);
for(j=0;j<total_shelfs;j++) {
heap->Free(ptr[j]);
}
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
#ifdef LFSWORKAROUND
sleep(10);
#endif
}
#ifndef LFSWORKAROUND
// Resize multiple times in a loop
TEST(EpochZoneHeap, MultipleResizeBoundary) {
PoolId pool_id = 1;
size_t min_alloc_size = 128;
size_t heap_size = min_alloc_size * 1024LLU; // 128 KB
size_t resize_size = heap_size;
size_t alloc_size = heap_size/2 ;
uint32_t total_resize_count = 126;
GlobalPtr ptr[512];
GlobalPtr ptr_fail;
uint32_t i = 0, j = 0;
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
// total_shelfs-1,as we have one shelf already created
for(i=0;i<total_resize_count;i++) {
ptr[i] = heap->Alloc(alloc_size);
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((uint32_t)ptr[i].GetShelfId().GetShelfIndex(),i+1);
ptr_fail = heap->Alloc(alloc_size);
EXPECT_EQ(ptr_fail,(GlobalPtr)0);
heap_size += resize_size;
EXPECT_EQ(heap->Resize(heap_size), NO_ERROR);
EXPECT_EQ(heap->Size(), heap_size);
}
ptr[i] = heap->Alloc(alloc_size);
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((uint32_t)ptr[i].GetShelfId().GetShelfIndex(),i+1);
ptr_fail = heap->Alloc(alloc_size);
EXPECT_EQ(ptr_fail,(GlobalPtr)0);
heap->Free(ptr[i]);
ptr[i] = heap->Alloc(alloc_size);
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((uint32_t)ptr[i].GetShelfId().GetShelfIndex(),i+1);
for(j=0;j<(total_resize_count + 1);j++) {
heap->Free(ptr[j]);
}
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
// Resize multiple times in a loop - until it fails.
// Failure should be graceful
TEST(EpochZoneHeap, MultipleResizeBoundaryFail) {
PoolId pool_id = 1;
size_t min_alloc_size = 128;
size_t heap_size = min_alloc_size * 1024LLU; // 128 KB
size_t resize_size = heap_size;
size_t alloc_size = heap_size/2 ;
uint32_t total_resize_count = 126;
GlobalPtr ptr[512];
GlobalPtr ptr_fail;
uint32_t i = 0, j = 0;
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
// total_shelfs-2,as we have one shelf already created
// and one more shelf for header
for(i=0;i<total_resize_count;i++) {
ptr[i] = heap->Alloc(alloc_size);
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((uint32_t)ptr[i].GetShelfId().GetShelfIndex(),i+1);
ptr_fail = heap->Alloc(alloc_size);
EXPECT_EQ(ptr_fail,(GlobalPtr)0);
heap_size += resize_size;
EXPECT_EQ(heap->Resize(heap_size), NO_ERROR);
EXPECT_EQ(heap->Size(), heap_size);
}
heap_size += resize_size;
EXPECT_EQ(heap->Resize(heap_size), HEAP_RESIZE_FAILED);
for(j=0;j<total_resize_count;j++) {
heap->Free(ptr[j]);
}
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
#endif
// Resize to a smaller size than the current size, it should not do
// anything and just return success.
TEST(EpochZoneHeap, SmallerResize) {
PoolId pool_id = 1;
int min_alloc_size = 128;
size_t alloc_size = 1024 * 1024LLU;
size_t heap_size = min_alloc_size * alloc_size; // 128 MB
size_t new_size = heap_size/2;
GlobalPtr ptr[512];
int i = 0;
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
for(i=0;i<min_alloc_size-1;i++) {
ptr[i] = heap->Alloc(alloc_size);
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),1);
}
ptr[i] = heap->Alloc(alloc_size);
EXPECT_EQ(ptr[i],(GlobalPtr)0);
// Since new size is lesser, resize wont do anything
EXPECT_EQ(NO_ERROR, heap->Resize(new_size));
std::cout<<"Total heap size= " <<heap->Size()<<std::endl;
EXPECT_EQ(heap->Size(), heap_size);
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
// Resize to add a new shelf which is non power of 2,
// EpochZoneHeap creates a shelf of size power of 2.
TEST(EpochZoneHeap, PowerOfTwoResize) {
PoolId pool_id = 1;
int min_alloc_size = 128;
size_t alloc_size = 1024 * 1024LLU;
size_t heap_size = min_alloc_size * alloc_size; // 128 MB
size_t new_size = 2 * heap_size - 10;
GlobalPtr ptr[512];
int i = 0;
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
for(i=0;i<min_alloc_size-1;i++) {
ptr[i] = heap->Alloc(alloc_size);
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),1);
}
ptr[i] = heap->Alloc(alloc_size);
EXPECT_EQ(ptr[i],(GlobalPtr)0);
// Since new size is lesser, resize wont do anything
EXPECT_EQ(NO_ERROR, heap->Resize(new_size));
std::cout<<"Total heap size= " <<heap->Size()<<std::endl;
EXPECT_EQ(heap->Size(), heap_size * 2);
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
// Verify the offset allocation method
TEST(EpochZoneHeap, OffsetAllocResize) {
PoolId pool_id = 1;
int min_alloc_size = 128;
size_t alloc_size = 1024 * 1024LLU;
size_t allocated_size = 0;
size_t heap_size = min_alloc_size * alloc_size; // 128 MB
Offset ptr[512];
int i = 0;
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
// We will be able to allocate (min_alloc_size - 1) objects of alloc_size
// in a heap size (min_alloc_size * alloc_size)
do {
ptr[i] = heap->AllocOffset(alloc_size);
allocated_size += alloc_size;
std::cout <<"ptr = "<<ptr[i]<<std::endl;
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((int)((GlobalPtr)ptr[i]).GetShelfId().GetShelfIndex(),0);
} while(allocated_size < (heap_size - alloc_size)); // Loop until last item.
ptr[i] = heap->Alloc(alloc_size);
EXPECT_EQ(ptr[i],(GlobalPtr)0);
heap_size = heap_size * 2;
EXPECT_EQ(NO_ERROR, heap->Resize(heap_size));
std::cout<<"Total heap size= " <<heap->Size()<<std::endl;
EXPECT_EQ(heap->Size(), heap_size);
allocated_size = heap_size;
do {
ptr[i] = heap->AllocOffset(alloc_size);
allocated_size += alloc_size;
std::cout <<"ptr = "<<ptr[i]<<std::endl;
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((int)((GlobalPtr)ptr[i]).GetShelfId().GetShelfIndex(),1);
} while(allocated_size < (heap_size - alloc_size)); // Loop until last item.
// Free loop
do{
heap->Free(ptr[i--]);
}while(i>=0);
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
// Allocate from heap, Resize from heap1, New space should be available heap1
TEST(EpochZoneHeap, AllocResize) {
PoolId pool_id = 1;
size_t min_alloc_size = 128;
size_t heap_size = min_alloc_size * 1024 * 1024LLU; // 128 MB
size_t allocated_size = 0;
size_t alloc_size = 1024 * 1024LLU; // 1MB per alloc
GlobalPtr ptr[512];
int i = 0;
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
// You should be able allocate (allocated_size - alloc_size) from the heap.
do {
ptr[i] = heap->Alloc(alloc_size);
allocated_size += alloc_size;
EXPECT_NE(ptr[i],(GlobalPtr)0);
EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),1);
i++;
} while(allocated_size < (heap_size - alloc_size)); // Loop until last item.
// Just do one more allocation in case we are able to allocate entire heap
ptr[i] = heap->Alloc(alloc_size);
if(ptr[i] != 0)
i++;
// Open a new heap data structure and resize
Heap *heap1;
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap1));
EXPECT_EQ(NO_ERROR, heap1->Open());
heap_size = heap_size * 2;
EXPECT_EQ(NO_ERROR, heap1->Resize(heap_size));
// Allocate from new heap data structure
ptr[i] = heap->Alloc(alloc_size);
EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),2);
// Both heap and heap1 should report same size
EXPECT_EQ(heap->Size(),heap1->Size());
std::cout<<"Allocated , gptr = "<<ptr[i]<<std::endl;
// Allocated the data items from heap, free it using heap1
do {
heap1->Free(ptr[i]);
i--;
} while (i>=0);
EXPECT_EQ(NO_ERROR, heap->Close());
EXPECT_EQ(NO_ERROR, heap1->Close());
delete heap;
delete heap1;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
}
// DelayedFree Resize test
TEST(EpochZoneHeap, DelayedFreeResize) {
PoolId pool_id = 1;
size_t heap_size = 128 * 1024 * 1024LLU; // 128 MB
size_t alloc_size = heap_size / 2;
MemoryManager *mm = MemoryManager::GetInstance();
EpochManager *em = EpochManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
EpochCounter e1;
GlobalPtr ptr1, ptr3;
// allocate & delayed free
{
EpochOp op(em);
e1 = op.reported_epoch();
std::cout << "first epoch " << e1 << std::endl;
ptr1 = heap->Alloc(op, alloc_size);
EXPECT_NE((GlobalPtr)0,ptr1);
heap->Free(op, ptr1);
// allocate again, because of delayed free, free will not happen
// and the alloc will fail.
GlobalPtr ptr2 = heap->Alloc(op, alloc_size);
EXPECT_EQ((GlobalPtr)0, ptr2);
// First shelf is full, Resize and create one more shelf
heap->Resize(heap_size * 2);
// Alloc from next shelf
ptr3 = heap->Alloc(op, alloc_size);
EXPECT_NE((GlobalPtr)0,ptr3);
heap->Free(op, ptr3);
// allocate again, because of delayed free, free will not happen
// and the alloc will fail.
ptr2 = heap->Alloc(op, alloc_size);
EXPECT_EQ((GlobalPtr)0, ptr2);
}
// wait a few epoches and make sure the background thread picks up this
// chunk and frees it
EpochCounter e2;
while (1) {
{
// Begin epoch in a new scope block so that we exit the epoch when
// we out of scope and don't block others when we then sleep.
{
EpochOp op(em);
e2 = op.reported_epoch();
}
if (e2 - e1 >= 3 && e2 % 5 == (e1 + 3) % 5) {
std::cout << "sleeping at epoch " << e2 << std::endl;
sleep(2); // making sure the background thread wakes up in this
// epoch
break;
}
}
}
while (1) {
{
EpochOp op(em);
EpochCounter e3 = op.reported_epoch();
if (e3 > e2) {
break;
}
}
}
// now the ptr that was delayed freed must have been actually freed
{
EpochOp op(em);
std::cout << "final epoch " << op.reported_epoch() << std::endl;
// Alloc should from first shelf. Verify.
GlobalPtr ptr2 = heap->Alloc(op, alloc_size);
EXPECT_EQ(ptr1, ptr2);
// Alloc should from next shelf. Verify.
GlobalPtr ptr4 = heap->Alloc(op, alloc_size);
EXPECT_EQ(ptr3, ptr4);
heap->Free(ptr2);
heap->Free(ptr4);
}
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
#ifndef LFSWORKAROUND
// Multiple DelayedFree Resize test
TEST(EpochZoneHeap, MultipleDelayedFreeResize) {
PoolId pool_id = 1;
size_t shelf_size = 128 * 1024 * 1024LLU; // 128 MB
size_t heap_size = shelf_size;
size_t alloc_size = heap_size / 4;
const int total_shelf = 16;
int total_allocs;
MemoryManager *mm = MemoryManager::GetInstance();
EpochManager *em = EpochManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
EpochCounter e1;
GlobalPtr ptr;
std::cout<<"Going to resize the heap"<<std::endl;
for (int i = 0;i<total_shelf; i++) {
heap_size += shelf_size;
EXPECT_EQ(NO_ERROR,heap->Resize(heap_size));
std::cout<<"Resize: "<<i<<" Done" <<std::endl;
}
// allocate & delayed free
{
EpochOp op(em);
e1 = op.reported_epoch();
std::cout << "first epoch " << e1 << std::endl;
total_allocs = 0;
while (1){
ptr = heap->Alloc(op, alloc_size);
if(ptr == 0)
break;
total_allocs++;
heap->Free(op, ptr);
}
EXPECT_GE (total_allocs, total_shelf * 3);
// allocate again, because of delayed free, free will not happen
// and the alloc will fail.
ptr = heap->Alloc(op, alloc_size);
EXPECT_EQ((GlobalPtr)0, ptr);
}
// wait a few epoches and make sure the background thread picks up this
// chunk and frees it
EpochCounter e2;
while (1) {
{
// Begin epoch in a new scope block so that we exit the epoch when
// we out of scope and don't block others when we then sleep.
{
EpochOp op(em);
e2 = op.reported_epoch();
}
if (e2 - e1 >= 3 && e2 % 5 == (e1 + 3) % 5) {
std::cout << "sleeping at epoch " << e2 << std::endl;
sleep(2); // making sure the background thread wakes up in this
// epoch
break;
}
}
}
while (1) {
{
EpochOp op(em);
EpochCounter e3 = op.reported_epoch();
if (e3 > e2) {
break;
}
}
}
// now the ptr that was delayed freed must have been actually freed
{
EpochOp op(em);
std::cout << "final epoch " << op.reported_epoch() << std::endl;
// Alloc should from first shelf. Verify.
for(int i = 0;i < total_allocs;i++) {
GlobalPtr ptr = heap->Alloc(op, alloc_size);
EXPECT_NE(ptr,(GlobalPtr)0);
heap->Free(op, ptr);
}
// This allocate should fail
ptr = heap->Alloc(op, alloc_size);
EXPECT_EQ((GlobalPtr)0, ptr);
}
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
// Multiple DelayedFree Resize test - Close test
TEST(EpochZoneHeap, MultipleDelayedFreeResizeClose) {
PoolId pool_id = 1;
size_t shelf_size = 128 * 1024 * 1024LLU; // 128 MB
size_t heap_size = shelf_size;
size_t alloc_size = heap_size / 4;
const int total_shelf = 16;
int total_allocs;
MemoryManager *mm = MemoryManager::GetInstance();
EpochManager *em = EpochManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
EpochCounter e1;
GlobalPtr ptr;
std::cout<<"Going to resize the heap"<<std::endl;
for (int i = 0;i<total_shelf; i++) {
heap_size += shelf_size;
EXPECT_EQ(NO_ERROR,heap->Resize(heap_size));
std::cout<<"Resize: "<<i<<" Done" <<std::endl;
}
// allocate & delayed free
{
EpochOp op(em);
e1 = op.reported_epoch();
std::cout << "first epoch " << e1 << std::endl;
total_allocs = 0;
while (1){
ptr = heap->Alloc(op, alloc_size);
if(ptr == 0)
break;
total_allocs++;
heap->Free(op, ptr);
}
EXPECT_GE (total_allocs, total_shelf * 3);
// allocate again, because of delayed free, free will not happen
// and the alloc will fail.
ptr = heap->Alloc(op, alloc_size);
EXPECT_EQ((GlobalPtr)0, ptr);
}
// Close the heap
EXPECT_EQ(NO_ERROR, heap->Close());
// Open the heap
EXPECT_EQ(NO_ERROR, heap->Open());
// wait a few epoches and make sure the background thread picks up this
// chunk and frees it
EpochCounter e2;
while (1) {
{
// Begin epoch in a new scope block so that we exit the epoch when
// we out of scope and don't block others when we then sleep.
{
EpochOp op(em);
e2 = op.reported_epoch();
}
if (e2 - e1 >= 3 && e2 % 5 == (e1 + 3) % 5) {
std::cout << "sleeping at epoch " << e2 << std::endl;
sleep(2); // making sure the background thread wakes up in this
// epoch
break;
}
}
}
while (1) {
{
EpochOp op(em);
EpochCounter e3 = op.reported_epoch();
if (e3 > e2) {
break;
}
}
}
// now the ptr that was delayed freed must have been actually freed
{
EpochOp op(em);
std::cout << "final epoch " << op.reported_epoch() << std::endl;
// Alloc should from first shelf. Verify.
for(int i = 0;i < total_allocs;i++) {
GlobalPtr ptr = heap->Alloc(op, alloc_size);
EXPECT_NE(ptr,(GlobalPtr)0);
heap->Free(op, ptr);
}
// This allocate should fail
ptr = heap->Alloc(op, alloc_size);
EXPECT_EQ((GlobalPtr)0, ptr);
}
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
#endif
//
TEST(EpochZoneHeap, Permissions) {
PoolId pool_id = 1;
size_t size = 128 * 1024 * 1024LLU; // 128 MB
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size, 128, S_IRUSR | S_IWUSR | S_IRGRP ));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size));
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
mode_t mode;
EXPECT_EQ(NO_ERROR, heap->GetPermission(&mode));
EXPECT_NE((mode_t)0, mode & S_IRGRP);
EXPECT_EQ((mode_t)0, mode & S_IWGRP);
EXPECT_EQ(NO_ERROR, heap->SetPermission(mode | S_IWGRP));
EXPECT_EQ(NO_ERROR, heap->GetPermission(&mode));
EXPECT_NE((mode_t)0, mode & S_IWGRP);
EXPECT_EQ(NO_ERROR,heap->Resize(size * 2));
EXPECT_EQ(NO_ERROR, heap->SetPermission(S_IRUSR | S_IWUSR));
EXPECT_EQ(NO_ERROR, heap->GetPermission(&mode));
EXPECT_EQ((mode_t)0, mode & (S_IRGRP | S_IWGRP));
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
// merge
TEST(EpochZoneHeap, Merge) {
PoolId pool_id = 1;
size_t size = 128 * 1024 * 1024LLU; // 128 MB
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
// in unit of 64-byte:
// [0, 8) has been allocated to the header
// [4096, 8192) has been allocated to the merge bitmap
uint64_t min_obj_size = heap->MinAllocSize();
// merge at levels < max_zone_level-2
// allocate 64 byte x 24, covering [8, 32)
GlobalPtr ptr[24];
GlobalPtr new_ptr;
#if 0
for(int i=0; i<24; i++) {
ptr[i]= heap->Alloc(min_obj_size);
}
// free 64 byte x 24
for(int i=0; i<24; i++) {
heap->Free(ptr[i]);
}
// before merge, allocate 1024 bytes
new_ptr = heap->Alloc(16*min_obj_size);
EXPECT_EQ(32*min_obj_size, new_ptr.GetOffset());
// merge
heap->Merge();
// after merge, allocate 1024 bytes
new_ptr = heap->Alloc(16*min_obj_size);
EXPECT_EQ(16*min_obj_size, new_ptr.GetOffset());
#endif
// merge at the last 3 levels
// allocate 16MB x 7
for (int i = 0; i < 7; i++) {
ptr[i] = heap->Alloc(262144 * min_obj_size);
}
// free 16MB x 7
for (int i = 0; i < 7; i++) {
heap->Free(ptr[i]);
}
// before merge, allocate 64MB
new_ptr = heap->Alloc(1048576 * min_obj_size);
EXPECT_EQ(0UL, new_ptr.GetOffset());
// merge
heap->Merge();
// after merge, allocate 64MB
new_ptr = heap->Alloc(1048576 * min_obj_size);
EXPECT_EQ(1048576 * min_obj_size, new_ptr.GetOffset());
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
// Test large pool id
TEST(EpochZoneHeap, LargePoolId) {
MemoryManager *mm = MemoryManager::GetInstance();
PoolId pool_id = 1;
for (PoolId i = 10; i <= 14; i++) {
pool_id = PoolId(1 << i);
if (i == 14)
pool_id = PoolId((1 << i) - 1);
std::cout << "Creating heap with pool id=" << pool_id << "\n";
size_t size = 128 * 1024 * 1024; // 128MB
#ifdef LFSWORKAROUND
sleep(10);
#endif
ErrorCode ret = mm->CreateHeap(pool_id, size);
assert(ret == NO_ERROR);
// acquire the heap
Heap *heap = NULL;
ret = mm->FindHeap(pool_id, &heap);
assert(ret == NO_ERROR);
// open the heap
ret = heap->Open();
assert(ret == NO_ERROR);
// use the heap
GlobalPtr ptr = heap->Alloc(
sizeof(int)); // Alloc returns a GlobalPtr consisting of a shelf ID
// and offset
assert(ptr.IsValid() == true);
int *int_ptr = (int *)mm->GlobalToLocal(
ptr); // convert the GlobalPtr into a local pointer
*int_ptr = 123;
assert(*int_ptr == 123);
heap->Free(ptr);
// close the heap
ret = heap->Close();
assert(ret == NO_ERROR);
// release the heap
delete heap;
// delete the heap
ret = mm->DestroyHeap(pool_id);
assert(ret == NO_ERROR);
}
}
// Larger data item size
TEST(EpochZoneHeap, Largeallocsize) {
PoolId pool_id = 1;
size_t size = 128 * 1024 * 1024LLU; // 128 MB
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size,512));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size,512));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
// allocate & free
GlobalPtr ptr = heap->Alloc(sizeof(int));
// allocate again, This offset should 512 + ptr
GlobalPtr ptr1 = heap->Alloc(sizeof(int));
std::cout<<"ptr :"<<ptr.GetOffset()<<std::endl;
std::cout<<"ptr1 :"<<ptr1.GetOffset()<<std::endl;
EXPECT_EQ(ptr.GetOffset()+512, ptr1.GetOffset());
heap->Free(ptr);
heap->Free(ptr1);
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
void AllocFree(Heap *heap, int cnt) {
std::cout << "Thread " << std::this_thread::get_id() << " started"
<< std::endl;
std::list<GlobalPtr> ptrs;
for (int i = 0; i < cnt; i++) {
if (rand_uint64(0, 1) == 1) {
GlobalPtr ptr = heap->Alloc(rand_uint64(0, 1024 * 1024));
if (ptr)
ptrs.push_back(ptr);
} else {
if (!ptrs.empty()) {
GlobalPtr ptr = ptrs.front();
ptrs.pop_front();
heap->Free(ptr);
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
for (auto ptr : ptrs) {
heap->Free(ptr);
}
std::cout << "Thread " << std::this_thread::get_id() << " ended"
<< std::endl;
}
// merge and concurrent alloc and free
TEST(EpochZoneHeap, MergeAllocFree) {
PoolId pool_id = 1;
size_t size = 1024 * 1024 * 1024LLU; // 1024 MB
int thread_cnt = 16;
int loop_cnt = 1000;
MemoryManager *mm = MemoryManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open());
// start the threads
std::vector<std::thread> workers;
for (int i = 0; i < thread_cnt; i++) {
workers.push_back(std::thread(AllocFree, heap, loop_cnt));
}
for (int i = 0; i < 5; i++) {
heap->Merge();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
for (auto &worker : workers) {
if (worker.joinable())
worker.join();
}
heap->Merge();
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
// No delayed free - Disable backgroundWorker thread
TEST(EpochZoneHeap, NoDelayedFree) {
PoolId pool_id = 1;
size_t size = 128 * 1024 * 1024LLU; // 128 MB
MemoryManager *mm = MemoryManager::GetInstance();
EpochManager *em = EpochManager::GetInstance();
Heap *heap = NULL;
// create a heap
EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size));
EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size));
// get the heap
EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap));
EXPECT_EQ(NO_ERROR, heap->Open(NVMM_NO_BG_THREAD));
EpochCounter e1;
GlobalPtr ptr1;
// allocate & delayed free
{
EpochOp op(em);
e1 = op.reported_epoch();
std::cout << "first epoch " << e1 << std::endl;
ptr1 = heap->Alloc(op, sizeof(int));
heap->Free(op, ptr1);
}
// wait a few epoches and make sure the background thread (if it had existed)
// picks up this chunk and frees it
EpochCounter e2;
while (1) {
{
// Begin epoch in a new scope block so that we exit the epoch when
// we out of scope and don't block others when we then sleep.
{
EpochOp op(em);
e2 = op.reported_epoch();
}
if (e2 - e1 >= 3 && e2 % 5 == (e1 + 3) % 5) {
std::cout << "sleeping at epoch " << e2 << std::endl;
sleep(1); // making sure the background thread wakes up in this
// epoch.
break;
}
}
}
while (1) {
{
EpochOp op(em);
EpochCounter e3 = op.reported_epoch();
if (e3 > e2) {
break;
}
}
}
// Since BackgroundWorker thread is disabled, delayed free will not take place.
// Next allocation will get different pointer.
{
EpochOp op(em);
std::cout << "final epoch " << op.reported_epoch() << std::endl;
GlobalPtr ptr2 = heap->Alloc(op, sizeof(int));
EXPECT_NE(ptr1, ptr2);
heap->Free(ptr2);
}
// Call Offline Free - It frees delayed freed data items
heap->OfflineFree();
{
EpochOp op(em);
std::cout << "final epoch " << op.reported_epoch() << std::endl;
GlobalPtr ptr2 = heap->Alloc(op, sizeof(int));
std::cout << "ptr2: "<<ptr2<<" ptr1: "<<ptr1<<std::endl;
// Offline free should have freed it, So ptr1 will be re-allocated.
EXPECT_EQ(ptr1, ptr2);
heap->Free(ptr2);
}
// destroy the heap
EXPECT_EQ(NO_ERROR, heap->Close());
delete heap;
EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id));
EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id));
}
int main(int argc, char **argv) {
InitTest(nvmm::trace, false);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 31.251152 | 90 | 0.602989 |
442a57ff64a6f8baded266e3cdc995a8bf515340 | 1,521 | cpp | C++ | masteruser/zoo.cpp | JasonPap/Buffer-Overflows | e8d2a981fb0f09512b85b06f8caf40e865274a94 | [
"MIT"
] | 14 | 2015-03-13T15:55:47.000Z | 2021-06-01T20:08:01.000Z | masteruser/zoo.cpp | JasonPap/Buffer-Overflows | e8d2a981fb0f09512b85b06f8caf40e865274a94 | [
"MIT"
] | 4 | 2015-03-14T16:32:45.000Z | 2015-03-15T18:04:13.000Z | masteruser/zoo.cpp | JasonPap/Buffer-Overflows | e8d2a981fb0f09512b85b06f8caf40e865274a94 | [
"MIT"
] | 4 | 2015-09-14T06:20:25.000Z | 2021-06-16T23:40:17.000Z | #include <iostream>
#include <cstdlib>
#include <cstring>
#include <getopt.h>
#define MAX_BUFFER_SIZE 256
class Animal{
private:
char name[MAX_BUFFER_SIZE];
public:
Animal() { strcpy(name, "Ylvis"); }
void set_name(char *nname) { strcpy(name, nname); }
char *get_name() { return name; }
virtual void speak() = 0;
};
class Cow : public Animal{
public:
void speak();
};
class Fox : public Animal{
public:
void speak();
};
void Cow::speak()
{
std::cout << get_name() << " says Moo.\n";
return;
}
void Fox::speak()
{
std::cout << get_name() << " says Hatee-hatee-hatee-ho.\n";
return;
}
void usage()
{
std::cout << "Usage: zoo [options]\n"
<< "Options:\n"
<< "\t-c <name> : Set cow name\n"
<< "\t-f <name> : Set fox name\n"
<< "\t-s : Instruct animals to speak\n"
<< "\t-h : Print options\n";
return;
}
int main(int argc, char *argv[])
{
Animal *a1, *a2;
bool speak = false;
char c;
if (argc < 2){
usage();
return 1;
}
a1 = new Cow;
a2 = new Fox;
while ((c = getopt(argc, argv, "hsc:f:")) != -1){
switch (c){
case 'h':
usage();
return 0;
case 's':
speak = true;
break;
case 'c':
a1 -> set_name(optarg);
break;
case 'f':
a2 -> set_name(optarg);
break;
case '?':
usage();
return 1;
}
}
if (speak){
a1 -> speak();
a2 -> speak();
}else
std::cout <<"Another silent night in the zoo\n";
delete a2;
delete a1;
return 0;
}
| 15.680412 | 61 | 0.535174 |
442ab6973bd178895d04eb4c8bad071d6ce5c757 | 3,890 | cpp | C++ | DearPyGui/src/core/AppItems/basic/mvSelectable.cpp | liu-kan/DearPyGui | dbbf03519b4eff6fc3e8fc56e31c27aa29ac7a39 | [
"MIT"
] | null | null | null | DearPyGui/src/core/AppItems/basic/mvSelectable.cpp | liu-kan/DearPyGui | dbbf03519b4eff6fc3e8fc56e31c27aa29ac7a39 | [
"MIT"
] | null | null | null | DearPyGui/src/core/AppItems/basic/mvSelectable.cpp | liu-kan/DearPyGui | dbbf03519b4eff6fc3e8fc56e31c27aa29ac7a39 | [
"MIT"
] | null | null | null | #include <utility>
#include "mvSelectable.h"
#include "mvApp.h"
#include "mvItemRegistry.h"
namespace Marvel {
void mvSelectable::InsertParser(std::map<std::string, mvPythonParser>* parsers)
{
parsers->insert({ "add_selectable", mvPythonParser({
{mvPythonDataType::String, "name"},
{mvPythonDataType::KeywordOnly},
{mvPythonDataType::Bool, "default_value", "", "False"},
{mvPythonDataType::Callable, "callback", "Registers a callback", "None"},
{mvPythonDataType::Object, "callback_data", "Callback data", "None"},
{mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"},
{mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"},
{mvPythonDataType::String, "source", "", "''"},
{mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"},
{mvPythonDataType::String, "label", "", "''"},
{mvPythonDataType::Bool, "show", "Attempt to render", "True"},
{mvPythonDataType::Bool, "span_columns", "span all columns", "False"},
}, "Adds a selectable.", "None", "Adding Widgets") });
}
mvSelectable::mvSelectable(const std::string& name, bool default_value, const std::string& dataSource)
: mvBoolPtrBase(name, default_value)
{
m_description.disableAllowed = true;
}
void mvSelectable::setEnabled(bool value)
{
if (value)
m_flags &= ~ImGuiSelectableFlags_Disabled;
else
m_flags |= ImGuiSelectableFlags_Disabled;
m_core_config.enabled = value;
}
void mvSelectable::draw()
{
auto styleManager = m_styleManager.getScopedStyleManager();
ScopedID id;
mvImGuiThemeScope scope(this);
if (ImGui::Selectable(m_label.c_str(), m_value.get(), m_flags))
mvApp::GetApp()->getCallbackRegistry().addCallback(m_core_config.callback, m_core_config.name, m_core_config.callback_data);
}
#ifndef MV_CPP
void mvSelectable::setExtraConfigDict(PyObject* dict)
{
if (dict == nullptr)
return;
// helper for bit flipping
auto flagop = [dict](const char* keyword, int flag, int& flags, bool flip)
{
if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag;
};
// window flags
flagop("span_columns", ImGuiSelectableFlags_SpanAllColumns, m_flags, false);
}
void mvSelectable::getExtraConfigDict(PyObject* dict)
{
if (dict == nullptr)
return;
// helper to check and set bit
auto checkbitset = [dict](const char* keyword, int flag, const int& flags, bool flip)
{
PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag));
};
// window flags
checkbitset("span_columns", ImGuiSelectableFlags_SpanAllColumns, m_flags, false);
}
PyObject* add_selectable(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* name;
int default_value = false;
PyObject* callback = nullptr;
PyObject* callback_data = nullptr;
const char* before = "";
const char* parent = "";
const char* source = "";
int enabled = true;
const char* label = "";
int show = true;
int span_columns = false;
//ImGuiSelectableFlags flags = ImGuiSelectableFlags_None;
if (!(*mvApp::GetApp()->getParsers())["add_selectable"].parse(args, kwargs, __FUNCTION__, &name,
&default_value, &callback, &callback_data, &parent, &before, &source, &enabled,
&label, &show, &span_columns))
return ToPyBool(false);
auto item = CreateRef<mvSelectable>(name, default_value, source);
if (callback)
Py_XINCREF(callback);
item->setCallback(callback);
if (callback_data)
Py_XINCREF(callback_data);
item->setCallbackData(callback_data);
item->checkConfigDict(kwargs);
item->setConfigDict(kwargs);
item->setExtraConfigDict(kwargs);
mvApp::GetApp()->getItemRegistry().addItemWithRuntimeChecks(item, parent, before);
return GetPyNone();
}
#endif // !MV_CPP
} | 30.155039 | 135 | 0.70437 |
442b44e77ac38337fa0e6d69bb518d1671499481 | 472 | cpp | C++ | projeto1/src/SyntaxTree.cpp | lucaspetry/lukasiewicz-compiler | 7029cc26f48c20a8479d27579a07a9e88e177bff | [
"MIT"
] | null | null | null | projeto1/src/SyntaxTree.cpp | lucaspetry/lukasiewicz-compiler | 7029cc26f48c20a8479d27579a07a9e88e177bff | [
"MIT"
] | null | null | null | projeto1/src/SyntaxTree.cpp | lucaspetry/lukasiewicz-compiler | 7029cc26f48c20a8479d27579a07a9e88e177bff | [
"MIT"
] | null | null | null | #include "SyntaxTree.h"
SyntaxTree::SyntaxTree() {
}
SyntaxTree::~SyntaxTree() {
}
void SyntaxTree::print() {
for (TreeNode* line: lines) {
std::string toPrint = line->printPreOrder();
if(toPrint.back() == ' ') {
toPrint = toPrint.substr(0, toPrint.length()-1);
}
std::cout << toPrint << std::endl;
}
}
void SyntaxTree::insertLine(TreeNode* line) {
this->lines.insert(lines.begin(), line);
} | 20.521739 | 60 | 0.559322 |
442b8734c611d250bdd535cbb037af12fd964656 | 12,534 | cpp | C++ | src/sysGCU/P2DScreen.cpp | projectPiki/pikmin2 | a431d992acde856d092889a515ecca0e07a3ea7c | [
"Unlicense"
] | 33 | 2021-12-08T11:10:59.000Z | 2022-03-26T19:59:37.000Z | src/sysGCU/P2DScreen.cpp | projectPiki/pikmin2 | a431d992acde856d092889a515ecca0e07a3ea7c | [
"Unlicense"
] | 6 | 2021-12-22T17:54:31.000Z | 2022-01-07T21:43:18.000Z | src/sysGCU/P2DScreen.cpp | projectPiki/pikmin2 | a431d992acde856d092889a515ecca0e07a3ea7c | [
"Unlicense"
] | 2 | 2022-01-04T06:00:49.000Z | 2022-01-26T07:27:28.000Z | #include "JSystem/JUT/JUTException.h"
#include "P2DScreen.h"
#include "System.h"
#include "types.h"
/*
Generated from dpostproc
.section .rodata # 0x804732E0 - 0x8049E220
.global lbl_8049A6C0
lbl_8049A6C0:
.4byte 0x50324453
.4byte 0x63726565
.4byte 0x6E2E6370
.4byte 0x70000000
.global lbl_8049A6D0
lbl_8049A6D0:
.asciz "P2Assert"
.skip 3
.4byte 0x00000000
.section .data, "wa" # 0x8049E220 - 0x804EFC20
.global __vt__Q29P2DScreen10Mgr_tuning
__vt__Q29P2DScreen10Mgr_tuning:
.4byte 0
.4byte 0
.4byte __dt__Q29P2DScreen10Mgr_tuningFv
.4byte getTypeID__9J2DScreenCFv
.4byte move__7J2DPaneFff
.4byte add__7J2DPaneFff
.4byte resize__7J2DPaneFff
.4byte setCullBack__7J2DPaneFb
.4byte setCullBack__7J2DPaneF11_GXCullMode
.4byte setAlpha__7J2DPaneFUc
.4byte setConnectParent__7J2DPaneFb
.4byte calcMtx__9J2DScreenFv
.4byte update__Q29P2DScreen3MgrFv
.4byte drawSelf__7J2DPaneFff
.4byte drawSelf__9J2DScreenFffPA3_A4_f
.4byte search__9J2DScreenFUx
.4byte searchUserInfo__9J2DScreenFUx
.4byte makeMatrix__7J2DPaneFff
.4byte makeMatrix__7J2DPaneFffff
.4byte isUsed__9J2DScreenFPC7ResTIMG
.4byte isUsed__9J2DScreenFPC7ResFONT
.4byte clearAnmTransform__9J2DScreenFv
.4byte rewriteAlpha__7J2DPaneFv
.4byte setAnimation__9J2DScreenFP10J2DAnmBase
.4byte setAnimation__9J2DScreenFP15J2DAnmTransform
.4byte setAnimation__9J2DScreenFP11J2DAnmColor
.4byte setAnimation__9J2DScreenFP16J2DAnmTexPattern
.4byte setAnimation__9J2DScreenFP19J2DAnmTextureSRTKey
.4byte setAnimation__9J2DScreenFP15J2DAnmTevRegKey
.4byte setAnimation__9J2DScreenFP20J2DAnmVisibilityFull
.4byte setAnimation__9J2DScreenFP14J2DAnmVtxColor
.4byte animationTransform__7J2DPaneFPC15J2DAnmTransform
.4byte setVisibileAnimation__7J2DPaneFP20J2DAnmVisibilityFull
.4byte setAnimationVF__9J2DScreenFP20J2DAnmVisibilityFull
.4byte setVtxColorAnimation__7J2DPaneFP14J2DAnmVtxColor
.4byte setAnimationVC__9J2DScreenFP14J2DAnmVtxColor
.4byte animationPane__7J2DPaneFPC15J2DAnmTransform
.4byte
createPane__9J2DScreenFRC18J2DScrnBlockHeaderP20JSURandomInputStreamP7J2DPaneUl
.4byte
createPane__9J2DScreenFRC18J2DScrnBlockHeaderP20JSURandomInputStreamP7J2DPaneUlP10JKRArchive
.4byte draw__Q29P2DScreen10Mgr_tuningFR8GraphicsR14J2DGrafContext
.global __vt__Q29P2DScreen3Mgr
__vt__Q29P2DScreen3Mgr:
.4byte 0
.4byte 0
.4byte __dt__Q29P2DScreen3MgrFv
.4byte getTypeID__9J2DScreenCFv
.4byte move__7J2DPaneFff
.4byte add__7J2DPaneFff
.4byte resize__7J2DPaneFff
.4byte setCullBack__7J2DPaneFb
.4byte setCullBack__7J2DPaneF11_GXCullMode
.4byte setAlpha__7J2DPaneFUc
.4byte setConnectParent__7J2DPaneFb
.4byte calcMtx__9J2DScreenFv
.4byte update__Q29P2DScreen3MgrFv
.4byte drawSelf__7J2DPaneFff
.4byte drawSelf__9J2DScreenFffPA3_A4_f
.4byte search__9J2DScreenFUx
.4byte searchUserInfo__9J2DScreenFUx
.4byte makeMatrix__7J2DPaneFff
.4byte makeMatrix__7J2DPaneFffff
.4byte isUsed__9J2DScreenFPC7ResTIMG
.4byte isUsed__9J2DScreenFPC7ResFONT
.4byte clearAnmTransform__9J2DScreenFv
.4byte rewriteAlpha__7J2DPaneFv
.4byte setAnimation__9J2DScreenFP10J2DAnmBase
.4byte setAnimation__9J2DScreenFP15J2DAnmTransform
.4byte setAnimation__9J2DScreenFP11J2DAnmColor
.4byte setAnimation__9J2DScreenFP16J2DAnmTexPattern
.4byte setAnimation__9J2DScreenFP19J2DAnmTextureSRTKey
.4byte setAnimation__9J2DScreenFP15J2DAnmTevRegKey
.4byte setAnimation__9J2DScreenFP20J2DAnmVisibilityFull
.4byte setAnimation__9J2DScreenFP14J2DAnmVtxColor
.4byte animationTransform__7J2DPaneFPC15J2DAnmTransform
.4byte setVisibileAnimation__7J2DPaneFP20J2DAnmVisibilityFull
.4byte setAnimationVF__9J2DScreenFP20J2DAnmVisibilityFull
.4byte setVtxColorAnimation__7J2DPaneFP14J2DAnmVtxColor
.4byte setAnimationVC__9J2DScreenFP14J2DAnmVtxColor
.4byte animationPane__7J2DPaneFPC15J2DAnmTransform
.4byte
createPane__9J2DScreenFRC18J2DScrnBlockHeaderP20JSURandomInputStreamP7J2DPaneUl
.4byte
createPane__9J2DScreenFRC18J2DScrnBlockHeaderP20JSURandomInputStreamP7J2DPaneUlP10JKRArchive
.4byte draw__Q29P2DScreen3MgrFR8GraphicsR14J2DGrafContext
.section .sdata2, "a" # 0x80516360 - 0x80520E40
.global lbl_80520790
lbl_80520790:
.4byte 0x00000000
.global mstTuningScaleX__Q29P2DScreen10Mgr_tuning
mstTuningScaleX__Q29P2DScreen10Mgr_tuning:
.4byte 0x3F733333
.global mstTuningScaleY__Q29P2DScreen10Mgr_tuning
mstTuningScaleY__Q29P2DScreen10Mgr_tuning:
.4byte 0x3F733333
.global mstTuningTransX__Q29P2DScreen10Mgr_tuning
mstTuningTransX__Q29P2DScreen10Mgr_tuning:
.4byte 0xC1733333
.global mstTuningTransY__Q29P2DScreen10Mgr_tuning
mstTuningTransY__Q29P2DScreen10Mgr_tuning:
.4byte 0xC1733333
.global lbl_805207A4
lbl_805207A4:
.4byte 0x3F733333
.global lbl_805207A8
lbl_805207A8:
.4byte 0xC1733333
.global lbl_805207AC
lbl_805207AC:
.float 0.5
.global lbl_805207B0
lbl_805207B0:
.4byte 0x43300000
.4byte 0x00000000
*/
/* __ct
* --INFO--
* Address: 80434AC0
* Size: 000064
*/
P2DScreen::Mgr::Mgr()
: J2DScreen()
, _118()
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
mr r31, r3
stw r30, 8(r1)
bl __ct__9J2DScreenFv
lis r3, __vt__Q29P2DScreen3Mgr@ha
addi r30, r31, 0x118
addi r0, r3, __vt__Q29P2DScreen3Mgr@l
stw r0, 0(r31)
mr r3, r30
bl __ct__5CNodeFv
lis r3, __vt__Q29P2DScreen4Node@ha
li r0, 0
addi r4, r3, __vt__Q29P2DScreen4Node@l
mr r3, r31
stw r4, 0(r30)
stw r0, 0x18(r30)
lwz r31, 0xc(r1)
lwz r30, 8(r1)
lwz r0, 0x14(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 80434B24
* Size: 000138
*/
J2DPane* P2DScreen::Mgr::addCallBack(u64 tag, P2DScreen::Node* node)
{
P2ASSERTLINE(73, (node != nullptr));
J2DPane* pane = search(tag);
if (pane != nullptr) {
node->_18 = pane;
node->doInit();
_118.add(node);
} else {
// TODO: There's stuff here... of some sort, at least.
}
return pane;
/*
stwu r1, -0x20(r1)
mflr r0
stw r0, 0x24(r1)
stw r31, 0x1c(r1)
stw r30, 0x18(r1)
or. r30, r7, r7
stw r29, 0x14(r1)
mr r29, r3
stw r5, 8(r1)
stw r6, 0xc(r1)
bne lbl_80434B6C
lis r3, lbl_8049A6C0@ha
lis r5, lbl_8049A6D0@ha
addi r3, r3, lbl_8049A6C0@l
li r4, 0x49
addi r5, r5, lbl_8049A6D0@l
crclr 6
bl panic_f__12JUTExceptionFPCciPCce
lbl_80434B6C:
mr r3, r29
lwz r5, 8(r1)
lwz r12, 0(r29)
lwz r6, 0xc(r1)
lwz r12, 0x3c(r12)
mtctr r12
bctrl
or. r31, r3, r3
beq lbl_80434BB8
stw r31, 0x18(r30)
mr r3, r30
lwz r12, 0(r30)
lwz r12, 0x18(r12)
mtctr r12
bctrl
mr r4, r30
addi r3, r29, 0x118
bl add__5CNodeFP5CNode
b lbl_80434C3C
lbl_80434BB8:
lbz r3, 8(r1)
li r0, 0x3f
extsb. r3, r3
bne lbl_80434BCC
stb r0, 8(r1)
lbl_80434BCC:
lbz r3, 9(r1)
extsb. r3, r3
bne lbl_80434BDC
stb r0, 9(r1)
lbl_80434BDC:
lbz r3, 0xa(r1)
extsb. r3, r3
bne lbl_80434BEC
stb r0, 0xa(r1)
lbl_80434BEC:
lbz r3, 0xb(r1)
extsb. r3, r3
bne lbl_80434BFC
stb r0, 0xb(r1)
lbl_80434BFC:
lbz r3, 0xc(r1)
extsb. r3, r3
bne lbl_80434C0C
stb r0, 0xc(r1)
lbl_80434C0C:
lbz r3, 0xd(r1)
extsb. r3, r3
bne lbl_80434C1C
stb r0, 0xd(r1)
lbl_80434C1C:
lbz r3, 0xe(r1)
extsb. r3, r3
bne lbl_80434C2C
stb r0, 0xe(r1)
lbl_80434C2C:
lbz r3, 0xf(r1)
extsb. r3, r3
bne lbl_80434C3C
stb r0, 0xf(r1)
lbl_80434C3C:
lwz r0, 0x24(r1)
mr r3, r31
lwz r31, 0x1c(r1)
lwz r30, 0x18(r1)
lwz r29, 0x14(r1)
mtlr r0
addi r1, r1, 0x20
blr
*/
}
/*
* --INFO--
* Address: 80434C5C
* Size: 000084
*/
void P2DScreen::Mgr::addCallBackPane(J2DPane* pane, P2DScreen::Node* node)
{
P2ASSERTLINE(97, (node != nullptr));
node->_18 = pane;
node->doInit();
_118.add(node);
}
/*
* --INFO--
* Address: 80434CE0
* Size: 00004C
*/
void P2DScreen::Mgr::update(void)
{
for (Node* node = (Node*)_118.m_child; node != nullptr; node = (Node*)node->m_next) {
node->update();
}
}
/*
* --INFO--
* Address: 80434D2C
* Size: 000080
*/
void P2DScreen::Mgr::draw(Graphics& gfx, J2DGrafContext& context)
{
J2DScreen::draw(0.0f, 0.0f, &context);
for (Node* node = (Node*)_118.m_child; node != nullptr; node = (Node*)node->m_next) {
node->draw(gfx, context);
}
}
/*
* --INFO--
* Address: 80434DAC
* Size: 000088
*/
P2DScreen::Mgr_tuning::Mgr_tuning(void)
: Mgr()
, m_widthMaybe(0.95f)
, m_heightMaybe(0.95f)
, m_someX(-15.2f)
, m_someY(-15.2f)
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
mr r31, r3
stw r30, 8(r1)
bl __ct__9J2DScreenFv
lis r3, __vt__Q29P2DScreen3Mgr@ha
addi r30, r31, 0x118
addi r0, r3, __vt__Q29P2DScreen3Mgr@l
stw r0, 0(r31)
mr r3, r30
bl __ct__5CNodeFv
lis r4, __vt__Q29P2DScreen4Node@ha
lis r3, __vt__Q29P2DScreen10Mgr_tuning@ha
addi r0, r4, __vt__Q29P2DScreen4Node@l
li r4, 0
stw r0, 0(r30)
addi r0, r3, __vt__Q29P2DScreen10Mgr_tuning@l
lfs f1, lbl_805207A4@sda21(r2)
mr r3, r31
stw r4, 0x18(r30)
lfs f0, lbl_805207A8@sda21(r2)
stw r0, 0(r31)
stfs f1, 0x138(r31)
stfs f1, 0x13c(r31)
stfs f0, 0x140(r31)
stfs f0, 0x144(r31)
lwz r31, 0xc(r1)
lwz r30, 8(r1)
lwz r0, 0x14(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/* draw__Q29P2DScreen10Mgr_tuningFR8GraphicsR14J2DGrafContext
* --INFO--
* Address: 80434E34
* Size: 000128
*/
void P2DScreen::Mgr_tuning::draw(Graphics& gfx, J2DGrafContext& context)
{
float xfb = (float)System::getRenderModeObj()->xfbHeight;
float efb = (float)System::getRenderModeObj()->efbHeight;
rotate(xfb * 0.5f, efb * 0.5f, 0x7A, 0.0f);
m_scale.x = m_widthMaybe;
m_scale.y = m_heightMaybe;
calcMtx();
_0D4[0] = m_someX;
_0D4[1] = m_someY;
calcMtx();
Mgr::draw(gfx, context);
/*
stwu r1, -0x30(r1)
mflr r0
stw r0, 0x34(r1)
stw r31, 0x2c(r1)
stw r30, 0x28(r1)
mr r30, r5
stw r29, 0x24(r1)
mr r29, r4
stw r28, 0x20(r1)
mr r28, r3
bl getRenderModeObj__6SystemFv
lhz r31, 4(r3)
bl getRenderModeObj__6SystemFv
lhz r5, 6(r3)
lis r0, 0x4330
stw r31, 0xc(r1)
mr r3, r28
lfd f2, lbl_805207B0@sda21(r2)
li r4, 0x7a
stw r0, 8(r1)
lfs f4, lbl_805207AC@sda21(r2)
lfd f0, 8(r1)
stw r5, 0x14(r1)
fsubs f1, f0, f2
lfs f3, lbl_80520790@sda21(r2)
stw r0, 0x10(r1)
lfd f0, 0x10(r1)
fmuls f1, f4, f1
fsubs f0, f0, f2
fmuls f2, f4, f0
bl rotate__7J2DPaneFff13J2DRotateAxisf
lfs f1, 0x13c(r28)
mr r3, r28
lfs f0, 0x138(r28)
stfs f0, 0xcc(r28)
stfs f1, 0xd0(r28)
lwz r12, 0(r28)
lwz r12, 0x2c(r12)
mtctr r12
bctrl
lfs f1, 0x144(r28)
mr r3, r28
lfs f0, 0x140(r28)
stfs f0, 0xd4(r28)
stfs f1, 0xd8(r28)
lwz r12, 0(r28)
lwz r12, 0x2c(r12)
mtctr r12
bctrl
lfs f1, lbl_80520790@sda21(r2)
mr r3, r28
mr r4, r30
fmr f2, f1
bl draw__9J2DScreenFffPC14J2DGrafContext
lwz r31, 0x128(r28)
b lbl_80434F34
lbl_80434F14:
mr r3, r31
mr r4, r29
lwz r12, 0(r31)
mr r5, r30
lwz r12, 0x14(r12)
mtctr r12
bctrl
lwz r31, 4(r31)
lbl_80434F34:
cmplwi r31, 0
bne lbl_80434F14
lwz r0, 0x34(r1)
lwz r31, 0x2c(r1)
lwz r30, 0x28(r1)
lwz r29, 0x24(r1)
lwz r28, 0x20(r1)
mtlr r0
addi r1, r1, 0x30
blr
*/
}
| 25.737166 | 95 | 0.655258 |
442d9a027b4d6a25aebd2c64f082ac438d192a60 | 3,960 | cc | C++ | tutorials/t1.cc | dianpeng/hge-unix | 0cade62a3494f1508cdaaa620714e69ae151e0c1 | [
"Zlib"
] | null | null | null | tutorials/t1.cc | dianpeng/hge-unix | 0cade62a3494f1508cdaaa620714e69ae151e0c1 | [
"Zlib"
] | null | null | null | tutorials/t1.cc | dianpeng/hge-unix | 0cade62a3494f1508cdaaa620714e69ae151e0c1 | [
"Zlib"
] | null | null | null | /*
** Haaf's Game Engine 1.8
** Copyright (C) 2003-2007, Relish Games
** hge.relishgames.com
**
** hge_tut05 - Using distortion mesh
*/
// Copy the files "particles.png", "menu.wav",
// "font1.fnt", "font1.png" and "trail.psi" from
// the folder "precompiled" to the folder with
// executable file. Also copy hge.dll and bass.dll
// to the same folder.
#include <hge/hge.h>
#include <hge/hgefont.h>
#include <hge/hgedistort.h>
#include <math.h>
// Pointer to the HGE interface.
// Helper classes require this to work.
HGE *hge=0;
HTEXTURE tex;
// Pointers to the HGE objects we will use
hgeDistortionMesh* dis;
hgeFont* fnt;
// Some "gameplay" variables
const int nRows=16;
const int nCols=16;
const float cellw=512.0f/(nCols-1);
const float cellh=512.0f/(nRows-1);
const float meshx=144;
const float meshy=44;
bool FrameFunc()
{
float dt=hge->Timer_GetDelta();
static float t=0.0f;
static int trans=0;
int i, j, col;
float r, a, dx, dy;
t+=dt;
// Process keys
switch(hge->Input_GetKey())
{
case HGEK_ESCAPE:
return true;
case HGEK_SPACE:
if(++trans > 2) trans=0;
dis->Clear(0xFF000000);
break;
}
// Calculate new displacements and coloring for one of the three effects
switch(trans)
{
case 0: for(i=1;i<nRows-1;i++)
for(j=1;j<nCols-1;j++)
{
dis->SetDisplacement(j,i,cosf(t*10+(i+j)/2)*5,sinf(t*10+(i+j)/2)*5,HGEDISP_NODE);
}
break;
case 1: for(i=0;i<nRows;i++)
for(j=1;j<nCols-1;j++)
{
dis->SetDisplacement(j,i,cosf(t*5+j/2)*15,0,HGEDISP_NODE);
col=int((cosf(t*5+(i+j)/2)+1)*35);
dis->SetColor(j,i,0xFF<<24 | col<<16 | col<<8 | col);
}
break;
case 2: for(i=0;i<nRows;i++)
for(j=0;j<nCols;j++)
{
r=sqrtf(powf(j-(float)nCols/2,2)+powf(i-(float)nRows/2,2));
a=r*cosf(t*2)*0.1f;
dx=sinf(a)*(i*cellh-256)+cosf(a)*(j*cellw-256);
dy=cosf(a)*(i*cellh-256)-sinf(a)*(j*cellw-256);
dis->SetDisplacement(j,i,dx,dy,HGEDISP_CENTER);
col=int((cos(r+t*4)+1)*40);
dis->SetColor(j,i,0xFF<<24 | col<<16 | (col/2)<<8);
}
break;
}
return false;
}
bool RenderFunc()
{
// Render graphics
hge->Gfx_BeginScene();
hge->Gfx_Clear(0);
dis->Render(meshx, meshy);
fnt->printf(5, 5, HGETEXT_LEFT, "dt:%.3f\nFPS:%d\n\nUse your\nSPACE!", hge->Timer_GetDelta(), hge->Timer_GetFPS());
hge->Gfx_EndScene();
return false;
}
#ifdef PLATFORM_UNIX
int main(int argc, char *argv[])
#else
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
#endif
{
hge = hgeCreate(HGE_VERSION);
hge->System_SetState(HGE_LOGFILE, "hge_tut05.log");
hge->System_SetState(HGE_FRAMEFUNC, FrameFunc);
hge->System_SetState(HGE_RENDERFUNC, RenderFunc);
hge->System_SetState(HGE_TITLE, "HGE Tutorial 05 - Using distortion mesh");
hge->System_SetState(HGE_WINDOWED, true);
hge->System_SetState(HGE_SCREENWIDTH, 800);
hge->System_SetState(HGE_SCREENHEIGHT, 600);
hge->System_SetState(HGE_SCREENBPP, 32);
hge->System_SetState(HGE_USESOUND, false);
if(hge->System_Initiate()) {
// Load sound and texture
tex=hge->Texture_Load("texture.jpg");
if(!tex)
{
// If one of the data files is not found, display
// an error message and shutdown.
#ifdef PLATFORM_UNIX
fprintf(stderr, "Error: Can't load texture.jpg\n");
#else
MessageBox(NULL, "Can't load texture.jpg", "Error", MB_OK | MB_ICONERROR | MB_APPLMODAL);
#endif
hge->System_Shutdown();
hge->Release();
return 0;
}
// Create a distortion mesh
dis=new hgeDistortionMesh(nCols, nRows);
dis->SetTexture(tex);
dis->SetTextureRect(0,0,512,512);
dis->SetBlendMode(BLEND_COLORADD | BLEND_ALPHABLEND | BLEND_ZWRITE);
dis->Clear(0xFF000000);
// Load a font
fnt=new hgeFont("font1.fnt");
// Let's rock now!
hge->System_Start();
// Delete created objects and free loaded resources
delete fnt;
delete dis;
hge->Texture_Free(tex);
}
// Clean up and shutdown
hge->System_Shutdown();
hge->Release();
return 0;
}
| 22.372881 | 116 | 0.658586 |
442e79aacca64364cf997543eca13ef35318ad63 | 4,525 | cpp | C++ | homework/Kulagin/07/main.cpp | mtrempoltsev/msu_cpp_autumn_2017 | 0e87491dc117670b99d2ca2f7e1c5efbc425ae1c | [
"MIT"
] | 10 | 2017-09-21T15:17:33.000Z | 2021-01-11T13:11:55.000Z | homework/Kulagin/07/main.cpp | mtrempoltsev/msu_cpp_autumn_2017 | 0e87491dc117670b99d2ca2f7e1c5efbc425ae1c | [
"MIT"
] | null | null | null | homework/Kulagin/07/main.cpp | mtrempoltsev/msu_cpp_autumn_2017 | 0e87491dc117670b99d2ca2f7e1c5efbc425ae1c | [
"MIT"
] | 22 | 2017-09-21T15:45:08.000Z | 2019-02-21T19:15:25.000Z | #include <iostream>
#include <cmath>
#include <cstring>
#include "src/calc.cpp"
using namespace std;
const double precision = 1e-15;
template<typename T>
void is(std::string text, T value, bool positive = true) {
const char* text_ptr = text.c_str();
Calculator<T> calc;
try {
auto result = calc.eval((char*)text_ptr);
if (abs(result - value) < precision) {
if (positive) {
cout << "'" << text << "'" << " == " << value << " - ";
cout << "ok" << endl;
} else {
cout << "'" << text << "'" << " != " << value << " - ";
cout << "not ok" << " " << "(got: " << result << ")" << endl;
}
} else {
if (positive) {
cout << "'" << text << "'" << " == " << value << " - ";
cout << "not ok" << " " << "(got: " << result << ")" << endl;
} else {
cout << "'" << text << "'" << " != " << value << " - ";
cout << "ok" << endl;
}
}
} catch (Error& e) {
if (positive) {
cout << "'" << text << "'" << " == " << value << " - ";
cout << "not ok " << endl;
} else {
cout << "'" << text << "'" << " != " << value << " - ";
cout << "ok " << endl;
}
cout << e.err_msg() << endl;
}
}
template <typename T>
void check_calc() {
const double Pi = 3.14;
const double e = 2.7;
// POSITIVE TESTS
cout << "POSITIVE TESTS:" << endl;
is<T>("1", 1);
is<T>(" 1", 1);
is<T>("+1", 1);
is<T>("-1", -1);
is<T>("1+2", 3);
is<T>("1 + 2", 3);
is<T>(" +1 + +2", 3);
is<T>(" -1 + -2", -3);
is<T>(" -1 - 2", -3);
is<T>(" -1 - -2", 1);
is<T>("2 - 6 * 2 / 2", -4);
is<T>("2 - 6 / 2 * 2", -4);
is<T>("3 + 4 * 2 - -1", 12);
is<T>("2*-2", -4);
is<T>(" +2 * -2", -4);
is<T>(" -2 * +2", -4);
is<T>("Pi", (T)Pi);
is<T>("e", (T)e);
is<T>("Pi + e", (T)Pi + (T)e);
is<T>("Pi + 3", (T)Pi + 3);
is<T>("-Pi + 4", -(T)Pi + 4);
is<T>(" +5 + Pi", 5 + (T)Pi);
is<T>(" +6 + -Pi", 6 - (T)Pi);
is<T>(" -7 - +Pi", -7 - (T)Pi);
is<T>("(1)", 1);
is<T>("(-1)", -1);
is<T>("-(1)", -1);
is<T>("-(-1)", 1);
is<T>("(Pi)", (T)Pi);
is<T>("(-Pi)", -(T)Pi);
is<T>("-(Pi)", -(T)Pi);
is<T>("-(-Pi)", (T)Pi);
is<T>("(e)", (T)e);
is<T>("(-e)", -(T)e);
is<T>("-(e)", -(T)e);
is<T>("-(-e)", (T)e);
is<T>(" ( e+3 ) + 5", (T)e + 3 + 5);
is<T>(" ( e*3 ) + 5", (T)e * 3 + 5);
is<T>("e + (3) + 4", (T)e + 3 + 4);
is<T>("e + (3 + 4) ", (T)e + (3 + 4));
is<T>("e / (5) ", (T)((T)e / 5));
is<T>("e / (6 + 7) ", (T)((T)e / (6 + 7)));
is<T>("(8 - e) / (9 + 10) ", (T)((8 - (T)e) / (9 + 10)));
is<T>("2.5", (T)2.5);
is<T>("(2.5)", (T)2.5);
is<T>("(-2.5)", -(T)2.5);
is<T>("-(2.5)", -(T)2.5);
is<T>("2.5 + 2.5", (T)5);
is<T>("2.5 + -2.5", 0);
is<T>(" -2.5 + 2.5", 0);
is<T>(" -2.5 + -2.5", (T) - 5);
is<T>(" -2.5 - -2.5", 0);
is<T>(" -2.5 * 3.25", (T)((T) - 2.5 * (T)3.25));
is<T>("2.445332664432 - 1223.434545634", (T)((T)2.445332664432 - (T)1223.434545634));
is<T>("5 + 0.", 5);
is<T>("5 + 0.", 5);
is<T>("5 + +0.", 5);
is<T>("5 + +.0", 5);
is<T>("5 - +0.", 5);
is<T>("5 - +.0", 5);
is<T>("5 - +1.", 4);
is<T>("5 - +.6", (T)4.4);
is<T>("22323232137128931", (T)22323232137128931);
cout << endl;
// NEGATIVE TESTS
cout << "NEGATIVE TESTS:" << endl;
is<T>("1 + +1", 0, false);
is<T>("2 2", 0, false);
is<T>("((3+3", 0, false);
is<T>("3+3))", 0, false);
is<T>("(3)+3)", 0, false);
is<T>("(3)+4/(5-0)", 0, false);
is<T>(".5 + 2", 0, false);
is<T>("(1 + 2", 0, false);
is<T>(")1 + 2", 0, false);
is<T>("4*+ 5", 0, false);
is<T>("5 + .", 5, false);
is<T>("2..+* 2", 0, false);
is<T>("r", 12, false);
}
int main(int argc, char** argv) {
if (argc < 3) {
cout << "Testing for 'int' type:" << endl << endl;
check_calc<int>();
cout << endl << endl << endl;
cout << "Testing for 'long' type:" << endl << endl;
check_calc<long>();
cout << endl << endl << endl;
cout << "Testing for 'double' type:" << endl;
check_calc<double>();
cout << endl;
} else {
const char* type = argv[2];
if (strcmp(type, "int") == 0 || strcmp(type, "Int") == 0) {
Calculator<int> calc;
cout << calc.eval((char*) argv[1]) << endl;
} else if (strcmp(type, "long") == 0 || strcmp(type, "Long") == 0) {
Calculator<int> calc;
cout << calc.eval((char*) argv[1]) << endl;
} else if (strcmp(type, "double") == 0 || strcmp(type, "Double") == 0) {
Calculator<double> calc;
cout << calc.eval((char*) argv[1]) << endl;
} else {
cout << "Usage: ./a.out <expression> <type>" << endl << endl;
cout << "<type>: int, long, double" << endl << endl;
cout << "Example: ./a.out '1+2' int" << endl;
}
}
return 0;
}
| 23.086735 | 86 | 0.417901 |
442f94ea5083e8f9b8e8d2d90652d22d4b0240d5 | 8,270 | cpp | C++ | process.cpp | mastmees/reflow_oven | 87cd23341e7fd70a18ddf194d513ae281879e9f3 | [
"MIT"
] | 2 | 2019-02-22T18:41:05.000Z | 2019-05-17T14:45:56.000Z | process.cpp | mastmees/reflow_oven | 87cd23341e7fd70a18ddf194d513ae281879e9f3 | [
"MIT"
] | null | null | null | process.cpp | mastmees/reflow_oven | 87cd23341e7fd70a18ddf194d513ae281879e9f3 | [
"MIT"
] | null | null | null | /* The MIT License (MIT)
Copyright (c) 2017 Madis Kaal <mast@nomad.ee>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "process.hpp"
#include "settings.hpp"
extern Button startbutton;
PID pidcontroller(10.0,0.0,0.0);
extern Oven oven;
#define SHOWPROFILE1() (PORTD|=_BV(PD4))
#define SHOWPROFILE0() (PORTD&=(~_BV(PD4)))
#define FAULT_BLINK() (PORTD^=_BV(PD4))
// assume starting at 25degC
// normal heating rate 2 degC/sec
// normal cooling rate 3 degC/sec
struct ProfileStep leadedsteps[] = {
{ ProfileStep::DOOR_CLOSE, 0},
{ 100, 60 }, // heat up to 100, this will lag and overshoot
{ 120, 30 }, // ride the overshoot to up to 150
{ 150, 40 }, // get to preheat temperature, still overshooting here
{ 150, 60 }, // stay at preheat
{ 185, 30 }, // ramp to reflow
{ 210, 20 }, // fast towards peak reflow, this will also overshoot
{ 228, 10 }, // reset controller then take last step
{ 228, 3 }, // reset controller then take last step
{ ProfileStep::DOOR_OPEN, 0},
{ 60, 60 }, // rapid cooldown
{ ProfileStep::PROCESS_DONE, 0 } // done
};
struct ProfileStep leadfreesteps[] = {
{ ProfileStep::DOOR_CLOSE,0 },
{ 100, 60 },
{ 125, 30 },
{ 160, 20 },
{ 180, 30 },
{ 200,30 }, // preheat, ramp to 200 in 90 seconds
{ 200,5 }, // hold for 5 seconds
{ 210,25 }, // ramp up to reflow temp at nominal rate
{ 235,10 },
{ 250,10 }, // ramp up to peak reflow at faster rate
{ 250,4 }, // stay at peak for 4 seconds
{ ProfileStep::DOOR_OPEN,0 },
{ 60,60 }, // cool down to 60deg
{ ProfileStep::PROCESS_DONE, 0 } // done
};
struct Profile leadedprofile = {
&leadedsteps[0],
160,
200
};
struct Profile leadfreeprofile = {
&leadfreesteps[0],
190,
215
};
void Process::SetProfile(Profile *p)
{
profile=p;
step=&p->steps[0];
while (1) {
if (step->temp==ProfileStep::PROCESS_DONE) {
state=STOPPING;
serial.print("#no steps in process?\n");
return;
}
if (step->temp==ProfileStep::DOOR_OPEN) {
oven.CoolerOn();
serial.print("#opening door\n");
step++;
continue;
}
if (step->temp==ProfileStep::DOOR_CLOSE) {
oven.CoolerOff();
serial.print("#closing door\n");
step++;
continue;
}
if (step->temp>0)
break;
step++; // safeguard for special steps not handled here
}
targettemp=step->temp;
setpoint=oven.Temperature();
if (step->seconds==0)
setpointstep=targettemp-setpoint;
else
setpointstep=(targettemp-setpoint)/step->seconds;
pidcontroller.SetSetPoint(setpoint);
pidcontroller.Reset();
runningtime=0;
}
void Process::ProcessTick()
{
float v=oven.Temperature();
if (step->seconds>runningtime) { // minimum time not expired yet
setpoint+=setpointstep;
pidcontroller.SetSetPoint(setpoint);
}
else {
pidcontroller.SetSetPoint(targettemp);
setpoint=targettemp;
if (setpointstep>=0.0) { // ramping upwards
if (v>=targettemp) {
while (1) {
step++;
if (step->temp==ProfileStep::PROCESS_DONE) {
state=STOPPING;
serial.print("#last step reached\n");
return;
}
if (step->temp==ProfileStep::DOOR_OPEN) {
oven.CoolerOn();
serial.print("#opening door\n");
continue;
}
if (step->temp==ProfileStep::DOOR_CLOSE) {
oven.CoolerOff();
serial.print("#closing door\n");
continue;
}
if (step->temp>0)
break;
}
if (step->temp==targettemp)
setpointstep=0.0;
else {
targettemp=step->temp;
if (step->seconds)
setpointstep=(targettemp-v)/step->seconds;
else
setpointstep=(targettemp-v);
}
runningtime=0;
pidcontroller.Reset();
}
}
else { // ramping downwards or steady
if (v<=targettemp) {
while (1) {
step++;
if (step->temp==ProfileStep::PROCESS_DONE) {
state=STOPPING;
serial.print("#last step reached\n");
return;
}
if (step->temp==ProfileStep::DOOR_OPEN) {
oven.CoolerOn();
serial.print("#opening door\n");
continue;
}
if (step->temp==ProfileStep::DOOR_CLOSE) {
oven.CoolerOff();
serial.print("#closing door\n");
continue;
}
if (step->temp>0)
break;
}
if (step->temp==targettemp)
setpointstep=0.0;
else {
targettemp=step->temp;
if (step->seconds)
setpointstep=(targettemp-v)/step->seconds;
else
setpointstep=targettemp-v;
}
runningtime=0;
pidcontroller.Reset();
}
}
}
runningtime++;
}
Process::Process()
{
state=STOPPING;
timestamp=(unsigned int)-1;
pidoutput=0;
profile=NULL;
pwmcounter=0;
targettemp=0.0;
setpointstep=0.0;
setpoint=0.0;
}
void Process::Run()
{
float v;
switch (state) {
case STOPPING:
serial.print("Stopping\n");
oven.Reset();
startbutton.Clear();
state=STOPPED;
break;
case STOPPED:
if (oven.IsFaulty()) {
state=FAULT;
break;
}
if (profilebutton.Pressed())
SHOWPROFILE1();
else
SHOWPROFILE0();
if (startbutton.Read())
state=STARTING;
break;
case STARTING:
pidcontroller.SetOutputLimits(-127,127);
pidcontroller.SetCoefficents(settings.P,settings.I,settings.D);
if (profilebutton.Pressed()) {
serial.print("#Lead-free profile\n");
SetProfile(&leadfreeprofile);
SHOWPROFILE1();
}
else {
serial.print("#Leaded profile\n");
SetProfile(&leadedprofile);
SHOWPROFILE0();
}
serial.print("Starting\n");
serial.print("time#i4,target#f4,setpoint#f4,temperature#f4,pidoutput#i4\n");
second_counter=0;
oven.ConvectionOn();
oven.CoolerOff();
state=RUNNING;
break;
case RUNNING:
if (oven.IsFaulty()) {
state=FAULT;
break;
}
//
if (startbutton.Read())
state=STOPPING;
//
if (timestamp!=second_counter && targettemp>=0.0) {
v=oven.Temperature();
pidoutput=pidcontroller.ProcessInput(v);
if (pidoutput>=0) {
oven.SetPWM(pidoutput);
}
else {
oven.SetPWM(0);
}
ProcessTick();
serial.print(second_counter);
serial.send(',');
serial.print(targettemp);
serial.send(',');
serial.print(setpoint);
serial.send(',');
serial.print(v);
serial.send(',');
serial.print((int32_t)pidoutput);
serial.send('\n');
}
break;
case FAULT:
serial.print("#Fault\n");
oven.Reset();
state=BLINKING;
break;
case BLINKING:
if (timestamp!=second_counter) {
FAULT_BLINK();
}
if (!oven.IsFaulty())
{
serial.print("#Fault cleared\n");
state=STOPPING;
}
break;
}
timestamp=second_counter;
}
| 26.850649 | 82 | 0.586699 |
443291baa2a8a1f8c4d2c2d3e4a7761b7f1eae63 | 2,922 | hpp | C++ | Programming Guide/Headers/Siv3D/GUITextField.hpp | Reputeless/Siv3D-Reference | d58e92885241d11612007fb9187ce0289a7ee9cb | [
"MIT"
] | 38 | 2016-01-14T13:51:13.000Z | 2021-12-29T01:49:30.000Z | Programming Guide/Headers/Siv3D/GUITextField.hpp | Reputeless/Siv3D-Reference | d58e92885241d11612007fb9187ce0289a7ee9cb | [
"MIT"
] | null | null | null | Programming Guide/Headers/Siv3D/GUITextField.hpp | Reputeless/Siv3D-Reference | d58e92885241d11612007fb9187ce0289a7ee9cb | [
"MIT"
] | 16 | 2016-01-15T11:07:51.000Z | 2021-12-29T01:49:37.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (C) 2008-2016 Ryo Suzuki
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "Fwd.hpp"
# include "IWidget.hpp"
# include "WidgetStyle.hpp"
namespace s3d
{
class GUITextField : public IWidget
{
private:
Optional<size_t> m_maxLength;
size_t m_cursorPos = 0;
String m_text;
double m_pressedPressure = 0.0;
double m_scaling = 0.0;
bool m_mouseOver = false;
bool m_hasChanged = false;
bool m_enabled = true;
bool m_active = false;
Point ItemSize() const;
Point TextRegion() const;
Rect MarginBox(const Point& offset) const;
Rect PaddingBox(const Point& offset) const;
Rect ItemBox(const Point& offset) const;
public:
static const String& Name()
{
static const String name = L"TextField";
return name;
}
static std::shared_ptr<GUITextField> Create(const Optional<size_t>& maxLength, const WidgetStyle& style = WidgetStyle())
{
return std::make_shared<GUITextField>(maxLength, true, style);
}
static std::shared_ptr<GUITextField> Create(const Optional<size_t>& maxLength, bool enabled, const WidgetStyle& style = WidgetStyle())
{
return std::make_shared<GUITextField>(maxLength, enabled, style);
}
GUITextField() {}
GUITextField(const Optional<size_t>& maxLength, bool enabled, const WidgetStyle& style);
const String& getWidgetName() const override;
Size getSize() const override;
bool forceNewLineBefore() const override;
bool forceNewLineAfter() const override;
void update(const WidgetState& state) override;
void draw(const WidgetState& state) const override;
bool& getEnabled();
bool& getActive();
const String& getText() const;
void setText(const String& text);
const Optional<size_t>& getMaxLength() const;
void setMaxLength(const Optional<size_t>& length);
Property_Get(bool, mouseOver) const;
Property_Get(bool, hasChanged) const;
};
class GUITextFieldWrapper
{
public:
using WidgetType = GUITextField;
private:
friend class GUI;
std::shared_ptr<WidgetType> m_widget;
GUITextFieldWrapper(const std::shared_ptr<WidgetType>& widget)
: m_widget(widget ? widget : std::make_shared<WidgetType>())
, enabled(m_widget->getEnabled())
, active(m_widget->getActive())
, style(m_widget->m_style) {}
GUITextFieldWrapper& operator = (const GUITextFieldWrapper&) = delete;
static const String& WidgetTypeName()
{
return WidgetType::Name();
}
public:
bool& enabled;
bool& active;
WidgetStyle& style;
Property_Get(bool, mouseOver) const;
Property_Get(bool, hasChanged) const;
Property_Get(const String&, text) const;
void setText(const String& text);
Property_Get(Optional<size_t>, maxLength) const;
void setMaxLength(const Optional<size_t>& length);
};
}
| 19.877551 | 136 | 0.689254 |
443388b6babb77ef756c43f749b560bb5f1b63f6 | 12,598 | cpp | C++ | PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gelss.cpp | diku-dk/PROX | c6be72cc253ff75589a1cac28e4e91e788376900 | [
"MIT"
] | null | null | null | PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gelss.cpp | diku-dk/PROX | c6be72cc253ff75589a1cac28e4e91e788376900 | [
"MIT"
] | null | null | null | PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gelss.cpp | diku-dk/PROX | c6be72cc253ff75589a1cac28e4e91e788376900 | [
"MIT"
] | null | null | null | //
// Copyright Jesse Manning 2007
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#include "convenience.h"
#include <boost/numeric/bindings/lapack/gelss.hpp>
// set to 1 to write test output to file, otherwise outputs to console
#define OUTPUT_TO_FILE 0
// determines which tests to run
#define TEST_SQUARE 1
#define TEST_UNDERDETERMINED 1
#define TEST_OVERDETERMINED 1
#define TEST_MULTIPLE_SOLUTION_VECTORS 1
// determines if optimal, minimal, or both workspaces are used for testing
#define USE_OPTIMAL_WORKSPACE 1
#define USE_MINIMAL_WORKSPACE 1
namespace lapack = boost::numeric::bindings::lapack;
// test function declarations
template <typename StreamType, typename MatrType, typename VecType>
int test_square_gelss(StreamType& oss);
template <typename StreamType, typename MatType, typename VecType>
int test_under_gelss(StreamType& oss);
template <typename StreamType, typename MatType, typename VecType>
int test_over_gelss(StreamType& oss);
template <typename StreamType, typename MatType, typename VecType>
int test_multiple_gelss(StreamType& oss);
template <typename StreamType, typename MatType, typename VecType>
int test_transpose_gel(StreamType& oss, const char& trans);
int main()
{
// stream for test output
typedef std::ostringstream stream_t;
stream_t oss;
#if TEST_SQUARE
oss << "Start Square Matrix Least Squares Tests" << std::endl;
oss << "Testing sgelss" << std::endl;
if (test_square_gelss<stream_t, fmat_t, fvec_t>(oss) == 0)
{
oss << "sgelss passed." << std::endl;
}
oss << "End sgelss tests" << std::endl;
oss << std::endl;
oss << "Testing dgelss" << std::endl;
if (test_square_gelss<stream_t, dmat_t, dvec_t>(oss) == 0)
{
oss << "dgelss passed." << std::endl;
}
oss << "End dgelss tests" << std::endl;
oss << std::endl;
oss << "Testing cgelss" << std::endl;
if (test_square_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)
{
oss << "cgelss passed." << std::endl;
}
oss << "End cgelss tests" << std::endl;
oss << std::endl;
oss << "Testing zgelss" << std::endl;
if (test_square_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)
{
oss << "zgelss passed." << std::endl;
}
oss << "End zgelss tests" << std::endl;
oss << std::endl;
oss << "End Square Matrix Least Squares Tests" << std::endl;
#endif
#if TEST_UNDERDETERMINED
oss << std::endl;
oss << "Start Under-determined Matrix Least Squares Test" << std::endl;
oss << "Testing sgelss" << std::endl;
if (test_under_gelss<stream_t, fmat_t, fvec_t>(oss) == 0)
{
oss << "sgelss passed." << std::endl;
}
oss << "End sgelss tests" << std::endl;
oss << std::endl;
oss << "Testing dgelss" << std::endl;
if (test_under_gelss<stream_t, dmat_t, dvec_t>(oss) == 0)
{
oss << "dgelss passed." << std::endl;
}
oss << "End dgelss tests" << std::endl;
oss << std::endl;
oss << "Testing cgelss" << std::endl;
if (test_under_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)
{
oss << "cgelss passed." << std::endl;
}
oss << "End cgelss tests" << std::endl;
oss << std::endl;
oss << "Testing zgelss" << std::endl;
if (test_under_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)
{
oss << "zgelss passed." << std::endl;
}
oss << "End zgelss tests" << std::endl;
oss << std::endl;
oss << "End Underdetermined Matrix Least Squares Tests" << std::endl;
#endif
#if TEST_OVERDETERMINED
oss << std::endl;
oss << "Start Overdetermined Matrix Least Squares Test" << std::endl;
oss << "Testing sgelss" << std::endl;
if (test_over_gelss<stream_t, fmat_t, fvec_t>(oss) == 0)
{
oss << "sgelss passed." << std::endl;
}
oss << "End sgelss tests" << std::endl;
oss << std::endl;
oss << "Testing dgelss" << std::endl;
if (test_over_gelss<stream_t, dmat_t, dvec_t>(oss) == 0)
{
oss << "dgelss passed." << std::endl;
}
oss << "End dgelss tests" << std::endl;
oss << std::endl;
oss << "Testing cgelss" << std::endl;
if (test_over_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)
{
oss << "cgelss passed." << std::endl;
}
oss << "End cgelss tests" << std::endl;
oss << std::endl;
oss << "Testing zgelss" << std::endl;
if (test_over_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)
{
oss << "zgelss passed." << std::endl;
}
oss << "End zgelss tests" << std::endl;
oss << std::endl;
oss << "End Overdetermined Matrix Least Squares Test" << std::endl;
#endif
#if TEST_MULTIPLE_SOLUTION_VECTORS
oss << std::endl;
oss << "Start Multiple Solution Vectors Least Squares Test" << std::endl;
oss << "Testing sgelss" << std::endl;
if (test_multiple_gelss<stream_t, fmat_t, fvec_t>(oss) == 0)
{
oss << "sgelss passed." << std::endl;
}
oss << "End sgelss tests" << std::endl;
oss << std::endl;
oss << "Testing dgelss" << std::endl;
if (test_multiple_gelss<stream_t, dmat_t, dvec_t>(oss) == 0)
{
oss << "dgelss passed." << std::endl;
}
oss << "End dgelss tests" << std::endl;
oss << std::endl;
oss << "Testing cgelss" << std::endl;
if (test_multiple_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)
{
oss << "cgelss passed." << std::endl;
}
oss << "End cgelss tests" << std::endl;
oss << std::endl;
oss << "Testing zgelss" << std::endl;
if (test_multiple_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)
{
oss << "zgelss passed." << std::endl;
}
oss << "End zgelss tests" << std::endl;
oss << std::endl;
oss << "End Multiple Solution Vectors Least Squares Test" << std::endl;
#endif
#if OUTPUT_TO_FILE
// Finished testing
std::cout << std::endl;
std::cout << "Tests Completed." << std::endl;
std::cout << std::endl;
std::string filename;
std::cout << "Enter filename to write test results: ";
std::getline(std::cin, filename);
std::ofstream testFile(filename.c_str());
if (testFile)
{
testFile << oss.str();
testFile.close();
}
#else
std::cout << oss.str() << std::endl;
// Finished testing
std::cout << std::endl;
std::cout << "Tests Completed." << std::endl;
std::cout << std::endl;
#endif
// wait for user to finish
// std::string done;
// std::cout << "Press Enter to exit";
// std::getline(std::cin, done);
}
// tests square system (m-by-n where m == n)
template <typename StreamType, typename MatType, typename VecType>
int test_square_gelss(StreamType& oss)
{
// return value
int err = 0;
// square matrix test
MatType mat(MatrixGenerator<MatType>()(row_size, col_size));
VecType vec(VectorGenerator<VecType>()(row_size));
//const int m = traits::matrix_size1(mat);
const int n = traits::matrix_size2(mat);
#if USE_OPTIMAL_WORKSPACE
MatType optimalmat(mat);
VecType optimalvec(vec);
err += lapack::gelss(optimalmat, optimalvec, lapack::optimal_workspace());
VecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n)));
VecType optimal_check = ublas::prod(mat, optimalanswer);
#endif
#if USE_MINIMAL_WORKSPACE
MatType minimalmat(mat);
VecType minimalvec(vec);
err += lapack::gelss(minimalmat, minimalvec, lapack::minimal_workspace());
VecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n)));
VecType minimal_check = ublas::prod(mat, minimalanswer);
#endif
matrix_print(oss, "A", mat);
oss << std::endl;
vector_print(oss, "B", vec);
oss << std::endl;
#if USE_OPTIMAL_WORKSPACE
vector_print(oss, "optimal workspace x", optimalanswer);
oss << std::endl;
#endif
#if USE_MINIMAL_WORKSPACE
vector_print(oss, "minimal workspace x", minimalanswer);
oss << std::endl;
#endif
#if USE_OPTIMAL_WORKSPACE
// check A*x=B
vector_print(oss, "optimal A*x=B", optimal_check);
oss << std::endl;
#endif
#if USE_MINIMAL_WORKSPACE
vector_print(oss, "minimal A*x=B", minimal_check);
oss << std::endl;
#endif
return err;
}
// tests overdetermined system (m-by-n where m < n)
template <typename StreamType, typename MatType, typename VecType>
int test_under_gelss(StreamType& oss)
{
// return value
int err = 0;
// under-determined matrix test
MatType mat(MatrixGenerator<MatType>()(row_range, col_size));
VecType vec(VectorGenerator<VecType>()(row_size));
//const int m = traits::matrix_size1(mat);
const int n = traits::matrix_size2(mat);
#if USE_OPTIMAL_WORKSPACE
MatType optimalmat(mat);
VecType optimalvec(vec);
err += lapack::gelss(optimalmat, optimalvec, lapack::optimal_workspace());
VecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n)));
VecType optimal_check = ublas::prod(mat, optimalanswer);
#endif
#if USE_MINIMAL_WORKSPACE
MatType minimalmat(mat);
VecType minimalvec(vec);
err += lapack::gelss(minimalmat, minimalvec, lapack::minimal_workspace());
VecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n)));
VecType minimal_check = ublas::prod(mat, minimalanswer);
#endif
matrix_print(oss, "A", mat);
oss << std::endl;
vector_print(oss, "B", vec);
oss << std::endl;
#if USE_OPTIMAL_WORKSPACE
vector_print(oss, "optimal workspace x", optimalanswer);
oss << std::endl;
#endif
#if USE_MINIMAL_WORKSPACE
vector_print(oss, "minimal workspace x", minimalanswer);
oss << std::endl;
#endif
#if USE_OPTIMAL_WORKSPACE
// check A*x=B
vector_print(oss, "optimal A*x=B", optimal_check);
oss << std::endl;
#endif
#if USE_MINIMAL_WORKSPACE
vector_print(oss, "minimal A*x=B", minimal_check);
oss << std::endl;
#endif
return err;
}
// tests overdetermined system (m-by-n where m > n)
template <typename StreamType, typename MatType, typename VecType>
int test_over_gelss(StreamType& oss)
{
// return value
int err = 0;
// overdetermined matrix test
MatType mat(MatrixGenerator<MatType>()(row_size, col_range));
VecType vec(VectorGenerator<VecType>()(row_size));
//const int m = traits::matrix_size1(mat);
const int n = traits::matrix_size2(mat);
#if USE_OPTIMAL_WORKSPACE
MatType optimalmat(mat);
VecType optimalvec(vec);
err += lapack::gelss(optimalmat, optimalvec, lapack::optimal_workspace());
VecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n)));
VecType optimal_check = ublas::prod(mat, optimalanswer);
#endif
#if USE_MINIMAL_WORKSPACE
MatType minimalmat(mat);
VecType minimalvec(vec);
err += lapack::gelss(minimalmat, minimalvec, lapack::minimal_workspace());
VecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n)));
VecType minimal_check = ublas::prod(mat, minimalanswer);
#endif
matrix_print(oss, "A", mat);
oss << std::endl;
vector_print(oss, "B", vec);
oss << std::endl;
#if USE_OPTIMAL_WORKSPACE
vector_print(oss, "optimal workspace x", optimalanswer);
oss << std::endl;
#endif
#if USE_MINIMAL_WORKSPACE
vector_print(oss, "minimal workspace x", minimalanswer);
oss << std::endl;
#endif
#if USE_OPTIMAL_WORKSPACE
// check A*x=B
vector_print(oss, "optimal A*x=B", optimal_check);
oss << std::endl;
#endif
#if USE_MINIMAL_WORKSPACE
vector_print(oss, "minimal A*x=B", minimal_check);
oss << std::endl;
#endif
return err;
}
// tests multiple solution vectors stored column-wise in B for equation A*x=B
template <typename StreamType, typename MatType, typename VecType>
int test_multiple_gelss(StreamType& oss)
{
// return value
int err = 0;
// multiple solutions vectors test
MatType mat(MatrixGenerator<MatType>()(row_size, col_size));
MatType vec(mat.size1(), 2);
ublas::column(vec, 0) = VectorGenerator<VecType>()(mat.size1());
ublas::column(vec, 1) = VectorGenerator<VecType>()(mat.size1());
//const int m = traits::matrix_size1(mat);
const int n = traits::matrix_size2(mat);
const int nrhs = traits::matrix_size2(vec);
#if USE_OPTIMAL_WORKSPACE
MatType optimalmat(mat);
MatType optimalvec(vec);
err += lapack::gelss(optimalmat, optimalvec, lapack::optimal_workspace());
MatType optimalanswer(ublas::project(optimalvec, ublas::range(0, n), ublas::range(0, nrhs)));
MatType optimal_check = ublas::prod(mat, optimalanswer);
#endif
#if USE_MINIMAL_WORKSPACE
MatType minimalmat(mat);
MatType minimalvec(vec);
err += lapack::gelss(minimalmat, minimalvec, lapack::minimal_workspace());
MatType minimalanswer(ublas::project(minimalvec, ublas::range(0, n), ublas::range(0, nrhs)));
MatType minimal_check = ublas::prod(mat, minimalanswer);
#endif
matrix_print(oss, "A", mat);
oss << std::endl;
matrix_print(oss, "B", vec);
oss << std::endl;
#if USE_OPTIMAL_WORKSPACE
matrix_print(oss, "optimal workspace x", optimalanswer);
oss << std::endl;
#endif
#if USE_MINIMAL_WORKSPACE
matrix_print(oss, "minimal workspace x", minimalanswer);
oss << std::endl;
#endif
#if USE_OPTIMAL_WORKSPACE
// check A*x=B
matrix_print(oss, "optimal A*x=B", optimal_check);
oss << std::endl;
#endif
#if USE_MINIMAL_WORKSPACE
matrix_print(oss, "minimal A*x=B", minimal_check);
oss << std::endl;
#endif
return err;
}
| 28.631818 | 94 | 0.698285 |
4433de13cab58b0713671dab27b56af01cbcca59 | 3,282 | cpp | C++ | Crossy_Roads/WaterParticles.cpp | Daryan7/Crossy_Roads | af816aa73ba29241fb1db4722940e42be8a76102 | [
"MIT"
] | 1 | 2018-04-18T12:54:33.000Z | 2018-04-18T12:54:33.000Z | Crossy_Roads/WaterParticles.cpp | Daryan7/Crossy_Roads | af816aa73ba29241fb1db4722940e42be8a76102 | [
"MIT"
] | null | null | null | Crossy_Roads/WaterParticles.cpp | Daryan7/Crossy_Roads | af816aa73ba29241fb1db4722940e42be8a76102 | [
"MIT"
] | null | null | null | #include "WaterParticles.h"
#include "Utils.h"
#include "Object.h"
using namespace glm;
inline void compileShader(ShaderProgram& program, const string& fileName) {
Shader vShader, fShader;
string path = "shaders/" + fileName;
vShader.initFromFile(VERTEX_SHADER, path + ".vert");
if (!vShader.isCompiled()) {
cout << "Vertex Shader " + fileName + " Error" << endl;
cout << "" << vShader.log() << endl << endl;
}
fShader.initFromFile(FRAGMENT_SHADER, path + ".frag");
if (!fShader.isCompiled()) {
cout << "Fragment Shader " + fileName + " Error" << endl;
cout << "" << fShader.log() << endl << endl;
}
program.init();
program.addShader(vShader);
program.addShader(fShader);
program.link();
if (!program.isLinked()) {
cout << "Shader " + fileName + " Linking Error" << endl;
cout << "" << program.log() << endl << endl;
}
vShader.free();
fShader.free();
for (uint i = 0; i < sizeof(uniformOrder) / sizeof(string); ++i) {
program.addUniform(uniformOrder[i]);
}
}
void WaterParticleSystem::firstInit() {
compileShader(program, "simpleColor");
program.bindFragmentOutput("outColor");
colorLoc = program.addUniform("color");
lightLoc = program.addUniform("lightDir");
}
void WaterParticleSystem::init(const Assets & assets) {
GameObject::init();
mesh = assets.getCubeMesh();
texture = assets.getTexture("water_plane");
}
void WaterParticleSystem::trigger(vec3 pos, uint numParticles, vec4 color) {
this->color = color;
pos.y += mesh->getbbSize().y*0.3f/2;
this->pos = pos;
uint nParticles = numParticles + between(-5, 5);
particles.resize(nParticles);
for (uint i = 0; i < nParticles; ++i) {
float horzAngle = between(0.f, 2 * PI);
float vertAngle = between(0.f, PI / 2);
particles[i].position = pos;
particles[i].speed = vec3(cos(horzAngle)*0.2f, sin(vertAngle), sin(horzAngle)*0.2f);
particles[i].lifetime = (uint)ceil(2 * (-particles[i].speed.y / g));
particles[i].scale = 0.3f;
particles[i].state = Falling;
}
}
void WaterParticleSystem::update() {
uint j = 0;
for (uint i = 0; i < particles.size(); i++) {
particles[i].lifetime -= 1;
switch (particles[i].state) {
case Falling:
particles[i] = particles[j];
if (particles[j].lifetime > 0) {
particles[j].speed.y += g;
particles[j].position += particles[j].speed;
}
else {
particles[j].position.y = pos.y;
particles[j].state = Stopped;
particles[j].lifetime = uint(particles[i].scale / 0.01f);
}
++j;
break;
case Stopped:
if (particles[i].lifetime > 0) {
particles[j] = particles[i];
particles[j].scale += -0.01f;
++j;
}
break;
}
}
particles.resize(j);
}
void WaterParticleSystem::render(const mat4& VP, vec3 lightDir) {
if (particles.size() == 0)
return;
program.use();
program.setUniformMatrix4f(viewProjectionLoc, VP);
program.setUniform4f(colorLoc, color);
program.setUniform3f(lightLoc, lightDir);
Object object;
mesh->setProgramParams(program);
texture->use();
for (uint i = 0; i < particles.size(); ++i) {
object.setPos(particles[i].position);
object.setScale(vec3(particles[i].scale));
program.setUniformMatrix4f(modelLoc, *object.getModel());
mesh->render();
}
}
WaterParticleSystem::WaterParticleSystem()
{
}
WaterParticleSystem::~WaterParticleSystem()
{
}
| 26.467742 | 86 | 0.661792 |
443473d3a57398771341de47c25e2c5042956da2 | 6,187 | cpp | C++ | src/geometry/FilePLY.cpp | mgradysaunders/precept | 966eb19d3c8b713e11be0885cabda632cefe9878 | [
"BSD-2-Clause"
] | null | null | null | src/geometry/FilePLY.cpp | mgradysaunders/precept | 966eb19d3c8b713e11be0885cabda632cefe9878 | [
"BSD-2-Clause"
] | null | null | null | src/geometry/FilePLY.cpp | mgradysaunders/precept | 966eb19d3c8b713e11be0885cabda632cefe9878 | [
"BSD-2-Clause"
] | null | null | null | #include <pre/geometry/FilePLY>
#include <pre/string>
#include "rply.h"
namespace pre {
static void error_cb(p_ply, const char* message) {
throw std::runtime_error(message);
}
static int vertex2_cb(p_ply_argument arg) {
void* pointer = nullptr;
long index = 0;
ply_get_argument_user_data(arg, &pointer, &index);
FilePLY::Buffer2* buffer = static_cast<FilePLY::Buffer2*>(pointer);
if (index == 0) buffer->emplace_back();
buffer->back()[index] = ply_get_argument_value(arg);
return 1;
}
static int vertex3_cb(p_ply_argument arg) {
void* pointer = nullptr;
long index = 0;
ply_get_argument_user_data(arg, &pointer, &index);
FilePLY::Buffer3* buffer = static_cast<FilePLY::Buffer3*>(pointer);
if (index == 0) buffer->emplace_back();
buffer->back()[index] = ply_get_argument_value(arg);
return 1;
}
static int face_cb(p_ply_argument arg) {
void* pointer = nullptr;
long count = 0;
long index = 0;
ply_get_argument_user_data(arg, &pointer, nullptr);
ply_get_argument_property(arg, nullptr, &count, &index);
FilePLY* ply = static_cast<FilePLY*>(pointer);
if (index == -1)
ply->face_sizes.push_back(count);
else {
double value = ply_get_argument_value(arg);
if (not(value >= 0 and value == std::uint32_t(value)))
throw std::runtime_error("Bad index");
ply->face_indexes.push_back(std::uint32_t(value));
}
return 1;
}
void FilePLY::read(const std::string& filename) {
clear();
p_ply ply = ply_open(filename.c_str(), error_cb, 0, nullptr);
Scoped remember_to_close([] {}, [&] { ply_close(ply); });
if (not ply) throw make_exception("can't open "s + quote(filename));
try {
if (not ply_read_header(ply)) throw std::runtime_error("Bad header");
ply_set_read_cb(ply, "vertex", "x", vertex3_cb, &positions, 0);
ply_set_read_cb(ply, "vertex", "y", vertex3_cb, &positions, 1);
ply_set_read_cb(ply, "vertex", "z", vertex3_cb, &positions, 2);
ply_set_read_cb(ply, "vertex", "nx", vertex3_cb, &normals, 0);
ply_set_read_cb(ply, "vertex", "ny", vertex3_cb, &normals, 1);
ply_set_read_cb(ply, "vertex", "nz", vertex3_cb, &normals, 2);
ply_set_read_cb(ply, "vertex", "s", vertex2_cb, &uvs, 0);
ply_set_read_cb(ply, "vertex", "t", vertex2_cb, &uvs, 1);
ply_set_read_cb(ply, "vertex", "r", vertex3_cb, &colors, 0);
ply_set_read_cb(ply, "vertex", "g", vertex3_cb, &colors, 1);
ply_set_read_cb(ply, "vertex", "b", vertex3_cb, &colors, 2);
ply_set_read_cb(ply, "face", "vertex_indices", face_cb, this, 0);
if (not ply_read(ply))
throw std::runtime_error("Unknown failure reason");
}
catch (const std::runtime_error& error) {
throw make_exception(
"can't read "s + quote(filename) + " ("s + error.what() + ")"s);
}
}
void FilePLY::write(const std::string& filename) const {
p_ply ply =
ply_create(filename.c_str(), PLY_LITTLE_ENDIAN, error_cb, 0, nullptr);
Scoped remember_to_close([] {}, [&] { ply_close(ply); });
try {
ply_add_element(ply, "vertex", positions.size());
ply_add_scalar_property(ply, "x", PLY_FLOAT);
ply_add_scalar_property(ply, "y", PLY_FLOAT);
ply_add_scalar_property(ply, "z", PLY_FLOAT);
if (normals.size() > 0) {
ply_add_scalar_property(ply, "nx", PLY_FLOAT);
ply_add_scalar_property(ply, "ny", PLY_FLOAT);
ply_add_scalar_property(ply, "nz", PLY_FLOAT);
}
if (uvs.size() > 0) {
ply_add_scalar_property(ply, "s", PLY_FLOAT);
ply_add_scalar_property(ply, "t", PLY_FLOAT);
}
if (colors.size() > 0) {
ply_add_scalar_property(ply, "r", PLY_FLOAT);
ply_add_scalar_property(ply, "g", PLY_FLOAT);
ply_add_scalar_property(ply, "b", PLY_FLOAT);
}
ply_add_element(ply, "face", face_sizes.size());
ply_add_list_property(ply, "vertex_indices", PLY_UCHAR, PLY_UINT);
if (not ply_write_header(ply)) throw std::runtime_error("Bad header");
for (size_t index = 0; index < positions.size(); index++) {
ply_write(ply, positions[index][0]);
ply_write(ply, positions[index][1]);
ply_write(ply, positions[index][2]);
if (normals.size() > 0) {
ply_write(ply, normals[index][0]);
ply_write(ply, normals[index][1]);
ply_write(ply, normals[index][2]);
}
if (uvs.size() > 0) {
ply_write(ply, uvs[index][0]);
ply_write(ply, uvs[index][1]);
}
if (colors.size() > 0) {
ply_write(ply, colors[index][0]);
ply_write(ply, colors[index][1]);
ply_write(ply, colors[index][2]);
}
}
auto face_index = face_indexes.begin();
for (size_t face_size : face_sizes) {
ply_write(ply, face_size);
while (face_size-- != 0) ply_write(ply, *face_index++);
}
}
catch (const std::runtime_error& error) {
throw make_exception(
"can't write "s + quote(filename) + " ("s + error.what() + ")"s);
}
}
void FilePLY::triangulate() {
std::uint32_t offset = 0;
std::vector<std::uint8_t> new_face_sizes;
std::vector<std::uint32_t> new_face_indexes;
new_face_sizes.reserve(face_sizes.size());
new_face_indexes.reserve(face_indexes.size());
for (std::uint8_t face_size : face_sizes) {
for (std::uint8_t local = 1; local + 1 < face_size; local++) {
new_face_indexes.push_back(face_indexes[offset]);
new_face_indexes.push_back(face_indexes[offset + local]);
new_face_indexes.push_back(face_indexes[offset + local + 1]);
new_face_sizes.push_back(3);
}
offset += face_size;
}
std::swap(face_sizes, new_face_sizes);
std::swap(face_indexes, new_face_indexes);
}
void FilePLY::normalize_normals() {
for (Vec3<float>& v : normals) v = normalize(v);
}
} // namespace pre
| 38.91195 | 78 | 0.604008 |
44398e5574da7e2691795d3d9841388a54cbf729 | 5,694 | cpp | C++ | WebLayoutCore/Source/WebCore/platform/win/SystemInfo.cpp | gubaojian/trylearn | 74dd5c6c977f8d867d6aa360b84bc98cb82f480c | [
"MIT"
] | 1 | 2020-05-25T16:06:49.000Z | 2020-05-25T16:06:49.000Z | WebLayoutCore/Source/WebCore/platform/win/SystemInfo.cpp | gubaojian/trylearn | 74dd5c6c977f8d867d6aa360b84bc98cb82f480c | [
"MIT"
] | null | null | null | WebLayoutCore/Source/WebCore/platform/win/SystemInfo.cpp | gubaojian/trylearn | 74dd5c6c977f8d867d6aa360b84bc98cb82f480c | [
"MIT"
] | 1 | 2018-07-10T10:53:18.000Z | 2018-07-10T10:53:18.000Z | /*
* Copyright (C) 2009 Apple 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h"
#include "SystemInfo.h"
#include <windows.h>
#include <wtf/text/WTFString.h>
namespace WebCore {
WindowsVersion windowsVersion(int* major, int* minor)
{
static bool initialized = false;
static WindowsVersion version;
static int majorVersion, minorVersion;
if (!initialized) {
initialized = true;
OSVERSIONINFOEX versionInfo;
ZeroMemory(&versionInfo, sizeof(versionInfo));
versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&versionInfo));
majorVersion = versionInfo.dwMajorVersion;
minorVersion = versionInfo.dwMinorVersion;
if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32s)
version = Windows3_1;
else if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
if (!minorVersion)
version = Windows95;
else
version = (minorVersion == 10) ? Windows98 : WindowsME;
} else {
if (majorVersion == 5) {
if (!minorVersion)
version = Windows2000;
else
version = (minorVersion == 1) ? WindowsXP : WindowsServer2003;
} else if (majorVersion >= 6) {
if (versionInfo.wProductType == VER_NT_WORKSTATION)
version = (majorVersion == 6 && !minorVersion) ? WindowsVista : Windows7;
else
version = WindowsServer2008;
} else
version = (majorVersion == 4) ? WindowsNT4 : WindowsNT3;
}
}
if (major)
*major = majorVersion;
if (minor)
*minor = minorVersion;
return version;
}
static String osVersionForUAString()
{
int major, minor;
WindowsVersion version = windowsVersion(&major, &minor);
switch (version) {
case WindowsCE1:
case WindowsCE2:
case WindowsCE3:
return "Windows CE";
case WindowsCE4:
return "Windows CE .NET";
case Windows3_1:
return "Windows 3.1";
case Windows95:
return "Windows 95";
case Windows98:
return "Windows 98";
case WindowsME:
return "Windows 98; Win 9x 4.90";
case WindowsNT4:
return "WinNT4.0";
}
const char* familyName = (version >= WindowsNT3) ? "Windows NT " : "Windows CE ";
return familyName + String::number(major) + '.' + String::number(minor);
}
static bool isWOW64()
{
static bool initialized = false;
static bool wow64 = false;
if (!initialized) {
initialized = true;
HMODULE kernel32Module = GetModuleHandleA("kernel32.dll");
if (!kernel32Module)
return wow64;
typedef BOOL (WINAPI* IsWow64ProcessFunc)(HANDLE, PBOOL);
IsWow64ProcessFunc isWOW64Process = reinterpret_cast<IsWow64ProcessFunc>(GetProcAddress(kernel32Module, "IsWow64Process"));
if (isWOW64Process) {
BOOL result = FALSE;
wow64 = isWOW64Process(GetCurrentProcess(), &result) && result;
}
}
return wow64;
}
static WORD processorArchitecture()
{
static bool initialized = false;
static WORD architecture = PROCESSOR_ARCHITECTURE_INTEL;
if (!initialized) {
initialized = true;
HMODULE kernel32Module = GetModuleHandleA("kernel32.dll");
if (!kernel32Module)
return architecture;
typedef VOID (WINAPI* GetNativeSystemInfoFunc)(LPSYSTEM_INFO);
GetNativeSystemInfoFunc getNativeSystemInfo = reinterpret_cast<GetNativeSystemInfoFunc>(GetProcAddress(kernel32Module, "GetNativeSystemInfo"));
if (getNativeSystemInfo) {
SYSTEM_INFO systemInfo;
ZeroMemory(&systemInfo, sizeof(systemInfo));
getNativeSystemInfo(&systemInfo);
architecture = systemInfo.wProcessorArchitecture;
}
}
return architecture;
}
static String architectureTokenForUAString()
{
if (isWOW64())
return "; WOW64";
if (processorArchitecture() == PROCESSOR_ARCHITECTURE_AMD64)
return "; Win64; x64";
if (processorArchitecture() == PROCESSOR_ARCHITECTURE_IA64)
return "; Win64; IA64";
return String();
}
String windowsVersionForUAString()
{
return osVersionForUAString() + architectureTokenForUAString();
}
} // namespace WebCore
| 34.095808 | 151 | 0.659993 |
4439fbfbae24e450c574bb98996663db71c45fcd | 1,568 | cpp | C++ | src/main.cpp | waneon/magfy | 2ebb905cf1730a5e6f66ad9164248e303bd051c4 | [
"MIT"
] | 1 | 2022-02-27T17:41:18.000Z | 2022-02-27T17:41:18.000Z | src/main.cpp | waneon/magfy | 2ebb905cf1730a5e6f66ad9164248e303bd051c4 | [
"MIT"
] | null | null | null | src/main.cpp | waneon/magfy | 2ebb905cf1730a5e6f66ad9164248e303bd051c4 | [
"MIT"
] | null | null | null | #include <fstream>
#include <spdlog/spdlog.h>
#include <yaml-cpp/exceptions.h>
#include <yaml-cpp/yaml.h>
#if defined(MAGFY_WINDOWS)
#include <spdlog/sinks/basic_file_sink.h>
#include <windows.h>
#else
#include <spdlog/sinks/stdout_color_sinks.h>
#endif
#include "Config.h"
#include "core.h"
// global logger object
std::shared_ptr<spdlog::logger> logger;
// global hInstance object for Windows
#if defined(MAGFY_WINDOWS)
HINSTANCE g_hInstance = NULL;
#endif
#if defined(MAGFY_WINDOWS)
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine,
int nCmdShow) {
#else
int main() {
#endif
// vendor-specific configure
#if defined(MAGFY_WINDOWS)
logger = spdlog::basic_logger_mt("magfy", get_log_file());
spdlog::flush_every(std::chrono::seconds(3));
g_hInstance = hInstance;
#else
logger = spdlog::stderr_color_mt("magfy");
#endif
// parse config.yaml file
Config config;
try {
YAML::Node root = YAML::LoadFile(get_config_file());
config = root.as<Config>();
} catch (YAML::BadFile ex) {
logger->error("Config file must be placed in proper directory.");
return 1;
} catch (YAML::Exception ex) {
logger->error("Parse error => {}", ex.msg);
return 1;
}
logger->info("Successfully loaded the config file.");
// run magfy
try {
run(config);
logger->info("Terminated normally.");
return 0;
} catch (std::exception ex) {
logger->error("Terminated abnormally.");
return 1;
}
} | 24.888889 | 80 | 0.654337 |
443b5fb2354c6e5d71872c1d092f885090115c99 | 421 | hpp | C++ | include/example.hpp | gnerkus/node-api-experiments | 0688e3e29da753313e2101b1fa74abb9509132b9 | [
"MIT"
] | null | null | null | include/example.hpp | gnerkus/node-api-experiments | 0688e3e29da753313e2101b1fa74abb9509132b9 | [
"MIT"
] | null | null | null | include/example.hpp | gnerkus/node-api-experiments | 0688e3e29da753313e2101b1fa74abb9509132b9 | [
"MIT"
] | null | null | null | #include <napi.h>
#include <iostream>
using namespace std;
namespace example {
//add two integers
// this is the function to be exported
double add(double x, double y);
//add function wrapper
// this wrapper will call the function above
Napi::Value addWrapped(const Napi::CallbackInfo& info);
//Export API
Napi::Object Init(Napi::Env env, Napi::Object exports);
NODE_API_MODULE(addon, Init)
}
| 20.047619 | 57 | 0.705463 |