text string | size int64 | token_count int64 |
|---|---|---|
// 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 has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8TouchEvent.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ScriptState.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/core/v8/V8TouchList.h"
#include "bindings/core/v8/V8Window.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/frame/UseCounter.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8TouchEvent::wrapperTypeInfo = { gin::kEmbedderBlink, V8TouchEvent::domTemplate, V8TouchEvent::refObject, V8TouchEvent::derefObject, V8TouchEvent::trace, 0, 0, V8TouchEvent::preparePrototypeObject, V8TouchEvent::installConditionallyEnabledProperties, "TouchEvent", &V8UIEvent::wrapperTypeInfo, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent, WrapperTypeInfo::WillBeGarbageCollectedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in TouchEvent.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& TouchEvent::s_wrapperTypeInfo = V8TouchEvent::wrapperTypeInfo;
namespace TouchEventV8Internal {
static void touchesAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
RefPtrWillBeRawPtr<TouchList> cppValue(impl->touches());
if (cppValue && DOMDataStore::setReturnValue(info.GetReturnValue(), cppValue.get()))
return;
v8::Local<v8::Value> v8Value(toV8(cppValue.get(), holder, info.GetIsolate()));
if (!v8Value.IsEmpty()) {
V8HiddenValue::setHiddenValue(info.GetIsolate(), holder, v8AtomicString(info.GetIsolate(), "touches"), v8Value);
v8SetReturnValue(info, v8Value);
}
}
static void touchesAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::touchesAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void targetTouchesAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
RefPtrWillBeRawPtr<TouchList> cppValue(impl->targetTouches());
if (cppValue && DOMDataStore::setReturnValue(info.GetReturnValue(), cppValue.get()))
return;
v8::Local<v8::Value> v8Value(toV8(cppValue.get(), holder, info.GetIsolate()));
if (!v8Value.IsEmpty()) {
V8HiddenValue::setHiddenValue(info.GetIsolate(), holder, v8AtomicString(info.GetIsolate(), "targetTouches"), v8Value);
v8SetReturnValue(info, v8Value);
}
}
static void targetTouchesAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::targetTouchesAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void changedTouchesAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
RefPtrWillBeRawPtr<TouchList> cppValue(impl->changedTouches());
if (cppValue && DOMDataStore::setReturnValue(info.GetReturnValue(), cppValue.get()))
return;
v8::Local<v8::Value> v8Value(toV8(cppValue.get(), holder, info.GetIsolate()));
if (!v8Value.IsEmpty()) {
V8HiddenValue::setHiddenValue(info.GetIsolate(), holder, v8AtomicString(info.GetIsolate(), "changedTouches"), v8Value);
v8SetReturnValue(info, v8Value);
}
}
static void changedTouchesAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::changedTouchesAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void altKeyAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
v8SetReturnValueBool(info, impl->altKey());
}
static void altKeyAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::altKeyAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void metaKeyAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
v8SetReturnValueBool(info, impl->metaKey());
}
static void metaKeyAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::metaKeyAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void ctrlKeyAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
v8SetReturnValueBool(info, impl->ctrlKey());
}
static void ctrlKeyAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::ctrlKeyAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void shiftKeyAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TouchEvent* impl = V8TouchEvent::toImpl(holder);
v8SetReturnValueBool(info, impl->shiftKey());
}
static void shiftKeyAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TouchEventV8Internal::shiftKeyAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void initTouchEventMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "initTouchEvent", "TouchEvent", info.Holder(), info.GetIsolate());
TouchEvent* impl = V8TouchEvent::toImpl(info.Holder());
TouchList* touches;
TouchList* targetTouches;
TouchList* changedTouches;
V8StringResource<> type;
DOMWindow* view;
int unused1;
int unused2;
int unused3;
int unused4;
bool ctrlKey;
bool altKey;
bool shiftKey;
bool metaKey;
{
touches = V8TouchList::toImplWithTypeCheck(info.GetIsolate(), info[0]);
targetTouches = V8TouchList::toImplWithTypeCheck(info.GetIsolate(), info[1]);
changedTouches = V8TouchList::toImplWithTypeCheck(info.GetIsolate(), info[2]);
type = info[3];
if (!type.prepare())
return;
view = toDOMWindow(info.GetIsolate(), info[4]);
unused1 = toInt32(info.GetIsolate(), info[5], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
unused2 = toInt32(info.GetIsolate(), info[6], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
unused3 = toInt32(info.GetIsolate(), info[7], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
unused4 = toInt32(info.GetIsolate(), info[8], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
ctrlKey = toBoolean(info.GetIsolate(), info[9], exceptionState);
if (exceptionState.throwIfNeeded())
return;
altKey = toBoolean(info.GetIsolate(), info[10], exceptionState);
if (exceptionState.throwIfNeeded())
return;
shiftKey = toBoolean(info.GetIsolate(), info[11], exceptionState);
if (exceptionState.throwIfNeeded())
return;
metaKey = toBoolean(info.GetIsolate(), info[12], exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
impl->initTouchEvent(scriptState, touches, targetTouches, changedTouches, type, view, unused1, unused2, unused3, unused4, ctrlKey, altKey, shiftKey, metaKey);
}
static void initTouchEventMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
UseCounter::countIfNotPrivateScript(info.GetIsolate(), callingExecutionContext(info.GetIsolate()), UseCounter::V8TouchEvent_InitTouchEvent_Method);
TouchEventV8Internal::initTouchEventMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
} // namespace TouchEventV8Internal
static const V8DOMConfiguration::AccessorConfiguration V8TouchEventAccessors[] = {
{"touches", TouchEventV8Internal::touchesAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"targetTouches", TouchEventV8Internal::targetTouchesAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"changedTouches", TouchEventV8Internal::changedTouchesAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"altKey", TouchEventV8Internal::altKeyAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"metaKey", TouchEventV8Internal::metaKeyAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"ctrlKey", TouchEventV8Internal::ctrlKeyAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"shiftKey", TouchEventV8Internal::shiftKeyAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
};
static const V8DOMConfiguration::MethodConfiguration V8TouchEventMethods[] = {
{"initTouchEvent", TouchEventV8Internal::initTouchEventMethodCallback, 0, 0, V8DOMConfiguration::ExposedToAllScripts},
};
static void installV8TouchEventTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "TouchEvent", V8UIEvent::domTemplate(isolate), V8TouchEvent::internalFieldCount,
0, 0,
V8TouchEventAccessors, WTF_ARRAY_LENGTH(V8TouchEventAccessors),
V8TouchEventMethods, WTF_ARRAY_LENGTH(V8TouchEventMethods));
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Local<v8::FunctionTemplate> V8TouchEvent::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8TouchEventTemplate);
}
bool V8TouchEvent::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8TouchEvent::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
TouchEvent* V8TouchEvent::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}
void V8TouchEvent::refObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<TouchEvent>()->ref();
#endif
}
void V8TouchEvent::derefObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<TouchEvent>()->deref();
#endif
}
} // namespace blink
| 14,056 | 4,641 |
////////////////////////////////////////////////////////////////////////////
//
//
// Project : VideoNet Ver. 1.0.
// Description : Video Conferencing over the LAN.
// Author : Vladiimir Novick ( v_novick@yahoo.com )
// Date : 17/12/2005
//
// I have converted origional fast h.263 encoder library from C to C++
// so that it can be integrated into any windows application easily.
// I have removed some of unnecessary codes/files from the
// fast h263 library.Also moved definitions and declarations
// in their proper .h and .cpp files.
//
// File description :
// Name : countbit.cpp
//
//
/////////////////////////////////////////////////////////////////////////////
/*************************************************
* libr263: fast H.263 encoder library
*
* Copyright (C) 1996, Roalt Aalmoes, Twente University
* SPA multimedia group
*
* Based on Telenor TMN 1.6 encoder (Copyright (C) 1995, Telenor R&D)
* created by Karl Lillevold
*
* Author encoder: Roalt Aalmoes, <aalmoes@huygens.nl>
*
* Date: 31-07-96
**************************************************/
/**********************************************************************
*
* Name: CountBitsMB
* Description: counts bits used for MB info
*
* Input: Mode, COD, CBP, Picture and Bits structures
* Returns:
* Side effects:
*
* Date: 941129 Author: Karl.Lillevold@nta.no
*
***********************************************************************/
#include "stdafx.h"
#include "countbit.h"
void CountBitsMB(int Mode, int COD, int CBP, int CBPB, Pict *pic, Bits *bits)
{
extern EHUFF *vlc_cbpy, *vlc_cbpcm, *vlc_cbpcm_intra;
int cbpy, cbpcm, length;
/* COD */
if (Global::trace) {
fprintf(Global::tf,"MB-nr: %d",pic->MB);
if (pic->picture_coding_type == PCT_INTER)
fprintf(Global::tf," COD: %d\n",COD);
}
if (pic->picture_coding_type == PCT_INTER) {
mputv(1,COD);
bits->COD++;
}
if (COD)
return; /* not coded */
/* CBPCM */
cbpcm = Mode | ((CBP&3)<<4);
if (Global::trace) {
fprintf(Global::tf,"CBPCM (CBP=%d) (cbpcm=%d): ",CBP,cbpcm);
}
if (pic->picture_coding_type == PCT_INTRA) {
length = Encode(cbpcm,vlc_cbpcm_intra);
} else {
length = Encode(cbpcm,vlc_cbpcm);
}
bits->CBPCM += length;
/* CBPY */
cbpy = CBP>>2;
if (Mode == MODE_INTRA || Mode == MODE_INTRA_Q) /* Intra */
cbpy = cbpy^15;
if (Global::trace) {
fprintf(Global::tf,"CBPY (CBP=%d) (cbpy=%d): ",CBP,cbpy);
}
length = Encode(cbpy, vlc_cbpy);
bits->CBPY += length;
return;
}
/**********************************************************************
*
* Name: CountBitsSlice
* Description: couonts bits used for slice (GOB) info
*
* Input: slice no., quantizer
*
* Date: 94???? Author: Karl.Lillevold@nta.no
*
***********************************************************************/
int CountBitsSlice(int slice, int quant)
{
int bits = 0;
/* Picture Start Code */
if (Global::trace)
fprintf(Global::tf,"GOB sync (GBSC): ");
mputv(PSC_LENGTH,PSC); /* PSC */
bits += PSC_LENGTH;
/* Group Number */
if (Global::trace)
fprintf(Global::tf,"GN: ");
mputv(5,slice);
bits += 5;
/* GOB Sub Bitstream Indicator */
/* if CPM == 1: read 2 bits GSBI */
/* not supported in this version */
/* GOB Frame ID */
if (Global::trace)
fprintf(Global::tf,"GFID: ");
mputv(2, 0);
/* NB: in error-prone environments this value should change if
PTYPE in picture header changes. In this version of the encoder
PTYPE only changes when PB-frames are used in the following cases:
(i) after the first intra frame
(ii) if the distance between two P-frames is very large
Therefore I haven't implemented this GFID change */
/* GFID is not allowed to change unless PTYPE changes */
bits += 2;
/* Gquant */
if (Global::trace)
fprintf(Global::tf,"GQUANT: ");
mputv(5,quant);
bits += 5;
return bits;
}
/**********************************************************************
*
* Name: CountBitsCoeff
* Description: counts bits used for coeffs
*
* Input: qcoeff, coding mode CBP, bits structure, no. of
* coeffs
*
* Returns: struct with no. of bits used
* Side effects:
*
* Date: 940111 Author: Karl.Lillevold@nta.no
*
***********************************************************************/
void CountBitsCoeff(int *qcoeff, int Mode, int CBP, Bits *bits, int ncoeffs)
{
int i;
if (Mode == MODE_INTRA) {
for (i = 0; i < 4; i++) {
bits->Y += CodeCoeff(Mode, qcoeff,i,ncoeffs);
}
for (i = 4; i < 6; i++) {
bits->C += CodeCoeff(Mode, qcoeff,i,ncoeffs);
}
}
else {
for (i = 0; i < 4; i++) {
if ((i==0 && CBP&32) ||
(i==1 && CBP&16) ||
(i==2 && CBP&8) ||
(i==3 && CBP&4) ||
(i==4 && CBP&2) ||
(i==5 && CBP&1)) {
bits->Y += CodeCoeff(Mode, qcoeff, i, ncoeffs);
}
}
for (i = 4; i < 6; i++) {
if ((i==0 && CBP&32) ||
(i==1 && CBP&16) ||
(i==2 && CBP&8) ||
(i==3 && CBP&4) ||
(i==4 && CBP&2) ||
(i==5 && CBP&1)) {
bits->C += CodeCoeff(Mode, qcoeff, i, ncoeffs);
}
}
}
return;
}
int CodeCoeff(int Mode, int *qcoeff, int block, int ncoeffs)
{
int j, bits;
int prev_run, run, prev_level, level, first;
int prev_ind, ind, prev_s, s, length;
extern EHUFF *vlc_3d;
run = bits = 0;
first = 1;
prev_run = prev_level = prev_ind = level = s = prev_s = ind = 0;
for (j = block*ncoeffs; j< (block + 1)*ncoeffs; j++) {
/* Do this block's DC-coefficient first */
if (!(j%ncoeffs) && (Mode == MODE_INTRA)) {
/* DC coeff */
if (Global::trace) {
fprintf(Global::tf,"DC: ");
}
if (qcoeff[block*ncoeffs] != 128)
mputv(8,qcoeff[block*ncoeffs]);
else
mputv(8,255);
bits += 8;
}
else {
/* AC coeff */
s = 0;
/* Increment run if coeff is zero */
if ((level = qcoeff[j]) == 0) {
run++;
}
else {
/* code run & level and count bits */
if (level < 0) {
s = 1;
level = -level;
}
ind = level | run<<4;
ind = ind | 0<<12; /* Not last coeff */
if (!first) {
/* Encode the previous ind */
if (prev_level < 13 && prev_run < 64) {
length = Encode(prev_ind,vlc_3d);
} else
length = 0;
if (length == 0) { /* Escape coding */
if (Global::trace) {
fprintf(Global::tf,"Escape coding:\n");
}
if (prev_s == 1) {prev_level = (prev_level^0xff)+1;}
Encode(ESCAPE,vlc_3d);
mputv(1,0);
mputv(6,prev_run);
mputv(8,prev_level);
bits += 22;
}
else {
mputv(1,prev_s);
bits += length + 1;
}
}
prev_run = run; prev_s = s;
prev_level = level; prev_ind = ind;
run = first = 0;
}
}
}
/* Encode the last coeff */
if (!first) {
if (Global::trace) {
fprintf(Global::tf,"Last coeff: ");
}
prev_ind = prev_ind | 1<<12; /* last coeff */
if (prev_level < 13 && prev_run < 64) {
length = Encode(prev_ind,vlc_3d);
} else
length = 0;
if (length == 0) { /* Escape coding */
if (Global::trace) {
fprintf(Global::tf,"Escape coding:\n");
}
if (prev_s == 1) {prev_level = (prev_level^0xff)+1;}
Encode(ESCAPE,vlc_3d);
mputv(1,1);
mputv(6,prev_run);
mputv(8,prev_level);
bits += 22;
}
else {
mputv(1,prev_s);
bits += length + 1;
}
}
return bits;
}
/**********************************************************************
*
* Name: FindCBP
* Description: Finds the CBP for a macroblock
*
* Input: qcoeff and mode
*
* Returns: CBP
* Side effects:
*
* Date: 940829 Author: Karl.Lillevold@nta.no
*
***********************************************************************/
int FindCBP(int *qcoeff, int Mode, int ncoeffs)
{
int i,j;
int CBP = 0;
/* IF INTRABLOCK then intra =1 else 0 */
int intra = (Mode == MODE_INTRA);
/* Set CBP for this Macroblock */
for (i = 0; i < 6; i++) {
/* First time i = 0: j = 0 ..64-1 set bit 5 if coeff != 0
Sec. time i = 1; j = 64..128-1 set bit 4 if coeff != 0
*/
/* OPTIMIZE: I think for i can be removed
and only values i=0 must be proessed */
for (j = i*ncoeffs + intra; j < (i+1)*ncoeffs; j++) {
if (qcoeff[j]) {
if (i == 0) {CBP |= 32;}
else if (i == 1) {CBP |= 16;}
else if (i == 2) {CBP |= 8;}
else if (i == 3) {CBP |= 4;}
else if (i == 4) {CBP |= 2;}
else if (i == 5) {CBP |= 1;}
else {
fprintf(stderr,"Error in CBP assignment\n");
exit(-1);
}
break;
}
}
}
return CBP;
}
void CountBitsVectors(MotionVector *MV_ptr, Bits *bits,
int x, int y, int Mode, int newgob, Pict *pic)
{
int y_vec, x_vec;
extern EHUFF *vlc_mv;
int pmv0, pmv1;
int start,stop,block;
MotionVector *MV_xy;
start = 0; stop = 0;
MV_xy = MV_ptr + y*Global::mbc + x;
for (block = start; block <= stop; block++) {
FindPMV(MV_ptr,x,y,&pmv0,&pmv1, block, newgob, 1);
x_vec = (2*(*MV_xy).x + (*MV_xy).x_half) - pmv0;
y_vec = (2*(*MV_xy).y + (*MV_xy).y_half) - pmv1;
if (!Global::long_vectors) {
if (x_vec < -32) x_vec += 64;
else if (x_vec > 31) x_vec -= 64;
if (y_vec < -32) y_vec += 64;
else if (y_vec > 31) y_vec -= 64;
}
else {
if (pmv0 < -31 && x_vec < -63) x_vec += 64;
else if (pmv0 > 32 && x_vec > 63) x_vec -= 64;
if (pmv1 < -31 && y_vec < -63) y_vec += 64;
else if (pmv1 > 32 && y_vec > 63) y_vec -= 64;
}
if (x_vec < 0) x_vec += 64;
if (y_vec < 0) y_vec += 64;
if (Global::trace) {
fprintf(Global::tf,"Vectors:\n");
}
bits->vec += Encode(x_vec,vlc_mv);
bits->vec += Encode(y_vec,vlc_mv);
if (Global::trace) {
if (x_vec > 31) x_vec -= 64;
if (y_vec > 31) y_vec -= 64;
fprintf(Global::tf,"(x,y) = (%d,%d) - ",
(2*(*MV_xy).x + (*MV_xy).x_half),
(2*(*MV_xy).y + (*MV_xy).y_half));
fprintf(Global::tf,"(Px,Py) = (%d,%d)\n", pmv0,pmv1);
fprintf(Global::tf,"(x_diff,y_diff) = (%d,%d)\n",x_vec,y_vec);
}
}
return;
}
void FindPMV(MotionVector *MV_ptr, int x, int y,
int *pmv0, int *pmv1, int block, int newgob, int half_pel)
{
int p1,p2,p3;
int xin1,xin2,xin3;
int yin1,yin2,yin3;
int vec1,vec2,vec3;
int l8,o8,or8;
l8 = o8 = or8 = 0;
vec1 = (l8 ? 2 : 0) ; yin1 = y ; xin1 = x-1;
vec2 = (o8 ? 3 : 0) ; yin2 = y-1; xin2 = x;
vec3 = (or8? 3 : 0) ; yin3 = y-1; xin3 = x+1;
if (half_pel) {
p1 = (x > 0) ?
2*((*(MV_ptr + yin1*Global::mbc + xin1)).x) + (*(MV_ptr+ yin1*Global::mbc + xin1)).x_half : 0;
p2 = (y > 0) ?
2*((*(MV_ptr + yin2*Global::mbc + xin2)).x) + (*(MV_ptr + yin2*Global::mbc + xin2)).x_half : 2*NO_VEC;
if((y > 0) && (x < Global::mbc - 1))
p3 = 2*((*(MV_ptr+yin3*Global::mbc + xin3)).x) + ((*(MV_ptr + yin3*Global::mbc + xin3)).x_half);
else if(x == Global::mbc - 1)
p3 = 0;
else /* y == 0 && x != Global::mbc - 1 */
p3 = 2*NO_VEC;
}
else {
p1 = (x > 0) ?
(2*((*(MV_ptr + yin1*Global::mbc + xin1)).x)) : 0;
p2 = (y > 0) ?
(2*((*(MV_ptr + yin2*Global::mbc + xin2)).x)) : 2*NO_VEC;
if((y > 0) && (x < Global::mbc - 1))
p3 = 2*((*(MV_ptr + yin3*Global::mbc + xin3)).x);
else if(x == Global::mbc - 1)
p3 = 0;
else /* y == 0 && x != Global::mbc - 1 */
p3 = 2*NO_VEC;
}
if (newgob && (block == 0 || block == 1 || block == 2))
p2 = 2*NO_VEC;
if (p2 == 2*NO_VEC) { p2 = p3 = p1; }
*pmv0 = p1+p2+p3 - mmax(p1,mmax(p2,p3)) - mmin(p1,mmin(p2,p3));
if (half_pel) {
p1 = (x > 0) ?
(2*((*(MV_ptr + yin1*Global::mbc + xin1)).y)) + ((*(MV_ptr + yin1*Global::mbc + xin1)).y_half) : 0;
p2 = (y > 0) ?
2*((*(MV_ptr + yin2*Global::mbc + xin2)).y) + ((*(MV_ptr + yin2*Global::mbc + xin2)).y_half) : 2*NO_VEC;
if((y > 0) && (x < Global::mbc - 1))
p3 = 2*((*(MV_ptr + yin3*Global::mbc + xin3)).y) + ((*(MV_ptr + Global::mbc*yin3 + xin3)).y_half);
else if(x == Global::mbc - 1)
p3 = 0;
else /* y == 0 && x != Global::mbc - 1 */
p3 = 2*NO_VEC;
}
else {
p1 = (x > 0) ?
(2*((*(MV_ptr + yin1*Global::mbc + xin1)).y)) : 0;
p2 = (y > 0) ?
(2*((*(MV_ptr + yin2*Global::mbc + xin2)).y)) : 2*NO_VEC;
if((y > 0) && (x < Global::mbc - 1))
p3 = 2*((*(MV_ptr + yin3*Global::mbc + xin3)).y);
else if(x == Global::mbc - 1)
p3 = 0;
else /* y == 0 && x != Global::mbc - 1 */
p3 = 2*NO_VEC;
}
if (newgob && (block == 0 || block == 1 || block == 2))
p2 = 2*NO_VEC;
if (p2 == 2*NO_VEC) { p2 = p3 = p1; }
*pmv1 = p1+p2+p3 - mmax(p1,mmax(p2,p3)) - mmin(p1,mmin(p2,p3));
return;
}
void ZeroBits(Bits *bits)
{
#ifndef MINIMAL_REPORT
bits->Y = 0;
bits->C = 0;
bits->vec = 0;
bits->CBPY = 0;
bits->CBPCM = 0;
bits->MODB = 0;
bits->CBPB = 0;
bits->COD = 0;
bits->DQUANT = 0;
bits->header = 0;
bits->total = 0;
bits->no_inter = 0;
bits->no_inter4v = 0;
bits->no_intra = 0;
#endif
return;
}
void ZeroRes(Results *res)
{
#ifndef MINIMAL_REPORT
res->SNR_l = 0;
res->SNR_Cr = 0;
res->SNR_Cb = 0;
res->QP_mean = 0;
#endif
}
void AddBits(Bits *total, Bits *bits)
{
#ifndef MINIMAL_REPORT
total->Y += bits->Y;
total->C += bits->C;
total->vec += bits->vec;
total->CBPY += bits->CBPY;
total->CBPCM += bits->CBPCM;
total->MODB += bits->MODB;
total->CBPB += bits->CBPB;
total->COD += bits->COD;
total->DQUANT += bits->DQUANT;
total->header += bits->header;
total->total += bits->total;
total->no_inter += bits->no_inter;
total->no_inter4v += bits->no_inter4v;
total->no_intra += bits->no_intra;
#endif
return;
}
void AddRes(Results *total, Results *res, Pict *pic)
{
#ifndef MINIMAL_REPORT
total->SNR_l += res->SNR_l;
total->SNR_Cr += res->SNR_Cr;
total->SNR_Cb += res->SNR_Cb;
total->QP_mean += pic->QP_mean;
#endif
return;
}
void AddBitsPicture(Bits *bits)
{
#ifndef MINIMAL_REPORT
bits->total =
bits->Y +
bits->C +
bits->vec +
bits->CBPY +
bits->CBPCM +
bits->MODB +
bits->CBPB +
bits->COD +
bits->DQUANT +
bits->header ;
#endif
}
void ZeroVec(MotionVector *MV)
{
MV->x = 0;
MV->y = 0;
MV->x_half = 0;
MV->y_half = 0;
return;
}
void MarkVec(MotionVector *MV)
{
MV->x = NO_VEC;
MV->y = NO_VEC;
MV->x_half = 0;
MV->y_half = 0;
return;
}
void CopyVec(MotionVector *MV2, MotionVector *MV1)
{
MV2->x = MV1->x;
MV2->x_half = MV1->x_half;
MV2->y = MV1->y;
MV2->y_half = MV1->y_half;
return;
}
int EqualVec(MotionVector *MV2, MotionVector *MV1)
{
if (MV1->x != MV2->x)
return 0;
if (MV1->y != MV2->y)
return 0;
if (MV1->x_half != MV2->x_half)
return 0;
if (MV1->y_half != MV2->y_half)
return 0;
return 1;
}
/**********************************************************************
*
* Name: CountBitsPicture(Pict *pic)
* Description: counts the number of bits needed for picture
* header
*
* Input: pointer to picture structure
* Returns: number of bits
* Side effects:
*
* Date: 941128 Author:Karl.Lillevold@nta.no
*
***********************************************************************/
int CountBitsPicture(Pict *pic)
{
int bits = 0;
/* Picture start code */
if (Global::trace) {
fprintf(Global::tf,"picture_start_code: ");
}
mputv(PSC_LENGTH,PSC);
bits += PSC_LENGTH;
/* Group number */
if (Global::trace) {
fprintf(Global::tf,"Group number in picture header: ");
}
mputv(5,0);
bits += 5;
/* Time reference */
if (Global::trace) {
fprintf(Global::tf,"Time reference: ");
}
mputv(8,pic->TR);
bits += 8;
/* bit 1 */
if (Global::trace) {
fprintf(Global::tf,"spare: ");
}
pic->spare = 1; /* always 1 to avoid start code emulation */
mputv(1,pic->spare);
bits += 1;
/* bit 2 */
if (Global::trace) {
fprintf(Global::tf,"always zero for distinction with H.261\n");
}
mputv(1,0);
bits += 1;
/* bit 3 */
if (Global::trace) {
fprintf(Global::tf,"split_screen_indicator: ");
}
mputv(1,0); /* no support for split-screen in this software */
bits += 1;
/* bit 4 */
if (Global::trace) {
fprintf(Global::tf,"document_camera_indicator: ");
}
mputv(1,0);
bits += 1;
/* bit 5 */
if (Global::trace) {
fprintf(Global::tf,"freeze_picture_release: ");
}
mputv(1,0);
bits += 1;
/* bit 6-8 */
if (Global::trace) {
fprintf(Global::tf,"source_format: ");
}
mputv(3,pic->source_format);
bits += 3;
/* bit 9 */
if (Global::trace) {
fprintf(Global::tf,"picture_coding_type: ");
}
mputv(1,pic->picture_coding_type);
bits += 1;
/* bit 10 */
if (Global::trace) {
fprintf(Global::tf,"Global::mv_outside_frame: ");
}
mputv(1,pic->unrestricted_mv_mode); /* Unrestricted Motion Vector mode */
bits += 1;
/* bit 11 */
if (Global::trace) {
fprintf(Global::tf,"sac_coding: ");
}
mputv(1,0); /* Syntax-based Arithmetic Coding mode not used*/
bits += 1;
/* bit 12 */
if (Global::trace) {
fprintf(Global::tf,"adv_pred_mode: ");
}
mputv(1,Global::advanced); /* Advanced Prediction mode */
bits += 1;
/* bit 13 */
if (Global::trace) {
fprintf(Global::tf,"PB-coded: "); /* PB-frames mode */
}
mputv(1,pic->PB);
bits += 1;
/* QUANT */
if (Global::trace) {
fprintf(Global::tf,"QUANT: ");
}
mputv(5,pic->QUANT);
bits += 5;
/* Continuous Presence Multipoint (CPM) */
mputv(1,0); /* CPM is not supported in this software */
bits += 1;
/* Picture Sub Bitstream Indicator (PSBI) */
/* if CPM == 1: 2 bits PSBI */
/* not supported */
/* PEI (extra information) */
if (Global::trace) {
fprintf(Global::tf,"PEI: ");
}
/* "Encoders shall not insert PSPARE until specified by the ITU" */
mputv(1,0);
bits += 1;
/* PSPARE */
/* if PEI == 1: 8 bits PSPARE + another PEI bit */
/* not supported */
return bits;
}
| 18,162 | 8,168 |
//
// Copyright (c) 2020 Richard Hodges (hodges.r@gmail.com)
//
// 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)
//
// Official repository: https://github.com/madmongo1/webclient
//
// This project was made possible with the generous support of:
// The C++ Alliance (https://cppalliance.org/)
// Jetbrains (https://www.jetbrains.com/)
//
// Talk to us on Slack (https://cppalliance.org/slack/)
//
// Many thanks to Vinnie Falco for continuous mentoring and support
//
#include "boost/webclient/polyfill/shared_composed_op.hpp"
#include <boost/asio/async_result.hpp>
#include <boost/asio/coroutine.hpp>
#include <boost/asio/executor.hpp>
#include <boost/asio/high_resolution_timer.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/_experimental/test/handler.hpp>
#include <boost/beast/core/bind_handler.hpp>
#include <catch2/catch.hpp>
#include <iostream>
using namespace boost::webclient;
using boost::beast::bind_front_handler;
struct has_error
{
error_code error;
error_code &assign_error(error_code &ec)
{
if (not error.failed() and ec.failed())
error = ec;
return error;
}
};
template < class Derived >
struct has_timeout
{
has_timeout(net::executor e, std::chrono::milliseconds to)
: timer_(e)
, to_(to)
{
}
struct timer_event
{
};
template < class Self >
void start_timeout(Self self)
{
timer_.expires_after(to_);
timer_.async_wait(bind_front_handler(self, timer_event()));
}
void cancel_timeout() { timer_.cancel(); }
template < class Self >
void operator()(Self &self, timer_event, error_code ec)
{
auto &this_ = *static_cast< Derived * >(this);
timeout = true;
if (ec == net::error::operation_aborted)
ec.clear();
else if (ec == error_code())
{
ec = net::error::timed_out;
this_.on_timeout();
}
this_(self, this_.assign_error(ec));
}
bool timeout = false;
net::high_resolution_timer timer_;
net::high_resolution_timer::duration to_;
};
template < class Protocol, class Derived >
struct has_resolver
{
using resolver = typename Protocol::resolver;
using resolver_results = typename resolver::results_type;
has_resolver(net::executor e)
: resolver_(e)
{
}
void cancel_resolver() { resolver_.cancel(); }
template < class Self >
void start_resolving(Self self, std::string const &hostname, std::string const &service)
{
resolver_.async_resolve(hostname, service, self);
}
template < class Self >
void operator()(Self &self, error_code ec, typename resolver::results_type results)
{
auto &this_ = *static_cast< Derived * >(this);
resolved = true;
if (ec == net::error::operation_aborted)
ec.clear();
else if (ec.failed())
this_.cancel_timeout();
else
endpoints = results;
this_(self, this_.assign_error(ec));
}
resolver resolver_;
resolver_results endpoints;
bool resolved = false;
};
template < class Protocol, class Derived >
struct has_multiconnect
{
has_multiconnect() {}
private:
using protocol = Protocol;
using socket_type = typename protocol::socket;
using endpoint_type = typename protocol::endpoint;
using resolver = typename protocol::resolver;
using resolver_results = typename resolver::results_type;
struct socket_id
{
std::size_t sock;
};
public:
void cancel_connects()
{
if (not sockets_canceled)
{
sockets_canceled = true;
for (auto &s : socks)
s.cancel();
}
}
template < class Self >
void operator()(Self &self, socket_id id, error_code ec)
{
auto &this_ = *static_cast< Derived * >(this);
--sockets_remaining;
if (not ec.failed() and not sockets_canceled) // we are first socket to complete
{
this->cancel_connects();
this_.on_socket_connect(std::move(socks[id.sock]));
}
else if (ec == net::error::operation_aborted)
ec.clear();
if (sockets_remaining)
ec.clear();
this_(self, this_.assign_error(ec));
}
template < class Self >
void initiate_connects(Self self, resolver_results const &endpoints)
{
std::transform(endpoints.begin(),
endpoints.end(),
std::back_inserter(socks),
[&](typename resolver_results::value_type const&) { return socket_type(self.get_executor()); });
auto i = std::size_t(0);
for (auto &&epi : endpoints)
{
socks[i].async_connect(epi.endpoint(), boost::beast::bind_front_handler(self, socket_id { i }));
++i;
}
sockets_remaining = i;
}
std::vector< socket_type > socks;
std::size_t sockets_remaining = 0;
bool sockets_canceled = false;
};
template < class Socket >
struct mass_connect_op
: net::coroutine
, has_error
, has_timeout< mass_connect_op< Socket > >
, has_resolver< typename Socket::protocol_type, mass_connect_op< Socket > >
, has_multiconnect< typename Socket::protocol_type, mass_connect_op< Socket > >
{
using protocol = typename Socket::protocol_type;
using socket_type = typename protocol::socket;
using endpoint_type = typename protocol::endpoint;
using resolver = typename protocol::resolver;
mass_connect_op(Socket &sock, std::string hostname, std::string port, std::chrono::milliseconds timeout)
: net::coroutine()
, has_error()
, has_timeout< mass_connect_op< Socket > >(sock.get_executor(), timeout)
, has_resolver< protocol, mass_connect_op< Socket > >(sock.get_executor())
, has_multiconnect< protocol, mass_connect_op< Socket > >()
, sock_(sock)
, hostname_(std::move(hostname))
, port_(std::move(port))
{
}
using has_timeout< mass_connect_op< Socket > >:: operator();
using has_resolver< protocol, mass_connect_op< Socket > >:: operator();
using has_multiconnect< protocol, mass_connect_op< Socket > >::operator();
void on_timeout()
{
this->cancel_resolver();
this->cancel_connects();
}
void on_resolved() { this->cancel_timeout(); }
void on_socket_connect(Socket s)
{
this->cancel_timeout();
sock_ = std::move(s);
}
template < class Self >
void operator()(Self &self, error_code ec = {})
{
using polyfill::share;
#include <boost/asio/yield.hpp>
reenter(this) for (;;)
{
// transform this coroutine into a shared coroutine
yield share(self);
// start the timer and a resolve operation
yield
{
this->start_timeout(share(self));
this->start_resolving(share(self), hostname_, port_);
}
// wait for the resolve to complete one way or another
while (not this->resolved)
yield;
// if we have a failure, complete...
if (ec.failed())
{
// ... after ensuring that the timer completion handler has been invoked
while (not this->timeout)
yield;
}
else
{
// otherwise, simulatenously connect to all endpoints
yield this->initiate_connects(share(self), this->endpoints);
// yield until all connect completion handlers have been invoked
while (this->sockets_remaining)
yield;
// and yield until the timer completion handler has been invoked
while (not this->timeout)
yield;
}
// return the result of the connect
return self.complete(ec);
}
#include <boost/asio/unyield.hpp>
}
Socket & sock_;
std::string hostname_, port_;
};
template < class Socket, class CompletionToken >
auto async_mass_connect(Socket & sock,
std::string host,
std::string port,
std::chrono::milliseconds timeout,
CompletionToken && token)
-> BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void(error_code))
{
return net::async_compose< CompletionToken, void(error_code) >(
mass_connect_op< Socket >(sock, std::move(host), std::move(port), timeout), token, sock);
}
TEST_CASE("boost::webclient::polyfill::shared_composed_op")
{
net::io_context ioc;
auto s = net::ip::tcp::socket(ioc);
async_mass_connect(s, "www.example.com", "http", std::chrono::seconds(10), [&](error_code ec) {
std::cout << ec.message() << std::endl;
auto ep = s.remote_endpoint(ec);
std::cout << ep << std::endl;
});
boost::beast::test::run(ioc);
} | 9,310 | 2,798 |
//! Assign nodal connectivity property for bspline elements
template <unsigned Tdim, unsigned Tnfunctions>
void mpm::HexahedronBSplineElement<Tdim, Tnfunctions>::
initialise_bspline_connectivity_properties(
const Eigen::MatrixXd& nodal_coordinates,
const std::vector<std::vector<unsigned>>& nodal_properties) {
assert(nodal_coordinates.rows() == nodal_properties.size());
this->nconnectivity_ = nodal_coordinates.rows();
this->nodal_coordinates_ = nodal_coordinates;
this->node_type_ = nodal_properties;
//! Uniform spacing length in 3D
this->spacing_length_ =
std::abs(nodal_coordinates(1, 0) - nodal_coordinates(0, 0));
}
//! Return shape functions of a Hexahedron BSpline Element at a given
//! local coordinate
template <unsigned Tdim, unsigned Tpolynomial>
inline Eigen::VectorXd
mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::shapefn(
const Eigen::Matrix<double, Tdim, 1>& xi,
const Eigen::Matrix<double, Tdim, 1>& particle_size,
const Eigen::Matrix<double, Tdim, 1>& deformation_gradient) const {
//! To store shape functions
Eigen::VectorXd shapefn =
Eigen::VectorXd::Constant(this->nconnectivity_, 1.0);
if (this->nconnectivity_ == 8)
return mpm::HexahedronElement<Tdim, 8>::shapefn(xi, particle_size,
deformation_gradient);
try {
//! Convert local coordinates to real coordinates
Eigen::Matrix<double, Tdim, 1> pcoord;
pcoord.setZero();
auto local_shapefn =
this->shapefn_local(xi, particle_size, deformation_gradient);
for (unsigned i = 0; i < local_shapefn.size(); ++i)
pcoord.noalias() +=
local_shapefn(i) * nodal_coordinates_.row(i).transpose();
//! Compute shape function following a multiplicative rule
for (unsigned n = 0; n < this->nconnectivity_; ++n) {
//! Loop over dimension
for (unsigned i = 0; i < Tdim; ++i) {
double N = this->kernel(pcoord[i], nodal_coordinates_.row(n)[i],
this->node_type_[n][i], Tpolynomial);
switch (this->node_type_[n][i]) {
case 1:
N += this->kernel(pcoord[i], nodal_coordinates_.row(n)[i], 5,
Tpolynomial);
break;
case 4:
N += this->kernel(pcoord[i], nodal_coordinates_.row(n)[i], 6,
Tpolynomial);
break;
}
shapefn[n] = shapefn[n] * N;
}
}
} catch (std::exception& exception) {
console_->error("{} #{}: {}\n", __FILE__, __LINE__, exception.what());
return shapefn;
}
return shapefn;
}
//! Return gradient of shape functions of a Hexahedron BSpline Element at a
//! given local coordinate
template <unsigned Tdim, unsigned Tpolynomial>
inline Eigen::MatrixXd
mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::grad_shapefn(
const Eigen::Matrix<double, Tdim, 1>& xi,
const Eigen::Matrix<double, Tdim, 1>& particle_size,
const Eigen::Matrix<double, Tdim, 1>& deformation_gradient) const {
//! To store grad shape functions
Eigen::MatrixXd grad_shapefn(this->nconnectivity_, Tdim);
if (this->nconnectivity_ == 8)
return mpm::HexahedronElement<Tdim, 8>::grad_shapefn(xi, particle_size,
deformation_gradient);
try {
//! Convert local coordinates to real coordinates
Eigen::Matrix<double, Tdim, 1> pcoord;
pcoord.setZero();
auto local_shapefn =
this->shapefn_local(xi, particle_size, deformation_gradient);
for (unsigned i = 0; i < local_shapefn.size(); ++i)
pcoord.noalias() +=
local_shapefn(i) * nodal_coordinates_.row(i).transpose();
//! Compute the shape function gradient following a multiplicative rule
for (unsigned n = 0; n < this->nconnectivity_; ++n)
//! Loop over dimension
for (unsigned i = 0; i < Tdim; ++i) {
double dN_dx = this->gradient(pcoord[i], nodal_coordinates_.row(n)[i],
(this->node_type_[n])[i], Tpolynomial);
switch (this->node_type_[n][i]) {
case 1:
dN_dx += this->gradient(pcoord[i], nodal_coordinates_.row(n)[i], 5,
Tpolynomial);
break;
case 4:
dN_dx += this->gradient(pcoord[i], nodal_coordinates_.row(n)[i], 6,
Tpolynomial);
break;
}
for (unsigned j = 0; j < Tdim; ++j) {
if (j != i) {
double N = this->kernel(pcoord[j], nodal_coordinates_.row(n)[j],
this->node_type_[n][j], Tpolynomial);
switch (this->node_type_[n][j]) {
case 1:
N += this->kernel(pcoord[j], nodal_coordinates_.row(n)[j], 5,
Tpolynomial);
break;
case 4:
N += this->kernel(pcoord[j], nodal_coordinates_.row(n)[j], 6,
Tpolynomial);
break;
}
dN_dx = dN_dx * N;
}
}
grad_shapefn(n, i) = dN_dx;
}
} catch (std::exception& exception) {
console_->error("{} #{}: {}\n", __FILE__, __LINE__, exception.what());
return grad_shapefn;
}
return grad_shapefn;
}
//! Return local shape functions of a BSpline Hexahedron Element at a given
//! Return local shape functions of a Hexahedron Element at a given local
//! coordinate, with particle size and deformation gradient
template <unsigned Tdim, unsigned Tpolynomial>
inline Eigen::VectorXd
mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::shapefn_local(
const Eigen::Matrix<double, Tdim, 1>& xi,
const Eigen::Matrix<double, Tdim, 1>& particle_size,
const Eigen::Matrix<double, Tdim, 1>& deformation_gradient) const {
return mpm::HexahedronElement<Tdim, 8>::shapefn(xi, particle_size,
deformation_gradient);
}
//! Compute Jacobian
template <unsigned Tdim, unsigned Tpolynomial>
inline Eigen::Matrix<double, Tdim, Tdim>
mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::jacobian(
const Eigen::Matrix<double, 3, 1>& xi,
const Eigen::MatrixXd& nodal_coordinates,
const Eigen::Matrix<double, 3, 1>& particle_size,
const Eigen::Matrix<double, 3, 1>& deformation_gradient) const {
// Get gradient shape functions
const Eigen::MatrixXd grad_shapefn =
this->grad_shapefn(xi, particle_size, deformation_gradient);
try {
// Check if dimensions are correct
if ((grad_shapefn.rows() != nodal_coordinates.rows()) ||
(xi.size() != nodal_coordinates.cols()))
throw std::runtime_error(
"Jacobian calculation: Incorrect dimension of xi and "
"nodal_coordinates");
} catch (std::exception& exception) {
console_->error("{} #{}: {}\n", __FILE__, __LINE__, exception.what());
return Eigen::Matrix<double, Tdim, Tdim>::Zero();
}
// Jacobian
return (grad_shapefn.transpose() * nodal_coordinates);
}
//! Compute dn_dx
template <unsigned Tdim, unsigned Tpolynomial>
inline Eigen::MatrixXd mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::dn_dx(
const VectorDim& xi, const Eigen::MatrixXd& nodal_coordinates,
const VectorDim& particle_size,
const VectorDim& deformation_gradient) const {
// Get gradient shape functions
return this->grad_shapefn(xi, particle_size, deformation_gradient);
}
//! Compute Jacobian local with particle size and deformation gradient
template <unsigned Tdim, unsigned Tpolynomial>
inline Eigen::Matrix<double, Tdim, Tdim>
mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::jacobian_local(
const Eigen::Matrix<double, 3, 1>& xi,
const Eigen::MatrixXd& nodal_coordinates,
const Eigen::Matrix<double, 3, 1>& particle_size,
const Eigen::Matrix<double, 3, 1>& deformation_gradient) const {
// Jacobian dx_i/dxi_j
return this->jacobian(xi, nodal_coordinates, particle_size,
deformation_gradient);
}
//! Compute Bmatrix
template <unsigned Tdim, unsigned Tpolynomial>
inline std::vector<Eigen::MatrixXd>
mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::bmatrix(
const VectorDim& xi, const Eigen::MatrixXd& nodal_coordinates,
const VectorDim& particle_size,
const VectorDim& deformation_gradient) const {
// Get gradient shape functions
Eigen::MatrixXd grad_sf =
this->grad_shapefn(xi, particle_size, deformation_gradient);
// B-Matrix
std::vector<Eigen::MatrixXd> bmatrix;
bmatrix.reserve(this->nconnectivity_);
try {
// Check if matrices dimensions are correct
if ((grad_sf.rows() != nodal_coordinates.rows()) ||
(xi.rows() != nodal_coordinates.cols()))
throw std::runtime_error(
"BMatrix - Jacobian calculation: Incorrect dimension of xi and "
"nodal_coordinates");
} catch (std::exception& exception) {
console_->error("{} #{}: {}\n", __FILE__, __LINE__, exception.what());
return bmatrix;
}
// Jacobian dx_i/dxi_j
Eigen::Matrix<double, Tdim, Tdim> jacobian =
(grad_sf.transpose() * nodal_coordinates);
// Gradient shapefn of the cell
// dN/dx = [J]^-1 * dN/dxi
Eigen::MatrixXd grad_shapefn = grad_sf * (jacobian.inverse()).transpose();
for (unsigned i = 0; i < this->nconnectivity_; ++i) {
// clang-format off
Eigen::Matrix<double, 6, Tdim> bi;
bi(0, 0) = grad_shapefn(i, 0); bi(0, 1) = 0.; bi(0, 2) = 0.;
bi(1, 0) = 0.; bi(1, 1) = grad_shapefn(i, 1); bi(1, 2) = 0.;
bi(2, 0) = 0.; bi(2, 1) = 0.; bi(2, 2) = grad_shapefn(i, 2);
bi(3, 0) = grad_shapefn(i, 1); bi(3, 1) = grad_shapefn(i, 0); bi(3, 2) = 0.;
bi(4, 0) = 0.; bi(4, 1) = grad_shapefn(i, 2); bi(4, 2) = grad_shapefn(i, 1);
bi(5, 0) = grad_shapefn(i, 2); bi(5, 1) = 0.; bi(5, 2) = grad_shapefn(i, 0);
// clang-format on
bmatrix.push_back(bi);
}
return bmatrix;
}
//! Compute B-Spline Basis Function using the recursive De Boor's algorithm
//! for single direction
template <unsigned Tdim, unsigned Tpolynomial>
double mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::kernel(
double point_coord, double nodal_coord, unsigned node_type,
unsigned poly_order, unsigned index) const {
double value = 0.0;
//! Compute knot coordinate
Eigen::VectorXd knot_vector = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(
(this->knot(node_type)).data(), (this->knot(node_type)).size());
const Eigen::VectorXd one =
Eigen::VectorXd::Constant(knot_vector.size(), 1.0);
const Eigen::VectorXd knot_coord =
nodal_coord * one + spacing_length_ * knot_vector;
if (poly_order == 0) {
if (point_coord >= knot_coord[index] &&
point_coord < knot_coord[index + 1]) {
value = 1.0;
} else {
value = 0.0;
}
} else {
const double den_a = (knot_coord[index + poly_order] - knot_coord[index]);
double a = (point_coord - knot_coord(index)) / den_a;
if (den_a < std::numeric_limits<double>::epsilon()) a = 0;
const double den_b =
(knot_coord[index + poly_order + 1] - knot_coord[index + 1]);
double b = (knot_coord[index + poly_order + 1] - point_coord) / den_b;
if (den_b < std::numeric_limits<double>::epsilon()) b = 0;
value = a * this->kernel(point_coord, nodal_coord, node_type,
poly_order - 1, index) +
b * this->kernel(point_coord, nodal_coord, node_type,
poly_order - 1, index + 1);
}
return value;
}
//! Compute B-Spline Basis Function Gradient using the recursive De Boor's
//! algorithm for single direction
template <unsigned Tdim, unsigned Tpolynomial>
double mpm::HexahedronBSplineElement<Tdim, Tpolynomial>::gradient(
double point_coord, double nodal_coord, unsigned node_type,
unsigned poly_order, unsigned index) const {
double value = 0;
Eigen::VectorXd knot_vector = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(
(this->knot(node_type)).data(), (this->knot(node_type)).size());
const Eigen::VectorXd one =
Eigen::VectorXd::Constant(knot_vector.size(), 1.0);
const Eigen::VectorXd knot_coord =
nodal_coord * one + spacing_length_ * knot_vector;
const double den_a = (knot_coord[index + poly_order] - knot_coord[index]);
double a = poly_order / den_a;
if (den_a < std::numeric_limits<double>::epsilon()) a = 0;
const double den_b =
(knot_coord[index + poly_order + 1] - knot_coord[index + 1]);
double b = poly_order / den_b;
if (den_b < std::numeric_limits<double>::epsilon()) b = 0;
value = a * this->kernel(point_coord, nodal_coord, node_type, poly_order - 1,
index) -
b * this->kernel(point_coord, nodal_coord, node_type, poly_order - 1,
index + 1);
return value;
}
| 13,036 | 4,456 |
#ifndef GODOT_CPP_SKELETON2D_HPP
#define GODOT_CPP_SKELETON2D_HPP
#include <gdnative_api_struct.gen.h>
#include <stdint.h>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include "Node2D.hpp"
namespace godot {
class Bone2D;
class Skeleton2D : public Node2D {
struct ___method_bindings {
godot_method_bind *mb__update_bone_setup;
godot_method_bind *mb__update_transform;
godot_method_bind *mb_get_bone;
godot_method_bind *mb_get_bone_count;
godot_method_bind *mb_get_skeleton;
};
static ___method_bindings ___mb;
static void *_detail_class_tag;
public:
static void ___init_method_bindings();
inline static size_t ___get_id() { return (size_t)_detail_class_tag; }
static inline const char *___get_class_name() { return (const char *) "Skeleton2D"; }
static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }
// enums
// constants
static Skeleton2D *_new();
// methods
void _update_bone_setup();
void _update_transform();
Bone2D *get_bone(const int64_t idx);
int64_t get_bone_count() const;
RID get_skeleton() const;
};
}
#endif | 1,262 | 515 |
class SparseMultiGRAPH
{
int Vcnt, Ecnt; bool digraph;
struct node
{
int v; node* next;
node(int x, node* t){ v = x; next = t; }
};
typedef node* link;
vector<link> adj;
public:
SparseMultiGRAPH(int V, bool digraph = false):
adj(V), Vcnt(V), Ecnt(0), digraph(digraph)
{ adj.assign(V,0);}
int V() const { return Vcnt; }
int E() const { return Ecnt; }
bool directed() const { return digraph; }
void insert(Edge e)
{
int v = e.v , w = e.w;
adj[v] = new node(w, adj[v]);
if(!digraph) adj[w] = new node(v,adj[w]);
}
void remove(Edge e);
bool edge(int v,int w) const;
class adjIterator;
friend class adjIterator;
};
class SparseMultiGRAPH::adjIterator
{
const SparseMultiGRAPH &G;
int v;
link t;
public:
adjIterator(const SparseMultiGRAPH &G, int v):
G(G), v(v) { t= 0; }
int begin()
{ t= G.adj[v]; return t? t->v : -1;}
int nxt()
{if(t) t = t->next; return t ? t->v : -1;}
bool end()
{ return t == 0; }
};
| 1,104 | 425 |
#include <QtWidgets/QApplication>
#include "cellcounter.h"
#include<QMessageBox>
#include<QIcon>
class CC: public QApplication
{
public:
CC(int argc, char **argv): QApplication(argc, argv)
{
}
bool notify(QObject *rec, QEvent *ev)
{
try{
return QApplication::notify(rec, ev);
}
catch (...)
{
QMessageBox::warning(NULL,
tr("Error"),
tr("Error occurred\n")+
tr("Please restart application."),
QMessageBox::Ok,NULL);
return false;
}
}
};
int main(int argc, char *argv[])
{
CC a(argc, argv);
//settings
CC::addLibraryPath(QCoreApplication::applicationDirPath());
CC::setApplicationName("CellCounter");
CC::setOrganizationDomain("cellcounter.org");
CC::setOrganizationName("Laboratory for Tumor Pathology,School of Life Sciences, University of Science and Technology of China");
CellCounter w;
w.showMaximized();
return a.exec();
}
| 1,089 | 315 |
// Copyright 2020 Krasilnikov Alexey
#include "../../../modules/task_1/krasilnikov_a_count_sentences/count_sentences.h"
#include <mpi.h>
#include <ctime>
#include <random>
#include <string>
std::string getRandomString(const size_t size) {
std::mt19937 generator;
std::string str(size, '_');
for (auto &symbol : str) {
if (generator() % 10 == 0) {
symbol = '.';
} else {
symbol = static_cast<char>(generator() % 128);
}
}
return str;
}
uint32_t getCountSentencesSequential(const std::string& str) {
uint32_t count_sentences = 0;
for (const auto symbol : str) {
if (symbol == '.') {
++count_sentences;
}
}
return count_sentences;
}
uint32_t getCountSentencesParallel(const std::string& str, const size_t size_str) {
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
uint32_t total_count = 0;
std::string local_str;
const uint32_t delta = size_str / size;
const uint32_t remain = size_str % size;
if (rank == 0) {
for (size_t process = 0; process < remain; ++process) {
MPI_Send(&str[0] + process * (delta + 1), delta + 1, MPI_CHAR, process + 1, 0, MPI_COMM_WORLD);
}
for (size_t process = remain; static_cast<int>(process) < size - 1; ++process) {
MPI_Send(&str[0] + process * delta + remain, delta, MPI_CHAR, process + 1, 0, MPI_COMM_WORLD);
}
local_str = str.substr((size - 1) * delta + remain);
} else {
MPI_Status status;
if (rank <= static_cast<int>(remain)) {
local_str.resize(delta + 1);
MPI_Recv(&local_str[0], delta + 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &status);
} else {
local_str.resize(delta);
MPI_Recv(&local_str[0], delta, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &status);
}
}
uint32_t local_count = getCountSentencesSequential(local_str);
MPI_Reduce(&local_count, &total_count, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
return total_count;
}
| 1,947 | 796 |
//============================================================================
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
//============================================================================
#ifndef CHANGENOTIFYDIALOG_HPP_
#define CHANGENOTIFYDIALOG_HPP_
#include <QtGlobal>
#include <QDialog>
#include <QLinearGradient>
#include <QSettings>
#include <QToolButton>
#include <QWidget>
#include "ui_ChangeNotifyDialog.h"
#include "ui_ChangeNotifyDialogWidget.h"
#include "VInfo.hpp"
class ChangeNotify;
class VProperty;
class QAbstractButton;
class QButtonGroup;
class QHBoxLayout;
class QLabel;
class ChangeNotifyDialogButton : public QToolButton
{
Q_OBJECT
public:
explicit ChangeNotifyDialogButton(QWidget* parent=nullptr);
void setNotifier(ChangeNotify*);
void updateSettings();
public Q_SLOTS:
void slotAppend();
void slotRemoveRow(int);
void slotReset();
protected:
ChangeNotify* notifier_{nullptr};
};
class ChangeNotifyDialogWidget : public QWidget, protected Ui::ChangeNotifyDialogWidget
{
Q_OBJECT
public:
explicit ChangeNotifyDialogWidget(QWidget* parent=nullptr);
~ChangeNotifyDialogWidget() override = default;
void init(ChangeNotify*);
void updateSettings();
ChangeNotify* notifier() const {return notifier_;}
void writeSettings(QSettings& settings);
void readSettings(const QSettings& settings);
protected Q_SLOTS:
void slotSelectItem(const QModelIndex&);
void slotDoubleClickItem(const QModelIndex&);
Q_SIGNALS:
void selectionChanged(VInfo_ptr);
protected:
ChangeNotify* notifier_{nullptr};
};
class ChangeNotifyDialog : public QDialog, protected Ui::ChangeNotifyDialog
{
Q_OBJECT
public:
explicit ChangeNotifyDialog(QWidget *parent=nullptr);
~ChangeNotifyDialog() override;
void add(ChangeNotify*);
void setCurrent(ChangeNotify*);
void setEnabled(ChangeNotify*,bool b);
void updateSettings(ChangeNotify*);
public Q_SLOTS:
void on_closePb__clicked(bool b);
void on_clearPb__clicked(bool b);
protected Q_SLOTS:
void slotSelectionChanged(VInfo_ptr);
void slotOptions();
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
void slotButtonToggled(QAbstractButton*, bool);
#else
void slotButtonToggled(int,bool);
#endif
protected:
ChangeNotify* indexToNtf(int idx);
int ntfToIndex(ChangeNotify* ntf);
void closeEvent(QCloseEvent*) override;
void clearCurrentData();
void writeSettings();
void readSettings();
void readNtfWidgetSettings(int tabIndex);
QList<ChangeNotifyDialogWidget*> ntfWidgets_;
QList<ChangeNotifyDialogButton*> ntfButtons_;
QButtonGroup* buttonGroup_;
bool ignoreCurrentChange_{false};
QLinearGradient grad_;
QHBoxLayout* buttonHb_;
VProperty* switchWsProp_{nullptr};
};
#endif
| 3,106 | 989 |
TEST(Color, base) {
// Testing same operations on colors.
// ==================================
// Colors are red, green, blue tuples.
Color c(-0.5, 0.4, 1.7);
EXPECT_EQ(c.red(), -0.5f);
EXPECT_EQ(c.green(), 0.4f);
EXPECT_EQ(c.blue(), 1.7f);
// Adding colors.
Color c1(0.9, 0.6, 0.75);
Color c2(0.7, 0.1, 0.25);
EXPECT_EQ(c1 + c2, Color(1.6, 0.7, 1.0));
// Subtracting colors.
c1 = Color(0.9, 0.6, 0.75);
c2 = Color(0.7, 0.1, 0.25);
EXPECT_EQ(c1 - c2, Color(0.2, 0.5, 0.5));
// Multiplying a color by a scalar.
c = Color(0.2, 0.3, 0.4);
EXPECT_EQ(c * 2.0, Color(0.4, 0.6, 0.8));
EXPECT_EQ(2.0 * c, Color(0.4, 0.6, 0.8));
// Dividing a color by a scalar.
c = Color(0.4, 0.6, 0.8);
EXPECT_EQ(c / 2.0, Color(0.2, 0.3, 0.4));
// Multiplying colors.
c1 = Color(1.0, 0.2, 0.4);
c2 = Color(0.9, 1.0, 0.1);
EXPECT_EQ(c1 * c2, Color(0.9, 0.2, 0.04));
// Multiplying colors/Hadamard product/Schur product
}
TEST(Color, output) {
Color c1(0.9, 0.6, 0.75);
EXPECT_EQ(std::string(c1),
"Color { red:0.9, green:0.6, blue:0.75, alpha:1}");
std::ostringstream string_stream;
string_stream << c1;
EXPECT_EQ(string_stream.str(),
"Color { red:0.9, green:0.6, blue:0.75, alpha:1}");
string_stream.str("");
Color c2(0.7, 0.1, 0.25, 0.5);
EXPECT_EQ(std::string(c2),
"Color { red:0.7, green:0.1, blue:0.25, alpha:0.5}");
string_stream << c2;
EXPECT_EQ(string_stream.str(),
"Color { red:0.7, green:0.1, blue:0.25, alpha:0.5}");
}
TEST(Color, helpers) {
EXPECT_EQ(Color::BLACK(), Color(0, 0, 0));
EXPECT_EQ(Color::WHITE(), Color(1, 1, 1));
EXPECT_EQ(Color::RED(), Color(1, 0, 0));
EXPECT_EQ(Color::GREEN(), Color(0, 1, 0));
EXPECT_EQ(Color::BLUE(), Color(0, 0, 1));
}
| 1,784 | 938 |
// 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/chromeos/login/help_app_launcher.h"
#include <string>
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "content/public/browser/browser_thread.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
using content::BrowserThread;
namespace {
const char kHelpAppFormat[] =
"chrome-extension://honijodknafkokifofgiaalefdiedpko/oobe.html?id=%d";
} // namespace
namespace chromeos {
///////////////////////////////////////////////////////////////////////////////
// HelpApp, public:
HelpAppLauncher::HelpAppLauncher(gfx::NativeWindow parent_window)
: parent_window_(parent_window) {
}
void HelpAppLauncher::ShowHelpTopic(HelpTopic help_topic_id) {
Profile* profile = ProfileManager::GetDefaultProfile();
ExtensionService* service = profile->GetExtensionService();
DCHECK(service);
if (!service)
return;
GURL url(base::StringPrintf(kHelpAppFormat,
static_cast<int>(help_topic_id)));
// HelpApp component extension presents only in official builds so we can
// show help only when the extensions is installed.
if (service->extensions()->GetByID(url.host()))
ShowHelpTopicDialog(GURL(url));
}
///////////////////////////////////////////////////////////////////////////////
// HelpApp, protected:
HelpAppLauncher::~HelpAppLauncher() {}
///////////////////////////////////////////////////////////////////////////////
// HelpApp, private:
void HelpAppLauncher::ShowHelpTopicDialog(const GURL& topic_url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
LoginWebDialog* dialog = new LoginWebDialog(
this,
parent_window_,
l10n_util::GetStringUTF16(IDS_LOGIN_OOBE_HELP_DIALOG_TITLE),
topic_url,
LoginWebDialog::STYLE_BUBBLE);
dialog->Show();
// The dialog object will be deleted on dialog close.
}
} // namespace chromeos
| 2,237 | 687 |
#include "a0_bin_conv.h"
#include "AESL_pkg.h"
using namespace std;
namespace ap_rtl {
void a0_bin_conv::thread_sel_tmp175_fu_26354_p3() {
sel_tmp175_fu_26354_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? old_word_buffer_0_5_18_fu_1550.read(): sel_tmp174_fu_26347_p3.read());
}
void a0_bin_conv::thread_sel_tmp176_fu_26509_p3() {
sel_tmp176_fu_26509_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_2_11_fu_1418.read(): old_word_buffer_0_7_10_fu_1594.read());
}
void a0_bin_conv::thread_sel_tmp177_fu_26516_p3() {
sel_tmp177_fu_26516_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_3_11_fu_1454.read(): sel_tmp176_fu_26509_p3.read());
}
void a0_bin_conv::thread_sel_tmp178_fu_26523_p3() {
sel_tmp178_fu_26523_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_4_12_fu_1490.read(): sel_tmp177_fu_26516_p3.read());
}
void a0_bin_conv::thread_sel_tmp179_fu_26530_p3() {
sel_tmp179_fu_26530_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_0_5_11_fu_1522.read(): sel_tmp178_fu_26523_p3.read());
}
void a0_bin_conv::thread_sel_tmp180_fu_32499_p3() {
sel_tmp180_fu_32499_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_2_29_reg_53917.read(): old_word_buffer_0_7_43_reg_54213.read());
}
void a0_bin_conv::thread_sel_tmp181_fu_32504_p3() {
sel_tmp181_fu_32504_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_3_29_reg_53958.read(): sel_tmp180_fu_32499_p3.read());
}
void a0_bin_conv::thread_sel_tmp182_fu_32510_p3() {
sel_tmp182_fu_32510_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_4_30_reg_54009.read(): sel_tmp181_fu_32504_p3.read());
}
void a0_bin_conv::thread_sel_tmp183_fu_32516_p3() {
sel_tmp183_fu_32516_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_0_5_29_reg_54058.read(): sel_tmp182_fu_32510_p3.read());
}
void a0_bin_conv::thread_sel_tmp184_fu_26544_p3() {
sel_tmp184_fu_26544_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_2_13_fu_1426.read(): old_word_buffer_0_7_12_fu_1602.read());
}
void a0_bin_conv::thread_sel_tmp185_fu_26551_p3() {
sel_tmp185_fu_26551_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_3_13_fu_1462.read(): sel_tmp184_fu_26544_p3.read());
}
void a0_bin_conv::thread_sel_tmp186_fu_26558_p3() {
sel_tmp186_fu_26558_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_4_14_fu_1498.read(): sel_tmp185_fu_26551_p3.read());
}
void a0_bin_conv::thread_sel_tmp187_fu_26565_p3() {
sel_tmp187_fu_26565_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_0_5_13_fu_1530.read(): sel_tmp186_fu_26558_p3.read());
}
void a0_bin_conv::thread_sel_tmp188_fu_32528_p3() {
sel_tmp188_fu_32528_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_2_30_reg_53925.read(): old_word_buffer_0_7_45_reg_54237.read());
}
void a0_bin_conv::thread_sel_tmp189_fu_32533_p3() {
sel_tmp189_fu_32533_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_3_30_reg_53968.read(): sel_tmp188_fu_32528_p3.read());
}
void a0_bin_conv::thread_sel_tmp190_fu_32539_p3() {
sel_tmp190_fu_32539_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_4_31_reg_54021.read(): sel_tmp189_fu_32533_p3.read());
}
void a0_bin_conv::thread_sel_tmp191_fu_32545_p3() {
sel_tmp191_fu_32545_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_0_5_30_reg_54072.read(): sel_tmp190_fu_32539_p3.read());
}
void a0_bin_conv::thread_sel_tmp192_fu_26579_p3() {
sel_tmp192_fu_26579_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_2_15_fu_1434.read(): old_word_buffer_0_7_14_fu_1610.read());
}
void a0_bin_conv::thread_sel_tmp193_fu_26586_p3() {
sel_tmp193_fu_26586_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_3_15_fu_1470.read(): sel_tmp192_fu_26579_p3.read());
}
void a0_bin_conv::thread_sel_tmp194_fu_26593_p3() {
sel_tmp194_fu_26593_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_4_16_fu_1506.read(): sel_tmp193_fu_26586_p3.read());
}
void a0_bin_conv::thread_sel_tmp195_fu_26600_p3() {
sel_tmp195_fu_26600_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_0_5_15_fu_1538.read(): sel_tmp194_fu_26593_p3.read());
}
void a0_bin_conv::thread_sel_tmp196_fu_32557_p3() {
sel_tmp196_fu_32557_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_2_31_reg_53933.read(): old_word_buffer_0_7_47_reg_54261.read());
}
void a0_bin_conv::thread_sel_tmp197_fu_32562_p3() {
sel_tmp197_fu_32562_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_3_31_reg_53978.read(): sel_tmp196_fu_32557_p3.read());
}
void a0_bin_conv::thread_sel_tmp198_fu_32568_p3() {
sel_tmp198_fu_32568_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_4_29_reg_53874.read(): sel_tmp197_fu_32562_p3.read());
}
void a0_bin_conv::thread_sel_tmp199_fu_32574_p3() {
sel_tmp199_fu_32574_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_0_5_31_reg_54086.read(): sel_tmp198_fu_32568_p3.read());
}
void a0_bin_conv::thread_sel_tmp200_fu_23702_p3() {
sel_tmp200_fu_23702_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_2_17_fu_1442.read(): old_word_buffer_0_7_16_fu_1618.read());
}
void a0_bin_conv::thread_sel_tmp201_fu_23709_p3() {
sel_tmp201_fu_23709_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_3_17_fu_1478.read(): sel_tmp200_fu_23702_p3.read());
}
void a0_bin_conv::thread_sel_tmp202_fu_23716_p3() {
sel_tmp202_fu_23716_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_4_17_fu_1510.read(): sel_tmp201_fu_23709_p3.read());
}
void a0_bin_conv::thread_sel_tmp203_fu_23723_p3() {
sel_tmp203_fu_23723_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_0_5_17_fu_1546.read(): sel_tmp202_fu_23716_p3.read());
}
void a0_bin_conv::thread_sel_tmp204_fu_32586_p3() {
sel_tmp204_fu_32586_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_2_32_reg_53941.read(): ap_reg_pp0_iter2_old_word_buffer_0_7_49_reg_52193.read());
}
void a0_bin_conv::thread_sel_tmp205_fu_32591_p3() {
sel_tmp205_fu_32591_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_3_32_reg_53988.read(): sel_tmp204_fu_32586_p3.read());
}
void a0_bin_conv::thread_sel_tmp206_fu_32597_p3() {
sel_tmp206_fu_32597_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_4_32_reg_54033.read(): sel_tmp205_fu_32591_p3.read());
}
void a0_bin_conv::thread_sel_tmp207_fu_32603_p3() {
sel_tmp207_fu_32603_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_0_5_32_reg_54100.read(): sel_tmp206_fu_32597_p3.read());
}
void a0_bin_conv::thread_sel_tmp208_fu_26614_p3() {
sel_tmp208_fu_26614_p3 = (!tmp_1225_reg_45756.read()[0].is_01())? sc_lv<2>(): ((tmp_1225_reg_45756.read()[0].to_bool())? old_word_buffer_0_7_fu_686.read(): ap_const_lv2_0);
}
void a0_bin_conv::thread_sel_tmp209_fu_26621_p3() {
sel_tmp209_fu_26621_p3 = (!sel_tmp79_reg_51283.read()[0].is_01())? sc_lv<2>(): ((sel_tmp79_reg_51283.read()[0].to_bool())? old_word_buffer_0_3_fu_670.read(): sel_tmp208_fu_26614_p3.read());
}
void a0_bin_conv::thread_sel_tmp210_fu_26628_p3() {
sel_tmp210_fu_26628_p3 = (!sel_tmp80_reg_51289.read()[0].is_01())? sc_lv<2>(): ((sel_tmp80_reg_51289.read()[0].to_bool())? old_word_buffer_0_4_fu_674.read(): sel_tmp209_fu_26621_p3.read());
}
void a0_bin_conv::thread_sel_tmp211_fu_26635_p3() {
sel_tmp211_fu_26635_p3 = (!sel_tmp81_reg_51295.read()[0].is_01())? sc_lv<2>(): ((sel_tmp81_reg_51295.read()[0].to_bool())? old_word_buffer_0_5_fu_678.read(): sel_tmp210_fu_26628_p3.read());
}
void a0_bin_conv::thread_sel_tmp212_fu_26642_p3() {
sel_tmp212_fu_26642_p3 = (!sel_tmp82_reg_51301.read()[0].is_01())? sc_lv<2>(): ((sel_tmp82_reg_51301.read()[0].to_bool())? old_word_buffer_0_6_fu_682.read(): sel_tmp211_fu_26635_p3.read());
}
void a0_bin_conv::thread_sel_tmp213_fu_26730_p3() {
sel_tmp213_fu_26730_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_3_11_fu_1454.read(): old_word_buffer_0_7_10_fu_1594.read());
}
void a0_bin_conv::thread_sel_tmp214_fu_26737_p3() {
sel_tmp214_fu_26737_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_4_12_fu_1490.read(): sel_tmp213_fu_26730_p3.read());
}
void a0_bin_conv::thread_sel_tmp215_fu_26744_p3() {
sel_tmp215_fu_26744_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_5_11_fu_1522.read(): sel_tmp214_fu_26737_p3.read());
}
void a0_bin_conv::thread_sel_tmp216_fu_32665_p3() {
sel_tmp216_fu_32665_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_3_29_reg_53958.read(): old_word_buffer_0_7_43_reg_54213.read());
}
void a0_bin_conv::thread_sel_tmp217_fu_32670_p3() {
sel_tmp217_fu_32670_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_4_30_reg_54009.read(): sel_tmp216_fu_32665_p3.read());
}
void a0_bin_conv::thread_sel_tmp218_fu_32676_p3() {
sel_tmp218_fu_32676_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_5_29_reg_54058.read(): sel_tmp217_fu_32670_p3.read());
}
void a0_bin_conv::thread_sel_tmp219_fu_26758_p3() {
sel_tmp219_fu_26758_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_3_13_fu_1462.read(): old_word_buffer_0_7_12_fu_1602.read());
}
void a0_bin_conv::thread_sel_tmp220_fu_26765_p3() {
sel_tmp220_fu_26765_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_4_14_fu_1498.read(): sel_tmp219_fu_26758_p3.read());
}
void a0_bin_conv::thread_sel_tmp221_fu_26772_p3() {
sel_tmp221_fu_26772_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_5_13_fu_1530.read(): sel_tmp220_fu_26765_p3.read());
}
void a0_bin_conv::thread_sel_tmp222_fu_32688_p3() {
sel_tmp222_fu_32688_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_3_30_reg_53968.read(): old_word_buffer_0_7_45_reg_54237.read());
}
void a0_bin_conv::thread_sel_tmp223_fu_32693_p3() {
sel_tmp223_fu_32693_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_4_31_reg_54021.read(): sel_tmp222_fu_32688_p3.read());
}
void a0_bin_conv::thread_sel_tmp224_fu_32699_p3() {
sel_tmp224_fu_32699_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_5_30_reg_54072.read(): sel_tmp223_fu_32693_p3.read());
}
void a0_bin_conv::thread_sel_tmp225_fu_26786_p3() {
sel_tmp225_fu_26786_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_3_15_fu_1470.read(): old_word_buffer_0_7_14_fu_1610.read());
}
void a0_bin_conv::thread_sel_tmp226_fu_26793_p3() {
sel_tmp226_fu_26793_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_4_16_fu_1506.read(): sel_tmp225_fu_26786_p3.read());
}
void a0_bin_conv::thread_sel_tmp227_fu_26800_p3() {
sel_tmp227_fu_26800_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_5_15_fu_1538.read(): sel_tmp226_fu_26793_p3.read());
}
void a0_bin_conv::thread_sel_tmp228_fu_32711_p3() {
sel_tmp228_fu_32711_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_3_31_reg_53978.read(): old_word_buffer_0_7_47_reg_54261.read());
}
void a0_bin_conv::thread_sel_tmp229_fu_32716_p3() {
sel_tmp229_fu_32716_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_4_29_reg_53874.read(): sel_tmp228_fu_32711_p3.read());
}
void a0_bin_conv::thread_sel_tmp230_fu_32722_p3() {
sel_tmp230_fu_32722_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_5_31_reg_54086.read(): sel_tmp229_fu_32716_p3.read());
}
void a0_bin_conv::thread_sel_tmp231_fu_23740_p3() {
sel_tmp231_fu_23740_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_3_17_fu_1478.read(): old_word_buffer_0_7_16_fu_1618.read());
}
void a0_bin_conv::thread_sel_tmp232_fu_23747_p3() {
sel_tmp232_fu_23747_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_4_17_fu_1510.read(): sel_tmp231_fu_23740_p3.read());
}
void a0_bin_conv::thread_sel_tmp233_fu_23754_p3() {
sel_tmp233_fu_23754_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_5_17_fu_1546.read(): sel_tmp232_fu_23747_p3.read());
}
void a0_bin_conv::thread_sel_tmp234_fu_32734_p3() {
sel_tmp234_fu_32734_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_3_32_reg_53988.read(): ap_reg_pp0_iter2_old_word_buffer_0_7_49_reg_52193.read());
}
void a0_bin_conv::thread_sel_tmp235_fu_32739_p3() {
sel_tmp235_fu_32739_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_4_32_reg_54033.read(): sel_tmp234_fu_32734_p3.read());
}
void a0_bin_conv::thread_sel_tmp236_fu_32745_p3() {
sel_tmp236_fu_32745_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_0_5_32_reg_54100.read(): sel_tmp235_fu_32739_p3.read());
}
void a0_bin_conv::thread_sel_tmp237_fu_26814_p3() {
sel_tmp237_fu_26814_p3 = (!tmp_1227_reg_45800.read()[0].is_01())? sc_lv<2>(): ((tmp_1227_reg_45800.read()[0].to_bool())? old_word_buffer_0_7_fu_686.read(): ap_const_lv2_0);
}
void a0_bin_conv::thread_sel_tmp238_fu_26821_p3() {
sel_tmp238_fu_26821_p3 = (!sel_tmp84_reg_51313.read()[0].is_01())? sc_lv<2>(): ((sel_tmp84_reg_51313.read()[0].to_bool())? old_word_buffer_0_4_fu_674.read(): sel_tmp237_fu_26814_p3.read());
}
void a0_bin_conv::thread_sel_tmp239_fu_26828_p3() {
sel_tmp239_fu_26828_p3 = (!sel_tmp85_reg_51319.read()[0].is_01())? sc_lv<2>(): ((sel_tmp85_reg_51319.read()[0].to_bool())? old_word_buffer_0_5_fu_678.read(): sel_tmp238_fu_26821_p3.read());
}
void a0_bin_conv::thread_sel_tmp240_fu_26835_p3() {
sel_tmp240_fu_26835_p3 = (!sel_tmp86_reg_51325.read()[0].is_01())? sc_lv<2>(): ((sel_tmp86_reg_51325.read()[0].to_bool())? old_word_buffer_0_6_fu_682.read(): sel_tmp239_fu_26828_p3.read());
}
void a0_bin_conv::thread_sel_tmp241_fu_26656_p3() {
sel_tmp241_fu_26656_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_0_1_1_fu_26044_p3.read(): word_buffer_0_2_1_fu_25951_p3.read());
}
void a0_bin_conv::thread_sel_tmp242_fu_26670_p3() {
sel_tmp242_fu_26670_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_0_3_1_fu_26031_p3.read(): word_buffer_0_2_3_1_reg_53427.read());
}
void a0_bin_conv::thread_sel_tmp243_fu_26682_p3() {
sel_tmp243_fu_26682_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_0_5_1_fu_26018_p3.read(): word_buffer_0_2_5_1_reg_53393.read());
}
void a0_bin_conv::thread_sel_tmp244_fu_26694_p3() {
sel_tmp244_fu_26694_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_0_7_1_fu_26005_p3.read(): word_buffer_0_2_7_1_reg_53360.read());
}
void a0_bin_conv::thread_sel_tmp245_fu_32624_p2() {
sel_tmp245_fu_32624_p2 = (tmp_1227_reg_45800.read() & last_wrd_not_fu_32619_p2.read());
}
void a0_bin_conv::thread_sel_tmp246_fu_32629_p2() {
sel_tmp246_fu_32629_p2 = (tmp_167_reg_50852.read() & sel_tmp245_fu_32624_p2.read());
}
void a0_bin_conv::thread_sel_tmp247_fu_32634_p3() {
sel_tmp247_fu_32634_p3 = (!sel_tmp246_fu_32629_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp246_fu_32629_p2.read()[0].to_bool())? ap_const_lv2_0: word_buffer_0_2_0_reg_55355.read());
}
void a0_bin_conv::thread_sel_tmp248_fu_32641_p2() {
sel_tmp248_fu_32641_p2 = (cond1_reg_50498.read() & sel_tmp245_fu_32624_p2.read());
}
void a0_bin_conv::thread_sel_tmp249_fu_32646_p3() {
sel_tmp249_fu_32646_p3 = (!sel_tmp248_fu_32641_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp248_fu_32641_p2.read()[0].to_bool())? word_buffer_0_1_0_reg_55417.read(): sel_tmp247_fu_32634_p3.read());
}
void a0_bin_conv::thread_sel_tmp250_fu_26954_p3() {
sel_tmp250_fu_26954_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_4_12_fu_1490.read(): old_word_buffer_0_7_10_fu_1594.read());
}
void a0_bin_conv::thread_sel_tmp251_fu_26961_p3() {
sel_tmp251_fu_26961_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_5_11_fu_1522.read(): sel_tmp250_fu_26954_p3.read());
}
void a0_bin_conv::thread_sel_tmp252_fu_32815_p3() {
sel_tmp252_fu_32815_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_4_30_reg_54009.read(): old_word_buffer_0_7_43_reg_54213.read());
}
void a0_bin_conv::thread_sel_tmp253_fu_32820_p3() {
sel_tmp253_fu_32820_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_5_29_reg_54058.read(): sel_tmp252_fu_32815_p3.read());
}
void a0_bin_conv::thread_sel_tmp254_fu_26975_p3() {
sel_tmp254_fu_26975_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_4_14_fu_1498.read(): old_word_buffer_0_7_12_fu_1602.read());
}
void a0_bin_conv::thread_sel_tmp255_fu_26982_p3() {
sel_tmp255_fu_26982_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_5_13_fu_1530.read(): sel_tmp254_fu_26975_p3.read());
}
void a0_bin_conv::thread_sel_tmp256_fu_32832_p3() {
sel_tmp256_fu_32832_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_4_31_reg_54021.read(): old_word_buffer_0_7_45_reg_54237.read());
}
void a0_bin_conv::thread_sel_tmp257_fu_32837_p3() {
sel_tmp257_fu_32837_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_5_30_reg_54072.read(): sel_tmp256_fu_32832_p3.read());
}
void a0_bin_conv::thread_sel_tmp258_fu_26996_p3() {
sel_tmp258_fu_26996_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_4_16_fu_1506.read(): old_word_buffer_0_7_14_fu_1610.read());
}
void a0_bin_conv::thread_sel_tmp259_fu_27003_p3() {
sel_tmp259_fu_27003_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_5_15_fu_1538.read(): sel_tmp258_fu_26996_p3.read());
}
void a0_bin_conv::thread_sel_tmp260_fu_32849_p3() {
sel_tmp260_fu_32849_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_4_29_reg_53874.read(): old_word_buffer_0_7_47_reg_54261.read());
}
void a0_bin_conv::thread_sel_tmp261_fu_32854_p3() {
sel_tmp261_fu_32854_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_5_31_reg_54086.read(): sel_tmp260_fu_32849_p3.read());
}
void a0_bin_conv::thread_sel_tmp262_fu_23774_p3() {
sel_tmp262_fu_23774_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_4_17_fu_1510.read(): old_word_buffer_0_7_16_fu_1618.read());
}
void a0_bin_conv::thread_sel_tmp263_fu_23781_p3() {
sel_tmp263_fu_23781_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_5_17_fu_1546.read(): sel_tmp262_fu_23774_p3.read());
}
void a0_bin_conv::thread_sel_tmp264_fu_32866_p3() {
sel_tmp264_fu_32866_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_4_32_reg_54033.read(): ap_reg_pp0_iter2_old_word_buffer_0_7_49_reg_52193.read());
}
void a0_bin_conv::thread_sel_tmp265_fu_32871_p3() {
sel_tmp265_fu_32871_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_0_5_32_reg_54100.read(): sel_tmp264_fu_32866_p3.read());
}
void a0_bin_conv::thread_sel_tmp266_fu_27017_p3() {
sel_tmp266_fu_27017_p3 = (!lb_3_reg_45835.read()[0].is_01())? sc_lv<2>(): ((lb_3_reg_45835.read()[0].to_bool())? ap_const_lv2_0: old_word_buffer_0_7_fu_686.read());
}
void a0_bin_conv::thread_sel_tmp267_fu_27024_p3() {
sel_tmp267_fu_27024_p3 = (!sel_tmp89_reg_51337.read()[0].is_01())? sc_lv<2>(): ((sel_tmp89_reg_51337.read()[0].to_bool())? old_word_buffer_0_5_fu_678.read(): sel_tmp266_fu_27017_p3.read());
}
void a0_bin_conv::thread_sel_tmp268_fu_27031_p3() {
sel_tmp268_fu_27031_p3 = (!sel_tmp90_reg_51343.read()[0].is_01())? sc_lv<2>(): ((sel_tmp90_reg_51343.read()[0].to_bool())? old_word_buffer_0_6_fu_682.read(): sel_tmp267_fu_27024_p3.read());
}
void a0_bin_conv::thread_sel_tmp269_fu_26849_p3() {
sel_tmp269_fu_26849_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_0_0_1_1_fu_26044_p3.read(): word_buffer_0_3_1_fu_25925_p3.read());
}
void a0_bin_conv::thread_sel_tmp270_fu_26856_p3() {
sel_tmp270_fu_26856_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_1_1_fu_25979_p3.read(): sel_tmp269_fu_26849_p3.read());
}
void a0_bin_conv::thread_sel_tmp271_fu_26870_p3() {
sel_tmp271_fu_26870_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_0_0_3_1_fu_26031_p3.read(): word_buffer_0_3_3_1_reg_53330.read());
}
void a0_bin_conv::thread_sel_tmp272_fu_26876_p3() {
sel_tmp272_fu_26876_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_1_3_1_reg_53536.read(): sel_tmp271_fu_26870_p3.read());
}
void a0_bin_conv::thread_sel_tmp273_fu_26888_p3() {
sel_tmp273_fu_26888_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_0_0_5_1_fu_26018_p3.read(): word_buffer_0_3_5_1_reg_53300.read());
}
void a0_bin_conv::thread_sel_tmp274_fu_26894_p3() {
sel_tmp274_fu_26894_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_1_5_1_reg_53498.read(): sel_tmp273_fu_26888_p3.read());
}
void a0_bin_conv::thread_sel_tmp275_fu_26906_p3() {
sel_tmp275_fu_26906_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_0_0_7_1_fu_26005_p3.read(): word_buffer_0_3_7_1_reg_53271.read());
}
void a0_bin_conv::thread_sel_tmp276_fu_26912_p3() {
sel_tmp276_fu_26912_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_1_7_1_reg_53461.read(): sel_tmp275_fu_26906_p3.read());
}
void a0_bin_conv::thread_sel_tmp277_fu_32761_p2() {
sel_tmp277_fu_32761_p2 = (brmerge5_fu_32757_p2.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp278_fu_32767_p2() {
sel_tmp278_fu_32767_p2 = (tmp_170_reg_51104.read() & sel_tmp277_fu_32761_p2.read());
}
void a0_bin_conv::thread_sel_tmp279_fu_32772_p3() {
sel_tmp279_fu_32772_p3 = (!sel_tmp278_fu_32767_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp278_fu_32767_p2.read()[0].to_bool())? ap_const_lv2_0: word_buffer_0_3_0_reg_55296.read());
}
void a0_bin_conv::thread_sel_tmp280_fu_32779_p2() {
sel_tmp280_fu_32779_p2 = (tmp_167_reg_50852.read() & sel_tmp277_fu_32761_p2.read());
}
void a0_bin_conv::thread_sel_tmp281_fu_32784_p3() {
sel_tmp281_fu_32784_p3 = (!sel_tmp280_fu_32779_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp280_fu_32779_p2.read()[0].to_bool())? word_buffer_0_1_0_reg_55417.read(): sel_tmp279_fu_32772_p3.read());
}
void a0_bin_conv::thread_sel_tmp282_fu_32791_p2() {
sel_tmp282_fu_32791_p2 = (cond1_reg_50498.read() & sel_tmp277_fu_32761_p2.read());
}
void a0_bin_conv::thread_sel_tmp283_fu_32796_p3() {
sel_tmp283_fu_32796_p3 = (!sel_tmp282_fu_32791_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp282_fu_32791_p2.read()[0].to_bool())? word_buffer_0_2_0_reg_55355.read(): sel_tmp281_fu_32784_p3.read());
}
void a0_bin_conv::thread_sel_tmp284_fu_27176_p3() {
sel_tmp284_fu_27176_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_5_11_fu_1522.read(): old_word_buffer_0_7_10_fu_1594.read());
}
void a0_bin_conv::thread_sel_tmp285_fu_32947_p3() {
sel_tmp285_fu_32947_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_5_29_reg_54058.read(): old_word_buffer_0_7_43_reg_54213.read());
}
void a0_bin_conv::thread_sel_tmp286_fu_27190_p3() {
sel_tmp286_fu_27190_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_5_13_fu_1530.read(): old_word_buffer_0_7_12_fu_1602.read());
}
void a0_bin_conv::thread_sel_tmp287_fu_32958_p3() {
sel_tmp287_fu_32958_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_5_30_reg_54072.read(): old_word_buffer_0_7_45_reg_54237.read());
}
void a0_bin_conv::thread_sel_tmp288_fu_27204_p3() {
sel_tmp288_fu_27204_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_5_15_fu_1538.read(): old_word_buffer_0_7_14_fu_1610.read());
}
void a0_bin_conv::thread_sel_tmp289_fu_32969_p3() {
sel_tmp289_fu_32969_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_5_31_reg_54086.read(): old_word_buffer_0_7_47_reg_54261.read());
}
void a0_bin_conv::thread_sel_tmp290_fu_23801_p3() {
sel_tmp290_fu_23801_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_5_17_fu_1546.read(): old_word_buffer_0_7_16_fu_1618.read());
}
void a0_bin_conv::thread_sel_tmp291_fu_32980_p3() {
sel_tmp291_fu_32980_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_5_32_reg_54100.read(): ap_reg_pp0_iter2_old_word_buffer_0_7_49_reg_52193.read());
}
void a0_bin_conv::thread_sel_tmp292_fu_27218_p3() {
sel_tmp292_fu_27218_p3 = (!lb_4_reg_45859.read()[0].is_01())? sc_lv<2>(): ((lb_4_reg_45859.read()[0].to_bool())? ap_const_lv2_0: old_word_buffer_0_7_fu_686.read());
}
void a0_bin_conv::thread_sel_tmp293_fu_27225_p3() {
sel_tmp293_fu_27225_p3 = (!sel_tmp93_reg_51355.read()[0].is_01())? sc_lv<2>(): ((sel_tmp93_reg_51355.read()[0].to_bool())? old_word_buffer_0_6_fu_682.read(): sel_tmp292_fu_27218_p3.read());
}
void a0_bin_conv::thread_sel_tmp294_fu_27045_p3() {
sel_tmp294_fu_27045_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_0_0_1_1_fu_26044_p3.read(): word_buffer_0_4_1_fu_25899_p3.read());
}
void a0_bin_conv::thread_sel_tmp295_fu_27052_p3() {
sel_tmp295_fu_27052_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_0_1_1_fu_25979_p3.read(): sel_tmp294_fu_27045_p3.read());
}
void a0_bin_conv::thread_sel_tmp296_fu_27059_p3() {
sel_tmp296_fu_27059_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_2_1_fu_25951_p3.read(): sel_tmp295_fu_27052_p3.read());
}
void a0_bin_conv::thread_sel_tmp297_fu_27073_p3() {
sel_tmp297_fu_27073_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_0_0_3_1_fu_26031_p3.read(): word_buffer_0_4_3_1_reg_53245.read());
}
void a0_bin_conv::thread_sel_tmp298_fu_27079_p3() {
sel_tmp298_fu_27079_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_0_1_3_1_reg_53536.read(): sel_tmp297_fu_27073_p3.read());
}
void a0_bin_conv::thread_sel_tmp299_fu_27085_p3() {
sel_tmp299_fu_27085_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_2_3_1_reg_53427.read(): sel_tmp298_fu_27079_p3.read());
}
void a0_bin_conv::thread_sel_tmp300_fu_27097_p3() {
sel_tmp300_fu_27097_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_0_0_5_1_fu_26018_p3.read(): word_buffer_0_4_5_1_reg_53219.read());
}
void a0_bin_conv::thread_sel_tmp301_fu_27103_p3() {
sel_tmp301_fu_27103_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_0_1_5_1_reg_53498.read(): sel_tmp300_fu_27097_p3.read());
}
void a0_bin_conv::thread_sel_tmp302_fu_27109_p3() {
sel_tmp302_fu_27109_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_2_5_1_reg_53393.read(): sel_tmp301_fu_27103_p3.read());
}
void a0_bin_conv::thread_sel_tmp303_fu_27121_p3() {
sel_tmp303_fu_27121_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_0_0_7_1_fu_26005_p3.read(): word_buffer_0_4_7_1_reg_53194.read());
}
void a0_bin_conv::thread_sel_tmp304_fu_27127_p3() {
sel_tmp304_fu_27127_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_0_1_7_1_reg_53461.read(): sel_tmp303_fu_27121_p3.read());
}
void a0_bin_conv::thread_sel_tmp305_fu_27133_p3() {
sel_tmp305_fu_27133_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_2_7_1_reg_53360.read(): sel_tmp304_fu_27127_p3.read());
}
void a0_bin_conv::thread_sel_tmp306_fu_32883_p2() {
sel_tmp306_fu_32883_p2 = (brmerge7_reg_55982.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp307_fu_32888_p2() {
sel_tmp307_fu_32888_p2 = (tmp_171_reg_51180.read() & sel_tmp306_fu_32883_p2.read());
}
void a0_bin_conv::thread_sel_tmp308_fu_32893_p3() {
sel_tmp308_fu_32893_p3 = (!sel_tmp307_fu_32888_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp307_fu_32888_p2.read()[0].to_bool())? ap_const_lv2_0: word_buffer_0_4_0_reg_55244.read());
}
void a0_bin_conv::thread_sel_tmp309_fu_32900_p2() {
sel_tmp309_fu_32900_p2 = (tmp_170_reg_51104.read() & sel_tmp306_fu_32883_p2.read());
}
void a0_bin_conv::thread_sel_tmp310_fu_32905_p3() {
sel_tmp310_fu_32905_p3 = (!sel_tmp309_fu_32900_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp309_fu_32900_p2.read()[0].to_bool())? word_buffer_0_1_0_reg_55417.read(): sel_tmp308_fu_32893_p3.read());
}
void a0_bin_conv::thread_sel_tmp311_fu_32912_p2() {
sel_tmp311_fu_32912_p2 = (tmp_167_reg_50852.read() & sel_tmp306_fu_32883_p2.read());
}
void a0_bin_conv::thread_sel_tmp312_fu_32917_p3() {
sel_tmp312_fu_32917_p3 = (!sel_tmp311_fu_32912_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp311_fu_32912_p2.read()[0].to_bool())? word_buffer_0_2_0_reg_55355.read(): sel_tmp310_fu_32905_p3.read());
}
void a0_bin_conv::thread_sel_tmp313_fu_32924_p2() {
sel_tmp313_fu_32924_p2 = (cond1_reg_50498.read() & sel_tmp306_fu_32883_p2.read());
}
void a0_bin_conv::thread_sel_tmp314_fu_32929_p3() {
sel_tmp314_fu_32929_p3 = (!sel_tmp313_fu_32924_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp313_fu_32924_p2.read()[0].to_bool())? word_buffer_0_3_0_reg_55296.read(): sel_tmp312_fu_32917_p3.read());
}
void a0_bin_conv::thread_sel_tmp315_fu_27239_p3() {
sel_tmp315_fu_27239_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_0_0_1_1_fu_26044_p3.read(): word_buffer_0_5_1_fu_25871_p3.read());
}
void a0_bin_conv::thread_sel_tmp316_fu_27246_p3() {
sel_tmp316_fu_27246_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_0_1_1_fu_25979_p3.read(): sel_tmp315_fu_27239_p3.read());
}
void a0_bin_conv::thread_sel_tmp317_fu_32991_p3() {
sel_tmp317_fu_32991_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_0_2_1_reg_55342.read(): sel_tmp316_reg_56020.read());
}
void a0_bin_conv::thread_sel_tmp318_fu_32996_p3() {
sel_tmp318_fu_32996_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_3_1_reg_55284.read(): sel_tmp317_fu_32991_p3.read());
}
void a0_bin_conv::thread_sel_tmp319_fu_27253_p3() {
sel_tmp319_fu_27253_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_0_0_3_1_fu_26031_p3.read(): word_buffer_0_5_3_1_reg_53172.read());
}
void a0_bin_conv::thread_sel_tmp320_fu_27259_p3() {
sel_tmp320_fu_27259_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_0_1_3_1_reg_53536.read(): sel_tmp319_fu_27253_p3.read());
}
void a0_bin_conv::thread_sel_tmp321_fu_33014_p3() {
sel_tmp321_fu_33014_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_3_1_reg_53427.read(): sel_tmp320_reg_56025.read());
}
void a0_bin_conv::thread_sel_tmp322_fu_33019_p3() {
sel_tmp322_fu_33019_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_3_1_reg_53330.read(): sel_tmp321_fu_33014_p3.read());
}
void a0_bin_conv::thread_sel_tmp323_fu_27265_p3() {
sel_tmp323_fu_27265_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_0_0_5_1_fu_26018_p3.read(): word_buffer_0_5_5_1_reg_53150.read());
}
void a0_bin_conv::thread_sel_tmp324_fu_27271_p3() {
sel_tmp324_fu_27271_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_0_1_5_1_reg_53498.read(): sel_tmp323_fu_27265_p3.read());
}
void a0_bin_conv::thread_sel_tmp325_fu_33037_p3() {
sel_tmp325_fu_33037_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_5_1_reg_53393.read(): sel_tmp324_reg_56030.read());
}
void a0_bin_conv::thread_sel_tmp326_fu_33042_p3() {
sel_tmp326_fu_33042_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_5_1_reg_53300.read(): sel_tmp325_fu_33037_p3.read());
}
void a0_bin_conv::thread_sel_tmp327_fu_27277_p3() {
sel_tmp327_fu_27277_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_0_0_7_1_fu_26005_p3.read(): word_buffer_0_5_7_1_reg_53129.read());
}
void a0_bin_conv::thread_sel_tmp328_fu_27283_p3() {
sel_tmp328_fu_27283_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_0_1_7_1_reg_53461.read(): sel_tmp327_fu_27277_p3.read());
}
void a0_bin_conv::thread_sel_tmp329_fu_33060_p3() {
sel_tmp329_fu_33060_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_7_1_reg_53360.read(): sel_tmp328_reg_56035.read());
}
void a0_bin_conv::thread_sel_tmp330_fu_33065_p3() {
sel_tmp330_fu_33065_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_7_1_reg_53271.read(): sel_tmp329_fu_33060_p3.read());
}
void a0_bin_conv::thread_sel_tmp331_fu_27293_p2() {
sel_tmp331_fu_27293_p2 = (brmerge9_fu_27289_p2.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp332_fu_27299_p2() {
sel_tmp332_fu_27299_p2 = (tmp_169_reg_51016.read() & sel_tmp331_fu_27293_p2.read());
}
void a0_bin_conv::thread_sel_tmp333_fu_27304_p3() {
sel_tmp333_fu_27304_p3 = (!sel_tmp332_fu_27299_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp332_fu_27299_p2.read()[0].to_bool())? ap_const_lv2_0: word_buffer_0_5_0_fu_25878_p3.read());
}
void a0_bin_conv::thread_sel_tmp334_fu_27312_p2() {
sel_tmp334_fu_27312_p2 = (tmp_171_reg_51180.read() & sel_tmp331_fu_27293_p2.read());
}
void a0_bin_conv::thread_sel_tmp335_fu_27317_p3() {
sel_tmp335_fu_27317_p3 = (!sel_tmp334_fu_27312_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp334_fu_27312_p2.read()[0].to_bool())? word_buffer_0_1_0_fu_25985_p3.read(): sel_tmp333_fu_27304_p3.read());
}
void a0_bin_conv::thread_sel_tmp336_fu_33083_p2() {
sel_tmp336_fu_33083_p2 = (tmp_170_reg_51104.read() & sel_tmp331_reg_56045.read());
}
void a0_bin_conv::thread_sel_tmp337_fu_33087_p3() {
sel_tmp337_fu_33087_p3 = (!sel_tmp336_fu_33083_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp336_fu_33083_p2.read()[0].to_bool())? word_buffer_0_2_0_reg_55355.read(): sel_tmp335_reg_56052.read());
}
void a0_bin_conv::thread_sel_tmp338_fu_33093_p2() {
sel_tmp338_fu_33093_p2 = (tmp_167_reg_50852.read() & sel_tmp331_reg_56045.read());
}
void a0_bin_conv::thread_sel_tmp339_fu_33097_p3() {
sel_tmp339_fu_33097_p3 = (!sel_tmp338_fu_33093_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp338_fu_33093_p2.read()[0].to_bool())? word_buffer_0_3_0_reg_55296.read(): sel_tmp337_fu_33087_p3.read());
}
void a0_bin_conv::thread_sel_tmp340_fu_33104_p2() {
sel_tmp340_fu_33104_p2 = (cond1_reg_50498.read() & sel_tmp331_reg_56045.read());
}
void a0_bin_conv::thread_sel_tmp341_fu_33108_p3() {
sel_tmp341_fu_33108_p3 = (!sel_tmp340_fu_33104_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp340_fu_33104_p2.read()[0].to_bool())? word_buffer_0_4_0_reg_55244.read(): sel_tmp339_fu_33097_p3.read());
}
void a0_bin_conv::thread_sel_tmp342_fu_27354_p3() {
sel_tmp342_fu_27354_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? word_buffer_0_0_1_1_fu_26044_p3.read(): word_buffer_0_6_1_fu_25843_p3.read());
}
void a0_bin_conv::thread_sel_tmp343_fu_27361_p3() {
sel_tmp343_fu_27361_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_0_1_1_fu_25979_p3.read(): sel_tmp342_fu_27354_p3.read());
}
void a0_bin_conv::thread_sel_tmp344_fu_33172_p3() {
sel_tmp344_fu_33172_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_0_2_1_reg_55342.read(): sel_tmp343_reg_56078.read());
}
void a0_bin_conv::thread_sel_tmp345_fu_33177_p3() {
sel_tmp345_fu_33177_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_0_3_1_reg_55284.read(): sel_tmp344_fu_33172_p3.read());
}
void a0_bin_conv::thread_sel_tmp346_fu_33183_p3() {
sel_tmp346_fu_33183_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_4_1_reg_55233.read(): sel_tmp345_fu_33177_p3.read());
}
void a0_bin_conv::thread_sel_tmp347_fu_27368_p3() {
sel_tmp347_fu_27368_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? word_buffer_0_0_3_1_fu_26031_p3.read(): word_buffer_0_6_3_1_reg_53111.read());
}
void a0_bin_conv::thread_sel_tmp348_fu_27374_p3() {
sel_tmp348_fu_27374_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_0_1_3_1_reg_53536.read(): sel_tmp347_fu_27368_p3.read());
}
void a0_bin_conv::thread_sel_tmp349_fu_27380_p3() {
sel_tmp349_fu_27380_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_0_2_3_1_reg_53427.read(): sel_tmp348_fu_27374_p3.read());
}
void a0_bin_conv::thread_sel_tmp350_fu_27386_p3() {
sel_tmp350_fu_27386_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_0_3_3_1_reg_53330.read(): sel_tmp349_fu_27380_p3.read());
}
void a0_bin_conv::thread_sel_tmp351_fu_27392_p3() {
sel_tmp351_fu_27392_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_0_4_3_1_reg_53245.read(): sel_tmp350_fu_27386_p3.read());
}
void a0_bin_conv::thread_sel_tmp352_fu_27404_p3() {
sel_tmp352_fu_27404_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? word_buffer_0_0_5_1_fu_26018_p3.read(): word_buffer_0_6_5_1_reg_53093.read());
}
void a0_bin_conv::thread_sel_tmp353_fu_27410_p3() {
sel_tmp353_fu_27410_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_0_1_5_1_reg_53498.read(): sel_tmp352_fu_27404_p3.read());
}
void a0_bin_conv::thread_sel_tmp354_fu_33202_p3() {
sel_tmp354_fu_33202_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_5_1_reg_53393.read(): sel_tmp353_reg_56094.read());
}
void a0_bin_conv::thread_sel_tmp355_fu_33207_p3() {
sel_tmp355_fu_33207_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_5_1_reg_53300.read(): sel_tmp354_fu_33202_p3.read());
}
void a0_bin_conv::thread_sel_tmp356_fu_33213_p3() {
sel_tmp356_fu_33213_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_5_1_reg_53219.read(): sel_tmp355_fu_33207_p3.read());
}
void a0_bin_conv::thread_sel_tmp357_fu_27416_p3() {
sel_tmp357_fu_27416_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? word_buffer_0_0_7_1_fu_26005_p3.read(): word_buffer_0_6_7_1_reg_53076.read());
}
void a0_bin_conv::thread_sel_tmp358_fu_27422_p3() {
sel_tmp358_fu_27422_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_0_1_7_1_reg_53461.read(): sel_tmp357_fu_27416_p3.read());
}
void a0_bin_conv::thread_sel_tmp359_fu_33232_p3() {
sel_tmp359_fu_33232_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_7_1_reg_53360.read(): sel_tmp358_reg_56099.read());
}
void a0_bin_conv::thread_sel_tmp360_fu_33237_p3() {
sel_tmp360_fu_33237_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_7_1_reg_53271.read(): sel_tmp359_fu_33232_p3.read());
}
void a0_bin_conv::thread_sel_tmp361_fu_33243_p3() {
sel_tmp361_fu_33243_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_7_1_reg_53194.read(): sel_tmp360_fu_33237_p3.read());
}
void a0_bin_conv::thread_sel_tmp362_fu_27432_p2() {
sel_tmp362_fu_27432_p2 = (brmerge11_fu_27428_p2.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp363_fu_27438_p2() {
sel_tmp363_fu_27438_p2 = (tmp_168_reg_50922.read() & sel_tmp362_fu_27432_p2.read());
}
void a0_bin_conv::thread_sel_tmp364_fu_27443_p3() {
sel_tmp364_fu_27443_p3 = (!sel_tmp363_fu_27438_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp363_fu_27438_p2.read()[0].to_bool())? ap_const_lv2_0: word_buffer_0_6_0_fu_25850_p3.read());
}
void a0_bin_conv::thread_sel_tmp365_fu_27451_p2() {
sel_tmp365_fu_27451_p2 = (tmp_169_reg_51016.read() & sel_tmp362_fu_27432_p2.read());
}
void a0_bin_conv::thread_sel_tmp366_fu_27456_p3() {
sel_tmp366_fu_27456_p3 = (!sel_tmp365_fu_27451_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp365_fu_27451_p2.read()[0].to_bool())? word_buffer_0_1_0_fu_25985_p3.read(): sel_tmp364_fu_27443_p3.read());
}
void a0_bin_conv::thread_sel_tmp367_fu_27464_p2() {
sel_tmp367_fu_27464_p2 = (tmp_171_reg_51180.read() & sel_tmp362_fu_27432_p2.read());
}
void a0_bin_conv::thread_sel_tmp368_fu_27469_p3() {
sel_tmp368_fu_27469_p3 = (!sel_tmp367_fu_27464_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp367_fu_27464_p2.read()[0].to_bool())? word_buffer_0_2_0_fu_25958_p3.read(): sel_tmp366_fu_27456_p3.read());
}
void a0_bin_conv::thread_sel_tmp369_fu_33262_p2() {
sel_tmp369_fu_33262_p2 = (tmp_170_reg_51104.read() & sel_tmp362_reg_56109.read());
}
void a0_bin_conv::thread_sel_tmp370_fu_33266_p3() {
sel_tmp370_fu_33266_p3 = (!sel_tmp369_fu_33262_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp369_fu_33262_p2.read()[0].to_bool())? word_buffer_0_3_0_reg_55296.read(): sel_tmp368_reg_56116.read());
}
void a0_bin_conv::thread_sel_tmp371_fu_33272_p2() {
sel_tmp371_fu_33272_p2 = (tmp_167_reg_50852.read() & sel_tmp362_reg_56109.read());
}
void a0_bin_conv::thread_sel_tmp372_fu_33276_p3() {
sel_tmp372_fu_33276_p3 = (!sel_tmp371_fu_33272_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp371_fu_33272_p2.read()[0].to_bool())? word_buffer_0_4_0_reg_55244.read(): sel_tmp370_fu_33266_p3.read());
}
void a0_bin_conv::thread_sel_tmp373_fu_33283_p2() {
sel_tmp373_fu_33283_p2 = (cond1_reg_50498.read() & sel_tmp362_reg_56109.read());
}
void a0_bin_conv::thread_sel_tmp374_fu_33287_p3() {
sel_tmp374_fu_33287_p3 = (!sel_tmp373_fu_33283_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp373_fu_33283_p2.read()[0].to_bool())? word_buffer_0_5_0_reg_55200.read(): sel_tmp372_fu_33276_p3.read());
}
void a0_bin_conv::thread_sel_tmp375_fu_27648_p3() {
sel_tmp375_fu_27648_p3 = (!tmp_143_reg_50572.read()[0].is_01())? sc_lv<2>(): ((tmp_143_reg_50572.read()[0].to_bool())? old_word_buffer_0_1_11_fu_1382.read(): old_word_buffer_0_7_10_fu_1594.read());
}
void a0_bin_conv::thread_sel_tmp376_fu_27655_p3() {
sel_tmp376_fu_27655_p3 = (!tmp_148_reg_50586.read()[0].is_01())? sc_lv<2>(): ((tmp_148_reg_50586.read()[0].to_bool())? old_word_buffer_0_2_11_fu_1418.read(): sel_tmp375_fu_27648_p3.read());
}
void a0_bin_conv::thread_sel_tmp377_fu_27662_p3() {
sel_tmp377_fu_27662_p3 = (!tmp_149_reg_50600.read()[0].is_01())? sc_lv<2>(): ((tmp_149_reg_50600.read()[0].to_bool())? old_word_buffer_0_3_11_fu_1454.read(): sel_tmp376_fu_27655_p3.read());
}
void a0_bin_conv::thread_sel_tmp378_fu_27669_p3() {
sel_tmp378_fu_27669_p3 = (!tmp_150_reg_50614.read()[0].is_01())? sc_lv<2>(): ((tmp_150_reg_50614.read()[0].to_bool())? old_word_buffer_0_4_12_fu_1490.read(): sel_tmp377_fu_27662_p3.read());
}
void a0_bin_conv::thread_sel_tmp379_fu_27676_p3() {
sel_tmp379_fu_27676_p3 = (!tmp_151_reg_50628.read()[0].is_01())? sc_lv<2>(): ((tmp_151_reg_50628.read()[0].to_bool())? old_word_buffer_0_5_11_fu_1522.read(): sel_tmp378_fu_27669_p3.read());
}
void a0_bin_conv::thread_sel_tmp380_fu_27708_p3() {
sel_tmp380_fu_27708_p3 = (!tmp_143_reg_50572.read()[0].is_01())? sc_lv<2>(): ((tmp_143_reg_50572.read()[0].to_bool())? old_word_buffer_0_1_13_fu_1390.read(): old_word_buffer_0_7_12_fu_1602.read());
}
void a0_bin_conv::thread_sel_tmp381_fu_27715_p3() {
sel_tmp381_fu_27715_p3 = (!tmp_148_reg_50586.read()[0].is_01())? sc_lv<2>(): ((tmp_148_reg_50586.read()[0].to_bool())? old_word_buffer_0_2_13_fu_1426.read(): sel_tmp380_fu_27708_p3.read());
}
void a0_bin_conv::thread_sel_tmp382_fu_27722_p3() {
sel_tmp382_fu_27722_p3 = (!tmp_149_reg_50600.read()[0].is_01())? sc_lv<2>(): ((tmp_149_reg_50600.read()[0].to_bool())? old_word_buffer_0_3_13_fu_1462.read(): sel_tmp381_fu_27715_p3.read());
}
void a0_bin_conv::thread_sel_tmp383_fu_27729_p3() {
sel_tmp383_fu_27729_p3 = (!tmp_150_reg_50614.read()[0].is_01())? sc_lv<2>(): ((tmp_150_reg_50614.read()[0].to_bool())? old_word_buffer_0_4_14_fu_1498.read(): sel_tmp382_fu_27722_p3.read());
}
void a0_bin_conv::thread_sel_tmp384_fu_27736_p3() {
sel_tmp384_fu_27736_p3 = (!tmp_151_reg_50628.read()[0].is_01())? sc_lv<2>(): ((tmp_151_reg_50628.read()[0].to_bool())? old_word_buffer_0_5_13_fu_1530.read(): sel_tmp383_fu_27729_p3.read());
}
void a0_bin_conv::thread_sel_tmp385_fu_27768_p3() {
sel_tmp385_fu_27768_p3 = (!tmp_143_reg_50572.read()[0].is_01())? sc_lv<2>(): ((tmp_143_reg_50572.read()[0].to_bool())? old_word_buffer_0_1_15_fu_1398.read(): old_word_buffer_0_7_14_fu_1610.read());
}
void a0_bin_conv::thread_sel_tmp386_fu_27775_p3() {
sel_tmp386_fu_27775_p3 = (!tmp_148_reg_50586.read()[0].is_01())? sc_lv<2>(): ((tmp_148_reg_50586.read()[0].to_bool())? old_word_buffer_0_2_15_fu_1434.read(): sel_tmp385_fu_27768_p3.read());
}
void a0_bin_conv::thread_sel_tmp387_fu_27782_p3() {
sel_tmp387_fu_27782_p3 = (!tmp_149_reg_50600.read()[0].is_01())? sc_lv<2>(): ((tmp_149_reg_50600.read()[0].to_bool())? old_word_buffer_0_3_15_fu_1470.read(): sel_tmp386_fu_27775_p3.read());
}
void a0_bin_conv::thread_sel_tmp388_fu_27789_p3() {
sel_tmp388_fu_27789_p3 = (!tmp_150_reg_50614.read()[0].is_01())? sc_lv<2>(): ((tmp_150_reg_50614.read()[0].to_bool())? old_word_buffer_0_4_16_fu_1506.read(): sel_tmp387_fu_27782_p3.read());
}
void a0_bin_conv::thread_sel_tmp389_fu_27796_p3() {
sel_tmp389_fu_27796_p3 = (!tmp_151_reg_50628.read()[0].is_01())? sc_lv<2>(): ((tmp_151_reg_50628.read()[0].to_bool())? old_word_buffer_0_5_15_fu_1538.read(): sel_tmp388_fu_27789_p3.read());
}
void a0_bin_conv::thread_sel_tmp390_fu_23854_p3() {
sel_tmp390_fu_23854_p3 = (!tmp_143_reg_50572.read()[0].is_01())? sc_lv<2>(): ((tmp_143_reg_50572.read()[0].to_bool())? old_word_buffer_0_1_17_fu_1406.read(): old_word_buffer_0_7_16_fu_1618.read());
}
void a0_bin_conv::thread_sel_tmp391_fu_23861_p3() {
sel_tmp391_fu_23861_p3 = (!tmp_148_reg_50586.read()[0].is_01())? sc_lv<2>(): ((tmp_148_reg_50586.read()[0].to_bool())? old_word_buffer_0_2_17_fu_1442.read(): sel_tmp390_fu_23854_p3.read());
}
void a0_bin_conv::thread_sel_tmp392_fu_23868_p3() {
sel_tmp392_fu_23868_p3 = (!tmp_149_reg_50600.read()[0].is_01())? sc_lv<2>(): ((tmp_149_reg_50600.read()[0].to_bool())? old_word_buffer_0_3_17_fu_1478.read(): sel_tmp391_fu_23861_p3.read());
}
void a0_bin_conv::thread_sel_tmp393_fu_23875_p3() {
sel_tmp393_fu_23875_p3 = (!tmp_150_reg_50614.read()[0].is_01())? sc_lv<2>(): ((tmp_150_reg_50614.read()[0].to_bool())? old_word_buffer_0_4_17_fu_1510.read(): sel_tmp392_fu_23868_p3.read());
}
void a0_bin_conv::thread_sel_tmp394_fu_23882_p3() {
sel_tmp394_fu_23882_p3 = (!tmp_151_reg_50628.read()[0].is_01())? sc_lv<2>(): ((tmp_151_reg_50628.read()[0].to_bool())? old_word_buffer_0_5_17_fu_1546.read(): sel_tmp393_fu_23875_p3.read());
}
void a0_bin_conv::thread_sel_tmp395_fu_27833_p2() {
sel_tmp395_fu_27833_p2 = (tmp_1225_reg_45756.read() & first_wrd_not_fu_27828_p2.read());
}
void a0_bin_conv::thread_sel_tmp396_fu_27838_p2() {
sel_tmp396_fu_27838_p2 = (tmp_148_reg_50586.read() & sel_tmp395_fu_27833_p2.read());
}
void a0_bin_conv::thread_sel_tmp397_fu_27843_p3() {
sel_tmp397_fu_27843_p3 = (!sel_tmp396_fu_27838_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp396_fu_27838_p2.read()[0].to_bool())? old_word_buffer_0_2_fu_666.read(): old_word_buffer_0_7_fu_686.read());
}
void a0_bin_conv::thread_sel_tmp398_fu_27851_p2() {
sel_tmp398_fu_27851_p2 = (tmp_149_reg_50600.read() & sel_tmp395_fu_27833_p2.read());
}
void a0_bin_conv::thread_sel_tmp399_fu_27856_p3() {
sel_tmp399_fu_27856_p3 = (!sel_tmp398_fu_27851_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp398_fu_27851_p2.read()[0].to_bool())? old_word_buffer_0_3_fu_670.read(): sel_tmp397_fu_27843_p3.read());
}
void a0_bin_conv::thread_sel_tmp400_fu_27864_p2() {
sel_tmp400_fu_27864_p2 = (tmp_150_reg_50614.read() & sel_tmp395_fu_27833_p2.read());
}
void a0_bin_conv::thread_sel_tmp401_fu_27869_p3() {
sel_tmp401_fu_27869_p3 = (!sel_tmp400_fu_27864_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp400_fu_27864_p2.read()[0].to_bool())? old_word_buffer_0_4_fu_674.read(): sel_tmp399_fu_27856_p3.read());
}
void a0_bin_conv::thread_sel_tmp402_fu_27877_p2() {
sel_tmp402_fu_27877_p2 = (tmp_151_reg_50628.read() & sel_tmp395_fu_27833_p2.read());
}
void a0_bin_conv::thread_sel_tmp403_fu_27882_p3() {
sel_tmp403_fu_27882_p3 = (!sel_tmp402_fu_27877_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp402_fu_27877_p2.read()[0].to_bool())? old_word_buffer_0_5_fu_678.read(): sel_tmp401_fu_27869_p3.read());
}
void a0_bin_conv::thread_sel_tmp404_fu_33564_p2() {
sel_tmp404_fu_33564_p2 = (tmp_152_reg_50642.read() & sel_tmp395_reg_56184.read());
}
void a0_bin_conv::thread_sel_tmp405_fu_33568_p3() {
sel_tmp405_fu_33568_p3 = (!sel_tmp404_fu_33564_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp404_fu_33564_p2.read()[0].to_bool())? old_word_buffer_0_6_54_reg_56179.read(): sel_tmp403_reg_56190.read());
}
void a0_bin_conv::thread_sel_tmp406_fu_33574_p2() {
sel_tmp406_fu_33574_p2 = (tmp_143_reg_50572.read() & sel_tmp395_reg_56184.read());
}
void a0_bin_conv::thread_sel_tmp407_fu_33578_p3() {
sel_tmp407_fu_33578_p3 = (!sel_tmp406_fu_33574_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp406_fu_33574_p2.read()[0].to_bool())? old_word_buffer_0_1_fu_662.read(): sel_tmp405_fu_33568_p3.read());
}
void a0_bin_conv::thread_sel_tmp408_fu_27905_p3() {
sel_tmp408_fu_27905_p3 = (!tmp_153_reg_50656.read()[0].is_01())? sc_lv<2>(): ((tmp_153_reg_50656.read()[0].to_bool())? old_word_buffer_0_2_11_fu_1418.read(): old_word_buffer_0_7_10_fu_1594.read());
}
void a0_bin_conv::thread_sel_tmp409_fu_27912_p3() {
sel_tmp409_fu_27912_p3 = (!tmp_154_reg_50670.read()[0].is_01())? sc_lv<2>(): ((tmp_154_reg_50670.read()[0].to_bool())? old_word_buffer_0_3_11_fu_1454.read(): sel_tmp408_fu_27905_p3.read());
}
void a0_bin_conv::thread_sel_tmp410_fu_27919_p3() {
sel_tmp410_fu_27919_p3 = (!tmp_155_reg_50684.read()[0].is_01())? sc_lv<2>(): ((tmp_155_reg_50684.read()[0].to_bool())? old_word_buffer_0_4_12_fu_1490.read(): sel_tmp409_fu_27912_p3.read());
}
void a0_bin_conv::thread_sel_tmp411_fu_27926_p3() {
sel_tmp411_fu_27926_p3 = (!tmp_156_reg_50698.read()[0].is_01())? sc_lv<2>(): ((tmp_156_reg_50698.read()[0].to_bool())? old_word_buffer_0_5_11_fu_1522.read(): sel_tmp410_fu_27919_p3.read());
}
void a0_bin_conv::thread_sel_tmp412_fu_27955_p3() {
sel_tmp412_fu_27955_p3 = (!tmp_153_reg_50656.read()[0].is_01())? sc_lv<2>(): ((tmp_153_reg_50656.read()[0].to_bool())? old_word_buffer_0_2_13_fu_1426.read(): old_word_buffer_0_7_12_fu_1602.read());
}
void a0_bin_conv::thread_sel_tmp413_fu_27962_p3() {
sel_tmp413_fu_27962_p3 = (!tmp_154_reg_50670.read()[0].is_01())? sc_lv<2>(): ((tmp_154_reg_50670.read()[0].to_bool())? old_word_buffer_0_3_13_fu_1462.read(): sel_tmp412_fu_27955_p3.read());
}
void a0_bin_conv::thread_sel_tmp414_fu_27969_p3() {
sel_tmp414_fu_27969_p3 = (!tmp_155_reg_50684.read()[0].is_01())? sc_lv<2>(): ((tmp_155_reg_50684.read()[0].to_bool())? old_word_buffer_0_4_14_fu_1498.read(): sel_tmp413_fu_27962_p3.read());
}
void a0_bin_conv::thread_sel_tmp415_fu_27976_p3() {
sel_tmp415_fu_27976_p3 = (!tmp_156_reg_50698.read()[0].is_01())? sc_lv<2>(): ((tmp_156_reg_50698.read()[0].to_bool())? old_word_buffer_0_5_13_fu_1530.read(): sel_tmp414_fu_27969_p3.read());
}
void a0_bin_conv::thread_sel_tmp416_fu_28005_p3() {
sel_tmp416_fu_28005_p3 = (!tmp_153_reg_50656.read()[0].is_01())? sc_lv<2>(): ((tmp_153_reg_50656.read()[0].to_bool())? old_word_buffer_0_2_15_fu_1434.read(): old_word_buffer_0_7_14_fu_1610.read());
}
void a0_bin_conv::thread_sel_tmp417_fu_28012_p3() {
sel_tmp417_fu_28012_p3 = (!tmp_154_reg_50670.read()[0].is_01())? sc_lv<2>(): ((tmp_154_reg_50670.read()[0].to_bool())? old_word_buffer_0_3_15_fu_1470.read(): sel_tmp416_fu_28005_p3.read());
}
void a0_bin_conv::thread_sel_tmp418_fu_28019_p3() {
sel_tmp418_fu_28019_p3 = (!tmp_155_reg_50684.read()[0].is_01())? sc_lv<2>(): ((tmp_155_reg_50684.read()[0].to_bool())? old_word_buffer_0_4_16_fu_1506.read(): sel_tmp417_fu_28012_p3.read());
}
void a0_bin_conv::thread_sel_tmp419_fu_28026_p3() {
sel_tmp419_fu_28026_p3 = (!tmp_156_reg_50698.read()[0].is_01())? sc_lv<2>(): ((tmp_156_reg_50698.read()[0].to_bool())? old_word_buffer_0_5_15_fu_1538.read(): sel_tmp418_fu_28019_p3.read());
}
void a0_bin_conv::thread_sel_tmp420_fu_23911_p3() {
sel_tmp420_fu_23911_p3 = (!tmp_153_reg_50656.read()[0].is_01())? sc_lv<2>(): ((tmp_153_reg_50656.read()[0].to_bool())? old_word_buffer_0_2_17_fu_1442.read(): old_word_buffer_0_7_16_fu_1618.read());
}
void a0_bin_conv::thread_sel_tmp421_fu_23918_p3() {
sel_tmp421_fu_23918_p3 = (!tmp_154_reg_50670.read()[0].is_01())? sc_lv<2>(): ((tmp_154_reg_50670.read()[0].to_bool())? old_word_buffer_0_3_17_fu_1478.read(): sel_tmp420_fu_23911_p3.read());
}
void a0_bin_conv::thread_sel_tmp422_fu_23925_p3() {
sel_tmp422_fu_23925_p3 = (!tmp_155_reg_50684.read()[0].is_01())? sc_lv<2>(): ((tmp_155_reg_50684.read()[0].to_bool())? old_word_buffer_0_4_17_fu_1510.read(): sel_tmp421_fu_23918_p3.read());
}
void a0_bin_conv::thread_sel_tmp423_fu_23932_p3() {
sel_tmp423_fu_23932_p3 = (!tmp_156_reg_50698.read()[0].is_01())? sc_lv<2>(): ((tmp_156_reg_50698.read()[0].to_bool())? old_word_buffer_0_5_17_fu_1546.read(): sel_tmp422_fu_23925_p3.read());
}
void a0_bin_conv::thread_sel_tmp424_fu_23951_p2() {
sel_tmp424_fu_23951_p2 = (tmp_1227_reg_45800.read() & first_wrd_not1_fu_23946_p2.read());
}
void a0_bin_conv::thread_sel_tmp425_fu_28062_p2() {
sel_tmp425_fu_28062_p2 = (tmp_154_reg_50670.read() & sel_tmp424_reg_53680.read());
}
void a0_bin_conv::thread_sel_tmp426_fu_28066_p3() {
sel_tmp426_fu_28066_p3 = (!sel_tmp425_fu_28062_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp425_fu_28062_p2.read()[0].to_bool())? old_word_buffer_0_3_fu_670.read(): old_word_buffer_0_7_fu_686.read());
}
void a0_bin_conv::thread_sel_tmp427_fu_28074_p2() {
sel_tmp427_fu_28074_p2 = (tmp_155_reg_50684.read() & sel_tmp424_reg_53680.read());
}
void a0_bin_conv::thread_sel_tmp428_fu_28078_p3() {
sel_tmp428_fu_28078_p3 = (!sel_tmp427_fu_28074_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp427_fu_28074_p2.read()[0].to_bool())? old_word_buffer_0_4_fu_674.read(): sel_tmp426_fu_28066_p3.read());
}
void a0_bin_conv::thread_sel_tmp429_fu_28086_p2() {
sel_tmp429_fu_28086_p2 = (tmp_156_reg_50698.read() & sel_tmp424_reg_53680.read());
}
void a0_bin_conv::thread_sel_tmp430_fu_28090_p3() {
sel_tmp430_fu_28090_p3 = (!sel_tmp429_fu_28086_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp429_fu_28086_p2.read()[0].to_bool())? old_word_buffer_0_5_fu_678.read(): sel_tmp428_fu_28078_p3.read());
}
void a0_bin_conv::thread_sel_tmp431_fu_28098_p2() {
sel_tmp431_fu_28098_p2 = (tmp_157_reg_50712.read() & sel_tmp424_reg_53680.read());
}
void a0_bin_conv::thread_sel_tmp432_fu_28102_p3() {
sel_tmp432_fu_28102_p3 = (!sel_tmp431_fu_28098_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp431_fu_28098_p2.read()[0].to_bool())? old_word_buffer_0_6_fu_682.read(): sel_tmp430_fu_28090_p3.read());
}
void a0_bin_conv::thread_sel_tmp433_fu_28110_p2() {
sel_tmp433_fu_28110_p2 = (tmp_153_reg_50656.read() & sel_tmp424_reg_53680.read());
}
void a0_bin_conv::thread_sel_tmp434_fu_28114_p3() {
sel_tmp434_fu_28114_p3 = (!sel_tmp433_fu_28110_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp433_fu_28110_p2.read()[0].to_bool())? old_word_buffer_0_2_fu_666.read(): sel_tmp432_fu_28102_p3.read());
}
void a0_bin_conv::thread_sel_tmp435_fu_33649_p3() {
sel_tmp435_fu_33649_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? word_buffer_0_1_1_reg_55405.read(): word_buffer_0_2_1_reg_55342.read());
}
void a0_bin_conv::thread_sel_tmp436_fu_33660_p3() {
sel_tmp436_fu_33660_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_2_1_reg_53555.read(): ap_reg_pp0_iter2_word_buffer_0_2_2_1_reg_53444.read());
}
void a0_bin_conv::thread_sel_tmp437_fu_33671_p3() {
sel_tmp437_fu_33671_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_3_1_reg_53536.read(): ap_reg_pp0_iter2_word_buffer_0_2_3_1_reg_53427.read());
}
void a0_bin_conv::thread_sel_tmp438_fu_33682_p3() {
sel_tmp438_fu_33682_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_4_1_reg_53517.read(): ap_reg_pp0_iter2_word_buffer_0_2_4_1_reg_53410.read());
}
void a0_bin_conv::thread_sel_tmp439_fu_33693_p3() {
sel_tmp439_fu_33693_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_5_1_reg_53498.read(): ap_reg_pp0_iter2_word_buffer_0_2_5_1_reg_53393.read());
}
void a0_bin_conv::thread_sel_tmp440_fu_33704_p3() {
sel_tmp440_fu_33704_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_6_1_reg_53479.read(): ap_reg_pp0_iter2_word_buffer_0_2_6_1_reg_53376.read());
}
void a0_bin_conv::thread_sel_tmp441_fu_33715_p3() {
sel_tmp441_fu_33715_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_7_1_reg_53461.read(): ap_reg_pp0_iter2_word_buffer_0_2_7_1_reg_53360.read());
}
void a0_bin_conv::thread_sel_tmp442_fu_33726_p3() {
sel_tmp442_fu_33726_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? word_buffer_0_2_0_1_reg_55388.read(): word_buffer_0_3_0_1_reg_55326.read());
}
void a0_bin_conv::thread_sel_tmp443_fu_33737_p3() {
sel_tmp443_fu_33737_p3 = (!tmp_173_reg_51413.read()[0].is_01())? sc_lv<2>(): ((tmp_173_reg_51413.read()[0].to_bool())? ap_const_lv2_0: word_buffer_0_2_0_reg_55355.read());
}
void a0_bin_conv::thread_sel_tmp444_fu_28142_p3() {
sel_tmp444_fu_28142_p3 = (!tmp_158_reg_50726.read()[0].is_01())? sc_lv<2>(): ((tmp_158_reg_50726.read()[0].to_bool())? old_word_buffer_0_3_11_fu_1454.read(): old_word_buffer_0_7_10_fu_1594.read());
}
void a0_bin_conv::thread_sel_tmp445_fu_28149_p3() {
sel_tmp445_fu_28149_p3 = (!tmp_159_reg_50740.read()[0].is_01())? sc_lv<2>(): ((tmp_159_reg_50740.read()[0].to_bool())? old_word_buffer_0_4_12_fu_1490.read(): sel_tmp444_fu_28142_p3.read());
}
void a0_bin_conv::thread_sel_tmp446_fu_28156_p3() {
sel_tmp446_fu_28156_p3 = (!tmp_160_reg_50754.read()[0].is_01())? sc_lv<2>(): ((tmp_160_reg_50754.read()[0].to_bool())? old_word_buffer_0_5_11_fu_1522.read(): sel_tmp445_fu_28149_p3.read());
}
void a0_bin_conv::thread_sel_tmp447_fu_28182_p3() {
sel_tmp447_fu_28182_p3 = (!tmp_158_reg_50726.read()[0].is_01())? sc_lv<2>(): ((tmp_158_reg_50726.read()[0].to_bool())? old_word_buffer_0_3_13_fu_1462.read(): old_word_buffer_0_7_12_fu_1602.read());
}
void a0_bin_conv::thread_sel_tmp448_fu_28189_p3() {
sel_tmp448_fu_28189_p3 = (!tmp_159_reg_50740.read()[0].is_01())? sc_lv<2>(): ((tmp_159_reg_50740.read()[0].to_bool())? old_word_buffer_0_4_14_fu_1498.read(): sel_tmp447_fu_28182_p3.read());
}
void a0_bin_conv::thread_sel_tmp449_fu_28196_p3() {
sel_tmp449_fu_28196_p3 = (!tmp_160_reg_50754.read()[0].is_01())? sc_lv<2>(): ((tmp_160_reg_50754.read()[0].to_bool())? old_word_buffer_0_5_13_fu_1530.read(): sel_tmp448_fu_28189_p3.read());
}
void a0_bin_conv::thread_sel_tmp450_fu_28222_p3() {
sel_tmp450_fu_28222_p3 = (!tmp_158_reg_50726.read()[0].is_01())? sc_lv<2>(): ((tmp_158_reg_50726.read()[0].to_bool())? old_word_buffer_0_3_15_fu_1470.read(): old_word_buffer_0_7_14_fu_1610.read());
}
void a0_bin_conv::thread_sel_tmp451_fu_28229_p3() {
sel_tmp451_fu_28229_p3 = (!tmp_159_reg_50740.read()[0].is_01())? sc_lv<2>(): ((tmp_159_reg_50740.read()[0].to_bool())? old_word_buffer_0_4_16_fu_1506.read(): sel_tmp450_fu_28222_p3.read());
}
void a0_bin_conv::thread_sel_tmp452_fu_28236_p3() {
sel_tmp452_fu_28236_p3 = (!tmp_160_reg_50754.read()[0].is_01())? sc_lv<2>(): ((tmp_160_reg_50754.read()[0].to_bool())? old_word_buffer_0_5_15_fu_1538.read(): sel_tmp451_fu_28229_p3.read());
}
void a0_bin_conv::thread_sel_tmp453_fu_23968_p3() {
sel_tmp453_fu_23968_p3 = (!tmp_158_reg_50726.read()[0].is_01())? sc_lv<2>(): ((tmp_158_reg_50726.read()[0].to_bool())? old_word_buffer_0_3_17_fu_1478.read(): old_word_buffer_0_7_16_fu_1618.read());
}
void a0_bin_conv::thread_sel_tmp454_fu_23975_p3() {
sel_tmp454_fu_23975_p3 = (!tmp_159_reg_50740.read()[0].is_01())? sc_lv<2>(): ((tmp_159_reg_50740.read()[0].to_bool())? old_word_buffer_0_4_17_fu_1510.read(): sel_tmp453_fu_23968_p3.read());
}
void a0_bin_conv::thread_sel_tmp455_fu_23982_p3() {
sel_tmp455_fu_23982_p3 = (!tmp_160_reg_50754.read()[0].is_01())? sc_lv<2>(): ((tmp_160_reg_50754.read()[0].to_bool())? old_word_buffer_0_5_17_fu_1546.read(): sel_tmp454_fu_23975_p3.read());
}
void a0_bin_conv::thread_sel_tmp456_fu_28265_p2() {
sel_tmp456_fu_28265_p2 = (brmerge18_reg_53698.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp457_fu_28270_p2() {
sel_tmp457_fu_28270_p2 = (tmp_159_reg_50740.read() & sel_tmp456_fu_28265_p2.read());
}
void a0_bin_conv::thread_sel_tmp458_fu_28275_p3() {
sel_tmp458_fu_28275_p3 = (!sel_tmp457_fu_28270_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp457_fu_28270_p2.read()[0].to_bool())? old_word_buffer_0_4_fu_674.read(): old_word_buffer_0_7_fu_686.read());
}
void a0_bin_conv::thread_sel_tmp459_fu_28283_p2() {
sel_tmp459_fu_28283_p2 = (tmp_160_reg_50754.read() & sel_tmp456_fu_28265_p2.read());
}
void a0_bin_conv::thread_sel_tmp460_fu_28288_p3() {
sel_tmp460_fu_28288_p3 = (!sel_tmp459_fu_28283_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp459_fu_28283_p2.read()[0].to_bool())? old_word_buffer_0_5_fu_678.read(): sel_tmp458_fu_28275_p3.read());
}
void a0_bin_conv::thread_sel_tmp461_fu_28296_p2() {
sel_tmp461_fu_28296_p2 = (tmp_161_reg_50768.read() & sel_tmp456_fu_28265_p2.read());
}
void a0_bin_conv::thread_sel_tmp462_fu_28301_p3() {
sel_tmp462_fu_28301_p3 = (!sel_tmp461_fu_28296_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp461_fu_28296_p2.read()[0].to_bool())? old_word_buffer_0_6_fu_682.read(): sel_tmp460_fu_28288_p3.read());
}
void a0_bin_conv::thread_sel_tmp463_fu_28309_p2() {
sel_tmp463_fu_28309_p2 = (tmp_158_reg_50726.read() & sel_tmp456_fu_28265_p2.read());
}
void a0_bin_conv::thread_sel_tmp464_fu_28314_p3() {
sel_tmp464_fu_28314_p3 = (!sel_tmp463_fu_28309_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp463_fu_28309_p2.read()[0].to_bool())? old_word_buffer_0_3_fu_670.read(): sel_tmp462_fu_28301_p3.read());
}
void a0_bin_conv::thread_sel_tmp465_fu_33753_p3() {
sel_tmp465_fu_33753_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? word_buffer_0_1_1_reg_55405.read(): word_buffer_0_3_1_reg_55284.read());
}
void a0_bin_conv::thread_sel_tmp466_fu_33758_p3() {
sel_tmp466_fu_33758_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? word_buffer_0_2_1_reg_55342.read(): sel_tmp465_fu_33753_p3.read());
}
void a0_bin_conv::thread_sel_tmp467_fu_33770_p3() {
sel_tmp467_fu_33770_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_2_1_reg_53555.read(): ap_reg_pp0_iter2_word_buffer_0_3_2_1_reg_53345.read());
}
void a0_bin_conv::thread_sel_tmp468_fu_33775_p3() {
sel_tmp468_fu_33775_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_2_1_reg_53444.read(): sel_tmp467_fu_33770_p3.read());
}
void a0_bin_conv::thread_sel_tmp469_fu_33787_p3() {
sel_tmp469_fu_33787_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_3_1_reg_53536.read(): ap_reg_pp0_iter2_word_buffer_0_3_3_1_reg_53330.read());
}
void a0_bin_conv::thread_sel_tmp470_fu_33792_p3() {
sel_tmp470_fu_33792_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_3_1_reg_53427.read(): sel_tmp469_fu_33787_p3.read());
}
void a0_bin_conv::thread_sel_tmp471_fu_33804_p3() {
sel_tmp471_fu_33804_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_4_1_reg_53517.read(): ap_reg_pp0_iter2_word_buffer_0_3_4_1_reg_53315.read());
}
void a0_bin_conv::thread_sel_tmp472_fu_33809_p3() {
sel_tmp472_fu_33809_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_4_1_reg_53410.read(): sel_tmp471_fu_33804_p3.read());
}
void a0_bin_conv::thread_sel_tmp473_fu_33821_p3() {
sel_tmp473_fu_33821_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_5_1_reg_53498.read(): ap_reg_pp0_iter2_word_buffer_0_3_5_1_reg_53300.read());
}
void a0_bin_conv::thread_sel_tmp474_fu_33826_p3() {
sel_tmp474_fu_33826_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_5_1_reg_53393.read(): sel_tmp473_fu_33821_p3.read());
}
void a0_bin_conv::thread_sel_tmp475_fu_33838_p3() {
sel_tmp475_fu_33838_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_6_1_reg_53479.read(): ap_reg_pp0_iter2_word_buffer_0_3_6_1_reg_53285.read());
}
void a0_bin_conv::thread_sel_tmp476_fu_33843_p3() {
sel_tmp476_fu_33843_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_6_1_reg_53376.read(): sel_tmp475_fu_33838_p3.read());
}
void a0_bin_conv::thread_sel_tmp477_fu_33855_p3() {
sel_tmp477_fu_33855_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_7_1_reg_53461.read(): ap_reg_pp0_iter2_word_buffer_0_3_7_1_reg_53271.read());
}
void a0_bin_conv::thread_sel_tmp478_fu_33860_p3() {
sel_tmp478_fu_33860_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_7_1_reg_53360.read(): sel_tmp477_fu_33855_p3.read());
}
void a0_bin_conv::thread_sel_tmp479_fu_33872_p3() {
sel_tmp479_fu_33872_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? word_buffer_0_2_0_1_reg_55388.read(): word_buffer_0_4_0_1_reg_55270.read());
}
void a0_bin_conv::thread_sel_tmp480_fu_33877_p3() {
sel_tmp480_fu_33877_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? word_buffer_0_3_0_1_reg_55326.read(): sel_tmp479_fu_33872_p3.read());
}
void a0_bin_conv::thread_sel_tmp481_fu_33889_p3() {
sel_tmp481_fu_33889_p3 = (!tmp_174_reg_51465.read()[0].is_01())? sc_lv<2>(): ((tmp_174_reg_51465.read()[0].to_bool())? ap_const_lv2_0: word_buffer_0_3_0_reg_55296.read());
}
void a0_bin_conv::thread_sel_tmp482_fu_33895_p3() {
sel_tmp482_fu_33895_p3 = (!sel_tmp102_reg_51471.read()[0].is_01())? sc_lv<2>(): ((sel_tmp102_reg_51471.read()[0].to_bool())? word_buffer_0_1_0_reg_55417.read(): sel_tmp481_fu_33889_p3.read());
}
void a0_bin_conv::thread_sel_tmp483_fu_28338_p3() {
sel_tmp483_fu_28338_p3 = (!tmp_162_reg_50782.read()[0].is_01())? sc_lv<2>(): ((tmp_162_reg_50782.read()[0].to_bool())? old_word_buffer_0_4_12_fu_1490.read(): old_word_buffer_0_7_10_fu_1594.read());
}
void a0_bin_conv::thread_sel_tmp484_fu_28345_p3() {
sel_tmp484_fu_28345_p3 = (!tmp_163_reg_50796.read()[0].is_01())? sc_lv<2>(): ((tmp_163_reg_50796.read()[0].to_bool())? old_word_buffer_0_5_11_fu_1522.read(): sel_tmp483_fu_28338_p3.read());
}
void a0_bin_conv::thread_sel_tmp485_fu_28368_p3() {
sel_tmp485_fu_28368_p3 = (!tmp_162_reg_50782.read()[0].is_01())? sc_lv<2>(): ((tmp_162_reg_50782.read()[0].to_bool())? old_word_buffer_0_4_14_fu_1498.read(): old_word_buffer_0_7_12_fu_1602.read());
}
void a0_bin_conv::thread_sel_tmp486_fu_28375_p3() {
sel_tmp486_fu_28375_p3 = (!tmp_163_reg_50796.read()[0].is_01())? sc_lv<2>(): ((tmp_163_reg_50796.read()[0].to_bool())? old_word_buffer_0_5_13_fu_1530.read(): sel_tmp485_fu_28368_p3.read());
}
void a0_bin_conv::thread_sel_tmp487_fu_28398_p3() {
sel_tmp487_fu_28398_p3 = (!tmp_162_reg_50782.read()[0].is_01())? sc_lv<2>(): ((tmp_162_reg_50782.read()[0].to_bool())? old_word_buffer_0_4_16_fu_1506.read(): old_word_buffer_0_7_14_fu_1610.read());
}
void a0_bin_conv::thread_sel_tmp488_fu_28405_p3() {
sel_tmp488_fu_28405_p3 = (!tmp_163_reg_50796.read()[0].is_01())? sc_lv<2>(): ((tmp_163_reg_50796.read()[0].to_bool())? old_word_buffer_0_5_15_fu_1538.read(): sel_tmp487_fu_28398_p3.read());
}
void a0_bin_conv::thread_sel_tmp489_fu_24009_p3() {
sel_tmp489_fu_24009_p3 = (!tmp_162_reg_50782.read()[0].is_01())? sc_lv<2>(): ((tmp_162_reg_50782.read()[0].to_bool())? old_word_buffer_0_4_17_fu_1510.read(): old_word_buffer_0_7_16_fu_1618.read());
}
void a0_bin_conv::thread_sel_tmp490_fu_24016_p3() {
sel_tmp490_fu_24016_p3 = (!tmp_163_reg_50796.read()[0].is_01())? sc_lv<2>(): ((tmp_163_reg_50796.read()[0].to_bool())? old_word_buffer_0_5_17_fu_1546.read(): sel_tmp489_fu_24009_p3.read());
}
void a0_bin_conv::thread_sel_tmp491_fu_28435_p2() {
sel_tmp491_fu_28435_p2 = (brmerge20_fu_28431_p2.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp492_fu_28441_p2() {
sel_tmp492_fu_28441_p2 = (tmp_163_reg_50796.read() & sel_tmp491_fu_28435_p2.read());
}
void a0_bin_conv::thread_sel_tmp493_fu_28446_p3() {
sel_tmp493_fu_28446_p3 = (!sel_tmp492_fu_28441_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp492_fu_28441_p2.read()[0].to_bool())? old_word_buffer_0_5_fu_678.read(): old_word_buffer_0_7_fu_686.read());
}
void a0_bin_conv::thread_sel_tmp494_fu_28454_p2() {
sel_tmp494_fu_28454_p2 = (tmp_164_reg_50810.read() & sel_tmp491_fu_28435_p2.read());
}
void a0_bin_conv::thread_sel_tmp495_fu_28459_p3() {
sel_tmp495_fu_28459_p3 = (!sel_tmp494_fu_28454_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp494_fu_28454_p2.read()[0].to_bool())? old_word_buffer_0_6_fu_682.read(): sel_tmp493_fu_28446_p3.read());
}
void a0_bin_conv::thread_sel_tmp496_fu_28467_p2() {
sel_tmp496_fu_28467_p2 = (tmp_162_reg_50782.read() & sel_tmp491_fu_28435_p2.read());
}
void a0_bin_conv::thread_sel_tmp497_fu_28472_p3() {
sel_tmp497_fu_28472_p3 = (!sel_tmp496_fu_28467_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp496_fu_28467_p2.read()[0].to_bool())? old_word_buffer_0_4_fu_674.read(): sel_tmp495_fu_28459_p3.read());
}
void a0_bin_conv::thread_sel_tmp498_fu_33911_p3() {
sel_tmp498_fu_33911_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? word_buffer_0_1_1_reg_55405.read(): word_buffer_0_4_1_reg_55233.read());
}
void a0_bin_conv::thread_sel_tmp499_fu_33916_p3() {
sel_tmp499_fu_33916_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? word_buffer_0_2_1_reg_55342.read(): sel_tmp498_fu_33911_p3.read());
}
void a0_bin_conv::thread_sel_tmp500_fu_33922_p3() {
sel_tmp500_fu_33922_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? word_buffer_0_3_1_reg_55284.read(): sel_tmp499_fu_33916_p3.read());
}
void a0_bin_conv::thread_sel_tmp501_fu_33934_p3() {
sel_tmp501_fu_33934_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_2_1_reg_53555.read(): ap_reg_pp0_iter2_word_buffer_0_4_2_1_reg_53258.read());
}
void a0_bin_conv::thread_sel_tmp502_fu_33939_p3() {
sel_tmp502_fu_33939_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_2_1_reg_53444.read(): sel_tmp501_fu_33934_p3.read());
}
void a0_bin_conv::thread_sel_tmp503_fu_33945_p3() {
sel_tmp503_fu_33945_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_2_1_reg_53345.read(): sel_tmp502_fu_33939_p3.read());
}
void a0_bin_conv::thread_sel_tmp504_fu_33957_p3() {
sel_tmp504_fu_33957_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_3_1_reg_53536.read(): ap_reg_pp0_iter2_word_buffer_0_4_3_1_reg_53245.read());
}
void a0_bin_conv::thread_sel_tmp505_fu_33962_p3() {
sel_tmp505_fu_33962_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_3_1_reg_53427.read(): sel_tmp504_fu_33957_p3.read());
}
void a0_bin_conv::thread_sel_tmp506_fu_33968_p3() {
sel_tmp506_fu_33968_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_3_1_reg_53330.read(): sel_tmp505_fu_33962_p3.read());
}
void a0_bin_conv::thread_sel_tmp507_fu_33980_p3() {
sel_tmp507_fu_33980_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_4_1_reg_53517.read(): ap_reg_pp0_iter2_word_buffer_0_4_4_1_reg_53232.read());
}
void a0_bin_conv::thread_sel_tmp508_fu_33985_p3() {
sel_tmp508_fu_33985_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_4_1_reg_53410.read(): sel_tmp507_fu_33980_p3.read());
}
void a0_bin_conv::thread_sel_tmp509_fu_33991_p3() {
sel_tmp509_fu_33991_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_4_1_reg_53315.read(): sel_tmp508_fu_33985_p3.read());
}
void a0_bin_conv::thread_sel_tmp510_fu_34003_p3() {
sel_tmp510_fu_34003_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_5_1_reg_53498.read(): ap_reg_pp0_iter2_word_buffer_0_4_5_1_reg_53219.read());
}
void a0_bin_conv::thread_sel_tmp511_fu_34008_p3() {
sel_tmp511_fu_34008_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_5_1_reg_53393.read(): sel_tmp510_fu_34003_p3.read());
}
void a0_bin_conv::thread_sel_tmp512_fu_34014_p3() {
sel_tmp512_fu_34014_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_5_1_reg_53300.read(): sel_tmp511_fu_34008_p3.read());
}
void a0_bin_conv::thread_sel_tmp513_fu_34026_p3() {
sel_tmp513_fu_34026_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_6_1_reg_53479.read(): ap_reg_pp0_iter2_word_buffer_0_4_6_1_reg_53206.read());
}
void a0_bin_conv::thread_sel_tmp514_fu_34031_p3() {
sel_tmp514_fu_34031_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_6_1_reg_53376.read(): sel_tmp513_fu_34026_p3.read());
}
void a0_bin_conv::thread_sel_tmp515_fu_34037_p3() {
sel_tmp515_fu_34037_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_6_1_reg_53285.read(): sel_tmp514_fu_34031_p3.read());
}
void a0_bin_conv::thread_sel_tmp516_fu_34049_p3() {
sel_tmp516_fu_34049_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_7_1_reg_53461.read(): ap_reg_pp0_iter2_word_buffer_0_4_7_1_reg_53194.read());
}
void a0_bin_conv::thread_sel_tmp517_fu_34054_p3() {
sel_tmp517_fu_34054_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_7_1_reg_53360.read(): sel_tmp516_fu_34049_p3.read());
}
void a0_bin_conv::thread_sel_tmp518_fu_34060_p3() {
sel_tmp518_fu_34060_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_7_1_reg_53271.read(): sel_tmp517_fu_34054_p3.read());
}
void a0_bin_conv::thread_sel_tmp519_fu_34072_p3() {
sel_tmp519_fu_34072_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? word_buffer_0_2_0_1_reg_55388.read(): word_buffer_0_5_0_1_reg_55221.read());
}
void a0_bin_conv::thread_sel_tmp520_fu_34077_p3() {
sel_tmp520_fu_34077_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? word_buffer_0_3_0_1_reg_55326.read(): sel_tmp519_fu_34072_p3.read());
}
void a0_bin_conv::thread_sel_tmp521_fu_34083_p3() {
sel_tmp521_fu_34083_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? word_buffer_0_4_0_1_reg_55270.read(): sel_tmp520_fu_34077_p3.read());
}
void a0_bin_conv::thread_sel_tmp522_fu_34095_p3() {
sel_tmp522_fu_34095_p3 = (!tmp_175_reg_51563.read()[0].is_01())? sc_lv<2>(): ((tmp_175_reg_51563.read()[0].to_bool())? ap_const_lv2_0: word_buffer_0_4_0_reg_55244.read());
}
void a0_bin_conv::thread_sel_tmp523_fu_34101_p3() {
sel_tmp523_fu_34101_p3 = (!sel_tmp110_reg_51569.read()[0].is_01())? sc_lv<2>(): ((sel_tmp110_reg_51569.read()[0].to_bool())? word_buffer_0_1_0_reg_55417.read(): sel_tmp522_fu_34095_p3.read());
}
void a0_bin_conv::thread_sel_tmp524_fu_34107_p3() {
sel_tmp524_fu_34107_p3 = (!sel_tmp111_reg_51575.read()[0].is_01())? sc_lv<2>(): ((sel_tmp111_reg_51575.read()[0].to_bool())? word_buffer_0_2_0_reg_55355.read(): sel_tmp523_fu_34101_p3.read());
}
void a0_bin_conv::thread_sel_tmp525_fu_28494_p3() {
sel_tmp525_fu_28494_p3 = (!tmp_165_reg_50824.read()[0].is_01())? sc_lv<2>(): ((tmp_165_reg_50824.read()[0].to_bool())? old_word_buffer_0_5_11_fu_1522.read(): old_word_buffer_0_7_10_fu_1594.read());
}
void a0_bin_conv::thread_sel_tmp526_fu_28514_p3() {
sel_tmp526_fu_28514_p3 = (!tmp_165_reg_50824.read()[0].is_01())? sc_lv<2>(): ((tmp_165_reg_50824.read()[0].to_bool())? old_word_buffer_0_5_13_fu_1530.read(): old_word_buffer_0_7_12_fu_1602.read());
}
void a0_bin_conv::thread_sel_tmp527_fu_28534_p3() {
sel_tmp527_fu_28534_p3 = (!tmp_165_reg_50824.read()[0].is_01())? sc_lv<2>(): ((tmp_165_reg_50824.read()[0].to_bool())? old_word_buffer_0_5_15_fu_1538.read(): old_word_buffer_0_7_14_fu_1610.read());
}
void a0_bin_conv::thread_sel_tmp528_fu_24036_p3() {
sel_tmp528_fu_24036_p3 = (!tmp_165_reg_50824.read()[0].is_01())? sc_lv<2>(): ((tmp_165_reg_50824.read()[0].to_bool())? old_word_buffer_0_5_17_fu_1546.read(): old_word_buffer_0_7_16_fu_1618.read());
}
void a0_bin_conv::thread_sel_tmp529_fu_28561_p2() {
sel_tmp529_fu_28561_p2 = (brmerge22_fu_28557_p2.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp530_fu_28567_p2() {
sel_tmp530_fu_28567_p2 = (tmp_166_reg_50838.read() & sel_tmp529_fu_28561_p2.read());
}
void a0_bin_conv::thread_sel_tmp531_fu_28572_p3() {
sel_tmp531_fu_28572_p3 = (!sel_tmp530_fu_28567_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp530_fu_28567_p2.read()[0].to_bool())? old_word_buffer_0_6_fu_682.read(): old_word_buffer_0_7_fu_686.read());
}
void a0_bin_conv::thread_sel_tmp532_fu_28580_p2() {
sel_tmp532_fu_28580_p2 = (tmp_165_reg_50824.read() & sel_tmp529_fu_28561_p2.read());
}
void a0_bin_conv::thread_sel_tmp533_fu_28585_p3() {
sel_tmp533_fu_28585_p3 = (!sel_tmp532_fu_28580_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp532_fu_28580_p2.read()[0].to_bool())? old_word_buffer_0_5_fu_678.read(): sel_tmp531_fu_28572_p3.read());
}
void a0_bin_conv::thread_sel_tmp534_fu_34123_p3() {
sel_tmp534_fu_34123_p3 = (!sel_tmp113_reg_51587.read()[0].is_01())? sc_lv<2>(): ((sel_tmp113_reg_51587.read()[0].to_bool())? word_buffer_0_1_1_reg_55405.read(): word_buffer_0_5_1_reg_55191.read());
}
void a0_bin_conv::thread_sel_tmp535_fu_34128_p3() {
sel_tmp535_fu_34128_p3 = (!sel_tmp114_reg_51607.read()[0].is_01())? sc_lv<2>(): ((sel_tmp114_reg_51607.read()[0].to_bool())? word_buffer_0_2_1_reg_55342.read(): sel_tmp534_fu_34123_p3.read());
}
void a0_bin_conv::thread_sel_tmp536_fu_34134_p3() {
sel_tmp536_fu_34134_p3 = (!sel_tmp115_reg_51627.read()[0].is_01())? sc_lv<2>(): ((sel_tmp115_reg_51627.read()[0].to_bool())? word_buffer_0_3_1_reg_55284.read(): sel_tmp535_fu_34128_p3.read());
}
void a0_bin_conv::thread_sel_tmp537_fu_34140_p3() {
sel_tmp537_fu_34140_p3 = (!sel_tmp116_reg_51647.read()[0].is_01())? sc_lv<2>(): ((sel_tmp116_reg_51647.read()[0].to_bool())? word_buffer_0_4_1_reg_55233.read(): sel_tmp536_fu_34134_p3.read());
}
void a0_bin_conv::thread_sel_tmp538_fu_34152_p3() {
sel_tmp538_fu_34152_p3 = (!sel_tmp113_reg_51587.read()[0].is_01())? sc_lv<2>(): ((sel_tmp113_reg_51587.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_2_1_reg_53555.read(): ap_reg_pp0_iter2_word_buffer_0_5_2_1_reg_53183.read());
}
void a0_bin_conv::thread_sel_tmp539_fu_34157_p3() {
sel_tmp539_fu_34157_p3 = (!sel_tmp114_reg_51607.read()[0].is_01())? sc_lv<2>(): ((sel_tmp114_reg_51607.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_2_1_reg_53444.read(): sel_tmp538_fu_34152_p3.read());
}
void a0_bin_conv::thread_sel_tmp540_fu_34163_p3() {
sel_tmp540_fu_34163_p3 = (!sel_tmp115_reg_51627.read()[0].is_01())? sc_lv<2>(): ((sel_tmp115_reg_51627.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_2_1_reg_53345.read(): sel_tmp539_fu_34157_p3.read());
}
void a0_bin_conv::thread_sel_tmp541_fu_34169_p3() {
sel_tmp541_fu_34169_p3 = (!sel_tmp116_reg_51647.read()[0].is_01())? sc_lv<2>(): ((sel_tmp116_reg_51647.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_2_1_reg_53258.read(): sel_tmp540_fu_34163_p3.read());
}
void a0_bin_conv::thread_sel_tmp542_fu_34181_p3() {
sel_tmp542_fu_34181_p3 = (!sel_tmp113_reg_51587.read()[0].is_01())? sc_lv<2>(): ((sel_tmp113_reg_51587.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_3_1_reg_53536.read(): ap_reg_pp0_iter2_word_buffer_0_5_3_1_reg_53172.read());
}
void a0_bin_conv::thread_sel_tmp543_fu_34186_p3() {
sel_tmp543_fu_34186_p3 = (!sel_tmp114_reg_51607.read()[0].is_01())? sc_lv<2>(): ((sel_tmp114_reg_51607.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_3_1_reg_53427.read(): sel_tmp542_fu_34181_p3.read());
}
void a0_bin_conv::thread_sel_tmp544_fu_34192_p3() {
sel_tmp544_fu_34192_p3 = (!sel_tmp115_reg_51627.read()[0].is_01())? sc_lv<2>(): ((sel_tmp115_reg_51627.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_3_1_reg_53330.read(): sel_tmp543_fu_34186_p3.read());
}
void a0_bin_conv::thread_sel_tmp545_fu_34198_p3() {
sel_tmp545_fu_34198_p3 = (!sel_tmp116_reg_51647.read()[0].is_01())? sc_lv<2>(): ((sel_tmp116_reg_51647.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_3_1_reg_53245.read(): sel_tmp544_fu_34192_p3.read());
}
void a0_bin_conv::thread_sel_tmp546_fu_34210_p3() {
sel_tmp546_fu_34210_p3 = (!sel_tmp113_reg_51587.read()[0].is_01())? sc_lv<2>(): ((sel_tmp113_reg_51587.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_4_1_reg_53517.read(): ap_reg_pp0_iter2_word_buffer_0_5_4_1_reg_53161.read());
}
void a0_bin_conv::thread_sel_tmp547_fu_34215_p3() {
sel_tmp547_fu_34215_p3 = (!sel_tmp114_reg_51607.read()[0].is_01())? sc_lv<2>(): ((sel_tmp114_reg_51607.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_4_1_reg_53410.read(): sel_tmp546_fu_34210_p3.read());
}
void a0_bin_conv::thread_sel_tmp548_fu_34221_p3() {
sel_tmp548_fu_34221_p3 = (!sel_tmp115_reg_51627.read()[0].is_01())? sc_lv<2>(): ((sel_tmp115_reg_51627.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_4_1_reg_53315.read(): sel_tmp547_fu_34215_p3.read());
}
void a0_bin_conv::thread_sel_tmp549_fu_34227_p3() {
sel_tmp549_fu_34227_p3 = (!sel_tmp116_reg_51647.read()[0].is_01())? sc_lv<2>(): ((sel_tmp116_reg_51647.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_4_1_reg_53232.read(): sel_tmp548_fu_34221_p3.read());
}
void a0_bin_conv::thread_sel_tmp550_fu_34239_p3() {
sel_tmp550_fu_34239_p3 = (!sel_tmp113_reg_51587.read()[0].is_01())? sc_lv<2>(): ((sel_tmp113_reg_51587.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_5_1_reg_53498.read(): ap_reg_pp0_iter2_word_buffer_0_5_5_1_reg_53150.read());
}
void a0_bin_conv::thread_sel_tmp551_fu_34244_p3() {
sel_tmp551_fu_34244_p3 = (!sel_tmp114_reg_51607.read()[0].is_01())? sc_lv<2>(): ((sel_tmp114_reg_51607.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_5_1_reg_53393.read(): sel_tmp550_fu_34239_p3.read());
}
void a0_bin_conv::thread_sel_tmp552_fu_34250_p3() {
sel_tmp552_fu_34250_p3 = (!sel_tmp115_reg_51627.read()[0].is_01())? sc_lv<2>(): ((sel_tmp115_reg_51627.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_5_1_reg_53300.read(): sel_tmp551_fu_34244_p3.read());
}
void a0_bin_conv::thread_sel_tmp553_fu_34256_p3() {
sel_tmp553_fu_34256_p3 = (!sel_tmp116_reg_51647.read()[0].is_01())? sc_lv<2>(): ((sel_tmp116_reg_51647.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_5_1_reg_53219.read(): sel_tmp552_fu_34250_p3.read());
}
void a0_bin_conv::thread_sel_tmp554_fu_34268_p3() {
sel_tmp554_fu_34268_p3 = (!sel_tmp113_reg_51587.read()[0].is_01())? sc_lv<2>(): ((sel_tmp113_reg_51587.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_6_1_reg_53479.read(): ap_reg_pp0_iter2_word_buffer_0_5_6_1_reg_53139.read());
}
void a0_bin_conv::thread_sel_tmp555_fu_34273_p3() {
sel_tmp555_fu_34273_p3 = (!sel_tmp114_reg_51607.read()[0].is_01())? sc_lv<2>(): ((sel_tmp114_reg_51607.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_6_1_reg_53376.read(): sel_tmp554_fu_34268_p3.read());
}
void a0_bin_conv::thread_sel_tmp556_fu_34279_p3() {
sel_tmp556_fu_34279_p3 = (!sel_tmp115_reg_51627.read()[0].is_01())? sc_lv<2>(): ((sel_tmp115_reg_51627.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_6_1_reg_53285.read(): sel_tmp555_fu_34273_p3.read());
}
void a0_bin_conv::thread_sel_tmp557_fu_34285_p3() {
sel_tmp557_fu_34285_p3 = (!sel_tmp116_reg_51647.read()[0].is_01())? sc_lv<2>(): ((sel_tmp116_reg_51647.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_6_1_reg_53206.read(): sel_tmp556_fu_34279_p3.read());
}
void a0_bin_conv::thread_sel_tmp558_fu_34297_p3() {
sel_tmp558_fu_34297_p3 = (!sel_tmp113_reg_51587.read()[0].is_01())? sc_lv<2>(): ((sel_tmp113_reg_51587.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_7_1_reg_53461.read(): ap_reg_pp0_iter2_word_buffer_0_5_7_1_reg_53129.read());
}
void a0_bin_conv::thread_sel_tmp559_fu_34302_p3() {
sel_tmp559_fu_34302_p3 = (!sel_tmp114_reg_51607.read()[0].is_01())? sc_lv<2>(): ((sel_tmp114_reg_51607.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_7_1_reg_53360.read(): sel_tmp558_fu_34297_p3.read());
}
void a0_bin_conv::thread_sel_tmp560_fu_34308_p3() {
sel_tmp560_fu_34308_p3 = (!sel_tmp115_reg_51627.read()[0].is_01())? sc_lv<2>(): ((sel_tmp115_reg_51627.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_7_1_reg_53271.read(): sel_tmp559_fu_34302_p3.read());
}
void a0_bin_conv::thread_sel_tmp561_fu_34314_p3() {
sel_tmp561_fu_34314_p3 = (!sel_tmp116_reg_51647.read()[0].is_01())? sc_lv<2>(): ((sel_tmp116_reg_51647.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_7_1_reg_53194.read(): sel_tmp560_fu_34308_p3.read());
}
void a0_bin_conv::thread_sel_tmp562_fu_34326_p3() {
sel_tmp562_fu_34326_p3 = (!sel_tmp113_reg_51587.read()[0].is_01())? sc_lv<2>(): ((sel_tmp113_reg_51587.read()[0].to_bool())? word_buffer_0_2_0_1_reg_55388.read(): word_buffer_0_6_0_1_reg_55181.read());
}
void a0_bin_conv::thread_sel_tmp563_fu_34331_p3() {
sel_tmp563_fu_34331_p3 = (!sel_tmp114_reg_51607.read()[0].is_01())? sc_lv<2>(): ((sel_tmp114_reg_51607.read()[0].to_bool())? word_buffer_0_3_0_1_reg_55326.read(): sel_tmp562_fu_34326_p3.read());
}
void a0_bin_conv::thread_sel_tmp564_fu_34337_p3() {
sel_tmp564_fu_34337_p3 = (!sel_tmp115_reg_51627.read()[0].is_01())? sc_lv<2>(): ((sel_tmp115_reg_51627.read()[0].to_bool())? word_buffer_0_4_0_1_reg_55270.read(): sel_tmp563_fu_34331_p3.read());
}
void a0_bin_conv::thread_sel_tmp565_fu_34343_p3() {
sel_tmp565_fu_34343_p3 = (!sel_tmp116_reg_51647.read()[0].is_01())? sc_lv<2>(): ((sel_tmp116_reg_51647.read()[0].to_bool())? word_buffer_0_5_0_1_reg_55221.read(): sel_tmp564_fu_34337_p3.read());
}
void a0_bin_conv::thread_sel_tmp566_fu_34355_p3() {
sel_tmp566_fu_34355_p3 = (!tmp_176_reg_51687.read()[0].is_01())? sc_lv<2>(): ((tmp_176_reg_51687.read()[0].to_bool())? ap_const_lv2_0: word_buffer_0_5_0_reg_55200.read());
}
void a0_bin_conv::thread_sel_tmp567_fu_34361_p3() {
sel_tmp567_fu_34361_p3 = (!sel_tmp120_reg_51693.read()[0].is_01())? sc_lv<2>(): ((sel_tmp120_reg_51693.read()[0].to_bool())? word_buffer_0_1_0_reg_55417.read(): sel_tmp566_fu_34355_p3.read());
}
void a0_bin_conv::thread_sel_tmp568_fu_34367_p3() {
sel_tmp568_fu_34367_p3 = (!sel_tmp121_reg_51699.read()[0].is_01())? sc_lv<2>(): ((sel_tmp121_reg_51699.read()[0].to_bool())? word_buffer_0_2_0_reg_55355.read(): sel_tmp567_fu_34361_p3.read());
}
void a0_bin_conv::thread_sel_tmp569_fu_34373_p3() {
sel_tmp569_fu_34373_p3 = (!sel_tmp122_reg_51705.read()[0].is_01())? sc_lv<2>(): ((sel_tmp122_reg_51705.read()[0].to_bool())? word_buffer_0_3_0_reg_55296.read(): sel_tmp568_fu_34367_p3.read());
}
void a0_bin_conv::thread_sel_tmp570_fu_34395_p3() {
sel_tmp570_fu_34395_p3 = (!sel_tmp124_reg_51717.read()[0].is_01())? sc_lv<2>(): ((sel_tmp124_reg_51717.read()[0].to_bool())? word_buffer_0_1_1_reg_55405.read(): word_buffer_0_6_1_reg_55157.read());
}
void a0_bin_conv::thread_sel_tmp571_fu_34400_p3() {
sel_tmp571_fu_34400_p3 = (!sel_tmp125_reg_51737.read()[0].is_01())? sc_lv<2>(): ((sel_tmp125_reg_51737.read()[0].to_bool())? word_buffer_0_2_1_reg_55342.read(): sel_tmp570_fu_34395_p3.read());
}
void a0_bin_conv::thread_sel_tmp572_fu_34406_p3() {
sel_tmp572_fu_34406_p3 = (!sel_tmp126_reg_51757.read()[0].is_01())? sc_lv<2>(): ((sel_tmp126_reg_51757.read()[0].to_bool())? word_buffer_0_3_1_reg_55284.read(): sel_tmp571_fu_34400_p3.read());
}
void a0_bin_conv::thread_sel_tmp573_fu_34412_p3() {
sel_tmp573_fu_34412_p3 = (!sel_tmp127_reg_51777.read()[0].is_01())? sc_lv<2>(): ((sel_tmp127_reg_51777.read()[0].to_bool())? word_buffer_0_4_1_reg_55233.read(): sel_tmp572_fu_34406_p3.read());
}
void a0_bin_conv::thread_sel_tmp574_fu_34418_p3() {
sel_tmp574_fu_34418_p3 = (!sel_tmp128_reg_51797.read()[0].is_01())? sc_lv<2>(): ((sel_tmp128_reg_51797.read()[0].to_bool())? word_buffer_0_5_1_reg_55191.read(): sel_tmp573_fu_34412_p3.read());
}
void a0_bin_conv::thread_sel_tmp575_fu_34430_p3() {
sel_tmp575_fu_34430_p3 = (!sel_tmp124_reg_51717.read()[0].is_01())? sc_lv<2>(): ((sel_tmp124_reg_51717.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_2_1_reg_53555.read(): ap_reg_pp0_iter2_word_buffer_0_6_2_1_reg_53120.read());
}
void a0_bin_conv::thread_sel_tmp576_fu_34435_p3() {
sel_tmp576_fu_34435_p3 = (!sel_tmp125_reg_51737.read()[0].is_01())? sc_lv<2>(): ((sel_tmp125_reg_51737.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_2_1_reg_53444.read(): sel_tmp575_fu_34430_p3.read());
}
void a0_bin_conv::thread_sel_tmp577_fu_34441_p3() {
sel_tmp577_fu_34441_p3 = (!sel_tmp126_reg_51757.read()[0].is_01())? sc_lv<2>(): ((sel_tmp126_reg_51757.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_2_1_reg_53345.read(): sel_tmp576_fu_34435_p3.read());
}
void a0_bin_conv::thread_sel_tmp578_fu_34447_p3() {
sel_tmp578_fu_34447_p3 = (!sel_tmp127_reg_51777.read()[0].is_01())? sc_lv<2>(): ((sel_tmp127_reg_51777.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_2_1_reg_53258.read(): sel_tmp577_fu_34441_p3.read());
}
void a0_bin_conv::thread_sel_tmp579_fu_34453_p3() {
sel_tmp579_fu_34453_p3 = (!sel_tmp128_reg_51797.read()[0].is_01())? sc_lv<2>(): ((sel_tmp128_reg_51797.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_5_2_1_reg_53183.read(): sel_tmp578_fu_34447_p3.read());
}
void a0_bin_conv::thread_sel_tmp580_fu_34465_p3() {
sel_tmp580_fu_34465_p3 = (!sel_tmp124_reg_51717.read()[0].is_01())? sc_lv<2>(): ((sel_tmp124_reg_51717.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_3_1_reg_53536.read(): ap_reg_pp0_iter2_word_buffer_0_6_3_1_reg_53111.read());
}
void a0_bin_conv::thread_sel_tmp581_fu_34470_p3() {
sel_tmp581_fu_34470_p3 = (!sel_tmp125_reg_51737.read()[0].is_01())? sc_lv<2>(): ((sel_tmp125_reg_51737.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_3_1_reg_53427.read(): sel_tmp580_fu_34465_p3.read());
}
void a0_bin_conv::thread_sel_tmp582_fu_34476_p3() {
sel_tmp582_fu_34476_p3 = (!sel_tmp126_reg_51757.read()[0].is_01())? sc_lv<2>(): ((sel_tmp126_reg_51757.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_3_1_reg_53330.read(): sel_tmp581_fu_34470_p3.read());
}
void a0_bin_conv::thread_sel_tmp583_fu_34482_p3() {
sel_tmp583_fu_34482_p3 = (!sel_tmp127_reg_51777.read()[0].is_01())? sc_lv<2>(): ((sel_tmp127_reg_51777.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_3_1_reg_53245.read(): sel_tmp582_fu_34476_p3.read());
}
void a0_bin_conv::thread_sel_tmp584_fu_34488_p3() {
sel_tmp584_fu_34488_p3 = (!sel_tmp128_reg_51797.read()[0].is_01())? sc_lv<2>(): ((sel_tmp128_reg_51797.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_5_3_1_reg_53172.read(): sel_tmp583_fu_34482_p3.read());
}
void a0_bin_conv::thread_sel_tmp585_fu_34500_p3() {
sel_tmp585_fu_34500_p3 = (!sel_tmp124_reg_51717.read()[0].is_01())? sc_lv<2>(): ((sel_tmp124_reg_51717.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_4_1_reg_53517.read(): ap_reg_pp0_iter2_word_buffer_0_6_4_1_reg_53102.read());
}
void a0_bin_conv::thread_sel_tmp586_fu_34505_p3() {
sel_tmp586_fu_34505_p3 = (!sel_tmp125_reg_51737.read()[0].is_01())? sc_lv<2>(): ((sel_tmp125_reg_51737.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_4_1_reg_53410.read(): sel_tmp585_fu_34500_p3.read());
}
void a0_bin_conv::thread_sel_tmp587_fu_34511_p3() {
sel_tmp587_fu_34511_p3 = (!sel_tmp126_reg_51757.read()[0].is_01())? sc_lv<2>(): ((sel_tmp126_reg_51757.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_4_1_reg_53315.read(): sel_tmp586_fu_34505_p3.read());
}
void a0_bin_conv::thread_sel_tmp588_fu_34517_p3() {
sel_tmp588_fu_34517_p3 = (!sel_tmp127_reg_51777.read()[0].is_01())? sc_lv<2>(): ((sel_tmp127_reg_51777.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_4_1_reg_53232.read(): sel_tmp587_fu_34511_p3.read());
}
void a0_bin_conv::thread_sel_tmp589_fu_34523_p3() {
sel_tmp589_fu_34523_p3 = (!sel_tmp128_reg_51797.read()[0].is_01())? sc_lv<2>(): ((sel_tmp128_reg_51797.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_5_4_1_reg_53161.read(): sel_tmp588_fu_34517_p3.read());
}
void a0_bin_conv::thread_sel_tmp590_fu_34535_p3() {
sel_tmp590_fu_34535_p3 = (!sel_tmp124_reg_51717.read()[0].is_01())? sc_lv<2>(): ((sel_tmp124_reg_51717.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_5_1_reg_53498.read(): ap_reg_pp0_iter2_word_buffer_0_6_5_1_reg_53093.read());
}
void a0_bin_conv::thread_sel_tmp591_fu_34540_p3() {
sel_tmp591_fu_34540_p3 = (!sel_tmp125_reg_51737.read()[0].is_01())? sc_lv<2>(): ((sel_tmp125_reg_51737.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_5_1_reg_53393.read(): sel_tmp590_fu_34535_p3.read());
}
void a0_bin_conv::thread_sel_tmp592_fu_34546_p3() {
sel_tmp592_fu_34546_p3 = (!sel_tmp126_reg_51757.read()[0].is_01())? sc_lv<2>(): ((sel_tmp126_reg_51757.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_5_1_reg_53300.read(): sel_tmp591_fu_34540_p3.read());
}
void a0_bin_conv::thread_sel_tmp593_fu_34552_p3() {
sel_tmp593_fu_34552_p3 = (!sel_tmp127_reg_51777.read()[0].is_01())? sc_lv<2>(): ((sel_tmp127_reg_51777.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_5_1_reg_53219.read(): sel_tmp592_fu_34546_p3.read());
}
void a0_bin_conv::thread_sel_tmp594_fu_34558_p3() {
sel_tmp594_fu_34558_p3 = (!sel_tmp128_reg_51797.read()[0].is_01())? sc_lv<2>(): ((sel_tmp128_reg_51797.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_5_5_1_reg_53150.read(): sel_tmp593_fu_34552_p3.read());
}
void a0_bin_conv::thread_sel_tmp595_fu_34570_p3() {
sel_tmp595_fu_34570_p3 = (!sel_tmp124_reg_51717.read()[0].is_01())? sc_lv<2>(): ((sel_tmp124_reg_51717.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_6_1_reg_53479.read(): ap_reg_pp0_iter2_word_buffer_0_6_6_1_reg_53084.read());
}
void a0_bin_conv::thread_sel_tmp596_fu_34575_p3() {
sel_tmp596_fu_34575_p3 = (!sel_tmp125_reg_51737.read()[0].is_01())? sc_lv<2>(): ((sel_tmp125_reg_51737.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_6_1_reg_53376.read(): sel_tmp595_fu_34570_p3.read());
}
void a0_bin_conv::thread_sel_tmp597_fu_34581_p3() {
sel_tmp597_fu_34581_p3 = (!sel_tmp126_reg_51757.read()[0].is_01())? sc_lv<2>(): ((sel_tmp126_reg_51757.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_6_1_reg_53285.read(): sel_tmp596_fu_34575_p3.read());
}
void a0_bin_conv::thread_sel_tmp598_fu_34587_p3() {
sel_tmp598_fu_34587_p3 = (!sel_tmp127_reg_51777.read()[0].is_01())? sc_lv<2>(): ((sel_tmp127_reg_51777.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_6_1_reg_53206.read(): sel_tmp597_fu_34581_p3.read());
}
void a0_bin_conv::thread_sel_tmp599_fu_34593_p3() {
sel_tmp599_fu_34593_p3 = (!sel_tmp128_reg_51797.read()[0].is_01())? sc_lv<2>(): ((sel_tmp128_reg_51797.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_5_6_1_reg_53139.read(): sel_tmp598_fu_34587_p3.read());
}
void a0_bin_conv::thread_sel_tmp600_fu_34605_p3() {
sel_tmp600_fu_34605_p3 = (!sel_tmp124_reg_51717.read()[0].is_01())? sc_lv<2>(): ((sel_tmp124_reg_51717.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_1_7_1_reg_53461.read(): ap_reg_pp0_iter2_word_buffer_0_6_7_1_reg_53076.read());
}
void a0_bin_conv::thread_sel_tmp601_fu_34610_p3() {
sel_tmp601_fu_34610_p3 = (!sel_tmp125_reg_51737.read()[0].is_01())? sc_lv<2>(): ((sel_tmp125_reg_51737.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_2_7_1_reg_53360.read(): sel_tmp600_fu_34605_p3.read());
}
void a0_bin_conv::thread_sel_tmp602_fu_34616_p3() {
sel_tmp602_fu_34616_p3 = (!sel_tmp126_reg_51757.read()[0].is_01())? sc_lv<2>(): ((sel_tmp126_reg_51757.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_3_7_1_reg_53271.read(): sel_tmp601_fu_34610_p3.read());
}
void a0_bin_conv::thread_sel_tmp603_fu_34622_p3() {
sel_tmp603_fu_34622_p3 = (!sel_tmp127_reg_51777.read()[0].is_01())? sc_lv<2>(): ((sel_tmp127_reg_51777.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_4_7_1_reg_53194.read(): sel_tmp602_fu_34616_p3.read());
}
void a0_bin_conv::thread_sel_tmp604_fu_34628_p3() {
sel_tmp604_fu_34628_p3 = (!sel_tmp128_reg_51797.read()[0].is_01())? sc_lv<2>(): ((sel_tmp128_reg_51797.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_0_5_7_1_reg_53129.read(): sel_tmp603_fu_34622_p3.read());
}
void a0_bin_conv::thread_sel_tmp605_fu_34640_p3() {
sel_tmp605_fu_34640_p3 = (!sel_tmp124_reg_51717.read()[0].is_01())? sc_lv<2>(): ((sel_tmp124_reg_51717.read()[0].to_bool())? word_buffer_0_2_0_1_reg_55388.read(): word_buffer_0_7_0_1_reg_55149.read());
}
void a0_bin_conv::thread_sel_tmp606_fu_34645_p3() {
sel_tmp606_fu_34645_p3 = (!sel_tmp125_reg_51737.read()[0].is_01())? sc_lv<2>(): ((sel_tmp125_reg_51737.read()[0].to_bool())? word_buffer_0_3_0_1_reg_55326.read(): sel_tmp605_fu_34640_p3.read());
}
void a0_bin_conv::thread_sel_tmp607_fu_34651_p3() {
sel_tmp607_fu_34651_p3 = (!sel_tmp126_reg_51757.read()[0].is_01())? sc_lv<2>(): ((sel_tmp126_reg_51757.read()[0].to_bool())? word_buffer_0_4_0_1_reg_55270.read(): sel_tmp606_fu_34645_p3.read());
}
void a0_bin_conv::thread_sel_tmp608_fu_34657_p3() {
sel_tmp608_fu_34657_p3 = (!sel_tmp127_reg_51777.read()[0].is_01())? sc_lv<2>(): ((sel_tmp127_reg_51777.read()[0].to_bool())? word_buffer_0_5_0_1_reg_55221.read(): sel_tmp607_fu_34651_p3.read());
}
void a0_bin_conv::thread_sel_tmp609_fu_34663_p3() {
sel_tmp609_fu_34663_p3 = (!sel_tmp128_reg_51797.read()[0].is_01())? sc_lv<2>(): ((sel_tmp128_reg_51797.read()[0].to_bool())? word_buffer_0_6_0_1_reg_55181.read(): sel_tmp608_fu_34657_p3.read());
}
void a0_bin_conv::thread_sel_tmp610_fu_34675_p3() {
sel_tmp610_fu_34675_p3 = (!tmp_177_reg_51837.read()[0].is_01())? sc_lv<2>(): ((tmp_177_reg_51837.read()[0].to_bool())? ap_const_lv2_0: word_buffer_0_6_0_reg_55164.read());
}
void a0_bin_conv::thread_sel_tmp611_fu_34681_p3() {
sel_tmp611_fu_34681_p3 = (!sel_tmp132_reg_51843.read()[0].is_01())? sc_lv<2>(): ((sel_tmp132_reg_51843.read()[0].to_bool())? word_buffer_0_1_0_reg_55417.read(): sel_tmp610_fu_34675_p3.read());
}
void a0_bin_conv::thread_sel_tmp612_fu_34687_p3() {
sel_tmp612_fu_34687_p3 = (!sel_tmp133_reg_51849.read()[0].is_01())? sc_lv<2>(): ((sel_tmp133_reg_51849.read()[0].to_bool())? word_buffer_0_2_0_reg_55355.read(): sel_tmp611_fu_34681_p3.read());
}
void a0_bin_conv::thread_sel_tmp613_fu_34693_p3() {
sel_tmp613_fu_34693_p3 = (!sel_tmp134_reg_51855.read()[0].is_01())? sc_lv<2>(): ((sel_tmp134_reg_51855.read()[0].to_bool())? word_buffer_0_3_0_reg_55296.read(): sel_tmp612_fu_34687_p3.read());
}
void a0_bin_conv::thread_sel_tmp614_fu_34699_p3() {
sel_tmp614_fu_34699_p3 = (!sel_tmp135_reg_51861.read()[0].is_01())? sc_lv<2>(): ((sel_tmp135_reg_51861.read()[0].to_bool())? word_buffer_0_4_0_reg_55244.read(): sel_tmp613_fu_34693_p3.read());
}
void a0_bin_conv::thread_sel_tmp615_fu_28709_p3() {
sel_tmp615_fu_28709_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_1_11_fu_1666.read(): old_word_buffer_1_7_11_fu_1882.read());
}
void a0_bin_conv::thread_sel_tmp616_fu_28716_p3() {
sel_tmp616_fu_28716_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_2_11_fu_1702.read(): sel_tmp615_fu_28709_p3.read());
}
void a0_bin_conv::thread_sel_tmp617_fu_28723_p3() {
sel_tmp617_fu_28723_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_3_11_fu_1738.read(): sel_tmp616_fu_28716_p3.read());
}
void a0_bin_conv::thread_sel_tmp618_fu_28730_p3() {
sel_tmp618_fu_28730_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_4_11_fu_1774.read(): sel_tmp617_fu_28723_p3.read());
}
void a0_bin_conv::thread_sel_tmp619_fu_28737_p3() {
sel_tmp619_fu_28737_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? old_word_buffer_1_5_11_fu_1810.read(): sel_tmp618_fu_28730_p3.read());
}
void a0_bin_conv::thread_sel_tmp620_fu_28751_p3() {
sel_tmp620_fu_28751_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_1_12_fu_1670.read(): old_word_buffer_1_7_12_fu_1886.read());
}
void a0_bin_conv::thread_sel_tmp621_fu_28758_p3() {
sel_tmp621_fu_28758_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_2_12_fu_1706.read(): sel_tmp620_fu_28751_p3.read());
}
void a0_bin_conv::thread_sel_tmp622_fu_28765_p3() {
sel_tmp622_fu_28765_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_3_12_fu_1742.read(): sel_tmp621_fu_28758_p3.read());
}
void a0_bin_conv::thread_sel_tmp623_fu_28772_p3() {
sel_tmp623_fu_28772_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_4_12_fu_1778.read(): sel_tmp622_fu_28765_p3.read());
}
void a0_bin_conv::thread_sel_tmp624_fu_28779_p3() {
sel_tmp624_fu_28779_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? old_word_buffer_1_5_12_fu_1814.read(): sel_tmp623_fu_28772_p3.read());
}
void a0_bin_conv::thread_sel_tmp625_fu_28793_p3() {
sel_tmp625_fu_28793_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_1_13_fu_1674.read(): old_word_buffer_1_7_13_fu_1890.read());
}
void a0_bin_conv::thread_sel_tmp626_fu_28800_p3() {
sel_tmp626_fu_28800_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_2_13_fu_1710.read(): sel_tmp625_fu_28793_p3.read());
}
void a0_bin_conv::thread_sel_tmp627_fu_28807_p3() {
sel_tmp627_fu_28807_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_3_13_fu_1746.read(): sel_tmp626_fu_28800_p3.read());
}
void a0_bin_conv::thread_sel_tmp628_fu_28814_p3() {
sel_tmp628_fu_28814_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_4_13_fu_1782.read(): sel_tmp627_fu_28807_p3.read());
}
void a0_bin_conv::thread_sel_tmp629_fu_28821_p3() {
sel_tmp629_fu_28821_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? old_word_buffer_1_5_13_fu_1818.read(): sel_tmp628_fu_28814_p3.read());
}
void a0_bin_conv::thread_sel_tmp630_fu_28835_p3() {
sel_tmp630_fu_28835_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_1_14_fu_1678.read(): old_word_buffer_1_7_14_fu_1894.read());
}
void a0_bin_conv::thread_sel_tmp631_fu_28842_p3() {
sel_tmp631_fu_28842_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_2_14_fu_1714.read(): sel_tmp630_fu_28835_p3.read());
}
void a0_bin_conv::thread_sel_tmp632_fu_28849_p3() {
sel_tmp632_fu_28849_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_3_14_fu_1750.read(): sel_tmp631_fu_28842_p3.read());
}
void a0_bin_conv::thread_sel_tmp633_fu_28856_p3() {
sel_tmp633_fu_28856_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_4_14_fu_1786.read(): sel_tmp632_fu_28849_p3.read());
}
void a0_bin_conv::thread_sel_tmp634_fu_28863_p3() {
sel_tmp634_fu_28863_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? old_word_buffer_1_5_14_fu_1822.read(): sel_tmp633_fu_28856_p3.read());
}
void a0_bin_conv::thread_sel_tmp635_fu_28877_p3() {
sel_tmp635_fu_28877_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_1_15_fu_1682.read(): old_word_buffer_1_7_15_fu_1898.read());
}
void a0_bin_conv::thread_sel_tmp636_fu_28884_p3() {
sel_tmp636_fu_28884_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_2_15_fu_1718.read(): sel_tmp635_fu_28877_p3.read());
}
void a0_bin_conv::thread_sel_tmp637_fu_28891_p3() {
sel_tmp637_fu_28891_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_3_15_fu_1754.read(): sel_tmp636_fu_28884_p3.read());
}
void a0_bin_conv::thread_sel_tmp638_fu_28898_p3() {
sel_tmp638_fu_28898_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_4_15_fu_1790.read(): sel_tmp637_fu_28891_p3.read());
}
void a0_bin_conv::thread_sel_tmp639_fu_28905_p3() {
sel_tmp639_fu_28905_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? old_word_buffer_1_5_15_fu_1826.read(): sel_tmp638_fu_28898_p3.read());
}
void a0_bin_conv::thread_sel_tmp640_fu_28919_p3() {
sel_tmp640_fu_28919_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_1_16_fu_1686.read(): old_word_buffer_1_7_16_fu_1902.read());
}
void a0_bin_conv::thread_sel_tmp641_fu_28926_p3() {
sel_tmp641_fu_28926_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_2_16_fu_1722.read(): sel_tmp640_fu_28919_p3.read());
}
void a0_bin_conv::thread_sel_tmp642_fu_28933_p3() {
sel_tmp642_fu_28933_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_3_16_fu_1758.read(): sel_tmp641_fu_28926_p3.read());
}
void a0_bin_conv::thread_sel_tmp643_fu_28940_p3() {
sel_tmp643_fu_28940_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_4_16_fu_1794.read(): sel_tmp642_fu_28933_p3.read());
}
void a0_bin_conv::thread_sel_tmp644_fu_28947_p3() {
sel_tmp644_fu_28947_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? old_word_buffer_1_5_16_fu_1830.read(): sel_tmp643_fu_28940_p3.read());
}
void a0_bin_conv::thread_sel_tmp645_fu_24059_p3() {
sel_tmp645_fu_24059_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_1_17_fu_1690.read(): old_word_buffer_1_7_17_fu_1906.read());
}
void a0_bin_conv::thread_sel_tmp646_fu_24066_p3() {
sel_tmp646_fu_24066_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_2_17_fu_1726.read(): sel_tmp645_fu_24059_p3.read());
}
void a0_bin_conv::thread_sel_tmp647_fu_24073_p3() {
sel_tmp647_fu_24073_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_3_17_fu_1762.read(): sel_tmp646_fu_24066_p3.read());
}
void a0_bin_conv::thread_sel_tmp648_fu_24080_p3() {
sel_tmp648_fu_24080_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_4_17_fu_1798.read(): sel_tmp647_fu_24073_p3.read());
}
void a0_bin_conv::thread_sel_tmp649_fu_24087_p3() {
sel_tmp649_fu_24087_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? old_word_buffer_1_5_17_fu_1834.read(): sel_tmp648_fu_24080_p3.read());
}
void a0_bin_conv::thread_sel_tmp650_fu_28961_p3() {
sel_tmp650_fu_28961_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_1_18_fu_1694.read(): old_word_buffer_1_7_42_reg_52212.read());
}
void a0_bin_conv::thread_sel_tmp651_fu_28967_p3() {
sel_tmp651_fu_28967_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_2_18_fu_1730.read(): sel_tmp650_fu_28961_p3.read());
}
void a0_bin_conv::thread_sel_tmp652_fu_28974_p3() {
sel_tmp652_fu_28974_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_3_18_fu_1766.read(): sel_tmp651_fu_28967_p3.read());
}
void a0_bin_conv::thread_sel_tmp653_fu_28981_p3() {
sel_tmp653_fu_28981_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_4_18_fu_1802.read(): sel_tmp652_fu_28974_p3.read());
}
void a0_bin_conv::thread_sel_tmp654_fu_28988_p3() {
sel_tmp654_fu_28988_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? old_word_buffer_1_5_18_fu_1838.read(): sel_tmp653_fu_28981_p3.read());
}
void a0_bin_conv::thread_sel_tmp655_fu_29143_p3() {
sel_tmp655_fu_29143_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_2_11_fu_1702.read(): old_word_buffer_1_7_11_fu_1882.read());
}
void a0_bin_conv::thread_sel_tmp656_fu_29150_p3() {
sel_tmp656_fu_29150_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_3_11_fu_1738.read(): sel_tmp655_fu_29143_p3.read());
}
void a0_bin_conv::thread_sel_tmp657_fu_29157_p3() {
sel_tmp657_fu_29157_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_4_11_fu_1774.read(): sel_tmp656_fu_29150_p3.read());
}
void a0_bin_conv::thread_sel_tmp658_fu_29164_p3() {
sel_tmp658_fu_29164_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_5_11_fu_1810.read(): sel_tmp657_fu_29157_p3.read());
}
void a0_bin_conv::thread_sel_tmp659_fu_34795_p3() {
sel_tmp659_fu_34795_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_2_29_reg_54309.read(): old_word_buffer_1_7_44_reg_54617.read());
}
void a0_bin_conv::thread_sel_tmp660_fu_34800_p3() {
sel_tmp660_fu_34800_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_3_29_reg_54350.read(): sel_tmp659_fu_34795_p3.read());
}
void a0_bin_conv::thread_sel_tmp661_fu_34806_p3() {
sel_tmp661_fu_34806_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_4_29_reg_54401.read(): sel_tmp660_fu_34800_p3.read());
}
void a0_bin_conv::thread_sel_tmp662_fu_34812_p3() {
sel_tmp662_fu_34812_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_5_29_reg_54462.read(): sel_tmp661_fu_34806_p3.read());
}
void a0_bin_conv::thread_sel_tmp663_fu_29178_p3() {
sel_tmp663_fu_29178_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_2_13_fu_1710.read(): old_word_buffer_1_7_13_fu_1890.read());
}
void a0_bin_conv::thread_sel_tmp664_fu_29185_p3() {
sel_tmp664_fu_29185_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_3_13_fu_1746.read(): sel_tmp663_fu_29178_p3.read());
}
void a0_bin_conv::thread_sel_tmp665_fu_29192_p3() {
sel_tmp665_fu_29192_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_4_13_fu_1782.read(): sel_tmp664_fu_29185_p3.read());
}
void a0_bin_conv::thread_sel_tmp666_fu_29199_p3() {
sel_tmp666_fu_29199_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_5_13_fu_1818.read(): sel_tmp665_fu_29192_p3.read());
}
void a0_bin_conv::thread_sel_tmp667_fu_34824_p3() {
sel_tmp667_fu_34824_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_2_30_reg_54317.read(): old_word_buffer_1_7_46_reg_54641.read());
}
void a0_bin_conv::thread_sel_tmp668_fu_34829_p3() {
sel_tmp668_fu_34829_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_3_30_reg_54360.read(): sel_tmp667_fu_34824_p3.read());
}
void a0_bin_conv::thread_sel_tmp669_fu_34835_p3() {
sel_tmp669_fu_34835_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_4_30_reg_54413.read(): sel_tmp668_fu_34829_p3.read());
}
void a0_bin_conv::thread_sel_tmp670_fu_34841_p3() {
sel_tmp670_fu_34841_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_5_30_reg_54476.read(): sel_tmp669_fu_34835_p3.read());
}
void a0_bin_conv::thread_sel_tmp671_fu_29213_p3() {
sel_tmp671_fu_29213_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_2_15_fu_1718.read(): old_word_buffer_1_7_15_fu_1898.read());
}
void a0_bin_conv::thread_sel_tmp672_fu_29220_p3() {
sel_tmp672_fu_29220_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_3_15_fu_1754.read(): sel_tmp671_fu_29213_p3.read());
}
void a0_bin_conv::thread_sel_tmp673_fu_29227_p3() {
sel_tmp673_fu_29227_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_4_15_fu_1790.read(): sel_tmp672_fu_29220_p3.read());
}
void a0_bin_conv::thread_sel_tmp674_fu_29234_p3() {
sel_tmp674_fu_29234_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_5_15_fu_1826.read(): sel_tmp673_fu_29227_p3.read());
}
void a0_bin_conv::thread_sel_tmp675_fu_34853_p3() {
sel_tmp675_fu_34853_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_2_31_reg_54325.read(): old_word_buffer_1_7_48_reg_54664.read());
}
void a0_bin_conv::thread_sel_tmp676_fu_34858_p3() {
sel_tmp676_fu_34858_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_3_31_reg_54370.read(): sel_tmp675_fu_34853_p3.read());
}
void a0_bin_conv::thread_sel_tmp677_fu_34864_p3() {
sel_tmp677_fu_34864_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_4_31_reg_54425.read(): sel_tmp676_fu_34858_p3.read());
}
void a0_bin_conv::thread_sel_tmp678_fu_34870_p3() {
sel_tmp678_fu_34870_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_5_31_reg_54490.read(): sel_tmp677_fu_34864_p3.read());
}
void a0_bin_conv::thread_sel_tmp679_fu_24104_p3() {
sel_tmp679_fu_24104_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_2_17_fu_1726.read(): old_word_buffer_1_7_17_fu_1906.read());
}
void a0_bin_conv::thread_sel_tmp680_fu_24111_p3() {
sel_tmp680_fu_24111_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_3_17_fu_1762.read(): sel_tmp679_fu_24104_p3.read());
}
void a0_bin_conv::thread_sel_tmp681_fu_24118_p3() {
sel_tmp681_fu_24118_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_4_17_fu_1798.read(): sel_tmp680_fu_24111_p3.read());
}
void a0_bin_conv::thread_sel_tmp682_fu_24125_p3() {
sel_tmp682_fu_24125_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_5_17_fu_1834.read(): sel_tmp681_fu_24118_p3.read());
}
void a0_bin_conv::thread_sel_tmp683_fu_34882_p3() {
sel_tmp683_fu_34882_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_2_32_reg_54333.read(): ap_reg_pp0_iter2_old_word_buffer_1_7_42_reg_52212.read());
}
void a0_bin_conv::thread_sel_tmp684_fu_34887_p3() {
sel_tmp684_fu_34887_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_3_32_reg_54380.read(): sel_tmp683_fu_34882_p3.read());
}
void a0_bin_conv::thread_sel_tmp685_fu_34893_p3() {
sel_tmp685_fu_34893_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_4_32_reg_54437.read(): sel_tmp684_fu_34887_p3.read());
}
void a0_bin_conv::thread_sel_tmp686_fu_34899_p3() {
sel_tmp686_fu_34899_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? old_word_buffer_1_5_32_reg_54504.read(): sel_tmp685_fu_34893_p3.read());
}
void a0_bin_conv::thread_sel_tmp687_fu_29248_p3() {
sel_tmp687_fu_29248_p3 = (!tmp_1225_reg_45756.read()[0].is_01())? sc_lv<2>(): ((tmp_1225_reg_45756.read()[0].to_bool())? old_word_buffer_1_7_fu_714.read(): ap_const_lv2_0);
}
void a0_bin_conv::thread_sel_tmp688_fu_29255_p3() {
sel_tmp688_fu_29255_p3 = (!sel_tmp79_reg_51283.read()[0].is_01())? sc_lv<2>(): ((sel_tmp79_reg_51283.read()[0].to_bool())? old_word_buffer_1_3_fu_698.read(): sel_tmp687_fu_29248_p3.read());
}
void a0_bin_conv::thread_sel_tmp689_fu_29262_p3() {
sel_tmp689_fu_29262_p3 = (!sel_tmp80_reg_51289.read()[0].is_01())? sc_lv<2>(): ((sel_tmp80_reg_51289.read()[0].to_bool())? old_word_buffer_1_4_fu_702.read(): sel_tmp688_fu_29255_p3.read());
}
void a0_bin_conv::thread_sel_tmp690_fu_29269_p3() {
sel_tmp690_fu_29269_p3 = (!sel_tmp81_reg_51295.read()[0].is_01())? sc_lv<2>(): ((sel_tmp81_reg_51295.read()[0].to_bool())? old_word_buffer_1_5_fu_706.read(): sel_tmp689_fu_29262_p3.read());
}
void a0_bin_conv::thread_sel_tmp691_fu_29276_p3() {
sel_tmp691_fu_29276_p3 = (!sel_tmp82_reg_51301.read()[0].is_01())? sc_lv<2>(): ((sel_tmp82_reg_51301.read()[0].to_bool())? old_word_buffer_1_6_fu_710.read(): sel_tmp690_fu_29269_p3.read());
}
void a0_bin_conv::thread_sel_tmp692_fu_29364_p3() {
sel_tmp692_fu_29364_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_3_11_fu_1738.read(): old_word_buffer_1_7_11_fu_1882.read());
}
void a0_bin_conv::thread_sel_tmp693_fu_29371_p3() {
sel_tmp693_fu_29371_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_4_11_fu_1774.read(): sel_tmp692_fu_29364_p3.read());
}
void a0_bin_conv::thread_sel_tmp694_fu_29378_p3() {
sel_tmp694_fu_29378_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_5_11_fu_1810.read(): sel_tmp693_fu_29371_p3.read());
}
void a0_bin_conv::thread_sel_tmp695_fu_34961_p3() {
sel_tmp695_fu_34961_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_3_29_reg_54350.read(): old_word_buffer_1_7_44_reg_54617.read());
}
void a0_bin_conv::thread_sel_tmp696_fu_34966_p3() {
sel_tmp696_fu_34966_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_4_29_reg_54401.read(): sel_tmp695_fu_34961_p3.read());
}
void a0_bin_conv::thread_sel_tmp697_fu_34972_p3() {
sel_tmp697_fu_34972_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_5_29_reg_54462.read(): sel_tmp696_fu_34966_p3.read());
}
void a0_bin_conv::thread_sel_tmp698_fu_29392_p3() {
sel_tmp698_fu_29392_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_3_13_fu_1746.read(): old_word_buffer_1_7_13_fu_1890.read());
}
void a0_bin_conv::thread_sel_tmp699_fu_29399_p3() {
sel_tmp699_fu_29399_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_4_13_fu_1782.read(): sel_tmp698_fu_29392_p3.read());
}
void a0_bin_conv::thread_sel_tmp700_fu_29406_p3() {
sel_tmp700_fu_29406_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_5_13_fu_1818.read(): sel_tmp699_fu_29399_p3.read());
}
void a0_bin_conv::thread_sel_tmp701_fu_34984_p3() {
sel_tmp701_fu_34984_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_3_30_reg_54360.read(): old_word_buffer_1_7_46_reg_54641.read());
}
void a0_bin_conv::thread_sel_tmp702_fu_34989_p3() {
sel_tmp702_fu_34989_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_4_30_reg_54413.read(): sel_tmp701_fu_34984_p3.read());
}
void a0_bin_conv::thread_sel_tmp703_fu_34995_p3() {
sel_tmp703_fu_34995_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_5_30_reg_54476.read(): sel_tmp702_fu_34989_p3.read());
}
void a0_bin_conv::thread_sel_tmp704_fu_29420_p3() {
sel_tmp704_fu_29420_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_3_15_fu_1754.read(): old_word_buffer_1_7_15_fu_1898.read());
}
void a0_bin_conv::thread_sel_tmp705_fu_29427_p3() {
sel_tmp705_fu_29427_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_4_15_fu_1790.read(): sel_tmp704_fu_29420_p3.read());
}
void a0_bin_conv::thread_sel_tmp706_fu_29434_p3() {
sel_tmp706_fu_29434_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_5_15_fu_1826.read(): sel_tmp705_fu_29427_p3.read());
}
void a0_bin_conv::thread_sel_tmp707_fu_35007_p3() {
sel_tmp707_fu_35007_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_3_31_reg_54370.read(): old_word_buffer_1_7_48_reg_54664.read());
}
void a0_bin_conv::thread_sel_tmp708_fu_35012_p3() {
sel_tmp708_fu_35012_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_4_31_reg_54425.read(): sel_tmp707_fu_35007_p3.read());
}
void a0_bin_conv::thread_sel_tmp709_fu_35018_p3() {
sel_tmp709_fu_35018_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_5_31_reg_54490.read(): sel_tmp708_fu_35012_p3.read());
}
void a0_bin_conv::thread_sel_tmp710_fu_24142_p3() {
sel_tmp710_fu_24142_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_3_17_fu_1762.read(): old_word_buffer_1_7_17_fu_1906.read());
}
void a0_bin_conv::thread_sel_tmp711_fu_24149_p3() {
sel_tmp711_fu_24149_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_4_17_fu_1798.read(): sel_tmp710_fu_24142_p3.read());
}
void a0_bin_conv::thread_sel_tmp712_fu_24156_p3() {
sel_tmp712_fu_24156_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_5_17_fu_1834.read(): sel_tmp711_fu_24149_p3.read());
}
void a0_bin_conv::thread_sel_tmp713_fu_35030_p3() {
sel_tmp713_fu_35030_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_3_32_reg_54380.read(): ap_reg_pp0_iter2_old_word_buffer_1_7_42_reg_52212.read());
}
void a0_bin_conv::thread_sel_tmp714_fu_35035_p3() {
sel_tmp714_fu_35035_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_4_32_reg_54437.read(): sel_tmp713_fu_35030_p3.read());
}
void a0_bin_conv::thread_sel_tmp715_fu_35041_p3() {
sel_tmp715_fu_35041_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? old_word_buffer_1_5_32_reg_54504.read(): sel_tmp714_fu_35035_p3.read());
}
void a0_bin_conv::thread_sel_tmp716_fu_29448_p3() {
sel_tmp716_fu_29448_p3 = (!tmp_1227_reg_45800.read()[0].is_01())? sc_lv<2>(): ((tmp_1227_reg_45800.read()[0].to_bool())? old_word_buffer_1_7_fu_714.read(): ap_const_lv2_0);
}
void a0_bin_conv::thread_sel_tmp717_fu_29455_p3() {
sel_tmp717_fu_29455_p3 = (!sel_tmp84_reg_51313.read()[0].is_01())? sc_lv<2>(): ((sel_tmp84_reg_51313.read()[0].to_bool())? old_word_buffer_1_4_fu_702.read(): sel_tmp716_fu_29448_p3.read());
}
void a0_bin_conv::thread_sel_tmp718_fu_29462_p3() {
sel_tmp718_fu_29462_p3 = (!sel_tmp85_reg_51319.read()[0].is_01())? sc_lv<2>(): ((sel_tmp85_reg_51319.read()[0].to_bool())? old_word_buffer_1_5_fu_706.read(): sel_tmp717_fu_29455_p3.read());
}
void a0_bin_conv::thread_sel_tmp719_fu_29469_p3() {
sel_tmp719_fu_29469_p3 = (!sel_tmp86_reg_51325.read()[0].is_01())? sc_lv<2>(): ((sel_tmp86_reg_51325.read()[0].to_bool())? old_word_buffer_1_6_fu_710.read(): sel_tmp718_fu_29462_p3.read());
}
void a0_bin_conv::thread_sel_tmp720_fu_29290_p3() {
sel_tmp720_fu_29290_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_0_1_1_fu_25795_p3.read(): word_buffer_1_2_1_fu_25723_p3.read());
}
void a0_bin_conv::thread_sel_tmp721_fu_29304_p3() {
sel_tmp721_fu_29304_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_0_3_1_fu_25782_p3.read(): word_buffer_1_2_3_1_reg_52882.read());
}
void a0_bin_conv::thread_sel_tmp722_fu_29316_p3() {
sel_tmp722_fu_29316_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_0_5_1_fu_25769_p3.read(): word_buffer_1_2_5_1_reg_52848.read());
}
void a0_bin_conv::thread_sel_tmp723_fu_29328_p3() {
sel_tmp723_fu_29328_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_0_7_1_fu_25756_p3.read(): word_buffer_1_2_7_1_reg_52815.read());
}
void a0_bin_conv::thread_sel_tmp724_fu_34920_p2() {
sel_tmp724_fu_34920_p2 = (tmp_1227_reg_45800.read() & last_wrd_not1_fu_34915_p2.read());
}
void a0_bin_conv::thread_sel_tmp725_fu_34925_p2() {
sel_tmp725_fu_34925_p2 = (tmp_167_reg_50852.read() & sel_tmp724_fu_34920_p2.read());
}
void a0_bin_conv::thread_sel_tmp726_fu_34930_p3() {
sel_tmp726_fu_34930_p3 = (!sel_tmp725_fu_34925_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp725_fu_34925_p2.read()[0].to_bool())? ap_const_lv2_0: word_buffer_1_2_0_1_reg_55582.read());
}
void a0_bin_conv::thread_sel_tmp727_fu_34937_p2() {
sel_tmp727_fu_34937_p2 = (cond1_reg_50498.read() & sel_tmp724_fu_34920_p2.read());
}
void a0_bin_conv::thread_sel_tmp728_fu_34942_p3() {
sel_tmp728_fu_34942_p3 = (!sel_tmp727_fu_34937_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp727_fu_34937_p2.read()[0].to_bool())? word_buffer_1_1_0_reg_54929.read(): sel_tmp726_fu_34930_p3.read());
}
void a0_bin_conv::thread_sel_tmp729_fu_29588_p3() {
sel_tmp729_fu_29588_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_4_11_fu_1774.read(): old_word_buffer_1_7_11_fu_1882.read());
}
void a0_bin_conv::thread_sel_tmp730_fu_29595_p3() {
sel_tmp730_fu_29595_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_5_11_fu_1810.read(): sel_tmp729_fu_29588_p3.read());
}
void a0_bin_conv::thread_sel_tmp731_fu_35111_p3() {
sel_tmp731_fu_35111_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_4_29_reg_54401.read(): old_word_buffer_1_7_44_reg_54617.read());
}
void a0_bin_conv::thread_sel_tmp732_fu_35116_p3() {
sel_tmp732_fu_35116_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_5_29_reg_54462.read(): sel_tmp731_fu_35111_p3.read());
}
void a0_bin_conv::thread_sel_tmp733_fu_29609_p3() {
sel_tmp733_fu_29609_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_4_13_fu_1782.read(): old_word_buffer_1_7_13_fu_1890.read());
}
void a0_bin_conv::thread_sel_tmp734_fu_29616_p3() {
sel_tmp734_fu_29616_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_5_13_fu_1818.read(): sel_tmp733_fu_29609_p3.read());
}
void a0_bin_conv::thread_sel_tmp735_fu_35128_p3() {
sel_tmp735_fu_35128_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_4_30_reg_54413.read(): old_word_buffer_1_7_46_reg_54641.read());
}
void a0_bin_conv::thread_sel_tmp736_fu_35133_p3() {
sel_tmp736_fu_35133_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_5_30_reg_54476.read(): sel_tmp735_fu_35128_p3.read());
}
void a0_bin_conv::thread_sel_tmp737_fu_29630_p3() {
sel_tmp737_fu_29630_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_4_15_fu_1790.read(): old_word_buffer_1_7_15_fu_1898.read());
}
void a0_bin_conv::thread_sel_tmp738_fu_29637_p3() {
sel_tmp738_fu_29637_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_5_15_fu_1826.read(): sel_tmp737_fu_29630_p3.read());
}
void a0_bin_conv::thread_sel_tmp739_fu_35145_p3() {
sel_tmp739_fu_35145_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_4_31_reg_54425.read(): old_word_buffer_1_7_48_reg_54664.read());
}
void a0_bin_conv::thread_sel_tmp740_fu_35150_p3() {
sel_tmp740_fu_35150_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_5_31_reg_54490.read(): sel_tmp739_fu_35145_p3.read());
}
void a0_bin_conv::thread_sel_tmp741_fu_24176_p3() {
sel_tmp741_fu_24176_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_4_17_fu_1798.read(): old_word_buffer_1_7_17_fu_1906.read());
}
void a0_bin_conv::thread_sel_tmp742_fu_24183_p3() {
sel_tmp742_fu_24183_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_5_17_fu_1834.read(): sel_tmp741_fu_24176_p3.read());
}
void a0_bin_conv::thread_sel_tmp743_fu_35162_p3() {
sel_tmp743_fu_35162_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_4_32_reg_54437.read(): ap_reg_pp0_iter2_old_word_buffer_1_7_42_reg_52212.read());
}
void a0_bin_conv::thread_sel_tmp744_fu_35167_p3() {
sel_tmp744_fu_35167_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? old_word_buffer_1_5_32_reg_54504.read(): sel_tmp743_fu_35162_p3.read());
}
void a0_bin_conv::thread_sel_tmp745_fu_29651_p3() {
sel_tmp745_fu_29651_p3 = (!lb_3_reg_45835.read()[0].is_01())? sc_lv<2>(): ((lb_3_reg_45835.read()[0].to_bool())? ap_const_lv2_0: old_word_buffer_1_7_fu_714.read());
}
void a0_bin_conv::thread_sel_tmp746_fu_29658_p3() {
sel_tmp746_fu_29658_p3 = (!sel_tmp89_reg_51337.read()[0].is_01())? sc_lv<2>(): ((sel_tmp89_reg_51337.read()[0].to_bool())? old_word_buffer_1_5_fu_706.read(): sel_tmp745_fu_29651_p3.read());
}
void a0_bin_conv::thread_sel_tmp747_fu_29665_p3() {
sel_tmp747_fu_29665_p3 = (!sel_tmp90_reg_51343.read()[0].is_01())? sc_lv<2>(): ((sel_tmp90_reg_51343.read()[0].to_bool())? old_word_buffer_1_6_fu_710.read(): sel_tmp746_fu_29658_p3.read());
}
void a0_bin_conv::thread_sel_tmp748_fu_29483_p3() {
sel_tmp748_fu_29483_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_1_0_1_1_fu_25795_p3.read(): word_buffer_1_3_1_fu_25697_p3.read());
}
void a0_bin_conv::thread_sel_tmp749_fu_29490_p3() {
sel_tmp749_fu_29490_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_1_1_fu_25730_p3.read(): sel_tmp748_fu_29483_p3.read());
}
void a0_bin_conv::thread_sel_tmp750_fu_29504_p3() {
sel_tmp750_fu_29504_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_1_0_3_1_fu_25782_p3.read(): word_buffer_1_3_3_1_reg_52785.read());
}
void a0_bin_conv::thread_sel_tmp751_fu_29510_p3() {
sel_tmp751_fu_29510_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_1_3_1_reg_52991.read(): sel_tmp750_fu_29504_p3.read());
}
void a0_bin_conv::thread_sel_tmp752_fu_29522_p3() {
sel_tmp752_fu_29522_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_1_0_5_1_fu_25769_p3.read(): word_buffer_1_3_5_1_reg_52755.read());
}
void a0_bin_conv::thread_sel_tmp753_fu_29528_p3() {
sel_tmp753_fu_29528_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_1_5_1_reg_52953.read(): sel_tmp752_fu_29522_p3.read());
}
void a0_bin_conv::thread_sel_tmp754_fu_29540_p3() {
sel_tmp754_fu_29540_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_1_0_7_1_fu_25756_p3.read(): word_buffer_1_3_7_1_reg_52726.read());
}
void a0_bin_conv::thread_sel_tmp755_fu_29546_p3() {
sel_tmp755_fu_29546_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_1_7_1_reg_52916.read(): sel_tmp754_fu_29540_p3.read());
}
void a0_bin_conv::thread_sel_tmp756_fu_35057_p2() {
sel_tmp756_fu_35057_p2 = (brmerge32_fu_35053_p2.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp757_fu_35063_p2() {
sel_tmp757_fu_35063_p2 = (tmp_170_reg_51104.read() & sel_tmp756_fu_35057_p2.read());
}
void a0_bin_conv::thread_sel_tmp758_fu_35068_p3() {
sel_tmp758_fu_35068_p3 = (!sel_tmp757_fu_35063_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp757_fu_35063_p2.read()[0].to_bool())? ap_const_lv2_0: word_buffer_1_3_0_reg_54858.read());
}
void a0_bin_conv::thread_sel_tmp759_fu_35075_p2() {
sel_tmp759_fu_35075_p2 = (tmp_167_reg_50852.read() & sel_tmp756_fu_35057_p2.read());
}
void a0_bin_conv::thread_sel_tmp760_fu_35080_p3() {
sel_tmp760_fu_35080_p3 = (!sel_tmp759_fu_35075_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp759_fu_35075_p2.read()[0].to_bool())? word_buffer_1_1_0_reg_54929.read(): sel_tmp758_fu_35068_p3.read());
}
void a0_bin_conv::thread_sel_tmp761_fu_35087_p2() {
sel_tmp761_fu_35087_p2 = (cond1_reg_50498.read() & sel_tmp756_fu_35057_p2.read());
}
void a0_bin_conv::thread_sel_tmp762_fu_35092_p3() {
sel_tmp762_fu_35092_p3 = (!sel_tmp761_fu_35087_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp761_fu_35087_p2.read()[0].to_bool())? word_buffer_1_2_0_1_reg_55582.read(): sel_tmp760_fu_35080_p3.read());
}
void a0_bin_conv::thread_sel_tmp763_fu_29810_p3() {
sel_tmp763_fu_29810_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_5_11_fu_1810.read(): old_word_buffer_1_7_11_fu_1882.read());
}
void a0_bin_conv::thread_sel_tmp764_fu_35243_p3() {
sel_tmp764_fu_35243_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_5_29_reg_54462.read(): old_word_buffer_1_7_44_reg_54617.read());
}
void a0_bin_conv::thread_sel_tmp765_fu_29824_p3() {
sel_tmp765_fu_29824_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_5_13_fu_1818.read(): old_word_buffer_1_7_13_fu_1890.read());
}
void a0_bin_conv::thread_sel_tmp766_fu_35254_p3() {
sel_tmp766_fu_35254_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_5_30_reg_54476.read(): old_word_buffer_1_7_46_reg_54641.read());
}
void a0_bin_conv::thread_sel_tmp767_fu_29838_p3() {
sel_tmp767_fu_29838_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_5_15_fu_1826.read(): old_word_buffer_1_7_15_fu_1898.read());
}
void a0_bin_conv::thread_sel_tmp768_fu_35265_p3() {
sel_tmp768_fu_35265_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_5_31_reg_54490.read(): old_word_buffer_1_7_48_reg_54664.read());
}
void a0_bin_conv::thread_sel_tmp769_fu_24203_p3() {
sel_tmp769_fu_24203_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_5_17_fu_1834.read(): old_word_buffer_1_7_17_fu_1906.read());
}
void a0_bin_conv::thread_sel_tmp770_fu_35276_p3() {
sel_tmp770_fu_35276_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_1_5_32_reg_54504.read(): ap_reg_pp0_iter2_old_word_buffer_1_7_42_reg_52212.read());
}
void a0_bin_conv::thread_sel_tmp771_fu_29852_p3() {
sel_tmp771_fu_29852_p3 = (!lb_4_reg_45859.read()[0].is_01())? sc_lv<2>(): ((lb_4_reg_45859.read()[0].to_bool())? ap_const_lv2_0: old_word_buffer_1_7_fu_714.read());
}
void a0_bin_conv::thread_sel_tmp772_fu_29859_p3() {
sel_tmp772_fu_29859_p3 = (!sel_tmp93_reg_51355.read()[0].is_01())? sc_lv<2>(): ((sel_tmp93_reg_51355.read()[0].to_bool())? old_word_buffer_1_6_fu_710.read(): sel_tmp771_fu_29852_p3.read());
}
void a0_bin_conv::thread_sel_tmp773_fu_29679_p3() {
sel_tmp773_fu_29679_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_1_0_1_1_fu_25795_p3.read(): word_buffer_1_4_1_fu_25671_p3.read());
}
void a0_bin_conv::thread_sel_tmp774_fu_29686_p3() {
sel_tmp774_fu_29686_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_1_1_1_fu_25730_p3.read(): sel_tmp773_fu_29679_p3.read());
}
void a0_bin_conv::thread_sel_tmp775_fu_29693_p3() {
sel_tmp775_fu_29693_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_2_1_fu_25723_p3.read(): sel_tmp774_fu_29686_p3.read());
}
void a0_bin_conv::thread_sel_tmp776_fu_29707_p3() {
sel_tmp776_fu_29707_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_1_0_3_1_fu_25782_p3.read(): word_buffer_1_4_3_1_reg_52700.read());
}
void a0_bin_conv::thread_sel_tmp777_fu_29713_p3() {
sel_tmp777_fu_29713_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_1_1_3_1_reg_52991.read(): sel_tmp776_fu_29707_p3.read());
}
void a0_bin_conv::thread_sel_tmp778_fu_29719_p3() {
sel_tmp778_fu_29719_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_2_3_1_reg_52882.read(): sel_tmp777_fu_29713_p3.read());
}
void a0_bin_conv::thread_sel_tmp779_fu_29731_p3() {
sel_tmp779_fu_29731_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_1_0_5_1_fu_25769_p3.read(): word_buffer_1_4_5_1_reg_52674.read());
}
void a0_bin_conv::thread_sel_tmp780_fu_29737_p3() {
sel_tmp780_fu_29737_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_1_1_5_1_reg_52953.read(): sel_tmp779_fu_29731_p3.read());
}
void a0_bin_conv::thread_sel_tmp781_fu_29743_p3() {
sel_tmp781_fu_29743_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_2_5_1_reg_52848.read(): sel_tmp780_fu_29737_p3.read());
}
void a0_bin_conv::thread_sel_tmp782_fu_29755_p3() {
sel_tmp782_fu_29755_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_1_0_7_1_fu_25756_p3.read(): word_buffer_1_4_7_1_reg_52649.read());
}
void a0_bin_conv::thread_sel_tmp783_fu_29761_p3() {
sel_tmp783_fu_29761_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_1_1_7_1_reg_52916.read(): sel_tmp782_fu_29755_p3.read());
}
void a0_bin_conv::thread_sel_tmp784_fu_29767_p3() {
sel_tmp784_fu_29767_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_2_7_1_reg_52815.read(): sel_tmp783_fu_29761_p3.read());
}
void a0_bin_conv::thread_sel_tmp785_fu_35179_p2() {
sel_tmp785_fu_35179_p2 = (brmerge34_reg_56771.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp786_fu_35184_p2() {
sel_tmp786_fu_35184_p2 = (tmp_171_reg_51180.read() & sel_tmp785_fu_35179_p2.read());
}
void a0_bin_conv::thread_sel_tmp787_fu_35189_p3() {
sel_tmp787_fu_35189_p3 = (!sel_tmp786_fu_35184_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp786_fu_35184_p2.read()[0].to_bool())? ap_const_lv2_0: word_buffer_1_4_0_reg_54806.read());
}
void a0_bin_conv::thread_sel_tmp788_fu_35196_p2() {
sel_tmp788_fu_35196_p2 = (tmp_170_reg_51104.read() & sel_tmp785_fu_35179_p2.read());
}
void a0_bin_conv::thread_sel_tmp789_fu_35201_p3() {
sel_tmp789_fu_35201_p3 = (!sel_tmp788_fu_35196_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp788_fu_35196_p2.read()[0].to_bool())? word_buffer_1_1_0_reg_54929.read(): sel_tmp787_fu_35189_p3.read());
}
void a0_bin_conv::thread_sel_tmp790_fu_35208_p2() {
sel_tmp790_fu_35208_p2 = (tmp_167_reg_50852.read() & sel_tmp785_fu_35179_p2.read());
}
void a0_bin_conv::thread_sel_tmp791_fu_35213_p3() {
sel_tmp791_fu_35213_p3 = (!sel_tmp790_fu_35208_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp790_fu_35208_p2.read()[0].to_bool())? word_buffer_1_2_0_1_reg_55582.read(): sel_tmp789_fu_35201_p3.read());
}
void a0_bin_conv::thread_sel_tmp792_fu_35220_p2() {
sel_tmp792_fu_35220_p2 = (cond1_reg_50498.read() & sel_tmp785_fu_35179_p2.read());
}
void a0_bin_conv::thread_sel_tmp793_fu_35225_p3() {
sel_tmp793_fu_35225_p3 = (!sel_tmp792_fu_35220_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp792_fu_35220_p2.read()[0].to_bool())? word_buffer_1_3_0_reg_54858.read(): sel_tmp791_fu_35213_p3.read());
}
void a0_bin_conv::thread_sel_tmp794_fu_29873_p3() {
sel_tmp794_fu_29873_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_1_0_1_1_fu_25795_p3.read(): word_buffer_1_5_1_fu_25643_p3.read());
}
void a0_bin_conv::thread_sel_tmp795_fu_29880_p3() {
sel_tmp795_fu_29880_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_1_1_1_fu_25730_p3.read(): sel_tmp794_fu_29873_p3.read());
}
void a0_bin_conv::thread_sel_tmp796_fu_35287_p3() {
sel_tmp796_fu_35287_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_1_2_1_reg_54904.read(): sel_tmp795_reg_56809.read());
}
void a0_bin_conv::thread_sel_tmp797_fu_35292_p3() {
sel_tmp797_fu_35292_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_3_1_reg_54846.read(): sel_tmp796_fu_35287_p3.read());
}
void a0_bin_conv::thread_sel_tmp798_fu_29887_p3() {
sel_tmp798_fu_29887_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_1_0_3_1_fu_25782_p3.read(): word_buffer_1_5_3_1_reg_52627.read());
}
void a0_bin_conv::thread_sel_tmp799_fu_29893_p3() {
sel_tmp799_fu_29893_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_1_1_3_1_reg_52991.read(): sel_tmp798_fu_29887_p3.read());
}
void a0_bin_conv::thread_sel_tmp79_fu_20457_p2() {
sel_tmp79_fu_20457_p2 = (tmp_168_fu_20424_p2.read() & tmp_1225_reg_45756.read());
}
void a0_bin_conv::thread_sel_tmp800_fu_35310_p3() {
sel_tmp800_fu_35310_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_3_1_reg_52882.read(): sel_tmp799_reg_56814.read());
}
void a0_bin_conv::thread_sel_tmp801_fu_35315_p3() {
sel_tmp801_fu_35315_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_3_3_1_reg_52785.read(): sel_tmp800_fu_35310_p3.read());
}
void a0_bin_conv::thread_sel_tmp802_fu_29899_p3() {
sel_tmp802_fu_29899_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_1_0_5_1_fu_25769_p3.read(): word_buffer_1_5_5_1_reg_52605.read());
}
void a0_bin_conv::thread_sel_tmp803_fu_29905_p3() {
sel_tmp803_fu_29905_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_1_1_5_1_reg_52953.read(): sel_tmp802_fu_29899_p3.read());
}
void a0_bin_conv::thread_sel_tmp804_fu_35333_p3() {
sel_tmp804_fu_35333_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_5_1_reg_52848.read(): sel_tmp803_reg_56819.read());
}
void a0_bin_conv::thread_sel_tmp805_fu_35338_p3() {
sel_tmp805_fu_35338_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_3_5_1_reg_52755.read(): sel_tmp804_fu_35333_p3.read());
}
void a0_bin_conv::thread_sel_tmp806_fu_29911_p3() {
sel_tmp806_fu_29911_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_1_0_7_1_fu_25756_p3.read(): word_buffer_1_5_7_1_reg_52584.read());
}
void a0_bin_conv::thread_sel_tmp807_fu_29917_p3() {
sel_tmp807_fu_29917_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_1_1_7_1_reg_52916.read(): sel_tmp806_fu_29911_p3.read());
}
void a0_bin_conv::thread_sel_tmp808_fu_35356_p3() {
sel_tmp808_fu_35356_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_7_1_reg_52815.read(): sel_tmp807_reg_56824.read());
}
void a0_bin_conv::thread_sel_tmp809_fu_35361_p3() {
sel_tmp809_fu_35361_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_3_7_1_reg_52726.read(): sel_tmp808_fu_35356_p3.read());
}
void a0_bin_conv::thread_sel_tmp80_fu_20462_p2() {
sel_tmp80_fu_20462_p2 = (tmp_169_fu_20430_p2.read() & tmp_1225_reg_45756.read());
}
void a0_bin_conv::thread_sel_tmp810_fu_29927_p2() {
sel_tmp810_fu_29927_p2 = (brmerge36_fu_29923_p2.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp811_fu_29933_p2() {
sel_tmp811_fu_29933_p2 = (tmp_169_reg_51016.read() & sel_tmp810_fu_29927_p2.read());
}
void a0_bin_conv::thread_sel_tmp812_fu_29938_p3() {
sel_tmp812_fu_29938_p3 = (!sel_tmp811_fu_29933_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp811_fu_29933_p2.read()[0].to_bool())? ap_const_lv2_0: word_buffer_1_5_0_fu_25650_p3.read());
}
void a0_bin_conv::thread_sel_tmp813_fu_29946_p2() {
sel_tmp813_fu_29946_p2 = (tmp_171_reg_51180.read() & sel_tmp810_fu_29927_p2.read());
}
void a0_bin_conv::thread_sel_tmp814_fu_29951_p3() {
sel_tmp814_fu_29951_p3 = (!sel_tmp813_fu_29946_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp813_fu_29946_p2.read()[0].to_bool())? word_buffer_1_1_0_fu_25736_p3.read(): sel_tmp812_fu_29938_p3.read());
}
void a0_bin_conv::thread_sel_tmp815_fu_35379_p2() {
sel_tmp815_fu_35379_p2 = (tmp_170_reg_51104.read() & sel_tmp810_reg_56834.read());
}
void a0_bin_conv::thread_sel_tmp816_fu_35383_p3() {
sel_tmp816_fu_35383_p3 = (!sel_tmp815_fu_35379_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp815_fu_35379_p2.read()[0].to_bool())? word_buffer_1_2_0_1_reg_55582.read(): sel_tmp814_reg_56841.read());
}
void a0_bin_conv::thread_sel_tmp817_fu_35389_p2() {
sel_tmp817_fu_35389_p2 = (tmp_167_reg_50852.read() & sel_tmp810_reg_56834.read());
}
void a0_bin_conv::thread_sel_tmp818_fu_35393_p3() {
sel_tmp818_fu_35393_p3 = (!sel_tmp817_fu_35389_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp817_fu_35389_p2.read()[0].to_bool())? word_buffer_1_3_0_reg_54858.read(): sel_tmp816_fu_35383_p3.read());
}
void a0_bin_conv::thread_sel_tmp819_fu_35400_p2() {
sel_tmp819_fu_35400_p2 = (cond1_reg_50498.read() & sel_tmp810_reg_56834.read());
}
void a0_bin_conv::thread_sel_tmp81_fu_20467_p2() {
sel_tmp81_fu_20467_p2 = (tmp_171_fu_20442_p2.read() & tmp_1225_reg_45756.read());
}
void a0_bin_conv::thread_sel_tmp820_fu_35404_p3() {
sel_tmp820_fu_35404_p3 = (!sel_tmp819_fu_35400_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp819_fu_35400_p2.read()[0].to_bool())? word_buffer_1_4_0_reg_54806.read(): sel_tmp818_fu_35393_p3.read());
}
void a0_bin_conv::thread_sel_tmp821_fu_29995_p3() {
sel_tmp821_fu_29995_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? word_buffer_1_0_1_1_fu_25795_p3.read(): word_buffer_1_6_1_fu_25615_p3.read());
}
void a0_bin_conv::thread_sel_tmp822_fu_30002_p3() {
sel_tmp822_fu_30002_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_1_1_1_fu_25730_p3.read(): sel_tmp821_fu_29995_p3.read());
}
void a0_bin_conv::thread_sel_tmp823_fu_35463_p3() {
sel_tmp823_fu_35463_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? word_buffer_1_2_1_reg_54904.read(): sel_tmp822_reg_56868.read());
}
void a0_bin_conv::thread_sel_tmp824_fu_35468_p3() {
sel_tmp824_fu_35468_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? word_buffer_1_3_1_reg_54846.read(): sel_tmp823_fu_35463_p3.read());
}
void a0_bin_conv::thread_sel_tmp825_fu_35474_p3() {
sel_tmp825_fu_35474_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? word_buffer_1_4_1_reg_54795.read(): sel_tmp824_fu_35468_p3.read());
}
void a0_bin_conv::thread_sel_tmp826_fu_30009_p3() {
sel_tmp826_fu_30009_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? word_buffer_1_0_3_1_fu_25782_p3.read(): word_buffer_1_6_3_1_reg_52566.read());
}
void a0_bin_conv::thread_sel_tmp827_fu_30015_p3() {
sel_tmp827_fu_30015_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_1_1_3_1_reg_52991.read(): sel_tmp826_fu_30009_p3.read());
}
void a0_bin_conv::thread_sel_tmp828_fu_35493_p3() {
sel_tmp828_fu_35493_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_3_1_reg_52882.read(): sel_tmp827_reg_56873.read());
}
void a0_bin_conv::thread_sel_tmp829_fu_35498_p3() {
sel_tmp829_fu_35498_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_3_3_1_reg_52785.read(): sel_tmp828_fu_35493_p3.read());
}
void a0_bin_conv::thread_sel_tmp82_fu_20472_p2() {
sel_tmp82_fu_20472_p2 = (tmp_170_fu_20436_p2.read() & tmp_1225_reg_45756.read());
}
void a0_bin_conv::thread_sel_tmp830_fu_35504_p3() {
sel_tmp830_fu_35504_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_4_3_1_reg_52700.read(): sel_tmp829_fu_35498_p3.read());
}
void a0_bin_conv::thread_sel_tmp831_fu_30021_p3() {
sel_tmp831_fu_30021_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? word_buffer_1_0_5_1_fu_25769_p3.read(): word_buffer_1_6_5_1_reg_52548.read());
}
void a0_bin_conv::thread_sel_tmp832_fu_30027_p3() {
sel_tmp832_fu_30027_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_1_1_5_1_reg_52953.read(): sel_tmp831_fu_30021_p3.read());
}
void a0_bin_conv::thread_sel_tmp833_fu_35523_p3() {
sel_tmp833_fu_35523_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_5_1_reg_52848.read(): sel_tmp832_reg_56878.read());
}
void a0_bin_conv::thread_sel_tmp834_fu_35528_p3() {
sel_tmp834_fu_35528_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_3_5_1_reg_52755.read(): sel_tmp833_fu_35523_p3.read());
}
void a0_bin_conv::thread_sel_tmp835_fu_35534_p3() {
sel_tmp835_fu_35534_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_4_5_1_reg_52674.read(): sel_tmp834_fu_35528_p3.read());
}
void a0_bin_conv::thread_sel_tmp836_fu_30033_p3() {
sel_tmp836_fu_30033_p3 = (!tmp_168_reg_50922.read()[0].is_01())? sc_lv<2>(): ((tmp_168_reg_50922.read()[0].to_bool())? word_buffer_1_0_7_1_fu_25756_p3.read(): word_buffer_1_6_7_1_reg_52531.read());
}
void a0_bin_conv::thread_sel_tmp837_fu_30039_p3() {
sel_tmp837_fu_30039_p3 = (!tmp_169_reg_51016.read()[0].is_01())? sc_lv<2>(): ((tmp_169_reg_51016.read()[0].to_bool())? word_buffer_1_1_7_1_reg_52916.read(): sel_tmp836_fu_30033_p3.read());
}
void a0_bin_conv::thread_sel_tmp838_fu_35553_p3() {
sel_tmp838_fu_35553_p3 = (!tmp_171_reg_51180.read()[0].is_01())? sc_lv<2>(): ((tmp_171_reg_51180.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_7_1_reg_52815.read(): sel_tmp837_reg_56883.read());
}
void a0_bin_conv::thread_sel_tmp839_fu_35558_p3() {
sel_tmp839_fu_35558_p3 = (!tmp_170_reg_51104.read()[0].is_01())? sc_lv<2>(): ((tmp_170_reg_51104.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_3_7_1_reg_52726.read(): sel_tmp838_fu_35553_p3.read());
}
void a0_bin_conv::thread_sel_tmp83_fu_20477_p2() {
sel_tmp83_fu_20477_p2 = (cond6_fu_20126_p2.read() & tmp_1225_reg_45756.read());
}
void a0_bin_conv::thread_sel_tmp840_fu_35564_p3() {
sel_tmp840_fu_35564_p3 = (!tmp_167_reg_50852.read()[0].is_01())? sc_lv<2>(): ((tmp_167_reg_50852.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_4_7_1_reg_52649.read(): sel_tmp839_fu_35558_p3.read());
}
void a0_bin_conv::thread_sel_tmp841_fu_30049_p2() {
sel_tmp841_fu_30049_p2 = (brmerge38_fu_30045_p2.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp842_fu_30055_p2() {
sel_tmp842_fu_30055_p2 = (tmp_168_reg_50922.read() & sel_tmp841_fu_30049_p2.read());
}
void a0_bin_conv::thread_sel_tmp843_fu_30060_p3() {
sel_tmp843_fu_30060_p3 = (!sel_tmp842_fu_30055_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp842_fu_30055_p2.read()[0].to_bool())? ap_const_lv2_0: word_buffer_1_6_0_fu_25622_p3.read());
}
void a0_bin_conv::thread_sel_tmp844_fu_30068_p2() {
sel_tmp844_fu_30068_p2 = (tmp_169_reg_51016.read() & sel_tmp841_fu_30049_p2.read());
}
void a0_bin_conv::thread_sel_tmp845_fu_30073_p3() {
sel_tmp845_fu_30073_p3 = (!sel_tmp844_fu_30068_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp844_fu_30068_p2.read()[0].to_bool())? word_buffer_1_1_0_fu_25736_p3.read(): sel_tmp843_fu_30060_p3.read());
}
void a0_bin_conv::thread_sel_tmp846_fu_30081_p2() {
sel_tmp846_fu_30081_p2 = (tmp_171_reg_51180.read() & sel_tmp841_fu_30049_p2.read());
}
void a0_bin_conv::thread_sel_tmp847_fu_30086_p3() {
sel_tmp847_fu_30086_p3 = (!sel_tmp846_fu_30081_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp846_fu_30081_p2.read()[0].to_bool())? word_buffer_1_2_0_1_fu_26050_p3.read(): sel_tmp845_fu_30073_p3.read());
}
void a0_bin_conv::thread_sel_tmp848_fu_35583_p2() {
sel_tmp848_fu_35583_p2 = (tmp_170_reg_51104.read() & sel_tmp841_reg_56893.read());
}
void a0_bin_conv::thread_sel_tmp849_fu_35587_p3() {
sel_tmp849_fu_35587_p3 = (!sel_tmp848_fu_35583_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp848_fu_35583_p2.read()[0].to_bool())? word_buffer_1_3_0_reg_54858.read(): sel_tmp847_reg_56900.read());
}
void a0_bin_conv::thread_sel_tmp84_fu_20482_p2() {
sel_tmp84_fu_20482_p2 = (tmp_168_fu_20424_p2.read() & tmp_1227_reg_45800.read());
}
void a0_bin_conv::thread_sel_tmp850_fu_35593_p2() {
sel_tmp850_fu_35593_p2 = (tmp_167_reg_50852.read() & sel_tmp841_reg_56893.read());
}
void a0_bin_conv::thread_sel_tmp851_fu_35597_p3() {
sel_tmp851_fu_35597_p3 = (!sel_tmp850_fu_35593_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp850_fu_35593_p2.read()[0].to_bool())? word_buffer_1_4_0_reg_54806.read(): sel_tmp849_fu_35587_p3.read());
}
void a0_bin_conv::thread_sel_tmp852_fu_35604_p2() {
sel_tmp852_fu_35604_p2 = (cond1_reg_50498.read() & sel_tmp841_reg_56893.read());
}
void a0_bin_conv::thread_sel_tmp853_fu_35608_p3() {
sel_tmp853_fu_35608_p3 = (!sel_tmp852_fu_35604_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp852_fu_35604_p2.read()[0].to_bool())? word_buffer_1_5_0_reg_54762.read(): sel_tmp851_fu_35597_p3.read());
}
void a0_bin_conv::thread_sel_tmp854_fu_30265_p3() {
sel_tmp854_fu_30265_p3 = (!tmp_143_reg_50572.read()[0].is_01())? sc_lv<2>(): ((tmp_143_reg_50572.read()[0].to_bool())? old_word_buffer_1_1_11_fu_1666.read(): old_word_buffer_1_7_11_fu_1882.read());
}
void a0_bin_conv::thread_sel_tmp855_fu_30272_p3() {
sel_tmp855_fu_30272_p3 = (!tmp_148_reg_50586.read()[0].is_01())? sc_lv<2>(): ((tmp_148_reg_50586.read()[0].to_bool())? old_word_buffer_1_2_11_fu_1702.read(): sel_tmp854_fu_30265_p3.read());
}
void a0_bin_conv::thread_sel_tmp856_fu_30279_p3() {
sel_tmp856_fu_30279_p3 = (!tmp_149_reg_50600.read()[0].is_01())? sc_lv<2>(): ((tmp_149_reg_50600.read()[0].to_bool())? old_word_buffer_1_3_11_fu_1738.read(): sel_tmp855_fu_30272_p3.read());
}
void a0_bin_conv::thread_sel_tmp857_fu_30286_p3() {
sel_tmp857_fu_30286_p3 = (!tmp_150_reg_50614.read()[0].is_01())? sc_lv<2>(): ((tmp_150_reg_50614.read()[0].to_bool())? old_word_buffer_1_4_11_fu_1774.read(): sel_tmp856_fu_30279_p3.read());
}
void a0_bin_conv::thread_sel_tmp858_fu_30293_p3() {
sel_tmp858_fu_30293_p3 = (!tmp_151_reg_50628.read()[0].is_01())? sc_lv<2>(): ((tmp_151_reg_50628.read()[0].to_bool())? old_word_buffer_1_5_11_fu_1810.read(): sel_tmp857_fu_30286_p3.read());
}
void a0_bin_conv::thread_sel_tmp859_fu_30325_p3() {
sel_tmp859_fu_30325_p3 = (!tmp_143_reg_50572.read()[0].is_01())? sc_lv<2>(): ((tmp_143_reg_50572.read()[0].to_bool())? old_word_buffer_1_1_13_fu_1674.read(): old_word_buffer_1_7_13_fu_1890.read());
}
void a0_bin_conv::thread_sel_tmp85_fu_20487_p2() {
sel_tmp85_fu_20487_p2 = (tmp_169_fu_20430_p2.read() & tmp_1227_reg_45800.read());
}
void a0_bin_conv::thread_sel_tmp860_fu_30332_p3() {
sel_tmp860_fu_30332_p3 = (!tmp_148_reg_50586.read()[0].is_01())? sc_lv<2>(): ((tmp_148_reg_50586.read()[0].to_bool())? old_word_buffer_1_2_13_fu_1710.read(): sel_tmp859_fu_30325_p3.read());
}
void a0_bin_conv::thread_sel_tmp861_fu_30339_p3() {
sel_tmp861_fu_30339_p3 = (!tmp_149_reg_50600.read()[0].is_01())? sc_lv<2>(): ((tmp_149_reg_50600.read()[0].to_bool())? old_word_buffer_1_3_13_fu_1746.read(): sel_tmp860_fu_30332_p3.read());
}
void a0_bin_conv::thread_sel_tmp862_fu_30346_p3() {
sel_tmp862_fu_30346_p3 = (!tmp_150_reg_50614.read()[0].is_01())? sc_lv<2>(): ((tmp_150_reg_50614.read()[0].to_bool())? old_word_buffer_1_4_13_fu_1782.read(): sel_tmp861_fu_30339_p3.read());
}
void a0_bin_conv::thread_sel_tmp863_fu_30353_p3() {
sel_tmp863_fu_30353_p3 = (!tmp_151_reg_50628.read()[0].is_01())? sc_lv<2>(): ((tmp_151_reg_50628.read()[0].to_bool())? old_word_buffer_1_5_13_fu_1818.read(): sel_tmp862_fu_30346_p3.read());
}
void a0_bin_conv::thread_sel_tmp864_fu_30385_p3() {
sel_tmp864_fu_30385_p3 = (!tmp_143_reg_50572.read()[0].is_01())? sc_lv<2>(): ((tmp_143_reg_50572.read()[0].to_bool())? old_word_buffer_1_1_15_fu_1682.read(): old_word_buffer_1_7_15_fu_1898.read());
}
void a0_bin_conv::thread_sel_tmp865_fu_30392_p3() {
sel_tmp865_fu_30392_p3 = (!tmp_148_reg_50586.read()[0].is_01())? sc_lv<2>(): ((tmp_148_reg_50586.read()[0].to_bool())? old_word_buffer_1_2_15_fu_1718.read(): sel_tmp864_fu_30385_p3.read());
}
void a0_bin_conv::thread_sel_tmp866_fu_30399_p3() {
sel_tmp866_fu_30399_p3 = (!tmp_149_reg_50600.read()[0].is_01())? sc_lv<2>(): ((tmp_149_reg_50600.read()[0].to_bool())? old_word_buffer_1_3_15_fu_1754.read(): sel_tmp865_fu_30392_p3.read());
}
void a0_bin_conv::thread_sel_tmp867_fu_30406_p3() {
sel_tmp867_fu_30406_p3 = (!tmp_150_reg_50614.read()[0].is_01())? sc_lv<2>(): ((tmp_150_reg_50614.read()[0].to_bool())? old_word_buffer_1_4_15_fu_1790.read(): sel_tmp866_fu_30399_p3.read());
}
void a0_bin_conv::thread_sel_tmp868_fu_30413_p3() {
sel_tmp868_fu_30413_p3 = (!tmp_151_reg_50628.read()[0].is_01())? sc_lv<2>(): ((tmp_151_reg_50628.read()[0].to_bool())? old_word_buffer_1_5_15_fu_1826.read(): sel_tmp867_fu_30406_p3.read());
}
void a0_bin_conv::thread_sel_tmp869_fu_24256_p3() {
sel_tmp869_fu_24256_p3 = (!tmp_143_reg_50572.read()[0].is_01())? sc_lv<2>(): ((tmp_143_reg_50572.read()[0].to_bool())? old_word_buffer_1_1_17_fu_1690.read(): old_word_buffer_1_7_17_fu_1906.read());
}
void a0_bin_conv::thread_sel_tmp86_fu_20492_p2() {
sel_tmp86_fu_20492_p2 = (tmp_171_fu_20442_p2.read() & tmp_1227_reg_45800.read());
}
void a0_bin_conv::thread_sel_tmp870_fu_24263_p3() {
sel_tmp870_fu_24263_p3 = (!tmp_148_reg_50586.read()[0].is_01())? sc_lv<2>(): ((tmp_148_reg_50586.read()[0].to_bool())? old_word_buffer_1_2_17_fu_1726.read(): sel_tmp869_fu_24256_p3.read());
}
void a0_bin_conv::thread_sel_tmp871_fu_24270_p3() {
sel_tmp871_fu_24270_p3 = (!tmp_149_reg_50600.read()[0].is_01())? sc_lv<2>(): ((tmp_149_reg_50600.read()[0].to_bool())? old_word_buffer_1_3_17_fu_1762.read(): sel_tmp870_fu_24263_p3.read());
}
void a0_bin_conv::thread_sel_tmp872_fu_24277_p3() {
sel_tmp872_fu_24277_p3 = (!tmp_150_reg_50614.read()[0].is_01())? sc_lv<2>(): ((tmp_150_reg_50614.read()[0].to_bool())? old_word_buffer_1_4_17_fu_1798.read(): sel_tmp871_fu_24270_p3.read());
}
void a0_bin_conv::thread_sel_tmp873_fu_24284_p3() {
sel_tmp873_fu_24284_p3 = (!tmp_151_reg_50628.read()[0].is_01())? sc_lv<2>(): ((tmp_151_reg_50628.read()[0].to_bool())? old_word_buffer_1_5_17_fu_1834.read(): sel_tmp872_fu_24277_p3.read());
}
void a0_bin_conv::thread_sel_tmp874_fu_30450_p2() {
sel_tmp874_fu_30450_p2 = (tmp_1225_reg_45756.read() & first_wrd_not2_fu_30445_p2.read());
}
void a0_bin_conv::thread_sel_tmp875_fu_30455_p2() {
sel_tmp875_fu_30455_p2 = (tmp_148_reg_50586.read() & sel_tmp874_fu_30450_p2.read());
}
void a0_bin_conv::thread_sel_tmp876_fu_30460_p3() {
sel_tmp876_fu_30460_p3 = (!sel_tmp875_fu_30455_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp875_fu_30455_p2.read()[0].to_bool())? old_word_buffer_1_2_fu_694.read(): old_word_buffer_1_7_fu_714.read());
}
void a0_bin_conv::thread_sel_tmp877_fu_30468_p2() {
sel_tmp877_fu_30468_p2 = (tmp_149_reg_50600.read() & sel_tmp874_fu_30450_p2.read());
}
void a0_bin_conv::thread_sel_tmp878_fu_30473_p3() {
sel_tmp878_fu_30473_p3 = (!sel_tmp877_fu_30468_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp877_fu_30468_p2.read()[0].to_bool())? old_word_buffer_1_3_fu_698.read(): sel_tmp876_fu_30460_p3.read());
}
void a0_bin_conv::thread_sel_tmp879_fu_30481_p2() {
sel_tmp879_fu_30481_p2 = (tmp_150_reg_50614.read() & sel_tmp874_fu_30450_p2.read());
}
void a0_bin_conv::thread_sel_tmp87_fu_20497_p2() {
sel_tmp87_fu_20497_p2 = (cond6_fu_20126_p2.read() & tmp_1227_reg_45800.read());
}
void a0_bin_conv::thread_sel_tmp880_fu_30486_p3() {
sel_tmp880_fu_30486_p3 = (!sel_tmp879_fu_30481_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp879_fu_30481_p2.read()[0].to_bool())? old_word_buffer_1_4_fu_702.read(): sel_tmp878_fu_30473_p3.read());
}
void a0_bin_conv::thread_sel_tmp881_fu_30494_p2() {
sel_tmp881_fu_30494_p2 = (tmp_151_reg_50628.read() & sel_tmp874_fu_30450_p2.read());
}
void a0_bin_conv::thread_sel_tmp882_fu_30499_p3() {
sel_tmp882_fu_30499_p3 = (!sel_tmp881_fu_30494_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp881_fu_30494_p2.read()[0].to_bool())? old_word_buffer_1_5_fu_706.read(): sel_tmp880_fu_30486_p3.read());
}
void a0_bin_conv::thread_sel_tmp883_fu_35873_p2() {
sel_tmp883_fu_35873_p2 = (tmp_152_reg_50642.read() & sel_tmp874_reg_56968.read());
}
void a0_bin_conv::thread_sel_tmp884_fu_35877_p3() {
sel_tmp884_fu_35877_p3 = (!sel_tmp883_fu_35873_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp883_fu_35873_p2.read()[0].to_bool())? old_word_buffer_1_6_54_reg_56963.read(): sel_tmp882_reg_56974.read());
}
void a0_bin_conv::thread_sel_tmp885_fu_35883_p2() {
sel_tmp885_fu_35883_p2 = (tmp_143_reg_50572.read() & sel_tmp874_reg_56968.read());
}
void a0_bin_conv::thread_sel_tmp886_fu_35887_p3() {
sel_tmp886_fu_35887_p3 = (!sel_tmp885_fu_35883_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp885_fu_35883_p2.read()[0].to_bool())? old_word_buffer_1_1_fu_690.read(): sel_tmp884_fu_35877_p3.read());
}
void a0_bin_conv::thread_sel_tmp887_fu_30522_p3() {
sel_tmp887_fu_30522_p3 = (!tmp_153_reg_50656.read()[0].is_01())? sc_lv<2>(): ((tmp_153_reg_50656.read()[0].to_bool())? old_word_buffer_1_2_11_fu_1702.read(): old_word_buffer_1_7_11_fu_1882.read());
}
void a0_bin_conv::thread_sel_tmp888_fu_30529_p3() {
sel_tmp888_fu_30529_p3 = (!tmp_154_reg_50670.read()[0].is_01())? sc_lv<2>(): ((tmp_154_reg_50670.read()[0].to_bool())? old_word_buffer_1_3_11_fu_1738.read(): sel_tmp887_fu_30522_p3.read());
}
void a0_bin_conv::thread_sel_tmp889_fu_30536_p3() {
sel_tmp889_fu_30536_p3 = (!tmp_155_reg_50684.read()[0].is_01())? sc_lv<2>(): ((tmp_155_reg_50684.read()[0].to_bool())? old_word_buffer_1_4_11_fu_1774.read(): sel_tmp888_fu_30529_p3.read());
}
void a0_bin_conv::thread_sel_tmp88_fu_20502_p2() {
sel_tmp88_fu_20502_p2 = (lb_3_reg_45835.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp890_fu_30543_p3() {
sel_tmp890_fu_30543_p3 = (!tmp_156_reg_50698.read()[0].is_01())? sc_lv<2>(): ((tmp_156_reg_50698.read()[0].to_bool())? old_word_buffer_1_5_11_fu_1810.read(): sel_tmp889_fu_30536_p3.read());
}
void a0_bin_conv::thread_sel_tmp891_fu_30572_p3() {
sel_tmp891_fu_30572_p3 = (!tmp_153_reg_50656.read()[0].is_01())? sc_lv<2>(): ((tmp_153_reg_50656.read()[0].to_bool())? old_word_buffer_1_2_13_fu_1710.read(): old_word_buffer_1_7_13_fu_1890.read());
}
void a0_bin_conv::thread_sel_tmp892_fu_30579_p3() {
sel_tmp892_fu_30579_p3 = (!tmp_154_reg_50670.read()[0].is_01())? sc_lv<2>(): ((tmp_154_reg_50670.read()[0].to_bool())? old_word_buffer_1_3_13_fu_1746.read(): sel_tmp891_fu_30572_p3.read());
}
void a0_bin_conv::thread_sel_tmp893_fu_30586_p3() {
sel_tmp893_fu_30586_p3 = (!tmp_155_reg_50684.read()[0].is_01())? sc_lv<2>(): ((tmp_155_reg_50684.read()[0].to_bool())? old_word_buffer_1_4_13_fu_1782.read(): sel_tmp892_fu_30579_p3.read());
}
void a0_bin_conv::thread_sel_tmp894_fu_30593_p3() {
sel_tmp894_fu_30593_p3 = (!tmp_156_reg_50698.read()[0].is_01())? sc_lv<2>(): ((tmp_156_reg_50698.read()[0].to_bool())? old_word_buffer_1_5_13_fu_1818.read(): sel_tmp893_fu_30586_p3.read());
}
void a0_bin_conv::thread_sel_tmp895_fu_30622_p3() {
sel_tmp895_fu_30622_p3 = (!tmp_153_reg_50656.read()[0].is_01())? sc_lv<2>(): ((tmp_153_reg_50656.read()[0].to_bool())? old_word_buffer_1_2_15_fu_1718.read(): old_word_buffer_1_7_15_fu_1898.read());
}
void a0_bin_conv::thread_sel_tmp896_fu_30629_p3() {
sel_tmp896_fu_30629_p3 = (!tmp_154_reg_50670.read()[0].is_01())? sc_lv<2>(): ((tmp_154_reg_50670.read()[0].to_bool())? old_word_buffer_1_3_15_fu_1754.read(): sel_tmp895_fu_30622_p3.read());
}
void a0_bin_conv::thread_sel_tmp897_fu_30636_p3() {
sel_tmp897_fu_30636_p3 = (!tmp_155_reg_50684.read()[0].is_01())? sc_lv<2>(): ((tmp_155_reg_50684.read()[0].to_bool())? old_word_buffer_1_4_15_fu_1790.read(): sel_tmp896_fu_30629_p3.read());
}
void a0_bin_conv::thread_sel_tmp898_fu_30643_p3() {
sel_tmp898_fu_30643_p3 = (!tmp_156_reg_50698.read()[0].is_01())? sc_lv<2>(): ((tmp_156_reg_50698.read()[0].to_bool())? old_word_buffer_1_5_15_fu_1826.read(): sel_tmp897_fu_30636_p3.read());
}
void a0_bin_conv::thread_sel_tmp899_fu_24313_p3() {
sel_tmp899_fu_24313_p3 = (!tmp_153_reg_50656.read()[0].is_01())? sc_lv<2>(): ((tmp_153_reg_50656.read()[0].to_bool())? old_word_buffer_1_2_17_fu_1726.read(): old_word_buffer_1_7_17_fu_1906.read());
}
void a0_bin_conv::thread_sel_tmp89_fu_20507_p2() {
sel_tmp89_fu_20507_p2 = (tmp_168_fu_20424_p2.read() & sel_tmp88_fu_20502_p2.read());
}
void a0_bin_conv::thread_sel_tmp900_fu_24320_p3() {
sel_tmp900_fu_24320_p3 = (!tmp_154_reg_50670.read()[0].is_01())? sc_lv<2>(): ((tmp_154_reg_50670.read()[0].to_bool())? old_word_buffer_1_3_17_fu_1762.read(): sel_tmp899_fu_24313_p3.read());
}
void a0_bin_conv::thread_sel_tmp901_fu_24327_p3() {
sel_tmp901_fu_24327_p3 = (!tmp_155_reg_50684.read()[0].is_01())? sc_lv<2>(): ((tmp_155_reg_50684.read()[0].to_bool())? old_word_buffer_1_4_17_fu_1798.read(): sel_tmp900_fu_24320_p3.read());
}
void a0_bin_conv::thread_sel_tmp902_fu_24334_p3() {
sel_tmp902_fu_24334_p3 = (!tmp_156_reg_50698.read()[0].is_01())? sc_lv<2>(): ((tmp_156_reg_50698.read()[0].to_bool())? old_word_buffer_1_5_17_fu_1834.read(): sel_tmp901_fu_24327_p3.read());
}
void a0_bin_conv::thread_sel_tmp903_fu_24353_p2() {
sel_tmp903_fu_24353_p2 = (tmp_1227_reg_45800.read() & first_wrd_not3_fu_24348_p2.read());
}
void a0_bin_conv::thread_sel_tmp904_fu_30679_p2() {
sel_tmp904_fu_30679_p2 = (tmp_154_reg_50670.read() & sel_tmp903_reg_53830.read());
}
void a0_bin_conv::thread_sel_tmp905_fu_30683_p3() {
sel_tmp905_fu_30683_p3 = (!sel_tmp904_fu_30679_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp904_fu_30679_p2.read()[0].to_bool())? old_word_buffer_1_3_fu_698.read(): old_word_buffer_1_7_fu_714.read());
}
void a0_bin_conv::thread_sel_tmp906_fu_30691_p2() {
sel_tmp906_fu_30691_p2 = (tmp_155_reg_50684.read() & sel_tmp903_reg_53830.read());
}
void a0_bin_conv::thread_sel_tmp907_fu_30695_p3() {
sel_tmp907_fu_30695_p3 = (!sel_tmp906_fu_30691_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp906_fu_30691_p2.read()[0].to_bool())? old_word_buffer_1_4_fu_702.read(): sel_tmp905_fu_30683_p3.read());
}
void a0_bin_conv::thread_sel_tmp908_fu_30703_p2() {
sel_tmp908_fu_30703_p2 = (tmp_156_reg_50698.read() & sel_tmp903_reg_53830.read());
}
void a0_bin_conv::thread_sel_tmp909_fu_30707_p3() {
sel_tmp909_fu_30707_p3 = (!sel_tmp908_fu_30703_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp908_fu_30703_p2.read()[0].to_bool())? old_word_buffer_1_5_fu_706.read(): sel_tmp907_fu_30695_p3.read());
}
void a0_bin_conv::thread_sel_tmp90_fu_20513_p2() {
sel_tmp90_fu_20513_p2 = (tmp_169_fu_20430_p2.read() & sel_tmp88_fu_20502_p2.read());
}
void a0_bin_conv::thread_sel_tmp910_fu_30715_p2() {
sel_tmp910_fu_30715_p2 = (tmp_157_reg_50712.read() & sel_tmp903_reg_53830.read());
}
void a0_bin_conv::thread_sel_tmp911_fu_30719_p3() {
sel_tmp911_fu_30719_p3 = (!sel_tmp910_fu_30715_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp910_fu_30715_p2.read()[0].to_bool())? old_word_buffer_1_6_fu_710.read(): sel_tmp909_fu_30707_p3.read());
}
void a0_bin_conv::thread_sel_tmp912_fu_30727_p2() {
sel_tmp912_fu_30727_p2 = (tmp_153_reg_50656.read() & sel_tmp903_reg_53830.read());
}
void a0_bin_conv::thread_sel_tmp913_fu_30731_p3() {
sel_tmp913_fu_30731_p3 = (!sel_tmp912_fu_30727_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp912_fu_30727_p2.read()[0].to_bool())? old_word_buffer_1_2_fu_694.read(): sel_tmp911_fu_30719_p3.read());
}
void a0_bin_conv::thread_sel_tmp914_fu_35958_p3() {
sel_tmp914_fu_35958_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? word_buffer_1_1_1_reg_54917.read(): word_buffer_1_2_1_reg_54904.read());
}
void a0_bin_conv::thread_sel_tmp915_fu_35969_p3() {
sel_tmp915_fu_35969_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_2_1_reg_53010.read(): ap_reg_pp0_iter2_word_buffer_1_2_2_1_reg_52899.read());
}
void a0_bin_conv::thread_sel_tmp916_fu_35980_p3() {
sel_tmp916_fu_35980_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_3_1_reg_52991.read(): ap_reg_pp0_iter2_word_buffer_1_2_3_1_reg_52882.read());
}
void a0_bin_conv::thread_sel_tmp917_fu_35991_p3() {
sel_tmp917_fu_35991_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_4_1_reg_52972.read(): ap_reg_pp0_iter2_word_buffer_1_2_4_1_reg_52865.read());
}
void a0_bin_conv::thread_sel_tmp918_fu_36002_p3() {
sel_tmp918_fu_36002_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_5_1_reg_52953.read(): ap_reg_pp0_iter2_word_buffer_1_2_5_1_reg_52848.read());
}
void a0_bin_conv::thread_sel_tmp919_fu_36013_p3() {
sel_tmp919_fu_36013_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_6_1_reg_52934.read(): ap_reg_pp0_iter2_word_buffer_1_2_6_1_reg_52831.read());
}
void a0_bin_conv::thread_sel_tmp91_fu_20519_p2() {
sel_tmp91_fu_20519_p2 = (cond6_fu_20126_p2.read() & sel_tmp88_fu_20502_p2.read());
}
void a0_bin_conv::thread_sel_tmp920_fu_36024_p3() {
sel_tmp920_fu_36024_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_7_1_reg_52916.read(): ap_reg_pp0_iter2_word_buffer_1_2_7_1_reg_52815.read());
}
void a0_bin_conv::thread_sel_tmp921_fu_36035_p3() {
sel_tmp921_fu_36035_p3 = (!sel_tmp95_reg_51373.read()[0].is_01())? sc_lv<2>(): ((sel_tmp95_reg_51373.read()[0].to_bool())? word_buffer_1_2_0_reg_55094.read(): word_buffer_1_3_0_1_reg_54888.read());
}
void a0_bin_conv::thread_sel_tmp922_fu_36046_p3() {
sel_tmp922_fu_36046_p3 = (!tmp_173_reg_51413.read()[0].is_01())? sc_lv<2>(): ((tmp_173_reg_51413.read()[0].to_bool())? ap_const_lv2_0: word_buffer_1_2_0_1_reg_55582.read());
}
void a0_bin_conv::thread_sel_tmp923_fu_30759_p3() {
sel_tmp923_fu_30759_p3 = (!tmp_158_reg_50726.read()[0].is_01())? sc_lv<2>(): ((tmp_158_reg_50726.read()[0].to_bool())? old_word_buffer_1_3_11_fu_1738.read(): old_word_buffer_1_7_11_fu_1882.read());
}
void a0_bin_conv::thread_sel_tmp924_fu_30766_p3() {
sel_tmp924_fu_30766_p3 = (!tmp_159_reg_50740.read()[0].is_01())? sc_lv<2>(): ((tmp_159_reg_50740.read()[0].to_bool())? old_word_buffer_1_4_11_fu_1774.read(): sel_tmp923_fu_30759_p3.read());
}
void a0_bin_conv::thread_sel_tmp925_fu_30773_p3() {
sel_tmp925_fu_30773_p3 = (!tmp_160_reg_50754.read()[0].is_01())? sc_lv<2>(): ((tmp_160_reg_50754.read()[0].to_bool())? old_word_buffer_1_5_11_fu_1810.read(): sel_tmp924_fu_30766_p3.read());
}
void a0_bin_conv::thread_sel_tmp926_fu_30799_p3() {
sel_tmp926_fu_30799_p3 = (!tmp_158_reg_50726.read()[0].is_01())? sc_lv<2>(): ((tmp_158_reg_50726.read()[0].to_bool())? old_word_buffer_1_3_13_fu_1746.read(): old_word_buffer_1_7_13_fu_1890.read());
}
void a0_bin_conv::thread_sel_tmp927_fu_30806_p3() {
sel_tmp927_fu_30806_p3 = (!tmp_159_reg_50740.read()[0].is_01())? sc_lv<2>(): ((tmp_159_reg_50740.read()[0].to_bool())? old_word_buffer_1_4_13_fu_1782.read(): sel_tmp926_fu_30799_p3.read());
}
void a0_bin_conv::thread_sel_tmp928_fu_30813_p3() {
sel_tmp928_fu_30813_p3 = (!tmp_160_reg_50754.read()[0].is_01())? sc_lv<2>(): ((tmp_160_reg_50754.read()[0].to_bool())? old_word_buffer_1_5_13_fu_1818.read(): sel_tmp927_fu_30806_p3.read());
}
void a0_bin_conv::thread_sel_tmp929_fu_30839_p3() {
sel_tmp929_fu_30839_p3 = (!tmp_158_reg_50726.read()[0].is_01())? sc_lv<2>(): ((tmp_158_reg_50726.read()[0].to_bool())? old_word_buffer_1_3_15_fu_1754.read(): old_word_buffer_1_7_15_fu_1898.read());
}
void a0_bin_conv::thread_sel_tmp92_fu_20525_p2() {
sel_tmp92_fu_20525_p2 = (lb_4_reg_45859.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp930_fu_30846_p3() {
sel_tmp930_fu_30846_p3 = (!tmp_159_reg_50740.read()[0].is_01())? sc_lv<2>(): ((tmp_159_reg_50740.read()[0].to_bool())? old_word_buffer_1_4_15_fu_1790.read(): sel_tmp929_fu_30839_p3.read());
}
void a0_bin_conv::thread_sel_tmp931_fu_30853_p3() {
sel_tmp931_fu_30853_p3 = (!tmp_160_reg_50754.read()[0].is_01())? sc_lv<2>(): ((tmp_160_reg_50754.read()[0].to_bool())? old_word_buffer_1_5_15_fu_1826.read(): sel_tmp930_fu_30846_p3.read());
}
void a0_bin_conv::thread_sel_tmp932_fu_24370_p3() {
sel_tmp932_fu_24370_p3 = (!tmp_158_reg_50726.read()[0].is_01())? sc_lv<2>(): ((tmp_158_reg_50726.read()[0].to_bool())? old_word_buffer_1_3_17_fu_1762.read(): old_word_buffer_1_7_17_fu_1906.read());
}
void a0_bin_conv::thread_sel_tmp933_fu_24377_p3() {
sel_tmp933_fu_24377_p3 = (!tmp_159_reg_50740.read()[0].is_01())? sc_lv<2>(): ((tmp_159_reg_50740.read()[0].to_bool())? old_word_buffer_1_4_17_fu_1798.read(): sel_tmp932_fu_24370_p3.read());
}
void a0_bin_conv::thread_sel_tmp934_fu_24384_p3() {
sel_tmp934_fu_24384_p3 = (!tmp_160_reg_50754.read()[0].is_01())? sc_lv<2>(): ((tmp_160_reg_50754.read()[0].to_bool())? old_word_buffer_1_5_17_fu_1834.read(): sel_tmp933_fu_24377_p3.read());
}
void a0_bin_conv::thread_sel_tmp935_fu_30882_p2() {
sel_tmp935_fu_30882_p2 = (brmerge45_reg_53848.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp936_fu_30887_p2() {
sel_tmp936_fu_30887_p2 = (tmp_159_reg_50740.read() & sel_tmp935_fu_30882_p2.read());
}
void a0_bin_conv::thread_sel_tmp937_fu_30892_p3() {
sel_tmp937_fu_30892_p3 = (!sel_tmp936_fu_30887_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp936_fu_30887_p2.read()[0].to_bool())? old_word_buffer_1_4_fu_702.read(): old_word_buffer_1_7_fu_714.read());
}
void a0_bin_conv::thread_sel_tmp938_fu_30900_p2() {
sel_tmp938_fu_30900_p2 = (tmp_160_reg_50754.read() & sel_tmp935_fu_30882_p2.read());
}
void a0_bin_conv::thread_sel_tmp939_fu_30905_p3() {
sel_tmp939_fu_30905_p3 = (!sel_tmp938_fu_30900_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp938_fu_30900_p2.read()[0].to_bool())? old_word_buffer_1_5_fu_706.read(): sel_tmp937_fu_30892_p3.read());
}
void a0_bin_conv::thread_sel_tmp93_fu_20530_p2() {
sel_tmp93_fu_20530_p2 = (tmp_168_fu_20424_p2.read() & sel_tmp92_fu_20525_p2.read());
}
void a0_bin_conv::thread_sel_tmp940_fu_30913_p2() {
sel_tmp940_fu_30913_p2 = (tmp_161_reg_50768.read() & sel_tmp935_fu_30882_p2.read());
}
void a0_bin_conv::thread_sel_tmp941_fu_30918_p3() {
sel_tmp941_fu_30918_p3 = (!sel_tmp940_fu_30913_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp940_fu_30913_p2.read()[0].to_bool())? old_word_buffer_1_6_fu_710.read(): sel_tmp939_fu_30905_p3.read());
}
void a0_bin_conv::thread_sel_tmp942_fu_30926_p2() {
sel_tmp942_fu_30926_p2 = (tmp_158_reg_50726.read() & sel_tmp935_fu_30882_p2.read());
}
void a0_bin_conv::thread_sel_tmp943_fu_30931_p3() {
sel_tmp943_fu_30931_p3 = (!sel_tmp942_fu_30926_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp942_fu_30926_p2.read()[0].to_bool())? old_word_buffer_1_3_fu_698.read(): sel_tmp941_fu_30918_p3.read());
}
void a0_bin_conv::thread_sel_tmp944_fu_36062_p3() {
sel_tmp944_fu_36062_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? word_buffer_1_1_1_reg_54917.read(): word_buffer_1_3_1_reg_54846.read());
}
void a0_bin_conv::thread_sel_tmp945_fu_36067_p3() {
sel_tmp945_fu_36067_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? word_buffer_1_2_1_reg_54904.read(): sel_tmp944_fu_36062_p3.read());
}
void a0_bin_conv::thread_sel_tmp946_fu_36079_p3() {
sel_tmp946_fu_36079_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_2_1_reg_53010.read(): ap_reg_pp0_iter2_word_buffer_1_3_2_1_reg_52800.read());
}
void a0_bin_conv::thread_sel_tmp947_fu_36084_p3() {
sel_tmp947_fu_36084_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_2_1_reg_52899.read(): sel_tmp946_fu_36079_p3.read());
}
void a0_bin_conv::thread_sel_tmp948_fu_36096_p3() {
sel_tmp948_fu_36096_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_3_1_reg_52991.read(): ap_reg_pp0_iter2_word_buffer_1_3_3_1_reg_52785.read());
}
void a0_bin_conv::thread_sel_tmp949_fu_36101_p3() {
sel_tmp949_fu_36101_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_3_1_reg_52882.read(): sel_tmp948_fu_36096_p3.read());
}
void a0_bin_conv::thread_sel_tmp94_fu_20536_p2() {
sel_tmp94_fu_20536_p2 = (cond6_fu_20126_p2.read() & sel_tmp92_fu_20525_p2.read());
}
void a0_bin_conv::thread_sel_tmp950_fu_36113_p3() {
sel_tmp950_fu_36113_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_4_1_reg_52972.read(): ap_reg_pp0_iter2_word_buffer_1_3_4_1_reg_52770.read());
}
void a0_bin_conv::thread_sel_tmp951_fu_36118_p3() {
sel_tmp951_fu_36118_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_4_1_reg_52865.read(): sel_tmp950_fu_36113_p3.read());
}
void a0_bin_conv::thread_sel_tmp952_fu_36130_p3() {
sel_tmp952_fu_36130_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_5_1_reg_52953.read(): ap_reg_pp0_iter2_word_buffer_1_3_5_1_reg_52755.read());
}
void a0_bin_conv::thread_sel_tmp953_fu_36135_p3() {
sel_tmp953_fu_36135_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_5_1_reg_52848.read(): sel_tmp952_fu_36130_p3.read());
}
void a0_bin_conv::thread_sel_tmp954_fu_36147_p3() {
sel_tmp954_fu_36147_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_6_1_reg_52934.read(): ap_reg_pp0_iter2_word_buffer_1_3_6_1_reg_52740.read());
}
void a0_bin_conv::thread_sel_tmp955_fu_36152_p3() {
sel_tmp955_fu_36152_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_6_1_reg_52831.read(): sel_tmp954_fu_36147_p3.read());
}
void a0_bin_conv::thread_sel_tmp956_fu_36164_p3() {
sel_tmp956_fu_36164_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_7_1_reg_52916.read(): ap_reg_pp0_iter2_word_buffer_1_3_7_1_reg_52726.read());
}
void a0_bin_conv::thread_sel_tmp957_fu_36169_p3() {
sel_tmp957_fu_36169_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_7_1_reg_52815.read(): sel_tmp956_fu_36164_p3.read());
}
void a0_bin_conv::thread_sel_tmp958_fu_36181_p3() {
sel_tmp958_fu_36181_p3 = (!sel_tmp99_reg_51425.read()[0].is_01())? sc_lv<2>(): ((sel_tmp99_reg_51425.read()[0].to_bool())? word_buffer_1_2_0_reg_55094.read(): word_buffer_1_4_0_1_reg_54832.read());
}
void a0_bin_conv::thread_sel_tmp959_fu_36186_p3() {
sel_tmp959_fu_36186_p3 = (!sel_tmp100_reg_51445.read()[0].is_01())? sc_lv<2>(): ((sel_tmp100_reg_51445.read()[0].to_bool())? word_buffer_1_3_0_1_reg_54888.read(): sel_tmp958_fu_36181_p3.read());
}
void a0_bin_conv::thread_sel_tmp95_fu_20547_p2() {
sel_tmp95_fu_20547_p2 = (!tmp_1243_fu_20204_p1.read().is_01() || !ap_const_lv3_1.is_01())? sc_lv<1>(): sc_lv<1>(tmp_1243_fu_20204_p1.read() == ap_const_lv3_1);
}
void a0_bin_conv::thread_sel_tmp960_fu_36198_p3() {
sel_tmp960_fu_36198_p3 = (!tmp_174_reg_51465.read()[0].is_01())? sc_lv<2>(): ((tmp_174_reg_51465.read()[0].to_bool())? ap_const_lv2_0: word_buffer_1_3_0_reg_54858.read());
}
void a0_bin_conv::thread_sel_tmp961_fu_36204_p3() {
sel_tmp961_fu_36204_p3 = (!sel_tmp102_reg_51471.read()[0].is_01())? sc_lv<2>(): ((sel_tmp102_reg_51471.read()[0].to_bool())? word_buffer_1_1_0_reg_54929.read(): sel_tmp960_fu_36198_p3.read());
}
void a0_bin_conv::thread_sel_tmp962_fu_30955_p3() {
sel_tmp962_fu_30955_p3 = (!tmp_162_reg_50782.read()[0].is_01())? sc_lv<2>(): ((tmp_162_reg_50782.read()[0].to_bool())? old_word_buffer_1_4_11_fu_1774.read(): old_word_buffer_1_7_11_fu_1882.read());
}
void a0_bin_conv::thread_sel_tmp963_fu_30962_p3() {
sel_tmp963_fu_30962_p3 = (!tmp_163_reg_50796.read()[0].is_01())? sc_lv<2>(): ((tmp_163_reg_50796.read()[0].to_bool())? old_word_buffer_1_5_11_fu_1810.read(): sel_tmp962_fu_30955_p3.read());
}
void a0_bin_conv::thread_sel_tmp964_fu_30985_p3() {
sel_tmp964_fu_30985_p3 = (!tmp_162_reg_50782.read()[0].is_01())? sc_lv<2>(): ((tmp_162_reg_50782.read()[0].to_bool())? old_word_buffer_1_4_13_fu_1782.read(): old_word_buffer_1_7_13_fu_1890.read());
}
void a0_bin_conv::thread_sel_tmp965_fu_30992_p3() {
sel_tmp965_fu_30992_p3 = (!tmp_163_reg_50796.read()[0].is_01())? sc_lv<2>(): ((tmp_163_reg_50796.read()[0].to_bool())? old_word_buffer_1_5_13_fu_1818.read(): sel_tmp964_fu_30985_p3.read());
}
void a0_bin_conv::thread_sel_tmp966_fu_31015_p3() {
sel_tmp966_fu_31015_p3 = (!tmp_162_reg_50782.read()[0].is_01())? sc_lv<2>(): ((tmp_162_reg_50782.read()[0].to_bool())? old_word_buffer_1_4_15_fu_1790.read(): old_word_buffer_1_7_15_fu_1898.read());
}
void a0_bin_conv::thread_sel_tmp967_fu_31022_p3() {
sel_tmp967_fu_31022_p3 = (!tmp_163_reg_50796.read()[0].is_01())? sc_lv<2>(): ((tmp_163_reg_50796.read()[0].to_bool())? old_word_buffer_1_5_15_fu_1826.read(): sel_tmp966_fu_31015_p3.read());
}
void a0_bin_conv::thread_sel_tmp968_fu_24411_p3() {
sel_tmp968_fu_24411_p3 = (!tmp_162_reg_50782.read()[0].is_01())? sc_lv<2>(): ((tmp_162_reg_50782.read()[0].to_bool())? old_word_buffer_1_4_17_fu_1798.read(): old_word_buffer_1_7_17_fu_1906.read());
}
void a0_bin_conv::thread_sel_tmp969_fu_24418_p3() {
sel_tmp969_fu_24418_p3 = (!tmp_163_reg_50796.read()[0].is_01())? sc_lv<2>(): ((tmp_163_reg_50796.read()[0].to_bool())? old_word_buffer_1_5_17_fu_1834.read(): sel_tmp968_fu_24411_p3.read());
}
void a0_bin_conv::thread_sel_tmp96_fu_20553_p2() {
sel_tmp96_fu_20553_p2 = (!tmp_1243_fu_20204_p1.read().is_01() || !ap_const_lv3_0.is_01())? sc_lv<1>(): sc_lv<1>(tmp_1243_fu_20204_p1.read() == ap_const_lv3_0);
}
void a0_bin_conv::thread_sel_tmp970_fu_31052_p2() {
sel_tmp970_fu_31052_p2 = (brmerge47_fu_31048_p2.read() ^ ap_const_lv1_1);
}
void a0_bin_conv::thread_sel_tmp971_fu_31058_p2() {
sel_tmp971_fu_31058_p2 = (tmp_163_reg_50796.read() & sel_tmp970_fu_31052_p2.read());
}
void a0_bin_conv::thread_sel_tmp972_fu_31063_p3() {
sel_tmp972_fu_31063_p3 = (!sel_tmp971_fu_31058_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp971_fu_31058_p2.read()[0].to_bool())? old_word_buffer_1_5_fu_706.read(): old_word_buffer_1_7_fu_714.read());
}
void a0_bin_conv::thread_sel_tmp973_fu_31071_p2() {
sel_tmp973_fu_31071_p2 = (tmp_164_reg_50810.read() & sel_tmp970_fu_31052_p2.read());
}
void a0_bin_conv::thread_sel_tmp974_fu_31076_p3() {
sel_tmp974_fu_31076_p3 = (!sel_tmp973_fu_31071_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp973_fu_31071_p2.read()[0].to_bool())? old_word_buffer_1_6_fu_710.read(): sel_tmp972_fu_31063_p3.read());
}
void a0_bin_conv::thread_sel_tmp975_fu_31084_p2() {
sel_tmp975_fu_31084_p2 = (tmp_162_reg_50782.read() & sel_tmp970_fu_31052_p2.read());
}
void a0_bin_conv::thread_sel_tmp976_fu_31089_p3() {
sel_tmp976_fu_31089_p3 = (!sel_tmp975_fu_31084_p2.read()[0].is_01())? sc_lv<2>(): ((sel_tmp975_fu_31084_p2.read()[0].to_bool())? old_word_buffer_1_4_fu_702.read(): sel_tmp974_fu_31076_p3.read());
}
void a0_bin_conv::thread_sel_tmp977_fu_36220_p3() {
sel_tmp977_fu_36220_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? word_buffer_1_1_1_reg_54917.read(): word_buffer_1_4_1_reg_54795.read());
}
void a0_bin_conv::thread_sel_tmp978_fu_36225_p3() {
sel_tmp978_fu_36225_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? word_buffer_1_2_1_reg_54904.read(): sel_tmp977_fu_36220_p3.read());
}
void a0_bin_conv::thread_sel_tmp979_fu_36231_p3() {
sel_tmp979_fu_36231_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? word_buffer_1_3_1_reg_54846.read(): sel_tmp978_fu_36225_p3.read());
}
void a0_bin_conv::thread_sel_tmp97_fu_20559_p2() {
sel_tmp97_fu_20559_p2 = (sel_tmp96_fu_20553_p2.read() & sel_tmp88_fu_20502_p2.read());
}
void a0_bin_conv::thread_sel_tmp980_fu_36243_p3() {
sel_tmp980_fu_36243_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_2_1_reg_53010.read(): ap_reg_pp0_iter2_word_buffer_1_4_2_1_reg_52713.read());
}
void a0_bin_conv::thread_sel_tmp981_fu_36248_p3() {
sel_tmp981_fu_36248_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_2_1_reg_52899.read(): sel_tmp980_fu_36243_p3.read());
}
void a0_bin_conv::thread_sel_tmp982_fu_36254_p3() {
sel_tmp982_fu_36254_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_3_2_1_reg_52800.read(): sel_tmp981_fu_36248_p3.read());
}
void a0_bin_conv::thread_sel_tmp983_fu_36266_p3() {
sel_tmp983_fu_36266_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_3_1_reg_52991.read(): ap_reg_pp0_iter2_word_buffer_1_4_3_1_reg_52700.read());
}
void a0_bin_conv::thread_sel_tmp984_fu_36271_p3() {
sel_tmp984_fu_36271_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_3_1_reg_52882.read(): sel_tmp983_fu_36266_p3.read());
}
void a0_bin_conv::thread_sel_tmp985_fu_36277_p3() {
sel_tmp985_fu_36277_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_3_3_1_reg_52785.read(): sel_tmp984_fu_36271_p3.read());
}
void a0_bin_conv::thread_sel_tmp986_fu_36289_p3() {
sel_tmp986_fu_36289_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_4_1_reg_52972.read(): ap_reg_pp0_iter2_word_buffer_1_4_4_1_reg_52687.read());
}
void a0_bin_conv::thread_sel_tmp987_fu_36294_p3() {
sel_tmp987_fu_36294_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_4_1_reg_52865.read(): sel_tmp986_fu_36289_p3.read());
}
void a0_bin_conv::thread_sel_tmp988_fu_36300_p3() {
sel_tmp988_fu_36300_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_3_4_1_reg_52770.read(): sel_tmp987_fu_36294_p3.read());
}
void a0_bin_conv::thread_sel_tmp989_fu_36312_p3() {
sel_tmp989_fu_36312_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_5_1_reg_52953.read(): ap_reg_pp0_iter2_word_buffer_1_4_5_1_reg_52674.read());
}
void a0_bin_conv::thread_sel_tmp98_fu_20570_p2() {
sel_tmp98_fu_20570_p2 = (sel_tmp95_fu_20547_p2.read() & sel_tmp88_fu_20502_p2.read());
}
void a0_bin_conv::thread_sel_tmp990_fu_36317_p3() {
sel_tmp990_fu_36317_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_5_1_reg_52848.read(): sel_tmp989_fu_36312_p3.read());
}
void a0_bin_conv::thread_sel_tmp991_fu_36323_p3() {
sel_tmp991_fu_36323_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_3_5_1_reg_52755.read(): sel_tmp990_fu_36317_p3.read());
}
void a0_bin_conv::thread_sel_tmp992_fu_36335_p3() {
sel_tmp992_fu_36335_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_6_1_reg_52934.read(): ap_reg_pp0_iter2_word_buffer_1_4_6_1_reg_52661.read());
}
void a0_bin_conv::thread_sel_tmp993_fu_36340_p3() {
sel_tmp993_fu_36340_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_6_1_reg_52831.read(): sel_tmp992_fu_36335_p3.read());
}
void a0_bin_conv::thread_sel_tmp994_fu_36346_p3() {
sel_tmp994_fu_36346_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_3_6_1_reg_52740.read(): sel_tmp993_fu_36340_p3.read());
}
void a0_bin_conv::thread_sel_tmp995_fu_36358_p3() {
sel_tmp995_fu_36358_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_1_7_1_reg_52916.read(): ap_reg_pp0_iter2_word_buffer_1_4_7_1_reg_52649.read());
}
void a0_bin_conv::thread_sel_tmp996_fu_36363_p3() {
sel_tmp996_fu_36363_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_2_7_1_reg_52815.read(): sel_tmp995_fu_36358_p3.read());
}
void a0_bin_conv::thread_sel_tmp997_fu_36369_p3() {
sel_tmp997_fu_36369_p3 = (!sel_tmp106_reg_51523.read()[0].is_01())? sc_lv<2>(): ((sel_tmp106_reg_51523.read()[0].to_bool())? ap_reg_pp0_iter2_word_buffer_1_3_7_1_reg_52726.read(): sel_tmp996_fu_36363_p3.read());
}
void a0_bin_conv::thread_sel_tmp998_fu_36381_p3() {
sel_tmp998_fu_36381_p3 = (!sel_tmp104_reg_51483.read()[0].is_01())? sc_lv<2>(): ((sel_tmp104_reg_51483.read()[0].to_bool())? word_buffer_1_2_0_reg_55094.read(): word_buffer_1_5_0_1_reg_54783.read());
}
void a0_bin_conv::thread_sel_tmp999_fu_36386_p3() {
sel_tmp999_fu_36386_p3 = (!sel_tmp105_reg_51503.read()[0].is_01())? sc_lv<2>(): ((sel_tmp105_reg_51503.read()[0].to_bool())? word_buffer_1_3_0_1_reg_54888.read(): sel_tmp998_fu_36381_p3.read());
}
void a0_bin_conv::thread_sel_tmp99_fu_20576_p2() {
sel_tmp99_fu_20576_p2 = (!r_V_64_0_4_cast_fu_20208_p2.read().is_01() || !ap_const_lv3_1.is_01())? sc_lv<1>(): sc_lv<1>(r_V_64_0_4_cast_fu_20208_p2.read() == ap_const_lv3_1);
}
void a0_bin_conv::thread_sel_tmp_fu_26075_p3() {
sel_tmp_fu_26075_p3 = (!cond6_reg_50242.read()[0].is_01())? sc_lv<2>(): ((cond6_reg_50242.read()[0].to_bool())? old_word_buffer_0_1_11_fu_1382.read(): old_word_buffer_0_7_10_fu_1594.read());
}
void a0_bin_conv::thread_storemerge1_fu_37020_p3() {
storemerge1_fu_37020_p3 = (!ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].is_01())? sc_lv<2>(): ((ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].to_bool())? ap_const_lv2_0: old_word_buffer_1_7_43_reg_54610.read());
}
void a0_bin_conv::thread_storemerge2_fu_37032_p3() {
storemerge2_fu_37032_p3 = (!ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].is_01())? sc_lv<2>(): ((ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].to_bool())? ap_const_lv2_0: old_word_buffer_1_7_45_reg_54634.read());
}
void a0_bin_conv::thread_storemerge3_fu_37044_p3() {
storemerge3_fu_37044_p3 = (!ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].is_01())? sc_lv<2>(): ((ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].to_bool())? ap_const_lv2_0: old_word_buffer_1_7_47_reg_54658.read());
}
void a0_bin_conv::thread_storemerge4_fu_37056_p3() {
storemerge4_fu_37056_p3 = (!ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].is_01())? sc_lv<2>(): ((ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].to_bool())? ap_const_lv2_0: ap_reg_pp0_iter2_old_word_buffer_1_7_49_reg_52231.read());
}
void a0_bin_conv::thread_storemerge5_fu_34711_p3() {
storemerge5_fu_34711_p3 = (!ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].is_01())? sc_lv<2>(): ((ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].to_bool())? ap_const_lv2_0: old_word_buffer_0_7_42_reg_54206.read());
}
void a0_bin_conv::thread_storemerge6_fu_34723_p3() {
storemerge6_fu_34723_p3 = (!ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].is_01())? sc_lv<2>(): ((ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].to_bool())? ap_const_lv2_0: old_word_buffer_0_7_44_reg_54230.read());
}
void a0_bin_conv::thread_storemerge7_fu_34735_p3() {
storemerge7_fu_34735_p3 = (!ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].is_01())? sc_lv<2>(): ((ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].to_bool())? ap_const_lv2_0: old_word_buffer_0_7_46_reg_54254.read());
}
void a0_bin_conv::thread_storemerge8_fu_34747_p3() {
storemerge8_fu_34747_p3 = (!ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].is_01())? sc_lv<2>(): ((ap_reg_pp0_iter2_first_wrd_reg_51897.read()[0].to_bool())? ap_const_lv2_0: ap_reg_pp0_iter2_old_word_buffer_0_7_48_reg_52184.read());
}
void a0_bin_conv::thread_storemerge_phi_fu_6214_p4() {
if (esl_seteq<1,1,1>(ap_condition_10219.read(), ap_const_boolean_1)) {
if (esl_seteq<1,1,1>(ap_const_lv1_1, tmp_130_fu_20930_p2.read())) {
storemerge_phi_fu_6214_p4 = ap_const_lv3_0;
} else if (esl_seteq<1,1,1>(ap_const_lv1_0, tmp_130_fu_20930_p2.read())) {
storemerge_phi_fu_6214_p4 = tmp_135_fu_20936_p2.read();
} else {
storemerge_phi_fu_6214_p4 = ap_phi_precharge_reg_pp0_iter1_storemerge_reg_6211.read();
}
} else {
storemerge_phi_fu_6214_p4 = ap_phi_precharge_reg_pp0_iter1_storemerge_reg_6211.read();
}
}
void a0_bin_conv::thread_t_V_2_phi_fu_6192_p4() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_51888.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter1.read()) &&
esl_seteq<1,1,1>(ap_block_pp0_stage0.read(), ap_const_boolean_0))) {
t_V_2_phi_fu_6192_p4 = wrd_phase_V_1_reg_52179.read();
} else {
t_V_2_phi_fu_6192_p4 = t_V_2_reg_6188.read();
}
}
void a0_bin_conv::thread_tmp3588_cast_fu_41576_p1() {
tmp3588_cast_fu_41576_p1 = esl_sext<12,6>(tmp669_reg_59109.read());
}
void a0_bin_conv::thread_tmp3589_cast_fu_41586_p1() {
tmp3589_cast_fu_41586_p1 = esl_sext<12,6>(tmp670_reg_59120.read());
}
void a0_bin_conv::thread_tmp3590_cast_fu_41596_p1() {
tmp3590_cast_fu_41596_p1 = esl_sext<12,6>(tmp671_reg_59131.read());
}
void a0_bin_conv::thread_tmp3591_cast_fu_41606_p1() {
tmp3591_cast_fu_41606_p1 = esl_sext<12,6>(tmp672_reg_59142.read());
}
void a0_bin_conv::thread_tmp3592_cast_fu_41616_p1() {
tmp3592_cast_fu_41616_p1 = esl_sext<12,6>(tmp673_reg_59153.read());
}
void a0_bin_conv::thread_tmp3593_cast_fu_41626_p1() {
tmp3593_cast_fu_41626_p1 = esl_sext<12,6>(tmp674_reg_59164.read());
}
void a0_bin_conv::thread_tmp3594_cast_fu_41636_p1() {
tmp3594_cast_fu_41636_p1 = esl_sext<12,6>(tmp675_reg_59175.read());
}
void a0_bin_conv::thread_tmp3595_cast_fu_41646_p1() {
tmp3595_cast_fu_41646_p1 = esl_sext<12,6>(tmp676_reg_59186.read());
}
void a0_bin_conv::thread_tmp3596_cast_fu_41656_p1() {
tmp3596_cast_fu_41656_p1 = esl_sext<12,6>(tmp677_reg_59197.read());
}
void a0_bin_conv::thread_tmp3597_cast_fu_41666_p1() {
tmp3597_cast_fu_41666_p1 = esl_sext<12,6>(tmp678_reg_59208.read());
}
void a0_bin_conv::thread_tmp3598_cast_fu_41676_p1() {
tmp3598_cast_fu_41676_p1 = esl_sext<12,6>(tmp679_reg_59219.read());
}
void a0_bin_conv::thread_tmp3599_cast_fu_41686_p1() {
tmp3599_cast_fu_41686_p1 = esl_sext<12,6>(tmp680_reg_59230.read());
}
void a0_bin_conv::thread_tmp3600_cast_fu_41696_p1() {
tmp3600_cast_fu_41696_p1 = esl_sext<12,6>(tmp681_reg_59241.read());
}
void a0_bin_conv::thread_tmp3601_cast_fu_41706_p1() {
tmp3601_cast_fu_41706_p1 = esl_sext<12,6>(tmp682_reg_59252.read());
}
void a0_bin_conv::thread_tmp3602_cast_fu_41716_p1() {
tmp3602_cast_fu_41716_p1 = esl_sext<12,6>(tmp683_reg_59263.read());
}
void a0_bin_conv::thread_tmp3603_cast_fu_41726_p1() {
tmp3603_cast_fu_41726_p1 = esl_sext<12,6>(tmp684_reg_59274.read());
}
void a0_bin_conv::thread_tmp3604_cast_fu_41736_p1() {
tmp3604_cast_fu_41736_p1 = esl_sext<12,6>(tmp685_reg_59285.read());
}
void a0_bin_conv::thread_tmp3605_cast_fu_41746_p1() {
tmp3605_cast_fu_41746_p1 = esl_sext<12,6>(tmp686_reg_59296.read());
}
void a0_bin_conv::thread_tmp3606_cast_fu_41756_p1() {
tmp3606_cast_fu_41756_p1 = esl_sext<12,6>(tmp687_reg_59307.read());
}
void a0_bin_conv::thread_tmp3607_cast_fu_41766_p1() {
tmp3607_cast_fu_41766_p1 = esl_sext<12,6>(tmp688_reg_59318.read());
}
void a0_bin_conv::thread_tmp3608_cast_fu_41776_p1() {
tmp3608_cast_fu_41776_p1 = esl_sext<12,6>(tmp689_reg_59329.read());
}
void a0_bin_conv::thread_tmp3609_cast_fu_41786_p1() {
tmp3609_cast_fu_41786_p1 = esl_sext<12,6>(tmp690_reg_59340.read());
}
void a0_bin_conv::thread_tmp3610_cast_fu_41796_p1() {
tmp3610_cast_fu_41796_p1 = esl_sext<12,6>(tmp691_reg_59351.read());
}
void a0_bin_conv::thread_tmp3611_cast_fu_41806_p1() {
tmp3611_cast_fu_41806_p1 = esl_sext<12,6>(tmp692_reg_59362.read());
}
void a0_bin_conv::thread_tmp3612_cast_fu_41816_p1() {
tmp3612_cast_fu_41816_p1 = esl_sext<12,6>(tmp693_reg_59373.read());
}
void a0_bin_conv::thread_tmp3613_cast_fu_41826_p1() {
tmp3613_cast_fu_41826_p1 = esl_sext<12,6>(tmp694_reg_59384.read());
}
void a0_bin_conv::thread_tmp3614_cast_fu_41836_p1() {
tmp3614_cast_fu_41836_p1 = esl_sext<12,6>(tmp695_reg_59395.read());
}
void a0_bin_conv::thread_tmp3615_cast_fu_41846_p1() {
tmp3615_cast_fu_41846_p1 = esl_sext<12,6>(tmp696_reg_59406.read());
}
void a0_bin_conv::thread_tmp3616_cast_fu_41856_p1() {
tmp3616_cast_fu_41856_p1 = esl_sext<12,6>(tmp697_reg_59417.read());
}
void a0_bin_conv::thread_tmp3617_cast_fu_41866_p1() {
tmp3617_cast_fu_41866_p1 = esl_sext<12,6>(tmp698_reg_59428.read());
}
void a0_bin_conv::thread_tmp3618_cast_fu_41876_p1() {
tmp3618_cast_fu_41876_p1 = esl_sext<12,6>(tmp699_reg_59439.read());
}
void a0_bin_conv::thread_tmp3619_cast_fu_41886_p1() {
tmp3619_cast_fu_41886_p1 = esl_sext<12,6>(tmp700_reg_59450.read());
}
void a0_bin_conv::thread_tmp3620_cast_fu_41896_p1() {
tmp3620_cast_fu_41896_p1 = esl_sext<12,6>(tmp701_reg_59461.read());
}
void a0_bin_conv::thread_tmp3621_cast_fu_41906_p1() {
tmp3621_cast_fu_41906_p1 = esl_sext<12,6>(tmp702_reg_59472.read());
}
void a0_bin_conv::thread_tmp3622_cast_fu_41916_p1() {
tmp3622_cast_fu_41916_p1 = esl_sext<12,6>(tmp703_reg_59483.read());
}
void a0_bin_conv::thread_tmp3623_cast_fu_41926_p1() {
tmp3623_cast_fu_41926_p1 = esl_sext<12,6>(tmp704_reg_59494.read());
}
void a0_bin_conv::thread_tmp3624_cast_fu_41936_p1() {
tmp3624_cast_fu_41936_p1 = esl_sext<12,6>(tmp705_reg_59505.read());
}
void a0_bin_conv::thread_tmp3625_cast_fu_41946_p1() {
tmp3625_cast_fu_41946_p1 = esl_sext<12,6>(tmp706_reg_59516.read());
}
void a0_bin_conv::thread_tmp3626_cast_fu_41956_p1() {
tmp3626_cast_fu_41956_p1 = esl_sext<12,6>(tmp707_reg_59527.read());
}
void a0_bin_conv::thread_tmp3627_cast_fu_41966_p1() {
tmp3627_cast_fu_41966_p1 = esl_sext<12,6>(tmp708_reg_59538.read());
}
void a0_bin_conv::thread_tmp3628_cast_fu_41976_p1() {
tmp3628_cast_fu_41976_p1 = esl_sext<12,6>(tmp709_reg_59549.read());
}
void a0_bin_conv::thread_tmp3629_cast_fu_41986_p1() {
tmp3629_cast_fu_41986_p1 = esl_sext<12,6>(tmp710_reg_59560.read());
}
void a0_bin_conv::thread_tmp3630_cast_fu_41996_p1() {
tmp3630_cast_fu_41996_p1 = esl_sext<12,6>(tmp711_reg_59571.read());
}
void a0_bin_conv::thread_tmp3631_cast_fu_42006_p1() {
tmp3631_cast_fu_42006_p1 = esl_sext<12,6>(tmp712_reg_59582.read());
}
void a0_bin_conv::thread_tmp3632_cast_fu_42016_p1() {
tmp3632_cast_fu_42016_p1 = esl_sext<12,6>(tmp713_reg_59593.read());
}
void a0_bin_conv::thread_tmp3633_cast_fu_42026_p1() {
tmp3633_cast_fu_42026_p1 = esl_sext<12,6>(tmp714_reg_59604.read());
}
void a0_bin_conv::thread_tmp3634_cast_fu_42036_p1() {
tmp3634_cast_fu_42036_p1 = esl_sext<12,6>(tmp715_reg_59615.read());
}
void a0_bin_conv::thread_tmp3635_cast_fu_42046_p1() {
tmp3635_cast_fu_42046_p1 = esl_sext<12,6>(tmp716_reg_59626.read());
}
void a0_bin_conv::thread_tmp3636_cast_fu_42056_p1() {
tmp3636_cast_fu_42056_p1 = esl_sext<12,6>(tmp717_reg_59637.read());
}
void a0_bin_conv::thread_tmp3637_cast_fu_42066_p1() {
tmp3637_cast_fu_42066_p1 = esl_sext<12,6>(tmp718_reg_59648.read());
}
void a0_bin_conv::thread_tmp3638_cast_fu_42076_p1() {
tmp3638_cast_fu_42076_p1 = esl_sext<12,6>(tmp719_reg_59659.read());
}
void a0_bin_conv::thread_tmp3639_cast_fu_42086_p1() {
tmp3639_cast_fu_42086_p1 = esl_sext<12,6>(tmp720_reg_59670.read());
}
void a0_bin_conv::thread_tmp3640_cast_fu_42096_p1() {
tmp3640_cast_fu_42096_p1 = esl_sext<12,6>(tmp721_reg_59681.read());
}
void a0_bin_conv::thread_tmp3641_cast_fu_42106_p1() {
tmp3641_cast_fu_42106_p1 = esl_sext<12,6>(tmp722_reg_59692.read());
}
void a0_bin_conv::thread_tmp3642_cast_fu_42116_p1() {
tmp3642_cast_fu_42116_p1 = esl_sext<12,6>(tmp723_reg_59703.read());
}
void a0_bin_conv::thread_tmp3643_cast_fu_42126_p1() {
tmp3643_cast_fu_42126_p1 = esl_sext<12,6>(tmp724_reg_59714.read());
}
void a0_bin_conv::thread_tmp3644_cast_fu_42136_p1() {
tmp3644_cast_fu_42136_p1 = esl_sext<12,6>(tmp725_reg_59725.read());
}
void a0_bin_conv::thread_tmp3645_cast_fu_42146_p1() {
tmp3645_cast_fu_42146_p1 = esl_sext<12,6>(tmp726_reg_59736.read());
}
void a0_bin_conv::thread_tmp3646_cast_fu_42156_p1() {
tmp3646_cast_fu_42156_p1 = esl_sext<12,6>(tmp727_reg_59747.read());
}
void a0_bin_conv::thread_tmp3647_cast_fu_42166_p1() {
tmp3647_cast_fu_42166_p1 = esl_sext<12,6>(tmp728_reg_59758.read());
}
void a0_bin_conv::thread_tmp3648_cast_fu_42176_p1() {
tmp3648_cast_fu_42176_p1 = esl_sext<12,6>(tmp729_reg_59769.read());
}
void a0_bin_conv::thread_tmp3649_cast_fu_42186_p1() {
tmp3649_cast_fu_42186_p1 = esl_sext<12,6>(tmp730_reg_59780.read());
}
void a0_bin_conv::thread_tmp3650_cast_fu_42196_p1() {
tmp3650_cast_fu_42196_p1 = esl_sext<12,6>(tmp731_reg_59791.read());
}
void a0_bin_conv::thread_tmp3651_cast_fu_42206_p1() {
tmp3651_cast_fu_42206_p1 = esl_sext<12,6>(tmp732_reg_59802.read());
}
void a0_bin_conv::thread_tmp669_fu_40688_p2() {
tmp669_fu_40688_p2 = (!tmp_361_0_1_cast_fu_40684_p1.read().is_01() || !tmp_361_cast_fu_40680_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_0_1_cast_fu_40684_p1.read()) + sc_bigint<6>(tmp_361_cast_fu_40680_p1.read()));
}
void a0_bin_conv::thread_tmp670_fu_40702_p2() {
tmp670_fu_40702_p2 = (!tmp_361_1_1_cast_fu_40698_p1.read().is_01() || !tmp_361_1_cast_fu_40694_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_1_1_cast_fu_40698_p1.read()) + sc_bigint<6>(tmp_361_1_cast_fu_40694_p1.read()));
}
void a0_bin_conv::thread_tmp671_fu_40716_p2() {
tmp671_fu_40716_p2 = (!tmp_361_2_1_cast_fu_40712_p1.read().is_01() || !tmp_361_2_cast_fu_40708_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_2_1_cast_fu_40712_p1.read()) + sc_bigint<6>(tmp_361_2_cast_fu_40708_p1.read()));
}
void a0_bin_conv::thread_tmp672_fu_40730_p2() {
tmp672_fu_40730_p2 = (!tmp_361_3_1_cast_fu_40726_p1.read().is_01() || !tmp_361_3_cast_fu_40722_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_3_1_cast_fu_40726_p1.read()) + sc_bigint<6>(tmp_361_3_cast_fu_40722_p1.read()));
}
void a0_bin_conv::thread_tmp673_fu_40744_p2() {
tmp673_fu_40744_p2 = (!tmp_361_4_1_cast_fu_40740_p1.read().is_01() || !tmp_361_4_cast_fu_40736_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_4_1_cast_fu_40740_p1.read()) + sc_bigint<6>(tmp_361_4_cast_fu_40736_p1.read()));
}
void a0_bin_conv::thread_tmp674_fu_40758_p2() {
tmp674_fu_40758_p2 = (!tmp_361_5_1_cast_fu_40754_p1.read().is_01() || !tmp_361_5_cast_fu_40750_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_5_1_cast_fu_40754_p1.read()) + sc_bigint<6>(tmp_361_5_cast_fu_40750_p1.read()));
}
void a0_bin_conv::thread_tmp675_fu_40772_p2() {
tmp675_fu_40772_p2 = (!tmp_361_6_1_cast_fu_40768_p1.read().is_01() || !tmp_361_6_cast_fu_40764_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_6_1_cast_fu_40768_p1.read()) + sc_bigint<6>(tmp_361_6_cast_fu_40764_p1.read()));
}
void a0_bin_conv::thread_tmp676_fu_40786_p2() {
tmp676_fu_40786_p2 = (!tmp_361_7_1_cast_fu_40782_p1.read().is_01() || !tmp_361_7_cast_fu_40778_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_7_1_cast_fu_40782_p1.read()) + sc_bigint<6>(tmp_361_7_cast_fu_40778_p1.read()));
}
void a0_bin_conv::thread_tmp677_fu_40800_p2() {
tmp677_fu_40800_p2 = (!tmp_361_8_1_cast_fu_40796_p1.read().is_01() || !tmp_361_8_cast_fu_40792_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_8_1_cast_fu_40796_p1.read()) + sc_bigint<6>(tmp_361_8_cast_fu_40792_p1.read()));
}
void a0_bin_conv::thread_tmp678_fu_40814_p2() {
tmp678_fu_40814_p2 = (!tmp_361_9_1_cast_fu_40810_p1.read().is_01() || !tmp_361_9_cast_fu_40806_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_9_1_cast_fu_40810_p1.read()) + sc_bigint<6>(tmp_361_9_cast_fu_40806_p1.read()));
}
void a0_bin_conv::thread_tmp679_fu_40828_p2() {
tmp679_fu_40828_p2 = (!tmp_361_10_1_cast_fu_40824_p1.read().is_01() || !tmp_361_cast_65_fu_40820_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_10_1_cast_fu_40824_p1.read()) + sc_bigint<6>(tmp_361_cast_65_fu_40820_p1.read()));
}
void a0_bin_conv::thread_tmp680_fu_40842_p2() {
tmp680_fu_40842_p2 = (!tmp_361_11_1_cast_fu_40838_p1.read().is_01() || !tmp_361_10_cast_fu_40834_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_11_1_cast_fu_40838_p1.read()) + sc_bigint<6>(tmp_361_10_cast_fu_40834_p1.read()));
}
void a0_bin_conv::thread_tmp681_fu_40856_p2() {
tmp681_fu_40856_p2 = (!tmp_361_12_1_cast_fu_40852_p1.read().is_01() || !tmp_361_11_cast_fu_40848_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_12_1_cast_fu_40852_p1.read()) + sc_bigint<6>(tmp_361_11_cast_fu_40848_p1.read()));
}
void a0_bin_conv::thread_tmp682_fu_40870_p2() {
tmp682_fu_40870_p2 = (!tmp_361_13_1_cast_fu_40866_p1.read().is_01() || !tmp_361_12_cast_fu_40862_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_13_1_cast_fu_40866_p1.read()) + sc_bigint<6>(tmp_361_12_cast_fu_40862_p1.read()));
}
void a0_bin_conv::thread_tmp683_fu_40884_p2() {
tmp683_fu_40884_p2 = (!tmp_361_14_1_cast_fu_40880_p1.read().is_01() || !tmp_361_13_cast_fu_40876_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_14_1_cast_fu_40880_p1.read()) + sc_bigint<6>(tmp_361_13_cast_fu_40876_p1.read()));
}
void a0_bin_conv::thread_tmp684_fu_40898_p2() {
tmp684_fu_40898_p2 = (!tmp_361_15_1_cast_fu_40894_p1.read().is_01() || !tmp_361_14_cast_fu_40890_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_15_1_cast_fu_40894_p1.read()) + sc_bigint<6>(tmp_361_14_cast_fu_40890_p1.read()));
}
void a0_bin_conv::thread_tmp685_fu_40912_p2() {
tmp685_fu_40912_p2 = (!tmp_361_16_1_cast_fu_40908_p1.read().is_01() || !tmp_361_15_cast_fu_40904_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_16_1_cast_fu_40908_p1.read()) + sc_bigint<6>(tmp_361_15_cast_fu_40904_p1.read()));
}
void a0_bin_conv::thread_tmp686_fu_40926_p2() {
tmp686_fu_40926_p2 = (!tmp_361_17_1_cast_fu_40922_p1.read().is_01() || !tmp_361_16_cast_fu_40918_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_17_1_cast_fu_40922_p1.read()) + sc_bigint<6>(tmp_361_16_cast_fu_40918_p1.read()));
}
void a0_bin_conv::thread_tmp687_fu_40940_p2() {
tmp687_fu_40940_p2 = (!tmp_361_18_1_cast_fu_40936_p1.read().is_01() || !tmp_361_17_cast_fu_40932_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_18_1_cast_fu_40936_p1.read()) + sc_bigint<6>(tmp_361_17_cast_fu_40932_p1.read()));
}
void a0_bin_conv::thread_tmp688_fu_40954_p2() {
tmp688_fu_40954_p2 = (!tmp_361_19_1_cast_fu_40950_p1.read().is_01() || !tmp_361_18_cast_fu_40946_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_19_1_cast_fu_40950_p1.read()) + sc_bigint<6>(tmp_361_18_cast_fu_40946_p1.read()));
}
void a0_bin_conv::thread_tmp689_fu_40968_p2() {
tmp689_fu_40968_p2 = (!tmp_361_20_1_cast_fu_40964_p1.read().is_01() || !tmp_361_19_cast_fu_40960_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_20_1_cast_fu_40964_p1.read()) + sc_bigint<6>(tmp_361_19_cast_fu_40960_p1.read()));
}
void a0_bin_conv::thread_tmp690_fu_40982_p2() {
tmp690_fu_40982_p2 = (!tmp_361_21_1_cast_fu_40978_p1.read().is_01() || !tmp_361_20_cast_fu_40974_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_21_1_cast_fu_40978_p1.read()) + sc_bigint<6>(tmp_361_20_cast_fu_40974_p1.read()));
}
void a0_bin_conv::thread_tmp691_fu_40996_p2() {
tmp691_fu_40996_p2 = (!tmp_361_22_1_cast_fu_40992_p1.read().is_01() || !tmp_361_21_cast_fu_40988_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_22_1_cast_fu_40992_p1.read()) + sc_bigint<6>(tmp_361_21_cast_fu_40988_p1.read()));
}
void a0_bin_conv::thread_tmp692_fu_41010_p2() {
tmp692_fu_41010_p2 = (!tmp_361_23_1_cast_fu_41006_p1.read().is_01() || !tmp_361_22_cast_fu_41002_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_23_1_cast_fu_41006_p1.read()) + sc_bigint<6>(tmp_361_22_cast_fu_41002_p1.read()));
}
void a0_bin_conv::thread_tmp693_fu_41024_p2() {
tmp693_fu_41024_p2 = (!tmp_361_24_1_cast_fu_41020_p1.read().is_01() || !tmp_361_23_cast_fu_41016_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_24_1_cast_fu_41020_p1.read()) + sc_bigint<6>(tmp_361_23_cast_fu_41016_p1.read()));
}
void a0_bin_conv::thread_tmp694_fu_41038_p2() {
tmp694_fu_41038_p2 = (!tmp_361_25_1_cast_fu_41034_p1.read().is_01() || !tmp_361_24_cast_fu_41030_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_25_1_cast_fu_41034_p1.read()) + sc_bigint<6>(tmp_361_24_cast_fu_41030_p1.read()));
}
void a0_bin_conv::thread_tmp695_fu_41052_p2() {
tmp695_fu_41052_p2 = (!tmp_361_26_1_cast_fu_41048_p1.read().is_01() || !tmp_361_25_cast_fu_41044_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_26_1_cast_fu_41048_p1.read()) + sc_bigint<6>(tmp_361_25_cast_fu_41044_p1.read()));
}
void a0_bin_conv::thread_tmp696_fu_41066_p2() {
tmp696_fu_41066_p2 = (!tmp_361_27_1_cast_fu_41062_p1.read().is_01() || !tmp_361_26_cast_fu_41058_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_27_1_cast_fu_41062_p1.read()) + sc_bigint<6>(tmp_361_26_cast_fu_41058_p1.read()));
}
void a0_bin_conv::thread_tmp697_fu_41080_p2() {
tmp697_fu_41080_p2 = (!tmp_361_28_1_cast_fu_41076_p1.read().is_01() || !tmp_361_27_cast_fu_41072_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_28_1_cast_fu_41076_p1.read()) + sc_bigint<6>(tmp_361_27_cast_fu_41072_p1.read()));
}
void a0_bin_conv::thread_tmp698_fu_41094_p2() {
tmp698_fu_41094_p2 = (!tmp_361_29_1_cast_fu_41090_p1.read().is_01() || !tmp_361_28_cast_fu_41086_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_29_1_cast_fu_41090_p1.read()) + sc_bigint<6>(tmp_361_28_cast_fu_41086_p1.read()));
}
void a0_bin_conv::thread_tmp699_fu_41108_p2() {
tmp699_fu_41108_p2 = (!tmp_361_30_1_cast_fu_41104_p1.read().is_01() || !tmp_361_29_cast_fu_41100_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_30_1_cast_fu_41104_p1.read()) + sc_bigint<6>(tmp_361_29_cast_fu_41100_p1.read()));
}
void a0_bin_conv::thread_tmp700_fu_41122_p2() {
tmp700_fu_41122_p2 = (!tmp_361_31_1_cast_fu_41118_p1.read().is_01() || !tmp_361_30_cast_fu_41114_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_31_1_cast_fu_41118_p1.read()) + sc_bigint<6>(tmp_361_30_cast_fu_41114_p1.read()));
}
void a0_bin_conv::thread_tmp701_fu_41136_p2() {
tmp701_fu_41136_p2 = (!tmp_361_32_1_cast_fu_41132_p1.read().is_01() || !tmp_361_31_cast_fu_41128_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_32_1_cast_fu_41132_p1.read()) + sc_bigint<6>(tmp_361_31_cast_fu_41128_p1.read()));
}
void a0_bin_conv::thread_tmp702_fu_41150_p2() {
tmp702_fu_41150_p2 = (!tmp_361_33_1_cast_fu_41146_p1.read().is_01() || !tmp_361_32_cast_fu_41142_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_33_1_cast_fu_41146_p1.read()) + sc_bigint<6>(tmp_361_32_cast_fu_41142_p1.read()));
}
void a0_bin_conv::thread_tmp703_fu_41164_p2() {
tmp703_fu_41164_p2 = (!tmp_361_34_1_cast_fu_41160_p1.read().is_01() || !tmp_361_33_cast_fu_41156_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_34_1_cast_fu_41160_p1.read()) + sc_bigint<6>(tmp_361_33_cast_fu_41156_p1.read()));
}
void a0_bin_conv::thread_tmp704_fu_41178_p2() {
tmp704_fu_41178_p2 = (!tmp_361_35_1_cast_fu_41174_p1.read().is_01() || !tmp_361_34_cast_fu_41170_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_35_1_cast_fu_41174_p1.read()) + sc_bigint<6>(tmp_361_34_cast_fu_41170_p1.read()));
}
void a0_bin_conv::thread_tmp705_fu_41192_p2() {
tmp705_fu_41192_p2 = (!tmp_361_36_1_cast_fu_41188_p1.read().is_01() || !tmp_361_35_cast_fu_41184_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_36_1_cast_fu_41188_p1.read()) + sc_bigint<6>(tmp_361_35_cast_fu_41184_p1.read()));
}
void a0_bin_conv::thread_tmp706_fu_41206_p2() {
tmp706_fu_41206_p2 = (!tmp_361_37_1_cast_fu_41202_p1.read().is_01() || !tmp_361_36_cast_fu_41198_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_37_1_cast_fu_41202_p1.read()) + sc_bigint<6>(tmp_361_36_cast_fu_41198_p1.read()));
}
void a0_bin_conv::thread_tmp707_fu_41220_p2() {
tmp707_fu_41220_p2 = (!tmp_361_38_1_cast_fu_41216_p1.read().is_01() || !tmp_361_37_cast_fu_41212_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_38_1_cast_fu_41216_p1.read()) + sc_bigint<6>(tmp_361_37_cast_fu_41212_p1.read()));
}
void a0_bin_conv::thread_tmp708_fu_41234_p2() {
tmp708_fu_41234_p2 = (!tmp_361_39_1_cast_fu_41230_p1.read().is_01() || !tmp_361_38_cast_fu_41226_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_39_1_cast_fu_41230_p1.read()) + sc_bigint<6>(tmp_361_38_cast_fu_41226_p1.read()));
}
void a0_bin_conv::thread_tmp709_fu_41248_p2() {
tmp709_fu_41248_p2 = (!tmp_361_40_1_cast_fu_41244_p1.read().is_01() || !tmp_361_39_cast_fu_41240_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_40_1_cast_fu_41244_p1.read()) + sc_bigint<6>(tmp_361_39_cast_fu_41240_p1.read()));
}
void a0_bin_conv::thread_tmp710_fu_41262_p2() {
tmp710_fu_41262_p2 = (!tmp_361_41_1_cast_fu_41258_p1.read().is_01() || !tmp_361_40_cast_fu_41254_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_41_1_cast_fu_41258_p1.read()) + sc_bigint<6>(tmp_361_40_cast_fu_41254_p1.read()));
}
void a0_bin_conv::thread_tmp711_fu_41276_p2() {
tmp711_fu_41276_p2 = (!tmp_361_42_1_cast_fu_41272_p1.read().is_01() || !tmp_361_41_cast_fu_41268_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_42_1_cast_fu_41272_p1.read()) + sc_bigint<6>(tmp_361_41_cast_fu_41268_p1.read()));
}
void a0_bin_conv::thread_tmp712_fu_41290_p2() {
tmp712_fu_41290_p2 = (!tmp_361_43_1_cast_fu_41286_p1.read().is_01() || !tmp_361_42_cast_fu_41282_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_43_1_cast_fu_41286_p1.read()) + sc_bigint<6>(tmp_361_42_cast_fu_41282_p1.read()));
}
void a0_bin_conv::thread_tmp713_fu_41304_p2() {
tmp713_fu_41304_p2 = (!tmp_361_44_1_cast_fu_41300_p1.read().is_01() || !tmp_361_43_cast_fu_41296_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_44_1_cast_fu_41300_p1.read()) + sc_bigint<6>(tmp_361_43_cast_fu_41296_p1.read()));
}
void a0_bin_conv::thread_tmp714_fu_41318_p2() {
tmp714_fu_41318_p2 = (!tmp_361_45_1_cast_fu_41314_p1.read().is_01() || !tmp_361_44_cast_fu_41310_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_45_1_cast_fu_41314_p1.read()) + sc_bigint<6>(tmp_361_44_cast_fu_41310_p1.read()));
}
void a0_bin_conv::thread_tmp715_fu_41332_p2() {
tmp715_fu_41332_p2 = (!tmp_361_46_1_cast_fu_41328_p1.read().is_01() || !tmp_361_45_cast_fu_41324_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_46_1_cast_fu_41328_p1.read()) + sc_bigint<6>(tmp_361_45_cast_fu_41324_p1.read()));
}
void a0_bin_conv::thread_tmp716_fu_41346_p2() {
tmp716_fu_41346_p2 = (!tmp_361_47_1_cast_fu_41342_p1.read().is_01() || !tmp_361_46_cast_fu_41338_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_47_1_cast_fu_41342_p1.read()) + sc_bigint<6>(tmp_361_46_cast_fu_41338_p1.read()));
}
void a0_bin_conv::thread_tmp717_fu_41360_p2() {
tmp717_fu_41360_p2 = (!tmp_361_48_1_cast_fu_41356_p1.read().is_01() || !tmp_361_47_cast_fu_41352_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_48_1_cast_fu_41356_p1.read()) + sc_bigint<6>(tmp_361_47_cast_fu_41352_p1.read()));
}
void a0_bin_conv::thread_tmp718_fu_41374_p2() {
tmp718_fu_41374_p2 = (!tmp_361_49_1_cast_fu_41370_p1.read().is_01() || !tmp_361_48_cast_fu_41366_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_49_1_cast_fu_41370_p1.read()) + sc_bigint<6>(tmp_361_48_cast_fu_41366_p1.read()));
}
void a0_bin_conv::thread_tmp719_fu_41388_p2() {
tmp719_fu_41388_p2 = (!tmp_361_50_1_cast_fu_41384_p1.read().is_01() || !tmp_361_49_cast_fu_41380_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_50_1_cast_fu_41384_p1.read()) + sc_bigint<6>(tmp_361_49_cast_fu_41380_p1.read()));
}
void a0_bin_conv::thread_tmp720_fu_41402_p2() {
tmp720_fu_41402_p2 = (!tmp_361_51_1_cast_fu_41398_p1.read().is_01() || !tmp_361_50_cast_fu_41394_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_51_1_cast_fu_41398_p1.read()) + sc_bigint<6>(tmp_361_50_cast_fu_41394_p1.read()));
}
void a0_bin_conv::thread_tmp721_fu_41416_p2() {
tmp721_fu_41416_p2 = (!tmp_361_52_1_cast_fu_41412_p1.read().is_01() || !tmp_361_51_cast_fu_41408_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_52_1_cast_fu_41412_p1.read()) + sc_bigint<6>(tmp_361_51_cast_fu_41408_p1.read()));
}
void a0_bin_conv::thread_tmp722_fu_41430_p2() {
tmp722_fu_41430_p2 = (!tmp_361_53_1_cast_fu_41426_p1.read().is_01() || !tmp_361_52_cast_fu_41422_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_53_1_cast_fu_41426_p1.read()) + sc_bigint<6>(tmp_361_52_cast_fu_41422_p1.read()));
}
void a0_bin_conv::thread_tmp723_fu_41444_p2() {
tmp723_fu_41444_p2 = (!tmp_361_54_1_cast_fu_41440_p1.read().is_01() || !tmp_361_53_cast_fu_41436_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_54_1_cast_fu_41440_p1.read()) + sc_bigint<6>(tmp_361_53_cast_fu_41436_p1.read()));
}
void a0_bin_conv::thread_tmp724_fu_41458_p2() {
tmp724_fu_41458_p2 = (!tmp_361_55_1_cast_fu_41454_p1.read().is_01() || !tmp_361_54_cast_fu_41450_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_55_1_cast_fu_41454_p1.read()) + sc_bigint<6>(tmp_361_54_cast_fu_41450_p1.read()));
}
void a0_bin_conv::thread_tmp725_fu_41472_p2() {
tmp725_fu_41472_p2 = (!tmp_361_56_1_cast_fu_41468_p1.read().is_01() || !tmp_361_55_cast_fu_41464_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_56_1_cast_fu_41468_p1.read()) + sc_bigint<6>(tmp_361_55_cast_fu_41464_p1.read()));
}
void a0_bin_conv::thread_tmp726_fu_41486_p2() {
tmp726_fu_41486_p2 = (!tmp_361_57_1_cast_fu_41482_p1.read().is_01() || !tmp_361_56_cast_fu_41478_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_57_1_cast_fu_41482_p1.read()) + sc_bigint<6>(tmp_361_56_cast_fu_41478_p1.read()));
}
void a0_bin_conv::thread_tmp727_fu_41500_p2() {
tmp727_fu_41500_p2 = (!tmp_361_58_1_cast_fu_41496_p1.read().is_01() || !tmp_361_57_cast_fu_41492_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_58_1_cast_fu_41496_p1.read()) + sc_bigint<6>(tmp_361_57_cast_fu_41492_p1.read()));
}
void a0_bin_conv::thread_tmp728_fu_41514_p2() {
tmp728_fu_41514_p2 = (!tmp_361_59_1_cast_fu_41510_p1.read().is_01() || !tmp_361_58_cast_fu_41506_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_59_1_cast_fu_41510_p1.read()) + sc_bigint<6>(tmp_361_58_cast_fu_41506_p1.read()));
}
void a0_bin_conv::thread_tmp729_fu_41528_p2() {
tmp729_fu_41528_p2 = (!tmp_361_60_1_cast_fu_41524_p1.read().is_01() || !tmp_361_59_cast_fu_41520_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_60_1_cast_fu_41524_p1.read()) + sc_bigint<6>(tmp_361_59_cast_fu_41520_p1.read()));
}
void a0_bin_conv::thread_tmp730_fu_41542_p2() {
tmp730_fu_41542_p2 = (!tmp_361_61_1_cast_fu_41538_p1.read().is_01() || !tmp_361_60_cast_fu_41534_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_61_1_cast_fu_41538_p1.read()) + sc_bigint<6>(tmp_361_60_cast_fu_41534_p1.read()));
}
void a0_bin_conv::thread_tmp731_fu_41556_p2() {
tmp731_fu_41556_p2 = (!tmp_361_62_1_cast_fu_41552_p1.read().is_01() || !tmp_361_61_cast_fu_41548_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_62_1_cast_fu_41552_p1.read()) + sc_bigint<6>(tmp_361_61_cast_fu_41548_p1.read()));
}
void a0_bin_conv::thread_tmp732_fu_41570_p2() {
tmp732_fu_41570_p2 = (!tmp_361_63_1_cast_fu_41566_p1.read().is_01() || !tmp_361_62_cast_fu_41562_p1.read().is_01())? sc_lv<6>(): (sc_bigint<6>(tmp_361_63_1_cast_fu_41566_p1.read()) + sc_bigint<6>(tmp_361_62_cast_fu_41562_p1.read()));
}
void a0_bin_conv::thread_tmp_104_fu_19662_p3() {
tmp_104_fu_19662_p3 = esl_concat<3,1>(log_width_V_fu_19620_p2.read(), ap_const_lv1_0);
}
void a0_bin_conv::thread_tmp_105_fu_19692_p2() {
tmp_105_fu_19692_p2 = (!tmp_113_cast2_fu_19658_p1.read().is_01())? sc_lv<7>(): ap_const_lv7_1 << (unsigned short)tmp_113_cast2_fu_19658_p1.read().to_uint();
}
void a0_bin_conv::thread_tmp_106_fu_19712_p2() {
tmp_106_fu_19712_p2 = (!tmp_117_cast_fu_19708_p1.read().is_01())? sc_lv<4>(): ap_const_lv4_F >> (unsigned short)tmp_117_cast_fu_19708_p1.read().to_uint();
}
void a0_bin_conv::thread_tmp_107_fu_19940_p2() {
tmp_107_fu_19940_p2 = (!p_7_reg_6154.read().is_01() || !ap_const_lv6_20.is_01())? sc_lv<1>(): sc_lv<1>(p_7_reg_6154.read() == ap_const_lv6_20);
}
void a0_bin_conv::thread_tmp_110_fu_20106_p2() {
tmp_110_fu_20106_p2 = (tmp_1231_fu_20038_p1.read() ^ ap_const_lv3_4);
}
void a0_bin_conv::thread_tmp_111_fu_20146_p2() {
tmp_111_fu_20146_p2 = (!ap_const_lv3_0.is_01() || !tmp_1231_fu_20038_p1.read().is_01())? sc_lv<3>(): (sc_biguint<3>(ap_const_lv3_0) - sc_biguint<3>(tmp_1231_fu_20038_p1.read()));
}
void a0_bin_conv::thread_tmp_112_cast_fu_19634_p1() {
tmp_112_cast_fu_19634_p1 = esl_zext<5,3>(tmp_s_fu_19626_p3.read());
}
void a0_bin_conv::thread_tmp_113_cast1_fu_19654_p1() {
tmp_113_cast1_fu_19654_p1 = esl_zext<5,3>(log_width_V_fu_19620_p2.read());
}
void a0_bin_conv::thread_tmp_113_cast2_fu_19658_p1() {
tmp_113_cast2_fu_19658_p1 = esl_zext<7,3>(log_width_V_fu_19620_p2.read());
}
void a0_bin_conv::thread_tmp_113_fu_19952_p1() {
tmp_113_fu_19952_p1 = esl_zext<32,6>(p_7_reg_6154.read());
}
void a0_bin_conv::thread_tmp_114_cast_fu_19670_p1() {
tmp_114_cast_fu_19670_p1 = esl_zext<12,4>(tmp_104_fu_19662_p3.read());
}
void a0_bin_conv::thread_tmp_114_fu_20825_p2() {
tmp_114_fu_20825_p2 = (!lhs_V_fu_20821_p1.read().is_01() || !n_phases_cast_reg_45729.read().is_01())? sc_lv<1>(): (sc_biguint<15>(lhs_V_fu_20821_p1.read()) < sc_biguint<15>(n_phases_cast_reg_45729.read()));
}
void a0_bin_conv::thread_tmp_117_cast_fu_19708_p1() {
tmp_117_cast_fu_19708_p1 = esl_zext<4,3>(grp_fu_19490_p2.read());
}
void a0_bin_conv::thread_tmp_118_fu_42316_p2() {
tmp_118_fu_42316_p2 = (!ap_const_lv3_2.is_01() || !log_slice_V_reg_45699.read().is_01())? sc_lv<3>(): (sc_biguint<3>(ap_const_lv3_2) + sc_biguint<3>(log_slice_V_reg_45699.read()));
}
void a0_bin_conv::thread_tmp_120_fu_45592_p0() {
tmp_120_fu_45592_p0 = (sc_lv<15>) (tmp_120_fu_45592_p00.read());
}
}
| 237,049 | 145,140 |
#include <bits/stdc++.h>
using namespace std;
#define SIZE 30000
inline int scan(int &x) {
char c;
while (c = getchar(), c < '0' || c > '9')
;
x = c - '0';
while (c = getchar(), c >= '0' && c <= '9')
x = x * 10 + c - '0';
}
int tree[32768][51];
int B, N, D;
int cost[SIZE + 1], value[SIZE + 1];
int ans[51];
void pushup(int par[], int c[]) {
for (int i = 50; i >= 0; i--) {
for (int j = i; j >= 0; j--) {
if (par[i - j] != -1 && c[j] != -1 && par[i] < par[i - j] + c[j]) {
par[i] = par[i - j] + c[j];
}
}
}
}
void build(int l, int r, int n) {
memset(tree[n], -1, sizeof tree[n]);
tree[n][0] = 0;
if (l == r) {
tree[n][cost[l]] = value[l];
return;
}
int mid = (l + r) >> 1;
build(l, mid, n << 1);
build(mid + 1, r, n << 1 | 1);
pushup(tree[n], tree[n << 1]);
pushup(tree[n], tree[n << 1 | 1]);
}
void update(int x, int n, int l, int r) {
memset(tree[n], -1, sizeof tree[n]);
tree[n][0] = 0;
if (l == x && r == x) {
tree[n][cost[x]] = value[x];
return;
}
int mid = (l + r) >> 1;
if (x <= mid)
update(x, n << 1, l, mid);
else
update(x, n << 1 | 1, mid + 1, r);
pushup(tree[n], tree[n << 1]);
pushup(tree[n], tree[n << 1 | 1]);
}
void query(int l, int r, int n, int x, int y) {
if (x == l && y == r) {
pushup(ans, tree[n]);
return;
}
int mid = (x + y) >> 1;
if (r <= mid)
query(l, r, n << 1, x, mid);
else if (l > mid)
query(l, r, n << 1 | 1, mid + 1, y);
else {
query(l, mid, n << 1, x, mid);
query(mid + 1, r, n << 1 | 1, mid + 1, y);
}
}
int main() {
freopen("in.txt", "r", stdin);
scan(B);
scan(N);
scan(D);
for (int i = 1; i <= N; i++) {
scan(cost[i]);
scan(value[i]);
}
build(1, N, 1);
for (int i = 0; i < D; i++) {
int a, b, x, y;
scan(a);
scan(b);
scan(x);
scan(y);
memset(ans, -1, sizeof ans);
ans[0] = 0;
cost[a] = b;
update(a, 1, 1, N);
query(x, y, 1, 1, N);
int res = 0;
for (int i = 0; i <= B; i++) {
res = max(res, ans[i]);
}
printf("%d\n", res);
}
}
| 2,101 | 1,046 |
#include "test_common.h"
TEST_CASE("RangeTracker objects must work correctly on the given get tests",
"[RangeTracker]") {
auto rts = ALL_IMPLEMENTATIONS(int);
std::vector<std::pair<int, int>> empty = {};
for(auto& it: rts) {
it->Add(1, 3);
it->Add(5, 6);
}
std::vector<std::pair<int, int>> existing = {{1, 3}, {5, 6}};
for(auto& it: rts) {
REQUIRE(it->Get(-200, 200) == existing);
REQUIRE(it->Get(1, 2) == subvec(existing, 0, 1));
REQUIRE(it->Get(-1, 1) == empty);
REQUIRE(it->Get(2, 3) == subvec(existing, 0, 1));
REQUIRE(it->Get(5, 6) == subvec(existing, 1, 1));
REQUIRE(it->Get(6, 7) == empty);
}
SECTION("get, scenario 1") {
for(auto& it: rts) {
REQUIRE(it->Get(4, 5) == empty);
}
}
SECTION("get, scenario 2") {
for(auto& it: rts) {
REQUIRE(it->Get(4, 6) == subvec(existing, 1, 1));
}
}
SECTION("get, scenario 3") {
for(auto& it: rts) {
REQUIRE(it->Get(2, 9) == existing);
}
}
}
// i) State [(1, 3), (5, 6)]. Get(4, 5). Returns []
// ii) State [(1, 3), (5, 6)]. Get(4, 6). Returns [(5, 6)]
// iii) State [(1, 3), (5, 6)]. Get(2, 9). Returns [(1, 3), (5, 6)]
| 1,173 | 565 |
#include "tarch/parallel/Node.h"
#include "tarch/Assertions.h"
#include "tarch/services/ServiceRepository.h"
#include <sstream>
#include <cstdlib>
#include "tarch/compiler/CompilerSpecificSettings.h"
#include "tarch/multicore/MulticoreDefinitions.h"
/**
* For the machine name. If it doesn't work, switch it off in the file
* CompilerSpecificSettings.h.
*/
#ifdef CompilerHasUTSName
#include <sys/utsname.h>
#endif
tarch::logging::Log tarch::parallel::Node::_log("tarch::parallel::Node");
bool tarch::parallel::Node::_initIsCalled = false;
namespace {
int tagCounter = 0;
}
void tarch::parallel::Node::releaseTag(int tag) {
if (tag==tagCounter-1) {
tagCounter--;
}
}
int tarch::parallel::Node::reserveFreeTag(const std::string& fullQualifiedMessageName) {
tagCounter++;
// I protect the tag manually (not via log filter), as many tags are actually
// grabbed before most applications initialise their log filters properly.
//
// We may not use isGlobalMaster() as this query checks whether the code is
// properly initialised. Please note rank is -1 as long as MPI is not properly
// initialised, i.e. any tag booking prior to the MPI initialisation is not
// logged properly.
if ( getInstance()._rank==getGlobalMasterRank() ) {
tarch::logging::Log _log("tarch::parallel::Node<static>");
logInfo(
"reserveFreeTag()",
"assigned message " << fullQualifiedMessageName
<< " the free tag " << tagCounter-1
);
}
return tagCounter-1;
}
bool tarch::parallel::Node::isInitialised() const {
return _initIsCalled;
}
void tarch::parallel::Node::ensureThatMessageQueuesAreEmpty( int fromRank, int tag ) {
#ifdef Parallel
int flag;
MPI_Iprobe(fromRank, tag, _communicator, &flag, MPI_STATUS_IGNORE);
if (flag!=0) {
plotMessageQueues();
}
assertion3( flag==0, fromRank, tag, getRank() );
#endif
}
void tarch::parallel::Node::plotMessageQueues() {
#ifdef Parallel
int flag;
MPI_Status status;
MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, _communicator, &flag, &status);
if (flag==0) {
_log.error("plotMessageQueues()", "there are no messages from any sender in MPI queue");
}
else {
logError(
"plotMessageQueues()",
"there is still a message in queue "
" from rank " << status.MPI_SOURCE <<
" with tag " << status.MPI_TAG
);
}
#endif
}
void tarch::parallel::Node::triggerDeadlockTimeOut(
const std::string& className,
const std::string& methodName,
int communicationPartnerRank,
int tag,
int numberOfExpectedMessages,
const std::string& comment
) {
std::ostringstream out;
out << "operation " << className << "::" << methodName << " on node "
<< getRank() << " had to wait more than " << _deadlockTimeOut
<< " seconds for " << numberOfExpectedMessages
<< " message(s) from node " << communicationPartnerRank << " with tag " << tag
<< ". Timeout. " << comment;
_log.error( "triggerDeadlockTimeOut(...)", out.str() );
plotMessageQueues();
exit(DEADLOCK_EXIT_CODE);
}
void tarch::parallel::Node::writeTimeOutWarning(
const std::string& className,
const std::string& methodName,
int communicationPartnerRank,
int tag,
int numberOfExpectedMessages
) {
std::ostringstream out;
out << "operation " << className << "::" << methodName << " on node "
<< getRank() << " had to wait more than " << _timeOutWarning
<< " seconds for " << numberOfExpectedMessages
<< " message(s) from node " << communicationPartnerRank << " with tag " << tag << ". Application "
<< "will terminate after " << _deadlockTimeOut << " seconds because "
<< "of a deadlock";
_log.warning( "writeTimeOutWarning(...)", out.str() );
}
clock_t tarch::parallel::Node::getDeadlockWarningTimeStamp() const {
clock_t result = clock() + _timeOutWarning * CLOCKS_PER_SEC;
assertion4( result>=0, result, clock(), _timeOutWarning, CLOCKS_PER_SEC);
return result;
}
clock_t tarch::parallel::Node::getDeadlockTimeOutTimeStamp() const {
clock_t result = clock() + _deadlockTimeOut * CLOCKS_PER_SEC;
assertion4( result>=0, result, clock(), _timeOutWarning, CLOCKS_PER_SEC);
return result;
}
bool tarch::parallel::Node::isTimeOutDeadlockEnabled() const {
return _areTimeoutsEnabled and _deadlockTimeOut > 0;
}
bool tarch::parallel::Node::isTimeOutWarningEnabled() const {
return _areTimeoutsEnabled and _timeOutWarning > 0;
}
void tarch::parallel::Node::suspendTimeouts( bool timeoutsDisabled ) {
_areTimeoutsEnabled = !timeoutsDisabled;
}
std::string tarch::parallel::MPIReturnValueToString( int result ) {
std::ostringstream out;
#ifdef Parallel
int resultlen;
char* string = new char[MPI_MAX_ERROR_STRING]; // (char *)malloc(MPI_MAX_ERROR_STRING * sizeof(char));
MPI_Error_string(result, string, &resultlen);
int errorclass;
MPI_Error_class(result, &errorclass);
out << "mpi error class: " << errorclass << "="
<< ", mpi error text: " << string;
switch ( errorclass ) {
case MPI_SUCCESS: out << "MPI_SUCCESS [no error]"; break;
case MPI_ERR_BUFFER: out << "MPI_ERR_BUFFER [invalid buffer pointer]"; break;
case MPI_ERR_COUNT: out << "MPI_ERR_COUNT [invalid count argument]"; break;
case MPI_ERR_TYPE: out << "MPI_ERR_TYPE [invalid datatype]"; break;
case MPI_ERR_TAG: out << "MPI_ERR_TAG [invalid tag]"; break;
case MPI_ERR_COMM: out << "MPI_ERR_COMM [invalid communicator]"; break;
case MPI_ERR_RANK: out << "MPI_ERR_RANK [invalid rank]"; break;
case MPI_ERR_REQUEST: out << "MPI_ERR_REQUEST [invalid request handle]"; break;
case MPI_ERR_ROOT: out << "MPI_ERR_ROOT [invalid root argument]"; break;
case MPI_ERR_GROUP: out << "MPI_ERR_GROUP [invalid group]"; break;
case MPI_ERR_OP: out << "MPI_ERR_OP [invalid operation]"; break;
case MPI_ERR_TOPOLOGY: out << "MPI_ERR_TOPOLOGY [invalid topology]"; break;
case MPI_ERR_DIMS: out << "MPI_ERR_DIMS [invalid dimensions]"; break;
case MPI_ERR_ARG: out << "MPI_ERR_ARG [invalid argument]"; break;
case MPI_ERR_UNKNOWN: out << "MPI_ERR_UNKNOWN [unknown error]"; break;
case MPI_ERR_TRUNCATE: out << "MPI_ERR_TRUNCATE [message has been truncated by receiver]"; break;
case MPI_ERR_OTHER: out << "MPI_ERR_OTHER [other unknown error]"; break;
case MPI_ERR_INTERN: out << "MPI_ERR_INTERN [internal mpi error]"; break;
default: out << "unknown"; break;
}
delete[] string;
#else
out << "compiled without -DParallel";
#endif
return out.str();
}
std::string tarch::parallel::MPIStatusToString( const MPI_Status& status ) {
std::ostringstream out;
#ifdef Parallel
out << "status flag:"
<< " MPI_ERROR=" << status.MPI_ERROR
<< " (" << MPIReturnValueToString(status.MPI_ERROR)
<< ") ,MPI_SOURCE=" << status.MPI_SOURCE
<< ",MPI_TAG=" << status.MPI_TAG;
#else
out << "compiled without -DParallel";
#endif
return out.str();
}
#ifdef Parallel
tarch::parallel::Node::Node():
_rank(-1),
_numberOfProcessors(-1),
_communicator( MPI_COMM_WORLD),
_timeOutWarning(0),
_deadlockTimeOut(0),
_areTimeoutsEnabled(true) {
}
#else
tarch::parallel::Node::Node():
_rank(0),
_numberOfProcessors(1),
_communicator(-1),
_timeOutWarning(0),
_deadlockTimeOut(0),
_areTimeoutsEnabled(true) {
}
#endif
#ifdef Parallel
tarch::parallel::Node::Node(const parallel::Node& node):
_rank(-1),
_numberOfProcessors(-1),
_communicator( MPI_COMM_WORLD) {
}
#else
tarch::parallel::Node::Node(const parallel::Node& node):
_rank(0),
_numberOfProcessors(-1),
_communicator(-1) {
}
#endif
tarch::parallel::Node::~Node() {
}
void tarch::parallel::Node::shutdown() {
#ifdef Parallel
assertion( _rank!=-1 );
MPI_Barrier( _communicator );
MPI_Finalize();
_communicator = MPI_COMM_WORLD;
#endif
_rank = -1;
}
int tarch::parallel::Node::getGlobalMasterRank() {
return 0;
}
bool tarch::parallel::Node::isGlobalMaster() const {
#ifdef Parallel
assertion(_initIsCalled);
return getRank() == getGlobalMasterRank();
#else
return true;
#endif
}
void tarch::parallel::Node::logStatus() const {
std::ostringstream statusMessage;
statusMessage << "MPI status:";
#ifdef CompilerHasUTSName
utsname* utsdata = new utsname();
assertion( utsdata!=NULL );
uname(utsdata);
statusMessage << " nodename=" << utsdata->nodename;
delete utsdata;
#else
statusMessage << " nodename=undef";
#endif
statusMessage << ", rank=" << _rank;
statusMessage << ", communicator=" << _communicator;
statusMessage << ", #processors=" << _numberOfProcessors;
_log.info( "logStatus()", statusMessage.str() );
}
bool tarch::parallel::Node::init(int* argc, char*** argv) {
#ifdef Parallel
int result = MPI_SUCCESS;
#if defined( SharedMemoryParallelisation ) && defined( MultipleThreadsMayTriggerMPICalls )
int initThreadProvidedThreadLevelSupport;
result = MPI_Init_thread( argc, argv, MPI_THREAD_MULTIPLE, &initThreadProvidedThreadLevelSupport );
if (initThreadProvidedThreadLevelSupport!=MPI_THREAD_MULTIPLE ) {
std::cerr << "warning: MPI implementation does not support MPI_THREAD_MULTIPLE. Support multithreading level is "
<< initThreadProvidedThreadLevelSupport << " instead of " << MPI_THREAD_MULTIPLE
<< ". Disable MultipleThreadsMayTriggerMPICalls in the compiler-specific settings or via -DnoMultipleThreadsMayTriggerMPICalls."<< std::endl;
exit(-1);
}
#else
result = MPI_Init( argc, argv );
#endif
if (result!=MPI_SUCCESS) {
std::cerr << "init(int*,char***)\t initialisation failed: " + MPIReturnValueToString(result) + " (no logging available yet)";
return false;
}
result = MPI_Comm_size( MPI_COMM_WORLD, &_numberOfProcessors );
if (result!=MPI_SUCCESS) {
std::cerr << "init(int*,char***)\t initialisation failed: " + MPIReturnValueToString(result) + " (no logging available yet)";
return false;
}
result = MPI_Comm_rank( MPI_COMM_WORLD, &_rank );
if (result!=MPI_SUCCESS) {
std::cerr << "init(int*,char***)\t initialisation failed: " + MPIReturnValueToString(result) + " (no logging available yet)";
return false;
}
#endif
_initIsCalled = true;
return true;
}
int tarch::parallel::Node::getRank() const {
#ifdef Parallel
assertion(_initIsCalled);
#endif
return _rank;
}
tarch::parallel::Node& tarch::parallel::Node::getInstance() {
static Node singleton;
return singleton;
}
MPI_Comm tarch::parallel::Node::getCommunicator() const {
assertion(_initIsCalled);
return _communicator;
}
int tarch::parallel::Node::getNumberOfNodes() const {
#ifdef Parallel
assertion(_initIsCalled);
#endif
return _numberOfProcessors;
}
void tarch::parallel::Node::setTimeOutWarning( const clock_t & value ) {
assertion( value>=0 );
_timeOutWarning = value;
}
void tarch::parallel::Node::setDeadlockTimeOut( const clock_t & value ) {
assertion( value>=0 );
_deadlockTimeOut = value;
}
void tarch::parallel::Node::setCommunicator( MPI_Comm communicator ) {
_communicator = communicator;
}
void tarch::parallel::Node::receiveDanglingMessages() {
/*
#ifdef Parallel
int flag;
MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, _communicator, &flag, MPI_STATUS_IGNORE);
if (flag) {
#endif
*/
tarch::services::ServiceRepository::getInstance().receiveDanglingMessages();
/*
#ifdef Parallel
}
#endif
*/
}
| 11,595 | 4,035 |
#include "renderer.h"
#include <SDL.h>
namespace SDL{
Renderer::Renderer():renderer(nullptr){}
Renderer::Renderer(const Window& window, int index, Uint32 flags){
//SDL_CreateRenderer(SDL_Window *window, int index, Uint32 flags)
renderer.reset(SDL_CreateRenderer(window.window.get(), index, flags), SDL_DestroyRenderer);
if (renderer == nullptr) renderer.reset(SDL_GetRenderer(window.window.get()), SDL_DestroyRenderer);
// if (renderer == nullptr) throw (SDLException("Renderer null __file__ at line __line__"));
}
Renderer::Renderer(Renderer&& rend){
renderer = rend.renderer;
rend.renderer = nullptr;
}
Renderer::Renderer(SDL_Renderer* rend){
renderer.reset(rend, SDL_DestroyRenderer);
}
std::shared_ptr<SDL_Renderer> Renderer::get(){
return renderer;
}
void Renderer::present(){
if(renderer != nullptr) SDL_RenderPresent(renderer.get());
else ; //Throw an error?
}
void Renderer::clear(){
if (renderer != nullptr) SDL_RenderClear(renderer.get());
}
void Renderer::fill(uint8_t r, uint8_t g, uint8_t b, uint8_t a){
//SDL_RenderFillRect(SDL_Renderer *renderer, const SDL_Rect *rect)
uint8_t pr,pg,pb,pa;
SDL_GetRenderDrawColor(renderer.get(), &pr, &pg, &pb, &pa);
SDL_SetRenderDrawColor(renderer.get(), r,g,b, a);
clear();
SDL_SetRenderDrawColor(renderer.get(), pr, pg, pb, pa);
}
void Renderer::operator=(Renderer&& rhs){
if(renderer != nullptr) SDL_DestroyRenderer(renderer.get());
renderer = rhs.renderer;
rhs.renderer = nullptr;
}
SDL_Renderer* Renderer::getRaw(){
return renderer.get();
}
}
| 1,635 | 600 |
#include <stdio.h>
#include <string.h>
#include "machine.hpp"
#include "utils.hpp"
#define MAX(a, b) ((a) > (b) ? (a) : (b))
void SingleStepInfo()
{
printf("Single Step Mode Help:\n");
printf("c: continue\n");
printf("r: print all registers\n");
printf("d: dump machine status to file 'status_dump.txt'\n");
printf("p: print page table\n");
printf("m <address/hex> <size/dec>: get data from address\n");
printf("q: quit\n\n");
}
void
Machine::SingleStepDebug()
{
char buf[100], tbuf[100];
while (true)
{
fgets(buf, 100, stdin);
switch (buf[0])
{
case 'c':
return;
case 'r':
PrintReg();
break;
case 'd':
FILE *dump_out;
dump_out = fopen("status_dump.txt", "w");
Status(dump_out);
fclose(dump_out);
break;
case 'p':
PrintPageTable();
break;
case 'm':
uint64_t addr, data;
int size;
sscanf(buf, "%s %llx %d", tbuf, &addr, &size);
printf("%llx %d\n", addr, size);
if (!ReadMem(addr, size, (void*)&data))
{
printf("cannot access that address.\n");
continue;
}
printf("data in %08llx: ", addr);
for (int i = size - 1; i >= 0 ; --i)
{
printf("%02llx ", (data >> (i * 8)) & 0xff);
}
printf("\n");
break;
case 'q':
exit(0);
default:
printf("unknown command.\n");
SingleStepInfo();
}
}
}
Machine::Machine(PRED_TYPE mode)
{
// register initialization
memset(reg, 0, sizeof reg);
// page table initialization
for (int i = 0; i < PhysicalPageNum; ++i)
freePage.push(i);
pte = new PageTableEntry[PhysicalPageNum];
predictor = new Predictor(mode);
cycCount = 0;
cpuCount = 0;
instCount = 0;
runTime = .0;
loadHzdCount = 0;
ctrlHzdCount = 0;
ecallStlCount = 0;
jalrStlCount = 0;
totalBranch = 0;
l1cache = NULL;
l2cache = NULL;
l3cache = NULL;
}
Machine::~Machine()
{
delete mainMem;
delete l1cache;
delete pte;
delete predictor;
}
void Machine::StorageInit(int cacheLevel)
{
// storage initialization
StorageLatency ll;
StorageStats s;
CacheConfig l1c;
s.access_time = 0;
mainMem = new Memory();
mainMem->SetStats(s);
ll.bus_latency = 0;
ll.hit_latency = cfg.GetConfig("MEM_CYC");
mainMem->SetLatency(ll);
if (cacheLevel > 2)
{
l3cache = new Cache("L3 cache", (CACHE_METHOD)cfg.GetConfig("L3C_METHOD"));
l3cache->SetStats(s);
ll.bus_latency = cfg.GetConfig("L3C_BUS_CYC");
ll.hit_latency = cfg.GetConfig("L3C_HIT_CYC");
l3cache->SetLatency(ll);
l1c.size = cfg.GetConfig("L3C_SIZE");
l1c.assoc = cfg.GetConfig("L3C_ASSOC");
l1c.line_size = cfg.GetConfig("L3C_BSIZE"); // Size of cache line
l1c.write_through = (bool)cfg.GetConfig("L3C_WT"); // 0|1 for back|through
l1c.write_allocate = (bool)cfg.GetConfig("L3C_WA"); // 0|1 for no-alc|alc
l3cache->SetConfig(l1c);
l3cache->SetPrefetch(cfg.GetConfig("L3C_PREFETCH"));
l3cache->Allocate();
l3cache->SetLower(mainMem);
}
if (cacheLevel > 1)
{
l2cache = new Cache("L2 cache", (CACHE_METHOD)cfg.GetConfig("L2C_METHOD"));
l2cache->SetStats(s);
ll.bus_latency = cfg.GetConfig("L2C_BUS_CYC");
ll.hit_latency = cfg.GetConfig("L2C_HIT_CYC");
l2cache->SetLatency(ll);
l1c.size = cfg.GetConfig("L2C_SIZE");
l1c.assoc = cfg.GetConfig("L2C_ASSOC");
l1c.line_size = cfg.GetConfig("L2C_BSIZE"); // Size of cache line
l1c.write_through = (bool)cfg.GetConfig("L2C_WT"); // 0|1 for back|through
l1c.write_allocate = (bool)cfg.GetConfig("L2C_WA"); // 0|1 for no-alc|alc
l2cache->SetConfig(l1c);
l2cache->SetPrefetch(cfg.GetConfig("L2C_PREFETCH"));
l2cache->Allocate();
if (cacheLevel > 2)
l2cache->SetLower(l3cache);
else
l2cache->SetLower(mainMem);
}
if (cacheLevel > 0)
{
l1cache = new Cache("L1 cache", (CACHE_METHOD)cfg.GetConfig("L1C_METHOD"));
l1cache->SetStats(s);
ll.bus_latency = cfg.GetConfig("L1C_BUS_CYC");
ll.hit_latency = cfg.GetConfig("L1C_HIT_CYC");
l1cache->SetLatency(ll);
l1c.size = cfg.GetConfig("L1C_SIZE");
l1c.assoc = cfg.GetConfig("L1C_ASSOC");
l1c.line_size = cfg.GetConfig("L1C_BSIZE"); // Size of cache line
l1c.write_through = (bool)cfg.GetConfig("L1C_WT"); // 0|1 for back|through
l1c.write_allocate = (bool)cfg.GetConfig("L1C_WA"); // 0|1 for no-alc|alc
l1cache->SetConfig(l1c);
l1cache->SetPrefetch(cfg.GetConfig("L1C_PREFETCH"));
l1cache->Allocate();
if (cacheLevel > 1)
l1cache->SetLower(l2cache);
else
l1cache->SetLower(mainMem);
}
if (cacheLevel != 0)
topStorage = l1cache;
else
topStorage = mainMem;
}
void
Machine::Run()
{
Timer timer;
runTime = 0;
F_reg.bubble = false;
if(singleStep)
SingleStepInfo();
for ( ; ; )
{
int mxCyc = 1, useCyc;
timer.StepTime();
if ((useCyc = Fetch()) == 0)
{
panic("Fetch error!\n");
}
else
{
vprintf("- Fetch CPU Cyc: %d\n", useCyc);
mxCyc = MAX(mxCyc, useCyc);
}
if ((useCyc = Decode()) == 0)
{
panic("Decode error!\n");
}
else
{
vprintf("- Decode CPU Cyc: %d\n", useCyc);
mxCyc = MAX(mxCyc, useCyc);
}
if ((useCyc = Execute()) == 0)
{
panic("Execute error!\n");
}
else
{
vprintf("- Execute CPU Cyc: %d\n", useCyc);
mxCyc = MAX(mxCyc, useCyc);
}
if ((useCyc = MemoryAccess()) == 0)
{
panic("Memory error!\n");
}
else
{
vprintf("- Memory CPU Cyc: %d\n", useCyc);
mxCyc = MAX(mxCyc, useCyc);
}
if ((useCyc = WriteBack()) == 0)
{
panic("WriteBack error!\n");
}
else
{
vprintf("- WriteBack CPU Cyc: %d\n", useCyc);
mxCyc = MAX(mxCyc, useCyc);
}
UpdatePipeline();
cycCount++;
cpuCount += mxCyc;
runTime += timer.StepTime();
if (debug)
{
PrintReg();
}
if (singleStep)
SingleStepDebug();
}
Status();
}
void
Machine::Status(FILE *fout)
{
bool isnull = fout == NULL;
if (isnull)
{
fout = stdout;
}
fprintf(fout, "\n---------------- Machine ---------------\n");
fprintf(fout, "BASIC STATUS: \n");
fprintf(fout, "- Cycle Count: %d\n", cycCount);
fprintf(fout, "- Inst. Count: %d\n", instCount);
fprintf(fout, "- Run Time: %.4lf\n", runTime);
fprintf(fout, "- Pipeline Cyc CpI: %.2lf\n", (double)cycCount/instCount);
fprintf(fout, "- CPU Cyc CpI: %.2lf\n\n", (double)cpuCount/instCount);
fprintf(fout, "- Pred Strategy: %s\n", predictor->Name());
fprintf(fout, "- Branch Pred Acc: %.2lf%%\t(%d / %d)\n", (double)(totalBranch - ctrlHzdCount)/totalBranch*100,
totalBranch - ctrlHzdCount, totalBranch);
fprintf(fout, "- Load-use Hazard: %d\n", loadHzdCount);
fprintf(fout, "- Ctrl. Hazard: %d * 2\t(cycles)\n", ctrlHzdCount);
fprintf(fout, "- ECALL Stall: %d * 3\t(cycles)\n", ecallStlCount);
fprintf(fout, "- JALR Stall: %d * 2\t(cycles)\n", jalrStlCount);
fprintf(fout, "\nREGISTER FILE: \n");
fprintf(fout, "- Reg. Num %d\n", RegNum);
PrintReg(fout);
fprintf(fout, "----------------------------------------\n");
// cfg.Print(fout);
fprintf(fout, "\n----------------- Cache ----------------\n");
fprintf(fout, "L1 Cache: \n");
if (l1cache)
{
l1cache->Print(fout);
}
else
{
fprintf(fout, " None\n");
}
fprintf(fout, "\nL2 Cache: \n");
if (l2cache)
{
l2cache->Print(fout);
}
else
{
fprintf(fout, " None\n");
}
fprintf(fout, "\nL3 Cache: \n");
if (l3cache)
{
l3cache->Print(fout);
}
else
{
fprintf(fout, " None\n");
}
fprintf(fout, "----------------------------------------\n");
if (isnull)
{
PrintMem(NULL, true);
fout = fopen("status_dump.txt", "w");
}
PrintMem(fout);
if (isnull)
{
printf("memory status dumped to file 'status_dump.txt'.\n");
fclose(fout);
}
else
{
printf("machine status dumped.\n");
}
}
void
Machine::PrintReg(FILE *fout)
{
if (fout == NULL)
fout = stdout;
for (int i = 0; i < RegNum; i += 4)
{
for (int j = 0; j < 4; j++)
fprintf(fout, "[%4s]: 0x%08llx(%10lld) ", i+j>33?"na":reg_str[i+j], reg[i+j], reg[i+j]);
fprintf(fout, "\n");
}
}
| 8,141 | 3,804 |
/* Copyright (c) <2003-2019> <Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely
*/
#include "toolbox_stdafx.h"
#include "SkyBox.h"
#include "DemoMesh.h"
#include "DemoCamera.h"
#include "PhysicsUtils.h"
#include "TargaToOpenGl.h"
#include "DemoEntityManager.h"
#include "DebugDisplay.h"
#include "HeightFieldPrimitive.h"
class dBalancingCharacterBoneDefinition
{
public:
enum jointType
{
m_none,
m_ball,
m_0dof,
m_1dof,
m_2dof,
m_3dof,
m_ikEffector,
m_fkEffector,
};
struct dJointLimit
{
dFloat m_minTwistAngle;
dFloat m_maxTwistAngle;
dFloat m_coneAngle;
};
struct dFrameMatrix
{
dFloat m_pitch;
dFloat m_yaw;
dFloat m_roll;
};
char* m_boneName;
jointType m_type;
dFloat m_massFraction;
dJointLimit m_jointLimits;
dFrameMatrix m_frameBasics;
};
static dBalancingCharacterBoneDefinition tredDefinition[] =
{
{ "bone_pelvis", dBalancingCharacterBoneDefinition::m_none, 1.0f },
{ "bone_rightLeg", dBalancingCharacterBoneDefinition::m_3dof, 0.3f, {60.0f, 60.0f, 70.0f}, { 0.0f, 90.0f, 0.0f }},
{ "bone_righCalf", dBalancingCharacterBoneDefinition::m_1dof, 0.2f, {-60.0f, 60.0f, 0.0f}, { 0.0f, 0.0f, 90.0f }},
{ "bone_rightAnkle", dBalancingCharacterBoneDefinition::m_fkEffector, 0.2f, {0.0f, 0.0f, 0.0f}, {-90.0f, 0.0f, 90.0f } },
{ "effector_rightAnkle", dBalancingCharacterBoneDefinition::m_ikEffector},
{ "bone_rightFoot", dBalancingCharacterBoneDefinition::m_3dof, 0.2f, {-30.0f, 30.0f, 0.0f}, { 0.0f, 0.0f, 90.0f }},
{ "bone_leftLeg", dBalancingCharacterBoneDefinition::m_3dof, 0.3f, { 60.0f, 60.0f, 70.0f }, { 0.0f, 90.0f, 0.0f } },
{ "bone_leftCalf", dBalancingCharacterBoneDefinition::m_1dof, 0.2f, {-60.0f, 60.0f, 0.0f }, { 0.0f, 0.0f, 90.0f } },
{ "bone_leftAnkle", dBalancingCharacterBoneDefinition::m_fkEffector, 0.2f,{ 0.0f, 0.0f, 0.0f },{ -90.0f, 0.0f, 90.0f } },
{ "effector_leftAnkle", dBalancingCharacterBoneDefinition::m_ikEffector},
{ "bone_leftFoot", dBalancingCharacterBoneDefinition::m_3dof, 0.2f, { -30.0f, 30.0f, 0.0f }, { 0.0f, 0.0f, 90.0f } },
{ NULL},
};
class dModelDescritor
{
public:
char* m_filename;
dFloat m_mass;
dBalancingCharacterBoneDefinition* m_skeletonDefinition;
};
static dModelDescritor tred = {"tred.ngd", 500.0f, tredDefinition};
class dBalacingCharacterEffector: public dCustomKinematicController
{
public:
dBalacingCharacterEffector(NewtonBody* const body, NewtonBody* const referenceBody, const dMatrix& attachmentMatrixInGlobalSpace, dFloat modelMass)
:dCustomKinematicController(body, attachmentMatrixInGlobalSpace, referenceBody)
,m_origin(GetTargetMatrix())
{
SetSolverModel(1);
SetControlMode(dCustomKinematicController::m_linearAndTwist);
SetMaxAngularFriction(modelMass * 100.0f);
SetMaxLinearFriction(modelMass * 9.8f * 10.0f);
dVector euler0;
dVector euler1;
m_origin.GetEulerAngles(euler0, euler1);
m_pitch = euler0.m_x;
m_yaw = euler0.m_y;
m_roll = euler0.m_z;
}
//void SetMatrix (dFloat x, dFloat y, dFloat z, dFloat pitch, dFloat yaw, dFloat roll)
void SetMatrix(dFloat x, dFloat y, dFloat z, dFloat pitch)
{
dMatrix matrix (dPitchMatrix(m_pitch + pitch) * dYawMatrix(m_yaw) * dRollMatrix(m_roll));
matrix.m_posit = m_origin.TransformVector(dVector (x, y, z, dFloat (1.0f)));
SetTargetMatrix(matrix);
}
dMatrix m_origin;
dFloat m_pitch;
dFloat m_yaw;
dFloat m_roll;
};
class dModelAnimTreeFootBase: public dModelAnimTree
{
public:
dModelAnimTreeFootBase(dModelRootNode* const model, dModelAnimTree* const child, dCustomKinematicController* const footEffector0, dCustomKinematicController* const footEffector1)
:dModelAnimTree(model)
,m_child(child)
,m_rootEffector0(footEffector0)
,m_rootEffector1(footEffector1)
{
}
~dModelAnimTreeFootBase()
{
delete m_child;
}
virtual void Debug(dCustomJoint::dDebugDisplay* const debugContext) const
{
m_child->Debug(debugContext);
}
int GetModelKeyFrames(const dModelKeyFramePose& input, dModelKeyFrame** const output) const
{
int count = 0;
for (dModelKeyFramePose::dListNode* node = input.GetFirst(); node; node = node->GetNext()) {
dModelKeyFrame& transform = node->GetInfo();
if ((transform.m_effector == m_rootEffector0) || (transform.m_effector == m_rootEffector1)) {
output[count] = &transform;
count++;
}
}
return count;
}
dModelAnimTree* m_child;
dCustomKinematicController* m_rootEffector0;
dCustomKinematicController* m_rootEffector1;
};
class dModelAnimTreePoseBalance: public dModelAnimTreeFootBase
{
public:
dModelAnimTreePoseBalance(dModelRootNode* const model, dModelAnimTree* const child, dCustomKinematicController* const footEffector0, dCustomKinematicController* const footEffector1)
:dModelAnimTreeFootBase(model, child, footEffector0, footEffector1)
{
}
virtual void Debug(dCustomJoint::dDebugDisplay* const debugContext) const
{
dMatrix matrix;
NewtonBodyGetMatrix(GetRoot()->GetBody(), &matrix[0][0]);
matrix.m_posit = CalculateCenterOfMass();
debugContext->DrawFrame(matrix);
m_child->Debug(debugContext);
}
/*
bool CalculateUpVector(dVector& upvector, dCustomKinematicController* const effector) const
{
bool ret = false;
NewtonBody* const body0 = effector->GetBody0();
for (NewtonJoint* contactjoint = NewtonBodyGetFirstContactJoint(body0); contactjoint; contactjoint = NewtonBodyGetNextContactJoint(body0, contactjoint)) {
ret = true;
dVector averageNormal(0.0f);
for (void* contact = NewtonContactJointGetFirstContact(contactjoint); contact; contact = NewtonContactJointGetNextContact(contactjoint, contact)) {
NewtonMaterial* const material = NewtonContactGetMaterial(contact);
dVector point(0.0f);
dVector normal(0.0f);
NewtonMaterialGetContactPositionAndNormal(material, body0, &point.m_x, &normal.m_x);
averageNormal += normal;
}
upvector = averageNormal.Normalize();
break;
}
ret = true;
upvector = dVector (0.0f, 1.0f, 0.0f, 0.0f);
upvector = dPitchMatrix(30.0f * dDegreeToRad).RotateVector(upvector);
return ret;
}
*/
dVector CalculateCenterOfMass() const
{
dMatrix matrix;
dVector com(0.0f);
dVector localCom;
dFloat Ixx;
dFloat Iyy;
dFloat Izz;
dFloat mass;
dFloat totalMass = 0.0f;
int stack = 1;
int bodyCount = 0;
const dModelNode* stackBuffer[32];
stackBuffer[0] = GetRoot();
while (stack) {
stack--;
const dModelNode* const root = stackBuffer[stack];
NewtonBody* const body = root->GetBody();
NewtonBodyGetMatrix(body, &matrix[0][0]);
NewtonBodyGetCentreOfMass(body, &localCom[0]);
NewtonBodyGetMass(body, &mass, &Ixx, &Iyy, &Izz);
totalMass += mass;
com += matrix.TransformVector(localCom).Scale(mass);
bodyCount++;
const dModelChildrenList& children = root->GetChildren();
for (const dModelChildrenList::dListNode* node = children.GetFirst(); node; node = node->GetNext()) {
stackBuffer[stack] = node->GetInfo();
stack++;
}
}
com = com.Scale(1.0f / totalMass);
com.m_w = 1.0f;
return com;
}
void GeneratePose(dFloat timestep, dModelKeyFramePose& output)
{
m_child->GeneratePose(timestep, output);
/*
dModelKeyFrame* feetPose[2];
const int count = GetModelKeyFrames(output, &feetPose[0]);
for (int i = 0; i < count; i++) {
dMatrix targetMatrix (m_rootEffector0->GetBodyMatrix());
dVector com (CalculateCenterOfMass());
dVector error (targetMatrix.m_posit - com);
//error.m_x = 0.0f;
error.m_y = 0.0f;
//error.m_z = 0.0f;
targetMatrix.m_posit -= error.Scale (0.35f);
//dTrace (("(%f %f %f) (%f %f %f)\n", com.m_x, com.m_y, com.m_z, targetMatrix.m_posit.m_x, targetMatrix.m_posit.m_y, targetMatrix.m_posit.m_z));
dMatrix rootMatrix;
NewtonBodyGetMatrix (m_rootEffector0->GetBody1(), &rootMatrix[0][0]);
dMatrix effectorMatrix (targetMatrix * rootMatrix.Inverse());
for (dModelKeyFramePose::dListNode* node = output.GetFirst(); node; node = node->GetNext()) {
//dModelKeyFrame& transform = node->GetInfo();
//transform.m_posit = effectorMatrix.m_posit;
//transform.SetMatrix(effectorMatrix);
}
}
*/
}
};
/*
class dModelAnimTreeFootAlignment: public dModelAnimTreeFootBase
{
#define RAY_CAST_LENGHT0 0.125f
#define RAY_CAST_LENGHT1 2.0f
class dFeetRayHitSensor
{
public:
dFeetRayHitSensor(dCustomKinematicController* const effector)
:m_rotation()
,m_footBody(NULL)
,m_ankleBody(NULL)
,m_effector(effector)
{
if (m_effector) {
m_footBody = effector->GetBody0();
NewtonCollision* const box = NewtonBodyGetCollision(m_footBody);
dMatrix matrix;
NewtonBodyGetMatrix(m_footBody, &matrix[0][0]);
dVector worldDir[] = {
{ 1.0f, -1.0f, 1.0, 0.0f },
{ -1.0f, -1.0f, 1.0, 0.0f },
{ -1.0f, -1.0f, -1.0, 0.0f },
{ 1.0f, -1.0f, -1.0, 0.0f }
};
for (int i = 0; i < 4; i++) {
dVector dir = matrix.UnrotateVector(worldDir[i]);
NewtonCollisionSupportVertex(box, &dir[0], &m_sensorHitPoint[i][0]);
m_sensorHitPoint[i].m_w = 0.0f;
}
for (NewtonJoint* joint = NewtonBodyGetFirstJoint(m_footBody); joint; joint = NewtonBodyGetNextJoint(m_footBody, joint)) {
dCustomJoint* const customJoint = (dCustomJoint*)NewtonJointGetUserData(joint);
NewtonBody* const body0 = customJoint->GetBody0();
NewtonBody* const body1 = customJoint->GetBody1();
NewtonBody* const otherBody = (body0 == m_footBody) ? body1 : body0;
if (otherBody != m_footBody) {
m_ankleBody = otherBody;
break;
}
}
}
}
dCustomKinematicController* GetEffector() const
{
return m_effector;
}
void DebugDraw(dCustomJoint::dDebugDisplay* const debugContext) const
{
if (m_effector) {
dMatrix matrix;
NewtonBodyGetMatrix(m_footBody, &matrix[0][0]);
for (int i = 0; i < 4; i++) {
dVector point0(matrix.TransformVector(m_sensorHitPoint[i]));
dVector point1(point0);
point0.m_y += RAY_CAST_LENGHT0;
point1.m_y -= RAY_CAST_LENGHT1;
debugContext->DrawLine(point0, point1);
}
}
}
void AlignMatrix(dModelKeyFrame* const transform, dFloat timestep)
{
dVector upvector;
if (CalculateSupportNormal(upvector)) {
// calculate foot desired matrix
dMatrix rootMatrix;
NewtonBodyGetMatrix(m_effector->GetBody1(), &rootMatrix[0][0]);
dMatrix targetMatrix(dMatrix(transform->m_rotation, transform->m_posit) * rootMatrix);
dFloat cosAngle = upvector.DotProduct3(targetMatrix.m_up);
if (cosAngle < 0.9997f) {
if (cosAngle > 0.87f) {
// align the matrix to the floor contacts.
dVector lateralDir(targetMatrix.m_up.CrossProduct(upvector));
lateralDir = lateralDir.Normalize();
dFloat coneAngle = dAcos(dClamp(cosAngle, dFloat(-1.0f), dFloat(1.0f)));
dMatrix pivotMatrix(m_effector->GetMatrix0().Inverse() * targetMatrix);
dQuaternion rotation(lateralDir, coneAngle);
dMatrix coneRotation(rotation, pivotMatrix.m_posit);
coneRotation.m_posit -= coneRotation.RotateVector(pivotMatrix.m_posit);
targetMatrix = targetMatrix * coneRotation;
// calculate and set new modified effector matrix.
transform->SetMatrix(targetMatrix * rootMatrix.Inverse());
} else {
cosAngle = 0;
}
}
}
}
private:
static unsigned FindFloorPrefilter(const NewtonBody* const body, const NewtonCollision* const collision, void* const userData)
{
dFeetRayHitSensor* const data = (dFeetRayHitSensor*)userData;
return ((data->m_footBody == body) || (data->m_ankleBody == body)) ? 0 : 1;
}
static dFloat FindFloor(const NewtonBody* const body, const NewtonCollision* const shapeHit, const dFloat* const hitContact, const dFloat* const hitNormal, dLong collisionID, void* const userData, dFloat intersectParam)
{
dFeetRayHitSensor* const data = (dFeetRayHitSensor*)userData;
dAssert(body != data->m_footBody);
dAssert(body != data->m_ankleBody);
if (intersectParam < data->m_hitParam) {
data->m_hitParam = intersectParam;
}
return data->m_hitParam;
}
bool CalculateSupportNormal(dVector& upvector)
{
bool ret = false;
dMatrix matrix;
dVector supportPlane[4];
NewtonWorld* const world = NewtonBodyGetWorld(m_footBody);
NewtonBodyGetMatrix(m_footBody, &matrix[0][0]);
int count = 0;
for (int i = 0; i < 4; i++) {
dVector point0(matrix.TransformVector(m_sensorHitPoint[i]));
dVector point1(point0);
m_hitParam = 1.2f;
point0.m_y += RAY_CAST_LENGHT0;
point1.m_y -= RAY_CAST_LENGHT1;
NewtonWorldRayCast(world, &point0[0], &point1[0], FindFloor, this, FindFloorPrefilter, 0);
if (m_hitParam < 1.0f) {
supportPlane[count] = point0 + (point1 - point0).Scale(m_hitParam);
count++;
}
}
if (count >= 3) {
dVector area(0.0f);
dVector e0(supportPlane[1] - supportPlane[0]);
for (int i = 2; i < count; i++) {
dVector e1(supportPlane[i] - supportPlane[0]);
area += e1.CrossProduct(e0);
e0 = e1;
}
ret = true;
upvector = area.Normalize();
//upvector = dPitchMatrix(45.0f * dDegreeToRad).RotateVector(dVector (0, 1.0f, 0.0f, 0.0f));
}
ret = true;
static dFloat angle = 0.0f;
dMatrix xxxx(dPitchMatrix(angle));
angle -= 0.002f;
upvector = xxxx[1];
//upvector = area.Normalize();
//upvector = dPitchMatrix(45.0f * dDegreeToRad).RotateVector(dVector (0, 1.0f, 0.0f, 0.0f));
return ret;
}
dVector m_sensorHitPoint[4];
dQuaternion m_rotation;
NewtonBody* m_footBody;
NewtonBody* m_ankleBody;
dCustomKinematicController* m_effector;
dFloat m_hitParam;
};
public:
dModelAnimTreeFootAlignment(dModelRootNode* const model, dModelAnimTree* const child, dCustomKinematicController* const footEffector0, dCustomKinematicController* const footEffector1)
:dModelAnimTreeFootBase(model, child, footEffector0, footEffector1)
,m_foot0(footEffector0)
,m_foot1(footEffector1)
{
}
virtual void Debug(dCustomJoint::dDebugDisplay* const debugContext) const
{
m_foot0.DebugDraw(debugContext);
m_foot1.DebugDraw(debugContext);
m_child->Debug(debugContext);
}
void GeneratePose(dFloat timestep, dModelKeyFramePose& output)
{
m_child->GeneratePose(timestep, output);
dModelKeyFrame* feetPose[2];
const int count = GetModelKeyFrames(output, &feetPose[0]);
for (int i = 0; i < count; i++) {
dMatrix rootMatrix;
dModelKeyFrame* const transform = feetPose[i];
dCustomKinematicController* const effector = transform->m_effector;
if (effector == m_foot0.GetEffector()) {
m_foot0.AlignMatrix(transform, timestep);
}
if (effector == m_foot1.GetEffector()) {
m_foot1.AlignMatrix(transform, timestep);
}
}
}
dFeetRayHitSensor m_foot0;
dFeetRayHitSensor m_foot1;
};
*/
class dModelAnimTreeAnkleAndFootController: public dModelAnimTree
{
public:
dModelAnimTreeAnkleAndFootController(dModelRootNode* const model, dModelAnimTree* const child, int count, dCustomKinematicController** const effectors)
:dModelAnimTree(model)
,m_child(child)
{
}
~dModelAnimTreeAnkleAndFootController()
{
delete m_child;
}
virtual void Debug(dCustomJoint::dDebugDisplay* const debugContext) const
{
//dMatrix matrix;
//NewtonBodyGetMatrix(GetRoot()->GetBody(), &matrix[0][0]);
//matrix.m_posit = CalculateCenterOfMass();
//debugContext->DrawFrame(matrix);
m_child->Debug(debugContext);
}
/*
bool CalculateUpVector(dVector& upvector, dCustomKinematicController* const effector) const
{
bool ret = false;
NewtonBody* const body0 = effector->GetBody0();
for (NewtonJoint* contactjoint = NewtonBodyGetFirstContactJoint(body0); contactjoint; contactjoint = NewtonBodyGetNextContactJoint(body0, contactjoint)) {
ret = true;
dVector averageNormal(0.0f);
for (void* contact = NewtonContactJointGetFirstContact(contactjoint); contact; contact = NewtonContactJointGetNextContact(contactjoint, contact)) {
NewtonMaterial* const material = NewtonContactGetMaterial(contact);
dVector point(0.0f);
dVector normal(0.0f);
NewtonMaterialGetContactPositionAndNormal(material, body0, &point.m_x, &normal.m_x);
averageNormal += normal;
}
upvector = averageNormal.Normalize();
break;
}
ret = true;
upvector = dVector (0.0f, 1.0f, 0.0f, 0.0f);
upvector = dPitchMatrix(30.0f * dDegreeToRad).RotateVector(upvector);
return ret;
}
*/
void GeneratePose(dFloat timestep, dModelKeyFramePose& output)
{
m_child->GeneratePose(timestep, output);
/*
dModelKeyFrame* feetPose[2];
const int count = GetModelKeyFrames(output, &feetPose[0]);
for (int i = 0; i < count; i++) {
dMatrix targetMatrix (m_rootEffector0->GetBodyMatrix());
dVector com (CalculateCenterOfMass());
dVector error (targetMatrix.m_posit - com);
//error.m_x = 0.0f;
error.m_y = 0.0f;
//error.m_z = 0.0f;
targetMatrix.m_posit -= error.Scale (0.35f);
//dTrace (("(%f %f %f) (%f %f %f)\n", com.m_x, com.m_y, com.m_z, targetMatrix.m_posit.m_x, targetMatrix.m_posit.m_y, targetMatrix.m_posit.m_z));
dMatrix rootMatrix;
NewtonBodyGetMatrix (m_rootEffector0->GetBody1(), &rootMatrix[0][0]);
dMatrix effectorMatrix (targetMatrix * rootMatrix.Inverse());
for (dModelKeyFramePose::dListNode* node = output.GetFirst(); node; node = node->GetNext()) {
//dModelKeyFrame& transform = node->GetInfo();
//transform.m_posit = effectorMatrix.m_posit;
//transform.SetMatrix(effectorMatrix);
}
}
*/
}
dModelAnimTree* m_child;
};
class dBalancingCharacter: public dModelRootNode
{
public:
dBalancingCharacter(NewtonBody* const rootBody)
:dModelRootNode(rootBody, dGetIdentityMatrix())
,m_pose()
,m_animtree(NULL)
{
}
~dBalancingCharacter()
{
if (m_animtree) {
delete m_animtree;
}
}
void SetAllPartsNonCollidable()
{
int stack = 1;
dModelNode* stackBuffer[32];
stackBuffer[0] = this;
void* const aggregate = NewtonCollisionAggregateCreate(NewtonBodyGetWorld(GetBody()));
while (stack) {
stack--;
dModelNode* const root = stackBuffer[stack];
NewtonBody* const body = root->GetBody();
NewtonCollisionAggregateAddBody(aggregate, body);
const dModelChildrenList& children = root->GetChildren();
for (dModelChildrenList::dListNode* node = children.GetFirst(); node; node = node->GetNext()) {
stackBuffer[stack] = node->GetInfo();
stack++;
}
}
NewtonCollisionAggregateSetSelfCollision(aggregate, false);
}
void SetAnimTree(int count, dCustomKinematicController** const effectors)
{
dModelAnimTree* const poseGenerator = new dModelAnimTreePose(this, m_pose);
dModelAnimTree* const feetController = new dModelAnimTreeAnkleAndFootController(this, poseGenerator, count, effectors);
//dModelAnimTreePoseBalance* const poseBalance = new dModelAnimTreePoseBalance(this, poseGenerator, rootEffector0, rootEffector1);
//dModelAnimTree* const footRoll = new dModelAnimTreeFootAlignment(this, poseBalance, rootEffector0, rootEffector1);
//m_animtree = footRoll;
//m_animtree = poseBalance;
m_animtree = feetController;
//m_animtree = poseGenerator;
}
void OnDebug(dCustomJoint::dDebugDisplay* const debugContext)
{
dFloat scale = debugContext->GetScale();
debugContext->SetScale(0.5f);
for (dModelKeyFramePose::dListNode* node = m_pose.GetFirst(); node; node = node->GetNext()) {
const dModelKeyFrame& keyFrame = node->GetInfo();
keyFrame.m_effector->Debug(debugContext);
}
if (m_animtree) {
m_animtree->Debug(debugContext);
}
debugContext->SetScale(scale);
}
void ApplyControls (dFloat timestep, dFloat x, dFloat y, dFloat z, dFloat pitch)
{
m_animtree->GeneratePose(timestep, m_pose);
//for (dModelKeyFramePose::dListNode* node = m_pose.GetFirst(); node; node = node->GetNext()) {
// dModelKeyFrame& transform = node->GetInfo();
// transform.m_effector->SetTargetMatrix(dMatrix(transform.m_rotation, transform.m_posit));
// //dBalacingCharacterEffector* const effector = (dBalacingCharacterEffector*)transform.m_effector;
// //effector->SetMatrix (x, y, z, pitch);
// //break;
//}
//dModelKeyFramePose::dListNode* node = m_pose.GetFirst();
//if (node) {
// dModelKeyFrame& transform = node->GetInfo();
// dBalacingCharacterEffector* const effector = (dBalacingCharacterEffector*)transform.m_effector;
// effector->SetMatrix(x, y, z, pitch);
//}
}
dModelKeyFramePose m_pose;
dModelAnimTree* m_animtree;
};
class dBalancingCharacterManager: public dModelManager
{
public:
dBalancingCharacterManager(DemoEntityManager* const scene)
:dModelManager(scene->GetNewton())
//,m_currentController(NULL)
{
m_pitch = 0.0f;
m_posit_x = 0.0f;
m_posit_y = 0.0f;
m_posit_z = 0.0f;
scene->Set2DDisplayRenderFunction(RenderHelpMenu, NULL, this);
}
~dBalancingCharacterManager()
{
}
static void RenderHelpMenu(DemoEntityManager* const scene, void* const context)
{
dVector color(1.0f, 1.0f, 0.0f, 0.0f);
dBalancingCharacterManager* const me = (dBalancingCharacterManager*)context;
scene->Print(color, "linear degrees of freedom");
ImGui::SliderFloat("pitch", &me->m_pitch, -30.0f, 30.0f);
ImGui::SliderFloat("posit_x", &me->m_posit_x, -1.0f, 1.0f);
ImGui::SliderFloat("posit_y", &me->m_posit_y, -1.0f, 1.0f);
ImGui::SliderFloat("posit_z", &me->m_posit_z, -1.0f, 1.0f);
//
//ImGui::Separator();
//scene->Print(color, "angular degrees of freedom");
//ImGui::SliderFloat("pitch", &me->m_gripper_pitch, -180.0f, 180.0f);
//ImGui::SliderFloat("yaw", &me->m_gripper_yaw, -80.0f, 80.0f);
//ImGui::SliderFloat("roll", &me->m_gripper_roll, -180.0f, 180.0f);
}
static void ClampAngularVelocity(const NewtonBody* body, dFloat timestep, int threadIndex)
{
dVector omega;
NewtonBodyGetOmega(body, &omega[0]);
omega.m_w = 0.0f;
dFloat mag2 = omega.DotProduct3(omega);
if (mag2 > (100.0f * 100.0f)) {
omega = omega.Normalize().Scale(100.0f);
NewtonBodySetOmega(body, &omega[0]);
}
PhysicsApplyGravityForce(body, timestep, threadIndex);
}
NewtonBody* CreateBodyPart(DemoEntity* const bodyPart, const dBalancingCharacterBoneDefinition& definition)
{
NewtonWorld* const world = GetWorld();
NewtonCollision* const shape = bodyPart->CreateCollisionFromchildren(world);
dAssert(shape);
// calculate the boneBody matrix
dMatrix matrix(bodyPart->CalculateGlobalMatrix());
// create the rigid body that will make this boneBody
NewtonBody* const boneBody = NewtonCreateDynamicBody(world, shape, &matrix[0][0]);
// calculate the moment of inertia and the relative center of mass of the solid
//NewtonBodySetMassProperties (boneBody, definition.m_mass, shape);
NewtonBodySetMassProperties(boneBody, definition.m_massFraction, shape);
// save the user data with the boneBody body (usually the visual geometry)
NewtonBodySetUserData(boneBody, bodyPart);
// assign the material for early collision culling
//NewtonBodySetMaterialGroupID(boneBody, m_material);
NewtonBodySetMaterialGroupID(boneBody, 0);
//dVector damping (0.0f);
//NewtonBodySetLinearDamping(boneBody, damping.m_x);
//NewtonBodySetAngularDamping(boneBody, &damping[0]);
// set the bod part force and torque call back to the gravity force, skip the transform callback
//NewtonBodySetForceAndTorqueCallback (boneBody, PhysicsApplyGravityForce);
NewtonBodySetForceAndTorqueCallback(boneBody, ClampAngularVelocity);
// destroy the collision helper shape
NewtonDestroyCollision(shape);
return boneBody;
}
dCustomKinematicController* ConnectEffector(dModelNode* const effectorNode, const dMatrix& effectorMatrix, const dFloat modelMass)
{
//const dModelNode* const referenceNode = effectorNode->GetParent()->GetParent();
//dAssert(referenceNode);
//dCustomJoint* const pivotJoint = FindJoint(referenceNode->GetBody(), referenceNode->GetParent()->GetBody());
//dAssert(pivotJoint);
//Assert(joint->GetBody1() == effectorNode->GetRoot()->GetBody());
//Matrix pivotMatrix(joint->GetMatrix1());
//dBalacingCharacterEffector* const effector = new dBalacingCharacterEffector(effectorNode->GetBody(), effectorNode->GetRoot()->GetBody(), effectorMatrix, modelMass, pivotJoint);
dBalacingCharacterEffector* const effector = new dBalacingCharacterEffector(effectorNode->GetBody(), effectorNode->GetRoot()->GetBody(), effectorMatrix, modelMass);
return effector;
}
dCustomJoint* ConnectLimb(NewtonBody* const bone, NewtonBody* const parent, const dBalancingCharacterBoneDefinition& definition)
{
dMatrix matrix;
NewtonBodyGetMatrix(bone, &matrix[0][0]);
dBalancingCharacterBoneDefinition::dFrameMatrix frameAngle(definition.m_frameBasics);
dMatrix pinAndPivotInGlobalSpace(dPitchMatrix(frameAngle.m_pitch * dDegreeToRad) * dYawMatrix(frameAngle.m_yaw * dDegreeToRad) * dRollMatrix(frameAngle.m_roll * dDegreeToRad));
pinAndPivotInGlobalSpace = pinAndPivotInGlobalSpace * matrix;
dCustomJoint* ret = NULL;
switch (definition.m_type)
{
case dBalancingCharacterBoneDefinition::m_ball:
{
dCustomBallAndSocket* const joint = new dCustomBallAndSocket(pinAndPivotInGlobalSpace, bone, parent);
joint->EnableCone(false);
joint->EnableTwist(false);
ret = joint;
break;
}
case dBalancingCharacterBoneDefinition::m_0dof:
{
dCustomHinge* const joint = new dCustomHinge(pinAndPivotInGlobalSpace, bone, parent);
joint->EnableLimits(true);
joint->SetLimits(0.0f, 0.0f);
ret = joint;
break;
}
case dBalancingCharacterBoneDefinition::m_1dof:
{
dCustomBallAndSocket* const joint = new dCustomBallAndSocket(pinAndPivotInGlobalSpace, bone, parent);
joint->EnableTwist(true);
joint->SetTwistLimits(definition.m_jointLimits.m_minTwistAngle * dDegreeToRad, definition.m_jointLimits.m_maxTwistAngle * dDegreeToRad);
joint->EnableCone(true);
joint->SetConeLimits(0.0f);
ret = joint;
break;
}
case dBalancingCharacterBoneDefinition::m_2dof:
{
dCustomBallAndSocket* const joint = new dCustomBallAndSocket(pinAndPivotInGlobalSpace, bone, parent);
joint->EnableTwist(true);
joint->SetTwistLimits(0.0f, 0.0f);
joint->EnableCone(true);
joint->SetConeLimits(definition.m_jointLimits.m_coneAngle * dDegreeToRad);
ret = joint;
break;
}
case dBalancingCharacterBoneDefinition::m_3dof:
{
dCustomBallAndSocket* const joint = new dCustomBallAndSocket(pinAndPivotInGlobalSpace, bone, parent);
joint->EnableTwist(true);
joint->SetTwistLimits(definition.m_jointLimits.m_minTwistAngle * dDegreeToRad, definition.m_jointLimits.m_maxTwistAngle * dDegreeToRad);
joint->EnableCone(true);
joint->SetConeLimits(definition.m_jointLimits.m_coneAngle * dDegreeToRad);
ret = joint;
break;
}
case dBalancingCharacterBoneDefinition::m_fkEffector:
{
dCustomKinematicController* const effector = new dCustomKinematicController(bone, pinAndPivotInGlobalSpace, parent);
effector->SetSolverModel(1);
effector->SetControlMode(dCustomKinematicController::m_full6dof);
effector->SetMaxAngularFriction(1.0e20f);
effector->SetMaxLinearFriction(1.0e20f);
ret = effector;
break;
}
default:
ret = NULL;
dAssert (0);
}
return ret;
}
void NormalizeMassAndInertia(dModelRootNode* const model, dFloat modelMass) const
{
int stack = 1;
int bodyCount = 0;
NewtonBody* bodyArray[1024];
dModelNode* stackBuffer[32];
stackBuffer[0] = model;
while (stack) {
stack--;
dModelNode* const root = stackBuffer[stack];
bodyArray[bodyCount] = root->GetBody();
bodyCount++;
const dModelChildrenList& children = root->GetChildren();
for (dModelChildrenList::dListNode* node = children.GetFirst(); node; node = node->GetNext()) {
stackBuffer[stack] = node->GetInfo();
stack++;
}
}
dFloat totalMass = 0.0f;
for (int i = 0; i < bodyCount; i++) {
dFloat Ixx;
dFloat Iyy;
dFloat Izz;
dFloat mass;
NewtonBody* const body = bodyArray[i];
NewtonBodyGetMass(body, &mass, &Ixx, &Iyy, &Izz);
totalMass += mass;
}
dFloat massNormalize = modelMass / totalMass;
for (int i = 0; i < bodyCount; i++) {
dFloat Ixx;
dFloat Iyy;
dFloat Izz;
dFloat mass;
NewtonBody* const body = bodyArray[i];
NewtonBodyGetMass(body, &mass, &Ixx, &Iyy, &Izz);
mass *= massNormalize;
Ixx *= massNormalize;
Iyy *= massNormalize;
Izz *= massNormalize;
dFloat minInertia = dMin(Ixx, dMin(Iyy, Izz));
if (minInertia < 10.0f) {
dFloat maxInertia = dMax(dFloat(10.0f), dMax(Ixx, dMax(Iyy, Izz)));
Ixx = maxInertia;
Iyy = maxInertia;
Izz = maxInertia;
}
NewtonBodySetMassMatrix(body, mass, Ixx, Iyy, Izz);
}
}
void CreateKinematicModel(dModelDescritor& descriptor, const dMatrix& location)
{
NewtonWorld* const world = GetWorld();
DemoEntityManager* const scene = (DemoEntityManager*)NewtonWorldGetUserData(world);
DemoEntity* const entityModel = DemoEntity::LoadNGD_mesh(descriptor.m_filename, world, scene->GetShaderCache());
scene->Append(entityModel);
dMatrix matrix0(entityModel->GetCurrentMatrix());
entityModel->ResetMatrix(*scene, matrix0 * location);
// create the root body, do not set the transform call back
NewtonBody* const rootBody = CreateBodyPart(entityModel, descriptor.m_skeletonDefinition[0]);
// make a kinematic controlled model.
dBalancingCharacter* const model = new dBalancingCharacter(rootBody);
// add the model to the manager
AddRoot(model);
// the the model to calculate the local transformation
model->SetTranformMode(true);
// save the controller as the collision user data, for collision culling
//NewtonCollisionSetUserData(NewtonBodyGetCollision(rootBone), controller);
int stackIndex = 0;
dModelNode* parentBones[32];
DemoEntity* childEntities[32];
for (DemoEntity* child = entityModel->GetChild(); child; child = child->GetSibling()) {
parentBones[stackIndex] = model;
childEntities[stackIndex] = child;
stackIndex++;
//dTrace(("name: %s\n", child->GetName().GetStr()));
}
// walk model hierarchic adding all children designed as rigid body bones.
int effectorsCount = 0;
dCustomKinematicController* effectorList[16];
while (stackIndex) {
stackIndex--;
DemoEntity* const entity = childEntities[stackIndex];
dModelNode* parentBone = parentBones[stackIndex];
const char* const name = entity->GetName().GetStr();
dTrace(("name: %s\n", name));
for (int i = 1; descriptor.m_skeletonDefinition[i].m_boneName; i++) {
if (!strcmp(descriptor.m_skeletonDefinition[i].m_boneName, name)) {
NewtonBody* const parentBody = parentBone->GetBody();
if (descriptor.m_skeletonDefinition[i].m_type == dBalancingCharacterBoneDefinition::m_ikEffector) {
dModelKeyFrame effectorPose;
dMatrix effectorMatrix(entity->CalculateGlobalMatrix());
effectorPose.m_effector = ConnectEffector(parentBone, effectorMatrix, descriptor.m_mass);
effectorPose.SetMatrix (effectorPose.m_effector->GetTargetMatrix());
model->m_pose.Append(effectorPose);
effectorList[effectorsCount] = effectorPose.m_effector;
effectorsCount++;
} else {
NewtonBody* const childBody = CreateBodyPart(entity, descriptor.m_skeletonDefinition[i]);
dCustomJoint* const joint = ConnectLimb(childBody, parentBody, descriptor.m_skeletonDefinition[i]);
dMatrix bindMatrix(entity->GetParent()->CalculateGlobalMatrix((DemoEntity*)NewtonBodyGetUserData(parentBody)).Inverse());
dModelNode* const bone = new dModelNode(childBody, bindMatrix, parentBone);
if (joint->IsType(dCustomKinematicController::GetType())) {
dModelKeyFrame effectorPose;
effectorPose.m_effector = (dCustomKinematicController*)joint;
effectorPose.SetMatrix(effectorPose.m_effector->GetTargetMatrix());
model->m_pose.Append(effectorPose);
effectorList[effectorsCount] = effectorPose.m_effector;
effectorsCount++;
}
for (DemoEntity* child = entity->GetChild(); child; child = child->GetSibling()) {
parentBones[stackIndex] = bone;
childEntities[stackIndex] = child;
stackIndex++;
}
}
break;
}
}
}
// set mass distribution by density and volume
NormalizeMassAndInertia(model, descriptor.m_mass);
// make internal part non collidable
model->SetAllPartsNonCollidable();
#if 0
dCustomHinge* const fixToWorld = new dCustomHinge (matrix0 * location, model->GetBody(), NULL);
fixToWorld->EnableLimits(true);
fixToWorld->SetLimits(0.0f, 0.0f);
#endif
// setup the pose generator
model->SetAnimTree(effectorsCount, effectorList);
//m_currentController = robot;
}
virtual void OnDebug(dModelRootNode* const root, dCustomJoint::dDebugDisplay* const debugContext)
{
dBalancingCharacter* const model = (dBalancingCharacter*)root;
model->OnDebug(debugContext);
}
virtual void OnUpdateTransform(const dModelNode* const bone, const dMatrix& localMatrix) const
{
NewtonBody* const body = bone->GetBody();
DemoEntity* const ent = (DemoEntity*)NewtonBodyGetUserData(body);
DemoEntityManager* const scene = (DemoEntityManager*)NewtonWorldGetUserData(NewtonBodyGetWorld(body));
dQuaternion rot(localMatrix);
ent->SetMatrix(*scene, rot, localMatrix.m_posit);
}
virtual void OnPreUpdate(dModelRootNode* const root, dFloat timestep) const
{
dBalancingCharacter* const model = (dBalancingCharacter*)root;
model->ApplyControls (timestep, m_posit_x, m_posit_y, m_posit_z, dDegreeToRad * m_pitch);
}
//dBalancingCharacter* m_currentController;
dFloat32 m_pitch;
dFloat32 m_posit_x;
dFloat32 m_posit_y;
dFloat32 m_posit_z;
};
void BalancingCharacter(DemoEntityManager* const scene)
{
// load the sky box
scene->CreateSkyBox();
CreateLevelMesh(scene, "flatPlane.ngd", true);
dBalancingCharacterManager* const manager = new dBalancingCharacterManager(scene);
NewtonWorld* const world = scene->GetNewton();
int defaultMaterialID = NewtonMaterialGetDefaultGroupID(world);
NewtonMaterialSetDefaultFriction(world, defaultMaterialID, defaultMaterialID, 1.0f, 1.0f);
NewtonMaterialSetDefaultElasticity(world, defaultMaterialID, defaultMaterialID, 0.0f);
dMatrix origin (dYawMatrix(-90.0f * dDegreeToRad));
origin.m_posit.m_y += 1.0f;
manager->CreateKinematicModel(tred, origin);
origin.m_posit.m_x = -8.0f;
origin.m_posit.m_y = 1.0f;
origin.m_posit.m_z = 0.0f;
scene->SetCameraMatrix(dGetIdentityMatrix(), origin.m_posit);
}
| 34,597 | 14,188 |
/** @file
MODULE : ImagePlaneDecoder
TAG : IPD
FILE NAME : ImagePlaneDecoder.cpp
DESCRIPTION : A base class with the common implementations for a
family of implementations to read sequentially from
a bit stream, decode and inverse quantise each colour
plane in an image. The colour plane info is held in
ColourPlaneDecoding objects. The process is as follows:
// Instantiate.
ImagePlaneDecoder* p = new ImagePlaneDecoderImpl();
p->Create();
p->SetEndOfPlaneMarkerVlc();
p->SetEndOfImageMarkerVlc();
.
.
// Attach utility classes.
p->AttachVectorQuantiser();
.
.
p->AttachBitStreamReader();
.
.
// Use.
p->Decode();
.
.
// Delete.
p->Destroy()
delete p;
REVISION HISTORY :
COPYRIGHT :
RESTRICTIONS :
===========================================================================
*/
#ifdef _WINDOWS
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#else
#include <stdio.h>
#endif
#include <memory.h>
#include <string.h>
#include <stdlib.h>
#include "ImagePlaneDecoder.h"
/*
--------------------------------------------------------------------------
Construction and destruction.
--------------------------------------------------------------------------
*/
ImagePlaneDecoder::ImagePlaneDecoder(void)
{
// Colour plane info.
for(int i = 0; i < IPD_COLOUR_PLANES; i++)
_pColourPlane[i] = NULL;
// References to helper classes not owned by this.
_pVectorQuantiser = NULL;
_pRunVlcDecoder = NULL;
_pVqVlcDecoder = NULL;
_pIntraVlcDecoder = NULL; // For INTRA coded images.
// Bit stream to read the encoded bits from.
_pBitStreamReader = NULL;
_minPelValue = 0; // Default to 6 bit range.
_maxPelValue = 63;
_endOfPlaneMarker = 32;
_endOfImageMarker = 33;
}//end constructor.
ImagePlaneDecoder::~ImagePlaneDecoder(void)
{
Destroy();
}//end destructor.
int ImagePlaneDecoder::Create(cpdType* refLum,
int lumWidth, int lumHeight,
cpdType* refChrU,
cpdType* refChrV,
int chrWidth, int chrHeight,
int vecLumWidth, int vecLumHeight,
int vecChrWidth, int vecChrHeight)
{
// Clear out any old baggage.
Destroy();
// For decoding an array of decoded data objects are required
// for each colour component in a plane. Create the colour
// plane info holders.
for(int colour = 0; colour < IPD_COLOUR_PLANES; colour++)
{
_pColourPlane[colour] = new ColourPlaneDecoding();
if( _pColourPlane[colour] == NULL )
{
Destroy();
return(0);
}//end if !_pColourPlane[colour]...
int created = 1;
switch(colour)
{
case IPD_LUM:
created &= _pColourPlane[colour]->Create( refLum,
lumWidth, lumHeight,
vecLumWidth, vecLumHeight);
break;
case IPD_CHRU:
created &= _pColourPlane[colour]->Create( refChrU,
chrWidth, chrHeight,
vecChrWidth, vecChrHeight);
break;
case IPD_CHRV:
created &= _pColourPlane[colour]->Create( refChrV,
chrWidth, chrHeight,
vecChrWidth, vecChrHeight);
break;
}//end switch colour...
if( !created )
{
Destroy();
return(0);
}//end if !created...
// All colours have the same range.
_pColourPlane[colour]->SetPelValueRange(_minPelValue, _maxPelValue);
}//end for colour...
return(1);
}//end Create.
void ImagePlaneDecoder::Destroy(void)
{
for(int i = 0; i < IPD_COLOUR_PLANES; i++)
{
if(_pColourPlane[i] != NULL)
delete _pColourPlane[i];
_pColourPlane[i] = NULL;
}//end for i...
// References.
_pVectorQuantiser = NULL;
_pRunVlcDecoder = NULL;
_pVqVlcDecoder = NULL;
_pIntraVlcDecoder = NULL;
_pBitStreamReader = NULL;
}//end Destroy.
/*
--------------------------------------------------------------------------
Common utility methods.
--------------------------------------------------------------------------
*/
| 4,458 | 2,068 |
#include <QDebug>
#include <Qt>
#include <QApplication>
#include "sniffermodel.h"
#include "snifferwindow.h"
#include "SnifferDelegate.h"
SnifferModel::SnifferModel(QObject *parent)
: QAbstractItemModel(parent),
mFilter(false),
mNeverExpire(false),
mFadeInactive(false),
mMuteNotched(false),
mTimeSequence(0)
{
QColor TextColor = QApplication::palette().color(QPalette::Text);
if (TextColor.red() + TextColor.green() + TextColor.blue() < 200)
{
mDarkMode = false;
}
else mDarkMode = true;
}
SnifferModel::~SnifferModel()
{
qDeleteAll(mMap);
mMap.clear();
mFilters.clear();
}
int SnifferModel::columnCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : tc::LAST+1;
}
int SnifferModel::rowCount(const QModelIndex &parent) const
{
const QMap<quint32, SnifferItem*>& map = mFilter ? mFilters : mMap;
return parent.isValid() ? 0 : map.size();
}
QVariant SnifferModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
SnifferItem *item = static_cast<SnifferItem*>(index.internalPointer());
if(!item) QVariant();
int col = index.column();
switch(role)
{
case Qt::DisplayRole:
{
switch(col)
{
case tc::DELTA:
return QString::number(item->getDelta(), 'f');
case tc::ID:
return QString("%1").arg(item->getId(), 5, 16, QLatin1Char(' ')).toUpper();
default:
break;
}
if(tc::DATA_0<=col && col <=tc::DATA_7)
{
int data = item->getData(col-tc::DATA_0);
if(data >= 0)
{
return QString("%1").arg((uint8_t)data, 2, 16, QLatin1Char('0')).toUpper();
}
}
break;
}
case Qt::ForegroundRole:
{
if (!mFadeInactive || col < 2) return QApplication::palette().brush(QPalette::Text);
int v = item->getSeqInterval(col - 2) * 10;
//qDebug() << "mTS: " << mTimeSequence << " gDT(" << (col - 2) << ") " << item->getDataTimestamp(col - 2);
if (v > 225) v = 225;
if (v < 0) v = 0;
if (!mDarkMode) //text defaults to being dark
{
return QBrush(QColor(v,v,v,255));
}
else //text defaults to being light
{
return QBrush(QColor(255-v,255-v,255-v,255));
}
}
case Qt::BackgroundRole:
{
if(tc::ID==col)
{
if(item->elapsed() > 4000)
{
if (!mDarkMode) return QBrush(Qt::red);
return QBrush(QColor(128,0,0));
}
}
else if(tc::DATA_0<=col && col<=tc::DATA_7)
{
dc change = item->dataChange(col-tc::DATA_0);
switch(change)
{
case dc::INC:
if (!mDarkMode) return QBrush(Qt::green);
return QBrush(QColor(0,128,0));
case dc::DEINC:
if (!mDarkMode) return QBrush(Qt::red);
return QBrush(QColor(128,0,0));
default:
return QApplication::palette().brush(QPalette::Base);
}
}
break;
}
}
return QVariant();
}
Qt::ItemFlags SnifferModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return QAbstractItemModel::flags(index);
}
QVariant SnifferModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{
switch(section)
{
case tc::DELTA:
return QString("Delta");
case tc::ID:
return QString("ID");
default:
break;
}
if(tc::DATA_0<=section && section <=tc::DATA_7)
return QString::number(section-tc::DATA_0);
}
return QVariant();
}
QModelIndex SnifferModel::index(int row, int column, const QModelIndex &parent) const
{
if (parent.isValid())
return QModelIndex();
const QMap<quint32, SnifferItem*>& map = mFilter ? mFilters : mMap;
if(column>tc::LAST || row>=map.size())
return QModelIndex();
/* ugly but I can't find best without creating a list to keep indexes */
QMap<quint32, SnifferItem*>::const_iterator iter;
int i;
for(iter = map.begin(), i=0 ; i<row ; ++i, ++iter);
return createIndex(row, column, iter.value());
}
QModelIndex SnifferModel::parent(const QModelIndex &) const
{
return QModelIndex();
}
bool SnifferModel::getNeverExpire()
{
return mNeverExpire;
}
bool SnifferModel::getFadeInactive()
{
return mFadeInactive;
}
bool SnifferModel::getMuteNotched()
{
return mMuteNotched;
}
void SnifferModel::setNeverExpire(bool val)
{
mNeverExpire = val;
}
void SnifferModel::setFadeInactive(bool val)
{
mFadeInactive = val;
}
void SnifferModel::setMuteNotched(bool val)
{
mMuteNotched = val;
}
void SnifferModel::clear()
{
beginResetModel();
qDeleteAll(mMap);
mMap.clear();
mFilters.clear();
mFilter = false;
endResetModel();
}
//Called from window with a timer (currently 200ms)
void SnifferModel::refresh()
{
QMap<quint32, SnifferItem*>::iterator i;
QVector<quint32> toRemove;
SnifferItem* item;
mTimeSequence++;
/* update markers */
for (i = mMap.begin(); i != mMap.end(); ++i)
{
i.value()->updateMarker();
if(i.value()->elapsed()>5000 && !mNeverExpire)
toRemove.append(i.key());
}
if(toRemove.size())
{
beginResetModel();
foreach(quint32 id, toRemove)
{
/* remove element */
item = mMap.take(id);
mFilters.remove(id);
delete item;
/* send notification */
emit idChange(id, false);
}
endResetModel();
}
else
/* refresh data */
dataChanged(createIndex(0, 0),
createIndex(rowCount()-1, columnCount()-1), QVector<int>(Qt::DisplayRole));
}
void SnifferModel::filter(fltType pType, int pId)
{
beginResetModel();
switch(pType)
{
case fltType::NONE:
/* erase everything */
mFilter = true;
mFilters.clear();
break;
case fltType::ADD:
/* add filter to list */
mFilter = true;
mFilters[pId] = mMap[pId];
break;
case fltType::REMOVE:
/* remove filter */
if(!mFilter)
mFilters = mMap;
mFilter = true;
mFilters.remove(pId);
break;
case fltType::ALL:
/* stop filtering */
mFilter = false;
mFilters.clear();
break;
}
endResetModel();
}
/***********************************************/
/********** slots ****************/
/***********************************************/
void SnifferModel::update(CANConnection*, QVector<CANFrame>& pFrames)
{
foreach(const CANFrame& frame, pFrames)
{
if(!mMap.contains(frame.frameId()))
{
int index = std::distance(mMap.begin(), mMap.lowerBound(frame.frameId()));
/* add the frame */
beginInsertRows(QModelIndex(), index, index);
mMap[frame.frameId()] = new SnifferItem(frame, mTimeSequence);
mMap[frame.frameId()]->update(frame, mTimeSequence, mMuteNotched);
endInsertRows();
emit idChange(frame.frameId(), true);
}
else
//updateData
mMap[frame.frameId()]->update(frame, mTimeSequence, mMuteNotched);
}
}
void SnifferModel::notch()
{
QMap<quint32, SnifferItem*>& map = mFilter ? mFilters : mMap;
foreach(SnifferItem* item, map)
item->notch(true);
}
void SnifferModel::unNotch()
{
QMap<quint32, SnifferItem*>& map = mFilter ? mFilters : mMap;
foreach(SnifferItem* item, map)
item->notch(false);
}
| 8,397 | 2,701 |
/////////////////////////////////////////////////////////////////////////////
// Name: bootdevice_vscp.cpp
// Purpose:
// Author: Ake Hedman
// Modified by:
// Created: 16/12/2009 22:26:09
// RCS-ID:
// Copyright: (C) 2000-2020
// Ake Hedman, Grodans Paradis AB, <akhe@vscp.org>
// (C) 2012 Dinesh Guleria
// Licence:
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version
// 2 of the License, or (at your option) any later version.
//
// This file is part of the VSCP (https://www.vscp.org)
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this file see the file COPYING. If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
// As a special exception, if other files instantiate templates or use macros
// or inline functions from this file, or you compile this file and link it
// with other works to produce a work based on this file, this file does not
// by itself cause the resulting work to be covered by the GNU General Public
// License. However the source code for this file must still be made available
// in accordance with section (3) of the GNU General Public License.
//
// This exception does not invalidate any other reasons why a work based on
// this file might be covered by the GNU General Public License.
//
// Alternative licenses for VSCP & Friends may be arranged by contacting
// Grodans Paradis AB at info@grodansparadis.com, http://www.grodansparadis.com
///
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma implementation "vscp_bootdevice_vscp.h"
#endif
#ifdef WIN32
#include <winsock2.h>
#endif
#include "vscp_bootdevice_vscp.h"
#include "vscp_bootdevice_vscp_defs.h"
#include <stdio.h>
#define CRC16
#include <crc.h>
CBootDevice_vscp::CBootDevice_vscp(CDllWrapper *pdll,
uint8_t nodeid,
bool bDeviceFound)
: CBootDevice(pdll, nodeid, bDeviceFound)
{
init();
}
CBootDevice_vscp::CBootDevice_vscp(VscpRemoteTcpIf *ptcpip,
cguid &guid,
cguid &ifguid,
bool bDeviceFound)
: CBootDevice(ptcpip, guid, ifguid, bDeviceFound)
{
init();
}
CBootDevice_vscp::~CBootDevice_vscp(void)
{
;
}
///////////////////////////////////////////////////////////////////////////////
// init
//
void
CBootDevice_vscp::init(void)
{
// Create buffers
m_pbufPrg = new unsigned char[BUFFER_SIZE_PROGRAM_COMMON];
m_pAddr = 0;
crcInit();
}
///////////////////////////////////////////////////////////////////////////////
// loadBinaryFile
//
bool
CBootDevice_vscp::loadBinaryFile(const wxString &path, uint16_t type)
{
unsigned long i;
bool rv = false;
#ifdef WIN32
errno_t err;
#else
long err;
#endif
unsigned long fullAddr = 0;
unsigned long highAddr = 0;
unsigned long lowAddr = 0;
unsigned long cntData = 0;
unsigned long recType = 0;
FILE *fs = NULL;
// Init. program memory pointers
m_minFlashAddr = 0xffffffff;
m_maxFlashAddr = 0;
m_totalCntData = 0;
m_bPrgData = false;
m_bFlashMemory = true; // Program memory should be programmed
// Init program memory buffer
if (NULL == m_pbufPrg) return false;
memset(m_pbufPrg, 0xff, BUFFER_SIZE_PROGRAM_COMMON);
#ifdef WIN32
if (0 != (err = fopen_s(&fs, path.char_str(), "r"))) {
return false;
}
#else
if (NULL == (fs = fopen(path.char_str(), "r"))) {
return false;
}
#endif
char szLine[MAX_PATH];
char szData[16];
char *endptr;
bool bRun = true;
while ((true == bRun) && (NULL != fgets(szLine, MAX_PATH, fs))) {
if (':' == szLine[0]) {
// Get data count
memset(szData, 0, 16);
#ifdef WIN32
strncpy_s(szData, 16, (szLine + 1), 2);
#else
strncpy(szData, (szLine + 1), 2);
#endif
cntData = strtoul(szData, &endptr, 16);
m_totalCntData += cntData;
// Get address
memset(szData, 0, 16);
#ifdef WIN32
strncpy_s(szData, 16, (szLine + 3), 4);
#else
strncpy(szData, (szLine + 3), 4);
#endif
lowAddr = strtoul(szData, &endptr, 16);
// Get record type
memset(szData, 0, 16);
#ifdef WIN32
strncpy_s(szData, 16, (szLine + 7), 2);
#else
strncpy(szData, (szLine + 7), 2);
#endif
recType = strtoul(szData, &endptr, 16);
fullAddr = (highAddr * 0xffff) + lowAddr;
// Decode the record type
switch (recType) {
case INTEL_LINETYPE_DATA:
for (i = 0; i < cntData; i++) {
memset(szData, 0, 16);
#ifdef WIN32
strncpy_s(szData, 16, (szLine + ((i * 2) + 9)), 2);
#else
strncpy(szData, (szLine + ((i * 2) + 9)), 2);
#endif
unsigned char val =
(unsigned char)(strtoul(szData, &endptr, 16) & 0xff);
/* In program memory address space? */
if ((fullAddr >= MEMREG_PRG_START_COMMON) &&
(fullAddr <= MEMREG_PRG_END_COMMON)) {
/* Avoid program memory buffer overflow. */
if ((fullAddr - MEMREG_PRG_START_COMMON) <
BUFFER_SIZE_PROGRAM_COMMON) {
// Write into program memory buffer
m_pbufPrg[fullAddr - MEMREG_PRG_START_COMMON] =
val;
m_bPrgData = true;
// Set min flash address
if (fullAddr < m_minFlashAddr)
m_minFlashAddr = fullAddr;
// Set max flash address
if (fullAddr > m_maxFlashAddr)
m_maxFlashAddr = fullAddr;
}
}
++fullAddr;
}
break;
case INTEL_LINETYPE_EOF:
bRun = false; // We are done
rv = true;
break;
case INTEL_LINETYPE_EXTENDED_SEGMENT:
// We don't handle this
break;
case INTEL_LINETYPE_EXTENDED_LINEAR:
memset(szData, 0, 16);
#ifdef WIN32
strncpy_s(szData, 16, (szLine + 9), 4);
#else
strncpy(szData, (szLine + 9), 4);
#endif
highAddr = strtoul(szData, &endptr, 16);
break;
}
}
}
// Flash to program if none read
if (!m_bPrgData) {
m_bFlashMemory = false;
m_minFlashAddr = 0x00000000;
}
fclose(fs);
return rv;
}
///////////////////////////////////////////////////////////////////////////////
// showInfo
//
void
CBootDevice_vscp::showInfo(wxHtmlWindow *phtmlWnd)
{
wxString strInfo;
// Check pointer
if (NULL == phtmlWnd) return;
// Clear HTML
phtmlWnd->SetPage(_(""));
// * * * Flash Memory * * *
phtmlWnd->AppendToPage(_("<b><u>Flash Memory</u></b><br>"));
phtmlWnd->AppendToPage(_("<b>Start :</b><font color=\"#005CB9\">"));
strInfo.Printf(_("0x%08X"), m_minFlashAddr);
phtmlWnd->AppendToPage(strInfo);
phtmlWnd->AppendToPage(_("</font><b> End :</b><font color=\"#005CB9\">"));
strInfo.Printf(_("0x%08X</font><br>"), m_maxFlashAddr);
phtmlWnd->AppendToPage(strInfo);
if (m_bFlashMemory) {
phtmlWnd->AppendToPage(
_("<font color=\"#348017\">Will be programmed</font><br>"));
} else {
phtmlWnd->AppendToPage(
_("<font color=\"#F6358A\">Will not be programmed</font><br>"));
}
phtmlWnd->AppendToPage(_("<br><br>"));
}
///////////////////////////////////////////////////////////////////////////////
// setDeviceInBootMode
//
bool
CBootDevice_vscp::setDeviceInBootMode(void)
{
bool bRun;
uint8_t pageSelectMsb = 0;
uint8_t pageSelectLsb = 0;
uint8_t guid0 = 0;
uint8_t guid3 = 0;
uint8_t guid5 = 0;
uint8_t guid7 = 0;
uint16_t vscpclass;
uint8_t vscptype;
uint8_t priority = 0;
wxBusyCursor busy;
if (USE_DLL_INTERFACE == m_type) {
canalMsg msg, rcvmsg;
time_t tstart, tnow;
memset(msg.data, 0x00, 8);
// Read page register Page select MSB
if (CANAL_ERROR_SUCCESS !=
m_pdll->readLevel1Register(
m_nodeid, 0, VSCP_REG_PAGE_SELECT_MSB, &pageSelectMsb)) {
return false;
}
// Read page register page select lsb
if (CANAL_ERROR_SUCCESS !=
m_pdll->readLevel1Register(
m_nodeid, 0, VSCP_REG_PAGE_SELECT_LSB, &pageSelectLsb)) {
return false;
}
// Read page register GUID0
if (CANAL_ERROR_SUCCESS !=
m_pdll->readLevel1Register(m_nodeid, 0, VSCP_REG_GUID0, &guid0)) {
return false;
}
// Read page register GUID3
if (CANAL_ERROR_SUCCESS !=
m_pdll->readLevel1Register(m_nodeid, 0, VSCP_REG_GUID3, &guid3)) {
return false;
}
// Read page register GUID5
if (CANAL_ERROR_SUCCESS !=
m_pdll->readLevel1Register(m_nodeid, 0, VSCP_REG_GUID5, &guid5)) {
return false;
}
// Read page register GUID7
if (CANAL_ERROR_SUCCESS !=
m_pdll->readLevel1Register(m_nodeid, 0, VSCP_REG_GUID7, &guid7)) {
return false;
}
vscpclass = VSCP_CLASS1_PROTOCOL;
vscptype = VSCP_ENTER_BOOTLODER_MODE;
priority = VSCP_PRIORITY_LOW_COMMON;
// Set device in boot mode
msg.data[0] = m_nodeid; // Nickname to read register from
msg.data[1] =
VSCP_BOOTLOADER_VSCP; // VSCP standard bootloader algorithm
msg.data[2] = guid0;
msg.data[3] = guid3;
msg.data[4] = guid5;
msg.data[5] = guid7;
msg.data[6] = pageSelectMsb;
msg.data[7] = pageSelectLsb;
// Send message
msg.id = ((uint32_t)priority << 26) | ((uint32_t)vscpclass << 16) |
((uint32_t)vscptype << 8) |
m_nodeid; // nodeaddress (our address)
msg.flags = CANAL_IDFLAG_EXTENDED;
msg.sizeData = 8;
if (CANAL_ERROR_SUCCESS == m_pdll->doCmdSend(&msg)) {
bRun = true;
// Get start time
time(&tstart);
while (bRun) {
time(&tnow);
if ((unsigned long)(tnow - tstart) >
BOOT_COMMAND_RESPONSE_TIMEOUT) {
bRun = false;
}
if (m_pdll->doCmdDataAvailable()) {
m_pdll->doCmdReceive(&rcvmsg);
vscpclass = VSCP_CLASS1_PROTOCOL;
vscptype = VSCP_TYPE_PROTOCOL_ACK_BOOT_LOADER;
if ((uint32_t)(rcvmsg.id & 0x01ffffff) ==
(uint32_t)(((uint32_t)vscpclass << 16) |
((uint32_t)vscptype << 8) | m_nodeid)) {
// OK in bootmode - return
m_blockSize = ((uint32_t)rcvmsg.data[0] << 24) |
((uint32_t)rcvmsg.data[1] << 16) |
((uint32_t)rcvmsg.data[2] << 8) |
((uint32_t)rcvmsg.data[3] << 0);
m_numBlocks = ((uint32_t)rcvmsg.data[4] << 24) |
((uint32_t)rcvmsg.data[5] << 16) |
((uint32_t)rcvmsg.data[6] << 8) |
((uint32_t)rcvmsg.data[7] << 0);
return true;
}
}
}
}
} else if (USE_TCPIP_INTERFACE == m_type) {
vscpEventEx event;
time_t tstart, tnow;
// Read page register MSB
if (VSCP_ERROR_SUCCESS !=
m_ptcpip->readLevel2Register(
VSCP_REG_PAGE_SELECT_MSB, 0, &pageSelectMsb, m_ifguid, &m_guid)) {
return false;
}
// Read page register LSB
if (VSCP_ERROR_SUCCESS !=
m_ptcpip->readLevel2Register(
VSCP_REG_PAGE_SELECT_LSB, 0, &pageSelectLsb, m_ifguid, &m_guid)) {
return false;
}
// Read GUID0
if (VSCP_ERROR_SUCCESS !=
m_ptcpip->readLevel2Register(
VSCP_REG_GUID0, 0, &guid0, m_ifguid, &m_guid)) {
return false;
}
// Read GUID3
if (VSCP_ERROR_SUCCESS !=
m_ptcpip->readLevel2Register(
VSCP_REG_GUID3, 0, &guid3, m_ifguid, &m_guid)) {
return false;
}
// Read GUID5
if (VSCP_ERROR_SUCCESS !=
m_ptcpip->readLevel2Register(
VSCP_REG_GUID5, 0, &guid5, m_ifguid, &m_guid)) {
return false;
}
// Read GUID7
if (VSCP_ERROR_SUCCESS !=
m_ptcpip->readLevel2Register(
VSCP_REG_GUID7, 0, &guid7, m_ifguid, &m_guid)) {
return false;
}
// Set device in boot mode
// Send message
event.head = 0;
event.vscp_class = 512; // CLASS2.PROTOCOL1
event.vscp_type =
VSCP_ENTER_BOOTLODER_MODE; // We want to enter bootloader mode
memset(event.GUID, 0, 16); // We use interface GUID
event.sizeData = 16 + 8; // Interface GUID
memset(event.data, 0, sizeof(event.data));
memcpy(event.data, m_ifguid.m_id, 16); // Address node i/f
event.data[16] = m_guid.getLSB(); // Nickname for device
event.data[17] =
VSCP_BOOTLOADER_VSCP; // VSCP standard bootloader algorithm
event.data[18] = guid0;
event.data[19] = guid3;
event.data[20] = guid5;
event.data[21] = guid7;
event.data[22] = pageSelectMsb;
event.data[23] = pageSelectLsb;
if (VSCP_ERROR_SUCCESS == m_ptcpip->doCmdSendEx(&event)) {
bRun = true;
// Get start time
time(&tstart);
while (bRun) {
time(&tnow);
if ((unsigned long)(tnow - tstart) >
BOOT_COMMAND_RESPONSE_TIMEOUT) {
bRun = false;
}
// vscpEventEx rcvmsg;
if (m_ptcpip->doCmdDataAvailable()) {
m_ptcpip->doCmdReceiveEx(&event);
// Check for response --- Type = 13 (0x0D) ACK boot loader
// mode.
if (VSCP_TYPE_PROTOCOL_ACK_BOOT_LOADER == event.vscp_type) {
// OK in bootmode - return
m_blockSize = ((uint32_t)event.data[0] << 24) |
((uint32_t)event.data[1] << 16) |
((uint32_t)event.data[2] << 8) |
((uint32_t)event.data[3] << 0);
m_numBlocks = ((uint32_t)event.data[4] << 24) |
((uint32_t)event.data[5] << 16) |
((uint32_t)event.data[6] << 8) |
((uint32_t)event.data[7] << 0);
return true;
}
}
}
}
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// doFirmwareLoad
//
bool
CBootDevice_vscp::doFirmwareLoad(void)
{
bool bRun = true;
bool rv = true;
bool flag_crc = true;
wxBusyCursor busy;
m_checksum = 0;
uint32_t progress = 0;
uint32_t addr;
wxString wxStatusStr;
uint32_t nFlashPackets = 0;
// Packet size is always eight byte due to CAN frame limitation
// Flash memory
if (m_bPrgData) {
nFlashPackets = (m_maxFlashAddr - m_minFlashAddr) / 8;
if (0 != ((m_maxFlashAddr - m_minFlashAddr) % 8)) {
nFlashPackets++;
}
}
long nTotalPackets = nFlashPackets;
wxProgressDialog *pDlg =
new wxProgressDialog(_T("Boot loading in progress..."),
_T("---"),
nTotalPackets,
NULL,
wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_CAN_ABORT |
wxPD_ELAPSED_TIME | wxPD_REMAINING_TIME);
// Initialize checksum
addr = m_minFlashAddr;
// * * * flash memory * * *
if (rv && m_bPrgData) {
addr = m_minFlashAddr;
// nFlashPackets = number of 8 byte packets
m_blockNumber = 0;
for (uint32_t blk = 0; ((blk < nFlashPackets) && (true == bRun));
blk++) {
// Start block data transfer
if (0 == (blk % (m_blockSize / 8))) {
if (true != sendVSCPCommandStartBlock(blk * 8 / m_blockSize))
wxMessageBox(_T("start Block error"));
bRun = false;
}
wxStatusStr.Printf(_("Loading flash... %0X"), addr);
if (false == (bRun = pDlg->Update(progress, wxStatusStr))) {
wxMessageBox(_T("Aborted by user."));
rv = false;
bRun = false;
}
if (false == writeFirmwareSector()) {
wxMessageBox(_T("Failed to write flash data to node(s)."));
rv = false;
bRun = false;
}
/* After a complete block, wait for the block data acknowledge. */
if (0 == ((blk + 1) % (m_blockSize / 8))) {
if (USE_DLL_INTERFACE == m_type) {
flag_crc = sendVSCPCommandSeqenceLevel1();
} else if (USE_TCPIP_INTERFACE == m_type) {
flag_crc = sendVSCPCommandSeqenceLevel2();
}
m_blockNumber++;
}
wxMilliSleep(1);
progress++;
addr += 8;
}
}
/*
** All blocks loaded -- now reset the device
*/
if (!sendVSCPBootCommand(
VSCP_TYPE_PROTOCOL_ACTIVATE_NEW_IMAGE)) { // send as Zero as at --
// present AVR bode for
// microcontroller -- does
// not implement this
// method.
// Failure
wxMessageBox(_T(" ACTIVATE_NEW_IMAGE TX fails"));
} else {
}
// Done
progress = nTotalPackets;
pDlg->Update(progress, wxStatusStr);
pDlg->Destroy();
return rv;
}
///////////////////////////////////////////////////////////////////////////////
// writeFirmwareSector
//
bool
CBootDevice_vscp::writeFirmwareSector(void)
{
canalMsg msg;
vscpEventEx event;
bool rv = true;
uint16_t vscpclass = VSCP_CLASS1_PROTOCOL;
uint8_t vscptype = VSCP_TYPE_PROTOCOL_BLOCK_DATA;
uint8_t priority = VSCP_PRIORITY_LOW_COMMON;
// Send event
if (USE_DLL_INTERFACE == m_type) {
// Send message
msg.id = ((uint32_t)priority << 26) | ((uint32_t)vscpclass << 16) |
((uint32_t)vscptype << 8) |
m_nodeid; // nodeaddress (our address)
msg.flags = CANAL_IDFLAG_EXTENDED;
msg.sizeData = 8;
} else if (USE_TCPIP_INTERFACE == m_type) {
event.head = 0;
event.vscp_class = 512; // CLASS2.PROTOCOL1
event.vscp_type = vscptype;
memset(event.GUID, 0, 16); // We use interface GUID
event.sizeData = 16 + 8; // Interface GUID
memcpy(event.data, m_guid.m_id, 16); // Address node
} else {
return false;
}
uint8_t b;
for (int i = 0; i < 8; i++) {
b = m_pbufPrg[m_pAddr];
m_checksum += m_pbufPrg[m_pAddr];
// Write data into frame
if (USE_DLL_INTERFACE == m_type) {
msg.data[i] = b;
} else if (USE_TCPIP_INTERFACE == m_type) {
event.data[16 + i] = b;
} else {
return false;
}
// Update address
m_pAddr++;
}
if (USE_DLL_INTERFACE == m_type) {
m_pdll->doCmdSend(&msg);
} else if (USE_TCPIP_INTERFACE == m_type) {
m_ptcpip->doCmdSendEx(&event);
} else {
rv = false;
}
return rv;
}
///////////////////////////////////////////////////////////////////////////////
// sendVSCPCommandStartBlock
// PageAddress : Page to be programmed
// This command have no ACK
bool
CBootDevice_vscp::sendVSCPCommandStartBlock(uint16_t PageAddress)
{
uint16_t vscpclass = 0;
uint8_t vscptype = 0;
uint8_t priority = 0;
wxBusyCursor busy;
if (USE_DLL_INTERFACE == m_type) {
canalMsg msg;
memset(msg.data, 0x00, 8);
vscpclass = VSCP_CLASS1_PROTOCOL; // Class
vscptype = VSCP_TYPE_PROTOCOL_START_BLOCK; // Start block data transfer.
priority = VSCP_PRIORITY_LOW_COMMON;
// block data transfer
msg.data[0] = 0x00; // Block number MSB
msg.data[1] = 0x00; // Block number
msg.data[2] = (PageAddress & 0xFF00) >> 8; // Block number
msg.data[3] = (PageAddress & 0x00FF); // Block number LSB
// Send message
msg.id = ((uint32_t)priority << 26) | ((uint32_t)vscpclass << 16) |
((uint32_t)vscptype << 8) |
m_nodeid; // nodeaddress (our address)
msg.flags = CANAL_IDFLAG_EXTENDED;
msg.sizeData = 4;
if (CANAL_ERROR_SUCCESS == m_pdll->doCmdSend(&msg)) {
wxMilliSleep(1);
return true;
}
} else if (USE_TCPIP_INTERFACE == m_type) {
// Start block data transfer.
vscpEventEx event;
// Send message
event.head = 0;
event.vscp_class = 512; // CLASS2.PROTOCOL1
event.vscp_type =
VSCP_TYPE_PROTOCOL_START_BLOCK; // We want to Start block data
// transfer.
memset(event.GUID, 0, 16); // We use interface GUID
event.sizeData = 16 + 4; // Interface GUID
memcpy(event.data, m_guid.m_id, 16); // Address node
event.data[16] = 0x00; // Block number MSB
event.data[17] = 0x00; // Block number
event.data[18] = (PageAddress & 0xFF00) >> 8; // Block number
event.data[19] = (PageAddress & 0x00FF); // Block number LSB
if (CANAL_ERROR_SUCCESS == m_ptcpip->doCmdSendEx(&event)) {
wxMilliSleep(1);
return true;
}
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// sendVSCPBootCommand
// This routine is used to send command from nodes under boot.
// Index tells which Type & class to send.
//
bool
CBootDevice_vscp::sendVSCPBootCommand(uint8_t index)
{
uint16_t vscpclass;
uint8_t vscptype;
// uint8_t nodeid;
uint8_t priority = 0;
if (USE_DLL_INTERFACE == m_type) {
canalMsg msg; // rcvmsg;
// time_t tstart, tnow;
memset(msg.data, 0x00, 8);
if (index == VSCP_TYPE_PROTOCOL_ACTIVATE_NEW_IMAGE) {
uint16_t crc16 = crcFast(&m_pbufPrg[0], m_numBlocks * m_blockSize);
vscpclass = VSCP_CLASS1_PROTOCOL; // Class
vscptype = VSCP_TYPE_PROTOCOL_ACTIVATE_NEW_IMAGE;
priority = VSCP_PRIORITY_LOW_COMMON;
msg.data[0] = (uint8_t)(crc16 >> 8) & 0xff;
msg.data[1] = (uint8_t)(crc16 >> 0) & 0xff;
msg.sizeData = 2;
} else if (index == VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA) {
vscpclass = VSCP_CLASS1_PROTOCOL; // Class
vscptype = VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA;
priority = VSCP_PRIORITY_LOW_COMMON;
// block data transfer
msg.data[0] = ((uint8_t)(m_blockNumber >> 24)) & 0xFF;
msg.data[1] = ((uint8_t)(m_blockNumber >> 16)) & 0xFF;
msg.data[2] = ((uint8_t)(m_blockNumber >> 8)) & 0xFF;
msg.data[3] = ((uint8_t)(m_blockNumber >> 0)) & 0xFF;
msg.sizeData = 4;
} else {
return false;
}
// Send message
msg.id = ((uint32_t)priority << 26) | ((uint32_t)vscpclass << 16) |
((uint32_t)vscptype << 8) |
m_nodeid; // nodeaddress (our address)
msg.flags = CANAL_IDFLAG_EXTENDED;
if (CANAL_ERROR_SUCCESS == m_pdll->doCmdSend(&msg)) {
// bRun = true;
wxMilliSleep(1);
return true;
}
} else if (USE_TCPIP_INTERFACE == m_type) {
vscpEventEx event;
// Send message
if (index == VSCP_TYPE_PROTOCOL_ACTIVATE_NEW_IMAGE) {
uint16_t crc16 = crcFast(&m_pbufPrg[0], m_numBlocks * m_blockSize);
event.head = 0;
event.vscp_class = 512; // CLASS2.PROTOCOL1
event.vscp_type =
VSCP_TYPE_PROTOCOL_ACTIVATE_NEW_IMAGE; // Activate new Image
memset(event.GUID, 0, 16); // We use interface GUID
event.sizeData = 16 + 2; // Interface GUID
memcpy(event.data, m_guid.m_id, 16); // Address node
event.data[16] = (uint8_t)(crc16 >> 8) & 0xff;
event.data[17] = (uint8_t)(crc16 >> 0) & 0xff;
} else if (index == VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA) {
event.head = 0;
event.vscp_class = 512; // CLASS2.PROTOCOL1
event.vscp_type =
VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA; // Activate new Image
memset(event.GUID, 0, 16); // We use interface GUID
event.sizeData = 16 + 4; // Interface GUID
memcpy(event.data, m_guid.m_id, 16); // Address node
event.data[16] = ((uint8_t)(m_blockNumber >> 24)) & 0xFF;
event.data[17] = ((uint8_t)(m_blockNumber >> 16)) & 0xFF;
event.data[18] = ((uint8_t)(m_blockNumber >> 8)) & 0xFF;
event.data[19] = ((uint8_t)(m_blockNumber >> 0)) & 0xFF;
} else {
return false;
}
if (CANAL_ERROR_SUCCESS == m_ptcpip->doCmdSendEx(&event)) {
wxMilliSleep(1);
return true;
}
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// sendVSCPCommandSeqenceLevel1
// This routine is used to check ack & send command from nodes under boot.
// check response VSCP_TYPE_PROTOCOL_BLOCK_DATA_ACK --- Check CRC
// send VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA
// check response VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA_ACK
//
bool
CBootDevice_vscp::sendVSCPCommandSeqenceLevel1(void)
{
if (!checkResponseLevel1(VSCP_TYPE_PROTOCOL_BLOCK_DATA_ACK)) {
wxMessageBox(_T(" Response PROTOCOL_BLOCK_DATA_ACK fails"));
} else {
if (crc_16_host != crc_16_remote) {
m_pAddr -= m_blockSize;
return false;
}
}
wxMilliSleep(1);
/*
** Send command
*/
if (!sendVSCPBootCommand(VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA)) {
wxMessageBox(_T(" PROGRAM_BLOCK_DATA TX fails"));
} else {
}
wxMilliSleep(1);
if (!checkResponseLevel1(VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA_ACK)) {
wxMessageBox(_T(" Response PROGRAM_BLOCK_DATA_ACK fails"));
} else {
}
wxMilliSleep(1);
return true;
}
///////////////////////////////////////////////////////////////////////////////
// sendVSCPCommandSeqenceLevel2
// This routine is used to check ack & send command from nodes under boot.
// check response VSCP_TYPE_PROTOCOL_BLOCK_DATA_ACK
// send VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA
// check response VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA_ACK
//
bool
CBootDevice_vscp::sendVSCPCommandSeqenceLevel2(void)
{
// Check response
if (!checkResponseLevel2(VSCP_TYPE_PROTOCOL_BLOCK_DATA_ACK)) {
wxMessageBox(_T(" Response PROTOCOL_BLOCK_DATA_ACK fails"));
} else {
if (crc_16_host != crc_16_remote) {
m_pAddr -= m_blockSize;
return false;
}
}
wxMilliSleep(1);
/*
** Send command
*/
if (!sendVSCPBootCommand(VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA)) {
// Failure
wxMessageBox(_T(" PROGRAM_BLOCK_DATA TX fails"));
} else {
;
}
wxMilliSleep(1);
// Check response
if (!checkResponseLevel2(
VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA_ACK)) { // send as Zero as at --
// present AVR bode for
// microcontroller --
// does not implement
// this method.
// Failure
// rv = false;
// TODO Resend the block
wxMessageBox(_T(" Response PROGRAM_BLOCK_DATA_ACK fails"));
} else {
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// checkResponseLevel1
//
// Type = 20 (0x14) ACK program data block -- for 8 byte packet received
// correctly by AVR bootloader
//
bool
CBootDevice_vscp::checkResponseLevel1(uint8_t index)
{
// canalMsg msg;
// time_t tstart, tnow;
bool rv = false;
uint16_t vscpclass;
uint8_t vscptype;
uint8_t priority = 0;
canalMsg rcvmsg; // msg,
if (NULL == m_pdll) return false;
// Get system time
// time( &tstart );
bool bRun = true;
while (bRun) {
if (m_pdll->doCmdDataAvailable()) {
// if(m_type==0xff)
// wxMessageBox( _T("123456") );
m_pdll->doCmdReceive(&rcvmsg);
if ((int)(rcvmsg.id & 0xff) == m_nodeid) {
// Case -- index = 0 --- not implemented always return true
if (index == 0) {
// Response received from all - return success
rv = true;
bRun = false;
}
// Case -- index = 1
else if (index == VSCP_TYPE_PROTOCOL_BLOCK_DATA_ACK) {
vscpclass = VSCP_CLASS1_PROTOCOL;
vscptype = VSCP_TYPE_PROTOCOL_BLOCK_DATA_ACK;
if ((uint32_t)(rcvmsg.id & 0x01ffffff) ==
(uint32_t)(((uint32_t)vscpclass << 16) |
((uint32_t)vscptype << 8) | m_nodeid)) {
// Calculate CRC in host
crc_16_host = crcFast(&m_pbufPrg[m_pAddr - m_blockSize],
m_blockSize);
// GET CRC in remote node
crc_16_remote = (((uint16_t)rcvmsg.data[0]) << 8) |
(((uint16_t)rcvmsg.data[1]) << 0);
// Response received from all - return success
rv = true;
bRun = false;
}
} else if (index == VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA_ACK) {
vscpclass = VSCP_CLASS1_PROTOCOL;
vscptype = VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA_ACK;
if ((uint32_t)(rcvmsg.id & 0x01ffffff) ==
(uint32_t)(((uint32_t)vscpclass << 16) |
((uint32_t)vscptype << 8) | m_nodeid)) {
// Response received from all - return success
rv = true;
bRun = false;
}
}
} // id found
} // received message
}
return rv;
}
///////////////////////////////////////////////////////////////////////////////
// checkResponseLevel2
// Type = 20 (0x14) ACK program data block --
// for 8 byte packet received correctly by bootloader
//
bool
CBootDevice_vscp::checkResponseLevel2(uint8_t index)
{
vscpEventEx event;
// time_t tstart, tnow;
bool rv = false;
if (NULL == m_ptcpip) return false;
bool bRun = true;
while (bRun) {
if (m_ptcpip->doCmdDataAvailable()) {
m_ptcpip->doCmdReceiveEx(&event);
if ((VSCP_CLASS1_PROTOCOL == event.vscp_class) &&
(m_guid.getLSB() == event.GUID[15])) { // correct id
// Case -- index = 0 --- not implemented always return true
if (index == 0) {
// Response received from all - return success
rv = true;
bRun = false;
}
// Case -- index = VSCP_TYPE_PROTOCOL_BLOCK_DATA_ACK
else if (index == VSCP_TYPE_PROTOCOL_BLOCK_DATA_ACK) {
if (event.vscp_type == VSCP_TYPE_PROTOCOL_BLOCK_DATA_ACK) {
// Calculate CRC in host
crc_16_host = crcFast(&m_pbufPrg[m_pAddr - m_blockSize],
m_blockSize);
// GET CRC in remote node
crc_16_remote = (((uint16_t)event.data[0]) << 8) |
(((uint16_t)event.data[1]) << 0);
// Response received from all - return success
rv = true;
bRun = false;
}
}
// Case -- index = VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA_ACK
else if (index == VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA_ACK) {
if (event.vscp_type ==
VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA_ACK) {
// Response received from all - return success
rv = true;
bRun = false;
}
}
} // id
} // received message
}
return rv;
}
| 35,226 | 11,958 |
#ifndef BIT_STL_UTILITIES_DETAIL_VARIANT_INL
#define BIT_STL_UTILITIES_DETAIL_VARIANT_INL
//----------------------------------------------------------------------------
// Constructors / Assignment
//----------------------------------------------------------------------------
template<typename...Types>
inline constexpr bit::stl::variant<Types...>
::variant( enable_overload_if_t<is_default_constructible,variant_ctor> )
noexcept(std::is_nothrow_default_constructible<T0>::value)
: base_type( in_place_index<0> )
{
}
template<typename...Types>
inline bit::stl::variant<Types...>
::variant( enable_overload_if_t<is_copy_constructible,const variant&> other )
noexcept( bit::stl::conjunction<std::is_nothrow_copy_constructible<Types>...>::value )
{
runtime_emplace( other.index(), other.m_union );
}
template<typename...Types>
inline bit::stl::variant<Types...>
::variant( enable_overload_if_t<is_move_constructible,variant&&> other )
noexcept( bit::stl::conjunction<std::is_nothrow_move_constructible<Types>...>::value )
{
runtime_emplace( other.index(), std::move(other.m_union) );
}
template<typename...Types>
template<typename T, typename>
inline constexpr bit::stl::variant<Types...>::variant( T&& t )
noexcept( std::is_nothrow_constructible<typename bit::stl::variant<Types...>::template T_j<T>,T>::value )
: base_type( in_place_index<detail::conversion_index_v<T,variant>>, std::forward<T>(t) )
{
}
template<typename...Types>
template<typename T, typename...Args, typename>
inline constexpr bit::stl::variant<Types...>
::variant( in_place_type_t<T>, Args&&... args )
: base_type( in_place_index<detail::index_from<T,Types...>::value>, std::forward<Args>(args)... )
{
}
template<typename...Types>
template<typename T, typename U, typename...Args, typename>
inline constexpr bit::stl::variant<Types...>
::variant( in_place_type_t<T>, std::initializer_list<U> il, Args&&... args )
: base_type( in_place_index<detail::index_from<T,Types...>::value>, il, std::forward<Args>(args)... )
{
}
template<typename...Types>
template<std::size_t I, typename...Args, typename>
inline constexpr bit::stl::variant<Types...>
::variant( in_place_index_t<I>, Args&&...args )
: base_type( in_place_index<I>, std::forward<Args>(args)... )
{
}
template<typename...Types>
template<std::size_t I, typename U, typename... Args, typename>
inline constexpr bit::stl::variant<Types...>
::variant( in_place_index_t<I>, std::initializer_list<U> il, Args&&...args )
: base_type( in_place_index<I>, il, std::forward<Args>(args)... )
{
}
//----------------------------------------------------------------------------
template<typename...Types>
inline bit::stl::variant<Types...>&
bit::stl::variant<Types...>::operator=( enable_overload_if_t<is_copy_assignable,const variant&> other )
{
if( other.valueless_by_exception() ) {
base_type::destruct();
} else if( index() == other.index() ) {
runtime_assign( other.index(),other.m_union );
} else {
this->operator=(variant(other));
}
return (*this);
}
//----------------------------------------------------------------------------
template<typename...Types>
inline bit::stl::variant<Types...>&
bit::stl::variant<Types...>::operator=( enable_overload_if_t<is_move_assignable,variant&&> other )
noexcept( bit::stl::conjunction<std::is_nothrow_move_constructible<Types>...,
std::is_nothrow_move_assignable<Types>...>::value)
{
if( other.valueless_by_exception() ) {
base_type::destruct();
} else if( index() == other.index() ) {
runtime_assign( other.index(), std::move(other.m_union) );
} else {
runtime_emplace( other.index(), std::move(other.m_union) );
}
return (*this);
}
//----------------------------------------------------------------------------
template<typename...Types>
template<typename T, typename>
inline bit::stl::variant<Types...>&
bit::stl::variant<Types...>::operator=(T&& t)
noexcept( std::is_nothrow_assignable<typename bit::stl::variant<Types...>::template T_j<T>,T>::value &&
std::is_nothrow_constructible<typename bit::stl::variant<Types...>::template T_j<T>,T>::value )
{
static constexpr auto index = detail::conversion_index<T,variant>::value;
using T_j = variant_alternative_t<index,variant>;
if( index == this->index() ) {
static_assign<index>( std::forward<T>(t) );
} else if (std::is_nothrow_constructible<T_j, T>::value ||
!std::is_nothrow_move_constructible<T_j>::value ) {
emplace<index>( std::forward<T>(t) );
} else {
this->operator=(variant(std::forward<T>(t)));
}
return (*this);
}
//----------------------------------------------------------------------------
// Observers
//----------------------------------------------------------------------------
template<typename...Types>
inline constexpr std::size_t bit::stl::variant<Types...>::index()
const noexcept
{
return base_type::m_index;
}
template<typename...Types>
inline constexpr bool bit::stl::variant<Types...>::valueless_by_exception()
const noexcept
{
return base_type::m_index == variant_npos;
}
//----------------------------------------------------------------------------
// Modifiers
//----------------------------------------------------------------------------
template<typename...Types>
template<typename T, typename...Args, typename>
inline T& bit::stl::variant<Types...>::emplace( Args&&...args )
{
using index = detail::index_from<T,Types...>;
return emplace<index::value>( std::forward<Args>(args)... );
}
template<typename...Types>
template<typename T, typename U, typename...Args, typename>
inline T& bit::stl::variant<Types...>::emplace( std::initializer_list<U> il,
Args&&...args )
{
using index = detail::index_from<T,Types...>;
return emplace<index::value>( il, std::forward<Args>(args)... );
}
template<typename...Types>
template<std::size_t I, typename... Args, typename>
inline bit::stl::variant_alternative_t<I, bit::stl::variant<Types...>>&
bit::stl::variant<Types...>::emplace( Args&&... args )
{
static_assert(I<sizeof...(Types), "");
base_type::destruct();
auto& result = static_emplace<I>( in_place_index<I>, base_type::m_union, std::forward<Args>(args)... );
base_type::m_index = I;
return result;
}
template<typename...Types>
template<std::size_t I, typename U, typename... Args, typename>
inline bit::stl::variant_alternative_t<I, bit::stl::variant<Types...>>&
bit::stl::variant<Types...>::emplace( std::initializer_list<U> il,
Args&&... args )
{
static_assert(I<sizeof...(Types), "");
base_type::destruct();
auto& result = static_emplace<I>( in_place_index<I>, base_type::m_union, il, std::forward<Args>(args)... );
base_type::m_index = I;
return result;
}
template<typename...Types>
inline void bit::stl::variant<Types...>::swap( variant& rhs )
{
// Do nothing if both types are valueless by exception
if( valueless_by_exception() && rhs.valueless_by_exception() ) {
return;
}
// If indices match, call swap
if( index() == rhs.index() ) {
base_type::swap( static_cast<base_type&>(rhs) );
} else {
variant tmp = std::move(*this);
*this = std::move(rhs);
rhs = std::move(tmp);
}
}
template<typename...Types>
template<std::size_t I>
inline constexpr bit::stl::variant_alternative_t<I,bit::stl::variant<Types...>>&
bit::stl::variant<Types...>::get( in_place_index_t<I> )
noexcept
{
return base_type::get( in_place_index<I> );
}
template<typename...Types>
template<std::size_t I>
inline constexpr const bit::stl::variant_alternative_t<I,bit::stl::variant<Types...>>&
bit::stl::variant<Types...>::get( in_place_index_t<I> )
const noexcept
{
return base_type::get( in_place_index<I> );
}
//----------------------------------------------------------------------------
// Private Member Functions
//----------------------------------------------------------------------------
template<typename...Types>
template<typename VariantUnion>
inline void bit::stl::variant<Types...>
::runtime_assign( std::size_t index,
VariantUnion&& source )
{
runtime_assign_impl( index, base_type::m_union, std::forward<VariantUnion>(source) );
}
template<typename...Types>
template<typename VariantUnion>
inline void bit::stl::variant<Types...>
::runtime_assign_impl( std::size_t current,
VariantUnion& dest,
VariantUnion&& source,
std::enable_if_t<detail::variant_union_has_next<std::decay_t<VariantUnion>>::value>* )
{
if( current == 0 ) {
dest.current = std::move(source.current);
return;
}
runtime_assign_impl( current-1, dest.next, std::move(source.next) );
}
template<typename...Types>
template<typename VariantUnion>
inline void bit::stl::variant<Types...>
::runtime_assign_impl( std::size_t current,
VariantUnion& dest,
VariantUnion&& source,
std::enable_if_t<!detail::variant_union_has_next<std::decay_t<VariantUnion>>::value>* )
{
dest.current = std::move(source.current);
}
template<typename...Types>
template<typename VariantUnion>
inline void bit::stl::variant<Types...>
::runtime_assign_impl( std::size_t current,
VariantUnion& dest,
const VariantUnion& source,
std::enable_if_t<detail::variant_union_has_next<std::decay_t<VariantUnion>>::value>* )
{
if( current == 0 ) {
dest.current = source.current;
return;
}
runtime_assign_impl( current-1, dest.next, source.next );
}
template<typename...Types>
template<typename VariantUnion>
inline void bit::stl::variant<Types...>
::runtime_assign_impl( std::size_t current,
VariantUnion& dest,
const VariantUnion& source,
std::enable_if_t<!detail::variant_union_has_next<std::decay_t<VariantUnion>>::value>* )
{
dest.current = source.current;
}
//----------------------------------------------------------------------------
template<typename...Types>
template<std::size_t I, typename T>
inline void bit::stl::variant<Types...>::static_assign( T&& value )
{
static_assign( in_place_index<I>, base_type::m_union, std::forward<T>(value) );
}
template<typename...Types>
template<typename VariantUnion, typename T>
inline void bit::stl::variant<Types...>
::static_assign( in_place_index_t<std::size_t(-1)>, VariantUnion&, T&& )
{
// avoid instantiation issues
}
template<typename...Types>
template<std::size_t I, typename VariantUnion, typename T>
inline void bit::stl::variant<Types...>
::static_assign( in_place_index_t<I>, VariantUnion& dest, T&& value )
{
static_assign( in_place_index<I-1>, dest.next, std::forward<T>(value) );
}
template<typename...Types>
template<typename VariantUnion, typename T>
inline void bit::stl::variant<Types...>
::static_assign( in_place_index_t<0>, VariantUnion& dest, T&& value )
{
dest.current = std::forward<T>(value);
}
//----------------------------------------------------------------------------
template<typename...Types>
template<typename VariantUnion>
inline void bit::stl::variant<Types...>
::runtime_emplace( std::size_t index, VariantUnion&& source )
{
base_type::destruct();
runtime_emplace_impl( index, base_type::m_union, std::forward<VariantUnion>(source) );
base_type::m_index = index;
}
template<typename...Types>
template<typename VariantUnion>
inline void bit::stl::variant<Types...>
::runtime_emplace_impl( std::size_t current,
VariantUnion& dest,
VariantUnion&& source,
std::enable_if_t<detail::variant_union_has_next<std::decay_t<VariantUnion>>::value>* )
{
using type = decltype(dest.current);
if( current == 0 ) {
new (&dest.current) type( std::move(source.current) );
return;
}
runtime_emplace_impl( current-1, dest.next, std::move(source.next) );
}
template<typename...Types>
template<typename VariantUnion>
inline void bit::stl::variant<Types...>
::runtime_emplace_impl( std::size_t current,
VariantUnion& dest,
VariantUnion&& source,
std::enable_if_t<!detail::variant_union_has_next<std::decay_t<VariantUnion>>::value>* )
{
using type = decltype(dest.current);
new (&dest.current) type( std::move(source.current) );
}
template<typename...Types>
template<typename VariantUnion>
inline void bit::stl::variant<Types...>
::runtime_emplace_impl( std::size_t current,
VariantUnion& dest,
const VariantUnion& source,
std::enable_if_t<detail::variant_union_has_next<std::decay_t<VariantUnion>>::value>* )
{
using type = decltype(dest.current);
if( current == 0 ) {
new (&dest.current) type( source.current );
return;
}
runtime_emplace_impl( current-1, dest.next, source.next );
}
template<typename...Types>
template<typename VariantUnion>
inline void bit::stl::variant<Types...>
::runtime_emplace_impl( std::size_t current,
VariantUnion& dest,
const VariantUnion& source,
std::enable_if_t<!detail::variant_union_has_next<std::decay_t<VariantUnion>>::value>* )
{
using type = decltype(dest.current);
new (&dest.current) type( source.current );
}
//----------------------------------------------------------------------------
template<typename...Types>
template<std::size_t I, std::size_t N, typename...Ts, typename...Args,typename>
inline bit::stl::variant_alternative_t<I, bit::stl::variant<Types...>>&
bit::stl::variant<Types...>::static_emplace( in_place_index_t<N>,
union_type<Ts...>& storage,
Args&&...args )
{
return static_emplace<I>( in_place_index<N-1>,
storage.next, std::forward<Args>(args)... );
}
template<typename...Types>
template<std::size_t I, typename...Ts, typename...Args>
inline bit::stl::variant_alternative_t<I, bit::stl::variant<Types...>>&
bit::stl::variant<Types...>::static_emplace( in_place_index_t<0>,
union_type<Ts...>& storage,
Args&&...args )
{
using type = variant_alternative_t<I, variant>;
new (&storage.current) type( std::forward<Args>(args)... );
return storage.current;
}
//-----------------------------------------------------------------------------
// Comparisons
//-----------------------------------------------------------------------------
namespace bit { namespace stl { namespace detail {
template<std::size_t N, typename...Types, typename Compare>
inline constexpr bool variant_compare( in_place_index_t<N>,
const variant<Types...>& lhs,
const variant<Types...>& rhs,
Compare&& compare )
noexcept
{
if( N == lhs.index() ) {
return std::forward<Compare>(compare)( get<N>(lhs), get<N>(rhs) );
}
return variant_compare( in_place_index<(N-1)>, lhs, rhs, std::forward<Compare>(compare) );
}
template<typename...Types, typename Compare>
inline constexpr bool variant_compare( in_place_index_t<0>,
const variant<Types...>& lhs,
const variant<Types...>& rhs,
Compare&& compare )
noexcept
{
return std::forward<Compare>(compare)( get<0>(lhs), get<0>(rhs) );
}
} } } // namespace bit::stl::detail
template<typename...Types>
inline constexpr bool bit::stl::operator==( const variant<Types...>& lhs,
const variant<Types...>& rhs )
noexcept
{
if( lhs.index() != rhs.index() ) return false;
if( lhs.valueless_by_exception() ) return true;
auto tag = in_place_index<(sizeof...(Types)-1)>;
return detail::variant_compare( tag, lhs, rhs, std::equal_to<>{});
}
template<typename...Types>
inline constexpr bool bit::stl::operator!=( const variant<Types...>& lhs,
const variant<Types...>& rhs )
noexcept
{
if( lhs.index() != rhs.index() ) return true;
if( lhs.valueless_by_exception() ) return false;
auto tag = in_place_index<(sizeof...(Types)-1)>;
return detail::variant_compare( tag, lhs, rhs, std::not_equal_to<>{});
}
template<typename...Types>
inline constexpr bool bit::stl::operator<( const variant<Types...>& lhs,
const variant<Types...>& rhs )
noexcept
{
if( rhs.valueless_by_exception() ) return false;
if( lhs.valueless_by_exception() ) return true;
if( lhs.index() < rhs.index() ) return true;
if( lhs.index() > rhs.index() ) return false;
auto tag = in_place_index<(sizeof...(Types)-1)>;
return detail::variant_compare( tag, lhs, rhs, std::less<>{});
}
template<typename...Types>
inline constexpr bool bit::stl::operator>( const variant<Types...>& lhs,
const variant<Types...>& rhs )
noexcept
{
if( lhs.valueless_by_exception() ) return false;
if( rhs.valueless_by_exception() ) return true;
if( lhs.index() > rhs.index() ) return true;
if( lhs.index() < rhs.index() ) return false;
auto tag = in_place_index<(sizeof...(Types)-1)>;
return detail::variant_compare( tag, lhs, rhs, std::greater<>{});
}
template<typename...Types>
inline constexpr bool bit::stl::operator<=( const variant<Types...>& lhs,
const variant<Types...>& rhs )
noexcept
{
if( lhs.valueless_by_exception() ) return true;
if( rhs.valueless_by_exception() ) return false;
if( lhs.index() < rhs.index() ) return true;
if( lhs.index() > rhs.index() ) return false;
auto tag = in_place_index<(sizeof...(Types)-1)>;
return detail::variant_compare( tag, lhs, rhs, std::less_equal<>{});
}
template<typename...Types>
inline constexpr bool bit::stl::operator>=( const variant<Types...>& lhs,
const variant<Types...>& rhs )
noexcept
{
if( rhs.valueless_by_exception() ) return true;
if( lhs.valueless_by_exception() ) return false;
if( lhs.index() > rhs.index() ) return true;
if( lhs.index() < rhs.index() ) return false;
auto tag = in_place_index<(sizeof...(Types)-1)>;
return detail::variant_compare( tag, lhs, rhs, std::greater_equal<>{});
}
//=============================================================================
// 23.7.5 : value access
//=============================================================================
template<typename T, typename...Types>
constexpr bool bit::stl::holds_alternative( const variant<Types...>& v )
noexcept
{
return detail::index_from<T,Types...>::value == v.index();
}
//----------------------------------------------------------------------------
template<std::size_t I, typename...Types>
constexpr bit::stl::variant_alternative_t<I, bit::stl::variant<Types...>>&
bit::stl::get( variant<Types...>& v )
{
static_assert( (I < sizeof...(Types)), "I is not a valid index into the variant" );
if( v.index() != I ) throw bad_variant_access{};
return v.get( in_place_index<I> );
}
template<std::size_t I, typename...Types>
constexpr bit::stl::variant_alternative_t<I, bit::stl::variant<Types...>>&&
bit::stl::get( variant<Types...>&& v )
{
static_assert( (I < sizeof...(Types)), "I is not a valid index into the variant" );
return std::move( get<I>( v ) );
}
template<std::size_t I, typename...Types>
constexpr const bit::stl::variant_alternative_t<I, bit::stl::variant<Types...>>&
bit::stl::get( const variant<Types...>& v )
{
static_assert( (I < sizeof...(Types)), "I is not a valid index into the variant" );
if( v.index() != I ) throw bad_variant_access{};
return v.get( in_place_index<I> );
}
template<std::size_t I, typename...Types>
constexpr const bit::stl::variant_alternative_t<I, bit::stl::variant<Types...>>&&
bit::stl::get( const variant<Types...>&& v )
{
static_assert( (I < sizeof...(Types)), "I is not a valid index into the variant" );
return std::move( get<I>( v ) );
}
//----------------------------------------------------------------------------
template<typename T, typename...Types>
constexpr T& bit::stl::get( variant<Types...>& v )
{
return get<detail::index_from<T,Types...>::value>(v);
}
template<typename T, typename...Types>
constexpr T&& bit::stl::get( variant<Types...>&& v )
{
return get<detail::index_from<T,Types...>::value>(v);
}
template<typename T, typename...Types>
constexpr const T& bit::stl::get( const variant<Types...>& v )
{
return get<detail::index_from<T,Types...>::value>(v);
}
template<typename T, typename...Types>
constexpr const T&& bit::stl::get( const variant<Types...>&& v )
{
return get<detail::index_from<T,Types...>::value>(v);
}
//----------------------------------------------------------------------------
template<std::size_t I, typename...Types>
constexpr std::add_pointer_t<bit::stl::variant_alternative_t<I, bit::stl::variant<Types...>>>
bit::stl::get_if( variant<Types...>* pv )
noexcept
{
static_assert( (I < sizeof...(Types)), "I is not a valid index into the variant" );
if( !pv ) return nullptr;
if( I != pv->index() ) return nullptr;
return &get<I>(*pv);
}
template<std::size_t I, typename...Types>
constexpr std::add_pointer_t<const bit::stl::variant_alternative_t<I, bit::stl::variant<Types...>>>
bit::stl::get_if( const variant<Types...>* pv )
noexcept
{
static_assert( (I < sizeof...(Types)), "I is not a valid index into the variant" );
if( !pv ) return nullptr;
if( I != pv->index() ) return nullptr;
return &get<I>(*pv);
}
template<typename T, typename...Types>
constexpr std::add_pointer_t<T> bit::stl::get_if( variant<Types...>* pv )
noexcept
{
return get_if<detail::index_from<T,Types...>::value>( pv );
}
template<typename T, typename...Types>
constexpr std::add_pointer_t<const T> bit::stl::get_if( const variant<Types...>* pv )
noexcept
{
return get_if<detail::index_from<T,Types...>::value>( pv );
}
//-----------------------------------------------------------------------------
namespace bit { namespace stl { namespace detail {
template<std::size_t N, typename...Types>
inline constexpr hash_t hash_variant_impl( in_place_index_t<N>,
const variant<Types...>& val )
{
if( val.index() == N ) {
return hash_value( get<N>( val ) );
}
return hash_variant_impl( in_place_index<(N-1)>, val );
}
template<typename...Types>
inline constexpr hash_t hash_variant_impl( in_place_index_t<0>,
const variant<Types...>& val )
{
// Must be 0 by here; what else can it be?
assert( val.index() == 0 );
return hash_value( get<0>( val ) );
}
} } } // namespace bit::stl::detail
template<typename...Types>
inline constexpr bit::stl::hash_t bit::stl::hash_value( const variant<Types...>& val )
noexcept
{
if( val.valueless_by_exception() ) return static_cast<hash_t>(0xDEADBEEF);
// hash from last value to first value
return detail::hash_variant_impl( in_place_index<(sizeof...(Types)-1)>, val );
}
#endif /* BIT_STL_UTILITIES_DETAIL_VARIANT_INL */
| 23,571 | 7,547 |
#include "lab2/vector.h"
#include <cmath>
#include <iterator>
#include <utility>
using namespace lab2;
Vector::Vector(std::istream& is) {
double el;
while (is >> el) {
data.push_back(el);
}
if (size() == 0) {
throw "Vector is empty";
}
}
Vector::Vector(const std::vector<double>& data_) : data(data_) {
if (size() == 0) {
throw "Vector is empty";
}
}
Vector::Vector(std::size_t size,
const std::function<double(std::size_t)>& generator) {
data.reserve(size);
for (std::size_t i = 0; i < size; i++) {
data.push_back(generator(i));
}
}
std::size_t Vector::size() const { return data.size(); }
double Vector::operator[](std::size_t idx) const { return data[idx]; }
double Vector::norm() const { return std::sqrt((*this) * (*this)); }
Vector Vector::operator+(Vector other) const {
if (size() != other.size()) {
throw "Size mismatch";
}
return Vector(size(), [this, &other](std::size_t i) {
return (*this)[i] + other[i];
});
}
Vector Vector::operator-(Vector other) const {
if (size() != other.size()) {
throw "Size mismatch";
}
return Vector(size(), [this, &other](std::size_t i) {
return (*this)[i] - other[i];
});
}
Vector Vector::operator*(double val) const {
std::vector<double> tmp;
return Vector(size(), [this, val](std::size_t i) {
return (*this)[i] * val;
});
}
double Vector::operator*(const Vector& other) const {
if (size() != other.size()) {
throw "Size mismatch";
}
double res = 0;
for (std::size_t i = 0; i < size(); i++) {
res += (*this)[i] * other[i];
}
return res;
}
bool Vector::operator==(const Vector& other) const {
return data == other.data;
}
namespace lab2 {
std::ostream& operator<<(std::ostream& os, const Vector& v) {
for (std::size_t i = 0; i < v.size(); i++) {
os << v[i];
if (i != v.size() - 1) {
os << " ";
}
}
return os;
}
} // namespace lab2
| 2,086 | 712 |
// Copyright 2021 Research Institute of Systems Planning, 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 <unordered_map>
#include <memory>
#include <utility>
#include "specialized_intra_process_comm/intra_process_manager.hpp"
namespace feature
{
Counter::Counter()
: count_(0)
{
}
uint64_t Counter::get_incremented_count()
{
std::lock_guard<std::mutex> lock(mutex_);
count_++;
return count_;
}
static std::atomic<uint64_t> _next_unique_id{1};
IntraProcessManager::~IntraProcessManager() {}
uint64_t IntraProcessManager::add_publisher(PublisherBase::SharedPtr publisher)
{
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
auto id = IntraProcessManager::get_next_unique_id();
publishers_[id].publisher = publisher;
publishers_[id].topic_name = publisher->get_topic_name();
publishers_[id].qos = publisher->get_actual_qos().get_rmw_qos_profile();
// Initialize the subscriptions storage for this publisher.
pub_to_subs_[id] = SplittedSubscriptions();
auto topic_name = publishers_[id].topic_name;
auto has_key = sequences_.find(topic_name) != sequences_.end();
if (!has_key) {
sequences_[topic_name] = std::make_shared<feature::Counter>();
}
// create an entry for the publisher id and populate with already existing
// subscriptions
for (auto & pair : subscriptions_) {
if (can_communicate(publishers_[id], pair.second)) {
insert_sub_id_for_pub(pair.first, id, pair.second.use_take_shared_method);
}
}
return id;
}
void IntraProcessManager::insert_sub_id_for_pub(
uint64_t sub_id, uint64_t pub_id, bool use_take_shared_method)
{
if (use_take_shared_method) {
pub_to_subs_[pub_id].take_shared_subscriptions.push_back(sub_id);
} else {
pub_to_subs_[pub_id].take_ownership_subscriptions.push_back(sub_id);
}
}
uint64_t IntraProcessManager::add_subscription(SubscriptionBase::SharedPtr subscription)
{
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
auto id = IntraProcessManager::get_next_unique_id();
subscriptions_[id].subscription = subscription;
subscriptions_[id].topic_name = subscription->get_topic_name();
subscriptions_[id].qos = subscription->get_actual_qos().get_rmw_qos_profile();
subscriptions_[id].use_take_shared_method = subscription->use_take_shared_method();
// adds the subscription id to all the matchable publishers
for (auto & pair : publishers_) {
if (can_communicate(pair.second, subscriptions_[id])) {
insert_sub_id_for_pub(id, pair.first, subscriptions_[id].use_take_shared_method);
}
}
return id;
}
void IntraProcessManager::remove_subscription(uint64_t intra_process_subscription_id)
{
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
subscriptions_.erase(intra_process_subscription_id);
for (auto & pair : pub_to_subs_) {
pair.second.take_shared_subscriptions.erase(
std::remove(
pair.second.take_shared_subscriptions.begin(), pair.second.take_shared_subscriptions.end(),
intra_process_subscription_id),
pair.second.take_shared_subscriptions.end());
pair.second.take_ownership_subscriptions.erase(
std::remove(
pair.second.take_ownership_subscriptions.begin(),
pair.second.take_ownership_subscriptions.end(), intra_process_subscription_id),
pair.second.take_ownership_subscriptions.end());
}
}
void IntraProcessManager::remove_publisher(uint64_t intra_process_publisher_id)
{
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
publishers_.erase(intra_process_publisher_id);
pub_to_subs_.erase(intra_process_publisher_id);
}
uint64_t IntraProcessManager::get_next_unique_id()
{
auto next_id = _next_unique_id.fetch_add(1, std::memory_order_relaxed);
// Check for rollover (we started at 1).
if (0 == next_id) {
// This puts a technical limit on the number of times you can add a publisher or subscriber.
// But even if you could add (and remove) them at 1 kHz (very optimistic rate)
// it would still be a very long time before you could exhaust the pool of id's:
// 2^64 / 1000 times per sec / 60 sec / 60 min / 24 hours / 365 days = 584,942,417 years
// So around 585 million years. Even at 1 GHz, it would take 585 years.
// I think it's safe to avoid trying to handle overflow.
// If we roll over then it's most likely a bug.
// *INDENT-OFF* (prevent uncrustify from making unnecessary indents here)
throw std::overflow_error(
"exhausted the unique id's for publishers and subscribers in this process "
"(congratulations your computer is either extremely fast or extremely old)");
// *INDENT-ON*
}
return next_id;
}
bool IntraProcessManager::can_communicate(PublisherInfo pub_info, SubscriptionInfo sub_info) const
{
// publisher and subscription must be on the same topic
if (strcmp(pub_info.topic_name, sub_info.topic_name) != 0) {
return false;
}
// TODO(alsora): the following checks for qos compatibility should be provided
// by the RMW a reliable subscription can't be connected with a best effort
// publisher
if (
sub_info.qos.reliability == RMW_QOS_POLICY_RELIABILITY_RELIABLE &&
pub_info.qos.reliability == RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT)
{
return false;
}
// a publisher and a subscription with different durability can't communicate
if (sub_info.qos.durability != pub_info.qos.durability) {
return false;
}
return true;
}
} // namespace feature
| 5,970 | 2,040 |
#include "console.h"
#include "fan.h"
#include "handtiles.h"
#include "print.h"
#include <iostream>
#include <vector>
int main() {
// 构造手牌
mahjong::Handtiles ht;
ht.StringToHandtiles("[456s,1][456s,1][456s,3]45s55m |EE0000|fah");
// 计算听牌
mahjong::Fan fan;
std::vector<mahjong::Tile> ting = fan.CalcTing(ht);
for (auto t : ting) {
mahjong::StdPrintTile(t);
}
std::cout << std::endl;
// 判断是否铳和
ht.SetTile(mahjong::Tile(TILE_8s));
printf("%s 是否和牌:%d\n", ht.HandtilesToString().c_str(), fan.JudgeHu(ht));
// 摸牌并算番
ht.DiscardTile(); // 出牌
ht.DrawTile(mahjong::Tile(TILE_6s)); // 摸牌
printf("手牌:%s\n", ht.HandtilesToString().c_str()); // 输出手牌
fan.CountFan(ht); // 计番
printf("总番数:%d\n", fan.tot_fan_res); // 总番数
for (int i = 1; i < mahjong::FAN_SIZE; i++) { // 输出所有的番
for (size_t j = 0; j < fan.fan_table_res[i].size(); j++) {
printf("%s %d番", mahjong::FAN_NAME[i], mahjong::FAN_SCORE[i]);
std::string pack_string;
for (auto pid : fan.fan_table_res[i][j]) { // 获取该番种具体的组合方式
pack_string += " " + mahjong::PackToEmojiString(fan.fan_packs_res[pid]);
}
printf("%s\n", pack_string.c_str());
}
}
return 0;
}
| 1,283 | 636 |
// generated from rosidl_generator_cpp/resource/idl__traits.hpp.em
// with input from rmf_traffic_msgs:msg/MirrorUpdate.idl
// generated code does not contain a copyright notice
#ifndef RMF_TRAFFIC_MSGS__MSG__DETAIL__MIRROR_UPDATE__TRAITS_HPP_
#define RMF_TRAFFIC_MSGS__MSG__DETAIL__MIRROR_UPDATE__TRAITS_HPP_
#include "rmf_traffic_msgs/msg/detail/mirror_update__struct.hpp"
#include <rosidl_runtime_cpp/traits.hpp>
#include <stdint.h>
#include <type_traits>
// Include directives for member types
// Member 'patch'
#include "rmf_traffic_msgs/msg/detail/schedule_patch__traits.hpp"
namespace rosidl_generator_traits
{
template<>
inline const char * data_type<rmf_traffic_msgs::msg::MirrorUpdate>()
{
return "rmf_traffic_msgs::msg::MirrorUpdate";
}
template<>
inline const char * name<rmf_traffic_msgs::msg::MirrorUpdate>()
{
return "rmf_traffic_msgs/msg/MirrorUpdate";
}
template<>
struct has_fixed_size<rmf_traffic_msgs::msg::MirrorUpdate>
: std::integral_constant<bool, has_fixed_size<rmf_traffic_msgs::msg::SchedulePatch>::value> {};
template<>
struct has_bounded_size<rmf_traffic_msgs::msg::MirrorUpdate>
: std::integral_constant<bool, has_bounded_size<rmf_traffic_msgs::msg::SchedulePatch>::value> {};
template<>
struct is_message<rmf_traffic_msgs::msg::MirrorUpdate>
: std::true_type {};
} // namespace rosidl_generator_traits
#endif // RMF_TRAFFIC_MSGS__MSG__DETAIL__MIRROR_UPDATE__TRAITS_HPP_
| 1,424 | 573 |
/***************************************************************************\
RenderWire.h
Scott Randolph
May 5, 1998
This sub class draws an out the window view in wire frame mode.
\***************************************************************************/
#include "TOD.h"
#include "Tpost.h"
#include "RViewPnt.h"
#include "RenderWire.h"
/***************************************************************************\
Setup the rendering context for this view
\***************************************************************************/
void RenderWire::Setup( ImageBuffer *imageBuffer, RViewPoint *vp )
{
// Call our base classes setup routine
RenderOTW::Setup( imageBuffer, vp );
// Set our drawing properties
// SetSmoothShadingMode( FALSE );
SetObjectTextureState( TRUE ); // Start with object textures ON
SetHazeMode( TRUE ); // Start with hazing turned ON
// Use a black terrain filler
haze_ground_color.r = haze_ground_color.g = haze_ground_color.b = 0.0f;
earth_end_color.r = earth_end_color.g = earth_end_color.b = 0.0f;
// Use a midnight blue sky
sky_color.r = 0.0f;
sky_color.g = 0.0f;
sky_color.b = 0.125f;
haze_sky_color.r = 0.0f;
haze_sky_color.g = 0.0f;
haze_sky_color.b = 0.25f;
// Use only moderate ambient lighting on the objects
lightAmbient = 0.8f;
lightDiffuse = 0.0f;
// Update our colors to account for our changes to the default settings
TimeUpdateCallback( this );
}
/***************************************************************************\
Do end of frame housekeeping
\***************************************************************************/
void RenderWire::StartFrame( void ) {
RenderOTW::StartDraw();
TheColorBank.SetColorMode( ColorBankClass::UnlitMode );
}
#define BLEND_MIN 0.25f
#define BLEND_MAX 0.95f
/***************************************************************************\
Compute the color and texture blend value for a single terrain vertex.
\***************************************************************************/
//void RenderWire::ComputeVertexColor( TerrainVertex *vert, Tpost *post, float distance )
void RenderWire::ComputeVertexColor( TerrainVertex *vert, Tpost *, float distance )
{
// float alpha;
// Set all verts to black
vert->r = 0.0f;
vert->g = 0.0f;
vert->b = 0.0f;
// Blend out the textures in the distance
/* if ( hazed && (distance > blend_start)) {
alpha = (distance - blend_start) / blend_depth;
if (alpha < BLEND_MIN) alpha = BLEND_MIN;
if (alpha > BLEND_MAX) alpha = BLEND_MAX;
vert->a = 1.0f - alpha;
vert->RenderingStateHandle = state_mid;
} else {
vert->a = BLEND_MAX;
if (distance < PERSPECTIVE_RANGE) {
vert->RenderingStateHandle = state_fore;
} else {
vert->RenderingStateHandle = state_near;
}
}*/
}
| 2,797 | 954 |
#include "catch.hpp"
#include "parser/parser.hpp"
#include <vector>
#include <string>
static std::vector<std::string> valid_queries = {
// true/false predicates
"truepredicate",
"falsepredicate",
" TRUEPREDICATE ",
" FALSEPREDICATE ",
"truepredicates = falsepredicates", // keypaths
// characters/strings
"\"\" = ''",
"'azAZ09/ :()[]{}<>,.^@-+=*&~`' = '\\\" \\' \\\\ \\/ \\b \\f \\n \\r \\t \\0'",
"\"azAZ09/\" = \"\\\" \\' \\\\ \\/ \\b \\f \\n \\r \\t \\0\"",
"'\\uffFf' = '\\u0020'",
"'\\u01111' = 'asdf\\u0111asdf'",
// expressions (numbers, bools, keypaths, arguments)
"-1 = 12",
"0 = 001",
"0x0 = -0X398235fcAb",
"10. = -.034",
"10.0 = 5.034",
"true = false",
"truelove = false",
"true = falsey",
"nullified = null",
"_ = a",
"_a = _.aZ",
"a09._br.z = __-__.Z-9",
"$0 = $19",
"$0=$0",
// operators
"0=0",
"0 = 0",
"0 =[c] 0",
"0!=0",
"0 != 0",
"0==0",
"0 == 0",
"0==[c]0",
"0 == [c] 0",
"0>0",
"0 > 0",
"0>=0",
"0 >= 0",
"0<0",
"0 < 0",
"0<=0",
"0 <= 0",
"0 contains 0",
"a CONTAINS[c] b",
"a contains [c] b",
"'a'CONTAINS[c]b",
"0 BeGiNsWiTh 0",
"0 ENDSWITH 0",
"contains contains 'contains'",
"beginswith beginswith 'beginswith'",
"endswith endswith 'endswith'",
"NOT NOT != 'NOT'",
"AND == 'AND' AND OR == 'OR'",
// FIXME - bug
// "truepredicate == 'falsepredicate' && truepredicate",
// atoms/groups
"(0=0)",
"( 0=0 )",
"((0=0))",
"!0=0",
"! 0=0",
"!(0=0)",
"! (0=0)",
"NOT0=0", // keypath NOT0
"NOT0.a=0", // keypath NOT0
"NOT0a.b=0", // keypath NOT0a
"not-1=1",
"not 0=0",
"NOT(0=0)",
"not (0=0)",
"NOT (!0=0)",
// compound
"a==a && a==a",
"a==a || a==a",
"a==a&&a==a||a=a",
"a==a and a==a",
"a==a OR a==a",
"and=='AND'&&'or'=='||'",
"and == or && ORE > GRAND",
"a=1AND NOTb=2",
};
static std::vector<std::string> invalid_queries = {
"predicate",
"'\\a' = ''", // invalid escape
// invalid unicode
"'\\u0' = ''",
// invalid strings
"\"' = ''",
"\" = ''",
"' = ''",
// expressions
"03a = 1",
"1..0 = 1",
"1.0. = 1",
"1-0 = 1",
"0x = 1",
"- = a",
"a..b = a",
"a$a = a",
"{} = $0",
"$-1 = $0",
"$a = $0",
"$ = $",
// operators
"0===>0",
"0 <> 0",
"0 contains1",
"a contains_something",
"endswith 0",
// atoms/groups
"0=0)",
"(0=0",
"(0=0))",
"! =0",
"NOTNOT(0=0)",
"not.a=0",
"(!!0=0)",
"0=0 !",
// compound
"a==a & a==a",
"a==a | a==a",
"a==a &| a==a",
"a==a && OR a==a",
"a==aORa==a",
"a==a ORa==a",
"a==a AND==a",
"a==a ANDa==a",
"a=1ANDNOT b=2",
"truepredicate &&",
"truepredicate & truepredicate",
};
TEST_CASE("valid queries") {
for (auto& query : valid_queries) {
INFO("query: " << query);
CHECK_NOTHROW(realm::parser::parse(query));
}
}
TEST_CASE("invalid queries") {
for (auto& query : invalid_queries) {
INFO("query: " << query);
CHECK_THROWS(realm::parser::parse(query));
}
}
| 3,293 | 1,520 |
/* The MIT License (MIT)
Copyright (c) [2015] [Nrupatunga]
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 "HOG.hpp"
HOG::HOG(String &strPosSamples, String &strNegSamples, Size &sizeWin = Size(64, 128))
{
glob(strPosSamples, vecStrPosSamples);
glob(strNegSamples, vecStrNegSamples);
s32NumPosSamples = vecStrPosSamples.size();
s32NumNegSamples = vecStrNegSamples.size();
if (s32NumPosSamples <= 0 || s32NumNegSamples <= 0){
cout << "Invalid Training Sample Path/ Please check if there are any training samples in the given path" << endl;
return;
}
objHog.winSize = sizeWin;
s32NumOfSamples = s32NumPosSamples + s32NumNegSamples;
return;
}
HOG::enumHOGError HOG::getFeatures(String &strFeatureFileName, HOG::enumSVMLib eSVMLib)
{
enumHOGError eHOGError = HOG_NO_ERROR;
Mat sMatInImage;
if (eSVMLib != SVM_LIGHT && eSVMLib != SVM_LIBSVM){
cout << " Invalid SVM library specified";
eSVMLib = SVM_LIBSVM;
}
if (s32NumOfSamples <= 0) {
cout << " ------------------------------------------------------------" << endl;
cout << " Please provide samples to train" << endl << " Refer to the function:: HOG(String &strPosSamples, String &strNegSamples, Size &sizeWin)" << endl;
cout << " ------------------------------------------------------------" << endl;
return HOG_INVALID_ARGUMENTS;
}
ofstream outFeatureFile;
outFeatureFile.open(strFeatureFileName, std::ofstream::trunc);
if (!(outFeatureFile.good() && outFeatureFile.is_open())) {
cout << "File " << strFeatureFileName << " failed to open. Please check the path" << endl;
return HOG_INVALID_ARGUMENTS;
}
#if WRITE_FILE_NAMES
ofstream outFileNames;
outFileNames.open("filenames.txt", std::ofstream::trunc);
#endif
// Remove following line for libsvm which does not support comment
if (eSVMLib == SVM_LIGHT){
outFeatureFile << "# Use this file to train, e.g. SVMlight by issuing $ svm_learn -i 1 -a weights.txt " << strFeatureFileName << endl;
}
cout << " ------------------------------------------------------------" << endl;
cout << " This could take a while, based on the number of training samples " << endl;
cout << " ------------------------------------------------------------" << endl;
cout << " Calculating HOG Features ... " << endl;
vector<float> vecFeature;
for (unsigned long i = 0; i < s32NumOfSamples; i++){
int s32Progress = (i * 100 / s32NumOfSamples);
const String strCurrentFile = (i < s32NumPosSamples) ? vecStrPosSamples.at(i) : vecStrNegSamples.at(i - s32NumPosSamples);
sMatInImage = imread(strCurrentFile);
#if WRITE_FILE_NAMES
outFileNames << strCurrentFile << endl;
#endif
if (sMatInImage.empty()){
cout << "Cannot open file " << strCurrentFile << " Please check the format of the image file" << endl;
break;
}
calculateFeature(sMatInImage, vecFeature, objHog);
Mat sMatHogVis = get_hogdescriptor_visu(sMatInImage, vecFeature, objHog.winSize);
if (vecFeature.empty()){
break;
}
#if 1
outFeatureFile << ((i < s32NumPosSamples) ? "+1" : "-1");
for (int j = 0; j < vecFeature.size(); j++){
int s32Count = j + 1;
outFeatureFile << " " << s32Count << ":" << vecFeature.at(j) << " ";
}
#else
for (int j = 0; j < vecFeature.size(); j++){
int s32Count = j + 1;
outFeatureFile << " " << vecFeature.at(j) << " ";
}
#endif
outFeatureFile << endl;
cout << " Progress :: " << s32Progress << "%\r";
cout.flush();
}
cout << " Progress :: " << "DONE.." << endl;
outFeatureFile.close();
#if WRITE_FILE_NAMES
outFileNames.close();
#endif
sMatInImage.release();
return eHOGError;
}
void HOG::setParameters(Size &sizeWinStride, Size &sizeTrainPadding)
{
if (sizeWinStride.width > 0 && sizeWinStride.height > 0)
winStride = sizeWinStride;
else
cout << "Invalid Window Stride " << endl;
if (sizeTrainPadding.width > 0 && sizeTrainPadding.height > 0)
trainingPadding = sizeTrainPadding;
else
cout << "Invalid Training padding " << endl;
}
void HOG::calculateFeature(const Mat &sMatInput, vector<float> &vecDescriptor, HOGDescriptor &objHog)
{
Size hogWinSize = objHog.winSize;
if (sMatInput.cols != hogWinSize.width || sMatInput.rows != hogWinSize.height){
vecDescriptor.clear();
cout << " ------------------------------------------------------------" << endl;
cout << "Input image dimensions " << sMatInput.cols << "x" << sMatInput.rows << \
" do not match with HOG window size " << hogWinSize.width << "x" << hogWinSize.height << endl;
cout << " ------------------------------------------------------------" << endl;
return;
}
objHog.compute(sMatInput, vecDescriptor, winStride, trainingPadding);
return;
}
//Source code from http://www.juergenwiki.de/work/wiki/doku.php?id=public:hog_descriptor_computation_and_visualization
Mat HOG::get_hogdescriptor_visu(const Mat& color_origImg, vector<float>& descriptorValues, const Size & size)
{
const int DIMX = size.width;
const int DIMY = size.height;
float zoomFac = 3;
Mat visu;
resize(color_origImg, visu, Size((int)(color_origImg.cols*zoomFac), (int)(color_origImg.rows*zoomFac)));
int cellSize = 8;
int gradientBinSize = 9;
float radRangeForOneBin = (float)(CV_PI / (float)gradientBinSize); // dividing 180 into 9 bins, how large (in rad) is one bin?
// prepare data structure: 9 orientation / gradient strenghts for each cell
int cells_in_x_dir = DIMX / cellSize;
int cells_in_y_dir = DIMY / cellSize;
float*** gradientStrengths = new float**[cells_in_y_dir];
int** cellUpdateCounter = new int*[cells_in_y_dir];
for (int y = 0; y<cells_in_y_dir; y++)
{
gradientStrengths[y] = new float*[cells_in_x_dir];
cellUpdateCounter[y] = new int[cells_in_x_dir];
for (int x = 0; x<cells_in_x_dir; x++)
{
gradientStrengths[y][x] = new float[gradientBinSize];
cellUpdateCounter[y][x] = 0;
for (int bin = 0; bin<gradientBinSize; bin++)
gradientStrengths[y][x][bin] = 0.0;
}
}
// nr of blocks = nr of cells - 1
// since there is a new block on each cell (overlapping blocks!) but the last one
int blocks_in_x_dir = cells_in_x_dir - 1;
int blocks_in_y_dir = cells_in_y_dir - 1;
// compute gradient strengths per cell
int descriptorDataIdx = 0;
int cellx = 0;
int celly = 0;
for (int blockx = 0; blockx<blocks_in_x_dir; blockx++)
{
for (int blocky = 0; blocky<blocks_in_y_dir; blocky++)
{
// 4 cells per block ...
for (int cellNr = 0; cellNr<4; cellNr++)
{
// compute corresponding cell nr
cellx = blockx;
celly = blocky;
if (cellNr == 1) celly++;
if (cellNr == 2) cellx++;
if (cellNr == 3)
{
cellx++;
celly++;
}
for (int bin = 0; bin<gradientBinSize; bin++)
{
float gradientStrength = descriptorValues[descriptorDataIdx];
descriptorDataIdx++;
gradientStrengths[celly][cellx][bin] += gradientStrength;
} // for (all bins)
// note: overlapping blocks lead to multiple updates of this sum!
// we therefore keep track how often a cell was updated,
// to compute average gradient strengths
cellUpdateCounter[celly][cellx]++;
} // for (all cells)
} // for (all block x pos)
} // for (all block y pos)
// compute average gradient strengths
for (celly = 0; celly<cells_in_y_dir; celly++)
{
for (cellx = 0; cellx<cells_in_x_dir; cellx++)
{
float NrUpdatesForThisCell = (float)cellUpdateCounter[celly][cellx];
// compute average gradient strenghts for each gradient bin direction
for (int bin = 0; bin<gradientBinSize; bin++)
{
gradientStrengths[celly][cellx][bin] /= NrUpdatesForThisCell;
}
}
}
// draw cells
for (celly = 0; celly<cells_in_y_dir; celly++)
{
for (cellx = 0; cellx<cells_in_x_dir; cellx++)
{
int drawX = cellx * cellSize;
int drawY = celly * cellSize;
int mx = drawX + cellSize / 2;
int my = drawY + cellSize / 2;
rectangle(visu, Point((int)(drawX*zoomFac), (int)(drawY*zoomFac)), Point((int)((drawX + cellSize)*zoomFac), (int)((drawY + cellSize)*zoomFac)), Scalar(100, 100, 100), 1);
// draw in each cell all 9 gradient strengths
for (int bin = 0; bin<gradientBinSize; bin++)
{
float currentGradStrength = gradientStrengths[celly][cellx][bin];
// no line to draw?
if (currentGradStrength == 0)
continue;
float currRad = bin * radRangeForOneBin + radRangeForOneBin / 2;
float dirVecX = cos(currRad);
float dirVecY = sin(currRad);
float maxVecLen = (float)(cellSize / 2.f);
float scale = 2.5; // just a visualization scale, to see the lines better
// compute line coordinates
float x1 = mx - dirVecX * currentGradStrength * maxVecLen * scale;
float y1 = my - dirVecY * currentGradStrength * maxVecLen * scale;
float x2 = mx + dirVecX * currentGradStrength * maxVecLen * scale;
float y2 = my + dirVecY * currentGradStrength * maxVecLen * scale;
// draw gradient visualization
line(visu, Point((int)(x1*zoomFac), (int)(y1*zoomFac)), Point((int)(x2*zoomFac), (int)(y2*zoomFac)), Scalar(0, 255, 0), 1);
} // for (all bins)
} // for (cellx)
} // for (celly)
// don't forget to free memory allocated by helper data structures!
for (int y = 0; y<cells_in_y_dir; y++)
{
for (int x = 0; x<cells_in_x_dir; x++)
{
delete[] gradientStrengths[y][x];
}
delete[] gradientStrengths[y];
delete[] cellUpdateCounter[y];
}
delete[] gradientStrengths;
delete[] cellUpdateCounter;
return visu;
} // get_hogdescriptor_visu | 10,739 | 4,235 |
#include "rational.h"
#include <iostream>
using std::cout;
using std::cin;
using std::cerr;
int main()
try {
cout << "Enter the integers of two rational numbers:\n";
int a, b, c, d;
cin >> a >> b >> c >> d;
Rational r1{a, b};
Rational r2{c, d};
cout << "Add: " << r1 + r2 << '\n'
<< "Sub: " << r1 - r2 << '\n'
<< "Mul: " << r1 * r2 << '\n'
<< "Div: " << r1 / r2 << '\n';
return 0;
}
catch(std::exception& e) {
cerr << e.what() << '\n';
}
catch(...) {
cerr << "unknown exception" << '\n';
}
| 557 | 228 |
/**
* @file GoalModel.cpp
*
* @author <a href="mailto:borisov@informatik.hu-berlin.de">Alexander Borisov</a>
* @author <a href="mailto:xu@informatik.hu-berlin.de">Xu, Yuan</a>
* @author <a href="mailto:scheunem@informatik.hu-berlin.de">Marcus Scheunemann</a>
* @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</
* Implementation of class GoalModel
*
*/
#include "GoalModel.h"
GoalModel::Goal GoalModel::getOwnGoal(const CompassDirection& compassDirection, const FieldInfo& fieldInfo) const
{
return getOwnGoal(compassDirection.angle, fieldInfo);
}
GoalModel::Goal GoalModel::getOwnGoal(double angle, const FieldInfo& fieldInfo) const
{
//TODO check this decision, compare with robotPose.rotation
//18.02.2012
//if (fabs(compassDirection.angle) > Math::pi_2 && fabs(goal.calculateCenter().angle()) < Math::pi_2) {
if(fabs(angle + goal.calculateCenter().angle()) > Math::pi_2){
return goal;
} else {
return calculateAnotherGoal(goal, fieldInfo.xLength);
}
}//end getOwnGoal
GoalModel::Goal GoalModel::getOppGoal(const CompassDirection& compassDirection, const FieldInfo& fieldInfo) const
{
return getOppGoal(compassDirection.angle, fieldInfo);
}
GoalModel::Goal GoalModel::getOppGoal(double angle, const FieldInfo& fieldInfo) const
{
//TODO check this decision, compare with robotPose.rotation
//18.02.2012
//if(fabs(goal.calculateCenter().rotate(compassDirection.angle).angle()) < Math::pi_2)
if(fabs(Math::normalize(angle + goal.calculateCenter().angle())) < Math::pi_2)
{
return goal;
} else {
return calculateAnotherGoal(goal, fieldInfo.xLength);
}
}//end getOppGoal
/*
const GoalModel::Goal& GoalModel::getTeamGoal(naoth::GameData::TeamColor teamColor) const
{
switch (teamColor)
{
case GameData::red:
return yellowGoal;
break;
case GameData::blue:
return blueGoal;
break;
default:
ASSERT(false);
}
return blueGoal;
}
GoalModel::Goal& GoalModel::getTeamGoal(naoth::GameData::TeamColor teamColor)
{
switch (teamColor)
{
case GameData::red:
return yellowGoal;
break;
case GameData::blue:
return blueGoal;
break;
default:
ASSERT(false);
}
return blueGoal;
}//end getTeamGoal
*/
void GoalModel::print(std::ostream& stream) const
{
stream<<"== Seen Goal ==\n";
stream<< goal.frameInfoWhenGoalLastSeen;
stream<<"LPost = "<<goal.leftPost<<'\n';
stream<<"RPost = "<<goal.rightPost<<'\n';
/*Goal anotherGoal;
calculateAnotherGoal(goal, anotherGoal, getFieldInfo().xLength);
stream<<"== Calculated Goal ==\n";
stream<<"LPost = "<<anotherGoal.leftPost<<'\n';
stream<<"RPost = "<<anotherGoal.rightPost<<'\n';*/
}//end print
void GoalModel::draw() const
{
//FIELD_DRAWING_CONTEXT;
//PEN("FF0000", 50);
//CIRCLE(goal.leftPost.x, goal.leftPost.y, 50);
//CIRCLE(goal.rightPost.x, goal.rightPost.y, 50);
}//end draw
LocalGoalModel::LocalGoalModel()
:
someGoalWasSeen(false),
opponentGoalIsValid(false),
ownGoalIsValid(false),
seen_angle(0.0)
{
}
GoalModel::Goal GoalModel::calculateAnotherGoal(const GoalModel::Goal& goal, double distance)
{
Vector2<double> normal = goal.rightPost - goal.leftPost;
GoalModel::Goal another;
normal.normalize(distance);
normal.rotateRight();
// swich the posts
another.leftPost = goal.rightPost + normal;
another.rightPost = goal.leftPost + normal;
return another;
}//end calculateAnotherGoal
Pose2D GoalModel::calculatePose(const CompassDirection& compassDirection, const FieldInfo& fieldInfo) const
{
return calculatePose(compassDirection.angle, fieldInfo);
}
Pose2D GoalModel::calculatePose(double angle, const FieldInfo& fieldInfo) const
{
const Vector2<double>& leftOpponentGoalPosition = fieldInfo.opponentGoalPostLeft;
const Vector2<double>& rightOpponentGoalPosition = fieldInfo.opponentGoalPostRight;
Goal modeledOpponentGoal = getOppGoal(angle, fieldInfo);
// TODO: make it nicer with Vector2 operations
double rotation = (modeledOpponentGoal.leftPost-modeledOpponentGoal.rightPost).angle() - Math::pi_2;
rotation = Math::normalize(-rotation);
// TODO: introduce const method Vector2<>.rotate()
Vector2<double> posLeft = leftOpponentGoalPosition - modeledOpponentGoal.leftPost.rotate(rotation);
Vector2<double> posRight = rightOpponentGoalPosition - modeledOpponentGoal.rightPost.rotate(rotation);
Pose2D pose;
pose.translation = (posLeft + posRight)*0.5;
pose.rotation = rotation;
return pose;
}//end calculatePosition
void LocalGoalModel::print(std::ostream& stream) const
{
stream<<"someGoalWasSeen = "<<(someGoalWasSeen?"true":"false")<< std::endl;
stream<<"estimatedCenterOfGoal = " << seen_center << std::endl;
stream<<"estimatedAngleToGoal = " << seen_angle << std::endl;
GoalModel::print(stream);
}//end print
void SelfLocGoalModel::update(const Pose2D& robotPose, const FieldInfo& fieldInfo)
{
//GoalModel::Goal ownGoal = getOwnGoal(compassDirection, fieldInfo);
//GoalModel::Goal oppGoal = getOppGoal(compassDirection, fieldInfo);
// transform the goal posts to the local coordinates according to the robotPose
//ownGoal.leftPost = robotPose/fieldInfo.ownGoalPostLeft;
//ownGoal.rightPost = robotPose/fieldInfo.ownGoalPostRight;
// set the opponent goal regarding my position on the field
goal.leftPost = robotPose/fieldInfo.opponentGoalPostLeft;
goal.rightPost = robotPose/fieldInfo.opponentGoalPostRight;
}//end update
SensingGoalModel::SensingGoalModel()
:
someGoalWasSeen(false),
horizonScan(false)
{
}
| 5,552 | 2,037 |
#include <sstream>
#include "evalexpr.hpp"
void test(std::string const &str) {
auto res = Evalexpr::pExpr(str);
std::cout << "test :\"" << str << "\"" << std::endl;
std::cout << res << std::endl;
if (res.valid()) {
std::cout << "size = " << sizeof(res.f) << std::endl;
std::cout << "exec : " << res() << std::endl;
}
std::cout << std::endl;
}
int main()
{
std::stringstream sstr;
srand(time(nullptr));
sstr << rand() % 10;
for (auto x = 0; x < 4; ++x) {
int op = rand() % 5;
switch (op) {
case 0: sstr << "+"; break;
case 1: sstr << "-"; break;
case 2: sstr << "*"; break;
case 3: sstr << "/"; break;
case 4: sstr << "%"; break;
}
sstr << rand() % 10;
}
test(sstr.str());
test("(34+12)*2-42");
// test("-12");
// test("+12");
// test("+12a");
// test("+");
}
// 75,840 bytes alloués
| 970 | 388 |
// SPDX-License-Identifier: Apache-2.0
// ----------------------------------------------------------------------------
// Copyright 2011-2021 Arm Limited
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
// ----------------------------------------------------------------------------
/**
* @brief Functions for encoding/decoding Bounded Integer Sequence Encoding.
*/
#include "astcenc_internal.h"
#include <array>
// unpacked quint triplets <low,middle,high> for each packed-quint value
static const uint8_t quints_of_integer[128][3] = {
{0, 0, 0}, {1, 0, 0}, {2, 0, 0}, {3, 0, 0},
{4, 0, 0}, {0, 4, 0}, {4, 4, 0}, {4, 4, 4},
{0, 1, 0}, {1, 1, 0}, {2, 1, 0}, {3, 1, 0},
{4, 1, 0}, {1, 4, 0}, {4, 4, 1}, {4, 4, 4},
{0, 2, 0}, {1, 2, 0}, {2, 2, 0}, {3, 2, 0},
{4, 2, 0}, {2, 4, 0}, {4, 4, 2}, {4, 4, 4},
{0, 3, 0}, {1, 3, 0}, {2, 3, 0}, {3, 3, 0},
{4, 3, 0}, {3, 4, 0}, {4, 4, 3}, {4, 4, 4},
{0, 0, 1}, {1, 0, 1}, {2, 0, 1}, {3, 0, 1},
{4, 0, 1}, {0, 4, 1}, {4, 0, 4}, {0, 4, 4},
{0, 1, 1}, {1, 1, 1}, {2, 1, 1}, {3, 1, 1},
{4, 1, 1}, {1, 4, 1}, {4, 1, 4}, {1, 4, 4},
{0, 2, 1}, {1, 2, 1}, {2, 2, 1}, {3, 2, 1},
{4, 2, 1}, {2, 4, 1}, {4, 2, 4}, {2, 4, 4},
{0, 3, 1}, {1, 3, 1}, {2, 3, 1}, {3, 3, 1},
{4, 3, 1}, {3, 4, 1}, {4, 3, 4}, {3, 4, 4},
{0, 0, 2}, {1, 0, 2}, {2, 0, 2}, {3, 0, 2},
{4, 0, 2}, {0, 4, 2}, {2, 0, 4}, {3, 0, 4},
{0, 1, 2}, {1, 1, 2}, {2, 1, 2}, {3, 1, 2},
{4, 1, 2}, {1, 4, 2}, {2, 1, 4}, {3, 1, 4},
{0, 2, 2}, {1, 2, 2}, {2, 2, 2}, {3, 2, 2},
{4, 2, 2}, {2, 4, 2}, {2, 2, 4}, {3, 2, 4},
{0, 3, 2}, {1, 3, 2}, {2, 3, 2}, {3, 3, 2},
{4, 3, 2}, {3, 4, 2}, {2, 3, 4}, {3, 3, 4},
{0, 0, 3}, {1, 0, 3}, {2, 0, 3}, {3, 0, 3},
{4, 0, 3}, {0, 4, 3}, {0, 0, 4}, {1, 0, 4},
{0, 1, 3}, {1, 1, 3}, {2, 1, 3}, {3, 1, 3},
{4, 1, 3}, {1, 4, 3}, {0, 1, 4}, {1, 1, 4},
{0, 2, 3}, {1, 2, 3}, {2, 2, 3}, {3, 2, 3},
{4, 2, 3}, {2, 4, 3}, {0, 2, 4}, {1, 2, 4},
{0, 3, 3}, {1, 3, 3}, {2, 3, 3}, {3, 3, 3},
{4, 3, 3}, {3, 4, 3}, {0, 3, 4}, {1, 3, 4}
};
// packed quint-value for every unpacked quint-triplet
// indexed by [high][middle][low]
static const uint8_t integer_of_quints[5][5][5] = {
{
{0, 1, 2, 3, 4},
{8, 9, 10, 11, 12},
{16, 17, 18, 19, 20},
{24, 25, 26, 27, 28},
{5, 13, 21, 29, 6}
},
{
{32, 33, 34, 35, 36},
{40, 41, 42, 43, 44},
{48, 49, 50, 51, 52},
{56, 57, 58, 59, 60},
{37, 45, 53, 61, 14}
},
{
{64, 65, 66, 67, 68},
{72, 73, 74, 75, 76},
{80, 81, 82, 83, 84},
{88, 89, 90, 91, 92},
{69, 77, 85, 93, 22}
},
{
{96, 97, 98, 99, 100},
{104, 105, 106, 107, 108},
{112, 113, 114, 115, 116},
{120, 121, 122, 123, 124},
{101, 109, 117, 125, 30}
},
{
{102, 103, 70, 71, 38},
{110, 111, 78, 79, 46},
{118, 119, 86, 87, 54},
{126, 127, 94, 95, 62},
{39, 47, 55, 63, 31}
}
};
// unpacked trit quintuplets <low,_,_,_,high> for each packed-quint value
static const uint8_t trits_of_integer[256][5] = {
{0, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {2, 0, 0, 0, 0}, {0, 0, 2, 0, 0},
{0, 1, 0, 0, 0}, {1, 1, 0, 0, 0}, {2, 1, 0, 0, 0}, {1, 0, 2, 0, 0},
{0, 2, 0, 0, 0}, {1, 2, 0, 0, 0}, {2, 2, 0, 0, 0}, {2, 0, 2, 0, 0},
{0, 2, 2, 0, 0}, {1, 2, 2, 0, 0}, {2, 2, 2, 0, 0}, {2, 0, 2, 0, 0},
{0, 0, 1, 0, 0}, {1, 0, 1, 0, 0}, {2, 0, 1, 0, 0}, {0, 1, 2, 0, 0},
{0, 1, 1, 0, 0}, {1, 1, 1, 0, 0}, {2, 1, 1, 0, 0}, {1, 1, 2, 0, 0},
{0, 2, 1, 0, 0}, {1, 2, 1, 0, 0}, {2, 2, 1, 0, 0}, {2, 1, 2, 0, 0},
{0, 0, 0, 2, 2}, {1, 0, 0, 2, 2}, {2, 0, 0, 2, 2}, {0, 0, 2, 2, 2},
{0, 0, 0, 1, 0}, {1, 0, 0, 1, 0}, {2, 0, 0, 1, 0}, {0, 0, 2, 1, 0},
{0, 1, 0, 1, 0}, {1, 1, 0, 1, 0}, {2, 1, 0, 1, 0}, {1, 0, 2, 1, 0},
{0, 2, 0, 1, 0}, {1, 2, 0, 1, 0}, {2, 2, 0, 1, 0}, {2, 0, 2, 1, 0},
{0, 2, 2, 1, 0}, {1, 2, 2, 1, 0}, {2, 2, 2, 1, 0}, {2, 0, 2, 1, 0},
{0, 0, 1, 1, 0}, {1, 0, 1, 1, 0}, {2, 0, 1, 1, 0}, {0, 1, 2, 1, 0},
{0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {2, 1, 1, 1, 0}, {1, 1, 2, 1, 0},
{0, 2, 1, 1, 0}, {1, 2, 1, 1, 0}, {2, 2, 1, 1, 0}, {2, 1, 2, 1, 0},
{0, 1, 0, 2, 2}, {1, 1, 0, 2, 2}, {2, 1, 0, 2, 2}, {1, 0, 2, 2, 2},
{0, 0, 0, 2, 0}, {1, 0, 0, 2, 0}, {2, 0, 0, 2, 0}, {0, 0, 2, 2, 0},
{0, 1, 0, 2, 0}, {1, 1, 0, 2, 0}, {2, 1, 0, 2, 0}, {1, 0, 2, 2, 0},
{0, 2, 0, 2, 0}, {1, 2, 0, 2, 0}, {2, 2, 0, 2, 0}, {2, 0, 2, 2, 0},
{0, 2, 2, 2, 0}, {1, 2, 2, 2, 0}, {2, 2, 2, 2, 0}, {2, 0, 2, 2, 0},
{0, 0, 1, 2, 0}, {1, 0, 1, 2, 0}, {2, 0, 1, 2, 0}, {0, 1, 2, 2, 0},
{0, 1, 1, 2, 0}, {1, 1, 1, 2, 0}, {2, 1, 1, 2, 0}, {1, 1, 2, 2, 0},
{0, 2, 1, 2, 0}, {1, 2, 1, 2, 0}, {2, 2, 1, 2, 0}, {2, 1, 2, 2, 0},
{0, 2, 0, 2, 2}, {1, 2, 0, 2, 2}, {2, 2, 0, 2, 2}, {2, 0, 2, 2, 2},
{0, 0, 0, 0, 2}, {1, 0, 0, 0, 2}, {2, 0, 0, 0, 2}, {0, 0, 2, 0, 2},
{0, 1, 0, 0, 2}, {1, 1, 0, 0, 2}, {2, 1, 0, 0, 2}, {1, 0, 2, 0, 2},
{0, 2, 0, 0, 2}, {1, 2, 0, 0, 2}, {2, 2, 0, 0, 2}, {2, 0, 2, 0, 2},
{0, 2, 2, 0, 2}, {1, 2, 2, 0, 2}, {2, 2, 2, 0, 2}, {2, 0, 2, 0, 2},
{0, 0, 1, 0, 2}, {1, 0, 1, 0, 2}, {2, 0, 1, 0, 2}, {0, 1, 2, 0, 2},
{0, 1, 1, 0, 2}, {1, 1, 1, 0, 2}, {2, 1, 1, 0, 2}, {1, 1, 2, 0, 2},
{0, 2, 1, 0, 2}, {1, 2, 1, 0, 2}, {2, 2, 1, 0, 2}, {2, 1, 2, 0, 2},
{0, 2, 2, 2, 2}, {1, 2, 2, 2, 2}, {2, 2, 2, 2, 2}, {2, 0, 2, 2, 2},
{0, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {2, 0, 0, 0, 1}, {0, 0, 2, 0, 1},
{0, 1, 0, 0, 1}, {1, 1, 0, 0, 1}, {2, 1, 0, 0, 1}, {1, 0, 2, 0, 1},
{0, 2, 0, 0, 1}, {1, 2, 0, 0, 1}, {2, 2, 0, 0, 1}, {2, 0, 2, 0, 1},
{0, 2, 2, 0, 1}, {1, 2, 2, 0, 1}, {2, 2, 2, 0, 1}, {2, 0, 2, 0, 1},
{0, 0, 1, 0, 1}, {1, 0, 1, 0, 1}, {2, 0, 1, 0, 1}, {0, 1, 2, 0, 1},
{0, 1, 1, 0, 1}, {1, 1, 1, 0, 1}, {2, 1, 1, 0, 1}, {1, 1, 2, 0, 1},
{0, 2, 1, 0, 1}, {1, 2, 1, 0, 1}, {2, 2, 1, 0, 1}, {2, 1, 2, 0, 1},
{0, 0, 1, 2, 2}, {1, 0, 1, 2, 2}, {2, 0, 1, 2, 2}, {0, 1, 2, 2, 2},
{0, 0, 0, 1, 1}, {1, 0, 0, 1, 1}, {2, 0, 0, 1, 1}, {0, 0, 2, 1, 1},
{0, 1, 0, 1, 1}, {1, 1, 0, 1, 1}, {2, 1, 0, 1, 1}, {1, 0, 2, 1, 1},
{0, 2, 0, 1, 1}, {1, 2, 0, 1, 1}, {2, 2, 0, 1, 1}, {2, 0, 2, 1, 1},
{0, 2, 2, 1, 1}, {1, 2, 2, 1, 1}, {2, 2, 2, 1, 1}, {2, 0, 2, 1, 1},
{0, 0, 1, 1, 1}, {1, 0, 1, 1, 1}, {2, 0, 1, 1, 1}, {0, 1, 2, 1, 1},
{0, 1, 1, 1, 1}, {1, 1, 1, 1, 1}, {2, 1, 1, 1, 1}, {1, 1, 2, 1, 1},
{0, 2, 1, 1, 1}, {1, 2, 1, 1, 1}, {2, 2, 1, 1, 1}, {2, 1, 2, 1, 1},
{0, 1, 1, 2, 2}, {1, 1, 1, 2, 2}, {2, 1, 1, 2, 2}, {1, 1, 2, 2, 2},
{0, 0, 0, 2, 1}, {1, 0, 0, 2, 1}, {2, 0, 0, 2, 1}, {0, 0, 2, 2, 1},
{0, 1, 0, 2, 1}, {1, 1, 0, 2, 1}, {2, 1, 0, 2, 1}, {1, 0, 2, 2, 1},
{0, 2, 0, 2, 1}, {1, 2, 0, 2, 1}, {2, 2, 0, 2, 1}, {2, 0, 2, 2, 1},
{0, 2, 2, 2, 1}, {1, 2, 2, 2, 1}, {2, 2, 2, 2, 1}, {2, 0, 2, 2, 1},
{0, 0, 1, 2, 1}, {1, 0, 1, 2, 1}, {2, 0, 1, 2, 1}, {0, 1, 2, 2, 1},
{0, 1, 1, 2, 1}, {1, 1, 1, 2, 1}, {2, 1, 1, 2, 1}, {1, 1, 2, 2, 1},
{0, 2, 1, 2, 1}, {1, 2, 1, 2, 1}, {2, 2, 1, 2, 1}, {2, 1, 2, 2, 1},
{0, 2, 1, 2, 2}, {1, 2, 1, 2, 2}, {2, 2, 1, 2, 2}, {2, 1, 2, 2, 2},
{0, 0, 0, 1, 2}, {1, 0, 0, 1, 2}, {2, 0, 0, 1, 2}, {0, 0, 2, 1, 2},
{0, 1, 0, 1, 2}, {1, 1, 0, 1, 2}, {2, 1, 0, 1, 2}, {1, 0, 2, 1, 2},
{0, 2, 0, 1, 2}, {1, 2, 0, 1, 2}, {2, 2, 0, 1, 2}, {2, 0, 2, 1, 2},
{0, 2, 2, 1, 2}, {1, 2, 2, 1, 2}, {2, 2, 2, 1, 2}, {2, 0, 2, 1, 2},
{0, 0, 1, 1, 2}, {1, 0, 1, 1, 2}, {2, 0, 1, 1, 2}, {0, 1, 2, 1, 2},
{0, 1, 1, 1, 2}, {1, 1, 1, 1, 2}, {2, 1, 1, 1, 2}, {1, 1, 2, 1, 2},
{0, 2, 1, 1, 2}, {1, 2, 1, 1, 2}, {2, 2, 1, 1, 2}, {2, 1, 2, 1, 2},
{0, 2, 2, 2, 2}, {1, 2, 2, 2, 2}, {2, 2, 2, 2, 2}, {2, 1, 2, 2, 2}
};
// packed trit-value for every unpacked trit-quintuplet
// indexed by [high][][][][low]
static const uint8_t integer_of_trits[3][3][3][3][3] = {
{
{
{
{0, 1, 2},
{4, 5, 6},
{8, 9, 10}
},
{
{16, 17, 18},
{20, 21, 22},
{24, 25, 26}
},
{
{3, 7, 15},
{19, 23, 27},
{12, 13, 14}
}
},
{
{
{32, 33, 34},
{36, 37, 38},
{40, 41, 42}
},
{
{48, 49, 50},
{52, 53, 54},
{56, 57, 58}
},
{
{35, 39, 47},
{51, 55, 59},
{44, 45, 46}
}
},
{
{
{64, 65, 66},
{68, 69, 70},
{72, 73, 74}
},
{
{80, 81, 82},
{84, 85, 86},
{88, 89, 90}
},
{
{67, 71, 79},
{83, 87, 91},
{76, 77, 78}
}
}
},
{
{
{
{128, 129, 130},
{132, 133, 134},
{136, 137, 138}
},
{
{144, 145, 146},
{148, 149, 150},
{152, 153, 154}
},
{
{131, 135, 143},
{147, 151, 155},
{140, 141, 142}
}
},
{
{
{160, 161, 162},
{164, 165, 166},
{168, 169, 170}
},
{
{176, 177, 178},
{180, 181, 182},
{184, 185, 186}
},
{
{163, 167, 175},
{179, 183, 187},
{172, 173, 174}
}
},
{
{
{192, 193, 194},
{196, 197, 198},
{200, 201, 202}
},
{
{208, 209, 210},
{212, 213, 214},
{216, 217, 218}
},
{
{195, 199, 207},
{211, 215, 219},
{204, 205, 206}
}
}
},
{
{
{
{96, 97, 98},
{100, 101, 102},
{104, 105, 106}
},
{
{112, 113, 114},
{116, 117, 118},
{120, 121, 122}
},
{
{99, 103, 111},
{115, 119, 123},
{108, 109, 110}
}
},
{
{
{224, 225, 226},
{228, 229, 230},
{232, 233, 234}
},
{
{240, 241, 242},
{244, 245, 246},
{248, 249, 250}
},
{
{227, 231, 239},
{243, 247, 251},
{236, 237, 238}
}
},
{
{
{28, 29, 30},
{60, 61, 62},
{92, 93, 94}
},
{
{156, 157, 158},
{188, 189, 190},
{220, 221, 222}
},
{
{31, 63, 127},
{159, 191, 255},
{252, 253, 254}
}
}
}
};
/**
* @brief The number of bits, trits, and quints needed for a quant level.
*/
struct btq_count {
/**< The quantization level. */
uint8_t quant;
/**< The number of bits. */
uint8_t bits;
/**< The number of trits. */
uint8_t trits;
/**< The number of quints. */
uint8_t quints;
};
/**
* @brief The table of bits, trits, and quints needed for a quant encode.
*/
static const std::array<btq_count, 21> btq_counts = {{
{ QUANT_2, 1, 0, 0 },
{ QUANT_3, 0, 1, 0 },
{ QUANT_4, 2, 0, 0 },
{ QUANT_5, 0, 0, 1 },
{ QUANT_6, 1, 1, 0 },
{ QUANT_8, 3, 0, 0 },
{ QUANT_10, 1, 0, 1 },
{ QUANT_12, 2, 1, 0 },
{ QUANT_16, 4, 0, 0 },
{ QUANT_20, 2, 0, 1 },
{ QUANT_24, 3, 1, 0 },
{ QUANT_32, 5, 0, 0 },
{ QUANT_40, 3, 0, 1 },
{ QUANT_48, 4, 1, 0 },
{ QUANT_64, 6, 0, 0 },
{ QUANT_80, 4, 0, 1 },
{ QUANT_96, 5, 1, 0 },
{ QUANT_128, 7, 0, 0 },
{ QUANT_160, 5, 0, 1 },
{ QUANT_192, 6, 1, 0 },
{ QUANT_256, 8, 0, 0 }
}};
/**
* @brief The sequence scale, round, and divisors needed to compute sizing.
*
* The length of a quantized sequence in bits is:
* (scale * <sequence_len> + round) / divisor
*/
struct ise_size {
/**< The quantization level. */
uint8_t quant;
/**< The scaling parameter. */
uint8_t scale;
/**< The rounding parameter. */
uint8_t round;
/**< The divisor parameter. */
uint8_t divisor;
};
/**
* @brief The table of scale, round, and divisors needed for quant sizing.
*/
static const std::array<ise_size, 21> ise_sizes = {{
{ QUANT_2, 1, 0, 1 },
{ QUANT_3, 8, 4, 5 },
{ QUANT_4, 2, 0, 1 },
{ QUANT_5, 7, 2, 3 },
{ QUANT_6, 13, 4, 5 },
{ QUANT_8, 3, 0, 1 },
{ QUANT_10, 10, 2, 3 },
{ QUANT_12, 18, 4, 5 },
{ QUANT_16, 4, 0, 1 },
{ QUANT_20, 13, 2, 3 },
{ QUANT_24, 23, 4, 5 },
{ QUANT_32, 5, 0, 1 },
{ QUANT_40, 16, 2, 3 },
{ QUANT_48, 28, 4, 5 },
{ QUANT_64, 6, 0, 1 },
{ QUANT_80, 19, 2, 3 },
{ QUANT_96, 33, 4, 5 },
{ QUANT_128, 7, 0, 1 },
{ QUANT_160, 22, 2, 3 },
{ QUANT_192, 38, 4, 5 },
{ QUANT_256, 8, 0, 1 }
}};
/* See header for documentation. */
int get_ise_sequence_bitcount(
int items,
quant_method quant
) {
// Cope with out-of bounds values - input might be invalid
if (static_cast<size_t>(quant) >= ise_sizes.size())
{
// Arbitrary large number that's more than an ASTC block can hold
return 1024;
}
auto& entry = ise_sizes[quant];
return (entry.scale * items + entry.round) / entry.divisor;
}
// routine to write up to 8 bits
static inline void write_bits(
int value,
int bitcount,
int bitoffset,
uint8_t* ptr
) {
int mask = (1 << bitcount) - 1;
value &= mask;
ptr += bitoffset >> 3;
bitoffset &= 7;
value <<= bitoffset;
mask <<= bitoffset;
mask = ~mask;
ptr[0] &= mask;
ptr[0] |= value;
ptr[1] &= mask >> 8;
ptr[1] |= value >> 8;
}
// routine to read up to 8 bits
static inline int read_bits(
int bitcount,
int bitoffset,
const uint8_t* ptr
) {
int mask = (1 << bitcount) - 1;
ptr += bitoffset >> 3;
bitoffset &= 7;
int value = ptr[0] | (ptr[1] << 8);
value >>= bitoffset;
value &= mask;
return value;
}
void encode_ise(
int quant_level,
int elements,
const uint8_t* input_data,
uint8_t* output_data,
int bit_offset
) {
int bits = btq_counts[quant_level].bits;
int trits = btq_counts[quant_level].trits;
int quints = btq_counts[quant_level].quints;
int mask = (1 << bits) - 1;
// Write out trits and bits
if (trits)
{
int i = 0;
int full_trit_blocks = elements / 5;
for (int j = 0; j < full_trit_blocks; j++)
{
int i4 = input_data[i + 4] >> bits;
int i3 = input_data[i + 3] >> bits;
int i2 = input_data[i + 2] >> bits;
int i1 = input_data[i + 1] >> bits;
int i0 = input_data[i + 0] >> bits;
uint8_t T = integer_of_trits[i4][i3][i2][i1][i0];
// The max size of a trit bit count is 6, so we can always safely
// pack a single MX value with the following 1 or 2 T bits.
uint8_t pack;
// Element 0 + T0 + T1
pack = (input_data[i++] & mask) | (((T >> 0) & 0x3) << bits);
write_bits(pack, bits + 2, bit_offset, output_data);
bit_offset += bits + 2;
// Element 1 + T2 + T3
pack = (input_data[i++] & mask) | (((T >> 2) & 0x3) << bits);
write_bits(pack, bits + 2, bit_offset, output_data);
bit_offset += bits + 2;
// Element 2 + T4
pack = (input_data[i++] & mask) | (((T >> 4) & 0x1) << bits);
write_bits(pack, bits + 1, bit_offset, output_data);
bit_offset += bits + 1;
// Element 3 + T5 + T6
pack = (input_data[i++] & mask) | (((T >> 5) & 0x3) << bits);
write_bits(pack, bits + 2, bit_offset, output_data);
bit_offset += bits + 2;
// Element 4 + T7
pack = (input_data[i++] & mask) | (((T >> 7) & 0x1) << bits);
write_bits(pack, bits + 1, bit_offset, output_data);
bit_offset += bits + 1;
}
// Loop tail for a partial block
if (i != elements)
{
// i4 cannot be present - we know the block is partial
// i0 must be present - we know the block isn't empty
int i4 = 0;
int i3 = i + 3 >= elements ? 0 : input_data[i + 3] >> bits;
int i2 = i + 2 >= elements ? 0 : input_data[i + 2] >> bits;
int i1 = i + 1 >= elements ? 0 : input_data[i + 1] >> bits;
int i0 = input_data[i + 0] >> bits;
uint8_t T = integer_of_trits[i4][i3][i2][i1][i0];
for (int j = 0; i < elements; i++, j++)
{
// Truncated table as this iteration is always partital
static const uint8_t tbits[4] { 2, 2, 1, 2 };
static const uint8_t tshift[4] { 0, 2, 4, 5 };
uint8_t pack = (input_data[i] & mask) |
(((T >> tshift[j]) & ((1 << tbits[j]) - 1)) << bits);
write_bits(pack, bits + tbits[j], bit_offset, output_data);
bit_offset += bits + tbits[j];
}
}
}
// Write out quints and bits
else if (quints)
{
int i = 0;
int full_quint_blocks = elements / 3;
for (int j = 0; j < full_quint_blocks; j++)
{
int i2 = input_data[i + 2] >> bits;
int i1 = input_data[i + 1] >> bits;
int i0 = input_data[i + 0] >> bits;
uint8_t T = integer_of_quints[i2][i1][i0];
// The max size of a quint bit count is 5, so we can always safely
// pack a single M value with the following 2 or 3 T bits.
uint8_t pack;
// Element 0
pack = (input_data[i++] & mask) | (((T >> 0) & 0x7) << bits);
write_bits(pack, bits + 3, bit_offset, output_data);
bit_offset += bits + 3;
// Element 1
pack = (input_data[i++] & mask) | (((T >> 3) & 0x3) << bits);
write_bits(pack, bits + 2, bit_offset, output_data);
bit_offset += bits + 2;
// Element 2
pack = (input_data[i++] & mask) | (((T >> 5) & 0x3) << bits);
write_bits(pack, bits + 2, bit_offset, output_data);
bit_offset += bits + 2;
}
// Loop tail for a partial block
if (i != elements)
{
// i2 cannot be present - we know the block is partial
// i0 must be present - we know the block isn't empty
int i2 = 0;
int i1 = i + 1 >= elements ? 0 : input_data[i + 1] >> bits;
int i0 = input_data[i + 0] >> bits;
uint8_t T = integer_of_quints[i2][i1][i0];
for (int j = 0; i < elements; i++, j++)
{
// Truncated table as this iteration is always partital
static const uint8_t tbits[2] { 3, 2 };
static const uint8_t tshift[2] { 0, 3 };
uint8_t pack = (input_data[i] & mask) |
(((T >> tshift[j]) & ((1 << tbits[j]) - 1)) << bits);
write_bits(pack, bits + tbits[j], bit_offset, output_data);
bit_offset += bits + tbits[j];
}
}
}
// Write out just bits
else
{
promise(elements > 0);
for (int i = 0; i < elements; i++)
{
write_bits(input_data[i], bits, bit_offset, output_data);
bit_offset += bits;
}
}
}
void decode_ise(
int quant_level,
int elements,
const uint8_t* input_data,
uint8_t* output_data,
int bit_offset
) {
// note: due to how the trit/quint-block unpacking is done in this function,
// we may write more temporary results than the number of outputs
// The maximum actual number of results is 64 bit, but we keep 4 additional elements
// of padding.
uint8_t results[68];
uint8_t tq_blocks[22]; // trit-blocks or quint-blocks
int bits = btq_counts[quant_level].bits;
int trits = btq_counts[quant_level].trits;
int quints = btq_counts[quant_level].quints;
int lcounter = 0;
int hcounter = 0;
// trit-blocks or quint-blocks must be zeroed out before we collect them in the loop below.
for (int i = 0; i < 22; i++)
{
tq_blocks[i] = 0;
}
// collect bits for each element, as well as bits for any trit-blocks and quint-blocks.
for (int i = 0; i < elements; i++)
{
results[i] = read_bits(bits, bit_offset, input_data);
bit_offset += bits;
if (trits)
{
static const int bits_to_read[5] { 2, 2, 1, 2, 1 };
static const int block_shift[5] { 0, 2, 4, 5, 7 };
static const int next_lcounter[5] { 1, 2, 3, 4, 0 };
static const int hcounter_incr[5] { 0, 0, 0, 0, 1 };
int tdata = read_bits(bits_to_read[lcounter], bit_offset, input_data);
bit_offset += bits_to_read[lcounter];
tq_blocks[hcounter] |= tdata << block_shift[lcounter];
hcounter += hcounter_incr[lcounter];
lcounter = next_lcounter[lcounter];
}
if (quints)
{
static const int bits_to_read[3] { 3, 2, 2 };
static const int block_shift[3] { 0, 3, 5 };
static const int next_lcounter[3] { 1, 2, 0 };
static const int hcounter_incr[3] { 0, 0, 1 };
int tdata = read_bits(bits_to_read[lcounter], bit_offset, input_data);
bit_offset += bits_to_read[lcounter];
tq_blocks[hcounter] |= tdata << block_shift[lcounter];
hcounter += hcounter_incr[lcounter];
lcounter = next_lcounter[lcounter];
}
}
// unpack trit-blocks or quint-blocks as needed
if (trits)
{
int trit_blocks = (elements + 4) / 5;
for (int i = 0; i < trit_blocks; i++)
{
const uint8_t *tritptr = trits_of_integer[tq_blocks[i]];
results[5 * i ] |= tritptr[0] << bits;
results[5 * i + 1] |= tritptr[1] << bits;
results[5 * i + 2] |= tritptr[2] << bits;
results[5 * i + 3] |= tritptr[3] << bits;
results[5 * i + 4] |= tritptr[4] << bits;
}
}
if (quints)
{
int quint_blocks = (elements + 2) / 3;
for (int i = 0; i < quint_blocks; i++)
{
const uint8_t *quintptr = quints_of_integer[tq_blocks[i]];
results[3 * i ] |= quintptr[0] << bits;
results[3 * i + 1] |= quintptr[1] << bits;
results[3 * i + 2] |= quintptr[2] << bits;
}
}
for (int i = 0; i < elements; i++)
{
output_data[i] = results[i];
}
}
| 20,448 | 13,200 |
/**
* Copyright (C) 2016 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/pipeline/expression_context.h"
#include "mongo/db/pipeline/stub_mongo_process_interface.h"
#include "mongo/db/query/collation/collation_spec.h"
#include "mongo/db/query/collation/collator_factory_interface.h"
namespace mongo {
using boost::intrusive_ptr;
ExpressionContext::ResolvedNamespace::ResolvedNamespace(NamespaceString ns,
std::vector<BSONObj> pipeline)
: ns(std::move(ns)), pipeline(std::move(pipeline)) {}
ExpressionContext::ExpressionContext(OperationContext* opCtx,
const AggregationRequest& request,
std::unique_ptr<CollatorInterface> collator,
std::shared_ptr<MongoProcessInterface> processInterface,
StringMap<ResolvedNamespace> resolvedNamespaces)
: ExpressionContext(opCtx, collator.get()) {
explain = request.getExplain();
comment = request.getComment();
fromMongos = request.isFromMongos();
needsMerge = request.needsMerge();
allowDiskUse = request.shouldAllowDiskUse();
bypassDocumentValidation = request.shouldBypassDocumentValidation();
ns = request.getNamespaceString();
mongoProcessInterface = std::move(processInterface);
collation = request.getCollation();
_ownedCollator = std::move(collator);
_resolvedNamespaces = std::move(resolvedNamespaces);
}
ExpressionContext::ExpressionContext(OperationContext* opCtx, const CollatorInterface* collator)
: opCtx(opCtx),
mongoProcessInterface(std::make_shared<StubMongoProcessInterface>()),
timeZoneDatabase(opCtx && opCtx->getServiceContext()
? TimeZoneDatabase::get(opCtx->getServiceContext())
: nullptr),
variablesParseState(variables.useIdGenerator()),
_collator(collator),
_documentComparator(_collator),
_valueComparator(_collator) {}
ExpressionContext::ExpressionContext(NamespaceString nss,
std::shared_ptr<MongoProcessInterface> processInterface,
const TimeZoneDatabase* tzDb)
: ns(std::move(nss)),
mongoProcessInterface(std::move(processInterface)),
timeZoneDatabase(tzDb),
variablesParseState(variables.useIdGenerator()) {}
void ExpressionContext::checkForInterrupt() {
// This check could be expensive, at least in relative terms, so don't check every time.
if (--_interruptCounter == 0) {
invariant(opCtx);
_interruptCounter = kInterruptCheckPeriod;
opCtx->checkForInterrupt();
}
}
ExpressionContext::CollatorStash::CollatorStash(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
std::unique_ptr<CollatorInterface> newCollator)
: _expCtx(expCtx),
_originalCollation(_expCtx->collation),
_originalCollatorOwned(std::move(_expCtx->_ownedCollator)),
_originalCollatorUnowned(_expCtx->_collator) {
_expCtx->setCollator(std::move(newCollator));
_expCtx->collation =
_expCtx->getCollator() ? _expCtx->getCollator()->getSpec().toBSON().getOwned() : BSONObj();
}
ExpressionContext::CollatorStash::~CollatorStash() {
if (_originalCollatorOwned) {
_expCtx->setCollator(std::move(_originalCollatorOwned));
} else {
_expCtx->setCollator(_originalCollatorUnowned);
if (!_originalCollatorUnowned && _expCtx->_ownedCollator) {
// If the original collation was 'nullptr', we cannot distinguish whether it was owned
// or not. We always set '_ownedCollator' with the stash, so should reset it to null
// here.
_expCtx->_ownedCollator = nullptr;
}
}
_expCtx->collation = _originalCollation;
}
std::unique_ptr<ExpressionContext::CollatorStash> ExpressionContext::temporarilyChangeCollator(
std::unique_ptr<CollatorInterface> newCollator) {
// This constructor of CollatorStash is private, so we can't use make_unique().
return std::unique_ptr<CollatorStash>(new CollatorStash(this, std::move(newCollator)));
}
void ExpressionContext::setCollator(const CollatorInterface* collator) {
_collator = collator;
// Document/Value comparisons must be aware of the collation.
_documentComparator = DocumentComparator(_collator);
_valueComparator = ValueComparator(_collator);
}
intrusive_ptr<ExpressionContext> ExpressionContext::copyWith(
NamespaceString ns,
boost::optional<UUID> uuid,
boost::optional<std::unique_ptr<CollatorInterface>> collator) const {
intrusive_ptr<ExpressionContext> expCtx =
new ExpressionContext(std::move(ns), mongoProcessInterface, timeZoneDatabase);
expCtx->uuid = std::move(uuid);
expCtx->explain = explain;
expCtx->comment = comment;
expCtx->needsMerge = needsMerge;
expCtx->fromMongos = fromMongos;
expCtx->inMongos = inMongos;
expCtx->allowDiskUse = allowDiskUse;
expCtx->bypassDocumentValidation = bypassDocumentValidation;
expCtx->subPipelineDepth = subPipelineDepth;
expCtx->tempDir = tempDir;
expCtx->opCtx = opCtx;
if (collator) {
expCtx->collation =
*collator ? (*collator)->getSpec().toBSON() : CollationSpec::kSimpleSpec;
expCtx->setCollator(std::move(*collator));
} else {
expCtx->collation = collation;
if (_ownedCollator) {
expCtx->setCollator(_ownedCollator->clone());
} else if (_collator) {
expCtx->setCollator(_collator);
}
}
expCtx->_resolvedNamespaces = _resolvedNamespaces;
// Note that we intentionally skip copying the value of '_interruptCounter' because 'expCtx' is
// intended to be used for executing a separate aggregation pipeline.
return expCtx;
}
} // namespace mongo
| 7,402 | 2,125 |
// Copyright (c) 2021 Jeremy Linton
//
// big_vec.cpp
// C++ wrapper around the $PLAT_objs.cpp vector to extend its len
//
//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.
// To build some basic unit tests for this module do:
// g++ -mfloat-abi=softfp -mfpu=neon -g -O3 -std=c++11 big_vec.cpp
// or
// g++ -msse3 -g -O3 -std=c++11 big_vec.cpp
// AVXx8 version
// g++ -mavx -g -O3 -std=c++11 big_vec.cpp
#define NO_MAIN
#ifdef __ARM_NEON__
#include "neon_objs.cpp"
#elif defined(__SSE3__)
#include "sse_objs2.cpp"
#else
#include "portable_objs.cpp"
#endif
// big allocs might need something like -Wl,-z,stack-size=XXXX; ulimit -s XXXXX
// define arbitrary len vector in relation to HW vector class
//
#define VECS ((ELEM_CNT/VEC_CNT)?(ELEM_CNT/VEC_CNT):1)
template<int VEC_CNT, int ELEM_CNT, class VEC_T> class BigVector
{
public:
BigVector():vec() {}; //construct unititalized
BigVector(BigVector *src) { for (int x=0;x<VECS;x++) vec[x]=src->vec[x]; };
BigVector(BigVector &src) { for (int x=0;x<VECS;x++) vec[x]=src.vec[x]; };
BigVector(VEC_T *src,int src_cnt) { VEC_T tmp(0.0); for (int x=0;x<VECS;x++) vec[x]=tmp; for (int x=0;x<src_cnt;x++) vec[x]=src[x]; }; //allows a resize op
//BigVector(double *fill) {VEC_T tmp(fill); for (int x=0;x<VECS;x++) vec[x]=tmp;}
template <typename... Args> BigVector(Args... args) {VEC_T tmp(0.0); for (int x=0;x<VECS;x++) vec[x]=tmp; Set(0, args...); }; // if this aborts, verify vec is properly aligned (32 bytes for x8)
// POD copy construct
// assign
BigVector & operator=(const BigVector &src_prm) { for (int x=0;x<VECS;x++) vec[x]=src_prm.vec[x]; return *this;}
BigVector & operator=(const float src[ELEM_CNT]) { for (int x=0;x<ELEM_CNT;x++) vec[x/VEC_CNT].Set(x-(x/VEC_CNT)*VEC_CNT,src[x]); return *this;};
void Set(int off, float Val) {const int n=off/VEC_CNT; vec[n].Set(off-n*VEC_CNT, Val); }
void Fill(float Val) {VEC_T tmp(Val); for (int x=1;x<VEC_CNT;x++) tmp.Set(x,Val); for (int x=0;x<VECS;x++) vec[x]=tmp;}
template <typename... Args> void Set(int off, float Val, Args... args) { int n=off/VEC_CNT; vec[n].Set(off-n*VEC_CNT, Val); Set(++off,args...); };
// reads
float operator[](int index_prm) const {int n=index_prm/VEC_CNT; return vec[n][index_prm-n*VEC_CNT];};
//BigVector Get(int index_prm);
//void save(float *dst_prm) { };
std::string as_str(const char *format_prm="%05.2f ") { std::string fmt; for (int x=0;x<VEC_CNT;x++) fmt+=format_prm; std::string tmp; for (int x=0;x<VECS;x++) tmp+=vec[x].as_str(fmt.c_str()); return tmp; }
// adds urinary
BigVector & operator+=(const BigVector &src2) { for (int x=0;x<VECS;x++) vec[x]+=src2.vec[x]; return *this;}
BigVector & operator-=(const BigVector &src2) { for (int x=0;x<VECS;x++) vec[x]-=src2.vec[x]; return *this;}
BigVector & operator+=(const float src2) { for (int x=0;x<VECS;x++) vec[x]+=src2; return *this;}
BigVector & operator-=(const float src2) { for (int x=0;x<VECS;x++) vec[x]-=src2;; return *this;}
// adds binary
BigVector const operator+ (const BigVector &src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]+src2.vec[x]; return tmp;}
BigVector const operator- (const BigVector &src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]-src2.vec[x]; return tmp;}
BigVector const operator+ (const float src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]+src2; return tmp;}
BigVector const operator- (const float src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]-src2; return tmp;}
// muls urinary
BigVector & operator*=(const BigVector &src2) { for (int x=0;x<VECS;x++) vec[x]*src2.vec[x]; return *this;}
BigVector & operator/=(const BigVector &src2) { for (int x=0;x<VECS;x++) vec[x]/src2.vec[x]; return *this;}
BigVector & operator*=(const float src2) { for (int x=0;x<VECS;x++) vec[x]=vec[x]*src2; return *this;}
BigVector & operator/=(const float src2) { for (int x=0;x<VECS;x++) vec[x]=vec[x]/src2; return *this;}
// muls binary
BigVector const operator* (const BigVector &src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]*src2.vec[x]; return tmp;}
BigVector const operator/ (const BigVector &src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]/src2.vec[x]; return tmp;}
BigVector const operator* (const float src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]*src2; return tmp;}
BigVector const operator/ (const float src2) { BigVector tmp; for (int x=0;x<VECS;x++) tmp.vec[x]=vec[x]/src2; return tmp;}
// other manipulations
float ElementSum(void) const { float tmp=0; for (int x=0;x<VECS;x++) tmp+=vec[x].ElementSum(); return tmp; }
float fma(BigVector &src2) {return 0.0;}//implement fma (which requires the underlying vector to do it too)
VEC_T *raw() {return vec;}
int raw_sz() {return VECS;}
private:
VEC_T vec[VECS];
};
// square matrix based on big vecs above
// most of these loops should be expanded with openMP if the matrix sizes get sufficiently large
template<int SIZE, class VEC_T> class MatrixS
{
public:
MatrixS() {} //construct unititalized
MatrixS(float val) { VEC_T tmp; tmp.Fill(val); for (int x=0;x<SIZE;x++) vecs[x]=tmp; }
MatrixS(const MatrixS &orig) {for (int x=0; x<SIZE; x++) vecs[x]=orig.vecs[x]; }
// assign
//BigVector & operator=(const BigVector &src_prm) { for (int x=0;x<VECS;x++) vec[x]=src_prm.vec[x]; }
//BigVector & operator=(const float src[ELEM_CNT]) { for (int x=0;x<ELEM_CNT;x++) vec[x/VEC_CNT].Set(x-(x/VEC_CNT)*VEC_CNT,src[x]);};
void Set(int col, int row, float Val) { vecs[row].Set(col, Val); }
//template <typename... Args> void Set(int off, float Val, Args... args) { int n=off/VEC_CNT; vec[n].Set(off-n*VEC_CNT, Val); Set(++off,args...); };
// reads
VEC_T &operator[](int index_prm) {return vecs[index_prm];};
float Get(int row,int col) {return vecs[row][col];}
//void save(float *dst_prm) { };
std::string as_str(const char *format_prm="%05.2f,") { std::string ret; for (int x=0;x<SIZE;x++) ret+=vecs[x].as_str(format_prm)+";\n"; return ret; }
// adds urinary
MatrixS & operator+=(const MatrixS &src2) { for (int x=0;x<SIZE;x++) vecs[x]+=src2.vec[x]; return *this;}
MatrixS & operator-=(const MatrixS &src2) { for (int x=0;x<SIZE;x++) vecs[x]-=src2.vec[x]; return *this;}
MatrixS & operator+=(const float src2) { for (int x=0;x<SIZE;x++) vecs[x]+=src2; return *this;}
MatrixS & operator-=(const float src2) { for (int x=0;x<SIZE;x++) vecs[x]-=src2;; return *this;}
// muls urinary
MatrixS & operator*=(const MatrixS &src2)
{
MatrixS Trans(src2); //todo heap allocate if matrix is really large (or maybe do something requiring the caller to pre transpose it?, or just use the gather loads..
Trans.Transpose();
for (int x=0; x<SIZE; x++)
{
VEC_T result;
for (int y=0; y<SIZE; y++)
{
float val = (vecs[x] * Trans.vecs[y]).ElementSum();
result.Set(y, val);
}
vecs[x]=result;
}
return *this;
}
MatrixS & operator/=(const MatrixS &src2)
{
MatrixS Trans(src2);
Trans.Transpose();
for (int x=0; x<SIZE; x++)
{
VEC_T result;
for (int y=0; y<SIZE; y++)
{
float val = (vecs[x] / Trans.vecs[y]).ElementSum();
result.Set(y, val);
}
vecs[x]=result;
}
return *this;
}
VEC_T & operator*=(const VEC_T &src2) { VEC_T ret; for (int x=0;x<SIZE;x++) ret.Set(x,(vecs[x]*src2).ElementSum()); return *this;}
VEC_T & operator/=(const VEC_T &src2) { VEC_T ret; for (int x=0;x<SIZE;x++) ret.Set(x,(vecs[x]/src2).ElementSum()); return *this;} //probably should build inverse vec?
MatrixS & operator*=(const float src2) { for (int x=0;x<SIZE;x++) vecs[x]*=src2; return *this;}
MatrixS & operator/=(const float src2) { for (int x=0;x<SIZE;x++) vecs[x]/=src2;; return *this;}
//other ops
void Transpose() { for (int x=1;x<SIZE;x++) for (int y=0;y<x;y++) { float tmp=vecs[x][y]; vecs[x].Set(y,vecs[y][x]); vecs[y].Set(x,tmp); } } //do something smarter?
void det() {
MatrixS ret(0);
for (int i=0;i<SIZE;i++)
{
}
}
// inverse
private:
VEC_T vecs[SIZE];
};
// non square matrix based on big vecs above
// most of these loops should be expanded with openMP if the matrix sizes get sufficiently large
#ifdef __AVX__
template<int SIZE_ROW,int SIZE_COL, class VEC_TR = BigVector<8,SIZE_ROW,SSEx8>, class VEC_TC = BigVector<8,SIZE_COL,SSEx8>> class MatrixST
#else
template<int SIZE_ROW,int SIZE_COL, class VEC_TR = BigVector<4,SIZE_ROW,Vec4>, class VEC_TC = BigVector<4,SIZE_COL,Vec4>> class MatrixST
#endif
{
// typedef BigVector<4,SIZE_ROW,Vec4> VEC_TX;
public:
MatrixST() {} //construct unititalized
MatrixST(float val) { VEC_TR tmp; tmp.Fill(val); for (int y=0;y<SIZE_COL;y++) vecs[y]=tmp; }
MatrixST(const MatrixST &orig) {for (int y=0; y<SIZE_COL; y++) vecs[y]=orig.vecs[y]; }
// assign
//BigVector & operator=(const BigVector &src_prm) { for (int x=0;x<VECS;x++) vec[x]=src_prm.vec[x]; }
//BigVector & operator=(const float src[ELEM_CNT]) { for (int x=0;x<ELEM_CNT;x++) vec[x/VEC_CNT].Set(x-(x/VEC_CNT)*VEC_CNT,src[x]);};
void Set(int col, int row, float Val) { vecs[row].Set(col, Val); }
//template <typename... Args> void Set(int off, float Val, Args... args) { int n=off/VEC_CNT; vec[n].Set(off-n*VEC_CNT, Val); Set(++off,args...); };
// reads
VEC_TR &operator[](int index_prm) {return vecs[index_prm];};
float Get(int col,int row) {return vecs[row][col];}
//void save(float *dst_prm) { };
std::string as_str(const char *format_prm="%05.2f,") { std::string ret; for (int x=0;x<SIZE_COL;x++) ret+=vecs[x].as_str(format_prm)+";\n"; return ret; }
// adds urinary
MatrixST & operator+=(const MatrixST &src2) { for (int y=0;y<SIZE_COL;y++) vecs[y]+=src2.vec[y]; return *this;}
MatrixST & operator-=(const MatrixST &src2) { for (int y=0;y<SIZE_COL;y++) vecs[y]-=src2.vec[y]; return *this;}
MatrixST & operator+=(const float src2) { for (int y=0;y<SIZE_COL;y++) vecs[y]+=src2; return *this;}
MatrixST & operator-=(const float src2) { for (int y=0;y<SIZE_COL;y++) vecs[y]-=src2;; return *this;}
// muls urinary (can't change the dimensions, so this only works when the result doesn't change dimensions)
template<int S2_ROW,int S2_COL, class S2_VR,class S2_VC>
MatrixST<SIZE_ROW, S2_COL, VEC_TR, S2_VC> & operator*=(const MatrixST<S2_ROW, S2_COL, S2_VR, S2_VC> &src2)
{
//MatrixST<SIZE_COL,SIZE_ROW, VEC_TC, VEC_TR> Trans(src2); //todo heap allocate if matrix is really large (or maybe do something requiring the caller to pre transpose it?, or just use the gather loads..
MatrixST<S2_COL, S2_ROW, S2_VC, S2_VR> Trans=src2.Transpose();
for (int x=0; x<SIZE_ROW; x++)
{
VEC_TR result;
for (int y=0; y<S2_COL; y++)
{
float val = (vecs[x] * Trans.vecs[y]).ElementSum();
result.Set(y, val);
}
vecs[x]=result;
}
return *this;
}
// muls binary, because it returns a type it can be used to change the dimensions
template<int S2_ROW,int S2_COL, class S2_VR,class S2_VC>
MatrixST<SIZE_COL, S2_ROW, VEC_TC, S2_VR> operator*(const MatrixST<S2_ROW, S2_COL, S2_VR, S2_VC> &src2)
{
//MatrixST<SIZE_COL,SIZE_ROW, VEC_TC, VEC_TR> Trans(src2); //todo heap allocate if matrix is really large (or maybe do something requiring the caller to pre transpose it?, or just use the gather loads..
MatrixST<S2_COL, S2_ROW, S2_VC, S2_VR> Trans=src2.Transpose();
MatrixST<SIZE_COL, S2_ROW, VEC_TC, S2_VR> ret(0);
for (int x=0; x<SIZE_COL; x++)
{
VEC_TC result;
for (int y=0; y<S2_ROW; y++)
{
float val = (vecs[x] * Trans.vecs[y]).ElementSum();
result.Set(y, val);
}
ret[x]=result;
}
return ret;
}
// version of above with the src pre-transposed
// template<int S2_ROW,int S2_COL, class S2_VR,class S2_VC>
// MatrixST<SIZE_COL, S2_ROW, VEC_TC, S2_VR> MultNoTrans(const MatrixST<S2_ROW, S2_COL, S2_VR, S2_VC> &src2)
VEC_TR & operator*=(const VEC_TR &src2) { VEC_TR ret; for (int y=0;y<SIZE_ROW;y++) ret.Set(y,(vecs[y]*src2).ElementSum()); return *this;}
VEC_TR & operator/=(const VEC_TR &src2) { VEC_TR ret; for (int y=0;y<SIZE_ROW;y++) ret.Set(y,(vecs[y]/src2).ElementSum()); return *this;} //probably should build inverse vec?
MatrixST & operator*=(const float src2) { for (int y=0;y<SIZE_ROW;y++) vecs[y]*=src2; return *this;}
MatrixST & operator/=(const float src2) { for (int y=0;y<SIZE_ROW;y++) vecs[y]/=src2;; return *this;}
//other ops
// must return transposed matrix because m X n becomes n X m
MatrixST<SIZE_COL,SIZE_ROW, VEC_TC, VEC_TR> Transpose() const
{
MatrixST<SIZE_COL,SIZE_ROW, VEC_TC, VEC_TR> ret;
for (int y=0;y<SIZE_ROW;y++)
{
for (int x=0;x<SIZE_COL;x++)
{
ret.Set(x, y, vecs[x][y]);
}
}
return ret; //should be move?!
} //do something smarter?
//void ITranspose() { for (int x=1;x<SIZE;x++) for (int y=0;y<=x;y++) { float tmp=vecs[x][y]; vecs[x].Set(y,1.0/vecs[y][x]); vecs[y].Set(x,1.0/tmp); } } //do something smarter?
MatrixST LU(void)
{
MatrixST U(0),L(0);
if (SIZE_ROW != SIZE_COL)
{
throw "can't deal with non square matrix";
}
for (int i=0;i<SIZE_COL;i++)
{
//U[i][i] = 1.0;
U.Set(i,i,1.0);
}
for (int j=0;j<SIZE_COL;j++)
{
for (int y=j;y<SIZE_COL;y++)
{
float sum = 0;
for (int k=0;k<j;k++)
{
sum += L[y][k] * U[k][j];
}
L.Set(j,y,vecs[y][j]-sum);
//printf("L:\n%s\n", L.as_str().c_str());
}
for (int i=j;i<SIZE_COL;i++)
{
float sum = 0;
for (int k=0;k<j;k++)
{
sum += L[j][k] * U[k][i];
}
if (L[j][j]== 0.0) L.Set(j,j,0.0000001);
U.Set(i,j,(vecs[j][i]-sum)/L[j][j]);
}
}
printf("L:\n%s\n", L.as_str().c_str());
printf("U:\n%s\n", U.as_str().c_str());
return L;
}
float Det(void)
{
MatrixST L=LU();
float det = L[0][0];//*U[0][0];
for (int i=1;i<SIZE_COL;i++)
{
det *= L[i][i];
// det *= U[i][i];
}
printf("Det:%f\n", det);
return det;
}
private:
VEC_TR vecs[SIZE_COL]; //number of rows
};
template<int A,int B,class C,class D,int SA,int SB,class SC,class SD,template<int ,int ,class ,class > class T1, template<int ,int ,class ,class > class T2>void muls(T1<A,B,C,D> &s1, T2<SA,SB,SC,SD> &s)
{
MatrixST<A,SB,C,SD> tmp(0);
printf("new big vec (%d,%d):(%d,%d):\n%s\n", A,B,SA,SB,tmp.as_str().c_str());
}
#ifdef __AVX__
typedef BigVector<8,8,SSEx8> Vec8;
typedef BigVector<8,16,SSEx8> Vec16;
typedef BigVector<8,32,SSEx8> Vec32;
typedef BigVector<8,64,SSEx8> Vec64;
typedef BigVector<8,4096,SSEx8> Vec4k;
#else
typedef BigVector<4,8,Vec4> Vec8;
typedef BigVector<4,16,Vec4> Vec16;
typedef BigVector<4,32,Vec4> Vec32;
typedef BigVector<4,64,Vec4> Vec64;
typedef BigVector<4,4096,Vec4> Vec4k;
#endif
// recursive template calls? sure why not. This breaks the raw() import method (and printing)..
typedef BigVector<64,128,Vec64> Vec128;
#include <memory>
int main(int argv,char *argc[])
{
Vec8 x8vec(0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0);
Vec8 x8vec2;
x8vec2.Fill(1.0);
Vec16 x16vec(0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0);
Vec128 x128vec(0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0);
printf(" big vec %s\n", x8vec.as_str().c_str());
x8vec+=10;
printf("+10 big vec %s\n", x8vec.as_str().c_str());
x8vec/=2;
printf("/2 big vec %s\n", x8vec.as_str().c_str());
x8vec+=x8vec;
printf("*2 big vec %s\n", x8vec.as_str().c_str());
x8vec+=x8vec2;
printf("+1 big vec %s\n", x8vec.as_str().c_str());
printf("\nbig vec %s\n", x16vec.as_str().c_str());
x16vec+=Vec16(x8vec.raw(), x8vec.raw_sz());
printf("big vec %s\n", x16vec.as_str().c_str());
//printf("\nbig vec %s\n", x128vec.as_str().c_str());
//std::unique_ptr<Vec4k> x4kvec=std::make_unique<Vec4096>();
Vec4k *x4kvec=new Vec4k(0.0);
*x4kvec+=6.5;
printf("\nbig vec %s\n", x4kvec->as_str().c_str());
delete x4kvec;
MatrixS<8,Vec8> x8Mat(1);
for (int x=0;x<8;x++) x8Mat.Set(x,x,float(x));
for (int x=0;x<8;x++) x8Mat.Set(0,x,float(x));
printf("\nbig mat:\n%s\n", x8Mat.as_str().c_str());
MatrixS<8,Vec8> x8Mat2(x8Mat);
x8Mat2.Transpose();
printf("big mat:\n%s\n", x8Mat2.as_str().c_str());
x8Mat2*=x8Mat;
printf("big mat:\n%s\n", x8Mat2.as_str().c_str());
/* not computed correctly yet because we want to calc inverse (and det()) first
x8Mat2/=x8Mat;
printf("big mat:\n%s\n", x8Mat2.as_str().c_str());*/
// square version, validate against above.
MatrixST<8,8,Vec8,Vec8> x8nsMat(1);
for (int x=0;x<8;x++) x8nsMat.Set(x,x,float(x));
for (int x=0;x<8;x++) x8nsMat.Set(0,x,float(x));
printf("\nbig matv:\n%s\n", x8nsMat.as_str().c_str());
MatrixST<8,8,Vec8,Vec8> x8nsMat2(x8nsMat.Transpose());
printf("big matv:\n%s\n", x8nsMat2.as_str().c_str());
x8nsMat2*=x8nsMat;
printf("big matv:\n%s\n", x8nsMat2.as_str().c_str());
// nonsquare version (with default prms)
MatrixST<16,8> x8nsMat3(0);
for (int x=0;x<8;x++) { x8nsMat3.Set(x,x,float(x)); x8nsMat3.Set(x+8,x,float(x));}
for (int x=0;x<8;x++) x8nsMat3.Set(0,x,float(x));
printf("big mat:\n%s\n", x8nsMat3.as_str().c_str());
MatrixST<8,16> x8nsMat4(x8nsMat3.Transpose());
// auto x8nsMat4(x8nsMat3.Transpose()); // this works?!!
printf("big mat:\n%s\n", x8nsMat4.as_str().c_str());
auto x8nsMat5 = x8nsMat4 * x8nsMat3;
printf("big mat:\n%s\n", x8nsMat5.as_str().c_str());
auto x8nsMat6 = x8nsMat3 * x8nsMat4;
printf("big mat:\n%s\n", x8nsMat6.as_str().c_str());
//x8nsMat6.LU();
//x8nsMat2.LU();
x8nsMat2.Det();
MatrixST<2,2> x2Mat(1);
printf("small mat:\n%s\n", x2Mat.as_str().c_str());
MatrixST<8,8> x2Mat2(1);
printf("small mat:\n%s\n", x2Mat2.as_str().c_str());
x2Mat2.LU();
// x8nsMat4 *= x8nsMat3; //could one get away with changing the type? lol!
// printf("big mat:\n%s\n", x8nsMat4.as_str().c_str());
// this will eat all your stack! lol
// MatrixST<4096,4096> x8nsMat7(1);
// printf("big mat:\n%s\n", x8nsMat7.as_str().c_str());
// muls(x8nsMat3,x8nsMat2);
}
| 18,661 | 8,504 |
#include "List.h"
#include <iostream>
Node *prepareNewNode(const int array[][2]) {
Node *tmp = new Node();
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
tmp->data[i][j] = array[i][j];
}
}
tmp->next = nullptr;
return tmp;
}
void prepare(List *list) {
list->head = nullptr;
list->tail = nullptr;
}
void prepare(List *to, const List *from) {
Node *tmp = from->head;
while(tmp != nullptr) {
add(to, tmp->data);
tmp = tmp->next;
}
}
void add(List *list, int array[][2]) {
if(empty(list)) {
list->head = list->tail = prepareNewNode(array);
} else {
list->tail->next = prepareNewNode(array);
list->tail = list->tail->next;
}
}
bool empty(const List *list) {
return list->head == nullptr;
}
void print(const List *list) {
for(int i = 0; i < 2; i++) {
Node *tmp = list->head;
while(tmp != nullptr) {
for(int j = 0; j < 2; j++) {
std::cout << tmp->data[i][j] << " ";
}
std::cout << " ";
tmp = tmp->next;
}
std::cout << std::endl;
}
}
void clear(List *list) {
Node *tmp = list->head;
Node *toDelete;
while(tmp != nullptr) {
toDelete = tmp;
tmp = tmp->next;
delete toDelete;
}
list->head = list->tail = nullptr;
}
| 1,403 | 505 |
/*=========================================================================
Program: ParaView
Module: $RCSfile$
Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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 "vtkSMClientDeliverySource.h"
#include "vtkDataObject.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkSMClientDeliverySource, "$Revision$");
vtkStandardNewMacro(vtkSMClientDeliverySource);
// Construct programmable filter with empty execute method.
vtkSMClientDeliverySource::vtkSMClientDeliverySource() :
DeliveryProxy(0)
{
this->SetNumberOfInputPorts(0);
}
vtkSMClientDeliverySource::~vtkSMClientDeliverySource()
{
this->SetDeliveryProxy(0);
}
int vtkSMClientDeliverySource::RequestData(
vtkInformation*,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
// Just update the delivery proxy and copy it to the output.
this->DeliveryProxy->Update();
vtkDataObject* input = this->DeliveryProxy->GetOutput();
vtkDataObject* output = outputVector->GetInformationObject(0)->
Get(vtkDataObject::DATA_OBJECT());
output->ShallowCopy(input);
return 1;
}
int vtkSMClientDeliverySource::RequestDataObject(
vtkInformation*,
vtkInformationVector**,
vtkInformationVector* outputVector)
{
if (!this->DeliveryProxy)
{
vtkErrorMacro("Delivery proxy must be set before update.");
}
// Make the algorithm's output type match the proxy's output.
this->DeliveryProxy->Update();
vtkDataObject* input = this->DeliveryProxy->GetOutput();
vtkInformation* info = outputVector->GetInformationObject(0);
vtkDataObject* output = info->Get(vtkDataObject::DATA_OBJECT());
if (!output || output->GetDataObjectType() != input->GetDataObjectType())
{
output = input->NewInstance();
output->SetPipelineInformation(info);
output->Delete();
this->GetOutputPortInformation(0)->Set(
vtkDataObject::DATA_EXTENT_TYPE(), output->GetExtentType());
}
return 1;
}
void vtkSMClientDeliverySource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
| 3,292 | 1,120 |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "BufferPoolClient"
//#define LOG_NDEBUG 0
#include <thread>
#include <utils/Log.h>
#include "BufferPoolClient.h"
#include "Connection.h"
namespace android {
namespace hardware {
namespace media {
namespace bufferpool {
namespace V1_0 {
namespace implementation {
static constexpr int64_t kReceiveTimeoutUs = 1000000; // 100ms
static constexpr int kPostMaxRetry = 3;
static constexpr int kCacheTtlUs = 1000000; // TODO: tune
class BufferPoolClient::Impl
: public std::enable_shared_from_this<BufferPoolClient::Impl> {
public:
explicit Impl(const sp<Accessor> &accessor);
explicit Impl(const sp<IAccessor> &accessor);
bool isValid() {
return mValid;
}
bool isLocal() {
return mValid && mLocal;
}
ConnectionId getConnectionId() {
return mConnectionId;
}
sp<IAccessor> &getAccessor() {
return mAccessor;
}
bool isActive(int64_t *lastTransactionUs, bool clearCache);
ResultStatus allocate(const std::vector<uint8_t> ¶ms,
native_handle_t **handle,
std::shared_ptr<BufferPoolData> *buffer);
ResultStatus receive(
TransactionId transactionId, BufferId bufferId,
int64_t timestampUs,
native_handle_t **handle, std::shared_ptr<BufferPoolData> *buffer);
void postBufferRelease(BufferId bufferId);
bool postSend(
BufferId bufferId, ConnectionId receiver,
TransactionId *transactionId, int64_t *timestampUs);
private:
bool postReceive(
BufferId bufferId, TransactionId transactionId,
int64_t timestampUs);
bool postReceiveResult(
BufferId bufferId, TransactionId transactionId, bool result, bool *needsSync);
void trySyncFromRemote();
bool syncReleased();
void evictCaches(bool clearCache = false);
ResultStatus allocateBufferHandle(
const std::vector<uint8_t>& params, BufferId *bufferId,
native_handle_t **handle);
ResultStatus fetchBufferHandle(
TransactionId transactionId, BufferId bufferId,
native_handle_t **handle);
struct BlockPoolDataDtor;
struct ClientBuffer;
bool mLocal;
bool mValid;
sp<IAccessor> mAccessor;
sp<Connection> mLocalConnection;
sp<IConnection> mRemoteConnection;
uint32_t mSeqId;
ConnectionId mConnectionId;
int64_t mLastEvictCacheUs;
// CachedBuffers
struct BufferCache {
std::mutex mLock;
bool mCreating;
std::condition_variable mCreateCv;
std::map<BufferId, std::unique_ptr<ClientBuffer>> mBuffers;
int mActive;
int64_t mLastChangeUs;
BufferCache() : mCreating(false), mActive(0), mLastChangeUs(getTimestampNow()) {}
void incActive_l() {
++mActive;
mLastChangeUs = getTimestampNow();
}
void decActive_l() {
--mActive;
mLastChangeUs = getTimestampNow();
}
} mCache;
// FMQ - release notifier
struct {
std::mutex mLock;
// TODO: use only one list?(using one list may dealy sending messages?)
std::list<BufferId> mReleasingIds;
std::list<BufferId> mReleasedIds;
std::unique_ptr<BufferStatusChannel> mStatusChannel;
} mReleasing;
// This lock is held during synchronization from remote side.
// In order to minimize remote calls and locking durtaion, this lock is held
// by best effort approach using try_lock().
std::mutex mRemoteSyncLock;
};
struct BufferPoolClient::Impl::BlockPoolDataDtor {
BlockPoolDataDtor(const std::shared_ptr<BufferPoolClient::Impl> &impl)
: mImpl(impl) {}
void operator()(BufferPoolData *buffer) {
BufferId id = buffer->mId;
delete buffer;
auto impl = mImpl.lock();
if (impl && impl->isValid()) {
impl->postBufferRelease(id);
}
}
const std::weak_ptr<BufferPoolClient::Impl> mImpl;
};
struct BufferPoolClient::Impl::ClientBuffer {
private:
bool mInvalidated; // TODO: implement
int64_t mExpireUs;
bool mHasCache;
ConnectionId mConnectionId;
BufferId mId;
native_handle_t *mHandle;
std::weak_ptr<BufferPoolData> mCache;
void updateExpire() {
mExpireUs = getTimestampNow() + kCacheTtlUs;
}
public:
ClientBuffer(
ConnectionId connectionId, BufferId id, native_handle_t *handle)
: mInvalidated(false), mHasCache(false),
mConnectionId(connectionId), mId(id), mHandle(handle) {
(void)mInvalidated;
mExpireUs = getTimestampNow() + kCacheTtlUs;
}
~ClientBuffer() {
if (mHandle) {
native_handle_close(mHandle);
native_handle_delete(mHandle);
}
}
bool expire() const {
int64_t now = getTimestampNow();
return now >= mExpireUs;
}
bool hasCache() const {
return mHasCache;
}
std::shared_ptr<BufferPoolData> fetchCache(native_handle_t **pHandle) {
if (mHasCache) {
std::shared_ptr<BufferPoolData> cache = mCache.lock();
if (cache) {
*pHandle = mHandle;
}
return cache;
}
return nullptr;
}
std::shared_ptr<BufferPoolData> createCache(
const std::shared_ptr<BufferPoolClient::Impl> &impl,
native_handle_t **pHandle) {
if (!mHasCache) {
// Allocates a raw ptr in order to avoid sending #postBufferRelease
// from deleter, in case of native_handle_clone failure.
BufferPoolData *ptr = new BufferPoolData(mConnectionId, mId);
if (ptr) {
std::shared_ptr<BufferPoolData> cache(ptr, BlockPoolDataDtor(impl));
if (cache) {
mCache = cache;
mHasCache = true;
*pHandle = mHandle;
return cache;
}
}
if (ptr) {
delete ptr;
}
}
return nullptr;
}
bool onCacheRelease() {
if (mHasCache) {
// TODO: verify mCache is not valid;
updateExpire();
mHasCache = false;
return true;
}
return false;
}
};
BufferPoolClient::Impl::Impl(const sp<Accessor> &accessor)
: mLocal(true), mValid(false), mAccessor(accessor), mSeqId(0),
mLastEvictCacheUs(getTimestampNow()) {
const QueueDescriptor *fmqDesc;
ResultStatus status = accessor->connect(
&mLocalConnection, &mConnectionId, &fmqDesc, true);
if (status == ResultStatus::OK) {
mReleasing.mStatusChannel =
std::make_unique<BufferStatusChannel>(*fmqDesc);
mValid = mReleasing.mStatusChannel &&
mReleasing.mStatusChannel->isValid();
}
}
BufferPoolClient::Impl::Impl(const sp<IAccessor> &accessor)
: mLocal(false), mValid(false), mAccessor(accessor), mSeqId(0),
mLastEvictCacheUs(getTimestampNow()) {
bool valid = false;
sp<IConnection>& outConnection = mRemoteConnection;
ConnectionId& id = mConnectionId;
std::unique_ptr<BufferStatusChannel>& outChannel =
mReleasing.mStatusChannel;
Return<void> transResult = accessor->connect(
[&valid, &outConnection, &id, &outChannel]
(ResultStatus status, sp<IConnection> connection,
ConnectionId connectionId, const QueueDescriptor& desc) {
if (status == ResultStatus::OK) {
outConnection = connection;
id = connectionId;
outChannel = std::make_unique<BufferStatusChannel>(desc);
if (outChannel && outChannel->isValid()) {
valid = true;
}
}
});
mValid = transResult.isOk() && valid;
}
bool BufferPoolClient::Impl::isActive(int64_t *lastTransactionUs, bool clearCache) {
bool active = false;
{
std::lock_guard<std::mutex> lock(mCache.mLock);
syncReleased();
evictCaches(clearCache);
*lastTransactionUs = mCache.mLastChangeUs;
active = mCache.mActive > 0;
}
if (mValid && mLocal && mLocalConnection) {
mLocalConnection->cleanUp(clearCache);
return true;
}
return active;
}
ResultStatus BufferPoolClient::Impl::allocate(
const std::vector<uint8_t> ¶ms,
native_handle_t **pHandle,
std::shared_ptr<BufferPoolData> *buffer) {
if (!mLocal || !mLocalConnection || !mValid) {
return ResultStatus::CRITICAL_ERROR;
}
BufferId bufferId;
native_handle_t *handle = nullptr;
buffer->reset();
ResultStatus status = allocateBufferHandle(params, &bufferId, &handle);
if (status == ResultStatus::OK) {
if (handle) {
std::unique_lock<std::mutex> lock(mCache.mLock);
syncReleased();
evictCaches();
auto cacheIt = mCache.mBuffers.find(bufferId);
if (cacheIt != mCache.mBuffers.end()) {
// TODO: verify it is recycled. (not having active ref)
mCache.mBuffers.erase(cacheIt);
}
auto clientBuffer = std::make_unique<ClientBuffer>(
mConnectionId, bufferId, handle);
if (clientBuffer) {
auto result = mCache.mBuffers.insert(std::make_pair(
bufferId, std::move(clientBuffer)));
if (result.second) {
*buffer = result.first->second->createCache(
shared_from_this(), pHandle);
if (*buffer) {
mCache.incActive_l();
}
}
}
}
if (!*buffer) {
ALOGV("client cache creation failure %d: %lld",
handle != nullptr, (long long)mConnectionId);
status = ResultStatus::NO_MEMORY;
postBufferRelease(bufferId);
}
}
return status;
}
ResultStatus BufferPoolClient::Impl::receive(
TransactionId transactionId, BufferId bufferId, int64_t timestampUs,
native_handle_t **pHandle,
std::shared_ptr<BufferPoolData> *buffer) {
if (!mValid) {
return ResultStatus::CRITICAL_ERROR;
}
if (timestampUs != 0) {
timestampUs += kReceiveTimeoutUs;
}
if (!postReceive(bufferId, transactionId, timestampUs)) {
return ResultStatus::CRITICAL_ERROR;
}
ResultStatus status = ResultStatus::CRITICAL_ERROR;
buffer->reset();
while(1) {
std::unique_lock<std::mutex> lock(mCache.mLock);
syncReleased();
evictCaches();
auto cacheIt = mCache.mBuffers.find(bufferId);
if (cacheIt != mCache.mBuffers.end()) {
if (cacheIt->second->hasCache()) {
*buffer = cacheIt->second->fetchCache(pHandle);
if (!*buffer) {
// check transfer time_out
lock.unlock();
std::this_thread::yield();
continue;
}
ALOGV("client receive from reference %lld", (long long)mConnectionId);
break;
} else {
*buffer = cacheIt->second->createCache(shared_from_this(), pHandle);
if (*buffer) {
mCache.incActive_l();
}
ALOGV("client receive from cache %lld", (long long)mConnectionId);
break;
}
} else {
if (!mCache.mCreating) {
mCache.mCreating = true;
lock.unlock();
native_handle_t* handle = nullptr;
status = fetchBufferHandle(transactionId, bufferId, &handle);
lock.lock();
if (status == ResultStatus::OK) {
if (handle) {
auto clientBuffer = std::make_unique<ClientBuffer>(
mConnectionId, bufferId, handle);
if (clientBuffer) {
auto result = mCache.mBuffers.insert(
std::make_pair(bufferId, std::move(
clientBuffer)));
if (result.second) {
*buffer = result.first->second->createCache(
shared_from_this(), pHandle);
if (*buffer) {
mCache.incActive_l();
}
}
}
}
if (!*buffer) {
status = ResultStatus::NO_MEMORY;
}
}
mCache.mCreating = false;
lock.unlock();
mCache.mCreateCv.notify_all();
break;
}
mCache.mCreateCv.wait(lock);
}
}
bool needsSync = false;
bool posted = postReceiveResult(bufferId, transactionId,
*buffer ? true : false, &needsSync);
ALOGV("client receive %lld - %u : %s (%d)", (long long)mConnectionId, bufferId,
*buffer ? "ok" : "fail", posted);
if (mValid && mLocal && mLocalConnection) {
mLocalConnection->cleanUp(false);
}
if (needsSync && mRemoteConnection) {
trySyncFromRemote();
}
if (*buffer) {
if (!posted) {
buffer->reset();
return ResultStatus::CRITICAL_ERROR;
}
return ResultStatus::OK;
}
return status;
}
void BufferPoolClient::Impl::postBufferRelease(BufferId bufferId) {
std::lock_guard<std::mutex> lock(mReleasing.mLock);
mReleasing.mReleasingIds.push_back(bufferId);
mReleasing.mStatusChannel->postBufferRelease(
mConnectionId, mReleasing.mReleasingIds, mReleasing.mReleasedIds);
}
// TODO: revise ad-hoc posting data structure
bool BufferPoolClient::Impl::postSend(
BufferId bufferId, ConnectionId receiver,
TransactionId *transactionId, int64_t *timestampUs) {
bool ret = false;
bool needsSync = false;
{
std::lock_guard<std::mutex> lock(mReleasing.mLock);
*timestampUs = getTimestampNow();
*transactionId = (mConnectionId << 32) | mSeqId++;
// TODO: retry, add timeout, target?
ret = mReleasing.mStatusChannel->postBufferStatusMessage(
*transactionId, bufferId, BufferStatus::TRANSFER_TO, mConnectionId,
receiver, mReleasing.mReleasingIds, mReleasing.mReleasedIds);
needsSync = !mLocal && mReleasing.mStatusChannel->needsSync();
}
if (mValid && mLocal && mLocalConnection) {
mLocalConnection->cleanUp(false);
}
if (needsSync && mRemoteConnection) {
trySyncFromRemote();
}
return ret;
}
bool BufferPoolClient::Impl::postReceive(
BufferId bufferId, TransactionId transactionId, int64_t timestampUs) {
for (int i = 0; i < kPostMaxRetry; ++i) {
std::unique_lock<std::mutex> lock(mReleasing.mLock);
int64_t now = getTimestampNow();
if (timestampUs == 0 || now < timestampUs) {
bool result = mReleasing.mStatusChannel->postBufferStatusMessage(
transactionId, bufferId, BufferStatus::TRANSFER_FROM,
mConnectionId, -1, mReleasing.mReleasingIds,
mReleasing.mReleasedIds);
if (result) {
return true;
}
lock.unlock();
std::this_thread::yield();
} else {
mReleasing.mStatusChannel->postBufferStatusMessage(
transactionId, bufferId, BufferStatus::TRANSFER_TIMEOUT,
mConnectionId, -1, mReleasing.mReleasingIds,
mReleasing.mReleasedIds);
return false;
}
}
return false;
}
bool BufferPoolClient::Impl::postReceiveResult(
BufferId bufferId, TransactionId transactionId, bool result, bool *needsSync) {
std::lock_guard<std::mutex> lock(mReleasing.mLock);
// TODO: retry, add timeout
bool ret = mReleasing.mStatusChannel->postBufferStatusMessage(
transactionId, bufferId,
result ? BufferStatus::TRANSFER_OK : BufferStatus::TRANSFER_ERROR,
mConnectionId, -1, mReleasing.mReleasingIds,
mReleasing.mReleasedIds);
*needsSync = !mLocal && mReleasing.mStatusChannel->needsSync();
return ret;
}
void BufferPoolClient::Impl::trySyncFromRemote() {
if (mRemoteSyncLock.try_lock()) {
bool needsSync = false;
{
std::lock_guard<std::mutex> lock(mReleasing.mLock);
needsSync = mReleasing.mStatusChannel->needsSync();
}
if (needsSync) {
TransactionId transactionId = (mConnectionId << 32);
BufferId bufferId = Connection::SYNC_BUFFERID;
Return<void> transResult = mRemoteConnection->fetch(
transactionId, bufferId,
[]
(ResultStatus outStatus, Buffer outBuffer) {
(void) outStatus;
(void) outBuffer;
});
if(!transResult.isOk()) {
ALOGD("sync from client %lld failed: bufferpool process died.",
(long long)mConnectionId);
}
}
mRemoteSyncLock.unlock();
}
}
// should have mCache.mLock
bool BufferPoolClient::Impl::syncReleased() {
std::lock_guard<std::mutex> lock(mReleasing.mLock);
if (mReleasing.mReleasingIds.size() > 0) {
mReleasing.mStatusChannel->postBufferRelease(
mConnectionId, mReleasing.mReleasingIds,
mReleasing.mReleasedIds);
}
if (mReleasing.mReleasedIds.size() > 0) {
for (BufferId& id: mReleasing.mReleasedIds) {
ALOGV("client release buffer %lld - %u", (long long)mConnectionId, id);
auto found = mCache.mBuffers.find(id);
if (found != mCache.mBuffers.end()) {
if (found->second->onCacheRelease()) {
mCache.decActive_l();
} else {
// should not happen!
ALOGW("client %lld cache release status inconsitent!",
(long long)mConnectionId);
}
} else {
// should not happen!
ALOGW("client %lld cache status inconsitent!", (long long)mConnectionId);
}
}
mReleasing.mReleasedIds.clear();
return true;
}
return false;
}
// should have mCache.mLock
void BufferPoolClient::Impl::evictCaches(bool clearCache) {
int64_t now = getTimestampNow();
if (now >= mLastEvictCacheUs + kCacheTtlUs || clearCache) {
size_t evicted = 0;
for (auto it = mCache.mBuffers.begin(); it != mCache.mBuffers.end();) {
if (!it->second->hasCache() && (it->second->expire() || clearCache)) {
it = mCache.mBuffers.erase(it);
++evicted;
} else {
++it;
}
}
ALOGV("cache count %lld : total %zu, active %d, evicted %zu",
(long long)mConnectionId, mCache.mBuffers.size(), mCache.mActive, evicted);
mLastEvictCacheUs = now;
}
}
ResultStatus BufferPoolClient::Impl::allocateBufferHandle(
const std::vector<uint8_t>& params, BufferId *bufferId,
native_handle_t** handle) {
if (mLocalConnection) {
const native_handle_t* allocHandle = nullptr;
ResultStatus status = mLocalConnection->allocate(
params, bufferId, &allocHandle);
if (status == ResultStatus::OK) {
*handle = native_handle_clone(allocHandle);
}
ALOGV("client allocate result %lld %d : %u clone %p",
(long long)mConnectionId, status == ResultStatus::OK,
*handle ? *bufferId : 0 , *handle);
return status;
}
return ResultStatus::CRITICAL_ERROR;
}
ResultStatus BufferPoolClient::Impl::fetchBufferHandle(
TransactionId transactionId, BufferId bufferId,
native_handle_t **handle) {
sp<IConnection> connection;
if (mLocal) {
connection = mLocalConnection;
} else {
connection = mRemoteConnection;
}
ResultStatus status;
Return<void> transResult = connection->fetch(
transactionId, bufferId,
[&status, &handle]
(ResultStatus outStatus, Buffer outBuffer) {
status = outStatus;
if (status == ResultStatus::OK) {
*handle = native_handle_clone(
outBuffer.buffer.getNativeHandle());
}
});
return transResult.isOk() ? status : ResultStatus::CRITICAL_ERROR;
}
BufferPoolClient::BufferPoolClient(const sp<Accessor> &accessor) {
mImpl = std::make_shared<Impl>(accessor);
}
BufferPoolClient::BufferPoolClient(const sp<IAccessor> &accessor) {
mImpl = std::make_shared<Impl>(accessor);
}
BufferPoolClient::~BufferPoolClient() {
// TODO: how to handle orphaned buffers?
}
bool BufferPoolClient::isValid() {
return mImpl && mImpl->isValid();
}
bool BufferPoolClient::isLocal() {
return mImpl && mImpl->isLocal();
}
bool BufferPoolClient::isActive(int64_t *lastTransactionUs, bool clearCache) {
if (!isValid()) {
*lastTransactionUs = 0;
return false;
}
return mImpl->isActive(lastTransactionUs, clearCache);
}
ConnectionId BufferPoolClient::getConnectionId() {
if (isValid()) {
return mImpl->getConnectionId();
}
return -1;
}
ResultStatus BufferPoolClient::getAccessor(sp<IAccessor> *accessor) {
if (isValid()) {
*accessor = mImpl->getAccessor();
return ResultStatus::OK;
}
return ResultStatus::CRITICAL_ERROR;
}
ResultStatus BufferPoolClient::allocate(
const std::vector<uint8_t> ¶ms,
native_handle_t **handle,
std::shared_ptr<BufferPoolData> *buffer) {
if (isValid()) {
return mImpl->allocate(params, handle, buffer);
}
return ResultStatus::CRITICAL_ERROR;
}
ResultStatus BufferPoolClient::receive(
TransactionId transactionId, BufferId bufferId, int64_t timestampUs,
native_handle_t **handle, std::shared_ptr<BufferPoolData> *buffer) {
if (isValid()) {
return mImpl->receive(transactionId, bufferId, timestampUs, handle, buffer);
}
return ResultStatus::CRITICAL_ERROR;
}
ResultStatus BufferPoolClient::postSend(
ConnectionId receiverId,
const std::shared_ptr<BufferPoolData> &buffer,
TransactionId *transactionId,
int64_t *timestampUs) {
if (isValid()) {
bool result = mImpl->postSend(
buffer->mId, receiverId, transactionId, timestampUs);
return result ? ResultStatus::OK : ResultStatus::CRITICAL_ERROR;
}
return ResultStatus::CRITICAL_ERROR;
}
} // namespace implementation
} // namespace V1_0
} // namespace bufferpool
} // namespace media
} // namespace hardware
} // namespace android
| 24,068 | 6,890 |
#include <iostream>
#include "calendar.h"
#include "date/tz.h"
int main()
{
Event event("test");
auto d = date::local_days{date::April/30/2004};
event.convertToTime(d, "8:10-9:10");
std::cout << event.dtstart << std::endl << event.dtend << std::endl;
return 0;
} | 284 | 116 |
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <ripple/protocol/Feature.h>
#include <ripple/basics/Slice.h>
#include <ripple/basics/contract.h>
#include <ripple/protocol/digest.h>
#include <boost/container_hash/hash.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/key_extractors.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index_container.hpp>
#include <cstring>
namespace ripple {
inline std::size_t
hash_value(ripple::uint256 const& feature)
{
std::size_t seed = 0;
using namespace boost;
for (auto const& n : feature)
hash_combine(seed, n);
return seed;
}
namespace {
enum class Supported : bool { no = false, yes };
// *NOTE*
//
// Features, or Amendments as they are called elsewhere, are enabled on the
// network at some specific time based on Validator voting. Features are
// enabled using run-time conditionals based on the state of the amendment.
// There is value in retaining that conditional code for some time after
// the amendment is enabled to make it simple to replay old transactions.
// However, once an Amendment has been enabled for, say, more than two years
// then retaining that conditional code has less value since it is
// uncommon to replay such old transactions.
//
// Starting in January of 2020 Amendment conditionals from before January
// 2018 are being removed. So replaying any ledger from before January
// 2018 needs to happen on an older version of the server code. There's
// a log message in Application.cpp that warns about replaying old ledgers.
//
// At some point in the future someone may wish to remove Amendment
// conditional code for Amendments that were enabled after January 2018.
// When that happens then the log message in Application.cpp should be
// updated.
class FeatureCollections
{
struct Feature
{
std::string name;
uint256 feature;
Feature() = delete;
explicit Feature(std::string const& name_, uint256 const& feature_)
: name(name_), feature(feature_)
{
}
// These structs are used by the `features` multi_index_container to
// provide access to the features collection by size_t index, string
// name, and uint256 feature identifier
struct byIndex
{
};
struct byName
{
};
struct byFeature
{
};
};
// Intermediate types to help with readability
template <class tag, typename Type, Type Feature::*PtrToMember>
using feature_hashed_unique = boost::multi_index::hashed_unique<
boost::multi_index::tag<tag>,
boost::multi_index::member<Feature, Type, PtrToMember>>;
// Intermediate types to help with readability
using feature_indexing = boost::multi_index::indexed_by<
boost::multi_index::random_access<
boost::multi_index::tag<Feature::byIndex>>,
feature_hashed_unique<Feature::byFeature, uint256, &Feature::feature>,
feature_hashed_unique<Feature::byName, std::string, &Feature::name>>;
// This multi_index_container provides access to the features collection by
// name, index, and uint256 feature identifier
boost::multi_index::multi_index_container<Feature, feature_indexing>
features;
std::map<std::string, DefaultVote> supported;
std::size_t upVotes = 0;
std::size_t downVotes = 0;
mutable std::atomic<bool> readOnly = false;
// These helper functions provide access to the features collection by name,
// index, and uint256 feature identifier, so the details of
// multi_index_container can be hidden
Feature const&
getByIndex(size_t i) const
{
if (i >= features.size())
LogicError("Invalid FeatureBitset index");
const auto& sequence = features.get<Feature::byIndex>();
return sequence[i];
}
size_t
getIndex(Feature const& feature) const
{
const auto& sequence = features.get<Feature::byIndex>();
auto const it_to = sequence.iterator_to(feature);
return it_to - sequence.begin();
}
Feature const*
getByFeature(uint256 const& feature) const
{
const auto& feature_index = features.get<Feature::byFeature>();
auto const feature_it = feature_index.find(feature);
return feature_it == feature_index.end() ? nullptr : &*feature_it;
}
Feature const*
getByName(std::string const& name) const
{
const auto& name_index = features.get<Feature::byName>();
auto const name_it = name_index.find(name);
return name_it == name_index.end() ? nullptr : &*name_it;
}
public:
FeatureCollections();
std::optional<uint256>
getRegisteredFeature(std::string const& name) const;
uint256
registerFeature(
std::string const& name,
Supported support,
DefaultVote vote);
/** Tell FeatureCollections when registration is complete. */
bool
registrationIsDone();
std::size_t
featureToBitsetIndex(uint256 const& f) const;
uint256 const&
bitsetIndexToFeature(size_t i) const;
std::string
featureToName(uint256 const& f) const;
/** Amendments that this server supports.
Whether they are enabled depends on the Rules defined in the validated
ledger */
std::map<std::string, DefaultVote> const&
supportedAmendments() const
{
return supported;
}
/** Amendments that this server WON'T vote for by default. */
std::size_t
numDownVotedAmendments() const
{
return downVotes;
}
/** Amendments that this server WILL vote for by default. */
std::size_t
numUpVotedAmendments() const
{
return upVotes;
}
};
//------------------------------------------------------------------------------
FeatureCollections::FeatureCollections()
{
features.reserve(ripple::detail::numFeatures);
}
std::optional<uint256>
FeatureCollections::getRegisteredFeature(std::string const& name) const
{
assert(readOnly);
Feature const* feature = getByName(name);
if (feature)
return feature->feature;
return std::nullopt;
}
void
check(bool condition, const char* logicErrorMessage)
{
if (!condition)
LogicError(logicErrorMessage);
}
uint256
FeatureCollections::registerFeature(
std::string const& name,
Supported support,
DefaultVote vote)
{
check(!readOnly, "Attempting to register a feature after startup.");
check(
support == Supported::yes || vote == DefaultVote::no,
"Invalid feature parameters. Must be supported to be up-voted.");
Feature const* i = getByName(name);
if (!i)
{
// If this check fails, and you just added a feature, increase the
// numFeatures value in Feature.h
check(
features.size() < detail::numFeatures,
"More features defined than allocated. Adjust numFeatures in "
"Feature.h.");
auto const f = sha512Half(Slice(name.data(), name.size()));
features.emplace_back(name, f);
if (support == Supported::yes)
{
supported.emplace(name, vote);
if (vote == DefaultVote::yes)
++upVotes;
else
++downVotes;
}
check(
upVotes + downVotes == supported.size(),
"Feature counting logic broke");
check(
supported.size() <= features.size(),
"More supported features than defined features");
return f;
}
else
// Each feature should only be registered once
LogicError("Duplicate feature registration");
}
/** Tell FeatureCollections when registration is complete. */
bool
FeatureCollections::registrationIsDone()
{
readOnly = true;
return true;
}
size_t
FeatureCollections::featureToBitsetIndex(uint256 const& f) const
{
assert(readOnly);
Feature const* feature = getByFeature(f);
if (!feature)
LogicError("Invalid Feature ID");
return getIndex(*feature);
}
uint256 const&
FeatureCollections::bitsetIndexToFeature(size_t i) const
{
assert(readOnly);
Feature const& feature = getByIndex(i);
return feature.feature;
}
std::string
FeatureCollections::featureToName(uint256 const& f) const
{
assert(readOnly);
Feature const* feature = getByFeature(f);
return feature ? feature->name : to_string(f);
}
static FeatureCollections featureCollections;
} // namespace
/** Amendments that this server supports.
Whether they are enabled depends on the Rules defined in the validated
ledger */
std::map<std::string, DefaultVote> const&
detail::supportedAmendments()
{
return featureCollections.supportedAmendments();
}
/** Amendments that this server won't vote for by default. */
std::size_t
detail::numDownVotedAmendments()
{
return featureCollections.numDownVotedAmendments();
}
/** Amendments that this server will vote for by default. */
std::size_t
detail::numUpVotedAmendments()
{
return featureCollections.numUpVotedAmendments();
}
//------------------------------------------------------------------------------
std::optional<uint256>
getRegisteredFeature(std::string const& name)
{
return featureCollections.getRegisteredFeature(name);
}
uint256
registerFeature(std::string const& name, Supported support, DefaultVote vote)
{
return featureCollections.registerFeature(name, support, vote);
}
// Retired features are in the ledger and have no code controlled by the
// feature. They need to be supported, but do not need to be voted on.
uint256
retireFeature(std::string const& name)
{
return registerFeature(name, Supported::yes, DefaultVote::no);
}
/** Tell FeatureCollections when registration is complete. */
bool
registrationIsDone()
{
return featureCollections.registrationIsDone();
}
size_t
featureToBitsetIndex(uint256 const& f)
{
return featureCollections.featureToBitsetIndex(f);
}
uint256
bitsetIndexToFeature(size_t i)
{
return featureCollections.bitsetIndexToFeature(i);
}
std::string
featureToName(uint256 const& f)
{
return featureCollections.featureToName(f);
}
#pragma push_macro("REGISTER_FEATURE")
#undef REGISTER_FEATURE
/**
Takes the name of a feature, whether it's supported, and the default vote. Will
register the feature, and create a variable whose name is "feature" plus the
feature name.
*/
#define REGISTER_FEATURE(fName, supported, defaultvote) \
uint256 const feature##fName = \
registerFeature(#fName, supported, defaultvote)
#pragma push_macro("REGISTER_FIX")
#undef REGISTER_FIX
/**
Takes the name of a feature, whether it's supported, and the default vote. Will
register the feature, and create a variable whose name is the unmodified feature
name.
*/
#define REGISTER_FIX(fName, supported, defaultvote) \
uint256 const fName = registerFeature(#fName, supported, defaultvote)
// clang-format off
// All known amendments must be registered either here or below with the
// "retired" amendments
REGISTER_FEATURE(OwnerPaysFee, Supported::no, DefaultVote::no);
REGISTER_FEATURE(Flow, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(FlowCross, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(CryptoConditionsSuite, Supported::yes, DefaultVote::no);
REGISTER_FIX (fix1513, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(DepositAuth, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(Checks, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fix1571, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fix1543, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fix1623, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(DepositPreauth, Supported::yes, DefaultVote::yes);
// Use liquidity from strands that consume max offers, but mark as dry
REGISTER_FIX (fix1515, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fix1578, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(MultiSignReserve, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixTakerDryOfferRemoval, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixMasterKeyAsRegularKey, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixCheckThreading, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixPayChanRecipientOwnerDir, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(DeletableAccounts, Supported::yes, DefaultVote::yes);
// fixQualityUpperBound should be activated before FlowCross
REGISTER_FIX (fixQualityUpperBound, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(RequireFullyCanonicalSig, Supported::yes, DefaultVote::yes);
// fix1781: XRPEndpointSteps should be included in the circular payment check
REGISTER_FIX (fix1781, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(HardenedValidations, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixAmendmentMajorityCalc, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(NegativeUNL, Supported::yes, DefaultVote::no);
REGISTER_FEATURE(TicketBatch, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(FlowSortStrands, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixSTAmountCanonicalize, Supported::yes, DefaultVote::yes);
REGISTER_FIX (fixRmSmallIncreasedQOffers, Supported::yes, DefaultVote::yes);
REGISTER_FEATURE(CheckCashMakesTrustLine, Supported::yes, DefaultVote::no);
REGISTER_FEATURE(NonFungibleTokensV1, Supported::yes, DefaultVote::no);
// The following amendments have been active for at least two years. Their
// pre-amendment code has been removed and the identifiers are deprecated.
// All known amendments and amendments that may appear in a validated
// ledger must be registered either here or above with the "active" amendments
[[deprecated("The referenced amendment has been retired"), maybe_unused]]
uint256 const
retiredMultiSign = retireFeature("MultiSign"),
retiredTrustSetAuth = retireFeature("TrustSetAuth"),
retiredFeeEscalation = retireFeature("FeeEscalation"),
retiredPayChan = retireFeature("PayChan"),
retiredCryptoConditions = retireFeature("CryptoConditions"),
retiredTickSize = retireFeature("TickSize"),
retiredFix1368 = retireFeature("fix1368"),
retiredEscrow = retireFeature("Escrow"),
retiredFix1373 = retireFeature("fix1373"),
retiredEnforceInvariants = retireFeature("EnforceInvariants"),
retiredSortedDirectories = retireFeature("SortedDirectories"),
retiredFix1201 = retireFeature("fix1201"),
retiredFix1512 = retireFeature("fix1512"),
retiredFix1523 = retireFeature("fix1523"),
retiredFix1528 = retireFeature("fix1528");
// clang-format on
#undef REGISTER_FIX
#pragma pop_macro("REGISTER_FIX")
#undef REGISTER_FEATURE
#pragma pop_macro("REGISTER_FEATURE")
// All of the features should now be registered, since variables in a cpp file
// are initialized from top to bottom.
//
// Use initialization of one final static variable to set
// featureCollections::readOnly.
[[maybe_unused]] static const bool readOnlySet =
featureCollections.registrationIsDone();
} // namespace ripple
| 16,642 | 5,002 |
/*******************************************************************************
* Copyright (c) 2000, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#include "codegen/OMRTreeEvaluator.hpp"
#include <stddef.h>
#include <stdint.h>
#include "codegen/CodeGenerator.hpp"
#include "codegen/FrontEnd.hpp"
#include "codegen/LiveRegister.hpp"
#include "codegen/Machine.hpp"
#include "codegen/MemoryReference.hpp"
#include "codegen/RealRegister.hpp"
#include "codegen/Register.hpp"
#include "codegen/RegisterConstants.hpp"
#include "codegen/RegisterDependency.hpp"
#include "codegen/TreeEvaluator.hpp"
#include "compile/Compilation.hpp"
#include "env/CompilerEnv.hpp"
#include "env/TRMemory.hpp"
#include "il/DataTypes.hpp"
#include "il/ILOpCodes.hpp"
#include "il/ILOps.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/Symbol.hpp"
#include "il/SymbolReference.hpp"
#include "il/symbol/LabelSymbol.hpp"
#include "infra/Assert.hpp"
#include "infra/List.hpp"
#include "ras/Debug.hpp"
#include "x/codegen/ConstantDataSnippet.hpp"
#include "x/codegen/OutlinedInstructions.hpp"
#include "x/codegen/X86Evaluator.hpp"
#include "x/codegen/X86Instruction.hpp"
#include "x/codegen/X86Ops.hpp"
TR::Register *OMR::X86::AMD64::TreeEvaluator::aconstEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
TR::Register *targetRegister = TR::TreeEvaluator::loadConstant(node, node->getLongInt(), TR_RematerializableAddress, cg);
node->setRegister(targetRegister);
return targetRegister;
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::lconstEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
TR::Register *targetRegister = TR::TreeEvaluator::loadConstant(node, node->getLongInt(), TR_RematerializableLong, cg);
node->setRegister(targetRegister);
return targetRegister;
}
// TODO:AMD64: Could this be combined with istoreEvaluator without too much ugliness?
TR::Register *OMR::X86::AMD64::TreeEvaluator::lstoreEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
TR::Node *valueChild;
TR::Compilation* comp = cg->comp();
if (node->getOpCode().isIndirect())
valueChild = node->getSecondChild();
else
valueChild = node->getFirstChild();
// Handle special cases
//
if (valueChild->getRegister() == NULL &&
valueChild->getReferenceCount() == 1)
{
// Special case storing a double value into long variable
//
if (valueChild->getOpCodeValue() == TR::dbits2l &&
!valueChild->normalizeNanValues())
{
if (node->getOpCode().isIndirect())
{
node->setChild(1, valueChild->getFirstChild());
TR::Node::recreate(node, TR::dstorei);
TR::TreeEvaluator::floatingPointStoreEvaluator(node, cg);
node->setChild(1, valueChild);
TR::Node::recreate(node, TR::lstorei);
}
else
{
node->setChild(0, valueChild->getFirstChild());
TR::Node::recreate(node, TR::dstore);
TR::TreeEvaluator::floatingPointStoreEvaluator(node, cg);
node->setChild(0, valueChild);
TR::Node::recreate(node, TR::lstore);
}
cg->decReferenceCount(valueChild);
return NULL;
}
}
return TR::TreeEvaluator::integerStoreEvaluator(node, cg);
}
// also handles ilload
TR::Register *OMR::X86::AMD64::TreeEvaluator::lloadEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
TR::MemoryReference *sourceMR = generateX86MemoryReference(node, cg);
TR::Register *reg = TR::TreeEvaluator::loadMemory(node, sourceMR, TR_RematerializableLong, node->getOpCode().isIndirect(), cg);
reg->setMemRef(sourceMR);
node->setRegister(reg);
sourceMR->decNodeReferenceCounts(cg);
return reg;
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::landEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
return TR::TreeEvaluator::logicalEvaluator(node, _logicalOpPackage[landOpPackage], cg);
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::lorEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
return TR::TreeEvaluator::logicalEvaluator(node, _logicalOpPackage[lorOpPackage], cg);
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::lxorEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
return TR::TreeEvaluator::logicalEvaluator(node, _logicalOpPackage[lxorOpPackage], cg);
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::i2lEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
TR::Compilation *comp = cg->comp();
if (node->getFirstChild()->getOpCode().isLoadConst())
{
TR::Register *targetRegister = cg->allocateRegister();
generateRegImmInstruction(MOV8RegImm4, node, targetRegister, node->getFirstChild()->getInt(), cg);
node->setRegister(targetRegister);
cg->decReferenceCount(node->getFirstChild());
return targetRegister;
}
else
{
// In theory, because iRegStore has chosen to disregard needsSignExtension,
// we must disregard skipSignExtension here for correctness.
//
// However, in fact, it is actually safe to obey skipSignExtension so
// long as the optimizer only uses it on nodes known to be non-negative
// when the i2l occurs. We do already have isNonNegative for that
// purpose, but it may not always be set by the optimizer if a node known
// to be non-negative at one point in a block is commoned up above the
// BNDCHK or branch that determines the node's non-negativity. The
// codegen does set the flag during tree evaluation, but the
// skipSignExtension flag is set by the optimizer with more global
// knowledge than the tree evaluator, so we will trust it.
//
TR_X86OpCodes regMemOpCode,regRegOpCode;
if( node->isNonNegative()
|| (node->skipSignExtension() && performTransformation(comp, "TREE EVALUATION: skipping sign extension on node %s despite lack of isNonNegative\n", comp->getDebug()->getName(node))))
{
// We prefer these plain (zero-extending) opcodes because the analyser can often eliminate them
//
regMemOpCode = L4RegMem;
regRegOpCode = MOVZXReg8Reg4;
}
else
{
regMemOpCode = MOVSXReg8Mem4;
regRegOpCode = MOVSXReg8Reg4;
}
return TR::TreeEvaluator::conversionAnalyser(node, regMemOpCode, regRegOpCode, cg);
}
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::l2iEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
TR::Node *child = node->getFirstChild();
TR::Register *reg = cg->evaluate(child);
if (child->getReferenceCount() > 1)
{
// This catches two scenarios:
//
// 1) A longClobberEvaluate (or any other register-clobbering logic) on
// the l2i node could see a refcount of 1, and hence won't make a copy.
// If child's refcount is more than 1, we do in fact need a copy, so we'd
// better do it here.
//
// 2) If the child is commoned, and the l2i node is also commoned, then
// we may end up with a situation where the last evaluation of the child
// is a clobberEvaluate. By that time, the child's refcount would be 1,
// so no copy is made, and the register would be clobbered. Therefore,
// the l2i node can't return that same register, or else the other uses
// of the node will end up getting the clobbered value.
//
// Note that case 2 is conservative, in that it presumes that the child's
// register will be clobbered by another node. If this does not occur,
// then the copy we're about to make is unnecessary.
//
TR::Register *childReg = reg;
reg = cg->allocateRegister();
// to support signExtension in GRA, need to preserve upper word
// in this move
generateRegRegInstruction(MOV8RegReg, node, reg, childReg, cg);
}
node->setRegister(reg);
cg->decReferenceCount(child);
if (cg->enableRegisterInterferences() && node->getOpCode().getSize() == 1)
cg->getLiveRegisters(TR_GPR)->setByteRegisterAssociation(node->getRegister());
return reg;
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::iu2lEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
if (node->getFirstChild()->getOpCode().isLoadConst())
{
TR::Register *targetRegister = cg->allocateRegister();
generateRegImmInstruction(MOV4RegImm4, node, targetRegister, node->getFirstChild()->getInt(), cg); // implicitly zero extended
node->setRegister(targetRegister);
cg->decReferenceCount(node->getFirstChild());
return targetRegister;
}
else
return TR::TreeEvaluator::conversionAnalyser(node, L4RegMem, MOVZXReg8Reg4, cg); // This zero-extends on AMD64
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::b2lEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
return TR::TreeEvaluator::conversionAnalyser(node, MOVSXReg8Mem1, MOVSXReg8Reg1, cg);
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::bu2lEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
return TR::TreeEvaluator::conversionAnalyser(node, MOVZXReg8Mem1, MOVZXReg8Reg1, cg);
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::s2lEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
return TR::TreeEvaluator::conversionAnalyser(node, MOVSXReg8Mem2, MOVSXReg8Reg2, cg);
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::su2lEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
return TR::TreeEvaluator::conversionAnalyser(node, MOVZXReg8Mem2, MOVZXReg8Reg2, cg);
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::c2lEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
return TR::TreeEvaluator::conversionAnalyser(node, MOVZXReg8Mem2, MOVZXReg8Reg2, cg);
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::lcmpEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
TR::Node *firstChild = node->getFirstChild();
TR::Node *secondChild = node->getSecondChild();
TR::Register *leftRegister = cg->evaluate(firstChild);
TR::Register *rightRegister = cg->evaluate(secondChild);
// Compare left and right operands, all finished with the operands after this.
generateRegRegInstruction(CMP8RegReg, node, leftRegister, rightRegister, cg);
cg->decReferenceCount(firstChild);
cg->decReferenceCount(secondChild);
TR::Register *isLessThanReg = cg->allocateRegister();
TR::Register *isNotEqualReg = cg->allocateRegister();
cg->getLiveRegisters(TR_GPR)->setByteRegisterAssociation(isLessThanReg);
cg->getLiveRegisters(TR_GPR)->setByteRegisterAssociation(isNotEqualReg);
// The state of things in each possible case after each instruction:
// left < right left = right left > right
// Processor flags: NE=1 LT=1 NE=0 LT=0 NE=1 LT=0
generateRegInstruction(SETL1Reg, node, isLessThanReg, cg);
// isLessThanReg: 00000001 00000000 00000000
generateRegInstruction(SETNE1Reg, node, isNotEqualReg, cg);
// isNotEqualReg: 00000001 00000000 00000001
generateRegInstruction(NEG1Reg, node, isLessThanReg, cg);
// isLessThanReg: 11111111 00000000 00000000
generateRegRegInstruction(OR1RegReg, node, isNotEqualReg, isLessThanReg, cg);
// isNotEqualReg: 11111111 00000000 00000001
generateRegRegInstruction(MOVSXReg4Reg1, node, isNotEqualReg, isNotEqualReg, cg);
node->setRegister(isNotEqualReg);
cg->stopUsingRegister(isLessThanReg);
return isNotEqualReg;
}
static TR::Register *l2fd(TR::Node *node, TR::RealRegister *target, TR_X86OpCodes opRegMem8, TR_X86OpCodes opRegReg8, TR::CodeGenerator *cg)
{
TR::Node *child = node->getFirstChild();
TR::MemoryReference *tempMR;
TR_ASSERT(cg->useSSEForSinglePrecision(), "assertion failure");
if (child->getRegister() == NULL &&
child->getReferenceCount() == 1 &&
child->getOpCode().isLoadVar())
{
tempMR = generateX86MemoryReference(child, cg);
generateRegMemInstruction(opRegMem8, node, target, tempMR, cg);
tempMR->decNodeReferenceCounts(cg);
}
else
{
TR::Register *intReg = cg->evaluate(child);
generateRegRegInstruction(opRegReg8, node, target, intReg, cg);
cg->decReferenceCount(child);
}
node->setRegister(target);
return target;
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::l2fEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
return l2fd(node, toRealRegister(cg->allocateSinglePrecisionRegister(TR_FPR)), CVTSI2SSRegMem8, CVTSI2SSRegReg8, cg);
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::l2dEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
return l2fd(node, toRealRegister(cg->allocateRegister(TR_FPR)), CVTSI2SDRegMem8, CVTSI2SDRegReg8, cg);
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::lbits2dEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
// TODO:AMD64: Peepholing
TR::Node *child = node->getFirstChild();
TR::Register *sreg = cg->evaluate(child);
TR::Register *treg = cg->allocateRegister(TR_FPR);
generateRegRegInstruction(MOVQRegReg8, node, treg, sreg, cg);
node->setRegister(treg);
cg->decReferenceCount(child);
return treg;
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::dbits2lEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
// TODO:AMD64: Peepholing
TR::Node *child = node->getFirstChild();
TR::Register *sreg = cg->evaluate(child);
TR::Register *treg = cg->allocateRegister(TR_GPR);
generateRegRegInstruction(MOVQReg8Reg, node, treg, sreg, cg);
if (node->normalizeNanValues())
{
static char *disableFastNormalizeNaNs = feGetEnv("TR_disableFastNormalizeNaNs");
if (disableFastNormalizeNaNs)
{
// This one is not clever, but it is simple, and it's based directly
// on the IA32 version which is known to work, so is safer.
//
TR::RegisterDependencyConditions *deps = generateRegisterDependencyConditions((uint8_t)0, (uint8_t)1, cg);
deps->addPostCondition(treg, TR::RealRegister::NoReg, cg);
TR::MemoryReference* nan1MR = generateX86MemoryReference(cg->findOrCreate8ByteConstant(node, DOUBLE_NAN_1_LOW), cg);
TR::MemoryReference* nan2MR = generateX86MemoryReference(cg->findOrCreate8ByteConstant(node, DOUBLE_NAN_2_LOW), cg);
TR::LabelSymbol *startLabel = TR::LabelSymbol::create(cg->trHeapMemory(),cg);
TR::LabelSymbol *normalizeLabel = TR::LabelSymbol::create(cg->trHeapMemory(),cg);
TR::LabelSymbol *endLabel = TR::LabelSymbol::create(cg->trHeapMemory(),cg);
startLabel->setStartInternalControlFlow();
endLabel ->setEndInternalControlFlow();
generateLabelInstruction( LABEL, node, startLabel, cg);
generateRegMemInstruction( CMP8RegMem, node, treg, nan1MR, cg);
generateLabelInstruction( JGE4, node, normalizeLabel, cg);
generateRegMemInstruction( CMP8RegMem, node, treg, nan2MR, cg);
generateLabelInstruction( JB4, node, endLabel, cg);
generateLabelInstruction( LABEL, node, normalizeLabel, cg);
generateRegImm64Instruction( MOV8RegImm64, node, treg, DOUBLE_NAN, cg);
generateLabelInstruction( LABEL, node, endLabel, deps, cg);
}
else
{
// A bunch of bookkeeping
//
uint64_t nanDetector = DOUBLE_NAN_2_LOW;
TR::RegisterDependencyConditions *internalControlFlowDeps = generateRegisterDependencyConditions((uint8_t)0, (uint8_t)1, cg);
internalControlFlowDeps->addPostCondition(treg, TR::RealRegister::NoReg, cg);
TR::RegisterDependencyConditions *helperDeps = generateRegisterDependencyConditions((uint8_t)1, (uint8_t)1, cg);
helperDeps->addPreCondition( treg, TR::RealRegister::eax, cg);
helperDeps->addPostCondition(treg, TR::RealRegister::eax, cg);
TR::MemoryReference* nanDetectorMR = generateX86MemoryReference(cg->findOrCreate8ByteConstant(node, nanDetector), cg);
TR::LabelSymbol *startLabel = TR::LabelSymbol::create(cg->trHeapMemory(),cg);
TR::LabelSymbol *slowPathLabel = TR::LabelSymbol::create(cg->trHeapMemory(),cg);
TR::LabelSymbol *normalizeLabel = TR::LabelSymbol::create(cg->trHeapMemory(),cg);
TR::LabelSymbol *endLabel = TR::LabelSymbol::create(cg->trHeapMemory(),cg);
startLabel->setStartInternalControlFlow();
endLabel ->setEndInternalControlFlow();
// Fast path: if subtracting nanDetector leaves CF=0 or OF=1, then it
// must be a NaN.
//
generateLabelInstruction( LABEL, node, startLabel, cg);
generateRegMemInstruction( CMP8RegMem, node, treg, nanDetectorMR, cg);
generateLabelInstruction( JAE4, node, slowPathLabel, cg);
generateLabelInstruction( JO4, node, slowPathLabel, cg);
// Slow path
//
{
TR_OutlinedInstructionsGenerator og(slowPathLabel, node, cg);
generateRegImm64Instruction(MOV8RegImm64, node, treg, DOUBLE_NAN, cg);
generateLabelInstruction(JMP4, node, endLabel, cg);
}
// Merge point
//
generateLabelInstruction(LABEL, node, endLabel, internalControlFlowDeps, cg);
}
}
node->setRegister(treg);
cg->decReferenceCount(child);
return treg;
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::awrtbarEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
// The wrtbar IL op represents a store with side effects.
// Currently we don't use the side effect node. So just evaluate it and decrement the reference count.
TR::Node *sideEffectNode = node->getSecondChild();
cg->evaluate(sideEffectNode);
cg->decReferenceCount(sideEffectNode);
// Delegate the evaluation of the remaining children and the store operation to the storeEvaluator.
return TR::TreeEvaluator::lstoreEvaluator(node, cg);
}
TR::Register *OMR::X86::AMD64::TreeEvaluator::awrtbariEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
// The wrtbar IL op represents a store with side effects.
// Currently we don't use the side effect node. So just evaluate it and decrement the reference count.
TR::Node *sideEffectNode = node->getThirdChild();
cg->evaluate(sideEffectNode);
cg->decReferenceCount(sideEffectNode);
// Delegate the evaluation of the remaining children and the store operation to the storeEvaluator.
return TR::TreeEvaluator::lstoreEvaluator(node, cg);
}
TR::Register *
OMR::X86::AMD64::TreeEvaluator::dwrtbarEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
// The wrtbar IL op represents a store with side effects.
// Currently we don't use the side effect node. So just evaluate it and decrement the reference count.
TR::Node *sideEffectNode = node->getSecondChild();
cg->evaluate(sideEffectNode);
cg->decReferenceCount(sideEffectNode);
// Delegate the evaluation of the remaining children and the store operation to the storeEvaluator.
return TR::TreeEvaluator::floatingPointStoreEvaluator(node, cg);
}
TR::Register *
OMR::X86::AMD64::TreeEvaluator::dwrtbariEvaluator(TR::Node *node, TR::CodeGenerator *cg)
{
// The wrtbar IL op represents a store with side effects.
// Currently we don't use the side effect node. So just evaluate it and decrement the reference count.
TR::Node *sideEffectNode = node->getThirdChild();
cg->evaluate(sideEffectNode);
cg->decReferenceCount(sideEffectNode);
// Delegate the evaluation of the remaining children and the store operation to the storeEvaluator.
return TR::TreeEvaluator::floatingPointStoreEvaluator(node, cg);
}
| 21,022 | 7,050 |
#ifndef LIGHTSOURCE_HPP_
#define LIGHTSOURCE_HPP_
#include <glm/vec3.hpp>
#include "abcg.hpp"
#include <glm/vec3.hpp>
#include "boids.hpp"
class OpenGLWindow;
class Boids;
class LightSource {
public:
void update(float deltaTime);
private:
friend OpenGLWindow;
friend Boids;
float scale{0.10f};
float rotationAngle{1.00f};
glm::vec3 lightSourcePosition;
void setupLightSource();
};
#endif | 486 | 179 |
//: C03:Menu.cpp
// Simple menu program demostrating
#include <iostream>
using namespace std;
int main()
{
char c;
while(true)
{
cout << "MAIN MENU: " << endl;
cout << "l: left, r: right, q: quit -> ";
cin >> c;
if(c == 'q')
break; // Out of "while(1)"
if(c == 'l')
{
cout << "LEFT MENU: " <<endl;
cout << "select a or b: ";
cin >> c;
if(c == 'a')
{
cout << "you chose 'a'" << endl;
continue; // Back to main menu
}
if(c == 'b')
{
cout << "you chose 'b'" << endl;
continue;
}
else
{
cout << "you didn't choose a or b!" << endl;
continue;
}
}
if(c == 'r')
{
cout << "RIGHT MENU: " << endl;
cout << "select c or d: ";
cin >> c;
if(c == 'c')
{
cout << "you chose 'c'" << endl;
continue;
}
if(c == 'd')
{
cout << "you chise 'd'" << endl;
continue;
}
else
{
cout << "you didn's choose c or d!" << endl;
continue;
}
}
else
cout << "you ust tyoe l or r or q!" << endl;
}
cout << "quitting menu..." << endl;
}///:~
| 1,066 | 543 |
#ifndef SRC_HTTPSSERVERCONSTANTS_HPP_
#define SRC_HTTPSSERVERCONSTANTS_HPP_
#include "Arduino.h"
// 1: Error
// 2: Error + Warn
// 3: Error + Warn + Info
// 4: Error + Warn + Info + Debug
#ifndef HTTPS_LOGLEVEL
#define HTTPS_LOGLEVEL 3
#endif
#ifdef HTTPS_LOGTIMESTAMP
#define HTTPS_LOGTAG(LVL) Serial.printf("[HTTPS:" LVL ":%10lu] ", millis())
#else
#define HTTPS_LOGTAG(LVL) Serial.print("[HTTPS:" LVL "] ")
#endif
#if HTTPS_LOGLEVEL > 0
#define HTTPS_LOGE(...) HTTPS_LOGTAG("E");Serial.printf(__VA_ARGS__);Serial.println()
#else
#define HTTPS_LOGE(...) do {} while (0)
#endif
#if HTTPS_LOGLEVEL > 1
#define HTTPS_LOGW(...) HTTPS_LOGTAG("W");Serial.printf(__VA_ARGS__);Serial.println()
#else
#define HTTPS_LOGW(...) do {} while (0)
#endif
#if HTTPS_LOGLEVEL > 2
#define HTTPS_LOGI(...) HTTPS_LOGTAG("I");Serial.printf(__VA_ARGS__);Serial.println()
#else
#define HTTPS_LOGI(...) do {} while (0)
#endif
#if HTTPS_LOGLEVEL > 3
#define HTTPS_LOGD(...) HTTPS_LOGTAG("D");Serial.printf(__VA_ARGS__);Serial.println()
#else
#define HTTPS_LOGD(...) do {} while (0)
#endif
// The following lines define limits of the protocol. Exceeding these limits will lead to a 500 error
// Maximum of header lines that are parsed
#ifndef HTTPS_REQUEST_MAX_HEADERS
#define HTTPS_REQUEST_MAX_HEADERS 20
#endif
// Maximum length of the request line (GET /... HTTP/1.1)
#ifndef HTTPS_REQUEST_MAX_REQUEST_LENGTH
#define HTTPS_REQUEST_MAX_REQUEST_LENGTH 128
#endif
// Maximum length of a header line (including name and value)
#ifndef HTTPS_REQUEST_MAX_HEADER_LENGTH
#define HTTPS_REQUEST_MAX_HEADER_LENGTH 384
#endif
// Chunk size used for reading data from the ssl-enabled socket
#ifndef HTTPS_CONNECTION_DATA_CHUNK_SIZE
#define HTTPS_CONNECTION_DATA_CHUNK_SIZE 512
#endif
// Size (in bytes) of the Connection:keep-alive Cache (we need to be able to
// store-and-forward the response to calculate the content-size)
#ifndef HTTPS_KEEPALIVE_CACHESIZE
#define HTTPS_KEEPALIVE_CACHESIZE 1400
#endif
// Timeout for an HTTPS connection without any transmission
#ifndef HTTPS_CONNECTION_TIMEOUT
#define HTTPS_CONNECTION_TIMEOUT 20000
#endif
// Timeout used to wait for shutdown of SSL connection (ms)
// (time for the client to return notify close flag) - without it, truncation attacks might be possible
#ifndef HTTPS_SHUTDOWN_TIMEOUT
#define HTTPS_SHUTDOWN_TIMEOUT 5000
#endif
// Length of a SHA1 hash
#ifndef HTTPS_SHA1_LENGTH
#define HTTPS_SHA1_LENGTH 20
#endif
#endif /* SRC_HTTPSSERVERCONSTANTS_HPP_ */
| 2,615 | 977 |
#include <../inc/InputValidation.hpp>
#include <gtest/gtest.h>
struct InputValidationTest : public ::testing::Test
{
};
TEST_F(InputValidationTest,
check_if_substring_from_object_input_will_be_correct)
{
// GIVEN
InputValidation input("Player:x|--|4/|x|");
// WHEN call gestSubstring method
// THEN
ASSERT_EQ("x|--|4/|x|", input.getSubstring());
}
TEST_F(InputValidationTest, expect_false_when_there_is_no_players_name)
{
// GIVEN
InputValidation input(":x|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_players_name_is_correct)
{
// GIVEN
InputValidation input("Mike:x|");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_there_are_two_sticks_around_x)
{
// GIVEN
InputValidation input("Mike:|x|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_miss_is_before_strike)
{
// GIVEN
InputValidation input("Mike:-x|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_there_is_no_stick_after_two_signs)
{
// GIVEN
InputValidation input("Mike:x|--");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_there_are_is_stick_after_two_signs)
{
// GIVEN
InputValidation input("Mike:X|--|");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_before_miss_is_correct_number)
{
// GIVEN
InputValidation input("Mike:x|5-|");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_after_stirke_is_miss)
{
// GIVEN
InputValidation input("Mike:x|x-|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_spare_is_the_first_sign)
{
// GIVEN
InputValidation input("Mike:x|/-|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_two_sticks_are_too_early)
{
// GIVEN
InputValidation input("Mike:x||-|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_spare_is_after_miss)
{
// GIVEN
InputValidation input("Mike:x|6-|-/|");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_there_is_number_less_then_one)
{
// GIVEN
InputValidation input("Mike:x|0-|-/|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_there_is_undefined_sign)
{
// GIVEN
InputValidation input("Mike:x|k-|-/|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_spare_is_after_strike)
{
// GIVEN
InputValidation input("Mike:x|--|x/|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, epect_false_when_spare_is_the_first_sign_in_frame)
{
// GIVEN
InputValidation input("Mike:x|--|//|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_spare_is_after_number_less_then_ten)
{
// GIVEN
InputValidation input("Mike:x|--|9/|");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_sum_of_numbers_is_bigger_then_nine)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|19|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_sum_of_numbers_is_less_then_nine)
{
// GIVEN
InputValidation input("Mike:x|--|9/|X|-3|18|");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_there_are_two_sticks_in_incorrect_place)
{
// GIVEN
InputValidation input("Mike:x|--|9/|X|-3|18|x|-3||");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_there_are_no_two_sticks_in_correct_place)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|--|");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_there_are_two_sticks_in_correct_place)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|--||");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_spare_is_before_two_sticks)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|-/||");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_there_is_strike_after_two_sticks_and_spare)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|-/||x");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_there_is_one_miss_after_two_sticks_and_spare)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|-/||-");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_there_is_number_after_two_sticks_and_spare)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|-/||9");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_there_is_spare_after_two_sticks_and_spare)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|-/||/");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_there_is_too_many_signs_after_two_sticks_and_spare)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|-/||5/");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_there_is_strike_after_two_sticks_and_strike)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||x");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_true_when_there_are_two_miss_after_two_sticks_and_strike)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||--");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(
InputValidationTest,
expect_true_when_there_are_2_numbers_which_sum_is_less_then_9_after_two_sticks_and_strike)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||17");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_there_is_spare_after_two_sticks_and_strike)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||/6");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest,
expect_false_when_there_are_too_many_signs_after_strike)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||123");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_the_game_is_in_progress)
{
// GIVEN
InputValidation input("Mike:x|--|3");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_there_is_no_stick_after_strike)
{
// GIVEN
InputValidation input("Mike:x|--|x");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_false_when_there_is_only_spare_after_stick)
{
// GIVEN
InputValidation input("Mike:x|--|/");
// WHEN call checkInputData method
// THEN
EXPECT_FALSE(input.checkInputData());
}
TEST_F(InputValidationTest, expect_true_when_the_game_is_not_finished)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||");
// WHEN call checkInputData method
// THEN
EXPECT_TRUE(input.checkInputData());
}
TEST_F(InputValidationTest, check_if_player_name_is_correct)
{
// GIVEN
InputValidation input("Mike:x|--|9/|x|-3|18|x|-3|5/|x||/");
// WHEN call checkInputData method
// THEN
ASSERT_EQ(input.getPlayerName(), "Mike");
}
| 9,460 | 3,582 |
/*
*
* Copyright (c) 2013-2017 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements the command handler for the 'weave' tool
* that converts a Weave private key between TLV and PEM/DER
* formats.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>
#include <unistd.h>
#include <ctype.h>
#include "weave-tool.h"
using namespace nl::Weave::Profiles::Security;
struct CSVValue
{
const char * Data;
size_t Length;
};
#define CMD_NAME "weave convert-provisioning-data"
static bool HandleOption(const char *progName, OptionSet *optSet, int id, const char *name, const char *arg);
static bool HandleNonOptionArgs(const char *progName, int argc, char *argv[]);
static void TrimSpace(const char * & p, size_t & len);
static bool ParseCSVLine(const char * input, size_t inputLen, char sep, CSVValue * values, size_t maxValues, size_t & numValues);
static bool ReadCSVLine(FILE * inFile, char * buf, size_t bufSize, CSVValue * values, size_t maxValues, size_t & numValues);
static bool WriteCSVLine(FILE * outFile, CSVValue * values, size_t numValues);
static bool ConvertCertificate(const char * inCertB64, size_t inCertB64Len, CertFormat outCertFormat, char * & outCertB64, size_t & outCertB64Len);
static bool ConvertPrivateKey(const char * inKeyB64, size_t inKeyB64Len, KeyFormat keyFormat, char * & outKeyB64, size_t & outKeyB64Len);
static size_t FindColumnByPrefix(const CSVValue * colNames, size_t numCols, const char * prefix, size_t prefixLen);
enum
{
kToolOpt_WeaveCert = 1000,
kToolOpt_DERCert = 1001,
kToolOpt_WeaveKey = 1002,
kToolOpt_DERKey = 1003,
kToolOpt_PKCS8Key = 1004,
};
static OptionDef gCmdOptionDefs[] =
{
{ "weave", kNoArgument, 'w' },
{ "der", kNoArgument, 'x' },
{ "weave-cert", kNoArgument, kToolOpt_WeaveCert },
{ "der-cert", kNoArgument, kToolOpt_DERCert },
{ "weave-key", kNoArgument, kToolOpt_WeaveKey },
{ "der-key", kNoArgument, kToolOpt_DERKey },
{ "pkcs8-key", kNoArgument, kToolOpt_PKCS8Key },
{ NULL }
};
static const char *const gCmdOptionHelp =
" -w, --weave\n"
"\n"
" Convert the certificate and private key to Weave TLV format.\n"
"\n"
" -x, --der\n"
"\n"
" Convert the certificate and private key to DER format. The certificate\n"
" is output in X.509 form, while the private key is output in SEC1/RFC-5915\n"
" form.\n"
"\n"
" --weave-cert\n"
"\n"
" Convert the certificate to Weave TLV format.\n"
"\n"
" --der-cert\n"
"\n"
" Convert the certificate to X.509 DER format.\n"
"\n"
" --weave-key\n"
"\n"
" Convert the private key to Weave TLV format.\n"
"\n"
" --der-key\n"
"\n"
" Convert the private key to SEC1/RFC-5915 DER format.\n"
"\n"
" --pkcs8-key\n"
"\n"
" Convert the private key to PKCS#8 DER format.\n"
"\n"
;
static OptionSet gCmdOptions =
{
HandleOption,
gCmdOptionDefs,
"COMMAND OPTIONS",
gCmdOptionHelp
};
static HelpOptions gHelpOptions(
CMD_NAME,
"Usage: " CMD_NAME " [ <options...> ] <in-file> <out-file>\n",
WEAVE_VERSION_STRING "\n" COPYRIGHT_STRING,
"Perform various conversions on a device provisioning data file.\n"
"\n"
"ARGUMENTS\n"
"\n"
" <in-file>\n"
"\n"
" A CSV file containing provisioning data to be converted, or - to read from\n"
" stdin. The first line of this file must contain names for each of the CSV\n"
" columns. Depending on which conversions are requested, the following columns\n"
" must be present:\n"
"\n"
" Certificate - Certificate in Weave TLV form, base-64 encoded\n"
" Certificate DER - Certificate in X.509 DER form, base-64 encoded\n"
" Private Key - Private key in Weave TLV form, base-64 encoded\n"
" Private Key DER - Private key in SEC1/RFC-5915 DER form, base-64 encoded\n"
" Private Key PKCS8 - Private key in PKCS8 DER form, base-64 encoded\n"
"\n"
" Any additional columns present in the input will be passed through to the output\n"
" without modification.\n"
"\n"
" <out-file>\n"
"\n"
" The CSV file to which the converted provisioning data should be written, or\n"
" - to write to stdout.\n"
"\n"
);
static OptionSet *gCmdOptionSets[] =
{
&gCmdOptions,
&gHelpOptions,
NULL
};
static const char *gInFileName;
static const char *gOutFileName;
static CertFormat gCertFormat = kCertFormat_Unknown;
static KeyFormat gKeyFormat = kKeyFormat_Unknown;
static const char gColumnName_Certificate[] = "Certificate";
static const size_t gColumnName_CertificateLen = sizeof(gColumnName_Certificate) - 1;
static const char gColumnName_CertificateDER[] = "Certificate DER";
static const size_t gColumnName_CertificateDERLen = sizeof(gColumnName_CertificateDER) - 1;
static const char gColumnName_PrivateKey[] = "Private Key";
static const size_t gColumnName_PrivateKeyLen = sizeof(gColumnName_PrivateKey) - 1;
static const char gColumnName_PrivateKeyDER[] = "Private Key DER";
static const size_t gColumnName_PrivateKeyDERLen = sizeof(gColumnName_PrivateKeyDER) - 1;
static const char gColumnName_PrivateKeyPKCS8[] = "Private Key PKCS8";
static const size_t gColumnName_PrivateKeyPKCS8Len = sizeof(gColumnName_PrivateKeyPKCS8) - 1;
bool Cmd_ConvertProvisioningData(int argc, char *argv[])
{
enum
{
kMaxLineLength = 2048,
kMaxCSVColumns = 20,
};
static char inBuf[kMaxLineLength];
static CSVValue inValues[kMaxCSVColumns];
bool res = true;
FILE * inFile = NULL;
FILE * outFile = NULL;
char * convertedCert = NULL;
size_t convertedCertLen = 0;
char * convertedKey = NULL;
size_t convertedKeyLen = 0;
size_t numCols;
size_t certCol, privKeyCol;
bool outFileCreated = false;
if (argc == 1)
{
gHelpOptions.PrintBriefUsage(stderr);
ExitNow(res = true);
}
if (!ParseArgs(CMD_NAME, argc, argv, gCmdOptionSets, HandleNonOptionArgs))
{
ExitNow(res = false);
}
// Open the input file.
if (strcmp(gInFileName, "-") != 0)
{
inFile = fopen(gInFileName, "rb");
if (inFile == NULL)
{
fprintf(stderr, "weave: Unable to open %s\n%s\n", gInFileName, strerror(errno));
ExitNow(res = false);
}
}
else
inFile = stdin;
// Open the output file.
if (strcmp(gOutFileName, "-") != 0)
{
outFile = fopen(gOutFileName, "w+b");
if (outFile == NULL)
{
fprintf(stderr, "weave: Unable to create %s\n%s\n", gOutFileName, strerror(errno));
ExitNow(res = false);
}
outFileCreated = true;
}
else
outFile = stdout;
// Initialize OpenSSL.
if (!InitOpenSSL())
ExitNow(res = false);
// Read the header line
if (!ReadCSVLine(inFile, inBuf, sizeof(inBuf), inValues, kMaxCSVColumns, numCols))
{
ExitNow(res = false);
}
// Search for a column whose name begins with "Certificate". Fail if requested to perform
// certificate conversion and no Certificate column exists.
certCol = FindColumnByPrefix(inValues, numCols, gColumnName_Certificate, gColumnName_CertificateLen);
if (gCertFormat != kCertFormat_Unknown && certCol == numCols)
{
fprintf(stderr, "weave: No Certificate column in input data\n");
ExitNow(res = false);
}
// Search for a column whose name begins with "Private Key".
privKeyCol = FindColumnByPrefix(inValues, numCols, gColumnName_PrivateKey, gColumnName_PrivateKeyLen);
if (gKeyFormat != kKeyFormat_Unknown && privKeyCol == numCols)
{
fprintf(stderr, "weave: No Private Key column in input data\n");
ExitNow(res = false);
}
// Write the column names line to the output, substituting the appropriate name for the
// columns being converted.
switch (gCertFormat)
{
case kCertFormat_Unknown:
break;
case kCertFormat_Weave_Base64:
inValues[certCol].Data = gColumnName_Certificate;
inValues[certCol].Length = gColumnName_CertificateLen;
break;
case kCertFormat_X509_DER:
inValues[certCol].Data = gColumnName_CertificateDER;
inValues[certCol].Length = gColumnName_CertificateDERLen;
break;
default:
fprintf(stderr, "INTERNAL ERROR: Invalid certificate format\n");
ExitNow(res = false);
}
switch (gKeyFormat)
{
case kKeyFormat_Unknown:
break;
case kKeyFormat_Weave_Base64:
inValues[privKeyCol].Data = gColumnName_PrivateKey;
inValues[privKeyCol].Length = gColumnName_PrivateKeyLen;
break;
case kKeyFormat_DER:
inValues[privKeyCol].Data = gColumnName_PrivateKeyDER;
inValues[privKeyCol].Length = gColumnName_PrivateKeyDERLen;
break;
case kKeyFormat_DER_PKCS8:
inValues[privKeyCol].Data = gColumnName_PrivateKeyPKCS8;
inValues[privKeyCol].Length = gColumnName_PrivateKeyPKCS8Len;
break;
default:
fprintf(stderr, "INTERNAL ERROR: Invalid key format\n");
ExitNow(res = false);
}
if (!WriteCSVLine(outFile, inValues, numCols))
{
ExitNow(res = false);
}
// Read the remaining lines in the file, converting the appropriate values...
while (true)
{
if (!ReadCSVLine(inFile, inBuf, sizeof(inBuf), inValues, kMaxCSVColumns, numCols))
{
ExitNow(res = false);
}
if (numCols == 0 && feof(inFile))
{
break;
}
if (gCertFormat != kCertFormat_Unknown && numCols > certCol)
{
if (!ConvertCertificate(inValues[certCol].Data, inValues[certCol].Length, gCertFormat, convertedCert, convertedCertLen))
{
ExitNow(res = false);
}
inValues[certCol].Data = convertedCert;
inValues[certCol].Length = convertedCertLen;
}
if (gKeyFormat != kKeyFormat_Unknown && numCols > privKeyCol)
{
if (!ConvertPrivateKey(inValues[privKeyCol].Data, inValues[privKeyCol].Length, gKeyFormat, convertedKey, convertedKeyLen))
{
ExitNow(res = false);
}
inValues[privKeyCol].Data = convertedKey;
inValues[privKeyCol].Length = convertedKeyLen;
}
if (!WriteCSVLine(outFile, inValues, numCols))
{
ExitNow(res = false);
}
if (convertedCert != NULL)
{
free(convertedCert);
convertedCert = NULL;
}
if (convertedKey != NULL)
{
free(convertedKey);
convertedKey = NULL;
}
}
exit:
if (inFile != NULL && inFile != stdin)
fclose(inFile);
if (outFile != NULL && outFile != stdout)
fclose(outFile);
if (gOutFileName != NULL && outFileCreated && !res)
unlink(gOutFileName);
if (convertedCert != NULL)
free(convertedCert);
if (convertedKey != NULL)
free(convertedKey);
return res;
}
bool HandleOption(const char * progName, OptionSet * optSet, int id, const char * name, const char * arg)
{
switch (id)
{
case 'w':
gCertFormat = kCertFormat_Weave_Base64;
gKeyFormat = kKeyFormat_Weave_Base64;
break;
case 'x':
gCertFormat = kCertFormat_X509_DER;
gKeyFormat = kKeyFormat_DER;
break;
case kToolOpt_WeaveCert:
gCertFormat = kCertFormat_Weave_Base64;
break;
case kToolOpt_DERCert:
gCertFormat = kCertFormat_X509_DER;
break;
case kToolOpt_WeaveKey:
gKeyFormat = kKeyFormat_Weave_Base64;
break;
case kToolOpt_DERKey:
gKeyFormat = kKeyFormat_DER;
break;
case kToolOpt_PKCS8Key:
gKeyFormat = kKeyFormat_DER_PKCS8;
break;
default:
PrintArgError("%s: INTERNAL ERROR: Unhandled option: %s\n", progName, name);
return false;
}
return true;
}
bool HandleNonOptionArgs(const char * progName, int argc, char * argv[])
{
if (argc == 0)
{
PrintArgError("%s: Please specify the name of the input key file, or - for stdin.\n", progName);
return false;
}
if (argc == 1)
{
PrintArgError("%s: Please specify the name of the output key file, or - for stdout\n", progName);
return false;
}
if (argc > 2)
{
PrintArgError("%s: Unexpected argument: %s\n", progName, argv[2]);
return false;
}
gInFileName = argv[0];
gOutFileName = argv[1];
return true;
}
void TrimSpace(const char * & p, size_t & len)
{
while (len > 0 && isspace(*p))
{
p++;
len--;
}
while (len > 0 && isspace(p[len - 1]))
{
len--;
}
}
bool ParseCSVLine(const char * input, size_t inputLen, char sep, CSVValue * values, size_t maxValues, size_t & numValues)
{
for (numValues = 0; inputLen > 0 && numValues < maxValues; numValues++)
{
CSVValue & value = values[numValues];
value.Data = input;
char * valueEnd = (char *)memchr(input, sep, inputLen);
if (valueEnd != NULL)
{
value.Length = valueEnd - input;
input = valueEnd + 1;
inputLen -= value.Length + 1;
}
else
{
value.Length = inputLen;
inputLen = 0;
}
TrimSpace(value.Data, value.Length);
}
if (inputLen != 0)
{
fprintf(stderr, "weave: Too many fields in input line\n");
return false;
}
return true;
}
bool ReadCSVLine(FILE * inFile, char * buf, size_t bufSize, CSVValue * values, size_t maxValues, size_t & numValues)
{
if (fgets(buf, bufSize, inFile) == NULL)
{
if (feof(inFile))
{
numValues = 0;
return true;
}
fprintf(stderr, "weave: Error reading input file\n%s\n", strerror(errno));
return false;
}
size_t lineLen = strlen(buf);
if (lineLen == bufSize - 1 && buf[lineLen - 1] != '\n')
{
fprintf(stderr, "weave: Input line too long\n");
return false;
}
return ParseCSVLine(buf, lineLen, ',', values, maxValues, numValues);
}
bool WriteCSVLine(FILE * outFile, CSVValue * values, size_t numValues)
{
bool res = true;
for (size_t i = 0; i < numValues; i++)
{
if (i != 0 && fputc(',', outFile) == EOF)
{
ExitNow(res = false);
}
if (fwrite(values[i].Data, 1, values[i].Length, outFile) != values[i].Length)
{
ExitNow(res = false);
}
}
res = (fputc('\n', outFile) != EOF);
exit:
if (!res)
{
fprintf(stderr, "weave: Error writing output file\n%s\n", strerror(ferror(outFile) ? errno : ENOSPC));
}
return res;
}
bool ConvertCertificate(const char * inCertB64, size_t inCertB64Len, CertFormat outCertFormat, char * & outCertB64, size_t & outCertB64Len)
{
bool res = true;
WEAVE_ERROR err;
uint8_t * inCert = NULL;
uint32_t inCertLen;
uint8_t * outCert = NULL;
uint32_t outCertLen;
CertFormat inCertFormat;
inCert = Base64Decode((const uint8_t *)inCertB64, (uint32_t)inCertB64Len, NULL, 0, inCertLen);
if (inCert == NULL)
{
ExitNow(res = false);
}
inCertFormat = DetectCertFormat(inCert, inCertLen);
if (inCertFormat != kCertFormat_Weave_Raw && inCertFormat != kCertFormat_X509_DER)
{
fprintf(stderr, "weave: Unrecognized certificate format: %*s\n", (int)inCertB64Len, inCertB64);
ExitNow(res = false);
}
outCertLen = inCertLen * 100;
outCert = (uint8_t *)malloc(outCertLen);
if (outCert == NULL)
{
fprintf(stderr, "weave: Memory allocation failure\n");
ExitNow(res = false);
}
if (inCertFormat == kCertFormat_Weave_Raw && outCertFormat == kCertFormat_X509_DER)
{
err = ConvertWeaveCertToX509Cert(inCert, inCertLen, outCert, outCertLen, outCertLen);
if (err != WEAVE_NO_ERROR)
{
fprintf(stderr, "weave: Error converting certificate: %s\n", nl::ErrorStr(err));
ExitNow(res = false);
}
}
else if (inCertFormat == kCertFormat_X509_DER && outCertFormat == kCertFormat_Weave_Base64)
{
err = ConvertX509CertToWeaveCert(inCert, inCertLen, outCert, outCertLen, outCertLen);
if (err != WEAVE_NO_ERROR)
{
fprintf(stderr, "weave: Error converting certificate: %s\n", nl::ErrorStr(err));
ExitNow(res = false);
}
}
else
{
memcpy(outCert, inCert, inCertLen);
outCertLen = inCertLen;
}
outCertB64 = Base64Encode(outCert, outCertLen);
if (outCertB64 == NULL)
{
ExitNow(res = false);
}
outCertB64Len = strlen(outCertB64);
exit:
if (inCert != NULL)
{
free(inCert);
}
if (outCert != NULL)
{
free(outCert);
}
return res;
}
bool ConvertPrivateKey(const char * inKeyB64, size_t inKeyB64Len, KeyFormat keyFormat, char * & outKeyB64, size_t & outKeyB64Len)
{
bool res = true;
uint8_t * inKey = NULL;
uint32_t inKeyLen;
EVP_PKEY *inKeyDecoded = NULL;
uint8_t *outKey = NULL;
uint32_t outKeyLen;
inKey = Base64Decode((const uint8_t *)inKeyB64, (uint32_t)inKeyB64Len, NULL, 0, inKeyLen);
if (inKey == NULL)
{
ExitNow(res = false);
}
if (!DecodePrivateKey(inKey, inKeyLen, kKeyFormat_Unknown, "", NULL, inKeyDecoded))
{
ExitNow(res = false);
}
// When Weave key format is requested, have EncodePrivateKey() encode to raw bytes, rather
// than base64, since base64 encoding is handled below.
if (keyFormat == kKeyFormat_Weave_Base64)
{
keyFormat = kKeyFormat_Weave_Raw;
}
if (!EncodePrivateKey(inKeyDecoded, keyFormat, outKey, outKeyLen))
{
ExitNow(res = false);
}
outKeyB64 = Base64Encode(outKey, outKeyLen);
if (outKeyB64 == NULL)
{
ExitNow(res = false);
}
outKeyB64Len = strlen(outKeyB64);
exit:
if (inKey != NULL)
{
free(inKey);
}
if (inKeyDecoded != NULL)
{
EVP_PKEY_free(inKeyDecoded);
}
if (outKey != NULL)
{
free(outKey);
}
return res;
}
size_t FindColumnByPrefix(const CSVValue * colNames, size_t numCols, const char * prefix, size_t prefixLen)
{
size_t i;
// Search for a column whose name matches prefix.
for (i = 0; i < numCols; i++)
{
if (colNames[i].Length >= prefixLen &&
memcmp(colNames[i].Data, prefix, prefixLen) == 0)
{
break;
}
}
return i;
}
| 19,822 | 6,731 |
// Generated from /POI/java/org/apache/poi/ss/formula/FormulaRenderer.java
#include <org/apache/poi/ss/formula/FormulaRenderer.hpp>
#include <java/io/Serializable.hpp>
#include <java/lang/ArrayStoreException.hpp>
#include <java/lang/CharSequence.hpp>
#include <java/lang/ClassCastException.hpp>
#include <java/lang/Comparable.hpp>
#include <java/lang/IllegalArgumentException.hpp>
#include <java/lang/IllegalStateException.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/RuntimeException.hpp>
#include <java/lang/String.hpp>
#include <java/lang/StringBuilder.hpp>
#include <java/util/Stack.hpp>
#include <org/apache/poi/ss/formula/WorkbookDependentFormula.hpp>
#include <org/apache/poi/ss/formula/ptg/AttrPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/MemAreaPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/MemErrPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/MemFuncPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/OperationPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/ParenthesisPtg.hpp>
#include <org/apache/poi/ss/formula/ptg/Ptg.hpp>
#include <SubArray.hpp>
#include <ObjectArray.hpp>
template<typename ComponentType, typename... Bases> struct SubArray;
namespace java
{
namespace io
{
typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray;
} // io
namespace lang
{
typedef ::SubArray< ::java::lang::CharSequence, ObjectArray > CharSequenceArray;
typedef ::SubArray< ::java::lang::Comparable, ObjectArray > ComparableArray;
typedef ::SubArray< ::java::lang::String, ObjectArray, ::java::io::SerializableArray, ComparableArray, CharSequenceArray > StringArray;
} // lang
} // java
namespace poi
{
namespace ss
{
namespace formula
{
namespace ptg
{
typedef ::SubArray< ::poi::ss::formula::ptg::Ptg, ::java::lang::ObjectArray > PtgArray;
} // ptg
} // formula
} // ss
} // poi
template<typename T, typename U>
static T java_cast(U* u)
{
if(!u) return static_cast<T>(nullptr);
auto t = dynamic_cast<T>(u);
if(!t) throw new ::java::lang::ClassCastException();
return t;
}
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
poi::ss::formula::FormulaRenderer::FormulaRenderer(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
poi::ss::formula::FormulaRenderer::FormulaRenderer()
: FormulaRenderer(*static_cast< ::default_init_tag* >(0))
{
ctor();
}
java::lang::String* poi::ss::formula::FormulaRenderer::toFormulaString(FormulaRenderingWorkbook* book, ::poi::ss::formula::ptg::PtgArray* ptgs)
{
clinit();
if(ptgs == nullptr || npc(ptgs)->length == 0) {
throw new ::java::lang::IllegalArgumentException(u"ptgs must not be null"_j);
}
auto stack = new ::java::util::Stack();
for(auto ptg : *npc(ptgs)) {
if(dynamic_cast< ::poi::ss::formula::ptg::MemAreaPtg* >(ptg) != nullptr || dynamic_cast< ::poi::ss::formula::ptg::MemFuncPtg* >(ptg) != nullptr || dynamic_cast< ::poi::ss::formula::ptg::MemErrPtg* >(ptg) != nullptr) {
continue;
}
if(dynamic_cast< ::poi::ss::formula::ptg::ParenthesisPtg* >(ptg) != nullptr) {
auto contents = java_cast< ::java::lang::String* >(npc(stack)->pop());
npc(stack)->push(::java::lang::StringBuilder().append(u"("_j)->append(contents)
->append(u")"_j)->toString());
continue;
}
if(dynamic_cast< ::poi::ss::formula::ptg::AttrPtg* >(ptg) != nullptr) {
auto attrPtg = (java_cast< ::poi::ss::formula::ptg::AttrPtg* >(ptg));
if(npc(attrPtg)->isOptimizedIf() || npc(attrPtg)->isOptimizedChoose() || npc(attrPtg)->isSkip()) {
continue;
}
if(npc(attrPtg)->isSpace()) {
continue;
}
if(npc(attrPtg)->isSemiVolatile()) {
continue;
}
if(npc(attrPtg)->isSum()) {
auto operands = getOperands(stack, npc(attrPtg)->getNumberOfOperands());
npc(stack)->push(npc(attrPtg)->toFormulaString(operands));
continue;
}
throw new ::java::lang::RuntimeException(::java::lang::StringBuilder().append(u"Unexpected tAttr: "_j)->append(static_cast< ::java::lang::Object* >(attrPtg))->toString());
}
if(dynamic_cast< WorkbookDependentFormula* >(ptg) != nullptr) {
auto optg = java_cast< WorkbookDependentFormula* >(ptg);
npc(stack)->push(npc(optg)->toFormulaString(book));
continue;
}
if(!(dynamic_cast< ::poi::ss::formula::ptg::OperationPtg* >(ptg) != nullptr)) {
npc(stack)->push(npc(ptg)->toFormulaString());
continue;
}
auto o = java_cast< ::poi::ss::formula::ptg::OperationPtg* >(ptg);
auto operands = getOperands(stack, npc(o)->getNumberOfOperands());
npc(stack)->push(npc(o)->toFormulaString(operands));
}
if(npc(stack)->isEmpty()) {
throw new ::java::lang::IllegalStateException(u"Stack underflow"_j);
}
auto result = java_cast< ::java::lang::String* >(npc(stack)->pop());
if(!npc(stack)->isEmpty()) {
throw new ::java::lang::IllegalStateException(u"too much stuff left on the stack"_j);
}
return result;
}
java::lang::StringArray* poi::ss::formula::FormulaRenderer::getOperands(::java::util::Stack* stack, int32_t nOperands)
{
clinit();
auto operands = new ::java::lang::StringArray(nOperands);
for (auto j = nOperands - int32_t(1); j >= 0; j--) {
if(npc(stack)->isEmpty()) {
auto msg = ::java::lang::StringBuilder().append(u"Too few arguments supplied to operation. Expected ("_j)->append(nOperands)
->append(u") operands but got ("_j)
->append((nOperands - j - int32_t(1)))
->append(u")"_j)->toString();
throw new ::java::lang::IllegalStateException(msg);
}
operands->set(j, java_cast< ::java::lang::String* >(npc(stack)->pop()));
}
return operands;
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::ss::formula::FormulaRenderer::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.FormulaRenderer", 41);
return c;
}
java::lang::Class* poi::ss::formula::FormulaRenderer::getClass0()
{
return class_();
}
| 6,566 | 2,299 |
/**
* \class L1GlobalTriggerObjectMapRecord
*
*
* Description: see header file.
*
* Implementation:
* <TODO: enter implementation details>
*
* \author: Vasile Mihai Ghete - HEPHY Vienna
* \author: W. David Dagenhart
*
*
*/
#include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerObjectMaps.h"
#include <algorithm>
#include <limits>
#include "FWCore/Utilities/interface/Exception.h"
void L1GlobalTriggerObjectMaps::swap(L1GlobalTriggerObjectMaps& rh) {
m_algorithmResults.swap(rh.m_algorithmResults);
m_conditionResults.swap(rh.m_conditionResults);
m_combinations.swap(rh.m_combinations);
m_namesParameterSetID.swap(rh.m_namesParameterSetID);
}
bool L1GlobalTriggerObjectMaps::algorithmExists(int algorithmBitNumber) const {
std::vector<AlgorithmResult>::const_iterator i = std::lower_bound(
m_algorithmResults.begin(), m_algorithmResults.end(), AlgorithmResult(0, algorithmBitNumber, false));
if (i == m_algorithmResults.end() || i->algorithmBitNumber() != algorithmBitNumber) {
return false;
}
return true;
}
bool L1GlobalTriggerObjectMaps::algorithmResult(int algorithmBitNumber) const {
std::vector<AlgorithmResult>::const_iterator i = std::lower_bound(
m_algorithmResults.begin(), m_algorithmResults.end(), AlgorithmResult(0, algorithmBitNumber, false));
if (i == m_algorithmResults.end() || i->algorithmBitNumber() != algorithmBitNumber) {
cms::Exception ex("L1GlobalTrigger");
ex << "algorithmBitNumber not found";
ex.addContext("Calling L1GlobalTriggerObjectMaps::algorithmResult");
throw ex;
}
return i->algorithmResult();
}
void L1GlobalTriggerObjectMaps::updateOperandTokenVector(
int algorithmBitNumber, std::vector<L1GtLogicParser::OperandToken>& operandTokenVector) const {
unsigned startIndex = 0;
unsigned endIndex = 0;
getStartEndIndex(algorithmBitNumber, startIndex, endIndex);
unsigned length = endIndex - startIndex;
if (length != operandTokenVector.size()) {
cms::Exception ex("L1GlobalTrigger");
ex << "operand token vector size does not match number of conditions";
ex.addContext("Calling L1GlobalTriggerObjectMaps::updateOperandTokenVector");
throw ex;
}
for (unsigned i = 0; i < length; ++i) {
operandTokenVector[i].tokenResult = m_conditionResults[startIndex + i].conditionResult();
}
}
void L1GlobalTriggerObjectMaps::getAlgorithmBitNumbers(std::vector<int>& algorithmBitNumbers) const {
algorithmBitNumbers.clear();
for (std::vector<AlgorithmResult>::const_iterator i = m_algorithmResults.begin(), iEnd = m_algorithmResults.end();
i != iEnd;
++i) {
algorithmBitNumbers.push_back(i->algorithmBitNumber());
}
}
unsigned L1GlobalTriggerObjectMaps::getNumberOfConditions(int algorithmBitNumber) const {
unsigned startIndex = 0;
unsigned endIndex = 0;
getStartEndIndex(algorithmBitNumber, startIndex, endIndex);
return endIndex - startIndex;
}
L1GlobalTriggerObjectMaps::ConditionsInAlgorithm L1GlobalTriggerObjectMaps::getConditionsInAlgorithm(
int algorithmBitNumber) const {
unsigned startIndex = 0;
unsigned endIndex = 0;
getStartEndIndex(algorithmBitNumber, startIndex, endIndex);
return ConditionsInAlgorithm(&m_conditionResults[startIndex], endIndex - startIndex);
}
L1GlobalTriggerObjectMaps::CombinationsInCondition L1GlobalTriggerObjectMaps::getCombinationsInCondition(
int algorithmBitNumber, unsigned conditionNumber) const {
unsigned startIndex = 0;
unsigned endIndex = 0;
getStartEndIndex(algorithmBitNumber, startIndex, endIndex);
if (endIndex <= startIndex + conditionNumber) {
cms::Exception ex("L1GlobalTrigger");
ex << "Condition number is out of range";
ex.addContext("Calling L1GlobalTriggerObjectMaps::getCombinationsInCondition");
throw ex;
}
unsigned endObjectIndex = m_combinations.size();
unsigned nextConditionIndex = startIndex + conditionNumber + 1U;
if (nextConditionIndex < m_conditionResults.size()) {
endObjectIndex = m_conditionResults[nextConditionIndex].startIndexOfCombinations();
}
unsigned beginObjectIndex = m_conditionResults[startIndex + conditionNumber].startIndexOfCombinations();
unsigned short nObjectsPerCombination = m_conditionResults[startIndex + conditionNumber].nObjectsPerCombination();
if (endObjectIndex == beginObjectIndex) {
return CombinationsInCondition(nullptr, 0, 0);
}
if (endObjectIndex < beginObjectIndex || m_combinations.size() < endObjectIndex || nObjectsPerCombination == 0 ||
(endObjectIndex - beginObjectIndex) % nObjectsPerCombination != 0) {
cms::Exception ex("L1GlobalTrigger");
ex << "Indexes to combinations are invalid";
ex.addContext("Calling L1GlobalTriggerObjectMaps::getCombinationsInCondition");
throw ex;
}
return CombinationsInCondition(&m_combinations[beginObjectIndex],
(endObjectIndex - beginObjectIndex) / nObjectsPerCombination,
nObjectsPerCombination);
}
void L1GlobalTriggerObjectMaps::reserveForAlgorithms(unsigned n) { m_algorithmResults.reserve(n); }
void L1GlobalTriggerObjectMaps::pushBackAlgorithm(unsigned startIndexOfConditions,
int algorithmBitNumber,
bool algorithmResult) {
m_algorithmResults.push_back(AlgorithmResult(startIndexOfConditions, algorithmBitNumber, algorithmResult));
}
void L1GlobalTriggerObjectMaps::consistencyCheck() const {
// None of these checks should ever fail unless there
// is a bug in the code filling this object
for (std::vector<AlgorithmResult>::const_iterator i = m_algorithmResults.begin(), iEnd = m_algorithmResults.end();
i != iEnd;
++i) {
std::vector<AlgorithmResult>::const_iterator j = i;
++j;
if (j != iEnd && !(*i < *j)) {
cms::Exception ex("L1GlobalTrigger");
ex << "AlgorithmResults should be sorted in increasing order of bit number with no duplicates. It is not.";
ex.addContext("Calling L1GlobalTriggerObjectMaps::consistencyCheck");
throw ex;
}
unsigned endIndex = (j != iEnd) ? j->startIndexOfConditions() : m_conditionResults.size();
if (endIndex < i->startIndexOfConditions()) {
cms::Exception ex("L1GlobalTrigger");
ex << "startIndexOfConditions decreases or exceeds the size of m_conditionResults";
ex.addContext("Calling L1GlobalTriggerObjectMaps::consistencyCheck");
throw ex;
}
}
for (std::vector<ConditionResult>::const_iterator i = m_conditionResults.begin(), iEnd = m_conditionResults.end();
i != iEnd;
++i) {
std::vector<ConditionResult>::const_iterator j = i;
++j;
unsigned endIndex = (j != iEnd) ? j->startIndexOfCombinations() : m_combinations.size();
if (endIndex < i->startIndexOfCombinations()) {
cms::Exception ex("L1GlobalTrigger");
ex << "startIndexOfCombinations decreases or exceeds the size of m_conditionResults";
ex.addContext("Calling L1GlobalTriggerObjectMaps::consistencyCheck");
throw ex;
}
unsigned length = endIndex - i->startIndexOfCombinations();
if (length == 0U) {
if (i->nObjectsPerCombination() != 0U) {
cms::Exception ex("L1GlobalTrigger");
ex << "Length is zero and nObjectsInCombination is not zero";
ex.addContext("Calling L1GlobalTriggerObjectMaps::consistencyCheck");
throw ex;
}
} else {
if (i->nObjectsPerCombination() == 0 || length % i->nObjectsPerCombination() != 0) {
cms::Exception ex("L1GlobalTrigger");
ex << "Size indicated by startIndexOfCombinations is not a multiple of nObjectsInCombination";
ex.addContext("Calling L1GlobalTriggerObjectMaps::consistencyCheck");
throw ex;
}
}
}
}
void L1GlobalTriggerObjectMaps::reserveForConditions(unsigned n) { m_conditionResults.reserve(n); }
void L1GlobalTriggerObjectMaps::pushBackCondition(unsigned startIndexOfCombinations,
unsigned short nObjectsPerCombination,
bool conditionResult) {
m_conditionResults.push_back(ConditionResult(startIndexOfCombinations, nObjectsPerCombination, conditionResult));
}
void L1GlobalTriggerObjectMaps::reserveForObjectIndexes(unsigned n) { m_combinations.reserve(n); }
void L1GlobalTriggerObjectMaps::pushBackObjectIndex(unsigned char objectIndex) {
m_combinations.push_back(objectIndex);
}
void L1GlobalTriggerObjectMaps::setNamesParameterSetID(edm::ParameterSetID const& psetID) {
m_namesParameterSetID = psetID;
}
L1GlobalTriggerObjectMaps::AlgorithmResult::AlgorithmResult()
: m_startIndexOfConditions(0), m_algorithmBitNumber(0), m_algorithmResult(false) {}
L1GlobalTriggerObjectMaps::AlgorithmResult::AlgorithmResult(unsigned startIndexOfConditions,
int algorithmBitNumber,
bool algorithmResult)
: m_startIndexOfConditions(startIndexOfConditions), m_algorithmResult(algorithmResult) {
// We made the decision to try to save space in the data format
// and fit this object into 8 bytes by making the persistent
// algorithmBitNumber a short. This creates something very
// ugly below. In practice the range should never be exceeded.
// In fact it is currently always supposed to be less than 128.
// I hope this never comes back to haunt us for some unexpected reason.
// I cringe when I look at it, but cannot think of any practical
// harm ... It is probably a real bug if anyone ever
// tries to shove a big int into here.
if (algorithmBitNumber < std::numeric_limits<short>::min() ||
algorithmBitNumber > std::numeric_limits<short>::max()) {
cms::Exception ex("L1GlobalTrigger");
ex << "algorithmBitNumber out of range of a short int";
ex.addContext("Calling L1GlobalTriggerObjectMaps::AlgorithmResult::AlgorithmResult");
throw ex;
}
m_algorithmBitNumber = static_cast<short>(algorithmBitNumber);
}
L1GlobalTriggerObjectMaps::ConditionResult::ConditionResult()
: m_startIndexOfCombinations(0), m_nObjectsPerCombination(0), m_conditionResult(false) {}
L1GlobalTriggerObjectMaps::ConditionResult::ConditionResult(unsigned startIndexOfCombinations,
unsigned short nObjectsPerCombination,
bool conditionResult)
: m_startIndexOfCombinations(startIndexOfCombinations),
m_nObjectsPerCombination(nObjectsPerCombination),
m_conditionResult(conditionResult) {}
L1GlobalTriggerObjectMaps::ConditionsInAlgorithm::ConditionsInAlgorithm(ConditionResult const* conditionResults,
unsigned nConditions)
: m_conditionResults(conditionResults), m_nConditions(nConditions) {}
bool L1GlobalTriggerObjectMaps::ConditionsInAlgorithm::getConditionResult(unsigned condition) const {
if (condition >= m_nConditions) {
cms::Exception ex("L1GlobalTrigger");
ex << "argument out of range";
ex.addContext("Calling L1GlobalTriggerObjectMaps::ConditionsInAlgorithm::getConditionResult");
throw ex;
}
return (m_conditionResults + condition)->conditionResult();
}
L1GlobalTriggerObjectMaps::CombinationsInCondition::CombinationsInCondition(unsigned char const* startOfObjectIndexes,
unsigned nCombinations,
unsigned short nObjectsPerCombination)
: m_startOfObjectIndexes(startOfObjectIndexes),
m_nCombinations(nCombinations),
m_nObjectsPerCombination(nObjectsPerCombination) {}
unsigned char L1GlobalTriggerObjectMaps::CombinationsInCondition::getObjectIndex(unsigned combination,
unsigned object) const {
if (combination >= m_nCombinations || object >= m_nObjectsPerCombination) {
cms::Exception ex("L1GlobalTrigger");
ex << "arguments out of range";
ex.addContext("Calling L1GlobalTriggerObjectMaps::CombinationsInCondition::getObjectIndex");
throw ex;
}
return m_startOfObjectIndexes[combination * m_nObjectsPerCombination + object];
}
void L1GlobalTriggerObjectMaps::getStartEndIndex(int algorithmBitNumber,
unsigned& startIndex,
unsigned& endIndex) const {
std::vector<AlgorithmResult>::const_iterator iAlgo = std::lower_bound(
m_algorithmResults.begin(), m_algorithmResults.end(), AlgorithmResult(0, algorithmBitNumber, false));
if (iAlgo == m_algorithmResults.end() || iAlgo->algorithmBitNumber() != algorithmBitNumber) {
cms::Exception ex("L1GlobalTrigger");
ex << "algorithmBitNumber not found";
ex.addContext("Calling L1GlobalTriggerObjectMaps::getStartEndIndex");
throw ex;
}
startIndex = iAlgo->startIndexOfConditions();
++iAlgo;
endIndex = (iAlgo != m_algorithmResults.end()) ? iAlgo->startIndexOfConditions() : m_conditionResults.size();
if (endIndex < startIndex || m_conditionResults.size() < endIndex) {
cms::Exception ex("L1GlobalTrigger");
ex << "index out of order or out of range";
ex.addContext("Calling L1GlobalTriggerObjectMaps::getStartEndIndex");
throw ex;
}
}
| 13,528 | 3,802 |
/*
* Copyright (c) 2017 - 2018, Intel Corporation
*
* 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 "unit_tests/os_interface/windows/wddm_fixture.h"
#include "runtime/execution_environment/execution_environment.h"
#include "runtime/gmm_helper/gmm.h"
#include "runtime/gmm_helper/gmm_helper.h"
#include "runtime/helpers/hw_info.h"
#include "runtime/helpers/options.h"
#include "runtime/memory_manager/os_agnostic_memory_manager.h"
#include "runtime/os_interface/windows/os_interface.h"
#include "runtime/os_interface/os_library.h"
#include "runtime/os_interface/windows/wddm_allocation.h"
#include "runtime/os_interface/windows/wddm_memory_manager.h"
#include "unit_tests/helpers/debug_manager_state_restore.h"
#include "unit_tests/mocks/mock_gmm_resource_info.h"
#include "gtest/gtest.h"
#include "runtime/os_interface/os_time.h"
#include <memory>
#include <functional>
using namespace OCLRT;
namespace GmmHelperFunctions {
Gmm *getGmm(void *ptr, size_t size) {
size_t alignedSize = alignSizeWholePage(ptr, size);
void *alignedPtr = alignUp(ptr, 4096);
Gmm *gmm = new Gmm(alignedPtr, alignedSize, false);
EXPECT_NE(gmm->gmmResourceInfo.get(), nullptr);
return gmm;
}
} // namespace GmmHelperFunctions
using Wddm20Tests = WddmTest;
using Wddm20WithMockGdiDllTests = WddmTestWithMockGdiDll;
using Wddm20InstrumentationTest = WddmInstrumentationTest;
HWTEST_F(Wddm20Tests, givenMinWindowsAddressWhenWddmIsInitializedThenWddmUseThisAddress) {
uintptr_t expectedAddress = 0x200000;
EXPECT_EQ(expectedAddress, OCLRT::windowsMinAddress);
bool status = wddm->init<FamilyType>();
EXPECT_TRUE(status);
EXPECT_TRUE(wddm->isInitialized());
EXPECT_EQ(expectedAddress, wddm->getWddmMinAddress());
}
HWTEST_F(Wddm20Tests, creation) {
bool error = wddm->init<FamilyType>();
EXPECT_TRUE(error);
EXPECT_TRUE(wddm->isInitialized());
}
HWTEST_F(Wddm20Tests, doubleCreation) {
bool error = wddm->init<FamilyType>();
EXPECT_EQ(1u, wddm->createContextResult.called);
error |= wddm->init<FamilyType>();
EXPECT_EQ(1u, wddm->createContextResult.called);
EXPECT_TRUE(error);
EXPECT_TRUE(wddm->isInitialized());
}
TEST_F(Wddm20Tests, givenNullPageTableManagerWhenUpdateAuxTableCalledThenReturnFalse) {
wddm->resetPageTableManager(nullptr);
EXPECT_EQ(nullptr, wddm->getPageTableManager());
auto gmm = std::unique_ptr<Gmm>(new Gmm(nullptr, 1, false));
auto mockGmmRes = reinterpret_cast<MockGmmResourceInfo *>(gmm->gmmResourceInfo.get());
mockGmmRes->setUnifiedAuxTranslationCapable();
EXPECT_FALSE(wddm->updateAuxTable(1234u, gmm.get(), true));
}
TEST(Wddm20EnumAdaptersTest, expectTrue) {
HardwareInfo outHwInfo;
const HardwareInfo hwInfo = *platformDevices[0];
OsLibrary *mockGdiDll = setAdapterInfo(hwInfo.pPlatform, hwInfo.pSysInfo);
bool success = Wddm::enumAdapters(outHwInfo);
EXPECT_TRUE(success);
const HardwareInfo *hwinfo = *platformDevices;
ASSERT_NE(nullptr, outHwInfo.pPlatform);
EXPECT_EQ(outHwInfo.pPlatform->eDisplayCoreFamily, hwinfo->pPlatform->eDisplayCoreFamily);
delete mockGdiDll;
delete outHwInfo.pPlatform;
delete outHwInfo.pSkuTable;
delete outHwInfo.pSysInfo;
delete outHwInfo.pWaTable;
}
TEST(Wddm20EnumAdaptersTest, givenEmptyHardwareInfoWhenEnumAdapterIsCalledThenCapabilityTableIsSet) {
HardwareInfo outHwInfo = {};
auto hwInfo = *platformDevices[0];
std::unique_ptr<OsLibrary> mockGdiDll(setAdapterInfo(hwInfo.pPlatform, hwInfo.pSysInfo));
bool success = Wddm::enumAdapters(outHwInfo);
EXPECT_TRUE(success);
const HardwareInfo *hwinfo = *platformDevices;
ASSERT_NE(nullptr, outHwInfo.pPlatform);
EXPECT_EQ(outHwInfo.pPlatform->eDisplayCoreFamily, hwinfo->pPlatform->eDisplayCoreFamily);
EXPECT_EQ(outHwInfo.capabilityTable.defaultProfilingTimerResolution, hwInfo.capabilityTable.defaultProfilingTimerResolution);
EXPECT_EQ(outHwInfo.capabilityTable.clVersionSupport, hwInfo.capabilityTable.clVersionSupport);
EXPECT_EQ(outHwInfo.capabilityTable.kmdNotifyProperties.enableKmdNotify, hwInfo.capabilityTable.kmdNotifyProperties.enableKmdNotify);
EXPECT_EQ(outHwInfo.capabilityTable.kmdNotifyProperties.delayKmdNotifyMicroseconds, hwInfo.capabilityTable.kmdNotifyProperties.delayKmdNotifyMicroseconds);
EXPECT_EQ(outHwInfo.capabilityTable.kmdNotifyProperties.enableQuickKmdSleep, hwInfo.capabilityTable.kmdNotifyProperties.enableQuickKmdSleep);
EXPECT_EQ(outHwInfo.capabilityTable.kmdNotifyProperties.delayQuickKmdSleepMicroseconds, hwInfo.capabilityTable.kmdNotifyProperties.delayQuickKmdSleepMicroseconds);
delete outHwInfo.pPlatform;
delete outHwInfo.pSkuTable;
delete outHwInfo.pSysInfo;
delete outHwInfo.pWaTable;
}
TEST(Wddm20EnumAdaptersTest, givenUnknownPlatformWhenEnumAdapterIsCalledThenFalseIsReturnedAndOutputIsEmpty) {
HardwareInfo outHwInfo;
memset(&outHwInfo, 0, sizeof(outHwInfo));
HardwareInfo hwInfo = *platformDevices[0];
auto bkp = hwInfo.pPlatform->eProductFamily;
PLATFORM platform = *(hwInfo.pPlatform);
platform.eProductFamily = IGFX_UNKNOWN;
std::unique_ptr<OsLibrary, std::function<void(OsLibrary *)>> mockGdiDll(
setAdapterInfo(&platform, hwInfo.pSysInfo),
[&](OsLibrary *ptr) {
platform.eProductFamily = bkp;
typedef void(__stdcall * pfSetAdapterInfo)(const void *, const void *);
pfSetAdapterInfo fSetAdpaterInfo = reinterpret_cast<pfSetAdapterInfo>(ptr->getProcAddress("MockSetAdapterInfo"));
fSetAdpaterInfo(&platform, hwInfo.pSysInfo);
delete ptr;
});
bool ret = Wddm::enumAdapters(outHwInfo);
EXPECT_FALSE(ret);
EXPECT_EQ(nullptr, outHwInfo.pPlatform);
EXPECT_EQ(nullptr, outHwInfo.pSkuTable);
EXPECT_EQ(nullptr, outHwInfo.pSysInfo);
EXPECT_EQ(nullptr, outHwInfo.pWaTable);
}
HWTEST_F(Wddm20Tests, context) {
EXPECT_TRUE(wddm->getOsDeviceContext() == static_cast<D3DKMT_HANDLE>(0));
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
EXPECT_TRUE(wddm->createContext());
auto context = wddm->getOsDeviceContext();
EXPECT_TRUE(context != static_cast<D3DKMT_HANDLE>(0));
EXPECT_TRUE(wddm->destroyContext(context));
}
HWTEST_F(Wddm20Tests, allocation) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
OsAgnosticMemoryManager mm(false);
WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr);
Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize());
allocation.gmm = gmm;
auto status = wddm->createAllocation(&allocation);
EXPECT_EQ(STATUS_SUCCESS, status);
EXPECT_TRUE(allocation.handle != 0);
auto error = wddm->destroyAllocation(&allocation);
EXPECT_TRUE(error);
delete gmm;
mm.freeSystemMemory(allocation.getUnderlyingBuffer());
}
HWTEST_F(Wddm20WithMockGdiDllTests, givenAllocationSmallerUnderlyingThanAlignedSizeWhenCreatedThenWddmUseAligned) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
void *ptr = reinterpret_cast<void *>(wddm->virtualAllocAddress + 0x1000);
size_t underlyingSize = 0x2100;
size_t alignedSize = 0x3000;
size_t underlyingPages = underlyingSize / MemoryConstants::pageSize;
size_t alignedPages = alignedSize / MemoryConstants::pageSize;
WddmAllocation allocation(ptr, 0x2100, ptr, 0x3000, nullptr);
Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getAlignedCpuPtr(), allocation.getAlignedSize());
allocation.gmm = gmm;
auto status = wddm->createAllocation(&allocation);
EXPECT_EQ(STATUS_SUCCESS, status);
EXPECT_NE(0, allocation.handle);
bool ret = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getAlignedSize(), allocation.is32BitAllocation, false, false);
EXPECT_TRUE(ret);
EXPECT_EQ(alignedPages, getLastCallMapGpuVaArgFcn()->SizeInPages);
EXPECT_NE(underlyingPages, getLastCallMapGpuVaArgFcn()->SizeInPages);
ret = wddm->destroyAllocation(&allocation);
EXPECT_TRUE(ret);
delete gmm;
}
HWTEST_F(Wddm20Tests, createAllocation32bit) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
uint64_t heap32baseAddress = 0x40000;
uint64_t heap32Size = 0x40000;
wddm->setHeap32(heap32baseAddress, heap32Size);
void *alignedPtr = (void *)0x12000;
size_t alignedSize = 0x2000;
WddmAllocation allocation(alignedPtr, alignedSize, nullptr);
Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize());
allocation.gmm = gmm;
allocation.is32BitAllocation = true; // mark 32 bit allocation
auto status = wddm->createAllocation(&allocation);
EXPECT_EQ(STATUS_SUCCESS, status);
EXPECT_TRUE(allocation.handle != 0);
bool ret = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getAlignedSize(), allocation.is32BitAllocation, false, false);
EXPECT_TRUE(ret);
EXPECT_EQ(1u, wddm->mapGpuVirtualAddressResult.called);
EXPECT_LE(heap32baseAddress, allocation.gpuPtr);
EXPECT_GT(heap32baseAddress + heap32Size, allocation.gpuPtr);
auto success = wddm->destroyAllocation(&allocation);
EXPECT_TRUE(success);
delete gmm;
}
HWTEST_F(Wddm20Tests, givenGraphicsAllocationWhenItIsMappedInHeap1ThenItHasGpuAddressWithingHeap1Limits) {
wddm->init<FamilyType>();
void *alignedPtr = (void *)0x12000;
size_t alignedSize = 0x2000;
WddmAllocation allocation(alignedPtr, alignedSize, nullptr);
allocation.handle = ALLOCATION_HANDLE;
allocation.gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize());
bool ret = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getAlignedSize(), false, false, true);
EXPECT_TRUE(ret);
auto cannonizedHeapBase = GmmHelper::canonize(this->wddm->getGfxPartition().Heap32[1].Base);
auto cannonizedHeapEnd = GmmHelper::canonize(this->wddm->getGfxPartition().Heap32[1].Limit);
EXPECT_GE(allocation.gpuPtr, cannonizedHeapBase);
EXPECT_LE(allocation.gpuPtr, cannonizedHeapEnd);
delete allocation.gmm;
}
HWTEST_F(Wddm20WithMockGdiDllTests, GivenThreeOsHandlesWhenAskedForDestroyAllocationsThenAllMarkedAllocationsAreDestroyed) {
EXPECT_TRUE(wddm->init<FamilyType>());
OsHandleStorage storage;
OsHandle osHandle1 = {0};
OsHandle osHandle2 = {0};
OsHandle osHandle3 = {0};
osHandle1.handle = ALLOCATION_HANDLE;
osHandle2.handle = ALLOCATION_HANDLE;
osHandle3.handle = ALLOCATION_HANDLE;
storage.fragmentStorageData[0].osHandleStorage = &osHandle1;
storage.fragmentStorageData[0].freeTheFragment = true;
storage.fragmentStorageData[1].osHandleStorage = &osHandle2;
storage.fragmentStorageData[1].freeTheFragment = false;
storage.fragmentStorageData[2].osHandleStorage = &osHandle3;
storage.fragmentStorageData[2].freeTheFragment = true;
D3DKMT_HANDLE handles[3] = {ALLOCATION_HANDLE, ALLOCATION_HANDLE, ALLOCATION_HANDLE};
bool retVal = wddm->destroyAllocations(handles, 3, 0, 0);
EXPECT_TRUE(retVal);
auto destroyWithResourceHandleCalled = 0u;
D3DKMT_DESTROYALLOCATION2 *ptrToDestroyAlloc2 = nullptr;
getSizesFcn(destroyWithResourceHandleCalled, ptrToDestroyAlloc2);
EXPECT_EQ(0u, ptrToDestroyAlloc2->Flags.SynchronousDestroy);
EXPECT_EQ(1u, ptrToDestroyAlloc2->Flags.AssumeNotInUse);
}
HWTEST_F(Wddm20Tests, mapAndFreeGpuVa) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
OsAgnosticMemoryManager mm(false);
WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr);
Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize());
allocation.gmm = gmm;
auto status = wddm->createAllocation(&allocation);
EXPECT_EQ(STATUS_SUCCESS, status);
EXPECT_TRUE(allocation.handle != 0);
auto error = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getUnderlyingBufferSize(), false, false, false);
EXPECT_TRUE(error);
EXPECT_TRUE(allocation.gpuPtr != 0);
error = wddm->freeGpuVirtualAddres(allocation.gpuPtr, allocation.getUnderlyingBufferSize());
EXPECT_TRUE(error);
EXPECT_TRUE(allocation.gpuPtr == 0);
error = wddm->destroyAllocation(&allocation);
EXPECT_TRUE(error);
delete gmm;
mm.freeSystemMemory(allocation.getUnderlyingBuffer());
}
HWTEST_F(Wddm20Tests, givenNullAllocationWhenCreateThenAllocateAndMap) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
OsAgnosticMemoryManager mm(false);
WddmAllocation allocation(nullptr, 100, nullptr);
Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize());
allocation.gmm = gmm;
auto status = wddm->createAllocation(&allocation);
EXPECT_EQ(STATUS_SUCCESS, status);
bool ret = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getAlignedSize(), allocation.is32BitAllocation, false, false);
EXPECT_TRUE(ret);
EXPECT_NE(0u, allocation.gpuPtr);
EXPECT_EQ(allocation.gpuPtr, GmmHelper::canonize(allocation.gpuPtr));
delete gmm;
mm.freeSystemMemory(allocation.getUnderlyingBuffer());
}
HWTEST_F(Wddm20Tests, makeResidentNonResident) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
OsAgnosticMemoryManager mm(false);
WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr);
Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize());
allocation.gmm = gmm;
auto status = wddm->createAllocation(&allocation);
EXPECT_EQ(STATUS_SUCCESS, status);
EXPECT_TRUE(allocation.handle != 0);
auto error = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getUnderlyingBufferSize(), false, false, false);
EXPECT_TRUE(error);
EXPECT_TRUE(allocation.gpuPtr != 0);
error = wddm->makeResident(&allocation.handle, 1, false, nullptr);
EXPECT_TRUE(error);
uint64_t sizeToTrim;
error = wddm->evict(&allocation.handle, 1, sizeToTrim);
EXPECT_TRUE(error);
auto monitoredFence = wddm->getMonitoredFence();
UINT64 fenceValue = 100;
monitoredFence.cpuAddress = &fenceValue;
monitoredFence.currentFenceValue = 101;
error = wddm->destroyAllocation(&allocation);
EXPECT_TRUE(error);
delete gmm;
mm.freeSystemMemory(allocation.getUnderlyingBuffer());
}
TEST_F(Wddm20Tests, GetCpuTime) {
uint64_t time = 0;
std::unique_ptr<OSTime> osTime(OSTime::create(nullptr).release());
auto error = osTime->getCpuTime(&time);
EXPECT_TRUE(error);
EXPECT_NE(0, time);
}
TEST_F(Wddm20Tests, GivenNoOSInterfaceGetCpuGpuTimeReturnsError) {
TimeStampData CPUGPUTime = {0};
std::unique_ptr<OSTime> osTime(OSTime::create(nullptr).release());
auto success = osTime->getCpuGpuTime(&CPUGPUTime);
EXPECT_FALSE(success);
EXPECT_EQ(0, CPUGPUTime.CPUTimeinNS);
EXPECT_EQ(0, CPUGPUTime.GPUTimeStamp);
}
TEST_F(Wddm20Tests, GetCpuGpuTime) {
TimeStampData CPUGPUTime01 = {0};
TimeStampData CPUGPUTime02 = {0};
std::unique_ptr<OSInterface> osInterface(new OSInterface());
osInterface->get()->setWddm(wddm.get());
std::unique_ptr<OSTime> osTime(OSTime::create(osInterface.get()).release());
auto success = osTime->getCpuGpuTime(&CPUGPUTime01);
EXPECT_TRUE(success);
EXPECT_NE(0, CPUGPUTime01.CPUTimeinNS);
EXPECT_NE(0, CPUGPUTime01.GPUTimeStamp);
success = osTime->getCpuGpuTime(&CPUGPUTime02);
EXPECT_TRUE(success);
EXPECT_NE(0, CPUGPUTime02.CPUTimeinNS);
EXPECT_NE(0, CPUGPUTime02.GPUTimeStamp);
EXPECT_GT(CPUGPUTime02.GPUTimeStamp, CPUGPUTime01.GPUTimeStamp);
EXPECT_GT(CPUGPUTime02.CPUTimeinNS, CPUGPUTime01.CPUTimeinNS);
}
HWTEST_F(Wddm20WithMockGdiDllTests, givenSharedHandleWhenCreateGraphicsAllocationFromSharedHandleIsCalledThenGraphicsAllocationWithSharedPropertiesIsCreated) {
void *pSysMem = (void *)0x1000;
std::unique_ptr<Gmm> gmm(new Gmm(pSysMem, 4096u, false));
auto status = setSizesFcn(gmm->gmmResourceInfo.get(), 1u, 1024u, 1u);
EXPECT_EQ(0u, status);
wddm->init<FamilyType>();
WddmMemoryManager mm(false, wddm.release());
auto graphicsAllocation = mm.createGraphicsAllocationFromSharedHandle(ALLOCATION_HANDLE, false, false);
auto wddmAllocation = (WddmAllocation *)graphicsAllocation;
ASSERT_NE(nullptr, wddmAllocation);
EXPECT_EQ(ALLOCATION_HANDLE, wddmAllocation->peekSharedHandle());
EXPECT_EQ(RESOURCE_HANDLE, wddmAllocation->resourceHandle);
EXPECT_NE(0u, wddmAllocation->handle);
EXPECT_EQ(ALLOCATION_HANDLE, wddmAllocation->handle);
EXPECT_NE(0u, wddmAllocation->getGpuAddress());
EXPECT_EQ(wddmAllocation->gpuPtr, wddmAllocation->getGpuAddress());
EXPECT_EQ(4096u, wddmAllocation->getUnderlyingBufferSize());
EXPECT_EQ(nullptr, wddmAllocation->getAlignedCpuPtr());
EXPECT_NE(nullptr, wddmAllocation->gmm);
EXPECT_EQ(4096u, wddmAllocation->gmm->gmmResourceInfo->getSizeAllocation());
mm.freeGraphicsMemory(graphicsAllocation);
auto destroyWithResourceHandleCalled = 0u;
D3DKMT_DESTROYALLOCATION2 *ptrToDestroyAlloc2 = nullptr;
status = getSizesFcn(destroyWithResourceHandleCalled, ptrToDestroyAlloc2);
EXPECT_EQ(0u, ptrToDestroyAlloc2->Flags.SynchronousDestroy);
EXPECT_EQ(1u, ptrToDestroyAlloc2->Flags.AssumeNotInUse);
EXPECT_EQ(0u, status);
EXPECT_EQ(1u, destroyWithResourceHandleCalled);
}
HWTEST_F(Wddm20WithMockGdiDllTests, givenSharedHandleWhenCreateGraphicsAllocationFromSharedHandleIsCalledThenMapGpuVaWithCpuPtrDepensOnBitness) {
void *pSysMem = (void *)0x1000;
std::unique_ptr<Gmm> gmm(new Gmm(pSysMem, 4096u, false));
auto status = setSizesFcn(gmm->gmmResourceInfo.get(), 1u, 1024u, 1u);
EXPECT_EQ(0u, status);
auto mockWddm = wddm.release();
mockWddm->init<FamilyType>();
WddmMemoryManager mm(false, mockWddm);
auto graphicsAllocation = mm.createGraphicsAllocationFromSharedHandle(ALLOCATION_HANDLE, false, false);
auto wddmAllocation = (WddmAllocation *)graphicsAllocation;
ASSERT_NE(nullptr, wddmAllocation);
if (is32bit) {
EXPECT_NE(mockWddm->mapGpuVirtualAddressResult.cpuPtrPassed, nullptr);
} else {
EXPECT_EQ(mockWddm->mapGpuVirtualAddressResult.cpuPtrPassed, nullptr);
}
mm.freeGraphicsMemory(graphicsAllocation);
}
HWTEST_F(Wddm20Tests, givenWddmCreatedWhenNotInitedThenMinAddressZero) {
uintptr_t expected = 0;
uintptr_t actual = wddm->getWddmMinAddress();
EXPECT_EQ(expected, actual);
}
HWTEST_F(Wddm20Tests, givenWddmCreatedWhenInitedThenMinAddressValid) {
bool ret = wddm->init<FamilyType>();
EXPECT_TRUE(ret);
uintptr_t expected = windowsMinAddress;
uintptr_t actual = wddm->getWddmMinAddress();
EXPECT_EQ(expected, actual);
}
HWTEST_F(Wddm20InstrumentationTest, configureDeviceAddressSpaceOnInit) {
SYSTEM_INFO sysInfo = {};
WddmMock::getSystemInfo(&sysInfo);
uintptr_t maxAddr = reinterpret_cast<uintptr_t>(sysInfo.lpMaximumApplicationAddress) + 1;
D3DKMT_HANDLE adapterHandle = ADAPTER_HANDLE;
D3DKMT_HANDLE deviceHandle = DEVICE_HANDLE;
const HardwareInfo hwInfo = *platformDevices[0];
ExecutionEnvironment execEnv;
execEnv.initGmm(&hwInfo);
BOOLEAN FtrL3IACoherency = hwInfo.pSkuTable->ftrL3IACoherency ? 1 : 0;
EXPECT_CALL(*gmmMem, configureDeviceAddressSpace(adapterHandle,
deviceHandle,
wddm->gdi->escape.mFunc,
maxAddr,
0,
0,
FtrL3IACoherency,
0,
0))
.Times(1)
.WillRepeatedly(::testing::Return(true));
wddm->init<FamilyType>();
EXPECT_TRUE(wddm->isInitialized());
}
HWTEST_F(Wddm20InstrumentationTest, configureDeviceAddressSpaceNoAdapter) {
wddm->adapter = static_cast<D3DKMT_HANDLE>(0);
ExecutionEnvironment execEnv;
execEnv.initGmm(*platformDevices);
EXPECT_CALL(*gmmMem, configureDeviceAddressSpace(static_cast<D3DKMT_HANDLE>(0),
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_))
.Times(1)
.WillRepeatedly(::testing::Return(false));
auto ret = wddm->configureDeviceAddressSpace<FamilyType>();
EXPECT_FALSE(ret);
}
HWTEST_F(Wddm20InstrumentationTest, configureDeviceAddressSpaceNoDevice) {
wddm->device = static_cast<D3DKMT_HANDLE>(0);
ExecutionEnvironment execEnv;
execEnv.initGmm(*platformDevices);
EXPECT_CALL(*gmmMem, configureDeviceAddressSpace(::testing::_,
static_cast<D3DKMT_HANDLE>(0),
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_))
.Times(1)
.WillRepeatedly(::testing::Return(false));
auto ret = wddm->configureDeviceAddressSpace<FamilyType>();
EXPECT_FALSE(ret);
}
HWTEST_F(Wddm20InstrumentationTest, configureDeviceAddressSpaceNoEscFunc) {
wddm->gdi->escape = static_cast<PFND3DKMT_ESCAPE>(nullptr);
ExecutionEnvironment execEnv;
execEnv.initGmm(*platformDevices);
EXPECT_CALL(*gmmMem, configureDeviceAddressSpace(::testing::_,
::testing::_,
static_cast<PFND3DKMT_ESCAPE>(nullptr),
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_,
::testing::_))
.Times(1)
.WillRepeatedly(::testing::Return(false));
auto ret = wddm->configureDeviceAddressSpace<FamilyType>();
EXPECT_FALSE(ret);
}
HWTEST_F(Wddm20Tests, getMaxApplicationAddress) {
wddm->init<FamilyType>();
EXPECT_TRUE(wddm->isInitialized());
uint64_t maxAddr = wddm->getMaxApplicationAddress();
if (is32bit) {
EXPECT_EQ(maxAddr, MemoryConstants::max32BitAppAddress);
} else {
EXPECT_EQ(maxAddr, MemoryConstants::max64BitAppAddress);
}
}
HWTEST_F(Wddm20Tests, dontCallCreateContextBeforeConfigureDeviceAddressSpace) {
wddm->createContext();
EXPECT_EQ(1u, wddm->createContextResult.called); // dont care about the result
wddm->configureDeviceAddressSpace<FamilyType>();
EXPECT_EQ(1u, wddm->configureDeviceAddressSpaceResult.called);
EXPECT_FALSE(wddm->configureDeviceAddressSpaceResult.success);
}
HWTEST_F(Wddm20WithMockGdiDllTests, givenUseNoRingFlushesKmdModeDebugFlagToFalseWhenCreateContextIsCalledThenNoRingFlushesKmdModeIsSetToFalse) {
DebugManagerStateRestore dbgRestore;
DebugManager.flags.UseNoRingFlushesKmdMode.set(false);
wddm->init<FamilyType>();
auto createContextParams = this->getCreateContextDataFcn();
auto privateData = (CREATECONTEXT_PVTDATA *)createContextParams->pPrivateDriverData;
EXPECT_FALSE(!!privateData->NoRingFlushes);
}
HWTEST_F(Wddm20WithMockGdiDllTests, givenUseNoRingFlushesKmdModeDebugFlagToTrueWhenCreateContextIsCalledThenNoRingFlushesKmdModeIsSetToTrue) {
DebugManagerStateRestore dbgRestore;
DebugManager.flags.UseNoRingFlushesKmdMode.set(true);
wddm->init<FamilyType>();
auto createContextParams = this->getCreateContextDataFcn();
auto privateData = (CREATECONTEXT_PVTDATA *)createContextParams->pPrivateDriverData;
EXPECT_TRUE(!!privateData->NoRingFlushes);
}
HWTEST_F(Wddm20WithMockGdiDllTests, whenCreateContextIsCalledThenDisableHwQueues) {
wddm->init<FamilyType>();
EXPECT_FALSE(wddm->hwQueuesSupported());
EXPECT_EQ(0u, getCreateContextDataFcn()->Flags.HwQueueSupported);
}
TEST_F(Wddm20Tests, whenCreateHwQueueIsCalledThenAlwaysReturnFalse) {
EXPECT_FALSE(wddm->createHwQueue());
}
HWTEST_F(Wddm20Tests, whenInitCalledThenDontCallToCreateHwQueue) {
wddm->init<FamilyType>();
EXPECT_EQ(0u, wddm->createHwQueueResult.called);
}
HWTEST_F(Wddm20Tests, whenWddmIsInitializedThenGdiDoesntHaveHwQueueDDIs) {
wddm->init<FamilyType>();
EXPECT_EQ(nullptr, wddm->gdi->createHwQueue.mFunc);
EXPECT_EQ(nullptr, wddm->gdi->destroyHwQueue.mFunc);
EXPECT_EQ(nullptr, wddm->gdi->submitCommandToHwQueue.mFunc);
}
HWTEST_F(Wddm20Tests, givenDebugManagerWhenGetForUseNoRingFlushesKmdModeIsCalledThenTrueIsReturned) {
EXPECT_TRUE(DebugManager.flags.UseNoRingFlushesKmdMode.get());
}
HWTEST_F(Wddm20Tests, makeResidentMultipleHandles) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
OsAgnosticMemoryManager mm(false);
WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr);
allocation.handle = ALLOCATION_HANDLE;
D3DKMT_HANDLE handles[2] = {0};
handles[0] = allocation.handle;
handles[1] = allocation.handle;
gdi->getMakeResidentArg().NumAllocations = 0;
gdi->getMakeResidentArg().AllocationList = nullptr;
bool error = wddm->makeResident(handles, 2, false, nullptr);
EXPECT_TRUE(error);
EXPECT_EQ(2u, gdi->getMakeResidentArg().NumAllocations);
EXPECT_EQ(handles, gdi->getMakeResidentArg().AllocationList);
mm.freeSystemMemory(allocation.getUnderlyingBuffer());
}
HWTEST_F(Wddm20Tests, makeResidentMultipleHandlesWithReturnBytesToTrim) {
wddm->init<FamilyType>();
ASSERT_TRUE(wddm->isInitialized());
OsAgnosticMemoryManager mm(false);
WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr);
allocation.handle = ALLOCATION_HANDLE;
D3DKMT_HANDLE handles[2] = {0};
handles[0] = allocation.handle;
handles[1] = allocation.handle;
gdi->getMakeResidentArg().NumAllocations = 0;
gdi->getMakeResidentArg().AllocationList = nullptr;
gdi->getMakeResidentArg().NumBytesToTrim = 30;
uint64_t bytesToTrim = 0;
bool success = wddm->makeResident(handles, 2, false, &bytesToTrim);
EXPECT_TRUE(success);
EXPECT_EQ(gdi->getMakeResidentArg().NumBytesToTrim, bytesToTrim);
mm.freeSystemMemory(allocation.getUnderlyingBuffer());
}
HWTEST_F(Wddm20Tests, makeNonResidentCallsEvict) {
wddm->init<FamilyType>();
D3DKMT_HANDLE handle = (D3DKMT_HANDLE)0x1234;
gdi->getEvictArg().AllocationList = nullptr;
gdi->getEvictArg().Flags.Value = 0;
gdi->getEvictArg().hDevice = 0;
gdi->getEvictArg().NumAllocations = 0;
gdi->getEvictArg().NumBytesToTrim = 20;
uint64_t sizeToTrim = 10;
wddm->evict(&handle, 1, sizeToTrim);
EXPECT_EQ(1u, gdi->getEvictArg().NumAllocations);
EXPECT_EQ(&handle, gdi->getEvictArg().AllocationList);
EXPECT_EQ(wddm->getDevice(), gdi->getEvictArg().hDevice);
EXPECT_EQ(0u, gdi->getEvictArg().NumBytesToTrim);
}
HWTEST_F(Wddm20Tests, destroyAllocationWithLastFenceValueGreaterThanCurrentValueCallsWaitFromCpu) {
wddm->init<FamilyType>();
WddmAllocation allocation((void *)0x23000, 0x1000, nullptr);
allocation.getResidencyData().lastFence = 20;
allocation.handle = ALLOCATION_HANDLE;
*wddm->getMonitoredFence().cpuAddress = 10;
D3DKMT_HANDLE handle = (D3DKMT_HANDLE)0x1234;
gdi->getWaitFromCpuArg().FenceValueArray = nullptr;
gdi->getWaitFromCpuArg().Flags.Value = 0;
gdi->getWaitFromCpuArg().hDevice = (D3DKMT_HANDLE)0;
gdi->getWaitFromCpuArg().ObjectCount = 0;
gdi->getWaitFromCpuArg().ObjectHandleArray = nullptr;
gdi->getDestroyArg().AllocationCount = 0;
gdi->getDestroyArg().Flags.Value = 0;
gdi->getDestroyArg().hDevice = (D3DKMT_HANDLE)0;
gdi->getDestroyArg().hResource = (D3DKMT_HANDLE)0;
gdi->getDestroyArg().phAllocationList = nullptr;
wddm->destroyAllocation(&allocation);
EXPECT_NE(nullptr, gdi->getWaitFromCpuArg().FenceValueArray);
EXPECT_EQ(wddm->getDevice(), gdi->getWaitFromCpuArg().hDevice);
EXPECT_EQ(1u, gdi->getWaitFromCpuArg().ObjectCount);
EXPECT_EQ(&wddm->getMonitoredFence().fenceHandle, gdi->getWaitFromCpuArg().ObjectHandleArray);
EXPECT_EQ(wddm->getDevice(), gdi->getDestroyArg().hDevice);
EXPECT_EQ(1u, gdi->getDestroyArg().AllocationCount);
EXPECT_NE(nullptr, gdi->getDestroyArg().phAllocationList);
}
HWTEST_F(Wddm20Tests, destroyAllocationWithLastFenceValueLessEqualToCurrentValueDoesNotCallWaitFromCpu) {
wddm->init<FamilyType>();
WddmAllocation allocation((void *)0x23000, 0x1000, nullptr);
allocation.getResidencyData().lastFence = 10;
allocation.handle = ALLOCATION_HANDLE;
*wddm->getMonitoredFence().cpuAddress = 10;
D3DKMT_HANDLE handle = (D3DKMT_HANDLE)0x1234;
gdi->getWaitFromCpuArg().FenceValueArray = nullptr;
gdi->getWaitFromCpuArg().Flags.Value = 0;
gdi->getWaitFromCpuArg().hDevice = (D3DKMT_HANDLE)0;
gdi->getWaitFromCpuArg().ObjectCount = 0;
gdi->getWaitFromCpuArg().ObjectHandleArray = nullptr;
gdi->getDestroyArg().AllocationCount = 0;
gdi->getDestroyArg().Flags.Value = 0;
gdi->getDestroyArg().hDevice = (D3DKMT_HANDLE)0;
gdi->getDestroyArg().hResource = (D3DKMT_HANDLE)0;
gdi->getDestroyArg().phAllocationList = nullptr;
wddm->destroyAllocation(&allocation);
EXPECT_EQ(nullptr, gdi->getWaitFromCpuArg().FenceValueArray);
EXPECT_EQ((D3DKMT_HANDLE)0, gdi->getWaitFromCpuArg().hDevice);
EXPECT_EQ(0u, gdi->getWaitFromCpuArg().ObjectCount);
EXPECT_EQ(nullptr, gdi->getWaitFromCpuArg().ObjectHandleArray);
EXPECT_EQ(wddm->getDevice(), gdi->getDestroyArg().hDevice);
EXPECT_EQ(1u, gdi->getDestroyArg().AllocationCount);
EXPECT_NE(nullptr, gdi->getDestroyArg().phAllocationList);
}
HWTEST_F(Wddm20Tests, WhenLastFenceLessEqualThanMonitoredThenWaitFromCpuIsNotCalled) {
wddm->init<FamilyType>();
WddmAllocation allocation((void *)0x23000, 0x1000, nullptr);
allocation.getResidencyData().lastFence = 10;
allocation.handle = ALLOCATION_HANDLE;
*wddm->getMonitoredFence().cpuAddress = 10;
gdi->getWaitFromCpuArg().FenceValueArray = nullptr;
gdi->getWaitFromCpuArg().Flags.Value = 0;
gdi->getWaitFromCpuArg().hDevice = (D3DKMT_HANDLE)0;
gdi->getWaitFromCpuArg().ObjectCount = 0;
gdi->getWaitFromCpuArg().ObjectHandleArray = nullptr;
auto status = wddm->waitFromCpu(10);
EXPECT_TRUE(status);
EXPECT_EQ(nullptr, gdi->getWaitFromCpuArg().FenceValueArray);
EXPECT_EQ((D3DKMT_HANDLE)0, gdi->getWaitFromCpuArg().hDevice);
EXPECT_EQ(0u, gdi->getWaitFromCpuArg().ObjectCount);
EXPECT_EQ(nullptr, gdi->getWaitFromCpuArg().ObjectHandleArray);
}
HWTEST_F(Wddm20Tests, WhenLastFenceGreaterThanMonitoredThenWaitFromCpuIsCalled) {
wddm->init<FamilyType>();
WddmAllocation allocation((void *)0x23000, 0x1000, nullptr);
allocation.getResidencyData().lastFence = 10;
allocation.handle = ALLOCATION_HANDLE;
*wddm->getMonitoredFence().cpuAddress = 10;
gdi->getWaitFromCpuArg().FenceValueArray = nullptr;
gdi->getWaitFromCpuArg().Flags.Value = 0;
gdi->getWaitFromCpuArg().hDevice = (D3DKMT_HANDLE)0;
gdi->getWaitFromCpuArg().ObjectCount = 0;
gdi->getWaitFromCpuArg().ObjectHandleArray = nullptr;
auto status = wddm->waitFromCpu(20);
EXPECT_TRUE(status);
EXPECT_NE(nullptr, gdi->getWaitFromCpuArg().FenceValueArray);
EXPECT_EQ((D3DKMT_HANDLE)wddm->getDevice(), gdi->getWaitFromCpuArg().hDevice);
EXPECT_EQ(1u, gdi->getWaitFromCpuArg().ObjectCount);
EXPECT_NE(nullptr, gdi->getWaitFromCpuArg().ObjectHandleArray);
}
HWTEST_F(Wddm20Tests, createMonitoredFenceIsInitializedWithFenceValueZeroAndCurrentFenceValueIsSetToOne) {
wddm->init<FamilyType>();
gdi->createSynchronizationObject2 = gdi->createSynchronizationObject2Mock;
gdi->getCreateSynchronizationObject2Arg().Info.MonitoredFence.InitialFenceValue = 300;
wddm->createMonitoredFence();
EXPECT_EQ(0u, gdi->getCreateSynchronizationObject2Arg().Info.MonitoredFence.InitialFenceValue);
EXPECT_EQ(1u, wddm->getMonitoredFence().currentFenceValue);
}
NTSTATUS APIENTRY queryResourceInfoMock(D3DKMT_QUERYRESOURCEINFO *pData) {
pData->NumAllocations = 0;
return 0;
}
HWTEST_F(Wddm20Tests, givenOpenSharedHandleWhenZeroAllocationsThenReturnNull) {
wddm->init<FamilyType>();
D3DKMT_HANDLE handle = 0;
WddmAllocation *alloc = nullptr;
gdi->queryResourceInfo = reinterpret_cast<PFND3DKMT_QUERYRESOURCEINFO>(queryResourceInfoMock);
auto ret = wddm->openSharedHandle(handle, alloc);
EXPECT_EQ(false, ret);
}
HWTEST_F(Wddm20Tests, givenReadOnlyMemoryWhenCreateAllocationFailsWithNoVideoMemoryThenCorrectStatusIsReturned) {
class MockCreateAllocation {
public:
static NTSTATUS APIENTRY mockCreateAllocation(D3DKMT_CREATEALLOCATION *param) {
return STATUS_GRAPHICS_NO_VIDEO_MEMORY;
};
};
gdi->createAllocation = MockCreateAllocation::mockCreateAllocation;
wddm->init<FamilyType>();
OsHandleStorage handleStorage;
OsHandle handle = {0};
ResidencyData residency;
handleStorage.fragmentCount = 1;
handleStorage.fragmentStorageData[0].cpuPtr = (void *)0x1000;
handleStorage.fragmentStorageData[0].fragmentSize = 0x1000;
handleStorage.fragmentStorageData[0].freeTheFragment = false;
handleStorage.fragmentStorageData[0].osHandleStorage = &handle;
handleStorage.fragmentStorageData[0].residency = &residency;
handleStorage.fragmentStorageData[0].osHandleStorage->gmm = GmmHelperFunctions::getGmm(nullptr, 0);
NTSTATUS result = wddm->createAllocationsAndMapGpuVa(handleStorage);
EXPECT_EQ(STATUS_GRAPHICS_NO_VIDEO_MEMORY, result);
delete handleStorage.fragmentStorageData[0].osHandleStorage->gmm;
}
HWTEST_F(Wddm20Tests, whenGetOsDeviceContextIsCalledThenWddmOsDeviceContextIsReturned) {
D3DKMT_HANDLE ctx = 0xc1;
wddm->context = ctx;
EXPECT_EQ(ctx, wddm->getOsDeviceContext());
}
| 36,367 | 13,191 |
#ifndef APP_GROUND_TYPE_HPP
#define APP_GROUND_TYPE_HPP
namespace app
{
enum class GroundType
{
Ground1,
Ground2,
Ground3,
Slope,
UnderWater
};
} // namespace app
#endif // APP_GROUND_TYPE_HPP
| 218 | 99 |
// G100Config.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h"
#include "MachDevice.h"
#include "G100Config.h"
#include "G100-Structs.h"
#include ".\g100config.h"
#include "LocalIPQuery.h"
#include "GRexControl.h"
extern GRexControl *TheRex;
bool Exit;
// G100Config dialog
IMPLEMENT_DYNAMIC(G100Config, CDialog)
G100Config::G100Config(CWnd* pParent /*=NULL*/)
: CDialog(G100Config::IDD, pParent)
, m_Error(_T(""))
, m_Perm(FALSE)
{
Exit = false;
}
G100Config::~G100Config()
{
}
void G100Config::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_IPG100, m_G100IP);
DDX_Control(pDX, IDC_NMG100, m_G100NM);
DDX_Control(pDX, IDC_MYIP, m_MyIP);
DDX_Text(pDX, IDC_ERRORS, m_Error);
}
BEGIN_MESSAGE_MAP(G100Config, CDialog)
ON_BN_CLICKED(IDC_SENDNEW, OnBnClickedSendnew)
ON_BN_CLICKED(IDOK, OnBnClickedOk)
ON_BN_CLICKED(IDC_BUTTON2, OnBnClickedButton2)
END_MESSAGE_MAP()
// G100Config message handlers
BOOL G100Config::OnInitDialog()
{
CDialog::OnInitDialog();
//Lets show what we have recieved so far in terms of G100 Address.
unsigned ipaddr, netmask;
if (!TheRex->ge || !TheRex->ge->getIP(TheRex->inst, ipaddr, netmask))
ipaddr = netmask = 0;
m_G100IP.SetAddress(ipaddr);
m_G100NM.SetAddress(netmask);
//now lets get ours..
LocalIPQuery LocalMachine; //setup a localIp search class
// Search for an address which is _not_ 127.****
//FIXME: should display a list of addresses to do this properly.
DWORD test;
for (unsigned i = 0; i < LocalMachine.m_vIPAddress.size(); ++i) {
test = (LocalMachine.m_vIPAddress[LocalMachine.m_vIPAddress.size()-1].GetNBO());
if ((test & 0xFF) != 127)
break;
}
m_MyIP.SetAddress(test);
m_Error = TheRex->Disability;
UpdateData( false );
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void G100Config::OnBnClickedSendnew()
{
UpdateData( true );
DWORD data;
m_G100IP.GetAddress( data );
unsigned ipaddr = (unsigned)data;
m_G100NM.GetAddress( data);
unsigned netmask = (unsigned)data;
TheRex->ge->setIP(TheRex->inst, ipaddr, netmask);
TheRex->PHASE = SETIP;
UpdateData( false );
}
void G100Config::OnBnClickedOk()
{
if( !Exit )
{
TheRex->PHASE = DISCOVERY;
}
OnOK();
}
void G100Config::OnBnClickedButton2()
{
Exit = true;
OnOK();
}
| 2,365 | 1,073 |
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--) {
long long ans= 0;
long long no = 0;
string x;
cin>>x;
long long streak = 0;
for(long i=0;i<x.size();i++) {
if(x[i] == '1') {
if(streak != 0){
ans += no;
ans += no*streak;
}
no++;
streak = 0;
} else
streak++;
}
if(streak != 0){
ans += no;
ans += no*streak;
}
cout<<ans<<endl;
}
return 0;
} | 443 | 252 |
// Copyright 2019 Open Source Robotics Foundation, 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.
#ifndef RCLCPP__EXPERIMENTAL__BUFFERS__RING_BUFFER_IMPLEMENTATION_HPP_
#define RCLCPP__EXPERIMENTAL__BUFFERS__RING_BUFFER_IMPLEMENTATION_HPP_
#include <mutex>
#include <stdexcept>
#include <utility>
#include <vector>
#include "rclcpp/experimental/buffers/buffer_implementation_base.hpp"
#include "rclcpp/logger.hpp"
#include "rclcpp/logging.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/visibility_control.hpp"
namespace rclcpp
{
namespace experimental
{
namespace buffers
{
/// Store elements in a fixed-size, FIFO buffer
/**
* All public member functions are thread-safe.
*/
template<typename BufferT>
class RingBufferImplementation : public BufferImplementationBase<BufferT>
{
public:
explicit RingBufferImplementation(size_t capacity)
: capacity_(capacity),
ring_buffer_(capacity),
write_index_(capacity_ - 1),
read_index_(0),
size_(0)
{
if (capacity == 0) {
throw std::invalid_argument("capacity must be a positive, non-zero value");
}
}
virtual ~RingBufferImplementation() {}
/// Add a new element to store in the ring buffer
/**
* This member function is thread-safe.
*
* \param request the element to be stored in the ring buffer
*/
void enqueue(BufferT request)
{
std::lock_guard<std::mutex> lock(mutex_);
write_index_ = next_(write_index_);
ring_buffer_[write_index_] = std::move(request);
if (is_full_()) {
read_index_ = next_(read_index_);
} else {
size_++;
}
}
/// Remove the oldest element from ring buffer
/**
* This member function is thread-safe.
*
* \return the element that is being removed from the ring buffer
*/
BufferT dequeue()
{
std::lock_guard<std::mutex> lock(mutex_);
if (!has_data_()) {
RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Calling dequeue on empty intra-process buffer");
throw std::runtime_error("Calling dequeue on empty intra-process buffer");
}
auto request = std::move(ring_buffer_[read_index_]);
read_index_ = next_(read_index_);
size_--;
return request;
}
/// Get the next index value for the ring buffer
/**
* This member function is thread-safe.
*
* \param val the current index value
* \return the next index value
*/
inline size_t next(size_t val)
{
std::lock_guard<std::mutex> lock(mutex_);
return next_(val);
}
/// Get if the ring buffer has at least one element stored
/**
* This member function is thread-safe.
*
* \return `true` if there is data and `false` otherwise
*/
inline bool has_data() const
{
std::lock_guard<std::mutex> lock(mutex_);
return has_data_();
}
/// Get if the size of the buffer is equal to its capacity
/**
* This member function is thread-safe.
*
* \return `true` if the size of the buffer is equal is capacity
* and `false` otherwise
*/
inline bool is_full() const
{
std::lock_guard<std::mutex> lock(mutex_);
return is_full_();
}
void clear() {}
private:
/// Get the next index value for the ring buffer
/**
* This member function is not thread-safe.
*
* \param val the current index value
* \return the next index value
*/
inline size_t next_(size_t val)
{
return (val + 1) % capacity_;
}
/// Get if the ring buffer has at least one element stored
/**
* This member function is not thread-safe.
*
* \return `true` if there is data and `false` otherwise
*/
inline bool has_data_() const
{
return size_ != 0;
}
/// Get if the size of the buffer is equal to its capacity
/**
* This member function is not thread-safe.
*
* \return `true` if the size of the buffer is equal is capacity
* and `false` otherwise
*/
inline bool is_full_() const
{
return size_ == capacity_;
}
size_t capacity_;
std::vector<BufferT> ring_buffer_;
size_t write_index_;
size_t read_index_;
size_t size_;
mutable std::mutex mutex_;
};
} // namespace buffers
} // namespace experimental
} // namespace rclcpp
#endif // RCLCPP__EXPERIMENTAL__BUFFERS__RING_BUFFER_IMPLEMENTATION_HPP_
| 4,736 | 1,555 |
/***************************************************************
* Name: wxwidgets_testMain.cpp
* Purpose: Code for Application Frame
* Author: tsn (talipovsn@gmail.com)
* Created: 2020-02-26
* Copyright: tsn (github.com/tsnsoft)
* License:
**************************************************************/
#include "wxwidgets_testMain.h"
#include <wx/msgdlg.h>
#include <iostream>
#include <sstream>
#include <cmath>
//(*InternalHeaders(wxwidgets_testDialog)
#include <wx/font.h>
#include <wx/intl.h>
#include <wx/settings.h>
#include <wx/string.h>
//*)
//helper functions
enum wxbuildinfoformat
{
short_f, long_f
};
wxString wxbuildinfo(wxbuildinfoformat format)
{
wxString wxbuild(wxVERSION_STRING);
if (format == long_f )
{
#if defined(__WXMSW__)
wxbuild << _T("-Windows");
#elif defined(__UNIX__)
wxbuild << _T("-Linux");
#endif
#if wxUSE_UNICODE
wxbuild << _T("-Unicode build");
#else
wxbuild << _T("-ANSI build");
#endif // wxUSE_UNICODE
}
return wxbuild;
}
//(*IdInit(wxwidgets_testDialog)
const long wxwidgets_testDialog::ID_STATICTEXT1 = wxNewId();
const long wxwidgets_testDialog::ID_STATICLINE1 = wxNewId();
const long wxwidgets_testDialog::ID_TEXTCTRL2 = wxNewId();
const long wxwidgets_testDialog::ID_TEXTCTRL1 = wxNewId();
const long wxwidgets_testDialog::ID_BUTTON1 = wxNewId();
const long wxwidgets_testDialog::ID_STATICTEXT3 = wxNewId();
const long wxwidgets_testDialog::ID_BUTTON2 = wxNewId();
//*)
BEGIN_EVENT_TABLE(wxwidgets_testDialog,wxDialog)
//(*EventTable(wxwidgets_testDialog)
//*)
END_EVENT_TABLE()
wxwidgets_testDialog::wxwidgets_testDialog(wxWindow* parent,wxWindowID id)
{
//(*Initialize(wxwidgets_testDialog)
Create(parent, id, _("Пример с wxWidgets"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE, _T("id"));
BoxSizer1 = new wxBoxSizer(wxHORIZONTAL);
StaticText1 = new wxStaticText(this, ID_STATICTEXT1, _("Я люблю\nwxWidgets !"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT1"));
wxFont StaticText1Font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
if ( !StaticText1Font.Ok() ) StaticText1Font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
StaticText1Font.SetPointSize(20);
StaticText1->SetFont(StaticText1Font);
BoxSizer1->Add(StaticText1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 10);
BoxSizer2 = new wxBoxSizer(wxVERTICAL);
StaticLine1 = new wxStaticLine(this, ID_STATICLINE1, wxDefaultPosition, wxSize(10,-1), wxLI_HORIZONTAL, _T("ID_STATICLINE1"));
BoxSizer2->Add(StaticLine1, 0, wxALL|wxEXPAND, 4);
TextCtrl2 = new wxTextCtrl(this, ID_TEXTCTRL2, _("0"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL2"));
BoxSizer2->Add(TextCtrl2, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
TextCtrl1 = new wxTextCtrl(this, ID_TEXTCTRL1, _("0"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL1"));
BoxSizer2->Add(TextCtrl1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
doCalc = new wxButton(this, ID_BUTTON1, _("Сумма"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON1"));
BoxSizer2->Add(doCalc, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
StaticText_Sum = new wxStaticText(this, ID_STATICTEXT3, _("0"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT3"));
BoxSizer2->Add(StaticText_Sum, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
BoxSizer1->Add(BoxSizer2, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 4);
Button2 = new wxButton(this, ID_BUTTON2, _("Выход"), wxDefaultPosition, wxSize(175,43), 0, wxDefaultValidator, _T("ID_BUTTON2"));
BoxSizer1->Add(Button2, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 4);
SetSizer(BoxSizer1);
BoxSizer1->Fit(this);
BoxSizer1->SetSizeHints(this);
Center();
Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxwidgets_testDialog::OndoCalcClick);
Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxwidgets_testDialog::OnQuit);
//*)
}
wxwidgets_testDialog::~wxwidgets_testDialog()
{
//(*Destroy(wxwidgets_testDialog)
//*)
}
void wxwidgets_testDialog::OnQuit(wxCommandEvent& event)
// Выход из программы
{
wxMessageBox(_("С++ с wxWidgets - это круто!"), _("До свидания!"));
Close();
}
void wxwidgets_testDialog::OndoCalcClick(wxCommandEvent& event)
// Кнопка расчета значения
{
double a = strtod(TextCtrl1->GetValue(), NULL);
double b = strtod(TextCtrl2->GetValue(), NULL);
double c = a + b;
std::ostringstream foo;
foo.precision(10);
foo << c;
StaticText_Sum->SetLabel(foo.str());
}
| 4,789 | 1,920 |
//------------------------------------------------------------------------------------------------------------
// File: Random.cpp
// Class: teh::Random
//
// Description:
// Random number generator using the code from zufall.h/.c.
// See header file for more details.
//
// Author: Thomas E. Hilinski <https://github.com/tehilinski>
//
// Copyright 2020 Thomas E. Hilinski. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// and in the accompanying file LICENSE.md.
// 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 "Random.h"
#include <cmath>
using std::exp;
using std::cos;
using std::sin;
using std::sqrt;
using std::log;
#include <stdexcept>
#include <string>
#include <ctime>
namespace teh {
namespace zufall {
//---------------------------------------- class RandomSeed ----------------------------------------
unsigned int const RandomSeed::seedUpperLimit = UINT_MAX - 144U;
RandomSeed::RandomSeed (
unsigned int const entropy,
unsigned int const minSeed,
unsigned int const maxSeed )
: seedMin ( minSeed > 0 ? minSeed : 1 ),
seedMax ( maxSeed < seedUpperLimit ? maxSeed : seedUpperLimit - 1 ),
seed ( entropy == 0 ?
std::time(NULL) % GetRange().second :
entropy % GetRange().second )
{
if ( seed < seedMin || seed >= seedMax )
{
std::string msg = "Random: seed is out of range.";
throw std::runtime_error( msg );
}
if ( seedMin >= seedMax )
{
std::string msg = "Either minimum or maximum seed (or both) is invalid.";
throw std::runtime_error( msg );
}
}
//---------------------------------------- private to Random ----------------------------------------
struct klotz0_1_
{
static short const size = 607;
std::vector<double> buff;
unsigned int ptr;
klotz0_1_ ()
: buff (size, 0.0),
ptr (0)
{
}
};
klotz0_1_ klotz0_1;
// private to Random
struct klotz1_1_
{
static short const size = 1024;
std::vector<double> xbuff;
unsigned int first, xptr;
klotz1_1_ ()
: xbuff (size, 0.0),
first (0),
xptr (0)
{
}
};
static klotz1_1_ klotz1_1;
//---------------------------------------- class Random ----------------------------------------
Random::Random (
unsigned int const seed )
{
InitializeSeedBuffer (seed);
}
// ----------------------------------------------------------------------------
// InitializeSeedBuffer (formerly zufalli)
// Generates initial seed buffer by linear congruential
// method. Taken from Marsaglia, FSU report FSU-SCRI-87-50
// Variable seed should be 0 < seed < ( numeric_limits<unsigned int> - 144 )
// ----------------------------------------------------------------------------
void Random::InitializeSeedBuffer (
unsigned int const seed)
{
unsigned int const ij = seed;
unsigned int i = ij / 177 % 177 + 2;
unsigned int j = ij % 177 + 2;
unsigned int k = 9373 / 169 % 178 + 1;
unsigned int l = 9373 % 169;
for (unsigned int ii = 0; ii < (unsigned int)klotz0_1.size; ++ii)
{
double s = 0.0;
double t = 0.5;
for (unsigned int jj = 1; jj <= 24; ++jj)
{
unsigned int m = i * j % 179 * k % 179;
i = j;
j = k;
k = m;
l = (l * 53 + 1) % 169;
if (l * m % 64 >= 32)
s += t;
t *= 0.5;
}
klotz0_1.buff[ii] = s;
}
}
// ----------------------------------------------------------------------------
// Uniform (formerly zufall)
// portable lagged Fibonacci series uniform random number
// generator with "lags" -273 und -607:
// W.P. Petersen, IPS, ETH Zuerich, 19 Mar. 92
// ----------------------------------------------------------------------------
double Random::Uniform ()
{
std::vector<double> a;
Uniform( 1, a );
return a[0];
}
void Random::Uniform (
unsigned int const n,
std::vector<double> & a)
{
if (n == 0)
return;
a.assign (n, 0.0);
unsigned int left, bptr, aptr0;
double t;
unsigned int vl, k273, k607, kptr;
unsigned int aptr = 0;
unsigned int nn = n;
L1:
if (nn == 0)
return;
/* factor nn = q*607 + r */
unsigned int q = (nn - 1) / klotz0_1.size;
left = klotz0_1.size - klotz0_1.ptr;
if (q <= 1)
{
/* only one or fewer full segments */
if (nn < left)
{
kptr = klotz0_1.ptr;
for (unsigned int i = 0; i < nn; ++i)
a[i + aptr] = klotz0_1.buff[kptr + i];
klotz0_1.ptr += nn;
return;
}
else
{
kptr = klotz0_1.ptr;
#pragma _CRI ivdep
for (unsigned int i = 0; i < left; ++i)
a[i + aptr] = klotz0_1.buff[kptr + i];
klotz0_1.ptr = 0;
aptr += left;
nn -= left;
/* buff -> buff case */
vl = 273;
k273 = 334;
k607 = 0;
for (unsigned int k = 0; k < 3; ++k)
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < vl; ++i)
{
t = klotz0_1.buff[k273+i]+klotz0_1.buff[k607+i];
klotz0_1.buff[k607+i] = t - (double) ((unsigned int) t);
}
k607 += vl;
k273 += vl;
vl = 167;
if (k == 0)
{
k273 = 0;
}
}
goto L1;
}
}
else
{
/* more than 1 full segment */
kptr = klotz0_1.ptr;
#pragma _CRI ivdep
for (unsigned int i = 0; i < left; ++i)
a[i + aptr] = klotz0_1.buff[kptr + i];
nn -= left;
klotz0_1.ptr = 0;
aptr += left;
/* buff -> a(aptr0) */
vl = 273;
k273 = 334;
k607 = 0;
for (unsigned int k = 0; k < 3; ++k)
{
if (k == 0)
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < vl; ++i)
{
t = klotz0_1.buff[k273+i]+klotz0_1.buff[k607+i];
a[aptr + i] = t - (double) ((unsigned int) t);
}
k273 = aptr;
k607 += vl;
aptr += vl;
vl = 167;
}
else
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < vl; ++i)
{
t = a[k273 + i] + klotz0_1.buff[k607 + i];
a[aptr + i] = t - (double) ((unsigned int) t);
}
k607 += vl;
k273 += vl;
aptr += vl;
}
}
nn += -klotz0_1.size;
/* a(aptr-607) -> a(aptr) for last of the q-1 segments */
aptr0 = aptr - klotz0_1.size;
vl = klotz0_1.size;
for (unsigned int qq = 0; qq < q-2; ++qq)
{
k273 = aptr0 + 334;
#pragma _CRI ivdep
for (unsigned int i = 0; i < vl; ++i)
{
t = a[k273 + i] + a[aptr0 + i];
a[aptr + i] = t - (double) ((unsigned int) t);
}
nn += -klotz0_1.size;
aptr += vl;
aptr0 += vl;
}
/* a(aptr0) -> buff, last segment before residual */
vl = 273;
k273 = aptr0 + 334;
k607 = aptr0;
bptr = 0;
for (unsigned int k = 0; k < 3; ++k)
{
if (k == 0)
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < vl; ++i)
{
t = a[k273 + i] + a[k607 + i];
klotz0_1.buff[bptr + i] = t - (double) ((unsigned int) t);
}
k273 = 0;
k607 += vl;
bptr += vl;
vl = 167;
}
else
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < vl; ++i)
{
t = klotz0_1.buff[k273 + i] + a[k607 + i];
klotz0_1.buff[bptr + i] = t - (double) ((unsigned int) t);
}
k607 += vl;
k273 += vl;
bptr += vl;
}
}
goto L1;
}
}
// ----------------------------------------------------------------------------
// Normal (formerly normalen)
// Box-Muller method for Gaussian random numbers.
// ----------------------------------------------------------------------------
double Random::Normal ()
{
std::vector<double> x;
Uniform( 1, x );
return x[0];
}
void Random::Normal (
unsigned int const n,
std::vector<double> & x)
{
if (n == 0)
return;
x.assign (n, 0.0);
if (klotz1_1.first == 0)
{
normal00();
klotz1_1.first = 1;
}
unsigned int ptr = 0;
unsigned int nn = n;
L1:
unsigned int const left = klotz1_1.size - klotz1_1.xptr;
unsigned int const kptr = klotz1_1.xptr;
if (nn < left)
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < nn; ++i)
x[i + ptr] = klotz1_1.xbuff[kptr + i];
klotz1_1.xptr += nn;
return;
}
else
{
#pragma _CRI ivdep
for (unsigned int i = 0; i < left; ++i)
x[i + ptr] = klotz1_1.xbuff[kptr + i];
klotz1_1.xptr = 0;
ptr += left;
nn -= left;
normal00();
goto L1;
}
}
// ----------------------------------------------------------------------------
// Poisson (formerly fische)
// Poisson generator for distribution function of p's:
// q(mu,p) = exp(-mu) mu**p/p!
// ----------------------------------------------------------------------------
unsigned int Random::Poisson (
double const mu)
{
std::vector<unsigned int> p;
Poisson( 1, mu, p );
return p[0];
}
void Random::Poisson (
unsigned int const n,
double const mu,
std::vector<unsigned int> & p)
{
if (n == 0)
return;
p.assign (n, 0);
double const pmu = exp(-mu);
unsigned int p0 = 0;
unsigned int nsegs = (n - 1) / klotz1_1.size;
unsigned int left = n - (nsegs << 10);
++nsegs;
unsigned int nl0 = left;
std::vector<unsigned int> indx (klotz1_1.size);
std::vector<double> q (klotz1_1.size);
std::vector<double> u (klotz1_1.size);
for (unsigned int k = 0; k < nsegs; ++k)
{
for (unsigned int i = 0; i < left; ++i)
{
indx[i] = i;
p[p0 + i] = 0;
q[i] = 1.;
}
/* Begin iterative loop on segment of p's */
do
{
Uniform (left, u); // Get the needed uniforms
unsigned int jj = 0;
for (unsigned int i = 0; i < left; ++i)
{
unsigned int const ii = indx[i];
double const q0 = q[ii] * u[i];
q[ii] = q0;
if (q0 > pmu)
{
indx[jj++] = ii;
++p[p0 + ii];
}
}
left = jj; // any left in this segment?
}
while (left > 0);
p0 += nl0;
nl0 = klotz1_1.size;
left = klotz1_1.size;
}
}
// ----------------------------------------------------------------------------
// zufallsv
// saves common blocks klotz0, containing seeds and
// pointer to position in seed block. IMPORTANT: svblk must be
// dimensioned at least 608 in driver. The entire contents
// of klotz0 (pointer in buff, and buff) must be saved.
// ----------------------------------------------------------------------------
void Random::zufallsv (
std::vector<double> & saveBuffer) // size = klotz0_1_.size + 1
{
saveBuffer.resize (klotz0_1_::size + 1);
saveBuffer[0] = (double) klotz0_1.ptr;
#pragma _CRI ivdep
for (short i = 0; i < klotz0_1.size; ++i)
saveBuffer[i + 1] = klotz0_1.buff[i];
}
// ----------------------------------------------------------------------------
// zufallrs
// restores common block klotz0, containing seeds and pointer
// to position in seed block. IMPORTANT: saveBuffer must be
// dimensioned at least 608 in driver. The entire contents
// of klotz0 must be restored.
// ----------------------------------------------------------------------------
void Random::zufallrs (
std::vector<double> const & saveBuffer) // size = klotz0_1_.size + 1
{
if ( saveBuffer.size() != klotz0_1_::size + 1 )
{
std::string msg;
msg = "Random::zufallrs, restore of uninitialized block.";
throw std::runtime_error (msg);
}
klotz0_1.ptr = (unsigned int) saveBuffer[0];
#pragma _CRI ivdep
for (short i = 0; i < klotz0_1.size; ++i)
klotz0_1.buff[i] = saveBuffer[i + 1];
}
// ----------------------------------------------------------------------------
// normalsv
// save zufall block klotz0
// IMPORTANT: svbox must be dimensioned at
// least 1634 in driver. The entire contents of blocks
// klotz0 (via zufallsv) and klotz1 must be saved.
// ----------------------------------------------------------------------------
void Random::normalsv (
std::vector<double> & saveBuffer) // size = 1634
{
if (klotz1_1.first == 0)
{
std::string msg;
msg = "Random::normalsv, save of uninitialized block.";
throw std::runtime_error (msg);
}
saveBuffer.resize (1634);
zufallsv (saveBuffer);
saveBuffer[klotz0_1.size + 1] = (double) klotz1_1.first; // [608]
saveBuffer[klotz0_1.size + 2] = (double) klotz1_1.xptr; // [609]
unsigned int const k = klotz0_1.size + 3; // 610
#pragma _CRI ivdep
for (short i = 0; i < klotz1_1.size; ++i)
saveBuffer[i + k] = klotz1_1.xbuff[i];
}
// ----------------------------------------------------------------------------
// normalrs
// restore zufall blocks klotz0 and klotz1
// IMPORTANT: saveBuffer must be dimensioned at
// least 1634 in driver. The entire contents
// of klotz0 and klotz1 must be restored.
// ----------------------------------------------------------------------------
void Random::normalrs (
std::vector<double> const & saveBuffer) // size = 1634
{
zufallrs (saveBuffer);
klotz1_1.first = (unsigned int) saveBuffer[klotz0_1.size + 1]; // [608]
if (klotz1_1.first == 0)
{
std::string msg;
msg = "Random::normalrs, restore of uninitialized block.";
throw std::runtime_error (msg);
}
klotz1_1.xptr = (unsigned int) saveBuffer[klotz0_1.size + 2]; // [609]
unsigned int const k = klotz0_1.size + 3; // 610
#pragma _CRI ivdep
for (short i = 0; i < klotz1_1.size; ++i)
klotz1_1.xbuff[i] = saveBuffer[i + k];
}
// ----------------------------------------------------------------------------
// normal00
// ----------------------------------------------------------------------------
void Random::normal00 ()
{
/* Builtin functions */
/* double cos(), sin(), log(), sqrt(); */
double const twopi = 6.2831853071795862;
Uniform (klotz1_1.size, klotz1_1.xbuff);
// std::vector<double>::iterator i = klotz1_1.xbuff.begin();
// std::vector<double>::iterator ip1 = klotz1_1.xbuff.begin();
// while ( ip1 != klotz1_1.xbuff.end() )
// {
// double const r1 = twopi * (*i);
// double const t1 = cos(r1);
// double const t2 = sin(r1);
// double const r2 = sqrt(-2.0 * ( log(1.0 - (*ip1) ) ) );
// (*i) = t1 * r2;
// (*ip1) = t2 * r2;
// ++i; ++i;
// ++ip1; ++ip1;
// }
#pragma _CRI ivdep
for (short i = 0; i < klotz1_1.size - 1; i += 2)
{
double const r1 = twopi * klotz1_1.xbuff[i];
double const t1 = cos(r1);
double const t2 = sin(r1);
double const r2 = sqrt(-2.0 * ( log(1.0 - klotz1_1.xbuff[i+1] ) ) );
klotz1_1.xbuff[i] = t1 * r2;
klotz1_1.xbuff[i+1] = t2 * r2;
}
} // class Random
} // namespace zufall
} // namespace teh
| 15,147 | 6,299 |
// Copyright 2019-2022 Cambridge Quantum Computing
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "CosSinDecomposition.hpp"
#include <cmath>
#include "Constants.hpp"
#include "EigenConfig.hpp"
#include "MatrixAnalysis.hpp"
#include "TketLog.hpp"
namespace tket {
csd_t CS_decomp(const Eigen::MatrixXcd &u) {
if (!is_unitary(u)) {
throw std::invalid_argument("Matrix for CS decomposition is not unitary");
}
unsigned N = u.rows();
if (N % 2 != 0) {
throw std::invalid_argument(
"Matrix for CS decomposition has odd dimensions");
}
unsigned n = N / 2;
Eigen::MatrixXcd u00 = u.topLeftCorner(n, n);
Eigen::MatrixXcd u01 = u.topRightCorner(n, n);
Eigen::MatrixXcd u10 = u.bottomLeftCorner(n, n);
Eigen::MatrixXcd u11 = u.bottomRightCorner(n, n);
Eigen::JacobiSVD<Eigen::MatrixXcd, Eigen::NoQRPreconditioner> svd(
u00, Eigen::ComputeFullU | Eigen::ComputeFullV);
Eigen::MatrixXcd l0 = svd.matrixU().rowwise().reverse();
Eigen::MatrixXcd r0_dag = svd.matrixV().rowwise().reverse();
Eigen::MatrixXd c = svd.singularValues().reverse().asDiagonal();
Eigen::MatrixXcd r0 = r0_dag.adjoint();
// Now u00 = l0 c r0; l0 and r0 are unitary, and c is diagonal with positive
// non-decreasing entries. Because u00 is a submatrix of a unitary matrix, its
// singular values (the entries of c) are all <= 1.
Eigen::HouseholderQR<Eigen::MatrixXcd> qr = (u10 * r0_dag).householderQr();
Eigen::MatrixXcd l1 = qr.householderQ();
Eigen::MatrixXcd S = qr.matrixQR().triangularView<Eigen::Upper>();
// Now u10 r0* = l1 S; l1 is unitary, and S is upper triangular.
//
// Claim: S is diagonal.
// Proof: Since u is unitary, we have
// I = u00* u00 + u10* u10
// = (l0 c r0)* (l0 c r0) + (l1 S r0)* (l1 S r0)
// = r0* c l0* l0 c r0 + r0* S* l1* l1 S r0
// = r0* c^2 r0 + r0* S* S r0
// = r0* (c^2 + S* S) r0
// So I = c^2 + (S* S), so (S* S) = I - c^2 is a diagonal matrix with non-
// increasing entries in the range [0,1). As S is upper triangular, this
// implies that S must be diagonal. (Proof by induction over the dimension n
// of S: consider the two cases S_00 = 0 and S_00 != 0 and reduce to the n-1
// case.)
//
// We want S to be real. This is not guaranteed, though since it is diagonal
// it can be made so by adjusting l1. In fact, it seems that Eigen always does
// give us a real S. We will not assume this, but will log an informational
// message and do the adjustment ourselves if that behaviour does change.
if (!S.imag().isZero()) {
tket_log()->info(
"Eigen surprisingly returned a non-real diagonal R in QR "
"decomposition; adjusting Q and R to make it real.");
for (unsigned j = 0; j < n; j++) {
std::complex<double> z = S(j, j);
double r = std::abs(z);
if (r > EPS) {
std::complex<double> w = std::conj(z) / r;
S(j, j) *= w;
l1.col(j) /= w;
}
}
}
// Now S is real and diagonal, and c^2 + S^2 = I.
Eigen::MatrixXd s = S.real();
// Make all entries in s non-negative.
for (unsigned j = 0; j < n; j++) {
if (s(j, j) < 0) {
s(j, j) = -s(j, j);
l1.col(j) = -l1.col(j);
}
}
// Finally compute r1, being careful not to divide by small things.
Eigen::MatrixXcd r1 = Eigen::MatrixXcd::Zero(n, n);
for (unsigned i = 0; i < n; i++) {
if (s(i, i) > c(i, i)) {
r1.row(i) = -(l0.adjoint() * u01).row(i) / s(i, i);
} else {
r1.row(i) = (l1.adjoint() * u11).row(i) / c(i, i);
}
}
return {l0, l1, r0, r1, c, s};
}
} // namespace tket
| 4,124 | 1,588 |
/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2012, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: openni_viewer.cpp 5059 2012-03-14 02:12:17Z gedikli $
*
*/
#include <pcl/apps/timer.h>
#include <pcl/common/common.h>
#include <pcl/common/angles.h>
#include <pcl/common/time.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/io/pcd_io.h>
#include <pcl/search/organized.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/segmentation/organized_multi_plane_segmentation.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/segmentation/extract_polygonal_prism_data.h>
#include <pcl/sample_consensus/sac_model_plane.h>
//#include <pcl/io/tar_io.h>
#include <pcl/surface/convex_hull.h>
#include <pcl/visualization/point_cloud_handlers.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/image_viewer.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/segmentation/euclidean_cluster_comparator.h>
#include <pcl/segmentation/organized_connected_component_segmentation.h>
#include <pcl/segmentation/edge_aware_plane_comparator.h>
#include <pcl/geometry/polygon_operations.h>
using namespace pcl;
using namespace std;
typedef PointXYZRGBA PointT;
#define SHOW_FPS 1
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class NILinemod {
public:
typedef PointCloud<PointT> Cloud;
typedef Cloud::Ptr CloudPtr;
typedef Cloud::ConstPtr CloudConstPtr;
bool added;
NILinemod(Grabber &grabber)
: cloud_viewer_("PointCloud"), grabber_(grabber),
image_viewer_("Image"), first_frame_(true) {
added = false;
// Set the parameters for normal estimation
ne_.setNormalEstimationMethod(ne_.COVARIANCE_MATRIX);
ne_.setMaxDepthChangeFactor(0.02f);
ne_.setNormalSmoothingSize(20.0f);
// Set the parameters for planar segmentation
plane_comparator_.reset(new EdgeAwarePlaneComparator<PointT, Normal>);
plane_comparator_->setDistanceThreshold(0.01f, false);
mps_.setMinInliers(5000);
mps_.setAngularThreshold(pcl::deg2rad(3.0)); // 3 degrees
mps_.setDistanceThreshold(0.02); // 2 cm
mps_.setMaximumCurvature(0.001); // a small curvature
mps_.setProjectPoints(true);
mps_.setComparator(plane_comparator_);
}
/////////////////////////////////////////////////////////////////////////
void cloud_callback(const CloudConstPtr &cloud) {
FPS_CALC("cloud callback");
boost::mutex::scoped_lock lock(cloud_mutex_);
cloud_ = cloud;
search_.setInputCloud(cloud);
// Subsequent frames are segmented by "tracking" the parameters of the
// previous frame We do this by using the estimated inliers from
// previous frames in the current frame, and refining the coefficients
if (!first_frame_) {
if (!plane_indices_ || plane_indices_->indices.empty() ||
!search_.getInputCloud()) {
PCL_ERROR(
"Lost tracking. Select the object again to continue.\n");
first_frame_ = true;
return;
}
SACSegmentation<PointT> seg;
seg.setOptimizeCoefficients(true);
seg.setModelType(SACMODEL_PLANE);
seg.setMethodType(SAC_RANSAC);
seg.setMaxIterations(1000);
seg.setDistanceThreshold(0.01);
seg.setInputCloud(search_.getInputCloud());
seg.setIndices(plane_indices_);
ModelCoefficients coefficients;
PointIndices inliers;
seg.segment(inliers, coefficients);
if (inliers.indices.empty()) {
PCL_ERROR("No planar model found. Select the object again to "
"continue.\n");
first_frame_ = true;
return;
}
// Visualize the object in 3D...
CloudPtr plane_inliers(new Cloud);
pcl::copyPointCloud(*search_.getInputCloud(), inliers.indices,
*plane_inliers);
if (plane_inliers->points.empty()) {
PCL_ERROR("No planar model found. Select the object again to "
"continue.\n");
first_frame_ = true;
return;
} else {
plane_.reset(new Cloud);
// Compute the convex hull of the plane
ConvexHull<PointT> chull;
chull.setDimension(2);
chull.setInputCloud(plane_inliers);
chull.reconstruct(*plane_);
}
}
}
/////////////////////////////////////////////////////////////////////////
CloudConstPtr getLatestCloud() {
// Lock while we swap our cloud and reset it.
boost::mutex::scoped_lock lock(cloud_mutex_);
CloudConstPtr temp_cloud;
temp_cloud.swap(cloud_);
return (temp_cloud);
}
/////////////////////////////////////////////////////////////////////////
void keyboard_callback(const visualization::KeyboardEvent &, void *) {
// if (event.getKeyCode())
// cout << "the key \'" << event.getKeyCode() << "\' (" <<
// event.getKeyCode() << ") was";
// else
// cout << "the special key \'" << event.getKeySym() << "\' was";
// if (event.keyDown())
// cout << " pressed" << endl;
// else
// cout << " released" << endl;
}
/////////////////////////////////////////////////////////////////////////
void mouse_callback(const visualization::MouseEvent &, void *) {
// if (mouse_event.getType() ==
// visualization::MouseEvent::MouseButtonPress && mouse_event.getButton()
// == visualization::MouseEvent::LeftButton)
//{
// cout << "left button pressed @ " << mouse_event.getX () << " , " <<
// mouse_event.getY () << endl;
//}
}
/////////////////////////////////////////////////////////////////////////
/** \brief Given a plane, and the set of inlier indices representing it,
* segment out the object of intererest supported by it.
*
* \param[in] picked_idx the index of a point on the object
* \param[in] cloud the full point cloud dataset
* \param[in] plane_indices a set of indices representing the plane
* supporting the object of interest \param[in] plane_boundary_indices a set
* of indices representing the boundary of the plane \param[out] object the
* segmented resultant object
*/
void segmentObject(int picked_idx, const CloudConstPtr &cloud,
const PointIndices::Ptr &plane_indices,
const PointIndices::Ptr &plane_boundary_indices,
Cloud &object) {
CloudPtr plane_hull(new Cloud);
// Compute the convex hull of the plane
ConvexHull<PointT> chull;
chull.setDimension(2);
chull.setInputCloud(cloud);
chull.setIndices(plane_boundary_indices);
chull.reconstruct(*plane_hull);
// Remove the plane indices from the data
PointIndices::Ptr everything_but_the_plane(new PointIndices);
if (indices_fullset_.size() != cloud->points.size()) {
indices_fullset_.resize(cloud->points.size());
for (int p_it = 0; p_it < static_cast<int>(indices_fullset_.size());
++p_it)
indices_fullset_[p_it] = p_it;
}
std::vector<int> indices_subset = plane_indices->indices;
std::sort(indices_subset.begin(), indices_subset.end());
set_difference(indices_fullset_.begin(), indices_fullset_.end(),
indices_subset.begin(), indices_subset.end(),
inserter(everything_but_the_plane->indices,
everything_but_the_plane->indices.begin()));
// Extract all clusters above the hull
PointIndices::Ptr points_above_plane(new PointIndices);
ExtractPolygonalPrismData<PointT> exppd;
exppd.setInputCloud(cloud);
exppd.setInputPlanarHull(plane_hull);
exppd.setIndices(everything_but_the_plane);
exppd.setHeightLimits(0.0, 0.5); // up to half a meter
exppd.segment(*points_above_plane);
// Use an organized clustering segmentation to extract the individual
// clusters
EuclideanClusterComparator<PointT, Normal, Label>::Ptr
euclidean_cluster_comparator(
new EuclideanClusterComparator<PointT, Normal, Label>);
euclidean_cluster_comparator->setInputCloud(cloud);
euclidean_cluster_comparator->setDistanceThreshold(0.03f, false);
// Set the entire scene to false, and the inliers of the objects located
// on top of the plane to true
Label l;
l.label = 0;
PointCloud<Label>::Ptr scene(
new PointCloud<Label>(cloud->width, cloud->height, l));
// Mask the objects that we want to split into clusters
for (int i = 0;
i < static_cast<int>(points_above_plane->indices.size()); ++i)
scene->points[points_above_plane->indices[i]].label = 1;
euclidean_cluster_comparator->setLabels(scene);
vector<bool> exclude_labels(2);
exclude_labels[0] = true;
exclude_labels[1] = false;
euclidean_cluster_comparator->setExcludeLabels(exclude_labels);
OrganizedConnectedComponentSegmentation<PointT, Label>
euclidean_segmentation(euclidean_cluster_comparator);
euclidean_segmentation.setInputCloud(cloud);
PointCloud<Label> euclidean_labels;
vector<PointIndices> euclidean_label_indices;
euclidean_segmentation.segment(euclidean_labels,
euclidean_label_indices);
// For each cluster found
bool cluster_found = false;
for (size_t i = 0; i < euclidean_label_indices.size(); i++) {
if (cluster_found)
break;
// Check if the point that we picked belongs to it
for (size_t j = 0; j < euclidean_label_indices[i].indices.size();
++j) {
if (picked_idx != euclidean_label_indices[i].indices[j])
continue;
// pcl::PointCloud<PointT> cluster;
pcl::copyPointCloud(*cloud, euclidean_label_indices[i].indices,
object);
cluster_found = true;
break;
// object_indices = euclidean_label_indices[i].indices;
// clusters.push_back (cluster);
}
}
}
/////////////////////////////////////////////////////////////////////////
void segment(const PointT &picked_point, int picked_idx,
PlanarRegion<PointT> ®ion, PointIndices &,
CloudPtr &object) {
// First frame is segmented using an organized multi plane segmentation
// approach from points and their normals
if (!first_frame_)
return;
// Estimate normals in the cloud
PointCloud<Normal>::Ptr normal_cloud(new PointCloud<Normal>);
ne_.setInputCloud(search_.getInputCloud());
ne_.compute(*normal_cloud);
plane_comparator_->setDistanceMap(ne_.getDistanceMap());
// Segment out all planes
mps_.setInputNormals(normal_cloud);
mps_.setInputCloud(search_.getInputCloud());
// Use one of the overloaded segmentAndRefine calls to get all the
// information that we want out
vector<PlanarRegion<PointT>,
Eigen::aligned_allocator<PlanarRegion<PointT>>>
regions;
vector<ModelCoefficients> model_coefficients;
vector<PointIndices> inlier_indices;
PointCloud<Label>::Ptr labels(new PointCloud<Label>);
vector<PointIndices> label_indices;
vector<PointIndices> boundary_indices;
mps_.segmentAndRefine(regions, model_coefficients, inlier_indices,
labels, label_indices, boundary_indices);
PCL_DEBUG("Number of planar regions detected: %zu for a cloud of %zu "
"points and %zu normals.\n",
regions.size(), search_.getInputCloud()->points.size(),
normal_cloud->points.size());
double max_dist = numeric_limits<double>::max();
// Compute the distances from all the planar regions to the picked
// point, and select the closest region
int idx = -1;
for (size_t i = 0; i < regions.size(); ++i) {
double dist = pointToPlaneDistance(picked_point,
regions[i].getCoefficients());
if (dist < max_dist) {
max_dist = dist;
idx = static_cast<int>(i);
}
}
PointIndices::Ptr plane_boundary_indices;
// Get the plane that holds the object of interest
if (idx != -1) {
region = regions[idx];
plane_indices_.reset(new PointIndices(inlier_indices[idx]));
plane_boundary_indices.reset(
new PointIndices(boundary_indices[idx]));
}
// Segment the object of interest
if (plane_boundary_indices &&
!plane_boundary_indices->indices.empty()) {
object.reset(new Cloud);
segmentObject(picked_idx, search_.getInputCloud(), plane_indices_,
plane_boundary_indices, *object);
// Save to disk
// pcl::io::saveTARPointCloud ("output.ltm", *object, "object.pcd");
}
first_frame_ = false;
}
/////////////////////////////////////////////////////////////////////////
/** \brief Point picking callback. This gets called when the user selects
* a 3D point on screen (in the PCLVisualizer window) using Shift+click.
*
* \param[in] event the event that triggered the call
*/
void pp_callback(const visualization::PointPickingEvent &event, void *) {
// Check to see if we got a valid point. Early exit.
int idx = event.getPointIndex();
if (idx == -1)
return;
vector<int> indices(1);
vector<float> distances(1);
// Use mutices to make sure we get the right cloud
boost::mutex::scoped_lock lock1(cloud_mutex_);
// Get the point that was picked
PointT picked_pt;
event.getPoint(picked_pt.x, picked_pt.y, picked_pt.z);
// Add a sphere to it in the PCLVisualizer window
stringstream ss;
ss << "sphere_" << idx;
cloud_viewer_.addSphere(picked_pt, 0.01, 1.0, 0.0, 0.0, ss.str());
// Check to see if we have access to the actual cloud data. Use the
// previously built search object.
if (!search_.isValid())
return;
// Because VTK/OpenGL stores data without NaN, we lose the 1-1
// correspondence, so we must search for the real point
search_.nearestKSearch(picked_pt, 1, indices, distances);
// Get the [u, v] in pixel coordinates for the ImageViewer. Remember
// that 0,0 is bottom left.
uint32_t width = search_.getInputCloud()->width,
height = search_.getInputCloud()->height;
int v = indices[0] / width, u = indices[0] % width;
// Add some marker to the image
image_viewer_.addCircle(u, v, 5, 1.0, 0.0, 0.0, "circles", 1.0);
image_viewer_.addFilledRectangle(u - 5, u + 5, v - 5, v + 5, 0.0, 1.0,
0.0, "boxes", 0.5);
image_viewer_.markPoint(u, v, visualization::red_color,
visualization::blue_color, 10);
// Segment the region that we're interested in, by employing a two step
// process:
// * first, segment all the planes in the scene, and find the one
// closest to our picked point
// * then, use euclidean clustering to find the object that we clicked
// on and return it
PlanarRegion<PointT> region;
CloudPtr object;
PointIndices region_indices;
segment(picked_pt, indices[0], region, region_indices, object);
// If no region could be determined, exit
if (region.getContour().empty()) {
PCL_ERROR("No planar region detected. Please select another point "
"or relax the thresholds and continue.\n");
return;
}
// Else, draw it on screen
else {
// cloud_viewer_.addPolygon (region, 1.0, 0.0, 0.0, "region");
// cloud_viewer_.setShapeRenderingProperties
// (visualization::PCL_VISUALIZER_LINE_WIDTH, 10, "region");
PlanarRegion<PointT> refined_region;
pcl::approximatePolygon(region, refined_region, 0.01, false, true);
PCL_INFO("Planar region: %zu points initial, %zu points after "
"refinement.\n",
region.getContour().size(),
refined_region.getContour().size());
cloud_viewer_.addPolygon(refined_region, 0.0, 0.0, 1.0,
"refined_region");
cloud_viewer_.setShapeRenderingProperties(
visualization::PCL_VISUALIZER_LINE_WIDTH, 10, "refined_region");
// Draw in image space
image_viewer_.addPlanarPolygon(search_.getInputCloud(),
refined_region, 0.0, 0.0, 1.0,
"refined_region", 1.0);
}
// If no object could be determined, exit
if (!object) {
PCL_ERROR("No object detected. Please select another point or "
"relax the thresholds and continue.\n");
return;
} else {
// Visualize the object in 3D...
visualization::PointCloudColorHandlerCustom<PointT> red(object, 255,
0, 0);
if (!cloud_viewer_.updatePointCloud(object, red, "object"))
cloud_viewer_.addPointCloud(object, red, "object");
// ...and 2D
image_viewer_.removeLayer("object");
image_viewer_.addMask(search_.getInputCloud(), *object, "object");
// Compute the min/max of the object
PointT min_pt, max_pt;
getMinMax3D(*object, min_pt, max_pt);
stringstream ss;
ss << "cube_" << idx;
// Visualize the bounding box in 3D...
cloud_viewer_.addCube(min_pt.x, max_pt.x, min_pt.y, max_pt.y,
min_pt.z, max_pt.z, 0.0, 1.0, 0.0, ss.str());
cloud_viewer_.setShapeRenderingProperties(
visualization::PCL_VISUALIZER_LINE_WIDTH, 10, ss.str());
// ...and 2D
image_viewer_.addRectangle(search_.getInputCloud(), *object);
}
}
/////////////////////////////////////////////////////////////////////////
void init() {
cloud_viewer_.registerMouseCallback(&NILinemod::mouse_callback, *this);
cloud_viewer_.registerKeyboardCallback(&NILinemod::keyboard_callback,
*this);
cloud_viewer_.registerPointPickingCallback(&NILinemod::pp_callback,
*this);
boost::function<void(const CloudConstPtr &)> cloud_cb =
boost::bind(&NILinemod::cloud_callback, this, _1);
cloud_connection = grabber_.registerCallback(cloud_cb);
image_viewer_.registerMouseCallback(&NILinemod::mouse_callback, *this);
image_viewer_.registerKeyboardCallback(&NILinemod::keyboard_callback,
*this);
}
/////////////////////////////////////////////////////////////////////////
void run() {
grabber_.start();
bool image_init = false, cloud_init = false;
while (!cloud_viewer_.wasStopped() && !image_viewer_.wasStopped()) {
if (cloud_) {
CloudConstPtr cloud = getLatestCloud();
if (!cloud_init) {
cloud_viewer_.setPosition(0, 0);
cloud_viewer_.setSize(cloud->width, cloud->height);
cloud_init = !cloud_init;
}
if (!cloud_viewer_.updatePointCloud(cloud, "OpenNICloud")) {
cloud_viewer_.addPointCloud(cloud, "OpenNICloud");
cloud_viewer_.resetCameraViewpoint("OpenNICloud");
}
if (!image_init) {
image_viewer_.setPosition(cloud->width, 0);
image_viewer_.setSize(cloud->width, cloud->height);
image_init = !image_init;
}
image_viewer_.showRGBImage<PointT>(cloud);
}
// Add the plane that we're tracking to the cloud visualizer
CloudPtr plane(new Cloud);
if (plane_)
*plane = *plane_;
visualization::PointCloudColorHandlerCustom<PointT> blue(plane, 0,
255, 0);
if (!cloud_viewer_.updatePointCloud(plane, blue, "plane"))
cloud_viewer_.addPointCloud(plane, "plane");
cloud_viewer_.spinOnce();
image_viewer_.spinOnce();
boost::this_thread::sleep(boost::posix_time::microseconds(100));
}
grabber_.stop();
cloud_connection.disconnect();
}
visualization::PCLVisualizer cloud_viewer_;
Grabber &grabber_;
boost::mutex cloud_mutex_;
CloudConstPtr cloud_;
visualization::ImageViewer image_viewer_;
search::OrganizedNeighbor<PointT> search_;
private:
boost::signals2::connection cloud_connection, image_connection;
bool first_frame_;
// Segmentation
std::vector<int> indices_fullset_;
PointIndices::Ptr plane_indices_;
CloudPtr plane_;
IntegralImageNormalEstimation<PointT, Normal> ne_;
OrganizedMultiPlaneSegmentation<PointT, Normal, Label> mps_;
EdgeAwarePlaneComparator<PointT, Normal>::Ptr plane_comparator_;
};
/* ---[ */
int main(int, char **) {
string device_id("#1");
OpenNIGrabber grabber(device_id);
NILinemod openni_viewer(grabber);
openni_viewer.init();
openni_viewer.run();
return (0);
}
/* ]--- */
| 24,452 | 7,095 |
// Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved.
#include "Managers/WidgetActor/Cache/CsCache_WidgetActorImpl.h"
// Library
#include "Managers/Pool/Payload/CsLibrary_Payload_PooledObject.h"
// Pool
#include "Managers/Pool/Payload/CsPayload_PooledObject.h"
// FX
#include "Managers/WidgetActor/Payload/CsPayload_WidgetActor.h"
#include "NiagaraComponent.h"
// Component
#include "Components/CsWidgetComponent.h"
const FName NCsWidgetActor::NCache::FImpl::Name = FName("NCsWidgetActor::NCache::FImpl");
namespace NCsWidgetActor
{
namespace NCache
{
namespace NImplCached
{
namespace Str
{
CS_DEFINE_CACHED_FUNCTION_NAME_AS_STRING(NCsWidgetActor::NCache::FImpl, Allocate);
}
}
FImpl::FImpl() :
// ICsGetInterfaceMap
InterfaceMap(nullptr),
// PooledCacheType (NCsPooledObject::NCache::ICache)
Index(INDEX_NONE),
bAllocated(false),
bQueueDeallocate(false),
State(NCsPooledObject::EState::Inactive),
UpdateType(NCsPooledObject::EUpdate::Manager),
Instigator(),
Owner(),
Parent(),
WarmUpTime(0.0f),
LifeTime(0.0f),
StartTime(),
ElapsedTime(),
// WidgetActorCacheType (NCsWidgetActor::NCache::ICache)
DeallocateMethod(ECsWidgetActorDeallocateMethod::Complete),
QueuedLifeTime(0.0f)
{
InterfaceMap = new FCsInterfaceMap();
InterfaceMap->SetRoot<FImpl>(this);
typedef NCsPooledObject::NCache::ICache PooledCacheType;
typedef NCsWidgetActor::NCache::ICache WidgetActorCacheType;
InterfaceMap->Add<PooledCacheType>(static_cast<PooledCacheType*>(this));
InterfaceMap->Add<WidgetActorCacheType>(static_cast<WidgetActorCacheType*>(this));
}
FImpl::~FImpl()
{
delete InterfaceMap;
}
// PooledCacheType (NCsPooledObject::NCache::ICache)
#pragma region
#define PooledPayloadType NCsPooledObject::NPayload::IPayload
void FImpl::Allocate(PooledPayloadType* Payload)
{
#undef PooledPayloadType
using namespace NImplCached;
const FString& Context = Str::Allocate;
// PooledCacheType (NCsPooledObject::NCache::ICache)
bAllocated = true;
State = NCsPooledObject::EState::Active;
UpdateType = Payload->GetUpdateType();
Instigator = Payload->GetInstigator();
Owner = Payload->GetOwner();
Parent = Payload->GetParent();
StartTime = Payload->GetTime();
// WidgetActorCacheType (NCsWidgetActor::NPayload::IPayload)
typedef NCsWidgetActor::NPayload::IPayload WidgetPayloadType;
typedef NCsPooledObject::NPayload::FLibrary PooledPayloadLibrary;
WidgetPayloadType* WidgetPayload = PooledPayloadLibrary::GetInterfaceChecked<WidgetPayloadType>(Context, Payload);
DeallocateMethod = WidgetPayload->GetDeallocateMethod();
QueuedLifeTime = WidgetPayload->GetLifeTime();
}
void FImpl::Deallocate()
{
Reset();
}
void FImpl::QueueDeallocate()
{
bQueueDeallocate = true;
// LifeTime
if (DeallocateMethod == ECsWidgetActorDeallocateMethod::LifeTime)
{
// Reset ElapsedTime
ElapsedTime.Reset();
// Set LifeTime
LifeTime = QueuedLifeTime;
}
}
bool FImpl::ShouldDeallocate() const
{
if (bQueueDeallocate)
{
// LifeTime, let HasLifeTimeExpired handle deallocation
if (DeallocateMethod == ECsWidgetActorDeallocateMethod::LifeTime)
{
return false;
}
return bQueueDeallocate;
}
return false;
}
bool FImpl::HasLifeTimeExpired()
{
return LifeTime > 0.0f && ElapsedTime.Time > LifeTime;
}
void FImpl::Reset()
{
// PooledCacheType (NCsPooledObject::NCache::ICache)
bAllocated = false;
bQueueDeallocate = false;
State = NCsPooledObject::EState::Inactive;
UpdateType = NCsPooledObject::EUpdate::Manager;
Instigator.Reset();
Owner.Reset();
Parent.Reset();
WarmUpTime = 0.0f;
LifeTime = 0.0f;
StartTime.Reset();
ElapsedTime.Reset();
// WidgetActorCacheType (NCsWidgetActor::NPayload::IPayload)
DeallocateMethod = ECsWidgetActorDeallocateMethod::ECsWidgetActorDeallocateMethod_MAX;
QueuedLifeTime = 0.0f;
}
#pragma endregion PooledCacheType (NCsPooledObject::NCache::ICache)
void FImpl::Update(const FCsDeltaTime& DeltaTime)
{
ElapsedTime += DeltaTime;
}
}
} | 4,185 | 1,744 |
// 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.
// This file tests the chrome.alarms extension API.
#include "base/json/json_writer.h"
#include "base/values.h"
#include "chrome/browser/extensions/api/discovery/discovery_api.h"
#include "chrome/browser/extensions/api/discovery/suggested_link.h"
#include "chrome/browser/extensions/api/discovery/suggested_links_registry.h"
#include "chrome/browser/extensions/api/discovery/suggested_links_registry_factory.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/extensions/api/experimental_discovery.h"
#include "chrome/test/base/browser_with_test_window_test.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace utils = extension_function_test_utils;
namespace {
typedef extensions::SuggestedLinksRegistry::SuggestedLinkList SuggestedLinkList;
typedef extensions::api::experimental_discovery::SuggestDetails SuggestDetails;
// Converts suggest details used as parameter into a JSON string.
std::string SuggestDetailsParamToJSON(const SuggestDetails& suggest_details) {
std::string result;
scoped_ptr<base::DictionaryValue> value = suggest_details.ToValue();
base::ListValue params;
params.Append(value.release()); // |params| takes ownership of |value|.
base::JSONWriter::Write(¶ms, &result);
return result;
}
// Converts the parameters to the API Suggest method to JSON (without score).
std::string UnscoredSuggestParamsToJSON(const std::string& link_url,
const std::string& link_text) {
SuggestDetails suggest_details;
suggest_details.link_url = link_url;
suggest_details.link_text = link_text;
return SuggestDetailsParamToJSON(suggest_details);
}
// Converts the parameters to the API Suggest method to JSON.
std::string SuggestParamsToJSON(const std::string& link_url,
const std::string& link_text,
double score) {
SuggestDetails suggest_details;
suggest_details.score.reset(new double(score));
suggest_details.link_url = link_url;
suggest_details.link_text = link_text;
return SuggestDetailsParamToJSON(suggest_details);
}
// Converts the parameters to the API RemoveSuggestion method to JSON.
std::string RemoveSuggestionParamsToJSON(const std::string& link_url) {
std::string result;
base::ListValue params;
params.Append(new base::StringValue(link_url));
base::JSONWriter::Write(¶ms, &result);
return result;
}
} // namespace
namespace extensions {
class ExtensionDiscoveryTest : public BrowserWithTestWindowTest {
public:
virtual void SetUp() {
BrowserWithTestWindowTest::SetUp();
extension_ = utils::CreateEmptyExtensionWithLocation(Manifest::UNPACKED);
}
// Runs a function and returns a pointer to a value, transferring ownership.
base::Value* RunFunctionWithExtension(
UIThreadExtensionFunction* function, const std::string& args) {
function->set_extension(extension_.get());
return utils::RunFunctionAndReturnSingleResult(function, args, browser());
}
// Runs a function and ignores the return value.
void RunFunction(UIThreadExtensionFunction* function,
const std::string& args) {
scoped_ptr<base::Value> result(RunFunctionWithExtension(function, args));
}
const std::string& GetExtensionId() const {
return extension_->id();
}
protected:
scoped_refptr<Extension> extension_;
};
TEST_F(ExtensionDiscoveryTest, Suggest) {
RunFunction(new DiscoverySuggestFunction(),
SuggestParamsToJSON("http://www.google.com", "Google", 0.5));
extensions::SuggestedLinksRegistry* registry =
extensions::SuggestedLinksRegistryFactory::GetForProfile(
browser()->profile());
const SuggestedLinkList* links = registry->GetAll(GetExtensionId());
ASSERT_EQ(1u, links->size());
ASSERT_EQ("http://www.google.com", links->at(0)->link_url());
ASSERT_EQ("Google", links->at(0)->link_text());
ASSERT_DOUBLE_EQ(0.5, links->at(0)->score());
}
TEST_F(ExtensionDiscoveryTest, SuggestWithoutScore) {
RunFunction(new DiscoverySuggestFunction(),
UnscoredSuggestParamsToJSON("https://amazon.com/", "Amazon"));
extensions::SuggestedLinksRegistry* registry =
extensions::SuggestedLinksRegistryFactory::GetForProfile(
browser()->profile());
const SuggestedLinkList* links = registry->GetAll(GetExtensionId());
ASSERT_EQ(1u, links->size());
ASSERT_EQ("https://amazon.com/", links->at(0)->link_url());
ASSERT_EQ("Amazon", links->at(0)->link_text());
ASSERT_DOUBLE_EQ(1.0, links->at(0)->score()); // Score should default to 1.
}
TEST_F(ExtensionDiscoveryTest, SuggestTwiceSameUrl) {
// Suggesting the same URL a second time should override the first.
RunFunction(new DiscoverySuggestFunction(),
SuggestParamsToJSON("http://www.google.com", "Google", 0.5));
RunFunction(new DiscoverySuggestFunction(),
SuggestParamsToJSON("http://www.google.com", "Google2", 0.1));
extensions::SuggestedLinksRegistry* registry =
extensions::SuggestedLinksRegistryFactory::GetForProfile(
browser()->profile());
const SuggestedLinkList* links = registry->GetAll(GetExtensionId());
ASSERT_EQ(1u, links->size());
ASSERT_EQ("http://www.google.com", links->at(0)->link_url());
ASSERT_EQ("Google2", links->at(0)->link_text());
ASSERT_DOUBLE_EQ(0.1, links->at(0)->score());
}
TEST_F(ExtensionDiscoveryTest, Remove) {
RunFunction(new DiscoverySuggestFunction(),
UnscoredSuggestParamsToJSON("http://www.google.com", "Google"));
RunFunction(new DiscoverySuggestFunction(),
UnscoredSuggestParamsToJSON("https://amazon.com/", "Amazon"));
RunFunction(new DiscoverySuggestFunction(),
UnscoredSuggestParamsToJSON("http://www.youtube.com/watch?v=zH5bJSG0DZk",
"YouTube"));
RunFunction(new DiscoveryRemoveSuggestionFunction(),
RemoveSuggestionParamsToJSON("https://amazon.com/"));
extensions::SuggestedLinksRegistry* registry =
extensions::SuggestedLinksRegistryFactory::GetForProfile(
browser()->profile());
const SuggestedLinkList* links = registry->GetAll(GetExtensionId());
ASSERT_EQ(2u, links->size());
ASSERT_EQ("http://www.google.com", links->at(0)->link_url());
ASSERT_EQ("Google", links->at(0)->link_text());
ASSERT_DOUBLE_EQ(1.0, links->at(0)->score());
ASSERT_EQ("http://www.youtube.com/watch?v=zH5bJSG0DZk",
links->at(1)->link_url());
ASSERT_EQ("YouTube", links->at(1)->link_text());
ASSERT_DOUBLE_EQ(1.0, links->at(1)->score());
}
TEST_F(ExtensionDiscoveryTest, ClearAll) {
RunFunction(new DiscoverySuggestFunction(),
UnscoredSuggestParamsToJSON("http://www.google.com", "Google"));
RunFunction(new DiscoverySuggestFunction(),
UnscoredSuggestParamsToJSON("https://amazon.com/", "Amazon"));
RunFunction(new DiscoverySuggestFunction(),
UnscoredSuggestParamsToJSON("http://www.youtube.com/watch?v=zH5bJSG0DZk",
"YouTube"));
RunFunction(new DiscoveryClearAllSuggestionsFunction(), "[]");
extensions::SuggestedLinksRegistry* registry =
extensions::SuggestedLinksRegistryFactory::GetForProfile(
browser()->profile());
const SuggestedLinkList* links = registry->GetAll(GetExtensionId());
ASSERT_EQ(0u, links->size());
}
} // namespace extensions
| 7,588 | 2,409 |
/****************************
Copyright (c) 2006-2012 Luke Salisbury
Copyright (c) 2008 Mokoi Gaming
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
****************************/
#include "core.h"
#include "luxengine.h"
/* Local functions */
CoreSystem::CoreSystem()
{
}
CoreSystem::~CoreSystem()
{
}
uint32_t CoreSystem::WasInit(uint32_t flag)
{
return 1;
}
void CoreSystem::QuitSubSystem(uint32_t flag)
{
}
bool CoreSystem::InitSubSystem(uint32_t flag)
{
return true;
}
bool CoreSystem::Good()
{
return this->good;
}
uint32_t CoreSystem::GetTime()
{
return 0;
}
uint32_t CoreSystem::GetFrameDelta()
{
return 15;
}
bool CoreSystem::DelayIf(uint32_t diff)
{
return false;
}
void CoreSystem::Idle()
{
}
LuxState CoreSystem::HandleFrame(LuxState old_state)
{
if ( this->state > PAUSED || old_state >= SAVING )
{
this->state = old_state;
}
this->RefreshInput(lux::display);
this->time = this->GetTime();
return this->state;
}
int16_t CoreSystem::GetInput(InputDevice device, uint32_t device_number, int32_t symbol)
{
if (device == NOINPUT)
{
return 0;
}
switch (device)
{
case CONTROLAXIS:
{
return 0;
}
case CONTROLBUTTON:
{
return 0;
}
case KEYBOARD:
case MOUSEAXIS:
case MOUSEBUTTON:
case NOINPUT:
default:
return 0;
}
return 0;
}
void CoreSystem::RefreshInput( DisplaySystem * display )
{
}
bool CoreSystem::InputLoopGet(uint16_t & key)
{
// Keyboard Stuff
return 0;
}
| 2,217 | 800 |
/* Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#define LOG_COMPONENT_TAG "test_services_threaded"
#include <fcntl.h>
#include <mysql/plugin.h>
#include <mysql_version.h>
#include <stdlib.h>
#include <mysql/components/my_service.h>
#include <mysql/components/services/log_builtins.h>
#include <mysqld_error.h>
#include "m_string.h" // strlen
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_io.h"
#include "my_sys.h" // my_write, my_malloc
#include "sql/sql_plugin.h" // st_plugin_int
#define STRING_BUFFER 256
static SERVICE_TYPE(registry) *reg_srv = nullptr;
SERVICE_TYPE(log_builtins) *log_bi = nullptr;
SERVICE_TYPE(log_builtins_string) *log_bs = nullptr;
File outfile;
struct test_services_context {
my_thread_handle test_services_thread;
};
/* Shows status of test (Busy/READY) */
enum t_test_status { BUSY = 0, READY = 1 };
static t_test_status test_status;
/* declaration of status variable for plugin */
static SHOW_VAR test_services_status[] = {
{"test_services_status", (char *)&test_status, SHOW_INT, SHOW_SCOPE_GLOBAL},
{nullptr, nullptr, SHOW_UNDEF, SHOW_SCOPE_GLOBAL}};
/* SQL variables to control test execution */
/* SQL variables to switch on/off test of services, default=on */
/* Only be effective at start od mysqld by setting it as option --loose-... */
static int with_log_message_val = 0;
static MYSQL_SYSVAR_INT(with_log_message, with_log_message_val,
PLUGIN_VAR_RQCMDARG,
"Switch on/off test of log message service", nullptr,
nullptr, 1, 0, 1, 0);
static SYS_VAR *test_services_sysvars[] = {MYSQL_SYSVAR(with_log_message),
nullptr};
/* The test cases for the log_message service. */
static int test_log_plugin_error() {
DBUG_TRACE;
/* Writes to mysqld.1.err: Plugin test_services reports an info text */
LogPluginErr(INFORMATION_LEVEL, ER_LOG_PRINTF_MSG,
"This is the test plugin for services");
/* Writes to mysqld.1.err: Plugin test_services reports a warning. */
LogPluginErr(WARNING_LEVEL, ER_LOG_PRINTF_MSG,
"This is a warning from test plugin for services");
/* Writes to mysqld.1.err: Plugin test_services reports an error. */
LogPluginErr(ERROR_LEVEL, ER_LOG_PRINTF_MSG,
"This is an error from test plugin for services");
return 0;
}
/* This fucntion is needed to be called in a thread. */
static void *test_services(void *p MY_ATTRIBUTE((unused))) {
DBUG_TRACE;
int ret = 0;
test_status = BUSY;
/* Test of service: LogPluginErr/LogPluginErrMsg */
/* Log the value of the switch in mysqld.err. */
LogPluginErrMsg(INFORMATION_LEVEL, ER_LOG_PRINTF_MSG,
"Test_services_threaded with_log_message_val: %d",
with_log_message_val);
if (with_log_message_val == 1) {
ret = test_log_plugin_error();
} else {
LogPluginErr(INFORMATION_LEVEL, ER_LOG_PRINTF_MSG,
"Test of log_message switched off");
}
test_status = READY;
if (ret != 0) {
LogPluginErr(ERROR_LEVEL, ER_LOG_PRINTF_MSG,
"Test services return code: %d", ret);
}
return nullptr;
}
/* Creates the plugin context "con", which holds a pointer to the thread. */
static int test_services_plugin_init(void *p) {
DBUG_TRACE;
int ret = 0;
if (init_logging_service_for_plugin(®_srv, &log_bi, &log_bs)) return 1;
struct test_services_context *con;
my_thread_attr_t attr; /* Thread attributes */
struct st_plugin_int *plugin = (struct st_plugin_int *)p;
con = (struct test_services_context *)my_malloc(
PSI_INSTRUMENT_ME, sizeof(struct test_services_context), MYF(0));
my_thread_attr_init(&attr);
(void)my_thread_attr_setdetachstate(&attr, MY_THREAD_CREATE_JOINABLE);
/* now create the thread and call test_services within the thread. */
if (my_thread_create(&con->test_services_thread, &attr, test_services, p) !=
0) {
LogPluginErr(ERROR_LEVEL, ER_LOG_PRINTF_MSG,
"Could not create test services thread!");
exit(0);
}
plugin->data = (void *)con;
return ret;
}
/* Clean up thread and frees plugin context "con". */
static int test_services_plugin_deinit(void *p) {
DBUG_TRACE;
void *dummy_retval;
struct st_plugin_int *plugin = (struct st_plugin_int *)p;
struct test_services_context *con =
(struct test_services_context *)plugin->data;
my_thread_cancel(&con->test_services_thread);
my_thread_join(&con->test_services_thread, &dummy_retval);
my_free(con);
deinit_logging_service_for_plugin(®_srv, &log_bi, &log_bs);
return 0;
}
/* Mandatory structure describing the properties of the plugin. */
struct st_mysql_daemon test_services_plugin = {MYSQL_DAEMON_INTERFACE_VERSION};
mysql_declare_plugin(test_daemon){
MYSQL_DAEMON_PLUGIN,
&test_services_plugin,
"test_services_threaded",
PLUGIN_AUTHOR_ORACLE,
"Test services with thread",
PLUGIN_LICENSE_GPL,
test_services_plugin_init, /* Plugin Init */
nullptr, /* Plugin Check uninstall */
test_services_plugin_deinit, /* Plugin Deinit */
0x0100 /* 1.0 */,
test_services_status, /* status variables */
test_services_sysvars, /* system variables */
nullptr, /* config options */
0, /* flags */
} mysql_declare_plugin_end;
| 6,602 | 2,199 |
// Created on: 1994-02-08
// Created by: Gilles DEBARBOUILLE
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Quantity_Impedance_HeaderFile
#define _Quantity_Impedance_HeaderFile
#include <Standard_Real.hxx>
//! Defined as the total opposition to the flow of current
//! in a circuit. Includes the contributions of resistance,
//! inductance, and capacitance.
//! It is measured in Ohms.
Standard_DEPRECATED("This type is deprecated - Standard_Real should be used instead")
typedef Standard_Real Quantity_Impedance;
#endif // _Quantity_Impedance_HeaderFile
| 1,206 | 383 |
#ifndef CUKE_STEPMANAGER_HPP_
#define CUKE_STEPMANAGER_HPP_
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <boost/enable_shared_from_this.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
#include "../Table.hpp"
#include "../utils/Regex.hpp"
namespace cucumber {
namespace internal {
typedef unsigned int step_id_type;
class StepInfo;
class SingleStepMatch {
public:
typedef RegexMatch::submatches_type submatches_type;
operator const void *() const;
boost::shared_ptr<const StepInfo> stepInfo;
submatches_type submatches;
};
class MatchResult {
public:
typedef std::vector<SingleStepMatch> match_results_type;
const match_results_type& getResultSet();
void addMatch(SingleStepMatch match);
operator void *();
operator bool() const;
private:
match_results_type resultSet;
};
class InvokeArgs {
typedef std::vector<std::string> args_type;
public:
typedef args_type::size_type size_type;
InvokeArgs() { }
void addArg(const std::string arg);
Table & getVariableTableArg();
template<class T> T getInvokeArg(size_type i) const;
const Table & getTableArg() const;
private:
Table tableArg;
args_type args;
};
enum InvokeResultType {
SUCCESS,
FAILURE,
PENDING
};
class InvokeResult {
private:
InvokeResultType type;
std::string description;
InvokeResult(const InvokeResultType type, const char *description);
public:
InvokeResult();
InvokeResult(const InvokeResult &ir);
InvokeResult& operator= (const InvokeResult& rhs);
static InvokeResult success();
static InvokeResult failure(const char *description);
static InvokeResult failure(const std::string &description);
static InvokeResult pending(const char *description);
bool isSuccess() const;
bool isPending() const;
InvokeResultType getType() const;
const std::string &getDescription() const;
};
class StepInfo : public boost::enable_shared_from_this<StepInfo> {
public:
StepInfo(const std::string &stepMatcher, const std::string source);
SingleStepMatch matches(const std::string &stepDescription) const;
virtual InvokeResult invokeStep(const InvokeArgs * pArgs) const = 0;
step_id_type id;
Regex regex;
const std::string source;
private:
StepInfo& operator=(const StepInfo& other);
};
class BasicStep {
public:
InvokeResult invoke(const InvokeArgs *pArgs);
protected:
typedef const Table table_type;
typedef const Table::hashes_type table_hashes_type;
virtual const InvokeResult invokeStepBody() = 0;
virtual void body() = 0;
void pending(const char *description);
void pending();
template<class T> const T getInvokeArg();
const InvokeArgs *getArgs();
private:
// FIXME: awful hack because of Boost::Test
InvokeResult currentResult;
const InvokeArgs *pArgs;
InvokeArgs::size_type currentArgIndex;
};
template<class T>
class StepInvoker : public StepInfo {
public:
StepInvoker(const std::string &stepMatcher, const std::string source);
InvokeResult invokeStep(const InvokeArgs *args) const;
};
class StepManager {
protected:
typedef std::map<step_id_type, boost::shared_ptr<const StepInfo> > steps_type;
public:
virtual ~StepManager();
void addStep(const boost::shared_ptr<StepInfo>& stepInfo);
MatchResult stepMatches(const std::string &stepDescription) const;
const boost::shared_ptr<const StepInfo>& getStep(step_id_type id);
protected:
steps_type& steps() const;
};
static inline std::string toSourceString(const char *filePath, const int line) {
using namespace std;
stringstream s;
string file(filePath);
string::size_type pos = file.find_last_of("/\\");
if (pos == string::npos) {
s << file;
} else {
s << file.substr(++pos);
}
s << ":" << line;
return s.str();
}
template<class T>
static int registerStep(const std::string &stepMatcher, const char *file, const int line) {
StepManager s;
boost::shared_ptr<StepInfo> stepInfo(boost::make_shared< StepInvoker<T> >(stepMatcher, toSourceString(file, line)));
s.addStep(stepInfo);
return stepInfo->id;
}
template<typename T>
T fromString(const std::string& s) {
std::istringstream stream(s);
T t;
stream >> t;
if (stream.fail()) {
throw std::invalid_argument("Cannot convert parameter");
}
return t;
}
template<>
inline std::string fromString(const std::string& s) {
return s;
}
template<typename T>
std::string toString(T arg) {
std::stringstream s;
s << arg;
return s.str();
}
template<typename T>
T InvokeArgs::getInvokeArg(size_type i) const {
if (i >= args.size()) {
throw std::invalid_argument("Parameter not found");
}
return fromString<T>(args.at(i));
}
template<typename T>
const T BasicStep::getInvokeArg() {
return pArgs->getInvokeArg<T>(currentArgIndex++);
}
template<class T>
StepInvoker<T>::StepInvoker(const std::string &stepMatcher, const std::string source) :
StepInfo(stepMatcher, source) {
}
template<class T>
InvokeResult StepInvoker<T>::invokeStep(const InvokeArgs *pArgs) const {
T t;
return t.invoke(pArgs);
}
}
}
#endif /* CUKE_STEPMANAGER_HPP_ */
| 5,340 | 1,707 |
#pragma once
#include <memory>
#include <string_view>
#include "Runtime/GCNTypes.hpp"
#include "Runtime/World/CActor.hpp"
namespace urde {
class CElementGen;
class CParticleElectric;
class CScriptEffect : public CActor {
static u32 g_NumParticlesUpdating;
static u32 g_NumParticlesRendered;
TLockedToken<CElectricDescription> xe8_electricToken;
std::unique_ptr<CParticleElectric> xf4_electric;
TLockedToken<CGenDescription> xf8_particleSystemToken;
std::unique_ptr<CElementGen> x104_particleSystem;
TUniqueId x108_lightId = kInvalidUniqueId;
CAssetId x10c_partId;
union {
struct {
bool x110_24_enable : 1;
bool x110_25_noTimerUnlessAreaOccluded : 1;
bool x110_26_rebuildSystemsOnActivate : 1;
bool x110_27_useRateInverseCamDist : 1;
bool x110_28_combatVisorVisible : 1;
bool x110_29_thermalVisorVisible : 1;
bool x110_30_xrayVisorVisible : 1;
bool x110_31_anyVisorVisible : 1;
bool x111_24_useRateCamDistRange : 1;
bool x111_25_dieWhenSystemsDone : 1;
bool x111_26_canRender : 1;
};
u32 _dummy = 0;
};
float x114_rateInverseCamDist;
float x118_rateInverseCamDistSq;
float x11c_rateInverseCamDistRate;
float x120_rateCamDistRangeMin;
float x124_rateCamDistRangeMax;
float x128_rateCamDistRangeFarRate;
float x12c_remTime;
float x130_duration;
float x134_durationResetWhileVisible;
std::unique_ptr<CActorLights> x138_actorLights;
TUniqueId x13c_triggerId = kInvalidUniqueId;
float x140_destroyDelayTimer = 0.f;
public:
CScriptEffect(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf,
const zeus::CVector3f& scale, CAssetId partId, CAssetId elscId, bool hotInThermal,
bool noTimerUnlessAreaOccluded, bool rebuildSystemsOnActivate, bool active, bool useRateInverseCamDist,
float rateInverseCamDist, float rateInverseCamDistRate, float duration, float durationResetWhileVisible,
bool useRateCamDistRange, float rateCamDistRangeMin, float rateCamDistRangeMax,
float rateCamDistRangeFarRate, bool combatVisorVisible, bool thermalVisorVisible, bool xrayVisorVisible,
const CLightParameters& lParms, bool dieWhenSystemsDone);
void Accept(IVisitor& visitor) override;
void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override;
void PreRender(CStateManager&, const zeus::CFrustum&) override;
void AddToRenderer(const zeus::CFrustum&, const CStateManager&) const override;
void Render(const CStateManager&) const override;
void Think(float, CStateManager&) override;
bool CanRenderUnsorted(const CStateManager&) const override { return false; }
void SetActive(bool active) override {
CActor::SetActive(active);
xe7_29_drawEnabled = true;
}
void CalculateRenderBounds() override;
zeus::CAABox GetSortingBounds(const CStateManager&) const override;
bool AreBothSystemsDeleteable() const;
static void ResetParticleCounts() {
g_NumParticlesUpdating = 0;
g_NumParticlesRendered = 0;
}
};
} // namespace urde
| 3,123 | 1,123 |
// RUN: %clang_cc1 -fsyntax-only -verify %s
// C++ [dcl.ref]p5:
// There shall be no references to references, no arrays of
// references, and no pointers to references.
// The crazy formatting in here is to enforce the exact report locations.
typedef int &intref;
typedef intref &intrefref;
template <class T> class RefMem { // expected-warning{{class 'RefMem<int &>' does not declare any constructor to initialize its non-modifiable members}}
T
&
member; // expected-note{{reference member 'member' will never be initialized}}
};
struct RefRef {
int
&
& // expected-error {{declared as a reference to a reference}}
refref0;
intref
&
refref1; // collapses
intrefref
&
refref2; // collapses
RefMem
<
int
&
>
refref3; // collapses expected-note{{in instantiation of template class 'RefMem<int &>' requested here}}
};
template <class T> class PtrMem {
T
* // expected-error {{declared as a pointer to a reference}}
member;
};
struct RefPtr {
typedef
int
&
* // expected-error {{declared as a pointer to a reference}}
intrefptr;
typedef
intref
* // expected-error {{declared as a pointer to a reference}}
intrefptr2;
int
&
* // expected-error {{declared as a pointer to a reference}}
refptr0;
intref
* // expected-error {{declared as a pointer to a reference}}
refptr1;
PtrMem
<
int
&
>
refptr2; // expected-note {{in instantiation}}
};
template <class T> class ArrMem {
T
member
[ // expected-error {{declared as array of references}}
10
];
};
template <class T, unsigned N> class DepArrMem {
T
member
[ // expected-error {{declared as array of references}}
N
];
};
struct RefArr {
typedef
int
&
intrefarr
[ // expected-error {{declared as array of references}}
2
];
typedef
intref
intrefarr
[ // expected-error {{declared as array of references}}
2
];
int
&
refarr0
[ // expected-error {{declared as array of references}}
2
];
intref
refarr1
[ // expected-error {{declared as array of references}}
2
];
ArrMem
<
int
&
>
refarr2; // expected-note {{in instantiation}}
DepArrMem
<
int
&,
10
>
refarr3; // expected-note {{in instantiation}}
};
// The declaration of a reference shall contain an initializer
// (8.5.3) except when the declaration contains an explicit extern
// specifier (7.1.1), is a class member (9.2) declaration within a
// class definition, or is the declaration of a parameter or a
// return type (8.3.5); see 3.1. A reference shall be initialized to
// refer to a valid object or function. [ Note: in particular, a
// null reference cannot exist in a well-defined program, because
// the only way to create such a reference would be to bind it to
// the "object" obtained by dereferencing a null pointer, which
// causes undefined behavior. As described in 9.6, a reference
// cannot be bound directly to a bit-field.
| 3,828 | 1,005 |
#include "./utility/rt.h"
#include <math.h>
int N;
int M;
#define A_OFFSET 0
#define R_OFFSET N * M
#define Q_OFFSET N * M + N * N
void gramschmidt_trace(double* A, double* R, double* Q) {
int k, i, j;
double nrm;
vector<int> idx;
for (k = 0; k < N; k++) {
nrm = 0.0;
for (i = 0; i < M; i++) {
idx.clear(); idx.push_back(k); idx.push_back(i);
nrm += A[i * N + k] * A[i * N + k];
rtTmpAccess(A_OFFSET + i * N + k, 0, 0, idx);
rtTmpAccess(A_OFFSET + i * N + k, 1, 0, idx);
}
idx.clear(); idx.push_back(k);
R[k * N + k] = sqrt(nrm);
rtTmpAccess(R_OFFSET + k * N + k, 2, 1, idx);
for (i = 0; i < M; i++) {
idx.clear(); idx.push_back(k); idx.push_back(i);
Q[i * N + k] = A[i * N + k] / R[k * N + k];
rtTmpAccess(A_OFFSET + i * N + k, 3, 0, idx);
rtTmpAccess(R_OFFSET + k * N + k, 4, 1, idx);
rtTmpAccess(Q_OFFSET + i * N + k, 5, 2, idx);
}
for (j = k + 1; j < N; j++) {
idx.clear(); idx.push_back(k); idx.push_back(j);
R[k * N + j] = 0.0;
rtTmpAccess(R_OFFSET + k * N + j, 6, 1, idx);
for (i = 0; i < M; i++) {
idx.clear(); idx.push_back(k); idx.push_back(j); idx.push_back(i);
R[k * N + j] += Q[i * N + k] * A[i * N + j];
rtTmpAccess(Q_OFFSET + i * N + k, 7, 2, idx);
rtTmpAccess(A_OFFSET + i * N + j, 8, 0, idx);
rtTmpAccess(R_OFFSET + k * N + j, 9, 1, idx);
rtTmpAccess(R_OFFSET + k * N + j, 10, 1, idx);
}
for (i = 0; i < M; i++) {
idx.clear(); idx.push_back(k); idx.push_back(j); idx.push_back(i);
A[i * N + j] = A[i * N + j] - Q[i * N + k] * R[k * N + j];
rtTmpAccess(A_OFFSET + i * N + j, 11, 0, idx);
rtTmpAccess(Q_OFFSET + i * N + k, 12, 2, idx);
rtTmpAccess(R_OFFSET + k * N + j, 13, 1, idx);
rtTmpAccess(A_OFFSET + i * N + j, 14, 0, idx);
}
}
}
}
int main(int argc, char* argv[]) {
if (argc != 3) {
cout << "This benchmark needs 2 loop bounds" << endl;
return 0;
}
for (int i = 1; i < argc; i++) {
if (!isdigit(argv[i][0])) {
cout << "arguments must be integer" << endl;
return 0;
}
}
M = stoi(argv[1]);
N = stoi(argv[2]);
double * A = (double *)malloc(N * M * sizeof(double));
double * R = (double *)malloc(N * N * sizeof(double));
double * Q = (double *)malloc(M * N * sizeof(double));
gramschmidt_trace(A, R, Q);
dumpRIHistogram();
return 0;
}
| 2,468 | 1,210 |
#pragma once
#include "chain_conversions.hpp"
#include "check.hpp"
#include "operators.hpp"
#include "reflection.hpp"
#include "from_json.hpp"
#include <stdint.h>
#include <string>
namespace eosio {
/**
* @defgroup time
* @ingroup core
* @brief Classes for working with time.
*/
class microseconds {
public:
microseconds() = default;
explicit microseconds(int64_t c) : _count(c) {}
/// @cond INTERNAL
static microseconds maximum() { return microseconds(0x7fffffffffffffffll); }
friend microseconds operator+(const microseconds& l, const microseconds& r) {
return microseconds(l._count + r._count);
}
friend microseconds operator-(const microseconds& l, const microseconds& r) {
return microseconds(l._count - r._count);
}
microseconds& operator+=(const microseconds& c) {
_count += c._count;
return *this;
}
microseconds& operator-=(const microseconds& c) {
_count -= c._count;
return *this;
}
int64_t count() const { return _count; }
int64_t to_seconds() const { return _count / 1000000; }
int64_t _count = 0;
/// @endcond
};
EOSIO_REFLECT(microseconds, _count);
EOSIO_COMPARE(microseconds);
inline microseconds seconds(int64_t s) { return microseconds(s * 1000000); }
inline microseconds milliseconds(int64_t s) { return microseconds(s * 1000); }
inline microseconds minutes(int64_t m) { return seconds(60 * m); }
inline microseconds hours(int64_t h) { return minutes(60 * h); }
inline microseconds days(int64_t d) { return hours(24 * d); }
/**
* High resolution time point in microseconds
*
* @ingroup time
*/
class time_point {
public:
time_point() = default;
explicit time_point(microseconds e) : elapsed(e) {}
const microseconds& time_since_epoch() const { return elapsed; }
uint32_t sec_since_epoch() const { return uint32_t(elapsed.count() / 1000000); }
static time_point max() { return time_point( microseconds::maximum() ); }
/// @cond INTERNAL
time_point& operator+=(const microseconds& m) {
elapsed += m;
return *this;
}
time_point& operator-=(const microseconds& m) {
elapsed -= m;
return *this;
}
time_point operator+(const microseconds& m) const { return time_point(elapsed + m); }
time_point operator+(const time_point& m) const { return time_point(elapsed + m.elapsed); }
time_point operator-(const microseconds& m) const { return time_point(elapsed - m); }
microseconds operator-(const time_point& m) const { return microseconds(elapsed.count() - m.elapsed.count()); }
microseconds elapsed;
/// @endcond
};
EOSIO_REFLECT(time_point, elapsed);
EOSIO_COMPARE(time_point);
template <typename S>
void from_json(time_point& obj, S& stream) {
auto s = stream.get_string();
uint64_t utc_microseconds;
if (!eosio::string_to_utc_microseconds(utc_microseconds, s.data(), s.data() + s.size())) {
check(false, convert_json_error(eosio::from_json_error::expected_time_point));
}
obj = time_point(microseconds(utc_microseconds));
}
template <typename S>
void to_json(const time_point& obj, S& stream) {
return to_json(eosio::microseconds_to_str(obj.elapsed._count), stream);
}
/**
* A lower resolution time_point accurate only to seconds from 1970
*
* @ingroup time
*/
class time_point_sec {
public:
time_point_sec() : utc_seconds(0) {}
explicit time_point_sec(uint32_t seconds) : utc_seconds(seconds) {}
time_point_sec(const time_point& t) : utc_seconds(uint32_t(t.time_since_epoch().count() / 1000000ll)) {}
static time_point_sec maximum() { return time_point_sec(0xffffffff); }
static time_point_sec min() { return time_point_sec(0); }
operator time_point() const { return time_point(eosio::seconds(utc_seconds)); }
uint32_t sec_since_epoch() const { return utc_seconds; }
/// @cond INTERNAL
time_point_sec operator=(const eosio::time_point& t) {
utc_seconds = uint32_t(t.time_since_epoch().count() / 1000000ll);
return *this;
}
time_point_sec& operator+=(uint32_t m) {
utc_seconds += m;
return *this;
}
time_point_sec& operator+=(microseconds m) {
utc_seconds += m.to_seconds();
return *this;
}
time_point_sec& operator+=(time_point_sec m) {
utc_seconds += m.utc_seconds;
return *this;
}
time_point_sec& operator-=(uint32_t m) {
utc_seconds -= m;
return *this;
}
time_point_sec& operator-=(microseconds m) {
utc_seconds -= m.to_seconds();
return *this;
}
time_point_sec& operator-=(time_point_sec m) {
utc_seconds -= m.utc_seconds;
return *this;
}
time_point_sec operator+(uint32_t offset) const { return time_point_sec(utc_seconds + offset); }
time_point_sec operator-(uint32_t offset) const { return time_point_sec(utc_seconds - offset); }
friend time_point operator+(const time_point_sec& t, const microseconds& m) { return time_point(t) + m; }
friend time_point operator-(const time_point_sec& t, const microseconds& m) { return time_point(t) - m; }
friend microseconds operator-(const time_point_sec& t, const time_point_sec& m) {
return time_point(t) - time_point(m);
}
friend microseconds operator-(const time_point& t, const time_point_sec& m) { return time_point(t) - time_point(m); }
uint32_t utc_seconds;
/// @endcond
};
EOSIO_REFLECT(time_point_sec, utc_seconds);
EOSIO_COMPARE(time_point);
template <typename S>
void from_json(time_point_sec& obj, S& stream) {
auto s = stream.get_string();
const char* p = s.data();
if (!eosio::string_to_utc_seconds(obj.utc_seconds, p, s.data() + s.size(), true, true)) {
check(false, convert_json_error(from_json_error::expected_time_point));
}
}
template <typename S>
void to_json(const time_point_sec& obj, S& stream) {
return to_json(eosio::microseconds_to_str(uint64_t(obj.utc_seconds) * 1'000'000), stream);
}
/**
* This class is used in the block headers to represent the block time
* It is a parameterised class that takes an Epoch in milliseconds and
* and an interval in milliseconds and computes the number of slots.
*
* @ingroup time
**/
class block_timestamp {
public:
block_timestamp() = default;
explicit block_timestamp(uint32_t s) : slot(s) {}
block_timestamp(const time_point& t) { set_time_point(t); }
block_timestamp(const time_point_sec& t) { set_time_point(t); }
static block_timestamp maximum() { return block_timestamp(0xffff); }
static block_timestamp min() { return block_timestamp(0); }
block_timestamp next() const {
eosio::check(std::numeric_limits<uint32_t>::max() - slot >= 1, "block timestamp overflow");
auto result = block_timestamp(*this);
result.slot += 1;
return result;
}
time_point to_time_point() const { return (time_point)(*this); }
operator time_point() const {
int64_t msec = slot * (int64_t)block_interval_ms;
msec += block_timestamp_epoch;
return time_point(milliseconds(msec));
}
/// @cond INTERNAL
void operator=(const time_point& t) { set_time_point(t); }
bool operator>(const block_timestamp& t) const { return slot > t.slot; }
bool operator>=(const block_timestamp& t) const { return slot >= t.slot; }
bool operator<(const block_timestamp& t) const { return slot < t.slot; }
bool operator<=(const block_timestamp& t) const { return slot <= t.slot; }
bool operator==(const block_timestamp& t) const { return slot == t.slot; }
bool operator!=(const block_timestamp& t) const { return slot != t.slot; }
uint32_t slot = 0;
static constexpr int32_t block_interval_ms = 500;
static constexpr int64_t block_timestamp_epoch = 946684800000ll; // epoch is year 2000
/// @endcond
private:
void set_time_point(const time_point& t) {
int64_t micro_since_epoch = t.time_since_epoch().count();
int64_t msec_since_epoch = micro_since_epoch / 1000;
slot = uint32_t((msec_since_epoch - block_timestamp_epoch) / int64_t(block_interval_ms));
}
void set_time_point(const time_point_sec& t) {
int64_t sec_since_epoch = t.sec_since_epoch();
slot = uint32_t((sec_since_epoch * 1000 - block_timestamp_epoch) / block_interval_ms);
}
}; // block_timestamp
/**
* @ingroup time
*/
typedef block_timestamp block_timestamp_type;
EOSIO_REFLECT(block_timestamp_type, slot);
template <typename S>
void from_json(block_timestamp& obj, S& stream) {
time_point tp;
from_json(tp, stream);
obj = block_timestamp(tp);
}
template <typename S>
void to_json(const block_timestamp& obj, S& stream) {
return to_json(time_point(obj), stream);
}
} // namespace eosio
| 8,958 | 3,118 |
#include "urlify_in_place.h"
using urlify_in_place::buffer_t;
namespace {
struct Lengths {
size_t current;
size_t urlficated;
};
Lengths compute_lengths(const buffer_t *p_buffer) {
Lengths lengths = {0, 0};
for (size_t i = 0; p_buffer->at(i) != '\0'; i++) {
lengths.current++;
lengths.urlficated += p_buffer->at(i) == ' ' ? 3 : 1;
}
return lengths;
}
void urlify_knowing_lengths(buffer_t *p_buffer, Lengths lengths) {
auto destination = lengths.urlficated;
auto source = lengths.current;
while (destination != source) {
auto character = p_buffer->at(source--);
if (character != ' ') {
p_buffer->at(destination--) = character;
} else {
p_buffer->at(destination--) = '0';
p_buffer->at(destination--) = '2';
p_buffer->at(destination--) = '%';
}
}
}
} // namespace
void urlify_in_place::urlify(buffer_t *p_buffer) {
urlify_knowing_lengths(p_buffer, compute_lengths(p_buffer));
}
| 950 | 358 |
/* NAME:
TThreadPool.cpp
DESCRIPTION:
NThreadPool tests.
COPYRIGHT:
Copyright (c) 2006-2021, refNum Software
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
___________________________________________________________________________
*/
//=============================================================================
// Includes
//-----------------------------------------------------------------------------
// Nano
#include "NTestFixture.h"
#include "NThreadPool.h"
#include "NThreadTask.h"
//=============================================================================
// Fixture
//-----------------------------------------------------------------------------
NANO_FIXTURE(TThreadPool)
{
std::unique_ptr<NThreadPool> thePool;
SETUP
{
thePool = std::make_unique<NThreadPool>("TThreadPool");
}
};
//=============================================================================
// Test Case
//-----------------------------------------------------------------------------
NANO_TEST(TThreadPool, "Default")
{
// Perform the test
REQUIRE(thePool->GetThreads() == 0);
REQUIRE(thePool->GetMinThreads() == 1);
REQUIRE(thePool->GetMaxThreads() != 0);
}
//=============================================================================
// Test Case
//-----------------------------------------------------------------------------
NANO_TEST(TThreadPool, "IsPaused")
{
// Perform the test
REQUIRE(!thePool->IsPaused());
thePool->Pause();
REQUIRE(thePool->IsPaused());
}
//=============================================================================
// Test Case
//-----------------------------------------------------------------------------
NANO_TEST(TThreadPool, "PauseResume")
{
// Perform the test
REQUIRE(!thePool->IsPaused());
thePool->Pause();
REQUIRE(thePool->IsPaused());
thePool->Resume();
REQUIRE(!thePool->IsPaused());
}
//=============================================================================
// Test Case
//-----------------------------------------------------------------------------
NANO_TEST(TThreadPool, "AddFunction")
{
// Perform the test
NSemaphore theSemaphore;
thePool->Add(
[&]()
{
theSemaphore.Signal();
});
REQUIRE(theSemaphore.Wait());
}
//=============================================================================
// Test Case
//-----------------------------------------------------------------------------
NANO_TEST(TThreadPool, "AddTask")
{
// Perform the test
NSemaphore theSemaphore;
auto theTask = std::make_shared<NThreadTask>(
[&]()
{
theSemaphore.Signal();
});
thePool->Add(theTask);
REQUIRE(theSemaphore.Wait());
}
//=============================================================================
// Test Case
//-----------------------------------------------------------------------------
NANO_TEST(TThreadPool, "GetMain")
{
// Perform the test
NThreadPool* mainPool = NThreadPool::GetMain();
REQUIRE(mainPool != nullptr);
REQUIRE(mainPool != thePool.get());
}
| 4,470 | 1,413 |
/*
* Copyright (c) CERN 2016
*
* 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 <boost/test/unit_test_suite.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/filesystem.hpp>
#include <boost/function.hpp>
#include <glib.h>
#include "msg-bus/consumer.h"
#include "msg-bus/producer.h"
using namespace fts3::events;
namespace boost {
bool operator==(const google::protobuf::Message &a, const google::protobuf::Message &b)
{
return a.SerializeAsString() == b.SerializeAsString();
}
}
namespace std {
std::ostream &operator<<(std::ostream &os, const google::protobuf::Message &msg)
{
os << msg.DebugString();
return os;
}
}
BOOST_AUTO_TEST_SUITE(MsgBusTest)
class MsgBusFixture {
protected:
static const std::string TEST_PATH;
public:
MsgBusFixture() {
boost::filesystem::create_directories(TEST_PATH);
}
~MsgBusFixture() {
boost::filesystem::remove_all(TEST_PATH);
}
};
const std::string MsgBusFixture::TEST_PATH("/tmp/MsgBusTest");
template <typename MSG_CONTAINER>
static void expectZeroMessages(boost::function<int (Consumer*, MSG_CONTAINER&)> func, Consumer &consumer)
{
MSG_CONTAINER container;
BOOST_CHECK_EQUAL(0, func(&consumer, container));
BOOST_CHECK_EQUAL(0, container.size());
}
BOOST_FIXTURE_TEST_CASE (simpleStatus, MsgBusFixture)
{
Producer producer(TEST_PATH);
Consumer consumer(TEST_PATH);
Message original;
original.set_job_id("1906cc40-b915-11e5-9a03-02163e006dd0");
original.set_transfer_status("FAILED");
original.set_transfer_message("TEST FAILURE, EVERYTHING IS TERRIBLE");
original.set_source_se("mock://source/file");
original.set_dest_se("mock://source/file2");
original.set_file_id(42);
original.set_process_id(1234);
original.set_time_in_secs(55);
original.set_filesize(1023);
original.set_nostreams(33);
original.set_timeout(22);
original.set_buffersize(1);
original.set_retry(5);
original.set_retry(0.2);
original.set_timestamp(15689);
original.set_throughput(0.88);
BOOST_CHECK_EQUAL(0, producer.runProducerStatus(original));
// Make sure the messages don't get messed up
expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerDeletions, consumer);
expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerStaging, consumer);
expectZeroMessages<std::map<int, MessageLog>>(&Consumer::runConsumerLog, consumer);
expectZeroMessages<std::vector<std::string>>(&Consumer::runConsumerMonitoring, consumer);
expectZeroMessages<std::vector<MessageUpdater>>(&Consumer::runConsumerStall, consumer);
// First attempt must return the single message
std::vector<Message> statuses;
BOOST_CHECK_EQUAL(0, consumer.runConsumerStatus(statuses));
BOOST_CHECK_EQUAL(1, statuses.size());
BOOST_CHECK_EQUAL(statuses[0], original);
// Second attempt must return empty (already consumed)
statuses.clear();
BOOST_CHECK_EQUAL(0, consumer.runConsumerStatus(statuses));
BOOST_CHECK_EQUAL(0, statuses.size());
}
BOOST_FIXTURE_TEST_CASE (simpleMonitoring, MsgBusFixture)
{
Producer producer(TEST_PATH);
Consumer consumer(TEST_PATH);
std::string original = "blah bleh blih bloh cluh";
BOOST_CHECK_EQUAL(0, producer.runProducerMonitoring(original));
// Make sure the messages don't get messed up
expectZeroMessages<std::vector<Message>>(&Consumer::runConsumerStatus, consumer);
expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerDeletions, consumer);
expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerStaging, consumer);
expectZeroMessages<std::map<int, MessageLog>>(&Consumer::runConsumerLog, consumer);
expectZeroMessages<std::vector<MessageUpdater>>(&Consumer::runConsumerStall, consumer);
// First attempt must return the single message
std::vector<std::string> monitoring;
BOOST_CHECK_EQUAL(0, consumer.runConsumerMonitoring(monitoring));
BOOST_CHECK_EQUAL(1, monitoring.size());
BOOST_CHECK_EQUAL(monitoring[0], original);
// Second attempt must return empty (already consumed)
monitoring.clear();
BOOST_CHECK_EQUAL(0, consumer.runConsumerMonitoring(monitoring));
BOOST_CHECK_EQUAL(0, monitoring.size());
}
BOOST_FIXTURE_TEST_CASE (simpleLog, MsgBusFixture)
{
Producer producer(TEST_PATH);
Consumer consumer(TEST_PATH);
MessageLog original;
original.set_job_id("1906cc40-b915-11e5-9a03-02163e006dd0");
original.set_file_id(44);
original.set_host("abc.cern.ch");
original.set_log_path("/var/log/fts3/transfers/log.log");
original.set_has_debug_file(true);
original.set_timestamp(time(NULL));
BOOST_CHECK_EQUAL(0, producer.runProducerLog(original));
// Make sure the messages don't get messed up
expectZeroMessages<std::vector<Message>>(&Consumer::runConsumerStatus, consumer);
expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerDeletions, consumer);
expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerStaging, consumer);
expectZeroMessages<std::vector<std::string>>(&Consumer::runConsumerMonitoring, consumer);
expectZeroMessages<std::vector<MessageUpdater>>(&Consumer::runConsumerStall, consumer);
// First attempt must return the single message
std::map<int, MessageLog> logs;
BOOST_CHECK_EQUAL(0, consumer.runConsumerLog(logs));
BOOST_CHECK_EQUAL(1, logs.size());
BOOST_CHECK_NO_THROW(logs.at(original.file_id()));
BOOST_CHECK_EQUAL(logs.at(original.file_id()), original);
// Second attempt must return empty (already consumed)
logs.clear();
BOOST_CHECK_EQUAL(0, consumer.runConsumerLog(logs));
BOOST_CHECK_EQUAL(0, logs.size());
}
BOOST_FIXTURE_TEST_CASE (simpleDeletion, MsgBusFixture)
{
Producer producer(TEST_PATH);
Consumer consumer(TEST_PATH);
MessageBringonline original;
original.set_job_id("1906cc40-b915-11e5-9a03-02163e006dd0");
original.set_file_id(44);
original.set_transfer_status("FAILED");
original.set_transfer_message("Could not open because of reasons");
BOOST_CHECK_EQUAL(0, producer.runProducerDeletions(original));
// Make sure the messages don't get messed up
expectZeroMessages<std::vector<Message>>(&Consumer::runConsumerStatus, consumer);
expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerStaging, consumer);
expectZeroMessages<std::map<int, MessageLog>>(&Consumer::runConsumerLog, consumer);
expectZeroMessages<std::vector<std::string>>(&Consumer::runConsumerMonitoring, consumer);
expectZeroMessages<std::vector<MessageUpdater>>(&Consumer::runConsumerStall, consumer);
// First attempt must return the single message
std::vector<MessageBringonline> statuses;
BOOST_CHECK_EQUAL(0, consumer.runConsumerDeletions(statuses));
BOOST_CHECK_EQUAL(1, statuses.size());
BOOST_CHECK_EQUAL(statuses[0], original);
// Second attempt must return empty (already consumed)
statuses.clear();
BOOST_CHECK_EQUAL(0, consumer.runConsumerDeletions(statuses));
BOOST_CHECK_EQUAL(0, statuses.size());
}
BOOST_FIXTURE_TEST_CASE (simpleStaging, MsgBusFixture)
{
Producer producer(TEST_PATH);
Consumer consumer(TEST_PATH);
MessageBringonline original;
original.set_job_id("1906cc40-b915-11e5-9a03-02163e006dd0");
original.set_file_id(44);
original.set_transfer_status("FAILED");
original.set_transfer_message("Could not open because of reasons");
BOOST_CHECK_EQUAL(0, producer.runProducerStaging(original));
// Make sure the messages don't get messed up
expectZeroMessages<std::vector<Message>>(&Consumer::runConsumerStatus, consumer);
expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerDeletions, consumer);
expectZeroMessages<std::map<int, MessageLog>>(&Consumer::runConsumerLog, consumer);
expectZeroMessages<std::vector<std::string>>(&Consumer::runConsumerMonitoring, consumer);
expectZeroMessages<std::vector<MessageUpdater>>(&Consumer::runConsumerStall, consumer);
// First attempt must return the single message
std::vector<MessageBringonline> statuses;
BOOST_CHECK_EQUAL(0, consumer.runConsumerStaging(statuses));
BOOST_CHECK_EQUAL(1, statuses.size());
BOOST_CHECK_EQUAL(statuses[0], original);
// Second attempt must return empty (already consumed)
statuses.clear();
BOOST_CHECK_EQUAL(0, consumer.runConsumerStaging(statuses));
BOOST_CHECK_EQUAL(0, statuses.size());
}
BOOST_AUTO_TEST_SUITE_END()
| 9,171 | 3,159 |
//
// mass.hpp
// krypton
//
// Created by Jack Zou on 2018/4/7.
// Copyright © 2018年 jack.zou. All rights reserved.
//
#ifndef mass_h
#define mass_h
#include "core/common.hpp"
#include "core/quantity.hpp"
BEGIN_KR_NAMESPACE
template<class T> using microgram = quantity<T, mass, std::micro>;
template<class T> using gram = quantity<T, mass>;
template<class T> using kilogram = quantity<T, mass, std::kilo>;
template<class T> using ton = quantity<T, mass, std::mega>;
END_KR_NAMESPACE
#endif /* mass_h */
| 517 | 212 |
/*
* ButtonControl.cpp
* Created: 31.03.2021 20:42:49
* Author: Markus Scheich
*/
#include "ButtonControl.h"
#include <string.h>
template <int StringLength>
ButtonControl<StringLength>::ButtonControl(unsigned char locX, unsigned char locY, unsigned char width, unsigned char height, const char* buttonText, void* controlContext, void(*onClick)(void* controlContext)) : UIElement(locX, locY, UI_CONTROL)
{
Width = width;
Height = height;
strncpy(_buttonText, buttonText, StringLength); // Copy a maximum number of StringLength characters to the _buttonText buffer. If text is shorter, the array is zero padded.
_buttonText[StringLength - 1] = '\0'; // The _buttonText buffer must contain at least one termination character ('\0') at the end to protect from overflow.
_controlContext = controlContext;
_onClick = onClick;
}
template <int StringLength>
void ButtonControl<StringLength>::Draw(u8g_t *u8g, bool isFirstPage)
{
if (Visible)
{
u8g_DrawHLine(u8g, LocX - 1, LocY - 1, 3); // Upper left corner
u8g_DrawVLine(u8g, LocX - 1, LocY - 1, 3);
u8g_DrawHLine(u8g, LocX + Width - 2, LocY - 1, 3); // Upper right corner
u8g_DrawVLine(u8g, LocX + Width, LocY - 1, 3);
u8g_DrawHLine(u8g, LocX - 1, LocY + Height, 3); // Lower left corner
u8g_DrawVLine(u8g, LocX - 1, LocY + Height - 2, 3);
u8g_DrawHLine(u8g, LocX + Width - 2, LocY + Height, 3); // Lower right corner
u8g_DrawVLine(u8g, LocX + Width, LocY + Height - 2, 3);
u8g_DrawStr(u8g, LocX, LocY, _buttonText);
}
}
template <int StringLength>
bool ButtonControl<StringLength>::KeyInput(Keys_t key)
{
switch (key)
{
case KEYOK:
if (_onClick != NULL) { _onClick(_controlContext); return true; }
else { return false; }
default:
return false;
}
} | 1,760 | 700 |
/* Copyright (c) 2008-2013, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
#include <avian/machine.h>
#include "debug-util.h"
namespace avian {
namespace jvm {
namespace debug {
uint16_t read16(uint8_t* code, unsigned& ip)
{
uint16_t a = code[ip++];
uint16_t b = code[ip++];
return (a << 8) | b;
}
uint32_t read32(uint8_t* code, unsigned& ip)
{
uint32_t b = code[ip++];
uint32_t a = code[ip++];
uint32_t c = code[ip++];
uint32_t d = code[ip++];
return (a << 24) | (b << 16) | (c << 8) | d;
}
using namespace vm;
int printInstruction(uint8_t* code, unsigned& ip, const char* prefix)
{
unsigned startIp = ip;
uint8_t instr = code[ip++];
switch (instr) {
case aaload:
return fprintf(stderr, "aaload");
case aastore:
return fprintf(stderr, "aastore");
case aconst_null:
return fprintf(stderr, "aconst_null");
case aload:
return fprintf(stderr, "aload %2d", code[ip++]);
case aload_0:
return fprintf(stderr, "aload_0");
case aload_1:
return fprintf(stderr, "aload_1");
case aload_2:
return fprintf(stderr, "aload_2");
case aload_3:
return fprintf(stderr, "aload_3");
case anewarray:
return fprintf(stderr, "anewarray %4d", read16(code, ip));
case areturn:
return fprintf(stderr, "areturn");
case arraylength:
return fprintf(stderr, "arraylength");
case astore:
return fprintf(stderr, "astore %2d", code[ip++]);
case astore_0:
return fprintf(stderr, "astore_0");
case astore_1:
return fprintf(stderr, "astore_1");
case astore_2:
return fprintf(stderr, "astore_2");
case astore_3:
return fprintf(stderr, "astore_3");
case athrow:
return fprintf(stderr, "athrow");
case baload:
return fprintf(stderr, "baload");
case bastore:
return fprintf(stderr, "bastore");
case bipush:
return fprintf(stderr, "bipush %2d", code[ip++]);
case caload:
return fprintf(stderr, "caload");
case castore:
return fprintf(stderr, "castore");
case checkcast:
return fprintf(stderr, "checkcast %4d", read16(code, ip));
case d2f:
return fprintf(stderr, "d2f");
case d2i:
return fprintf(stderr, "d2i");
case d2l:
return fprintf(stderr, "d2l");
case dadd:
return fprintf(stderr, "dadd");
case daload:
return fprintf(stderr, "daload");
case dastore:
return fprintf(stderr, "dastore");
case dcmpg:
return fprintf(stderr, "dcmpg");
case dcmpl:
return fprintf(stderr, "dcmpl");
case dconst_0:
return fprintf(stderr, "dconst_0");
case dconst_1:
return fprintf(stderr, "dconst_1");
case ddiv:
return fprintf(stderr, "ddiv");
case dmul:
return fprintf(stderr, "dmul");
case dneg:
return fprintf(stderr, "dneg");
case vm::drem:
return fprintf(stderr, "drem");
case dsub:
return fprintf(stderr, "dsub");
case dup:
return fprintf(stderr, "dup");
case dup_x1:
return fprintf(stderr, "dup_x1");
case dup_x2:
return fprintf(stderr, "dup_x2");
case dup2:
return fprintf(stderr, "dup2");
case dup2_x1:
return fprintf(stderr, "dup2_x1");
case dup2_x2:
return fprintf(stderr, "dup2_x2");
case f2d:
return fprintf(stderr, "f2d");
case f2i:
return fprintf(stderr, "f2i");
case f2l:
return fprintf(stderr, "f2l");
case fadd:
return fprintf(stderr, "fadd");
case faload:
return fprintf(stderr, "faload");
case fastore:
return fprintf(stderr, "fastore");
case fcmpg:
return fprintf(stderr, "fcmpg");
case fcmpl:
return fprintf(stderr, "fcmpl");
case fconst_0:
return fprintf(stderr, "fconst_0");
case fconst_1:
return fprintf(stderr, "fconst_1");
case fconst_2:
return fprintf(stderr, "fconst_2");
case fdiv:
return fprintf(stderr, "fdiv");
case fmul:
return fprintf(stderr, "fmul");
case fneg:
return fprintf(stderr, "fneg");
case frem:
return fprintf(stderr, "frem");
case fsub:
return fprintf(stderr, "fsub");
case getfield:
return fprintf(stderr, "getfield %4d", read16(code, ip));
case getstatic:
return fprintf(stderr, "getstatic %4d", read16(code, ip));
case goto_: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "goto %4d", offset + ip - 3);
}
case goto_w: {
int32_t offset = read32(code, ip);
return fprintf(stderr, "goto_w %08x", offset + ip - 5);
}
case i2b:
return fprintf(stderr, "i2b");
case i2c:
return fprintf(stderr, "i2c");
case i2d:
return fprintf(stderr, "i2d");
case i2f:
return fprintf(stderr, "i2f");
case i2l:
return fprintf(stderr, "i2l");
case i2s:
return fprintf(stderr, "i2s");
case iadd:
return fprintf(stderr, "iadd");
case iaload:
return fprintf(stderr, "iaload");
case iand:
return fprintf(stderr, "iand");
case iastore:
return fprintf(stderr, "iastore");
case iconst_m1:
return fprintf(stderr, "iconst_m1");
case iconst_0:
return fprintf(stderr, "iconst_0");
case iconst_1:
return fprintf(stderr, "iconst_1");
case iconst_2:
return fprintf(stderr, "iconst_2");
case iconst_3:
return fprintf(stderr, "iconst_3");
case iconst_4:
return fprintf(stderr, "iconst_4");
case iconst_5:
return fprintf(stderr, "iconst_5");
case idiv:
return fprintf(stderr, "idiv");
case if_acmpeq: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "if_acmpeq %4d", offset + ip - 3);
}
case if_acmpne: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "if_acmpne %4d", offset + ip - 3);
}
case if_icmpeq: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "if_icmpeq %4d", offset + ip - 3);
}
case if_icmpne: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "if_icmpne %4d", offset + ip - 3);
}
case if_icmpgt: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "if_icmpgt %4d", offset + ip - 3);
}
case if_icmpge: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "if_icmpge %4d", offset + ip - 3);
}
case if_icmplt: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "if_icmplt %4d", offset + ip - 3);
}
case if_icmple: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "if_icmple %4d", offset + ip - 3);
}
case ifeq: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "ifeq %4d", offset + ip - 3);
}
case ifne: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "ifne %4d", offset + ip - 3);
}
case ifgt: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "ifgt %4d", offset + ip - 3);
}
case ifge: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "ifge %4d", offset + ip - 3);
}
case iflt: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "iflt %4d", offset + ip - 3);
}
case ifle: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "ifle %4d", offset + ip - 3);
}
case ifnonnull: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "ifnonnull %4d", offset + ip - 3);
}
case ifnull: {
int16_t offset = read16(code, ip);
return fprintf(stderr, "ifnull %4d", offset + ip - 3);
}
case iinc: {
uint8_t a = code[ip++];
uint8_t b = code[ip++];
return fprintf(stderr, "iinc %2d %2d", a, b);
}
case iload:
return fprintf(stderr, "iload %2d", code[ip++]);
case fload:
return fprintf(stderr, "fload %2d", code[ip++]);
case iload_0:
return fprintf(stderr, "iload_0");
case fload_0:
return fprintf(stderr, "fload_0");
case iload_1:
return fprintf(stderr, "iload_1");
case fload_1:
return fprintf(stderr, "fload_1");
case iload_2:
return fprintf(stderr, "iload_2");
case fload_2:
return fprintf(stderr, "fload_2");
case iload_3:
return fprintf(stderr, "iload_3");
case fload_3:
return fprintf(stderr, "fload_3");
case imul:
return fprintf(stderr, "imul");
case ineg:
return fprintf(stderr, "ineg");
case instanceof:
return fprintf(stderr, "instanceof %4d", read16(code, ip));
case invokeinterface:
return fprintf(stderr, "invokeinterface %4d", read16(code, ip));
case invokespecial:
return fprintf(stderr, "invokespecial %4d", read16(code, ip));
case invokestatic:
return fprintf(stderr, "invokestatic %4d", read16(code, ip));
case invokevirtual:
return fprintf(stderr, "invokevirtual %4d", read16(code, ip));
case ior:
return fprintf(stderr, "ior");
case irem:
return fprintf(stderr, "irem");
case ireturn:
return fprintf(stderr, "ireturn");
case freturn:
return fprintf(stderr, "freturn");
case ishl:
return fprintf(stderr, "ishl");
case ishr:
return fprintf(stderr, "ishr");
case istore:
return fprintf(stderr, "istore %2d", code[ip++]);
case fstore:
return fprintf(stderr, "fstore %2d", code[ip++]);
case istore_0:
return fprintf(stderr, "istore_0");
case fstore_0:
return fprintf(stderr, "fstore_0");
case istore_1:
return fprintf(stderr, "istore_1");
case fstore_1:
return fprintf(stderr, "fstore_1");
case istore_2:
return fprintf(stderr, "istore_2");
case fstore_2:
return fprintf(stderr, "fstore_2");
case istore_3:
return fprintf(stderr, "istore_3");
case fstore_3:
return fprintf(stderr, "fstore_3");
case isub:
return fprintf(stderr, "isub");
case iushr:
return fprintf(stderr, "iushr");
case ixor:
return fprintf(stderr, "ixor");
case jsr:
return fprintf(stderr, "jsr %4d", read16(code, ip) + startIp);
case jsr_w:
return fprintf(stderr, "jsr_w %08x", read32(code, ip) + startIp);
case l2d:
return fprintf(stderr, "l2d");
case l2f:
return fprintf(stderr, "l2f");
case l2i:
return fprintf(stderr, "l2i");
case ladd:
return fprintf(stderr, "ladd");
case laload:
return fprintf(stderr, "laload");
case land:
return fprintf(stderr, "land");
case lastore:
return fprintf(stderr, "lastore");
case lcmp:
return fprintf(stderr, "lcmp");
case lconst_0:
return fprintf(stderr, "lconst_0");
case lconst_1:
return fprintf(stderr, "lconst_1");
case ldc:
return fprintf(stderr, "ldc %4d", read16(code, ip));
case ldc_w:
return fprintf(stderr, "ldc_w %08x", read32(code, ip));
case ldc2_w:
return fprintf(stderr, "ldc2_w %4d", read16(code, ip));
case ldiv_:
return fprintf(stderr, "ldiv_");
case lload:
return fprintf(stderr, "lload %2d", code[ip++]);
case dload:
return fprintf(stderr, "dload %2d", code[ip++]);
case lload_0:
return fprintf(stderr, "lload_0");
case dload_0:
return fprintf(stderr, "dload_0");
case lload_1:
return fprintf(stderr, "lload_1");
case dload_1:
return fprintf(stderr, "dload_1");
case lload_2:
return fprintf(stderr, "lload_2");
case dload_2:
return fprintf(stderr, "dload_2");
case lload_3:
return fprintf(stderr, "lload_3");
case dload_3:
return fprintf(stderr, "dload_3");
case lmul:
return fprintf(stderr, "lmul");
case lneg:
return fprintf(stderr, "lneg");
case lookupswitch: {
while (ip & 0x3) {
ip++;
}
int32_t default_ = read32(code, ip) + startIp;
int32_t pairCount = read32(code, ip);
fprintf(
stderr, "lookupswitch default: %d pairCount: %d", default_, pairCount);
for (int i = 0; i < pairCount; i++) {
int32_t k = read32(code, ip);
int32_t d = read32(code, ip) + startIp;
fprintf(stderr, "\n%s key: %2d dest: %d", prefix, k, d);
}
fprintf(stderr, "\n");
fflush(stderr);
return 0;
}
case lor:
return fprintf(stderr, "lor");
case lrem:
return fprintf(stderr, "lrem");
case lreturn:
return fprintf(stderr, "lreturn");
case dreturn:
return fprintf(stderr, "dreturn");
case lshl:
return fprintf(stderr, "lshl");
case lshr:
return fprintf(stderr, "lshr");
case lstore:
return fprintf(stderr, "lstore %2d", code[ip++]);
case dstore:
return fprintf(stderr, "dstore %2d", code[ip++]);
case lstore_0:
return fprintf(stderr, "lstore_0");
case dstore_0:
return fprintf(stderr, "dstore_0");
case lstore_1:
return fprintf(stderr, "lstore_1");
case dstore_1:
return fprintf(stderr, "dstore_1");
case lstore_2:
return fprintf(stderr, "lstore_2");
case dstore_2:
return fprintf(stderr, "dstore_2");
case lstore_3:
return fprintf(stderr, "lstore_3");
case dstore_3:
return fprintf(stderr, "dstore_3");
case lsub:
return fprintf(stderr, "lsub");
case lushr:
return fprintf(stderr, "lushr");
case lxor:
return fprintf(stderr, "lxor");
case monitorenter:
return fprintf(stderr, "monitorenter");
case monitorexit:
return fprintf(stderr, "monitorexit");
case multianewarray: {
unsigned type = read16(code, ip);
return fprintf(stderr, "multianewarray %4d %2d", type, code[ip++]);
}
case new_:
return fprintf(stderr, "new %4d", read16(code, ip));
case newarray:
return fprintf(stderr, "newarray %2d", code[ip++]);
case nop:
return fprintf(stderr, "nop");
case pop_:
return fprintf(stderr, "pop");
case pop2:
return fprintf(stderr, "pop2");
case putfield:
return fprintf(stderr, "putfield %4d", read16(code, ip));
case putstatic:
return fprintf(stderr, "putstatic %4d", read16(code, ip));
case ret:
return fprintf(stderr, "ret %2d", code[ip++]);
case return_:
return fprintf(stderr, "return_");
case saload:
return fprintf(stderr, "saload");
case sastore:
return fprintf(stderr, "sastore");
case sipush:
return fprintf(stderr, "sipush %4d", read16(code, ip));
case swap:
return fprintf(stderr, "swap");
case tableswitch: {
while (ip & 0x3) {
ip++;
}
int32_t default_ = read32(code, ip) + startIp;
int32_t bottom = read32(code, ip);
int32_t top = read32(code, ip);
fprintf(stderr,
"tableswitch default: %d bottom: %d top: %d",
default_,
bottom,
top);
for (int i = 0; i < top - bottom + 1; i++) {
int32_t d = read32(code, ip) + startIp;
fprintf(stderr, "%s key: %d dest: %d", prefix, i + bottom, d);
}
return 0;
}
case wide: {
switch (code[ip++]) {
case aload:
return fprintf(stderr, "wide aload %4d", read16(code, ip));
case astore:
return fprintf(stderr, "wide astore %4d", read16(code, ip));
case iinc:
fprintf(stderr, "wide iinc %4d %4d", read16(code, ip), read16(code, ip));
case iload:
return fprintf(stderr, "wide iload %4d", read16(code, ip));
case istore:
return fprintf(stderr, "wide istore %4d", read16(code, ip));
case lload:
return fprintf(stderr, "wide lload %4d", read16(code, ip));
case lstore:
return fprintf(stderr, "wide lstore %4d", read16(code, ip));
case ret:
return fprintf(stderr, "wide ret %4d", read16(code, ip));
default: {
fprintf(
stderr, "unknown wide instruction %2d %4d", instr, read16(code, ip));
}
}
}
default: {
return fprintf(stderr, "unknown instruction %2d", instr);
}
}
return ip;
}
void disassembleCode(const char* prefix, uint8_t* code, unsigned length)
{
unsigned ip = 0;
while (ip < length) {
fprintf(stderr, "%s%x:\t", prefix, ip);
printInstruction(code, ip, prefix);
fprintf(stderr, "\n");
}
}
} // namespace debug
} // namespace jvm
} // namespace avian
| 15,815 | 6,443 |
#include <array>
#include <cstdint>
#include <string>
#include <vector>
#include "source/common/buffer/buffer_impl.h"
#include "source/common/grpc/codec.h"
#include "test/common/buffer/utility.h"
#include "test/proto/helloworld.pb.h"
#include "test/test_common/printers.h"
#include "gtest/gtest.h"
namespace Envoy {
namespace Grpc {
namespace {
TEST(GrpcCodecTest, encodeHeader) {
Encoder encoder;
std::array<uint8_t, 5> buffer;
encoder.newFrame(GRPC_FH_DEFAULT, 1, buffer);
EXPECT_EQ(buffer[0], GRPC_FH_DEFAULT);
EXPECT_EQ(buffer[1], 0);
EXPECT_EQ(buffer[2], 0);
EXPECT_EQ(buffer[3], 0);
EXPECT_EQ(buffer[4], 1);
encoder.newFrame(GRPC_FH_COMPRESSED, 1, buffer);
EXPECT_EQ(buffer[0], GRPC_FH_COMPRESSED);
EXPECT_EQ(buffer[1], 0);
EXPECT_EQ(buffer[2], 0);
EXPECT_EQ(buffer[3], 0);
EXPECT_EQ(buffer[4], 1);
encoder.newFrame(GRPC_FH_DEFAULT, 0x100, buffer);
EXPECT_EQ(buffer[0], GRPC_FH_DEFAULT);
EXPECT_EQ(buffer[1], 0);
EXPECT_EQ(buffer[2], 0);
EXPECT_EQ(buffer[3], 1);
EXPECT_EQ(buffer[4], 0);
encoder.newFrame(GRPC_FH_DEFAULT, 0x10000, buffer);
EXPECT_EQ(buffer[0], GRPC_FH_DEFAULT);
EXPECT_EQ(buffer[1], 0);
EXPECT_EQ(buffer[2], 1);
EXPECT_EQ(buffer[3], 0);
EXPECT_EQ(buffer[4], 0);
encoder.newFrame(GRPC_FH_DEFAULT, 0x1000000, buffer);
EXPECT_EQ(buffer[0], GRPC_FH_DEFAULT);
EXPECT_EQ(buffer[1], 1);
EXPECT_EQ(buffer[2], 0);
EXPECT_EQ(buffer[3], 0);
EXPECT_EQ(buffer[4], 0);
}
TEST(GrpcCodecTest, decodeIncompleteFrame) {
helloworld::HelloRequest request;
request.set_name("hello");
std::string request_buffer = request.SerializeAsString();
Buffer::OwnedImpl buffer;
std::array<uint8_t, 5> header;
Encoder encoder;
encoder.newFrame(GRPC_FH_DEFAULT, request.ByteSize(), header);
buffer.add(header.data(), 5);
buffer.add(request_buffer.c_str(), 5);
std::vector<Frame> frames;
Decoder decoder;
EXPECT_TRUE(decoder.decode(buffer, frames));
EXPECT_EQ(static_cast<size_t>(0), buffer.length());
EXPECT_EQ(static_cast<size_t>(0), frames.size());
EXPECT_EQ(static_cast<uint32_t>(request.ByteSize()), decoder.length());
EXPECT_EQ(true, decoder.hasBufferedData());
buffer.add(request_buffer.c_str() + 5);
EXPECT_TRUE(decoder.decode(buffer, frames));
EXPECT_EQ(static_cast<size_t>(0), buffer.length());
EXPECT_EQ(static_cast<size_t>(1), frames.size());
EXPECT_EQ(static_cast<uint32_t>(0), decoder.length());
EXPECT_EQ(false, decoder.hasBufferedData());
helloworld::HelloRequest decoded_request;
EXPECT_TRUE(decoded_request.ParseFromArray(frames[0].data_->linearize(frames[0].data_->length()),
frames[0].data_->length()));
EXPECT_EQ("hello", decoded_request.name());
}
TEST(GrpcCodecTest, decodeInvalidFrame) {
helloworld::HelloRequest request;
request.set_name("hello");
Buffer::OwnedImpl buffer;
std::array<uint8_t, 5> header;
Encoder encoder;
encoder.newFrame(0b10u, request.ByteSize(), header);
buffer.add(header.data(), 5);
buffer.add(request.SerializeAsString());
size_t size = buffer.length();
std::vector<Frame> frames;
Decoder decoder;
EXPECT_FALSE(decoder.decode(buffer, frames));
EXPECT_EQ(size, buffer.length());
}
// This test shows that null bytes in the bytestring successfully decode into a frame with length 0.
// Should this test really pass?
TEST(GrpcCodecTest, DecodeMultipleFramesInvalid) {
// A frame constructed from null bytes followed by an invalid frame
const std::string data("\000\000\000\000\0000000", 9);
Buffer::OwnedImpl buffer(data.data(), data.size());
size_t size = buffer.length();
std::vector<Frame> frames;
Decoder decoder;
EXPECT_FALSE(decoder.decode(buffer, frames));
// When the decoder doesn't successfully decode, it puts decoded frames up until
// an invalid frame into output frame vector.
EXPECT_EQ(1, frames.size());
// Buffer does not get drained due to it returning false.
EXPECT_EQ(size, buffer.length());
// Only part of the buffer represented a frame. Thus, the frame length should not equal the buffer
// length. The frame put into the output vector has no length.
EXPECT_EQ(0, frames[0].length_);
}
// If there is a valid frame followed by an invalid frame, the decoder will successfully put the
// valid frame in the output and return false due to the invalid frame
TEST(GrpcCodecTest, DecodeValidFrameWithInvalidFrameAfterward) {
// Decode a valid encoded structured request plus invalid data afterward
helloworld::HelloRequest request;
request.set_name("hello");
Buffer::OwnedImpl buffer;
std::array<uint8_t, 5> header;
Encoder encoder;
encoder.newFrame(GRPC_FH_DEFAULT, request.ByteSize(), header);
buffer.add(header.data(), 5);
buffer.add(request.SerializeAsString());
buffer.add("000000", 6);
size_t size = buffer.length();
std::vector<Frame> frames;
Decoder decoder;
EXPECT_FALSE(decoder.decode(buffer, frames));
// When the decoder doesn't successfully decode, it puts valid frames up until
// an invalid frame into output frame vector.
EXPECT_EQ(1, frames.size());
// Buffer does not get drained due to it returning false.
EXPECT_EQ(size, buffer.length());
// Only part of the buffer represented a valid frame. Thus, the frame length should not equal the
// buffer length.
EXPECT_NE(size, frames[0].length_);
}
TEST(GrpcCodecTest, decodeEmptyFrame) {
Buffer::OwnedImpl buffer("\0\0\0\0", 5);
Decoder decoder;
std::vector<Frame> frames;
EXPECT_TRUE(decoder.decode(buffer, frames));
EXPECT_EQ(1, frames.size());
EXPECT_EQ(0, frames[0].length_);
}
TEST(GrpcCodecTest, decodeSingleFrame) {
helloworld::HelloRequest request;
request.set_name("hello");
Buffer::OwnedImpl buffer;
std::array<uint8_t, 5> header;
Encoder encoder;
encoder.newFrame(GRPC_FH_DEFAULT, request.ByteSize(), header);
buffer.add(header.data(), 5);
buffer.add(request.SerializeAsString());
std::vector<Frame> frames;
Decoder decoder;
EXPECT_TRUE(decoder.decode(buffer, frames));
EXPECT_EQ(static_cast<size_t>(0), buffer.length());
EXPECT_EQ(frames.size(), static_cast<uint64_t>(1));
EXPECT_EQ(GRPC_FH_DEFAULT, frames[0].flags_);
EXPECT_EQ(static_cast<uint64_t>(request.ByteSize()), frames[0].length_);
helloworld::HelloRequest result;
result.ParseFromArray(frames[0].data_->linearize(frames[0].data_->length()),
frames[0].data_->length());
EXPECT_EQ("hello", result.name());
}
TEST(GrpcCodecTest, decodeMultipleFrame) {
helloworld::HelloRequest request;
request.set_name("hello");
Buffer::OwnedImpl buffer;
std::array<uint8_t, 5> header;
Encoder encoder;
encoder.newFrame(GRPC_FH_DEFAULT, request.ByteSize(), header);
for (int i = 0; i < 1009; i++) {
buffer.add(header.data(), 5);
buffer.add(request.SerializeAsString());
}
std::vector<Frame> frames;
Decoder decoder;
EXPECT_TRUE(decoder.decode(buffer, frames));
EXPECT_EQ(static_cast<size_t>(0), buffer.length());
EXPECT_EQ(frames.size(), static_cast<uint64_t>(1009));
for (Frame& frame : frames) {
EXPECT_EQ(GRPC_FH_DEFAULT, frame.flags_);
EXPECT_EQ(static_cast<uint64_t>(request.ByteSize()), frame.length_);
helloworld::HelloRequest result;
result.ParseFromArray(frame.data_->linearize(frame.data_->length()), frame.data_->length());
EXPECT_EQ("hello", result.name());
}
}
TEST(GrpcCodecTest, FrameInspectorTest) {
{
Buffer::OwnedImpl buffer;
FrameInspector counter;
EXPECT_EQ(0, counter.inspect(buffer));
EXPECT_EQ(counter.state(), State::FhFlag);
EXPECT_EQ(counter.frameCount(), 0);
}
{
Buffer::OwnedImpl buffer;
FrameInspector counter;
Buffer::addSeq(buffer, {0});
EXPECT_EQ(1, counter.inspect(buffer));
EXPECT_EQ(counter.state(), State::FhLen0);
EXPECT_EQ(counter.frameCount(), 1);
}
{
Buffer::OwnedImpl buffer;
FrameInspector counter;
Buffer::addSeq(buffer, {1, 0, 0, 0, 1, 0xFF});
EXPECT_EQ(1, counter.inspect(buffer));
EXPECT_EQ(counter.state(), State::FhFlag);
EXPECT_EQ(counter.frameCount(), 1);
}
{
FrameInspector counter;
Buffer::OwnedImpl buffer1;
Buffer::addSeq(buffer1, {1, 0, 0, 0});
EXPECT_EQ(1, counter.inspect(buffer1));
EXPECT_EQ(counter.state(), State::FhLen3);
EXPECT_EQ(counter.frameCount(), 1);
Buffer::OwnedImpl buffer2;
Buffer::addSeq(buffer2, {1, 0xFF});
EXPECT_EQ(0, counter.inspect(buffer2));
EXPECT_EQ(counter.frameCount(), 1);
}
{
Buffer::OwnedImpl buffer;
FrameInspector counter;
Buffer::addSeq(buffer, {1, 0, 0, 0, 1, 0xFF});
Buffer::addSeq(buffer, {0, 0, 0, 0, 2, 0xFF, 0xFF});
EXPECT_EQ(2, counter.inspect(buffer));
EXPECT_EQ(counter.state(), State::FhFlag);
EXPECT_EQ(counter.frameCount(), 2);
}
{
Buffer::OwnedImpl buffer1;
Buffer::OwnedImpl buffer2;
FrameInspector counter;
// message spans two buffers
Buffer::addSeq(buffer1, {1, 0, 0, 0, 2, 0xFF});
Buffer::addSeq(buffer2, {0xFF, 0, 0, 0, 0, 2, 0xFF, 0xFF});
EXPECT_EQ(1, counter.inspect(buffer1));
EXPECT_EQ(1, counter.inspect(buffer2));
EXPECT_EQ(counter.state(), State::FhFlag);
EXPECT_EQ(counter.frameCount(), 2);
}
{
Buffer::OwnedImpl buffer;
FrameInspector counter;
// Add longer byte sequence
Buffer::addSeq(buffer, {1, 0, 0, 1, 0});
Buffer::addRepeated(buffer, 1 << 8, 0xFF);
// Start second message
Buffer::addSeq(buffer, {0});
EXPECT_EQ(2, counter.inspect(buffer));
EXPECT_EQ(counter.state(), State::FhLen0);
EXPECT_EQ(counter.frameCount(), 2);
}
{
// two empty messages
Buffer::OwnedImpl buffer;
FrameInspector counter;
Buffer::addRepeated(buffer, 10, 0);
EXPECT_EQ(2, counter.inspect(buffer));
EXPECT_EQ(counter.frameCount(), 2);
}
}
} // namespace
} // namespace Grpc
} // namespace Envoy
| 9,866 | 3,801 |
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Christian Schulte <schulte@gecode.org>
*
* Copyright:
* Christian Schulte, 2002
*
* Last modified:
* $Date: 2017-02-21 06:45:56 +0100 (Tue, 21 Feb 2017) $ by $Author: schulte $
* $Revision: 15465 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.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 <gecode/int.hh>
namespace Gecode { namespace Int {
forceinline bool
IntVarImp::closer_min(int n) const {
unsigned int l = static_cast<unsigned int>(n - dom.min());
unsigned int r = static_cast<unsigned int>(dom.max() - n);
return l < r;
}
int
IntVarImp::med(void) const {
// Computes the median
if (fst() == NULL)
return (dom.min()+dom.max())/2 - ((dom.min()+dom.max())%2 < 0 ? 1 : 0);
unsigned int i = size() / 2;
if (size() % 2 == 0)
i--;
const RangeList* p = NULL;
const RangeList* c = fst();
while (i >= c->width()) {
i -= c->width();
const RangeList* n=c->next(p); p=c; c=n;
}
return c->min() + static_cast<int>(i);
}
bool
IntVarImp::in_full(int m) const {
if (closer_min(m)) {
const RangeList* p = NULL;
const RangeList* c = fst();
while (m > c->max()) {
const RangeList* n=c->next(p); p=c; c=n;
}
return (m >= c->min());
} else {
const RangeList* n = NULL;
const RangeList* c = lst();
while (m < c->min()) {
const RangeList* p=c->prev(n); n=c; c=p;
}
return (m <= c->max());
}
}
/*
* "Standard" tell operations
*
*/
ModEvent
IntVarImp::lq_full(Space& home, int m) {
assert((m >= dom.min()) && (m <= dom.max()));
IntDelta d(m+1,dom.max());
ModEvent me = ME_INT_BND;
if (range()) { // Is already range...
dom.max(m);
if (assigned()) me = ME_INT_VAL;
} else if (m < fst()->next(NULL)->min()) { // Becomes range...
dom.max(std::min(m,fst()->max()));
fst()->dispose(home,NULL,lst());
fst(NULL); holes = 0;
if (assigned()) me = ME_INT_VAL;
} else { // Stays non-range...
RangeList* n = NULL;
RangeList* c = lst();
unsigned int h = 0;
while (m < c->min()) {
RangeList* p = c->prev(n); c->fix(n);
h += (c->min() - p->max() - 1);
n=c; c=p;
}
holes -= h;
int max_c = std::min(m,c->max());
dom.max(max_c); c->max(max_c);
if (c != lst()) {
n->dispose(home,lst());
c->next(n,NULL); lst(c);
}
}
return notify(home,me,d);
}
ModEvent
IntVarImp::gq_full(Space& home, int m) {
assert((m >= dom.min()) && (m <= dom.max()));
IntDelta d(dom.min(),m-1);
ModEvent me = ME_INT_BND;
if (range()) { // Is already range...
dom.min(m);
if (assigned()) me = ME_INT_VAL;
} else if (m > lst()->prev(NULL)->max()) { // Becomes range...
dom.min(std::max(m,lst()->min()));
fst()->dispose(home,NULL,lst());
fst(NULL); holes = 0;
if (assigned()) me = ME_INT_VAL;
} else { // Stays non-range...
RangeList* p = NULL;
RangeList* c = fst();
unsigned int h = 0;
while (m > c->max()) {
RangeList* n = c->next(p); c->fix(n);
h += (n->min() - c->max() - 1);
p=c; c=n;
}
holes -= h;
int min_c = std::max(m,c->min());
dom.min(min_c); c->min(min_c);
if (c != fst()) {
fst()->dispose(home,p);
c->prev(p,NULL); fst(c);
}
}
return notify(home,me,d);
}
ModEvent
IntVarImp::eq_full(Space& home, int m) {
dom.min(m); dom.max(m);
if (!range()) {
bool failed = false;
RangeList* p = NULL;
RangeList* c = fst();
while (m > c->max()) {
RangeList* n=c->next(p); c->fix(n); p=c; c=n;
}
if (m < c->min())
failed = true;
while (c != NULL) {
RangeList* n=c->next(p); c->fix(n); p=c; c=n;
}
assert(p == lst());
fst()->dispose(home,p);
fst(NULL); holes = 0;
if (failed)
return fail(home);
}
IntDelta d;
return notify(home,ME_INT_VAL,d);
}
ModEvent
IntVarImp::nq_full(Space& home, int m) {
assert(!((m < dom.min()) || (m > dom.max())));
ModEvent me = ME_INT_DOM;
if (range()) {
if ((m == dom.min()) && (m == dom.max()))
return fail(home);
if (m == dom.min()) {
dom.min(m+1);
me = assigned() ? ME_INT_VAL : ME_INT_BND;
} else if (m == dom.max()) {
dom.max(m-1);
me = assigned() ? ME_INT_VAL : ME_INT_BND;
} else {
RangeList* f = new (home) RangeList(dom.min(),m-1);
RangeList* l = new (home) RangeList(m+1,dom.max());
f->prevnext(NULL,l);
l->prevnext(f,NULL);
fst(f); lst(l); holes = 1;
}
} else if (m < fst()->next(NULL)->min()) { // Concerns the first range...
int f_max = fst()->max();
if (m > f_max)
return ME_INT_NONE;
int f_min = dom.min();
if ((m == f_min) && (m == f_max)) {
RangeList* f_next = fst()->next(NULL);
dom.min(f_next->min());
if (f_next == lst()) { // Turns into range
// Works as at the ends there are only NULL pointers
fst()->dispose(home,f_next);
fst(NULL); holes = 0;
me = assigned() ? ME_INT_VAL : ME_INT_BND;
} else { // Remains non-range
f_next->prev(fst(),NULL);
fst()->dispose(home); fst(f_next);
holes -= dom.min() - f_min - 1;
me = ME_INT_BND;
}
} else if (m == f_min) {
dom.min(m+1); fst()->min(m+1);
me = ME_INT_BND;
} else if (m == f_max) {
fst()->max(m-1); holes += 1;
} else {
// Create new hole
RangeList* f = new (home) RangeList(f_min,m-1);
f->prevnext(NULL,fst());
fst()->min(m+1); fst()->prev(NULL,f);
fst(f); holes += 1;
}
} else if (m > lst()->prev(NULL)->max()) { // Concerns the last range...
int l_min = lst()->min();
if (m < l_min)
return ME_INT_NONE;
int l_max = dom.max();
if ((m == l_min) && (m == l_max)) {
RangeList* l_prev = lst()->prev(NULL);
dom.max(l_prev->max());
if (l_prev == fst()) {
// Turns into range
l_prev->dispose(home,lst());
fst(NULL); holes = 0;
me = assigned() ? ME_INT_VAL : ME_INT_BND;
} else { // Remains non-range
l_prev->next(lst(),NULL);
lst()->dispose(home); lst(l_prev);
holes -= l_max - dom.max() - 1;
me = ME_INT_BND;
}
} else if (m == l_max) {
dom.max(m-1); lst()->max(m-1);
me = ME_INT_BND;
} else if (m == l_min) {
lst()->min(m+1); holes += 1;
} else { // Create new hole
RangeList* l = new (home) RangeList(m+1,l_max);
l->prevnext(lst(),NULL);
lst()->max(m-1); lst()->next(NULL,l);
lst(l); holes += 1;
}
} else { // Concerns element in the middle of the list of ranges
RangeList* p;
RangeList* c;
RangeList* n;
if (closer_min(m)) {
assert(m > fst()->max());
p = NULL;
c = fst();
do {
n=c->next(p); p=c; c=n;
} while (m > c->max());
if (m < c->min())
return ME_INT_NONE;
n=c->next(p);
} else {
assert(m < lst()->min());
n = NULL;
c = lst();
do {
p=c->prev(n); n=c; c=p;
} while (m < c->min());
if (m > c->max())
return ME_INT_NONE;
p=c->prev(n);
}
assert((fst() != c) && (lst() != c));
assert((m >= c->min()) && (m <= c->max()));
holes += 1;
int c_min = c->min();
int c_max = c->max();
if ((c_min == m) && (c_max == m)) {
c->dispose(home);
p->next(c,n); n->prev(c,p);
} else if (c_min == m) {
c->min(m+1);
} else {
c->max(m-1);
if (c_max != m) {
RangeList* l = new (home) RangeList(m+1,c_max);
l->prevnext(c,n);
c->next(n,l);
n->prev(c,l);
}
}
}
IntDelta d(m,m);
return notify(home,me,d);
}
/*
* Copying variables
*
*/
forceinline
IntVarImp::IntVarImp(Space& home, bool share, IntVarImp& x)
: IntVarImpBase(home,share,x), dom(x.dom.min(),x.dom.max()) {
holes = x.holes;
if (holes) {
int m = 1;
// Compute length
{
RangeList* s_p = x.fst();
RangeList* s_c = s_p->next(NULL);
do {
m++;
RangeList* s_n = s_c->next(s_p); s_p=s_c; s_c=s_n;
} while (s_c != NULL);
}
RangeList* d_c = home.alloc<RangeList>(m);
fst(d_c); lst(d_c+m-1);
d_c->min(x.fst()->min());
d_c->max(x.fst()->max());
d_c->prevnext(NULL,NULL);
RangeList* s_p = x.fst();
RangeList* s_c = s_p->next(NULL);
do {
RangeList* d_n = d_c + 1;
d_c->next(NULL,d_n);
d_n->prevnext(d_c,NULL);
d_n->min(s_c->min()); d_n->max(s_c->max());
d_c = d_n;
RangeList* s_n=s_c->next(s_p); s_p=s_c; s_c=s_n;
} while (s_c != NULL);
d_c->next(NULL,NULL);
} else {
fst(NULL);
}
}
IntVarImp*
IntVarImp::perform_copy(Space& home, bool share) {
return new (home) IntVarImp(home,share,*this);
}
/*
* Dependencies
*
*/
void
IntVarImp::subscribe(Space& home, Propagator& p, PropCond pc,
bool schedule) {
IntVarImpBase::subscribe(home,p,pc,dom.min()==dom.max(),schedule);
}
void
IntVarImp::reschedule(Space& home, Propagator& p, PropCond pc) {
IntVarImpBase::reschedule(home,p,pc,dom.min()==dom.max());
}
void
IntVarImp::subscribe(Space& home, Advisor& a, bool fail) {
IntVarImpBase::subscribe(home,a,dom.min()==dom.max(),fail);
}
}}
// STATISTICS: int-var
| 11,092 | 4,273 |
#include <Core/Core.h>
#include <Functions4U/Functions4U.h>
#include <Eigen/Eigen.h>
#include "Utility.h"
namespace Upp {
using namespace Eigen;
double R2(const VectorXd &serie, const VectorXd &serie0, double mean) {
if (IsNull(mean))
mean = serie.mean();
double sse = 0, sst = 0;
for (Eigen::Index i = 0; i < serie.size(); ++i) {
double y = serie(i);
double err = y - serie0(i);
sse += err*err;
double d = y - mean;
sst += d*d;
}
if (sst < 1E-50 || sse > sst)
return 0;
return 1 - sse/sst;
}
} | 545 | 248 |
#include <wayfire/plugin.hpp>
#include <wayfire/output.hpp>
#include <wayfire/render-manager.hpp>
#include <wayfire/input-device.hpp>
#include <wayfire/output-layout.hpp>
#include <wayfire/core.hpp>
#include <wayfire/util/log.hpp>
#include <giomm/dbusconnection.h>
#include <giomm/dbuswatchname.h>
#include <giomm/dbusproxy.h>
#include <giomm/init.h>
#include <glibmm/main.h>
#include <glibmm/init.h>
#include <map>
extern "C"
{
#include <wlr/types/wlr_cursor.h>
#include <wlr/types/wlr_seat.h>
}
using namespace Gio;
class WayfireAutorotateIIO : public wf::plugin_interface_t
{
/* Tries to detect whether autorotate is enabled for the current output.
* Currently it is enabled only for integrated panels */
bool is_autorotate_enabled()
{
static const std::string integrated_connectors[] = {
"eDP",
"LVDS",
"DSI",
};
/* In wlroots, the output name is based on the connector */
auto output_connector = std::string(output->handle->name);
for (auto iconnector : integrated_connectors)
{
if (output_connector.find(iconnector) != iconnector.npos)
{
return true;
}
}
return false;
}
wf::signal_callback_t on_input_devices_changed = [=] (void*)
{
if (!is_autorotate_enabled())
{
return;
}
auto devices = wf::get_core().get_input_devices();
for (auto& dev : devices)
{
if (dev->get_wlr_handle()->type == WLR_INPUT_DEVICE_TOUCH)
{
auto cursor = wf::get_core().get_wlr_cursor();
wlr_cursor_map_input_to_output(cursor, dev->get_wlr_handle(),
output->handle);
}
}
};
wf::option_wrapper_t<wf::activatorbinding_t>
rotate_up_opt{"autorotate-iio/rotate_up"},
rotate_left_opt{"autorotate-iio/rotate_left"},
rotate_down_opt{"autorotate-iio/rotate_down"},
rotate_right_opt{"autorotate-iio/rotate_right"};
wf::option_wrapper_t<bool>
config_rotation_locked{"autorotate-iio/lock_rotation"};
guint watch_id;
wf::activator_callback on_rotate_left = [=] (wf::activator_source_t src, int32_t)
{
return on_rotate_binding(WL_OUTPUT_TRANSFORM_270);
};
wf::activator_callback on_rotate_right =
[=] (wf::activator_source_t src, int32_t)
{
return on_rotate_binding(WL_OUTPUT_TRANSFORM_90);
};
wf::activator_callback on_rotate_up = [=] (wf::activator_source_t src, int32_t)
{
return on_rotate_binding(WL_OUTPUT_TRANSFORM_NORMAL);
};
wf::activator_callback on_rotate_down = [=] (wf::activator_source_t src, int32_t)
{
return on_rotate_binding(WL_OUTPUT_TRANSFORM_180);
};
/* User-specified rotation via keybinding, -1 means not set */
int32_t user_rotation = -1;
/* Transform coming from the iio-sensors, -1 means not set */
int32_t sensor_transform = -1;
bool on_rotate_binding(int32_t target_rotation)
{
if (!output->can_activate_plugin(grab_interface))
{
return false;
}
/* If the user presses the same rotation binding twice, this means
* unlock the rotation. Otherwise, just use the new rotation. */
if (target_rotation == user_rotation)
{
user_rotation = -1;
} else
{
user_rotation = target_rotation;
}
return update_transform();
}
/** Calculate the transform based on user and sensor data, and apply it */
bool update_transform()
{
wl_output_transform transform_to_use;
if (user_rotation >= 0)
{
transform_to_use = (wl_output_transform)user_rotation;
} else if ((sensor_transform >= 0) && !config_rotation_locked)
{
transform_to_use = (wl_output_transform)sensor_transform;
} else
{
/* No user rotation set, and no sensor data */
return false;
}
auto configuration =
wf::get_core().output_layout->get_current_configuration();
if (configuration[output->handle].transform == transform_to_use)
{
return false;
}
configuration[output->handle].transform = transform_to_use;
wf::get_core().output_layout->apply_configuration(configuration);
return true;
}
wf::effect_hook_t on_frame = [=] ()
{
Glib::MainContext::get_default()->iteration(false);
};
Glib::RefPtr<Glib::MainLoop> loop;
public:
void init() override
{
output->add_activator(rotate_left_opt, &on_rotate_left);
output->add_activator(rotate_right_opt, &on_rotate_right);
output->add_activator(rotate_up_opt, &on_rotate_up);
output->add_activator(rotate_down_opt, &on_rotate_down);
on_input_devices_changed(nullptr);
wf::get_core().connect_signal("input-device-added",
&on_input_devices_changed);
init_iio_sensors();
}
void init_iio_sensors()
{
if (!is_autorotate_enabled())
{
return;
}
Glib::init();
Gio::init();
loop = Glib::MainLoop::create(true);
output->render->add_effect(&on_frame, wf::OUTPUT_EFFECT_PRE);
watch_id = DBus::watch_name(DBus::BUS_TYPE_SYSTEM, "net.hadess.SensorProxy",
sigc::mem_fun(this, &WayfireAutorotateIIO::on_iio_appeared),
sigc::mem_fun(this, &WayfireAutorotateIIO::on_iio_disappeared));
}
Glib::RefPtr<DBus::Proxy> iio_proxy;
void on_iio_appeared(const Glib::RefPtr<DBus::Connection>& conn,
Glib::ustring name, Glib::ustring owner)
{
LOGI("iio-sensors appeared, connecting ...");
iio_proxy = DBus::Proxy::create_sync(conn,
name, "/net/hadess/SensorProxy", "net.hadess.SensorProxy");
if (!iio_proxy)
{
LOGE("Failed to connect to iio-proxy.");
return;
}
iio_proxy->signal_properties_changed().connect_notify(
sigc::mem_fun(this, &WayfireAutorotateIIO::on_properties_changed));
iio_proxy->call_sync("ClaimAccelerometer");
}
void on_properties_changed(
const Gio::DBus::Proxy::MapChangedProperties& properties,
const std::vector<Glib::ustring>& invalidated)
{
update_orientation();
}
void update_orientation()
{
if (!iio_proxy)
{
return;
}
Glib::Variant<Glib::ustring> orientation;
iio_proxy->get_cached_property(orientation, "AccelerometerOrientation");
LOGI("IIO Accelerometer orientation: %s", orientation.get().c_str());
static const std::map<std::string, wl_output_transform> transform_by_name =
{
{"normal", WL_OUTPUT_TRANSFORM_NORMAL},
{"left-up", WL_OUTPUT_TRANSFORM_270},
{"right-up", WL_OUTPUT_TRANSFORM_90},
{"bottom-up", WL_OUTPUT_TRANSFORM_180},
};
if (transform_by_name.count(orientation.get()))
{
sensor_transform = transform_by_name.find(orientation.get())->second;
update_transform();
}
}
void on_iio_disappeared(const Glib::RefPtr<DBus::Connection>& conn,
Glib::ustring name)
{
LOGI("lost connection to iio-sensors.");
iio_proxy.reset();
}
void fini() override
{
output->rem_binding(&on_rotate_left);
output->rem_binding(&on_rotate_right);
output->rem_binding(&on_rotate_up);
output->rem_binding(&on_rotate_down);
wf::get_core().disconnect_signal("input-device-added",
&on_input_devices_changed);
/* If loop is NULL, autorotate was disabled for the current output */
if (loop)
{
iio_proxy.reset();
DBus::unwatch_name(watch_id);
loop->quit();
output->render->rem_effect(&on_frame);
}
}
};
DECLARE_WAYFIRE_PLUGIN(WayfireAutorotateIIO);
| 8,121 | 2,689 |
#pragma once
#if defined(SPRAWL_NO_EXCEPTIONS)
# define SPRAWL_EXCEPTIONS_ENABLED 0
#elif defined(__clang__)
# define SPRAWL_EXCEPTIONS_ENABLED __has_feature(cxx_exceptions)
#elif defined(__GNUC__)
# ifdef __EXCEPTIONS
# define SPRAWL_EXCEPTIONS_ENABLED 1
# else
# define SPRAWL_EXCEPTIONS_ENABLED 0
# endif
#elif defined(_WIN32)
# ifdef _CPPUNWIND
# define SPRAWL_EXCEPTIONS_ENABLED 1
# else
# define SPRAWL_EXCEPTIONS_ENABLED 0
# endif
#else
# define SPRAWL_EXCEPTIONS_ENABLED 0
#endif
#if SPRAWL_EXCEPTIONS_ENABLED
# define SPRAWL_THROW_EXCEPTION(exception, returnValue) throw exception
#else
namespace sprawl { void throw_exception(std::exception const& exception); }
# define SPRAWL_THROW_EXCEPTION(exception, returnValue) sprawl::throw_exception(exception); return returnValue
#endif
#define SPRAWL_ABORT_MSG(msg, ...) fprintf(stderr, msg, ## __VA_ARGS__); fputs("\n", stderr); abort();
#define SPRAWL_UNIMPLEMENTED_BASE_CLASS_METHOD SPRAWL_ABORT_MSG("This method called is not implemented on this object")
| 1,022 | 430 |
////////////////////////////////////////////////////////////////////
//
// $Id: PMLIO.cxx 2021/06/05 13:58:48 kanai Exp $
//
// Copyright (c) 2021 Takashi Kanai
// Released under the MIT license
//
////////////////////////////////////////////////////////////////////
#include "envDep.h"
#include <iostream>
#include <fstream>
#include <string>
#include "MeshL.hxx"
#include "VertexL.hxx"
#include "FaceL.hxx"
#include "VSplitL.hxx"
#include "PMLIO.hxx"
// open ppd file using STL fstream
bool PMLIO::outputToFile( const char * const pmfile )
{
std::ofstream ofs( pmfile ); if ( !ofs ) return false;
int vn = mesh().vertices().size() + vsplist().size() * 2;
int fn = mesh().faces().size() + vsplist().size() * 2;
ofs << "header" << std::endl;
ofs << "\tsolid\t1" << std::endl;
ofs << "\tpart\t1" << std::endl;
ofs << "\tvertex\t" << mesh().vertices().size() << std::endl;
ofs << "\tface\t" << mesh().faces().size() << std::endl;
ofs << "\tfnode\t" << mesh().faces().size() * 3 << std::endl;
ofs << "\tvsplit\t " << vsplist().size() << std::endl;
ofs << "\tvall\t " << vn << std::endl;
ofs << "\tfall\t " << fn << std::endl;
ofs << "end" << std::endl;
std::vector<int> v_id_( orgVtSize() );
std::vector<int> f_id_( orgFcSize() );
// solid, part
ofs << "solid" << std::endl;
ofs << "\t1\t/p 1 1 ";
if ( mesh().vertices().size() ) ofs << "/v 1 " << mesh().vertices().size() << " ";
if ( mesh().faces().size() ) ofs << "/f 1 " << mesh().faces().size() << " ";
ofs << std::endl;
ofs << "end" << std::endl;
ofs << "part" << std::endl;
if ( mesh().faces().size() ) ofs << "\t1\t/f 1 " << mesh().faces().size() << std::endl;
ofs << "end" << std::endl;
int v_sid = 1;
int vid = 1;
if ( vn )
{
ofs << "vall" << std::endl;
foreach ( std::list<VertexL*>, mesh().vertices(), vt )
{
// cout << "vt (in vertex) " << (*vt)->id() << endl;
Point3d p( (*vt)->point() );
if ( mesh().isNormalized() )
{
p.scale( mesh().maxLength() );
p += mesh().center();
}
ofs << "\t" << v_sid << "\t"
<< p.x << " "
<< p.y << " "
<< p.z << std::endl;
v_id_[ (*vt)->id() ] = vid;
++vid;
++v_sid;
}
for ( int i = vsplist().size()-1 ; i >= 0; --i )
{
Point3d p( vspl(i)->pos(0) );
if ( mesh().isNormalized() )
{
p.scale( mesh().maxLength() );
p += mesh().center();
}
// cout << "i = " << i << endl;
// cout << "vt = " << vspl(i)->id() << endl;
ofs << "\t" << v_sid << "\t"
<< p.x << " "
<< p.y << " "
<< p.z << std::endl;
++v_sid;
p.set( vspl(i)->pos(1) );
if ( mesh().isNormalized() )
{
p.scale( mesh().maxLength() );
p += mesh().center();
}
ofs << "\t" << v_sid << "\t"
<< p.x << " "
<< p.y << " "
<< p.z << std::endl;
++v_sid;
}
ofs << "end" << std::endl;
}
int id = 1;
if ( mesh().faces().size() )
{
ofs << "face" << std::endl;
foreach ( std::list<FaceL*>, mesh().faces(), fc )
{
ofs << "\t" << id << "\t";
foreach ( std::list<HalfedgeL*>, (*fc)->halfedges(), he )
{
ofs << v_id_[ (*he)->vertex()->id() ];
ofs << " ";
}
ofs << std::endl;
f_id_[ (*fc)->id() ] = id;
++id;
}
ofs << "end" << std::endl;
}
if ( vsplist().size() )
{
ofs << "vsplit" << std::endl;
int vspl_id = 1;
for ( int i = vsplist().size()-1 ; i >= 0; --i )
{
//cout << "vt (in vsplit) " << vspl(i)->vt() << endl;
f_id_[ vspl(i)->fl() ] = id++;
f_id_[ vspl(i)->fr() ] = id++;
ofs << "\t" << vspl_id << "\t"
<< v_id_[ vspl(i)->vt() ] << " /f "
<< f_id_[ vspl(i)->fn(0) ] << " "
<< f_id_[ vspl(i)->fn(1) ] << " "
<< f_id_[ vspl(i)->fn(2) ] << " "
<< f_id_[ vspl(i)->fn(3) ] << std::endl;
v_id_[ vspl(i)->vn(0) ] = vid; vid++;
v_id_[ vspl(i)->vn(1) ] = vid; vid++;
++vspl_id;
}
ofs << "end" << std::endl;
}
ofs.close();
return true;
}
| 4,340 | 1,747 |
// Shasta.
#include "CompressedAssemblyGraph.hpp"
#include "Assembler.hpp"
#include "deduplicate.hpp"
#include "findLinearChains.hpp"
#include "html.hpp"
#include "platformDependent.hpp"
#include "runCommandWithTimeout.hpp"
#include "subgraph.hpp"
using namespace shasta;
// Boost libraries.
#include <boost/algorithm/string.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
// Standard library.
#include "fstream.hpp"
#include "vector.hpp"
// Create the CompressedAssemblyGraph from the AssemblyGraph.
CompressedAssemblyGraph::CompressedAssemblyGraph(
const Assembler& assembler)
{
CompressedAssemblyGraph& graph = *this;
const AssemblyGraph& assemblyGraph = *(assembler.assemblyGraphPointer);
cout << "The assembly graph has " << assemblyGraph.vertices.size() <<
" vertices and " << assemblyGraph.edges.size() << " edges." << endl;
// Create a vertex for each vertex of the assembly graph.
vector<vertex_descriptor> vertexTable;
createVertices(assemblyGraph.vertices.size(), vertexTable);
// Create an edge for each set of parallel edges of the assembly graph.
createEdges(assemblyGraph, vertexTable);
removeReverseBubbles();
// Merge linear chains of edges.
mergeLinearChains();
cout << "The compressed assembly graph has " <<
num_vertices(graph) <<
" vertices and " << num_edges(graph) << " edges." << endl;
// Assign an id to each edge.
assignEdgeIds();
// Fill in the assembly graph edges that go into each
// edge of the compressed assembly graph.
fillContributingEdges(assemblyGraph);
// Fill in minimum and maximum marker counts for each edge.
fillMarkerCounts(assemblyGraph);
// Find the oriented reads that appear in marker graph vertices
// internal to each edge of the compressed assembly graph.
findOrientedReads(assembler);
fillOrientedReadTable(assembler);
// Find edges that have at least one common oriented read
// which each edge.
findRelatedEdges();
}
// Create a vertex for each vertex of the assembly graph.
void CompressedAssemblyGraph::createVertices(
uint64_t vertexCount,
vector<vertex_descriptor>& vertexTable)
{
CompressedAssemblyGraph& graph = *this;
vertexTable.resize(vertexCount, null_vertex());
for(VertexId vertexId=0; vertexId<vertexCount; vertexId++) {
const vertex_descriptor v = add_vertex(CompressedAssemblyGraphVertex(vertexId), graph);
vertexTable[vertexId] = v;
}
}
// Create an edge for each set of parallel edges of the assembly graph.
void CompressedAssemblyGraph::createEdges(
const AssemblyGraph& assemblyGraph,
const vector<vertex_descriptor>& vertexTable)
{
CompressedAssemblyGraph& graph = *this;
// Loop over assembly graph edges.
for(const AssemblyGraph::Edge& edge: assemblyGraph.edges) {
const vertex_descriptor v0 = vertexTable[edge.source];
const vertex_descriptor v1 = vertexTable[edge.target];
// Do we already have an edge between these two vertices?
bool edgeExists = false;
tie(ignore, edgeExists) = boost::edge(v0, v1, graph);
// If we don't already have an edge between these two vertices, add it.
// We only create one of each set of parallel edges.
if(not edgeExists) {
edge_descriptor e;
bool edgeWasAdded = false;
tie(e, edgeWasAdded) = add_edge(v0, v1, graph);
SHASTA_ASSERT(edgeWasAdded);
// Store the assembly graph vertices.
CompressedAssemblyGraphEdge& edge = graph[e];
edge.vertices.push_back(graph[v0].vertexId);
edge.vertices.push_back(graph[v1].vertexId);
}
}
}
// Remove back edges that create reverse bubbles.
// A reverse bubble is defined by two vertices v0 and v1 such that:
// - Edge v0->v1 exists.
// - Edge v1->v0 exists.
// - Out-degree(v0) = 1
// - In-degree(v1) = 1.
// Under these conditions, we remove vertex v1->v0.
void CompressedAssemblyGraph::removeReverseBubbles()
{
CompressedAssemblyGraph& graph = *this;
// Vector to contain the edges that we wil remove.
vector<edge_descriptor> edgesToBeRemoved;
// Try all edges.
BGL_FORALL_EDGES(e01, graph, CompressedAssemblyGraph) {
// Check that v0 has out-degree 1.
const vertex_descriptor v0 = source(e01, graph);
if(out_degree(v0, graph) != 1) {
continue;
}
// Check that v1 has in-degree 1.
const vertex_descriptor v1 = target(e01, graph);
if(in_degree(v1, graph) != 1) {
continue;
}
// Look for edges v1->v0.
// Try all edges v1->v2. Fkag to be renmoved if v2=v0.
BGL_FORALL_OUTEDGES(v1, e12, graph, CompressedAssemblyGraph) {
const vertex_descriptor v2 = target(e12, graph);
if(v2 == v0) {
edgesToBeRemoved.push_back(e12);
}
}
}
// Remove the edges we flagged.
deduplicate(edgesToBeRemoved);
for(const edge_descriptor e: edgesToBeRemoved) {
boost::remove_edge(e, graph);
}
}
// Merge linear chains of edges.
void CompressedAssemblyGraph::mergeLinearChains()
{
CompressedAssemblyGraph& graph = *this;
// Find linear chains.
vector< std::list<edge_descriptor> > chains;
findLinearChains(graph, chains);
// Replace each chain with a single edge.
for(const std::list<edge_descriptor>& chain: chains) {
// If the chain has length 1, leave it alone.
if(chain.size() == 1) {
continue;
}
// Add the new edge.
const vertex_descriptor v0 = source(chain.front(), graph);
const vertex_descriptor v1 = target(chain.back(), graph);
edge_descriptor eNew;
bool edgeWasAdded = false;
tie(eNew, edgeWasAdded) = add_edge(v0, v1, graph);
SHASTA_ASSERT(edgeWasAdded);
CompressedAssemblyGraphEdge& newEdge = graph[eNew];
// Fill in the assembly graph vertices corresponding to this new edge.
newEdge.vertices.push_back(graph[v0].vertexId);
for(const edge_descriptor e: chain) {
const vertex_descriptor v = target(e, graph);
newEdge.vertices.push_back(graph[v].vertexId);
}
// Remove the edges of the chain.
// We will remove the vertices later.
for(const edge_descriptor e: chain) {
boost::remove_edge(e, graph);
}
}
// Remove the vertices that have become isolated.
vector<vertex_descriptor> verticesToBeRemoved;
BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) {
if(in_degree(v, graph) == 0 and out_degree(v, graph) == 0) {
verticesToBeRemoved.push_back(v);
}
}
for(const vertex_descriptor v: verticesToBeRemoved) {
remove_vertex(v, graph);
}
}
// Assign an id to each edge.
void CompressedAssemblyGraph::assignEdgeIds()
{
CompressedAssemblyGraph& graph = *this;
uint64_t edgeId = 0;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
graph[e].id = edgeId++;
}
}
// Fill in the assembly graph edges that go into each
// edge of the compressed assembly graph.
void CompressedAssemblyGraph::fillContributingEdges(
const AssemblyGraph& assemblyGraph)
{
CompressedAssemblyGraph& graph = *this;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
CompressedAssemblyGraphEdge& edge = graph[e];
edge.edges.resize(edge.vertices.size() - 1);
for(uint64_t i=0; i<edge.edges.size(); i++) {
const VertexId vertexId0 = edge.vertices[i];
const VertexId vertexId1 = edge.vertices[i+1];
const span<const EdgeId> edges0 = assemblyGraph.edgesBySource[vertexId0];
for(const EdgeId edge01: edges0) {
if(assemblyGraph.edges[edge01].target == vertexId1) {
edge.edges[i].push_back(edge01);
}
}
}
}
}
// Find the oriented reads that appear in marker graph vertices
// internal to each edge of the compressed assembly graph.
void CompressedAssemblyGraph::findOrientedReads(
const Assembler& assembler)
{
CompressedAssemblyGraph& graph = *this;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
graph[e].findOrientedReads(assembler);
}
// Fill in the oriented read table, which tells us
// which edges each read appears in.
orientedReadTable.resize(2 * assembler.getReads().readCount());
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
for(const OrientedReadId orientedReadId: graph[e].orientedReadIds) {
orientedReadTable[orientedReadId.getValue()].push_back(e);
}
}
}
void CompressedAssemblyGraph::fillOrientedReadTable(
const Assembler& assembler)
{
CompressedAssemblyGraph& graph = *this;
orientedReadTable.clear();
orientedReadTable.resize(2 * assembler.getReads().readCount());
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
for(const OrientedReadId orientedReadId: graph[e].orientedReadIds) {
orientedReadTable[orientedReadId.getValue()].push_back(e);
}
}
}
// Find the oriented reads that appear in marker graph vertices
// internal to an edge of the compressed assembly graph.
void CompressedAssemblyGraphEdge::findOrientedReads(
const Assembler& assembler)
{
const AssemblyGraph& assemblyGraph = *assembler.assemblyGraphPointer;
// Loop over assembly graph edges.
for(const vector<AssemblyGraph::EdgeId>& edgesHere: edges) {
for(const AssemblyGraph::EdgeId assemblyGraphEdgeId: edgesHere) {
// Loop over marker graph edges corresponding to this
// assembly graph edge.
const span<const MarkerGraph::EdgeId> markerGraphEdgeIds =
assemblyGraph.edgeLists[assemblyGraphEdgeId];
for(const MarkerGraph::EdgeId markerGraphEdgeId: markerGraphEdgeIds) {
findOrientedReads(assembler, markerGraphEdgeId);
}
}
}
// Deduplicate oriented reads and count their occurrences.
deduplicateAndCount(orientedReadIds, orientedReadIdsFrequency);
}
// Append to orientedReadIds the oriented reads that
// appear in a given marker graph edge.
void CompressedAssemblyGraphEdge::findOrientedReads(
const Assembler& assembler,
const MarkerGraph::EdgeId& markerGraphEdgeId)
{
const span<const MarkerInterval> markerIntervals =
assembler.markerGraph.edgeMarkerIntervals[markerGraphEdgeId];
for(const MarkerInterval markerInterval: markerIntervals) {
orientedReadIds.push_back(markerInterval.orientedReadId);
}
}
// Find edges that have at least one common oriented read
// which each edge.
void CompressedAssemblyGraph::findRelatedEdges()
{
CompressedAssemblyGraph& graph = *this;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
findRelatedEdges(e);
}
}
void CompressedAssemblyGraph::findRelatedEdges(edge_descriptor e0)
{
CompressedAssemblyGraph& graph = *this;
CompressedAssemblyGraphEdge& edge0 = graph[e0];
for(const OrientedReadId orientedReadId: edge0.orientedReadIds) {
const vector<edge_descriptor>& edges = orientedReadTable[orientedReadId.getValue()];
for(const edge_descriptor e1: edges) {
if(e1 != e0) {
edge0.relatedEdges.push_back(e1);
}
}
}
deduplicate(edge0.relatedEdges);
edge0.relatedEdges.shrink_to_fit();
/*
cout << edge0.gfaId() << ":";
for(const edge_descriptor e1: edge0.relatedEdges) {
cout << " " << graph[e1].gfaId();
}
cout << endl;
*/
}
string CompressedAssemblyGraphEdge::gfaId() const
{
if(edges.size()==1 and edges.front().size()==1) {
// Return the one and only assembly graph edge associated with this
// compressed assembly graph edge.
return to_string(edges.front().front());
} else {
// Return the id of this compressed assembly graph edge,
// prefixed with "C".
return "C" + to_string(id);
}
}
// Return the edge with a given GFA id.
pair<CompressedAssemblyGraph::edge_descriptor, bool>
CompressedAssemblyGraph::getEdgeFromGfaId(
const string& s) const
{
const CompressedAssemblyGraph& graph = *this;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
if(graph[e].gfaId() == s) {
return make_pair(e, true);
}
}
return make_pair(edge_descriptor(), false);
}
uint64_t CompressedAssemblyGraph::maxPloidy() const
{
const CompressedAssemblyGraph& graph = *this;
uint64_t returnValue = 0;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
returnValue = max(returnValue, graph[e].maxPloidy());
}
return returnValue;
}
uint64_t CompressedAssemblyGraphEdge::maxPloidy() const
{
uint64_t returnValue = 0;
for(const auto& v: edges) {
returnValue = max(returnValue, uint64_t(v.size()));
}
return returnValue;
}
// GFA output (without sequence).
void CompressedAssemblyGraph::writeGfa(const string& fileName, double basesPerMarker) const
{
ofstream gfa(fileName);
writeGfa(gfa, basesPerMarker);
}
void CompressedAssemblyGraph::writeGfa(ostream& gfa, double basesPerMarker) const
{
const CompressedAssemblyGraph& graph = *this;
// Write the header line.
gfa << "H\tVN:Z:1.0\n";
// Write a segment record for each edge.
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
gfa <<
"S\t" <<
edge.gfaId() << "\t" <<
"*\t" <<
"LN:i:" << uint64_t(basesPerMarker * 0.5 *
double(edge.minMarkerCount + edge.maxMarkerCount)) <<
"\n";
}
// Write GFA links.
// For each vertex in the compressed assembly graph there is a link for
// each combination of in-edges and out-edges.
// Therefore each vertex generates a number of
// links equal to the product of its in-degree and out-degree.
BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) {
BGL_FORALL_INEDGES(v, eIn, graph, CompressedAssemblyGraph) {
BGL_FORALL_OUTEDGES(v, eOut, graph, CompressedAssemblyGraph) {
gfa <<
"L\t" <<
graph[eIn].gfaId() << "\t" <<
"+\t" <<
graph[eOut].gfaId() << "\t" <<
"+\t" <<
"*\n";
}
}
}
}
void CompressedAssemblyGraph::writeCsv() const
{
writeCsvEdges();
writeCsvBubbleChains();
writeCsvOrientedReadsByEdge();
writeCsvOrientedReads();
}
void CompressedAssemblyGraph::writeCsvEdges() const
{
const CompressedAssemblyGraph& graph = *this;
ofstream csv("CompressedGraph-Edges.csv");
csv << "Id,GFA id,Source,Target,MinMarkerCount,MaxMarkerCount,OrientedReadsCount,RelatedEdgesCount,\n";
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
const vertex_descriptor v0 = source(e, graph);
const vertex_descriptor v1 = target(e, graph);
csv << edge.id << ",";
csv << edge.gfaId() << ",";
csv << graph[v0].vertexId << ",";
csv << graph[v1].vertexId << ",";
csv << edge.minMarkerCount << ",";
csv << edge.maxMarkerCount << ",";
csv << edge.orientedReadIds.size() << ",";
csv << edge.relatedEdges.size() << ",";
csv << "\n";
}
}
void CompressedAssemblyGraph::writeCsvOrientedReadsByEdge() const
{
const CompressedAssemblyGraph& graph = *this;
ofstream csv("CompressedGraph-OrientedReadsByEdge.csv");
csv << "Id,GFA id,OrientedRead,Frequency\n";
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
SHASTA_ASSERT(edge.orientedReadIds.size() == edge.orientedReadIdsFrequency.size());
for(uint64_t i=0; i<edge.orientedReadIds.size(); i++) {
const OrientedReadId orientedReadId = edge.orientedReadIds[i];
const uint64_t frequency = edge.orientedReadIdsFrequency[i];
csv << edge.id << ",";
csv << edge.gfaId() << ",";
csv << orientedReadId << ",";
csv << frequency << "\n";
}
}
}
void CompressedAssemblyGraph::writeCsvBubbleChains() const
{
const CompressedAssemblyGraph& graph = *this;
const uint64_t maxPloidy = graph.maxPloidy();
ofstream csv("CompressedGraph-BubbleChains.csv");
csv << "Id,GFA id,Position,";
for(uint64_t i=0; i<maxPloidy; i++) {
csv << "Edge" << i << ",";
}
csv << "\n";
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
for(uint64_t position=0; position<edge.edges.size(); position++) {
const vector<AssemblyGraph::EdgeId>& edgesAtPosition = edge.edges[position];
csv << edge.id << ",";
csv << edge.gfaId() << ",";
csv << position << ",";
for(const AssemblyGraph::EdgeId edgeId: edgesAtPosition) {
csv << edgeId << ",";
}
csv << "\n";
}
}
}
void CompressedAssemblyGraph::writeCsvOrientedReads() const
{
const CompressedAssemblyGraph& graph = *this;
ofstream csv("CompressedGraph-OrientedReads.csv");
csv << "OrientedReadId,Id,GFA id,\n";
for(OrientedReadId::Int orientedReadId=0; orientedReadId<orientedReadTable.size();
orientedReadId++) {
const vector<edge_descriptor>& edges = orientedReadTable[orientedReadId];
for(const edge_descriptor e: edges) {
const CompressedAssemblyGraphEdge& edge = graph[e];
csv << OrientedReadId(orientedReadId) << ",";
csv << edge.id << ",";
csv << edge.gfaId() << "\n";
}
}
}
// Fill in minimum and maximum marker counts for each edge.
void CompressedAssemblyGraph::fillMarkerCounts(const AssemblyGraph& assemblyGraph)
{
CompressedAssemblyGraph& graph = *this;
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
graph[e].fillMarkerCounts(assemblyGraph);
}
}
void CompressedAssemblyGraphEdge::fillMarkerCounts(const AssemblyGraph& assemblyGraph)
{
minMarkerCount = 0;
maxMarkerCount = 0;
for(const vector<AssemblyGraph::EdgeId>& parallelEdges: edges) {
SHASTA_ASSERT(not parallelEdges.empty());
// Compute the minimum and maximum number of markers
// over this set of parallel edges.
uint64_t minMarkerCountHere = std::numeric_limits<uint64_t>::max();
uint64_t maxMarkerCountHere = 0;
for(const AssemblyGraph::EdgeId edgeId: parallelEdges) {
const uint64_t markerCount = assemblyGraph.edgeLists.size(edgeId);
minMarkerCountHere = min(minMarkerCountHere, markerCount);
maxMarkerCountHere = max(maxMarkerCountHere, markerCount);
}
// Update the totals.
minMarkerCount += minMarkerCountHere;
maxMarkerCount += maxMarkerCountHere;
}
}
// Create a local subgraph.
// See createLocalSubgraph for argument explanation.
CompressedAssemblyGraph::CompressedAssemblyGraph(
const CompressedAssemblyGraph& graph,
const Assembler& assembler,
const vector<vertex_descriptor>& startVertices,
uint64_t maxDistance,
boost::bimap<vertex_descriptor, vertex_descriptor>& vertexMap,
boost::bimap<edge_descriptor, edge_descriptor>& edgeMap,
std::map<vertex_descriptor, uint64_t>& distanceMap
)
{
CompressedAssemblyGraph& subgraph = *this;
createLocalSubgraph(
graph,
startVertices,
maxDistance,
subgraph,
vertexMap,
edgeMap,
distanceMap);
// Make sure the relatedEdges of each edge contain
// edge descriptors in the subgraph.
BGL_FORALL_EDGES(e0, subgraph, CompressedAssemblyGraph) {
vector<edge_descriptor> relatedEdges;
for(const edge_descriptor e1: subgraph[e0].relatedEdges) {
const auto it = edgeMap.right.find(e1);
if(it != edgeMap.right.end()) {
relatedEdges.push_back(it->second);
}
}
subgraph[e0].relatedEdges.swap(relatedEdges);
}
subgraph.fillOrientedReadTable(assembler);
}
// Graphviz output.
void CompressedAssemblyGraph::writeGraphviz(
const string& fileName,
uint64_t sizePixels,
double vertexScalingFactor,
double edgeLengthScalingFactor,
double edgeThicknessScalingFactor,
double edgeArrowScalingFactor,
std::map<vertex_descriptor, array<double, 2 > >& vertexPositions) const
{
ofstream s(fileName);
writeGraphviz(s,
sizePixels,
vertexScalingFactor,
edgeLengthScalingFactor,
edgeThicknessScalingFactor,
edgeArrowScalingFactor,
vertexPositions) ;
}
void CompressedAssemblyGraph::writeGraphviz(
ostream& s,
uint64_t sizePixels,
double vertexScalingFactor,
double edgeLengthScalingFactor,
double edgeThicknessScalingFactor,
double edgeArrowScalingFactor,
std::map<vertex_descriptor, array<double, 2 > >& vertexPositions) const
{
const CompressedAssemblyGraph& graph = *this;
s << "digraph CompressedAssemblyGraph {\n"
"layout=neato;\n"
"size=" << uint64_t(double(sizePixels)/72.) << ";\n"
"ratio=expand;\n"
"splines=true;\n"
"node [shape=point];\n"
"node [width=" << vertexScalingFactor << "];\n"
"edge [penwidth=" << edgeThicknessScalingFactor << "];\n"
"edge [arrowsize=" << edgeArrowScalingFactor << "];\n";
// Write the vertices.
BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) {
const auto it = vertexPositions.find(v);
SHASTA_ASSERT(it != vertexPositions.end());
const auto& x = it->second;
s << graph[v].vertexId <<
" [pos=\"" << x[0] << "," << x[1] << "\"];\n";
}
// Write the edges.
// Each edge is written as a number of dummy edges,
// to make it look longer, proportionally to its number of markers.
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
const string gfaId = edge.gfaId();
const vertex_descriptor v0 = source(e, graph);
const vertex_descriptor v1 = target(e, graph);
// To color the edge, use a hash function of the edge id,
// so the same edge always gets colored the same way.
const uint32_t hashValue = MurmurHash2(&edge.id, sizeof(edge.id), 757);
const double H = double(hashValue) / double(std::numeric_limits<uint32_t>::max());
const double S = 0.7;
const double V = 0.7;
s <<
graph[v0].vertexId << "->" <<
graph[v1].vertexId <<
"[tooltip=\"" << gfaId << "\" "
"color = \"" << H << "," << S << "," << "," << V << "\"" <<
"];\n";
}
s << "}";
}
#if 0
void CompressedAssemblyGraph::writeGraphviz(
ostream& s,
uint64_t sizePixels,
double vertexScalingFactor,
double edgeLengthScalingFactor,
double edgeThicknessScalingFactor,
double edgeArrowScalingFactor,
std::map<vertex_descriptor, array<double, 2 > >& vertexPositions) const
{
const CompressedAssemblyGraph& graph = *this;
s << "digraph CompressedAssemblyGraph {\n"
"layout=sfdp;\n"
"size=" << uint64_t(double(sizePixels)/72.) << ";\n"
"ratio=expand;\n"
"rankdir=LR;\n"
"node [shape=point];\n"
"node [width=" << vertexScalingFactor << "];\n"
"edge [penwidth=" << edgeThicknessScalingFactor << "];\n"
"edge [arrowsize=" << edgeArrowScalingFactor << "];\n"
"edge [arrowhead=none];\n";
// Write the vertices.
BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) {
s << graph[v].vertexId << ";\n";
}
// Write the edges.
// Each edge is written as a number of dummy edges,
// to make it look longer, proportionally to its number of markers.
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
const string gfaId = edge.gfaId();
const vertex_descriptor v0 = source(e, graph);
const vertex_descriptor v1 = target(e, graph);
const uint64_t dummyEdgeCount =
max(uint64_t(1), uint64_t(0.5 + edgeLengthScalingFactor * edge.averageMarkerCount()));
// Write the dummy vertices.
for(uint64_t i=1; i<dummyEdgeCount; i++) {
s << "\"" << gfaId << "-dummy" << i << "\" [width=" <<
edgeThicknessScalingFactor/72 << "];\n";
}
// Write the dummy edges.
for(uint64_t i=0; i<dummyEdgeCount; i++) {
// First vertex - either v0 or a dummy vertex.
s << "\"";
if(i == 0) {
s << graph[v0].vertexId;
} else {
s << gfaId << "-dummy" << i;
}
s << "\"->\"";
// Second vertex - either v1 or a dummy vertex.
if(i == dummyEdgeCount-1) {
s << graph[v1].vertexId;
} else {
s << gfaId << "-dummy" << i+1;
}
s << "\"";
s << " [";
if(i == dummyEdgeCount-1) {
s << "style=tapered";
}
/*
if(i == dummyEdgeCount/2) {
s << " label=" << edge.gfaId();
}
*/
s << "]";
s << ";\n";
}
}
s << "}";
}
#endif
// Use sfdp to compute a vertex layout.
// But sfdp does not support edges of different length
// (it tries to make all edges the same length).
// Here, we expand each edge into a variable number
// of dummy edges. Longer edges are expanded into more
// dummy edges. Then we use sfdp to compute a layout
// including all these dummy edges (and their vertices).
// Finally, we extract the coordinates for the original
// vertices only.
void CompressedAssemblyGraph::computeVertexLayout(
uint64_t sizePixels,
double vertexScalingFactor,
double edgeLengthPower,
double edgeLengthScalingFactor,
double timeout,
std::map<vertex_descriptor, array<double, 2 > >& vertexPositions
) const
{
const CompressedAssemblyGraph& graph = *this;
// Create a dot file to contain the graph including the dummy edges.
const string uuid = to_string(boost::uuids::random_generator()());
const string dotFileName = tmpDirectory() + uuid + ".dot";
ofstream graphOut(dotFileName);
graphOut <<
"digraph G{\n"
"layout=sfdp;\n"
"smoothing=triangle;\n"
"overlap=false;\n" <<
"size=" << uint64_t(double(sizePixels)/72.) << ";\n"
"ratio=expand;\n"
"node [shape=point];\n"
"node [width=" << vertexScalingFactor << "];\n";
// Write the vertices.
BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) {
graphOut << graph[v].vertexId << ";\n";
}
// Write the dummy edges.
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
const CompressedAssemblyGraphEdge& edge = graph[e];
const string gfaId = edge.gfaId();
const vertex_descriptor v0 = source(e, graph);
const vertex_descriptor v1 = target(e, graph);
// Figure out the number of dummy edges, based on the number of
// markers on this edge.
const double desiredDummyEdgeCount =
edgeLengthScalingFactor * std::pow(edge.averageMarkerCount(), edgeLengthPower);
const uint64_t dummyEdgeCount = max(
uint64_t(1),
uint64_t(0.5 + desiredDummyEdgeCount));
// Write the dummy edges.
for(uint64_t i=0; i<dummyEdgeCount; i++) {
// First vertex - either v0 or a dummy vertex.
if(i == 0) {
graphOut << graph[v0].vertexId;
} else {
graphOut << "D" << i << "_" << gfaId;
}
graphOut << "->";
// Second vertex - either v1 or a dummy vertex.
if(i == dummyEdgeCount-1) {
graphOut << graph[v1].vertexId;
} else {
graphOut << "D" << i+1 << "_" << gfaId;
}
graphOut << ";\n";
}
}
graphOut << "}";
graphOut.close();
// Now use sfdp to compute the layout.
// Use plain format output described here
// https://www.graphviz.org/doc/info/output.html#d:plain
const string plainFileName = dotFileName + ".txt";
const string command = "sfdp -T plain " + dotFileName + " -o " + plainFileName;
bool timeoutTriggered = false;
bool signalOccurred = false;
int returnCode = 0;
runCommandWithTimeout(command, timeout,
timeoutTriggered, signalOccurred, returnCode);
if(signalOccurred) {
throw runtime_error("Unable to compute graph layout: terminated by a signal. "
"The failing command was: " + command);
}
if(timeoutTriggered) {
throw runtime_error("Timeout exceeded during graph layout computation. "
"Increase the timeout or decrease the maximum distance to simplify the graph");
}
if(returnCode!=0 ) {
throw runtime_error("Unable to compute graph layout: return code " +
to_string(returnCode) +
". The failing command was: " + command);
}
filesystem::remove(dotFileName);
// Map vertex ids to vertex descriptors.
std::map<uint64_t, vertex_descriptor> vertexMap;
BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) {
vertexMap.insert(make_pair(graph[v].vertexId, v));
}
// Extract vertex coordinates.
ifstream plainFile(plainFileName);
string line;
vector<string> tokens;
while(true) {
// Read the next line.
std::getline(plainFile, line);
if( not plainFile) {
break;
}
// Parse it.
boost::algorithm::split(tokens, line, boost::algorithm::is_any_of(" "));
// SHASTA_ASSERT(not tokens.empty());
// If not a line describing a vertex, skip it.
if(tokens.front() != "node") {
continue;
}
SHASTA_ASSERT(tokens.size() >= 4);
// If a dummy vertex, skip it.
const string& vertexName = tokens[1];
SHASTA_ASSERT(not vertexName.empty());
if(vertexName[0] == 'D') {
continue;
}
// Get the vertex id.
const uint64_t vertexId = boost::lexical_cast<uint64_t>(vertexName);
// Get the corresponding vertex descriptor.
const auto it = vertexMap.find(vertexId);
const vertex_descriptor v = it->second;
// Store it in the layout.
array<double, 2> x;
x[0] = boost::lexical_cast<double>(tokens[2]);
x[1] = boost::lexical_cast<double>(tokens[3]);
vertexPositions.insert(make_pair(v, x));
}
plainFile.close();
filesystem::remove(plainFileName);
}
// Create a csv file with coloring.
// If the string passed in is an oriented read,
// it colors all edges that have that read.
// If it is the gfaId of an edge, it colors that edge in red
// and all related edges in green.
// This can be loaded in Bandage to color the edges.
void CompressedAssemblyGraph::color(
const string& s,
const string& fileName) const
{
ofstream csv(fileName);
color(s, csv);
}
void CompressedAssemblyGraph::color(
const string& s,
ostream& csv) const
{
const CompressedAssemblyGraph& graph = *this;
std::map<edge_descriptor, string> colorMap;
// If it is the gfaId of an edge, color that edge in red
// and all related edges in green.
edge_descriptor e0;
bool edgeWasFound = false;
tie(e0, edgeWasFound) = getEdgeFromGfaId(s);
if(edgeWasFound) {
colorMap.insert(make_pair(e0, "Red"));
for(const edge_descriptor e1: graph[e0].relatedEdges) {
colorMap.insert(make_pair(e1, "Green"));
}
}
// If it is an oriented read id, color in green all segments
// that have that oriented read.
else {
try {
const OrientedReadId orientedReadId = OrientedReadId(s);
for(const edge_descriptor e1: orientedReadTable[orientedReadId.getValue()]) {
colorMap.insert(make_pair(e1, "Green"));
}
} catch(...) {
cout << "The string to color by does not correspond to a valid "
"GFA id or a valid oriented read id.\n";
}
}
csv << "Segment,Color\n";
BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) {
csv << graph[e].gfaId() << ",";
const auto it = colorMap.find(e);
if(it == colorMap.end()) {
csv << "Grey";
} else {
csv << it->second;
}
csv << "\n";
}
}
| 33,341 | 10,376 |
#include "stdafx.h"
#include "ShopManager.h"
//public
#include "Obj_Human.h"
#include "Player.h"
#include "Obj_Monster.h"
#include "PAP_DBC.h"//DBC
#include "ItemHelper.h"//TSerialHelper
#include "ItemTable.h"//_ITEM_TYPE
#include "TimeManager.h"//g_pTimeManager
#include "GCShopUpdateMerchandiseList.h"//GCShopUpdateMerchandiseList
#include "FileDef.h"
//globle
using namespace DBC;
StaticShopManager* g_pStaticShopManager = NULL;
//macro
#define SHOP_ITEM_PROPERTY_NUM 3
#define SHOP_ID 0
//#define SHOP_NAME SHOP_ID+1
#define SHOP_TYPE SHOP_ID+1
#define SHOP_REPAIR_LEVEL SHOP_TYPE+1
#define SHOP_BUY_LEVEL SHOP_REPAIR_LEVEL+1
#define SHOP_REPAIR_TYPE SHOP_BUY_LEVEL+1
#define SHOP_BUY_TYPE SHOP_REPAIR_TYPE+1
#define SHOP_REPAIR_SPEND SHOP_BUY_TYPE+1
#define SHOP_REPAIR_OKPROB SHOP_REPAIR_SPEND+1
#define SHOP_SCALE SHOP_REPAIR_OKPROB+1 +2//LM修改
#define SHOP_REFRESH_TIME SHOP_SCALE+1
#define SHOP_ITEM_NUM SHOP_REFRESH_TIME+1
#define SHOP_ITEM_PROPERTY_BEGIN SHOP_ITEM_NUM+1
#define NEW_AND_COPY_ARRAY(PDEST, PSOURCE, NUM, TYPE)\
PDEST = new TYPE[NUM];\
memcpy((CHAR*)PDEST, (CHAR*)PSOURCE, NUM*sizeof(TYPE));\
ShopMgr::ShopMgr()
{
__ENTER_FUNCTION
m_Count = 0;
m_Shops = NULL;
__LEAVE_FUNCTION
}
ShopMgr::~ShopMgr()
{
__ENTER_FUNCTION
CleanUp();
__LEAVE_FUNCTION
}
VOID ShopMgr::CleanUp( )
{
__ENTER_FUNCTION
SAFE_DELETE_ARRAY(m_Shops)
__LEAVE_FUNCTION
}
//直接从ItemBoxManager::ConvertItemType2Index抄过来
INT ShopMgr::ConvertItemType2Money(_ITEM_TYPE it)
{
__ENTER_FUNCTION
Assert(it.isNull() == FALSE);
switch(it.m_Class)
{
case ICLASS_EQUIP:
{
switch(it.m_Quality)
{
case EQUALITY_NORMAL:
{
COMMON_EQUIP_TB* pGET = g_ItemTable.GetWhiteItemTB(it.ToSerial());
Assert(pGET);
return pGET->m_BasePrice;
}
break;
case EQUALITY_BLUE:
{
BLUE_EQUIP_TB* pGET = g_ItemTable.GetBlueItemTB(it.ToSerial());
Assert(pGET);
return pGET->m_BasePrice;
}
break;
case EQUALITY_YELLOW:
{
}
break;
case EQUALITY_GREEN:
{
GREEN_EQUIP_TB* pGET = g_ItemTable.GetGreenItemTB(it.ToSerial());
Assert(pGET);
return pGET->m_BasePrice;
}
break;
default:
{
Assert(FALSE);
return FALSE;
}
}
Assert(FALSE);
}
break;
case ICLASS_MATERIAL:
case ICLASS_COMITEM:
{
COMMITEM_INFO_TB* pGET = g_ItemTable.GetCommItemInfoTB(it.ToSerial());
Assert(pGET);
return pGET->m_nBasePrice;
}
break;
case ICLASS_TASKITEM:
{
return 1;
}
break;
case ICLASS_GEM:
{
GEMINFO_TB* pGET = g_ItemTable.GetGemInfoTB(it.ToSerial());
Assert(pGET);
return pGET->m_nPrice;
}
break;
case ICLASS_STOREMAP:
{
STORE_MAP_INFO_TB* pGET = g_ItemTable.GetStoreMapTB(it.ToSerial());
Assert(pGET);
return pGET->m_nBasePrice;
break;
}
case ICLASS_TALISMAN:
Assert(FALSE);
break;
case ICLASS_GUILDITEM:
Assert(FALSE);
break;
default:
Assert(FALSE);
break;
}
Assert(FALSE);
__LEAVE_FUNCTION
return -1;
}
_SHOP* ShopMgr::GetShopByID(INT id)
{
__ENTER_FUNCTION
for(INT i = 0; i<m_Count; i++)
{
if(m_Shops[i].m_ShopId == id)
{
return &m_Shops[i];
}
}
return NULL;
__LEAVE_FUNCTION
return NULL;
}
INT ShopMgr::GetShopIndexByID(INT id)
{
__ENTER_FUNCTION
for(INT i = 0; i<m_Count; i++)
{
if(m_Shops[i].m_ShopId == id)
{
return i;
}
}
return -1;
__LEAVE_FUNCTION
return -1;
}
/*
StaticShopManager
*/
StaticShopManager::~StaticShopManager()
{
__ENTER_FUNCTION
CleanUp();
__LEAVE_FUNCTION
}
BOOL StaticShopManager::Init()
{
return LoadShopsFromFile( FILE_SHOP );
}
VOID StaticShopManager::CleanUp()
{
__ENTER_FUNCTION
SAFE_DELETE_ARRAY(m_Shops)
__LEAVE_FUNCTION
}
BOOL StaticShopManager::LoadShopsFromFile( CHAR* filename )
{
__ENTER_FUNCTION
UINT d = sizeof(_ITEM);
DBCFile ShopFile(0);
BOOL ret = ShopFile.OpenFromTXT(filename);
if( !ret )
return FALSE;
INT iTableCount = ShopFile.GetRecordsNum();
INT iTableColumn = ShopFile.GetFieldsNum();
m_Count = iTableCount;
m_Shops = new _SHOP[m_Count];
INT itemnum = 0;
INT i,j,k;
INT itemTypeSn;
_ITEM_TYPE itemType;
INT PerItemNum = 0;
INT MaxItemNum = 0;
FLOAT PerRate = 0.0;
for(i =0;i<iTableCount;i++)
{
m_Shops[i].m_ShopId = ShopFile.Search_Posistion(i,SHOP_ID)->iValue;
//strncpy( m_Shops[i].m_szShopName, ShopFile.Search_Posistion(i,SHOP_NAME)->pString, MAX_SHOP_NAME-2 );
m_Shops[i].m_ShopType = ShopFile.Search_Posistion(i,SHOP_TYPE)->iValue;
m_Shops[i].m_nRepairLevel = ShopFile.Search_Posistion(i,SHOP_REPAIR_LEVEL)->iValue;
m_Shops[i].m_nBuyLevel = ShopFile.Search_Posistion(i,SHOP_BUY_LEVEL)->iValue;
m_Shops[i].m_nRepairType = ShopFile.Search_Posistion(i,SHOP_REPAIR_TYPE)->iValue;
m_Shops[i].m_nBuyType = ShopFile.Search_Posistion(i,SHOP_BUY_TYPE)->iValue;
m_Shops[i].m_nRepairSpend = ShopFile.Search_Posistion(i,SHOP_REPAIR_SPEND)->fValue;
m_Shops[i].m_nRepairOkProb = ShopFile.Search_Posistion(i,SHOP_REPAIR_OKPROB)->fValue;
m_Shops[i].m_scale = ShopFile.Search_Posistion(i,SHOP_SCALE)->fValue;
m_Shops[i].m_refreshTime = ShopFile.Search_Posistion(i,SHOP_REFRESH_TIME)->iValue;
itemnum = ShopFile.Search_Posistion(i,SHOP_ITEM_NUM)->iValue;
//分析实际有的数据
INT nNum = 0;
for(k=0; k<itemnum*SHOP_ITEM_PROPERTY_NUM; k++)
{
itemTypeSn = ShopFile.Search_Posistion(i,SHOP_ITEM_PROPERTY_BEGIN+k)->iValue;
if(itemTypeSn == 0)
{
break;
}
nNum ++;
k = k+2;
}
itemnum = nNum;
m_Shops[i].m_ItemList = new _SHOP::_MERCHANDISE_LIST(itemnum);
for(j = 0; j<itemnum*SHOP_ITEM_PROPERTY_NUM; j++)
{
//Type
itemTypeSn = ShopFile.Search_Posistion(i,SHOP_ITEM_PROPERTY_BEGIN+j)->iValue;
TSerialHelper help(itemTypeSn);
itemType = help.GetItemTypeStruct();
//GroupNum 0~100
PerItemNum = ShopFile.Search_Posistion(i,SHOP_ITEM_PROPERTY_BEGIN+(++j))->iValue;
if(PerItemNum<0) PerItemNum = 1;
if(PerItemNum>100) PerItemNum = 100;
//MaxNum -1代表无限,>0代表有限商品上限,不可以填0,<100
MaxItemNum = ShopFile.Search_Posistion(i,SHOP_ITEM_PROPERTY_BEGIN+(++j))->iValue;
if(MaxItemNum == 0) MaxItemNum = -1;
if(PerItemNum>100) PerItemNum = 100;
//Rate 0.0~1.0
PerRate = 1.0;
//ADD TO STRUCTURE
m_Shops[i].m_ItemList->AddType(itemType, PerItemNum, MaxItemNum, PerRate);
}
}
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
/*
DynamicShopManager
*/
DynamicShopManager::DynamicShopManager(Obj_Monster* pboss)
{
__ENTER_FUNCTION
m_pBoss = pboss;
m_Count = MAX_SHOP_PER_PERSON;
m_Shops = new _SHOP[m_Count];
m_aRefeshTimer = new CMyTimer[m_Count];
memset(m_aRefeshTimer,0, m_Count*sizeof(CMyTimer));
__LEAVE_FUNCTION
}
DynamicShopManager::~DynamicShopManager()
{
__ENTER_FUNCTION
CleanUp();
__LEAVE_FUNCTION
}
BOOL DynamicShopManager::Init()
{
m_nCurrent = 0;
return (m_Shops!= NULL)? TRUE:FALSE;
}
VOID DynamicShopManager::CleanUp()
{
SAFE_DELETE_ARRAY(m_Shops)
SAFE_DELETE_ARRAY(m_aRefeshTimer)
return;
}
INT DynamicShopManager::AddDynamicShop(_SHOP* pSource)
{
__ENTER_FUNCTION
if(m_nCurrent > MAX_SHOP_PER_PERSON)
return -1;
for(INT i = 0;i<m_nCurrent; i++)
{
if(m_Shops[i].m_ShopId == pSource->m_ShopId)
{//表里已经有了
return -1;
}
}
INT itemnum;
_SHOP& ShopRef = m_Shops[m_nCurrent];
ShopRef.m_ShopId = pSource->m_ShopId;
ShopRef.m_scale = pSource->m_scale;
ShopRef.m_refreshTime = pSource->m_refreshTime;
itemnum = pSource->m_ItemList->m_ListCount;
ShopRef.m_ItemList = new _SHOP::_MERCHANDISE_LIST;
ShopRef.m_ItemList->m_nCurrent = pSource->m_ItemList->m_nCurrent;
ShopRef.m_ItemList->m_ListCount = itemnum;
ShopRef.m_ShopType = pSource->m_ShopType;
ShopRef.m_bIsRandShop = pSource->m_bIsRandShop;
ShopRef.m_nCountForSell = pSource->m_nCountForSell;
ShopRef.m_nRepairLevel = pSource->m_nRepairLevel;
ShopRef.m_nBuyLevel = pSource->m_nBuyLevel;
ShopRef.m_nRepairType = pSource->m_nRepairType;
ShopRef.m_nBuyType = pSource->m_nBuyType;
ShopRef.m_nRepairSpend = pSource->m_nRepairSpend;
ShopRef.m_nRepairOkProb = pSource->m_nRepairOkProb;
ShopRef.m_bCanBuyBack = pSource->m_bCanBuyBack;
ShopRef.m_bCanMultiBuy = pSource->m_bCanMultiBuy;
ShopRef.m_uSerialNum = pSource->m_uSerialNum;
ShopRef.m_Rand100 = pSource->m_Rand100;
strncpy( ShopRef.m_szShopName, pSource->m_szShopName, MAX_SHOP_NAME );
//copycopycopy!!!!!,这些数据要保存在本地,供每个商人自己改变
NEW_AND_COPY_ARRAY(ShopRef.m_ItemList->m_TypeMaxNum, pSource->m_ItemList->m_TypeMaxNum, itemnum, INT)
//其他数据全部共享静态表中的数据,这些应该全部是只读的,程序启动时由静态商店管理器初始化,
//系统运行起来后谁都不准改!!
ShopRef.m_ItemList->m_ListType = pSource->m_ItemList->m_ListType;
ShopRef.m_ItemList->m_ListTypeIndex = pSource->m_ItemList->m_ListTypeIndex;
ShopRef.m_ItemList->m_TypeCount = pSource->m_ItemList->m_TypeCount;
ShopRef.m_ItemList->m_AppearRate = pSource->m_ItemList->m_AppearRate;
//全部操作完成,标识这个商店为动态表中的商店,即,可以被商人自己修改
ShopRef.m_IsDyShop = TRUE;
//启动计时器
if(ShopRef.m_refreshTime >0)
m_aRefeshTimer[m_nCurrent].BeginTimer(ShopRef.m_refreshTime, g_pTimeManager->CurrentTime());
return m_nCurrent++;
__LEAVE_FUNCTION
return -1;
}
BOOL DynamicShopManager::Tick(UINT uTime)
{
__ENTER_FUNCTION
if(!m_pBoss)
return FALSE;
Scene* pCurScene = m_pBoss->getScene();
for(INT i = 0; i< m_nCurrent; i++)
{
if(m_Shops[i].m_refreshTime <= 0)
continue;
if(m_aRefeshTimer[i].CountingTimer(uTime))
{//refresh
INT k = 0;
//GCShopUpdateMerchandiseList::_MERCHANDISE_ITEM MerchandiseList[MAX_BOOTH_NUMBER];
for (INT j = 0; j<m_Shops[i].m_ItemList->m_ListCount;j++)
{//用静态表中的数据刷新动态表的数据
INT& LocalMaxNum = m_Shops[i].m_ItemList->m_TypeMaxNum[j] ;
INT& GlobleMaxNum = g_pStaticShopManager->GetShopByID(m_Shops[i].m_ShopId)->m_ItemList->m_TypeMaxNum[j];
if(LocalMaxNum != GlobleMaxNum)
{//改变了,填充消息
LocalMaxNum = GlobleMaxNum;
}
}
}
}
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
| 12,729 | 4,900 |
#include "gdx/test/testbase.h"
#include "gdx/algo/clip.h"
#include "infra/crs.h"
namespace gdx::test {
TEST_CASE_TEMPLATE("Clip raster", TypeParam, UnspecializedRasterTypes)
{
RasterMetadata meta(4, 4, -1.0);
meta.xll = 0.0;
meta.yll = 0.0;
meta.set_cell_size(100.0);
meta.set_projection_from_epsg(inf::crs::epsg::BelgianLambert72);
SUBCASE("clip edges")
{
using FloatRaster = typename TypeParam::template type<float>;
FloatRaster raster(meta, std::vector<float>{
-1.f, 1.0f, 2.0f, 3.0f,
4.f, 5.f, 6.0f, 7.0f,
8.f, 9.f, -1.0f, 11.0f,
12.f, 13.f, 14.f, -1.f});
FloatRaster expected(meta, std::vector<float>{
-1.f, -1.f, -1.f, -1.f,
-1.f, 5.f, 6.0f, -1.f,
-1.f, 9.f, -1.0f, -1.f,
-1.f, -1.f, -1.f, -1.f});
std::vector<inf::Coordinate> polygon = {{
{100, 100},
{100, 300},
{300, 300},
{300, 100},
}};
clip_raster(raster, polygon, inf::crs::epsg::BelgianLambert72);
CHECK_RASTER_EQ(expected, raster);
}
}
}
| 1,352 | 550 |
//Include the deafult library iostream
#include <iostream>
//Main function
int main() {
//std cout to print hello world
std::cout << "Hello world!\n";
} | 161 | 49 |
#include <bits/stdc++.h>
using namespace std;
int main(void)
{
int n, num, i;
char c;
float coe = 0, rat = 0, sap = 0;
float total;
float coep, ratp, sapp;
scanf("%d", &n);
for( i = 1; i <= n; i++)
{
scanf("%d %c", &num, &c);
if(c == 'C')
coe += num;
else if(c == 'R')
rat += num;
else if(c == 'S')
sap += num;
}
total = coe + rat + sap;
coep = ((coe/total)*100);
ratp = ((rat/total)*100);
sapp = ((sap/total)*100);
printf("Total: %d cobaias\n", (int)total);
printf("Total de coelhos: %d\n", (int)coe);
printf("Total de ratos: %d\n", (int)rat );
printf("Total de sapos: %d\n", (int)sap);
printf("Percentual de coelhos: %.2f %%\n", coep);
printf("Percentual de ratos: %.2f %%\n", ratp );
printf("Percentual de sapos: %.2f %%\n", sapp);
}
| 900 | 384 |
#include "stdAfx.h"
#include "Logger.h"
#include "ErrorHandling.h"
#include "fileops.h"
#include "ComponentSystem.h"
using namespace std;
void ComponentSystem::readComponentConnections() {
pugi::xpath_node_set::const_iterator it;
map<FriendlyNameType, OriginalNameType>::iterator iter;
// Read <connect> elements
pugi::xpath_node_set connectionsNodeSet;
connectionsNodeSet = xmlParser.xpathQuery(
"/ComponentNetwork/ApplicationDescription/InterfaceConnections/Connect"
);
for (
it = connectionsNodeSet.begin();
it != connectionsNodeSet.end();
++it
)
{
string interfaceToBeConnected;
string xmlInterface = it->node().attribute("interface").value();
//Here we change the possible interface's friendly name into the real name
iter = interfacesConversion.find(xmlInterface);
if (iter != interfacesConversion.end()) {
interfaceToBeConnected = iter->second;
}else{
interfaceToBeConnected = xmlInterface;
}
/*interfaceImplementationsRepository.addInterfaceImplementor(
(char *)it->node().attribute("requiredBy").value(),
(char *)it->node().attribute("interface").value(),
(char *)it->node().attribute("providedBy").value()
);*/
interfaceImplementationsRepository.addInterfaceImplementor(
(char *)it->node().attribute("requiredBy").value(),
(char *)interfaceToBeConnected.c_str(),
(char *)it->node().attribute("providedBy").value()
);
}
// Read <ConnectAll> elements
pugi::xpath_node_set connectAllNodeSet;
connectAllNodeSet = xmlParser.xpathQuery(
"/ComponentNetwork/ApplicationDescription/InterfaceConnections/ConnectAll"
);
// Loop through ConnectAll elements
for (
it = connectAllNodeSet.begin();
it != connectAllNodeSet.end();
++it
)
{
string interfaceToBeConnected;
string xmlInterface = it->node().attribute("interface").value();
//Here we change the possible interface's friendly name into the real name
iter = interfacesConversion.find(xmlInterface);
if (iter != interfacesConversion.end()) {
interfaceToBeConnected = iter->second;
}else{
interfaceToBeConnected = xmlInterface;
}
//const char *interfaceName = it->node().attribute("interface").value();
const char *providingInstance = it->node().attribute("providedBy").value();
LoggerInfo(
"ConnectAll components requesting %s to implementation provided by instance %s",
interfaceToBeConnected.c_str(),
providingInstance
);
// Loop through all instantiated components.
for (
int idx = 0;
idx < interfaceImplementationsRepository.instances.componentInstances.size();
idx++
)
{
// Loop through all required interfaces of the components
vector<string> requiredInterfaces;
requiredInterfaces =
interfaceImplementationsRepository.
instances.
componentInstances[idx].
second->
componentDescription->
requiredInterfaces;
for (int i = 0; i < requiredInterfaces.size(); i++) {
if (!strcmp(
interfaceToBeConnected.c_str(),
requiredInterfaces[i].c_str()
)
)
{
LoggerInfo(
"Connect all: instance %s implements "
"interface %s required by instance %s",
(char *)providingInstance,
interfaceToBeConnected.c_str(),
(char *)interfaceImplementationsRepository.instances.componentInstances[idx].first.c_str()
);
interfaceImplementationsRepository.addInterfaceImplementor(
(char *)interfaceImplementationsRepository.instances.componentInstances[idx].first.c_str(),
(char *)interfaceToBeConnected.c_str(),
(char *)providingInstance
);
}
}
}
}
}
| 3,736 | 1,323 |
#include<bits/stdc++.h>
int main()
{
freopen("saloon.in","r", stdin);
freopen("saloon.out","w", stdout);
int n, h, m ,k, time, x;
scanf("%d", &n);
std :: deque <int> arr;
int person = 0, j = 0;
for(int i = 0; i < n; i++)
{
scanf("%d %d %d", &h, &m, &k);
time = h * 60 + m;
while(person != 0 && arr[j] <= time)
{
person--;
j++;
}
if(person == 0)
{
arr.push_back(time + 20);
person++;
printf("%d %d\n", (time + 20)/60, (time + 20)%60);
continue;
}
if(person <= k)
{
x = arr[j] + person * 20;
arr.push_back(x);
person++;
printf("%d %d\n", x/60, x%60);
continue;
}
else
{
printf("%d %d\n", time/60, time%60);
continue;
}
}
}
| 928 | 355 |
//
// Created by Megha Ganesh on 4/24/20.
//
#include "ParticleController.h"
#include "Conversions.h"
#include "Globals.h"
#include "cinder/Vector.h"
namespace particles {
ParticleController::ParticleController() {}
b2World* ParticleController::setup(b2World &w) {
world_ = &w;
return world_;
}
void ParticleController::draw() {
for (auto & particle : particles_) {
particle.draw();
}
}
void ParticleController::update() {
for (auto & particle : particles_) {
particle.update();
}
}
void ParticleController::AddParticle(const cinder::ivec2 &mouse_pos) {
Particle p = Particle();
// Define a body
b2BodyDef body_def;
body_def.type = b2_staticBody;
// Set the position to that of the mouse
body_def.position.Set(Conversions::ToPhysics(mouse_pos.x),
Conversions::ToPhysics(mouse_pos.y));
// b2Body will be referenced to its corresponding particle instead of just
// creating a new body
body_def.userData = &p;
// Use the world to create the body
p.body_ = world_->CreateBody(&body_def);
// Define the fixture
b2PolygonShape static_box;
// Box is 0.5f x 0.5f
static_box.SetAsBox(Conversions::ToPhysics(global::BOX_SIZE_X),
Conversions::ToPhysics(global::BOX_SIZE_Y));
b2FixtureDef fixture_def;
fixture_def.shape = &static_box;
fixture_def.density = global::DENSITY;
fixture_def.friction = global::FRICTION;
// Restitution = bounce
fixture_def.restitution = global::RESTITUTION;
// Create the fixture with density, friction, and bounce
p.body_->CreateFixture(&fixture_def);
// Particle can do the rest of the initialization on its own
p.setup(cinder::vec2(global::BOX_SIZE_X, global::BOX_SIZE_Y));
// Add Particle to list of Particles
particles_.push_back(p);
}
void ParticleController::RemoveAll() {
for (auto & particle : particles_) {
world_->DestroyBody(particle.body_);
}
particles_.clear();
// Change color of particles
if (global::COLOR_SCHEME == 0 || global::COLOR_SCHEME == 1) {
global::COLOR_SCHEME++;
} else if (global::COLOR_SCHEME == 2) {
global::COLOR_SCHEME = 0;
}
}
b2BodyType ParticleController::SwitchBodyType() {
for (auto & particle : particles_) {
// Set body type to dynamic instead of static
particle.body_->SetType(b2_dynamicBody);
b2PolygonShape dynamic_box;
// +3 is to account for the body size increasing/decreasing
dynamic_box.SetAsBox(
Conversions::ToPhysics(global::BOX_SIZE_X + kSizeDifference),
Conversions::ToPhysics(global::BOX_SIZE_Y + kSizeDifference));
b2FixtureDef fixture_def;
fixture_def.shape = &dynamic_box;
fixture_def.density = global::DENSITY;
fixture_def.friction = global::FRICTION;
// Restitution = bounce
fixture_def.restitution = global::RESTITUTION;
// Create the fixture with density, friction, and bounce
particle.body_->CreateFixture(&fixture_def);
}
return particles_.begin()->body_->GetType();
}
cinder::vec2 ParticleController::IncreaseBodySize() {
cinder::vec2 size = cinder::vec2(global::BOX_SIZE_X + kSizeDifference,
global::BOX_SIZE_X + kSizeDifference);
for (auto & particle : particles_) {
particle.resize(size);
}
return size;
}
cinder::vec2 ParticleController::DecreaseBodySize() {
cinder::vec2 size = cinder::vec2(global::BOX_SIZE_X - kSizeDifference,
global::BOX_SIZE_X - kSizeDifference);
for (auto & particle : particles_) {
particle.resize(size);
}
return size;
}
}
| 3,501 | 1,211 |
// Copyright 2020 The XLS 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 "xls/codegen/combinational_generator.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/status/statusor.h"
#include "xls/common/status/matchers.h"
#include "xls/examples/sample_packages.h"
#include "xls/interpreter/ir_interpreter.h"
#include "xls/ir/function_builder.h"
#include "xls/ir/ir_parser.h"
#include "xls/ir/package.h"
#include "xls/ir/value_helpers.h"
#include "xls/simulation/module_simulator.h"
#include "xls/simulation/verilog_simulators.h"
#include "xls/simulation/verilog_test_base.h"
namespace xls {
namespace verilog {
namespace {
using status_testing::IsOkAndHolds;
constexpr char kTestName[] = "combinational_generator_test";
constexpr char kTestdataPath[] = "xls/codegen/testdata";
class CombinationalGeneratorTest : public VerilogTestBase {};
TEST_P(CombinationalGeneratorTest, RrotToCombinationalText) {
auto rrot32_data = sample_packages::BuildRrot32();
Function* f = rrot32_data.second;
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.RunAndReturnSingleOutput(
{{"x", UBits(0x12345678ULL, 32)}, {"y", UBits(4, 32)}}),
IsOkAndHolds(UBits(0x81234567, 32)));
}
TEST_P(CombinationalGeneratorTest, RandomExpression) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", u8);
auto b = fb.Param("b", u8);
auto c = fb.Param("c", u8);
auto a_minus_b = fb.Subtract(a, b, /*loc=*/absl::nullopt, /*name=*/"diff");
auto lhs = (a_minus_b * a_minus_b);
auto rhs = (c * a_minus_b);
auto out = fb.Add(lhs, rhs, /*loc=*/absl::nullopt, /*name=*/"the_output");
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(out));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
// Value should be: (7-2)*(7-2) + 3*(7-2) = 40
EXPECT_THAT(simulator.RunAndReturnSingleOutput(
{{"a", UBits(7, 8)}, {"b", UBits(2, 8)}, {"c", UBits(3, 8)}}),
IsOkAndHolds(UBits(40, 8)));
}
TEST_P(CombinationalGeneratorTest, ReturnsLiteral) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
fb.Literal(UBits(123, 8));
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.RunAndReturnSingleOutput(ModuleSimulator::BitsMap()),
IsOkAndHolds(UBits(123, 8)));
}
TEST_P(CombinationalGeneratorTest, ReturnsTupleLiteral) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
fb.Literal(Value::Tuple({Value(UBits(123, 8)), Value(UBits(42, 32))}));
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(
simulator.Run(absl::flat_hash_map<std::string, Value>()),
IsOkAndHolds(Value::Tuple({Value(UBits(123, 8)), Value(UBits(42, 32))})));
}
TEST_P(CombinationalGeneratorTest, ReturnsEmptyTuple) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
fb.Literal(Value::Tuple({}));
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.Run(absl::flat_hash_map<std::string, Value>()),
IsOkAndHolds(Value::Tuple({})));
}
TEST_P(CombinationalGeneratorTest, PassesEmptyTuple) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
fb.Param("x", package.GetTupleType({}));
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.Run({{"x", Value::Tuple({})}}),
IsOkAndHolds(Value::Tuple({})));
}
TEST_P(CombinationalGeneratorTest, TakesEmptyTuple) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", u8);
fb.Param("b", package.GetTupleType({}));
auto c = fb.Param("c", u8);
fb.Add(a, c, /*loc=*/absl::nullopt, /*name=*/"sum");
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.Run({{"a", Value(UBits(42, 8))},
{"b", Value::Tuple({})},
{"c", Value(UBits(100, 8))}}),
IsOkAndHolds(Value(UBits(142, 8))));
}
TEST_P(CombinationalGeneratorTest, ReturnsParam) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
fb.Param("a", u8);
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.RunAndReturnSingleOutput({{"a", UBits(0x42, 8)}}),
IsOkAndHolds(UBits(0x42, 8)));
}
TEST_P(CombinationalGeneratorTest, ExpressionWhichRequiresNamedIntermediate) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", u8);
auto b = fb.Param("b", u8);
auto a_plus_b = a + b;
auto out = fb.BitSlice(a_plus_b, /*start=*/3, /*width=*/4,
/*loc=*/absl::nullopt, /*name=*/"slice_n_dice");
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(out));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.RunAndReturnSingleOutput(
{{"a", UBits(0x42, 8)}, {"b", UBits(0x33, 8)}}),
IsOkAndHolds(UBits(14, 4)));
}
TEST_P(CombinationalGeneratorTest, ExpressionsOfTuples) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
Type* u10 = package.GetBitsType(10);
Type* u16 = package.GetBitsType(16);
Type* tuple_u10_u16 = package.GetTupleType({u10, u16});
auto a = fb.Param("a", u8);
auto b = fb.Param("b", u10);
auto c = fb.Param("c", tuple_u10_u16);
// Glom all the inputs together into a big tuple.
auto a_b_c = fb.Tuple({a, b, c}, /*loc=*/absl::nullopt, /*name=*/"big_tuple");
// Then extract some elements and perform some arithmetic operations on them
// after zero-extending them to the same width (16-bits).
auto a_plus_b = fb.ZeroExtend(fb.TupleIndex(a_b_c, 0), 16) +
fb.ZeroExtend(fb.TupleIndex(a_b_c, 1), 16);
auto c_tmp = fb.TupleIndex(a_b_c, 2);
auto c0_minus_c1 =
fb.ZeroExtend(fb.TupleIndex(c_tmp, 0), 16) - fb.TupleIndex(c_tmp, 1);
// Result should be a two-tuple containing {a + b, c[0] - c[1]}
auto return_value = fb.Tuple({a_plus_b, c0_minus_c1});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(return_value));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.Run({{"a", Value(UBits(42, 8))},
{"b", Value(UBits(123, 10))},
{"c", Value::Tuple({Value(UBits(333, 10)),
Value(UBits(222, 16))})}}),
IsOkAndHolds(Value::Tuple(
{Value(UBits(165, 16)), Value(UBits(111, 16))})));
}
TEST_P(CombinationalGeneratorTest, TupleLiterals) {
std::string text = R"(
package TupleLiterals
fn main(x: bits[123]) -> bits[123] {
literal.1: (bits[123], bits[123], bits[123]) = literal(value=(0x10000, 0x2000, 0x300))
tuple_index.2: bits[123] = tuple_index(literal.1, index=0)
tuple_index.3: bits[123] = tuple_index(literal.1, index=1)
tuple_index.4: bits[123] = tuple_index(literal.1, index=2)
sum1: bits[123] = add(tuple_index.2, tuple_index.3)
sum2: bits[123] = add(tuple_index.4, x)
ret total: bits[123] = add(sum1, sum2)
}
)";
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(text));
XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction());
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateCombinationalModule(entry, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.Run({{"x", Value(UBits(0x40, 123))}}),
IsOkAndHolds(Value(UBits(0x12340, 123))));
}
TEST_P(CombinationalGeneratorTest, ArrayLiteral) {
std::string text = R"(
package ArrayLiterals
fn main(x: bits[32], y: bits[32]) -> bits[44] {
literal.1: bits[44][3][2] = literal(value=[[1, 2, 3], [4, 5, 6]])
array_index.2: bits[44][3] = array_index(literal.1, indices=[x])
ret result: bits[44] = array_index(array_index.2, indices=[y])
}
)";
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(text));
XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction());
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateCombinationalModule(entry, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(
simulator.Run({{"x", Value(UBits(0, 32))}, {"y", Value(UBits(1, 32))}}),
IsOkAndHolds(Value(UBits(2, 44))));
EXPECT_THAT(
simulator.Run({{"x", Value(UBits(1, 32))}, {"y", Value(UBits(0, 32))}}),
IsOkAndHolds(Value(UBits(4, 44))));
}
TEST_P(CombinationalGeneratorTest, OneHot) {
std::string text = R"(
package OneHot
fn main(x: bits[3]) -> bits[4] {
ret one_hot.1: bits[4] = one_hot(x, lsb_prio=true)
}
)";
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(text));
XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction());
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateCombinationalModule(entry, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b000, 3))}}),
IsOkAndHolds(Value(UBits(0b1000, 4))));
EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b001, 3))}}),
IsOkAndHolds(Value(UBits(0b0001, 4))));
EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b010, 3))}}),
IsOkAndHolds(Value(UBits(0b0010, 4))));
EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b011, 3))}}),
IsOkAndHolds(Value(UBits(0b0001, 4))));
EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b100, 3))}}),
IsOkAndHolds(Value(UBits(0b0100, 4))));
EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b101, 3))}}),
IsOkAndHolds(Value(UBits(0b0001, 4))));
EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b110, 3))}}),
IsOkAndHolds(Value(UBits(0b0010, 4))));
EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b111, 3))}}),
IsOkAndHolds(Value(UBits(0b0001, 4))));
}
TEST_P(CombinationalGeneratorTest, OneHotSelect) {
std::string text = R"(
package OneHotSelect
fn main(p: bits[2], x: bits[16], y: bits[16]) -> bits[16] {
ret one_hot_sel.1: bits[16] = one_hot_sel(p, cases=[x, y])
}
)";
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(text));
XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction());
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateCombinationalModule(entry, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
absl::flat_hash_map<std::string, Value> args = {
{"x", Value(UBits(0x00ff, 16))}, {"y", Value(UBits(0xf0f0, 16))}};
args["p"] = Value(UBits(0b00, 2));
EXPECT_THAT(simulator.Run(args), IsOkAndHolds(Value(UBits(0x0000, 16))));
args["p"] = Value(UBits(0b01, 2));
EXPECT_THAT(simulator.Run(args), IsOkAndHolds(Value(UBits(0x00ff, 16))));
args["p"] = Value(UBits(0b10, 2));
EXPECT_THAT(simulator.Run(args), IsOkAndHolds(Value(UBits(0xf0f0, 16))));
args["p"] = Value(UBits(0b11, 2));
EXPECT_THAT(simulator.Run(args), IsOkAndHolds(Value(UBits(0xf0ff, 16))));
}
TEST_P(CombinationalGeneratorTest, CrazyParameterTypes) {
std::string text = R"(
package CrazyParameterTypes
fn main(a: bits[32],
b: (bits[32], ()),
c: bits[32][3],
d: (bits[32], bits[32])[1],
e: (bits[32][2], (), ()),
f: bits[0],
g: bits[1]) -> bits[32] {
tuple_index.1: bits[32] = tuple_index(b, index=0)
literal.2: bits[32] = literal(value=0)
array_index.3: bits[32] = array_index(c, indices=[g])
array_index.4: (bits[32], bits[32]) = array_index(d, indices=[literal.2])
tuple_index.5: bits[32] = tuple_index(array_index.4, index=1)
tuple_index.6: bits[32][2] = tuple_index(e, index=0)
array_index.7: bits[32] = array_index(tuple_index.6, indices=[g])
ret or.8: bits[32] = or(a, tuple_index.1, array_index.3, tuple_index.5, array_index.7)
}
)";
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(text));
XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction());
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateCombinationalModule(entry, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
std::minstd_rand engine;
std::vector<Value> arguments = RandomFunctionArguments(entry, &engine);
XLS_ASSERT_OK_AND_ASSIGN(Value expected,
IrInterpreter::Run(entry, arguments));
EXPECT_THAT(simulator.Run(arguments), IsOkAndHolds(expected));
}
TEST_P(CombinationalGeneratorTest, TwoDArray) {
// Build up a two dimensional array from scalars, then deconstruct it and do
// something with the elements.
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", u8);
auto b = fb.Param("b", u8);
auto c = fb.Param("c", u8);
auto row_0 = fb.Array({a, b, c}, a.GetType());
auto row_1 = fb.Array({a, b, c}, a.GetType());
auto two_d = fb.Array({row_0, row_1}, row_0.GetType());
fb.Add(fb.ArrayIndex(fb.ArrayIndex(two_d, {fb.Literal(UBits(0, 8))}),
{fb.Literal(UBits(2, 8))}),
fb.ArrayIndex(fb.ArrayIndex(two_d, {fb.Literal(UBits(1, 8))}),
{fb.Literal(UBits(1, 8))}));
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.Run({{"a", Value(UBits(123, 8))},
{"b", Value(UBits(42, 8))},
{"c", Value(UBits(100, 8))}}),
IsOkAndHolds(Value(UBits(142, 8))));
}
TEST_P(CombinationalGeneratorTest, ReturnTwoDArray) {
// Build up a two dimensional array from scalars and return it.
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", u8);
auto b = fb.Param("b", u8);
auto row_0 = fb.Array({a, b}, a.GetType());
auto row_1 = fb.Array({b, a}, a.GetType());
fb.Array({row_0, row_1}, row_0.GetType());
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(
simulator.Run({{"a", Value(UBits(123, 8))}, {"b", Value(UBits(42, 8))}}),
IsOkAndHolds(Value::ArrayOrDie({
Value::ArrayOrDie({Value(UBits(123, 8)), Value(UBits(42, 8))}),
Value::ArrayOrDie({Value(UBits(42, 8)), Value(UBits(123, 8))}),
})));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdateBitElements) {
std::string text = R"(
package ArrayUpdate
fn main(idx: bits[2]) -> bits[32][3] {
literal.5: bits[32][3] = literal(value=[1, 2, 3])
literal.6: bits[32] = literal(value=99)
ret updated_array: bits[32][3] = array_update(literal.5, literal.6, indices=[idx])
}
)";
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(text));
XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction());
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateCombinationalModule(entry, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
auto make_array = [](absl::Span<const int64> values) {
std::vector<Value> elements;
for (auto v : values) {
elements.push_back(Value(UBits(v, 32)));
}
absl::StatusOr<Value> array = Value::Array(elements);
EXPECT_TRUE(array.ok());
return array.value();
};
EXPECT_THAT(simulator.Run({{"idx", Value(UBits(0b00, 2))}}),
IsOkAndHolds(make_array({99, 2, 3})));
EXPECT_THAT(simulator.Run({{"idx", Value(UBits(0b01, 2))}}),
IsOkAndHolds(make_array({1, 99, 3})));
EXPECT_THAT(simulator.Run({{"idx", Value(UBits(0b10, 2))}}),
IsOkAndHolds(make_array({1, 2, 99})));
EXPECT_THAT(simulator.Run({{"idx", Value(UBits(0b11, 2))}}),
IsOkAndHolds(make_array({1, 2, 3})));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdateArrayElements) {
std::string text = R"(
package ArrayUpdate
fn main(idx: bits[2]) -> bits[32][2][3] {
literal.17: bits[32][2][3] = literal(value=[[1, 2], [3, 4], [5, 6]])
literal.14: bits[32][2] = literal(value=[98, 99])
ret updated_array: bits[32][2][3] = array_update(literal.17, literal.14, indices=[idx])
}
)";
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(text));
XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction());
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateCombinationalModule(entry, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
auto make_array = [](absl::Span<const int64> values) {
std::vector<Value> elements;
for (auto v : values) {
elements.push_back(Value(UBits(v, 32)));
}
absl::StatusOr<Value> array = Value::Array(elements);
EXPECT_TRUE(array.ok());
return array.value();
};
auto make_array_of_values = [&](absl::Span<const Value> values) {
std::vector<Value> elements;
for (auto array : values) {
elements.push_back(array);
}
absl::StatusOr<Value> array_of_values = Value::Array(elements);
EXPECT_TRUE(array_of_values.ok());
return array_of_values.value();
};
EXPECT_THAT(
simulator.Run({{"idx", Value(UBits(0b00, 2))}}),
IsOkAndHolds(make_array_of_values(
{make_array({98, 99}), make_array({3, 4}), make_array({5, 6})})));
EXPECT_THAT(
simulator.Run({{"idx", Value(UBits(0b01, 2))}}),
IsOkAndHolds(make_array_of_values(
{make_array({1, 2}), make_array({98, 99}), make_array({5, 6})})));
EXPECT_THAT(
simulator.Run({{"idx", Value(UBits(0b10, 2))}}),
IsOkAndHolds(make_array_of_values(
{make_array({1, 2}), make_array({3, 4}), make_array({98, 99})})));
EXPECT_THAT(
simulator.Run({{"idx", Value(UBits(0b11, 2))}}),
IsOkAndHolds(make_array_of_values(
{make_array({1, 2}), make_array({3, 4}), make_array({5, 6})})));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdateTupleElements) {
std::string text = R"(
package ArrayUpdate
fn main(idx: bits[2]) -> (bits[32], bits[32])[3] {
literal.17: (bits[32], bits[32])[3] = literal(value=[(1,2),(3,4),(5,6)])
literal.14: (bits[32], bits[32]) = literal(value=(98, 99))
ret array_update.15: (bits[32], bits[32])[3] = array_update(literal.17, literal.14, indices=[idx])
}
)";
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(text));
XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction());
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateCombinationalModule(entry, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
auto make_tuple = [](absl::Span<const int64> values) {
std::vector<Value> elements;
for (auto v : values) {
elements.push_back(Value(UBits(v, 32)));
}
absl::StatusOr<Value> tuple = Value::Tuple(elements);
EXPECT_TRUE(tuple.ok());
return tuple.value();
};
auto make_array_of_values = [&](absl::Span<const Value> values) {
std::vector<Value> elements;
for (auto array : values) {
elements.push_back(array);
}
absl::StatusOr<Value> array_of_values = Value::Array(elements);
EXPECT_TRUE(array_of_values.ok());
return array_of_values.value();
};
EXPECT_THAT(
simulator.Run({{"idx", Value(UBits(0b00, 2))}}),
IsOkAndHolds(make_array_of_values(
{make_tuple({98, 99}), make_tuple({3, 4}), make_tuple({5, 6})})));
EXPECT_THAT(
simulator.Run({{"idx", Value(UBits(0b01, 2))}}),
IsOkAndHolds(make_array_of_values(
{make_tuple({1, 2}), make_tuple({98, 99}), make_tuple({5, 6})})));
EXPECT_THAT(
simulator.Run({{"idx", Value(UBits(0b10, 2))}}),
IsOkAndHolds(make_array_of_values(
{make_tuple({1, 2}), make_tuple({3, 4}), make_tuple({98, 99})})));
EXPECT_THAT(
simulator.Run({{"idx", Value(UBits(0b11, 2))}}),
IsOkAndHolds(make_array_of_values(
{make_tuple({1, 2}), make_tuple({3, 4}), make_tuple({5, 6})})));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdateTupleWithArrayElements) {
std::string text = R"(
package ArrayUpdate
fn main(idx: bits[2]) -> (bits[32], bits[8][2])[2] {
literal.17: (bits[32], bits[8][2])[2] = literal(value=[(1,[2,3]),(4,[5,6])])
literal.14: (bits[32], bits[8][2]) = literal(value=(98, [99, 100]))
ret array_update.15: (bits[32], bits[8][2])[2] = array_update(literal.17, literal.14, indices=[idx])
}
)";
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(text));
XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction());
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateCombinationalModule(entry, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
auto make_array = [](absl::Span<const int64> values) {
std::vector<Value> elements;
for (auto v : values) {
elements.push_back(Value(UBits(v, 8)));
}
absl::StatusOr<Value> array = Value::Array(elements);
EXPECT_TRUE(array.ok());
return array.value();
};
auto make_tuple = [](absl::Span<const Value> values) {
std::vector<Value> elements;
for (auto v : values) {
elements.push_back(v);
}
absl::StatusOr<Value> tuple = Value::Tuple(elements);
EXPECT_TRUE(tuple.ok());
return tuple.value();
};
auto make_array_of_values = [&](absl::Span<const Value> values) {
std::vector<Value> elements;
for (auto array : values) {
elements.push_back(array);
}
absl::StatusOr<Value> array_of_values = Value::Array(elements);
EXPECT_TRUE(array_of_values.ok());
return array_of_values.value();
};
EXPECT_THAT(
simulator.Run({{"idx", Value(UBits(0b01, 2))}}),
IsOkAndHolds(make_array_of_values(
{make_tuple({Value(UBits(1, 32)), make_array({2, 3})}),
make_tuple({Value(UBits(98, 32)), make_array({99, 100})})})));
}
TEST_P(CombinationalGeneratorTest, BuildComplicatedType) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
// Construct some terrible abomination of tuples and arrays.
auto a = fb.Param("a", u8);
auto b = fb.Param("b", u8);
auto c = fb.Param("c", u8);
auto row_0 = fb.Array({a, b}, a.GetType());
auto row_1 = fb.Array({b, a}, a.GetType());
auto ar = fb.Array({row_0, row_1}, row_0.GetType());
auto tuple = fb.Tuple({ar, a});
// Deconstruct it and return some scalar element.
fb.ArrayIndex(fb.ArrayIndex(fb.TupleIndex(tuple, 0), {a}), {c});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.Run({{"a", Value(UBits(0, 8))},
{"b", Value(UBits(42, 8))},
{"c", Value(UBits(1, 8))}}),
IsOkAndHolds(Value(UBits(42, 8))));
}
TEST_P(CombinationalGeneratorTest, ArrayShapedSel) {
VerilogFile file;
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
BValue p = fb.Param("p", package.GetBitsType(8));
BValue x = fb.Param("x", package.GetArrayType(3, package.GetBitsType(8)));
BValue y = fb.Param("y", package.GetArrayType(3, package.GetBitsType(8)));
BValue z = fb.Param("z", package.GetArrayType(3, package.GetBitsType(8)));
BValue d = fb.Param("d", package.GetArrayType(3, package.GetBitsType(8)));
fb.Select(p, {x, y, z}, /*default_value=*/d);
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
XLS_ASSERT_OK_AND_ASSIGN(
Value x_in,
Parser::ParseTypedValue("[bits[8]:0xa, bits[8]:0xb, bits[8]:0xc]"));
XLS_ASSERT_OK_AND_ASSIGN(
Value y_in,
Parser::ParseTypedValue("[bits[8]:0x1, bits[8]:0x2, bits[8]:0x3]"));
XLS_ASSERT_OK_AND_ASSIGN(
Value z_in,
Parser::ParseTypedValue("[bits[8]:0x4, bits[8]:0x5, bits[8]:0x6]"));
XLS_ASSERT_OK_AND_ASSIGN(
Value d_in,
Parser::ParseTypedValue("[bits[8]:0x7, bits[8]:0x8, bits[8]:0x9]"));
EXPECT_THAT(simulator.Run({{"p", Value(UBits(0, 8))},
{"x", x_in},
{"y", y_in},
{"z", z_in},
{"d", d_in}}),
IsOkAndHolds(x_in));
EXPECT_THAT(simulator.Run({{"p", Value(UBits(1, 8))},
{"x", x_in},
{"y", y_in},
{"z", z_in},
{"d", d_in}}),
IsOkAndHolds(y_in));
EXPECT_THAT(simulator.Run({{"p", Value(UBits(2, 8))},
{"x", x_in},
{"y", y_in},
{"z", z_in},
{"d", d_in}}),
IsOkAndHolds(z_in));
EXPECT_THAT(simulator.Run({{"p", Value(UBits(3, 8))},
{"x", x_in},
{"y", y_in},
{"z", z_in},
{"d", d_in}}),
IsOkAndHolds(d_in));
EXPECT_THAT(simulator.Run({{"p", Value(UBits(100, 8))},
{"x", x_in},
{"y", y_in},
{"z", z_in},
{"d", d_in}}),
IsOkAndHolds(d_in));
}
TEST_P(CombinationalGeneratorTest, ArrayShapedSelNoDefault) {
VerilogFile file;
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
BValue p = fb.Param("p", package.GetBitsType(1));
BValue x = fb.Param("x", package.GetArrayType(3, package.GetBitsType(8)));
BValue y = fb.Param("y", package.GetArrayType(3, package.GetBitsType(8)));
fb.Select(p, {x, y});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build());
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
XLS_ASSERT_OK_AND_ASSIGN(
Value x_in,
Parser::ParseTypedValue("[bits[8]:0xa, bits[8]:0xb, bits[8]:0xc]"));
XLS_ASSERT_OK_AND_ASSIGN(
Value y_in,
Parser::ParseTypedValue("[bits[8]:0x1, bits[8]:0x2, bits[8]:0x3]"));
EXPECT_THAT(
simulator.Run({{"p", Value(UBits(0, 1))}, {"x", x_in}, {"y", y_in}}),
IsOkAndHolds(x_in));
EXPECT_THAT(
simulator.Run({{"p", Value(UBits(1, 1))}, {"x", x_in}, {"y", y_in}}),
IsOkAndHolds(y_in));
}
TEST_P(CombinationalGeneratorTest, ArrayConcatArrayOfBits) {
Package package(TestBaseName());
std::string ir_text = R"(
fn f(a0: bits[32][2], a1: bits[32][3]) -> bits[32][7] {
array_concat.3: bits[32][5] = array_concat(a0, a1)
ret array_concat.4: bits[32][7] = array_concat(array_concat.3, a0)
}
)";
XLS_ASSERT_OK_AND_ASSIGN(Function * function,
Parser::ParseFunction(ir_text, &package));
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateCombinationalModule(function, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
XLS_ASSERT_OK_AND_ASSIGN(Value a0, Value::UBitsArray({1, 2}, 32));
XLS_ASSERT_OK_AND_ASSIGN(Value a1, Value::UBitsArray({3, 4, 5}, 32));
XLS_ASSERT_OK_AND_ASSIGN(Value ret,
Value::UBitsArray({1, 2, 3, 4, 5, 1, 2}, 32));
EXPECT_THAT(simulator.Run({{"a0", a0}, {"a1", a1}}), IsOkAndHolds(ret));
}
TEST_P(CombinationalGeneratorTest, ArrayConcatArrayOfBitsMixedOperands) {
Package package(TestBaseName());
std::string ir_text = R"(
fn f(a0: bits[32][2], a1: bits[32][3], a2: bits[32][1]) -> bits[32][7] {
array_concat.4: bits[32][1] = array_concat(a2)
array_concat.5: bits[32][2] = array_concat(array_concat.4, array_concat.4)
array_concat.6: bits[32][7] = array_concat(a0, array_concat.5, a1)
ret array_concat.7: bits[32][7] = array_concat(array_concat.6)
}
)";
XLS_ASSERT_OK_AND_ASSIGN(Function * function,
Parser::ParseFunction(ir_text, &package));
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateCombinationalModule(function, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
XLS_ASSERT_OK_AND_ASSIGN(Value a0, Value::UBitsArray({1, 2}, 32));
XLS_ASSERT_OK_AND_ASSIGN(Value a1, Value::UBitsArray({3, 4, 5}, 32));
XLS_ASSERT_OK_AND_ASSIGN(Value a2, Value::SBitsArray({-1}, 32));
XLS_ASSERT_OK_AND_ASSIGN(Value ret,
Value::SBitsArray({1, 2, -1, -1, 3, 4, 5}, 32));
EXPECT_THAT(simulator.Run({{"a0", a0}, {"a1", a1}, {"a2", a2}}),
IsOkAndHolds(ret));
}
TEST_P(CombinationalGeneratorTest, InterpretArrayConcatArraysOfArrays) {
Package package(TestBaseName());
std::string ir_text = R"(
fn f() -> bits[32][2][3] {
literal.1: bits[32][2][2] = literal(value=[[1, 2], [3, 4]])
literal.2: bits[32][2][1] = literal(value=[[5, 6]])
ret array_concat.3: bits[32][2][3] = array_concat(literal.2, literal.1)
}
)";
XLS_ASSERT_OK_AND_ASSIGN(Function * function,
Parser::ParseFunction(ir_text, &package));
XLS_ASSERT_OK_AND_ASSIGN(
auto result, GenerateCombinationalModule(function, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
XLS_ASSERT_OK_AND_ASSIGN(Value ret,
Value::SBits2DArray({{5, 6}, {1, 2}, {3, 4}}, 32));
std::vector<Value> args;
EXPECT_THAT(simulator.Run(args), IsOkAndHolds(ret));
}
TEST_P(CombinationalGeneratorTest, SimpleProc) {
const std::string ir_text = R"(package test
chan in(my_in: bits[32], id=0, kind=single_value, ops=receive_only,
metadata="""module_port { flopped: false, port_order: 1 }""")
chan out(my_out: bits[32], id=1, kind=single_value, ops=send_only,
metadata="""module_port { flopped: false, port_order: 0 }""")
proc my_proc(my_token: token, my_state: (), init=()) {
rcv: (token, bits[32]) = receive(my_token, channel_id=0)
data: bits[32] = tuple_index(rcv, index=1)
negate: bits[32] = neg(data)
rcv_token: token = tuple_index(rcv, index=0)
send: token = send(rcv_token, data=[negate], channel_id=1)
next (send, my_state)
}
)";
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(ir_text));
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, package->GetProc("my_proc"));
XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModuleFromProc(
proc, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.RunAndReturnSingleOutput({{"my_in", SBits(10, 32)}}),
IsOkAndHolds(SBits(-10, 32)));
EXPECT_THAT(simulator.RunAndReturnSingleOutput({{"my_in", SBits(0, 32)}}),
IsOkAndHolds(SBits(0, 32)));
}
TEST_P(CombinationalGeneratorTest, ProcWithMultipleInputChannels) {
const std::string ir_text = R"(package test
chan in0(my_in0: bits[32], id=0, kind=single_value, ops=receive_only,
metadata="""module_port { flopped: false, port_order: 0 }""")
chan in1(my_in1: bits[32], id=1, kind=single_value, ops=receive_only,
metadata="""module_port { flopped: false, port_order: 2 }""")
chan in2(my_in2: bits[32], id=2, kind=single_value, ops=receive_only,
metadata="""module_port { flopped: false, port_order: 1 }""")
chan out(my_out: bits[32], id=3, kind=single_value, ops=send_only,
metadata="""module_port { flopped: false, port_order: 0 }""")
proc my_proc(my_token: token, my_state: (), init=()) {
rcv0: (token, bits[32]) = receive(my_token, channel_id=0)
rcv0_token: token = tuple_index(rcv0, index=0)
rcv1: (token, bits[32]) = receive(rcv0_token, channel_id=1)
rcv1_token: token = tuple_index(rcv1, index=0)
rcv2: (token, bits[32]) = receive(rcv1_token, channel_id=2)
rcv2_token: token = tuple_index(rcv2, index=0)
data0: bits[32] = tuple_index(rcv0, index=1)
data1: bits[32] = tuple_index(rcv1, index=1)
data2: bits[32] = tuple_index(rcv2, index=1)
neg_data1: bits[32] = neg(data1)
two: bits[32] = literal(value=2)
data2_times_two: bits[32] = umul(data2, two)
tmp: bits[32] = add(neg_data1, data2_times_two)
sum: bits[32] = add(tmp, data0)
send: token = send(rcv2_token, data=[sum], channel_id=3)
next (send, my_state)
}
)";
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(ir_text));
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, package->GetProc("my_proc"));
XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModuleFromProc(
proc, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
// The computed expression is: my_out = my_in0 - my_in1 + 2 * my_in2
EXPECT_THAT(simulator.RunAndReturnSingleOutput({{"my_in0", UBits(10, 32)},
{"my_in1", SBits(7, 32)},
{"my_in2", SBits(42, 32)}}),
IsOkAndHolds(UBits(87, 32)));
}
TEST_P(CombinationalGeneratorTest, ProcWithMultipleOutputChannels) {
const std::string ir_text = R"(package test
chan in(my_in: bits[32], id=0, kind=single_value, ops=receive_only,
metadata="""module_port { flopped: false, port_order: 1 }""")
chan out0(my_out0: bits[32], id=1, kind=single_value, ops=send_only,
metadata="""module_port { flopped: false, port_order: 0 }""")
chan out1(my_out1: bits[32], id=2, kind=single_value, ops=send_only,
metadata="""module_port { flopped: false, port_order: 2 }""")
proc my_proc(my_token: token, my_state: (), init=()) {
rcv: (token, bits[32]) = receive(my_token, channel_id=0)
data: bits[32] = tuple_index(rcv, index=1)
negate: bits[32] = neg(data)
rcv_token: token = tuple_index(rcv, index=0)
send0: token = send(rcv_token, data=[data], channel_id=1)
send1: token = send(send0, data=[negate], channel_id=2)
next (send1, my_state)
}
)";
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(ir_text));
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, package->GetProc("my_proc"));
XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModuleFromProc(
proc, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.Run({{"my_in", SBits(10, 32)}}),
IsOkAndHolds(ModuleSimulator::BitsMap(
{{"my_out0", SBits(10, 32)}, {"my_out1", SBits(-10, 32)}})));
}
TEST_P(CombinationalGeneratorTest, NToOneMuxProc) {
Package package(TestBaseName());
ProcBuilder pb(TestBaseName(), /*init_value=*/Value::Tuple({}),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
const int64 kInputCount = 4;
const int64 kSelectorBitCount = 2;
Type* data_type = package.GetBitsType(32);
Type* bit_type = package.GetBitsType(1);
Type* selector_type = package.GetBitsType(kSelectorBitCount);
int64 port_order = 0;
auto make_channel_metadata = [&port_order]() {
ChannelMetadataProto metadata;
metadata.mutable_module_port()->set_flopped(false);
metadata.mutable_module_port()->set_port_order(port_order++);
return metadata;
};
BValue token = pb.GetTokenParam();
// Sends the given data over the given channel. Threads 'token' through the
// Send operation.
auto make_send = [&](Channel* ch, BValue data) {
BValue send = pb.Send(ch, token, {data});
token = send;
return send;
};
// Adds a receive instruction and returns the data BValue. Threads 'token'
// through the Receive operation.
auto make_receive = [&](Channel* ch) {
BValue receive = pb.Receive(ch, token);
token = pb.TupleIndex(receive, 0);
return pb.TupleIndex(receive, 1);
};
// Add the selector module port which selects which input to forward.
XLS_ASSERT_OK_AND_ASSIGN(
Channel * selector_channel,
package.CreateSingleValueChannel(
"selector", Channel::SupportedOps::kReceiveOnly,
{DataElement{.name = "selector", .type = selector_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
BValue selector = make_receive(selector_channel);
// Add the output ready channel. It's an input and will be used to generate
// the input ready outputs.
XLS_ASSERT_OK_AND_ASSIGN(
Channel * out_ready_channel,
package.CreateSingleValueChannel(
"out_rdy", Channel::SupportedOps::kReceiveOnly,
{DataElement{.name = "out_rdy", .type = bit_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
BValue output_ready = make_receive(out_ready_channel);
// Generate all the input ports and their ready/valid signals.
std::vector<BValue> input_datas;
std::vector<BValue> input_valids;
for (int64 i = 0; i < kInputCount; ++i) {
XLS_ASSERT_OK_AND_ASSIGN(
Channel * data_channel,
package.CreateSingleValueChannel(
absl::StrFormat("in_%d", i), Channel::SupportedOps::kReceiveOnly,
{DataElement{.name = absl::StrFormat("in_%d", i),
.type = data_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
input_datas.push_back(make_receive(data_channel));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * valid_channel,
package.CreateSingleValueChannel(
absl::StrFormat("in_%d_vld", i),
Channel::SupportedOps::kReceiveOnly,
{DataElement{.name = absl::StrFormat("in_%d_vld", i),
.type = bit_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
input_valids.push_back(make_receive(valid_channel));
BValue ready = pb.And(
output_ready, pb.Eq(selector, pb.Literal(UBits(i, kSelectorBitCount))));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * ready_channel,
package.CreateSingleValueChannel(
absl::StrFormat("in_%d_rdy", i), Channel::SupportedOps::kSendOnly,
{DataElement{.name = absl::StrFormat("in_%d_rdy", i),
.type = bit_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
make_send(ready_channel, ready);
}
// Output data is a select amongst the input data.
XLS_ASSERT_OK_AND_ASSIGN(Channel * out_data_channel,
package.CreateSingleValueChannel(
"out", Channel::SupportedOps::kSendOnly,
{DataElement{.name = "out", .type = data_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
make_send(out_data_channel, pb.Select(selector, /*cases=*/input_datas));
// Output valid is a select amongs the input valid signals.
XLS_ASSERT_OK_AND_ASSIGN(
Channel * out_valid_channel,
package.CreateSingleValueChannel(
"out_vld", Channel::SupportedOps::kSendOnly,
{DataElement{.name = "out_vld", .type = bit_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
make_send(out_valid_channel, pb.Select(selector, /*cases=*/input_valids));
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(token, pb.GetStateParam()));
XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModuleFromProc(
proc, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
}
TEST_P(CombinationalGeneratorTest, OneToNMuxProc) {
Package package(TestBaseName());
ProcBuilder pb(TestBaseName(), /*init_value=*/Value::Tuple({}),
/*token_name=*/"tkn", /*state_name=*/"st", &package);
const int64 kOutputCount = 4;
const int64 kSelectorBitCount = 2;
Type* data_type = package.GetBitsType(32);
Type* bit_type = package.GetBitsType(1);
Type* selector_type = package.GetBitsType(kSelectorBitCount);
int64 port_order = 0;
auto make_channel_metadata = [&port_order]() {
ChannelMetadataProto metadata;
metadata.mutable_module_port()->set_flopped(false);
metadata.mutable_module_port()->set_port_order(port_order++);
return metadata;
};
BValue token = pb.GetTokenParam();
// Sends the given data over the given channel. Threads 'token' through the
// Send operation.
auto make_send = [&](Channel* ch, BValue data) {
BValue send = pb.Send(ch, token, {data});
token = send;
return send;
};
// Adds a receive instruction and returns the data BValue. Threads 'token'
// through the Receive operation.
auto make_receive = [&](Channel* ch) {
BValue receive = pb.Receive(ch, token);
token = pb.TupleIndex(receive, 0);
return pb.TupleIndex(receive, 1);
};
// Add the selector module port which selects which input to forward.
XLS_ASSERT_OK_AND_ASSIGN(
Channel * selector_channel,
package.CreateSingleValueChannel(
"selector", Channel::SupportedOps::kReceiveOnly,
{DataElement{.name = "selector", .type = selector_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
BValue selector = make_receive(selector_channel);
// Add the input data channel.
XLS_ASSERT_OK_AND_ASSIGN(Channel * input_data_channel,
package.CreateSingleValueChannel(
"in", Channel::SupportedOps::kReceiveOnly,
{DataElement{.name = "in", .type = data_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
BValue input = make_receive(input_data_channel);
// Add the input valid channel. It's an input and will be used to generate
// the output valid outputs.
XLS_ASSERT_OK_AND_ASSIGN(
Channel * input_valid_channel,
package.CreateSingleValueChannel(
"in_vld", Channel::SupportedOps::kReceiveOnly,
{DataElement{.name = "in_vld", .type = bit_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
BValue input_valid = make_receive(input_valid_channel);
// Generate all the output ports and their ready/valid signals.
std::vector<BValue> output_readys;
for (int64 i = 0; i < kOutputCount; ++i) {
XLS_ASSERT_OK_AND_ASSIGN(
Channel * data_channel,
package.CreateSingleValueChannel(
absl::StrFormat("out_%d", i), Channel::SupportedOps::kSendOnly,
{DataElement{.name = absl::StrFormat("out_%d", i),
.type = data_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
make_send(data_channel, input);
XLS_ASSERT_OK_AND_ASSIGN(
Channel * ready_channel,
package.CreateSingleValueChannel(
absl::StrFormat("out_%d_rdy", i),
Channel::SupportedOps::kReceiveOnly,
{DataElement{.name = absl::StrFormat("out_%d_rdy", i),
.type = bit_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
output_readys.push_back(make_receive(ready_channel));
BValue valid = pb.And(
input_valid, pb.Eq(selector, pb.Literal(UBits(i, kSelectorBitCount))));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * valid_channel,
package.CreateSingleValueChannel(
absl::StrFormat("out_%d_vld", i), Channel::SupportedOps::kSendOnly,
{DataElement{.name = absl::StrFormat("out_%d_vld", i),
.type = bit_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
make_send(valid_channel, valid);
}
// Output ready is a select amongs the input ready signals.
XLS_ASSERT_OK_AND_ASSIGN(
Channel * input_ready_channel,
package.CreateSingleValueChannel(
"in_rdy", Channel::SupportedOps::kSendOnly,
{DataElement{.name = "in_rdy", .type = bit_type}},
/*id=*/absl::nullopt, make_channel_metadata()));
make_send(input_ready_channel, pb.Select(selector, /*cases=*/output_readys));
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(token, pb.GetStateParam()));
XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModuleFromProc(
proc, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
}
TEST_P(CombinationalGeneratorTest, ArrayIndexSimpleArray) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
Type* u16 = package.GetBitsType(16);
auto a = fb.Param("a", package.GetArrayType(3, u8));
auto idx = fb.Param("idx", u16);
auto ret = fb.ArrayIndex(a, {idx});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.Run({{"a", Value::UBitsArray({11, 22, 33}, 8).value()},
{"idx", Value(UBits(2, 16))}}),
IsOkAndHolds(Value(UBits(33, 8))));
}
TEST_P(CombinationalGeneratorTest, ArrayIndexNilIndex) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", package.GetArrayType(3, u8));
auto ret = fb.ArrayIndex(a, {});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(
simulator.Run({{"a", Value::UBitsArray({11, 22, 33}, 8).value()}}),
IsOkAndHolds(Value::UBitsArray({11, 22, 33}, 8).value()));
}
TEST_P(CombinationalGeneratorTest, ArrayIndex2DArrayIndexSingleElement) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
Type* u16 = package.GetBitsType(16);
auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8)));
auto idx0 = fb.Param("idx0", u16);
auto idx1 = fb.Param("idx1", u16);
auto ret = fb.ArrayIndex(a, {idx0, idx1});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"idx0", Value(UBits(0, 16))},
{"idx1", Value(UBits(1, 16))}}),
IsOkAndHolds(Value(UBits(22, 8))));
}
TEST_P(CombinationalGeneratorTest, ArrayIndex2DArrayIndexSubArray) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
Type* u16 = package.GetBitsType(16);
auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8)));
auto idx = fb.Param("idx", u16);
auto ret = fb.ArrayIndex(a, {idx});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"idx", Value(UBits(0, 16))}}),
IsOkAndHolds(Value::UBitsArray({11, 22, 33}, 8).value()));
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"idx", Value(UBits(1, 16))}}),
IsOkAndHolds(Value::UBitsArray({44, 55, 66}, 8).value()));
// Out-of-bounds index should return the max element.
// TODO(meheff): Handle when out-of-bounds access is handled.
// EXPECT_THAT(
// simulator.Run(
// {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}},
// 8).value()},
// {"idx", Value(UBits(42, 16))}}),
// IsOkAndHolds(
// Value::UBitsArray({44, 55, 66}, 8).value()));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdateLiteralIndex) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", package.GetArrayType(3, u8));
auto update_value = fb.Param("value", u8);
auto idx = fb.Literal(UBits(1, 16));
auto ret = fb.ArrayUpdate(a, update_value, {idx});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.Run({{"a", Value::UBitsArray({11, 22, 33}, 8).value()},
{"value", Value(UBits(123, 8))}}),
IsOkAndHolds(Value::UBitsArray({11, 123, 33}, 8).value()));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdateVariableIndex) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", package.GetArrayType(3, u8));
auto update_value = fb.Param("value", u8);
auto idx = fb.Param("idx", package.GetBitsType(32));
auto ret = fb.ArrayUpdate(a, update_value, {idx});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.Run({{"a", Value::UBitsArray({11, 22, 33}, 8).value()},
{"idx", Value(UBits(0, 32))},
{"value", Value(UBits(123, 8))}}),
IsOkAndHolds(Value::UBitsArray({123, 22, 33}, 8).value()));
// Out-of-bounds should just return the original array.
EXPECT_THAT(simulator.Run({{"a", Value::UBitsArray({11, 22, 33}, 8).value()},
{"idx", Value(UBits(3, 32))},
{"value", Value(UBits(123, 8))}}),
IsOkAndHolds(Value::UBitsArray({11, 22, 33}, 8).value()));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdate2DLiteralIndex) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8)));
auto update_value = fb.Param("value", u8);
auto idx0 = fb.Literal(UBits(0, 32));
auto idx1 = fb.Literal(UBits(2, 14));
auto ret = fb.ArrayUpdate(a, update_value, {idx0, idx1});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"value", Value(UBits(123, 8))}}),
IsOkAndHolds(
Value::UBits2DArray({{11, 22, 123}, {44, 55, 66}}, 8).value()));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdate2DVariableIndex) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8)));
auto update_value = fb.Param("value", u8);
auto idx0 = fb.Param("idx0", package.GetBitsType(32));
auto idx1 = fb.Param("idx1", package.GetBitsType(32));
auto ret = fb.ArrayUpdate(a, update_value, {idx0, idx1});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"value", Value(UBits(123, 8))},
{"idx0", Value(UBits(1, 32))},
{"idx1", Value(UBits(0, 32))}}),
IsOkAndHolds(
Value::UBits2DArray({{11, 22, 33}, {123, 55, 66}}, 8).value()));
// Out-of-bounds should just return the original array.
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"value", Value(UBits(123, 8))},
{"idx0", Value(UBits(1, 32))},
{"idx1", Value(UBits(44, 32))}}),
IsOkAndHolds(
Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()));
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"value", Value(UBits(123, 8))},
{"idx0", Value(UBits(11, 32))},
{"idx1", Value(UBits(0, 32))}}),
IsOkAndHolds(
Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdate2DLiteralAndVariableIndex) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8)));
auto update_value = fb.Param("value", u8);
auto idx0 = fb.Param("idx", package.GetBitsType(32));
auto idx1 = fb.Literal(UBits(2, 14));
auto ret = fb.ArrayUpdate(a, update_value, {idx0, idx1});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"value", Value(UBits(123, 8))},
{"idx", Value(UBits(0, 32))}}),
IsOkAndHolds(
Value::UBits2DArray({{11, 22, 123}, {44, 55, 66}}, 8).value()));
// Out-of-bounds should just return the original array.
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"value", Value(UBits(123, 8))},
{"idx", Value(UBits(10, 32))}}),
IsOkAndHolds(
Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdate2DUpdateArrayLiteralIndex) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8)));
auto update_value = fb.Param("value", package.GetArrayType(3, u8));
auto idx = fb.Literal(UBits(1, 14));
auto ret = fb.ArrayUpdate(a, update_value, {idx});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"value", Value::UBitsArray({101, 102, 103}, 8).value()}}),
IsOkAndHolds(
Value::UBits2DArray({{11, 22, 33}, {101, 102, 103}}, 8).value()));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdate2DUpdateArrayVariableIndex) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8)));
auto update_value = fb.Param("value", package.GetArrayType(3, u8));
auto idx = fb.Param("idx", package.GetBitsType(37));
auto ret = fb.ArrayUpdate(a, update_value, {idx});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"value", Value::UBitsArray({101, 102, 103}, 8).value()},
{"idx", Value(UBits(1, 37))}}),
IsOkAndHolds(
Value::UBits2DArray({{11, 22, 33}, {101, 102, 103}}, 8).value()));
// Out-of-bounds should just return the original array.
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"value", Value::UBitsArray({101, 102, 103}, 8).value()},
{"idx", Value(UBits(2, 37))}}),
IsOkAndHolds(
Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdate2DUpdateArrayNilIndex) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8)));
auto update_value =
fb.Param("value", package.GetArrayType(2, package.GetArrayType(3, u8)));
auto ret = fb.ArrayUpdate(a, update_value, {});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(
simulator.Run(
{{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()},
{"value", Value::UBits2DArray({{101, 102, 103}, {104, 105, 106}}, 8)
.value()}}),
IsOkAndHolds(
Value::UBits2DArray({{101, 102, 103}, {104, 105, 106}}, 8).value()));
}
TEST_P(CombinationalGeneratorTest, ArrayUpdateBitsNilIndex) {
Package package(TestBaseName());
FunctionBuilder fb(TestBaseName(), &package);
Type* u8 = package.GetBitsType(8);
auto a = fb.Param("a", u8);
auto update_value = fb.Param("value", u8);
auto ret = fb.ArrayUpdate(a, update_value, {});
XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret));
XLS_ASSERT_OK_AND_ASSIGN(auto result,
GenerateCombinationalModule(f, UseSystemVerilog()));
ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath),
result.verilog_text);
ModuleSimulator simulator(result.signature, result.verilog_text,
GetSimulator());
EXPECT_THAT(simulator.RunAndReturnSingleOutput(
{{"a", UBits(11, 8)}, {"value", UBits(22, 8)}}),
IsOkAndHolds(UBits(22, 8)));
}
INSTANTIATE_TEST_SUITE_P(CombinationalGeneratorTestInstantiation,
CombinationalGeneratorTest,
testing::ValuesIn(kDefaultSimulationTargets),
ParameterizedTestName<CombinationalGeneratorTest>);
} // namespace
} // namespace verilog
} // namespace xls
| 67,167 | 24,812 |
/*************************************************************************/
/* memory_pool_dynamic_static.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "memory_pool_dynamic_static.h"
#include "os/memory.h"
#include "os/os.h"
#include "ustring.h"
#include "print_string.h"
#include <stdio.h>
MemoryPoolDynamicStatic::Chunk *MemoryPoolDynamicStatic::get_chunk(ID p_id) {
uint64_t check = p_id/MAX_CHUNKS;
uint64_t idx = p_id%MAX_CHUNKS;
if (!chunk[idx].mem || chunk[idx].check!=check)
return NULL;
return &chunk[idx];
}
const MemoryPoolDynamicStatic::Chunk *MemoryPoolDynamicStatic::get_chunk(ID p_id) const {
uint64_t check = p_id/MAX_CHUNKS;
uint64_t idx = p_id%MAX_CHUNKS;
if (!chunk[idx].mem || chunk[idx].check!=check)
return NULL;
return &chunk[idx];
}
MemoryPoolDynamic::ID MemoryPoolDynamicStatic::alloc(size_t p_amount,const char* p_description) {
_THREAD_SAFE_METHOD_
int idx=-1;
for (int i=0;i<MAX_CHUNKS;i++) {
last_alloc++;
if (last_alloc>=MAX_CHUNKS)
last_alloc=0;
if ( !chunk[last_alloc].mem ) {
idx=last_alloc;
break;
}
}
if (idx==-1) {
ERR_EXPLAIN("Out of dynamic Memory IDs");
ERR_FAIL_V(INVALID_ID);
//return INVALID_ID;
}
//chunk[idx].mem = Memory::alloc_static(p_amount,p_description);
chunk[idx].mem = memalloc(p_amount);
if (!chunk[idx].mem)
return INVALID_ID;
chunk[idx].size=p_amount;
chunk[idx].check=++last_check;
chunk[idx].descr=p_description;
chunk[idx].lock=0;
total_usage+=p_amount;
if (total_usage>max_usage)
max_usage=total_usage;
ID id = chunk[idx].check*MAX_CHUNKS + (uint64_t)idx;
return id;
}
void MemoryPoolDynamicStatic::free(ID p_id) {
_THREAD_SAFE_METHOD_
Chunk *c = get_chunk(p_id);
ERR_FAIL_COND(!c);
total_usage-=c->size;
memfree(c->mem);
c->mem=0;
if (c->lock>0) {
ERR_PRINT("Freed ID Still locked");
}
}
Error MemoryPoolDynamicStatic::realloc(ID p_id, size_t p_amount) {
_THREAD_SAFE_METHOD_
Chunk *c = get_chunk(p_id);
ERR_FAIL_COND_V(!c,ERR_INVALID_PARAMETER);
ERR_FAIL_COND_V(c->lock > 0 , ERR_LOCKED );
void * new_mem = memrealloc(c->mem,p_amount);
ERR_FAIL_COND_V(!new_mem,ERR_OUT_OF_MEMORY);
total_usage-=c->size;
c->mem=new_mem;
c->size=p_amount;
total_usage+=c->size;
if (total_usage>max_usage)
max_usage=total_usage;
return OK;
}
bool MemoryPoolDynamicStatic::is_valid(ID p_id) {
_THREAD_SAFE_METHOD_
Chunk *c = get_chunk(p_id);
return c!=NULL;
}
size_t MemoryPoolDynamicStatic::get_size(ID p_id) const {
_THREAD_SAFE_METHOD_
const Chunk *c = get_chunk(p_id);
ERR_FAIL_COND_V(!c,0);
return c->size;
}
const char* MemoryPoolDynamicStatic::get_description(ID p_id) const {
_THREAD_SAFE_METHOD_
const Chunk *c = get_chunk(p_id);
ERR_FAIL_COND_V(!c,"");
return c->descr;
}
bool MemoryPoolDynamicStatic::is_locked(ID p_id) const {
_THREAD_SAFE_METHOD_
const Chunk *c = get_chunk(p_id);
ERR_FAIL_COND_V(!c,false);
return c->lock>0;
}
Error MemoryPoolDynamicStatic::lock(ID p_id) {
_THREAD_SAFE_METHOD_
Chunk *c = get_chunk(p_id);
ERR_FAIL_COND_V(!c,ERR_INVALID_PARAMETER);
c->lock++;
return OK;
}
void * MemoryPoolDynamicStatic::get(ID p_id) {
_THREAD_SAFE_METHOD_
const Chunk *c = get_chunk(p_id);
ERR_FAIL_COND_V(!c,NULL);
ERR_FAIL_COND_V( c->lock==0, NULL );
return c->mem;
}
Error MemoryPoolDynamicStatic::unlock(ID p_id) {
_THREAD_SAFE_METHOD_
Chunk *c = get_chunk(p_id);
ERR_FAIL_COND_V(!c,ERR_INVALID_PARAMETER);
ERR_FAIL_COND_V( c->lock<=0, ERR_INVALID_PARAMETER );
c->lock--;
return OK;
}
size_t MemoryPoolDynamicStatic::get_available_mem() const {
return Memory::get_static_mem_available();
}
size_t MemoryPoolDynamicStatic::get_total_usage() const {
_THREAD_SAFE_METHOD_
return total_usage;
}
MemoryPoolDynamicStatic::MemoryPoolDynamicStatic() {
last_check=1;
last_alloc=0;
total_usage=0;
max_usage=0;
}
MemoryPoolDynamicStatic::~MemoryPoolDynamicStatic() {
#ifdef DEBUG_MEMORY_ENABLED
if (OS::get_singleton()->is_stdout_verbose()) {
if (total_usage>0) {
ERR_PRINT("DYNAMIC ALLOC: ** MEMORY LEAKS DETECTED **");
ERR_PRINT(String("DYNAMIC ALLOC: "+String::num(total_usage)+" bytes of memory in use at exit.").ascii().get_data());
ERR_PRINT("DYNAMIC ALLOC: Following is the list of leaked allocations:");
for (int i=0;i<MAX_CHUNKS;i++) {
if (chunk[i].mem) {
ERR_PRINT(String("\t"+String::num(chunk[i].size)+" bytes - "+String(chunk[i].descr)).ascii().get_data());
}
}
ERR_PRINT("DYNAMIC ALLOC: End of Report.");
print_line("INFO: dynmem - max: "+itos(max_usage)+", "+itos(total_usage)+" leaked.");
} else {
print_line("INFO: dynmem - max: "+itos(max_usage)+", no leaks.");
}
}
#endif
}
| 6,680 | 2,582 |
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "subsystems/subsystem_Arm.h"
subsystem_Arm::subsystem_Arm() : m_ArmMotor{ArmConstants::ArmMotorPort, rev::CANSparkMax::MotorType::kBrushless}{
//arm motor set up
double kP = 1, kI = 0, kD = 0, kIz = 0, kFF = 0, kMaxOutput = .3, kMinOutput = -.3;
m_ArmPidController.SetP(kP);
m_ArmPidController.SetI(kI);
m_ArmPidController.SetD(kD);
m_ArmPidController.SetIZone(kIz);
m_ArmPidController.SetFF(kFF);
m_ArmPidController.SetOutputRange(kMinOutput, kMaxOutput);
m_ArmPidController.SetSmartMotionAccelStrategy(rev::CANPIDController::AccelStrategy::kTrapezoidal, 0);
m_ArmPidController.SetSmartMotionMaxAccel(ArmConstants::ArmAcceleration);
m_ArmPidController.SetSmartMotionMaxVelocity(ArmConstants::ArmVelocity);
m_ArmEncoder.SetPosition(0);
m_ArmMotor.SetInverted(true);
// m_ArmEncoder.SetInverted(true);
//built_different
//thing
}
/*moves the position of the arm by the inputed amount of ticks.
0 ticks is the arm in the horizontal position */
void subsystem_Arm::SetArmPosition(int ticks){
m_ArmPidController.SetReference(ticks, rev::ControlType::kPosition,0);
}
// This method will be called once per scheduler run
void subsystem_Arm::Periodic() {
frc::SmartDashboard::PutNumber("POSITION", m_ArmEncoder.GetPosition());
frc::SmartDashboard::PutNumber("CURRENT", m_ArmMotor.GetOutputCurrent());
//Stall prevention, checks the current of the motor to make sure that it isn't stuck
if(m_ArmMotor.GetOutputCurrent() > 100){
SetArmPosition(ArmConstants::ArmTicksUp);
}
}
| 1,780 | 643 |
// tests execution with different flags
#include "regexp-executor.hpp"
#include "catch.hpp"
namespace e = regulator::executor;
namespace f = regulator::fuzz;
TEST_CASE( "compile and exec with case-insensitive (8-bit)" )
{
v8::Isolate *isolate = regulator::executor::Initialize();
v8::HandleScope scope(isolate);
v8::Local<v8::Context> ctx = v8::Context::New(isolate);
ctx->Enter();
e::V8RegExp regexp;
std::string sz_regexp = "foo.+bar";
e::Result compile_result_status = e::Compile(sz_regexp.c_str(), "i", ®exp);
REQUIRE( compile_result_status == e::kSuccess );
REQUIRE_FALSE( regexp.regexp.is_null() );
uint8_t negative_subject[] = {
'f',
'f',
'o',
'o',
'b',
'a',
'r'
};
uint8_t positive_subject[] = {
'f',
'F',
'o',
'O',
'_',
'B',
'a',
'R',
'x'
};
e::Result exec_result_status;
e::V8RegExpResult exec_result;
exec_result_status = e::Exec(
®exp,
negative_subject,
sizeof(negative_subject),
exec_result,
e::kOnlyOneByte
);
REQUIRE( exec_result_status == e::kSuccess );
REQUIRE( exec_result.match_success == false );
exec_result_status = e::Exec(
®exp,
positive_subject,
sizeof(positive_subject),
exec_result,
e::kOnlyOneByte
);
REQUIRE( exec_result_status == e::kSuccess );
REQUIRE( exec_result.match_success == true );
}
TEST_CASE( "compile and exec with sticky bit " )
{
}
| 1,598 | 567 |
// dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications)
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
// Implemented features:
// [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. ImGui::IsKeyPressed(VK_SPACE).
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
#pragma once
#include <windows.h>
IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd);
IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown();
IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame();
// Configuration
// - Disable gamepad support or linking with xinput.lib
//#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
//#define IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT
// Win32 message handler
// - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on <windows.h>
// - You can COPY this line into your .cpp code to forward declare the function.
IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// DPI-related helpers (optional)
// - Use to enable DPI awareness without having to create an application manifest.
// - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps.
// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc.
// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime,
// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies.
IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness();
IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd
IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor
| 2,459 | 800 |
namespace stk
{
template<typename T>
VolumeHelper<T> normalize(const VolumeHelper<T>& src,
T min,
T max,
VolumeHelper<T>* out)
{
T src_min, src_max;
find_min_max(src, src_min, src_max);
dim3 dims = src.size();
VolumeHelper<T> dest;
if (!out) {
dest.allocate(src.size());
out = &dest;
}
ASSERT(out->size() == dims);
out->copy_meta_from(src);
double range = double(max - min);
double src_range = double(src_max - src_min);
#pragma omp parallel for
for (int z = 0; z < int(dims.z); ++z) {
for (int y = 0; y < int(dims.y); ++y) {
for (int x = 0; x < int(dims.x); ++x) {
(*out)(x,y,z) = T(range * (src(x, y, z) - src_min) / src_range + min);
}
}
}
return *out;
}
}
| 983 | 329 |
//!
//! Copyright (c) 2021, The casual project
//!
//! This software is licensed under the MIT license, https://opensource.org/licenses/MIT
//!
#include "transaction/manager/transform.h"
#include "transaction/common.h"
#include "common/event/send.h"
#include "common/environment.h"
#include "common/environment/normalize.h"
#include "common/algorithm/coalesce.h"
#include "configuration/system.h"
namespace casual
{
using namespace common;
namespace transaction::manager::transform
{
namespace local
{
namespace
{
template< typename T>
std::filesystem::path initialize_log( T configuration)
{
Trace trace{ "transaction::manager::transfrom::local::initialize_log"};
if( ! configuration.empty())
return common::environment::expand( std::move( configuration));
auto file = environment::directory::transaction() / "log.db";
// TODO: remove this in 2.0 (that exist to be backward compatible)
{
// if the wanted path exists, we can't overwrite with the old
if( std::filesystem::exists( file))
return file;
auto old = environment::directory::domain() / "transaction" / "log.db";
if( std::filesystem::exists( old))
{
std::filesystem::rename( old, file);
event::notification::send( "transaction log file moved: ", std::filesystem::relative( old), " -> ", std::filesystem::relative( file));
log::line( log::category::warning, "transaction log file moved: ", old, " -> ", file);
}
}
return file;
};
auto resources = []( auto&& resources, const auto& properties)
{
Trace trace{ "transaction::manager::transform::local::resources"};
auto transform_resource = []( const auto& configuration)
{
state::resource::Proxy result{ configuration};
// make sure we've got a name
result.configuration.name = common::algorithm::coalesce(
std::move( result.configuration.name),
common::string::compose( ".rm.", result.configuration.key, '.', result.id));
return result;
};
auto validate = [&]( const auto& r)
{
if( common::algorithm::find( properties, r.key))
return true;
common::event::error::fatal::send( code::casual::invalid_argument, "failed to correlate resource key: '", r.key, "'");
return false;
};
std::vector< state::resource::Proxy> result;
common::algorithm::transform_if(
resources,
result,
transform_resource,
validate);
return result;
};
} // <unnamed>
} // local
State state( casual::configuration::Model model)
{
Trace trace{ "transaction::manager::transform::state"};
State state;
state.persistent.log = decltype( state.persistent.log){ local::initialize_log( std::move( model.transaction.log))};
auto get_system = []( auto system)
{
if( system != decltype( system){})
return system;
// TODO deprecated, will be removed at some point
return configuration::system::get();
};
state.system.configuration = get_system( std::move( model.system));
state.resources = local::resources( model.transaction.resources, state.system.configuration.resources);
for( auto& mapping : model.transaction.mappings)
{
state.alias.configuration.emplace( mapping.alias, algorithm::transform( mapping.resources, [&state]( auto& name)
{
return state.get_resource( name).id;
}));
}
return state;
}
} // transaction::manager::transform
} // casual | 4,284 | 1,052 |
#include "util/codec_util.h"
#include <cassert>
#include <string.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/md5.h>
#include "util/file_util.h"
#include "util/sha1.h"
#include <openssl/sha.h>
namespace qcloud_cos {
#define REVERSE_HEX(c) ( ((c) >= 'A') ? ((c) & 0xDF) - 'A' + 10 : (c) - '0' )
#define HMAC_LENGTH 20
unsigned char CodecUtil::ToHex(const unsigned char& x) {
return x > 9 ? (x - 10 + 'A') : x + '0';
}
void CodecUtil::BinToHex(const unsigned char *bin,unsigned int binLen, char *hex) {
for(unsigned int i = 0; i < binLen; ++i) {
hex[i<<1] = ToHex(bin[i] >> 4);
hex[(i<<1)+1] = ToHex(bin[i] & 15 );
}
}
std::string CodecUtil::EncodeKey(const std::string& key) {
std::string encodedKey = "";
std::size_t length = key.length();
for (size_t i = 0; i < length; ++i) {
if (isalnum((unsigned char)key[i]) ||
(key[i] == '-') ||
(key[i] == '_') ||
(key[i] == '.') ||
(key[i] == '~') ||
(key[i] == '/')) {
encodedKey += key[i];
} else {
encodedKey += '%';
encodedKey += ToHex((unsigned char)key[i] >> 4);
encodedKey += ToHex((unsigned char)key[i] % 16);
}
}
return encodedKey;
}
std::string CodecUtil::UrlEncode(const std::string& str) {
std::string encodedUrl = "";
std::size_t length = str.length();
for (size_t i = 0; i < length; ++i) {
if (isalnum((unsigned char)str[i]) ||
(str[i] == '-') ||
(str[i] == '_') ||
(str[i] == '.') ||
(str[i] == '~')) {
encodedUrl += str[i];
} else {
encodedUrl += '%';
encodedUrl += ToHex((unsigned char)str[i] >> 4);
encodedUrl += ToHex((unsigned char)str[i] % 16);
}
}
return encodedUrl;
}
std::string CodecUtil::Base64Encode(const std::string& plain_text) {
static const char b64_table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const std::size_t plain_text_len = plain_text.size();
std::string retval((((plain_text_len + 2) / 3) * 4), '=');
std::size_t outpos = 0;
int bits_collected = 0;
unsigned int accumulator = 0;
const std::string::const_iterator plain_text_end = plain_text.end();
for (std::string::const_iterator i = plain_text.begin(); i != plain_text_end; ++i) {
accumulator = (accumulator << 8) | (*i & 0xffu);
bits_collected += 8;
while (bits_collected >= 6) {
bits_collected -= 6;
retval[outpos++] = b64_table[(accumulator >> bits_collected) & 0x3fu];
}
}
if (bits_collected > 0) {
assert(bits_collected < 6);
accumulator <<= 6 - bits_collected;
retval[outpos++] = b64_table[accumulator & 0x3fu];
}
assert(outpos >= (retval.size() - 2));
assert(outpos <= retval.size());
return retval;
}
std::string CodecUtil::HmacSha1(const std::string& plainText, const std::string& key) {
const EVP_MD *engine = EVP_sha1();
unsigned char *output = (unsigned char *)malloc(EVP_MAX_MD_SIZE);
unsigned int output_len = 0;
HMAC_CTX *ctx = HMAC_CTX_new();
HMAC_CTX_reset(ctx);
HMAC_Init_ex(ctx, (char *)key.c_str(), key.length(), engine, NULL);
HMAC_Update(ctx, (unsigned char*)plainText.c_str(), plainText.length());
HMAC_Final(ctx, output, &output_len);
HMAC_CTX_free(ctx);
std::string hmac_sha1_ret((char *)output, output_len);
free(output);
return hmac_sha1_ret;
}
std::string CodecUtil::HmacSha1Hex(const std::string& plain_text,const std::string& key) {
std::string encode_str = HmacSha1(plain_text, key);
char hex[(HMAC_LENGTH<<1)+1] = {0};
BinToHex((const unsigned char*)encode_str.c_str(), encode_str.size(), hex);
return std::string(hex, (HMAC_LENGTH << 1));
}
std::string CodecUtil::RawMd5(const std::string& plainText) {
const int md5_length = 16;
unsigned char md[md5_length];
MD5((const unsigned char*)plainText.data(), plainText.size(), md);
std::string tmp((const char *)md, md5_length);
return tmp;
}
// convert a hexadecimal string to binary value
std::string CodecUtil::HexToBin(const std::string &strHex) {
if (strHex.size() % 2 != 0) {
return "";
}
std::string strBin;
strBin.resize(strHex.size() / 2);
for (size_t i = 0; i < strBin.size(); i++) {
uint8_t cTmp = 0;
for (size_t j = 0; j < 2; j++) {
char cCur = strHex[2 * i + j];
if (cCur >= '0' && cCur <= '9') {
cTmp = (cTmp << 4) + (cCur - '0');
}
else if (cCur >= 'a' && cCur <= 'f') {
cTmp = (cTmp << 4) + (cCur - 'a' + 10);
}
else if (cCur >= 'A' && cCur <= 'F') {
cTmp = (cTmp << 4) + (cCur - 'A' + 10);
}
else {
return "";
}
}
strBin[i] = cTmp;
}
return strBin;
}// end of HexToBin
}// end of qcloud_cos namespace
| 5,199 | 2,000 |
#include "LightHelper.h"
| 25 | 10 |
#include <cstdio>
#include <cstdlib>
#include <list>
#include <fstream>
#include <iostream>
#include <sstream>
#include <cstring>
#include <random>
#include <stdio.h>
#include <stdlib.h>
#include <sys/timeb.h>
#include "../QmaxKV.hpp"
#include "../HeapKV.hpp"
#include "../SkiplistKV.hpp"
#include "Utils.hpp"
#define CLK_PER_SEC CLOCKS_PER_SEC
#define CAIDA16_SIZE 152197437
#define CAIDA18_SIZE 175880808
#define UNIV1_SIZE 17323447
using namespace std;
void benchmark_psskiplist(int q, key** keys, val** vals, ofstream &ostream, string dataset, int numKeys) {
std::random_device _rd;
std::mt19937 _e2(_rd());
std::uniform_real_distribution<double> _dist(0,1);
key *elements = *keys;
val *weights = *vals;
struct timeb begintb, endtb;
clock_t begint, endt;
double time;
SkiplistKV sl(q);
begint = clock();
ftime(&begintb);
for (int i = 0; i < numKeys; i++) {
val priority = weights[i] / (1-_dist(_e2));
sl.add(pair<key, val>(elements[i], priority));
}
endt = clock();
ftime(&endtb);
time = ((double)(endt-begint))/CLK_PER_SEC;
ostream << dataset << ",SkipList," << numKeys << "," << q << ",," << time << endl;
}
void benchmark_psheap(int q, key** keys, val** vals, ofstream &ostream, string dataset, int numKeys) {
std::random_device _rd;
std::mt19937 _e2(_rd());
std::uniform_real_distribution<double> _dist(0,1);
key *elements = *keys;
val *weights = *vals;
struct timeb begintb, endtb;
clock_t begint, endt;
double time;
HeapKV heap(q);
begint = clock();
ftime(&begintb);
for (int i = 0; i < numKeys; i++) {
val priority = weights[i] / (1-_dist(_e2));
heap.add(pair<key,val>(elements[i], priority));
}
endt = clock();
ftime(&endtb);
time = ((double)(endt-begint))/CLK_PER_SEC;
ostream << dataset << ",Heap," << numKeys << "," << q << ",," << time << endl;
}
void benchmark_psqmax(int q, double gamma, key** keys, val** vals, ofstream &ostream, string dataset, int numKeys) {
std::random_device _rd;
std::mt19937 _e2(_rd());
std::uniform_real_distribution<double> _dist(0,1);
key *elements = *keys;
val *weights = *vals;
struct timeb begintb, endtb;
clock_t begint, endt;
double time;
QMaxKV qmax = QMaxKV(q, gamma);
begint = clock();
ftime(&begintb);
for (int i = 0; i < numKeys; i++) {
val priority = weights[i] / (1-_dist(_e2));
qmax.insert(elements[i], priority);
}
endt = clock();
ftime(&endtb);
time = ((double)(endt-begint))/CLK_PER_SEC;
ostream << dataset << ",AmortizedQMax," << numKeys << "," << q << "," << gamma << "," << time << endl;
}
void getKeysAndValsFromFile(string filename, vector<key*> &keys, vector<val*> &vals, int size) {
ifstream stream;
stream.open(filename, fstream::in | fstream::out | fstream::app);
if (!stream) {
throw invalid_argument("Could not open " + filename + " for reading.");
}
key* file_keys = (key*) malloc(sizeof(key) * size);
val* file_vals = (val*) malloc(sizeof(val) * size);
string line;
string len;
string id;
for (int i = 0; i < size; ++i){
getline(stream, line);
std::istringstream iss(line);
iss >> len;
iss >> id;
try {
file_keys[i] = stoull(id);
file_vals[i] = stoull(len);
} catch (const std::invalid_argument& ia) {
cerr << "Invalid argument: " << ia.what() << " at line " << i << endl;
cerr << len << " " << id << endl;;
--i;
exit(1);
}
}
keys.push_back(file_keys);
vals.push_back(file_vals);
stream.close();
}
int main() {
vector<ofstream*> streams;
vector<key*> keys;
vector<val*> vals;
vector<int> sizes;
vector<string> datasets;
ofstream univ1stream;
setupOutputFile("../results/ps_univ1.raw_res", univ1stream, false);
streams.push_back(&univ1stream);
getKeysAndValsFromFile("../datasets/UNIV1/mergedPktlen_Srcip", keys, vals, UNIV1_SIZE);
sizes.push_back(UNIV1_SIZE);
datasets.push_back("univ1");
ofstream caida16stream;
setupOutputFile("../results/ps_caida.raw_res", caida16stream, false);
streams.push_back(&caida16stream);
getKeysAndValsFromFile("../datasets/CAIDA16/mergedPktlen_Srcip", keys, vals, CAIDA16_SIZE);
sizes.push_back(CAIDA16_SIZE);
datasets.push_back("caida");
ofstream caida18stream;
setupOutputFile("../results/ps_caida18.raw_res", caida18stream, false);
streams.push_back(&caida18stream);
getKeysAndValsFromFile("../datasets/CAIDA18/mergedPktlen_Srcip", keys, vals, CAIDA18_SIZE);
sizes.push_back(CAIDA18_SIZE);
datasets.push_back("caida18");
list<unsigned int> qs = {10000000, 1000000, 100000, 10000};
for (int run = 0; run < 5; run++) {
for (unsigned q: qs) {
vector<key*>::iterator k_it = keys.begin();
vector<val*>::iterator v_it = vals.begin();
vector<int>::iterator s_it = sizes.begin();
vector<string>::iterator d_it = datasets.begin();
for (auto& stream : streams) {
key* k = *k_it;
val* v = *v_it;
int size = *s_it;
string dataset = *d_it;
benchmark_psheap(q, &k, &v, *stream, dataset, size);
benchmark_psskiplist(q, &k, &v, *stream, dataset, size);
list<double> gammas = {0.5, 0.25, 0.1, 0.05};
for (double g : gammas) {
benchmark_psqmax(q, g, &k, &v, *stream, dataset, size);
}
++k_it;
++v_it;
++s_it;
++d_it;
}
}
}
univ1stream.close();
caida16stream.close();
caida18stream.close();
return 0;
}
| 5,405 | 2,193 |
/***
* ==++==
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ==--==
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* constructor_tests.cpp
*
* Tests for constructors of the uri class.
*
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
****/
#include "stdafx.h"
using namespace web; using namespace utility;
using namespace http;
namespace tests { namespace functional { namespace uri_tests {
SUITE(constructor_tests)
{
TEST(parsing_constructor_char)
{
uri u(uri::encode_uri(U("net.tcp://testname.com:81/bleh%?qstring#goo")));
VERIFY_ARE_EQUAL(U("net.tcp"), u.scheme());
VERIFY_ARE_EQUAL(U("testname.com"), u.host());
VERIFY_ARE_EQUAL(81, u.port());
VERIFY_ARE_EQUAL(U("/bleh%25"), u.path());
VERIFY_ARE_EQUAL(U("qstring"), u.query());
VERIFY_ARE_EQUAL(U("goo"), u.fragment());
}
TEST(parsing_constructor_encoded_string)
{
uri u(uri::encode_uri(U("net.tcp://testname.com:81/bleh%?qstring#goo")));
VERIFY_ARE_EQUAL(U("net.tcp"), u.scheme());
VERIFY_ARE_EQUAL(U("testname.com"), u.host());
VERIFY_ARE_EQUAL(81, u.port());
VERIFY_ARE_EQUAL(U("/bleh%25"), u.path());
VERIFY_ARE_EQUAL(U("qstring"), u.query());
VERIFY_ARE_EQUAL(U("goo"), u.fragment());
}
TEST(parsing_constructor_string_string)
{
uri u(uri::encode_uri(U("net.tcp://testname.com:81/bleh%?qstring#goo")));
VERIFY_ARE_EQUAL(U("net.tcp"), u.scheme());
VERIFY_ARE_EQUAL(U("testname.com"), u.host());
VERIFY_ARE_EQUAL(81, u.port());
VERIFY_ARE_EQUAL(U("/bleh%25"), u.path());
VERIFY_ARE_EQUAL(U("qstring"), u.query());
VERIFY_ARE_EQUAL(U("goo"), u.fragment());
}
TEST(empty_strings)
{
VERIFY_IS_TRUE(uri(U("")).is_empty());
VERIFY_IS_TRUE(uri(U("")).is_empty());
VERIFY_IS_TRUE(uri(uri::encode_uri(U(""))).is_empty());
}
TEST(default_constructor)
{
VERIFY_IS_TRUE(uri().is_empty());
}
TEST(relative_ref_string)
{
uri u(uri::encode_uri(U("first/second#boff")));
VERIFY_ARE_EQUAL(U(""), u.scheme());
VERIFY_ARE_EQUAL(U(""), u.host());
VERIFY_ARE_EQUAL(0, u.port());
VERIFY_ARE_EQUAL(U("first/second"), u.path());
VERIFY_ARE_EQUAL(U(""), u.query());
VERIFY_ARE_EQUAL(U("boff"), u.fragment());
}
TEST(absolute_ref_string)
{
uri u(uri::encode_uri(U("/first/second#boff")));
VERIFY_ARE_EQUAL(U(""), u.scheme());
VERIFY_ARE_EQUAL(U(""), u.host());
VERIFY_ARE_EQUAL(0, u.port());
VERIFY_ARE_EQUAL(U("/first/second"), u.path());
VERIFY_ARE_EQUAL(U(""), u.query());
VERIFY_ARE_EQUAL(U("boff"), u.fragment());
}
TEST(copy_constructor)
{
uri original(U("http://localhost:456/path1?qstring#goo"));
uri new_uri(original);
VERIFY_ARE_EQUAL(original, new_uri);
}
TEST(move_constructor)
{
const utility::string_t uri_str(U("http://localhost:456/path1?qstring#goo"));
uri original(uri_str);
uri new_uri = std::move(original);
VERIFY_ARE_EQUAL(uri_str, new_uri.to_string());
VERIFY_ARE_EQUAL(uri(uri_str), new_uri);
}
TEST(assignment_operator)
{
uri original(U("http://localhost:456/path?qstring#goo"));
uri new_uri = original;
VERIFY_ARE_EQUAL(original, new_uri);
}
// Tests invalid URI being passed in constructor.
TEST(parsing_constructor_invalid)
{
VERIFY_THROWS(uri(U("123http://localhost:345/")), uri_exception);
VERIFY_THROWS(uri(U("h*ttp://localhost:345/")), uri_exception);
VERIFY_THROWS(uri(U("http://localhost:345/\"")), uri_exception);
VERIFY_THROWS(uri(U("http://localhost:345/path?\"")), uri_exception);
VERIFY_THROWS(uri(U("http://local\"host:345/")), uri_exception);
}
// Tests a variety of different URIs using the examples in RFC 3986.
TEST(RFC_3968_examples_string)
{
uri ftp(U("ftp://ftp.is.co.za/rfc/rfc1808.txt"));
VERIFY_ARE_EQUAL(U("ftp"), ftp.scheme());
VERIFY_ARE_EQUAL(U(""), ftp.user_info());
VERIFY_ARE_EQUAL(U("ftp.is.co.za"), ftp.host());
VERIFY_ARE_EQUAL(0, ftp.port());
VERIFY_ARE_EQUAL(U("/rfc/rfc1808.txt"), ftp.path());
VERIFY_ARE_EQUAL(U(""), ftp.query());
VERIFY_ARE_EQUAL(U(""), ftp.fragment());
// TFS #371892
//uri ldap(U("ldap://[2001:db8::7]/?c=GB#objectClass?one"));
//VERIFY_ARE_EQUAL(U("ldap"), ldap.scheme());
//VERIFY_ARE_EQUAL(U(""), ldap.user_info());
//VERIFY_ARE_EQUAL(U("2001:db8::7"), ldap.host());
//VERIFY_ARE_EQUAL(0, ldap.port());
//VERIFY_ARE_EQUAL(U("/"), ldap.path());
//VERIFY_ARE_EQUAL(U("c=GB"), ldap.query());
//VERIFY_ARE_EQUAL(U("objectClass?one"), ldap.fragment());
// We don't support anything scheme specific like in C# so
// these common ones don't have a great experience yet.
uri mailto(U("mailto:John.Doe@example.com"));
VERIFY_ARE_EQUAL(U("mailto"), mailto.scheme());
VERIFY_ARE_EQUAL(U(""), mailto.user_info());
VERIFY_ARE_EQUAL(U(""), mailto.host());
VERIFY_ARE_EQUAL(0, mailto.port());
VERIFY_ARE_EQUAL(U("John.Doe@example.com"), mailto.path());
VERIFY_ARE_EQUAL(U(""), mailto.query());
VERIFY_ARE_EQUAL(U(""), mailto.fragment());
uri tel(U("tel:+1-816-555-1212"));
VERIFY_ARE_EQUAL(U("tel"), tel.scheme());
VERIFY_ARE_EQUAL(U(""), tel.user_info());
VERIFY_ARE_EQUAL(U(""), tel.host());
VERIFY_ARE_EQUAL(0, tel.port());
VERIFY_ARE_EQUAL(U("+1-816-555-1212"), tel.path());
VERIFY_ARE_EQUAL(U(""), tel.query());
VERIFY_ARE_EQUAL(U(""), tel.fragment());
uri telnet(U("telnet://192.0.2.16:80/"));
VERIFY_ARE_EQUAL(U("telnet"), telnet.scheme());
VERIFY_ARE_EQUAL(U(""), telnet.user_info());
VERIFY_ARE_EQUAL(U("192.0.2.16"), telnet.host());
VERIFY_ARE_EQUAL(80, telnet.port());
VERIFY_ARE_EQUAL(U("/"), telnet.path());
VERIFY_ARE_EQUAL(U(""), telnet.query());
VERIFY_ARE_EQUAL(U(""), telnet.fragment());
}
TEST(user_info_string)
{
uri ftp(U("ftp://johndoe:testname@ftp.is.co.za/rfc/rfc1808.txt"));
VERIFY_ARE_EQUAL(U("ftp"), ftp.scheme());
VERIFY_ARE_EQUAL(U("johndoe:testname"), ftp.user_info());
VERIFY_ARE_EQUAL(U("ftp.is.co.za"), ftp.host());
VERIFY_ARE_EQUAL(0, ftp.port());
VERIFY_ARE_EQUAL(U("/rfc/rfc1808.txt"), ftp.path());
VERIFY_ARE_EQUAL(U(""), ftp.query());
VERIFY_ARE_EQUAL(U(""), ftp.fragment());
}
// Test query component can be seperated with '&' or ';'.
TEST(query_seperated_with_semi_colon)
{
uri u(U("http://localhost/path1?key1=val1;key2=val2"));
VERIFY_ARE_EQUAL(U("key1=val1;key2=val2"), u.query());
}
} // SUITE(constructor_tests)
}}}
| 7,118 | 3,265 |
// problem name: Life of Phi
// problem link: https://toph.co/p/life-of-phi
// contest link: https://toph.co/c/practice-icpc-2019-dhaka
// author: reyad
// time: (?)
#include <bits/stdc++.h>
using namespace std;
#define N 1000000
long long int phi[N + 10], sum[N + 10];
int mark[N + 10] = {0};
int main() {
sum[0] = 0; phi[0] = 0;
for(int i=1; i<=N; i++) {
phi[i] = i;
sum[i] = sum[i-1] + i;
}
phi[1] = 1;
mark[1] = 1;
for(int i=2; i<=N; i++) {
if(!mark[i]) {
for(int j=i; j<=N; j+=i) {
mark[j] = 1;
phi[j] = (i - 1) * phi[j] / i;
}
}
}
int tc;
scanf("%d", &tc);
for(int cc=0; cc<tc; cc++) {
int n;
scanf("%d", &n);
printf("%lld\n", sum[n-1] - n * phi[n] / 2);
}
return 0;
} | 766 | 432 |
// InjectHook.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
| 65 | 42 |