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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bea22392664416aacba57e1ec2c161350ba0766a | 2,751 | hpp | C++ | back/project2/include/ast_terminal.hpp | wht-github/CS323-Compilers | d49c8e61f17b18503504d11e0eca58b1f89997c4 | [
"MIT"
] | null | null | null | back/project2/include/ast_terminal.hpp | wht-github/CS323-Compilers | d49c8e61f17b18503504d11e0eca58b1f89997c4 | [
"MIT"
] | null | null | null | back/project2/include/ast_terminal.hpp | wht-github/CS323-Compilers | d49c8e61f17b18503504d11e0eca58b1f89997c4 | [
"MIT"
] | null | null | null | #ifndef AST_TERMINAL_HPP
#define AST_TERMINAL_HPP
#include "ast.hpp"
#include <string>
#include <iostream>
class Terminal : public Base
{
public:
std::string symbol;
Terminal(const std::string &_symbol) : symbol(_symbol) {}
virtual void print(int idt = 0) const
{
for (int i = 0; i < idt; i++)
std::cout << " ";
std::cout << symbol << std::endl;
}
virtual void push(const Base *_base) const
{
std::cerr << "Can't call this function for terminal" << std::endl;
(void)_base;
}
};
class ValInt : public Base
{
public:
unsigned int val;
ValInt(unsigned int _val) : val(_val) {}
virtual void print(int idt = 0) const
{
for (int i = 0; i < idt; i++)
std::cout << " ";
std::cout << "INT: " << val << std::endl;
}
virtual void push(const Base *_base) const
{
std::cerr << "Can't call this function for int" << std::endl;
(void)_base;
}
};
class ValFloat : public Base
{
public:
float val;
ValFloat(float _val) : val(_val) {}
virtual void print(int idt = 0) const
{
for (int i = 0; i < idt; i++)
std::cout << " ";
std::cout << "FLOAT: " << val << std::endl;
}
virtual void push(const Base *_base) const
{
std::cerr << "Can't call this function for float" << std::endl;
(void)_base;
}
};
class ValChar : public Base
{
public:
std::string val;
ValChar(std::string &_val) : val(_val) {}
virtual void print(int idt = 0) const
{
for (int i = 0; i < idt; i++)
std::cout << " ";
std::cout << "CHAR: " << val << std::endl;
}
virtual void push(const Base *_base) const
{
std::cerr << "Can't call this function for char" << std::endl;
(void)_base;
}
};
class ValType : public Base
{
public:
std::string val;
ValType(std::string &_val) : val(_val) {}
virtual void print(int idt = 0) const
{
for (int i = 0; i < idt; i++)
std::cout << " ";
std::cout << "TYPE: " << val << std::endl;
}
virtual void push(const Base *_base) const
{
std::cerr << "Can't call this function for type" << std::endl;
(void)_base;
}
};
class ValId : public Base
{
public:
std::string val;
ValId(std::string &_val) : val(_val) {}
virtual void print(int idt = 0) const
{
for (int i = 0; i < idt; i++)
std::cout << " ";
std::cout << "ID: " << val << std::endl;
}
virtual void push(const Base *_base) const
{
std::cerr << "Can't call this function for identifier" << std::endl;
(void)_base;
}
};
#endif | 20.377778 | 76 | 0.519084 |
bea449ef8b9f73d67cc1795b47b70625c93d379d | 2,361 | cpp | C++ | src/common.cpp | psg-mit/leto | e39312e33a309df6dd01c70a170926aa4ecaabfb | [
"MIT"
] | null | null | null | src/common.cpp | psg-mit/leto | e39312e33a309df6dd01c70a170926aa4ecaabfb | [
"MIT"
] | null | null | null | src/common.cpp | psg-mit/leto | e39312e33a309df6dd01c70a170926aa4ecaabfb | [
"MIT"
] | null | null | null | #include "common.h"
z3::expr* binop(z3::context* context,
operator_t op,
type_t type,
z3::expr* lhs,
z3::expr* rhs) {
Z3_ast rm = Z3_mk_fpa_rne(*context);
z3::expr *res = nullptr;
switch (op) {
case RPLUS:
case OPLUS:
switch (type) {
case INT:
case REAL:
case UINT:
res = new z3::expr(*lhs + *rhs);
break;
case FLOAT:
{
Z3_ast prim = Z3_mk_fpa_add(*context, rm, *lhs, *rhs);
res = new z3::expr(z3::to_expr(*context, prim));
}
break;
case BOOL:
assert(false);
break;
}
break;
case RMINUS:
case OMINUS:
switch (type) {
case INT:
case REAL:
case UINT:
res = new z3::expr(*lhs - *rhs);
break;
case FLOAT:
{
Z3_ast prim = Z3_mk_fpa_sub(*context, rm, *lhs, *rhs);
res = new z3::expr(z3::to_expr(*context, prim));
}
break;
case BOOL:
assert(false);
break;
}
break;
case RTIMES:
case OTIMES:
switch (type) {
case INT:
case REAL:
case UINT:
res = new z3::expr(*lhs * *rhs);
break;
case FLOAT:
{
Z3_ast prim = Z3_mk_fpa_mul(*context, rm, *lhs, *rhs);
res = new z3::expr(z3::to_expr(*context, prim));
}
break;
case BOOL:
assert(false);
break;
}
break;
case RDIV:
case ODIV:
switch(type) {
case INT:
case REAL:
case UINT:
res = new z3::expr(*lhs / *rhs);
break;
case FLOAT:
{
Z3_ast prim = Z3_mk_fpa_div(*context, rm, *lhs, *rhs);
res = new z3::expr(z3::to_expr(*context, prim));
}
break;
case BOOL:
assert(false);
break;
}
break;
case FREAD:
case FWRITE:
assert(false);
break;
}
assert(res);
return res;
}
z3::expr* float_val(z3::context* context, float val) {
Z3_sort fl = Z3_mk_fpa_sort_single(*context);
Z3_ast float_val = Z3_mk_fpa_numeral_float(*context, val, fl);
return new z3::expr(z3::to_expr(*context, float_val));
}
| 23.147059 | 66 | 0.466751 |
bea5412932ae445664a243bc6db51fb808638852 | 616 | hpp | C++ | Code/Engine/Math/RigidBodyBucket.hpp | pronaypeddiraju/Engine | 0ca9720a00f51340c6eb6bba07d70972489663e8 | [
"Unlicense"
] | 1 | 2021-01-25T23:53:44.000Z | 2021-01-25T23:53:44.000Z | Code/Engine/Math/RigidBodyBucket.hpp | pronaypeddiraju/Engine | 0ca9720a00f51340c6eb6bba07d70972489663e8 | [
"Unlicense"
] | null | null | null | Code/Engine/Math/RigidBodyBucket.hpp | pronaypeddiraju/Engine | 0ca9720a00f51340c6eb6bba07d70972489663e8 | [
"Unlicense"
] | 1 | 2021-01-25T23:53:46.000Z | 2021-01-25T23:53:46.000Z | //------------------------------------------------------------------------------------------------------------------------------
#pragma once
#include <vector>
#include "Engine/Math/PhysicsTypes.hpp"
//------------------------------------------------------------------------------------------------------------------------------
class Rigidbody2D;
//------------------------------------------------------------------------------------------------------------------------------
class RigidBodyBucket
{
public:
RigidBodyBucket();
~RigidBodyBucket();
std::vector<Rigidbody2D*> m_RbBucket[NUM_SIMULATION_TYPES];
}; | 36.235294 | 128 | 0.287338 |
bea5eee63b0ceec1509be64925c74c24d88fb744 | 1,964 | cpp | C++ | toonz/sources/tnztools/inputstate.cpp | morevnaproject-org/opentoonz | 3335715599092c3f173c2ffd015f09b1a0b3cb91 | [
"BSD-3-Clause"
] | 36 | 2020-05-18T22:26:35.000Z | 2022-02-19T00:09:25.000Z | toonz/sources/tnztools/inputstate.cpp | morevnaproject-org/opentoonz | 3335715599092c3f173c2ffd015f09b1a0b3cb91 | [
"BSD-3-Clause"
] | 16 | 2020-05-14T17:51:08.000Z | 2022-02-11T01:49:38.000Z | toonz/sources/tnztools/inputstate.cpp | morevnaproject-org/opentoonz | 3335715599092c3f173c2ffd015f09b1a0b3cb91 | [
"BSD-3-Clause"
] | 8 | 2020-06-12T17:01:20.000Z | 2021-09-15T07:03:12.000Z |
#include <tools/inputstate.h>
//*****************************************************************************************
// TKey static members
//*****************************************************************************************
const TKey TKey::shift(Qt::Key_Shift, true);
const TKey TKey::control(Qt::Key_Control, true);
const TKey TKey::alt(Qt::Key_Alt, true);
const TKey TKey::meta(Qt::Key_Meta, true);
Qt::Key TKey::mapKey(Qt::Key key) {
switch (key) {
case Qt::Key_AltGr:
return Qt::Key_Alt;
default:
break;
}
return key;
}
bool TKey::isModifier(Qt::Key key) {
key = mapKey(key);
return key == Qt::Key_Shift || key == Qt::Key_Control || key == Qt::Key_Alt ||
key == Qt::Key_AltGr || key == Qt::Key_Meta;
}
bool TKey::isNumber(Qt::Key key) {
key = mapKey(key);
return key >= Qt::Key_0 && key <= Qt::Key_9;
}
//*****************************************************************************************
// TInputState implementation
//*****************************************************************************************
TInputState::TInputState() : m_ticks(), m_keyHistory(new KeyHistory()) {}
TInputState::~TInputState() {}
void TInputState::touch(TTimerTicks ticks) {
if (m_ticks < ticks)
m_ticks = ticks;
else
++m_ticks;
}
TInputState::ButtonHistory::Pointer TInputState::buttonHistory(
DeviceId device) const {
ButtonHistory::Pointer &history = m_buttonHistories[device];
if (!history) history = new ButtonHistory();
return history;
}
TInputState::ButtonState::Pointer TInputState::buttonFindAny(
Button button, DeviceId &outDevice) {
for (ButtonHistoryMap::const_iterator i = m_buttonHistories.begin();
i != m_buttonHistories.end(); ++i) {
ButtonState::Pointer state = i->second->current()->find(button);
if (state) {
outDevice = i->first;
return state;
}
}
outDevice = DeviceId();
return ButtonState::Pointer();
}
| 28.057143 | 91 | 0.535642 |
bea71ffa482ff76d6c4ef7897f0d4ce830dc5fa1 | 34,635 | cc | C++ | test/TestStratum.cc | vpashka/btcpool | dab18b2bc90b3db2fb30698fc04e7e21a06acd11 | [
"MIT"
] | null | null | null | test/TestStratum.cc | vpashka/btcpool | dab18b2bc90b3db2fb30698fc04e7e21a06acd11 | [
"MIT"
] | null | null | null | test/TestStratum.cc | vpashka/btcpool | dab18b2bc90b3db2fb30698fc04e7e21a06acd11 | [
"MIT"
] | 1 | 2021-11-05T08:36:28.000Z | 2021-11-05T08:36:28.000Z | /*
The MIT License (MIT)
Copyright (c) [2016] [BTC.COM]
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 "gtest/gtest.h"
#include "Common.h"
#include "Utils.h"
#include "Stratum.h"
#include "bitcoin/BitcoinUtils.h"
#include "bitcoin/StratumBitcoin.h"
#include "rsk/RskWork.h"
#include <chainparams.h>
#include <hash.h>
#include <script/script.h>
#include <uint256.h>
#include <util.h>
#ifdef INCLUDE_BTC_KEY_IO_H
#include <key_io.h> // IsValidDestinationString for bch is not in this file.
#endif
#include <stdint.h>
TEST(Stratum, jobId2Time) {
uint64_t jobId;
// jobId: timestamp + gbtHash
// ---------- ----------
// uint32_t uint32_t
// const string jobIdStr = Strings::Format("%08x%s", (uint32_t)time(nullptr),
// gbtHash.ToString().substr(0,
// 8).c_str());
jobId = (1469002809ull << 32) | 0x00000000FFFFFFFFull;
ASSERT_EQ(jobId2Time(jobId), 1469002809u);
jobId = (1469002809ull << 32) | 0x0000000000000000ull;
ASSERT_EQ(jobId2Time(jobId), 1469002809u);
}
TEST(Stratum, Share) {
ShareBitcoin s;
ASSERT_EQ(s.isValid(), false);
ASSERT_EQ(s.score(), 0);
ASSERT_EQ(
s.toString(),
"share(jobId: 0, ip: 0.0.0.0, userId: 0, workerId: 0, "
"time: 0/1970-01-01 00:00:00, height: 0, blkBits: 00000000/inf, "
"shareDiff: 0, status: 0/Share rejected)");
IpAddress ip;
ip.fromIpv4Int(htonl(167772161));
s.set_ip(ip.toString()); // 167772161 : 10.0.0.1
ASSERT_EQ(
s.toString(),
"share(jobId: 0, ip: 10.0.0.1, userId: 0, workerId: 0, "
"time: 0/1970-01-01 00:00:00, height: 0, blkBits: 00000000/inf, "
"shareDiff: 0, status: 0/Share rejected)");
}
TEST(Stratum, Share2) {
ShareBitcoin s;
s.set_blkbits(0x1d00ffffu);
s.set_sharediff(1ll);
ASSERT_EQ(s.score(), 1ll);
s.set_blkbits(0x18050edcu);
s.set_sharediff(UINT32_MAX);
// double will be: 0.0197583
ASSERT_EQ(score2Str(s.score()), "0.0197582875516673");
}
TEST(Stratum, StratumWorker) {
StratumWorker w;
uint64_t u;
int64_t workerId;
ASSERT_EQ(w.getUserName("abcd"), "abcd");
ASSERT_EQ(
w.getUserName("abcdabcdabcdabcdabcdabcdabcd"),
"abcdabcdabcdabcdabcdabcdabcd");
ASSERT_EQ(w.getUserName("abcd."), "abcd");
ASSERT_EQ(w.getUserName("abcd.123"), "abcd");
ASSERT_EQ(w.getUserName("abcd.123.456"), "abcd");
//
// echo -n '123' |openssl dgst -sha256 -binary |openssl dgst -sha256
//
w.setUserIDAndNames(INT32_MAX, "abcd.123");
ASSERT_EQ(w.fullName_, "abcd.123");
ASSERT_EQ(w.userId_, INT32_MAX);
ASSERT_EQ(w.userName_, "abcd");
ASSERT_EQ(w.workerName_, "123");
// '123' dsha256 :
// 5a77d1e9612d350b3734f6282259b7ff0a3f87d62cfef5f35e91a5604c0490a3
// uint256 :
// a390044c60a5915ef3f5fe2cd6873f0affb7592228f634370b352d61e9d1775a
u = strtoull("a390044c60a5915e", nullptr, 16);
memcpy((uint8_t *)&workerId, (uint8_t *)&u, 8);
ASSERT_EQ(w.workerHashId_, workerId);
w.setUserIDAndNames(0, "abcdefg");
ASSERT_EQ(w.fullName_, "abcdefg.__default__");
ASSERT_EQ(w.userId_, 0);
ASSERT_EQ(w.userName_, "abcdefg");
ASSERT_EQ(w.workerName_, "__default__");
// '__default__' dsha256 :
// e00f302bc411fde77d954283be6904911742f2ac76c8e79abef5dff4e6a19770
// uint256 : 7097a1e6f4dff5be
u = strtoull("7097a1e6f4dff5be", nullptr, 16);
memcpy((uint8_t *)&workerId, (uint8_t *)&u, 8);
ASSERT_EQ(w.workerHashId_, workerId);
// check allow chars
w.setUserIDAndNames(0, "abcdefg.azAZ09-._:|^/");
ASSERT_EQ(w.workerName_, "azAZ09-._:|^/");
ASSERT_EQ(w.fullName_, "abcdefg.azAZ09-._:|^/");
// some of them are bad chars
w.setUserIDAndNames(0, "abcdefg.~!@#$%^&*()+={}|[]\\<>?,./");
ASSERT_EQ(w.workerName_, "^|./");
ASSERT_EQ(w.fullName_, "abcdefg.^|./");
// all bad chars
w.setUserIDAndNames(0, "abcdefg.~!@#$%&*()+={}[]\\<>?,");
ASSERT_EQ(w.workerName_, "__default__");
ASSERT_EQ(w.fullName_, "abcdefg.__default__");
}
TEST(JobMaker, BitcoinAddress) {
// main net
SelectParams(CBaseChainParams::MAIN);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"),
true);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"1A1zP1eP5QGefi2DMPPfTL5SLmv7DivfNa"),
false);
#ifdef CHAIN_TYPE_BTC
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"),
true);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"bc1qw508c6qejxtdg4y5r3zarvary4c5xw7kv8f3t4"),
false);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3"),
true);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"bc1qrp33g0q5c5txsp8arysrx4k6zdkfs4nde4xj0gdcccefvpysxf3qccfmv3"),
false);
#endif
#ifdef CHAIN_TYPE_BCH
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"bitcoincash:qp3wjpa3tjlj042z2wv7hahsldgwhwy0rq9sywjpyy"),
true);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"bitcoincash:qp3wjpa3tjlj142z2wv7hahsldgwhwy0rq9sywjpyy"),
false);
#endif
// test net
SelectParams(CBaseChainParams::TESTNET);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"myxopLJB19oFtNBdrAxD5Z34Aw6P8o9P8U"),
true);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"myxopLJB19oFtNBdrADD5Z34Aw6P8o9P8U"),
false);
#ifdef CHAIN_TYPE_BTC
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx"),
true);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"tb1qw508d6qejxtdg6y5r3zarvary0c5xw7kxpjzsx"),
false);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7"),
true);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"tb1qrp33g0q5c5txsp9arysrx4k6zdkgs4nce4xj0gdcccefvpysxf3q0sl5k7"),
false);
#endif
#ifdef CHAIN_TYPE_BCH
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"bchtest:qr99vqygcra4umcz374pzzz7vslrgw50ts58trd220"),
true);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"bchtest:qr99vqygcra5umcz374pzzz7vslrgw50ts58trd220"),
false);
#endif
}
TEST(Stratum, StratumJobBitcoin) {
StratumJobBitcoin sjob;
string poolCoinbaseInfo = "/BTC.COM/";
uint32_t blockVersion = 0;
bool res;
{
string gbt;
gbt += "{\"result\":{";
gbt += " \"capabilities\": [";
gbt += " \"proposal\"";
gbt += " ],";
gbt += " \"version\": 536870912,";
gbt +=
" \"previousblockhash\": "
"\"000000004f2ea239532b2e77bb46c03b86643caac3fe92959a31fd2d03979c34\",";
gbt += " \"transactions\": [";
gbt += " {";
gbt +=
" \"data\": "
"\"01000000010291939c5ae8191c2e7d4ce8eba7d6616a66482e3200037cb8b8c2d0af"
"45b445000000006a47304402204df709d9e149804e358de4b082e41d8bb21b3c9d3472"
"41b728b1362aafcb153602200d06d9b6f2eca899f43dcd62ec2efb2d9ce2e10adf0273"
"8bb908420d7db93ede012103cae98ab925e20dd6ae1f76e767e9e99bc47b3844095c68"
"600af9c775104fb36cffffffff0290f1770b000000001976a91400dc5fd62f6ee48eb8"
"ecda749eaec6824a780fdd88aca08601000000000017a914eb65573e5dd52d3d950396"
"ccbe1a47daf8f400338700000000\",";
gbt +=
" \"hash\": "
"\"bd36bd4fff574b573152e7d4f64adf2bb1c9ab0080a12f8544c351f65aca79ff\",";
gbt += " \"depends\": [";
gbt += " ],";
gbt += " \"fee\": 10000,";
gbt += " \"sigops\": 1";
gbt += " }";
gbt += " ],";
gbt += " \"coinbaseaux\": {";
gbt += " \"flags\": \"\"";
gbt += " },";
gbt += " \"coinbasevalue\": 312659655,";
gbt +=
" \"longpollid\": "
"\"000000004f2ea239532b2e77bb46c03b86643caac3fe92959a31fd2d03979c341911"
"\",";
gbt +=
" \"target\": "
"\"000000000000018ae20000000000000000000000000000000000000000000000\",";
gbt += " \"mintime\": 1469001544,";
gbt += " \"mutable\": [";
gbt += " \"time\",";
gbt += " \"transactions\",";
gbt += " \"prevblock\"";
gbt += " ],";
gbt += " \"noncerange\": \"00000000ffffffff\",";
gbt += " \"sigoplimit\": 20000,";
gbt += " \"sizelimit\": 1000000,";
gbt += " \"curtime\": 1469006933,";
gbt += " \"bits\": \"1a018ae2\",";
gbt += " \"height\": 898487";
gbt += "}}";
blockVersion = 0;
SelectParams(CBaseChainParams::TESTNET);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"myxopLJB19oFtNBdrAxD5Z34Aw6P8o9P8U"),
true);
CTxDestination poolPayoutAddrTestnet =
BitcoinUtils::DecodeDestination("myxopLJB19oFtNBdrAxD5Z34Aw6P8o9P8U");
res = sjob.initFromGbt(
gbt.c_str(),
poolCoinbaseInfo,
poolPayoutAddrTestnet,
blockVersion,
"",
RskWork(),
1,
false);
ASSERT_EQ(res, true);
const string jsonStr = sjob.serializeToJson();
StratumJobBitcoin sjob2;
res = sjob2.unserializeFromJson(jsonStr.c_str(), jsonStr.length());
ASSERT_EQ(res, true);
ASSERT_EQ(
sjob2.prevHash_,
uint256S("000000004f2ea239532b2e77bb46c03b86643caac3fe92959a31fd2d03979"
"c34"));
ASSERT_EQ(
sjob2.prevHashBeStr_,
"03979c349a31fd2dc3fe929586643caabb46c03b532b2e774f2ea23900000000");
ASSERT_EQ(sjob2.height_, 898487);
// 46 bytes, 5 bytes (timestamp), 9 bytes (poolCoinbaseInfo)
// 02000000010000000000000000000000000000000000000000000000000000000000000000ffffffff1e03b7b50d
// 0402363d58 2f4254432e434f4d2f
ASSERT_EQ(
sjob2.coinbase1_.substr(0, 92),
"0200000001000000000000000000000000000000000000000000000000000000000000"
"0000ffffffff1e03b7b50d");
ASSERT_EQ(sjob2.coinbase1_.substr(102, 18), "2f4254432e434f4d2f");
// 0402363d58 -> 0x583d3602 = 1480406530 = 2016-11-29 16:02:10
uint32_t ts =
(uint32_t)strtoull(sjob2.coinbase1_.substr(94, 8).c_str(), nullptr, 16);
ts = HToBe(ts);
ASSERT_EQ(ts == time(nullptr) || ts + 1 == time(nullptr), true);
ASSERT_EQ(
sjob2.coinbase2_,
"ffffffff" // sequence
"01" // 1 output
// c7cea21200000000 -> 0000000012a2cec7 -> 312659655
"c7cea21200000000"
// 0x19 -> 25 bytes
"1976a914ca560088c0fb5e6f028faa11085e643e343a8f5c88ac"
// lock_time
"00000000");
ASSERT_EQ(sjob2.merkleBranch_.size(), 1U);
ASSERT_EQ(
sjob2.merkleBranch_[0],
uint256S("bd36bd4fff574b573152e7d4f64adf2bb1c9ab0080a12f8544c351f65aca7"
"9ff"));
ASSERT_EQ(sjob2.nVersion_, 536870912);
ASSERT_EQ(sjob2.nBits_, 436308706U);
ASSERT_EQ(sjob2.nTime_, 1469006933U);
ASSERT_EQ(sjob2.minTime_, 1469001544U);
ASSERT_EQ(sjob2.coinbaseValue_, 312659655);
ASSERT_GE(time(nullptr), jobId2Time(sjob2.jobId_));
}
}
#ifdef CHAIN_TYPE_BTC
TEST(Stratum, StratumJobWithWitnessCommitment) {
StratumJobBitcoin sjob;
string poolCoinbaseInfo = "/BTC.COM/";
uint32_t blockVersion = 0;
bool res;
{
string gbt;
gbt += "{\"result\":";
gbt += "{";
gbt += " \"capabilities\": [";
gbt += " \"proposal\"";
gbt += " ],";
gbt += " \"version\": 536870912,";
gbt += " \"rules\": [";
gbt += " \"csv\",";
gbt += " \"!segwit\"";
gbt += " ],";
gbt += " \"vbavailable\": {";
gbt += " },";
gbt += " \"vbrequired\": 0,";
gbt +=
" \"previousblockhash\": "
"\"0000000000000047e5bda122407654b25d52e0f3eeb00c152f631f70e9803772\",";
gbt += " \"transactions\": [";
gbt += " {";
gbt +=
" \"data\": "
"\"0100000002449f651247d5c09d3020c30616cb1807c268e2c2346d1de28442b89ef3"
"4c976d000000006a47304402203eae3868946a312ba712f9c9a259738fee6e3163b05d"
"206e0f5b6c7980";
gbt +=
"161756022017827f248432f7313769f120fb3b7a65137bf93496a1ae7d6a775879fbdf"
"b8cd0121027d7b71dab3bb16582c97fc0ccedeacd8f75ebee62fa9c388290294ee3bc3"
"e935feffffffcbc82a21497f8db";
gbt +=
"8d57d054fefea52aba502a074ed984efc81ec2ef211194aa6010000006a47304402207"
"f5462295e52fb4213f1e63802d8fe9ec020ac8b760535800564694ea87566a802205ee"
"01096fc9268eac483136ce08250";
gbt +=
"6ac951a7dbc9e4ae24dca07ca2a1fdf2f30121023b86e60ef66fe8ace403a0d77d27c8"
"0ba9ba5404ee796c47c03c73748e59d125feffffff0286c35b00000000001976a914ab"
"29f668d284fd2d65cec5f098432";
gbt +=
"c4ece01055488ac8093dc14000000001976a914ac19d3fd17710e6b9a331022fe92c69"
"3fdf6659588ac8dd70f00\",";
gbt +=
" \"txid\": "
"\"c284853b65e7887c5fd9b635a932e2e0594d19849b22914a8e6fb180fea0954f\",";
gbt +=
" \"hash\": "
"\"c284853b65e7887c5fd9b635a932e2e0594d19849b22914a8e6fb180fea0954f\",";
gbt += " \"depends\": [";
gbt += " ],";
gbt += " \"fee\": 37400,";
gbt += " \"sigops\": 8,";
gbt += " \"weight\": 1488";
gbt += " },";
gbt += " {";
gbt +=
" \"data\": "
"\"0100000001043f5e73755b5c6919b4e361f4cae84c8805452de3df265a6e2d3d71cb"
"cb385501000000da0047304402202b14552521cd689556d2e44d914caf2195da37b80d"
"e4f8cd0fad9adf";
gbt +=
"7ef768ef022026fcddd992f447c39c48c3ce50c5960e2f086ebad455159ffc3e36a562"
"4af2f501483045022100f2b893e495f41b22cd83df6908c2fa4f917fd7bce9f8da14e6"
"ab362042e11f7d022075bc2451e";
gbt +=
"1cf2ae2daec0f109a3aceb6558418863070f5e84c94526201850324014752210263217"
"8d046673c9729d828cfee388e121f497707f810c131e0d3fc0fe0bd66d62103a0951ec"
"7d3a9da9de171617026442fcd30";
gbt +=
"f34d66100fab539853b43f508787d452aeffffffff0240420f000000000017a9143e9a"
"6b79be836762c8ef591cf16b76af1327ced58790dfdf8c0000000017a9148ce5408cfe"
"addb7ccb2545ded41ef47810945";
gbt += "4848700000000\",";
gbt +=
" \"txid\": "
"\"28b1a5c2f0bb667aea38e760b6d55163abc9be9f1f830d9969edfab902d17a0f\",";
gbt +=
" \"hash\": "
"\"28b1a5c2f0bb667aea38e760b6d55163abc9be9f1f830d9969edfab902d17a0f\",";
gbt += " \"depends\": [";
gbt += " ],";
gbt += " \"fee\": 20000,";
gbt += " \"sigops\": 8,";
gbt += " \"weight\": 1332";
gbt += " },";
gbt += " {";
gbt +=
" \"data\": "
"\"01000000013faf73481d6b96c2385b9a4300f8974b1b30c34be30000c7dcef11f686"
"62de4501000000db00483045022100f9881f4c867b5545f6d7a730ae26f598107171d0"
"f68b860bd973db";
gbt +=
"b855e073a002207b511ead1f8be8a55c542ce5d7e91acfb697c7fa2acd2f322b47f177"
"875bffc901483045022100a37aa9998b9867633ab6484ad08b299de738a86ae997133d"
"827717e7ed73d953022011e3f99";
gbt +=
"d1bd1856f6a7dc0bf611de6d1b2efb60c14fc5931ba09da01558757f60147522102632"
"178d046673c9729d828cfee388e121f497707f810c131e0d3fc0fe0bd66d62103a0951"
"ec7d3a9da9de171617026442fcd";
gbt +=
"30f34d66100fab539853b43f508787d452aeffffffff0240420f000000000017a9148d"
"57003ecbaa310a365f8422602cc507a702197e87806868a90000000017a9148ce5408c"
"feaddb7ccb2545ded41ef478109";
gbt += "454848700000000\",";
gbt +=
" \"txid\": "
"\"67878210e268d87b4e6587db8c6e367457cea04820f33f01d626adbe5619b3dd\",";
gbt +=
" \"hash\": "
"\"67878210e268d87b4e6587db8c6e367457cea04820f33f01d626adbe5619b3dd\",";
gbt += " \"depends\": [";
gbt += " ],";
gbt += " \"fee\": 20000,";
gbt += " \"sigops\": 8,";
gbt += " \"weight\": 1336";
gbt += " },";
gbt += " ],";
gbt += " \"coinbaseaux\": {";
gbt += " \"flags\": \"\"";
gbt += " },";
gbt += " \"coinbasevalue\": 319367518,";
gbt +=
" \"longpollid\": "
"\"0000000000000047e5bda122407654b25d52e0f3eeb00c152f631f70e98037726045"
"97\",";
gbt +=
" \"target\": "
"\"0000000000001714480000000000000000000000000000000000000000000000\",";
gbt += " \"mintime\": 1480831053,";
gbt += " \"mutable\": [";
gbt += " \"time\",";
gbt += " \"transactions\",";
gbt += " \"prevblock\"";
gbt += " ],";
gbt += " \"noncerange\": \"00000000ffffffff\",";
gbt += " \"sigoplimit\": 80000,";
gbt += " \"sizelimit\": 4000000,";
gbt += " \"weightlimit\": 4000000,";
gbt += " \"curtime\": 1480834892,";
gbt += " \"bits\": \"1a171448\",";
gbt += " \"height\": 1038222,";
gbt +=
" \"default_witness_commitment\": "
"\"6a24aa21a9ed842a6d6672504c2b7abb796fdd7cfbd7262977b71b945452e17fbac6"
"9ed22bf8\"";
gbt += "}}";
blockVersion = 0;
SelectParams(CBaseChainParams::TESTNET);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"myxopLJB19oFtNBdrAxD5Z34Aw6P8o9P8U"),
true);
CTxDestination poolPayoutAddrTestnet =
BitcoinUtils::DecodeDestination("myxopLJB19oFtNBdrAxD5Z34Aw6P8o9P8U");
res = sjob.initFromGbt(
gbt.c_str(),
poolCoinbaseInfo,
poolPayoutAddrTestnet,
blockVersion,
"",
RskWork(),
1,
false);
ASSERT_EQ(res, true);
const string jsonStr = sjob.serializeToJson();
StratumJobBitcoin sjob2;
res = sjob2.unserializeFromJson(jsonStr.c_str(), jsonStr.length());
ASSERT_EQ(res, true);
ASSERT_EQ(
sjob2.prevHash_,
uint256S("0000000000000047e5bda122407654b25d52e0f3eeb00c152f631f70e9803"
"772"));
ASSERT_EQ(
sjob2.prevHashBeStr_,
"e98037722f631f70eeb00c155d52e0f3407654b2e5bda1220000004700000000");
ASSERT_EQ(sjob2.height_, 1038222);
ASSERT_EQ(
sjob2.coinbase2_,
"ffffffff" // sequence
"02" // 2 outputs
// 5e29091300000000 -> 000000001309295e -> 319367518
"5e29091300000000"
// 0x19 -> 25 bytes
"1976a914ca560088c0fb5e6f028faa11085e643e343a8f5c88ac"
//
"0000000000000000"
// 0x26 -> 38 bytes
"266a24aa21a9ed842a6d6672504c2b7abb796fdd7cfbd7262977b71b945452e17fbac6"
"9ed22bf8"
// lock_time
"00000000");
ASSERT_EQ(sjob2.nVersion_, 536870912);
ASSERT_EQ(sjob2.nBits_, 0x1a171448U);
ASSERT_EQ(sjob2.nTime_, 1480834892U);
ASSERT_EQ(sjob2.minTime_, 1480831053U);
ASSERT_EQ(sjob2.coinbaseValue_, 319367518);
ASSERT_GE(time(nullptr), jobId2Time(sjob2.jobId_));
}
}
#endif
#ifdef CHAIN_TYPE_BTC
TEST(Stratum, StratumJobWithSegwitPayoutAddr) {
StratumJobBitcoin sjob;
string poolCoinbaseInfo = "/BTC.COM/";
uint32_t blockVersion = 0;
bool res;
{
string gbt;
gbt += "{\"result\":";
gbt += "{";
gbt += " \"capabilities\": [";
gbt += " \"proposal\"";
gbt += " ],";
gbt += " \"version\": 536870912,";
gbt += " \"rules\": [";
gbt += " \"csv\",";
gbt += " \"!segwit\"";
gbt += " ],";
gbt += " \"vbavailable\": {";
gbt += " },";
gbt += " \"vbrequired\": 0,";
gbt +=
" \"previousblockhash\": "
"\"0000000000000047e5bda122407654b25d52e0f3eeb00c152f631f70e9803772\",";
gbt += " \"transactions\": [";
gbt += " {";
gbt +=
" \"data\": "
"\"0100000002449f651247d5c09d3020c30616cb1807c268e2c2346d1de28442b89ef3"
"4c976d000000006a47304402203eae3868946a312ba712f9c9a259738fee6e3163b05d"
"206e0f5b6c7980";
gbt +=
"161756022017827f248432f7313769f120fb3b7a65137bf93496a1ae7d6a775879fbdf"
"b8cd0121027d7b71dab3bb16582c97fc0ccedeacd8f75ebee62fa9c388290294ee3bc3"
"e935feffffffcbc82a21497f8db";
gbt +=
"8d57d054fefea52aba502a074ed984efc81ec2ef211194aa6010000006a47304402207"
"f5462295e52fb4213f1e63802d8fe9ec020ac8b760535800564694ea87566a802205ee"
"01096fc9268eac483136ce08250";
gbt +=
"6ac951a7dbc9e4ae24dca07ca2a1fdf2f30121023b86e60ef66fe8ace403a0d77d27c8"
"0ba9ba5404ee796c47c03c73748e59d125feffffff0286c35b00000000001976a914ab"
"29f668d284fd2d65cec5f098432";
gbt +=
"c4ece01055488ac8093dc14000000001976a914ac19d3fd17710e6b9a331022fe92c69"
"3fdf6659588ac8dd70f00\",";
gbt +=
" \"txid\": "
"\"c284853b65e7887c5fd9b635a932e2e0594d19849b22914a8e6fb180fea0954f\",";
gbt +=
" \"hash\": "
"\"c284853b65e7887c5fd9b635a932e2e0594d19849b22914a8e6fb180fea0954f\",";
gbt += " \"depends\": [";
gbt += " ],";
gbt += " \"fee\": 37400,";
gbt += " \"sigops\": 8,";
gbt += " \"weight\": 1488";
gbt += " },";
gbt += " {";
gbt +=
" \"data\": "
"\"0100000001043f5e73755b5c6919b4e361f4cae84c8805452de3df265a6e2d3d71cb"
"cb385501000000da0047304402202b14552521cd689556d2e44d914caf2195da37b80d"
"e4f8cd0fad9adf";
gbt +=
"7ef768ef022026fcddd992f447c39c48c3ce50c5960e2f086ebad455159ffc3e36a562"
"4af2f501483045022100f2b893e495f41b22cd83df6908c2fa4f917fd7bce9f8da14e6"
"ab362042e11f7d022075bc2451e";
gbt +=
"1cf2ae2daec0f109a3aceb6558418863070f5e84c94526201850324014752210263217"
"8d046673c9729d828cfee388e121f497707f810c131e0d3fc0fe0bd66d62103a0951ec"
"7d3a9da9de171617026442fcd30";
gbt +=
"f34d66100fab539853b43f508787d452aeffffffff0240420f000000000017a9143e9a"
"6b79be836762c8ef591cf16b76af1327ced58790dfdf8c0000000017a9148ce5408cfe"
"addb7ccb2545ded41ef47810945";
gbt += "4848700000000\",";
gbt +=
" \"txid\": "
"\"28b1a5c2f0bb667aea38e760b6d55163abc9be9f1f830d9969edfab902d17a0f\",";
gbt +=
" \"hash\": "
"\"28b1a5c2f0bb667aea38e760b6d55163abc9be9f1f830d9969edfab902d17a0f\",";
gbt += " \"depends\": [";
gbt += " ],";
gbt += " \"fee\": 20000,";
gbt += " \"sigops\": 8,";
gbt += " \"weight\": 1332";
gbt += " },";
gbt += " {";
gbt +=
" \"data\": "
"\"01000000013faf73481d6b96c2385b9a4300f8974b1b30c34be30000c7dcef11f686"
"62de4501000000db00483045022100f9881f4c867b5545f6d7a730ae26f598107171d0"
"f68b860bd973db";
gbt +=
"b855e073a002207b511ead1f8be8a55c542ce5d7e91acfb697c7fa2acd2f322b47f177"
"875bffc901483045022100a37aa9998b9867633ab6484ad08b299de738a86ae997133d"
"827717e7ed73d953022011e3f99";
gbt +=
"d1bd1856f6a7dc0bf611de6d1b2efb60c14fc5931ba09da01558757f60147522102632"
"178d046673c9729d828cfee388e121f497707f810c131e0d3fc0fe0bd66d62103a0951"
"ec7d3a9da9de171617026442fcd";
gbt +=
"30f34d66100fab539853b43f508787d452aeffffffff0240420f000000000017a9148d"
"57003ecbaa310a365f8422602cc507a702197e87806868a90000000017a9148ce5408c"
"feaddb7ccb2545ded41ef478109";
gbt += "454848700000000\",";
gbt +=
" \"txid\": "
"\"67878210e268d87b4e6587db8c6e367457cea04820f33f01d626adbe5619b3dd\",";
gbt +=
" \"hash\": "
"\"67878210e268d87b4e6587db8c6e367457cea04820f33f01d626adbe5619b3dd\",";
gbt += " \"depends\": [";
gbt += " ],";
gbt += " \"fee\": 20000,";
gbt += " \"sigops\": 8,";
gbt += " \"weight\": 1336";
gbt += " },";
gbt += " ],";
gbt += " \"coinbaseaux\": {";
gbt += " \"flags\": \"\"";
gbt += " },";
gbt += " \"coinbasevalue\": 319367518,";
gbt +=
" \"longpollid\": "
"\"0000000000000047e5bda122407654b25d52e0f3eeb00c152f631f70e98037726045"
"97\",";
gbt +=
" \"target\": "
"\"0000000000001714480000000000000000000000000000000000000000000000\",";
gbt += " \"mintime\": 1480831053,";
gbt += " \"mutable\": [";
gbt += " \"time\",";
gbt += " \"transactions\",";
gbt += " \"prevblock\"";
gbt += " ],";
gbt += " \"noncerange\": \"00000000ffffffff\",";
gbt += " \"sigoplimit\": 80000,";
gbt += " \"sizelimit\": 4000000,";
gbt += " \"weightlimit\": 4000000,";
gbt += " \"curtime\": 1480834892,";
gbt += " \"bits\": \"1a171448\",";
gbt += " \"height\": 1038222,";
gbt +=
" \"default_witness_commitment\": "
"\"6a24aa21a9ed842a6d6672504c2b7abb796fdd7cfbd7262977b71b945452e17fbac6"
"9ed22bf8\"";
gbt += "}}";
blockVersion = 0;
SelectParams(CBaseChainParams::TESTNET);
ASSERT_EQ(
BitcoinUtils::IsValidDestinationString(
"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7"),
true);
CTxDestination poolPayoutAddrTestnet = BitcoinUtils::DecodeDestination(
"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7");
res = sjob.initFromGbt(
gbt.c_str(),
poolCoinbaseInfo,
poolPayoutAddrTestnet,
blockVersion,
"",
RskWork(),
1,
false);
ASSERT_EQ(res, true);
const string jsonStr = sjob.serializeToJson();
StratumJobBitcoin sjob2;
res = sjob2.unserializeFromJson(jsonStr.c_str(), jsonStr.length());
ASSERT_EQ(res, true);
ASSERT_EQ(
sjob2.prevHash_,
uint256S("0000000000000047e5bda122407654b25d52e0f3eeb00c152f631f70e9803"
"772"));
ASSERT_EQ(
sjob2.prevHashBeStr_,
"e98037722f631f70eeb00c155d52e0f3407654b2e5bda1220000004700000000");
ASSERT_EQ(sjob2.height_, 1038222);
ASSERT_EQ(
sjob2.coinbase2_,
"ffffffff" // sequence
"02" // 2 outputs
// 5e29091300000000 -> 000000001309295e -> 319367518
"5e29091300000000"
// 0x22 -> 34 bytes
"2200201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262"
//
"0000000000000000"
// 0x26 -> 38 bytes
"266a24aa21a9ed842a6d6672504c2b7abb796fdd7cfbd7262977b71b945452e17fbac6"
"9ed22bf8"
// lock_time
"00000000");
ASSERT_EQ(sjob2.nVersion_, 536870912);
ASSERT_EQ(sjob2.nBits_, 0x1a171448U);
ASSERT_EQ(sjob2.nTime_, 1480834892U);
ASSERT_EQ(sjob2.minTime_, 1480831053U);
ASSERT_EQ(sjob2.coinbaseValue_, 319367518);
ASSERT_GE(time(nullptr), jobId2Time(sjob2.jobId_));
}
}
#endif
#ifdef CHAIN_TYPE_BTC
TEST(Stratum, StratumJobWithRskWork) {
StratumJobBitcoin sjob;
RskWork rskWork;
string poolCoinbaseInfo = "/BTC.COM/";
uint32_t blockVersion = 0;
{
string gbt;
gbt += "{\"result\":{";
gbt += " \"capabilities\": [";
gbt += " \"proposal\"";
gbt += " ],";
gbt += " \"version\": 536870912,";
gbt +=
" \"previousblockhash\": "
"\"000000004f2ea239532b2e77bb46c03b86643caac3fe92959a31fd2d03979c34\",";
gbt += " \"transactions\": [";
gbt += " {";
gbt +=
" \"data\": "
"\"01000000010291939c5ae8191c2e7d4ce8eba7d6616a66482e3200037cb8b8c2d0af"
"45b445000000006a47304402204df709d9e149804e358de4b082e41d8bb21b3c9d3472"
"41b728b1362aafcb153602200d06d9b6f2eca899f43dcd62ec2efb2d9ce2e10adf0273"
"8bb908420d7db93ede012103cae98ab925e20dd6ae1f76e767e9e99bc47b3844095c68"
"600af9c775104fb36cffffffff0290f1770b000000001976a91400dc5fd62f6ee48eb8"
"ecda749eaec6824a780fdd88aca08601000000000017a914eb65573e5dd52d3d950396"
"ccbe1a47daf8f400338700000000\",";
gbt +=
" \"hash\": "
"\"bd36bd4fff574b573152e7d4f64adf2bb1c9ab0080a12f8544c351f65aca79ff\",";
gbt += " \"depends\": [";
gbt += " ],";
gbt += " \"fee\": 10000,";
gbt += " \"sigops\": 1";
gbt += " }";
gbt += " ],";
gbt += " \"coinbaseaux\": {";
gbt += " \"flags\": \"\"";
gbt += " },";
gbt += " \"coinbasevalue\": 312659655,";
gbt +=
" \"longpollid\": "
"\"000000004f2ea239532b2e77bb46c03b86643caac3fe92959a31fd2d03979c341911"
"\",";
gbt +=
" \"target\": "
"\"000000000000018ae20000000000000000000000000000000000000000000000\",";
gbt += " \"mintime\": 1469001544,";
gbt += " \"mutable\": [";
gbt += " \"time\",";
gbt += " \"transactions\",";
gbt += " \"prevblock\"";
gbt += " ],";
gbt += " \"noncerange\": \"00000000ffffffff\",";
gbt += " \"sigoplimit\": 20000,";
gbt += " \"sizelimit\": 1000000,";
gbt += " \"curtime\": 1469006933,";
gbt += " \"bits\": \"1a018ae2\",";
gbt += " \"height\": 898487";
gbt += "}}";
uint32_t creationTime = (uint32_t)time(nullptr);
string rawgw;
rawgw = Strings::Format(
"{\"created_at_ts\": %u,"
"\"rskdRpcAddress\":\"http://10.0.2.2:4444\","
"\"rskdRpcUserPwd\":\"user:pass\","
"\"target\":"
"\"0x5555555555555555555555555555555555555555555555555555555555555555\""
","
"\"parentBlockHash\":"
"\"0x13532f616f89e3ac2e0a9ef7363be28e7f2ca39764684995fb30c0d96e664ae4\""
","
"\"blockHashForMergedMining\":"
"\"0xe6b0a8e84e0ce68471ca28db4f51b71139b0ab78ae1c3e0ae8364604e9f8a15d\""
","
"\"feesPaidToMiner\":\"0\","
"\"notify\":\"true\"}",
creationTime);
blockVersion = 0;
SelectParams(CBaseChainParams::TESTNET);
bool resInitRskWork = rskWork.initFromGw(rawgw);
ASSERT_TRUE(resInitRskWork);
ASSERT_EQ(rskWork.isInitialized(), true);
ASSERT_EQ(rskWork.getCreatedAt(), creationTime);
ASSERT_EQ(
rskWork.getBlockHash(),
"0xe6b0a8e84e0ce68471ca28db4f51b71139b0ab78ae1c3e0ae8364604e9f8a15d");
ASSERT_EQ(
rskWork.getTarget(),
"0x5555555555555555555555555555555555555555555555555555555555555555");
ASSERT_EQ(rskWork.getFees(), "0");
ASSERT_EQ(rskWork.getRpcAddress(), "http://10.0.2.2:4444");
ASSERT_EQ(rskWork.getRpcUserPwd(), "user:pass");
ASSERT_EQ(rskWork.getNotifyFlag(), true);
CTxDestination poolPayoutAddrTestnet =
BitcoinUtils::DecodeDestination("myxopLJB19oFtNBdrAxD5Z34Aw6P8o9P8U");
sjob.initFromGbt(
gbt.c_str(),
poolCoinbaseInfo,
poolPayoutAddrTestnet,
blockVersion,
"",
rskWork,
1,
true);
// check rsk required data copied properly to the stratum job
ASSERT_EQ(
sjob.blockHashForMergedMining_,
"0xe6b0a8e84e0ce68471ca28db4f51b71139b0ab78ae1c3e0ae8364604e9f8a15d");
ASSERT_EQ(
sjob.rskNetworkTarget_,
uint256S("0x55555555555555555555555555555555555555555555555555555555555"
"55555"));
ASSERT_EQ(sjob.feesForMiner_, "0");
ASSERT_EQ(sjob.rskdRpcAddress_, "http://10.0.2.2:4444");
ASSERT_EQ(sjob.rskdRpcUserPwd_, "user:pass");
ASSERT_EQ(sjob.isMergedMiningCleanJob_, true);
// check rsk merged mining tag present in the coinbase
// Hex("RSKBLOCK:") = 0x52534b424c4f434b3a
string rskTagHex =
"52534b424c4f434b3ae6b0a8e84e0ce68471ca28db4f51b71139b0ab78ae1c3e0ae836"
"4604e9f8a15d";
size_t rskTagPos = sjob.coinbase2_.find(rskTagHex);
ASSERT_NE(rskTagPos, string::npos);
ASSERT_EQ(
sjob.prevHash_,
uint256S("000000004f2ea239532b2e77bb46c03b86643caac3fe92959a31fd2d03979"
"c34"));
ASSERT_EQ(
sjob.prevHashBeStr_,
"03979c349a31fd2dc3fe929586643caabb46c03b532b2e774f2ea23900000000");
ASSERT_EQ(sjob.height_, 898487);
// 46 bytes, 5 bytes (timestamp), 9 bytes (poolCoinbaseInfo)
// 02000000010000000000000000000000000000000000000000000000000000000000000000ffffffff1e03b7b50d
// 0402363d58 2f4254432e434f4d2f
ASSERT_EQ(
sjob.coinbase1_.substr(0, 92),
"0200000001000000000000000000000000000000000000000000000000000000000000"
"0000ffffffff1e03b7b50d");
ASSERT_EQ(sjob.coinbase1_.substr(102, 18), "2f4254432e434f4d2f");
// 0402363d58 -> 0x583d3602 = 1480406530 = 2016-11-29 16:02:10
uint32_t ts =
(uint32_t)strtoull(sjob.coinbase1_.substr(94, 8).c_str(), nullptr, 16);
ts = HToBe(ts);
ASSERT_EQ(ts == time(nullptr) || ts + 1 == time(nullptr), true);
ASSERT_EQ(
sjob.coinbase2_,
"ffffffff" // sequence
"02" // 2 outputs. Rsk tag is stored in an additional CTxOut besides the
// cb's standard output
// c7cea21200000000 -> 0000000012a2cec7 -> 312659655
"c7cea21200000000"
// 0x19 -> 25 bytes of first output script
"1976a914ca560088c0fb5e6f028faa11085e643e343a8f5c88ac"
// rsk tx out value
"0000000000000000"
// 0x29 = 41 bytes of second output script containing the rsk merged
// mining tag
"2952534b424c4f434b3ae6b0a8e84e0ce68471ca28db4f51b71139b0ab78ae1c3e0ae8"
"364604e9f8a15d"
// lock_time
"00000000");
ASSERT_EQ(sjob.merkleBranch_.size(), 1U);
ASSERT_EQ(
sjob.merkleBranch_[0],
uint256S("bd36bd4fff574b573152e7d4f64adf2bb1c9ab0080a12f8544c351f65aca7"
"9ff"));
ASSERT_EQ(sjob.nVersion_, 536870912);
ASSERT_EQ(sjob.nBits_, 436308706U);
ASSERT_EQ(sjob.nTime_, 1469006933U);
ASSERT_EQ(sjob.minTime_, 1469001544U);
ASSERT_EQ(sjob.coinbaseValue_, 312659655);
ASSERT_GE(time(nullptr), jobId2Time(sjob.jobId_));
}
}
#endif
| 35.269857 | 99 | 0.640739 |
beb0d6ff680cac5f823633fd8fed15abceef505f | 1,556 | cc | C++ | physicalrobots/player/client_libs/libplayerc++/test/test_speech.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | physicalrobots/player/client_libs/libplayerc++/test/test_speech.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | physicalrobots/player/client_libs/libplayerc++/test/test_speech.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
* Player - One Hell of a Robot Server
* Copyright (C) Andrew Howard 2003
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Testing the Speech Proxy. Alexis Maldonado. May 4 2007.
*/
#include "test.h"
#if !defined (WIN32)
#include <unistd.h>
#endif
#include <string>
#include <playerconfig.h>
#if !HAVE_USLEEP
#include <replace.h>
#endif
using namespace std;
using namespace PlayerCc;
int
test_speech(PlayerClient* client, int index)
{
TEST("speech");
SpeechProxy sp(client,index);
TEST("speech: saying something");
string hello("Hello World!");
string numbers("12345678901234567890123456789012345678901234567890");
TEST1("writing data (attempt %d)", 1);
sp.Say(hello.c_str());
PASS();
usleep(1000000);
TEST1("writing data (attempt %d)", 2);
sp.Say(numbers.c_str());
PASS();
return(0);
}
| 23.223881 | 77 | 0.705013 |
beb0e6d6183bbf6bb8da617438c661f83e3ccafe | 1,691 | cpp | C++ | BZOJ/4896.cpp | sshockwave/Online-Judge-Solutions | 9d0bc7fd68c3d1f661622929c1cb3752601881d3 | [
"MIT"
] | 6 | 2019-09-30T16:11:00.000Z | 2021-11-01T11:42:33.000Z | BZOJ/4896.cpp | sshockwave/Online-Judge-Solutions | 9d0bc7fd68c3d1f661622929c1cb3752601881d3 | [
"MIT"
] | 4 | 2017-11-21T08:17:42.000Z | 2020-07-28T12:09:52.000Z | BZOJ/4896.cpp | sshockwave/Online-Judge-Solutions | 9d0bc7fd68c3d1f661622929c1cb3752601881d3 | [
"MIT"
] | 4 | 2017-07-26T05:54:06.000Z | 2020-09-30T13:35:38.000Z | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <cctype>
#include <vector>
using namespace std;
typedef long long lint;
#define ni (next_num<int>())
#define nl (next_num<lint>())
template<class T>inline T next_num(){
T i=0;char c;
while(!isdigit(c=getchar())&&c!='-');
bool flag=c=='-';
flag?(c=getchar()):0;
while(i=i*10-'0'+c,isdigit(c=getchar()));
return flag?-i:i;
}
template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){
if(a<b){
a=b;
}
}
template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){
if(a>b){
a=b;
}
}
inline int abs(int x){
return x>=0?x:-x;
}
const int L=65,SIGMA=26,N=100010;
char s[L];
struct Trie{
typedef Trie* node;
int val;
vector<int>q;
node son[SIGMA];
Trie(){
memset(son,0,sizeof(son));
q.push_back(0);
val=0;
}
inline void update(int id){
val++;
if(val==q.size()){
q.push_back(id);
assert(q[val]==id);
}
}
inline node go(int c){
c-='a';
if(son[c]==0){
son[c]=new Trie();
}
return son[c];
}
inline void insert(char *s,int id){
for(node pt=this;pt->update(id),*s;pt=pt->go(*s),s++);
}
inline void del(char *s){
for(node pt=this;pt->val--,*s;pt=pt->son[(*s)-'a'],s++);
}
inline node find(char *s){
node pt=this;
for(;*s;pt=pt->son[(*s)-'a'],s++);
return pt;
}
}trie;
inline int work(Trie *pt,int ans){
lint a=nl,b=nl,c=nl;
lint x=(a*abs(ans)+b)%c+1;
if(pt->q.size()<=x){
return -1;
}
return pt->q[x];
}
int main(){
int ans=0;
for(int i=1,n=ni;i<=n;i++){
int k=ni;
scanf("%s",s);
if(k==1){
trie.insert(s,i);
}else if(k==2){
trie.del(s);
}else{
assert(k==3);
printf("%d\n",ans=work(trie.find(s),ans));
}
}
}
| 18.182796 | 64 | 0.583678 |
beb86b042dc547fbe7ac9c8cc6a4a39888c5251a | 6,646 | cpp | C++ | Common/utils/iStyle/ASResource.cpp | testdrive-profiling-master/profiles | 6e3854874366530f4e7ae130000000812eda5ff7 | [
"BSD-3-Clause"
] | null | null | null | Common/utils/iStyle/ASResource.cpp | testdrive-profiling-master/profiles | 6e3854874366530f4e7ae130000000812eda5ff7 | [
"BSD-3-Clause"
] | null | null | null | Common/utils/iStyle/ASResource.cpp | testdrive-profiling-master/profiles | 6e3854874366530f4e7ae130000000812eda5ff7 | [
"BSD-3-Clause"
] | null | null | null | // $Id: ASResource.cpp,v 1.2 2004/02/04 07:35:10 devsolar Exp $
// --------------------------------------------------------------------------
//
// Copyright (c) 1998,1999,2000,2001,2002 Tal Davidson. All rights reserved.
//
// compiler_defines.h
// by Tal Davidson (davidsont@bigfoot.com)
//
// This file is a part of "Artistic Style" - an indentater and reformatter
// of C, C++, C# and Java source files.
//
// --------------------------------------------------------------------------
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// --------------------------------------------------------------------------
#include "compiler_defines.h"
#include "astyle.h"
#include <string>
#ifdef USES_NAMESPACE
using namespace std;
namespace astyle
{
#endif
const string ASResource::AS_IF = string("if");
const string ASResource::AS_ELSE = string ("else");
const string ASResource::AS_FOR = string("for");
const string ASResource::AS_WHILE = string("while");
const string ASResource::AS_SWITCH = string ("switch");
const string ASResource::AS_DEFAULT = string("default");
const string ASResource::PRO_CELLDEFINE = string("`celldefine");
const string ASResource::PRO_DEFAULT_NETTYPE = string("`default_nettype");
const string ASResource::PRO_DEFINE = string("`define");
const string ASResource::PRO_ELSE = string("`else");
const string ASResource::PRO_ENDCELLDEFINE = string("`endcelldefine");
const string ASResource::PRO_ENDIF = string("`endif");
const string ASResource::PRO_IFDEF = string("`ifdef");
const string ASResource::PRO_INCLUDE = string("`include");
const string ASResource::PRO_NOUNCONNECTED_DRIVE = string("`nounconnected_drive");
const string ASResource::PRO_RESETALL = string("`resetall");
const string ASResource::PRO_TIMESCALE = string("`timescale");
const string ASResource::PRO_UNCONNECTED_DRIVE = string("`unconnected_drive");
const string ASResource::PRO_UNDEF = string("`undef");
const string ASResource::PRO_IMPORT = string("import");
const string ASResource::AS_OPEN_BRACKET = string("{");
const string ASResource::AS_CLOSE_BRACKET = string("}");
const string ASResource::AS_OPEN_LINE_COMMENT = string("//");
const string ASResource::AS_OPEN_COMMENT = string("/*");
const string ASResource::AS_CLOSE_COMMENT = string("*/");
const string ASResource::AS_ASSIGN = string("=");
const string ASResource::AS_LS_ASSIGN = string("<=");
const string ASResource::AS_EQUAL = string("==");
const string ASResource::AS_NOT_EQUAL = string("!=");
const string ASResource::AS_EQUAL_EQUAL = string("===");
const string ASResource::AS_NOT_EQUAL_EQUAL = string("!==");
const string ASResource::AS_BITNOT_AND = string("~&");
const string ASResource::AS_BITNOT_OR = string("~|");
const string ASResource::AS_BITNOT_XNOR = string("~^");
const string ASResource::AS_NOT_XNOR = string("^~");
const string ASResource::AS_GR_EQUAL = string(">=");
const string ASResource::AS_GR_GR = string(">>");
const string ASResource::AS_LS_EQUAL = string("<=");
const string ASResource::AS_LS_LS = string("<<");
const string ASResource::AS_AND = string("&&");
const string ASResource::AS_OR = string("||");
const string ASResource::AS_PAREN_PAREN = string("()");
const string ASResource::AS_BLPAREN_BLPAREN = string("[]");
const string ASResource::AS_PLUS = string("+");
const string ASResource::AS_MINUS = string("-");
const string ASResource::AS_MULT = string("*");
const string ASResource::AS_DIV = string("/");
const string ASResource::AS_MOD = string("%");
const string ASResource::AS_GR = string(">");
const string ASResource::AS_LS = string("<");
const string ASResource::AS_NOT = string("!");
const string ASResource::AS_BIT_OR = string("|");
const string ASResource::AS_BIT_AND = string("&");
const string ASResource::AS_BIT_NOT = string("~");
const string ASResource::AS_BIT_XOR = string("^");
const string ASResource::AS_QUESTION = string("?");
const string ASResource::AS_COLON = string(":");
const string ASResource::AS_COMMA = string(",");
const string ASResource::AS_SEMICOLON = string(";");
const string ASResource::AS_INITIAL = string("initial");
const string ASResource::AS_FOREVER = string("forever");
const string ASResource::AS_ALWAYS = string("always");
const string ASResource::AS_REPEAT = string("repeat");
const string ASResource::AS_CASE = string("case" );
const string ASResource::AS_CASEX = string("casex" );
const string ASResource::AS_CASEZ = string("casez" );
const string ASResource::AS_FUNCTION = string("function" );
const string ASResource::AS_GENERATE = string("generate" );
const string ASResource::AS_FORK = string("fork" );
const string ASResource::AS_TABLE = string("table" );
const string ASResource::AS_TASK = string("task" );
const string ASResource::AS_SPECIFY = string("specify" );
const string ASResource::AS_PRIMITIVE = string("primitive");
//const string ASResource::AS_MODULE = string("module" );
const string ASResource::AS_BEGIN = string("begin" );
const string ASResource::AS_ENDCASE = string("endcase" );
const string ASResource::AS_ENDFUNCTION = string("endfunction" );
const string ASResource::AS_ENDGENERATE = string("endgenerate" );
const string ASResource::AS_JOIN = string("join" );
const string ASResource::AS_ENDTASK = string("endtask" );
const string ASResource::AS_ENDTABLE = string("endtable" );
const string ASResource::AS_ENDSPECIFY = string("endspecify" );
const string ASResource::AS_ENDPRIMITIVE = string("endprimitive" );
//const string ASResource::AS_ENDMODULE = string("endmodule" );
const string ASResource::AS_END = string("end" );
const char ASResource::PREPROCESSOR_CHAR ='`';
#ifdef USES_NAMESPACE
}
#endif
| 43.437908 | 84 | 0.671532 |
beb879e76be433f8d05e2a88d7fabb47b17c7273 | 13,202 | cpp | C++ | example/FieldContainer/example_01.cpp | Sandia2014/intrepid | 9a310ddc033da1dda162a09bf80cca6c2dde2d6b | [
"MIT"
] | null | null | null | example/FieldContainer/example_01.cpp | Sandia2014/intrepid | 9a310ddc033da1dda162a09bf80cca6c2dde2d6b | [
"MIT"
] | null | null | null | example/FieldContainer/example_01.cpp | Sandia2014/intrepid | 9a310ddc033da1dda162a09bf80cca6c2dde2d6b | [
"MIT"
] | null | null | null | // @HEADER
// ************************************************************************
//
// Intrepid Package
// Copyright (2007) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Pavel Bochev (pbboche@sandia.gov)
// Denis Ridzal (dridzal@sandia.gov), or
// Kara Peterson (kjpeter@sandia.gov)
//
// ************************************************************************
// @HEADER
/** \file
\brief Illustrates use of the FieldContainer class.
\author Created by P. Bochev and D. Ridzal
*/
#include "Intrepid_FieldContainer.hpp"
#include "Teuchos_Time.hpp"
#include "Teuchos_GlobalMPISession.hpp"
using namespace std;
using namespace Intrepid;
int main(int argc, char *argv[]) {
Teuchos::GlobalMPISession mpiSession(&argc, &argv);
std::cout \
<< "===============================================================================\n" \
<< "| |\n" \
<< "| Example use of the FieldContainer class |\n" \
<< "| |\n" \
<< "| 1) Creating and filling FieldContainer objects |\n" \
<< "| 2) Accessing elements in FieldContainer objects |\n" \
<< "| |\n" \
<< "| Questions? Contact Pavel Bochev (pbboche@sandia.gov) or |\n" \
<< "| Denis Ridzal (dridzal@sandia.gov). |\n" \
<< "| |\n" \
<< "| Intrepid's website: http://trilinos.sandia.gov/packages/intrepid |\n" \
<< "| Trilinos website: http://trilinos.sandia.gov |\n" \
<< "| |\n" \
<< "===============================================================================\n\n";
// Define variables to create and use FieldContainers
Teuchos::Array<int> dimension;
Teuchos::Array<int> multiIndex;
std::cout \
<< "===============================================================================\n"\
<< "| EXAMPLE 1: rank 2 multi-index: {u(p,i) | 0 <= p < 5; 0 <= i < 3 } |\n"\
<< "===============================================================================\n\n";
// This rank 2 multi-indexed value can be used to store values of 3D vector field
// evaluated at 5 points, or values of gradient of scalar field evaluated at the points
// Resize dimension and multiIndex for rank-2 multi-indexed value
dimension.resize(2);
multiIndex.resize(2);
// Load upper ranges for the two indices in the multi-indexed value
dimension[0] = 5;
dimension[1] = 3;
// Create FieldContainer that can hold the rank-2 multi-indexed value
FieldContainer<double> myContainer(dimension);
// Fill with some data: leftmost index changes last, rightmost index changes first!
for(int p = 0; p < dimension[0]; p++){
multiIndex[0] = p;
for(int i = 0; i < dimension[1]; i++){
multiIndex[1] = i;
// Load value with multi-index {p,i} to container
myContainer.setValue((double)(i+p), multiIndex);
}
}
// Show container contents
std::cout << myContainer;
// Access by overloaded (), multiindex and []:
multiIndex[0] = 3;
multiIndex[1] = 1;
int enumeration = myContainer.getEnumeration(multiIndex);
std::cout << "Access by (): myContainer(" << 3 <<"," << 1 << ") = " << myContainer(3,1) << "\n";
std::cout << "Access by multi-index: myContainer{" << multiIndex[0] << multiIndex[1] << "} = "<< myContainer.getValue(multiIndex) <<"\n";
std::cout << "Access by enumeration: myContainer[" << enumeration << "] = " << myContainer[enumeration] <<"\n";
std::cout << "Assigning value by (): \n old value at (3,1) = " << myContainer(3,1) <<"\n";
myContainer(3,1) = 999.99;
std::cout << " new value at (3,1) = " << myContainer(3,1) <<"\n";
std::cout << "\n" \
<< "===============================================================================\n"\
<< "| EXAMPLE 2: rank 3 multi-index: {u(p,i,j) | 0 <=p< 5; 0 <= i<2, 0<=j<3 |\n"\
<< "===============================================================================\n\n";
// This rank-3 value can be used to store subset of second partial derivatives values
// of a scalar function at p points.
// Resize dimension and multiIndex for rank-3 multi-indexed value
dimension.resize(3);
multiIndex.resize(3);
// Define upper ranges for the three indices in the multi-indexed value
dimension[0] = 5;
dimension[1] = 2;
dimension[2] = 3;
// Reset the existing container to accept rank-3 value with the specified index ranges
myContainer.resize(dimension);
// Fill with some data
for(int p = 0; p < dimension[0]; p++){
multiIndex[0] = p;
for(int i = 0; i < dimension[1]; i++){
multiIndex[1] = i;
for(int j = 0; j < dimension[2]; j++){
multiIndex[2] = j;
// Load value with multi-index {p,i} to container
myContainer.setValue((double)(p+i+j), multiIndex);
}
}
}
// Display contents
std::cout << myContainer;
// Access by overloaded (), multiindex and []:
multiIndex[0] = 3;
multiIndex[1] = 1;
multiIndex[2] = 2;
enumeration = myContainer.getEnumeration(multiIndex);
std::cout << "Access by (): myContainer(" << 3 <<"," << 1 << "," << 2 << ") = " << myContainer(3,1,2) << "\n";
std::cout << "Access by multi-index: myContainer{" << multiIndex[0] << multiIndex[1] << multiIndex[2] << "} = "<< myContainer.getValue(multiIndex) <<"\n";
std::cout << "Access by enumeration: myContainer[" << enumeration << "] = " << myContainer[enumeration] <<"\n";
std::cout << "Assigning value by (): \n old value at (3,1,2) = " << myContainer(3,1,2) <<"\n";
myContainer(3,1,2) = -999.999;
std::cout << " new value at (3,1,2) = " << myContainer(3,1,2) <<"\n";
std::cout << "\n" \
<< "===============================================================================\n"\
<< "| EXAMPLE 4: making rank-5 FieldContainer from data array and index range array |\n"\
<< "===============================================================================\n\n";
// Initialize dimension for rank-5 multi-index value
dimension.resize(5);
dimension[0] = 5;
dimension[1] = 2;
dimension[2] = 3;
dimension[3] = 4;
dimension[4] = 6;
// Define Teuchos::Array to store values with dimension equal to the number of multi-indexed values
Teuchos::Array<double> dataTeuchosArray(5*2*3*4*6);
// Fill with data
int counter = 0;
for(int i=0; i < dimension[0]; i++){
for(int j=0; j < dimension[1]; j++){
for(int k=0; k < dimension[2]; k++){
for(int l = 0; l < dimension[3]; l++){
for(int m = 0; m < dimension[4]; m++){
dataTeuchosArray[counter] = (double)counter;
counter++;
}
}
}
}
}
// Create FieldContainer from data array and index array and show it
FieldContainer<double> myNewContainer(dimension, dataTeuchosArray);
std::cout << myNewContainer;
// Access by overloaded (), multiindex and []:
multiIndex.resize(myNewContainer.rank());
multiIndex[0] = 3;
multiIndex[1] = 1;
multiIndex[2] = 2;
multiIndex[3] = 2;
multiIndex[4] = 5;
enumeration = myNewContainer.getEnumeration(multiIndex);
std::cout << "Access by (): myNewContainer(" << 3 <<"," << 1 << "," << 2 << "," << 2 << "," << 5 << ") = " << myNewContainer(3,1,2,2,5) << "\n";
std::cout << "Access by multi-index: myNewContainer{" << multiIndex[0] << multiIndex[1] << multiIndex[2] << multiIndex[3] << multiIndex[4] << "} = "<< myNewContainer.getValue(multiIndex) <<"\n";
std::cout << "Access by enumeration: myNewContainer[" << enumeration << "] = " << myNewContainer[enumeration] <<"\n";
std::cout << "Assigning value by (): \n old value at (3,1,2,2,5) = " << myNewContainer(3,1,2,2,5) <<"\n";
myNewContainer(3,1,2,2,5) = -888.888;
std::cout << " new value at (3,1,2,2,5) = " << myNewContainer(3,1,2,2,5) <<"\n";
std::cout << "\n" \
<< "===============================================================================\n"\
<< "| EXAMPLE 5: making trivial FieldContainers and storing a single zero |\n"\
<< "===============================================================================\n\n";
// Make trivial container by resetting the index range to zero rank (no indices) and then
// using resize method
dimension.resize(0);
myContainer.resize(dimension);
std::cout << myContainer;
// Make trivial container by using clear method:
myNewContainer.clear();
std::cout << myNewContainer;
// Now use initialize() to reset the container to hold a single zero
myNewContainer.initialize();
std::cout << myNewContainer;
std::cout << "\n" \
<< "===============================================================================\n"\
<< "| EXAMPLE 6: Timing read and write operations using () and getValue |\n"\
<< "===============================================================================\n\n";
// Initialize dimensions for rank-5 multi-index value
int dim0 = 10; // number of cells
int dim1 = 50; // number of points
int dim2 = 27; // number of functions
int dim3 = 3; // 1st space dim
int dim4 = 3; // 2nd space dim
FieldContainer<double> myTensorContainer(dim0, dim1, dim2, dim3, dim4);
multiIndex.resize(myTensorContainer.rank());
double aValue;
Teuchos::Time timerGetValue("Reading and writing from rank-5 container using getValue");
timerGetValue.start();
for(int i0 = 0; i0 < dim0; i0++){
multiIndex[0] = i0;
for(int i1 = 0; i1 < dim1; i1++){
multiIndex[1] = i1;
for(int i2 = 0; i2 < dim2; i2++) {
multiIndex[2] = i2;
for(int i3 = 0; i3 < dim3; i3++) {
multiIndex[3] = i3;
for(int i4 =0; i4 < dim4; i4++) {
multiIndex[4] = i4;
aValue = myTensorContainer.getValue(multiIndex);
myTensorContainer.setValue(999.999,multiIndex);
}
}
}
}
}
timerGetValue.stop();
std::cout << " Time to read and write from container using getValue: " << timerGetValue.totalElapsedTime() <<"\n";
Teuchos::Time timerRound("Reading and writing from rank-5 container using ()");
timerRound.start();
for(int i0 = 0; i0 < dim0; i0++){
for(int i1 = 0; i1 < dim1; i1++) {
for(int i2 = 0; i2 < dim2; i2++) {
for(int i3 = 0; i3 < dim3; i3++) {
for(int i4 =0; i4 < dim4; i4++) {
aValue = myTensorContainer(i0,i1,i2,i3,i4);
myTensorContainer(i0,i1,i2,i3,i4) = 999.999;
}
}
}
}
}
timerRound.stop();
std::cout << " Time to read and write from container using (): " << timerRound.totalElapsedTime() <<"\n";
std::cout << "\n" \
<< "===============================================================================\n"\
<< "| EXAMPLE 6: Specialized methods of FieldContainer |\n"\
<< "===============================================================================\n\n";
return 0;
}
| 41.127726 | 196 | 0.522269 |
beba7f22985606f3d10d46aa8181f390f0d1d17c | 6,940 | hpp | C++ | src/si_derived.hpp | DarthPigrum/TypeSI | 3505cad5113c1c6c907c48b3bd71e24e9ddb32bc | [
"BSL-1.0"
] | null | null | null | src/si_derived.hpp | DarthPigrum/TypeSI | 3505cad5113c1c6c907c48b3bd71e24e9ddb32bc | [
"BSL-1.0"
] | null | null | null | src/si_derived.hpp | DarthPigrum/TypeSI | 3505cad5113c1c6c907c48b3bd71e24e9ddb32bc | [
"BSL-1.0"
] | null | null | null | #pragma once
/// @file si_derived.hpp
/// @brief Derived SI units
#include "si_base.hpp"
#include <utility>
namespace Si {
/// @brief Derived SI units
namespace Derived {
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Hertz = decltype(std::declval<Internal::Dimensionless<T>>() /
std::declval<Base::Second<T>>());
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Newton = decltype(
std::declval<Base::Kilogram<T>>() * std::declval<Base::Meter<T>>() /
(std::declval<Base::Second<T>>() * std::declval<Base::Second<T>>()));
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Pascal =
decltype(std::declval<Newton<T>>() /
(std::declval<Base::Meter<T>>() * std::declval<Base::Meter<T>>()));
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Joule =
decltype(std::declval<Base::Meter<T>>() * std::declval<Newton<T>>());
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Watt =
decltype(std::declval<Joule<T>>() / std::declval<Base::Second<T>>());
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Coulomb =
decltype(std::declval<Base::Second<T>>() * std::declval<Base::Ampere<T>>());
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Volt =
decltype(std::declval<Watt<T>>() / std::declval<Base::Ampere<T>>());
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Farad = decltype(std::declval<Coulomb<T>>() / std::declval<Volt<T>>());
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Ohm = decltype(std::declval<Volt<T>>() / std::declval<Base::Ampere<T>>());
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Siemens =
decltype(std::declval<Base::Ampere<T>>() / std::declval<Volt<T>>());
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Weber =
decltype(std::declval<Joule<T>>() / std::declval<Base::Ampere<T>>());
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Tesla =
decltype(std::declval<Newton<T>>() / (std::declval<Base::Ampere<T>>() *
std::declval<Base::Meter<T>>()));
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Henry =
decltype(std::declval<Weber<T>>() / std::declval<Base::Ampere<T>>());
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T> using Lumen = Base::Candela<T>;
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Lux =
decltype(std::declval<Lumen<T>>() /
(std::declval<Base::Meter<T>>() * std::declval<Base::Meter<T>>()));
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T> using Becquerel = Hertz<T>;
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Gray =
decltype(std::declval<Joule<T>>() / std::declval<Base::Kilogram<T>>());
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T> using Sievert = Gray<T>;
/// @tparam T Any number type such as float, double or long double used as a
/// container
template <typename T>
using Katal =
decltype(std::declval<Base::Mole<T>>() / std::declval<Base::Second<T>>());
/// @brief Use this namespace to enable literals for base units
namespace Literals {
/// @brief _m long double literal for hertz
Hertz<long double> operator"" _Hz(long double value) {
return Hertz<long double>(value);
}
/// @brief _kg long double literal for newton
Newton<long double> operator"" _N(long double value) {
return Newton<long double>(value);
}
/// @brief _s long double literal for pascal
Pascal<long double> operator"" _Pa(long double value) {
return Pascal<long double>(value);
}
/// @brief _A long double literal for joule
Joule<long double> operator"" _J(long double value) {
return Joule<long double>(value);
}
/// @brief _K long double literal for watt
Watt<long double> operator"" _W(long double value) {
return Watt<long double>(value);
}
/// @brief _mol long double literal for coulomb
Coulomb<long double> operator"" _C(long double value) {
return Coulomb<long double>(value);
}
/// @brief _cd long double literal for volt
Volt<long double> operator"" _V(long double value) {
return Volt<long double>(value);
}
/// @brief _cd long double literal for farad
Farad<long double> operator"" _F(long double value) {
return Farad<long double>(value);
}
/// @brief _cd long double literal for ohm(not as defined by standard because of
/// non-ASCII symbol)
Ohm<long double> operator"" _Ohm(long double value) {
return Ohm<long double>(value);
}
/// @brief _cd long double literal for siemens
Siemens<long double> operator"" _S(long double value) {
return Siemens<long double>(value);
}
/// @brief _cd long double literal for weber
Weber<long double> operator"" _Wb(long double value) {
return Weber<long double>(value);
}
/// @brief _cd long double literal for tesla
Tesla<long double> operator"" _T(long double value) {
return Tesla<long double>(value);
}
/// @brief _cd long double literal for henry
Henry<long double> operator"" _H(long double value) {
return Henry<long double>(value);
}
/// @brief _cd long double literal for lumen
Lumen<long double> operator"" _lm(long double value) {
return Lumen<long double>(value);
}
/// @brief _cd long double literal for lux
Lux<long double> operator"" _lx(long double value) {
return Lux<long double>(value);
}
/// @brief _cd long double literal for becquerel
Becquerel<long double> operator"" _Bq(long double value) {
return Becquerel<long double>(value);
}
/// @brief _cd long double literal for gray
Gray<long double> operator"" _Gy(long double value) {
return Gray<long double>(value);
}
/// @brief _cd long double literal for sievert
Sievert<long double> operator"" _Sv(long double value) {
return Sievert<long double>(value);
}
/// @brief _cd long double literal for katal
Katal<long double> operator"" _kat(long double value) {
return Katal<long double>(value);
}
} // namespace Literals
} // namespace Derived
} // namespace Si
| 38.131868 | 80 | 0.692507 |
bebb061abaa5720627f10a235f9cc4065b56a1fb | 4,500 | cpp | C++ | rviz-groovy-devel/src/test/fun_display.cpp | tuw-cpsg/dynamic_mapping | 12c5c9a9e66e16cb451c457d46a4d6cab5e2213b | [
"CC0-1.0"
] | 9 | 2017-12-17T07:43:15.000Z | 2021-10-10T15:03:39.000Z | rviz-groovy-devel/src/test/fun_display.cpp | tuw-cpsg/dynamic_mapping | 12c5c9a9e66e16cb451c457d46a4d6cab5e2213b | [
"CC0-1.0"
] | null | null | null | rviz-groovy-devel/src/test/fun_display.cpp | tuw-cpsg/dynamic_mapping | 12c5c9a9e66e16cb451c457d46a4d6cab5e2213b | [
"CC0-1.0"
] | 6 | 2016-01-27T03:40:58.000Z | 2021-06-15T08:12:14.000Z | /*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h> // for random
#include <stdio.h> // for printf
#include <QTimer>
#include "fun_display.h"
// static member
FunDisplay* FunDisplay::previous_fun_ = NULL;
FunDisplay::FunDisplay()
: count_( 0 )
{
size_ = new Property( "Size", 10, "How big, in units", this );
connect( size_, SIGNAL( changed() ), this, SLOT( onSizeChanged() ));
master_ = new Property( "Master", "chunky", "Type of butter.", this );
connect( master_, SIGNAL( changed() ), this, SLOT( onMasterChanged() ));
if( previous_fun_ )
{
connect( previous_fun_->master_, SIGNAL( changed() ), this, SLOT( onMasterChanged() ));
}
previous_fun_ = this;
new Property( "Double", 1.0, "double", this );
new Property( "Float", 1.0f, "float", this );
slave_ = new Property( "Slave", "chunky", "Slave to the butter.", this );
mood_ = new EnumProperty( "Mood", "sad", "Feelings, nothing more than feelings...", this );
mood_->addOption( "sad", 0 );
mood_->addOption( "happy", 1 );
mood_->addOption( "angry", 2 );
mood_->addOption( "jumpy", 3 );
mood_->addOption( "squirmy", 4 );
connect( mood_, SIGNAL( changed() ), this, SLOT( onMoodChanged() ));
dance_ = new EditableEnumProperty( "Dance", "clown", "Stomple stomple", this );
connect( dance_, SIGNAL( requestOptions( EditableEnumProperty* )), this, SLOT( makeDances( EditableEnumProperty* )));
QTimer* timer = new QTimer( this );
connect( timer, SIGNAL( timeout() ), this, SLOT( onTimerTick() ));
timer->start( 1000 );
}
void FunDisplay::onTimerTick()
{
count_++;
slave_->setValue( count_ );
if( (count_ / 10) % 2 )
{
setStatus( StatusProperty::Warn, "Slave", "Too odd." );
}
else
{
setStatus( StatusProperty::Ok, "Slave", "Even enough." );
}
}
void FunDisplay::onMasterChanged()
{
slave_->setValue( master_->getValue() );
}
void FunDisplay::onSizeChanged()
{
if( size_->getValue().toInt() > 10 )
{
setStatus( StatusProperty::Error, "Size", "Too large." );
}
else if( size_->getValue().toInt() < 5 )
{
setStatus( StatusProperty::Warn, "Size", "Too small." );
}
else
{
setStatus( StatusProperty::Ok, "Size", "Just fine." );
}
}
void FunDisplay::onMoodChanged()
{
printf( "Mood is now %d.\n", mood_->getOptionInt() );
}
void FunDisplay::makeDances( EditableEnumProperty* prop )
{
QStringList dances;
dances.push_back( "Robot/Turtlebot" );
dances.push_back( "Robot/PR2" );
dances.push_back( "Macarena/Fast" );
dances.push_back( "Macarena/Slow" );
dances.push_back( "Twist" );
dances.push_back( "Tango" );
dances.push_back( "Swing/Lindy" );
dances.push_back( "Swing/Hop/Small" );
dances.push_back( "Swing/Hop/Big" );
dances.push_back( "Stumble" );
dances.push_back( "Stomple" );
prop->clearOptions();
for( int i = 0; i < 9; i++ )
{
int index = random() % dances.size();
prop->addOption( dances[ index ]);
}
}
| 32.608696 | 119 | 0.677778 |
bebcf0902de4b69fe2a506c8136d4c024ee247d5 | 3,274 | cpp | C++ | Source/Array-1-RemoveDups.cpp | KarateSnoopy/LeetCodeSubmissions | 6da0c71e4104a43aea7a5029597685739b9f31b2 | [
"MIT"
] | null | null | null | Source/Array-1-RemoveDups.cpp | KarateSnoopy/LeetCodeSubmissions | 6da0c71e4104a43aea7a5029597685739b9f31b2 | [
"MIT"
] | null | null | null | Source/Array-1-RemoveDups.cpp | KarateSnoopy/LeetCodeSubmissions | 6da0c71e4104a43aea7a5029597685739b9f31b2 | [
"MIT"
] | null | null | null | // LeetCode.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
//int x = input[inputSize - 1];
//for (int i = inputSize - 1; i > 0; i--)
//{
// input[i] = input[i - 1];
//}
//input[0] = x;
//while (numsSize > 0)
//{
// numsSize -= 1;
//}
// nums = { 2, 2, 3, 4 }. numSize = 4;
int removeDuplicates(int* nums, int numsSize)
{
int x = 1;
int y = 2;
while( y < numsSize && x < numsSize )
{
if (nums[x] == nums[y])
{
y++;
}
else
{
nums[x] = nums[y];
x++;
y++;
}
}
int length = 0;
return length;
}
//
//
//int removeDuplicates(int* nums, int numsSize)
//{
// if (numsSize <= 1 || nums == NULL)
// {
// return numsSize;
// }
//
// int oldLength = numsSize;
// int* p1 = nums + 0;
// int* p2 = nums + 0;
// int newLength = 1;
//
// while (p2 < nums + numsSize) // p2 < nums[1] if numsSize == 2
// {
// if (*p1 == *p2)
// {
// p2++;
// }
// else
// {
// p1++;
// *p1 = *p2;
// newLength++;
// if (p2 == nums + numsSize - 1)
// {
// break;
// }
// p2++;
// }
// }
//
// return newLength;
//}
bool VerifyResult( std::vector<int> input, std::vector<int> expectedOutput )
{
//std::cout << "Input: ";
for (size_t i = 0; i < input.size(); i++)
{
std::cout << input[i] << ", ";
}
std::cout << std::endl;
int newLength = removeDuplicates(input.data(), (int)input.size());
std::cout << "Output: ";
for (int i = 0; i < newLength; i++)
{
std::cout << input[i] << ", ";
}
std::cout << std::endl;
if( newLength != expectedOutput.size() )
{
return false;
}
for (int i = 0; i < newLength; i++)
{
if( input[i] != expectedOutput[i] )
{
return false;
}
}
return true;
}
void TestArray1()
{
int nums[6] = { 7,1,5,3,9,4 };
int length = 6;
int biggestIndexSoFar = 0;
int smallestIndexSoFar = 0;
for (int i = 1; i < length; i++)
{
if (nums[biggestIndexSoFar] < nums[i])
{
biggestIndexSoFar = i;
}
if (nums[smallestIndexSoFar] > nums[i])
{
smallestIndexSoFar = i;
}
}
bool failed = false;
if (!VerifyResult({ 2,2,3,4 }, { 2,3,4 })) { std::cout << "Failed!"; failed = true; }
//if (!VerifyResult({ }, { })) { std::cout << "Failed!"; failed = true; }
//if (!VerifyResult({ 1 }, { 1 })) { std::cout << "Failed!"; failed = true; }
//if (!VerifyResult({ 10,10 }, { 10 })) { std::cout << "Failed!"; failed = true; }
//if (!VerifyResult({ 1,1,1 }, { 1 })) { std::cout << "Failed!"; failed = true; }
//if (!VerifyResult({ 2,5,9 }, { 2,5,9 })) { std::cout << "Failed!"; failed = true; }
//if (!VerifyResult({ -10,-10,5,9 }, { -10,5,9 })) { std::cout << "Failed!"; failed = true; }
//if (!VerifyResult({ 1,1,2,2,3,3,5,5 }, { 1,2,3,5 })) { std::cout << "Failed!"; failed = true; }
if( !failed ) std::cout << "Success!";
}
| 21.682119 | 101 | 0.442578 |
bec3cdfdc085fb7a2f2997c3cc209c5ba9794212 | 410 | cc | C++ | src/tools/hot_backup/sync_fault_state.cc | jdisearch/isearch1 | 272bd4ab0dc82d9e33c8543474b1294569947bb3 | [
"Apache-2.0"
] | 3 | 2021-08-18T09:59:42.000Z | 2021-09-07T03:11:28.000Z | src/tools/hot_backup/sync_fault_state.cc | jdisearch/isearch1 | 272bd4ab0dc82d9e33c8543474b1294569947bb3 | [
"Apache-2.0"
] | null | null | null | src/tools/hot_backup/sync_fault_state.cc | jdisearch/isearch1 | 272bd4ab0dc82d9e33c8543474b1294569947bb3 | [
"Apache-2.0"
] | null | null | null | #include "sync_fault_state.h"
FaultState::FaultState(SyncStateManager* pSyncStateManager)
: SyncStateBase()
{
m_pSyncStateManager = pSyncStateManager;
}
FaultState::~FaultState()
{
}
void FaultState::Enter()
{
log_error("Here is ErrorState");
}
void FaultState::Exit()
{
// do nothing
}
void FaultState::HandleEvent()
{
// 简单处理,程序结束
log_info("GoodBye hot_backup.");
exit(0);
} | 14.137931 | 59 | 0.682927 |
bec528bdccaf409b043f71101ac596fdadec3888 | 1,431 | hpp | C++ | nd-coursework/books/cpp/C++MoveSemantics/basics/card.hpp | crdrisko/nd-grad | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | 1 | 2020-09-26T12:38:55.000Z | 2020-09-26T12:38:55.000Z | nd-coursework/books/cpp/C++MoveSemantics/basics/card.hpp | crdrisko/nd-research | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | null | null | null | nd-coursework/books/cpp/C++MoveSemantics/basics/card.hpp | crdrisko/nd-research | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | null | null | null | // Copyright (c) 2020 by Nicolai Josuttis. All rights reserved.
// Licensed under the CCA-4.0 International License. See the LICENSE file in the project root for more information.
//
// Name: card.hpp
// Author: crdrisko
// Date: 08/08/2021-07:22:39
// Description: A class for the cards of a card game where each object is a valid card
#ifndef CARD_HPP
#define CARD_HPP
#include <cassert>
#include <iostream>
#include <string>
void assertValidCard(const std::string& val)
{
assert(val.find("seven") != std::string::npos || val.find("eight") != std::string::npos
|| val.find("nine") != std::string::npos || val.find("ten") != std::string::npos
|| val.find("jack") != std::string::npos || val.find("queen") != std::string::npos
|| val.find("king") != std::string::npos || val.find("ace") != std::string::npos);
assert(val.find("clubs") != std::string::npos || val.find("spades") != std::string::npos
|| val.find("hearts") != std::string::npos || val.find("diamonds") != std::string::npos);
}
class Card
{
private:
std::string value; // rank + "-of-" + suit
public:
Card(const std::string& val) : value {val}
{
assertValidCard(value); // ensure the value is always valid
}
// ...
std::string getValue() const { return value; }
friend std::ostream& operator<<(std::ostream& strm, const Card& c) { return strm << c.value; }
};
#endif
| 31.8 | 115 | 0.621244 |
bec673d7073fe18807d852a87afb6c56bc84cb75 | 2,024 | hpp | C++ | code/source/util/parallel_buffer.hpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | 12 | 2015-01-12T00:19:20.000Z | 2021-08-05T10:47:20.000Z | code/source/util/parallel_buffer.hpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | code/source/util/parallel_buffer.hpp | crafn/clover | 586acdbcdb34c3550858af125e9bb4a6300343fe | [
"MIT"
] | null | null | null | #ifndef CLOVER_UTIL_PARALLEL_BUFFER_HPP
#define CLOVER_UTIL_PARALLEL_BUFFER_HPP
#include "build.hpp"
#include "hardware/clstate.hpp"
namespace clover {
namespace visual {
/// @todo Shouldn't be in util >:(
class BaseVertexArrayObject;
class Framebuffer;
class Texture;
} // visual
namespace util {
class ParallelQueue;
/// @note Destroying/resetting can cause blocking if using kernel is running
class ParallelBuffer {
public:
ParallelBuffer();
ParallelBuffer(ParallelBuffer&&);
ParallelBuffer(const ParallelBuffer&)= delete;
virtual ~ParallelBuffer();
ParallelBuffer& operator=(ParallelBuffer&&);
ParallelBuffer& operator=(const ParallelBuffer&)= delete;
template <typename T>
void create(hardware::ClState::BufferFlag flags, T& first, uint32 element_count=1);
/// @note After aliasing, modifying state of GL object through GL API is UB!
void alias(hardware::ClState::BufferFlag flags, const visual::BaseVertexArrayObject& vao);
void alias(hardware::ClState::BufferFlag flags, const visual::Framebuffer& fbo);
void alias(hardware::ClState::BufferFlag flags, const visual::Texture& tex);
void aliasTex(hardware::ClState::BufferFlag flags, uint32 tex_target, uint32 tex_id);
void attachToQueue(util::ParallelQueue& q){ attachedQueue= &q; }
/// Reads data back to elements specified in create(..)
void read();
void acquire();
void release();
cl_mem getDId() const { return buffer.id; }
void reset();
private:
util::ParallelQueue* attachedQueue;
hardware::ClState::Buffer buffer;
void* hostData;
SizeType hostDataSize;
};
template <typename T>
void ParallelBuffer::create(hardware::ClState::BufferFlag flags, T& first, uint32 element_count){
ensure(hardware::gClState);
hostData= &first;
hostDataSize= sizeof(T)*element_count;
ensure(buffer.id == 0);
buffer=
hardware::gClState->createBuffer<T>(
hardware::gClState->getDefaultContext(),
(hardware::ClState::BufferFlag)flags,
first,
element_count);
}
} // util
} // clover
#endif // CLOVER_UTIL_PARALLEL_BUFFER_HPP | 25.620253 | 97 | 0.755435 |
bec90fa1a37ccc0f1313f73c188b4b4ca7998b28 | 328 | cpp | C++ | crack project/Keygen/1.2.cpp | IceIce1ce/Crack-project | 4bb3b35aad9efa5ff6f41886dc0f5efc169a44de | [
"MIT"
] | null | null | null | crack project/Keygen/1.2.cpp | IceIce1ce/Crack-project | 4bb3b35aad9efa5ff6f41886dc0f5efc169a44de | [
"MIT"
] | null | null | null | crack project/Keygen/1.2.cpp | IceIce1ce/Crack-project | 4bb3b35aad9efa5ff6f41886dc0f5efc169a44de | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
int main()
{
int id;
cout << "Enter number from 0 to 9999: ";
cin >> id;
int serial = 0;
serial += id + 76 + 1 + 907;
serial += serial;
serial *= 3;
serial -= 1;
cout << "Serial: "<< serial << endl;
system("pause");
return 0;
} | 19.294118 | 45 | 0.496951 |
bed3fd7ab77b0348ee635ae3c37007cd43ebd1be | 920 | cpp | C++ | FFmpegMediaCodecDemo/app/src/main/cpp/player_main.cpp | xhunmon/AFPlayer | ded67bb09e1606e7b105b5d1a8cec1e6ccda9b75 | [
"Apache-2.0"
] | 11 | 2021-01-30T01:52:20.000Z | 2022-01-23T19:19:03.000Z | FFmpegMediaCodecDemo/app/src/main/cpp/player_main.cpp | xhunmon/AFPlayer | ded67bb09e1606e7b105b5d1a8cec1e6ccda9b75 | [
"Apache-2.0"
] | null | null | null | FFmpegMediaCodecDemo/app/src/main/cpp/player_main.cpp | xhunmon/AFPlayer | ded67bb09e1606e7b105b5d1a8cec1e6ccda9b75 | [
"Apache-2.0"
] | 3 | 2021-07-24T16:17:27.000Z | 2021-12-14T08:43:55.000Z | #include <jni.h>
#include <string>
extern "C"{
#include "libavcodec/jni.h"
}
#include "core/hw_mediacodec.h"
extern "C"
JNIEXPORT jstring JNICALL
Java_com_xhunmon_ffmpegmediacodecdemo_core_Player_getFFVersion(JNIEnv *env, jobject type) {
return env->NewStringUTF(av_version_info());
}
extern "C"
JNIEXPORT void JNICALL
Java_com_xhunmon_ffmpegmediacodecdemo_core_Player_decode_1file(JNIEnv *env, jobject thiz, jstring in_path,
jstring out_path) {
const char *inPath = env->GetStringUTFChars(in_path, NULL);
const char *outPath = env->GetStringUTFChars(out_path, NULL);
new HWMediaCodec(inPath, outPath);
env->ReleaseStringUTFChars(in_path, inPath);
env->ReleaseStringUTFChars(out_path, outPath);
}
extern "C"
JNIEXPORT
jint JNI_OnLoad(JavaVM *vm, void *res) {
av_jni_set_java_vm(vm, 0);
// 返回jni版本
return JNI_VERSION_1_4;
} | 29.677419 | 106 | 0.711957 |
bed523490f6d089862452166226f5b9b085e44cc | 2,691 | cpp | C++ | cpp/cpp_libs/src/pcl_icp.cpp | maximilianharr/code_snippets | 8b271e6fa9174e24200e88be59e417abd5f2f59a | [
"BSD-3-Clause"
] | null | null | null | cpp/cpp_libs/src/pcl_icp.cpp | maximilianharr/code_snippets | 8b271e6fa9174e24200e88be59e417abd5f2f59a | [
"BSD-3-Clause"
] | null | null | null | cpp/cpp_libs/src/pcl_icp.cpp | maximilianharr/code_snippets | 8b271e6fa9174e24200e88be59e417abd5f2f59a | [
"BSD-3-Clause"
] | null | null | null | /**
* @file pcl_icp.cpp
* @author Maximilian Harr <maximilian.harr@daimler.com>
* @date 22.04.2017
*
* @brief Point cloud library [http://www.pointclouds.org/]
* Comes with ROS [http://wiki.ros.org/pcl/]
* ICP (Iterative Closest Point) Tutorial [ http://pointclouds.org/documentation/tutorials/iterative_closest_point.php ]
*
* Coding Standard:
* wiki.ros.org/CppStyleGuide
* https://google.github.io/styleguide/cppguide.html
*
*
* @bug
*
*
* @todo Plot data in Gnuplot (visualize GNSS data) see "int main()"
*
*
*/
#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/registration/icp.h>
#include <pcl/features/feature.h>
#include <pcl/features/impl/feature.hpp>
#include <pcl/search/impl/kdtree.hpp>
#include <pcl/kdtree/impl/kdtree_flann.hpp>
#include <pcl/features/impl/shot_omp.hpp>
int
main (int argc, char** argv)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_in (new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_out (new pcl::PointCloud<pcl::PointXYZ>);
// Fill in the CloudIn data
cloud_in->width = 5;
cloud_in->height = 1;
cloud_in->is_dense = false;
cloud_in->points.resize (cloud_in->width * cloud_in->height);
for (size_t i = 0; i < cloud_in->points.size (); ++i)
{
cloud_in->points[i].x = 1024 * rand () / (RAND_MAX + 1.0f);
cloud_in->points[i].y = 1024 * rand () / (RAND_MAX + 1.0f);
cloud_in->points[i].z = 1024 * rand () / (RAND_MAX + 1.0f);
}
std::cout << "Saved " << cloud_in->points.size () << " data points to input:"
<< std::endl;
for (size_t i = 0; i < cloud_in->points.size (); ++i) std::cout << " " <<
cloud_in->points[i].x << " " << cloud_in->points[i].y << " " <<
cloud_in->points[i].z << std::endl;
*cloud_out = *cloud_in;
std::cout << "size:" << cloud_out->points.size() << std::endl;
for (size_t i = 0; i < cloud_in->points.size (); ++i)
cloud_out->points[i].x = cloud_in->points[i].x + 0.7f;
std::cout << "Transformed " << cloud_in->points.size () << " data points:"
<< std::endl;
for (size_t i = 0; i < cloud_out->points.size (); ++i)
std::cout << " " << cloud_out->points[i].x << " " <<
cloud_out->points[i].y << " " << cloud_out->points[i].z << std::endl;
pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;
icp.setInputCloud(cloud_in);
icp.setInputTarget(cloud_out);
pcl::PointCloud<pcl::PointXYZ> Final;
icp.align(Final);
std::cout << "has converged:" << icp.hasConverged() << " score: " <<
icp.getFitnessScore() << std::endl;
std::cout << icp.getFinalTransformation() << std::endl;
return (0);
}
| 35.407895 | 128 | 0.622445 |
bed56def576f735df8f63bce3be00f3d85769aa7 | 15,173 | cpp | C++ | gb-emu/Main.cpp | darkxex/GameLad | 4c21383a1a023cea4f439e9a64323f21bd656634 | [
"MIT"
] | 8 | 2021-04-29T02:43:37.000Z | 2021-05-06T20:50:11.000Z | gb-emu/Main.cpp | darkxex/GameLad | 4c21383a1a023cea4f439e9a64323f21bd656634 | [
"MIT"
] | null | null | null | gb-emu/Main.cpp | darkxex/GameLad | 4c21383a1a023cea4f439e9a64323f21bd656634 | [
"MIT"
] | null | null | null | #include "PCH.hpp"
#include <Emulator.hpp>
#ifdef __SWITCH__
#include <unistd.h>
#include <switch.h>
#include <dirent.h>
#include <iostream>
#endif
// 60 FPS or 16.67ms
const double TimePerFrame = 1.0 / 60.0;
// The number of CPU cycles per frame
const unsigned int CyclesPerFrame = 70224;
struct SDLWindowDeleter
{
void operator()(SDL_Window* window)
{
if (window != nullptr)
{
SDL_DestroyWindow(window);
}
}
};
struct SDLRendererDeleter
{
void operator()(SDL_Renderer* renderer)
{
if (renderer != nullptr)
{
SDL_DestroyRenderer(renderer);
}
}
};
struct SDLTextureDeleter
{
void operator()(SDL_Texture* texture)
{
if (texture != nullptr)
{
SDL_DestroyTexture(texture);
}
}
};
int windowWidth = 1280;
int windowHeight = 720;
void Render(SDL_Renderer* pRenderer, SDL_Texture* pTexture, Emulator& emulator)
{
// Clear window
SDL_SetRenderDrawColor(pRenderer, 0x00, 0x00, 0x00, 0xFF);
SDL_RenderClear(pRenderer);
byte* pPixels;
int pitch = 0;
SDL_LockTexture(pTexture, nullptr, (void**)&pPixels, &pitch);
// Render Game
byte* pData = emulator.GetCurrentFrame();
memcpy(pPixels, pData, 160 * 144 * 4);
SDL_UnlockTexture(pTexture);
SDL_Rect dstrect;
dstrect.w = 160*5;
dstrect.h = 144*5;
dstrect.x = (windowWidth - dstrect.w)/2;
dstrect.y = 0;
SDL_RenderCopy(pRenderer, pTexture, nullptr, &dstrect);
// Update window
SDL_RenderPresent(pRenderer);
}
// TODO: refactor this
std::unique_ptr<SDL_Renderer, SDLRendererDeleter> spRenderer;
std::unique_ptr<SDL_Texture, SDLTextureDeleter> spTexture;
Emulator emulator;
// The emulator will call this whenever we hit VBlank
void VSyncCallback()
{
Render(spRenderer.get(), spTexture.get(), emulator);
}
PadState pad;
bool closegame = false;
void ProcessInput(Emulator& emulator)
{
SDL_PumpEvents();
const Uint8 *keys = SDL_GetKeyboardState(NULL);
byte input = JOYPAD_NONE;
byte buttons = JOYPAD_NONE;
if(keys[SDL_SCANCODE_W])
{
input |= JOYPAD_INPUT_UP;
}
if(keys[SDL_SCANCODE_A])
{
input |= JOYPAD_INPUT_LEFT;
}
if(keys[SDL_SCANCODE_S])
{
input |= JOYPAD_INPUT_DOWN;
}
if(keys[SDL_SCANCODE_D])
{
input |= JOYPAD_INPUT_RIGHT;
}
if(keys[SDL_SCANCODE_K])
{
buttons |= JOYPAD_BUTTONS_A;
}
if(keys[SDL_SCANCODE_L])
{
buttons |= JOYPAD_BUTTONS_B;
}
if(keys[SDL_SCANCODE_N])
{
buttons |= JOYPAD_BUTTONS_START;
}
if(keys[SDL_SCANCODE_M])
{
buttons |= JOYPAD_BUTTONS_SELECT;
}
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
// padGetButtons returns the set of buttons that are currently pressed
u64 kHeld = padGetButtons(&pad);
// padGetButtonsUp returns the set of buttons that have been
// newly released in this frame compared to the previous one
u64 kUp = padGetButtonsUp(&pad);
if (kHeld & HidNpadButton_Plus)
{
buttons |= JOYPAD_BUTTONS_START;
}
if (kHeld & HidNpadButton_Minus)
{
buttons |= JOYPAD_BUTTONS_SELECT;
}
if (kHeld & HidNpadButton_Left)
{
input |= JOYPAD_INPUT_LEFT;
}
if (kHeld & HidNpadButton_Up)
{
input |= JOYPAD_INPUT_UP;
}
if (kHeld & HidNpadButton_Right)
{
input |= JOYPAD_INPUT_RIGHT;
}
if (kHeld & HidNpadButton_Down)
{
input |= JOYPAD_INPUT_DOWN;
}
if (kHeld & HidNpadButton_A)
{
buttons |= JOYPAD_BUTTONS_A;
}
if (kHeld & HidNpadButton_B)
{
buttons |= JOYPAD_BUTTONS_B;
}
if (kHeld & HidNpadButton_StickR && kHeld & HidNpadButton_StickL)
{
closegame = true;
}
emulator.SetInput(input, buttons);
}
#ifdef __SWITCH__
int getInd(char* curFile, int curIndex) {
DIR* dir;
struct dirent* ent;
if (curIndex < 0)
curIndex = 0;
dir = opendir("sdmc:/gbroms/");//Open current-working-directory.
if (dir == NULL)
{
sprintf(curFile, "Failed to open dir!");
return curIndex;
}
else
{
int i;
for (i = 0; i <= curIndex; i++) {
ent = readdir(dir);
}
if (ent)
sprintf(curFile, "sdmc:/gbroms/%s", ent->d_name);
else
curIndex--;
closedir(dir);
}
return curIndex;
}
#endif
int main(int argc, char** argv)
{
romfsInit();
socketInitializeDefault();
nxlinkStdio();
struct stat st = { 0 };
if (stat("sdmc:/gbroms", &st) == -1) {
mkdir("sdmc:/gbroms", 0777);
}
// Configure our supported input layout: a single player with standard controller styles
padConfigureInput(1, HidNpadStyleSet_NpadStandard);
// Initialize the default gamepad (which reads handheld mode inputs as well as the first connected controller)
padInitializeDefault(&pad);
int curIndex = 0;
char curFile[255];
curIndex = getInd(curFile, curIndex);
/* if(argc > 1)
{
windowScale = atoi(argv[1]);
}
*/
std::string bootROM;
//std::string bootROM = "res/games/dmg_bios.bin";
//std::string bootROM = "res/games/gbc_bios.bin";
std::string romPath = ""; // PASSED
//std::string romPath = "res/tests/01-special.gb"; // PASSED
//std::string romPath = "res/tests/02-interrupts.gb"; // PASSED
//std::string romPath = "res/tests/03-op sp,hl.gb"; // PASSED
//std::string romPath = "res/tests/04-op r,imm.gb"; // PASSED
//std::string romPath = "res/tests/05-op rp.gb"; // PASSED
//std::string romPath = "res/tests/06-ld r,r.gb"; // PASSED
//std::string romPath = "res/tests/07-jr,jp,call,ret,rst.gb"; // PASSED
//std::string romPath = "res/tests/08-misc instrs.gb"; // PASSED
//std::string romPath = "res/tests/09-op r,r.gb"; // PASSED
//std::string romPath = "res/tests/10-bit ops.gb"; // PASSED
//std::string romPath = "res/tests/11-op a,(hl).gb"; // PASSED
//std::string romPath = "res/tests/instr_timing.gb"; // PASSED
//std::string romPath = "res/tests/mem_timing.gb"; // FAILED
//std::string romPath = "res/tests/01-read_timing.gb"; // FAILED
//std::string romPath = "res/tests/02-write_timing.gb"; // FAILED
//std::string romPath = "res/tests/03-modify_timing.gb"; // FAILED
//std::string romPath = "res/tests/oam_bug.gb"; // FAILED
//std::string romPath = "res/games/Pokemon - Blue Version.gb";
//std::string romPath = "res/games/Tetris (World).gb";
//std::string romPath = "res/games/Super Mario Land (World).gb";
//std::string romPath = "res/games/Tamagotchi.gb";
//std::string romPath = "res/games/Battletoads.gb";
//std::string romPath = "res/games/Tetris.gb";
//std::string romPath = "res/games/Zelda.gb";
//std::string romPath = "res/games/plantboy.gb";
//std::string romPath = "res/games/Metroid.gb";
//std::string romPath = "res/games/Castlevania.gb";
// CGB Only
//std::string romPath = "res/games/Lemmings.gbc"; // Requires MBC5
//std::string romPath = "res/games/Mario2.gbc"; // Requires MBC5
if(argc > 2)
{
romPath = argv[2];
}
bool isRunning = true;
std::unique_ptr<SDL_Window, SDLWindowDeleter> spWindow;
//selectrom
/* consoleInit(NULL);
while(appletMainLoop())
{consoleClear();
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
printf("\x1b[16;0HSelect the gb rom from your Roms folder with Left Button and Right Button:");
printf("\x1b[18;0H%s", curFile);
// padGetButtonsDown returns the set of buttons that have been newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
if (kDown & HidNpadButton_Left)
{
curIndex--;
curIndex = getInd(curFile, curIndex);
}
if (kDown & HidNpadButton_Right)
{
curIndex++;
curIndex = getInd(curFile, curIndex);
}
if (kDown & HidNpadButton_A)
{
break;}
consoleUpdate(NULL);
}
consoleExit(NULL);*/
SDL_Event event;
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0)
{
Logger::LogError("SDL could not initialize! SDL error: '%s'", SDL_GetError());
return false;
}
//Initialize SDL_ttf
if( TTF_Init() == -1 )
{
return false;
}
// Create window
spWindow = std::unique_ptr<SDL_Window, SDLWindowDeleter>(
SDL_CreateWindow(
"GameLad",
0,
0,
windowWidth,
windowHeight,
0));
if (spWindow == nullptr)
{
Logger::LogError("Window could not be created! SDL error: '%s'", SDL_GetError());
return false;
}
// Create renderer
spRenderer = std::unique_ptr<SDL_Renderer, SDLRendererDeleter>(
SDL_CreateRenderer(spWindow.get(), 0, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC));
if (spRenderer == nullptr)
{
Logger::LogError("Renderer could not be created! SDL error: '%s'", SDL_GetError());
return false;
}
//test injection
bool quit = false;
SDL_Surface* Loading_Surf;
SDL_Texture* Background_Tx;
SDL_Texture* BlueShapes;
/* Rectangles for drawing which will specify source (inside the texture)
and target (on the screen) for rendering our textures. */
SDL_Rect SrcR;
SDL_Rect DestR;
while (!quit && appletMainLoop())
{
// Scan the gamepad. This should be done once for each frame
padUpdate(&pad);
// padGetButtonsDown returns the set of buttons that have been
// newly pressed in this frame compared to the previous one
u64 kDown = padGetButtonsDown(&pad);
// padGetButtons returns the set of buttons that are currently pressed
u64 kHeld = padGetButtons(&pad);
// padGetButtonsUp returns the set of buttons that have been
// newly released in this frame compared to the previous one
u64 kUp = padGetButtonsUp(&pad);
if (kDown & HidNpadButton_Left)
{
curIndex--;
curIndex = getInd(curFile, curIndex);
std::cout << curFile << std::endl;
}
if (kDown & HidNpadButton_Right)
{
curIndex++;
curIndex = getInd(curFile, curIndex);
std::cout << curFile << std::endl;
}
if (kDown & HidNpadButton_A)
{
romPath = curFile;
quit = true;
}
// Clear window
SDL_SetRenderDrawColor(spRenderer.get(), 0x00, 0x00, 0x00, 0xFF);
SDL_RenderClear(spRenderer.get());
TTF_Font* Sans = TTF_OpenFont("romfs:/lazy.ttf", 30); //this opens a font style and sets a size
TTF_Font* Sans2 = TTF_OpenFont("romfs:/lazy.ttf", 30); //this opens a font style and sets a size
SDL_Color White = {255, 255, 255}; // this is the color in rgb format, maxing out all would give you the color white, and it will be your text's color
SDL_Surface* surfaceMessage = TTF_RenderText_Blended(Sans, "Select your GBRom from your gbroms Folder in SD. L3 + R3 for Exit with SRAM.", White); // as TTF_RenderText_Solid could only be used on SDL_Surface then you have to create the surface first
SDL_Texture* Message = SDL_CreateTextureFromSurface(spRenderer.get(), surfaceMessage); //now you can convert it into a texture
SDL_Rect Message_rect; //create a rect
Message_rect.x = 10; //controls the rect's x coordinate
Message_rect.y = 360; // controls the rect's y coordinte
Message_rect.w = surfaceMessage->w; // controls the width of the rect
Message_rect.h = surfaceMessage->h; // controls the height of the rect
SDL_Surface* surfaceMessage2 = TTF_RenderText_Blended(Sans2, curFile, White); // as TTF_RenderText_Solid could only be used on SDL_Surface then you have to create the surface first
SDL_Texture* Message2 = SDL_CreateTextureFromSurface(spRenderer.get(), surfaceMessage2); //now you can convert it into a texture
SDL_Rect Message2_rect; //create a rect
Message2_rect.x = 10; //controls the rect's x coordinate
Message2_rect.y = 600; // controls the rect's y coordinte
Message2_rect.w = surfaceMessage2->w; // controls the width of the rect
Message2_rect.h = surfaceMessage2->h; // controls the height of the rect
SDL_FreeSurface(surfaceMessage);
SDL_FreeSurface(surfaceMessage2);
SDL_RenderCopy(spRenderer.get(), Message, nullptr, &Message_rect);
SDL_RenderCopy(spRenderer.get(), Message2, nullptr, &Message2_rect);
// Update window
SDL_RenderPresent(spRenderer.get());
}
//test injection
spTexture = std::unique_ptr<SDL_Texture, SDLTextureDeleter>(
SDL_CreateTexture(spRenderer.get(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, 160, 144));
if (emulator.Initialize(bootROM.empty() ? nullptr : bootROM.data(), romPath.data()))
{
emulator.SetVSyncCallback(&VSyncCallback);
unsigned int cycles = 0;
Uint64 frameStart = SDL_GetPerformanceCounter();
while (isRunning)
{
// Poll for window input
while (SDL_PollEvent(&event) != 0)
{
if (event.type == SDL_QUIT)
{
isRunning = false;
emulator.SetVSyncCallback(nullptr);
}
}
if (closegame == true)
{
isRunning = false;
emulator.SetVSyncCallback(nullptr);
}
if (!isRunning)
{
// Exit early if the app is closing
continue;
}
ProcessInput(emulator);
while (cycles < CyclesPerFrame)
{
cycles += emulator.Step();
}
cycles -= CyclesPerFrame;
Uint64 frameEnd = SDL_GetPerformanceCounter();
// Loop until we use up the rest of our frame time
while (true)
{
frameEnd = SDL_GetPerformanceCounter();
double frameElapsedInSec = (double)(frameEnd - frameStart) / SDL_GetPerformanceFrequency();
// Break out once we use up our time per frame
if (frameElapsedInSec >= TimePerFrame)
{
break;
}
}
frameStart = frameEnd;
}
}
emulator.Stop();
spTexture.reset();
spRenderer.reset();
spWindow.reset();
socketExit();
romfsExit();
SDL_Quit();
return 0;
}
| 27.94291 | 249 | 0.605813 |
bede311bcd84c89fdf5538666aed61f014d642c4 | 5,855 | cpp | C++ | source/lib/memory/mmu_factory.cpp | olduf/gb-emu | 37a2195fa67a2656cc11541eb75b1f7a548057b2 | [
"Unlicense"
] | null | null | null | source/lib/memory/mmu_factory.cpp | olduf/gb-emu | 37a2195fa67a2656cc11541eb75b1f7a548057b2 | [
"Unlicense"
] | null | null | null | source/lib/memory/mmu_factory.cpp | olduf/gb-emu | 37a2195fa67a2656cc11541eb75b1f7a548057b2 | [
"Unlicense"
] | null | null | null | #include "lib/memory/mmu_factory.hpp"
// Initial values come from the Gambatte source code
// https://github.com/sinamas/gambatte/blob/master/libgambatte/src/initstate.cpp
namespace gb_lib {
MMU* MMUFactory::create(uint8_t* rom, uint32_t romSize, DMAMediator* dmaMediator, DMAMediator* hdmaMediator, MemorySpace* timerHandler, InterruptMediator* interruptMediator, bool isCGB)
{
MemorySpace* cartridge = this->cartridgeFactory.create(rom, romSize);
MemorySpace* highRam = this->createHighRam(isCGB);
MemorySpace* ioRegisters = this->createIORegisters(dmaMediator, hdmaMediator, timerHandler, interruptMediator, isCGB);
MemorySpace* oam = new OAM(ioRegisters);
MemorySpace* unusedMemoryFEA0_FEFF = nullptr;
MemorySpace* videoRam = nullptr;
MemorySpace* workingRam = nullptr;
if (isCGB)
{
unusedMemoryFEA0_FEFF = new CGBUnusedMemoryFEA0_FEFF();
videoRam = new CGBVideoRam(ioRegisters);
workingRam = new CGBWorkingRam(ioRegisters);
}
else
{
unusedMemoryFEA0_FEFF = new UnusedMemoryFEA0_FEFF();
videoRam = new VideoRam(ioRegisters);
workingRam = new WorkingRam();
}
return new MMU(cartridge, highRam, ioRegisters, oam, unusedMemoryFEA0_FEFF, videoRam, workingRam);
}
MemorySpace* MMUFactory::createHighRam(bool isCGB)
{
MemorySpace* highRam = new HighRam();
if (isCGB)
{
uint8_t initialValues[0x80] = {
0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B,
0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D,
0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E,
0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99,
0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC,
0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E,
0x45, 0xEC, 0x42, 0xFA, 0x08, 0xB7, 0x07, 0x5D,
0x01, 0xF5, 0xC0, 0xFF, 0x08, 0xFC, 0x00, 0xE5,
0x0B, 0xF8, 0xC2, 0xCA, 0xF4, 0xF9, 0x0D, 0x7F,
0x44, 0x6D, 0x19, 0xFE, 0x46, 0x97, 0x33, 0x5E,
0x08, 0xFF, 0xD1, 0xFF, 0xC6, 0x8B, 0x24, 0x74,
0x12, 0xFC, 0x00, 0x9F, 0x94, 0xB7, 0x06, 0xD5,
0x40, 0x7A, 0x20, 0x9E, 0x04, 0x5F, 0x41, 0x2F,
0x3D, 0x77, 0x36, 0x75, 0x81, 0x8A, 0x70, 0x3A,
0x98, 0xD1, 0x71, 0x02, 0x4D, 0x01, 0xC1, 0xFF,
0x0D, 0x00, 0xD3, 0x05, 0xF9, 0x00, 0x0B, 0x00
};
for (uint16_t i = 0; i < 0x80; i++)
{
highRam->setByteInternal(0xFF80 + i, initialValues[i]);
}
}
else
{
uint8_t initialValues[0x80] = {
0x2B, 0x0B, 0x64, 0x2F, 0xAF, 0x15, 0x60, 0x6D,
0x61, 0x4E, 0xAC, 0x45, 0x0F, 0xDA, 0x92, 0xF3,
0x83, 0x38, 0xE4, 0x4E, 0xA7, 0x6C, 0x38, 0x58,
0xBE, 0xEA, 0xE5, 0x81, 0xB4, 0xCB, 0xBF, 0x7B,
0x59, 0xAD, 0x50, 0x13, 0x5E, 0xF6, 0xB3, 0xC1,
0xDC, 0xDF, 0x9E, 0x68, 0xD7, 0x59, 0x26, 0xF3,
0x62, 0x54, 0xF8, 0x36, 0xB7, 0x78, 0x6A, 0x22,
0xA7, 0xDD, 0x88, 0x15, 0xCA, 0x96, 0x39, 0xD3,
0xE6, 0x55, 0x6E, 0xEA, 0x90, 0x76, 0xB8, 0xFF,
0x50, 0xCD, 0xB5, 0x1B, 0x1F, 0xA5, 0x4D, 0x2E,
0xB4, 0x09, 0x47, 0x8A, 0xC4, 0x5A, 0x8C, 0x4E,
0xE7, 0x29, 0x50, 0x88, 0xA8, 0x66, 0x85, 0x4B,
0xAA, 0x38, 0xE7, 0x6B, 0x45, 0x3E, 0x30, 0x37,
0xBA, 0xC5, 0x31, 0xF2, 0x71, 0xB4, 0xCF, 0x29,
0xBC, 0x7F, 0x7E, 0xD0, 0xC7, 0xC3, 0xBD, 0xCF,
0x59, 0xEA, 0x39, 0x01, 0x2E, 0x00, 0x69, 0x00
};
for (uint16_t i = 0; i < 0x80; i++)
{
highRam->setByteInternal(0xFF80 + i, initialValues[i]);
}
}
return highRam;
}
MemorySpace* MMUFactory::createIORegisters(DMAMediator* dmaMediator, DMAMediator* hdmaMediator, MemorySpace* timerHandler, InterruptMediator* interruptMediator, bool isCGB)
{
MemorySpace* ioRegisters = new IORegisters(dmaMediator, hdmaMediator, timerHandler, interruptMediator, isCGB);
ioRegisters->setByteInternal(0xFF05, 0x00); // TIMA
ioRegisters->setByteInternal(0xFF06, 0x00); // TMA
ioRegisters->setByteInternal(0xFF07, 0x00); // TAC
ioRegisters->setByteInternal(0xFF10, 0x80); // NR10
ioRegisters->setByteInternal(0xFF11, 0xBF); // NR11
ioRegisters->setByteInternal(0xFF12, 0xF3); // NR12
ioRegisters->setByteInternal(0xFF14, 0xBF); // NR14
ioRegisters->setByteInternal(0xFF16, 0x3F); // NR21
ioRegisters->setByteInternal(0xFF17, 0x00); // NR22
ioRegisters->setByteInternal(0xFF19, 0xBF); // NR24
ioRegisters->setByteInternal(0xFF1A, 0x7F); // NR30
ioRegisters->setByteInternal(0xFF1B, 0xFF); // NR31
ioRegisters->setByteInternal(0xFF1C, 0x9F); // NR32
ioRegisters->setByteInternal(0xFF1E, 0xBF); // NR33
ioRegisters->setByteInternal(0xFF20, 0xFF); // NR41
ioRegisters->setByteInternal(0xFF21, 0x00); // NR42
ioRegisters->setByteInternal(0xFF22, 0x00); // NR43
ioRegisters->setByteInternal(0xFF23, 0xBF); // NR30
ioRegisters->setByteInternal(0xFF24, 0x77); // NR50
ioRegisters->setByteInternal(0xFF25, 0xF3); // NR51
ioRegisters->setByteInternal(0xFF26, 0xF1); // NR52
ioRegisters->setByteInternal(0xFF40, 0x91); // LCDC
ioRegisters->setByteInternal(0xFF42, 0x00); // SCY
ioRegisters->setByteInternal(0xFF43, 0x00); // SCX
ioRegisters->setByteInternal(0xFF45, 0x00); // LYC
ioRegisters->setByteInternal(0xFF47, 0xFC); // BGP
ioRegisters->setByteInternal(0xFF48, 0xFF); // OBP0
ioRegisters->setByteInternal(0xFF49, 0xFF); // OBP1
ioRegisters->setByteInternal(0xFF4A, 0x00); // WY
ioRegisters->setByteInternal(0xFF4B, 0x00); // WX
if (isCGB)
{
// unsure, pandocs states it should be for SGB
ioRegisters->setByteInternal(0xFF26, 0xF0); // NR52
}
return ioRegisters;
}
}
| 42.122302 | 186 | 0.641674 |
bedf9bf367676509351f56af3d525586bf7520cd | 1,210 | cpp | C++ | src/main.cpp | lukasz-pawlos/ukladV2 | 56d643d339160a891e5168fdaa576bab0a87f8a4 | [
"MIT"
] | null | null | null | src/main.cpp | lukasz-pawlos/ukladV2 | 56d643d339160a891e5168fdaa576bab0a87f8a4 | [
"MIT"
] | null | null | null | src/main.cpp | lukasz-pawlos/ukladV2 | 56d643d339160a891e5168fdaa576bab0a87f8a4 | [
"MIT"
] | null | null | null | #include <iostream>
#include "SWektor.hh"
#include "Macierz.hh"
#include "UkladRownan.hh"
#include "rozmiar.h"
#include "LZespolona.hh"
using namespace std;
int main()
{
char x;
cin >> x;
if (x == 'r') ///DLA DOUBLE
{
UkladRownanLiniowych<double, ROZMIAR> B;
SWektor<double, ROZMIAR> C, D;
cin >> B;
C = B.obliczuklad(); //Obliczenie wektora wynikow
B.wywtrans(); //Ztransponowanie macierzy
cout << B;
D = B.wekbl(C); //Obliczenie wektora bledu
wyswrozw(C, D); // Wyswietlenie rozwiazan
return 0;
}
else if (x == 'z') ///DLA ZESPOLONYCH
{
UkladRownanLiniowych<LZespolona, ROZMIAR> B;
SWektor<LZespolona, ROZMIAR> C, D;
cin >> B;
C = B.obliczuklad(); //Obliczenie wektora wynikow
B.wywtrans(); //Ztransponowanie macierzy
cout << B;
D = B.wekbl(C); //Obliczenie wektora bledu
wyswrozw(C, D); // Wyswietlenie rozwiazan
return 0;
}
else
{
cout << endl << "Nieprawidlowa opcja wywolania!" << endl;
cout << "Dostepne opcje to: 'r'->(rzeczywiste) lub 'z'->(zespolone)" << endl;
return 1;
}
}
| 20.166667 | 84 | 0.561157 |
bee1e1e4b5c5800a360b7a72a22951d90ac2ce30 | 4,666 | cpp | C++ | ch16-09-extruded-a/src/Utils.cpp | pulpobot/C-SFML-html5-animation | 14154008b853d1235e8ca35a5b23b6a70366f914 | [
"MIT"
] | 73 | 2017-12-14T00:33:23.000Z | 2022-02-09T12:04:52.000Z | ch17-03-extruded-a-light/src/Utils.cpp | threaderic/C-SFML-html5-animation | 22f302cdf7c7c00247609da30e1bcf472d134583 | [
"MIT"
] | null | null | null | ch17-03-extruded-a-light/src/Utils.cpp | threaderic/C-SFML-html5-animation | 22f302cdf7c7c00247609da30e1bcf472d134583 | [
"MIT"
] | 5 | 2017-12-26T03:30:07.000Z | 2020-07-05T04:58:24.000Z | #include <sstream>
#include <iostream>
#include "Utils.h"
void Utils::Bezier::QuadraticBezierCurve(const sf::Vector2f &p0, sf::Vector2f &p1, sf::Vector2f &p2, int segments,
std::vector<sf::Vector2f> &curvePoints, bool throughControlPoint) {
//If there are any segments required
if (segments <= 0)
return;
//Quadratic Bezier Curve Math Formula: (1 - t)*((1-t)*p0 + t*p1) + t*((1-t)*p1 + t*p2);
curvePoints.clear();
float stepIncreasement = 1.0f / segments;
float t = 0.0f;
float px = 0.0f;
float py = 0.0f;
if (throughControlPoint) {
p1.x = p1.x * 2 - (p0.x + p2.x) / 2;
p1.y = p1.y * 2 - (p0.y + p2.y) / 2;
}
for (int i = 0; i <= segments; i++) {
px = (1.0f - t) * ((1.0f - t) * p0.x + t * p1.x) + t * ((1.0f - t) * p1.x + t * p2.x);
py = (1.0f - t) * ((1.0f - t) * p0.y + t * p1.y) + t * ((1.0f - t) * p1.y + t * p2.y);
curvePoints.push_back(sf::Vector2f(px, py));
t += stepIncreasement;
}
}
void Utils::Bezier::QuadraticBezierCurve(const sf::Vector2f &p0, sf::Vector2f &p1, sf::Vector2f &p2, int segments,
std::vector<sf::Vertex> &curvePoints, sf::Color lineColor,
bool throughControlPoint) {
//If there are any segments required
if (segments <= 0)
return;
//Quadratic Bezier Curve Math Formula: (1 - t)*((1-t)*p0 + t*p1) + t*((1-t)*p1 + t*p2);
curvePoints.clear();
float stepIncreasement = 1.0f / segments;
float t = 0;
float px = 0;
float py = 0;
if (throughControlPoint) {
p1.x = p1.x * 2 - (p0.x + p2.x) / 2;
p1.y = p1.y * 2 - (p0.y + p2.y) / 2;
}
//Add points based on control point's position
for (int i = 0; i <= segments; i++) {
px = (1.0f - t) * ((1.0f - t) * p0.x + t * p1.x) + t * ((1.0f - t) * p1.x + t * p2.x);
py = (1.0f - t) * ((1.0f - t) * p0.y + t * p1.y) + t * ((1.0f - t) * p1.y + t * p2.y);
curvePoints.push_back(sf::Vertex(sf::Vector2f(px, py), lineColor));
t += stepIncreasement;
}
}
///Same as QuadraticBezierCurve, but it doesn't clear the array before pushing vertex
void Utils::Bezier::AccumulativeQuadraticBezierCurve(const sf::Vector2f &p0, sf::Vector2f &p1, sf::Vector2f &p2,
int segments, std::vector<sf::Vertex> &curvePoints,
sf::Color lineColor, bool throughControlPoint) {
//If there are any segments required
if (segments <= 0)
return;
//Quadratic Bezier Curve Math Formula: (1 - t)*((1-t)*p0 + t*p1) + t*((1-t)*p1 + t*p2);
float stepIncreasement = 1.0f / segments;
float t = 0;
float px = 0;
float py = 0;
if (throughControlPoint) {
p1.x = p1.x * 2 - (p0.x + p2.x) / 2;
p1.y = p1.y * 2 - (p0.y + p2.y) / 2;
}
//Add points based on control point's position
for (int i = 0; i <= segments; i++) {
px = (1.0f - t) * ((1.0f - t) * p0.x + t * p1.x) + t * ((1.0f - t) * p1.x + t * p2.x);
py = (1.0f - t) * ((1.0f - t) * p0.y + t * p1.y) + t * ((1.0f - t) * p1.y + t * p2.y);
curvePoints.push_back(sf::Vertex(sf::Vector2f(px, py), lineColor));
t += stepIncreasement;
}
}
bool ::Utils::ContainsPoint(sf::FloatRect rect, float x, float y) {
//SFML already has a "contains" function inside FloatRect class
//return rect.contains(x,y);
return !(x < rect.left || x > rect.left + rect.width ||
y < rect.top || y > rect.top + rect.height);
}
bool ::Utils::Intersects(sf::FloatRect rectA, sf::FloatRect rectB) {
//SFML already has an "intersects" function inside FloatRect class
//return rectA.intersects(rectB);
return !(rectA.left + rectA.width < rectB.left ||
rectB.left + rectB.width < rectA.left ||
rectA.top + rectA.width < rectB.top ||
rectB.top + rectB.width < rectA.top );
}
/// Input string examples: "#ffcccc" - "ffcccc" - "#ff" - "ffccccff" - "ffcccc"
sf::Color Utils::HexColorToSFMLColor(std::string hexValue){
//remove # symbol
if(hexValue.size() % 2 != 0)
hexValue = hexValue.substr(1);
unsigned int r = std::stoul(hexValue.substr(0,2), nullptr, 16);
unsigned int g = (hexValue.size() > 2) ? std::stoul(hexValue.substr(2,2), nullptr, 16) : 0;
unsigned int b = (hexValue.size() > 4) ? std::stoul(hexValue.substr(4,2), nullptr, 16) : 0;
unsigned int a = (hexValue.size() > 6) ? std::stoul(hexValue.substr(6,2), nullptr, 16) : 255;
return sf::Color(r,g,b,a);
}
| 39.542373 | 114 | 0.536434 |
bee226083cad300103ba217fb6ad1b1e20152853 | 983 | cpp | C++ | tests/whole-program/structreturn.cpp | v8786339/NyuziProcessor | 34854d333d91dbf69cd5625505fb81024ec4f785 | [
"Apache-2.0"
] | 1,388 | 2015-02-05T17:16:17.000Z | 2022-03-31T07:17:08.000Z | tests/whole-program/structreturn.cpp | czvf/NyuziProcessor | 31f74e43a785fa66d244f1e9744ca0ca9b8a1fad | [
"Apache-2.0"
] | 176 | 2015-02-02T02:54:06.000Z | 2022-02-01T06:00:21.000Z | tests/whole-program/structreturn.cpp | czvf/NyuziProcessor | 31f74e43a785fa66d244f1e9744ca0ca9b8a1fad | [
"Apache-2.0"
] | 271 | 2015-02-18T02:19:04.000Z | 2022-03-28T13:30:25.000Z | //
// Copyright 2011-2015 Jeff Bush
//
// 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 <stdio.h>
//
// Struct as return value
//
struct MyStruct
{
int a;
int b;
};
MyStruct __attribute__ ((noinline)) doIt(int a, int b)
{
MyStruct s1;
s1.a = a;
s1.b = b;
return s1;
}
int main()
{
MyStruct s1 = doIt(0x37523482, 0x10458422);
printf("s1a 0x%08x\n", s1.a); // CHECK: s1a 0x37523482
printf("s1b 0x%08x\n", s1.b); // CHECK: s1b 0x10458422
return 0;
}
| 20.914894 | 75 | 0.693795 |
bee3e00eb1fadc197284ad56a53b228d4fe3a61e | 4,061 | cpp | C++ | inetsrv/iis/svcs/cmp/aspcmp/shared/src/instrm.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/iis/svcs/cmp/aspcmp/shared/src/instrm.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/iis/svcs/cmp/aspcmp/shared/src/instrm.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1997 Microsoft Corporation
Module Name :
InStrm.cpp
Abstract:
A lightweight implementation of input streams. This class provides
the interface, as well as a basic skeleton for input streams.
Author:
Neil Allain ( a-neilal ) August-1997
Revision History:
--*/
#include "stdafx.h"
#include "InStrm.h"
static void throwIOException( HRESULT s );
void
throwIOException(
HRESULT s
)
{
if ( s != InStream::EndOfFile )
{
ATLTRACE( _T("InStream error: %d\n"), s );
}
}
bool
IsWhiteSpace::operator()(
_TCHAR c
)
{
bool rc = false;
switch ( c )
{
case _T('\r'):
case _T(' '):
case _T('\t'):
case _T('\n'):
{
rc = true;
} break;
}
return rc;
}
bool
IsNewLine::operator()(
_TCHAR c
)
{
bool rc = false;
if ( ( c != _T('\n') ) && ( c != _T('\r') ) )
{
}
else
{
rc = true;
}
return rc;
}
InStream::InStream()
: m_bEof(false),
m_lastError( S_OK )
{
}
HRESULT
InStream::readInt16(
SHORT& i
)
{
String str;
HRESULT rc = readString( str );
if ( ( rc == S_OK ) || rc == EndOfFile )
{
i = str.toInt16();
}
setLastError( rc );
return rc;
}
HRESULT
InStream::readInt(
int& i
)
{
String str;
HRESULT rc = readString( str );
if ( ( rc == S_OK ) || rc == EndOfFile )
{
i = str.toInt32();
}
setLastError( rc );
return rc;
}
HRESULT
InStream::readInt32(
LONG& i
)
{
String str;
HRESULT rc = readString( str );
if ( ( rc == S_OK ) || rc == EndOfFile )
{
i = str.toInt32();
}
setLastError( rc );
return rc;
}
HRESULT
InStream::readUInt32(
ULONG& i
)
{
String str;
HRESULT rc = readString( str );
if ( ( rc == S_OK ) || rc == EndOfFile )
{
i = str.toUInt32();
}
setLastError( rc );
return rc;
}
HRESULT
InStream::readFloat(
float& f
)
{
String str;
HRESULT rc = readString( str );
if ( ( rc == S_OK ) || rc == EndOfFile )
{
f = str.toFloat();
}
setLastError( rc );
return rc;
}
HRESULT
InStream::readDouble(
double& f
)
{
String str;
HRESULT rc = readString( str );
if ( ( rc == S_OK ) || rc == EndOfFile )
{
f = str.toDouble();
}
setLastError( rc );
return rc;
}
HRESULT
InStream::readString(
String& str
)
{
return read( IsWhiteSpace(), str );
}
HRESULT
InStream::readLine(
String& str
)
{
return read( IsNewLine(), str );
}
HRESULT
InStream::skipWhiteSpace()
{
return skip( IsWhiteSpace() );
}
InStream&
InStream::operator>>(
_TCHAR& c
)
{
HRESULT s = readChar(c);
if ( s == S_OK )
{
}
else
{
throwIOException(s);
}
return *this;
}
InStream&
InStream::operator>>(
SHORT& i
)
{
HRESULT s = readInt16(i);
if ( s == S_OK )
{
}
else
{
throwIOException(s);
}
return *this;
}
InStream&
InStream::operator>>(
int& i
)
{
HRESULT s = readInt(i);
if ( s == S_OK )
{
}
else
{
throwIOException(s);
}
return *this;
}
InStream&
InStream::operator>>(
LONG& i
)
{
HRESULT s = readInt32(i);
if ( s == S_OK )
{
}
else
{
throwIOException(s);
}
return *this;
}
InStream&
InStream::operator>>(
ULONG& i
)
{
HRESULT s = readUInt32(i);
if ( s == S_OK )
{
}
else
{
throwIOException(s);
}
return *this;
}
InStream&
InStream::operator>>(
float& f
)
{
HRESULT s = readFloat(f);
if ( s == S_OK )
{
}
else
{
throwIOException(s);
}
return *this;
}
InStream&
InStream::operator>>(
double& f
)
{
HRESULT s = readDouble(f);
if ( s == S_OK )
{
}
else
{
throwIOException(s);
}
return *this;
}
InStream&
InStream::operator>>(
String& str
)
{
HRESULT s = readString(str);
if ( s == S_OK )
{
}
else
{
throwIOException(s);
}
return *this;
}
void
InStream::setLastError(
HRESULT hr )
{
if ( hr == S_OK )
{
}
else
{
if ( hr == EndOfFile )
{
m_bEof = true;
}
m_lastError = hr;
}
}
| 12.122388 | 70 | 0.534351 |
bee879658e13c9e5d37bbf59ce9afb46702e32d4 | 1,406 | cpp | C++ | src/cube/src/syntax/cubepl/evaluators/nullary/CubeNullaryEvaluation.cpp | OpenCMISS-Dependencies/cube | bb425e6f75ee5dbdf665fa94b241b48deee11505 | [
"Cube"
] | null | null | null | src/cube/src/syntax/cubepl/evaluators/nullary/CubeNullaryEvaluation.cpp | OpenCMISS-Dependencies/cube | bb425e6f75ee5dbdf665fa94b241b48deee11505 | [
"Cube"
] | null | null | null | src/cube/src/syntax/cubepl/evaluators/nullary/CubeNullaryEvaluation.cpp | OpenCMISS-Dependencies/cube | bb425e6f75ee5dbdf665fa94b241b48deee11505 | [
"Cube"
] | 2 | 2016-09-19T00:16:05.000Z | 2021-03-29T22:06:45.000Z | /****************************************************************************
** CUBE http://www.scalasca.org/ **
*****************************************************************************
** Copyright (c) 1998-2016 **
** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre **
** **
** Copyright (c) 2009-2015 **
** German Research School for Simulation Sciences GmbH, **
** Laboratory for Parallel Programming **
** **
** This software may be modified and distributed under the terms of **
** a BSD-style license. See the COPYING file in the package base **
** directory for details. **
****************************************************************************/
#ifndef __NULLARY_EVALUATION_CPP
#define __NULLARY_EVALUATION_CPP 0
#include "CubeNullaryEvaluation.h"
using namespace cube;
NullaryEvaluation::NullaryEvaluation() : GeneralEvaluation()
{
};
NullaryEvaluation::~NullaryEvaluation()
{
}
size_t
NullaryEvaluation::getNumOfArguments()
{
return 0;
}
#endif
| 36.051282 | 77 | 0.396159 |
bee973e6c2fd0c9807aab42fd68929f55c1ceaf2 | 6,965 | cxx | C++ | src/writeMerge.cxx | fermi-lat/eventFile | 36bae3f7b949c7eaa77725dc6d7ec919f77b14ee | [
"BSD-3-Clause"
] | null | null | null | src/writeMerge.cxx | fermi-lat/eventFile | 36bae3f7b949c7eaa77725dc6d7ec919f77b14ee | [
"BSD-3-Clause"
] | null | null | null | src/writeMerge.cxx | fermi-lat/eventFile | 36bae3f7b949c7eaa77725dc6d7ec919f77b14ee | [
"BSD-3-Clause"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <sstream>
#include <stdexcept>
#include <algorithm>
#include "eventFile/LSEReader.h"
#include "eventFile/LSEWriter.h"
#include "eventFile/LSE_Context.h"
#include "eventFile/LSE_Info.h"
#include "eventFile/LPA_Handler.h"
#include "eventFile/EBF_Data.h"
#include "eventFile/LSE_Keys.h"
struct EvtIdx {
std::string tag;
unsigned startedAt;
unsigned long long sequence;
unsigned long long elapsed;
unsigned long long livetime;
double evtUTC;
unsigned scid;
unsigned apid;
unsigned datagrams;
unsigned dgmevt;
std::string oaction;
std::string caction;
double dgmUTC;
off_t fileofst;
std::string evtfile;
EvtIdx( const std::string& idxline ) {
// make the text line into an input stream
std::istringstream iss( idxline );
// extract the components
iss >> tag;
iss >> startedAt;
iss >> sequence;
// iss >> elapsed;
// iss >> livetime;
// iss >> evtUTC;
// iss >> scid;
iss >> apid;
iss >> datagrams;
// iss >> dgmevt;
iss >> oaction;
iss >> caction;
// iss >> dgmUTC;
iss >> fileofst;
iss >> evtfile;
};
};
typedef std::map< std::string, eventFile::LSEReader* > lser_map;
typedef lser_map::iterator lser_iter;
struct cleanup {
void operator() ( lser_map::value_type x ) { delete x.second; }
};
int main( int argc, char* argv[] )
{
// get the input and output file names
if ( argc < 4 ) {
std::cout << "writeMerge: not enough input arguments" << std::endl;
exit( EXIT_FAILURE );
}
std::string idxfile( argv[1] );
std::string evtfile( argv[2] ); // this contains format specifiers
int downlinkID = atoi( argv[3] );
// add support for configurable output file size
int maxEvents = -1;
if ( argc >= 5 ) {
maxEvents = atoi( argv[4] );
}
int currMax = maxEvents;
// make the output-file-size scaling externally tunable
double WRITEMERGE_CHUNKSCALE = 0.90;
char* envbuf = getenv( "WRITEMERGE_CHUNKSCALE" );
if ( envbuf ) {
WRITEMERGE_CHUNKSCALE = atof( envbuf );
}
double WRITEMERGE_CHUNKFLOOR = 0.50;
envbuf = getenv( "WRITEMERGE_CHUNKFLOOR" );
if ( envbuf ) {
WRITEMERGE_CHUNKFLOOR = atof( envbuf );
}
// add support for overriding translated LATC master key
unsigned long overrideLATC = 0xffffffff;
if ( argc >= 6 ) {
overrideLATC = strtoul( argv[5], NULL, 0 );
std::cout << "writeMerge: overriding LATC key to " << overrideLATC << std::endl;
} else {
std::cout << "writeMerge: no LATC key override" << std::endl;
}
// declare the file-output object pointer
int eventsOut = 0;
eventFile::LSEWriter* pLSEW = NULL;
// create a container for the chunk-evt input files
lser_map mapLSER;
// declare object to receive the event information
eventFile::LSE_Context ctx;
eventFile::EBF_Data ebf;
eventFile::LSE_Info::InfoType infotype;
eventFile::LPA_Info pinfo;
eventFile::LCI_ACD_Info ainfo;
eventFile::LCI_CAL_Info cinfo;
eventFile::LCI_TKR_Info tinfo;
eventFile::LSE_Keys::KeysType ktype;
eventFile::LPA_Keys pakeys;
eventFile::LCI_Keys cikeys;
// read the index file and parse the entries, retrieving the
// requeseted events as we go
std::string idxline;
std::ifstream idx( idxfile.c_str() );
if ( idx.fail() ) {
std::cout << "writeMerge: failed to open " << idxfile;
std::cout << " (" << errno << ":" << strerror(errno) << ")" << std::endl;
exit( EXIT_FAILURE );
}
while ( getline( idx, idxline ) ) {
// skip non-event records
if ( idxline.find( "EVT:" ) != 0 ) continue;
// make an event-index object
EvtIdx edx( idxline );
// get an LSEReader for the file
lser_iter it = mapLSER.find( edx.evtfile );
if ( it == mapLSER.end() ) {
try {
it = mapLSER.insert( std::pair< std::string, eventFile::LSEReader* >( edx.evtfile, new eventFile::LSEReader( edx.evtfile ) ) ).first;
} catch ( std::runtime_error& e ) {
std::cout << e.what() << std::endl;
exit( EXIT_FAILURE );
}
}
// read the event at the specified location
bool bevtread = false;
try {
it->second->seek( edx.fileofst );
bevtread = it->second->read( ctx, ebf, infotype, pinfo, ainfo, cinfo, tinfo, ktype, pakeys, cikeys );
} catch( std::runtime_error e ) {
std::cout << e.what() << std::endl;
exit( EXIT_FAILURE );
}
if ( !bevtread ) {
std::cout << "no event read from " << edx.fileofst << " of " << edx.evtfile << std::endl;
exit( EXIT_FAILURE);
}
// open an output file if necessary
if ( !pLSEW ) {
// create the output filename from the user-supplied template
char ofn[512];
#ifndef _FILE_OFFSET_BITS
_snprintf( ofn, 512, evtfile.c_str(), ctx.run.startedAt, ctx.scalers.sequence );
#else
snprintf( ofn, 512, evtfile.c_str(), ctx.run.startedAt, ctx.scalers.sequence );
#endif
// open the output file
try {
pLSEW = new eventFile::LSEWriter( std::string( ofn ), downlinkID );
} catch ( std::runtime_error& e ) {
std::cout << e.what() << std::endl;
exit( EXIT_FAILURE );
}
std::cout << "writeMerge: created output file " << pLSEW->name() << std::endl;
}
// write the event to the merged file
try {
switch( infotype ) {
case eventFile::LSE_Info::LPA:
if ( overrideLATC != 0xffffffff ) {
pakeys.LATC_master = overrideLATC;
}
pLSEW->write( ctx, ebf, pinfo, pakeys );
break;
case eventFile::LSE_Info::LCI_ACD:
pLSEW->write( ctx, ebf, ainfo, cikeys );
break;
case eventFile::LSE_Info::LCI_CAL:
pLSEW->write( ctx, ebf, cinfo, cikeys );
break;
case eventFile::LSE_Info::LCI_TKR:
pLSEW->write( ctx, ebf, tinfo, cikeys );
break;
default:
std::ostringstream ess;
ess << "writeMerge: unknown LSE_Info type " << infotype;
ess << " at offset " << edx.fileofst;
ess << " in " << edx.evtfile;
throw std::runtime_error( ess.str() );
break;
}
} catch ( std::runtime_error& e ) {
std::cout << e.what() << std::endl;
exit( EXIT_FAILURE );
}
// check to see if the output file is full
if ( currMax > 0 && ++eventsOut >= currMax ) {
// close the current file and reset the event counter
std::cout << "writeMerge: wrote " << pLSEW->evtcnt() << " events to " << pLSEW->name() << std::endl;
delete pLSEW; pLSEW = NULL;
eventsOut = 0;
// rescale the max-event count for the next file
currMax = ( currMax <= WRITEMERGE_CHUNKFLOOR * maxEvents ) ? maxEvents : WRITEMERGE_CHUNKSCALE * currMax;
}
}
std::for_each( mapLSER.begin(), mapLSER.end(), cleanup() );
idx.close();
if ( pLSEW ) {
std::cout << "writeMerge: wrote " << pLSEW->evtcnt() << " events to " << pLSEW->name() << std::endl;
delete pLSEW;
}
// all done
return 0;
}
| 28.900415 | 134 | 0.628141 |
beec1efd6d8fb105a62da73812293c5bd8c6c137 | 778 | cpp | C++ | Solutions/7-ReverseInteger.cpp | zcmcxm/LeetCode-practice | 5e3a25a66221c9b7d37d2a826133783906d8ac70 | [
"MIT"
] | null | null | null | Solutions/7-ReverseInteger.cpp | zcmcxm/LeetCode-practice | 5e3a25a66221c9b7d37d2a826133783906d8ac70 | [
"MIT"
] | null | null | null | Solutions/7-ReverseInteger.cpp | zcmcxm/LeetCode-practice | 5e3a25a66221c9b7d37d2a826133783906d8ac70 | [
"MIT"
] | null | null | null | class Solution {
public:
//Intuitive method
//Check before overflow
//INT_MAX = 2147483647
//INT_MIN = -2147483648
//if current result == INT_MAX/10 and reminder > 7, overflow will happen
//if current result == INT_MIN/10 and reminder < -8, overflow will happen
//Runtime faster than 100.00%
//MU less than 76.31%
int reverse(int x) {
int result = 0;
int count = 0;
while(x!=0){
int reminder = x%10;
if (result > INT_MAX/10 || (result == INT_MAX / 10 && reminder > 7)) return 0;
if (result < INT_MIN/10 || (result == INT_MIN / 10 && reminder < -8)) return 0;
result = (reminder + result*10);
count++;
x -= reminder;
x /= 10;
}
return result;
}
}; | 31.12 | 91 | 0.55527 |
bef417c20988375bffb50833d1b329e3772f95dd | 26,949 | cpp | C++ | orca/gporca/server/src/unittest/gpopt/base/CStatsEquivClassTest.cpp | vitessedata/gpdb.4.3.99.x | 9462aad5df1bf120a2a87456b1f9574712227da4 | [
"PostgreSQL",
"Apache-2.0"
] | 3 | 2017-12-10T16:41:21.000Z | 2020-07-08T12:59:12.000Z | orca/gporca/server/src/unittest/gpopt/base/CStatsEquivClassTest.cpp | vitessedata/gpdb.4.3.99.x | 9462aad5df1bf120a2a87456b1f9574712227da4 | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | orca/gporca/server/src/unittest/gpopt/base/CStatsEquivClassTest.cpp | vitessedata/gpdb.4.3.99.x | 9462aad5df1bf120a2a87456b1f9574712227da4 | [
"PostgreSQL",
"Apache-2.0"
] | 4 | 2017-12-10T16:41:35.000Z | 2020-11-28T12:20:30.000Z | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// CStatsEquivClassTest.cpp
//
// @doc:
// Test for constraint
//
// @owner:
//
//
// @test:
//
//
//---------------------------------------------------------------------------
#include "unittest/base.h"
#include "unittest/gpopt/base/CStatsEquivClassTest.h"
#include "unittest/gpopt/base/CConstraintTest.h"
#include "gpopt/operators/CPredicateUtils.h"
#include "gpopt/base/CStatsEquivClass.h"
#include "gpopt/eval/CConstExprEvaluatorDefault.h"
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::EresUnittest
//
// @doc:
// Unittest for ranges
//
//---------------------------------------------------------------------------
GPOS_RESULT
CStatsEquivClassTest::EresUnittest()
{
CUnittest rgut[] =
{
GPOS_UNITTEST_FUNC(CStatsEquivClassTest::EresUnittest_EquivClassFromScalarExpr),
};
CAutoMemoryPool amp;
IMemoryPool *pmp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(pmp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
// install opt context in TLS
CAutoOptCtxt aoc
(
pmp,
&mda,
NULL, /* pceeval */
CTestUtils::Pcm(pmp)
);
return CUnittest::EresExecute(rgut, GPOS_ARRAY_SIZE(rgut));
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::EresUnittest_EquivClassFromScalarExpr
//
// @doc:
// Equivalence class from scalar expressions tests
//
//---------------------------------------------------------------------------
GPOS_RESULT
CStatsEquivClassTest::EresUnittest_EquivClassFromScalarExpr()
{
// create memory pool
CAutoMemoryPool amp;
IMemoryPool *pmp = amp.Pmp();
// setup a file-based provider
CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
pmdp->AddRef();
CMDAccessor mda(pmp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
CColumnFactory *pcf = COptCtxt::PoctxtFromTLS()->Pcf();
SEquivClassSTestCase rgequivclasstc[] =
{
{PequivclasstcScIdCmpConst},
{PequivclasstcScIdCmpScId},
{PequivclasstcSameCol},
{PequivclasstcConj1},
{PequivclasstcConj2},
{PequivclasstcConj3},
{PequivclasstcConj4},
{PequivclasstcConj5},
{PequivclasstcDisj1},
{PequivclasstcDisj2},
{PequivclasstcDisjConj1},
{PequivclasstcDisjConj2},
{PequivclasstcDisjConj3},
{PequivclasstcCast}
};
const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgequivclasstc);
for (ULONG ul = 0; ul < ulTestCases; ul++)
{
SEquivClassSTestCase elem = rgequivclasstc[ul];
GPOS_CHECK_ABORT;
// generate the test case
FnPequivclass *pf = elem.m_pf;
GPOS_ASSERT(NULL != pf);
SEquivClass *pequivclass = pf(pmp, pcf, &mda);
CExpression *pexpr = pequivclass->Pexpr();
DrgPcrs *pdrgpcrsExpected = pequivclass->PdrgpcrsEquivClass();
DrgPcrs *pdrgpcrsActual = CStatsEquivClass::PdrgpcrsEquivClassFromScalarExpr(pmp, pexpr);
{
// debug print
CAutoTrace at(pmp);
at.Os() << std::endl;
at.Os() << "EXPR:" << std::endl << *pexpr << std::endl;
}
CConstraintTest::PrintEquivClasses(pmp, pdrgpcrsActual, false /* fExpected */);
CConstraintTest::PrintEquivClasses(pmp, pdrgpcrsExpected, true /* fExpected */);
if (!FMatchingEquivClasses(pdrgpcrsActual, pdrgpcrsExpected))
{
return GPOS_FAILED;
}
// clean up
CRefCount::SafeRelease(pdrgpcrsActual);
GPOS_DELETE(pequivclass);
}
return GPOS_OK;
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcScIdCmpConst
//
// @doc:
// Expression and equivalence classes of a scalar comparison between
// column reference and a constant
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcScIdCmpConst
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr = pcf->PcrCreate(pmdtypeint4);
IDatum *pdatum = (IDatum *) pmda->PtMDType<IMDTypeInt4>(CTestUtils::m_sysidDefault)->PdatumInt4(pmp, 1, false /* fNull */);
CExpression *pexprConst = GPOS_NEW(pmp) CExpression(pmp, GPOS_NEW(pmp) CScalarConst(pmp, pdatum));
// col1 == const
CExpression *pexpr = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr), pexprConst);
// Equivalence class {}
DrgPcrs *pdrpcrs = NULL;
SEquivClass *pequivclass = GPOS_NEW(pmp) SEquivClass(pexpr, pdrpcrs);
return pequivclass;
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcScIdCmpScId
//
// @doc:
// Expression and equivalence classes of a scalar comparison between
// column references
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcScIdCmpScId
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4);
// col1 == col2
CExpression *pexpr = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
// Equivalence class {1,2}
DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp);
pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2));
SEquivClass *pequivclass = GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
return pequivclass;
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcSameCol
//
// @doc:
// Expression and equivalence classes of a predicate on same column
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcSameCol
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
// col1 == col1
CExpression *pexpr = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr1));
// Equivalence class {}
DrgPcrs *pdrgpcrs = NULL;
SEquivClass *pequivclass = GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
return pequivclass;
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcConj1
//
// @doc:
// Expression and its equivalence class for a conjunctive predicate
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcConj1
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
DrgPexpr *pdrgpexpr = GPOS_NEW(pmp) DrgPexpr(pmp);
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4);
// (col1 == col2) AND (col1 == const) AND (col1 == col1)
// (col1 == col2)
CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexpr->Append(pexpr1);
// (col1 == const)
IDatum *pdatum = (IDatum *) pmda->PtMDType<IMDTypeInt4>(CTestUtils::m_sysidDefault)->PdatumInt4(pmp, 1, false /* fNull */);
CExpression *pexprConst = GPOS_NEW(pmp) CExpression(pmp, GPOS_NEW(pmp) CScalarConst(pmp, pdatum));
CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), pexprConst);
pdrgpexpr->Append(pexpr2);
// (col1 == col1)
CExpression *pexpr3 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr1));
pdrgpexpr->Append(pexpr3);
CExpression *pexpr = CPredicateUtils::PexprConjunction(pmp, pdrgpexpr);
// Equivalence class {1,2}
DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp);
pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2));
SEquivClass *pequivclass = GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
return pequivclass;
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcConj2
//
// @doc:
// Expression and equivalence classes for a conjunctive predicate
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcConj2
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4);
// (col1 = col2) AND (col1 = col3)
DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp);
// (col1 = col2)
CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexprA->Append(pexpr1);
// (col1 = col3)
CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr3));
pdrgpexprA->Append(pexpr2);
CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA);
// Equivalence class {1,2,3}
DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp);
CColRefSet *pcrs = CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2);
pcrs->Include(pcr3);
pdrgpcrs->Append(pcrs);
return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcConj3
//
// @doc:
// Expression and equivalence classes for a conjunctive predicate
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcConj3
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4);
// (col1 = col2) AND (col2 = col3)
DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp);
// (col1 = col2)
CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexprA->Append(pexpr1);
// (col2 = col3)
CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr2), CUtils::PexprScalarIdent(pmp, pcr3));
pdrgpexprA->Append(pexpr2);
CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA);
// Equivalence class {1,2,3}
DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp);
CColRefSet *pcrs = CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2);
pcrs->Include(pcr3);
pdrgpcrs->Append(pcrs);
return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcConj4
//
// @doc:
// Expression and equivalence classes for a conjunctive predicate
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcConj4
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr4 = pcf->PcrCreate(pmdtypeint4);
// (col1 = col2) AND (col3 = col4)
DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp);
// (col1 = col2)
CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexprA->Append(pexpr1);
// (col3 = col4)
CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr3), CUtils::PexprScalarIdent(pmp, pcr4));
pdrgpexprA->Append(pexpr2);
CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA);
// Equivalence class {1,2} {3,4}
DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp);
pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2));
pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr3, pcr4));
return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcConj5
//
// @doc:
// Expression and equivalence classes for a conjunctive predicate
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcConj5
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4);
// (col1 = col2) AND (col3 = col3)
DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp);
// (col1 = col2)
CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexprA->Append(pexpr1);
// (col3 = col3)
CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr3), CUtils::PexprScalarIdent(pmp, pcr3));
pdrgpexprA->Append(pexpr2);
CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA);
// Equivalence class {1,2}
DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp);
pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2));
return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcDisj1
//
// @doc:
// Expression and its equivalence class for a disjunctive predicate
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcDisj1
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
DrgPexpr *pdrgpexpr = GPOS_NEW(pmp) DrgPexpr(pmp);
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4);
// (col1 = col2)
CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexpr->Append(pexpr1);
// (col1 = const)
IDatum *pdatum = (IDatum *) pmda->PtMDType<IMDTypeInt4>(CTestUtils::m_sysidDefault)->PdatumInt4(pmp, 1, false /* fNull */);
CExpression *pexprConst = GPOS_NEW(pmp) CExpression(pmp, GPOS_NEW(pmp) CScalarConst(pmp, pdatum));
CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), pexprConst);
pdrgpexpr->Append(pexpr2);
// (col1 = col1)
CExpression *pexpr3 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr1));
pdrgpexpr->Append(pexpr3);
// (col1 = col3)
CExpression *pexpr4 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr3));
pdrgpexpr->Append(pexpr4);
CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopOr, pdrgpexpr);
// Equivalence class {}
DrgPcrs *pdrgpcrs = NULL;
SEquivClass *pequivclass = GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
return pequivclass;
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcDisj2
//
// @doc:
// Expression and its equivalence class for a disjunctive predicate
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcDisj2
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
DrgPexpr *pdrgpexpr = GPOS_NEW(pmp) DrgPexpr(pmp);
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4);
// (col1 = col2)
CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexpr->Append(pexpr1);
// (col1 = col2)
CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexpr->Append(pexpr2);
CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopOr, pdrgpexpr);
// Equivalence class {1,2}
DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp);
pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2));
return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcDisjConj1
//
// @doc:
// Expression and equivalence classes of a predicate with disjunction and conjunction
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcDisjConj1
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4);
// (col1 = col2) AND (col1 = col3)
DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp);
// (col1 = col2)
CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexprA->Append(pexpr1);
// (col1 = col3)
CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr3));
pdrgpexprA->Append(pexpr2);
CExpression *pexprA = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA);
// (col3 = col2) AND (col1 = col2)
DrgPexpr *pdrgpexprB = GPOS_NEW(pmp) DrgPexpr(pmp);
// (col3 = col2)
CExpression *pexpr3 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr3), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexprB->Append(pexpr3);
// (col1 = col2)
CExpression *pexpr4 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexprB->Append(pexpr4);
CExpression *pexprB = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprB);
// exprA OR exprB
DrgPexpr *pdrgpexpr = GPOS_NEW(pmp) DrgPexpr(pmp);
pdrgpexpr->Append(pexprA);
pdrgpexpr->Append(pexprB);
CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopOr, pdrgpexpr);
// Equivalence class {1,2,3}
DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp);
CColRefSet *pcrs = CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2);
pcrs->Include(pcr3);
pdrgpcrs->Append(pcrs);
return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcDisjConj2
//
// @doc:
// Expression and equivalence classes of a predicate with disjunction and conjunction
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcDisjConj2
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr4 = pcf->PcrCreate(pmdtypeint4);
// (col1 = col2) AND (col1 = col3)
DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp);
// (col1 = col2)
CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexprA->Append(pexpr1);
// (col3 = col4)
CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr3), CUtils::PexprScalarIdent(pmp, pcr4));
pdrgpexprA->Append(pexpr2);
CExpression *pexprA = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA);
// (col1 = col2) AND (col2 = col4)
DrgPexpr *pdrgpexprB = GPOS_NEW(pmp) DrgPexpr(pmp);
// (col1 = col2)
CExpression *pexpr3 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexprB->Append(pexpr3);
// (col2 = col4)
CExpression *pexpr4 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr2), CUtils::PexprScalarIdent(pmp, pcr4));
pdrgpexprB->Append(pexpr4);
CExpression *pexprB = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprB);
// exprA OR exprB
DrgPexpr *pdrgpexpr = GPOS_NEW(pmp) DrgPexpr(pmp);
pdrgpexpr->Append(pexprA);
pdrgpexpr->Append(pexprB);
CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopOr, pdrgpexpr);
// Equivalence class {1,2}
DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp);
CColRefSet *pcrs = CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2);
pdrgpcrs->Append(pcrs);
return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcDisjConj3
//
// @doc:
// Expression and equivalence classes of a predicate with disjunction and conjunction
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcDisjConj3
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr3 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr4 = pcf->PcrCreate(pmdtypeint4);
// exprA: (col1 = col2) AND (col3 = col4)
DrgPexpr *pdrgpexprA = GPOS_NEW(pmp) DrgPexpr(pmp);
// (col1 = col2)
CExpression *pexpr1 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr2));
pdrgpexprA->Append(pexpr1);
// (col3 = col4)
CExpression *pexpr2 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr3), CUtils::PexprScalarIdent(pmp, pcr4));
pdrgpexprA->Append(pexpr2);
CExpression *pexprA = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprA);
// exprB: (col1 = col3) AND (col2 = col4)
DrgPexpr *pdrgpexprB = GPOS_NEW(pmp) DrgPexpr(pmp);
// (col1 = col3)
CExpression *pexpr3 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr1), CUtils::PexprScalarIdent(pmp, pcr3));
pdrgpexprB->Append(pexpr3);
// (col2 = col4)
CExpression *pexpr4 = CUtils::PexprScalarEqCmp(pmp, CUtils::PexprScalarIdent(pmp, pcr2), CUtils::PexprScalarIdent(pmp, pcr4));
pdrgpexprB->Append(pexpr4);
CExpression *pexprB = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopAnd, pdrgpexprB);
// exprA OR exprB
DrgPexpr *pdrgpexpr = GPOS_NEW(pmp) DrgPexpr(pmp);
pdrgpexpr->Append(pexprA);
pdrgpexpr->Append(pexprB);
CExpression *pexpr = CUtils::PexprScalarBoolOp(pmp, CScalarBoolOp::EboolopOr, pdrgpexpr);
// Equivalence class {}
DrgPcrs *pdrgpcrs = NULL;
return GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::PequivclasstcCast
//
// @doc:
// Expression and equivalence classes of a scalar comparison between
// column references
//
//---------------------------------------------------------------------------
CStatsEquivClassTest::SEquivClass *
CStatsEquivClassTest::PequivclasstcCast
(
IMemoryPool *pmp,
CColumnFactory *pcf,
CMDAccessor *pmda
)
{
const IMDTypeInt4 *pmdtypeint4 = pmda->PtMDType<IMDTypeInt4>();
const IMDTypeInt4 *pmdtypeint8 = pmda->PtMDType<IMDTypeInt4>();
// col1::int8 = col2
CColRef *pcr1 = pcf->PcrCreate(pmdtypeint4);
CColRef *pcr2 = pcf->PcrCreate(pmdtypeint4);
CExpression *pexprScId1 = CUtils::PexprScalarIdent(pmp, pcr1);
CExpression *pexprCast = CPredicateUtils::PexprCast(pmp, pmda, pexprScId1, pmdtypeint8->Pmdid());
CExpression *pexpr = CUtils::PexprScalarEqCmp(pmp, pexprCast, CUtils::PexprScalarIdent(pmp, pcr2));
DrgPcrs *pdrgpcrs = GPOS_NEW(pmp) DrgPcrs(pmp);
pdrgpcrs->Append(CStatsEquivClass::PcrsEquivClass(pmp, pcr1, pcr2));
// Equivalence class {}
SEquivClass *pequivclass = GPOS_NEW(pmp) SEquivClass(pexpr, pdrgpcrs);
return pequivclass;
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::FMatchingEquivClasses
//
// @doc:
// Check if the two equivalence classes match
//
//---------------------------------------------------------------------------
BOOL
CStatsEquivClassTest::FMatchingEquivClasses
(
const DrgPcrs *pdrgpcrsActual,
const DrgPcrs *pdrgpcrsExpected
)
{
if (NULL != pdrgpcrsExpected && NULL != pdrgpcrsActual)
{
const ULONG ulActual = pdrgpcrsActual->UlLength();
const ULONG ulExpected = pdrgpcrsExpected->UlLength();
if (ulActual < ulExpected)
{
// there can be equivalence classes that can be singleton in pdrgpcrsActual
return false;
}
for (ULONG ulA = 0; ulA < ulActual; ulA++)
{
CColRefSet *pcrsActual = (*pdrgpcrsActual)[ulA];
BOOL fMatch = (1 == pcrsActual->CElements());
for (ULONG ulE = 0; ulE < ulExpected && !fMatch; ulE++)
{
CColRefSet *pcrsExpected = (*pdrgpcrsExpected)[ulE];
if (pcrsActual->FEqual(pcrsExpected))
{
fMatch = true;
}
}
if (!fMatch)
{
return false;
}
}
return true;
}
return (UlEquivClasses(pdrgpcrsExpected) == UlEquivClasses(pdrgpcrsActual));
}
//---------------------------------------------------------------------------
// @function:
// CStatsEquivClassTest::UlEquivClasses
//
// @doc:
// Return the number of non-singleton equivalence classes
//
//---------------------------------------------------------------------------
ULONG
CStatsEquivClassTest::UlEquivClasses
(
const DrgPcrs *pdrgpcrs
)
{
ULONG ulSize = 0;
if (NULL == pdrgpcrs)
{
return ulSize;
}
const ULONG ulActual = pdrgpcrs->UlLength();
for (ULONG ul = 0; ul < ulActual; ul++)
{
CColRefSet *pcrs = (*pdrgpcrs)[ul];
if (1 != pcrs->CElements())
{
ulSize++;
}
}
return ulSize;
}
// EOF
| 30.279775 | 127 | 0.653605 |
befaaa250ca59ec25b0ef40e6f1523895ff98a9f | 2,625 | cpp | C++ | Client/Client.cpp | Vasar007/HW | e441f87dfeb58ab3c7b3120c9972cae5fd8d869d | [
"Apache-2.0"
] | null | null | null | Client/Client.cpp | Vasar007/HW | e441f87dfeb58ab3c7b3120c9972cae5fd8d869d | [
"Apache-2.0"
] | null | null | null | Client/Client.cpp | Vasar007/HW | e441f87dfeb58ab3c7b3120c9972cae5fd8d869d | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <thread>
#include "Client.h"
namespace vasily
{
Client::Client(const quint16 serverPort, const std::string& serverIP, QObject* parent)
: QObject(parent),
_serverPort(serverPort),
_socket(std::make_unique<QTcpSocket>(this)),
_serverIP(serverIP)
{
qDebug() << "Server Port:" << serverPort << "\nLayer IP:" << serverIP.c_str() << '\n';
connect(_socket.get(), &QTcpSocket::readyRead, this, &Client::slotReadFromServer);
connect(_socket.get(), &QTcpSocket::disconnected, this, &Client::slotServerDisconnected,
Qt::QueuedConnection);
connect(this, &Client::signalToSend, this, &Client::slotSendDataToServer);
}
void Client::slotReadFromServer() const
{
if (_socket->bytesAvailable() > 0)
{
const QByteArray array = _socket->readAll();
const std::string receivedData = array.toStdString();
qDebug() << _socket->localPort() << '-' << array << '\n';
}
}
void Client::slotServerDisconnected() const
{
qDebug() << "\nServer disconnected!\n";
tryReconnect();
}
void Client::slotSendDataToServer(const QByteArray& data) const
{
_socket->write(data);
qDebug() << "Sent data:" << data << "successfully.\n";
}
void Client::run()
{
std::thread workThread(&Client::waitLoop, this);
workThread.detach();
}
void Client::waitLoop() const
{
qDebug() << "\nWaiting for reply...\n\n";
while (true)
{
std::string input;
qDebug() << "Enter command: ";
std::getline(std::cin, input);
if (!input.empty())
{
sendData(input);
}
}
}
bool Client::tryConnect(const quint16 port, const std::string& ip, QTcpSocket* socketToConnect,
const int msecs) const
{
if (socketToConnect->isOpen())
{
socketToConnect->close();
}
socketToConnect->connectToHost(ip.c_str(), port);
if (socketToConnect->waitForConnected(msecs))
{
qDebug() << "Connected to Server!\n";
return true;
}
qDebug() << "Not connected to Server!\n";
return false;
}
void Client::tryReconnect() const
{
launch();
}
void Client::launch() const
{
bool isConnected = tryConnect(_serverPort, _serverIP, _socket.get(), true);
while (!isConnected)
{
isConnected = tryConnect(_serverPort, _serverIP, _socket.get(), true);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
qDebug() << "\nClient launched...\n";
}
void Client::sendData(const std::string& data) const
{
emit signalToSend(data.c_str());
}
} // namespace vasily
| 22.435897 | 95 | 0.620952 |
befdb4dc51f299c04b6b126655aa1748ff502e0f | 629 | cpp | C++ | comsci-110/Chapter 5/consoleInput.cpp | colmentse/Cplusplus-class | 0c7eff6b3fa6f2a2c42571889453d1bf5c0a5050 | [
"MIT"
] | null | null | null | comsci-110/Chapter 5/consoleInput.cpp | colmentse/Cplusplus-class | 0c7eff6b3fa6f2a2c42571889453d1bf5c0a5050 | [
"MIT"
] | null | null | null | comsci-110/Chapter 5/consoleInput.cpp | colmentse/Cplusplus-class | 0c7eff6b3fa6f2a2c42571889453d1bf5c0a5050 | [
"MIT"
] | null | null | null | /*
Author : Colmen Tse
Compsci : 120
5.6 consoleinput.cpp
*/
#include <string>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int age;
cout << "Enter your age: ";
cin >> age;
cin.ignore(1000, 10);
string name;
cout << "Enter your name: ";
getline(cin, name);
double temp;
cout << "Enter the temperature outside right now (degrees F): ";
cin >> temp;
cin.ignore(1000, 10);
string location;
cout << "What city are you in right now? ";
getline(cin, location);
cout << name << " is " << age << " years old." << endl;
cout << "It's " << temp << " degrees F in " << location << endl;
} | 17.971429 | 65 | 0.613672 |
befefa3a238c5a224d33a3c2e82fabedb5ecc0ad | 67 | cc | C++ | fluid/src/framework/op_desc.cc | ImageMetrics/paddle-mobile | 8edfa0ddfc542962ba4530410bd2d2c9b8d77cc4 | [
"MIT"
] | 2 | 2018-07-17T10:55:48.000Z | 2018-08-03T01:35:20.000Z | fluid/src/framework/op_desc.cc | ImageMetrics/paddle-mobile | 8edfa0ddfc542962ba4530410bd2d2c9b8d77cc4 | [
"MIT"
] | null | null | null | fluid/src/framework/op_desc.cc | ImageMetrics/paddle-mobile | 8edfa0ddfc542962ba4530410bd2d2c9b8d77cc4 | [
"MIT"
] | null | null | null | //
// Created by liuRuiLong on 2018/4/23.
//
#include "op_desc.h"
| 11.166667 | 38 | 0.641791 |
8300c0f55d032bf6a2e2de1405cc34f743d7696e | 236 | cpp | C++ | Job.cpp | suyunu/Discrete-Event-Simulation | be2da51697e546827890f502366025959975d473 | [
"MIT"
] | 5 | 2016-09-25T19:45:34.000Z | 2021-01-02T10:25:29.000Z | Job.cpp | suyunu/Discrete-Event-Simulation | be2da51697e546827890f502366025959975d473 | [
"MIT"
] | null | null | null | Job.cpp | suyunu/Discrete-Event-Simulation | be2da51697e546827890f502366025959975d473 | [
"MIT"
] | null | null | null | #include "Job.h"
using namespace std;
Job::Job(){
no = enterTime = timeToGo = 0;
cond = -1;
}
Job::~Job(){}
void Job::initialize(int No, double enter_time){
no = No;
enterTime = enter_time;
timeToGo = enter_time;
cond = -1;
}
| 13.111111 | 48 | 0.631356 |
8305a43c0016eb26e8d544d2c621426147818ff0 | 5,383 | cpp | C++ | tests/collection.cpp | dead1ock/algorithms-cpp | 35b79b4cfe5db24e83ce157765fbcb221bc2ed38 | [
"MIT"
] | null | null | null | tests/collection.cpp | dead1ock/algorithms-cpp | 35b79b4cfe5db24e83ce157765fbcb221bc2ed38 | [
"MIT"
] | null | null | null | tests/collection.cpp | dead1ock/algorithms-cpp | 35b79b4cfe5db24e83ce157765fbcb221bc2ed38 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <collection/FixedArrayStack.h>
#include <collection/FixedQueue.h>
#include <collection/LinkedListStack.h>
#include <collection/LinkedQueue.h>
#include <collection/ResizableStack.h>
#include <collection/ResizableQueue.h>
TEST(LINKEDLISTSTACK, PushPopCount)
{
LinkedListStack<int> stack;
stack.Push(100);
stack.Push(200);
stack.Push(300);
EXPECT_EQ(3, stack.Count());
EXPECT_EQ(300, stack.Pop());
EXPECT_EQ(200, stack.Pop());
EXPECT_EQ(100, stack.Pop());
}
TEST(LINKEDLISTSTACK, Push1000)
{
LinkedListStack<int> stack;
for (int x = 1; x <= 1000; x++)
stack.Push(x);
EXPECT_EQ(1000, stack.Count());
}
TEST(LINKEDLISTSTACK, Push100000)
{
LinkedListStack<int> stack;
for (int x = 1; x <= 100000; x++)
stack.Push(x);
EXPECT_EQ(100000, stack.Count());
}
TEST(LINKEDLISTSTACK, Push1000000)
{
LinkedListStack<int> stack;
for (int x = 1; x <= 1000000; x++)
stack.Push(x);
EXPECT_EQ(1000000, stack.Count());
}
// =====================================================
//
// =====================================================
TEST(FixedArrayStack, PushPopCount)
{
FixedArrayStack<int> stack(3);
stack.Push(100);
stack.Push(200);
stack.Push(300);
EXPECT_EQ(3, stack.Count());
EXPECT_EQ(300, stack.Pop());
EXPECT_EQ(200, stack.Pop());
EXPECT_EQ(100, stack.Pop());
}
TEST(FixedArrayStack, Push1000)
{
FixedArrayStack<int> stack(1000);
for (int x = 1; x <= 1000; x++)
stack.Push(x);
EXPECT_EQ(1000, stack.Count());
}
TEST(FixedArrayStack, Push100000)
{
FixedArrayStack<int> stack(100000);
for (int x = 1; x <= 1000; x++)
stack.Push(x);
EXPECT_EQ(1000, stack.Count());
}
TEST(FixedArrayStack, Push1000000)
{
FixedArrayStack<int> stack(1000000);
for (int x = 1; x <= 1000; x++)
stack.Push(x);
EXPECT_EQ(1000, stack.Count());
}
// =====================================================
//
// =====================================================
TEST(ResizableStack, PushPopCount)
{
ResizableStack<int> stack;
stack.Push(100);
stack.Push(200);
stack.Push(300);
EXPECT_EQ(3, stack.Count());
EXPECT_EQ(300, stack.Pop());
EXPECT_EQ(200, stack.Pop());
EXPECT_EQ(100, stack.Pop());
}
TEST(ResizableStack, Push1000)
{
ResizableStack<int> stack;
for (int x = 1; x <= 1000; x++)
stack.Push(x);
EXPECT_EQ(1000, stack.Count());
}
TEST(ResizableStack, Push100000)
{
ResizableStack<int> stack;
for (int x = 1; x <= 1000; x++)
stack.Push(x);
EXPECT_EQ(1000, stack.Count());
}
TEST(ResizableStack, Push1000000)
{
ResizableStack<int> stack;
for (int x = 1; x <= 1000; x++)
stack.Push(x);
EXPECT_EQ(1000, stack.Count());
}
// =====================================================
//
// =====================================================
TEST(FixedQueue, EnqueueDequeueCount)
{
FixedQueue<int> queue(3);
queue.Enqueue(100);
queue.Enqueue(200);
queue.Enqueue(300);
EXPECT_EQ(3, queue.Count());
EXPECT_EQ(100, queue.Dequeue());
EXPECT_EQ(200, queue.Dequeue());
EXPECT_EQ(300, queue.Dequeue());
}
TEST(FixedQueue, Enqueue1000)
{
FixedQueue<int> queue(1000);
for (int x = 1; x <= 1000; x++)
queue.Enqueue(x);
EXPECT_EQ(1000, queue.Count());
}
TEST(FixedQueue, Enqueue100000)
{
FixedQueue<int> queue(100000);
for (int x = 1; x <= 100000; x++)
queue.Enqueue(x);
EXPECT_EQ(100000, queue.Count());
}
TEST(FixedQueue, Enqueue1000000)
{
FixedQueue<int> queue(1000000);
for (int x = 1; x <= 1000000; x++)
queue.Enqueue(x);
EXPECT_EQ(1000000, queue.Count());
}
TEST(FixedQueue, ProduceEnqueueOverflow)
{
FixedQueue<int> queue(1000000);
for (int x = 1; x <= 1000001; x++)
queue.Enqueue(x);
EXPECT_EQ(1000000, queue.Count());
}
// =====================================================
//
// =====================================================
TEST(LinkedQueue, EnqueueDequeueCount)
{
LinkedQueue<int> queue;
queue.Enqueue(100);
queue.Enqueue(200);
queue.Enqueue(300);
EXPECT_EQ(3, queue.Count());
EXPECT_EQ(100, queue.Dequeue());
EXPECT_EQ(200, queue.Dequeue());
EXPECT_EQ(300, queue.Dequeue());
}
TEST(LinkedQueue, Enqueue1000)
{
LinkedQueue<int> queue;
for (int x = 1; x <= 1000; x++)
queue.Enqueue(x);
EXPECT_EQ(1000, queue.Count());
}
TEST(LinkedQueue, Enqueue100000)
{
LinkedQueue<int> queue;
for (int x = 1; x <= 100000; x++)
queue.Enqueue(x);
EXPECT_EQ(100000, queue.Count());
}
TEST(LinkedQueue, Enqueue1000000)
{
LinkedQueue<int> queue;
for (int x = 1; x <= 1000000; x++)
queue.Enqueue(x);
EXPECT_EQ(1000000, queue.Count());
}
// =====================================================
//
// =====================================================
TEST(ResizableQueue, EnqueueDequeueCount)
{
ResizableQueue<int> queue;
queue.Enqueue(100);
queue.Enqueue(200);
queue.Enqueue(300);
EXPECT_EQ(3, queue.Count());
EXPECT_EQ(100, queue.Dequeue());
EXPECT_EQ(200, queue.Dequeue());
EXPECT_EQ(300, queue.Dequeue());
}
TEST(ResizableQueue, Enqueue1000)
{
ResizableQueue<int> queue;
for (int x = 1; x <= 1000; x++)
queue.Enqueue(x);
EXPECT_EQ(1000, queue.Count());
}
TEST(ResizableQueue, Enqueue100000)
{
ResizableQueue<int> queue;
for (int x = 1; x <= 100000; x++)
queue.Enqueue(x);
EXPECT_EQ(100000, queue.Count());
}
TEST(ResizableQueue, Enqueue1000000)
{
ResizableQueue<int> queue;
for (int x = 1; x <= 1000000; x++)
queue.Enqueue(x);
EXPECT_EQ(1000000, queue.Count());
} | 17.824503 | 56 | 0.602638 |
8306d502d0de3894cbff049ac4e1904b81fd428b | 729 | cpp | C++ | test/examples_test/04_module_test/04_module_tests.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-julieei206 | e1fb506dbe4b068c01db307cd7626fd88b456a20 | [
"MIT"
] | null | null | null | test/examples_test/04_module_test/04_module_tests.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-julieei206 | e1fb506dbe4b068c01db307cd7626fd88b456a20 | [
"MIT"
] | 1 | 2020-10-30T23:36:49.000Z | 2020-11-06T19:33:56.000Z | test/examples_test/04_module_test/04_module_tests.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-julieei206 | e1fb506dbe4b068c01db307cd7626fd88b456a20 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
TEST_CASE("Verify Test Configuration", "verification") {
REQUIRE(true == true);
}
TEST_CASE("Verify sum of squares function")
{
REQUIRE(sum_of_squares(3)==14);
REQUIRE(sum_of_squares(4)==30);
REQUIRE(sum_of_squares(5)==55);
}
TEST_CASE("Verify sum numbers function")
{
REQUIRE(sum_numbers(4)==20);
}
TEST_CASE("Test get area with default parameters")
{
REQUIRE(get_area()==200);
REQUIRE(get_area(5)==50);
REQUIRE(get_area(20,20)==400);
}
TEST_CASE("Test value and reference parameters")
{
int num1=0, num2=0;
pass_by_val_and_ref(num1, num2);
REQUIRE(num1==0);
REQUIRE(num2==50);
}
| 20.828571 | 97 | 0.702332 |
8308730f7101ec449e3d4e3edfe2a179f4995b52 | 776 | cpp | C++ | Backtracking/ModularExpression.cpp | ssokjin/Interview-Bit | 8714d3d627eb5875f49d205af779b59ca33ab4a3 | [
"MIT"
] | 513 | 2016-08-16T12:52:14.000Z | 2022-03-30T19:32:10.000Z | Backtracking/ModularExpression.cpp | CodeOctal/Interview-Bit | 88c021685d6cdef17906d077411ce34723363a08 | [
"MIT"
] | 25 | 2018-02-14T15:25:48.000Z | 2022-03-23T11:52:08.000Z | Backtracking/ModularExpression.cpp | CodeOctal/Interview-Bit | 88c021685d6cdef17906d077411ce34723363a08 | [
"MIT"
] | 505 | 2016-09-02T15:04:20.000Z | 2022-03-25T06:36:31.000Z | // https://www.interviewbit.com/problems/modular-expression/
long long int calMod(int A, int B, int C){
if(B == 0){
return 1;
}
else if(B%2 == 0){
long long int y = calMod(A, B/2, C);
return (y*y)%C;
}
else{
return ((A%C)*calMod(A,B-1,C))%C;
}
}
int Solution::Mod(int A, int B, int C) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
if(A == 0){
return 0;
}
if(calMod(A, B, C) < 0){
return C+(int)calMod(A, B, C);
}
return (int)calMod(A, B, C);
}
| 24.25 | 93 | 0.552835 |
830b9919832d3b721808454193278df544785653 | 570 | cpp | C++ | input/array.cpp | xdevkartik/cpp_basics | a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55 | [
"MIT"
] | null | null | null | input/array.cpp | xdevkartik/cpp_basics | a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55 | [
"MIT"
] | null | null | null | input/array.cpp | xdevkartik/cpp_basics | a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
main(){
string name[5] = {"apple", "google", "microsoft", "ibm", "tesla"};
string arr[5] = {"ab", "bc", "cd", "de", "ff"};
string arr2[] = {"apappappapapap", "hghghdgahdgahsdghag"};
int num = sizeof(name[4]);
int num2 = sizeof(arr[0]);
int num3 = sizeof(arr2);
cout << "The size of this array is "<< num; // The output will be 24 bcz of 3 pointers.
cout << "The size of array 2 is "<< num2; // Each of size 8 bit. Thats why 8*3 = 24.
cout << "The size of array 3 is "<< num3;
return 0;
} | 38 | 91 | 0.578947 |
830c7aed466d2196cbf375ac5744dff58545af4e | 2,429 | cpp | C++ | source/file_interface/bit_field.cpp | burz/tap | 61f8f2cf2022db99e02992340735e342f4a8394d | [
"MIT"
] | 1 | 2016-10-07T01:52:57.000Z | 2016-10-07T01:52:57.000Z | source/file_interface/bit_field.cpp | burz/tap | 61f8f2cf2022db99e02992340735e342f4a8394d | [
"MIT"
] | null | null | null | source/file_interface/bit_field.cpp | burz/tap | 61f8f2cf2022db99e02992340735e342f4a8394d | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include "bit_field.h"
typedef struct {
unsigned short width;
unsigned short height;
size_t type_size;
GLint internal_format;
GLenum format;
GLenum type;
} BF_HEADER;
void create_bit_field_file(const char *destination, unsigned short width,
unsigned short height, size_t type_size,
GLint internal_format, GLenum format, GLenum type, void *data)
{
BF_HEADER header;
header.width = width;
header.height = height;
header.type_size = type_size;
header.internal_format = internal_format;
header.format = format;
header.type = type;
FILE *file = fopen(destination, "w+b");
if(file == NULL) {
fprintf(stderr, "Could not open %s for writting.\n", destination);
exit(1);
}
if( fwrite(&header, sizeof(BF_HEADER), 1, file) != 1) {
fprintf(stderr, "Writting to %s failed.\n", destination);
exit(1);
}
if(fwrite(data, width * height * type_size, 1, file) != 1) {
fprintf(stderr, "Writting to %s failed.\n", destination);
exit(1);
}
fclose( file );
}
void read_bit_field_file(const char *source, unsigned short *width,
unsigned short *height, size_t *type_size,
GLint *internal_format, GLenum *format, GLenum *type,
void **data)
{
FILE *file = fopen(source, "rb");
if(file == NULL) {
fprintf(stderr, "Could not open %s for reading.\n", source);
exit(1);
}
BF_HEADER header;
if(fread(&header, sizeof(BF_HEADER), 1, file) != 1) {
fprintf(stderr, "Could not read the header of %s\n", source);
exit(1);
}
if(width != NULL)
*width = header.width;
if(height != NULL)
*height = header.height;
if(type_size != NULL)
*type_size = header.type_size;
if(internal_format != NULL)
*internal_format = header.internal_format;
if(format != NULL)
*format = header.format;
if(type != NULL)
*type = header.type;
if(data == NULL)
return;
unsigned long image_size = header.height * header.width * header.type_size;
*data = malloc(image_size);
if(*data == NULL) {
fprintf(stderr, "Could not allocate enough space to load %s", source);
exit(1);
}
if(fread(*data, image_size, 1, file) != 1) {
fprintf(stderr, "Could not read image data from %s", source);
free(*data);
exit(1);
}
fclose(file);
}
| 22.915094 | 89 | 0.616715 |
83124097feb5012b57dc4f4fec5f0ab33adc840f | 1,446 | hpp | C++ | code/aoce/Module/ModuleManager.hpp | msqljj/aoce | b15320acbb9454fb461501c8cf0c598d1b15c495 | [
"MIT"
] | 71 | 2020-10-15T03:13:50.000Z | 2022-03-30T02:04:28.000Z | code/aoce/Module/ModuleManager.hpp | msqljj/aoce | b15320acbb9454fb461501c8cf0c598d1b15c495 | [
"MIT"
] | 9 | 2021-02-20T10:30:10.000Z | 2022-03-04T07:59:58.000Z | code/aoce/Module/ModuleManager.hpp | msqljj/aoce | b15320acbb9454fb461501c8cf0c598d1b15c495 | [
"MIT"
] | 19 | 2021-01-01T12:03:02.000Z | 2022-03-21T07:59:59.000Z | #pragma once
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "IModule.hpp"
namespace aoce {
typedef IModule* (*loadModuleAction)();
typedef std::function<IModule*(void)> loadModuleHandle;
class ModuleInfo {
public:
void* handle = nullptr;
IModule* module = nullptr;
std::string name = "";
loadModuleHandle onLoadEvent = nullptr;
bool load = false;
public:
ModuleInfo(/* args */){};
~ModuleInfo(){};
};
class ACOE_EXPORT ModuleManager {
public:
static ModuleManager& Get();
~ModuleManager();
protected:
ModuleManager();
private:
static ModuleManager* instance;
std::map<std::string, ModuleInfo*> modules;
private:
ModuleManager(const ModuleManager&) = delete;
ModuleManager& operator=(const ModuleManager&) = delete;
/* data */
public:
void registerModule(const char* name, loadModuleHandle handle = nullptr);
void loadModule(const char* name);
void unloadModule(const char* name);
void regAndLoad(const char* name);
public:
bool checkLoadModel(const char* name);
};
template <class module>
class StaticLinkModule {
public:
StaticLinkModule(const std::string& name) {
auto& fun = std::bind(&StaticLinkModule<module>::InitModeule, this);
ModuleManager::Get().registerModule(name, fun);
}
public:
IModule* InitModeule() { return new module(); }
};
} // namespace aoce
| 22.246154 | 77 | 0.670124 |
23fdffc29d4c01c820a8cf2a814b06bee7d887ba | 1,430 | cpp | C++ | xysetcolorwidget.cpp | xiaoyanLG/IconEditor | 2bcd95f5bba732b51e1f941eb7488d06f93f5fcd | [
"MIT"
] | null | null | null | xysetcolorwidget.cpp | xiaoyanLG/IconEditor | 2bcd95f5bba732b51e1f941eb7488d06f93f5fcd | [
"MIT"
] | null | null | null | xysetcolorwidget.cpp | xiaoyanLG/IconEditor | 2bcd95f5bba732b51e1f941eb7488d06f93f5fcd | [
"MIT"
] | null | null | null | #include "xysetcolorwidget.h"
#include "ui_xysetcolorwidget.h"
#include <QPainter>
#include <QMouseEvent>
XYSetColorWidget::XYSetColorWidget(QWidget *parent) :
QDialog(parent),
ui(new Ui::XYSetColorWidget), pressed(false)
{
ui->setupUi(this);
setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
setAutoFillBackground(true);
}
XYSetColorWidget::~XYSetColorWidget()
{
delete ui;
}
bool XYSetColorWidget::ignoreAlpha()
{
return ui->checkBox->isChecked();
}
QString XYSetColorWidget::getColor()
{
return ui->lineEdit->text().trimmed();
}
void XYSetColorWidget::on_cancelPushButton_clicked()
{
reject();
}
void XYSetColorWidget::on_replacePushButton_clicked()
{
accept();
}
bool XYSetColorWidget::event(QEvent *event)
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
switch (event->type())
{
case QEvent::MouseButtonPress:
pressed = true;
lastPressedPos = mouseEvent->pos();
break;
case QEvent::MouseButtonRelease:
pressed = false;
break;
case QEvent::MouseMove:
if (pressed)
move(pos() + mouseEvent->pos() - lastPressedPos);
break;
default:
break;
}
return QDialog::event(event);
}
void XYSetColorWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setPen(QColor("cccccc"));
painter.drawRect(rect().adjusted(0, 0, -1, -1));
}
| 20.724638 | 64 | 0.666434 |
9b01091ed19e91701e87e18fd4691b40ac1c724e | 856 | cpp | C++ | pico_src/conversion.cpp | Bambofy/pico | a26d853cca9e28170efa6ca694a9233f08f9b655 | [
"MIT"
] | 5 | 2020-03-03T16:02:28.000Z | 2020-03-17T12:43:55.000Z | pico_src/conversion.cpp | Bambofy/pico | a26d853cca9e28170efa6ca694a9233f08f9b655 | [
"MIT"
] | null | null | null | pico_src/conversion.cpp | Bambofy/pico | a26d853cca9e28170efa6ca694a9233f08f9b655 | [
"MIT"
] | 1 | 2020-03-04T12:16:05.000Z | 2020-03-04T12:16:05.000Z | #include "../pico_inc/conversion.h"
void Conversion_Uint_To_Char_Array(uint32_t inNumber, char * outDestinationPtrLocation, uint32_t outDestinationByteLength)
{
uintptr_t destPtr = reinterpret_cast<uintptr_t>(outDestinationPtrLocation);
_Conversion_Uint_To_Char_Array(inNumber, destPtr, outDestinationByteLength);
}
void Conversion_Int_To_Char_Array(int32_t inNumber, char * outDestinationPtrLocation, uint32_t outDestinationByteLength)
{
uintptr_t destPtr = reinterpret_cast<uintptr_t>(outDestinationPtrLocation);
_Conversion_Int_To_Char_Array(inNumber, destPtr, outDestinationByteLength);
}
int32_t Conversion_String_To_Int32(char * inCharArray, uint32_t inCharArrayPtrLength)
{
uintptr_t inCharArrayPtr = reinterpret_cast<uintptr_t>(inCharArray);
return _Conversion_String_To_Int32(inCharArrayPtr, inCharArrayPtrLength);
} | 37.217391 | 122 | 0.83528 |
9b05d31c458571d55d4d9b0ae720162f60569b39 | 609 | cpp | C++ | 2017.4.12/poj3176.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | 2017.4.12/poj3176.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | 2017.4.12/poj3176.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<string>
#include<vector>
#include<stack>
#include<set>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
int dp[355][355];
int a[355][355];
int main(){
int n,i,j;
while(~scanf("%d",&n)){
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
scanf("%d",&a[i][j]);
}
}
for(i=1;i<=n;i++){
dp[n][i]=a[n][i];
}
for(i=n-1;i>=1;i--){
for(j=1;j<=i;j++){
dp[i][j]=max(dp[i+1][j],dp[i+1][j+1])+a[i][j];
}
}
printf("%d\n",dp[1][1]);
memset(dp,0,sizeof(dp));
}
return 0;
}
| 16.459459 | 50 | 0.543514 |
9b0a3563dab2a04ccc0e60408e3dab89439e70d4 | 3,269 | cpp | C++ | test/core/image_processing/hough_circle_transform.cpp | harsh-4/gil | 6da59cc3351e5657275d3a536e0b6e7a1b6ac738 | [
"BSL-1.0"
] | 153 | 2015-02-03T06:03:54.000Z | 2022-03-20T15:06:34.000Z | test/core/image_processing/hough_circle_transform.cpp | harsh-4/gil | 6da59cc3351e5657275d3a536e0b6e7a1b6ac738 | [
"BSL-1.0"
] | 429 | 2015-03-22T09:49:04.000Z | 2022-03-28T08:32:08.000Z | test/core/image_processing/hough_circle_transform.cpp | harsh-4/gil | 6da59cc3351e5657275d3a536e0b6e7a1b6ac738 | [
"BSL-1.0"
] | 215 | 2015-03-15T09:20:51.000Z | 2022-03-30T12:40:07.000Z | // Boost.GIL (Generic Image Library) - tests
//
// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>
//
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/core/lightweight_test.hpp>
#include <boost/gil/image.hpp>
#include <boost/gil/image_processing/hough_transform.hpp>
#include <boost/gil/image_view.hpp>
#include <boost/gil/typedefs.hpp>
#include <cstddef>
#include <iostream>
#include <limits>
#include <vector>
namespace gil = boost::gil;
template <typename Rasterizer>
void exact_fit_test(std::ptrdiff_t radius, gil::point_t offset, Rasterizer rasterizer)
{
std::vector<gil::point_t> circle_points(rasterizer.point_count(radius));
rasterizer(radius, offset, circle_points.begin());
// const std::ptrdiff_t diameter = radius * 2 - 1;
const std::ptrdiff_t width = offset.x + radius + 1;
const std::ptrdiff_t height = offset.y + radius + 1;
gil::gray8_image_t image(width, height);
auto input = gil::view(image);
for (const auto& point : circle_points)
{
input(point) = std::numeric_limits<gil::uint8_t>::max();
}
using param_t = gil::hough_parameter<std::ptrdiff_t>;
const auto radius_parameter = param_t{radius, 0, 1};
// const auto x_parameter = param_t::from_step_count(offset.x, neighborhood, half_step_count);
// const auto y_parameter = param_t::from_step_count(offset.y, neighborhood, half_step_count);
const auto x_parameter = param_t{offset.x, 0, 1};
const auto y_parameter = param_t{offset.y, 0, 1};
std::vector<gil::gray16_image_t> output_images(
radius_parameter.step_count,
gil::gray16_image_t(x_parameter.step_count, y_parameter.step_count));
std::vector<gil::gray16_view_t> output_views(radius_parameter.step_count);
std::transform(output_images.begin(), output_images.end(), output_views.begin(),
[](gil::gray16_image_t& img)
{
return gil::view(img);
});
gil::hough_circle_transform_brute(input, radius_parameter, x_parameter, y_parameter,
output_views.begin(), rasterizer);
if (output_views[0](0, 0) != rasterizer.point_count(radius))
{
std::cout << "accumulated value: " << static_cast<int>(output_views[0](0, 0))
<< " expected value: " << rasterizer.point_count(radius) << "\n\n";
}
BOOST_TEST(output_views[0](0, 0) == rasterizer.point_count(radius));
}
int main()
{
const int test_dim_length = 20;
for (std::ptrdiff_t radius = 5; radius < test_dim_length; ++radius)
{
for (std::ptrdiff_t x_offset = radius; x_offset < radius + test_dim_length; ++x_offset)
{
for (std::ptrdiff_t y_offset = radius; y_offset < radius + test_dim_length; ++y_offset)
{
exact_fit_test(radius, {x_offset, y_offset}, gil::midpoint_circle_rasterizer{});
exact_fit_test(radius, {x_offset, y_offset},
gil::trigonometric_circle_rasterizer{});
}
}
}
return boost::report_errors();
}
| 38.916667 | 99 | 0.657693 |
9b10a45f76002112ed294a14d916e6f2af835d83 | 2,704 | cpp | C++ | src/18_Appendix_mathematics_4_deep_learning/Statistics.cpp | jiamny/D2L_pytorch_cpp | 5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09 | [
"MIT"
] | null | null | null | src/18_Appendix_mathematics_4_deep_learning/Statistics.cpp | jiamny/D2L_pytorch_cpp | 5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09 | [
"MIT"
] | null | null | null | src/18_Appendix_mathematics_4_deep_learning/Statistics.cpp | jiamny/D2L_pytorch_cpp | 5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09 | [
"MIT"
] | 1 | 2022-03-11T00:12:20.000Z | 2022-03-11T00:12:20.000Z | #include <unistd.h>
#include <iomanip>
#include <torch/utils.h>
#include "../utils/Ch_18_util.h"
#include "../matplotlibcpp.h"
namespace plt = matplotlibcpp;
using torch::indexing::Slice;
using torch::indexing::None;
// Statistical bias
torch::Tensor stat_bias(float true_theta, torch::Tensor est_theta) {
return(torch::mean(est_theta) - true_theta);
}
// Mean squared error
torch::Tensor mse(torch::Tensor data, float true_theta) {
return(torch::mean(torch::square(data - true_theta)));
}
int main() {
std::cout << "Current path is " << get_current_dir_name() << '\n';
// Device
auto cuda_available = torch::cuda::is_available();
torch::Device device(cuda_available ? torch::kCUDA : torch::kCPU);
std::cout << (cuda_available ? "CUDA available. Training on GPU." : "Training on CPU.") << '\n';
torch::manual_seed(8675309);
auto torch_pi = torch::acos(torch::zeros(1)) * 2; // define pi in torch
// Sample datapoints and create y coordinate
float epsilon = 0.1;
auto xs = torch::randn({300});
std::cout << xs.size(0) << '\n';
std::vector<float> ys;
for(int i = 0; i < xs.size(0); i++) {
auto yi = torch::sum(torch::exp(-1*torch::pow((xs.index({Slice(None, i)}) - xs[i]), 2) / (2 * epsilon*epsilon)))
/ torch::sqrt(2*torch_pi*epsilon*epsilon) / xs.size(0);
ys.push_back(yi.data().item<float>());
}
// Compute true density
auto xd = torch::arange(torch::min(xs).data().item<float>(), torch::max(xs).data().item<float>(), 0.01);
auto yd = torch::exp(-1*torch::pow(xd, 2)/2) / torch::sqrt(2 * torch_pi);
std::vector<float> xx(xs.data_ptr<float>(), xs.data_ptr<float>() + xs.numel());
std::vector<float> xxd(xd.data_ptr<float>(), xd.data_ptr<float>() + xd.numel());
std::vector<float> yyd(yd.data_ptr<float>(), yd.data_ptr<float>() + yd.numel());
plt::figure_size(700, 500);
plt::plot(xxd, yyd, "b-");
plt::scatter(xx, ys);
plt::plot({0.0,0.0}, {0.0, 0.5}, {{"color", "purple"}, {"linestyle", "--"}, {"lw", "2"}});
plt::xlabel("x");
plt::ylabel("density");
plt::title("sample mean: " + std::to_string(xs.mean().data().item<float>()));
plt::show();
plt::close();
float theta_true = 1.0;
float sigma = 4.0;
int sample_len = 10000;
auto samples = torch::normal(theta_true, sigma, {sample_len, 1});
auto theta_est = torch::mean(samples);
std::cout << "theta_est: " << theta_est << '\n';
std::cout << "mse(samples, theta_true): " << mse(samples, theta_true) << '\n';
// Next, we calculate Var(θ^n)+[bias(θ^n)]2 as below.
auto bias = stat_bias(theta_true, theta_est);
std::cout << "torch::square(samples.std(false)) + torch::square(bias): " <<
torch::square(samples.std(false)) + torch::square(bias) <<'\n';
std::cout << "Done!\n";
}
| 31.811765 | 114 | 0.637574 |
9b11201d895aebd1c232215dd1a6d43437170e38 | 4,093 | cpp | C++ | src/gamelib/editor/ui/Overlay.cpp | mall0c/GameLib | df4116b53c39be7b178dd87f7eb0fe32a94d00d3 | [
"MIT"
] | 1 | 2020-02-17T09:53:36.000Z | 2020-02-17T09:53:36.000Z | src/gamelib/editor/ui/Overlay.cpp | mall0c/GameLib | df4116b53c39be7b178dd87f7eb0fe32a94d00d3 | [
"MIT"
] | null | null | null | src/gamelib/editor/ui/Overlay.cpp | mall0c/GameLib | df4116b53c39be7b178dd87f7eb0fe32a94d00d3 | [
"MIT"
] | null | null | null | #include "gamelib/editor/ui/Overlay.hpp"
#include "gamelib/editor/tools/ToolUtils.hpp"
#include "gamelib/editor/EditorShared.hpp"
#include "gamelib/core/ecs/Entity.hpp"
#include "gamelib/core/geometry/flags.hpp"
#include "gamelib/core/input/InputSystem.hpp"
#include "gamelib/core/Game.hpp"
#include "gamelib/core/rendering/CameraSystem.hpp"
#include "gamelib/core/rendering/RenderSystem.hpp"
#include "gamelib/components/geometry/Polygon.hpp"
#include "gamelib/components/update/QPhysics.hpp"
#include "imgui.h"
namespace gamelib
{
Overlay::Overlay() :
renderSolid(true),
renderNormals(true),
renderVel(true),
showCoords(false),
debugOverlay(true),
debugOverlayMovable(true),
renderCams(true)
{ }
void Overlay::drawDebugOverlay()
{
if (debugOverlay)
{
if (!debugOverlayMovable)
ImGui::SetNextWindowPos(ImVec2(0, 16));
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.0f, 0.0f, 0.0f, 0.0f));
if (ImGui::Begin("Stats overlay", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize))
{
auto game = getSubsystem<Game>();
auto frametime = game->getFrametime();
ImGui::Text("FPS: %i", (int)(frametime != 0 ? 1.0 / frametime : 0));
ImGui::Text("Frametime: %i ms", (int)(frametime * 1000));
ImGui::Text("Real frametime: %i ms", (int)(game->getRealFrametime() * 1000));
ImGui::Text("Render time: %f ms", game->getRenderTime() * 1000);
ImGui::Text("Update time: %f ms", game->getUpdateTime() * 1000);
auto numrendered = getSubsystem<CameraSystem>()->getNumRendered();
if (!numrendered)
numrendered = RenderSystem::getActive()->getNumObjectsRendered();
ImGui::Text("Objects rendered: %lu", numrendered);
}
ImGui::End();
ImGui::PopStyleColor();
}
}
void Overlay::drawGui()
{
auto input = getSubsystem<InputSystem>();
if (!input->isMouseConsumed() && showCoords)
{
auto mouse = EditorShared::isSnapEnabled() ? EditorShared::getMouseSnapped() : EditorShared::getMouse();
ImGui::BeginTooltip();
ImGui::SetTooltip("%i, %i", (int)mouse.x, (int)mouse.y);
ImGui::EndTooltip();
}
}
void Overlay::render(sf::RenderTarget& target)
{
if (renderCams)
{
auto camsys = getSubsystem<CameraSystem>();
sf::Color col = sf::Color::Green;
for (size_t i = 0; i < camsys->size(); ++i)
{
auto cam = camsys->get(i);
const math::AABBf baserect(math::Point2f(), cam->getSize());
drawRectOutline(target, baserect, col, cam->getMatrix());
// if (!math::almostEquals(cam->getZoom(), 1.f))
// {
// auto nozoomTransform = cam->getTransformation();
// nozoomTransform.scale.fill(1);
// drawRectOutline(target, baserect, col, nozoomTransform.getMatrix());
// }
}
}
const auto ent = EditorShared::getSelected();
if (!ent)
return;
if (renderSolid)
drawCollisions(target, *ent, collision_solid);
if (renderVel)
{
auto phys = ent->findByName<QPhysics>();
if (phys && !phys->vel.isZero())
{
auto start = ent->getTransform().getBBox().getCenter();
auto end = start + phys->vel;
drawArrow(target, start.x, start.y, end.x, end.y, sf::Color::Cyan);
}
}
if (renderNormals)
ent->findAllByName<PolygonCollider>([&](CompRef<PolygonCollider> pol) {
if (pol->flags & collision_solid)
drawNormals(target, pol->getGlobal());
return false;
});
}
}
| 36.221239 | 120 | 0.548986 |
9b1409601663e4eec9f87a44ace803d145b51bfe | 1,079 | cc | C++ | cpp/Codeforces/401-450/447A_DZY_Loves_Hash.cc | phongvcao/CP_Contests_Solutions | 2e76e73ee7e53c798f63e1870be47653c75180a9 | [
"MIT"
] | null | null | null | cpp/Codeforces/401-450/447A_DZY_Loves_Hash.cc | phongvcao/CP_Contests_Solutions | 2e76e73ee7e53c798f63e1870be47653c75180a9 | [
"MIT"
] | null | null | null | cpp/Codeforces/401-450/447A_DZY_Loves_Hash.cc | phongvcao/CP_Contests_Solutions | 2e76e73ee7e53c798f63e1870be47653c75180a9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <stdint.h>
#include <cmath>
using namespace std;
typedef int64_t Int;
typedef uint64_t UInt;
int main(int argc, char **argv) {
UInt p = 0;
UInt n = 0;
// Read the first line
string line = "";
if (getline(cin, line)) {
stringstream ss(line);
ss >> p >> n;
}
unordered_map<Int, Int> intMap;
UInt lineIdx = 0;
UInt insertionCount = 0;
// Read the next n line
while (getline(cin, line)) {
stringstream ss(line);
UInt value = 0;
ss >> value;
UInt key = value % p;
unordered_map<Int, Int>::iterator iter = intMap.find(key);
if (iter != intMap.end()) {
break;
}
else {
intMap.insert(make_pair(key, value));
++insertionCount;
}
++lineIdx;
if (lineIdx == n) break;
}
if (insertionCount == n)
cout << -1;
else
cout << insertionCount + 1;
return 0;
}
| 17.983333 | 66 | 0.533828 |
9b160d656c01cbc5d492dfd427aabf9eaf021f2b | 1,816 | cc | C++ | src/monitor_unix.cc | jeroenvollenbrock/reset-date-cache | 7f88c35d0f992686e366dba9aeea70bbbe3d3373 | [
"MIT"
] | null | null | null | src/monitor_unix.cc | jeroenvollenbrock/reset-date-cache | 7f88c35d0f992686e366dba9aeea70bbbe3d3373 | [
"MIT"
] | null | null | null | src/monitor_unix.cc | jeroenvollenbrock/reset-date-cache | 7f88c35d0f992686e366dba9aeea70bbbe3d3373 | [
"MIT"
] | 1 | 2019-10-14T19:32:07.000Z | 2019-10-14T19:32:07.000Z | #include <uv.h>
#include <string.h>
#include "monitor.h"
// There is no true standard for where time zone information is actually
// stored. glibc uses /etc/localtime, uClibc uses /etc/TZ, and some older
// systems store the name of the time zone file within /usr/share/zoneinfo
// in /etc/timezone. Different libraries and custom builds may mean that
// still more paths are used. Just watch all three of these paths, because
// false positives are harmless, assuming the false positive rate is
// reasonable.
static const char* kFilesToWatch[] = {
"localtime",
"timezone",
"TZ",
};
// libuv seems to have some troubles when monitoring symlinks.
//It does however work if we monitor the parent folder non-recursively
static const char* kWatchFolder = "/etc/";
class TimeZoneMonitorUnix : public TimeZoneMonitor {
public:
TimeZoneMonitorUnix();
private:
static void tzChange(uv_fs_event_t *handle, const char *filename, int events, int status);
uv_fs_event_t fileWatcher;
};
void TimeZoneMonitorUnix::tzChange(uv_fs_event_t *handle, const char *filename, int events, int status) {
TimeZoneMonitorUnix *monitor = static_cast<TimeZoneMonitorUnix *>(handle->data);
for (size_t i = 0; i < sizeof(kFilesToWatch)/sizeof(kFilesToWatch[0]); i++) {
if(strcmp(kFilesToWatch[i], filename) == 0) {
monitor->DebouncedNotify(); //Debounce the notification (sometimes multiple files change)
return;
}
}
}
TimeZoneMonitorUnix::TimeZoneMonitorUnix()
{
uv_fs_event_init(uv_default_loop(), &fileWatcher);
fileWatcher.data = this;
uv_unref((uv_handle_t*)&fileWatcher);
uv_fs_event_start(&fileWatcher, TimeZoneMonitorUnix::tzChange, kWatchFolder, 0);
}
// static
TimeZoneMonitor *TimeZoneMonitor::Create() {
return new TimeZoneMonitorUnix();
} | 34.264151 | 105 | 0.729626 |
9b19915623890a71c6440137e1819b08795a6ab4 | 1,018 | cpp | C++ | engine/strings/source/RangedCombatTextKeys.cpp | sidav/shadow-of-the-wyrm | 747afdeebed885b1a4f7ab42f04f9f756afd3e52 | [
"MIT"
] | 60 | 2019-08-21T04:08:41.000Z | 2022-03-10T13:48:04.000Z | engine/strings/source/RangedCombatTextKeys.cpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 3 | 2021-03-18T15:11:14.000Z | 2021-10-20T12:13:07.000Z | engine/strings/source/RangedCombatTextKeys.cpp | cleancoindev/shadow-of-the-wyrm | 51b23e98285ecb8336324bfd41ebf00f67b30389 | [
"MIT"
] | 8 | 2019-11-16T06:29:05.000Z | 2022-01-23T17:33:43.000Z | #include "RangedCombatTextKeys.hpp"
using namespace std;
// Ranged combat messages
RangedCombatTextKeys::RangedCombatTextKeys()
{
}
RangedCombatTextKeys::~RangedCombatTextKeys()
{
}
const string RangedCombatTextKeys::RANGED_COMBAT_UNAVAILABLE_ON_WORLD_MAP = "RANGED_COMBAT_UNAVAILABLE_ON_WORLD_MAP";
const string RangedCombatTextKeys::RANGED_COMBAT_WEAPON_NOT_EQUIPPED = "RANGED_COMBAT_WEAPON_NOT_EQUIPPED";
const string RangedCombatTextKeys::RANGED_COMBAT_AMMUNITION_NOT_EQUIPPED = "RANGED_COMBAT_AMMUNITION_NOT_EQUIPPED";
const string RangedCombatTextKeys::RANGED_COMBAT_WEAPON_AMMUNITION_MISMATCH = "RANGED_COMBAT_WEAPON_AMMUNITION_MISMATCH";
const string RangedCombatTextKeys::RANGED_COMBAT_AMMUNITION_REQUIRES_RANGED_WEAPON = "RANGED_COMBAT_AMMUNITION_REQUIRES_RANGED_WEAPON";
const string RangedCombatTextKeys::RANGED_COMBAT_AMMUNITION_CURSED = "RANGED_COMBAT_AMMUNITION_CURSED";
const string RangedCombatTextKeys::RANGED_COMBAT_OVERBURDENED = "RANGED_COMBAT_OVERBURDENED"; | 50.9 | 135 | 0.852652 |
9b1d4f31caa5ccafbba94af952d5598e43d485ab | 1,603 | hpp | C++ | rayt-cpp/utils.hpp | gkmngrgn/rayt | 726d8e3d9716e91f27fec2c5982b7f79bfe0ea8a | [
"CC0-1.0",
"MIT"
] | 11 | 2020-07-04T13:35:10.000Z | 2022-03-30T17:34:27.000Z | rayt-cpp/utils.hpp | gkmngrgn/rayt | 726d8e3d9716e91f27fec2c5982b7f79bfe0ea8a | [
"CC0-1.0",
"MIT"
] | null | null | null | rayt-cpp/utils.hpp | gkmngrgn/rayt | 726d8e3d9716e91f27fec2c5982b7f79bfe0ea8a | [
"CC0-1.0",
"MIT"
] | 2 | 2021-03-02T06:31:43.000Z | 2022-03-30T17:34:28.000Z | #ifndef UTILS_HPP
#define UTILS_HPP
//==============================================================================
// Originally written in 2016 by Peter Shirley <ptrshrl@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy (see file COPYING.txt) of the CC0 Public
// Domain Dedication along with this software. If not, see
// <http://creativecommons.org/publicdomain/zero/1.0/>.
//==============================================================================
#include <cmath>
#include <cstdlib>
#include <limits>
#include <memory>
#include <random>
// Usings
using std::make_shared;
using std::shared_ptr;
using std::sqrt;
// Constants
const double infinity = std::numeric_limits<double>::infinity();
const double pi = 3.1415926535897932385;
// Utility Functions
inline double degrees_to_radians(double degrees) { return degrees * pi / 180; }
inline double random_double() {
static std::uniform_real_distribution<double> distribution(0.0, 1.0);
static std::mt19937 generator;
return distribution(generator);
}
inline double random_double(double min, double max) {
return min + (max - min) * random_double();
}
inline int random_int(int min, int max) {
return static_cast<int>(random_double(min, max + 1));
}
inline double clamp(double x, double min, double max) {
if (x < min) {
return min;
}
if (x > max) {
return max;
}
return x;
}
#endif
| 27.169492 | 80 | 0.65315 |
9b1e120f3f985b6e526ca03ec3955e648466096f | 5,202 | hh | C++ | kenlm/include/util/mmap.hh | pokey/w2ldecode | 03f9995a48c5c1043be309fe5b20c6126851a9ff | [
"BSD-3-Clause"
] | 114 | 2015-01-11T05:41:03.000Z | 2021-08-31T03:47:12.000Z | Part 02/001_LM/ngram_lm_lab/kenlm/include/util/mmap.hh | Kabongosalomon/AMMI-NLP | 00a0e47399926ad1951b84a11cd936598a9c7c3b | [
"MIT"
] | 29 | 2015-01-09T01:00:09.000Z | 2019-09-25T06:04:02.000Z | Part 02/001_LM/ngram_lm_lab/kenlm/include/util/mmap.hh | Kabongosalomon/AMMI-NLP | 00a0e47399926ad1951b84a11cd936598a9c7c3b | [
"MIT"
] | 50 | 2015-02-13T13:48:39.000Z | 2019-08-07T09:45:11.000Z | #ifndef UTIL_MMAP_H
#define UTIL_MMAP_H
// Utilities for mmaped files.
#include <cstddef>
#include <limits>
#include <stdint.h>
#include <sys/types.h>
namespace util {
class scoped_fd;
long SizePage();
// (void*)-1 is MAP_FAILED; this is done to avoid including the mmap header here.
class scoped_mmap {
public:
scoped_mmap() : data_((void*)-1), size_(0) {}
scoped_mmap(void *data, std::size_t size) : data_(data), size_(size) {}
~scoped_mmap();
void *get() const { return data_; }
const uint8_t *begin() const { return reinterpret_cast<uint8_t*>(data_); }
const uint8_t *end() const { return reinterpret_cast<uint8_t*>(data_) + size_; }
std::size_t size() const { return size_; }
void reset(void *data, std::size_t size) {
scoped_mmap other(data_, size_);
data_ = data;
size_ = size;
}
void reset() {
reset((void*)-1, 0);
}
private:
void *data_;
std::size_t size_;
scoped_mmap(const scoped_mmap &);
scoped_mmap &operator=(const scoped_mmap &);
};
/* For when the memory might come from mmap, new char[], or malloc. Uses NULL
* and 0 for blanks even though mmap signals errors with (void*)-1). The reset
* function checks that blank for mmap.
*/
class scoped_memory {
public:
typedef enum {MMAP_ALLOCATED, ARRAY_ALLOCATED, MALLOC_ALLOCATED, NONE_ALLOCATED} Alloc;
scoped_memory(void *data, std::size_t size, Alloc source)
: data_(data), size_(size), source_(source) {}
scoped_memory() : data_(NULL), size_(0), source_(NONE_ALLOCATED) {}
~scoped_memory() { reset(); }
void *get() const { return data_; }
const char *begin() const { return reinterpret_cast<char*>(data_); }
const char *end() const { return reinterpret_cast<char*>(data_) + size_; }
std::size_t size() const { return size_; }
Alloc source() const { return source_; }
void reset() { reset(NULL, 0, NONE_ALLOCATED); }
void reset(void *data, std::size_t size, Alloc from);
// realloc allows the current data to escape hence the need for this call
// If realloc fails, destroys the original too and get() returns NULL.
void call_realloc(std::size_t to);
private:
void *data_;
std::size_t size_;
Alloc source_;
scoped_memory(const scoped_memory &);
scoped_memory &operator=(const scoped_memory &);
};
typedef enum {
// mmap with no prepopulate
LAZY,
// On linux, pass MAP_POPULATE to mmap.
POPULATE_OR_LAZY,
// Populate on Linux. malloc and read on non-Linux.
POPULATE_OR_READ,
// malloc and read.
READ,
// malloc and read in parallel (recommended for Lustre)
PARALLEL_READ,
} LoadMethod;
extern const int kFileFlags;
// Wrapper around mmap to check it worked and hide some platform macros.
void *MapOrThrow(std::size_t size, bool for_write, int flags, bool prefault, int fd, uint64_t offset = 0);
void MapRead(LoadMethod method, int fd, uint64_t offset, std::size_t size, scoped_memory &out);
void MapAnonymous(std::size_t size, scoped_memory &to);
// Open file name with mmap of size bytes, all of which are initially zero.
void *MapZeroedWrite(int fd, std::size_t size);
void *MapZeroedWrite(const char *name, std::size_t size, scoped_fd &file);
// msync wrapper
void SyncOrThrow(void *start, size_t length);
// Forward rolling memory map with no overlap.
class Rolling {
public:
Rolling() {}
explicit Rolling(void *data) { Init(data); }
Rolling(const Rolling ©_from, uint64_t increase = 0);
Rolling &operator=(const Rolling ©_from);
// For an actual rolling mmap.
explicit Rolling(int fd, bool for_write, std::size_t block, std::size_t read_bound, uint64_t offset, uint64_t amount);
// For a static mapping
void Init(void *data) {
ptr_ = data;
current_end_ = std::numeric_limits<uint64_t>::max();
current_begin_ = 0;
// Mark as a pass-through.
fd_ = -1;
}
void IncreaseBase(uint64_t by) {
file_begin_ += by;
ptr_ = static_cast<uint8_t*>(ptr_) + by;
if (!IsPassthrough()) current_end_ = 0;
}
void DecreaseBase(uint64_t by) {
file_begin_ -= by;
ptr_ = static_cast<uint8_t*>(ptr_) - by;
if (!IsPassthrough()) current_end_ = 0;
}
void *ExtractNonRolling(scoped_memory &out, uint64_t index, std::size_t size);
// Returns base pointer
void *get() const { return ptr_; }
// Returns base pointer.
void *CheckedBase(uint64_t index) {
if (index >= current_end_ || index < current_begin_) {
Roll(index);
}
return ptr_;
}
// Returns indexed pointer.
void *CheckedIndex(uint64_t index) {
return static_cast<uint8_t*>(CheckedBase(index)) + index;
}
private:
void Roll(uint64_t index);
// True if this is just a thin wrapper on a pointer.
bool IsPassthrough() const { return fd_ == -1; }
void *ptr_;
uint64_t current_begin_;
uint64_t current_end_;
scoped_memory mem_;
int fd_;
uint64_t file_begin_;
uint64_t file_end_;
bool for_write_;
std::size_t block_;
std::size_t read_bound_;
};
} // namespace util
#endif // UTIL_MMAP_H
| 26.953368 | 122 | 0.662438 |
9b1ef61068f354d7463caaa27ecf5b7deb9a80a4 | 501 | hpp | C++ | ffl/include/pipeline/FFL_PipelineNodeParser.hpp | zhenfei2016/FFL-v2 | 376c79a0611af580d4767a4bbb05822f1a4fd454 | [
"MIT"
] | null | null | null | ffl/include/pipeline/FFL_PipelineNodeParser.hpp | zhenfei2016/FFL-v2 | 376c79a0611af580d4767a4bbb05822f1a4fd454 | [
"MIT"
] | null | null | null | ffl/include/pipeline/FFL_PipelineNodeParser.hpp | zhenfei2016/FFL-v2 | 376c79a0611af580d4767a4bbb05822f1a4fd454 | [
"MIT"
] | null | null | null | /*
* This file is part of FFL project.
*
* The MIT License (MIT)
* Copyright (C) 2017-2018 zhufeifei All rights reserved.
*
* FFL_PipelineNodeParser.hpp
* Created by zhufeifei(34008081@qq.com) on 2018/02/11
* https://github.com/zhenfei2016/FFL-v2.git
*
* Pipelin系统中通过脚本创建node的parser
*
*/
#ifndef _FFL_PIPELINENODE_PARSER_HPP_
#define _FFL_PIPELINENODE_PARSER_HPP_
namespace FFL{
class PipelineNodeParser {
public:
PipelineNodeParser();
virtual ~PipelineNodeParser();
};
}
#endif
| 17.892857 | 57 | 0.740519 |
9b22c51c017eac7389037e7adac6f8198921ebaf | 1,740 | cc | C++ | sync/api/attachments/attachment_store.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-11-28T10:46:52.000Z | 2019-11-28T10:46:52.000Z | sync/api/attachments/attachment_store.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | sync/api/attachments/attachment_store.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sync/api/attachments/attachment_store.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/location.h"
#include "base/sequenced_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "sync/internal_api/public/attachments/attachment_store_handle.h"
#include "sync/internal_api/public/attachments/in_memory_attachment_store.h"
#include "sync/internal_api/public/attachments/on_disk_attachment_store.h"
namespace syncer {
AttachmentStoreBase::AttachmentStoreBase() {}
AttachmentStoreBase::~AttachmentStoreBase() {}
AttachmentStore::AttachmentStore() {}
AttachmentStore::~AttachmentStore() {}
scoped_refptr<AttachmentStore> AttachmentStore::CreateInMemoryStore() {
// Both frontend and backend of attachment store will live on current thread.
scoped_ptr<AttachmentStoreBase> backend(
new InMemoryAttachmentStore(base::ThreadTaskRunnerHandle::Get()));
return scoped_refptr<AttachmentStore>(new AttachmentStoreHandle(
backend.Pass(), base::ThreadTaskRunnerHandle::Get()));
}
scoped_refptr<AttachmentStore> AttachmentStore::CreateOnDiskStore(
const base::FilePath& path,
const scoped_refptr<base::SequencedTaskRunner>& backend_task_runner,
const InitCallback& callback) {
scoped_ptr<OnDiskAttachmentStore> backend(
new OnDiskAttachmentStore(base::ThreadTaskRunnerHandle::Get(), path));
scoped_refptr<AttachmentStore> attachment_store =
new AttachmentStoreHandle(backend.Pass(), backend_task_runner);
attachment_store->Init(callback);
return attachment_store;
}
} // namespace syncer
| 37.021277 | 79 | 0.791379 |
9b23977b50d0add8801a8561d2bb08694a34cd37 | 1,233 | hpp | C++ | include/manala/selector/framemanagermostrecent.hpp | tpeterka/decaf | ad6ad823070793bfd7fc8d9384d5475f7cf20848 | [
"BSD-3-Clause"
] | 1 | 2019-05-10T02:50:50.000Z | 2019-05-10T02:50:50.000Z | include/manala/selector/framemanagermostrecent.hpp | tpeterka/decaf | ad6ad823070793bfd7fc8d9384d5475f7cf20848 | [
"BSD-3-Clause"
] | 2 | 2020-10-28T03:44:51.000Z | 2021-01-18T19:49:33.000Z | include/manala/selector/framemanagermostrecent.hpp | tpeterka/decaf | ad6ad823070793bfd7fc8d9384d5475f7cf20848 | [
"BSD-3-Clause"
] | 2 | 2018-08-31T14:02:47.000Z | 2020-04-17T16:01:54.000Z | //---------------------------------------------------------------------------
// Framemanager sequential implementation. The frame are sent one by one
// in the receiving order.
//
// Matthieu Dreher
// Argonne National Laboratory
// 9700 S. Cass Ave.
// Argonne, IL 60439
// mdreher@anl.gov
//
//--------------------------------------------------------------------------
#ifndef DECAF_FRAMEMANAGER_RECENT
#define DECAF_FRAMEMANAGER_RECENT
#include <manala/selector/framemanager.hpp>
#include <list>
namespace decaf
{
class FrameManagerRecent : public FrameManager
{
public:
FrameManagerRecent(CommHandle comm, TaskType role, unsigned int prod_freq_output);
virtual ~FrameManagerRecent();
virtual bool sendFrame(unsigned int id);
virtual void putFrame(unsigned int id);
virtual FrameCommand getNextFrame(unsigned int* frame_id);
virtual bool hasNextFrameId();
virtual bool hasNextFrame();
virtual void computeNextFrame();
protected:
std::list<unsigned int> buffer_;
bool received_frame_id_;
bool received_frame_;
int frame_to_send_;
int previous_frame_;
unsigned prod_freq_output_;
};
}
#endif
| 26.804348 | 90 | 0.609895 |
9b23a487cc1e235334005a4fd35d270a66e79f66 | 328 | cpp | C++ | chapter10/Proj1013.cpp | basstal/CPPPrimer | 6366965657f873ac62003cf0a30a3fdb26c09351 | [
"MIT"
] | null | null | null | chapter10/Proj1013.cpp | basstal/CPPPrimer | 6366965657f873ac62003cf0a30a3fdb26c09351 | [
"MIT"
] | null | null | null | chapter10/Proj1013.cpp | basstal/CPPPrimer | 6366965657f873ac62003cf0a30a3fdb26c09351 | [
"MIT"
] | null | null | null | #include"head.h"
bool func(const string &s);
int main(){
vector<string> words{"fox","jumps","over","quick","red","quick","blow","slow","the","turtle"};
auto iter = partition(words.begin(),words.end(),func);
for(const auto &e:words)
cout<<e<<" ";
cout<<endl;
return 0;
}
bool func(const string &s){
return s.size()>=5;
} | 23.428571 | 95 | 0.631098 |
9b25946d853b291db8676fcd613c862454f7ef3e | 1,719 | cpp | C++ | firmware/Heat controller/lib/NTC/src/NTC.cpp | atoomnetmarc/IoT12 | 7706f69758a800da70bf8034a91a331206706824 | [
"Apache-2.0"
] | null | null | null | firmware/Heat controller/lib/NTC/src/NTC.cpp | atoomnetmarc/IoT12 | 7706f69758a800da70bf8034a91a331206706824 | [
"Apache-2.0"
] | null | null | null | firmware/Heat controller/lib/NTC/src/NTC.cpp | atoomnetmarc/IoT12 | 7706f69758a800da70bf8034a91a331206706824 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2021-2022 Marc Ketel
SPDX-License-Identifier: Apache-2.0
*/
#include <math.h>
#include "NTC.h"
/*
Class which is able to calculate the temperature of a NTC given the voltage of a resistor divider.
Simple schematic:
resistorDividerVoltage---[resistorDividerResistance]---[NTC]---GND
*/
NTC::NTC(void)
{
}
/**
@param resistorDividerVoltage Voltage of the resistor divider.
@param resistorDividerResistance The fixed resistance of the resistor divider.
@param thermistorResistance Resistance of the NTC at thermistorTemperature.
@param thermistorTemperature Temperature in Kelvin of the NTC at thermistorResistance.
@param thermistorBValue β-value of the NTC in Kelvin.
*/
void NTC::SetParameters(
float resistorDividerVoltage,
float resistorDividerResistance,
float thermistorResistance,
float thermistorTemperature,
float thermistorBValue)
{
this->resistorDividerVoltage = resistorDividerVoltage;
this->resistorDividerResistance = resistorDividerResistance;
this->thermistorResistance = thermistorResistance;
this->thermistorTemperature = thermistorTemperature;
this->thermistorBValue = thermistorBValue;
}
/**
@return Temperature in Kelvin
*/
float NTC::GetTemperature(float voltage)
{
//Current though NTC.
float I = (this->resistorDividerVoltage - voltage) / this->resistorDividerResistance;
//NTC resistance.
float Rntc = (voltage / I);
//Apply Steinhart–Hart equation: https://en.wikipedia.org/wiki/Thermistor#B_or_%CE%B2_parameter_equation
float temperature = (1 / ((log(Rntc / this->resistorDividerResistance) / this->thermistorBValue) + (1 / this->thermistorTemperature)));
return temperature;
} | 28.180328 | 139 | 0.753345 |
9b2a012c2808ffd3d8332d0b950ec6d09f53f0c1 | 22,385 | cpp | C++ | src/MFGame.cpp | tristanstcyr/MacFungus-2.0 | 8f1f7e384f478828dc9b992f1d69f88e93b591bc | [
"BSD-3-Clause"
] | 2 | 2019-08-14T16:28:42.000Z | 2021-07-17T19:29:06.000Z | src/MFGame.cpp | tristanstcyr/MacFungus-2.0 | 8f1f7e384f478828dc9b992f1d69f88e93b591bc | [
"BSD-3-Clause"
] | null | null | null | src/MFGame.cpp | tristanstcyr/MacFungus-2.0 | 8f1f7e384f478828dc9b992f1d69f88e93b591bc | [
"BSD-3-Clause"
] | 2 | 2017-02-27T22:12:56.000Z | 2017-08-10T10:02:36.000Z | #include <fstream>
#include <xmlParser.h>
#include <MFGame.h>
#include <time.h>
static const unsigned int MIN_GRID_SIZE = 10;
static const std::string SHAPES_XML_FILE_PATH = "../../shapes.xml";
static char highlightChar = '*';
static char hotCornerChar = '&';
using std::vector;
template <typename T>
bool vectorContains(vector<T> aVector, T anObject) {
for (int i = 0; i < aVector.size(); i++) {
T anotherObject = aVector.at(i);
if (anotherObject == anObject)
return true;
}
return false;
}
#pragma mark -
#pragma mark MFGame
#pragma mark -Constructors
MFGame::MFGame(unsigned int gridSize, std::vector<boost::shared_ptr<MFPlayer> > thePlayers) :
players(thePlayers), currentShapeIndex(0), currentPlayerIndex(0), winnerIndex(-1),
isGameStarted(false), isUsingHotCorners(true) { setGridSize(gridSize); }
MFGame::MFGame() : currentGrid(MFGrid(MIN_GRID_SIZE)), currentShapeIndex(0), currentPlayerIndex(0),
winnerIndex(-1), isGameStarted(false), isUsingHotCorners(true) {}
// Constructed from an XML saved state
MFGame::MFGame(const char *xmlCString)
{
int numPlayers;
XMLNode xGameNode = XMLNode::parseString(xmlCString, "game");
char *buffer;
XMLNode xGridNobe = xGameNode.getChildNode("grid");
XMLNode xPlayersNode = xGameNode.getChildNode("players");
numPlayers = xPlayersNode.nChildNode("player");
if (numPlayers == 0)
goto bailout;
// set ints & bools
isGameStarted = ( atoi(xGameNode.getAttribute("isGameStarted")) != 0 );
currentPlayerIndex = atoi((char*)xGameNode.getAttribute("currentPlayerIndex"));
winnerIndex = atoi((char*)xGameNode.getAttribute("winnerIndex"));
// set grid
buffer = xGridNobe.createXMLString(false);
currentGrid = MFGrid(buffer);
free(buffer);
// set players
for (int playerIndex = 0; playerIndex < numPlayers; playerIndex++) {
boost::shared_ptr<MFPlayer> aPlayer(new MFPlayer());
XMLNode xPlayerNode = xPlayersNode.getChildNode("player", playerIndex);
aPlayer->name = xPlayerNode.getAttribute("name");
aPlayer->color.red = atof(xPlayerNode.getAttribute("red"));
aPlayer->color.blue = atof(xPlayerNode.getAttribute("blue"));
aPlayer->color.green = atof(xPlayerNode.getAttribute("blue"));
aPlayer->alive = ( atoi(xPlayerNode.getAttribute("alive")) != 0 );
players.push_back(aPlayer);
}
return;
bailout:
*this = MFGame();
}
#pragma mark - Gameplay
void MFGame::startGame()
{
if (players.size() < 2)
throw "MFGame::startGame(): Not enough players to start game";
const int gridSize = currentGrid.size();
const int biteNum = 3;
const int borderDistance = gridSize/5;
std::vector<boost::shared_ptr<MFPlayer> >::iterator aPlayerPtr;
winnerIndex = -1;
currentPlayerIndex = 0;
isGameStarted = true;
currentGrid.clear();
//Set all players to alive
for (aPlayerPtr = players.begin(); aPlayerPtr < players.end(); aPlayerPtr++) {
(*aPlayerPtr)->alive = true;
(*aPlayerPtr)->bites = biteNum;
(*aPlayerPtr)->turnSkips = 0;
}
// Assign a starting point for each player
switch (players.size()) {
case 4 : currentGrid.drawPosition(borderDistance, gridSize-1 - borderDistance, getPlayerCharHead(3));
case 3 : currentGrid.drawPosition(gridSize-1 - borderDistance, borderDistance, getPlayerCharHead(2));
case 2 : currentGrid.drawPosition(gridSize-1 - borderDistance, gridSize-1 - borderDistance, getPlayerCharHead(1));
currentGrid.drawPosition(borderDistance, borderDistance, getPlayerCharHead(0));
}
if (isUsingHotCorners) {
currentGrid.drawPosition(0,0, hotCornerChar);
currentGrid.drawPosition(0,currentGrid.size()-1, hotCornerChar);
currentGrid.drawPosition(currentGrid.size()-1, 0, hotCornerChar);
currentGrid.drawPosition(currentGrid.size()-1, currentGrid.size()-1, hotCornerChar);
}
}
bool MFGame::getIsGameStarted() { return isGameStarted; }
bool MFGame::playShape(const int& degrees, const int& player, const int& row, const int& col)
{
const int cornerExtraBites = 3;
if (this->playShapeIsValid(degrees, player, row, col) == false)
return false;
vector<char*>newBodyChars;
vector<char*>::iterator charItrtr;
MFGridShape rotatedShape = shapesVector.at(currentShapeIndex).rotate(degrees);
players.at(player)->turnSkips = 0;
lastErasedSequence.clear();
lastEatenSequence.clear();
lastMoveGrid = currentGrid;
newBodyChars = currentGrid.charsAtShape(rotatedShape, row, col);
for (charItrtr = newBodyChars.begin(); charItrtr < newBodyChars.end(); charItrtr++) {
if (**charItrtr == hotCornerChar)
players.at(player)->bites += cornerExtraBites;
}
currentGrid.drawShape(rotatedShape, row, col, getPlayerCharBody(currentPlayerIndex));
if(sandwichedChars(newBodyChars, player).size())
eraseDisconnects();
endTurn();
return true;
}
vector<char*> MFGame::sandwichedChars(vector<char*>initialChars, const int& playerIndex) {
vector<char*>::iterator charItrtr;
vector<char*> finalChars;
for (charItrtr = initialChars.begin(); charItrtr < initialChars.end(); charItrtr++) {
int row, col;
currentGrid.rowColForChar(*charItrtr, row, col);
// Check sandwiched chars from specific char
vector<char*> foundSandwichedChars = currentGrid.sandwitchedChars(row, col, getPlayerCharBody(playerIndex), getPlayerCharHead(playerIndex));
for (int i = 0; i < foundSandwichedChars.size(); i++) {
*(foundSandwichedChars.at(i)) = getPlayerCharBody(playerIndex);
lastEatenSequence.push_back(pMFGrid( new MFGrid(currentGrid) ));
}
// If any chrs were sandwiched check sandwiches for those
if (foundSandwichedChars.size() > 0) { // Recursive call
vector<char*> recursiveSandwichedChars = sandwichedChars(foundSandwichedChars, playerIndex);
finalChars.insert(finalChars.end(), recursiveSandwichedChars.begin() , recursiveSandwichedChars.end());
}
finalChars.insert(finalChars.end(), foundSandwichedChars.begin() , foundSandwichedChars.end());
}
return finalChars;
}
bool MFGame::playBite(const int& shapeIndex, const int& playerIndex, const int& row, const int& col)
{
if (playBiteIsValid(shapeIndex, playerIndex, row, col) == false)
return false;
MFGrid newGrid = currentGrid;
MFGridShape aShape = getShapeAtIndex(shapeIndex).rotate(getCurrentShapeDegrees());
char currentBody = getPlayerCharBody(getCurrentPlayerIndex()),
currentHead = getPlayerCharHead(getCurrentPlayerIndex());
newGrid.drawShapeWithExceptions(aShape, row, col, newGrid.getDefaultChar(), 2, ¤tBody, ¤tHead);
lastErasedSequence.erase(lastErasedSequence.begin(), lastErasedSequence.end());
lastMoveGrid = newGrid;
players.at(playerIndex)->bites -= aShape.cellVectors.size();
currentGrid = newGrid;
eraseDisconnects();
return true;
}
bool MFGame::skipTurn(const int& anIndex)
{
if (anIndex != currentPlayerIndex)
return false;
boost::shared_ptr<MFPlayer> skipPlayer = players.at(anIndex);
skipPlayer->turnSkips += 1;
if (skipPlayer->turnSkips > 2) {
punishPlayerAtIndex(anIndex);
skipPlayer->turnSkips = 0;
}
endTurn();
return true;
}
bool MFGame::playShapeIsValid(const int& degrees, const int& player, const int& row, const int& col)
{
int i;
bool isTouching = false;
std::vector<Position> rotatedShape(shapesVector.at(currentShapeIndex).rotate(degrees).cellVectors);
int gridsize = currentGrid.size();
// Is it the current player or is the game over?
if (player != currentPlayerIndex || winnerIndex != -1 || getIsGameStarted() == false)
return false;
// Can the shape be placed?
for (i = 0; i < rotatedShape.size(); i++)
{
Position displacement = rotatedShape.at(i);
int dispRow = displacement.row + row;
int dispCol = displacement.col + col;
// Is it out of bound
if ( dispRow > gridsize - 1 || dispRow < 0 )
return false;
if ( dispCol > gridsize - 1 || dispCol < 0 )
return false;
// Is the spot blank or an artifact
char *charOnGrid = currentGrid.charAtRowCol(dispRow, dispCol);
if (*charOnGrid != currentGrid.getDefaultChar() && *charOnGrid != '&')
return false;
// Is touching some similar char
if (currentGrid.charNeighbors(dispRow, dispCol, getPlayerCharBody(player)).size() > 0)
isTouching = true;
if (currentGrid.charNeighbors(dispRow, dispCol, getPlayerCharHead(player)).size() > 0)
isTouching = true;
}
return isTouching;
}
bool MFGame::playBiteIsValid(const int& shapeIndex, const int& playerIndex, const int& row, const int& col)
{
using std::vector;
bool foundBiteable = false;
MFGridShape shape = getShapeAtIndex(shapeIndex);
vector<char*> bittenChars = currentGrid.charsAtShape(shape, row, col);
vector<char*>::iterator charItrtr;
vector<char*> neighbors;
for (charItrtr = bittenChars.begin(); charItrtr < bittenChars.end(); charItrtr++) {
vector<char*> headNeighbors, bodyNeighbors;
int aRow, aCol;
currentGrid.rowColForChar(*charItrtr, aRow, aCol);
headNeighbors = currentGrid.charNeighbors(aRow, aCol, getPlayerCharHead(playerIndex));
bodyNeighbors = currentGrid.charNeighbors(aRow, aCol, getPlayerCharBody(playerIndex));
neighbors.insert(neighbors.end(), headNeighbors.begin(), headNeighbors.end());
neighbors.insert(neighbors.end(), bodyNeighbors.begin(), bodyNeighbors.end());
if (**charItrtr != currentGrid.getDefaultChar() &&
**charItrtr != getPlayerCharHead(getCurrentPlayerIndex()) &&
**charItrtr != getPlayerCharBody(getCurrentPlayerIndex()))
foundBiteable = true;
}
//Check if the game's conditions are right
if (playerIndex != currentPlayerIndex ||
getIsGameStarted() == false ||
players.at(playerIndex)->bites < shape.cellVectors.size() ||
neighbors.size() == 0 ||
!foundBiteable)
return false;
//Check bounds
if (row > currentGrid.size() - 1 || col > currentGrid.size() - 1 || row < 0 || row < 0)
return false;
return true;
}
// Called when the player skips a certain number of turns consecutively from the skipTurn function
void MFGame::punishPlayerAtIndex(const int& anIndex) // Choose a percentage or a player's square's at
{ // random and delete'em
const int PUNISH_PERC = 10;
int charNum, eraseCharNum;
std::vector<char*> playerChars = currentGrid.identicalChars(getPlayerCharBody(anIndex)),
charErases;
char *aChar;
charNum = playerChars.size();
lastEatenSequence.clear();
if (charNum == 0) // Don't punish someone with only a head
return;
eraseCharNum = charNum/PUNISH_PERC;
srand((unsigned)time(0));
for (int i = 0; i < eraseCharNum; i++) { // get eraseCharNum number of unique random chars
int row, col;
do {
int randomInt = rand();
int randomIndex = randomInt % charNum; // get a randomIndex from 0 to eraseCharNum
aChar = playerChars.at(randomIndex); // get the char
} while (vectorContains(charErases, aChar)); // continue until it's a new one
charErases.push_back(aChar);
currentGrid.rowColForChar(aChar, row, col);
currentGrid.drawPosition(row, col, currentGrid.getDefaultChar()); // erase the char
lastEatenSequence.push_back(pMFGrid( new MFGrid(currentGrid)));
}
eraseDisconnects();
}
void MFGame::endTurn()
{
if (getIsGameStarted() == false)
return;
int nextPlayerIndex = currentPlayerIndex;
std::vector<boost::shared_ptr<MFPlayer> > deadPlayers, alivePlayers;
// Check dead players and set blocks
for (int i = 0; i < players.size(); i++)
{
int row, col;
if (currentGrid.rowColForUniqueChar(getPlayerCharHead(i), &row, &col) == false)
{
players.at(i)->alive = false;
deadPlayers.push_back(players.at(i));
} else {
players.at(i)->blocks = currentGrid.identicalChars(getPlayerCharBody(i)).size() + 1;
alivePlayers.push_back(players.at(i));
}
}
// Game over if one player is left
if (deadPlayers.size() == players.size() - 1) {
winnerIndex = playerIndex(alivePlayers.at(0));
isGameStarted = false;
return;
}
// Switch to the next player that is not dead
while (nextPlayerIndex == currentPlayerIndex || players.at(nextPlayerIndex)->alive == false) {
if (++nextPlayerIndex > players.size()-1)
nextPlayerIndex = 0;
}
currentPlayerIndex = nextPlayerIndex;
}
#pragma mark - Grid
void MFGame::setGridSize(const int& anInt) {
if (isGameStarted) isGameStarted = false;
currentGrid = (anInt < MIN_GRID_SIZE ? MFGrid(MIN_GRID_SIZE) : MFGrid(anInt));
}
MFGrid MFGame::getCurrentGrid() { return currentGrid; }
MFGrid MFGame::getLastMoveGrid() { return lastMoveGrid; }
MFGrid MFGame::getShapeOnGrid(const int& degrees, const int& player, const int& row, const int& col) {
MFGrid aGrid = currentGrid;
MFGridShape rotatedShape = shapesVector.at(currentShapeIndex).rotate(degrees);
aGrid.drawShape(rotatedShape, row, col, getPlayerCharBody(player));
return aGrid;
}
MFGrid MFGame::getShapeHighlightGrid(const int& degrees, const int& player, const int& row, const int& col)
{
MFGrid highlightGrid = MFGrid(getCurrentGrid().size());
MFGrid currentGridCopy =MFGrid(getCurrentGrid().size());
std::vector<char*> highlightChars;
std::vector<char*>::iterator charItrtr;
MFGridShape aShape = shapesVector.at(currentShapeIndex);
currentGridCopy.drawShapeOnDefaultChars(aShape.rotate(degrees), row, col, highlightChar);
highlightChars = currentGridCopy.identicalChars(highlightChar);
for (charItrtr = highlightChars.begin(); charItrtr < highlightChars.end(); charItrtr++)
{
int aRow, aCol;
currentGridCopy.rowColForChar(*charItrtr, aRow, aCol);
highlightGrid.drawPosition(aRow, aCol, highlightChar);
}
return highlightGrid;
}
MFGrid MFGame::getBiteHighlightGrid(const int& shapeIndex, const int& degrees, const int& playerIndex, const int& row, const int& col)
{
MFGrid intersectingGrid = MFGrid(currentGrid.size());
MFGridShape aShape = shapesVector.at(shapeIndex).rotate(degrees);
std::vector<Position>::iterator posItrtr;
for (posItrtr = aShape.cellVectors.begin() ; posItrtr < aShape.cellVectors.end(); posItrtr++)
{
Position charPosition = *posItrtr;
charPosition.row += row;
charPosition.col += col;
if (charPosition.row >= 0 && charPosition.col >= 0 && charPosition.row < currentGrid.size() && charPosition.col < currentGrid.size()) {
char foundChar = *currentGrid.charAtRowCol(charPosition.row, charPosition.col);
if (foundChar != getPlayerCharBody(playerIndex) && foundChar != getPlayerCharHead(playerIndex) && foundChar != currentGrid.getDefaultChar())
intersectingGrid.drawPosition(charPosition.row, charPosition.col, highlightChar);
}
}
return intersectingGrid;
}
std::vector<pMFGrid> MFGame::getLastEatSequence() { return lastEatenSequence; }
std::vector<pMFGrid> MFGame::getLastEraseSequence() { return lastErasedSequence; }
void MFGame::eraseDisconnects() {
lastErasedSequence.clear();
for (int i = 0; i < players.size(); i++)
{
int headRow, headCol;
vector<char*>isolatedChars, sandwitchedChars;
vector<char*>::iterator itrtr;
// If the head is still on the grid we check for isolated if not we take all
if (currentGrid.rowColForUniqueChar(getPlayerCharHead(i), &headRow, &headCol))
isolatedChars = currentGrid.isolatedChars(headRow, headCol, getPlayerCharBody(i));
else
isolatedChars = currentGrid.identicalChars(getPlayerCharBody(i));
for (itrtr = isolatedChars.begin(); itrtr < isolatedChars.end(); itrtr++)
{
**itrtr = currentGrid.getDefaultChar();
// Assemble the animation for eaten chars
lastErasedSequence.push_back(pMFGrid( new MFGrid(currentGrid) ));
}
}
}
#pragma mark - Players
int MFGame::getWinnerIndex() { return winnerIndex; }
int MFGame::getNumberOfPlayers() { return players.size(); }
int MFGame::getCurrentPlayerIndex() { return currentPlayerIndex; }
MFPlayer MFGame::getPlayerAtIndex(int anIndex) {
if (anIndex >= players.size()) {
std::cout << "\nMFGame::getPlayerAtIndex : ";
std::cout << anIndex;
std::cout << " beyond range\n";
}
return *players.at(anIndex);
}
void MFGame::removePlayerAtIndex(int deleteIndex)
{
if (deleteIndex < 0 || deleteIndex > players.size())
return;
boost::shared_ptr<MFPlayer> erasedPlayer = players.at(deleteIndex);
std::vector<boost::shared_ptr<MFPlayer> >::iterator itrtr;
for (itrtr = players.begin(); itrtr < players.end(); itrtr++) {
if (*itrtr == erasedPlayer)
players.erase(itrtr);
}
if (currentPlayerIndex > deleteIndex)
--currentPlayerIndex;
else if (currentPlayerIndex == deleteIndex) {
--currentPlayerIndex;
endTurn();
}
}
void MFGame::swapPlayersAtIndexes(const int i1,const int i2) {
std::vector<boost::shared_ptr<MFPlayer> > newPlayersVector;
for (int i = 0; i < players.size(); i++) {
if (i == i1)
newPlayersVector.push_back(players.at(i2));
else if (i == i2)
newPlayersVector.push_back(players.at(i1));
else
newPlayersVector.push_back(players.at(i));
}
players = newPlayersVector;
}
void MFGame::addPlayer(std::string aName, Color aColor)
{
bool isAlive = (getIsGameStarted() == false);
boost::shared_ptr<MFPlayer> aPlayer(new MFPlayer(aColor, aName, DEFAULT_BITES, isAlive));
players.push_back(aPlayer);
}
int MFGame::playerIndex(boost::shared_ptr<MFPlayer> aPlayer)
{
for (int i = 0; i < players.size(); i++) {
if (players.at(i) == aPlayer)
return i;
}
return -1;
}
// Returns the number of chars on the grid of the player at index
int MFGame::getNumberOfCharsForPlayerIndex(int anIndex)
{
int numChars = 0;
if (anIndex >= getNumberOfPlayers() || getPlayerAtIndex(anIndex).alive == false)
return numChars;
numChars = currentGrid.identicalChars(getPlayerCharBody(anIndex)).size();
return numChars+1;
}
char MFGame::getPlayerCharBody(int anIndex) {
if (anIndex >= players.size() || anIndex < 0)
return currentGrid.getDefaultChar();
else
return 'a' + anIndex;
}
char MFGame::getPlayerCharHead(int anIndex) {
if (anIndex >= players.size() || anIndex < 0)
return currentGrid.getDefaultChar();
else
return 'A' + anIndex;
}
#pragma mark - Shapes
int MFGame::getRandomShapeIndex() { srand(time(NULL)); return (rand() % shapesVector.size()) + 1; }
int MFGame::getCurrentShapeIndex() { return currentShapeIndex; }
void MFGame::setCurrentShapeIndex(int anIndex)
{
if (anIndex >= 0 && anIndex < shapesVector.size())
currentShapeIndex = anIndex;
shapeDegrees = 0;
}
int MFGame::rotateCurrentShape() {
switch (shapeDegrees) {
case 0: shapeDegrees = 90; break;
case 90: shapeDegrees = 180; break;
case 180: shapeDegrees = 270; break;
default : shapeDegrees = 0; break;
}
return shapeDegrees;
}
int MFGame::setShapesFromXMLCString(const char *xmlCString)
{
int i, numShapes;
std::vector<MFGridShape> newShapesVector;
// this open and parse the XML file and looks for the tag "Shapes":
XMLNode xMainNode = XMLNode::parseString(xmlCString, "Shapes");
numShapes = xMainNode.nChildNode("Shape");
if (numShapes == 0)
return -1;
std::cout << numShapes;
// Get each shape
for (i = 0; i < numShapes; i++)
{
int j, numCells;
bool rotates;
std::vector<Position> shape;
XMLNode shapeNode = xMainNode.getChildNode("Shape",i);
numCells = shapeNode.nChildNode("Cell");
rotates = (bool)atoi(shapeNode.getAttribute("rotates"));
// Get the x y coordinates
for (j = 0; j < numCells; j++) {
XMLNode cellNode = shapeNode.getChildNode("Cell", j);
Position coordinates;
coordinates.row = atoi(cellNode.getAttribute("row"));
coordinates.col = atoi(cellNode.getAttribute("col"));
shape.push_back(coordinates);
}
newShapesVector.push_back(MFGridShape(shape, rotates));
}
shapesVector = newShapesVector;
return 0;
bailout:
std::cout << "Error loading shapes";
return -1;
}
int MFGame::setRandomShapeIndex() {
srand(time(NULL));
int randomInt = rand();
int numberOfShapes = getNumberOfShapes();
int randomIndex = randomInt % (numberOfShapes + 1);
setCurrentShapeIndex(randomIndex);
return randomIndex;
}
int MFGame::getCurrentShapeDegrees() { return shapeDegrees; }
MFGridShape MFGame::getShapeAtIndex(int i) { return shapesVector.at(i); }
int MFGame::getNumberOfShapes() { return shapesVector.size(); }
#pragma mark - Misc
void MFGame::setIsUsingHotCorners(const bool& aBool) { isUsingHotCorners = aBool; }
// Loads an XML file at specifies path and returns the string
boost::shared_ptr<std::string> MFGame::loadXMLfile(std::string path)
{
std::ifstream myFile(path.c_str());
std::string xmlString;
while (! myFile.eof() )
{
std::string line;
getline(myFile, line);
xmlString.append(line+"\n");
}
myFile.close();
return boost::shared_ptr<std::string>(new std::string(xmlString));
}
std::string MFGame::getGameXMLData()
{
/*
The state of the game can be saved and transported over the network using this method.
It packs the following ivars: isGameStarted, currentPlayerIndex, winnerIndex, currentGrid and players.
From this XML data another quasi identical MFGame instance can be isntantiate with the proper constructor
*/
const int MAX_CHAR_LENGTH = 20;
char bufferChar[MAX_CHAR_LENGTH], *XMLCString;
std::string XMLString;
XMLNode xMainNode = XMLNode::createXMLTopNode("xml", TRUE), xGameNode, xGridNode, xPlayersNode;
std::vector<boost::shared_ptr<MFPlayer> >::iterator playerPtr;
xGameNode = xMainNode.addChild("game");
xGameNode.addAttribute("isGameStarted", ( getIsGameStarted() ? "0" : "1" ));
sprintf(bufferChar, "%i", getCurrentPlayerIndex());
xGameNode.addAttribute("currentPlayerIndex", bufferChar);
sprintf(bufferChar, "%i", getWinnerIndex());
xGameNode.addAttribute("winnerIndex", bufferChar);
// pack the grid
xGameNode.addChild(currentGrid.getXMLNode());
// pack the players
xPlayersNode = xGameNode.addChild("players");
for (playerPtr = players.begin(); playerPtr < players.end(); playerPtr++)
{
XMLNode xPlayerNode = xPlayersNode.addChild("player");
Color playerColor = (*playerPtr)->color;
xPlayerNode.addAttribute("name", (*playerPtr)->name.c_str());
sprintf(bufferChar, "%f", playerColor.red);
xPlayerNode.addAttribute("red", bufferChar);
sprintf(bufferChar, "%f", playerColor.green);
xPlayerNode.addAttribute("green", bufferChar);
sprintf(bufferChar, "%f", playerColor.blue);
xPlayerNode.addAttribute("blue", bufferChar);
sprintf(bufferChar, "%i", (*playerPtr)->bites);
xPlayerNode.addAttribute("bites", bufferChar);
sprintf(bufferChar, "%i", (*playerPtr)->alive);
xPlayerNode.addAttribute("alive", bufferChar);
}
XMLCString = xMainNode.createXMLString(false);
XMLString = XMLCString;
free(XMLCString);
return XMLString;
}
| 33.410448 | 143 | 0.722582 |
9b2a0aeeed97f88621425a9a0b549c20a5d110d2 | 1,065 | hpp | C++ | src/elona/serialization/std/bitset.hpp | nanbansenji/ElonaFoobar | ddbd6639db8698e89f09b2512526e855d8016e46 | [
"MIT"
] | 84 | 2018-03-03T02:44:32.000Z | 2019-07-14T16:16:24.000Z | src/elona/serialization/std/bitset.hpp | AFB111/elonafoobar | da7a3c86dd45e68e6e490fb260ead1d67c9fff5e | [
"MIT"
] | 685 | 2018-02-27T04:31:17.000Z | 2019-07-12T13:43:00.000Z | src/elona/serialization/std/bitset.hpp | nanbansenji/ElonaFoobar | ddbd6639db8698e89f09b2512526e855d8016e46 | [
"MIT"
] | 23 | 2019-07-26T08:52:38.000Z | 2021-11-09T09:21:58.000Z | #pragma once
#include <bitset>
#include "../concepts.hpp"
namespace elona::serialization
{
template <size_t N, typename Archive>
void serialize(std::bitset<N>& value, Archive& ar)
{
if constexpr (concepts::is_iarchive_v<Archive>)
{
if constexpr (N <= 32)
{
uint32_t tmp;
ar.scalar(tmp);
value = tmp;
}
else if constexpr (N <= 64)
{
uint64_t tmp;
ar.scalar(tmp);
value = tmp;
}
else
{
std::string tmp;
ar.str(tmp);
value = std::bitset<N>(tmp);
}
}
else
{
if constexpr (N <= 32)
{
uint32_t tmp = value.to_ulong();
ar.scalar(tmp);
}
else if constexpr (N <= 64)
{
uint64_t tmp = value.to_ulong();
ar.scalar(tmp);
}
else
{
std::string tmp = value.to_string();
ar.str(tmp);
}
}
}
} // namespace elona::serialization
| 18.684211 | 51 | 0.449765 |
9b2b78b9110a940be1ce88a548c6fadf5e412df8 | 6,835 | cpp | C++ | modules/sensors/dynamic_sensor/HidUtils/HidReport.cpp | lighthouse-os/hardware_libhardware | c6fa046a69d9b1adf474cf5de58318b677801e49 | [
"Apache-2.0"
] | null | null | null | modules/sensors/dynamic_sensor/HidUtils/HidReport.cpp | lighthouse-os/hardware_libhardware | c6fa046a69d9b1adf474cf5de58318b677801e49 | [
"Apache-2.0"
] | null | null | null | modules/sensors/dynamic_sensor/HidUtils/HidReport.cpp | lighthouse-os/hardware_libhardware | c6fa046a69d9b1adf474cf5de58318b677801e49 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "HidReport.h"
#include "HidDefs.h"
#include <cmath>
#include <sstream>
#include <iomanip>
namespace HidUtil {
HidReport::HidReport(uint32_t type, uint32_t data,
const HidGlobal &global, const HidLocal &local)
: mReportType(type),
mFlag(data),
mUsagePage(global.usagePage.get(0)), // default value 0
mUsage(local.getUsage(0)),
mUsageVector(local.usage),
mLogicalMin(global.logicalMin.get(0)), // default value 0
mLogicalMax(global.logicalMax.get(0)),
mReportSize(global.reportSize),
mReportCount(global.reportCount),
mPhysicalMin(global.physicalMin),
mPhysicalMax(global.physicalMax),
mExponent(global.exponent),
mUnit(global.unit),
mReportId(global.reportId) { }
std::string HidReport::getStringType() const {
return reportTypeToString(mReportType);
}
std::string HidReport::reportTypeToString(int type) {
using namespace HidDef::MainTag;
switch(type) {
case INPUT:
return "INPUT";
case OUTPUT:
return "OUTPUT";
case FEATURE:
return "FEATURE";
default:
return "<<UNKNOWN>>";
}
}
double HidReport::getExponentValue() const {
if (!mExponent.isSet()) {
return 1;
}
// default exponent is 0
int exponentInt = mExponent.get(0);
if (exponentInt > 15 || exponentInt < 0) {
return NAN;
}
return pow(10.0, static_cast<double>((exponentInt <= 7) ? exponentInt : exponentInt - 16));
}
std::string HidReport::getExponentString() const {
int exponentInt = mExponent.get(0);
if (exponentInt > 15 || exponentInt < 0) {
return "[error]";
}
return std::string("x10^")
+ std::to_string((exponentInt <= 7) ? exponentInt : exponentInt - 16);
}
std::string HidReport::getUnitString() const {
if (!mUnit.isSet()) {
return "default";
}
return "[not implemented]";
std::ostringstream ret;
ret << std::hex << std::setfill('0') << std::setw(2) << mUnit.get(0);
return ret.str();
}
std::string HidReport::getFlagString() const {
using namespace HidDef::ReportFlag;
std::string ret;
ret += (mFlag & DATA_CONST) ? "Const " : "Data ";
ret += (mFlag & ARRAY_VARIABLE) ? "Variable " : "Array ";
ret += (mFlag & WRAP) ? "Wrap " : "";
ret += (mFlag & NONLINEAR) ? "Nonlinear " : "";
ret += (mFlag & NO_PREFERRED) ? "NoPreferred " : "";
ret += (mFlag & NULL_STATE) ? "NullState " : "";
ret += (mFlag & VOLATILE) ? "Volatile " : "";
ret += (mFlag & BUFFERED_BYTES) ? "BufferedBytes " : "";
return ret;
}
// isArray() will return true for reports that may contains multiple values, e.g. keyboard scan
// code, which can have multiple value, each denoting a key pressed down at the same time. It will
// return false if repor represent a vector or matrix.
//
// This slightly deviates from HID's definition, it is more convenient this way as matrix/vector
// input is treated similarly as variables.
bool HidReport::isArray() const {
using namespace HidDef::ReportFlag;
return (mFlag & ARRAY_VARIABLE) == 0 && mIsCollapsed;
}
bool HidReport::isVariable() const {
return !isArray();
}
bool HidReport::isData() const {
using namespace HidDef::ReportFlag;
return (mFlag & DATA_CONST) == 0;
}
std::ostream& operator<<(std::ostream& os, const HidReport& h) {
os << h.getStringType() << ", "
<< "usage: " << std::hex << h.getFullUsage() << std::dec << ", ";
if (h.isData()) {
auto range = h.getLogicalRange();
os << "logMin: " << range.first << ", "
<< "logMax: " << range.second << ", ";
if (range == h.getPhysicalRange()) {
os << "phy===log, ";
} else {
range = h.getPhysicalRange();
os << "phyMin: " << range.first << ", "
<< "phyMax: " << range.second << ", ";
}
if (h.isArray()) {
os << "map: (" << std::hex;
for (auto i : h.getUsageVector()) {
os << i << ",";
}
os << "), " << std::dec;
}
os << "exponent: " << h.getExponentString() << ", "
<< "unit: " << h.getUnitString() << ", ";
} else {
os << "constant: ";
}
os << "size: " << h.getSize() << "bit x " << h.getCount() << ", "
<< "id: " << h.mReportId;
return os;
}
std::pair<int64_t, int64_t> HidReport::getLogicalRange() const {
int64_t a = mLogicalMin;
int64_t b = mLogicalMax;
if (a > b) {
// might be unsigned
a = a & ((static_cast<int64_t>(1) << getSize()) - 1);
b = b & ((static_cast<int64_t>(1) << getSize()) - 1);
if (a > b) {
// bad hid descriptor
return {0, 0};
}
}
return {a, b};
}
std::pair<int64_t, int64_t> HidReport::getPhysicalRange() const {
if (!(mPhysicalMin.isSet() && mPhysicalMax.isSet())) {
// physical range undefined, use logical range
return getLogicalRange();
}
int64_t a = mPhysicalMin.get(0);
int64_t b = mPhysicalMax.get(0);
if (a > b) {
a = a & ((static_cast<int64_t>(1) << getSize()) - 1);
b = b & ((static_cast<int64_t>(1) << getSize()) - 1);
if (a > b) {
return {0, 0};
}
}
return {a, b};
}
unsigned int HidReport::getFullUsage() const {
return mUsage | (mUsagePage << 16);
}
size_t HidReport::getSize() const {
return mReportSize;
}
size_t HidReport::getCount() const {
return mReportCount;
}
unsigned int HidReport::getUnit() const {
return mUnit.get(0); // default unit is 0 means default unit
}
unsigned HidReport::getReportId() const {
// if report id is not specified, it defaults to zero
return mReportId.get(0);
}
unsigned HidReport::getType() const {
return mReportType;
}
void HidReport::setCollapsed(uint32_t fullUsage) {
mUsage = fullUsage & 0xFFFF;
mUsagePage = fullUsage >> 16;
mIsCollapsed = true;
}
const std::vector<unsigned int>& HidReport::getUsageVector() const {
return mUsageVector;
}
} // namespace HidUtil
| 29.717391 | 98 | 0.58654 |
9b2d7bdf8175e9af1324c8529f05ebc9298df440 | 4,713 | cpp | C++ | node_modules/lzz-gyp/lzz-source/smtc_DefineLazyClass.cpp | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 3 | 2019-09-18T16:44:33.000Z | 2021-03-29T13:45:27.000Z | node_modules/lzz-gyp/lzz-source/smtc_DefineLazyClass.cpp | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | null | null | null | node_modules/lzz-gyp/lzz-source/smtc_DefineLazyClass.cpp | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 2 | 2019-03-29T01:06:38.000Z | 2019-09-18T16:44:34.000Z | // smtc_DefineLazyClass.cpp
//
#include "smtc_DefineLazyClass.h"
#include "smtc_ClassDefn.h"
#include "smtc_ClassScope.h"
#include "smtc_CreateLazyClass.h"
#include "smtc_CreateLazyClassEntity.h"
#include "smtc_CreateLazyClassScope.h"
#include "smtc_CreateMbrInit.h"
#include "smtc_CreateQualName.h"
#include "smtc_CreateTmplLazyClass.h"
#include "smtc_CreateTmplLazyClassEntity.h"
#include "smtc_DeclareLazyClassObjParamSet.h"
#include "smtc_FormTmplName.h"
#include "smtc_GetNameLoc.h"
#include "smtc_IsNameQual.h"
#include "smtc_LazyBaseSpec.h"
#include "smtc_LazyClass.h"
#include "smtc_Message.h"
#include "smtc_Ns.h"
#include "smtc_NsScope.h"
#include "smtc_ScopeVisitor.h"
#include "smtc_TmplSpecScope.h"
#include "smtc_TmplSpecToArgString.h"
#define LZZ_INLINE inline
namespace
{
using namespace smtc;
}
namespace
{
struct DefineLazyClass : ScopeVisitor
{
bool is_tmpl;
TmplSpecPtrVector & tmpl_spec_set;
gram::SpecSel const & spec_sel;
ClassKey key;
NamePtr const & name;
bool is_dll_api;
ParamPtrVector const & param_set;
bool vararg;
BaseSpecPtrVector const & base_spec_set;
ScopePtr & res_scope;
void visit (NsScope const & scope) const;
void visit (ClassScope const & scope) const;
void visit (TmplSpecScope const & scope) const;
EntityPtr buildEntity (NamePtr const & encl_qual_name = NamePtr ()) const;
public:
explicit DefineLazyClass (bool is_tmpl, TmplSpecPtrVector & tmpl_spec_set, gram::SpecSel const & spec_sel, ClassKey key, NamePtr const & name, bool is_dll_api, ParamPtrVector const & param_set, bool vararg, BaseSpecPtrVector const & base_spec_set, ScopePtr & res_scope);
~ DefineLazyClass ();
};
}
namespace smtc
{
ScopePtr defineLazyClass (ScopePtr const & scope, gram::SpecSel const & spec_sel, ClassKey key, NamePtr const & name, bool is_dll_api, ParamPtrVector const & param_set, bool vararg, BaseSpecPtrVector const & base_spec_set)
{
ScopePtr res_scope;
TmplSpecPtrVector tmpl_spec_set;
scope->accept (DefineLazyClass (false, tmpl_spec_set, spec_sel, key, name, is_dll_api, param_set, vararg, base_spec_set, res_scope));
return res_scope;
}
}
namespace
{
void DefineLazyClass::visit (NsScope const & scope) const
{
// build ns lazy class
scope.getNs ()->addEntity (buildEntity ());
}
}
namespace
{
void DefineLazyClass::visit (ClassScope const & scope) const
{
// cannot be qualified
if (isNameQual (name))
{
msg::qualClassClassDefn (getNameLoc (name));
}
// build mbr lazy class
ClassDefnPtr const & class_defn = scope.getClassDefn ();
class_defn->addEntity (buildEntity (class_defn->getQualName ()));
}
}
namespace
{
void DefineLazyClass::visit (TmplSpecScope const & scope) const
{
// declare template class
tmpl_spec_set.push_back (scope.getTmplSpec ());
scope.getParent ()->accept (DefineLazyClass (true, tmpl_spec_set, spec_sel, key, name, is_dll_api, param_set,
vararg, base_spec_set, res_scope));
}
}
namespace
{
EntityPtr DefineLazyClass::buildEntity (NamePtr const & encl_qual_name) const
{
int flags = spec_sel.getFlags ();
LazyClassPtr lazy_class = createLazyClass (flags, key, name, is_dll_api, param_set, vararg, base_spec_set);
declareLazyClassObjParamSet (lazy_class, param_set, base_spec_set);
// get qual name and entity
NamePtr qual_name;
EntityPtr entity;
if (is_tmpl)
{
qual_name = formTmplName (name, tmplSpecToArgString (tmpl_spec_set.front ()));
TmplLazyClassPtr tmpl_lazy_class = createTmplLazyClass (tmpl_spec_set, lazy_class);
entity = createTmplLazyClassEntity (tmpl_lazy_class);
}
else
{
qual_name = name;
entity = createLazyClassEntity (lazy_class);
}
if (encl_qual_name.isSet ())
{
qual_name = createQualName (encl_qual_name, qual_name);
}
lazy_class->setQualName (qual_name);
res_scope = createLazyClassScope (lazy_class);
return entity;
}
}
namespace
{
LZZ_INLINE DefineLazyClass::DefineLazyClass (bool is_tmpl, TmplSpecPtrVector & tmpl_spec_set, gram::SpecSel const & spec_sel, ClassKey key, NamePtr const & name, bool is_dll_api, ParamPtrVector const & param_set, bool vararg, BaseSpecPtrVector const & base_spec_set, ScopePtr & res_scope)
: is_tmpl (is_tmpl), tmpl_spec_set (tmpl_spec_set), spec_sel (spec_sel), key (key), name (name), is_dll_api (is_dll_api), param_set (param_set), vararg (vararg), base_spec_set (base_spec_set), res_scope (res_scope)
{}
}
namespace
{
DefineLazyClass::~ DefineLazyClass ()
{}
}
#undef LZZ_INLINE
| 34.152174 | 290 | 0.717165 |
9b2fc253f49469923daac323b0bb90353b68c7fb | 1,847 | cpp | C++ | uva/821 - Page Hopping floyed warshall .cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | 1 | 2021-11-22T02:26:43.000Z | 2021-11-22T02:26:43.000Z | uva/821 - Page Hopping floyed warshall .cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | null | null | null | uva/821 - Page Hopping floyed warshall .cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
#define MX 60
int dist[105] [105];
int main()
{
int x, y;
int n=100;
int tc=1;
int mp[105] = {0};
while(scanf("%d %d", &x, &y)==2)
{
if(x==0) break;
for(int i=1; i<=n; i++)
{
for( int j=1; j<=n; j++)
if(i!= j)
dist[i][j] = (1<<10);
}
n=2;
memset(mp, 0, sizeof mp);
mp[x]=1;
x=1;
mp[y]=2;
y=2;
dist[x][y]=1;
while(x!=0)
{
scanf("%d %d", &x, &y);
if(x==0) break;
if(!mp[x])
mp[x] = ++n;
x = mp[x];
if(!mp[y])
mp[y] = ++n;
y = mp[y];
dist[x][y]=1;
//n = max(n, max(x, y));
}
for(int k=1; k<=n; k++)
{
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
if(dist[i][k]+dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k]+dist[k][j];
}
}
}
double ans=0;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
if(dist[i][j] != (1<<10) )
{
ans+= dist[i][j];
}
//printf("i %d j %d dist %d\n", i, j, dist[i][j]);
}
}
// cout<<ans/(n*(n-1))<<endl;
// printf("nnn %d\n", n);
// printf("ans %lf n %d\n", ans, n);
printf("Case %d: average length between pages = %0.3lf clicks\n",tc++, ans/ (double)(n *(n-1)));
}
return 0;
}
| 22.802469 | 105 | 0.30157 |
9b36bf4ac6c6a7f412d25e45df5084a4df3baa41 | 530 | cc | C++ | pathtracer/src/scene_elements/serialized/lights/SpotLight.cc | bjorn-grape/bidirectional-pathtracer | 6fbbf5fc6cee39f595533494d779726658d646e1 | [
"MIT"
] | null | null | null | pathtracer/src/scene_elements/serialized/lights/SpotLight.cc | bjorn-grape/bidirectional-pathtracer | 6fbbf5fc6cee39f595533494d779726658d646e1 | [
"MIT"
] | null | null | null | pathtracer/src/scene_elements/serialized/lights/SpotLight.cc | bjorn-grape/bidirectional-pathtracer | 6fbbf5fc6cee39f595533494d779726658d646e1 | [
"MIT"
] | null | null | null | #include "SpotLight.hh"
float SpotLight::getAngle() const {
return angle_;
}
void SpotLight::setAngle(float angle) {
SpotLight::angle_ = angle;
}
const Vector3D<float> &SpotLight::getDirection() const {
return direction_;
}
void SpotLight::setDirection(const Vector3D<float> &direction) {
SpotLight::direction_ = direction;
}
const Vector3D<float> &SpotLight::getPosition() const {
return position_;
}
void SpotLight::setPosition(const Vector3D<float> &position) {
SpotLight::position_ = position;
}
| 20.384615 | 64 | 0.720755 |
9b375c34a28ab4aee9774fa54acb33fb2ebd7fa8 | 8,869 | cpp | C++ | code/utils/encoding.cpp | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 307 | 2015-04-10T13:27:32.000Z | 2022-03-21T03:30:38.000Z | code/utils/encoding.cpp | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 2,231 | 2015-04-27T10:47:35.000Z | 2022-03-31T19:22:37.000Z | code/utils/encoding.cpp | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 282 | 2015-01-05T12:16:57.000Z | 2022-03-28T04:45:11.000Z | //
//
#include "utils/encoding.h"
#include "mod_table/mod_table.h"
namespace util {
Encoding guess_encoding(const SCP_string& content, bool assume_utf8) {
if (content.size()>= 3 && !strncmp(content.c_str(), "\xEF\xBB\xBF", 3)) { // UTF-8
return Encoding::UTF8;
}
if (content.size()>= 4 && !strncmp(content.c_str(), "\x00\x00\xFE\xFF", 4)) { // UTF-32 big-endian
return Encoding::UTF32BE;
}
if (content.size()>= 4 && !strncmp(content.c_str(), "\xFF\xFE\x00\x00", 4)) { // UTF-32 little-endian
return Encoding::UTF32LE;
}
if (content.size()>= 2 && !strncmp(content.c_str(), "\xFE\xFF", 2)) { // UTF-16 big-endian
return Encoding::UTF16BE;
}
if (content.size()>= 2 && !strncmp(content.c_str(), "\xFF\xFE", 2)) { // UTF-16 little-endian
return Encoding::UTF16LE;
}
return assume_utf8 ? Encoding::UTF8 : Encoding::ASCII;
}
bool has_bom(const SCP_string& content) {
if (content.size()>= 3 && !strncmp(content.c_str(), "\xEF\xBB\xBF", 3)) { // UTF-8
return true;
}
if (content.size()>= 4 && !strncmp(content.c_str(), "\x00\x00\xFE\xFF", 4)) { // UTF-32 big-endian
return true;
}
if (content.size()>= 4 && !strncmp(content.c_str(), "\xFF\xFE\x00\x00", 4)) { // UTF-32 little-endian
return true;
}
if (content.size()>= 2 && !strncmp(content.c_str(), "\xFE\xFF", 2)) { // UTF-16 big-endian
return true;
}
if (content.size()>= 2 && !strncmp(content.c_str(), "\xFF\xFE", 2)) { // UTF-16 little-endian
return true;
}
return false;
}
int check_encoding_and_skip_bom(CFILE* file, const char* filename, int* start_offset) {
cfseek(file, 0, CF_SEEK_SET);
// Read up to 10 bytes from the file to check if there is a BOM
SCP_string probe;
auto probe_size = (size_t)std::min(10, cfilelength(file));
probe.resize(probe_size);
cfread(&probe[0], 1, (int) probe_size, file);
cfseek(file, 0, CF_SEEK_SET);
auto filelength = cfilelength(file);
if (start_offset) {
*start_offset = 0;
}
// Determine encoding. Assume UTF-8 if we are in unicode text mode
auto encoding = util::guess_encoding(probe, Unicode_text_mode);
if (Unicode_text_mode) {
if (encoding != util::Encoding::UTF8) {
//This is probably fatal, so let's abort right here and now.
Error(LOCATION,
"%s is in an Unicode/UTF format that cannot be read by FreeSpace Open. Please convert it to UTF-8\n",
filename);
}
if (util::has_bom(probe)) {
// The encoding has to be UTF-8 here so we know that the BOM is 3 Bytes long
// This makes sure that the first byte we read will be the first actual text byte.
cfseek(file, 3, SEEK_SET);
filelength -= 3;
if (start_offset) {
*start_offset = 3;
}
}
} else {
if (encoding != util::Encoding::ASCII) {
//This is probably fatal, so let's abort right here and now.
Error(LOCATION,
"%s is in Unicode/UTF format and cannot be read by FreeSpace Open without turning on Unicode mode. Please convert it to ASCII/ANSI\n",
filename);
}
}
return filelength;
}
// The following code is adapted from the uchardet library, the original licence of the file has been kept
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Universal charset detector code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Shy Shalom <shooshX@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <cstdio>
#define UDF 0 // undefined
#define OTH 1 //other
#define ASC 2 // ascii capital letter
#define ASS 3 // ascii small letter
#define ACV 4 // accent capital vowel
#define ACO 5 // accent capital other
#define ASV 6 // accent small vowel
#define ASO 7 // accent small other
#define CLASS_NUM 8 // total classes
#define FREQ_CAT_NUM 4
static const unsigned char Latin1_CharToClass[] = { OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 00 - 07
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 08 - 0F
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 10 - 17
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 18 - 1F
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 20 - 27
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 28 - 2F
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 30 - 37
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 38 - 3F
OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC, // 40 - 47
ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, // 48 - 4F
ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, // 50 - 57
ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH, // 58 - 5F
OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS, // 60 - 67
ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, // 68 - 6F
ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, // 70 - 77
ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH, // 78 - 7F
OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH, // 80 - 87
OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF, // 88 - 8F
UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // 90 - 97
OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO, // 98 - 9F
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // A0 - A7
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // A8 - AF
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // B0 - B7
OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, // B8 - BF
ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO, // C0 - C7
ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV, // C8 - CF
ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH, // D0 - D7
ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO, // D8 - DF
ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO, // E0 - E7
ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV, // E8 - EF
ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH, // F0 - F7
ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO, // F8 - FF
};
/* 0 : illegal
1 : very unlikely
2 : normal
3 : very likely
*/
static const unsigned char Latin1ClassModel[] = {
/* UDF OTH ASC ASS ACV ACO ASV ASO */
/*UDF*/ 0, 0, 0, 0, 0, 0, 0, 0,
/*OTH*/ 0, 3, 3, 3, 3, 3, 3, 3,
/*ASC*/ 0, 3, 3, 3, 3, 3, 3, 3,
/*ASS*/ 0, 3, 3, 3, 1, 1, 3, 3,
/*ACV*/ 0, 3, 3, 3, 1, 2, 1, 2,
/*ACO*/ 0, 3, 3, 3, 3, 3, 3, 3,
/*ASV*/ 0, 3, 1, 3, 1, 1, 1, 3,
/*ASO*/ 0, 3, 1, 3, 1, 1, 3, 3, };
bool guessLatin1Encoding(const char* aBuf, size_t aLen) {
char mLastCharClass = OTH;
uint32_t mFreqCounter[FREQ_CAT_NUM];
for (int i = 0; i < FREQ_CAT_NUM; i++) {
mFreqCounter[i] = 0;
}
unsigned char charClass;
unsigned char freq;
for (size_t i = 0; i < aLen; i++) {
charClass = Latin1_CharToClass[(unsigned char) aBuf[i]];
freq = Latin1ClassModel[mLastCharClass * CLASS_NUM + charClass];
if (freq == 0) {
return false;
}
mFreqCounter[freq]++;
mLastCharClass = charClass;
}
float confidence;
uint32_t total = 0;
for (int32_t i = 0; i < FREQ_CAT_NUM; i++) {
total += mFreqCounter[i];
}
if (!total) {
confidence = 0.0f;
} else {
confidence = mFreqCounter[3] * 1.0f / total;
confidence -= mFreqCounter[1] * 20.0f / total;
}
if (confidence < 0.0f) {
confidence = 0.0f;
}
return confidence > .5f;
}
}
| 35.906883 | 140 | 0.597023 |
9b37b184d2817217fb506c030d0f645051b8f56f | 4,446 | cpp | C++ | ByteCamp/Day1/l.cpp | JackBai0914/Competitive-Programming-Codebase | a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9 | [
"MIT"
] | null | null | null | ByteCamp/Day1/l.cpp | JackBai0914/Competitive-Programming-Codebase | a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9 | [
"MIT"
] | null | null | null | ByteCamp/Day1/l.cpp | JackBai0914/Competitive-Programming-Codebase | a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <ctime>
#include <vector>
using namespace std;
#define F first
#define S second
#define MP make_pair
typedef long long ll;
typedef long double ld;
typedef pair <ld, ld> Point;
const ld eps = 1e-7;
const ld ERROR = 666666;
const Point ERRORP = MP(ERROR, ERROR);
bool if_same (ld a, ld b) {
return -eps <= (a - b) && (a - b) <= eps;
}
bool if_same (Point a, Point b) {
return if_same(a.F, b.F) && if_same(a.S, b.S);
}
struct Line {
ld a, b, c;
Line() {}
Line(ld A, ld B, ld C) {a = A, b = B, c = C;}
Point on_Line (ld x) {
return MP(x, -(c + a * x) / b);
}
Point on_Line_y (ld y) {
return MP(-(c + b * y) / a, y);
}
bool if_on (Point x) {
return if_same (0, a * x.F + b * x.S + c);
}
}l[22];
Point cross_point (Line A, Line B) {
// cerr << "calc cp: " << A.a << " " << A.b << " " << A.c << " , " << B.a << " " << B.b << " " << B.c << endl;
if (if_same(0, A.a * B.b - B.a * A.b))
return ERRORP;
return A.on_Line ((B.c * A.b - A.c * B.b) / (A.a * B.b - B.a * A.b));
}
struct Curve {
ld a, b, c; //ax^2+bx+c;
Curve () {}
Curve (ld aa, ld bb, ld cc) {a = aa, b = bb, c = cc;}
ld delta() {
ld ans = b*b-4*a*c;
if (if_same(ans, 0))
return 0;
return ans;
}
Point find_zero () {
if (delta() < 0 - eps)
return ERRORP;
return MP((-b-sqrt(delta()))/(2*a), (-b+sqrt(delta()))/(2*a));
}
};
struct Hypo {
ld q0, q1, q2, q3, q4, q5;
Point subs(bool tp, ld a, ld b) {
if (tp == 0) { // x
Curve c = Curve(q0 * a * a + q1 * a + q2, q0 * 2 * a * b + q1 * b + q3 * a + q4, q0 * b * b + q3 * b + q5);
return c.find_zero();
}
else {
Curve c = Curve(q2 * a * a + q1 * a + q0, q2 * 2 * a * b + q1 * b + q4 * a + q3, q2 * b * b + q4 * b + q5);
return c.find_zero();
}
}
ld delta () {return q1*q1-q0*q2;}
bool if_on (Point p) {
return if_same (0, q0 * p.F * p.F + q1 * p.F * p.S + q2 * p.S * p.S + q3 * p.F + q4 * p.S + q5);
}
}h;
vector <Point> cps;
int n;
int e_num[22];
bool fake[22];
int main() {
ios::sync_with_stdio(false);
//freopen("1.in", "r", stdin);
//freopen("1.out", "w", stdout);
cin >> n;
cin >> h.q0 >> h.q1 >> h.q2 >> h.q3 >> h.q4 >> h.q5;
for (int i = 1; i <= n; i ++) {
cin >> l[i].a >> l[i].b >> l[i].c;
for (int j = 1; j < i; j ++) {
if (if_same(0, l[i].a)) {
if (if_same(0, l[j].a))
continue ;
if (if_same(l[i].c / l[i].b, l[j].c / l[j].b)) {
fake[i] = true;
break;
}
}
else {
if (if_same(0, l[j].a))
continue ;
ld X1 = l[i].c / l[i].a;
ld Y1 = l[i].b / l[i].a;
ld X2 = l[j].c / l[j].a;
ld Y2 = l[j].b / l[j].a;
if (if_same(X1, X2) && if_same (Y1, Y2)) {
fake[i] = true;
break;
}
}
}
// cerr << i << " : " << fake[i] << endl;
}
for (int i = 1; i <= n; i ++)
for (int j = i + 1; j <= n; j ++) {
if (fake[i] || fake[j])
continue ;
Point cp = cross_point(l[i], l[j]);
if (cp != ERRORP) {
// cerr << "LL cp : " << cp.F << " " << cp.S << endl;
cps.push_back(cp);
}
}
for (int i = 1; i <= n; i ++) {
if (fake[i])
continue ;
if (h.delta() > 0 + eps) {
if ()
}
if (if_same(0, l[i].a)) {
Point cp = h.subs(1, 0, -l[i].c / l[i].b);
if (cp != ERRORP) {
cps.push_back(l[i].on_Line(cp.F));
cps.push_back(l[i].on_Line(cp.S));
}
}
else {
Point cp = h.subs(0, -l[i].b / l[i].a, -l[i].c / l[i].a);
if (cp != ERRORP) {
// cerr << "LH cp: " << cp.F << " " << cp.S << endl;
cps.push_back(l[i].on_Line_y(cp.F));
cps.push_back(l[i].on_Line_y(cp.S));
}
}
}
int p_num = 0;
sort (cps.begin(), cps.end());
for (int i = 0; i < cps.size(); i ++) {
if (i && if_same (cps[i], cps[i - 1]))
continue ;
// cerr << "a cp: " << cps[i].F << " " << cps[i].S << endl;
p_num ++;
for (int j = 1; j <= n; j ++)
if (l[j].if_on(cps[i]))
e_num[j] ++;
if (h.if_on(cps[i]))
e_num[0] ++;
}
// for (int i = 0; i <= n; i ++)
// cerr << i << " : " << e_num[i] << endl;
//v-e+f=1
int fans = 1;
for (int i = 1; i <= n; i ++) {
if (fake[i])
continue ;
fans += e_num[i] + 1;
}
fans -= p_num;
if (if_same (0, h.delta())) {
// cerr << "should be here " << endl;
fans += e_num[0] + 1;
}
else if (h.delta() < 0) {
if (e_num[0] == 0) fans ++;
else fans += e_num[0];
}
else if (h.delta() > 0) {
fans += e_num[0] + 2;
}
cout << fans << endl;
return 0;
} | 22.683673 | 111 | 0.468961 |
9b3addf69baf6396826baea1132848c4bea1126f | 353 | cpp | C++ | Artemis/Source/Graphics/Artemis.Graphics.cpp | NoriyukiHiromoto/TinyGameEngine | ea683db3d498c1b8df91930a262a4c50a4e69b82 | [
"MIT"
] | null | null | null | Artemis/Source/Graphics/Artemis.Graphics.cpp | NoriyukiHiromoto/TinyGameEngine | ea683db3d498c1b8df91930a262a4c50a4e69b82 | [
"MIT"
] | null | null | null | Artemis/Source/Graphics/Artemis.Graphics.cpp | NoriyukiHiromoto/TinyGameEngine | ea683db3d498c1b8df91930a262a4c50a4e69b82 | [
"MIT"
] | null | null | null | //----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
#include "Artemis.Local.hpp"
#include "Artemis.Graphics.hpp"
#if defined(ATS_API_DIRECTX11)
#include "Platform/Artemis.Graphics.directx11.cpp"
#endif//defined(ATS_API_DIRECTX11)
| 35.3 | 85 | 0.407932 |
9b3cc3cd55dd4d87adcbf4cab59dd62587a51248 | 3,360 | cpp | C++ | GraphAlgorithms/Monsters.cpp | su050300/CSES-Problemset-Solutions | 292281f9ac3c57c21c8208b30087386c29238d17 | [
"MIT"
] | 2 | 2021-02-05T04:21:42.000Z | 2021-02-10T14:24:38.000Z | GraphAlgorithms/Monsters.cpp | su050300/CSES-Problemset-Solutions | 292281f9ac3c57c21c8208b30087386c29238d17 | [
"MIT"
] | null | null | null | GraphAlgorithms/Monsters.cpp | su050300/CSES-Problemset-Solutions | 292281f9ac3c57c21c8208b30087386c29238d17 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
vector<vector<char>>v(n,vector<char>(m));
vector<vector<int>>poss(n,vector<int>(m,-1));
queue<pair<int,int>>q;
int xi,yi;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>v[i][j];
if(v[i][j]=='M')
{
q.push({i,j});
poss[i][j]=0;
}
if(v[i][j]=='A')
{
xi=i,yi=j;
}
}
}
vector<vector<int>>visited(n,vector<int>(m));
vector<pair<int,int>>pos={{1,0},{0,1},{-1,0},{0,-1}};
vector<char>pat={'D','R','U','L'};
while(!q.empty())
{
pair<int,int>d=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int x=pos[i].first+d.first;
int y=pos[i].second+d.second;
if(x>=0&&x<n&&y>=0&&y<m&&!visited[x][y]&&v[x][y]=='.')
{
visited[x][y]=1;
q.push({x,y});
poss[x][y]=poss[d.first][d.second]+1;
}
// else if(x>=0&&x<n&&y>=0&&y<m&&v[x][y]=='.')
// {
// poss[x][y]=min(poss[x][y],poss[d.first][d.second]);
// }
}
}
q.push({xi,yi});
vector<vector<int>>vis(n,vector<int>(m));
vector<vector<int>>posss(n,vector<int>(m,-1));
vector<vector<char>>path(n,vector<char>(m));
posss[xi][yi]=0;
vis[xi][yi]=1;
if(poss[xi][yi]!=-1)
{
cout<<"NO"<<endl;
return 0;
}
while(!q.empty())
{
pair<int,int>d=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int x=d.first+pos[i].first;
int y=d.second+pos[i].second;
if(x>=0&&x<n&&y>=0&&y<m&&!vis[x][y]&&v[x][y]=='.')
{
vis[x][y]=1;
if(poss[x][y]!=-1&&poss[x][y]<=posss[d.first][d.second]+1)
{
continue;
}
posss[x][y]=posss[d.first][d.second]+1;
q.push({x,y});
path[x][y]=pat[i];
}
}
}
int selx=-1,sely=-1;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
// cout<<posss[i][j]<<" ";
if(i==0||j==0||i==n-1||j==m-1)
{
if((v[i][j]=='.'||v[i][j]=='A')&&posss[i][j]!=-1)
{
selx=i,sely=j;
break;
}
}
}
// cout<<endl;
}
if(selx==-1&&sely==-1)
{
cout<<"NO"<<endl;
}
else
{
cout<<"YES"<<endl;
vector<char>res;
path[xi][yi]='F';
while(path[selx][sely]!='F')
{
// cout<<selx<<" "<<sely<<endl;
res.push_back(path[selx][sely]);
if(path[selx][sely]=='L')
{
sely+=1;
}
else if(path[selx][sely]=='R')
{
sely-=1;
}
else if(path[selx][sely]=='U')
{
selx+=1;
}
else
{
selx-=1;
}
}
reverse(res.begin(),res.end());
cout<<res.size()<<endl;
for(char d:res)
{
cout<<d;
}
}
return 0;
} | 24.347826 | 73 | 0.344048 |
9b3e2593d9ff36628dfe296383a498755d0df0e7 | 3,595 | cpp | C++ | src/main.cpp | shouxieai/kiwi-rknn | 55c1a4ae2b664acf564b1218728b6ed85b9713aa | [
"MIT"
] | 8 | 2022-03-02T08:51:21.000Z | 2022-03-23T13:24:11.000Z | src/main.cpp | shouxieai/kiwi-rknn | 55c1a4ae2b664acf564b1218728b6ed85b9713aa | [
"MIT"
] | 3 | 2022-03-15T02:40:14.000Z | 2022-03-29T03:25:17.000Z | src/main.cpp | shouxieai/kiwi-rknn | 55c1a4ae2b664acf564b1218728b6ed85b9713aa | [
"MIT"
] | 3 | 2022-03-03T07:46:21.000Z | 2022-03-14T08:32:45.000Z | #include <stdio.h>
#include <thread>
#include <opencv2/opencv.hpp>
#include "kiwi-logger.hpp"
#include "kiwi-app-nanodet.hpp"
#include "kiwi-app-scrfd.hpp"
#include "kiwi-app-arcface.hpp"
#include "kiwi-infer-rknn.hpp"
using namespace cv;
using namespace std;
void test_pref(const char* model){
// 测试性能启用sync mode目的是尽可能的利用npu。实际使用如果无法掌握sync mode,尽量别用
// 你会发现sync mode的耗时会是非这个模式的80%左右,性能有提升,这与你实际推理时有区别,注意查看
auto infer = rknn::load_infer(model, true);
infer->forward();
auto tic = kiwi::timestamp_now_float();
for(int i = 0; i < 100; ++i){
infer->forward();
}
auto toc = kiwi::timestamp_now_float();
INFO("%s avg time: %f ms", model, (toc - tic) / 100);
}
void scrfd_demo(){
auto infer = scrfd::create_infer("scrfd_2.5g_bnkps.rknn", 0.4, 0.5);
auto image = cv::imread("faces.jpg");
auto box_result = infer->commit(image).get();
auto tic = kiwi::timestamp_now_float();
for(int i = 0; i < 100; ++i){
infer->commit(image).get();
}
auto toc = kiwi::timestamp_now_float();
INFO("scrfd time: %f ms", (toc - tic) / 100);
for(auto& obj : box_result){
cv::rectangle(image, cv::Point(obj.left, obj.top), cv::Point(obj.right, obj.bottom), cv::Scalar(0, 255, 0), 2);
auto pl = obj.landmark;
for(int i = 0; i < 5; ++i, pl += 2){
cv::circle(image, cv::Point(pl[0], pl[1]), 3, cv::Scalar(0, 0, 255), -1, 16);
}
}
cv::imwrite("scrfd-result.jpg", image);
}
void nanodet_demo(){
auto infer = nanodet::create_infer("person_m416_plus_V15.rknn", 0.4, 0.5);
auto image = cv::imread("faces.jpg");
auto box_result = infer->commit(image).get();
auto tic = kiwi::timestamp_now_float();
for(int i = 0; i < 100; ++i){
infer->commit(image).get();
}
auto toc = kiwi::timestamp_now_float();
INFO("nanodet time: %f ms", (toc - tic) / 100);
for(auto& obj : box_result){
cv::rectangle(image, cv::Point(obj.left, obj.top), cv::Point(obj.right, obj.bottom), cv::Scalar(0, 255, 0), 2);
}
cv::imwrite("nanodet-result.jpg", image);
}
void arcface_demo(){
auto det = scrfd::create_infer("scrfd_2.5g_bnkps.rknn", 0.4, 0.5);
auto ext = arcface::create_infer("w600k_r50_new.rknn");
auto a = cv::imread("library/2ys3.jpg");
auto b = cv::imread("library/male.jpg");
auto c = cv::imread("library/2ys5.jpg");
auto compute_sim = [](const cv::Mat& a, const cv::Mat& b){
auto c = cv::Mat(a * b.t());
return *c.ptr<float>(0);
};
auto extract_feature = [&](const cv::Mat& image){
auto faces = det->commit(image).get();
if(faces.empty()){
INFOE("Can not detect any face");
return cv::Mat();
}
auto max_face = std::max_element(faces.begin(), faces.end(), [](kiwi::Face& a, kiwi::Face& b){
return (a.right - a.left) * (a.bottom - a.top) > (b.right - b.left) * (b.bottom - b.top);
});
auto out = arcface::face_alignment(image, max_face->landmark);
return ext->commit(out, true).get();
};
auto fa = extract_feature(a);
auto fb = extract_feature(b);
auto fc = extract_feature(c);
float ab = compute_sim(fa, fb);
float ac = compute_sim(fa, fc);
float bc = compute_sim(fb, fc);
INFO("ab[differ] = %f, ac[same] = %f, bc[differ] = %f", ab, ac, bc);
}
int main(){
test_pref("person_m416_plus_V15.rknn");
test_pref("scrfd_2.5g_bnkps.rknn");
test_pref("w600k_r50_new.rknn");
// scrfd_demo();
// nanodet_demo();
arcface_demo();
return 0;
} | 30.726496 | 119 | 0.59249 |
9b41b65dac7fc919f5d55dae818426899396d8ba | 22 | cpp | C++ | src/DlibDotNet.Native/dlib/image_saver/save_jpeg.cpp | ejoebstl/DlibDotNet | 47436a573c931fc9c9107442b10cf32524805378 | [
"MIT"
] | 387 | 2017-10-14T23:08:59.000Z | 2022-03-28T05:26:44.000Z | src/DlibDotNet.Native/dlib/image_saver/save_jpeg.cpp | ejoebstl/DlibDotNet | 47436a573c931fc9c9107442b10cf32524805378 | [
"MIT"
] | 246 | 2017-10-09T11:40:20.000Z | 2022-03-22T08:04:08.000Z | src/DlibDotNet.Native/dlib/image_saver/save_jpeg.cpp | ejoebstl/DlibDotNet | 47436a573c931fc9c9107442b10cf32524805378 | [
"MIT"
] | 113 | 2017-10-18T12:04:53.000Z | 2022-03-28T09:05:27.000Z | #include "save_jpeg.h" | 22 | 22 | 0.772727 |
9b48d5e4e8a9a8f65d4e01e68adc6cfac40bc6dc | 4,261 | hpp | C++ | mllib/LogisticRegression.hpp | Christina-hshi/Boosting-with-Husky | 1744f0c90567a969d3e50d19f27f358f5865d2f6 | [
"Apache-2.0"
] | 1 | 2019-01-23T02:10:10.000Z | 2019-01-23T02:10:10.000Z | mllib/LogisticRegression.hpp | Christina-hshi/Boosting-with-Husky | 1744f0c90567a969d3e50d19f27f358f5865d2f6 | [
"Apache-2.0"
] | null | null | null | mllib/LogisticRegression.hpp | Christina-hshi/Boosting-with-Husky | 1744f0c90567a969d3e50d19f27f358f5865d2f6 | [
"Apache-2.0"
] | null | null | null | /*
Edit by Christina
*/
#pragma once
#include <limits>
#include "mllib/Utility.hpp"
#include "mllib/Instances.hpp"
#include "lib/aggregator_factory.hpp"
#include "mllib/Classifier.hpp"
namespace husky{
namespace mllib{
/*
MODE
GLOBAL: global training
LOCAL: training using local data
*/
enum class MODE {GLOBAL=0, LOCAL=1};
class LogisticRegression : public Classifier{
private:
matrix_double param_matrix;//parameter matrix
int max_iter; //Maximun iterations|pass through the data, default:5
double eta0; //The initial learning rate. The default value is 1.
double alpha; //Constant that multuplies the regularization term, defualt: 0.0001.
double trival_improve_th; //If weighted squared error improve is less than trival_improve_th, then this improve is trival.
int max_trival_improve_iter; //If there are max_trival_improve_iter sequential iteration with trival_improve, then training will be stopped.
MODE mode; //default: GLOBAL
int class_num; //default: 2
/*
Default settings
maximize conditional log likelihood
gradient descent update rule
L2 penalty (least squares of 'param_vec'), a regularizer
invscaling learning_rate : eta = eta0/pow(t, 0.5) NOTE: learning rate will only be updated when the loss increases, at the same time t will be increased by 1.
*/
/* Variables for extension
std::string loss;//The loss function to be used. Defaults to "squared_loss". Only "Squared loss" is implemented in this stage.
std::string penalty; //The penalty to be used. Defaults to "L2", second norm of 'param_vec', which is a standard regularizer.
std::string learning_rate; //Type of learning rate to be used. Options include (1)'constant': eta = eta0;(2)'invscaling': eta = eta0/pow(t, 0.5);
*/
public:
LogisticRegression(){
//default parameters
max_iter = 5;
eta0 = 1;
alpha = 0.0001;
trival_improve_th = 0.001;
max_trival_improve_iter = 100;
mode = MODE::GLOBAL;
class_num = 2;
}
LogisticRegression(int m_iter, double e0, double al, double trival_im, double max_trival_im, MODE m, int classNum) : max_iter(m_iter), eta0(e0), alpha(al), trival_improve_th(trival_im), max_trival_improve_iter(max_trival_im), mode(m), class_num(classNum){}
/*
train a logistic regression model with even weighted instances.
*/
void fit(const Instances& instances);
/*
train model in global or local mode.
*/
void local_fit(const Instances& instances);
void global_fit(const Instances& instances);
void local_fit(const Instances& instances, std::string instance_weight_name);
void global_fit(const Instances& instances, std::string instance_weight_name);
/*
train a logistic regression model using instance weight, which is specified as a attribute list of original_instances, name of which is 'instance_weight_name'.
*/
void fit(const Instances& instances, std::string instance_weight_name);
AttrList<Instance, Prediction>& predict(const Instances& instances,std::string prediction_name="prediction");
Classifier* clone(int seed=0){
return new LogisticRegression(this->max_iter, this->eta0, this->alpha, this->trival_improve_th, this->max_trival_improve_iter, this->mode, this->class_num);
}
matrix_double get_parameters(){
return param_matrix;
}
};
}
}
| 45.817204 | 273 | 0.574513 |
9b494df3b5e60407052fe5b8a93ae58a3c4bab6a | 565 | hpp | C++ | include/MemeCore/TestRequest.hpp | Gurman8r/CppSandbox | a0f1cf0ade69ecaba4d167c0611a620914155e53 | [
"MIT"
] | null | null | null | include/MemeCore/TestRequest.hpp | Gurman8r/CppSandbox | a0f1cf0ade69ecaba4d167c0611a620914155e53 | [
"MIT"
] | null | null | null | include/MemeCore/TestRequest.hpp | Gurman8r/CppSandbox | a0f1cf0ade69ecaba4d167c0611a620914155e53 | [
"MIT"
] | null | null | null | #ifndef _ML_REQUEST_HPP_
#define _ML_REQUEST_HPP_
#include <MemeCore/IRequest.hpp>
namespace ml
{
/* * * * * * * * * * * * * * * * * * * * */
class ML_CORE_API TestRequest
: public IRequest
{
public:
using LogFunc = void(*)(const ml::String &);
public:
TestRequest();
~TestRequest();
public:
void setValue(int32_t value);
void setFunc(LogFunc value);
public:
void process() override;
void finish() override;
private:
int32_t m_value;
LogFunc m_func;
};
/* * * * * * * * * * * * * * * * * * * * */
}
#endif // !_ML_REQUEST_HPP_ | 15.694444 | 46 | 0.59469 |
9b4d06272898ff03d5b0622f8eb060b9d8371e03 | 6,505 | cc | C++ | src/modular/lib/modular_config/modular_config.cc | dahlia-os/fuchsia-pine64-pinephone | 57aace6f0b0bd75306426c98ab9eb3ff4524a61d | [
"BSD-3-Clause"
] | 14 | 2020-10-25T05:48:36.000Z | 2021-09-20T02:46:20.000Z | src/modular/lib/modular_config/modular_config.cc | DamieFC/fuchsia | f78a4a1326f4a4bb5834500918756173c01bab4f | [
"BSD-2-Clause"
] | 1 | 2022-01-14T23:38:40.000Z | 2022-01-14T23:38:40.000Z | src/modular/lib/modular_config/modular_config.cc | DamieFC/fuchsia | f78a4a1326f4a4bb5834500918756173c01bab4f | [
"BSD-2-Clause"
] | 4 | 2020-12-28T17:04:45.000Z | 2022-03-12T03:20:44.000Z | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/modular/lib/modular_config/modular_config.h"
#include <fcntl.h>
#include <lib/syslog/cpp/macros.h>
#include <rapidjson/document.h>
#include <rapidjson/error/en.h>
#include "src/lib/files/directory.h"
#include "src/lib/files/file.h"
#include "src/lib/files/path.h"
#include "src/lib/fxl/strings/substitute.h"
#include "src/modular/lib/fidl/clone.h"
#include "src/modular/lib/fidl/json_xdr.h"
#include "src/modular/lib/modular_config/modular_config_constants.h"
#include "src/modular/lib/modular_config/modular_config_xdr.h"
// Flags passed to RapidJSON that control JSON parsing behavior.
// This is used to enable parsing non-standard JSON syntax, like comments.
constexpr unsigned kModularConfigParseFlags = rapidjson::kParseCommentsFlag;
namespace modular {
namespace {
rapidjson::Document GetSectionAsDoc(const rapidjson::Document& doc,
const std::string& section_name) {
rapidjson::Document section_doc;
auto config_json = doc.FindMember(section_name);
if (config_json != doc.MemberEnd()) {
section_doc.CopyFrom(config_json->value, section_doc.GetAllocator());
} else {
// |section_name| was not found; return an empty object
section_doc.SetObject();
}
return section_doc;
}
std::string StripLeadingSlash(std::string str) {
if (str.find("/") == 0)
return str.substr(1);
return str;
}
} // namespace
fit::result<fuchsia::modular::session::ModularConfig, std::string> ParseConfig(
std::string_view config_json) {
rapidjson::Document doc;
doc.Parse<kModularConfigParseFlags>(config_json.data(), config_json.length());
if (doc.HasParseError()) {
auto error = std::stringstream();
error << "Failed to parse JSON: " << rapidjson::GetParseError_En(doc.GetParseError()) << " ("
<< doc.GetErrorOffset() << ")";
return fit::error(error.str());
}
fuchsia::modular::session::ModularConfig config;
if (!XdrRead(&doc, &config, XdrModularConfig)) {
return fit::error("Failed to read JSON as Modular configuration (does not follow schema?)");
}
return fit::ok(std::move(config));
}
// Returns the default Modular configuration.
fuchsia::modular::session::ModularConfig DefaultConfig() {
rapidjson::Document doc;
doc.SetObject();
fuchsia::modular::session::ModularConfig config;
auto ok = XdrRead(&doc, &config, XdrModularConfig);
FX_DCHECK(ok);
return config;
}
std::string ConfigToJsonString(const fuchsia::modular::session::ModularConfig& config) {
std::string json;
auto config_copy = CloneStruct(config);
XdrWrite(&json, &config_copy, XdrModularConfig);
return json;
}
ModularConfigReader::ModularConfigReader(fbl::unique_fd dir_fd) {
FX_CHECK(dir_fd.get() >= 0);
// 1. Figure out where the config file is.
std::string config_path = files::JoinPath(StripLeadingSlash(modular_config::kOverriddenConfigDir),
modular_config::kStartupConfigFilePath);
if (!files::IsFileAt(dir_fd.get(), config_path)) {
config_path = files::JoinPath(StripLeadingSlash(modular_config::kDefaultConfigDir),
modular_config::kStartupConfigFilePath);
}
// 2. Read the file
std::string config;
if (!files::ReadFileToStringAt(dir_fd.get(), config_path, &config)) {
FX_LOGS(ERROR) << "Failed to read file: " << config_path;
UseDefaults();
return;
}
// 3. Parse the JSON
ParseConfig(config, config_path);
}
ModularConfigReader::ModularConfigReader(std::string config) {
constexpr char kPathForErrorStrings[] = ".";
ParseConfig(config, kPathForErrorStrings);
}
// static
ModularConfigReader ModularConfigReader::CreateFromNamespace() {
return ModularConfigReader(fbl::unique_fd(open("/", O_RDONLY)));
}
// static
std::string ModularConfigReader::GetOverriddenConfigPath() {
return files::JoinPath(StripLeadingSlash(modular_config::kOverriddenConfigDir),
modular_config::kStartupConfigFilePath);
}
// static
bool ModularConfigReader::OverriddenConfigExists() {
return files::IsFile(GetOverriddenConfigPath());
}
void ModularConfigReader::ParseConfig(const std::string& config, const std::string& config_path) {
rapidjson::Document doc;
doc.Parse<kModularConfigParseFlags>(config);
if (doc.HasParseError()) {
FX_LOGS(ERROR) << "Failed to parse " << config_path << ": "
<< rapidjson::GetParseError_En(doc.GetParseError()) << " ("
<< doc.GetErrorOffset() << ")";
UseDefaults();
return;
}
// Parse the `basemgr` and `sessionmgr` sections out of the config.
rapidjson::Document basemgr_doc = GetSectionAsDoc(doc, modular_config::kBasemgrConfigName);
rapidjson::Document sessionmgr_doc = GetSectionAsDoc(doc, modular_config::kSessionmgrConfigName);
if (!XdrRead(&basemgr_doc, &basemgr_config_, XdrBasemgrConfig)) {
FX_LOGS(ERROR) << "Unable to parse 'basemgr' from " << config_path;
}
if (!XdrRead(&sessionmgr_doc, &sessionmgr_config_, XdrSessionmgrConfig)) {
FX_LOGS(ERROR) << "Unable to parse 'sessionmgr' from " << config_path;
}
}
void ModularConfigReader::UseDefaults() {
rapidjson::Document doc;
doc.SetObject();
XdrRead(&doc, &basemgr_config_, XdrBasemgrConfig);
XdrRead(&doc, &sessionmgr_config_, XdrSessionmgrConfig);
}
fuchsia::modular::session::BasemgrConfig ModularConfigReader::GetBasemgrConfig() const {
fuchsia::modular::session::BasemgrConfig result;
basemgr_config_.Clone(&result);
return result;
}
fuchsia::modular::session::SessionmgrConfig ModularConfigReader::GetSessionmgrConfig() const {
fuchsia::modular::session::SessionmgrConfig result;
sessionmgr_config_.Clone(&result);
return result;
}
// static
std::string ModularConfigReader::GetConfigAsString(
fuchsia::modular::session::BasemgrConfig* basemgr_config,
fuchsia::modular::session::SessionmgrConfig* sessionmgr_config) {
std::string basemgr_json;
std::string sessionmgr_json;
XdrWrite(&basemgr_json, basemgr_config, XdrBasemgrConfig);
XdrWrite(&sessionmgr_json, sessionmgr_config, XdrSessionmgrConfig);
return fxl::Substitute(R"({
"$0": $1,
"$2": $3
})",
modular_config::kBasemgrConfigName, basemgr_json,
modular_config::kSessionmgrConfigName, sessionmgr_json);
}
} // namespace modular
| 33.188776 | 100 | 0.713605 |
9b4ea9f0b2be8e91eb8e1e8c5ad918940e0471a0 | 8,771 | cc | C++ | tce/src/applibs/ProGe/Netlist.cc | kanishkan/tce | 430e764b4d43f46bd1dc754aeb1d5632fc742110 | [
"MIT"
] | 74 | 2015-10-22T15:34:10.000Z | 2022-03-25T07:57:23.000Z | tce/src/applibs/ProGe/Netlist.cc | kanishkan/tce | 430e764b4d43f46bd1dc754aeb1d5632fc742110 | [
"MIT"
] | 79 | 2015-11-19T09:23:08.000Z | 2022-01-12T14:15:16.000Z | tce/src/applibs/ProGe/Netlist.cc | kanishkan/tce | 430e764b4d43f46bd1dc754aeb1d5632fc742110 | [
"MIT"
] | 38 | 2015-11-17T10:12:23.000Z | 2022-03-25T07:57:24.000Z | /*
Copyright (c) 2002-2009 Tampere University.
This file is part of TTA-Based Codesign Environment (TCE).
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.
*/
/**
* @file Netlist.cc
*
* Implementation of the Netlist class.
*
* @author Lasse Laasonen 2005 (lasse.laasonen-no.spam-tut.fi)
* @author Otto Esko 2010 (otto.esko-no.spam-tut.fi)
* @note rating: red
*/
#include <cstdlib>
#include <string>
#include "Netlist.hh"
#include "NetlistPort.hh"
#include "NetlistBlock.hh"
#include "MapTools.hh"
#include "Application.hh"
#include "Conversion.hh"
namespace ProGe {
const std::string Netlist::INVERTER_MODULE = "util_inverter";
const std::string Netlist::INVERTER_INPUT = "data_in";
const std::string Netlist::INVERTER_OUTPUT = "data_out";
/**
* The constructor.
*/
Netlist::Netlist() : coreEntityName_("") {
}
/**
* The destructor.
*/
Netlist::~Netlist() {
}
/**
* Partially connects two netlist ports.
*
* Connects two given subsets of bits of two netlist ports. The bit subsets
* have equal cardinality and represent an ordered range of adjacent bits.
* The bits are connected in the same order (the first bit of the subset of
* the first port is connected to the first bit of the subset of the second
* port).
*
* @param port1 The first port to connect.
* @param port2 The second port to connect.
* @param port1FirstBit The first bit of the first port to connect.
* @param port2FirstBit The first bit of the second port to connect.
* @param width The width of the connection.
*/
void
Netlist::connectPorts(
NetlistPort& port1,
NetlistPort& port2,
int port1FirstBit,
int port2FirstBit,
int width) {
size_t port1Descriptor = descriptor(port1);
size_t port2Descriptor = descriptor(port2);
// create first edge
PortConnectionProperty property1(
port1FirstBit, port2FirstBit, width);
boost::add_edge(port1Descriptor, port2Descriptor, property1, *this);
// create the opposite edge
PortConnectionProperty property2(
port2FirstBit, port1FirstBit, width);
boost::add_edge(port2Descriptor, port1Descriptor, property2, *this);
}
/**
* Connects two netlist ports completely.
*
* Each bit of the first port is connected to a bit of the second port. The
* bits are connected in the same order (the first bit of the first port is
* connected to the first bit of the second port).
*
* @param port1 The first port to connect.
* @param port2 The second port to connect.
*/
void
Netlist::connectPorts(
NetlistPort& port1,
NetlistPort& port2) {
size_t port1Descriptor = descriptor(port1);
size_t port2Descriptor = descriptor(port2);
PortConnectionProperty property;
// create first edge
boost::add_edge(port1Descriptor, port2Descriptor, property, *this);
// create the opposite edge
boost::add_edge(port2Descriptor, port1Descriptor, property, *this);
}
/**
* TODO: partial connection version and support BIT_VECTOR length > 1
*/
void
Netlist::connectPortsInverted(
NetlistPort& input,
NetlistPort& output) {
std::string instance = input.name() + "_" + INVERTER_MODULE;
NetlistBlock* inverter =
new NetlistBlock(INVERTER_MODULE, instance, *this);
NetlistPort* inverterInput =
new NetlistPort(INVERTER_INPUT, "1", 1, ProGe::BIT, HDB::IN,
*inverter);
NetlistPort* inverterOutput =
new NetlistPort(INVERTER_OUTPUT, "1", 1, ProGe::BIT, HDB::OUT,
*inverter);
this->topLevelBlock().addSubBlock(inverter);
this->connectPorts(input, *inverterInput, 0, 0, 1);
this->connectPorts(output, *inverterOutput, 0, 0 ,1);
}
/**
* Tells whether the netlist port is connected in this netlist instance
*
* @param port The netlist port
* @return True if port is connected
*/
bool
Netlist::isPortConnected(const NetlistPort& port) const {
size_t vertDesc = descriptor(port);
boost::graph_traits<Netlist>::degree_size_type edges =
boost::out_degree(vertDesc, *this);
return edges != 0;
}
/**
* Tells whether the netlist is empty.
*
* @return True if the netlist is empty, otherwise false.
*/
bool
Netlist::isEmpty() const {
return boost::num_vertices(*this) == 0;
}
/**
* Returns the top-level block in the netlist.
*
* @return The top-level block.
* @exception InstanceNotFound If the netlist is empty.
*/
NetlistBlock&
Netlist::topLevelBlock() const {
if (isEmpty()) {
throw InstanceNotFound(__FILE__, __LINE__, __func__);
}
boost::graph_traits<Netlist>::vertex_iterator iter =
boost::vertices(*this).first;
size_t vertexDescriptor = *iter;
NetlistPort* port = (*this)[vertexDescriptor];
NetlistBlock* block = port->parentBlock();
while (block->hasParentBlock()) {
block = &block->parentBlock();
}
return *block;
}
/**
* Maps the given descriptor for the given port.
*
* This method does not need to be called by clients.
*
* @param port The port.
* @param descriptor The descriptor.
*/
void
Netlist::mapDescriptor(const NetlistPort& port, size_t descriptor) {
assert(!MapTools::containsKey(vertexDescriptorMap_, &port));
vertexDescriptorMap_.insert(
std::pair<const NetlistPort*, size_t>(&port, descriptor));
}
/**
* Returns descriptor for the given port.
*
* @return Descriptor for the given port.
*/
size_t
Netlist::descriptor(const NetlistPort& port) const {
assert(MapTools::containsKey(vertexDescriptorMap_, &port));
return MapTools::valueForKey<size_t>(vertexDescriptorMap_, &port);
}
/**
* Adds a parameter for the netlist.
*
* If the netlist already has a parameter with the given name, it is replaced
* by the new parameter.
*
* @param name Name of the parameter.
* @param type Type of the parameter.
* @param value Value of the parameter.
*/
void
Netlist::setParameter(
const std::string& name,
const std::string& type,
const std::string& value) {
if (hasParameter(name)) {
removeParameter(name);
}
Parameter param = {name, type, value};
parameters_.push_back(param);
}
/**
* Removes the given parameter from the netlist.
*
* @param name Name of the parameter.
*/
void
Netlist::removeParameter(const std::string& name) {
for (ParameterTable::iterator iter = parameters_.begin();
iter != parameters_.end(); iter++) {
if (iter->name == name) {
parameters_.erase(iter);
break;
}
}
}
/**
* Tells whether the netlist has the given parameter.
*
* @param name Name of the parameter.
*/
bool
Netlist::hasParameter(const std::string& name) const {
for (ParameterTable::const_iterator iter = parameters_.begin();
iter != parameters_.end(); iter++) {
if (iter->name == name) {
return true;
}
}
return false;
}
/**
* Returns the number of parameters in the netlist.
*
* @return The number of parameters.
*/
int
Netlist::parameterCount() const {
return parameters_.size();
}
/**
* Returns the parameter at the given position.
*
* @param index The position.
* @exception OutOfRange If the given index is negative or not smaller than
* the number of parameters.
*/
Netlist::Parameter
Netlist::parameter(int index) const {
if (index < 0 || index >= parameterCount()) {
throw OutOfRange(__FILE__, __LINE__, __func__);
}
return parameters_[index];
}
void
Netlist::setCoreEntityName(TCEString coreEntityName) {
coreEntityName_ = coreEntityName;
}
TCEString
Netlist::coreEntityName() const {
if (coreEntityName_ == "")
return topLevelBlock().moduleName();
else
return coreEntityName_;
}
}
| 26.498489 | 78 | 0.688063 |
9b52892eac05dc229e55bcbb9214c1db73817838 | 9,115 | hpp | C++ | libraries/protocol/include/scorum/protocol/betting/market.hpp | scorum/scorum | 1da00651f2fa14bcf8292da34e1cbee06250ae78 | [
"MIT"
] | 53 | 2017-10-28T22:10:35.000Z | 2022-02-18T02:20:48.000Z | libraries/protocol/include/scorum/protocol/betting/market.hpp | Scorum/Scorum | fb4aa0b0960119b97828865d7a5b4d0409af7876 | [
"MIT"
] | 38 | 2017-11-25T09:06:51.000Z | 2018-10-31T09:17:22.000Z | libraries/protocol/include/scorum/protocol/betting/market.hpp | Scorum/Scorum | fb4aa0b0960119b97828865d7a5b4d0409af7876 | [
"MIT"
] | 27 | 2018-01-08T19:43:35.000Z | 2022-01-14T10:50:42.000Z | #pragma once
#include <fc/static_variant.hpp>
#include <scorum/protocol/betting/wincase.hpp>
#include <scorum/protocol/betting/market_kind.hpp>
#include <scorum/protocol/config.hpp>
#include <boost/range/algorithm/transform.hpp>
namespace scorum {
namespace protocol {
template <market_kind kind, typename tag = void> struct over_under_market
{
int16_t threshold;
template <bool site> using wincase = over_under_wincase<site, kind, tag>;
using over = wincase<true>;
using under = wincase<false>;
static constexpr market_kind kind_v = kind;
bool has_trd_state() const
{
return threshold % SCORUM_BETTING_THRESHOLD_FACTOR == 0;
}
};
template <market_kind kind, typename tag = void> struct score_yes_no_market
{
uint16_t home;
uint16_t away;
template <bool site> using wincase = score_yes_no_wincase<site, kind, tag>;
using yes = wincase<true>;
using no = wincase<false>;
static constexpr market_kind kind_v = kind;
bool has_trd_state() const
{
return false;
}
};
template <market_kind kind, typename tag = void> struct yes_no_market
{
template <bool site> using wincase = yes_no_wincase<site, kind, tag>;
using yes = wincase<true>;
using no = wincase<false>;
static constexpr market_kind kind_v = kind;
bool has_trd_state() const
{
return false;
}
};
struct home_tag;
struct away_tag;
struct draw_tag;
struct both_tag;
using result_home = yes_no_market<market_kind::result, home_tag>;
using result_draw = yes_no_market<market_kind::result, draw_tag>;
using result_away = yes_no_market<market_kind::result, away_tag>;
using round_home = yes_no_market<market_kind::round>;
using handicap = over_under_market<market_kind::handicap>;
using correct_score_home = yes_no_market<market_kind::correct_score, home_tag>;
using correct_score_draw = yes_no_market<market_kind::correct_score, draw_tag>;
using correct_score_away = yes_no_market<market_kind::correct_score, away_tag>;
using correct_score = score_yes_no_market<market_kind::correct_score>;
using goal_home = yes_no_market<market_kind::goal, home_tag>;
using goal_both = yes_no_market<market_kind::goal, both_tag>;
using goal_away = yes_no_market<market_kind::goal, away_tag>;
using total = over_under_market<market_kind::total>;
using total_goals_home = over_under_market<market_kind::total_goals, home_tag>;
using total_goals_away = over_under_market<market_kind::total_goals, away_tag>;
using market_type = fc::static_variant<result_home,
result_draw,
result_away,
round_home,
handicap,
correct_score_home,
correct_score_draw,
correct_score_away,
correct_score,
goal_home,
goal_both,
goal_away,
total,
total_goals_home,
total_goals_away>;
using wincase_type = fc::static_variant<result_home::yes,
result_home::no,
result_draw::yes,
result_draw::no,
result_away::yes,
result_away::no,
round_home::yes,
round_home::no,
handicap::over,
handicap::under,
correct_score_home::yes,
correct_score_home::no,
correct_score_draw::yes,
correct_score_draw::no,
correct_score_away::yes,
correct_score_away::no,
correct_score::yes,
correct_score::no,
goal_home::yes,
goal_home::no,
goal_both::yes,
goal_both::no,
goal_away::yes,
goal_away::no,
total::over,
total::under,
total_goals_home::over,
total_goals_home::under,
total_goals_away::over,
total_goals_away::under>;
std::pair<wincase_type, wincase_type> create_wincases(const market_type& market);
wincase_type create_opposite(const wincase_type& wincase);
market_type create_market(const wincase_type& wincase);
bool has_trd_state(const market_type& market);
bool match_wincases(const wincase_type& lhs, const wincase_type& rhs);
market_kind get_market_kind(const wincase_type& wincase);
template <typename T> std::set<market_kind> get_markets_kind(const T& markets)
{
std::set<market_kind> actual_markets;
boost::transform(markets, std::inserter(actual_markets, actual_markets.begin()), [](const market_type& m) {
return m.visit([&](const auto& market_impl) { return market_impl.kind_v; });
});
return actual_markets;
}
template <typename T> bool is_belong_markets(const wincase_type& wincase, const T& markets)
{
const auto wincase_market = create_market(wincase);
for (const auto& market : markets)
{
if (wincase_market == market)
return true;
}
return false;
}
} // namespace protocol
} // namespace scorum
#include <scorum/protocol/betting/wincase_comparison.hpp>
#include <scorum/protocol/betting/market_comparison.hpp>
namespace fc {
using scorum::protocol::market_type;
using scorum::protocol::wincase_type;
template <> void to_variant(const wincase_type& wincase, fc::variant& variant);
template <> void from_variant(const fc::variant& variant, wincase_type& wincase);
template <> void to_variant(const market_type& market, fc::variant& var);
template <> void from_variant(const fc::variant& var, market_type& market);
}
FC_REFLECT_EMPTY(scorum::protocol::result_home)
FC_REFLECT_EMPTY(scorum::protocol::result_draw)
FC_REFLECT_EMPTY(scorum::protocol::result_away)
FC_REFLECT_EMPTY(scorum::protocol::round_home)
FC_REFLECT(scorum::protocol::handicap, (threshold))
FC_REFLECT_EMPTY(scorum::protocol::correct_score_home)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_draw)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_away)
FC_REFLECT(scorum::protocol::correct_score, (home)(away))
FC_REFLECT_EMPTY(scorum::protocol::goal_home)
FC_REFLECT_EMPTY(scorum::protocol::goal_both)
FC_REFLECT_EMPTY(scorum::protocol::goal_away)
FC_REFLECT(scorum::protocol::total, (threshold))
FC_REFLECT(scorum::protocol::total_goals_home, (threshold))
FC_REFLECT(scorum::protocol::total_goals_away, (threshold))
FC_REFLECT_EMPTY(scorum::protocol::result_home::yes)
FC_REFLECT_EMPTY(scorum::protocol::result_home::no)
FC_REFLECT_EMPTY(scorum::protocol::result_draw::yes)
FC_REFLECT_EMPTY(scorum::protocol::result_draw::no)
FC_REFLECT_EMPTY(scorum::protocol::result_away::yes)
FC_REFLECT_EMPTY(scorum::protocol::result_away::no)
FC_REFLECT_EMPTY(scorum::protocol::round_home::yes)
FC_REFLECT_EMPTY(scorum::protocol::round_home::no)
FC_REFLECT(scorum::protocol::handicap::over, (threshold))
FC_REFLECT(scorum::protocol::handicap::under, (threshold))
FC_REFLECT_EMPTY(scorum::protocol::correct_score_home::yes)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_home::no)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_draw::yes)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_draw::no)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_away::yes)
FC_REFLECT_EMPTY(scorum::protocol::correct_score_away::no)
FC_REFLECT(scorum::protocol::correct_score::yes, (home)(away))
FC_REFLECT(scorum::protocol::correct_score::no, (home)(away))
FC_REFLECT_EMPTY(scorum::protocol::goal_home::yes)
FC_REFLECT_EMPTY(scorum::protocol::goal_home::no)
FC_REFLECT_EMPTY(scorum::protocol::goal_both::yes)
FC_REFLECT_EMPTY(scorum::protocol::goal_both::no)
FC_REFLECT_EMPTY(scorum::protocol::goal_away::yes)
FC_REFLECT_EMPTY(scorum::protocol::goal_away::no)
FC_REFLECT(scorum::protocol::total::over, (threshold))
FC_REFLECT(scorum::protocol::total::under, (threshold))
FC_REFLECT(scorum::protocol::total_goals_home::over, (threshold))
FC_REFLECT(scorum::protocol::total_goals_home::under, (threshold))
FC_REFLECT(scorum::protocol::total_goals_away::over, (threshold))
FC_REFLECT(scorum::protocol::total_goals_away::under, (threshold))
| 40.691964 | 111 | 0.635765 |
9b56abc30532d95aa4808cf0df4697960bb64d96 | 8,559 | cpp | C++ | genCaseNary.cpp | kumar-archit/SumCapacityMAC | 16b0c88bb7eea508c14b00ab3b1b338e7104efd1 | [
"MIT"
] | null | null | null | genCaseNary.cpp | kumar-archit/SumCapacityMAC | 16b0c88bb7eea508c14b00ab3b1b338e7104efd1 | [
"MIT"
] | null | null | null | genCaseNary.cpp | kumar-archit/SumCapacityMAC | 16b0c88bb7eea508c14b00ab3b1b338e7104efd1 | [
"MIT"
] | null | null | null | /* A program to find the capacity of MAC channel Multi user case (each alphabet is arbitrary size) by implementing Blahut Arimoto Algorithm
*
* Created on: 20-Oct-2018
* Author : Archit Kumar
*/
/*
Input[Optional]:
1. input probability distribution of input alphabet.
2. transition matrix for the channel
[3]. Number of iterations for Expectation-Maximisation to run.
[4]. Accepted error in Capacity.
Output:
Capacity of the Channel
*/
#include <bits/stdc++.h>
using namespace std;
/*
* a function to convert a decimal number to a vector, the size equal to inputAlphabetsDisSize.
* this function is required to find the row corresponding to the input vector in the transmission matrix.
* See also: binToDec
*/
void xM(int x, vector<vector<double> > &inputAlphabetsDistribution, vector<int>& inpVector) {
int i, siz;
for(i=0; i<inpVector.size(); i++)inpVector[i]=0;
i=0;
while(x > 0) {
siz = (inputAlphabetsDistribution[i].size());
inpVector[i] = x % siz;
++i;
x /= siz;
}
reverse(inpVector.begin(), inpVector.end());
}
/*
* converts a vector to a decimal number which translates to the row corresponding to the input vector in the
* transition matrix.
*/
int nPerm(vector<int> inpVector, vector<vector<double> > &inputAlphabetsDistribution, int noOfPermutation){
int siz = inpVector.size();
int ans=0;
for(int temp = siz - 1; temp>=0;temp--){
noOfPermutation /= inputAlphabetsDistribution[temp].size();
//here we mush denote ordinal values to symbols i.e. they must start from 0 and be sequential integers
ans += inpVector[temp]*noOfPermutation;
}
return ans;
}
/*
* a function to calculate capacity by first calculating probability distribution of output alphabet
* noOfPermutation : total number of possible input vectors
* probY : vector to store output alphabet probability distribution
*/
double capacity(vector<double> &outputDis, vector<vector<double> > &inputAlphabetsDistribution, vector<vector<double> > &transmissionMatrix){
//calc P(Y)
int noOfPermutation = transmissionMatrix.size();
int outputAlphabetSize = transmissionMatrix[0].size();
int noOfInputAlphabets = inputAlphabetsDistribution.size();
double cumPro, probY, capacity=0;
vector<int> inpVector(noOfInputAlphabets,0);
int i, j, y;
for(y = 0; y < outputAlphabetSize; ++y) {
probY = 0;
for(i = 0; i < noOfPermutation; ++i) {
xM(i, inputAlphabetsDistribution, inpVector);
cumPro = 1;
for(j = 0; j < inpVector.size(); ++j) {
cumPro *= inputAlphabetsDistribution[j][inpVector[j]];
}
probY += cumPro*transmissionMatrix[i][y];
}
outputDis[y] = probY;
}
for(y=0; y<outputAlphabetSize; y++){
for(i=0; i< noOfPermutation; ++i){
xM(i, inputAlphabetsDistribution, inpVector);
cumPro = 1;
for(j = 0; j < inpVector.size(); ++j) {
cumPro *= inputAlphabetsDistribution[j][inpVector[j]];
}
capacity += cumPro*transmissionMatrix[i][y]*log(transmissionMatrix[i][y]/outputDis[y]);
}
}
return capacity;
}
/*
* a function to calculate mutual information of each alphabets' every symbol in a 2d vector mutualIm
* tempDistribution is a 2d vector used to store the probability distribution of all alphabets other than the
* currently focussed one in Marginalisation algorithm. This matrix is of size (noOfInputAlphabets-1)*2.
*
* a temporary vector xm_dash (one less dimension) is generated which can be used to in-turn generate many more
* (equal to size of omitted alphabet).
*
*/
void marginalisation( vector<vector<double> > &mutualIm, vector<double> &outputDis, vector<vector<double> > &inputAlphabetsDistribution, vector<vector<double> > &transmissionMatrix){
int noOfInputAlphabets = inputAlphabetsDistribution.size();
int count, siz, pos;
double product, p_xm_dash;
vector<vector<double> > tempDistribution;
tempDistribution.resize(noOfInputAlphabets-1);
vector<int> xm_dash(noOfInputAlphabets-1);
vector<int> xm;
// int lim = pow(2, M-1);
int noOfPermutation = 1, lim;
for(int i=0; i<noOfInputAlphabets; i++)
noOfPermutation *= inputAlphabetsDistribution.size();
for(int i = 0; i < noOfInputAlphabets; i++) {
count=0;
for(int j = 0; j < noOfInputAlphabets; j++) if(j != i){
siz = inputAlphabetsDistribution[j].size();
tempDistribution[count].resize(siz);
for(int k=0; k<siz; k++){
tempDistribution[count][k] = inputAlphabetsDistribution[j][k];
}
count++;
}
siz = inputAlphabetsDistribution[i].size();
lim = noOfPermutation/siz;
for(int k=0; k<siz; k++){
product = 1;
for(int j = 0; j < lim; ++j) {
xM(j, tempDistribution, xm_dash);
xm = xm_dash;
xm.emplace(xm.begin() + i, k);
pos = nPerm(xm, inputAlphabetsDistribution, noOfPermutation);
p_xm_dash=1 ;
for(int p=0; p<noOfInputAlphabets-1; p++){
p_xm_dash *= tempDistribution[p][xm_dash[p]];
}
for(int y = 0; y < outputDis.size(); ++y) {
double p_y_given_x_M = transmissionMatrix[pos][y];
double p_y = outputDis[y];
product *= pow((p_y_given_x_M)/(p_y), p_xm_dash*p_y_given_x_M);
}
}
mutualIm[i][k] = product;
}
}
}
/*
* a function to change the probability distributions of input alphabets using
* mutual information. This updation of probability distribution happens in each step of EM method.
*/
void prob_adjustment(vector<vector<double> >& inputAlphabetsDistribution, vector<vector<double> > &mutualIm) {
int noOfInputAlphabets = inputAlphabetsDistribution.size();
double num, deno;
for(int i=0; i<noOfInputAlphabets; i++){
for(int j=0; j<inputAlphabetsDistribution[i].size(); j++){
deno=0;
num = mutualIm[i][j];
for(int k=0; k < inputAlphabetsDistribution[i].size() ; k++) {
deno += (inputAlphabetsDistribution[i][k]*mutualIm[i][k]);
}
if(deno == 0)
cout << "Error: Denominator zero" << endl;
inputAlphabetsDistribution[i][j] *= num/deno;
}
}
}
/*
* Implementation of Expectation-Maximisation paradigm
* Expectation step is performed by marginalisation function
* Maximisation step is performed by Maximisation function
*/
double em(vector<vector<double> > &inputAlphabetsDistribution, vector<vector<double> > &transmissionMatrix, double error = 0.01, int iterations = 1){
double capa, old_c = 0;
int noOfInputAlphabets = inputAlphabetsDistribution.size(), outputAlphabetSize=transmissionMatrix[0].size();
vector<double> outputDis(outputAlphabetSize,0);
vector<vector <double> >mutualIm;
mutualIm.resize(noOfInputAlphabets);
for(int i=0;i<noOfInputAlphabets; i++){
mutualIm[i].resize(inputAlphabetsDistribution[i].size(),0);
}
int LIM = iterations;
while(iterations--){
capa = capacity(outputDis, inputAlphabetsDistribution, transmissionMatrix);
if(abs(capa - old_c) < error) return capa;
old_c = capa;
cout << LIM - iterations << " " << capa << endl;
marginalisation(mutualIm, outputDis, inputAlphabetsDistribution, transmissionMatrix);
prob_adjustment(inputAlphabetsDistribution, mutualIm);
}
}
//Initialization of inputAlphabetsDistribution vector and transmissionMatrix 2d vector by taking input from user/ file
void init(int noOfInputAlphabets, int outputAlphabetSize, vector<int> &alphabetSize, vector<vector<double> > &inputAlphabetsDistribution, vector<vector<double> > &transmissionMatrix){
int i,j, siz=1, tSiz;
alphabetSize.resize(noOfInputAlphabets);
inputAlphabetsDistribution.resize(noOfInputAlphabets);
for(i=0; i<noOfInputAlphabets; i++){
cin>>tSiz;
alphabetSize[i]=tSiz;
siz *= tSiz;
inputAlphabetsDistribution[i].resize(tSiz);
for(j=0; j<tSiz; j++)
cin>>inputAlphabetsDistribution[i][j];
}
transmissionMatrix.resize(siz);
for(i=0; i<siz; i++)
transmissionMatrix[i].resize(outputAlphabetSize);
for(i=0; i<siz; i++){
for(j=0; j<outputAlphabetSize; j++)
cin>>transmissionMatrix[i][j];
}
}
int main(){
int noOfInputAlphabets, outputAlphabetSize;
cin>>noOfInputAlphabets >> outputAlphabetSize;
//the transmission matrix is still of size 2^(Sum n_i)*outputAlphabetSize
vector <vector<double> > inputAlphabetsDistribution;
vector<int> alphabetSize;
vector <vector<double> > transmissionMatrix;
init(noOfInputAlphabets, outputAlphabetSize, alphabetSize, inputAlphabetsDistribution, transmissionMatrix);
em(inputAlphabetsDistribution, transmissionMatrix, 0.000001, 10000);
return 0;
}
| 37.213043 | 184 | 0.696343 |
9b58686529189be7eecc3c0c17292971a5e6f185 | 3,378 | cpp | C++ | tddd86-algorithms/life.cpp | AxelGard/university-projects | 0c9a6e785f1918c6ed0fd365b2d419c9f52edb50 | [
"MIT"
] | 2 | 2022-01-30T17:53:33.000Z | 2022-02-03T23:34:36.000Z | tddd86-algorithms/life.cpp | AxelGard/university-projects | 0c9a6e785f1918c6ed0fd365b2d419c9f52edb50 | [
"MIT"
] | null | null | null | tddd86-algorithms/life.cpp | AxelGard/university-projects | 0c9a6e785f1918c6ed0fd365b2d419c9f52edb50 | [
"MIT"
] | null | null | null | /*
* Martin Gustafsson @margu424 && Axel Gard @axega544
*
* The task was to crate a replication of the game of life.
*
* Soruces :
* labb PM - https://www.ida.liu.se/~TDDD86/info/misc/labb1.pdf
* C++ doc - http://www.cplusplus.com/doc/tutorial/files/
* StackOverFlow - https://stackoverflow.com/questions/25225948/how-to-check-if-a-file-exists-in-c-with-fstreamopen?rq=1
*
*/
#include <iostream>
#include "grid.h"
#include "lifeutil.h"
#include <string>
#include <fstream>
/* Prints the given grid to the terminal */
void printGrid(const Grid<int>& grid){
for (int i = 0; i < grid.numRows(); i++){
for(int j = 0; j < grid.numCols(); j++){
if (grid.get(i,j)){
std::cout << "X";
}
else{
std::cout << "-";
}
}
std::cout << std::endl;
}
}
/* returns the number of neighbours in a given grid at pos row and col */
int getNeighbours(const Grid<int>& grid, int row, int col){
int neighbours = 0;
for (int i = -1; i < 2; i++){
for (int j = -1; j < 2; j++){
if (i == 0 && j == 0) continue;
if (!grid.inBounds(row+i, col+j)) continue;
if (grid.get(row+i, col+j)) neighbours++;
}
}
return neighbours;
}
/* Runs the game one genaration forward */
void tick(Grid<int>& grid){
Grid<int> newGrid = Grid<int>(grid.numRows(), grid.numCols());
for (int i = 0; i < grid.numRows(); i++){
for (int j = 0; j < grid.numCols(); j++){
if (getNeighbours(grid, i,j) == 2) newGrid.set(i,j,grid.get(i,j));
else if (getNeighbours(grid, i,j) == 3) newGrid.set(i,j,1);
else newGrid.set(i,j, 0);
}
}
grid = newGrid;
}
/* will run the game forever */
void animate(Grid<int>& grid){
while (true) {
clearConsole();
printGrid(grid);
pause(100);
tick(grid);
}
}
/* main function that handels user input */
int main() {
std::cout << "Welcome to the TDDD86 Game of Life,\n"
"a simulation of the lifecycle of a bacteria colony.\n"
"Cells (X) live and die by the following rules:\n"
" - A cell with 1 or fewer neighbours dies.\n"
" - Locations with 2 neighbours remain stable.\n"
" - Locations with 3 neighbours will create life. \n"
" - A cell with 4 or more neighbours dies. \n\n";
std::string filename;
std::cout << "Grid input file name? : ";
std::cin >> filename;
std::ifstream infile(filename);
if (!infile.is_open()){
std::cout << "file not found : " << std::endl;
return 1;
}
int rows;
int coloums;
infile >> rows;
infile >> coloums;
Grid<int> grid = Grid<int>(rows, coloums);
// get given grid
for (int i = 0; i < rows; i++){
std::string row;
infile >> row;
for (int j = 0; j < coloums; j++){
if (row[j] == 'X'){
grid.set(i, j, 1);
}
}
}
printGrid(grid);
char choice;
while (true) {
std::cout << "a)nimate, t)ick, q)uit? ";
std::cin >> choice;
if (choice == 'a') animate(grid);
else if (choice == 't'){
tick(grid);
printGrid(grid);
}
else return 0;
}
}
| 25.78626 | 120 | 0.51717 |
9b64451c57a5c7befdabc8f310f8399877a8fad6 | 2,233 | cpp | C++ | src/Aims.cpp | weiboad/aidt | dabb0877675326f8bd80fdb450a4f3d7108ac5db | [
"Apache-2.0"
] | 16 | 2017-07-06T04:54:06.000Z | 2021-06-24T03:37:33.000Z | src/Aims.cpp | weiboad/aidt | dabb0877675326f8bd80fdb450a4f3d7108ac5db | [
"Apache-2.0"
] | 1 | 2018-05-18T07:32:03.000Z | 2018-05-18T10:02:24.000Z | src/Aims.cpp | weiboad/aidt | dabb0877675326f8bd80fdb450a4f3d7108ac5db | [
"Apache-2.0"
] | 3 | 2017-07-11T03:43:30.000Z | 2018-08-16T12:10:42.000Z | #include "Aims.hpp"
// {{{ Aims::Aims()
Aims::Aims(AimsContext* context) :
_context(context) {
_configure = _context->config;
}
// }}}
// {{{ Aims::~Aims()
Aims::~Aims() {
}
// }}}
// {{{ void Aims::run()
void Aims::run() {
// 初始化 server
init();
_kafkaProducerIn->start();
}
// }}}
// {{{ void Aims::init()
void Aims::init() {
initKafkaProducer();
}
// }}}
// {{{ void Aims::stop()
void Aims::stop() {
if (_kafkaProducerIn != nullptr) {
_kafkaProducerIn->stop();
}
if (_kafkaProducerCallbackIn != nullptr) {
delete _kafkaProducerCallbackIn;
_kafkaProducerCallbackIn = nullptr;
}
}
// }}}
// {{{ adbase::kafka::Producer* Aims::getProducer()
adbase::kafka::Producer* Aims::getProducer() {
return _kafkaProducerIn;
}
// }}}
// {{{ void Aims::initKafkaProducer()
void Aims::initKafkaProducer() {
_kafkaProducerCallbackIn = new aims::kafka::ProducerIn(_context);
std::unordered_map<std::string, std::string> configs;
configs["metadata.broker.list"] = _configure->brokerListProducerIn;
configs["debug"] = _configure->debugIn;
configs["security.protocol"] = _configure->securityProtocol;
configs["sasl.mechanisms"] = _configure->saslMechanisms;
configs["sasl.kerberos.service.name"] = _configure->kerberosServiceName;
configs["sasl.kerberos.principal"] = _configure->kerberosPrincipal;
configs["sasl.kerberos.kinit.cmd"] = _configure->kerberosCmd;
configs["sasl.kerberos.keytab"] = _configure->kerberosKeytab;
configs["sasl.kerberos.min.time.before.relogin"] = _configure->kerberosMinTime;
configs["sasl.username"] = _configure->saslUsername;
configs["sasl.password"] = _configure->saslPassword;
_kafkaProducerIn = new adbase::kafka::Producer(configs, _configure->queueLengthIn);
_kafkaProducerIn->setSendHandler(std::bind(&aims::kafka::ProducerIn::send,
_kafkaProducerCallbackIn,
std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3));
_kafkaProducerIn->setErrorHandler(std::bind(&aims::kafka::ProducerIn::errorCallback,
_kafkaProducerCallbackIn,
std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4));
}
// }}}
| 26.903614 | 85 | 0.670846 |
9b64fe04440fda5b7bfc633eaf03e32d5e2ea0a8 | 1,259 | cc | C++ | deps/steamworks_sdk/public/rail/sdk/base/rail_array_test.cc | jeffersQuan/greenworks | ab73a59574e4a15a1e97091334b384f6e84257eb | [
"MIT"
] | null | null | null | deps/steamworks_sdk/public/rail/sdk/base/rail_array_test.cc | jeffersQuan/greenworks | ab73a59574e4a15a1e97091334b384f6e84257eb | [
"MIT"
] | null | null | null | deps/steamworks_sdk/public/rail/sdk/base/rail_array_test.cc | jeffersQuan/greenworks | ab73a59574e4a15a1e97091334b384f6e84257eb | [
"MIT"
] | null | null | null | // Copyright (c) 2019, Entropy Game Global Limited.
// All rights reserved.
#include <stdint.h>
#include "rail/sdk/base/rail_array.h"
#include "thirdparty/gtest/gtest.h"
struct Item {
int32_t id;
int32_t value;
};
TEST(RailArray, size) {
rail::RailArray<struct Item> array;
EXPECT_EQ(0U, array.size());
array.resize(100);
EXPECT_EQ(100U, array.size());
array.resize(0);
EXPECT_EQ(0U, array.size());
struct Item item;
item.id = 1;
item.value = 100;
array.push_back(item);
EXPECT_EQ(1U, array.size());
EXPECT_EQ(100, array[0].value);
array[0].value = 101;
EXPECT_EQ(101, array[0].value);
const struct Item& it = array[0];
EXPECT_EQ(101, it.value);
struct Item item2;
item2.id = 2;
item2.value = 200;
array.push_back(item2);
EXPECT_EQ(2U, array.size());
rail::RailArray<char> str("Hello", 5);
EXPECT_EQ(5U, str.size());
}
TEST(RailArray, assign) {
rail::RailArray<struct Item> array;
Item items[5];
items[1].value = 100;
array.assign(items, sizeof(items) / sizeof(Item));
EXPECT_EQ(5U, array.size());
EXPECT_EQ(100, array[1].value);
}
TEST(RailArray, buf) {
rail::RailArray<int64_t> array;
EXPECT_EQ(NULL, array.buf());
}
| 22.890909 | 54 | 0.631454 |
9b6caf18dd8e10d0f32bb9507f848b8ed7329c4f | 1,552 | hpp | C++ | code/szen/inc/szen/System/SpriteBatch.hpp | Sonaza/scyori | a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf | [
"BSD-3-Clause"
] | null | null | null | code/szen/inc/szen/System/SpriteBatch.hpp | Sonaza/scyori | a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf | [
"BSD-3-Clause"
] | null | null | null | code/szen/inc/szen/System/SpriteBatch.hpp | Sonaza/scyori | a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf | [
"BSD-3-Clause"
] | null | null | null | #ifndef SZEN_SPRITEBATCH_HPP
#define SZEN_SPRITEBATCH_HPP
#include <SFML/Graphics.hpp>
#include <functional>
#include <map>
#include <vector>
#include <thor/Particles.hpp>
namespace sz
{
class TextureAsset;
class ShaderAsset;
struct BatchData
{
BatchData() : texture(NULL), shader(NULL), particles(NULL) {}
BatchData(size_t layer, const sf::Texture*, const sf::Shader*, sf::BlendMode);
BatchData(size_t layer, thor::ParticleSystem*, const sf::Shader*, sf::BlendMode);
BatchData(size_t layer, sf::Text*, sf::BlendMode);
size_t layer;
sf::VertexArray vertices;
const sf::Texture* texture;
const sf::Shader* shader;
sf::BlendMode blendmode;
thor::ParticleSystem* particles;
sf::Text text;
enum Type
{
Vertices,
Particles,
Text
} type;
};
typedef std::vector<BatchData> BatchDataList;
class SpriteBatch
{
public:
SpriteBatch();
~SpriteBatch();
static void init();
static void clear();
//static void append(const sf::Vertex* quad, sf::Uint32 layer, TextureAsset* texture, ShaderAsset* shader, sf::BlendMode blendmode);
static void append(const sf::Vertex* quad, sf::Uint32 layer, const sf::Texture* texture, ShaderAsset* shader, sf::BlendMode blendmode);
static void append(thor::ParticleSystem* system, sf::Uint32 layer, ShaderAsset* shader, sf::BlendMode blendmode);
static void append(sf::Text* text, sf::Uint32 layer, sf::BlendMode blendmode);
static void draw(sf::RenderTarget&);
private:
static BatchDataList m_batchData;
};
}
#endif // SZEN_SPRITEBATCH_HPP
| 21.555556 | 137 | 0.717784 |
9b6d41b5fb0fc4f82fd71de1611c606f27f09f1f | 8,171 | cpp | C++ | client_tools/lms/src/OPE_LMS/db.cpp | kgonyo/ope | a5b548ad7716e76f42af9bdd8f0079752760edee | [
"MIT"
] | null | null | null | client_tools/lms/src/OPE_LMS/db.cpp | kgonyo/ope | a5b548ad7716e76f42af9bdd8f0079752760edee | [
"MIT"
] | null | null | null | client_tools/lms/src/OPE_LMS/db.cpp | kgonyo/ope | a5b548ad7716e76f42af9bdd8f0079752760edee | [
"MIT"
] | null | null | null | #include "db.h"
APP_DB::APP_DB(QQmlApplicationEngine *parent) : QObject(parent)
{
_db = QSqlDatabase::addDatabase("QSQLITE");
this->setParent(parent);
// DEBUG STUFF
QString crypt_pw = QCryptographicHash::hash(QString("abcd").toLocal8Bit(),
QCryptographicHash::Sha256).toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals);
qDebug() << "TEST PW: " << crypt_pw;
}
/**
* @brief DB::init_db - Connect to database and ensure that scheme is in place and/or migrated
* @return true on success
*/
bool APP_DB::init_db()
{
bool ret = false;
QQmlApplicationEngine *p = qobject_cast<QQmlApplicationEngine*>(this->parent());
p->rootContext()->setContextProperty("database", this);
// Find DB path
QDir d;
d.setPath(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/");
d.mkpath(d.path());
QString db_file = d.path() + "/lms.db";
_db.setHostName(db_file);
_db.setDatabaseName(db_file);
_db.setPassword("TEST PW"); // TODO - doesn't do anything, need sqlite extetion to add encryption?
ret = _db.open();
if (ret) {
// Create and/or migrate tables
QSqlQuery query;
QString sql;
//QSqlTableModel *model;
GenericQueryModel *model;
// Create student users table
sql = "CREATE TABLE IF NOT EXISTS `students` ( \
`id` INTEGER PRIMARY KEY AUTOINCREMENT, \
`user_name` TEXT NOT NULL, \
`password` TEXT NOT NULL, \
`auth_cookie` TEXT NOT NULL DEFAULT '' \
);";
if (!query.exec(sql)) {
qDebug() << "DB Error: " << query.lastError().text();
ret = false;
}
// Add to the table models list
model = new GenericQueryModel(this);
//model->setTable("students");
//model->setEditStrategy(QSqlTableModel::OnManualSubmit);
//model->select();
//model->setHeaderData(0, Qt::Horizontal, tr("id"));
//model->setHeaderData(1, Qt::Horizontal, tr("user_name"));
//model->setHeaderData(2, Qt::Horizontal, tr("password"));
//model->setHeaderData(3, Qt::Horizontal, tr("auth_cookie"));
_tables["students"] = model;
// Expose this to QML
p->rootContext()->setContextProperty("students_model", model);
// Create the classes table
sql = "CREATE TABLE IF NOT EXISTS `classes` ( \
`id` INTEGER PRIMARY KEY AUTOINCREMENT, \
`tid_student` INTEGER NOT NULL DEFAULT 0, \
`class_name` TEXT NOT NULL DEFAULT '', \
`class_code` TEXT NOT NULL DEFAULT '', \
`class_description` TEXT NOT NULL DEFAULT '' \
);";
if (!query.exec(sql)) {
qDebug() << "DB Error: " << query.lastError().text();
ret = false;
}
// Add to the table models list
model = new GenericQueryModel(this);
//model->select();
//model->setHeaderData(0, Qt::Horizontal, tr("id"));
//model->setHeaderData(1, Qt::Horizontal, tr("tid_student"));
//model->setHeaderData(2, Qt::Horizontal, tr("class_name"));
//model->setHeaderData(3, Qt::Horizontal, tr("class_code"));
//model->setHeaderData(4, Qt::Horizontal, tr("class_description"));
_tables["classes"] = model;
// Expose this to QML
p->rootContext()->setContextProperty("classes_model", model);
// Create the resources table
sql = "CREATE TABLE IF NOT EXISTS `resources` ( \
`id` INTEGER PRIMARY KEY AUTOINCREMENT, \
`resource_name` TEXT NOT NULL DEFAULT '', \
`resource_url` TEXT NOT NULL DEFAULT '', \
`resource_description` TEXT NOT NULL DEFAULT '', \
`sort_order` INTEGER NOT NULL DEFAULT 0 \
);";
if (!query.exec(sql)) {
qDebug() << "DB Error: " << query.lastError().text();
ret = false;
}
// Add to the table models list
model = new GenericQueryModel(this);
model->setQuery("SELECT * FROM resources", _db);
//model->select();
//model->setHeaderData(0, Qt::Horizontal, tr("id"));
//model->setHeaderData(1, Qt::Horizontal, tr("resource_name"));
//model->setHeaderData(2, Qt::Horizontal, tr("resource_url"));
//model->setHeaderData(3, Qt::Horizontal, tr("resource_description"));
//model->setHeaderData(4, Qt::Horizontal, tr("sort_order"));
_tables["resources"] = model;
// Expose this to QML
p->rootContext()->setContextProperty("resources_model", model);
// Make sure the default resource entries are in place
add_resource("Start Here", "/start_here/index.html", "Getting started...", 0);
// Make sure to commit and release locks
_db.commit();
}
return ret;
}
/**
* @brief APP_DB::auth_student - Authenticate the student against the local database
* @param user_name
* @param password
* @return true on success
*/
bool APP_DB::auth_student(QString user_name, QString password)
{
bool ret = false;
// If the password is empty always return false
if (password == "") {
return false;
}
// Encode password
QString crypt_pw = QCryptographicHash::hash(password.toLocal8Bit(),
QCryptographicHash::Sha256).toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals);
// Query to see if the user exists
QString sql = "SELECT COUNT(*) user_count FROM students WHERE user_name=:user_name and password=:password";
QSqlQuery q;
q.prepare(sql);
q.bindValue(":user_name", user_name);
q.bindValue(":password", crypt_pw);
q.exec();
int user_count = 0;
while(q.next()) {
user_count = q.value("user_count").toInt();
}
if (user_count > 0) {
ret = true;
}
return ret;
}
bool APP_DB::add_resource(QString resource_name, QString resource_url, QString resource_description, int sort_order)
{
bool ret = false;
QString sql;
QSqlQuery q;
// Check if the resource exists
sql = "SELECT count(*) as count FROM resources WHERE resource_name=:resource_name";
q.prepare(sql);
q.bindValue(":resource_name", resource_name);
q.exec();
int count = 0;
while (q.next()) {
count = q.value("count").toInt();
}
if (count > 0) {
// Already present
return true;
}
// Not present, add it
sql = "INSERT INTO resources (resource_name, resource_url, resource_description, sort_order) \
VALUES (:resource_name, :resource_url, :resource_description, :sort_order)";
q.prepare(sql);
q.bindValue(":resource_name", resource_name);
q.bindValue(":resource_url", resource_url);
q.bindValue(":resource_description", resource_description);
q.bindValue(":sort_order", sort_order);
q.exec();
// Write changes to the db
_db.commit();
// Refresh data after insert? TODO - should this be an emit signal instead?
//_tables["resources"]->select();
ret = true;
return ret;
}
GenericQueryModel::GenericQueryModel(QObject *parent) : QSqlQueryModel(parent)
{
}
void GenericQueryModel::setQuery(const QString &query, const QSqlDatabase &db)
{
QSqlQueryModel::setQuery(query, db);
generateRoleNames();
}
void GenericQueryModel::setQuery(const QSqlQuery &query)
{
QSqlQueryModel::setQuery(query);
generateRoleNames();
}
QVariant GenericQueryModel::data(const QModelIndex &index, int role) const
{
QVariant value;
if (role < Qt::UserRole) {
value = QSqlQueryModel::data(index, role);
} else {
int columnIndex = role - Qt::UserRole -1;
QModelIndex modelIndex = this->index(index.row(), columnIndex);
value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
}
return value;
}
void GenericQueryModel::generateRoleNames()
{
m_roleNames.clear();
for(int i = 0; i < record().count(); i++) {
m_roleNames.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8());
}
}
| 31.548263 | 116 | 0.61241 |
9b724925d691a7781cd8a990a5556961f5e913fb | 37,941 | cpp | C++ | src/Parser.cpp | MichaelMCE/LCDMisc | 1d2a913d62fd4d940ad95b5f8463a5f06e683427 | [
"CC-BY-4.0"
] | null | null | null | src/Parser.cpp | MichaelMCE/LCDMisc | 1d2a913d62fd4d940ad95b5f8463a5f06e683427 | [
"CC-BY-4.0"
] | null | null | null | src/Parser.cpp | MichaelMCE/LCDMisc | 1d2a913d62fd4d940ad95b5f8463a5f06e683427 | [
"CC-BY-4.0"
] | null | null | null | #include "Parser.h"
#include "Tokenizer.h"
#include "malloc.h"
#include "config.h"
//#include <stdio.h>
//#include "string.h"
#define REDUCE 0x20000000
#define SHIFT 0x40000000
#define ACCEPT 0x60000000
#define ACTION_MASK 0x60000000
struct Rule {
ScriptTokenType result;
NodeType nodeType;
unsigned char numTerms:4;
unsigned char operatorPos:4;
ScriptTokenType terms[8];
};
const Rule rules[] = {
{PARSER_SCRIPT, NODE_NONE, 2, 1, PARSER_FUNCTION_LIST, TOKEN_END},
{PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 2, 1, PARSER_FUNCTION, PARSER_FUNCTION_LIST},
{PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 1, 0, PARSER_FUNCTION},
{PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 2, 1, PARSER_STRUCT, PARSER_FUNCTION_LIST},
{PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 1, 0, PARSER_STRUCT},
//{PARSER_FUNCTION_LIST, NODE_FUNCTION_LIST, 1, 0, PARSER_RAW_STRUCT},
/*
{PARSER_RAW_STRUCT, NODE_RAW_STRUCT, 6, 1, TOKEN_RAW, TOKEN_STRUCT, TOKEN_IDENTIFIER, TOKEN_OPEN_CODE, PARSER_RAW_STRUCT_LIST, TOKEN_CLOSE_CODE, TOKEN_END_STATEMENT},
{PARSER_RAW_STRUCT_LIST, NODE_RAW_STRUCT_LIST, 3, 0, PARSER_RAW_STRUCT_ENTRY, TOKEN_SEMICOLON, PARSER_STRUCT_LIST},
{PARSER_RAW_STRUCT_LIST, NODE_RAW_STRUCT_LIST, 2, 0, PARSER_RAW_STRUCT_ENTRY, TOKEN_SEMICOLON},
{PARSER_RAW_STRUCT_ENTRY, NODE_STRUCT_VALUES, 2, 0, PARSER_TYPE, TOKEN_IDENTIFIER},
{PARSER_RAW_STRUCT_ENTRY, NODE_STRUCT_VALUES, 3, 0, PARSER_RAW_STRUCT_ENTRY, TOKEN_COMMA, TOKEN_IDENTIFIER},
{PARSER_RAW_STRUCT_ENTRY, NODE_STRUCT_VALUES, 5, 0, PARSER_TYPE, TOKEN_ TOKEN_IDENTIFIER},
{PARSER_RAW_STRUCT_ENTRY, NODE_STRUCT_VALUES, 6, 0, PARSER_RAW_STRUCT_ENTRY, TOKEN_COMMA, TOKEN_IDENTIFIER},
{PARSER_TYPE, NODE_INT_TYPE, 1, 0, TOKEN_INT_TYPE},
{PARSER_TYPE, NODE_FLOAT_TYPE, 1, 0, TOKEN_FLOAT_TYPE},
{PARSER_TYPE, NODE_DOUBLE_TYPE, 1, 0, TOKEN_DOUBLE_TYPE},
{PARSER_TYPE, NODE_CHAR_TYPE, 1, 0, TOKEN_CHAR_TYPE},
{PARSER_TYPE, NODE_STRING_TYPE, 1, 0, TOKEN_STRING_TYPE},
//*/
{PARSER_STRUCT, NODE_STRUCT, 5, 0, TOKEN_STRUCT, TOKEN_IDENTIFIER, TOKEN_OPEN_CODE, PARSER_STRUCT_LIST, TOKEN_CLOSE_CODE, TOKEN_END_STATEMENT},
{PARSER_STRUCT, NODE_STRUCT, 7, 0, TOKEN_STRUCT, TOKEN_IDENTIFIER, TOKEN_EXTENDS, PARSER_IDENTIFIER_LIST, TOKEN_OPEN_CODE, PARSER_STRUCT_LIST, TOKEN_CLOSE_CODE, TOKEN_END_STATEMENT},
//{PARSER_STRUCT, NODE_STRUCT, 4, 1, TOKEN_STRUCT, TOKEN_IDENTIFIER, TOKEN_OPEN_CODE, TOKEN_CLOSE_CODE},
{PARSER_STRUCT_LIST, NODE_STRUCT_LIST, 2, 1, PARSER_STRUCT_ENTRY, PARSER_STRUCT_LIST},
{PARSER_STRUCT_LIST, NODE_STRUCT_LIST, 1, 0, PARSER_STRUCT_ENTRY},
{PARSER_STRUCT_ENTRY, NODE_NONE, 3, 1, TOKEN_VAR, PARSER_STRUCT_VALUES, TOKEN_END_STATEMENT},
{PARSER_STRUCT_ENTRY, NODE_NONE, 1, 0, PARSER_FUNCTION},
{PARSER_STRUCT_VALUES, NODE_STRUCT_VALUES, 1, 0, TOKEN_IDENTIFIER},
{PARSER_STRUCT_VALUES, NODE_STRUCT_VALUES, 2, 1, TOKEN_MOD, TOKEN_IDENTIFIER},
{PARSER_STRUCT_VALUES, NODE_STRUCT_VALUES, 3, 0, TOKEN_IDENTIFIER, TOKEN_COMMA, PARSER_STRUCT_VALUES},
{PARSER_STRUCT_VALUES, NODE_STRUCT_VALUES, 4, 1, TOKEN_MOD, TOKEN_IDENTIFIER, TOKEN_COMMA, PARSER_STRUCT_VALUES},
{PARSER_FUNCTION, NODE_IGNORE, 1, 0, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_FUNCTION_ALIAS, 5, 3, TOKEN_ALIAS, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_END_STATEMENT},
//{PARSER_FUNCTION, NODE_DLL32, 4, 1, TOKEN_DLL32, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT},
//{PARSER_FUNCTION, NODE_DLL64, 4, 1, TOKEN_DLL64, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL32, 5, 1, TOKEN_DLL32, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_STRING, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL64, 5, 1, TOKEN_DLL64, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_STRING, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL32, 4, 1, TOKEN_DLL32, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL64, 4, 1, TOKEN_DLL64, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL_FUNCTION, 6, 1, TOKEN_DLL, TOKEN_IDENTIFIER, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL_FUNCTION, 7, 1, TOKEN_DLL, TOKEN_IDENTIFIER, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_STRING, PARSER_DLL_ARG_LIST, TOKEN_END_STATEMENT},
{PARSER_FUNCTION, NODE_DLL_FUNCTION_SIMPLE, 7, 1, TOKEN_DLL, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_STRING, PARSER_DLL_ARG_LIST, TOKEN_END_STATEMENT},
// Hack to allow 0 element list.
{PARSER_DLL_ARG_LIST, NODE_DLL_ARG, 2, 0, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN},
{PARSER_DLL_ARG_LIST, NODE_NONE, 3, 0, TOKEN_OPEN_PAREN, PARSER_DLL_ARGS, TOKEN_CLOSE_PAREN},
{PARSER_DLL_ARGS, NODE_DLL_ARGS, 1, 0, PARSER_DLL_ARG},
{PARSER_DLL_ARGS, NODE_DLL_ARGS, 3, 0, PARSER_DLL_ARG, TOKEN_COMMA, PARSER_DLL_ARGS},
{PARSER_DLL_ARG, NODE_DLL_ARG, 2, 0, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER},
{PARSER_DLL_ARG, NODE_DLL_ARG, 1, 0, TOKEN_IDENTIFIER},
{PARSER_FUNCTION, NODE_FUNCTION, 6, 0, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, PARSER_IDENTIFIER_LIST, TOKEN_CLOSE_PAREN, PARSER_STATEMENT_BLOCK},
{PARSER_FUNCTION, NODE_FUNCTION, 5, 0, TOKEN_FUNCTION, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN, PARSER_STATEMENT_BLOCK},
{PARSER_STRUCT_ENTRY, NODE_FUNCTION, 7, 0, TOKEN_FUNCTION, TOKEN_MOD, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, PARSER_IDENTIFIER_LIST, TOKEN_CLOSE_PAREN, PARSER_STATEMENT_BLOCK},
{PARSER_STRUCT_ENTRY, NODE_FUNCTION, 6, 0, TOKEN_FUNCTION, TOKEN_MOD, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN, PARSER_STATEMENT_BLOCK},
//{PARSER_SIMPLE_EXPRESSION, NODE_FUNCTION_CALL, 3, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN},
{PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_STRUCT_REF_CALL, 8, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_CALL, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_COMMA, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_REF_CALL, 6, 0, TOKEN_CALL, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_COMMA, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_FUNCTION_CALL, 2, 0, TOKEN_IDENTIFIER, PARSER_VALUE_LIST},
{PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_STRUCT_FUNCTION_CALL, 4, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_IDENTIFIER, PARSER_VALUE_LIST},
{PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_STRUCT_FUNCTION_CALL, 5, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_MOD, TOKEN_IDENTIFIER, PARSER_VALUE_LIST},
{PARSER_SIMPLE_DEREFERENCE_EXPRESSION, NODE_STRUCT_THIS_FUNCTION_CALL, 3, 0, TOKEN_MOD, TOKEN_IDENTIFIER, PARSER_VALUE_LIST},
//{PARSER_FUNCTION_CALL, NODE_FUNCTION_CALL, 4, TOKEN_IDENTIFIER, TOKEN_OPEN_PAREN, PARSER_LIST, TOKEN_CLOSE_PAREN},
{PARSER_VALUE_LIST, NODE_MAKE_COPY, 4, 0, TOKEN_OPEN_PAREN, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_VALUE_LIST, NODE_LIST_CREATE, 3, 0, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_VALUE_LIST, NODE_EMPTY_LIST, 2, 0, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN},
{PARSER_VALUE_LIST, NODE_LIST_ADD_NULL, 3, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_VALUE_LIST, NODE_LIST_ADD, 4, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_VALUE_LIST, NODE_APPEND, 5, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_LIST},
//{PARSER_LIST, NODE_LIST_ADD_NULL, 4, TOKEN_LIST, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_CLOSE_PAREN},
//{PARSER_LIST, NODE_LIST_CREATE, 4, TOKEN_LIST, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
//{PARSER_LIST, NODE_EMPTY_LIST, 3, TOKEN_LIST, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN},
// {PARSER_SIMPLE_EXPRESSION, NODE_DICT_TO_LIST, 4, 0, TOKEN_DICT_TO_LIST, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_LIST, NODE_NONE, 4, 0, TOKEN_OPEN_PAREN, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_LIST, NODE_LIST_ADD_NULL, 3, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_LIST, NODE_LIST_ADD, 4, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_LIST, NODE_APPEND, 5, 0, TOKEN_OPEN_PAREN, PARSER_LIST_EXPRESSION, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
//{PARSER_LIST, NODE_LIST_CREATE, 4, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_COMMA, TOKEN_CLOSE_PAREN},
//{PARSER_LIST_EXPRESSION, NODE_LIST_CREATE, 3, PARSER_LIST_EXPRESSION, TOKEN_COMMA, PARSER_EXPRESSION},
{PARSER_LIST_EXPRESSION, NODE_LIST_ADD, 3, 0, PARSER_LIST_EXPRESSION, PARSER_EXPRESSION, TOKEN_COMMA},
{PARSER_LIST_EXPRESSION, NODE_LIST_ADD_NULL, 2, 0, PARSER_LIST_EXPRESSION, TOKEN_COMMA},
{PARSER_LIST_EXPRESSION, NODE_APPEND, 4, 0, PARSER_LIST_EXPRESSION, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_COMMA},
{PARSER_LIST_EXPRESSION, NODE_LIST_CREATE_NULL, 1, 0, TOKEN_COMMA},
//{PARSER_LIST_EXPRESSION, NODE_LIST_CREATE, 2, PARSER_EXPRESSION, TOKEN_COMMA},
{PARSER_LIST_EXPRESSION, NODE_LIST_CREATE, 2, 0, PARSER_EXPRESSION, TOKEN_COMMA},
{PARSER_LIST_EXPRESSION, NODE_NONE, 3, 0, TOKEN_APPEND, PARSER_EXPRESSION, TOKEN_COMMA},
{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_DICT},
{PARSER_DICT, NODE_NONE, 4, 0, TOKEN_DICT, TOKEN_OPEN_PAREN, PARSER_DICT_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_DICT, NODE_NONE, 3, 0, TOKEN_OPEN_PAREN, PARSER_DICT_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_DICT, NODE_EMPTY_DICT, 3, 0, TOKEN_DICT, TOKEN_OPEN_PAREN, TOKEN_CLOSE_PAREN},
{PARSER_DICT_EXPRESSION, NODE_APPEND, 3, 0, PARSER_DICT_EXPRESSION, TOKEN_COMMA, PARSER_MINI_DICT_EXPRESSION},
{PARSER_DICT_EXPRESSION, NODE_NONE, 1, 0, PARSER_MINI_DICT_EXPRESSION},
{PARSER_MINI_DICT_EXPRESSION, NODE_DICT_CREATE, 3, 0, PARSER_EXPRESSION, TOKEN_COLON, PARSER_EXPRESSION},
{PARSER_MINI_DICT_EXPRESSION, NODE_MAKE_COPY, 2, 0, TOKEN_APPEND, PARSER_EXPRESSION},
{PARSER_SIMPLE_EXPRESSION, NODE_SIZE, 4, 0, TOKEN_SIZE, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_IDENTIFIER_LIST, NODE_IDENTIFIER_LIST, 3, 0, TOKEN_IDENTIFIER, TOKEN_COMMA, PARSER_IDENTIFIER_LIST},
{PARSER_IDENTIFIER_LIST, NODE_IDENTIFIER_LIST, 1, 0, TOKEN_IDENTIFIER},
{PARSER_IDENTIFIER_LIST, NODE_IDENTIFIER_LIST, 4, 0, TOKEN_DOLLAR, TOKEN_IDENTIFIER, TOKEN_COMMA, PARSER_IDENTIFIER_LIST},
{PARSER_IDENTIFIER_LIST, NODE_IDENTIFIER_LIST, 2, 0, TOKEN_DOLLAR, TOKEN_IDENTIFIER},
{PARSER_STATEMENT_LIST, NODE_NONE, 1, 0, PARSER_STATEMENT},
{PARSER_STATEMENT_LIST, NODE_STATEMENT_LIST, 2, 0, PARSER_STATEMENT_LIST, PARSER_STATEMENT},
{PARSER_STATEMENT_BLOCK, NODE_NONE, 3, 0, TOKEN_OPEN_CODE, PARSER_STATEMENT_LIST, TOKEN_CLOSE_CODE},
{PARSER_STATEMENT_BLOCK, NODE_EMPTY, 2, 0, TOKEN_OPEN_CODE, TOKEN_CLOSE_CODE},
{PARSER_STATEMENT, NODE_DISCARD_LAST, 2, 0, PARSER_EXPRESSION, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_EMPTY, 1, 0, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_NONE, 1, 0, PARSER_STATEMENT_BLOCK},
//{PARSER_STATEMENT, NODE_DISCARD_FIRST, 1, PARSER_IF},
//{PARSER_STATEMENT, NODE_DISCARD_FIRST, 1, PARSER_IF_ELSE},
//{PARSER_STATEMENT, NODE_NONE, 1, PARSER_RETURN},
//{PARSER_RETURN, NODE_RETURN, 3, TOKEN_RETURN, PARSER_EXPRESSION, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_RETURN, 3, 0, TOKEN_RETURN, PARSER_EXPRESSION, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_RETURN, 2, 0, TOKEN_RETURN, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_BREAK, 2, 0, TOKEN_BREAK, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_CONTINUE, 2, 0, TOKEN_CONTINUE, TOKEN_END_STATEMENT},
{PARSER_STATEMENT, NODE_FOR, 7, 0, TOKEN_FOR, TOKEN_OPEN_PAREN, PARSER_FOR_PRE_STATEMENT_LIST, PARSER_EXPRESSION, PARSER_FOR_POST_STATEMENT_LIST, TOKEN_CLOSE_PAREN, PARSER_STATEMENT},
{PARSER_FOR_PRE_STATEMENT_LIST, NODE_EMPTY, 1, 0, TOKEN_END_STATEMENT},
{PARSER_FOR_POST_STATEMENT_LIST, NODE_EMPTY, 1, 0, TOKEN_END_STATEMENT},
{PARSER_FOR_PRE_STATEMENT_LIST, NODE_DISCARD_LAST, 2, 0, PARSER_FOR_SUB_STATEMENT_LIST, TOKEN_END_STATEMENT},
{PARSER_FOR_POST_STATEMENT_LIST, NODE_DISCARD_LAST, 2, 0, TOKEN_END_STATEMENT, PARSER_FOR_SUB_STATEMENT_LIST},
{PARSER_FOR_SUB_STATEMENT_LIST, NODE_NONE, 1, 0, PARSER_EXPRESSION},
{PARSER_FOR_SUB_STATEMENT_LIST, NODE_DISCARD_FIRST, 3, 0, PARSER_EXPRESSION, TOKEN_COMMA, PARSER_FOR_SUB_STATEMENT_LIST},
{PARSER_STATEMENT, NODE_WHILE, 5, 0, TOKEN_WHILE, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT},
{PARSER_STATEMENT, NODE_DO_WHILE, 7, 0, TOKEN_DO, PARSER_STATEMENT, TOKEN_WHILE, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, TOKEN_END_STATEMENT},
//{PARSER_IF, NODE_IF, 5, TOKEN_IF, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT},
//{PARSER_IF_ELSE, NODE_IF_ELSE, 7, TOKEN_IF, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT, TOKEN_ELSE, PARSER_STATEMENT},
{PARSER_STATEMENT, NODE_IF, 5, 0, TOKEN_IF, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT},
{PARSER_STATEMENT, NODE_IF_ELSE, 7, 0, TOKEN_IF, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN, PARSER_STATEMENT, TOKEN_ELSE, PARSER_STATEMENT},
{PARSER_EXPRESSION, NODE_NONE, 1, 0, PARSER_ASSIGN_EXPRESSION},
//{PARSER_ASSIGN_EXPRESSION, NODE_ASSIGN, 3, PARSER_LOCAL_INDEX_EXPRESSION, TOKEN_ASSIGN, PARSER_ADD_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_CONCAT_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_CONCATE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_MUL_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_MULE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_DIV_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_DIVE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_MOD_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_MODE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_ADD_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_ADDE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_SUB_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_SUBE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_AND_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_ANDE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_XOR_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_XORE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_OR_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_ORE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_LSHIFT_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_LSHIFTE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_RSHIFT_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_RSHIFTE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_CONCAT_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_CONCATE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_MUL_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_MULE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_DIV_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_DIVE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_MOD_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_MODE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_ADD_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_ADDE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_SUB_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_SUBE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_AND_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_ANDE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_XOR_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_XORE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_OR_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_ORE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_LSHIFT_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_LSHIFTE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_RSHIFT_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_RSHIFTE, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_SIMPLE_ASSIGN, 3, 1, PARSER_IDENTIFIER_EXPRESSION, TOKEN_ASSIGN, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_ELEMENT_ASSIGN, 6, 4, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET, TOKEN_ASSIGN, PARSER_ASSIGN_EXPRESSION},
{PARSER_ASSIGN_EXPRESSION, NODE_NONE, 1, 0, PARSER_APPEND_EXPRESSION},
{PARSER_APPEND_EXPRESSION, NODE_APPEND, 3, 1, PARSER_APPEND_EXPRESSION, TOKEN_APPEND, PARSER_BOOL_OR_EXPRESSION},
{PARSER_APPEND_EXPRESSION, NODE_NONE, 1, 0, PARSER_BOOL_OR_EXPRESSION},
{PARSER_BOOL_OR_EXPRESSION, NODE_BOOL_OR, 3, 1, PARSER_BOOL_OR_EXPRESSION, TOKEN_BOOL_OR, PARSER_BOOL_AND_EXPRESSION},
{PARSER_BOOL_OR_EXPRESSION, NODE_NONE, 1, 0, PARSER_BOOL_AND_EXPRESSION},
{PARSER_BOOL_AND_EXPRESSION, NODE_BOOL_AND, 3, 1, PARSER_BOOL_AND_EXPRESSION, TOKEN_BOOL_AND, PARSER_OR_EXPRESSION},
{PARSER_BOOL_AND_EXPRESSION, NODE_NONE, 1, 0, PARSER_OR_EXPRESSION},
{PARSER_OR_EXPRESSION, NODE_OR, 3, 1, PARSER_OR_EXPRESSION, TOKEN_OR, PARSER_XOR_EXPRESSION},
{PARSER_OR_EXPRESSION, NODE_NONE, 1, 0, PARSER_XOR_EXPRESSION},
{PARSER_XOR_EXPRESSION, NODE_XOR, 3, 1, PARSER_XOR_EXPRESSION, TOKEN_XOR, PARSER_AND_EXPRESSION},
{PARSER_XOR_EXPRESSION, NODE_NONE, 1, 0, PARSER_AND_EXPRESSION},
{PARSER_AND_EXPRESSION, NODE_AND, 3, 1, PARSER_AND_EXPRESSION, TOKEN_AND, PARSER_EQUALS_EXPRESSION},
{PARSER_AND_EXPRESSION, NODE_NONE, 1, 0, PARSER_EQUALS_EXPRESSION},
{PARSER_EQUALS_EXPRESSION, NODE_E, 3, 1, PARSER_EQUALS_EXPRESSION, TOKEN_E, PARSER_COMPARE_EXPRESSION},
{PARSER_EQUALS_EXPRESSION, NODE_NE, 3, 1, PARSER_EQUALS_EXPRESSION, TOKEN_NE, PARSER_COMPARE_EXPRESSION},
{PARSER_EQUALS_EXPRESSION, NODE_NONE, 1, 0, PARSER_COMPARE_EXPRESSION},
{PARSER_COMPARE_EXPRESSION, NODE_L, 3, 1, PARSER_COMPARE_EXPRESSION, TOKEN_L, PARSER_COMPARE_STRING_EXPRESSION},
{PARSER_COMPARE_EXPRESSION, NODE_LE, 3, 1, PARSER_COMPARE_EXPRESSION, TOKEN_LE, PARSER_COMPARE_STRING_EXPRESSION},
{PARSER_COMPARE_EXPRESSION, NODE_G, 3, 1, PARSER_COMPARE_EXPRESSION, TOKEN_G, PARSER_COMPARE_STRING_EXPRESSION},
{PARSER_COMPARE_EXPRESSION, NODE_GE, 3, 1, PARSER_COMPARE_EXPRESSION, TOKEN_GE, PARSER_COMPARE_STRING_EXPRESSION},
{PARSER_COMPARE_EXPRESSION, NODE_NONE, 1, 0, PARSER_COMPARE_STRING_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_E, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCIE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_NE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCINE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_L, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCIL, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_LE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCILE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_G, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCIG, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_SCI_GE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SCIGE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_S_E, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_S_NE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SNE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_S_L, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SL, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_S_LE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SLE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_S_G, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SG, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_S_GE, 3, 1, PARSER_COMPARE_STRING_EXPRESSION, TOKEN_SGE, PARSER_CONCAT_EXPRESSION},
{PARSER_COMPARE_STRING_EXPRESSION, NODE_NONE, 1, 0, PARSER_CONCAT_EXPRESSION},
{PARSER_CONCAT_EXPRESSION, NODE_CONCAT_STRING, 3, 1, PARSER_CONCAT_EXPRESSION, TOKEN_CONCAT, PARSER_SHIFT_EXPRESSION},
{PARSER_CONCAT_EXPRESSION, NODE_NONE, 1, 0, PARSER_SHIFT_EXPRESSION},
{PARSER_SHIFT_EXPRESSION, NODE_LSHIFT, 3, 1, PARSER_SHIFT_EXPRESSION, TOKEN_LSHIFT, PARSER_ADD_EXPRESSION},
{PARSER_SHIFT_EXPRESSION, NODE_RSHIFT, 3, 1, PARSER_SHIFT_EXPRESSION, TOKEN_RSHIFT, PARSER_ADD_EXPRESSION},
{PARSER_SHIFT_EXPRESSION, NODE_NONE, 1, 0, PARSER_ADD_EXPRESSION},
{PARSER_ADD_EXPRESSION, NODE_ADD, 3, 1, PARSER_ADD_EXPRESSION, TOKEN_ADD, PARSER_MUL_EXPRESSION},
{PARSER_ADD_EXPRESSION, NODE_SUB, 3, 1, PARSER_ADD_EXPRESSION, TOKEN_SUB, PARSER_MUL_EXPRESSION},
{PARSER_ADD_EXPRESSION, NODE_NONE, 1, 0, PARSER_MUL_EXPRESSION},
{PARSER_MUL_EXPRESSION, NODE_MUL, 3, 1, PARSER_MUL_EXPRESSION, TOKEN_MUL, PARSER_PREFIX_EXPRESSION},
{PARSER_MUL_EXPRESSION, NODE_MOD, 3, 1, PARSER_MUL_EXPRESSION, TOKEN_MOD, PARSER_PREFIX_EXPRESSION},
{PARSER_MUL_EXPRESSION, NODE_DIV, 3, 1, PARSER_MUL_EXPRESSION, TOKEN_DIV, PARSER_PREFIX_EXPRESSION},
{PARSER_MUL_EXPRESSION, NODE_NONE, 1, 0, PARSER_PREFIX_EXPRESSION},
{PARSER_PREFIX_EXPRESSION, NODE_NOT, 2, 0, TOKEN_NOT, PARSER_PREFIX_EXPRESSION},
{PARSER_PREFIX_EXPRESSION, NODE_NEG, 2, 0, TOKEN_SUB, PARSER_PREFIX_EXPRESSION},
{PARSER_PREFIX_EXPRESSION, NODE_BIN_NEG, 2, 0, TOKEN_TILDE, PARSER_PREFIX_EXPRESSION},
{PARSER_PREFIX_EXPRESSION, NODE_NONE, 2, 0, TOKEN_ADD, PARSER_PREFIX_EXPRESSION},
{PARSER_PREFIX_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_EXPRESSION},
//{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, PARSER_FUNCTION_CALL},
{PARSER_SIMPLE_EXPRESSION, NODE_INT, 1, 0, TOKEN_INT},
{PARSER_SIMPLE_EXPRESSION, NODE_DOUBLE, 1, 0, TOKEN_DOUBLE},
//{PARSER_SIMPLE_EXPRESSION, NODE_IDENTIFIER, 1, TOKEN_IDENTIFIER},
{PARSER_SIMPLE_EXPRESSION, NODE_STRING, 1, 0, TOKEN_STRING},
{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 3, 1, TOKEN_OPEN_PAREN, PARSER_EXPRESSION, TOKEN_CLOSE_PAREN},
{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_POSTMOD_EXPRESSION},
//{PARSER_SIMPLE_EXPRESSION2, NODE_NONE, 1, 0, PARSER_SIMPLE_EXPRESSION},
{PARSER_SIMPLE_POSTMOD_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_PREMOD_EXPRESSION},
{PARSER_SIMPLE_POSTMOD_EXPRESSION, NODE_SIMPLE_POST_INC, 2, 1, PARSER_SIMPLE_POSTMOD_EXPRESSION, TOKEN_INC},
{PARSER_SIMPLE_POSTMOD_EXPRESSION, NODE_SIMPLE_POST_DEC, 2, 1, PARSER_SIMPLE_POSTMOD_EXPRESSION, TOKEN_DEC},
{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_DEREFERENCE_EXPRESSION},
{PARSER_DEREFERENCE_EXPRESSION, NODE_NONE, 1, 0, PARSER_SIMPLE_DEREFERENCE_EXPRESSION},
{PARSER_DEREFERENCE_EXPRESSION, NODE_DEREFERENCE, 1, 0, PARSER_IDENTIFIER_EXPRESSION},
{PARSER_DEREFERENCE_EXPRESSION, NODE_SUB_REFERENCE, 4, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
{PARSER_SIMPLE_PREMOD_EXPRESSION, NODE_DEREFERENCE, 1, 0, PARSER_IDENTIFIER_EXPRESSION},
{PARSER_SIMPLE_PREMOD_EXPRESSION, NODE_SIMPLE_PRE_INC, 2, 0, TOKEN_INC, PARSER_SIMPLE_PREMOD_EXPRESSION},
{PARSER_SIMPLE_PREMOD_EXPRESSION, NODE_SIMPLE_PRE_DEC, 2, 0, TOKEN_DEC, PARSER_SIMPLE_PREMOD_EXPRESSION},
//{PARSER_SIMPLE_EXPRESSION, NODE_DEREFERENCE, 1, PARSER_IDENTIFIER_EXPRESSION},
//{PARSER_INDEX_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_INDEX_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//{PARSER_SIMPLE_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_SIMPLE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//{PARSER_SIMPLE_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_SIMPLE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//{PARSER_ELEMENT_PREMOD_IDENTIFIER, NODE_NONE, 1, PARSER_SIMPLE_EXPRESSION},
//{PARSER_ELEMENT_PREPREMOD_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_ELEMENT_PREPREMOD_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//{PARSER_ELEMENT_PREPREMOD_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_ELEMENT_PREMOD_IDENTIFIER, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//{PARSER_ELEMENT_PREMOD_IDENTIFIER, NODE_DEREFERENCE, 1, PARSER_IDENTIFIER_EXPRESSION},
{PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_SUB_REFERENCE, 4, 1, PARSER_DEREFERENCE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
{PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_ELEMENT_PRE_INC, 2, 0, TOKEN_INC, PARSER_ELEMENT_PREMOD_EXPRESSION},
{PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_ELEMENT_PRE_DEC, 2, 0, TOKEN_DEC, PARSER_ELEMENT_PREMOD_EXPRESSION},
{PARSER_ELEMENT_POSTMOD_EXPRESSION, NODE_NONE, 1, 0, PARSER_ELEMENT_PREMOD_EXPRESSION},
{PARSER_ELEMENT_POSTMOD_EXPRESSION, NODE_ELEMENT_POST_INC, 2, 1, PARSER_ELEMENT_POSTMOD_EXPRESSION, TOKEN_INC},
{PARSER_ELEMENT_POSTMOD_EXPRESSION, NODE_ELEMENT_POST_DEC, 2, 1, PARSER_ELEMENT_POSTMOD_EXPRESSION, TOKEN_DEC},
{PARSER_SIMPLE_EXPRESSION, NODE_NONE, 1, 0, PARSER_ELEMENT_POSTMOD_EXPRESSION},
//{PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_NONE, 1, PARSER_ELEMENT_PREPREMOD_EXPRESSION},
//{PARSER_ELEMENT_PREMOD_EXPRESSION, NODE_SUB_REFERENCE, 4, PARSER_SIMPLE_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//{SIMPLE_EXPRESSION, NODE_DEREFERENCE, 4, PARSER_IDENTIFIER_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
{PARSER_IDENTIFIER_EXPRESSION, NODE_STRUCT_REFERENCE, 3, 2, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_IDENTIFIER},
{PARSER_IDENTIFIER_EXPRESSION, NODE_STRUCT_REFERENCE, 4, 2, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_MOD, TOKEN_IDENTIFIER},
//{PARSER_IDENTIFIER_EXPRESSION, NODE_STRUCT_REFERENCE, 3, 2, PARSER_DEREFERENCE_EXPRESSION, TOKEN_PERIOD, TOKEN_IDENTIFIER},
{PARSER_IDENTIFIER_EXPRESSION, NODE_STRUCT_THIS_REFERENCE, 2, 0, TOKEN_MOD, TOKEN_IDENTIFIER},
{PARSER_IDENTIFIER_EXPRESSION, NODE_LOCAL_REFERENCE, 2, 0, TOKEN_DOLLAR, TOKEN_IDENTIFIER},
{PARSER_IDENTIFIER_EXPRESSION, NODE_GLOBAL_REFERENCE, 1, 0, TOKEN_IDENTIFIER},
//{PARSER_INDEX_EXPRESSION, NODE_REFERENCE, 4, PARSER_INDEX_EXPRESSION, TOKEN_OPEN_BRACKET, PARSER_EXPRESSION, TOKEN_CLOSE_BRACKET},
//*/
};
#define NUM_RULES (sizeof(rules)/sizeof(Rule))
struct Item {
int transition;
int rule;
int position;
};
struct ItemSet {
int numItems;
Item items[1];
};
int CalcClosure(ItemSet **s, int *mem, int id) {
int k = s[0]->numItems;
int maxSize = k;
int numCare = k;
for (int j=0; j<numCare; j++) {
int position = s[0]->items[j].position;
const Rule *rule = &rules[s[0]->items[j].rule];
if (position >= rule->numTerms) continue;
int term = rule->terms[position];
for (int i=1; i<NUM_RULES; i++) {
if (term != rules[i].result)
continue;
if (mem[i] == id)
break;
if (k < maxSize || (srealloc(s[0], sizeof(ItemSet)+sizeof(Item)*(maxSize+16)) && (maxSize+=16))) {
mem[i] = id;
int q;
for (q = 0; q<numCare; q++) {
if (rules[s[0]->items[q].rule].terms[s[0]->items[q].position] == rules[i].terms[0]) {
break;
}
}
int out = k;
if (q == numCare && rules[i].terms[0] > TOKEN_END) {
s[0]->items[k] = s[0]->items[numCare];
out = numCare++;
}
s[0]->items[out].rule = i;
s[0]->items[out].position = 0;
s[0]->items[out].transition = -1;
s[0]->numItems = ++k;
}
}
}
return 1;
}
void CleanupTree(ParseTree *t) {
if (t->val) free(t->val);
for (int i=0; i<t->numChildren; i++) {
if (t->children[i])
CleanupTree(t->children[i]);
}
free(t);
}
void ParseError(Token *token) {
errorPrintf(2, "Parse error, line %i:\r\n", token->line);
errors++;
DisplayErrorLine(token->start, token->pos);
}
int *actionTable = 0;
ParseTree * ParseScript(Token *tokens, int numTokens) {
int i;
if (numTokens == 1) {
CleanupTokens(tokens, numTokens);
return 0;
}
if (!actionTable) {
int numSets = 0;
ItemSet **set = (ItemSet**) malloc(sizeof(ItemSet*)*1000);
ItemSet **newSets = (ItemSet**) malloc(sizeof(ItemSet*)*1000);
if (!set || !newSets) {
free(set);
free(newSets);
return 0;
}
int changed = 1;
int *followSets = (int*) calloc(1, PARSER_NONE * sizeof(int) * PARSER_NONE);
int *firstSets = (int*) calloc(1, PARSER_NONE * sizeof(int) * PARSER_NONE);
for (i=0; i<PARSER_SCRIPT; i++) {
firstSets[PARSER_NONE*i+i] = 1;
}
while (changed) {
changed = 0;
for (int r = 0; r<NUM_RULES; r++) {
int R = rules[r].result;
int F = rules[r].terms[0];
for (i=0; i<PARSER_NONE;i++) {
if (firstSets[F*PARSER_NONE+i] && !firstSets[R*PARSER_NONE+i]) {
firstSets[R*PARSER_NONE+i] = 1;
changed = 1;
}
}
}
}
changed = 1;
while (changed) {
changed = 0;
for (int r = 0; r<NUM_RULES; r++) {
for (int p=0; p<rules[r].numTerms-1; p++) {
ScriptTokenType F = rules[r].terms[p];
ScriptTokenType S = rules[r].terms[p+1];
for (i=0; i<PARSER_NONE;i++) {
if (firstSets[S*PARSER_NONE+i] && !followSets[F*PARSER_NONE+i]) {
followSets[F*PARSER_NONE+i] = 1;
changed = 1;
}
}
}
ScriptTokenType F = rules[r].terms[rules[r].numTerms-1];
ScriptTokenType S = rules[r].result;
for (i=0; i<PARSER_NONE;i++) {
if (followSets[S*PARSER_NONE+i] && !followSets[F*PARSER_NONE+i]) {
followSets[F*PARSER_NONE+i] = 1;
changed = 1;
}
}
}
}
set[numSets++] = (ItemSet *) malloc(sizeof(ItemSet));
set[0]->numItems = 1;
set[0]->items[0].position = 0;
set[0]->items[0].rule = 0;
int closureId = 0;
int closureNotes[sizeof(rules) / sizeof(Rule)];
for (i=0; i<sizeof(closureNotes)/sizeof(int);i++)
closureNotes[i] = -1;
//memset(closureNotes, -1, sizeof(closureNotes));
CalcClosure(&set[0], closureNotes, closureId++);
for (i=0; i<numSets; i++) {
int numNewSets = 0;
int j;
for (j=0; j<set[i]->numItems; j++) {
set[i]->items[j].transition = -1;
if (set[i]->items[j].position != rules[set[i]->items[j].rule].numTerms) {
int q;
for (q=0; q<numNewSets; q++) {
if (rules[set[i]->items[j].rule].terms[set[i]->items[j].position] == rules[newSets[q]->items[0].rule].terms[newSets[q]->items[0].position-1]) {
srealloc(newSets[q] , sizeof(ItemSet) + sizeof(Item) * newSets[q]->numItems);
break;
}
}
if (q==numNewSets) {
newSets[q] = (ItemSet*) malloc(sizeof(ItemSet));
newSets[q]->numItems = 0;
numNewSets++;
}
newSets[q]->items[newSets[q]->numItems].position = set[i]->items[j].position+1;
newSets[q]->items[newSets[q]->numItems].rule = set[i]->items[j].rule;
newSets[q]->items[newSets[q]->numItems].transition = j;
newSets[q]->numItems++;
}
}
for (j=0; j<numNewSets; j++) {
CalcClosure(&newSets[j], closureNotes, closureId++);
int q = 0;
for (q = 0; q<numSets; q++) {
int match = 0;
if (set[q]->numItems == newSets[j]->numItems)
while (match < newSets[j]->numItems) {
int f;
for (f = 0; f<set[q]->numItems; f++) {
if (set[q]->items[f].rule == newSets[j]->items[match].rule &&
set[q]->items[f].position == newSets[j]->items[match].position)
break;
}
if (f == set[q]->numItems) break;
match++;
}
if (match == newSets[j]->numItems) break;
}
for (int w=0; w<newSets[j]->numItems; w++)
if (newSets[j]->items[w].transition >= 0)
set[i]->items[newSets[j]->items[w].transition].transition = q;
if (q<numSets) {
free(newSets[j]);
}
else {
set[numSets++] = newSets[j];
}
}
}
free(newSets);
actionTable = (int*) malloc(sizeof(int) * numSets*PARSER_NONE);
for (i=numSets*PARSER_NONE-1; i>=0;i--) {
actionTable[i] = -1;
}
for (i=0; i<numSets; i++) {
int reduce = 0;
for (int w=0; w<set[i]->numItems; w++) {
if (set[i]->items[w].position < rules[set[i]->items[w].rule].numTerms) {
int term = rules[set[i]->items[w].rule].terms[set[i]->items[w].position];
if (actionTable[i*PARSER_NONE+term]>=0&& (actionTable[i*PARSER_NONE+term]&0xFFFFFF)-set[i]->items[w].transition !=0) {
i=i;
}
actionTable[i*PARSER_NONE+term] = set[i]->items[w].transition;
if (term < PARSER_SCRIPT) {
if (term != TOKEN_END)
actionTable[i*PARSER_NONE+term] |= SHIFT;
else
actionTable[i*PARSER_NONE+term] = ACCEPT;
}
/*
if (rules[set[i]->items[w].rule].terms[set[i]->items[w].position] < S) {
actionTable[i*PARSER_NONE+set[i]->items[w].rule] = set[i]->items[w].transition;
else
actionTable[i*PARSER_NONE+set[i]->items[w].rule] |= SHIFT;
}//*/
}
else {
/*if (reduce && reduce != set[i]->items[w].rule) {
reduce = reduce;
}
reduce = set[i]->items[w].rule;
//*/
reduce = set[i]->items[w].rule;
for (int x = 0; x<PARSER_SCRIPT; x++) {
if (followSets[rules[reduce].result*PARSER_NONE+x]) {
if (actionTable[x+i*PARSER_NONE] == -1) {
actionTable[x+i*PARSER_NONE] = REDUCE | reduce;
}
else {
i=i;
}
}
}
}
}
/*if (reduce) {
for (int w = 0; w<PARSER_SCRIPT; w++) {
if (actionTable[w+i*PARSER_NONE] == -1) {
actionTable[w+i*PARSER_NONE] = REDUCE | reduce;
}
}
}*/
}
free(followSets);
free(firstSets);
for (i=0; i<numSets; i++) {
free(set[i]);
}
free(set);
}
int maxStackSize = 1000;
int *stack = (int*) malloc(sizeof(int) * 1000);
//int output[1000];
stack[0] = 0;
//int outputLen = 0;
int stackSize = 1;
int pos = 0;
int accept = 0;
int ParseTrees = 0;
int maxParseTrees = 1000;
ParseTree **tree = (ParseTree**) malloc(sizeof(ParseTree*) * 1000);
int error = 0;
while (pos < numTokens && stackSize > 0) {
int row = stack[stackSize-1];
ScriptTokenType token = tokens[pos].type;
int i = actionTable[token+row*PARSER_NONE];
if (i==-1) {
if (pos && !tokens[pos].line) {
ParseError(tokens+pos-1);
}
else {
ParseError(tokens+pos);
}
error = 1;
break;
}
else if ((i&ACTION_MASK) == SHIFT) {
i &= ~SHIFT;
if (stackSize == maxStackSize) {
if (!srealloc(stack, sizeof(int) * (maxStackSize*=2))) {
ParseError(tokens+pos);
error = 1;
break;
}
}
if (ParseTrees == maxParseTrees) {
if (!srealloc(tree, sizeof(ParseTree*) * (maxParseTrees*=2))) {
ParseError(tokens+pos);
error = 1;
break;
}
}
stack[stackSize++] = i;
tree[ParseTrees] = (ParseTree*) calloc(1, sizeof(ParseTree));
if (!tree[ParseTrees]) {
ParseError(tokens+pos);
error = 1;
break;
}
{
tree[ParseTrees]->line = tokens[pos].line;
tree[ParseTrees]->pos = tokens[pos].pos;
tree[ParseTrees]->start = tokens[pos].start;
}
// Temporary node. Will be eaten by another.
tree[ParseTrees]->type = NODE_LEAF;
tree[ParseTrees]->numChildren = 0;
tree[ParseTrees]->intVal = tokens[pos].intVal;
tree[ParseTrees++]->val = tokens[pos].val;
tokens[pos].val = 0;
pos++;
}
else if ((i&ACTION_MASK) == REDUCE) {
i &= ~REDUCE;
// output[outputLen++] = i;
ParseTree *children[5] = {0,0,0,0,0};
int numChildren = 0;
int nline;
unsigned char *npos;
unsigned char *nstart;
for (int j = 0; j<rules[i].numTerms; j++) {
if (j == rules[i].operatorPos) {
nline = tree[ParseTrees - rules[i].numTerms+j]->line;
npos = tree[ParseTrees - rules[i].numTerms+j]->pos;
nstart = tree[ParseTrees - rules[i].numTerms+j]->start;
}
if (rules[i].terms[j] <= TOKEN_IDENTIFIER || rules[i].terms[j]>=TOKEN_END) {
children[numChildren++] = tree[ParseTrees - rules[i].numTerms+j];
}
else {
free(tree[ParseTrees - rules[i].numTerms+j]);
tree[ParseTrees - rules[i].numTerms+j] = 0;
}
}
ParseTrees -= rules[i].numTerms;
if (rules[i].nodeType == NODE_NONE) {
tree[ParseTrees] = children[0];
}
else {
if (numChildren && children[0]->type == NODE_LEAF) {
tree[ParseTrees] = children[0];
}
else {
tree[ParseTrees] = (ParseTree*) calloc(1, sizeof(ParseTree));
if (!tree[ParseTrees]) {
ParseError(tokens+pos);
error = 1;
break;
}
tree[ParseTrees]->children[0] = children[0];
}
tree[ParseTrees]->numChildren = numChildren;
tree[ParseTrees]->children[1] = children[1];
tree[ParseTrees]->children[2] = children[2];
tree[ParseTrees]->children[3] = children[3];
tree[ParseTrees]->children[4] = children[4];
tree[ParseTrees]->type = rules[i].nodeType;
}
tree[ParseTrees]->line = nline;
tree[ParseTrees]->pos = npos;
tree[ParseTrees]->start = nstart;
ParseTrees++;
stackSize -= rules[i].numTerms;
if (stackSize <= 0) {
ParseError(tokens+pos);
error = 1;
break;
}
else {
int w = rules[i].result;
int t = actionTable[stack[stackSize-1]*PARSER_NONE + w];
if (t >= 0 && t < 0x1000000) {
stack[stackSize++] = t;
}
else {
ParseError(tokens+pos);
error = 1;
break;
}
}
}
else if (i == ACCEPT) {
accept = 1;
break;
}
else {
ParseError(tokens+pos);
error = 1;
break;
}
}
free(stack);
CleanupTokens(tokens, numTokens);
if (error) {
for (int i=0; i<ParseTrees; i++) {
CleanupTree(tree[i]);
}
free(tree);
return 0;
}
ParseTree *out = tree[0];
free(tree);
return out;
}
void CleanupParser() {
free(actionTable);
actionTable = 0;
}
| 49.791339 | 213 | 0.760048 |
9b73b78f9a528cba963dadd7c36bffc881a59b7f | 4,198 | cpp | C++ | src/ossiarch/Katakros.cpp | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 5 | 2019-02-01T01:41:19.000Z | 2021-06-17T02:16:13.000Z | src/ossiarch/Katakros.cpp | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 2 | 2020-01-14T16:57:42.000Z | 2021-04-01T00:53:18.000Z | src/ossiarch/Katakros.cpp | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 1 | 2019-03-02T20:03:51.000Z | 2019-03-02T20:03:51.000Z | /*
* Warhammer Age of Sigmar battle simulator.
*
* Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include <UnitFactory.h>
#include "ossiarch/Katakros.h"
#include "OssiarchBonereaperPrivate.h"
namespace OssiarchBonereapers {
static const int g_basesize = 120; // x92 oval
static const int g_wounds = 20;
static const int g_pointsPerUnit = 470;
bool Katakros::s_registered = false;
Unit *Katakros::Create(const ParameterList ¶meters) {
auto legion = (Legion) GetEnumParam("Legion", parameters, g_legion[0]);
auto general = GetBoolParam("General", parameters, false);
return new Katakros(legion, general);
}
void Katakros::Init() {
if (!s_registered) {
static FactoryMethod factoryMethod = {
Katakros::Create,
OssiarchBonereaperBase::ValueToString,
OssiarchBonereaperBase::EnumStringToInt,
Katakros::ComputePoints,
{
EnumParameter("Legion", g_legion[0], g_legion),
BoolParameter("General")
},
DEATH,
{OSSIARCH_BONEREAPERS}
};
s_registered = UnitFactory::Register("Orpheon Katakros", factoryMethod);
}
}
Katakros::Katakros(Legion legion, bool isGeneral) :
OssiarchBonereaperBase("Orpheon Katakros", 4, g_wounds, 10, 3, false, g_pointsPerUnit) {
m_keywords = {DEATH, DEATHLORDS, OSSIARCH_BONEREAPERS, MORTIS_PRAETORIANS, LIEGE, HERO, KATAKROS};
m_weapons = {&m_indaKhaat, &m_shieldImmortis, &m_nadiriteDagger, &m_blades, &m_greatblade, &m_spiritDagger};
m_battleFieldRole = Role::Leader;
setLegion(legion);
setGeneral(isGeneral);
auto model = new Model(g_basesize, wounds());
model->addMeleeWeapon(&m_indaKhaat);
model->addMeleeWeapon(&m_shieldImmortis);
model->addMeleeWeapon(&m_nadiriteDagger);
model->addMeleeWeapon(&m_blades);
model->addMeleeWeapon(&m_greatblade);
model->addMeleeWeapon(&m_spiritDagger);
m_shieldImmortis.activate(false);
addModel(model);
}
int Katakros::generateHits(int unmodifiedHitRoll, const Weapon *weapon, const Unit *unit) const {
if ((unmodifiedHitRoll == 6) &&
((weapon->name() == m_nadiriteDagger.name()) || (weapon->name() == m_blades.name())))
return 2;
return OssiarchBonereaperBase::generateHits(unmodifiedHitRoll, weapon, unit);
}
void Katakros::onWounded() {
OssiarchBonereaperBase::onWounded();
if (woundsTaken() >= 13) {
m_shieldImmortis.activate(true);
m_blades.activate(false);
m_indaKhaat.setAttacks(4);
} else if (woundsTaken() >= 8) {
m_spiritDagger.activate(false);
} else if (woundsTaken() >= 4) {
m_greatblade.activate(false);
m_indaKhaat.setAttacks(2);
} else if (woundsTaken() >= 2) {
m_nadiriteDagger.activate(false);
}
}
Wounds Katakros::weaponDamage(const Model* attackingModel, const Weapon *weapon, const Unit *target, int hitRoll, int woundRoll) const {
// Deadly Combination
if ((hitRoll == 6) && (weapon->name() == m_shieldImmortis.name())) {
return {weapon->damage(), 2};
}
return OssiarchBonereaperBase::weaponDamage(attackingModel, weapon, target, hitRoll, woundRoll);
}
int Katakros::ComputePoints(const ParameterList& /*parameters*/) {
return g_pointsPerUnit;
}
void Katakros::onRestore() {
OssiarchBonereaperBase::onRestore();
// Restore table-driven attributes
onWounded();
// Defaults
m_shieldImmortis.activate(false);
m_blades.activate(true);
m_indaKhaat.setAttacks(1);
m_spiritDagger.activate(true);
m_greatblade.activate(true);
m_nadiriteDagger.activate(true);
}
} // namespace OssiarchBonereapers
| 35.576271 | 140 | 0.61696 |
9b75f1f2214cae98acf730f268709fbce6f226cd | 9,703 | hpp | C++ | redemption/src/core/RDP/tpdu_buffer.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | redemption/src/core/RDP/tpdu_buffer.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | redemption/src/core/RDP/tpdu_buffer.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | /*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Product name: redemption, a FLOSS RDP proxy
* Copyright (C) Wallix 2013-2019
* Author(s): Jonathan Poelen
*/
#pragma once
#include "core/buf64k.hpp"
#include "utils/hexdump.hpp"
#include "transport/transport.hpp"
#include "core/RDP/x224.hpp"
#include "utils/parse.hpp"
namespace Extractors
{
enum {
FASTPATH = 1,
CR_TPDU = X224::CR_TPDU, // Connection Request 1110 xxxx
CC_TPDU = X224::CC_TPDU, // Connection Confirm 1101 xxxx
DR_TPDU = X224::DR_TPDU, // Disconnect Request 1000 0000
DT_TPDU = X224::DT_TPDU, // Data 1111 0000 (no ROA = No Ack)
ER_TPDU = X224::ER_TPDU, // TPDU Error 0111 0000
};
struct HeaderResult
{
static HeaderResult fail() noexcept
{
return HeaderResult{};
}
static HeaderResult ok(uint16_t n) noexcept
{
return HeaderResult{n};
}
explicit operator bool () const noexcept
{
return this->is_extracted;
}
[[nodiscard]] uint16_t data_size() const noexcept
{
return this->len;
}
private:
explicit HeaderResult() noexcept = default;
explicit HeaderResult(uint16_t len) noexcept
: is_extracted(true)
, len(len)
{}
bool is_extracted{false};
uint16_t len;
};
struct X224Extractor
{
HeaderResult read_header(Buf64k & buf)
{
// fast path header occupies 2 or 3 octets, but assume then data len at least 2 octets.
if (buf.remaining() < 4)
{
return HeaderResult::fail();
}
auto av = buf.av(4);
uint16_t len;
REDEMPTION_DIAGNOSTIC_PUSH()
REDEMPTION_DIAGNOSTIC_CLANG_IGNORE("-Wcovered-switch-default")
switch (FastPath::FASTPATH_OUTPUT(av[0] & 0x03))
{
case FastPath::FASTPATH_OUTPUT_ACTION_FASTPATH:
{
len = av[1];
if (len & 0x80){
len = (len & 0x7F) << 8 | av[2];
// len -= 1;
// buf.advance(1);
}
// len -= 1;
// buf.advance(2);
this->has_fast_path = true;
this->type = Extractors::FASTPATH;
}
break;
case FastPath::FASTPATH_OUTPUT_ACTION_X224:
{
len = Parse(av.subarray(2, 2).data()).in_uint16_be();
if (len < 6) {
LOG(LOG_ERR, "Bad X224 header, length too short (length = %u)", len);
throw Error(ERR_X224);
}
// len -= 4;
// buf.advance(4);
this->has_fast_path = false;
}
break;
default:
LOG(LOG_ERR, "Bad X224 header, unknown TPKT version (%.2x)", av[0]);
throw Error(ERR_X224);
}
REDEMPTION_DIAGNOSTIC_POP()
return HeaderResult::ok(len);
}
void prepare_data(Buf64k const & buf)
{
if (this->has_fast_path) {
this->type = FASTPATH;
return;
}
uint8_t tpdu_type = Parse(buf.sub(5, 1).data()).in_uint8();
switch (uint8_t(tpdu_type & 0xF0)) {
case X224::CR_TPDU: // Connection Request 1110 xxxx
this->type = Extractors::CR_TPDU;
break;
case X224::CC_TPDU: // Connection Confirm 1101 xxxx
this->type = Extractors::CC_TPDU;
break;
case X224::DR_TPDU: // Disconnect Request 1000 0000
this->type = Extractors::DR_TPDU;
break;
case X224::DT_TPDU: // Data 1111 0000 (no ROA = No Ack)
this->type = Extractors::DT_TPDU;
break;
case X224::ER_TPDU: // TPDU Error 0111 0000
this->type = Extractors::ER_TPDU;
break;
default:
this->type = 0;
LOG(LOG_ERR, "Bad X224 header, unknown TPDU type (code = %u)", tpdu_type);
throw Error(ERR_X224);
}
}
[[nodiscard]] uint8_t get_type() const noexcept
{
if (this->has_fast_path){
return Extractors::FASTPATH;
}
return this->type;
}
private:
bool has_fast_path;
uint8_t type;
};
struct CreedsppExtractor
{
static HeaderResult read_header(Buf64k & buf)
{
if (buf.remaining() < 4)
{
return HeaderResult::fail();
}
auto av = buf.av(4);
if (av[1] <= 0x7F) { return HeaderResult::ok(av[1] + 2); }
if (av[1] == 0x81) { return HeaderResult::ok(av[2] + 3); }
if (av[1] == 0x82) { return HeaderResult::ok(((av[2] << 8) | av[3]) + 4); }
throw Error(ERR_NEGO_INCONSISTENT_FLAGS);
}
static void prepare_data(Buf64k const & /*unused*/)
{}
};
} // namespace Extractors
struct TpduBuffer
{
enum TpduType
{
PDU = 0,
CREDSSP = 1,
};
TpduBuffer() = default;
void load_data(InTransport trans)
{
this->buf.read_from(trans);
}
[[nodiscard]] uint16_t remaining() const noexcept
{
return this->buf.remaining();
}
u8_array_view remaining_data() noexcept
{
return this->buf.av();
}
// Having two 'next' functions is a bit awkward.
// Also it will work only if the buffer
// knows how to consume the previous packet *and* the reader code
// knows what the current packet type is (TPDU or CREDSSP)
// Maybe something like below is possible:
// bool next(TpduType packet)
// {
// switch (packet){
// case PACKET_TPDU:
// return this->extract(this->extractors.x224);
// case PACKET_CREDSSP:
// return this->extract(this->extractors.credssp);
// }
// }
// or fully extracting the knowledge of the Tpdu structure.
// Write tests with both CredSSP and Tpdu and see how it looks.
bool next(TpduType packet)
{
switch (packet){
case PDU:
return this->extract(this->extractors.x224);
case CREDSSP:
return this->extract(this->extractors.credssp);
}
REDEMPTION_UNREACHABLE();
}
// Works the same way for CREDSSP or PDU
// We can use it to trace CREDSSP buffer
writable_u8_array_view current_pdu_buffer() noexcept
{
assert(this->pdu_len);
auto av = this->buf.av(this->pdu_len);
if (this->trace_pdu){
::hexdump_d(av);
}
return av;
}
[[nodiscard]] uint8_t current_pdu_get_type() const noexcept
{
assert(this->pdu_len);
return this->extractors.x224.get_type();
}
void consume_current_packet() noexcept
{
this->buf.advance(this->pdu_len);
this->pdu_len = 0;
}
private:
enum class StateRead : bool
{
Header,
Data,
};
struct Extractor // Extractor concept
{
Extractors::HeaderResult read_header(Buf64k& buf);
void check_data(Buf64k const &) const;
};
template<class Extractor>
bool extract(Extractor & extractor)
{
if (this->data_ready){
this->data_ready = false;
return true;
}
switch (this->state)
{
case StateRead::Header:
this->consume_current_packet();
if (auto r = extractor.read_header(this->buf))
{
this->pdu_len = r.data_size();
if (this->pdu_len <= this->buf.remaining())
{
extractor.prepare_data(this->buf);
return true;
}
this->state = StateRead::Data;
}
return false;
case StateRead::Data:
if (this->pdu_len <= this->buf.remaining())
{
this->state = StateRead::Header;
extractor.prepare_data(this->buf);
return true;
}
return false;
}
}
StateRead state = StateRead::Header;
union U
{
Extractors::X224Extractor x224;
Extractors::CreedsppExtractor credssp;
char dummy;
U():dummy() {}
} extractors;
uint16_t pdu_len = 0;
Buf64k buf;
bool data_ready = false;
public:
bool trace_pdu = false;
};
| 28.622419 | 99 | 0.514068 |
9b7879f8798acba0bac70c850965937646e3b0bd | 2,435 | cpp | C++ | DataFrame.cpp | padelli/C-DataFrame | e750942fa7d3f88d9a499334412a808083486144 | [
"MIT"
] | 1 | 2017-10-10T03:32:11.000Z | 2017-10-10T03:32:11.000Z | DataFrame.cpp | padelli/C-DataFrame | e750942fa7d3f88d9a499334412a808083486144 | [
"MIT"
] | null | null | null | DataFrame.cpp | padelli/C-DataFrame | e750942fa7d3f88d9a499334412a808083486144 | [
"MIT"
] | null | null | null | #include "DataFrame.h"
#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<sstream>
void DataFrame::read_csv(std::string path)
{
std::ifstream File;
File.open(path);
std::string line;
std::vector<double> temp;
std::getline(File, line);
std::stringstream lineStream(line);
std::string cell;
//Reading first line into index vector
while (std::getline(lineStream, cell, ','))
{
df[cell] = vector();
index_vector.push_back(cell);
}
//Reading data into columns
int i = 0;
while (std::getline(File, line))
{
std::stringstream lineStream(line);
while (std::getline(lineStream, cell, ',') && i < index_vector.size())
{
df[index_vector[i]].push(std::stod(cell));
i++;
}
i = 0;
}
//shape.second = index_vector.size();
//if (shape.second) shape.first = df[0].size();
}
void DataFrame::print()
{
for (auto j : index_vector)
{
std::cout << j << " ";
}
std::cout << std::endl;
for (int i = 0; i < df[index_vector[0]].size(); i++)
{
for (auto j : index_vector)
{
std::cout << df[j][i] << " ";
}
std::cout << std::endl;
}
}
vector& DataFrame::operator[](std::string Column_name)
{
if (df.find(Column_name) != df.end())
{
//print(df[Column_name]);
return df[Column_name];
}
else
{
df[Column_name] = vector();
index_vector.push_back(Column_name);
//print(df[Column_name]);
return df[Column_name];
}
}
vector& DataFrame::operator[](int Column_idx)
{
if (Column_idx >= index_vector.size())
{
df[std::to_string(Column_idx)] = std::vector<double>();
index_vector.push_back(std::to_string(Column_idx));
return df[std::to_string(Column_idx)];
}
else
{
return df[index_vector[Column_idx]];
}
}
void DataFrame::print(vector& vec)
{
vec.print();
return;
}
/*double& DataFrame::operator[](std::pair<int, int> p)
{
if (p.first < shape.first && p.second < shape.second)
return df[index_vector[p.second]][p.first];
throw std::out_of_range("Index is out of range");
}*/
DataFrame DataFrame::operator()(std::initializer_list<std::string> init_list, std::vector<int> row_indices)
{
DataFrame result;
for (auto cln : init_list)
{
result[cln] = vector();
for (auto idx : row_indices)
{
result[cln].push(df[cln][idx]);
}
}
return result;
} | 17.904412 | 108 | 0.601232 |
9b78ede68f1cf46c0fa464ce85795cc3441fc52c | 4,099 | cpp | C++ | libpandabase/tests/type_converter_tests.cpp | openharmony-gitee-mirror/ark_runtime_core | 2e6f195caf482dc9607efda7cfb5cc5f98da5598 | [
"Apache-2.0"
] | 1 | 2021-09-09T03:17:23.000Z | 2021-09-09T03:17:23.000Z | libpandabase/tests/type_converter_tests.cpp | openharmony-gitee-mirror/ark_runtime_core | 2e6f195caf482dc9607efda7cfb5cc5f98da5598 | [
"Apache-2.0"
] | null | null | null | libpandabase/tests/type_converter_tests.cpp | openharmony-gitee-mirror/ark_runtime_core | 2e6f195caf482dc9607efda7cfb5cc5f98da5598 | [
"Apache-2.0"
] | 1 | 2021-09-13T11:21:57.000Z | 2021-09-13T11:21:57.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "utils/type_converter.h"
#include <sstream>
#include <random>
#include <gtest/gtest.h>
#ifndef PANDA_NIGHTLY_TEST_ON
constexpr size_t ITERATION = 64;
#else
constexpr size_t ITERATION = 1024;
#endif
namespace panda::helpers::test {
TEST(TimeTest, RandomTimeConverterTest)
{
std::mt19937 gen;
std::uniform_int_distribution<time_t> distrib_nanos_right(0, 1e3 - 1);
std::uniform_int_distribution<time_t> distrib_nanos_left(1, 23);
for (size_t i = 0; i < ITERATION; i++) {
uint64_t left_part_time = distrib_nanos_left(gen);
uint64_t right_part_time = distrib_nanos_right(gen);
ASSERT_NE(TimeConverter(left_part_time), ValueUnit(left_part_time, "ns"));
ASSERT_NE(TimeConverter(right_part_time), ValueUnit(right_part_time, "ns"));
ASSERT_EQ(TimeConverter(left_part_time), ValueUnit(static_cast<double>(left_part_time), "ns"));
ASSERT_EQ(TimeConverter(right_part_time), ValueUnit(static_cast<double>(right_part_time), "ns"));
double expected = left_part_time + right_part_time * 1e-3;
uint64_t nanos = left_part_time * 1e3 + right_part_time;
ASSERT_EQ(TimeConverter(nanos), ValueUnit(expected, "us"));
ASSERT_EQ(TimeConverter(nanos * 1e3), ValueUnit(expected, "ms"));
ASSERT_EQ(TimeConverter(nanos * 1e6), ValueUnit(expected, "s"));
ASSERT_EQ(TimeConverter(nanos * 1e6 * 60), ValueUnit(expected, "m"));
ASSERT_EQ(TimeConverter(nanos * 1e6 * 60 * 60), ValueUnit(expected, "h"));
ASSERT_EQ(TimeConverter(nanos * 1e6 * 60 * 60 * 24), ValueUnit(expected, "day"));
}
}
TEST(TimeTest, RoundTimeConverterTest)
{
ASSERT_EQ(TimeConverter(11'119'272), ValueUnit(11.119, "ms"));
ASSERT_EQ(TimeConverter(11'119'472), ValueUnit(11.119, "ms"));
ASSERT_EQ(TimeConverter(11'119'499), ValueUnit(11.119, "ms"));
ASSERT_EQ(TimeConverter(11'119'500), ValueUnit(11.120, "ms"));
ASSERT_EQ(TimeConverter(11'119'572), ValueUnit(11.120, "ms"));
ASSERT_EQ(TimeConverter(11'119'999), ValueUnit(11.120, "ms"));
}
TEST(MemoryTest, RandomMemoryConverterTest)
{
std::mt19937 gen;
std::uniform_int_distribution<uint64_t> distrib_bytes(1, 1023);
for (size_t i = 0; i < ITERATION; i++) {
uint64_t left_part_bytes = distrib_bytes(gen);
uint64_t right_part_bytes = distrib_bytes(gen);
ASSERT_NE(MemoryConverter(left_part_bytes), ValueUnit(left_part_bytes, "B"));
ASSERT_NE(MemoryConverter(right_part_bytes), ValueUnit(right_part_bytes, "B"));
ASSERT_EQ(MemoryConverter(left_part_bytes), ValueUnit(static_cast<double>(left_part_bytes), "B"));
ASSERT_EQ(MemoryConverter(right_part_bytes), ValueUnit(static_cast<double>(right_part_bytes), "B"));
double expected = left_part_bytes + right_part_bytes * 1e-3;
uint64_t bytes = left_part_bytes * 1024 + right_part_bytes;
ASSERT_EQ(MemoryConverter(bytes), ValueUnit(expected, "KB"));
ASSERT_EQ(MemoryConverter(bytes * (1UL << 10)), ValueUnit(expected, "MB"));
ASSERT_EQ(MemoryConverter(bytes * (1UL << 20)), ValueUnit(expected, "GB"));
ASSERT_EQ(MemoryConverter(bytes * (1UL << 30)), ValueUnit(expected, "TB"));
}
}
TEST(MemoryTest, RoundMemoryConverterTest)
{
ASSERT_EQ(MemoryConverter(11'119'272), ValueUnit(10.604, "MB"));
ASSERT_EQ(MemoryConverter(11'120'149), ValueUnit(10.605, "MB"));
ASSERT_EQ(MemoryConverter(11'121'092), ValueUnit(10.606, "MB"));
}
} // namespace panda::helpers::test
| 43.147368 | 108 | 0.706758 |
9b7950992e4d849dbac86ca9d939085a949e337a | 19,891 | cpp | C++ | cplus/libcfint/CFIntSubProjectEditObj.cpp | msobkow/cfint_2_13 | 63ff9dfc85647066d0c8d61469ada572362e2b48 | [
"Apache-2.0"
] | null | null | null | cplus/libcfint/CFIntSubProjectEditObj.cpp | msobkow/cfint_2_13 | 63ff9dfc85647066d0c8d61469ada572362e2b48 | [
"Apache-2.0"
] | null | null | null | cplus/libcfint/CFIntSubProjectEditObj.cpp | msobkow/cfint_2_13 | 63ff9dfc85647066d0c8d61469ada572362e2b48 | [
"Apache-2.0"
] | null | null | null | // Description: C++18 edit object instance implementation for CFInt SubProject.
/*
* org.msscf.msscf.CFInt
*
* Copyright (c) 2020 Mark Stephen Sobkow
*
* MSS Code Factory CFInt 2.13 Internet Essentials
*
* Copyright 2020-2021 Mark Stephen Sobkow
*
* This file is part of MSS Code Factory.
*
* MSS Code Factory is available under dual commercial license from Mark Stephen
* Sobkow, or under the terms of the GNU General Public License, Version 3
* or later.
*
* MSS Code Factory is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MSS Code Factory 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 MSS Code Factory. If not, see <https://www.gnu.org/licenses/>.
*
* Donations to support MSS Code Factory can be made at
* https://www.paypal.com/paypalme2/MarkSobkow
*
* Please contact Mark Stephen Sobkow at mark.sobkow@gmail.com for commercial licensing.
*
* Manufactured by MSS Code Factory 2.12
*/
#include <cflib/ICFLibPublic.hpp>
using namespace std;
#include <cfint/ICFIntPublic.hpp>
#include <cfintobj/ICFIntObjPublic.hpp>
#include <cfintobj/CFIntSubProjectObj.hpp>
#include <cfintobj/CFIntSubProjectEditObj.hpp>
namespace cfint {
const std::string CFIntSubProjectEditObj::CLASS_NAME( "CFIntSubProjectEditObj" );
CFIntSubProjectEditObj::CFIntSubProjectEditObj( cfint::ICFIntSubProjectObj* argOrig )
: ICFIntSubProjectEditObj()
{
static const std::string S_ProcName( "CFIntSubProjectEditObj-construct" );
static const std::string S_OrigBuff( "origBuff" );
orig = argOrig;
cfint::CFIntSubProjectBuff* origBuff = orig->getBuff();
if( origBuff == NULL ) {
throw cflib::CFLibNullArgumentException( CLASS_NAME,
S_ProcName,
0,
S_OrigBuff );
}
buff = dynamic_cast<cfint::CFIntSubProjectBuff*>( origBuff->clone() );
}
CFIntSubProjectEditObj::~CFIntSubProjectEditObj() {
orig = NULL;
if( buff != NULL ) {
delete buff;
buff = NULL;
}
}
const std::string& CFIntSubProjectEditObj::getClassName() const {
return( CLASS_NAME );
}
cfsec::ICFSecSecUserObj* CFIntSubProjectEditObj::getCreatedBy() {
if( createdBy == NULL ) {
createdBy = dynamic_cast<cfint::ICFIntSchemaObj*>( getSchema() )->getSecUserTableObj()->readSecUserByIdIdx( getSubProjectBuff()->getCreatedByUserId() );
}
return( createdBy );
}
const std::chrono::system_clock::time_point& CFIntSubProjectEditObj::getCreatedAt() {
return( getSubProjectBuff()->getCreatedAt() );
}
cfsec::ICFSecSecUserObj* CFIntSubProjectEditObj::getUpdatedBy() {
if( updatedBy == NULL ) {
updatedBy = dynamic_cast<cfint::ICFIntSchemaObj*>( getSchema() )->getSecUserTableObj()->readSecUserByIdIdx( getSubProjectBuff()->getUpdatedByUserId() );
}
return( updatedBy );
}
const std::chrono::system_clock::time_point& CFIntSubProjectEditObj::getUpdatedAt() {
return( getSubProjectBuff()->getUpdatedAt() );
}
void CFIntSubProjectEditObj::setCreatedBy( cfsec::ICFSecSecUserObj* value ) {
createdBy = value;
if( value != NULL ) {
getSubProjectEditBuff()->setCreatedByUserId( value->getRequiredSecUserIdReference() );
}
}
void CFIntSubProjectEditObj::setCreatedAt( const std::chrono::system_clock::time_point& value ) {
getSubProjectEditBuff()->setCreatedAt( value );
}
void CFIntSubProjectEditObj::setUpdatedBy( cfsec::ICFSecSecUserObj* value ) {
updatedBy = value;
if( value != NULL ) {
getSubProjectEditBuff()->setUpdatedByUserId( value->getRequiredSecUserIdReference() );
}
}
void CFIntSubProjectEditObj::setUpdatedAt( const std::chrono::system_clock::time_point& value ) {
getSubProjectEditBuff()->setUpdatedAt( value );
}
const classcode_t CFIntSubProjectEditObj::getClassCode() const {
return( cfint::CFIntSubProjectBuff::CLASS_CODE );
}
bool CFIntSubProjectEditObj::implementsClassCode( const classcode_t value ) const {
if( value == cfint::CFIntSubProjectBuff::CLASS_CODE ) {
return( true );
}
else {
return( false );
}
}
std::string CFIntSubProjectEditObj::toString() {
static const std::string S_Space( " " );
static const std::string S_Preamble( "<CFIntSubProjectEditObj" );
static const std::string S_Postamble( "/>" );
static const std::string S_Revision( "Revision" );
static const std::string S_CreatedBy( "CreatedBy" );
static const std::string S_CreatedAt( "CreatedAt" );
static const std::string S_UpdatedBy( "UpdatedBy" );
static const std::string S_UpdatedAt( "UpdatedAt" );
static const std::string S_TenantId( "TenantId" );
static const std::string S_Id( "Id" );
static const std::string S_TopProjectId( "TopProjectId" );
static const std::string S_Name( "Name" );
static const std::string S_Description( "Description" );
std::string ret( S_Preamble );
ret.append( cflib::CFLibXmlUtil::formatRequiredInt32( &S_Space, S_Revision, CFIntSubProjectEditObj::getRequiredRevision() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_CreatedBy, CFIntSubProjectEditObj::getCreatedBy()->toString() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredTZTimestamp( &S_Space, S_CreatedAt, CFIntSubProjectEditObj::getCreatedAt() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_UpdatedBy, CFIntSubProjectEditObj::getUpdatedBy()->toString() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredTZTimestamp( &S_Space, S_UpdatedAt, CFIntSubProjectEditObj::getUpdatedAt() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredInt64( &S_Space, S_TenantId, CFIntSubProjectEditObj::getRequiredTenantId() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredInt64( &S_Space, S_Id, CFIntSubProjectEditObj::getRequiredId() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredInt64( &S_Space, S_TopProjectId, CFIntSubProjectEditObj::getRequiredTopProjectId() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_Name, CFIntSubProjectEditObj::getRequiredName() ) );
if( ! CFIntSubProjectEditObj::isOptionalDescriptionNull() ) {
ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_Description, CFIntSubProjectEditObj::getOptionalDescriptionValue() ) );
}
ret.append( S_Postamble );
return( ret );
}
int32_t CFIntSubProjectEditObj::getRequiredRevision() const {
return( buff->getRequiredRevision() );
}
void CFIntSubProjectEditObj::setRequiredRevision( int32_t value ) {
getSubProjectEditBuff()->setRequiredRevision( value );
}
std::string CFIntSubProjectEditObj::getObjName() {
std::string objName( CLASS_NAME ); objName;
objName.clear();
objName.append( getRequiredName() );
return( objName );
}
const std::string CFIntSubProjectEditObj::getGenDefName() {
return( cfint::CFIntSubProjectBuff::GENDEFNAME );
}
cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getScope() {
cfint::ICFIntTopProjectObj* scope = getRequiredContainerParentTPrj();
return( scope );
}
cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getObjScope() {
cfint::ICFIntTopProjectObj* scope = getRequiredContainerParentTPrj();
return( scope );
}
cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getObjQualifier( const classcode_t* qualifyingClass ) {
cflib::ICFLibAnyObj* container = this;
if( qualifyingClass != NULL ) {
while( container != NULL ) {
if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) {
break;
}
else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) {
break;
}
else if( container->implementsClassCode( *qualifyingClass ) ) {
break;
}
container = container->getObjScope();
}
}
else {
while( container != NULL ) {
if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) {
break;
}
else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) {
break;
}
container = container->getObjScope();
}
}
return( container );
}
cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getNamedObject( const classcode_t* qualifyingClass, const std::string& objName ) {
cflib::ICFLibAnyObj* topContainer = getObjQualifier( qualifyingClass );
if( topContainer == NULL ) {
return( NULL );
}
cflib::ICFLibAnyObj* namedObject = topContainer->getNamedObject( objName );
return( namedObject );
}
cflib::ICFLibAnyObj* CFIntSubProjectEditObj::getNamedObject( const std::string& objName ) {
std::string nextName;
std::string remainingName;
cflib::ICFLibAnyObj* subObj = NULL;
cflib::ICFLibAnyObj* retObj;
int32_t nextDot = objName.find( '.' );
if( nextDot >= 0 ) {
nextName = objName.substr( 0, nextDot );
remainingName = objName.substr( nextDot + 1 );
}
else {
nextName.clear();
nextName.append( objName );
remainingName.clear();
}
if( subObj == NULL ) {
subObj = dynamic_cast<ICFIntSchemaObj*>( getSchema() )->getMajorVersionTableObj()->readMajorVersionByLookupNameIdx( getRequiredTenantId(),
getRequiredId(),
nextName,
false );
}
if( remainingName.length() <= 0 ) {
retObj = subObj;
}
else if( subObj == NULL ) {
retObj = NULL;
}
else {
retObj = subObj->getNamedObject( remainingName );
}
return( retObj );
}
std::string CFIntSubProjectEditObj::getObjQualifiedName() {
const static std::string S_Dot( "." );
std::string qualName( getObjName() );
cflib::ICFLibAnyObj* container = getObjScope();
std::string containerName;
std::string buildName;
while( container != NULL ) {
if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) {
container = NULL;
}
else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) {
container = NULL;
}
else if( container->implementsClassCode( cfsec::CFSecTenantBuff::CLASS_CODE ) ) {
container = NULL;
}
else {
containerName = container->getObjName();
buildName.clear();
buildName.append( containerName );
buildName.append( S_Dot );
buildName.append( qualName );
qualName.clear();
qualName.append( buildName );
container = container->getObjScope();
}
}
return( qualName );
}
std::string CFIntSubProjectEditObj::getObjFullName() {
const static std::string S_Dot( "." );
std::string fullName = getObjName();
cflib::ICFLibAnyObj* container = getObjScope();
std::string containerName;
std::string buildName;
while( container != NULL ) {
if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) {
container = NULL;
}
else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) {
container = NULL;
}
else {
containerName = container->getObjName();
buildName.clear();
buildName.append( containerName );
buildName.append( S_Dot );
buildName.append( fullName );
fullName.clear();
fullName.append( buildName );
container = container->getObjScope();
}
}
return( fullName );
}
cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::realize() {
// We realize this so that it's buffer will get copied to orig during realization
cfint::ICFIntSubProjectObj* retobj = getSchema()->getSubProjectTableObj()->realizeSubProject( dynamic_cast<cfint::ICFIntSubProjectObj*>( this ) );
return( retobj );
}
cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::read( bool forceRead ) {
cfint::ICFIntSubProjectObj* retval = getOrigAsSubProject()->read( forceRead );
if( retval != orig ) {
throw cflib::CFLibUsageException( CLASS_NAME,
"read",
"retval != orig" );
}
copyOrigToBuff();
return( retval );
}
cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::create() {
cfint::ICFIntSubProjectObj* retobj = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsSubProject()->getSchema() )->getSubProjectTableObj()->createSubProject( this );
// Note that this instance is usually discarded during the creation process,
// and retobj now references the cached instance of the created object.
return( retobj );
}
cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::update() {
getSchema()->getSubProjectTableObj()->updateSubProject( this );
return( NULL );
}
cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::deleteInstance() {
static const std::string S_MethodName( "deleteInstance" );
static const std::string S_CannotDeleteNewInstance( "Cannot delete a new instance" );
if( getIsNew() ) {
throw cflib::CFLibUsageException( CLASS_NAME, S_MethodName, S_CannotDeleteNewInstance );
}
getSchema()->getSubProjectTableObj()->deleteSubProject( this );
return( NULL );
}
cfint::ICFIntSubProjectTableObj* CFIntSubProjectEditObj::getSubProjectTable() {
return( orig->getSchema()->getSubProjectTableObj() );
}
cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::getEdit() {
return( this );
}
cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::getSubProjectEdit() {
return( (cfint::ICFIntSubProjectEditObj*)this );
}
cfint::ICFIntSubProjectEditObj* CFIntSubProjectEditObj::beginEdit() {
static const std::string S_ProcName( "beginEdit" );
static const std::string S_Message( "Cannot edit an edition" );
throw cflib::CFLibUsageException( CLASS_NAME,
S_ProcName,
S_Message );
}
void CFIntSubProjectEditObj::endEdit() {
orig->endEdit();
}
cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::getOrig() {
return( orig );
}
cfint::ICFIntSubProjectObj* CFIntSubProjectEditObj::getOrigAsSubProject() {
return( dynamic_cast<cfint::ICFIntSubProjectObj*>( orig ) );
}
cfint::ICFIntSchemaObj* CFIntSubProjectEditObj::getSchema() {
return( orig->getSchema() );
}
cfint::CFIntSubProjectBuff* CFIntSubProjectEditObj::getBuff() {
return( buff );
}
void CFIntSubProjectEditObj::setBuff( cfint::CFIntSubProjectBuff* value ) {
if( buff != value ) {
if( ( buff != NULL ) && ( buff != value ) ) {
delete buff;
buff = NULL;
}
buff = value;
}
}
cfint::CFIntSubProjectPKey* CFIntSubProjectEditObj::getPKey() {
return( orig->getPKey() );
}
void CFIntSubProjectEditObj::setPKey( cfint::CFIntSubProjectPKey* value ) {
if( orig->getPKey() != value ) {
orig->setPKey( value );
}
copyPKeyToBuff();
}
bool CFIntSubProjectEditObj::getIsNew() {
return( orig->getIsNew() );
}
void CFIntSubProjectEditObj::setIsNew( bool value ) {
orig->setIsNew( value );
}
const int64_t CFIntSubProjectEditObj::getRequiredTenantId() {
return( getPKey()->getRequiredTenantId() );
}
const int64_t* CFIntSubProjectEditObj::getRequiredTenantIdReference() {
return( getPKey()->getRequiredTenantIdReference() );
}
const int64_t CFIntSubProjectEditObj::getRequiredId() {
return( getPKey()->getRequiredId() );
}
const int64_t* CFIntSubProjectEditObj::getRequiredIdReference() {
return( getPKey()->getRequiredIdReference() );
}
const int64_t CFIntSubProjectEditObj::getRequiredTopProjectId() {
return( getSubProjectBuff()->getRequiredTopProjectId() );
}
const int64_t* CFIntSubProjectEditObj::getRequiredTopProjectIdReference() {
return( getSubProjectBuff()->getRequiredTopProjectIdReference() );
}
const std::string& CFIntSubProjectEditObj::getRequiredName() {
return( getSubProjectBuff()->getRequiredName() );
}
const std::string* CFIntSubProjectEditObj::getRequiredNameReference() {
return( getSubProjectBuff()->getRequiredNameReference() );
}
void CFIntSubProjectEditObj::setRequiredName( const std::string& value ) {
if( getSubProjectBuff()->getRequiredName() != value ) {
getSubProjectEditBuff()->setRequiredName( value );
}
}
bool CFIntSubProjectEditObj::isOptionalDescriptionNull() {
return( getSubProjectBuff()->isOptionalDescriptionNull() );
}
const std::string& CFIntSubProjectEditObj::getOptionalDescriptionValue() {
return( getSubProjectBuff()->getOptionalDescriptionValue() );
}
const std::string* CFIntSubProjectEditObj::getOptionalDescriptionReference() {
return( getSubProjectBuff()->getOptionalDescriptionReference() );
}
void CFIntSubProjectEditObj::setOptionalDescriptionNull() {
if( ! getSubProjectBuff()->isOptionalDescriptionNull() ) {
getSubProjectEditBuff()->setOptionalDescriptionNull();
}
}
void CFIntSubProjectEditObj::setOptionalDescriptionValue( const std::string& value ) {
if( getSubProjectBuff()->isOptionalDescriptionNull() ) {
getSubProjectEditBuff()->setOptionalDescriptionValue( value );
}
else if( getSubProjectBuff()->getOptionalDescriptionValue() != value ) {
getSubProjectEditBuff()->setOptionalDescriptionValue( value );
}
}
cfsec::ICFSecTenantObj* CFIntSubProjectEditObj::getRequiredOwnerTenant( bool forceRead ) {
cfsec::ICFSecTenantObj* retobj = NULL;
bool anyMissing = false;
if( ! anyMissing ) {
retobj = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsSubProject()->getSchema() )->getTenantTableObj()->readTenantByIdIdx( getPKey()->getRequiredTenantId() );
}
return( retobj );
}
void CFIntSubProjectEditObj::setRequiredOwnerTenant( cfsec::ICFSecTenantObj* value ) {
if( value != NULL ) {
getPKey()->setRequiredTenantId
( value->getRequiredId() );
getSubProjectEditBuff()->setRequiredTenantId( value->getRequiredId() );
}
}
cfint::ICFIntTopProjectObj* CFIntSubProjectEditObj::getRequiredContainerParentTPrj( bool forceRead ) {
cfint::ICFIntTopProjectObj* retobj = NULL;
bool anyMissing = false;
if( ! anyMissing ) {
retobj = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsSubProject()->getSchema() )->getTopProjectTableObj()->readTopProjectByIdIdx( getPKey()->getRequiredTenantId(),
getSubProjectBuff()->getRequiredTopProjectId() );
}
return( retobj );
}
void CFIntSubProjectEditObj::setRequiredContainerParentTPrj( cfint::ICFIntTopProjectObj* value ) {
if( value != NULL ) {
getPKey()->setRequiredTenantId
( value->getRequiredTenantId() );
getSubProjectEditBuff()->setRequiredTenantId( value->getRequiredTenantId() );
getSubProjectEditBuff()->setRequiredTopProjectId( value->getRequiredId() );
}
}
std::vector<cfint::ICFIntMajorVersionObj*> CFIntSubProjectEditObj::getOptionalComponentsMajorVer( bool forceRead ) {
std::vector<cfint::ICFIntMajorVersionObj*> retval;
retval = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsSubProject()->getSchema() )->getMajorVersionTableObj()->readMajorVersionBySubProjectIdx( getPKey()->getRequiredTenantId(),
getPKey()->getRequiredId(),
forceRead );
return( retval );
}
void CFIntSubProjectEditObj::copyPKeyToBuff() {
cfint::CFIntSubProjectPKey* tablePKey = getPKey();
cfint::CFIntSubProjectBuff* tableBuff = getSubProjectEditBuff();
tableBuff->setRequiredTenantId( tablePKey->getRequiredTenantId() );
tableBuff->setRequiredId( tablePKey->getRequiredId() );
}
void CFIntSubProjectEditObj::copyBuffToPKey() {
cfint::CFIntSubProjectPKey* tablePKey = getPKey();
cfint::CFIntSubProjectBuff* tableBuff = getSubProjectBuff();
tablePKey->setRequiredTenantId( tableBuff->getRequiredTenantId() );
tablePKey->setRequiredId( tableBuff->getRequiredId() );
}
void CFIntSubProjectEditObj::copyBuffToOrig() {
cfint::CFIntSubProjectBuff* origBuff = getOrigAsSubProject()->getSubProjectEditBuff();
cfint::CFIntSubProjectBuff* myBuff = getSubProjectBuff();
if( origBuff != myBuff ) {
*origBuff = *myBuff;
}
}
void CFIntSubProjectEditObj::copyOrigToBuff() {
cfint::CFIntSubProjectBuff* origBuff = getOrigAsSubProject()->getSubProjectBuff();
cfint::CFIntSubProjectBuff* myBuff = getSubProjectEditBuff();
if( origBuff != myBuff ) {
*myBuff = *origBuff;
}
}
}
| 34.413495 | 181 | 0.727062 |
f926c57c62e11c0191895d80560b45d9e36323fa | 19,255 | cpp | C++ | kernel/Scheduler.cpp | SmkViper/CranberryOS | ef4823aa526cf9e2b1ab05f01c87528a8bfff5c6 | [
"MIT"
] | null | null | null | kernel/Scheduler.cpp | SmkViper/CranberryOS | ef4823aa526cf9e2b1ab05f01c87528a8bfff5c6 | [
"MIT"
] | null | null | null | kernel/Scheduler.cpp | SmkViper/CranberryOS | ef4823aa526cf9e2b1ab05f01c87528a8bfff5c6 | [
"MIT"
] | null | null | null | #include "Scheduler.h"
#include <cstring>
#include <new>
#include "ARM/SchedulerDefines.h"
#include "IRQ.h"
#include "MemoryManager.h"
#include "Timer.h"
// How the scheduler currently works:
//
// CopyProcess creates a new memory page and puts the task struct at the bottom of the page, with the stack pointer
// pointing at a certain distance above it.
//
// 0xXXXXXXXX +--------------------+ ^
// | TaskStruct | |
// +--------------------+ | One page
// | | |
// | Stack (grows up) | |
// +--------------------+ |
// | ProcessState | |
// 0xXXXX1000 +--------------------+ v
//
// ScheduleImpl is called, either voluntarily or via timer
// cpu_switch_to saves all callee-saved registers in the current task to the TaskStruct context member
// cpu_switch_to "restores" all callee-saved registers for the new task, setting sp to 0xXXXX1000, the link register
// to ret_from_create, x19 to the task's process function, and x20 to the process function parameter
// cpu_switch_to returns, loading ret_from_create's address from the link register
// ret_from_create reads from x19 and x20, and calls to the function in x19, passing it x20
//
// Eventually a timer interrupt happens, saving all registers + elr_el1 and spsr_el1 to the bottom of the current
// task's stack
//
// 0xXXXXXXXX +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xXXXX1000 +----------------------+
//
// The current task is now handling an interrupt, and grows a little bit more on the stack to pick the task to resume
//
// 0xXXXXXXXX +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Stack (interrupt) |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xXXXX1000 +----------------------+
//
// The interrupt picks a second new task to run, repeating the process performed for the first task to set up the
// second new task. This task begins executing and growing its own stack. Note that execution is still in the timer
// interrupt handler, but interrupts have been re-enabled at this point, so another timer can come in again.
//
// 0xXXXXXXXX +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Stack (interrupt) |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xXXXX1000 +----------------------+
// | ... |
// 0xYYYYYYYY +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xYYYY1000 +----------------------+
//
// Another timer interrupt happens, and the process repeats to save off all the registers, elr_el1 and spsr_el1 at the
// bottom of the second task's stack, and the interrupt stack for that task starts to grow
//
// 0xXXXXXXXX +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Stack (interrupt) |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xXXXX1000 +----------------------+
// | ... |
// 0xYYYYYYYY +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Stack (interrupt) |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xYYYY1000 +----------------------+
//
// ScheduleImpl is now called, and notes that both tasks have their counter at 0. It then sets the counters to their
// priority and picks the first task to run again. (Though it could pick either if their priorities were the same)
// cpu_switch_to is called and it restores all the callee-saved registers from the first task context. The link
// register now points at the end of the SwitchTo function, since that's what it was the last time this task was
// running. The stack pointer also is set to point at the bottom of the first task's interrupt stack.
// The TimerTick function now resumes execution, disabling interrupts again and returns to the interrupt handler,
// collapsing the interrupt stack to 0.
//
// 0xXXXXXXXX +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xXXXX1000 +----------------------+
// | ... |
// 0xYYYYYYYY +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Stack (interrupt) |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xYYYY1000 +----------------------+
//
// The interrupt cleans up, restoring all the regsters that were saved from the stack, including the elr_el1 and
// spsr_el1 registers. elr_el1 now points somewhere in the middle of the process function (wherever the interrupt)
// originally happened. And sp now points at the bottom of the task's original stack
//
// 0xXXXXXXXX +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xXXXX1000 +----------------------+
// | ... |
// 0xYYYYYYYY +----------------------+
// | TaskStruct |
// +----------------------+
// | |
// +----------------------+
// | Stack (interrupt) |
// +----------------------+
// | Task saved registers |
// +----------------------+
// | Stack (grows up) |
// +----------------------+
// | ProcessState |
// 0xYYYY1000 +----------------------+
//
// The eret instruction is executed, using the saved elr_el1 register to jump back to whatever the first task was doing
namespace
{
// SPSR_EL1 bits - See section C5.2.18 in the ARMv8 manual
constexpr uint64_t PSRModeEL0tC = 0x00000000;
struct CPUContext
{
// ARM calling conventions allow registers x0-x18 to be overwritten by a called function,
// so we don't need to save those off
//
// #TODO: May need to save off additional registers (i.e. SIMD/FP registers?)
uint64_t x19 = 0;
uint64_t x20 = 0;
uint64_t x21 = 0;
uint64_t x22 = 0;
uint64_t x23 = 0;
uint64_t x24 = 0;
uint64_t x25 = 0;
uint64_t x26 = 0;
uint64_t x27 = 0;
uint64_t x28 = 0;
uint64_t fp = 0; // x29
uint64_t sp = 0;
uint64_t pc = 0; // x30
};
enum class TaskState : int64_t
{
Running,
Zombie
};
struct TaskStruct
{
CPUContext Context;
TaskState State = TaskState::Running;
int64_t Counter = 0; // decrements each timer tick. When reaches 0, another task will be scheduled
int64_t Priority = 1; // copied to Counter when a task is scheduled, so higher priority will run for longer
int64_t PreemptCount = 0; // If non-zero, task will not be preempted
void* pStack = nullptr; // pointer to the stack root so it can be cleaned up if necessary
uint64_t Flags = 0;
};
// Expected to match what is put on the stack via the kernel_entry macro in the exception handler so it can
// "restore" the processor state we want
struct ProcessState
{
uint64_t Registers[31] = {0u};
uint64_t StackPointer = 0u;
uint64_t ProgramCounter = 0u;
uint64_t ProcessorState = 0u;
};
static_assert(offsetof(TaskStruct, Context) == TASK_STRUCT_CONTEXT_OFFSET, "Unexpected offset of context in task struct");
}
extern "C"
{
/**
* Return to the newly created task (Defined in ExceptionVectors.S)
*/
extern void ret_from_create();
/**
* Switch the CPU from running the previous task to the next task
*
* @param apPrev The previously running task
* @param apNext The new task to resume
*/
extern void cpu_switch_to(TaskStruct* apPrev, TaskStruct* apNext);
}
namespace
{
constexpr auto TimerTickMSC = 200; // tick every 200ms
constexpr auto ThreadSizeC = 4096; // 4k stack size (#TODO: Pull from page size?)
constexpr auto NumberOfTasksC = 64u;
TaskStruct InitTask; // task running kernel init
TaskStruct* pCurrentTask = &InitTask;
TaskStruct* Tasks[NumberOfTasksC] = {&InitTask, nullptr};
auto NumberOfTasks = 1;
/**
* Enable scheduler preemption in the current task
*/
void PreemptEnable()
{
// #TODO: Assert/error when we have it
--pCurrentTask->PreemptCount;
}
/**
* Disable scheduler preemption in the current task
*/
void PreemptDisable()
{
++pCurrentTask->PreemptCount;
}
/**
* Helper to disable scheduler preempting in the current scope
*/
struct DisablePreemptingInScope
{
/**
* Constructor - disables scheduler preempting
*/
[[nodiscard]] DisablePreemptingInScope()
{
PreemptDisable();
}
/**
* Destructor - reenables scheduler preempting
*/
~DisablePreemptingInScope()
{
PreemptEnable();
}
// Disable copying
DisablePreemptingInScope(const DisablePreemptingInScope&) = delete;
DisablePreemptingInScope& operator=(const DisablePreemptingInScope&) = delete;
};
/**
* Switch from running the current task to the next task
*
* @param apNextTask The next task to run
*/
void SwitchTo(TaskStruct* const apNextTask)
{
if (pCurrentTask == apNextTask)
{
return;
}
const auto pprevTask = pCurrentTask;
pCurrentTask = apNextTask;
cpu_switch_to(pprevTask, apNextTask);
}
/**
* Find and resume a running task
*/
void ScheduleImpl()
{
// Make sure we don't get called while we're in the middle of picking a task
DisablePreemptingInScope disablePreempt;
auto foundTask = false;
auto taskToResume = 0u;
while (!foundTask)
{
// Find the task with the largest counter value (i.e. the one that has the highest priority that has
// not run in a while)
auto largestCounter = -1ll;
taskToResume = 0;
for (auto curTask = 0u; curTask < NumberOfTasksC; ++curTask)
{
const auto ptask = Tasks[curTask];
if (ptask && (ptask->State == TaskState::Running) && (ptask->Counter > largestCounter))
{
largestCounter = ptask->Counter;
taskToResume = curTask;
}
}
// If we don't find any running task with a non-zero counter, then we need to go and reset all their
// counters according to their priority
foundTask = (largestCounter > 0);
if (!foundTask)
{
for (const auto pcurTask : Tasks)
{
if (pcurTask)
{
// Increment the counter by the priority, ensuring that we don't go above 2 * priority
// So the longer the task has been waiting, the higher the counter should be.
pcurTask->Counter = (pcurTask->Counter / 1) + pcurTask->Priority;
}
}
}
// If at least one task is running, then we should only loop around once. If all tasks are not running
// then we keep looping until a task changes its state to running again (i.e. via an interrupt)
}
SwitchTo(Tasks[taskToResume]);
}
/**
* Triggered by the timer interrupt to schedule a new task
*
* @param apParam The parameter registered for our callback
*/
void TimerTick(const void* /*apParam*/)
{
// Only switch task if the counter has run out and it hasn't been blocked
--pCurrentTask->Counter;
if ((pCurrentTask->Counter > 0) || (pCurrentTask->PreemptCount > 0))
{
return;
}
pCurrentTask->Counter = 0;
// Interrupts are disabled while handing one, so re-enable them for the schedule call because some tasks
// might be waiting from an interrupt and we want them to be able to get them while the scheduler is trying
// to find a task (otherwise we might just have all tasks waiting for interrupts and loop forever without
// finding a task to run)
enable_irq();
ScheduleImpl();
// And re-disable them before returning to the interrupt handler (which will deal with re-enabling them later)
disable_irq();
}
/**
* Extract the state memory from the stack for the given task
*
* @param apTask Task to get the state for
* @return The process state for the task
*/
void* GetTargetStateMemoryForTask(TaskStruct* apTask)
{
const auto state = reinterpret_cast<uintptr_t>(apTask) + ThreadSizeC - sizeof(ProcessState);
return reinterpret_cast<void*>(state);
}
}
extern "C"
{
/**
* Called by assembly to finish any work up before staring the process call
*/
void schedule_tail()
{
PreemptEnable();
}
}
namespace Scheduler
{
void InitTimer()
{
// We're using a local timer instead of the global timer because it works on both QEMU and real hardware
LocalTimer::RegisterCallback(TimerTickMSC, TimerTick, nullptr);
}
void Schedule()
{
pCurrentTask->Counter = 0;
ScheduleImpl();
}
int CreateProcess(const uint32_t aCreateFlags, ProcessFunctionPtr apProcessFn, const void* apParam, void* apStack)
{
// Make sure we don't get preempted in the middle of making a new task
DisablePreemptingInScope disablePreempt;
auto pmemory = reinterpret_cast<uint8_t*>(MemoryManager::GetFreePage());
if (pmemory == nullptr)
{
return -1;
}
auto pnewTask = new (pmemory) TaskStruct{};
const auto puninitializedState = reinterpret_cast<uint8_t*>(GetTargetStateMemoryForTask(pnewTask));
const auto pnewState = new (puninitializedState) ProcessState{};
if ((aCreateFlags & CreationFlags::KernelThreadC) == CreationFlags::KernelThreadC)
{
pnewTask->Context.x19 = reinterpret_cast<uint64_t>(apProcessFn);
pnewTask->Context.x20 = reinterpret_cast<uint64_t>(apParam);
}
else
{
// extract and clone the current processor state
const auto psourceState = reinterpret_cast<ProcessState*>(GetTargetStateMemoryForTask(pCurrentTask));
*pnewState = *psourceState;
pnewState->Registers[0] = 0; // make sure ret_from_create knows this is the new user process
pnewState->StackPointer = reinterpret_cast<uint64_t>(apStack) + ThreadSizeC;
pnewTask->pStack = apStack;
}
pnewTask->Flags = aCreateFlags;
pnewTask->Priority = pCurrentTask->Priority;
pnewTask->Counter = pnewTask->Priority;
pnewTask->PreemptCount = 1; // disable preemption until schedule_tail
pnewTask->Context.pc = reinterpret_cast<uint64_t>(ret_from_create);
pnewTask->Context.sp = reinterpret_cast<uint64_t>(pnewState);
const auto processID = NumberOfTasks++;
Tasks[processID] = pnewTask;
return processID;
}
bool MoveToUserMode(UserModeFunctionPtr apUserModeFn)
{
const auto puninitializedState = reinterpret_cast<uint8_t*>(GetTargetStateMemoryForTask(pCurrentTask));
auto pstate = new (puninitializedState) ProcessState{};
static_assert(sizeof(UserModeFunctionPtr) == sizeof(uint64_t), "Unexpected pointer size");
pstate->ProgramCounter = reinterpret_cast<uint64_t>(apUserModeFn);
pstate->ProcessorState = PSRModeEL0tC;
const auto pstack = MemoryManager::GetFreePage();
if (pstack == nullptr)
{
pstate->~ProcessState();
return false;
}
pstate->StackPointer = reinterpret_cast<uint64_t>(pstack) + ThreadSizeC;
pCurrentTask->pStack = pstack;
return true;
}
void ExitProcess()
{
{
// Make sure we don't get preempted in the middle of cleaning up the task
DisablePreemptingInScope disablePreempt;
// Flag the task as a zombie so it isn't rescheduled
for (const auto pcurTask : Tasks)
{
if (pcurTask == pCurrentTask)
{
pcurTask->State = TaskState::Zombie;
break;
}
}
if (pCurrentTask->pStack)
{
MemoryManager::FreePage(pCurrentTask->pStack);
}
}
// Won't ever return because a new task will be scheduled and this one is now flagged as a zombie
Schedule();
}
} | 36.746183 | 126 | 0.513944 |
f9324ed31b1c1a246663744e94bbe6de7c2e2e05 | 1,525 | cpp | C++ | ip_protocol.cpp | folkertvanheusden/myip | 374802136afad4bd7efafd5931cb04f67c0b4487 | [
"Apache-2.0"
] | 8 | 2021-08-14T11:12:53.000Z | 2021-11-06T08:36:02.000Z | ip_protocol.cpp | folkertvanheusden/myip | 374802136afad4bd7efafd5931cb04f67c0b4487 | [
"Apache-2.0"
] | 8 | 2021-08-22T11:34:10.000Z | 2021-12-29T13:11:07.000Z | ip_protocol.cpp | folkertvanheusden/myip | 374802136afad4bd7efafd5931cb04f67c0b4487 | [
"Apache-2.0"
] | null | null | null | // (C) 2020 by folkert van heusden <mail@vanheusden.com>, released under Apache License v2.0
#include <chrono>
#include "ip_protocol.h"
#include "utils.h"
constexpr size_t pkts_max_size { 512 };
ip_protocol::ip_protocol(stats *const s, const std::string & stats_name)
{
pkts = new fifo<const packet *>(s, stats_name, pkts_max_size);
}
ip_protocol::~ip_protocol()
{
delete pkts;
}
void ip_protocol::queue_packet(const packet *p)
{
if (!pkts->try_put(p))
DOLOG(warning, "IP-Protocol: packet dropped\n");
}
uint16_t tcp_udp_checksum(const any_addr & src_addr, const any_addr & dst_addr, const bool tcp, const uint8_t *const tcp_payload, const int len)
{
uint16_t checksum { 0 };
if (dst_addr.get_len() == 16) { // IPv6
size_t temp_len = 40 + len + (len & 1);
uint8_t *temp = new uint8_t[temp_len]();
src_addr.get(&temp[0], 16);
dst_addr.get(&temp[16], 16);
temp[32] = len >> 24;
temp[33] = len >> 16;
temp[34] = len >> 8;
temp[35] = len;
temp[39] = tcp ? 0x06 : 0x11;
memcpy(&temp[40], tcp_payload, len);
checksum = ip_checksum((const uint16_t *)temp, temp_len / 2);
delete [] temp;
}
else { // IPv4
size_t temp_len = 12 + len + (len & 1);
uint8_t *temp = new uint8_t[temp_len]();
src_addr.get(&temp[0], 4);
dst_addr.get(&temp[4], 4);
temp[9] = tcp ? 0x06 : 0x11;
temp[10] = len >> 8; // TCP len
temp[11] = len;
memcpy(&temp[12], tcp_payload, len);
checksum = ip_checksum((const uint16_t *)temp, temp_len / 2);
delete [] temp;
}
return checksum;
}
| 21.180556 | 144 | 0.645902 |
f932855ce8ff9510153c6fba8ac23fd35798abfb | 999 | cpp | C++ | videocodering/Encoder/Quantiser.cpp | FlashYoshi/UGentProjects | 5561ce3bb73d5bc5bf31bcda2be7e038514c7072 | [
"MIT"
] | null | null | null | videocodering/Encoder/Quantiser.cpp | FlashYoshi/UGentProjects | 5561ce3bb73d5bc5bf31bcda2be7e038514c7072 | [
"MIT"
] | null | null | null | videocodering/Encoder/Quantiser.cpp | FlashYoshi/UGentProjects | 5561ce3bb73d5bc5bf31bcda2be7e038514c7072 | [
"MIT"
] | 1 | 2019-07-18T11:23:49.000Z | 2019-07-18T11:23:49.000Z | #include "Quantiser.h"
#include <math.h>
#include <stdio.h>
// Breng wijzigingen aan in onderstaande methode
// Quantisatie van de luminanitie- en chrominantiecoefficienten.
// De quantisatiestap qp moet bij het encoderen verschillend zijn van nul aangezien deling door nul niet is toegestaan.
int Quantiser::sign(pixel i){
return (i > 0) ? 1 : -1;
}
void Quantiser::Quantise(Macroblock *mb, int qp)
{
//qp mag niet 0 zijn maar we willen wel Quantise uitvoeren
qp++;
//CB en CR zijn 8x8 matrices
for(int i = 0; i < max; i++){
for(int j = 0; j < max; j++){
int cb = mb->cb[i][j];
int cr = mb->cr[i][j];
mb->cb[i][j] = (pixel) (sign(cb) * floor(abs(cb) / qp + 0.5));
mb->cr[i][j] = (pixel) (sign(cr) * floor(abs(cr) / qp + 0.5));
}
}
//Luma moeten we apart doen omdat het een 16x16 matrix is
for (int i = 0; i < 2 * max; i++){
for (int j = 0; j < 2 * max; j++){
int luma = mb->luma[i][j];
mb->luma[i][j] = (pixel) (sign(luma) * floor(abs(luma) / qp + 0.5));
}
}
} | 32.225806 | 119 | 0.608609 |
f9332c89d81651c0bce337bd11e78b7ec79d451c | 4,546 | cpp | C++ | QMC2-crypto/qmc2-crypto/StreamCencrypt.cpp | jixunmoe/qmc2 | 4334a64abb4def3d44b1860ac7c34400e2ada85c | [
"MIT"
] | 76 | 2021-12-12T19:07:30.000Z | 2022-03-30T14:31:30.000Z | QMC2-crypto/qmc2-crypto/StreamCencrypt.cpp | jixunmoe/qmc2 | 4334a64abb4def3d44b1860ac7c34400e2ada85c | [
"MIT"
] | 3 | 2021-12-27T09:21:17.000Z | 2022-03-22T01:59:56.000Z | QMC2-crypto/qmc2-crypto/StreamCencrypt.cpp | jixunmoe/qmc2 | 4334a64abb4def3d44b1860ac7c34400e2ada85c | [
"MIT"
] | 16 | 2021-12-12T19:23:46.000Z | 2022-03-11T15:57:18.000Z | #include "qmc2-crypto/StreamCencrypt.h"
#include <cassert>
#include <cstring>
#include <algorithm>
void StreamCencrypt::StreamEncrypt(uint64_t offset, uint8_t *buf, size_t len)
{
if (N > 300)
{
ProcessByRC4(offset, buf, len);
}
else
{
for (size_t i = 0; i < len; i++)
{
buf[i] ^= mapL(offset + i);
}
}
}
void StreamCencrypt::StreamDecrypt(uint64_t offset, uint8_t *buf, size_t len)
{
this->StreamEncrypt(offset, buf, len);
}
void StreamCencrypt::SetKeyDec(KeyDec *key_dec)
{
Uninit();
rc4_key = nullptr;
if (key_dec)
{
key_dec->GetKey(this->rc4_key, N);
if (N > 300)
{
InitRC4KSA();
}
}
}
void StreamCencrypt::Uninit()
{
// reset initial rc4 key
if (rc4_key)
{
delete[] rc4_key;
rc4_key = nullptr;
}
// reset sbox
this->N = 0;
if (S)
{
delete[] S;
S = nullptr;
}
}
#define FIRST_SEGMENT_SIZE (0x80)
#define SEGMENT_SIZE (0x1400)
void StreamCencrypt::ProcessByRC4(size_t offset, uint8_t *buf, size_t size)
{
uint8_t *orig_buf = buf;
uint8_t *last_addr = orig_buf + size;
auto len = size;
// Initial segment
if (offset < FIRST_SEGMENT_SIZE)
{
auto len_segment = std::min(size, FIRST_SEGMENT_SIZE - offset);
EncFirstSegment(offset, buf, len_segment);
len -= len_segment;
buf += len_segment;
offset += len_segment;
}
// FIXME: Move this as a private member?
uint8_t *S = new uint8_t[N]();
// Align segment
if (offset % SEGMENT_SIZE != 0)
{
auto len_segment = std::min(SEGMENT_SIZE - (offset % SEGMENT_SIZE), len);
EncASegment(S, offset, buf, len_segment);
len -= len_segment;
buf += len_segment;
offset += len_segment;
}
// Batch process segments
while (len > SEGMENT_SIZE)
{
auto len_segment = std::min(size_t{SEGMENT_SIZE}, len);
EncASegment(S, offset, buf, len_segment);
len -= len_segment;
buf += len_segment;
offset += len_segment;
}
// Last segment (incomplete segment)
if (len > 0)
{
EncASegment(S, offset, buf, len);
}
assert(last_addr == buf + len);
delete[] S;
}
uint64_t StreamCencrypt::GetSegmentKey(uint64_t id, uint64_t seed)
{
return uint64_t((double)this->key_hash / double((id + 1) * seed) * 100.0);
}
void StreamCencrypt::EncFirstSegment(size_t offset, uint8_t *buf, size_t len)
{
for (size_t i = 0; i < len; i++)
{
uint64_t key = uint64_t{this->rc4_key[offset % this->N]};
buf[i] ^= this->rc4_key[GetSegmentKey(offset, key) % this->N];
offset++;
}
}
void StreamCencrypt::EncASegment(uint8_t *S, size_t offset, uint8_t *buf, size_t len)
{
if (rc4_key == nullptr)
{
// We need to initialise RC4 key first!
return;
}
const auto N = this->N;
// Initialise a new seedbox
memcpy(S, this->S, N);
// Calculate segment id
int segment_id = (offset / SEGMENT_SIZE) & 0x1FF;
// Calculate the number of bytes to skip.
// The initial "key" derived from segment id, plus the current offset.
auto skip_len = GetSegmentKey(offset / SEGMENT_SIZE, this->rc4_key[segment_id]) & 0x1FF;
skip_len += offset % SEGMENT_SIZE;
int j = 0;
int k = 0;
for (size_t i = 0; i < skip_len; i++)
{
j = (j + 1) % N;
k = (S[j] + k) % N;
std::swap(S[j], S[k]);
}
// Now we also manipulate the buffer:
for (size_t i = 0; i < len; i++)
{
j = (j + 1) % N;
k = (S[j] + k) % N;
std::swap(S[j], S[k]);
buf[i] ^= S[(S[j] + S[k]) % N];
}
}
void StreamCencrypt::InitRC4KSA()
{
if (!S)
{
S = new uint8_t[N]();
}
for (size_t i = 0; i < N; ++i)
{
S[i] = i & 0xFF;
}
int j = 0;
for (size_t i = 0; i < N; ++i)
{
j = (S[i] + j + rc4_key[i % N]) % N;
std::swap(S[i], S[j]);
}
GetHashBase();
}
void StreamCencrypt::GetHashBase()
{
this->key_hash = 1;
for (size_t i = 0; i < this->N; i++)
{
int32_t value = int32_t{this->rc4_key[i]};
// ignore if key char is '\x00'
if (!value)
continue;
auto next_hash = this->key_hash * value;
if (next_hash == 0 || next_hash <= this->key_hash)
break;
this->key_hash = next_hash;
}
}
inline uint8_t rotate(uint8_t value, int bits)
{
int rotate = (bits + 4) % 8;
auto left = value << rotate;
auto right = value >> rotate;
return uint8_t(left | right);
}
// Untested, this might be wrong.
uint8_t StreamCencrypt::mapL(uint64_t offset)
{
if (offset > 0x7FFF)
offset %= 0x7FFF;
uint64_t key = (offset * offset + 71214) % this->N;
uint8_t value = this->rc4_key[key];
return rotate(value, key & 0b0111);
}
| 19.594828 | 90 | 0.602508 |
f935d5845c9b02a9c2aca16f33c9703cce725ceb | 1,475 | cpp | C++ | Deprecated/Debug/Debug.cpp | Theundeadwarrior/Casiope | f21b53b8e51adb9b341269471443b9dc0f61e9d8 | [
"MIT"
] | 3 | 2016-08-04T05:08:59.000Z | 2018-03-28T04:40:43.000Z | Deprecated/Debug/Debug.cpp | Theundeadwarrior/Casiope | f21b53b8e51adb9b341269471443b9dc0f61e9d8 | [
"MIT"
] | 6 | 2016-08-05T17:57:51.000Z | 2018-03-28T04:41:09.000Z | Deprecated/Debug/Debug.cpp | Theundeadwarrior/Casiope | f21b53b8e51adb9b341269471443b9dc0f61e9d8 | [
"MIT"
] | 1 | 2016-08-16T05:40:59.000Z | 2016-08-16T05:40:59.000Z | #include "Debug.h"
#include <assert.h>
#include <stdio.h>
#include <stdarg.h>
#include <string>
#include <Windows.h>
#include <iostream>
namespace Atum
{
namespace Utilities
{
void OutputTrace(char* text, ...)
{
char buffer[256];
va_list args;
va_start (args, text);
vsprintf_s (buffer, text, args);
OutputDebugString (buffer);
va_end (args);
}
void OutputError(char* text, ...)
{
char buffer[256];
va_list args;
va_start (args, text);
vsprintf_s (buffer,text, args);
perror (buffer);
// Make crash?
va_end (args);
}
void OutputAssert( const char* _condition, const char* _message, char* _filename, char* _line )
{
std::string condition(_condition);
std::string message(_message);
std::string file(_filename);
std::string line(_line);
// Remove the path if there is a path
int fileNameBeginPosition = file.find_last_of("\\");
if(fileNameBeginPosition != file.size())
{
file.erase(0,fileNameBeginPosition + 1);
file.erase(file.size() - 1, 1);
}
std::string errorMessage("[ASSERT] Condition: ");
errorMessage.append(condition);
errorMessage.append(" failed. ");
errorMessage.append("Error in file ");
errorMessage.append(file);
errorMessage.append(" at line ");
errorMessage.append(line);
errorMessage.append(". ");
errorMessage.append(message);
OutputDebugString(errorMessage.c_str());
perror(errorMessage.c_str());
// make crash?
}
}
}
| 22.014925 | 97 | 0.660339 |
f93beb17c624eec0a5608f205c92cf140dd92f1b | 5,973 | cpp | C++ | ray/AI.cpp | guille0/space-chess | 3e8a3c8c8b91fbcbc00fbb4b35596a3b2ad1a37c | [
"MIT"
] | 17 | 2019-08-02T16:52:14.000Z | 2021-09-21T15:32:14.000Z | ray/AI.cpp | guille0/space-chess | 3e8a3c8c8b91fbcbc00fbb4b35596a3b2ad1a37c | [
"MIT"
] | 1 | 2020-01-02T07:44:22.000Z | 2020-01-02T07:44:22.000Z | ray/AI.cpp | guille0/space-chess | 3e8a3c8c8b91fbcbc00fbb4b35596a3b2ad1a37c | [
"MIT"
] | 4 | 2019-11-10T17:52:39.000Z | 2022-02-25T14:55:48.000Z | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <limits>
#include "AI.h"
#include "Moves.h"
#include "Board.h"
namespace chess {
AI::AI () {}
AI::AI (long* t_array, int t_maxZ, int t_maxY, int t_maxX, int t_turn, bool t_pawn2step)
: m_maxZ(t_maxZ), m_maxY(t_maxY), m_maxX(t_maxX), m_startingTurn(t_turn), m_pawn2step(t_pawn2step){
m_chessboard = Board(t_array, t_maxZ, t_maxY, t_maxX, t_turn, t_pawn2step);
}
AI::~AI () {}
void AI::setBoard(long* t_array, int t_turn) {
m_chessboard = Board(t_array, m_maxZ, m_maxY, m_maxX, t_turn, m_pawn2step);
}
// Getters and setters
Board AI::getBoard() {
return m_chessboard;
}
std::string AI::boardToString() {
return m_chessboard.toString();
}
std::vector<std::pair<std::vector<int>,std::vector<int>>> AI::getMoves() {
std::vector<std::pair<std::vector<int>,std::vector<int>>> moves;
// get every single move we could make (including moves that would put our king in danger)
moves = m_chessboard.possibleMoves(m_chessboard.getTurn());
// from those, exclude the ones that would put our king in danger
moves = m_chessboard.allowedMoves(moves, m_chessboard.getTurn());
return moves;
}
bool AI::isInCheck() {
// Check all possible moves for the (which sets the check variable)
m_chessboard.possibleMoves(m_startingTurn*-1);
return m_chessboard.getCheck();
}
std::pair<std::vector<int>,std::vector<int>> AI::bestMove(int t_maxRecursion) {
m_maxRecursion = t_maxRecursion;
MinimaxBranch bestIdea =
MinimaxBranch(std::numeric_limits<double>::max()*m_chessboard.getTurn()*-1, {0,0,0}, {0,0,0});
std::vector<std::pair<std::vector<int>,std::vector<int>>> moves = getMoves();
for (auto pieceAndMove : moves) {
const std::vector<int> piece = pieceAndMove.first;
const std::vector<int> move = pieceAndMove.second;
const int type = m_chessboard.get(piece[0], piece[1], piece[2]);
const int type2 = m_chessboard.get(move[0], move[1], move[2]);
m_chessboard.set(move[0], move[1], move[2], type);
m_chessboard.set(piece[0], piece[1], piece[2], 0);
const double value = minimax(m_chessboard.getTurn()*-1,
-std::numeric_limits<double>::max(), std::numeric_limits<double>::max(), 0);
m_chessboard.set(move[0], move[1], move[2], type2);
m_chessboard.set(piece[0], piece[1], piece[2], type);
// If this one is better than the last best one
const MinimaxBranch thisIdea = MinimaxBranch(value, piece, move);
if ((m_chessboard.getTurn() == -1 && thisIdea < bestIdea)
|| (m_chessboard.getTurn() == 1 && thisIdea > bestIdea)) {
bestIdea = thisIdea;
}
}
return std::pair<std::vector<int>,std::vector<int>> {bestIdea.getPiece(), bestIdea.getMove()};
}
double AI::minimax(int t_turn, double t_biggest, double t_smallest, int t_recursionLevel) {
// Get the moves for this board and player
const std::vector<std::pair<std::vector<int>,std::vector<int>>> moves
= m_chessboard.allowedMoves(m_chessboard.possibleMoves(t_turn), t_turn);
if (moves.empty()) {
m_chessboard.allowedMoves(m_chessboard.possibleMoves(t_turn*-1), t_turn*-1);
// This player cannot move, let's see if he is in check (checkmate) or not (draw)
if (m_chessboard.getCheck()) {
return (9999-t_recursionLevel*5)*t_turn*-1;
} else {
return 0;
}
} else if (t_recursionLevel >= m_maxRecursion) {
return m_chessboard.getValue();
} else if (t_turn == 1) {
double maxEval = -std::numeric_limits<double>::max();
for (auto pieceAndMove : moves) {
const std::vector<int> piece = pieceAndMove.first;
const std::vector<int> move = pieceAndMove.second;
const int type = m_chessboard.get(piece[0], piece[1], piece[2]);
const int type2 = m_chessboard.get(move[0], move[1], move[2]);
m_chessboard.set(move[0], move[1], move[2], type);
m_chessboard.set(piece[0], piece[1], piece[2], 0);
const double value = minimax(t_turn*-1, t_biggest, t_smallest, t_recursionLevel+1);
m_chessboard.set(move[0], move[1], move[2], type2);
m_chessboard.set(piece[0], piece[1], piece[2], type);
// Alpha-beta pruning
maxEval = std::max(maxEval, value);
t_biggest = std::max(t_biggest, value);
if (t_smallest <= t_biggest) {
break;
}
}
return maxEval;
} else {
double minEval = std::numeric_limits<double>::max();
for (auto pieceAndMove : moves) {
const std::vector<int> piece = pieceAndMove.first;
const std::vector<int> move = pieceAndMove.second;
const int type = m_chessboard.get(piece[0], piece[1], piece[2]);
const int type2 = m_chessboard.get(move[0], move[1], move[2]);
m_chessboard.set(move[0], move[1], move[2], type);
m_chessboard.set(piece[0], piece[1], piece[2], 0);
const double value = minimax(t_turn*-1, t_biggest, t_smallest, t_recursionLevel+1);
m_chessboard.set(move[0], move[1], move[2], type2);
m_chessboard.set(piece[0], piece[1], piece[2], type);
// Alpha-beta pruning
minEval = std::min(minEval, value);
t_smallest = std::min(t_smallest, value);
if (t_smallest <= t_biggest) {
break;
}
}
return minEval;
}
}
// MinimaxBranch
MinimaxBranch::MinimaxBranch() {}
MinimaxBranch::MinimaxBranch(double t_value, std::vector<int> t_piece, std::vector<int> t_move)
: m_value(t_value), m_piece(t_piece), m_move(t_move) {}
MinimaxBranch::~MinimaxBranch () {}
// Comparing
bool MinimaxBranch::operator<(const MinimaxBranch& rhs) const {
return m_value < rhs.m_value;
}
bool MinimaxBranch::operator>(const MinimaxBranch& rhs) const {
return m_value > rhs.m_value;
}
// Getters and setters
double MinimaxBranch::getValue() const {
return m_value;
}
std::vector<int> MinimaxBranch::getPiece() const {
return m_piece;
}
std::vector<int> MinimaxBranch::getMove() const {
return m_move;
}
}
| 34.929825 | 99 | 0.664323 |
f93cbce816eabe0acb98a508a6479f13f027ed1c | 2,930 | cpp | C++ | Rasterizer/src/Light.cpp | litelawliet/ISARTRasterizer | 329ed70ea830cfff286c01d8efa5e726276f1fcd | [
"MIT"
] | 1 | 2020-03-23T14:36:02.000Z | 2020-03-23T14:36:02.000Z | Rasterizer/src/Light.cpp | litelawliet/ISARTRasterizer | 329ed70ea830cfff286c01d8efa5e726276f1fcd | [
"MIT"
] | null | null | null | Rasterizer/src/Light.cpp | litelawliet/ISARTRasterizer | 329ed70ea830cfff286c01d8efa5e726276f1fcd | [
"MIT"
] | null | null | null | #include "Light.h"
#include "Color.h"
#include "Vertex.h"
#include "Maths/Vec4.h"
#include <iostream>
#include <algorithm>
using namespace Maths::Vector;
//ADD LIGHTING HERE EVENTUALLY
Light::Light(const Maths::Vector::Vec3 p_position, const float p_ambient, const float p_diffuse, const float p_specular)
: m_position{ p_position }, m_ambientComponent{ p_ambient }, m_diffuseComponent{ p_diffuse }, m_specularComponent{ p_specular }
{}
Light::Light(const float p_x, const float p_y, const float p_z, const float p_ambient, const float p_diffuse, const float p_specular)
: m_position{ p_x, p_y, p_z }, m_ambientComponent{ p_ambient }, m_diffuseComponent{ p_diffuse }, m_specularComponent{ p_specular }
{}
Vec3& Light::GetPosition()
{
return { m_position };
}
float Light::GetAmbientComponent() const
{
return m_ambientComponent;
}
float Light::GetDiffuseComponent() const
{
return m_diffuseComponent;
}
float Light::GetSpecularComponent() const
{
return m_specularComponent;
}
void Light::SetPosition(const Vec3 & p_position)
{
m_position = p_position;
}
void Light::SetPosition(const float p_x, const float p_y, const float p_z)
{
m_position.m_x = p_x;
m_position.m_y = p_x;
m_position.m_z = p_z;
}
void Light::SetAmbientComponent(const float p_value)
{
m_ambientComponent = p_value;
}
void Light::SetDiffuseComponent(const float p_value)
{
m_diffuseComponent = p_value;
}
void Light::SetSpecularComponent(const float p_value)
{
m_specularComponent = p_value;
}
Color Light::CalculateColor(const Color p_color, const Vec3 p_surface, Vec4 p_vertex)
{
Vec3 normalSurface = p_surface;
//normalSurface.Normalize();
Vec3 homogenizedVec = Vec3{ p_vertex.m_x / p_vertex.m_w, p_vertex.m_y / p_vertex.m_w, p_vertex.m_z / p_vertex.m_w };
Vec3 lightPosNormal = m_position - homogenizedVec;
lightPosNormal.Normalize();
Vec3 reflectedLightVector = GetLightReflection(lightPosNormal, normalSurface);
float specAngle = std::max(Vec3::GetDotProduct(reflectedLightVector, homogenizedVec), 0.0f);
float lambertian = std::max(Vec3::GetDotProduct(normalSurface, lightPosNormal), 0.0f);
float specular = std::powf(specAngle, 1.0);
float r = (m_ambientComponent * p_color.m_r) + (m_diffuseComponent * lambertian * p_color.m_r) + (m_specularComponent * specular * p_color.m_r);
float g = (m_ambientComponent * p_color.m_g) + (m_diffuseComponent * lambertian * p_color.m_g) + (m_specularComponent * specular * p_color.m_g);
float b = (m_ambientComponent * p_color.m_b) + (m_diffuseComponent * lambertian * p_color.m_b) + (m_specularComponent * specular * p_color.m_b);
return { Color { static_cast<unsigned char>(r), static_cast<unsigned char>(g), static_cast<unsigned char>(b), p_color.m_a} };
}
Vec3 Light::GetLightReflection(Vec3 p_v0, Vec3 p_v1)
{
Vec3 negatedP0 = p_v0 * -1;
float dotProductResult = Vec3::GetDotProduct(negatedP0, p_v1);
return { negatedP0 - (p_v1 * (2 * dotProductResult)) };
} | 30.206186 | 145 | 0.757679 |
f93ce1b91c54c5d7ea4614131913b4c31402e25f | 2,445 | cpp | C++ | compiler-rt/test/tsan/signal_block2.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | compiler-rt/test/tsan/signal_block2.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | compiler-rt/test/tsan/signal_block2.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | // RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
// The test was reported to hang sometimes on Darwin:
// https://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20210517/917003.html
// UNSUPPORTED: darwin
#include "test.h"
#include <signal.h>
#include <string.h>
#include <sys/time.h>
int test;
int done;
int signals_handled;
pthread_t main_thread;
pthread_mutex_t mutex;
pthread_cond_t cond;
void timer_handler(int signum) {
write(2, "timer_handler\n", strlen("timer_handler\n"));
if (++signals_handled < 10)
return;
switch (test) {
case 0:
__atomic_store_n(&done, 1, __ATOMIC_RELEASE);
(void)pthread_kill(main_thread, SIGUSR1);
case 1:
if (pthread_mutex_trylock(&mutex) == 0) {
__atomic_store_n(&done, 1, __ATOMIC_RELEASE);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
case 2:
__atomic_store_n(&done, 1, __ATOMIC_RELEASE);
}
}
int main(int argc, char **argv) {
main_thread = pthread_self();
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGUSR1);
if (sigprocmask(SIG_BLOCK, &sigset, NULL))
exit((perror("sigprocmask"), 1));
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &timer_handler;
if (sigaction(SIGALRM, &sa, NULL))
exit((perror("setitimer"), 1));
for (test = 0; test < 3; test++) {
fprintf(stderr, "test %d\n", test);
struct itimerval timer;
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 50000;
timer.it_interval = timer.it_value;
if (setitimer(ITIMER_REAL, &timer, NULL))
exit((perror("setitimer"), 1));
switch (test) {
case 0:
while (__atomic_load_n(&done, __ATOMIC_ACQUIRE) == 0) {
int signum;
sigwait(&sigset, &signum);
write(2, "sigwait\n", strlen("sigwait\n"));
}
case 1:
pthread_mutex_lock(&mutex);
while (__atomic_load_n(&done, __ATOMIC_ACQUIRE) == 0) {
pthread_cond_wait(&cond, &mutex);
write(2, "pthread_cond_wait\n", strlen("pthread_cond_wait\n"));
}
pthread_mutex_unlock(&mutex);
case 2:
while (__atomic_load_n(&done, __ATOMIC_ACQUIRE) == 0) {
}
}
memset(&timer, 0, sizeof(timer));
if (setitimer(ITIMER_REAL, &timer, NULL))
exit((perror("setitimer"), 1));
done = 0;
signals_handled = 0;
}
fprintf(stderr, "DONE\n");
}
// CHECK: DONE
| 26.576087 | 81 | 0.643354 |
f93da586f7696291600bee410e128438d30e4fbf | 15,828 | cc | C++ | ash/login/ui/login_bubble_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | ash/login/ui/login_bubble_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | ash/login/ui/login_bubble_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <utility>
#include "ash/login/ui/login_bubble.h"
#include "ash/login/ui/login_button.h"
#include "ash/login/ui/login_menu_view.h"
#include "ash/login/ui/login_test_base.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/animation/test/ink_drop_host_view_test_api.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace {
// Total width of the bubble view.
constexpr int kBubbleTotalWidthDp = 178;
// Horizontal margin of the bubble view.
constexpr int kBubbleHorizontalMarginDp = 14;
// Top margin of the bubble view.
constexpr int kBubbleTopMarginDp = 13;
// Bottom margin of the bubble view.
constexpr int kBubbleBottomMarginDp = 18;
// Non zero size for the bubble anchor view.
constexpr int kBubbleAnchorViewSizeDp = 100;
std::vector<LoginMenuView::Item> PopulateMenuItems() {
std::vector<LoginMenuView::Item> items;
// Add one regular item.
LoginMenuView::Item item1;
item1.title = "Regular Item 1";
item1.is_group = false;
item1.selected = true;
items.push_back(item1);
// Add one group item.
LoginMenuView::Item item2;
item2.title = "Group Item 2";
item2.is_group = true;
items.push_back(item2);
// Add another regular item.
LoginMenuView::Item item3;
item3.title = "Regular Item 2";
item3.is_group = false;
items.push_back(item3);
return items;
}
class LoginBubbleTest : public LoginTestBase {
protected:
LoginBubbleTest() = default;
~LoginBubbleTest() override = default;
// LoginTestBase:
void SetUp() override {
LoginTestBase::SetUp();
container_ = new views::View();
container_->SetLayoutManager(
std::make_unique<views::BoxLayout>(views::BoxLayout::kVertical));
bubble_opener_ = new LoginButton(nullptr /*listener*/);
other_view_ = new views::View();
bubble_opener_->SetFocusBehavior(views::View::FocusBehavior::ALWAYS);
other_view_->SetFocusBehavior(views::View::FocusBehavior::ALWAYS);
other_view_->SetPreferredSize(
gfx::Size(kBubbleAnchorViewSizeDp, kBubbleAnchorViewSizeDp));
bubble_opener_->SetPreferredSize(
gfx::Size(kBubbleAnchorViewSizeDp, kBubbleAnchorViewSizeDp));
container_->AddChildView(bubble_opener_);
container_->AddChildView(other_view_);
SetWidget(CreateWidgetWithContent(container_));
bubble_ = std::make_unique<LoginBubble>();
}
void TearDown() override {
bubble_.reset();
LoginTestBase::TearDown();
}
void ShowUserMenu(base::OnceClosure on_remove_show_warning,
base::OnceClosure on_remove) {
bool show_remove_user = !on_remove.is_null();
bubble_->ShowUserMenu(
base::string16() /*username*/, base::string16() /*email*/,
user_manager::UserType::USER_TYPE_REGULAR, false /*is_owner*/,
container_, bubble_opener_, show_remove_user,
std::move(on_remove_show_warning), std::move(on_remove));
}
void ShowSelectionMenu(const LoginMenuView::OnSelect& on_select) {
LoginMenuView* view =
new LoginMenuView(PopulateMenuItems(), container_, on_select);
bubble_->ShowSelectionMenu(view, bubble_opener_);
}
// Owned by test widget view hierarchy.
views::View* container_ = nullptr;
// Owned by test widget view hierarchy.
LoginButton* bubble_opener_ = nullptr;
// Owned by test widget view hierarchy.
views::View* other_view_ = nullptr;
std::unique_ptr<LoginBubble> bubble_;
private:
DISALLOW_COPY_AND_ASSIGN(LoginBubbleTest);
};
} // namespace
// Verifies the base bubble settings.
TEST_F(LoginBubbleTest, BaseBubbleSettings) {
bubble_->ShowTooltip(base::string16(), bubble_opener_);
EXPECT_TRUE(bubble_->IsVisible());
LoginBaseBubbleView* bubble_view = bubble_->bubble_view();
EXPECT_EQ(bubble_view->GetDialogButtons(), ui::DIALOG_BUTTON_NONE);
EXPECT_EQ(bubble_view->width(), kBubbleTotalWidthDp);
EXPECT_EQ(bubble_view->color(), SK_ColorBLACK);
EXPECT_EQ(bubble_view->margins(),
gfx::Insets(kBubbleTopMarginDp, kBubbleHorizontalMarginDp,
kBubbleBottomMarginDp, kBubbleHorizontalMarginDp));
bubble_->Close();
}
// Verifies the bubble handles key event correctly.
TEST_F(LoginBubbleTest, BubbleKeyEventHandling) {
EXPECT_FALSE(bubble_->IsVisible());
// Verifies that key event won't open the bubble.
ui::test::EventGenerator& generator = GetEventGenerator();
other_view_->RequestFocus();
generator.PressKey(ui::KeyboardCode::VKEY_A, ui::EF_NONE);
EXPECT_FALSE(bubble_->IsVisible());
// Verifies that key event on the bubble opener view won't close the bubble.
ShowUserMenu(base::OnceClosure(), base::OnceClosure());
EXPECT_TRUE(bubble_->IsVisible());
bubble_opener_->RequestFocus();
generator.PressKey(ui::KeyboardCode::VKEY_A, ui::EF_NONE);
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that key event on the other view will close the bubble.
other_view_->RequestFocus();
generator.PressKey(ui::KeyboardCode::VKEY_A, ui::EF_NONE);
EXPECT_FALSE(bubble_->IsVisible());
}
// Verifies the bubble handles mouse event correctly.
TEST_F(LoginBubbleTest, BubbleMouseEventHandling) {
EXPECT_FALSE(bubble_->IsVisible());
// Verifies that mouse event won't open the bubble.
ui::test::EventGenerator& generator = GetEventGenerator();
generator.MoveMouseTo(other_view_->GetBoundsInScreen().CenterPoint());
generator.ClickLeftButton();
EXPECT_FALSE(bubble_->IsVisible());
// Verifies that mouse event on the bubble opener view won't close the bubble.
ShowUserMenu(base::OnceClosure(), base::OnceClosure());
EXPECT_TRUE(bubble_->IsVisible());
generator.MoveMouseTo(bubble_opener_->GetBoundsInScreen().CenterPoint());
generator.ClickLeftButton();
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that mouse event on the bubble itself won't close the bubble.
generator.MoveMouseTo(
bubble_->bubble_view()->GetBoundsInScreen().CenterPoint());
generator.ClickLeftButton();
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that mouse event on the other view will close the bubble.
generator.MoveMouseTo(other_view_->GetBoundsInScreen().CenterPoint());
generator.ClickLeftButton();
EXPECT_FALSE(bubble_->IsVisible());
}
// Verifies the bubble handles gesture event correctly.
TEST_F(LoginBubbleTest, BubbleGestureEventHandling) {
EXPECT_FALSE(bubble_->IsVisible());
// Verifies that gesture event won't open the bubble.
ui::test::EventGenerator& generator = GetEventGenerator();
generator.GestureTapAt(other_view_->GetBoundsInScreen().CenterPoint());
EXPECT_FALSE(bubble_->IsVisible());
// Verifies that gesture event on the bubble opener view won't close the
// bubble.
ShowUserMenu(base::OnceClosure(), base::OnceClosure());
EXPECT_TRUE(bubble_->IsVisible());
generator.GestureTapAt(bubble_opener_->GetBoundsInScreen().CenterPoint());
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that gesture event on the bubble itself won't close the bubble.
generator.GestureTapAt(
bubble_->bubble_view()->GetBoundsInScreen().CenterPoint());
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that gesture event on the other view will close the bubble.
generator.GestureTapAt(other_view_->GetBoundsInScreen().CenterPoint());
EXPECT_FALSE(bubble_->IsVisible());
}
// Verifies the ripple effects for the login button.
TEST_F(LoginBubbleTest, LoginButtonRipple) {
views::test::InkDropHostViewTestApi ink_drop_api(bubble_opener_);
EXPECT_EQ(ink_drop_api.ink_drop_mode(),
views::InkDropHostView::InkDropMode::ON);
// Show the bubble to activate the ripple effect.
ShowUserMenu(base::OnceClosure(), base::OnceClosure());
EXPECT_TRUE(bubble_->IsVisible());
EXPECT_TRUE(ink_drop_api.HasInkDrop());
EXPECT_EQ(ink_drop_api.GetInkDrop()->GetTargetInkDropState(),
views::InkDropState::ACTIVATED);
EXPECT_TRUE(ink_drop_api.GetInkDrop()->IsHighlightFadingInOrVisible());
// Close the bubble should hide the ripple effect.
ui::test::EventGenerator& generator = GetEventGenerator();
generator.MoveMouseTo(other_view_->GetBoundsInScreen().CenterPoint());
generator.ClickLeftButton();
EXPECT_FALSE(bubble_->IsVisible());
// InkDropState::DEACTIVATED state will automatically transition to the
// InkDropState::HIDDEN state.
EXPECT_EQ(ink_drop_api.GetInkDrop()->GetTargetInkDropState(),
views::InkDropState::HIDDEN);
EXPECT_FALSE(ink_drop_api.GetInkDrop()->IsHighlightFadingInOrVisible());
}
// Verifies that clicking remove user requires two clicks before firing the
// callback.
TEST_F(LoginBubbleTest, RemoveUserRequiresTwoActivations) {
// Show the user menu.
bool remove_warning_called = false;
bool remove_called = false;
ShowUserMenu(
base::BindOnce(
[](bool* remove_warning_called) { *remove_warning_called = true; },
&remove_warning_called),
base::BindOnce([](bool* remove_called) { *remove_called = true; },
&remove_called));
EXPECT_TRUE(bubble_->IsVisible());
// Focus the remove user button.
views::View* remove_user_button = bubble_->bubble_view()->GetViewByID(
LoginBubble::kUserMenuRemoveUserButtonIdForTest);
remove_user_button->RequestFocus();
EXPECT_TRUE(remove_user_button->HasFocus());
auto click = [&]() {
EXPECT_TRUE(remove_user_button->HasFocus());
GetEventGenerator().PressKey(ui::KeyboardCode::VKEY_RETURN, 0);
};
// First click calls remove warning.
EXPECT_NO_FATAL_FAILURE(click());
EXPECT_TRUE(remove_warning_called);
EXPECT_FALSE(remove_called);
remove_warning_called = false;
// Second click calls remove.
EXPECT_NO_FATAL_FAILURE(click());
EXPECT_FALSE(remove_warning_called);
EXPECT_TRUE(remove_called);
}
TEST_F(LoginBubbleTest, ErrorBubbleKeyEventHandling) {
ui::test::EventGenerator& generator = GetEventGenerator();
EXPECT_FALSE(bubble_->IsVisible());
views::Label* error_text = new views::Label(base::ASCIIToUTF16("Error text"));
bubble_->ShowErrorBubble(error_text, container_, LoginBubble::kFlagsNone);
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that key event on a view other than error closes the error bubble.
other_view_->RequestFocus();
generator.PressKey(ui::KeyboardCode::VKEY_A, ui::EF_NONE);
EXPECT_FALSE(bubble_->IsVisible());
}
TEST_F(LoginBubbleTest, ErrorBubbleMouseEventHandling) {
ui::test::EventGenerator& generator = GetEventGenerator();
EXPECT_FALSE(bubble_->IsVisible());
views::Label* error_text = new views::Label(base::ASCIIToUTF16("Error text"));
bubble_->ShowErrorBubble(error_text, container_, LoginBubble::kFlagsNone);
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that mouse event on the bubble itself won't close the bubble.
generator.MoveMouseTo(
bubble_->bubble_view()->GetBoundsInScreen().CenterPoint());
generator.ClickLeftButton();
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that mouse event on the other view will close the bubble.
generator.MoveMouseTo(other_view_->GetBoundsInScreen().CenterPoint());
generator.ClickLeftButton();
EXPECT_FALSE(bubble_->IsVisible());
}
TEST_F(LoginBubbleTest, ErrorBubbleGestureEventHandling) {
ui::test::EventGenerator& generator = GetEventGenerator();
EXPECT_FALSE(bubble_->IsVisible());
views::Label* error_text = new views::Label(base::ASCIIToUTF16("Error text"));
bubble_->ShowErrorBubble(error_text, container_, LoginBubble::kFlagsNone);
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that gesture event on the bubble itself won't close the bubble.
generator.GestureTapAt(
bubble_->bubble_view()->GetBoundsInScreen().CenterPoint());
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that gesture event on the other view will close the bubble.
generator.GestureTapAt(other_view_->GetBoundsInScreen().CenterPoint());
EXPECT_FALSE(bubble_->IsVisible());
}
TEST_F(LoginBubbleTest, PersistentErrorBubbleEventHandling) {
ui::test::EventGenerator& generator = GetEventGenerator();
EXPECT_FALSE(bubble_->IsVisible());
views::Label* error_text = new views::Label(base::ASCIIToUTF16("Error text"));
bubble_->ShowErrorBubble(error_text, container_,
LoginBubble::kFlagPersistent);
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that mouse event on the bubble itself won't close the bubble.
generator.MoveMouseTo(
bubble_->bubble_view()->GetBoundsInScreen().CenterPoint());
generator.ClickLeftButton();
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that mouse event on the other view won't close the bubble.
generator.MoveMouseTo(other_view_->GetBoundsInScreen().CenterPoint());
generator.ClickLeftButton();
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that gesture event on the bubble itself won't close the bubble.
generator.GestureTapAt(
bubble_->bubble_view()->GetBoundsInScreen().CenterPoint());
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that gesture event on the other view won't close the bubble.
generator.GestureTapAt(other_view_->GetBoundsInScreen().CenterPoint());
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that key event on the other view won't close the bubble.
other_view_->RequestFocus();
generator.PressKey(ui::KeyboardCode::VKEY_A, ui::EF_NONE);
EXPECT_TRUE(bubble_->IsVisible());
// LoginBubble::Close should close the persistent error bubble.
bubble_->Close();
EXPECT_FALSE(bubble_->IsVisible());
}
TEST_F(LoginBubbleTest, TestShowSelectionMenu) {
ui::test::EventGenerator& generator = GetEventGenerator();
EXPECT_FALSE(bubble_->IsVisible());
LoginMenuView::Item selected_item;
bool selected = false;
ShowSelectionMenu(base::BindLambdaForTesting([&](LoginMenuView::Item item) {
selected_item = item;
selected = true;
}));
EXPECT_TRUE(bubble_->IsVisible());
// Verifies that regular item 1 is selectable.
LoginMenuView* menu_view =
static_cast<LoginMenuView*>(bubble_->bubble_view());
LoginMenuView::TestApi test_api1(menu_view);
EXPECT_TRUE(test_api1.contents()->child_at(0)->HasFocus());
generator.PressKey(ui::KeyboardCode::VKEY_RETURN, 0 /*flag*/);
EXPECT_FALSE(bubble_->IsVisible());
EXPECT_EQ(selected_item.title, "Regular Item 1");
EXPECT_TRUE(selected);
// Verfies that group item 2 is not selectable.
selected = false;
ShowSelectionMenu(base::BindLambdaForTesting([&](LoginMenuView::Item item) {
selected_item = item;
selected = true;
}));
EXPECT_TRUE(bubble_->IsVisible());
menu_view = static_cast<LoginMenuView*>(bubble_->bubble_view());
LoginMenuView::TestApi test_api2(menu_view);
test_api2.contents()->child_at(1)->RequestFocus();
generator.PressKey(ui::KeyboardCode::VKEY_RETURN, 0 /*flag*/);
EXPECT_TRUE(bubble_->IsVisible());
EXPECT_FALSE(selected);
// Verifies up/down arrow key can navigate menu entries.
generator.PressKey(ui::KeyboardCode::VKEY_UP, 0 /*flag*/);
EXPECT_TRUE(test_api2.contents()->child_at(0)->HasFocus());
generator.PressKey(ui::KeyboardCode::VKEY_UP, 0 /*flag*/);
EXPECT_TRUE(test_api2.contents()->child_at(0)->HasFocus());
generator.PressKey(ui::KeyboardCode::VKEY_DOWN, 0 /*flag*/);
// Group item is skipped in up/down key navigation.
EXPECT_TRUE(test_api2.contents()->child_at(2)->HasFocus());
generator.PressKey(ui::KeyboardCode::VKEY_DOWN, 0 /*flag*/);
EXPECT_TRUE(test_api2.contents()->child_at(2)->HasFocus());
EXPECT_TRUE(bubble_->IsVisible());
bubble_->Close();
EXPECT_FALSE(bubble_->IsVisible());
}
} // namespace ash
| 36.809302 | 80 | 0.740649 |
f93f1f10cc37eb7f4b1115bb7731d417a9b66855 | 481 | cpp | C++ | Matrici/el_pozitive.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 11 | 2015-08-29T13:41:22.000Z | 2020-01-08T20:34:06.000Z | Matrici/el_pozitive.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | null | null | null | Matrici/el_pozitive.cpp | rusucosmin/Cplusplus | 0e95cd01d20b22404aa4166c71d5a9e834a5a21b | [
"MIT"
] | 5 | 2016-01-20T18:17:01.000Z | 2019-10-30T11:57:15.000Z | #include <iostream>
using namespace std;
int main()
{
int a[30][30] ,nr, i, j, n, m ;
cout<<"Numar de linii "; cin>>n;
cout<<"Numar de coloane "; cin>>m;
for(i=1; i<=n; i++)
{ for(j=1; j<=m; j++)
{cout<<"a["<<i<<"]["<<j<<"] = "; cin>>a[i][j]; }
if(a[i][j]>0)
nr++; }
cout<<"Numarul elemtelor pozitive: "<<nr;
system("pause");
return 0 ;
}
| 26.722222 | 64 | 0.37422 |
f943654563d0575b5057d5468ba72d1f3e85fac9 | 8,700 | cc | C++ | src/main/c/zmq/zmq_pub.cc | bopopescu/hydra | ec0793f8c1f49ceb93bf1f1a9789085b68d55f08 | [
"Apache-2.0"
] | 10 | 2016-05-28T15:56:43.000Z | 2018-01-03T21:30:58.000Z | src/main/c/zmq/zmq_pub.cc | bopopescu/hydra | ec0793f8c1f49ceb93bf1f1a9789085b68d55f08 | [
"Apache-2.0"
] | 17 | 2016-06-06T22:15:28.000Z | 2020-07-22T20:28:12.000Z | src/main/c/zmq/zmq_pub.cc | bopopescu/hydra | ec0793f8c1f49ceb93bf1f1a9789085b68d55f08 | [
"Apache-2.0"
] | 5 | 2016-06-01T22:01:44.000Z | 2020-07-22T20:12:49.000Z |
#include <zmq.hpp>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <assert.h>
#include <stdlib.h>
#include <ctime>
#include "hdaemon.pb.h"
#include <iostream>
class TestControl {
public:
TestControl() {
publishing = start_publishing = false;
test_duration = 5;
msg_batch = 100;
msg_requested_rate = 1000;
msg_cnt = 0;
}
uint64_t start_test() {
floatStats.clear();
intStats.clear();
uint64_t start_time = std::time(0);
intStats["time:start"] = start_time;
msg_cnt = 0;
return start_time;
}
void stop_test() {
// do stats calculation here
intStats["time:end"] = std::time(0);
uint64_t elapsed_time = intStats["time:end"] - intStats["time:start"];
floatStats["rate"] = 1.0 * msg_cnt / elapsed_time;
intStats["msg_cnt"] = msg_cnt;
}
bool publishing;
bool start_publishing;
std::map <std::string, uint64_t> intStats;
std::map <std::string, float> floatStats;
uint32_t test_duration;
uint32_t msg_batch;
uint32_t msg_requested_rate;
uint64_t msg_cnt;
};
void process_message(const std::string& msg, TestControl* tctrl, std::string* resp) {
hydra::CommandMessage cmsg;
hydra::ResponseMessage rmsg;
hydra::ResponseMessage_Resp* r;
if (!cmsg.ParseFromString(msg)) {
rmsg.set_status("error");
r = rmsg.add_resp();
r->set_name("__r");
r->set_strvalue("Unable to parse the protobuf string!!!");
printf("Unable to parse protbuf message received of size %d\n", (int)msg.size());
} else if (cmsg.type() == hydra::CommandMessage::SUBCMD && cmsg.has_cmd()) {
std::string cmd_name = cmsg.cmd().cmd_name();
printf("Received a command [%s]\n", cmd_name.c_str());
fflush(NULL);
if (cmd_name == "ping") {
// PING - PONG.
rmsg.set_status("ok");
r = rmsg.add_resp();
r->set_name("__r");
r->set_strvalue("pong");
} else if (cmd_name == "teststart") {
// START of test.
r = rmsg.add_resp();
r->set_name("__r");
if (tctrl->publishing || tctrl->start_publishing) {
rmsg.set_status("error");
r->set_strvalue("test is still running, cant start.");
} else {
rmsg.set_status("ok");
r->set_strvalue("starting");
tctrl->start_publishing = true;
}
} else if (cmd_name == "teststatus") {
// get test status
rmsg.set_status("ok");
std::string tstatus;
if (tctrl->publishing && tctrl->start_publishing)
tstatus = "running";
else if (tctrl->publishing && !tctrl->start_publishing)
tstatus = "stopping";
else if (!tctrl->publishing && tctrl->start_publishing)
tstatus = "starting";
else
tstatus = "stopped";
r = rmsg.add_resp();
r->set_name("__r");
r->set_strvalue(tstatus);
printf("\t -> TestStatus:%s\n", tstatus.c_str());
} else if (cmd_name == "updateconfig") {
// update test properties
for (int i = 0; i < cmsg.cmd().argument_size(); ++i) {
hydra::CommandMessage_CommandArgs arg = cmsg.cmd().argument(i);
printf("\t -> name = %s [int:%d float:%d str:%d]\n", arg.name().c_str(), arg.has_intvalue(), arg.has_floatvalue(), arg.has_strvalue());
fflush(NULL);
if (arg.name() == "test_duration") {
assert(arg.has_intvalue());
tctrl->test_duration = arg.intvalue();
printf("\t -> updatedpub test_duration=%d\n", tctrl->test_duration);
} else if (arg.name() == "msg_batch") {
assert(arg.has_intvalue());
tctrl->msg_batch = arg.intvalue();
printf("\t -> updatedpub msg_batch=%d\n", tctrl->msg_batch);
} else if (arg.name() == "msg_requested_rate") {
assert(arg.has_intvalue() || arg.has_floatvalue());
if (arg.has_intvalue())
tctrl->msg_requested_rate = arg.intvalue();
else
tctrl->msg_requested_rate = arg.floatvalue();
printf("\t -> updatedpub msg_requested_rate=%d\n", tctrl->msg_requested_rate);
}
}
rmsg.set_status("ok");
} else if (cmd_name == "getstats") {
rmsg.set_status("ok");
for (auto it = tctrl->intStats.begin();
it != tctrl->intStats.end();
++it) {
r = rmsg.add_resp();
r->set_name(it->first);
r->set_intvalue(it->second);
}
for (auto it = tctrl->floatStats.begin();
it != tctrl->floatStats.end();
++it) {
r = rmsg.add_resp();
r->set_name(it->first);
r->set_floatvalue(it->second);
}
} else {
// INVALID COMMAND.
rmsg.set_status("error");
r = rmsg.add_resp();
r->set_name("__r");
std::string m = "Did not find implemented for Command ";
m += cmd_name;
r->set_strvalue(m);
}
} else {
rmsg.set_status("error");
r = rmsg.add_resp();
r->set_name("__r");
std::string m = "Did not find Command in the message or cmd type[" + std::to_string(cmsg.type()) + "] is incorrect";
r->set_strvalue(m);
}
printf(" -> Responding with status [%s]\n", rmsg.status().c_str());
fflush(NULL);
assert(rmsg.SerializeToString(resp));
}
// ping
// start
// get stats
// test status
// update pub metrics
// parse protobuf
// extract command
// process command
// create response
// send reply
int main (void) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
zmq::context_t context(1);
zmq::socket_t socket_rep(context, ZMQ_REP);
zmq::socket_t socket_pub(context, ZMQ_PUB);
if (0) {
// with the watermark disabled
// no drops will be there
// however a slow client can cause the publisher to slow down.
int hwm = 0;
socket_pub.setsockopt(ZMQ_SNDHWM, &hwm, sizeof(hwm));
}
{
int ghwm;
size_t ghwm_s = sizeof(ghwm);
socket_pub.getsockopt(ZMQ_SNDHWM, &ghwm, &ghwm_s);
printf("ZMQ SNDHWM is set to %d\n", ghwm);
}
std::string strPort = std::string(getenv("PORT0"));
printf("Starting Rep Server on port %s\n", strPort.c_str());
fflush(NULL);
socket_rep.bind("tcp://*:" + strPort);
socket_pub.bind("tcp://*:15556");
TestControl tctrl;
uint32_t cnt = 0;
uint64_t start_time;
char message_ch[120];
while(true) {
zmq_pollitem_t items[] = {
{static_cast<void *>(socket_rep), 0, ZMQ_POLLIN, 0}
};
int rc = zmq_poll(items, 1, 0);
if (rc == -1) {
printf("ZMQ POLL had error \n");
break;
}
if (items[0].revents & ZMQ_POLLIN) {
zmq::message_t request;
socket_rep.recv(&request);
std::string resp;
process_message(std::string((char *)request.data(), request.size()),
&tctrl, &resp);
zmq::message_t reply(resp.c_str(), resp.size());
socket_rep.send(reply);
}
if (!tctrl.publishing && tctrl.start_publishing) {
tctrl.publishing = true;
start_time = tctrl.start_test();
cnt = 0;
printf("Starting the test\n"); fflush(NULL);
} else if (tctrl.publishing && !tctrl.start_publishing) {
tctrl.publishing = false;
tctrl.stop_test();
printf("Stopped the test\n"); fflush(NULL);
} else if (!tctrl.publishing) {
// to prevent spinning while test is idle
sleep(1);
}
// Send the message to pub
while (tctrl.publishing) {
++cnt;
if (cnt >= (tctrl.msg_batch-1)) {
// check cnt and delay if needed
if (cnt == (tctrl.msg_batch - 1))
break; // break once before sleep to allow poll to
// use up some of the delay
if (cnt >= tctrl.msg_batch) {
time_t duration = std::time(0) - start_time;
double exp_time = (double) tctrl.msg_cnt / tctrl.msg_requested_rate;
double delay = 0;
if (duration > tctrl.test_duration) {
tctrl.start_publishing = false;
break;
}
if (exp_time > duration)
delay = exp_time - duration;
if (delay > 1) delay = 1;
usleep(delay * 1e6);
cnt = 0;
}
}
// send some data
//std::strig str_msgcnt = atoi(msg_cnt);
//std::string msg = str_msgcnt + " msg" + str_msgcnt;
snprintf(message_ch, sizeof(message_ch),
"%ld msg%ld",tctrl.msg_cnt, tctrl.msg_cnt);
zmq::message_t message(strlen(message_ch));
memcpy(message.data(), message_ch, strlen(message_ch));
//message.rebuild(message_ch, strlen(message_ch));
rc = socket_pub.send(message);
if (!rc)
printf(" ERROR Failed to send message %s\n", message_ch);
++tctrl.msg_cnt;
} // while(publishing)
} // while(true)
return 0;
}
| 32.222222 | 143 | 0.586667 |
f946696a7d0623b6cb4cc3138e4b97679ef3ab6d | 8,891 | hpp | C++ | test/gaussian_filter/gaussian_filter_linear_vs_x_test_suite.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 17 | 2015-07-03T06:53:05.000Z | 2021-05-15T20:55:12.000Z | test/gaussian_filter/gaussian_filter_linear_vs_x_test_suite.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 3 | 2015-02-20T12:48:17.000Z | 2019-12-18T08:45:13.000Z | test/gaussian_filter/gaussian_filter_linear_vs_x_test_suite.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 15 | 2015-02-20T11:34:14.000Z | 2021-05-15T20:55:13.000Z | /*
* This is part of the fl library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2015 Max Planck Society,
* Autonomous Motion Department,
* Institute for Intelligent Systems
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file gaussian_filter_linear_vs_x_test_suite.hpp
* \date July 2015
* \author Jan Issac (jan.issac@gmail.com)
*/
#include <gtest/gtest.h>
#include "../typecast.hpp"
#include <Eigen/Dense>
#include <cmath>
#include <iostream>
#include <fl/util/math/linear_algebra.hpp>
#include <fl/filter/filter_interface.hpp>
#include <fl/filter/gaussian/gaussian_filter_linear.hpp>
#include <fl/model/transition/linear_transition.hpp>
#include <fl/model/sensor/linear_gaussian_sensor.hpp>
#include <fl/model/sensor/linear_decorrelated_gaussian_sensor.hpp>
enum : signed int
{
DecorrelatedGaussianModel,
GaussianModel
};
static constexpr double epsilon = 0.1;
template <typename TestType>
class GaussianFilterLinearVsXTest
: public ::testing::Test
{
protected:
typedef typename TestType::Parameter Configuration;
enum: signed int
{
StateDim = Configuration::StateDim,
InputDim = Configuration::InputDim,
ObsrvDim = Configuration::ObsrvDim,
StateSize = fl::TestSize<StateDim, TestType>::Value,
InputSize = fl::TestSize<InputDim, TestType>::Value,
ObsrvSize = fl::TestSize<ObsrvDim, TestType>::Value
};
enum ModelSetup
{
Random,
Identity
};
typedef Eigen::Matrix<fl::Real, StateSize, 1> State;
typedef Eigen::Matrix<fl::Real, InputSize, 1> Input;
typedef Eigen::Matrix<fl::Real, ObsrvSize, 1> Obsrv;
typedef fl::IntegerTypeMap<
fl::IntegerTypePair<
DecorrelatedGaussianModel,
fl::LinearDecorrelatedGaussianSensor<Obsrv, State>
>,
fl::IntegerTypePair<
GaussianModel,
fl::LinearGaussianSensor<Obsrv, State>
>
> SensorMap;
typedef fl::LinearTransition<State, State, Input> LinearTransition;
typedef typename SensorMap::template Select<
Configuration::SelectedModel
>::Type LinearSensor;
typedef fl::GaussianFilter<
LinearTransition, LinearSensor
> KalmanFilter;
typedef typename Configuration::template FilterDefinition<
LinearTransition,
LinearSensor
> FilterDefinition;
typedef typename FilterDefinition::Type Filter;
GaussianFilterLinearVsXTest()
: predict_steps_(200),
predict_update_steps_(30)
{ }
KalmanFilter create_kalman_filter() const
{
return KalmanFilter(
LinearTransition(StateDim, InputDim),
LinearSensor(ObsrvDim, StateDim));
}
Filter create_filter() const
{
return Configuration::create_filter(
LinearTransition(StateDim, InputDim),
LinearSensor(ObsrvDim, StateDim));
}
void setup_models(
KalmanFilter& kalman_filter, Filter& other_filter, ModelSetup setup)
{
auto A = kalman_filter.transition().create_dynamics_matrix();
auto B = kalman_filter.transition().create_input_matrix();
auto Q = kalman_filter.transition().create_noise_matrix();
auto H = kalman_filter.sensor().create_sensor_matrix();
auto R = kalman_filter.sensor().create_noise_matrix();
Q.setZero();
R.setZero();
B.setZero();
switch (setup)
{
case Random:
A.diagonal().setRandom();
H.diagonal().setRandom();
Q.diagonal().setRandom(); Q *= Q.transpose().eval();
R.diagonal().setRandom(); R *= R.transpose().eval();
break;
case Identity:
A.setIdentity();
H.setIdentity();
Q.setIdentity();
R.setIdentity();
break;
}
kalman_filter.transition().dynamics_matrix(A);
kalman_filter.transition().input_matrix(B);
kalman_filter.transition().noise_matrix(Q);
kalman_filter.sensor().sensor_matrix(H);
kalman_filter.sensor().noise_matrix(R);
other_filter.transition().dynamics_matrix(A);
other_filter.transition().input_matrix(B);
other_filter.transition().noise_matrix(Q);
other_filter.sensor().sensor_matrix(H);
other_filter.sensor().noise_matrix(R);
}
State zero_state() { return State::Zero(StateDim); }
Input zero_input() { return Input::Zero(InputDim); }
Obsrv zero_obsrv() { return Obsrv::Zero(ObsrvDim); }
State rand_state() { return State::Random(StateDim); }
Input rand_input() { return Input::Random(InputDim); }
Obsrv rand_obsrv() { return Obsrv::Random(ObsrvDim); }
protected:
int predict_steps_;
int predict_update_steps_;
};
TYPED_TEST_CASE_P(GaussianFilterLinearVsXTest);
//TYPED_TEST_P(GaussianFilterLinearVsXTest, predict)
//{
// typedef TestFixture This;
// auto other_filter = This::create_filter();
// auto kalman_filter = This::create_kalman_filter();
// This::setup_models(kalman_filter, other_filter, This::Random);
// auto belief_other = other_filter.create_belief();
// auto belief_kf = kalman_filter.create_belief();
// for (int i = 0; i < This::predict_steps_; ++i)
// {
// other_filter.predict(belief_other, This::zero_input(), belief_other);
// kalman_filter.predict(belief_kf, This::zero_input(), belief_kf);
// if (!fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon))
// {
// std::cout << "i = " << i << std::endl;
// PV(belief_kf.mean());
// PV(belief_other.mean());
// }
// if (!fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon))
// {
// std::cout << "i = " << i << std::endl;
// PV(belief_kf.covariance());
// PV(belief_other.covariance());
// }
// ASSERT_TRUE(
// fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon));
// ASSERT_TRUE(
// fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon));
// }
// PV(belief_kf.mean());
// PV(belief_other.mean());
// PV(belief_kf.covariance());
// PV(belief_other.covariance());
//}
TYPED_TEST_P(GaussianFilterLinearVsXTest, predict_and_update)
{
typedef TestFixture This;
auto other_filter = This::create_filter();
auto kalman_filter = This::create_kalman_filter();
This::setup_models(kalman_filter, other_filter, This::Random);
auto belief_other = other_filter.create_belief();
auto belief_kf = kalman_filter.create_belief();
for (int i = 0; i < This::predict_update_steps_; ++i)
{
auto y = This::rand_obsrv();
kalman_filter.predict(belief_kf, This::zero_input(), belief_kf);
other_filter.predict(belief_other, This::zero_input(), belief_other);
// if (!fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon))
// {
// std::cout << "predict i = " << i << std::endl;
// PV(belief_kf.mean());
// PV(belief_other.mean());
// }
// if (!fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon))
// {
// std::cout << "predict i = " << i << std::endl;
// PV(belief_kf.covariance());
// PV(belief_other.covariance());
// }
kalman_filter.update(belief_kf, y, belief_kf);
other_filter.update(belief_other, y, belief_other);
// if (!fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon))
// {
// std::cout << "update i = " << i << std::endl;
// PV(belief_kf.mean());
// PV(belief_other.mean());
// }
// if (!fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon))
// {
// std::cout << "update i = " << i << std::endl;
// PV(belief_kf.covariance());
// PV(belief_other.covariance());
// }
ASSERT_TRUE(
fl::are_similar(belief_other.mean(), belief_kf.mean(), epsilon));
ASSERT_TRUE(
fl::are_similar(belief_other.covariance(), belief_kf.covariance(), epsilon));
}
// PV(belief_kf.mean());
// PV(belief_other.mean());
// PV(belief_kf.covariance());
// PV(belief_other.covariance());
// std::cout << other_filter.name() << std::endl;
}
REGISTER_TYPED_TEST_CASE_P(GaussianFilterLinearVsXTest,
predict_and_update);
| 30.44863 | 91 | 0.614554 |
f9489c7099d51b45affa6dae1069cc8b8267ccdf | 780 | cpp | C++ | test/TestCommons.cpp | gtauzin/metaLBM | 07291e085962f50848489fd36ece46ce412bdbb5 | [
"MIT"
] | 7 | 2019-10-19T22:58:30.000Z | 2022-03-29T03:45:51.000Z | test/TestCommons.cpp | gtauzin/metaLBM | 07291e085962f50848489fd36ece46ce412bdbb5 | [
"MIT"
] | 1 | 2022-02-04T14:08:45.000Z | 2022-02-05T21:06:28.000Z | test/TestCommons.cpp | gtauzin/metaLBM | 07291e085962f50848489fd36ece46ce412bdbb5 | [
"MIT"
] | 2 | 2021-02-05T23:52:14.000Z | 2021-06-16T02:49:20.000Z | #define BOOST_TEST_MODULE "C++ Unit Tests for metaLBM"
#include <boost/test/included/unit_test.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
namespace tt = boost::test_tools;
#include <iostream>
#define NPROCS 1
#include "Lattice.h"
typedef double valueType;
typedef lbm::Lattice<valueType, lbm::LatticeType::D1Q3> L;
#include "Commons.h"
#include "MathVector.h"
using namespace lbm;
BOOST_AUTO_TEST_SUITE(TestCommons)
BOOST_AUTO_TEST_CASE(TestVTR) {
constexpr CommonsType commonsType = CommonsType::Global;
constexpr MathVector<int, 3> iP{{1}};
Commons<valueType, commonsType> commons(amplitude);
BOOST_TEST(commons.write(iP)[d::X] == (valueType) 1,
tt::tolerance(1e-15));
}
BOOST_AUTO_TEST_SUITE_END()
| 25.16129 | 58 | 0.755128 |
f94e38df5799ef9f869a4654054e011cac6b46a3 | 13,307 | hpp | C++ | common/cxx/adstlog_cxx/include/adstlog_cxx/adstlog.hpp | csitarichie/someip_cyclone_dds_bridge | 2ccaaa6e2484a938b08562497431df61ab23769f | [
"MIT"
] | null | null | null | common/cxx/adstlog_cxx/include/adstlog_cxx/adstlog.hpp | csitarichie/someip_cyclone_dds_bridge | 2ccaaa6e2484a938b08562497431df61ab23769f | [
"MIT"
] | null | null | null | common/cxx/adstlog_cxx/include/adstlog_cxx/adstlog.hpp | csitarichie/someip_cyclone_dds_bridge | 2ccaaa6e2484a938b08562497431df61ab23769f | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <string>
#include <vector>
#include "adstlog_cxx/p7_trace_wrapper.hpp"
// clang-format off
// Actor module registers all of these channels
#define ADSTLOG_ACTOR_CH p7ActorCh_
#define ADSTLOG_MSG_TX_CH p7MsgTxCh_
#define ADSTLOG_MSG_RX_CH p7MsgRxCh_
#define ADSTLOG_GRPC_RX_CH p7GrpcRxCh_
#define ADSTLOG_GRPC_TX_CH p7GrpcTxCh_
#define ADSTLOG_GRPC_CH p7GrpcCh_
#define ADSTLOG_CORE_CH p7CoreCh_
// channel names to be used for set trace level on channels
#define ADSTLOG_MSG_TX_CH_NAME "msg_tx" // message published internal dispatch
#define ADSTLOG_MSG_RX_CH_NAME "msg_rx" // message consumed internal dispatch
#define ADSTLOG_GRPC_RX_CH_NAME "grpc_rx" // message received between processes
#define ADSTLOG_GRPC_TX_CH_NAME "grpc_tx" // message transmitted between processes
#define ADSTLOG_GRPC_CH_NAME "grpc" // used in gRPC boarder actors debugging
#define ADSTLOG_CORE_CH_NAME "core" // used by all framework classes
#define ADSTLOG_ACTOR_CH_NAME "actor" // all user modules are on this channel
// helper to be used in for loops to iterate over on channels.
#define ADSTLOG_TRACE_CHANNELS \
ADSTLOG_MSG_TX_CH_NAME, \
ADSTLOG_MSG_RX_CH_NAME, \
ADSTLOG_GRPC_RX_CH_NAME, \
ADSTLOG_GRPC_TX_CH_NAME, \
ADSTLOG_GRPC_CH_NAME, \
ADSTLOG_CORE_CH_NAME, \
ADSTLOG_ACTOR_CH_NAME
// the actual call for the trace function
#define ADSTLOG_LOG_ON(OBJ, LVL, CHANNEL, MODULE, ...) \
OBJ->CHANNEL->getObj()->Trace(0, \
LVL, \
OBJ->MODULE, \
(tUINT16)__LINE__, \
(const char*)__FILE__, \
(const char*)__FUNCTION__, \
__VA_ARGS__)
// then the logging is happening in a class where trace defined
#define ADSTLOG_LOG(...) \
ADSTLOG_LOG_ON(this, __VA_ARGS__)
// helper macros
#define ADSTLOG_CH(CH) ADSTLOG_##CH##_CH
#define ADSTLOG_CH_MOD(CH, MOD) p7_##CH##_##MOD##_
// Helper macros for define / declare traces in actor base
#define ADSTLOG_GET_CH(CH) mutable adst::common::Logger::ChannelUPtr ADSTLOG_CH(CH) = \
std::make_unique<adst::common::ManageTraceObj<IP7_Trace>>(&P7_Get_Shared_Trace, \
ADSTLOG_##CH##_CH_NAME, &IP7_Trace::Release)
#define ADSTLOG_DEFINE_CH(CH) mutable adst::common::Logger::ChannelUPtr ADSTLOG_CH(CH) = nullptr
#define ADSTLOG_INIT_CH(CH) ADSTLOG_CH(CH) = \
std::make_unique<adst::common::ManageTraceObj<IP7_Trace>>(&P7_Get_Shared_Trace, \
ADSTLOG_##CH##_CH_NAME, &IP7_Trace::Release)
#define ADSTLOG_REGISTER_MODULE(CH, MOD, NAME) \
mutable IP7_Trace::hModule ADSTLOG_CH_MOD(CH, MOD) = nullptr; \
tBOOL isNewModule_##CH##_##MOD = ADSTLOG_CH(CH)->getObj()->Register_Module(NAME, &ADSTLOG_CH_MOD(CH, MOD))
#define ADSTLOG_DEFINE_MODULE(CH, MOD) mutable IP7_Trace::hModule ADSTLOG_CH_MOD(CH, MOD) = nullptr
#define ADSTLOG_INIT_MODULE(CH, MOD, NAME) ADSTLOG_CH(CH)->getObj()->Register_Module(NAME, &ADSTLOG_CH_MOD(CH, MOD))
#define TEST_HELPER_ADSTLOG_UNUSED(CH, MOD) \
mutable (void)isNewModule_##CH##_##MOD
// public macros
#define TEST_HELPER_ADSTLOG_UNUSED_ALL() \
TEST_HELPER_ADSTLOG_UNUSED(ACTOR, ACTOR); \
TEST_HELPER_ADSTLOG_UNUSED(MSG_TX, ACTOR); \
TEST_HELPER_ADSTLOG_UNUSED(MSG_RX, ACTOR); \
TEST_HELPER_ADSTLOG_UNUSED(GRPC_RX, ACTOR); \
TEST_HELPER_ADSTLOG_UNUSED(GRPC_TX, ACTOR); \
TEST_HELPER_ADSTLOG_UNUSED(GRPC, ACTOR); \
TEST_HELPER_ADSTLOG_UNUSED(CORE, ACTOR)
/**
* Generic trace macros can be used in ADST FW to log on non actor channel and non actor.name_ module.
* The need for this is very rare. Normally, user shall not use these.
*
* They are used by the more restrictive trace macros like LOG_I(...), and LOG_CH_I(...), etc.
*/
#define LOG_CH_MOD_E(CH, MOD, ...) \
ADSTLOG_LOG(EP7TRACE_LEVEL_ERROR, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_W(CH, MOD, ...) \
ADSTLOG_LOG(EP7TRACE_LEVEL_WARNING, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_I(CH, MOD, ...) \
ADSTLOG_LOG(EP7TRACE_LEVEL_INFO, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_D(CH, MOD, ...) \
ADSTLOG_LOG(EP7TRACE_LEVEL_DEBUG, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_T(CH, MOD, ...) \
ADSTLOG_LOG(EP7TRACE_LEVEL_TRACE, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_E_ON(OBJ, CH, MOD, ...) \
ADSTLOG_LOG_ON(OBJ, EP7TRACE_LEVEL_ERROR, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_W_ON(OBJ, CH, MOD, ...) \
ADSTLOG_LOG_ON(OBJ, EP7TRACE_LEVEL_WARNING, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_I_ON(OBJ, CH, MOD, ...) \
ADSTLOG_LOG_ON(OBJ, EP7TRACE_LEVEL_INFO, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_D_ON(OBJ, CH, MOD, ...) \
ADSTLOG_LOG_ON(OBJ, EP7TRACE_LEVEL_DEBUG, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
#define LOG_CH_MOD_T_ON(OBJ, CH, MOD, ...) \
ADSTLOG_LOG(OBJ, EP7TRACE_LEVEL_TRACE, ADSTLOG_CH(CH), ADSTLOG_CH_MOD(CH, MOD), __VA_ARGS__) /* NOLINT */
/**
* Log macro meant to be used within the ADST FW for tracing
* on actor.name_ channel instead of actor or core.
*
* Mostly used in fw to log gRPC and dispatch message tx/rx.
*/
#define LOG_CH_E(CH, ...) LOG_CH_MOD_E(CH, ACTOR, __VA_ARGS__)
#define LOG_CH_W(CH, ...) LOG_CH_MOD_W(CH, ACTOR, __VA_ARGS__)
#define LOG_CH_I(CH, ...) LOG_CH_MOD_I(CH, ACTOR, __VA_ARGS__)
#define LOG_CH_D(CH, ...) LOG_CH_MOD_D(CH, ACTOR, __VA_ARGS__)
#define LOG_CH_T(CH, ...) LOG_CH_MOD_T(CH, ACTOR, __VA_ARGS__)
#define LOG_CH_E_ON(OBJ, CH, ...) LOG_CH_MOD_E_ON((&OBJ), CH, ACTOR, __VA_ARGS__)
#define LOG_CH_W_ON(OBJ, CH, ...) LOG_CH_MOD_W_ON((&OBJ), CH, ACTOR, __VA_ARGS__)
#define LOG_CH_I_ON(OBJ, CH, ...) LOG_CH_MOD_I_ON((&OBJ), CH, ACTOR, __VA_ARGS__)
#define LOG_CH_D_ON(OBJ, CH, ...) LOG_CH_MOD_D_ON((&OBJ), CH, ACTOR, __VA_ARGS__)
#define LOG_CH_T_ON(OBJ, CH, ...) LOG_CH_MOD_T_ON((&OBJ), CH, ACTOR, __VA_ARGS__)
/**
* Logging macro meant to be used within the ADST FW for logging on core channel and on actor.name_ module
* main macro used for tracing within the fw for debug
*/
#define LOG_C_E(...) LOG_CH_E(CORE, __VA_ARGS__)
#define LOG_C_W(...) LOG_CH_W(CORE, __VA_ARGS__)
#define LOG_C_I(...) LOG_CH_I(CORE, __VA_ARGS__)
#define LOG_C_D(...) LOG_CH_D(CORE, __VA_ARGS__)
// core trace TRACE_LEVEL very verbose and has performance penalty it is not compiled in by default.
#ifdef ADSTLOG_TRACE_LEVEL_CORE_COMPILED_IN
#define LOG_C_T(...) LOG_CH_T(CORE, __VA_ARGS__)
#else
#define LOG_C_T(...)
#endif
/**
* Default logging macros. Shall be used by components and all code logic outside of ADST FW. Logs
* on actor channel on Actor.name_ module
*/
#define LOG_E(...) LOG_CH_E(ACTOR, __VA_ARGS__)
#define LOG_W(...) LOG_CH_W(ACTOR, __VA_ARGS__)
#define LOG_I(...) LOG_CH_I(ACTOR, __VA_ARGS__)
#define LOG_D(...) LOG_CH_D(ACTOR, __VA_ARGS__)
#define LOG_T(...) LOG_CH_T(ACTOR, __VA_ARGS__)
/**
* Default logging macros. Shall be used by components and all code logic outside of ADST FW. Logs
* on actor channel on Actor.name_ module
*/
#define LOG_E_ON(OBJ, ...) LOG_CH_E_ON(OBJ, ACTOR, __VA_ARGS__)
#define LOG_W_ON(OBJ, ...) LOG_CH_W_ON(OBJ, ACTOR, __VA_ARGS__)
#define LOG_I_ON(OBJ, ...) LOG_CH_I_ON(OBJ, ACTOR, __VA_ARGS__)
#define LOG_D_ON(OBJ, ...) LOG_CH_D_ON(OBJ, ACTOR, __VA_ARGS__)
#define LOG_T_ON(OBJ, ...) LOG_CH_T_ON(OBJ, ACTOR, __VA_ARGS__)
// Every Class which works in actor context shall use this trace macro to enable tracing within the class
/**
* Only defines the member variables for tracing but does not initialize them this might be
* necessary in case of template classes.
*
* If this macro is used, the constructor must call ADSTLOG_INIT_ACTOR_TRACE_MODULES.
* *Before* considering to use this macro, make sure that ADSTLOG_DEF_DEC_ACTOR_TRACE_MODULES is not
* suitable.
*/
#define ADSTLOG_DEF_ACTOR_TRACE_MODULES() \
ADSTLOG_DEFINE_CH(ACTOR); \
ADSTLOG_DEFINE_CH(MSG_TX); \
ADSTLOG_DEFINE_CH(MSG_RX); \
ADSTLOG_DEFINE_CH(GRPC_RX); \
ADSTLOG_DEFINE_CH(GRPC_TX); \
ADSTLOG_DEFINE_CH(GRPC); \
ADSTLOG_DEFINE_CH(CORE); \
ADSTLOG_DEFINE_MODULE(ACTOR, ACTOR); \
ADSTLOG_DEFINE_MODULE(MSG_TX, ACTOR); \
ADSTLOG_DEFINE_MODULE(MSG_RX, ACTOR); \
ADSTLOG_DEFINE_MODULE(GRPC_RX, ACTOR); \
ADSTLOG_DEFINE_MODULE(GRPC_TX, ACTOR); \
ADSTLOG_DEFINE_MODULE(GRPC, ACTOR); \
ADSTLOG_DEFINE_MODULE(CORE, ACTOR)
/**
* The macro is meant to used together with ADSTLOG_DEF_ACTOR_TRACE_MODULES. It shall be used in
* class constructor when ADSTLOG_DEF_ACTOR_TRACE_MODULES was used in the class declaration.
*/
#define ADSTLOG_INIT_ACTOR_TRACE_MODULES(NAME) \
ADSTLOG_INIT_CH(ACTOR); \
ADSTLOG_INIT_CH(MSG_TX); \
ADSTLOG_INIT_CH(MSG_RX); \
ADSTLOG_INIT_CH(GRPC_RX); \
ADSTLOG_INIT_CH(GRPC_TX); \
ADSTLOG_INIT_CH(GRPC); \
ADSTLOG_INIT_CH(CORE); \
ADSTLOG_INIT_MODULE(ACTOR, ACTOR, NAME); \
ADSTLOG_INIT_MODULE(MSG_TX, ACTOR, NAME); \
ADSTLOG_INIT_MODULE(MSG_RX, ACTOR, NAME); \
ADSTLOG_INIT_MODULE(GRPC_RX, ACTOR, NAME); \
ADSTLOG_INIT_MODULE(GRPC_TX, ACTOR, NAME); \
ADSTLOG_INIT_MODULE(GRPC, ACTOR, NAME); \
ADSTLOG_INIT_MODULE(CORE, ACTOR, NAME)
/**
* Register threads used by ADST FW (user shall not create threads).
*/
#define ADSTLOG_REGISTER_THREAD(THREAD_ID, NAME) \
ADSTLOG_CH(ACTOR)->getObj()->Register_Thread(NAME, THREAD_ID); \
ADSTLOG_CH(MSG_TX)->getObj()->Register_Thread(NAME, THREAD_ID); \
ADSTLOG_CH(MSG_RX)->getObj()->Register_Thread(NAME, THREAD_ID); \
ADSTLOG_CH(GRPC_RX)->getObj()->Register_Thread(NAME, THREAD_ID); \
ADSTLOG_CH(GRPC_TX)->getObj()->Register_Thread(NAME, THREAD_ID); \
ADSTLOG_CH(GRPC)->getObj()->Register_Thread(NAME, THREAD_ID); \
ADSTLOG_CH(CORE)->getObj()->Register_Thread(NAME, THREAD_ID)
#define ADSTLOG_REGISTER_THREAD_ON(OBJ, THREAD_ID, NAME) \
OBJ.ADSTLOG_CH(ACTOR)->getObj()->Register_Thread(NAME, THREAD_ID); \
OBJ.ADSTLOG_CH(MSG_TX)->getObj()->Register_Thread(NAME, THREAD_ID); \
OBJ.ADSTLOG_CH(MSG_RX)->getObj()->Register_Thread(NAME, THREAD_ID); \
OBJ.ADSTLOG_CH(GRPC_RX)->getObj()->Register_Thread(NAME, THREAD_ID); \
OBJ.ADSTLOG_CH(GRPC_TX)->getObj()->Register_Thread(NAME, THREAD_ID); \
OBJ.ADSTLOG_CH(GRPC)->getObj()->Register_Thread(NAME, THREAD_ID); \
OBJ.ADSTLOG_CH(CORE)->getObj()->Register_Thread(NAME, THREAD_ID)
/**
* Unregister threads used by ADST FW (user shall not create threads).
*/
#define ADSTLOG_UNREGISTER_THREAD(THREAD_ID) \
ADSTLOG_CH(ACTOR)->getObj()->Unregister_Thread(THREAD_ID); \
ADSTLOG_CH(MSG_TX)->getObj()->Unregister_Thread(THREAD_ID); \
ADSTLOG_CH(MSG_RX)->getObj()->Unregister_Thread(THREAD_ID); \
ADSTLOG_CH(GRPC_RX)->getObj()->Unregister_Thread(THREAD_ID); \
ADSTLOG_CH(GRPC_TX)->getObj()->Unregister_Thread(THREAD_ID); \
ADSTLOG_CH(GRPC)->getObj()->Unregister_Thread(THREAD_ID); \
ADSTLOG_CH(CORE)->getObj()->Unregister_Thread(THREAD_ID)
// clang-format on
#define ADSTLOG_UNREGISTER_THREAD_ON(OBJ, THREAD_ID) \
OBJ.ADSTLOG_CH(ACTOR)->getObj()->Unregister_Thread(THREAD_ID); \
OBJ.ADSTLOG_CH(MSG_TX)->getObj()->Unregister_Thread(THREAD_ID); \
OBJ.ADSTLOG_CH(MSG_RX)->getObj()->Unregister_Thread(THREAD_ID); \
OBJ.ADSTLOG_CH(GRPC_RX)->getObj()->Unregister_Thread(THREAD_ID); \
OBJ.ADSTLOG_CH(GRPC_TX)->getObj()->Unregister_Thread(THREAD_ID); \
OBJ.ADSTLOG_CH(GRPC)->getObj()->Unregister_Thread(THREAD_ID); \
OBJ.ADSTLOG_CH(CORE)->getObj()->Unregister_Thread(THREAD_ID)
// clang-format on
namespace adst::common {
struct Config;
/**
* Only one single instance of logger shall exist in any ADST c++ process.
*/
class Logger
{
// not copyable or movable
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
Logger(Logger&&) = delete;
Logger& operator=(Logger&&) = delete;
public:
using ClientUPtr = std::unique_ptr<ManageTraceObj<IP7_Client>>;
using ChannelUPtr = std::unique_ptr<ManageTraceObj<IP7_Trace>>;
Logger(const Config& config);
// there is no flush is needed when the logger is recycled flush is called from the trance Object destructor.
~Logger() = default;
private:
std::string getClientConfigStr(const Config& config);
ClientUPtr client_ = nullptr;
std::vector<ChannelUPtr> channels_;
};
} // namespace adst::common
| 46.044983 | 116 | 0.690915 |
f952d5cc45ae8b814c1940f16c5fc9eda719b50a | 6,025 | cpp | C++ | src/SearchRange.cpp | emweb/aga | bd7ad699e901168fe1658bea7c3c5d53fa5938e5 | [
"OML",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 13 | 2017-10-12T10:10:55.000Z | 2020-11-12T08:28:43.000Z | src/SearchRange.cpp | emweb/aga | bd7ad699e901168fe1658bea7c3c5d53fa5938e5 | [
"OML",
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/SearchRange.cpp | emweb/aga | bd7ad699e901168fe1658bea7c3c5d53fa5938e5 | [
"OML",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 6 | 2018-09-13T04:49:10.000Z | 2020-11-12T08:28:45.000Z | #include "SearchRange.h"
#include "Cigar.h"
SearchRangeItem::SearchRangeItem(Type aType, int aStartColumn, int anEndColumn,
int aStartRow, int anEndRow)
: type(aType),
startRow(aStartRow),
endRow(anEndRow),
startColumn(aStartColumn),
endColumn(anEndColumn)
{ }
std::ostream& operator<<(std::ostream& o, const SearchRangeItem& sri)
{
switch (sri.type) {
case SearchRangeItem::Rectangle:
o << "rect Start=(" << sri.startColumn << "," << sri.startRow << ") "
<< "End=(" << sri.endColumn << "," << sri.endRow << ")";
break;
case SearchRangeItem::Parallelogram:
o << "para Start=(" << sri.startColumn << "," << sri.startRow << " - " << sri.endRow << ") "
<< "End=(" << sri.endColumn << "," << sri.startRow + (sri.endColumn - sri.startColumn)
<< " - " << sri.endRow + (sri.endColumn - sri.startColumn) << ")";
}
return o;
}
SearchRange::SearchRange()
: columns(0),
rows(0)
{ }
SearchRange::SearchRange(int aColumns, int aRows)
: columns(aColumns),
rows(aRows)
{
items.push_back(SearchRangeItem(SearchRangeItem::Rectangle,
0, columns,
0, rows));
}
int SearchRange::startRow(int column) const
{
for (const auto& i : items) {
if (column < i.endColumn) {
switch (i.type) {
case SearchRangeItem::Rectangle:
return std::max(0, i.startRow);
case SearchRangeItem::Parallelogram:
return std::max(0, i.startRow + (column - i.startColumn));
}
}
}
throw std::runtime_error("Incomplete search range not covering " + std::to_string(column));
}
int SearchRange::endRow(int column) const
{
for (const auto& i : items) {
if (column < i.endColumn) {
switch (i.type) {
case SearchRangeItem::Rectangle:
return std::min(rows, i.endRow);
case SearchRangeItem::Parallelogram:
return std::min(rows, i.endRow + (column - i.startColumn));
}
}
}
throw std::runtime_error("Incomplete search range not covering " +
std::to_string(column));
}
int SearchRange::maxRowCount() const
{
int result = 0;
for (const auto& i : items) {
int h = i.endRow - i.startRow;
if (h > result)
result = h;
}
return result;
}
long SearchRange::size() const
{
long result = 0;
for (const auto& i : items) {
long h = i.endRow - i.startRow;
long w = i.endColumn - i.startColumn;
result += h * w;
}
return result;
}
SearchRange getSearchRange(const Cigar& seed,
int refSize, int querySize, int margin)
{
if (seed.empty())
return SearchRange(refSize + 1, querySize + 1);
else {
SearchRange result(refSize + 1, querySize + 1);
result.items.clear();
SearchRangeItem::Type currentType = SearchRangeItem::Rectangle;
int currentRefStart = 0;
int currentQueryStart = 0;
int refI = 1;
int queryI = 1;
const int MARGIN = margin;
for (const auto& i : seed) {
if (i.op() == CigarItem::RefSkipped ||
i.op() == CigarItem::QuerySkipped) {
// terminate current aligned block
if (currentType == SearchRangeItem::Parallelogram) {
if (refI > currentRefStart && queryI > currentQueryStart) {
int deviation = std::abs((queryI - currentQueryStart) -
(refI - currentRefStart));
deviation += MARGIN;
result.items.push_back
(SearchRangeItem(currentType,
currentRefStart,
refI,
currentQueryStart - deviation,
currentQueryStart + deviation));
}
currentType = SearchRangeItem::Rectangle;
currentRefStart = refI;
currentQueryStart = queryI - MARGIN;
}
if (i.op() == CigarItem::RefSkipped)
refI += i.length();
else
queryI += i.length();
} else {
// terminate current non-aligned block
if (currentType == SearchRangeItem::Rectangle) {
if (result.items.empty()) {
int s = refI - queryI - 10 * MARGIN;
if (s > MARGIN) {
result.items.push_back
(SearchRangeItem(currentType,
currentRefStart,
s,
currentQueryStart,
1));
currentRefStart = s;
}
}
result.items.push_back
(SearchRangeItem(currentType,
currentRefStart,
refI,
currentQueryStart,
queryI + MARGIN));
currentType = SearchRangeItem::Parallelogram;
currentRefStart = refI;
currentQueryStart = queryI;
}
switch (i.op()) {
case CigarItem::Match:
refI += i.length();
queryI += i.length();
break;
case CigarItem::RefGap:
queryI += i.length();
break;
case CigarItem::QueryGap:
refI += i.length();
break;
default:
break;
}
}
refI = std::min(refI, refSize);
queryI = std::min(queryI, querySize);
}
// Terminate last block
if (currentType == SearchRangeItem::Parallelogram) {
if (refI > currentRefStart && queryI > currentQueryStart) {
int deviation = std::abs((queryI - currentQueryStart) -
(refI - currentRefStart));
deviation += MARGIN;
result.items.push_back
(SearchRangeItem(currentType,
currentRefStart,
refI,
currentQueryStart - deviation,
currentQueryStart + deviation));
currentRefStart = refI;
currentQueryStart = queryI - MARGIN;
}
}
if (currentRefStart < refSize + 1) {
int s = currentRefStart + (querySize - queryI + 10 * MARGIN);
if (s < refSize + 1 - MARGIN) {
result.items.push_back
(SearchRangeItem(SearchRangeItem::Rectangle,
currentRefStart, s,
currentQueryStart, querySize + 1));
currentRefStart = s;
currentQueryStart = querySize;
}
result.items.push_back
(SearchRangeItem(SearchRangeItem::Rectangle,
currentRefStart, refSize + 1,
currentQueryStart, querySize + 1));
}
return result;
}
}
std::ostream& operator<<(std::ostream& o, const SearchRange& sr)
{
std::cerr << "SearchRange [";
bool first = true;
for (const auto& i : sr.items) {
if (!first)
std::cerr << ",";
std::cerr << std::endl << " " << i;
first = false;
}
std::cerr << std::endl << "]" << std::endl;
return o;
}
| 23.720472 | 99 | 0.618257 |
f953fc44bb7d10293222e69195cbc3c3cdbb7bee | 13,193 | cpp | C++ | samples/examples/imkRecognizeObject-file.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | 2 | 2021-02-22T11:36:33.000Z | 2021-07-20T11:31:08.000Z | samples/examples/imkRecognizeObject-file.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | null | null | null | samples/examples/imkRecognizeObject-file.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | 3 | 2018-10-19T10:39:23.000Z | 2021-04-07T13:39:03.000Z | /******************************************************************************
* Copyright (c) 2017 Johann Prankl
*
* 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 <float.h>
#include <pcl/common/centroid.h>
#include <pcl/common/time.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <v4r/config.h>
#include <v4r/io/filesystem.h>
#include <v4r/recognition/IMKRecognizer.h>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <fstream>
#include <iostream>
#include <map>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <stdexcept>
#include <v4r/keypoints/impl/PoseIO.hpp>
#include <v4r/keypoints/impl/invPose.hpp>
#include <v4r/keypoints/impl/toString.hpp>
#include <v4r/reconstruction/impl/projectPointToImage.hpp>
#include "pcl/common/transforms.h"
//#include <v4r/features/FeatureDetector_KD_FAST_IMGD.h>
#if HAVE_SIFTGPU
#define USE_SIFT_GPU
#include <v4r/features/FeatureDetector_KD_SIFTGPU.h>
#else
#include <v4r/features/FeatureDetector_KD_CVSIFT.h>
#endif
#include <pcl/common/time.h>
using namespace std;
namespace po = boost::program_options;
void drawConfidenceBar(cv::Mat &im, const double &conf);
cv::Point2f drawCoordinateSystem(cv::Mat &im, const Eigen::Matrix4f &pose, const cv::Mat_<double> &intrinsic,
const cv::Mat_<double> &dist_coeffs, double size, int thickness);
void convertImage(const pcl::PointCloud<pcl::PointXYZRGB> &cloud, cv::Mat &image);
//--------------------------- default configuration -------------------------------
void InitParameter();
void InitParameter() {}
//------------------------------ helper methods -----------------------------------
// static void onMouse(int event, int x, int y, int flags, void *);
void setup(int argc, char **argv);
//----------------------------- data containers -----------------------------------
cv::Mat_<cv::Vec3b> image;
cv::Mat_<cv::Vec3b> im_draw;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>);
cv::Mat_<double> dist_coeffs; // = cv::Mat::zeros(4, 1, CV_64F);
cv::Mat_<double> intrinsic = cv::Mat_<double>::eye(3, 3);
Eigen::Matrix4f pose = Eigen::Matrix4f::Identity();
int ul_lr = 0;
int start = 0, end_idx = 10;
cv::Point track_win[2];
std::string cam_file;
string filenames, base_dir, codebook_filename;
std::vector<std::string> object_names;
std::vector<v4r::triple<std::string, double, Eigen::Matrix4f>> objects;
double thr_conf = 0;
int live = -1;
bool loop = false;
/******************************************************************
* MAIN
*/
int main(int argc, char *argv[]) {
int sleep = 0;
char filename[PATH_MAX];
track_win[0] = cv::Point(0, 0);
track_win[1] = cv::Point(640, 480);
// config
InitParameter();
setup(argc, argv);
intrinsic(0, 0) = intrinsic(1, 1) = 525;
intrinsic(0, 2) = 320, intrinsic(1, 2) = 240;
if (cam_file.size() > 0) {
cv::FileStorage fs(cam_file, cv::FileStorage::READ);
fs["camera_matrix"] >> intrinsic;
fs["distortion_coefficients"] >> dist_coeffs;
}
cv::namedWindow("image", CV_WINDOW_AUTOSIZE);
// init recognizer
v4r::IMKRecognizer::Parameter param;
param.pnp_param.eta_ransac = 0.01;
param.pnp_param.max_rand_trials = 10000;
param.pnp_param.inl_dist_px = 2;
param.pnp_param.inl_dist_z = 0.02;
param.vc_param.cluster_dist = 40;
#ifdef USE_SIFT_GPU
param.cb_param.nnr = 1.000001;
param.cb_param.thr_desc_rnn = 0.25;
param.cb_param.max_dist = FLT_MAX;
v4r::FeatureDetector::Ptr detector(new v4r::FeatureDetector_KD_SIFTGPU());
#else
v4r::KeypointObjectRecognizer::Parameter param;
param.cb_param.nnr = 1.000001;
param.cb_param.thr_desc_rnn = 250.;
param.cb_param.max_dist = FLT_MAX;
v4r::FeatureDetector::Ptr detector(new v4r::FeatureDetector_KD_CVSIFT());
#endif
// // -- test imgd --
// param.cb_param.nnr = 1.000001;
// param.cb_param.thr_desc_rnn = 0.25;
// param.cb_param.max_dist = FLT_MAX;
// v4r::FeatureDetector_KD_FAST_IMGD::Parameter imgd_param(1000, 1.3, 4, 15);
// v4r::FeatureDetector::Ptr detector(new v4r::FeatureDetector_KD_FAST_IMGD(imgd_param));
// // -- end --
v4r::IMKRecognizer recognizer(param, detector, detector);
recognizer.setCameraParameter(intrinsic, dist_coeffs);
recognizer.setDataDirectory(base_dir);
if (!codebook_filename.empty())
recognizer.setCodebookFilename(codebook_filename);
if (object_names.size() == 0) { // take all direcotry names from the base_dir
object_names = v4r::io::getFoldersInDirectory(base_dir);
}
for (unsigned i = 0; i < object_names.size(); i++)
recognizer.addObject(object_names[i]);
std::cout << "Number of models: " << object_names.size() << std::endl;
recognizer.initModels();
cv::VideoCapture cap;
if (live != -1) {
cap.open(live);
cap.set(CV_CAP_PROP_FRAME_WIDTH, 640);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
loop = true;
if (!cap.isOpened()) {
cout << "Could not initialize capturing...\n";
return 0;
}
}
// ---------------------- recognize object ---------------------------
for (int i = start; i <= end_idx || loop; i++) {
cout << "---------------- FRAME #" << i << " -----------------------" << endl;
if (live != -1) {
cap >> image;
} else {
snprintf(filename, PATH_MAX, filenames.c_str(), i);
cout << filename << endl;
image = cv::Mat_<cv::Vec3b>();
if (filenames.compare(filenames.size() - 3, 3, "pcd") == 0) {
if (pcl::io::loadPCDFile(filename, *cloud) == -1)
continue;
convertImage(*cloud, image);
} else {
image = cv::imread(filename, 1);
}
}
image.copyTo(im_draw);
recognizer.dbg = im_draw;
// cloud->clear();
// track
{
pcl::ScopeTime t("overall time");
if (cloud->width != (unsigned)image.cols || cloud->height != (unsigned)image.rows) {
recognizer.recognize(image, objects);
cout << "Use image only!" << endl;
} else {
recognizer.recognize(*cloud, objects);
cout << "Use image and cloud!" << endl;
}
} //-- overall time --
// debug out draw
// cv::addText( image, P::toString(1000./time)+std::string(" fps"), cv::Point(25,35), font);
cout << "Confidence value threshold for visualization: " << thr_conf << endl;
cout << "Found objects:" << endl;
for (unsigned j = 0; j < objects.size(); j++) {
cout << j << ": name= " << objects[j].first << ", conf= " << objects[j].second << endl;
if (objects[j].second >= thr_conf) {
cv::Point2f origin = drawCoordinateSystem(im_draw, objects[j].third, intrinsic, dist_coeffs, 0.1, 4);
// cv::addText( im_draw, objects[i].first+std::string(" (")+v4r::toString(objects[i].second)<<std::string(")"),
// origin+cv::Point(0,-10), font);
std::string txt = v4r::toString(j) + std::string(": ") + objects[j].first + std::string(" (") +
v4r::toString(objects[j].second) + std::string(")");
cv::putText(im_draw, txt, origin + cv::Point2f(0, 10), cv::FONT_HERSHEY_PLAIN, 1.5, CV_RGB(255, 255, 255), 2,
CV_AA);
}
}
cv::imshow("image", im_draw);
int key = cv::waitKey(sleep);
if (((char)key) == 27)
break;
if (((char)key) == 'r')
sleep = 1;
if (((char)key) == 's')
sleep = 0;
}
cv::waitKey(0);
return 0;
}
/******************************** SOME HELPER METHODS **********************************/
/*
* static void onMouse(int event, int x, int y, int flags, void *) {
if (x < 0 || x >= im_draw.cols || y < 0 || y >= im_draw.rows)
return;
if (event == CV_EVENT_LBUTTONUP && (flags & CV_EVENT_FLAG_LBUTTON)) {
track_win[ul_lr % 2] = cv::Point(x, y);
if (ul_lr % 2 == 0)
cout << "upper left corner: " << track_win[ul_lr % 2] << endl;
else
cout << "lower right corner: " << track_win[ul_lr % 2] << endl;
ul_lr++;
}
}
*/
/**
* setup
*/
void setup(int argc, char **argv) {
po::options_description general("General options");
general.add_options()("help,h", "show help message")("filenames,f",
po::value<std::string>(&filenames)->default_value(filenames),
"Input filename for recognition (printf-style)")(
"base_dir,d", po::value<std::string>(&base_dir)->default_value(base_dir), "Object model directory")(
"codebook_filename,c", po::value<std::string>(&codebook_filename), "Optional filename for codebook")(
"object_names,n", po::value<std::vector<std::string>>(&object_names)->multitoken(), "Object names")(
"start,s", po::value<int>(&start)->default_value(start), "start index")(
"end,e", po::value<int>(&end_idx)->default_value(end_idx), "end index")(
"cam_file,a", po::value<std::string>(&cam_file)->default_value(cam_file),
"camera calibration files (opencv format)")("live,l", po::value<int>(&live)->default_value(live),
"use live camera (OpenCV)")(
"thr_conf,t", po::value<double>(&thr_conf)->default_value(thr_conf),
"Confidence value threshold (visualization)");
po::options_description all("");
all.add(general);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(all).run(), vm);
po::notify(vm);
std::string usage = "";
if (vm.count("help")) {
std::cout << usage << std::endl;
std::cout << all;
return;
}
return;
}
/**
* drawConfidenceBar
*/
void drawConfidenceBar(cv::Mat &im, const double &conf) {
int bar_start = 50, bar_end = 200;
int diff = bar_end - bar_start;
int draw_end = diff * conf;
double col_scale = 255. / (double)diff;
cv::Point2f pt1(0, 30);
cv::Point2f pt2(0, 30);
cv::Vec3b col(0, 0, 0);
if (draw_end <= 0)
draw_end = 1;
for (int i = 0; i < draw_end; i++) {
col = cv::Vec3b(255 - (i * col_scale), i * col_scale, 0);
pt1.x = bar_start + i;
pt2.x = bar_start + i + 1;
cv::line(im, pt1, pt2, CV_RGB(col[0], col[1], col[2]), 8);
}
}
cv::Point2f drawCoordinateSystem(cv::Mat &im, const Eigen::Matrix4f &_pose, const cv::Mat_<double> &_intrinsic,
const cv::Mat_<double> &_dist_coeffs, double size, int thickness) {
Eigen::Matrix3f R = _pose.topLeftCorner<3, 3>();
Eigen::Vector3f t = _pose.block<3, 1>(0, 3);
Eigen::Vector3f pt0 = R * Eigen::Vector3f(0, 0, 0) + t;
Eigen::Vector3f pt_x = R * Eigen::Vector3f(size, 0, 0) + t;
Eigen::Vector3f pt_y = R * Eigen::Vector3f(0, size, 0) + t;
Eigen::Vector3f pt_z = R * Eigen::Vector3f(0, 0, size) + t;
cv::Point2f im_pt0, im_pt_x, im_pt_y, im_pt_z;
if (!_dist_coeffs.empty()) {
v4r::projectPointToImage(&pt0[0], &_intrinsic(0), &_dist_coeffs(0), &im_pt0.x);
v4r::projectPointToImage(&pt_x[0], &_intrinsic(0), &_dist_coeffs(0), &im_pt_x.x);
v4r::projectPointToImage(&pt_y[0], &_intrinsic(0), &_dist_coeffs(0), &im_pt_y.x);
v4r::projectPointToImage(&pt_z[0], &_intrinsic(0), &_dist_coeffs(0), &im_pt_z.x);
} else {
v4r::projectPointToImage(&pt0[0], &_intrinsic(0), &im_pt0.x);
v4r::projectPointToImage(&pt_x[0], &_intrinsic(0), &im_pt_x.x);
v4r::projectPointToImage(&pt_y[0], &_intrinsic(0), &im_pt_y.x);
v4r::projectPointToImage(&pt_z[0], &_intrinsic(0), &im_pt_z.x);
}
cv::line(im, im_pt0, im_pt_x, CV_RGB(255, 0, 0), thickness);
cv::line(im, im_pt0, im_pt_y, CV_RGB(0, 255, 0), thickness);
cv::line(im, im_pt0, im_pt_z, CV_RGB(0, 0, 255), thickness);
return im_pt0;
}
void convertImage(const pcl::PointCloud<pcl::PointXYZRGB> &_cloud, cv::Mat &_image) {
_image = cv::Mat_<cv::Vec3b>(_cloud.height, _cloud.width);
for (unsigned v = 0; v < _cloud.height; v++) {
for (unsigned u = 0; u < _cloud.width; u++) {
cv::Vec3b &cv_pt = _image.at<cv::Vec3b>(v, u);
const pcl::PointXYZRGB &pt = _cloud(u, v);
cv_pt[2] = pt.r;
cv_pt[1] = pt.g;
cv_pt[0] = pt.b;
}
}
}
| 35.560647 | 119 | 0.612901 |
f95623fc124c783cd96198949f96e5a69b54b9e0 | 1,560 | cpp | C++ | src/modes/mode_reprint_hbp.cpp | kliment-olechnovic/voronota | 4e3063aa86b44f1f2e7b088ec9976f3e12047549 | [
"MIT"
] | 9 | 2019-08-23T10:46:18.000Z | 2022-03-11T12:20:27.000Z | src/modes/mode_reprint_hbp.cpp | kliment-olechnovic/voronota | 4e3063aa86b44f1f2e7b088ec9976f3e12047549 | [
"MIT"
] | null | null | null | src/modes/mode_reprint_hbp.cpp | kliment-olechnovic/voronota | 4e3063aa86b44f1f2e7b088ec9976f3e12047549 | [
"MIT"
] | 3 | 2020-09-17T19:07:47.000Z | 2021-04-29T01:19:38.000Z | #include "../auxiliaries/program_options_handler.h"
#include "../auxiliaries/atoms_io.h"
#include "../auxiliaries/io_utilities.h"
#include "../common/chain_residue_atom_descriptor.h"
void reprint_hbp(const voronota::auxiliaries::ProgramOptionsHandler& poh)
{
voronota::auxiliaries::ProgramOptionsHandlerWrapper pohw(poh);
pohw.describe_io("stdin", true, false, "hbplus output");
pohw.describe_io("stdout", false, true, "output");
if(!pohw.assert_or_print_help(false))
{
return;
}
typedef voronota::common::ChainResidueAtomDescriptor CRAD;
typedef voronota::common::ChainResidueAtomDescriptorsPair CRADsPair;
std::set<CRADsPair> set_of_hbplus_crad_pairs;
voronota::auxiliaries::AtomsIO::HBPlusReader::Data hbplus_file_data=voronota::auxiliaries::AtomsIO::HBPlusReader::read_data_from_file_stream(std::cin);
if(!hbplus_file_data.hbplus_records.empty())
{
for(std::vector<voronota::auxiliaries::AtomsIO::HBPlusReader::HBPlusRecord>::const_iterator it=hbplus_file_data.hbplus_records.begin();it!=hbplus_file_data.hbplus_records.end();++it)
{
const voronota::auxiliaries::AtomsIO::HBPlusReader::ShortAtomDescriptor& a=it->first;
const voronota::auxiliaries::AtomsIO::HBPlusReader::ShortAtomDescriptor& b=it->second;
const CRADsPair crads_pair(CRAD(CRAD::null_num(), a.chainID, a.resSeq, a.resName, a.name, "", ""), CRAD(CRAD::null_num(), b.chainID, b.resSeq, b.resName, b.name, "", ""));
set_of_hbplus_crad_pairs.insert(crads_pair);
}
}
voronota::auxiliaries::IOUtilities().write_set(set_of_hbplus_crad_pairs, std::cout);
}
| 42.162162 | 184 | 0.771154 |