hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fd5fa10b6db556030c76f218199308328ececf93
| 5,256
|
cpp
|
C++
|
src/shapes/ofxLaserPolyline.cpp
|
suaretjorge/laser_ofx
|
42d733489947c95cc83505f5708e89309f7d856f
|
[
"MIT"
] | 228
|
2015-08-19T06:33:13.000Z
|
2022-03-21T13:38:47.000Z
|
src/shapes/ofxLaserPolyline.cpp
|
suaretjorge/laser_ofx
|
42d733489947c95cc83505f5708e89309f7d856f
|
[
"MIT"
] | 19
|
2018-06-29T17:22:39.000Z
|
2022-03-11T17:48:42.000Z
|
src/shapes/ofxLaserPolyline.cpp
|
suaretjorge/laser_ofx
|
42d733489947c95cc83505f5708e89309f7d856f
|
[
"MIT"
] | 27
|
2015-11-21T02:31:51.000Z
|
2022-03-20T02:25:55.000Z
|
//
// ofxLaserPolyline.cpp
// ofxLaser
//
// Created by Seb Lee-Delisle on 16/11/2017.
//
//
#include "ofxLaserPolyline.h"
using namespace ofxLaser;
Polyline::Polyline() {
reversable = true;
colour = ofColor::white;
cachedProfile = NULL;
multicoloured = false;
tested = false;
profileLabel = "";
}
Polyline::Polyline(const ofPolyline& poly, const ofColor& col, string profilelabel){
init(poly, col, profilelabel);
}
Polyline::Polyline(const ofPolyline& poly, const vector<ofColor>& sourcecolours, string profilelabel){
init(poly, sourcecolours, profilelabel);
}
void Polyline::init(const ofPolyline& poly, const ofColor& col, string profilelabel){
reversable = true;
colour = col;
cachedProfile = NULL;
multicoloured = false;
tested = false;
profileLabel = profilelabel;
initPoly(poly);
}
void Polyline::init(const ofPolyline& poly, const vector<ofColor>& sourcecolours, string profilelabel){
reversable = true;
cachedProfile = NULL;
multicoloured = true;
colours = sourcecolours; // should copy
tested = false;
profileLabel = profilelabel;
initPoly(poly);
}
void Polyline::initPoly(const ofPolyline& poly){
if(polylinePointer==NULL) {
polylinePointer = ofxLaser::Factory::getPolyline();
} else {
polylinePointer->clear();
}
*polylinePointer = poly; // makes a copy, hopefully
// auto & vertices =poly.getVertices();
// ofPoint p;
// for(size_t i = 0; i<vertices.size(); i++) {
//
// //p = ofxLaser::Manager::instance()->gLProject(vertices[i]);
// p = vertices[i];
// polyline.addVertex(p);
//
// }
ofPolyline& polyline = *polylinePointer;
if(poly.isClosed()) {
polyline.addVertex(polyline.getVertices().front());
polyline.setClosed(false);
}
const vector<glm::vec3>& vertices = polyline.getVertices();
startPos = vertices.front();
// to avoid a bug in polyline in open polys
endPos = vertices.back();
boundingBox = polyline.getBoundingBox();
}
Polyline:: ~Polyline() {
// not sure if there's any point clearing the polyline - they should just get destroyed, right?
//polyline.clear();
if(polylinePointer!=NULL) {
ofxLaser::Factory::releasePolyline(polylinePointer);
}
}
void Polyline::appendPointsToVector(vector<ofxLaser::Point>& points, const RenderProfile& profile, float speedMultiplier) {
// TODO - take into account the speed multiplier!
ofPolyline& polyline = *polylinePointer;
if(&profile == cachedProfile) {
// ofLog(OF_LOG_NOTICE, "cached points used");
points.insert(points.end(), cachedPoints.begin(), cachedPoints.end());
return;
}
cachedProfile = &profile;
cachedPoints.clear();
float acceleration = profile.acceleration;
float speed = profile.speed;
float cornerThresholdAngle = profile.cornerThreshold;
int startpoint = 0;
int endpoint = 0;
int numVertices =(int)polyline.size();
while(endpoint<numVertices-1) {
do {
endpoint++;
} while ((endpoint< (int)polyline.size()-1) && abs(polyline.getDegreesAtIndex(endpoint)) < cornerThresholdAngle);
float startdistance = polyline.getLengthAtIndex(startpoint);
float enddistance = polyline.getLengthAtIndex(endpoint);
float length = enddistance - startdistance;
ofPoint lastpoint;
if(length>0) {
vector<float>& unitDistances = getPointsAlongDistance(length, acceleration, speed, speedMultiplier);
for(size_t i = 0; i<unitDistances.size(); i++) {
float distanceAlongPoly = (unitDistances[i]*0.999* length) + startdistance;
ofPoint p = polyline.getPointAtLength(distanceAlongPoly);
if(multicoloured) {
int colourindex = round(polyline.getIndexAtLength(distanceAlongPoly)); // TODO - interpolate?
colourindex = ofClamp(colourindex, 0,colours.size());
cachedPoints.push_back(ofxLaser::Point(p, colours[colourindex]));
} else {
cachedPoints.push_back(ofxLaser::Point(p, colour));
}
lastpoint = p;
}
}
startpoint=endpoint;
}
points.insert(points.end(), cachedPoints.begin(), cachedPoints.end());
}
void Polyline :: addPreviewToMesh(ofMesh& mesh){
ofPolyline& polyline = *polylinePointer;
const vector<glm::vec3>& vertices = polyline.getVertices();
mesh.addColor(ofColor(0));
mesh.addVertex(vertices.front());
for(size_t i = 0; i<vertices.size(); i++) {
if(multicoloured) {
int colourindex = ofClamp(i, 0, colours.size()-1);
mesh.addColor(colours[colourindex]);
} else {
mesh.addColor(colour);
}
mesh.addVertex(vertices[i]);
}
mesh.addColor(ofColor(0));
mesh.addVertex(vertices.back());
}
bool Polyline:: intersectsRect(ofRectangle & rect){
ofPolyline& polyline = *polylinePointer;
if(!rect.intersects(boundingBox)) return false;
const vector<glm::vec3> & vertices = polyline.getVertices();
for(size_t i = 1; i< vertices.size(); i++) {
if(rect.intersects(vertices[i-1],vertices[i])) return true;
}
return false;
}
//
//void Polyline::transformPolyline(const ofPolyline& source, ofPolyline& target, ofPoint pos, float rotation, ofPoint scale){
//
// target = source;
// for(int i = 0; i<target.size(); i++) {
// ofPoint& p = target[i];
// p*=scale;
// p.rotate(rotation, ofPoint(0,0,1));
// p+=pos;
//
// }
//
//
//}
| 22.753247
| 125
| 0.68379
|
suaretjorge
|
fd616d567fa11e1541b57700aaa19c14568de93a
| 1,784
|
cpp
|
C++
|
source/msynth/msynth/model/util/MEnvelopeFollower.cpp
|
MRoc/MSynth
|
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
|
[
"MIT"
] | 1
|
2022-01-30T07:40:31.000Z
|
2022-01-30T07:40:31.000Z
|
source/msynth/msynth/model/util/MEnvelopeFollower.cpp
|
MRoc/MSynth
|
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
|
[
"MIT"
] | null | null | null |
source/msynth/msynth/model/util/MEnvelopeFollower.cpp
|
MRoc/MSynth
|
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
|
[
"MIT"
] | null | null | null |
#include "MEnvelopeFollower.h"
/**
* constructor
*/
MEnvelopeFollower::MEnvelopeFollower() :
ivBUp( 0.001f ),
ivBDown( 0.99999f ),
ivPeak( 0.0f )
{
}
/**
* destructor
*/
MEnvelopeFollower::~MEnvelopeFollower()
{
}
/**
* does a envelope follow
*/
void MEnvelopeFollower::goNext( MSoundBuffer* pBuffer, unsigned int start, unsigned int stop )
{
FP* pSrc = pBuffer->getData( 0 ) + start;
FP* pStop = pSrc + (stop-start);
for( ;pSrc<pStop;pSrc++ )
{
// fetch input...
FP fCur = (*pSrc);
// abs...
if( fCur < 0.0f )
fCur *= -1;
// calc e...
FP b = fCur > ivPeak ? ivBUp : ivBDown;
FP g = 1-b;
// iteration...
ivPeak = g * fCur + ivPeak * b;
}
//fireEnvelopeChanged( ivPeak );
}
/**
* when invoked, the envelope follower fires
* a change notification.
*/
void MEnvelopeFollower::fireUpdate()
{
fireEnvelopeChanged( ivPeak );
}
/**
* adds a listener to the enveloper
*/
void MEnvelopeFollower::addListener( IEnvelopeFollowerListener* pListener )
{
ivListeners.addListener( pListener );
}
/**
* removes a listener from the enveloper
*/
void MEnvelopeFollower::removeListener( IEnvelopeFollowerListener* pListener )
{
ivListeners.removeListener( pListener );
}
/**
* fires a envelope changed event
*/
void MEnvelopeFollower::fireEnvelopeChanged( FP value )
{
unsigned int count = ivListeners.getListenerCount();
for( unsigned int i=0;i<count;i++ )
((IEnvelopeFollowerListener*)ivListeners.getListener( i ))->onEnvelopeChanged( value );
/*{
char buffer[ 256 ];
sprintf( buffer, " |\n" );
int tmp = (int)(value*10);
if( tmp > 10 )
tmp = 10;
for( int i=0;i<tmp;i++ )
buffer[ i ] = '*';
TRACE( buffer );
}*/
}
| 19.391304
| 95
| 0.612668
|
MRoc
|
fd61d39c9df23988ba4e9aab7823a7b49729f496
| 16,936
|
cpp
|
C++
|
uppsrc/ide/Debuggers/Gdb.cpp
|
UltimateScript/Forgotten
|
ac59ad21767af9628994c0eecc91e9e0e5680d95
|
[
"BSD-3-Clause"
] | null | null | null |
uppsrc/ide/Debuggers/Gdb.cpp
|
UltimateScript/Forgotten
|
ac59ad21767af9628994c0eecc91e9e0e5680d95
|
[
"BSD-3-Clause"
] | null | null | null |
uppsrc/ide/Debuggers/Gdb.cpp
|
UltimateScript/Forgotten
|
ac59ad21767af9628994c0eecc91e9e0e5680d95
|
[
"BSD-3-Clause"
] | null | null | null |
#include "Debuggers.h"
#define METHOD_NAME UPP_METHOD_NAME("Gdb")
void Gdb::WatchMenu(Bar& bar)
{
bool b = !IdeIsDebugLock();
bar.Add(b, PdbKeys::AK_CLEARWATCHES, THISBACK(ClearWatches));
bar.Add(b, PdbKeys::AK_ADDWATCH, THISBACK(QuickWatch));
}
void Gdb::DebugBar(Bar& bar)
{
using namespace PdbKeys;
bar.Add("Stop debugging", DbgImg::StopDebug(), THISBACK(Stop))
.Key(K_SHIFT_F5);
bar.Separator();
bool b = !IdeIsDebugLock();
bar.Add(b, AK_STEPINTO, DbgImg::StepInto(), THISBACK1(Step, disas.HasFocus() ? "stepi"
: "step"));
bar.Add(b, AK_STEPOVER, DbgImg::StepOver(), THISBACK1(Step, disas.HasFocus() ? "nexti"
: "next"));
bar.Add(b, AK_STEPOUT, DbgImg::StepOut(), THISBACK1(Step, "finish"));
bar.Add(b, AK_RUNTO, DbgImg::RunTo(), THISBACK(DoRunTo));
bar.Add(b, AK_RUN, DbgImg::Run(), THISBACK(Run));
bar.Add(!b && pid, AK_BREAK, DbgImg::Stop(), THISBACK(BreakRunning));
bar.MenuSeparator();
bar.Add(b, AK_AUTOS, THISBACK1(SetTab, 0));
bar.Add(b, AK_LOCALS, THISBACK1(SetTab, 1));
bar.Add(b, AK_THISS, THISBACK1(SetTab, 2));
bar.Add(b, AK_WATCHES, THISBACK1(SetTab, 3));
WatchMenu(bar);
bar.Add(b, AK_CPU, THISBACK1(SetTab, 4));
bar.MenuSeparator();
bar.Add(b, "Copy backtrace", THISBACK(CopyStack));
bar.Add(b, "Copy backtrace of all threads", THISBACK(CopyStackAll));
bar.Add(b, "Copy dissassembly", THISBACK(CopyDisas));
}
String FirstLine(const String& s)
{
int q = s.Find('\r');
if(q < 0)
q = s.Find('\n');
return q >= 0 ? s.Mid(0, q) : s;
}
String FormatFrame(const char *s)
{
if(*s++ != '#')
return Null;
while(IsDigit(*s))
s++;
while(*s == ' ')
s++;
if(s[0] == '0' && ToUpper(s[1]) == 'X') {
s += 2;
while(IsXDigit(*s))
s++;
while(*s == ' ')
s++;
if(s[0] == 'i' && s[1] == 'n')
s += 2;
while(*s == ' ')
s++;
}
String result;
const char *w = strchr(s, '\r');
if(!w)
w = strchr(s, '\n');
if(w)
result = String(s, w);
else
result = s;
if(!IsAlpha(*s)) {
int q = result.ReverseFind(' ');
if(q >= 0)
result = result.Mid(q + 1);
}
return result.GetCount() > 2 ? result : Null;
}
void Gdb::CopyStack()
{
if(IdeIsDebugLock())
return;
DropFrames();
String s;
for(int i = 0; i < frame.GetCount(); i++)
s << frame.GetValue(i) << "\n";
WriteClipboardText(s);
}
void Gdb::CopyStackAll()
{
String s = FastCmd("info threads");
StringStream ss(s);
String r;
while(!ss.IsEof()) {
String s = ss.GetLine();
CParser p(s);
try {
p.Char('*');
if(p.IsNumber()) {
int id = p.ReadInt();
r << "----------------------------------\r\n"
<< "Thread: " << id << "\r\n\r\n";
FastCmd(Sprintf("thread %d", id));
int i = 0;
for(;;) {
String s = FormatFrame(FastCmd("frame " + AsString(i++)));
if(IsNull(s)) break;
r << s << "\r\n";
}
r << "\r\n";
}
}
catch(CParser::Error) {}
}
FastCmd("thread " + ~~threads);
WriteClipboardText(r);
}
void Gdb::CopyDisas()
{
if(IdeIsDebugLock())
return;
disas.WriteClipboard();
}
int CharFilterReSlash(int c)
{
return c == '\\' ? '/' : c;
}
String Bpoint(Host& host, const String& file, int line)
{
return String().Cat() << Filter(host.GetHostPath(NormalizePath(file)), CharFilterReSlash) << ":" << line + 1;
}
bool Gdb::TryBreak(const char *text)
{
return FindTag(FastCmd(text), "Breakpoint");
}
bool Gdb::SetBreakpoint(const String& filename, int line, const String& bp)
{
if(IdeIsDebugLock()) {
BreakRunning();
bp_filename = filename;
bp_line = line;
bp_val = bp;
return true;
}
String bi = Bpoint(*host, filename, line);
String command;
if(bp.IsEmpty())
command = "clear " + bi;
else if(bp[0]==0xe || bp == "1")
command = "b " + bi;
else
command = "b " + bi + " if " + bp;
return !FastCmd(command).IsEmpty();
}
void Gdb::SetDisas(const String& text)
{
disas.Clear();
StringStream ss(text);
while(!ss.IsEof()) {
String ln = ss.GetLine();
const char *s = ln;
while(*s && !IsDigit(*s))
s++;
adr_t adr = 0;
String code, args;
if(s[0] == '0' && ToLower(s[1]) == 'x')
adr = (adr_t)ScanInt64(s + 2, NULL, 16);
int q = nodebuginfo ? ln.Find(":\t") : ln.Find(">:");
if(q >= 0) {
s = ~ln + q + 2;
while(IsSpace(*s))
s++;
while(*s && !IsSpace(*s))
code.Cat(*s++);
while(IsSpace(*s))
s++;
args = s;
q = args.Find("0x");
if(q >= 0)
disas.AddT(ScanInt(~args + q + 2, NULL, 16));
disas.Add(adr, code, args);
}
}
}
void Gdb::SyncDisas(bool fr)
{
if(!disas.IsVisible())
return;
if(!disas.InRange(addr))
SetDisas(FastCmd("disas"));
disas.SetCursor(addr);
disas.SetIp(addr, fr ? DbgImg::FrameLinePtr() : DbgImg::IpLinePtr());
}
bool ParsePos(const String& s, String& fn, int& line, adr_t & adr)
{
const char *q = FindTag(s, "\x1a\x1a");
if(!q) return false;
q += 2;
Vector<String> p = Split(q + 2, ':');
p.SetCount(5);
fn = String(q, q + 2) + p[0];
line = atoi(p[1]);
try {
CParser pa(p[4]);
pa.Char2('0', 'x');
if(pa.IsNumber(16))
adr = (adr_t)pa.ReadNumber64(16);
}
catch(CParser::Error) {}
return true;
}
void Gdb::CheckEnd(const char *s)
{
if(!dbg) {
Stop();
return;
}
if(FindTag(s, "Program exited normally.")) {
Stop();
return;
}
const char *q = FindTag(s, "Program exited with code ");
if(q) {
PutConsole(q);
Stop();
return;
}
}
String Gdb::Cmdp(const char *cmdline, bool fr, bool setframe)
{
expression_cache.Clear();
IdeHidePtr();
String s = Cmd(cmdline);
exception.Clear();
if(!running_interrupted) {
int q = s.Find("received signal SIG");
if(q >= 0) {
int l = s.ReverseFind('\n', q);
if(l < 0)
l = 0;
int r = s.Find('\n', q);
if(r < 0)
r = s.GetCount();
if(l < r)
exception = s.Mid(l, r - l);
}
}
else {
running_interrupted = false;
}
if(ParsePos(s, file, line, addr)) {
IdeSetDebugPos(GetLocalPath(file), line - 1, fr ? DbgImg::FrameLinePtr()
: DbgImg::IpLinePtr(), 0);
IdeSetDebugPos(GetLocalPath(file), line - 1,
disas.HasFocus() ? fr ? DbgImg::FrameLinePtr() : DbgImg::IpLinePtr()
: Image(), 1);
SyncDisas(fr);
autoline.Clear();
for(int i = -4; i <= 4; i++)
autoline << ' ' << IdeGetLine(line + i);
}
else {
file = Null;
try {
int q = s.ReverseFind("0x");
if(q >= 0) {
CParser pa(~s + q + 2);
addr = (adr_t)pa.ReadNumber64(16);
SetDisas(FastCmd(String() << "disas 0x" << FormatHex((void *)addr) << ",+1024"));
disas.SetCursor(addr);
disas.SetIp(addr, DbgImg::IpLinePtr());
}
}
catch(CParser::Error) {}
}
if(setframe) {
frame.Clear();
String f = FastCmd("frame");
frame.Add(0, nodebuginfo ? FirstLine(f) : FormatFrame(f));
frame <<= 0;
SyncFrameButtons();
}
if (dbg->IsRunning()) {
if (IsProcessExitedNormally(s))
Stop();
else {
s = ObtainThreadsInfo();
ObtainData();
}
}
return s;
}
bool Gdb::IsProcessExitedNormally(const String& cmd_output) const
{
const auto phrase = String().Cat() << "(process " << pid << ") exited normally";
return cmd_output.Find(phrase) >= 0;
}
String Gdb::ObtainThreadsInfo()
{
threads.Clear();
String output = FastCmd("info threads");
StringStream ss(output);
int active_thread = -1;
bool main = true;
while(!ss.IsEof()) {
String s = ss.GetLine();
CParser p(s);
try {
bool is_active = p.Char('*');
if(!p.IsNumber())
continue;
int id = p.ReadInt();
String name;
while (!p.IsEof()) {
if (p.IsString()) {
name = p.ReadString();
break;
}
p.SkipTerm();
}
AttrText text(String() << "Thread " << id);
if (!name.IsEmpty())
text.Set(text.ToString() << " (" << name << ")");
if(is_active) {
active_thread = id;
text.Bold();
}
if(main) {
text.Underline();
main = false;
}
threads.Add(id, text);
threads.GoBegin();
}
catch(CParser::Error e) {
Loge() << METHOD_NAME << e;
}
}
if(active_thread >= 0)
threads <<= active_thread;
return output;
}
void Gdb::ShowException()
{
if(exception.GetCount())
ErrorOK(exception);
exception.Clear();
}
String Gdb::DoRun()
{
if(firstrun) {
firstrun = false;
nodebuginfo_bg.Hide();
nodebuginfo = false;
if(Cmd("start").Find("No symbol") >= 0) {
nodebuginfo_bg.Show();
nodebuginfo = true;
String t = Cmd("run");
int q = t.ReverseFind("exited normally");
if(t.GetLength() - q < 20) {
Stop();
return Null;
}
}
if(!IsFinished()) {
String s = Cmd("info inferior");
int q = s.FindAfter("process");
pid = atoi(~s + q);
}
IdeSetBar();
}
String s;
for(;;) {
ClearCtrls();
s = Cmdp("continue");
if(IsNull(bp_filename))
break;
if(!IdeIsDebugLock())
SetBreakpoint(bp_filename, bp_line, bp_val);
bp_filename.Clear();
}
ShowException();
return s;
}
bool Gdb::RunTo()
{
if(IdeIsDebugLock() || nodebuginfo)
return false;
String bi;
bool df = disas.HasFocus();
if(df) {
if(!disas.GetCursor())
return false;
bi = Sprintf("*0x%X", disas.GetCursor());
}
else
bi = Bpoint(*host, IdeGetFileName(), IdeGetFileLine());
if(!TryBreak("b " + bi)) {
Exclamation("No code at chosen location!");
return false;
}
String e = DoRun();
FastCmd("clear " + bi);
if(df)
disas.SetFocus();
CheckEnd(e);
IdeActivateBottom();
return true;
}
void Gdb::BreakRunning()
{
Logd() << METHOD_NAME << "PID: " << pid << "\n";
auto error = gdb_utils->BreakRunning(pid);
if(!error.IsEmpty()) {
Loge() << METHOD_NAME << error;
ErrorOK(error);
return;
}
running_interrupted = true;
}
void Gdb::Run()
{
if(IdeIsDebugLock())
return;
String s = DoRun();
CheckEnd(s);
IdeActivateBottom();
}
void Gdb::Step(const char *cmd)
{
if(IdeIsDebugLock())
return;
bool b = disas.HasFocus();
String s = Cmdp(cmd);
if(b) disas.SetFocus();
CheckEnd(s);
IdeActivateBottom();
ShowException();
}
void Gdb::DisasCursor()
{
if(!disas.HasFocus())
return;
int line;
String file;
adr_t addr;
if(ParsePos(FastCmd(Sprintf("info line *0x%X", disas.GetCursor())), file, line, addr))
IdeSetDebugPos(file, line - 1, DbgImg::DisasPtr(), 1);
disas.SetFocus();
}
void Gdb::DisasFocus()
{
}
void Gdb::DropFrames()
{
if(frame.GetCount() < 2)
LoadFrames();
SyncFrameButtons();
}
void Gdb::LoadFrames()
{
if(frame.GetCount())
frame.Trim(frame.GetCount() - 1);
int i = frame.GetCount();
int n = 0;
for(;;) {
String f = FastCmd(Sprintf("frame %d", i));
String s;
if(nodebuginfo) {
s = FirstLine(f);
int q = s.Find("0x");
if(q < 0)
break;
try {
CParser p(~s + q + 2);
if(p.ReadNumber64(16) == 0)
break;
}
catch(CParser::Error) {
break;
}
}
else
s = nodebuginfo ? FirstLine(f) : FormatFrame(f);
if(IsNull(s))
break;
if(n++ >= max_stack_trace_size) {
frame.Add(Null, Sprintf("<load more> (%d loaded)", frame.GetCount()));
break;
}
frame.Add(i++, s);
}
SyncFrameButtons();
}
void Gdb::SwitchFrame()
{
int i = ~frame;
if(IsNull(i)) {
i = frame.GetCount() - 1;
LoadFrames();
frame <<= i;
}
Cmdp("frame " + AsString(i), i, false);
SyncFrameButtons();
}
void Gdb::FrameUpDown(int dir)
{
if(frame.GetCount() < 2)
LoadFrames();
int q = frame.GetIndex() + dir;
if(q >= 0 && q < frame.GetCount()) {
frame.SetIndex(q);
SwitchFrame();
}
}
void Gdb::SwitchThread()
{
int i = ~threads;
Cmdp("thread " + AsString(i));
SyncFrameButtons();
}
void Gdb::ClearCtrls()
{
threads.Clear();
disas.Clear();
locals.Clear();
autos.Clear();
self.Clear();
cpu.Clear();
tree.Clear();
}
bool Gdb::Key(dword key, int count)
{
if(key >= 32 && key < 65535 && tab.Get() == 2) {
watches.DoInsertAfter();
Ctrl* f = GetFocusCtrl();
if(f && watches.HasChildDeep(f))
f->Key(key, count);
return true;
}
return Ctrl::Key(key, count);
}
bool Gdb::Create(One<Host>&& _host, const String& exefile, const String& cmdline, bool console)
{
host = pick(_host);
dbg = host->StartProcess(GdbCommand(console) + host->NormalizeExecutablePath(exefile));
if (!dbg) {
ErrorOK("Error while invoking gdb!");
return false;
}
IdeSetBottom(*this);
IdeSetRight(disas);
disas.WhenCursor = THISBACK(DisasCursor);
disas.WhenFocus = THISBACK(DisasFocus);
frame.WhenDrop = THISBACK(DropFrames);
frame <<= THISBACK(SwitchFrame);
threads <<= THISBACK(SwitchThread);
watches.WhenAcceptEdit = THISBACK(ObtainData);
tab <<= THISBACK(ObtainData);
Cmd("set prompt " GDB_PROMPT);
Cmd("set disassembly-flavor intel");
Cmd("set exec-done-display off");
Cmd("set annotate 1");
Cmd("set height 0");
Cmd("set width 0");
Cmd("set confirm off");
Cmd("set print asm-demangle");
Cmd("set print static-members off");
Cmd("set print vtbl off");
Cmd("set print repeat 0");
Cmd("set print null-stop");
#ifdef PLATFORM_WIN32
Cmd("set new-console on");
#endif
if(!IsNull(cmdline))
Cmd("set args " + cmdline);
firstrun = true;
running_interrupted = false;
return true;
}
Gdb::~Gdb()
{
StringStream ss;
Store(callback(this, &Gdb::SerializeSession), ss);
WorkspaceConfigData("gdb-debugger") = ss;
IdeRemoveBottom(*this);
IdeRemoveRight(disas);
KillDebugTTY();
}
void Gdb::Periodic()
{
if(TTYQuit())
Stop();
}
void Gdb::SerializeSession(Stream& s)
{
int version = 0;
s / version;
int n = watches.GetCount();
s / n;
for(int i = 0; i < n; i++) {
String w;
if(s.IsStoring())
w = watches.Get(i, 0);
s % w;
if(s.IsLoading())
watches.Add(w);
}
}
Gdb::Gdb()
: gdb_utils(GdbUtilsFactory().Create())
{
auto Mem = [=](Bar& bar, ArrayCtrl& h) {
String s = h.GetKey();
if(s.GetCount()) {
if(!IsAlpha(*s))
s = '(' + s + ')';
MemoryMenu(bar, s);
}
};
locals.NoHeader();
locals.AddColumn("", 1);
locals.AddColumn("", 6);
locals.EvenRowColor();
locals.WhenSel = THISBACK1(SetTree, &locals);
locals.WhenBar = [=](Bar& bar) { Mem(bar, locals); };
watches.NoHeader();
watches.AddColumn("", 1).Edit(watchedit);
watches.AddColumn("", 6);
watches.Inserting().Removing();
watches.EvenRowColor();
watches.WhenSel = THISBACK1(SetTree, &watches);
watches.WhenBar = [=](Bar& bar) { Mem(bar, watches); WatchMenu(bar); };
autos.NoHeader();
autos.AddColumn("", 1);
autos.AddColumn("", 6);
autos.EvenRowColor();
autos.WhenSel = THISBACK1(SetTree, &autos);
autos.WhenBar = [=](Bar& bar) { Mem(bar, autos); };
self.NoHeader();
self.AddColumn("", 1);
self.AddColumn("", 6);
self.EvenRowColor();
self.WhenSel = THISBACK1(SetTree, &self);
self.WhenBar = [=](Bar& bar) { Mem(bar, self); };
cpu.Columns(3);
cpu.ItemHeight(Courier(Ctrl::HorzLayoutZoom(12)).GetCy());
pane.Add(tab.SizePos());
tab.Add(autos.SizePos(), "Autos");
tab.Add(locals.SizePos(), "Locals");
tab.Add(watches.SizePos(), "Watches");
tab.Add(self.SizePos(), "this");
tab.Add(cpu.SizePos(), "CPU");
tab.Add(memory.SizePos(), "Memory");
pane.Add(threads.LeftPosZ(330, 150).TopPos(2));
memory.WhenGotoDlg = [=] { MemoryGoto(); };
int bcx = min(EditField::GetStdHeight(), DPI(16));
pane.Add(frame.HSizePos(Zx(484), 2 * bcx).TopPos(2));
pane.Add(frame_up.RightPos(bcx, bcx).TopPos(2, EditField::GetStdHeight()));
frame_up.SetImage(DbgImg::FrameUp());
frame_up << [=] { FrameUpDown(-1); };
frame_up.Tip("Previous Frame");
pane.Add(frame_down.RightPos(0, bcx).TopPos(2, EditField::GetStdHeight()));
frame_down.SetImage(DbgImg::FrameDown());
frame_down << [=] { FrameUpDown(1); };
frame_down.Tip("Next Frame");
split.Horz(pane, tree.SizePos());
split.SetPos(8000);
Add(split);
tree.WhenOpen = THISBACK(OnTreeExpand);
tree.WhenBar = THISBACK(OnTreeBar);
frame.Ctrl::Add(dlock.SizePos());
dlock = " Running..";
dlock.SetFrame(BlackFrame());
dlock.SetInk(Red);
dlock.NoTransparent();
dlock.Hide();
CtrlLayoutOKCancel(quickwatch, "Watch");
quickwatch.WhenClose = quickwatch.Breaker(IDCANCEL);
quickwatch.value.SetReadOnly();
quickwatch.value.SetFont(CourierZ(11));
quickwatch.Sizeable().Zoomable();
quickwatch.SetRect(0, 150, 300, 400);
Transparent();
periodic.Set(-50, THISBACK(Periodic));
StringStream ss(WorkspaceConfigData("gdb-debugger"));
Load(callback(this, &Gdb::SerializeSession), ss);
const char *text = "No symbolic information available";
Size sz = GetTextSize(text, StdFont().Italic().Bold());
nodebuginfo_bg.Background(Gray())
.RightPos(0, sz.cx + DPI(8))
.BottomPos(0, sz.cy + DPI(6))
.Add(nodebuginfo_text.SizePos());
nodebuginfo_text = text;
nodebuginfo_text.AlignCenter().SetInk(Yellow()).SetFont(StdFont().Italic().Bold());
pane.Add(nodebuginfo_bg);
}
One<Debugger> GdbCreate(One<Host>&& host, const String& exefile, const String& cmdline, bool console)
{
auto dbg = MakeOne<Gdb>();
if(!dbg->Create(pick(host), exefile, cmdline, console))
return nullptr;
return pick(dbg); // CLANG does not like this without pick
}
| 21.519695
| 110
| 0.604924
|
UltimateScript
|
fd6ea4d689aed0719629580f075ec2d06008a897
| 11,246
|
cpp
|
C++
|
deployment/configenv/xml_jlibpt/EnvHelper.cpp
|
davidarcher/HPCC-Platform
|
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
|
[
"Apache-2.0"
] | null | null | null |
deployment/configenv/xml_jlibpt/EnvHelper.cpp
|
davidarcher/HPCC-Platform
|
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
|
[
"Apache-2.0"
] | null | null | null |
deployment/configenv/xml_jlibpt/EnvHelper.cpp
|
davidarcher/HPCC-Platform
|
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
|
[
"Apache-2.0"
] | 3
|
2021-05-02T17:01:57.000Z
|
2021-05-02T17:02:28.000Z
|
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2018 HPCC Systems®.
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 "build-config.h"
#include "EnvHelper.hpp"
#include "Hardware.hpp"
#include "Programs.hpp"
#include "EnvSettings.hpp"
#include "Software.hpp"
#include "ComponentBase.hpp"
#include "deployutils.hpp"
#include "build-config.h"
#include "confighelper.hpp"
namespace ech
{
EnvHelper::EnvHelper(IPropertyTree *config)
{
init(config);
}
void EnvConfigOptions::loadFile(const char* filename)
{
m_options.setown(createProperties(filename));
}
const char* EnvHelper::getConfig(const char* key, CONFIG_TYPE type) const
{
StringBuffer sbKey;
sbKey.clear();
if (key[0] != '@')
sbKey.append("@");
sbKey.append(key);
if ((type == CONFIG_INPUT) ||(type == CONFIG_ALL))
{
if (m_config->hasProp(sbKey.str()))
return m_config->queryProp(sbKey.str());
}
if ((type == CONFIG_ENV) || (type == CONFIG_ALL))
{
const IProperties * envCfg = m_envCfgOptions->getProperties();
if (envCfg->hasProp(sbKey.str()))
return envCfg->queryProp(sbKey.str());
}
return NULL;
}
EnvHelper::~EnvHelper()
{
HashIterator compIter(m_compMap);
ForEach(compIter)
{
IMapping &cur = compIter.query();
IConfigComp* pComp = m_compMap.mapToValue(&cur);
ComponentBase *cb = (ComponentBase*) pComp;
::Release(cb);
}
m_envTree.clear();
m_buildSetTree.clear();
if (m_envCfgOptions) delete m_envCfgOptions;
if (m_genEnvRules) delete m_genEnvRules;
if (m_numOfCompSigned) delete [] m_numOfCompSigned;
}
void EnvHelper::init(IPropertyTree *config)
{
this->m_config = config;
/*
//id
m_baseIds.setValue("Hardware", 1);
m_baseIds.setValue("EnvSettings", 2);
m_baseIds.setValue("Programs", 3);
m_baseIds.setValue("Software", 4);
*/
StringBuffer fileName;
const char* optionsFileName = m_config->queryProp("@options");
if (optionsFileName && *optionsFileName)
fileName.clear().append(optionsFileName);
else
fileName.clear().append(DEFAULT_ENV_OPTIONS);
m_envCfgOptions = new EnvConfigOptions(fileName.str());
const char* genEnvRulesFileName = m_config->queryProp("@rules");
if (genEnvRulesFileName && *genEnvRulesFileName)
fileName.clear().append(genEnvRulesFileName);
else
fileName.clear().append(DEFAULT_GEN_ENV_RULES);
m_genEnvRules = new GenEnvRules(fileName.str());
const char* buildSetFileName = m_config->queryProp("@buildset");
if (buildSetFileName && * buildSetFileName)
fileName.clear().append(buildSetFileName);
else
fileName.clear().append(DEFAULT_BUILDSET);
m_buildSetTree.setown(createPTreeFromXMLFile(fileName.str()));
const char* envXmlFileName = m_config->queryProp("@env-in");
if (envXmlFileName && *envXmlFileName)
m_envTree.setown(createPTreeFromXMLFile(envXmlFileName));
else if (!USE_WIZARD)
{
m_envTree.setown(createPTreeFromXMLString("<" XML_HEADER "><" XML_TAG_ENVIRONMENT "></" XML_TAG_ENVIRONMENT ">"));
//Initialize CConfigHelper
const char* espConfigPath = (m_config->hasProp("@esp-config"))?
m_config->queryProp("@esp-config") : ESP_CONFIG_PATH;
Owned<IPropertyTree> espCfg = createPTreeFromXMLFile(espConfigPath);
const char* espServiceName = (m_config->hasProp("@esp-service"))?
m_config->queryProp("@esp-service") : "WsDeploy_wsdeploy_esp";
// just initialize the instance which is static member
CConfigHelper *pch = CConfigHelper::getInstance(espCfg, espServiceName);
if (pch == NULL)
{
throw MakeStringException( -1 , "Error loading buildset from configuration");
}
}
m_numOfCompSigned = NULL;
}
EnvHelper * EnvHelper::setEnvTree(StringBuffer &envXml)
{
m_envTree.setown(createPTreeFromXMLString(envXml));
return this;
}
IConfigComp* EnvHelper::getEnvComp(const char *compName)
{
const char * compNameLC = (StringBuffer(compName).toLowerCase()).str();
IConfigComp * pComp = m_compMap.getValue(compNameLC);
if (pComp) return pComp;
pComp = NULL;
if (stricmp(compNameLC, "hardware") == 0)
{
pComp = (IConfigComp*) new Hardware(this);
}
else if (stricmp(compNameLC, "programs") == 0)
{
pComp = (IConfigComp*) new Programs(this);
}
else if (stricmp(compNameLC, "envsettings") == 0)
{
pComp = (IConfigComp*) new EnvSettings(this);
}
else if (stricmp(compNameLC, "software") == 0)
{
pComp = (IConfigComp*) new Software(this);
}
if (pComp != NULL)
{
m_compMap.setValue(compNameLC, pComp);
}
return pComp;
}
IConfigComp* EnvHelper::getEnvSWComp(const char *swCompName)
{
Software* sw = (Software*)getEnvComp("software");
IConfigComp* icc = sw->getSWComp(swCompName);
return icc;
//return ((Software*)getEnvComp("software"))->getSWComp(swCompName);
}
int EnvHelper::processNodeAddress(const char *ipInfo, StringArray &ips, bool isFile)
{
int len = ips.ordinality();
if (!ipInfo || !(*ipInfo)) return 0;
if (isFile)
{
StringBuffer ipAddrs;
ipAddrs.loadFile(ipInfo);
if (ipAddrs.str())
formIPList(ipAddrs.str(), ips);
else
return 0;
}
else
{
formIPList(ipInfo, ips);
}
return ips.ordinality() - len;
}
void EnvHelper::processNodeAddress(IPropertyTree * param)
{
const char* ipList = param->queryProp("@ip-list");
if (ipList)
{
formIPList(ipList, m_ipArray);
processNodeAddress(ipList, m_ipArray);
}
const char* ipFileName = param->queryProp("@ip-file");
if (ipFileName)
{
processNodeAddress(ipFileName, m_ipArray, true);
}
if (m_ipArray.ordinality() > 0)
{
if (m_numOfCompSigned) delete [] m_numOfCompSigned;
m_numOfCompSigned = new int(m_ipArray.ordinality());
for (unsigned i=0; i < m_ipArray.ordinality(); i++)
m_numOfCompSigned[i] = 0;
}
}
bool EnvHelper::getCompNodeList(const char * compName, StringArray *ipList, const char *cluster)
{
return true;
}
const char* EnvHelper::assignNode(const char * compName)
{
return NULL;
}
bool EnvHelper::validateAndToInteger(const char *str,int &out, bool throwExcepFlag)
{
bool bIsValid = false;
char *end = NULL;
errno = 0;
const long sl = strtol(str,&end,10);
if (end == str)
{
if (throwExcepFlag)
throw MakeStringException( CfgEnvErrorCode::NonInteger , "Error: non-integer parameter '%s' specified.\n",str);
}
else if ('\0' != *end)
{
if (throwExcepFlag)
throw MakeStringException( CfgEnvErrorCode::NonInteger , "Error: non-integer characters found in '%s' when expecting integer input.\n",str);
}
else if ( (INT_MAX < sl || INT_MIN > sl) || ((LONG_MIN == sl || LONG_MAX == sl) && ERANGE == errno))
{
if (throwExcepFlag)
throw MakeStringException( CfgEnvErrorCode::OutOfRange , "Error: integer '%s' is out of range.\n",str);
}
else
{
out = (int)sl;
bIsValid = true;
}
return bIsValid;
}
const char* EnvHelper::getXMLTagName(const char* name)
{
if (!name)
throw MakeStringException(CfgEnvErrorCode::InvalidParams, "Null string in getXMLTagName");
const char * nameLC = (StringBuffer(name).toLowerCase()).str();
if (!strcmp(nameLC, "hardware") || !strcmp(nameLC, "hd"))
return XML_TAG_HARDWARE;
else if (!strcmp(nameLC, "computer") || !strcmp(nameLC, "cmpt"))
return XML_TAG_COMPUTER;
else if (!strcmp(nameLC, "software") || !strcmp(nameLC, "sw"))
return XML_TAG_SOFTWARE;
else if (!strcmp(nameLC, "envsettings") || !strcmp(nameLC, "es"))
return "EnvSettings";
else if (!strcmp(nameLC, "programs") || !strcmp(nameLC, "pg") ||
!strcmp(nameLC, "build") || !strcmp(nameLC, "bd"))
return "Programs/Build";
else if (!strcmp(nameLC, "directories") || !strcmp(nameLC, "dirs"))
return XML_TAG_DIRECTORIES;
else if (!strcmp(nameLC, "roxie") || !strcmp(nameLC, "roxiecluster"))
return XML_TAG_ROXIECLUSTER;
else if (!strcmp(nameLC, "thor") || !strcmp(nameLC, "thorcluster"))
return XML_TAG_THORCLUSTER;
else if (!strcmp(nameLC, "dali") || !strcmp(nameLC, "daliserverprocess") ||
!strcmp(nameLC, "dalisrv"))
return XML_TAG_DALISERVERPROCESS;
else if (!strcmp(nameLC, "dafile") || !strcmp(nameLC, "dafilesrv") ||
!strcmp(nameLC, "dafileserverprocess"))
return XML_TAG_DAFILESERVERPROCESS;
else if (!strcmp(nameLC, "dfu") || !strcmp(nameLC, "dfusrv") ||
!strcmp(nameLC, "dfuserverprocess"))
return "DfuServerProcess";
else if (!strcmp(nameLC, "dropzone"))
return XML_TAG_DROPZONE;
else if (!strcmp(nameLC, "eclcc"))
return "EclCCProcess";
else if (!strcmp(nameLC, "eclccsrv") || !strcmp(nameLC, "eclccserver") || !strcmp(nameLC, "eclcc"))
return XML_TAG_ECLCCSERVERPROCESS;
else if (!strcmp(nameLC, "esp") || !strcmp(nameLC, "espprocess"))
return XML_TAG_ESPPROCESS;
else if (!strcmp(nameLC, "espsvc") || !strcmp(nameLC, "espservice") || !strcmp(nameLC, "espsmc") ||
!strcmp(nameLC, "ws_sql") || !strcmp(nameLC, "DynamicESDL") || !strcmp(nameLC, "wslogging") ||
!strcmp(nameLC, "ws_ecl"))
return XML_TAG_ESPSERVICE;
else if (!strcmp(nameLC, "binding") || !strcmp(nameLC, "espbinding"))
return XML_TAG_ESPBINDING;
else if (!strcmp(nameLC, "sasha") || !strcmp(nameLC, "sashasrv"))
return XML_TAG_SASHA_SERVER_PROCESS;
else if (!strcmp(nameLC, "eclsch") || !strcmp(nameLC, "eclscheduler"))
return XML_TAG_ECLSCHEDULERPROCESS;
else if (!strcmp(nameLC, "agent") || !strcmp(nameLC, "eclagent"))
return XML_TAG_ECLAGENTPROCESS;
else if (!strcmp(nameLC, "topology") || !strcmp(nameLC, "topo"))
return XML_TAG_TOPOLOGY;
else if (!strcmp(nameLC, "ftslave") || !strcmp(nameLC, "ftslaveprocess"))
return "FTSlaveProcess";
else if (!strcmp(nameLC, "backupnode") || !strcmp(nameLC, "backup") || !strcmp(nameLC, "BackupNodeProcess"))
return "BackupNodeProcess";
else
return name;
}
IPropertyTree * EnvHelper::clonePTree(const char* xpath)
{
StringBuffer error;
if (!validateXPathSyntax(xpath, &error))
throw MakeStringException(CfgEnvErrorCode::InvalidParams,
"Syntax error in xpath %s: %s", xpath, error.str());
IPropertyTree *src = m_envTree->queryPropTree(xpath);
return clonePTree(src);
}
IPropertyTree * EnvHelper::clonePTree(IPropertyTree *src)
{
StringBuffer xml;
toXML(src, xml);
return createPTreeFromXMLString(xml.str());
}
}
| 29.751323
| 146
| 0.65899
|
davidarcher
|
fd70cfc66f7fe2a203060bb684887e5724c6ecc4
| 3,204
|
cpp
|
C++
|
SDK/Plugin/Block/SidechainMerkleBlock.cpp
|
alexpan0610/Elastos.ELA.SPV.Cpp
|
18a089ed0d0c1551868442d2d7e4a1cc7087332e
|
[
"MIT"
] | null | null | null |
SDK/Plugin/Block/SidechainMerkleBlock.cpp
|
alexpan0610/Elastos.ELA.SPV.Cpp
|
18a089ed0d0c1551868442d2d7e4a1cc7087332e
|
[
"MIT"
] | null | null | null |
SDK/Plugin/Block/SidechainMerkleBlock.cpp
|
alexpan0610/Elastos.ELA.SPV.Cpp
|
18a089ed0d0c1551868442d2d7e4a1cc7087332e
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2012-2018 The Elastos Open Source Project
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "MerkleBlock.h"
#include "SidechainMerkleBlock.h"
#include <SDK/Common/Log.h>
#include <SDK/Common/Utils.h>
#include <SDK/Plugin/Registry.h>
#include <SDK/Common/hash.h>
#include <sstream>
#define MAX_PROOF_OF_WORK 0xff7fffff // highest value for difficulty target
namespace Elastos {
namespace ElaWallet {
SidechainMerkleBlock::SidechainMerkleBlock() {
}
SidechainMerkleBlock::~SidechainMerkleBlock() {
}
void SidechainMerkleBlock::Serialize(ByteStream &ostream) const {
MerkleBlockBase::SerializeNoAux(ostream);
idAuxPow.Serialize(ostream);
ostream.WriteUint8(1);
MerkleBlockBase::SerializeAfterAux(ostream);
}
bool SidechainMerkleBlock::Deserialize(const ByteStream &istream) {
if (!MerkleBlockBase::DeserializeNoAux(istream) || !idAuxPow.Deserialize(istream))
return false;
istream.Skip(1);
if (!MerkleBlockBase::DeserializeAfterAux(istream))
return false;
GetHash();
return true;
}
const uint256 &SidechainMerkleBlock::GetHash() const {
if (_blockHash == 0) {
ByteStream ostream;
MerkleBlockBase::SerializeNoAux(ostream);
_blockHash = sha256_2(ostream.GetBytes());
}
return _blockHash;
}
bool SidechainMerkleBlock::IsValid(uint32_t currentTime) const {
// target is in "compact" format, where the most significant byte is the size of resulting value in bytes, the next
// bit is the sign, and the remaining 23bits is the value after having been right shifted by (size - 3)*8 bits
static const uint32_t maxsize = MAX_PROOF_OF_WORK >> 24, maxtarget = MAX_PROOF_OF_WORK & 0x00ffffff;
const uint32_t size = _target >> 24, target = _target & 0x00ffffff;
size_t hashIdx = 0, flagIdx = 0;
uint256 merkleRoot = MerkleBlockBase::MerkleBlockRootR(&hashIdx, &flagIdx, 0), t;
int r = 1;
// check if merkle root is correct
if (_totalTx > 0 && merkleRoot != _merkleRoot) r = 0;
// check if timestamp is too far in future
if (_timestamp > currentTime + BLOCK_MAX_TIME_DRIFT) r = 0;
// check if proof-of-work target is out of range
if (target == 0 || target & 0x00800000 || size > maxsize || (size == maxsize && target > maxtarget)) r = 0;
//todo verify block hash
// if (size > 3) UInt32SetLE(&t.u8[size - 3], target);
// else UInt32SetLE(t.u8, target >> (3 - size) * 8);
// uint256 auxBlockHash = _merkleBlock->auxPow.getParBlockHeaderHash();
// for (int i = sizeof(t) - 1; r && i >= 0; i--) { // check proof-of-work
// if (auxBlockHash.u8[i] < t.u8[i]) break;
// if (auxBlockHash.u8[i] > t.u8[i]) r = 0;
// }
return r;
}
std::string SidechainMerkleBlock::GetBlockType() const {
return "SideStandard";
}
MerkleBlockPtr SidechainMerkleBlockFactory::createBlock() {
return MerkleBlockPtr(new SidechainMerkleBlock);
}
fruit::Component<ISidechainMerkleBlockFactory> getSidechainMerkleBlockFactoryComponent() {
return fruit::createComponent()
.bind<ISidechainMerkleBlockFactory, SidechainMerkleBlockFactory>();
}
}
}
| 32.363636
| 118
| 0.707865
|
alexpan0610
|
fd71e098370110c1895a3f40406f7e48a715938a
| 6,921
|
cc
|
C++
|
src/xpgom/gomwrappeddocument.cc
|
jberkman/gom
|
4bccfec5e5ada830a4c5f076dfefb9ad9baab6a5
|
[
"MIT"
] | null | null | null |
src/xpgom/gomwrappeddocument.cc
|
jberkman/gom
|
4bccfec5e5ada830a4c5f076dfefb9ad9baab6a5
|
[
"MIT"
] | null | null | null |
src/xpgom/gomwrappeddocument.cc
|
jberkman/gom
|
4bccfec5e5ada830a4c5f076dfefb9ad9baab6a5
|
[
"MIT"
] | null | null | null |
/*
The MIT License
Copyright (c) 2008 jacob berkman <jacob@ilovegom.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 "config.h"
#include "gom/dom/gomdocument.h"
#include "gom/dom/gomdomexception.h"
#include "xpgom/gomwrappeddocument.hh"
#include "xpgom/xgDocument.hh"
#include <nsIDOMDocument.h>
#include <nsCOMPtr.h>
#include <nsIDOMElement.h>
#include <nsIDOMDocumentType.h>
#include <nsIDOMDOMImplementation.h>
#include "gommacros.h"
enum {
PROP_DOCTYPE = 1,
PROP_IMPLEMENTATION,
PROP_DOCUMENT_ELEMENT,
PROP_NODE_NAME,
PROP_NODE_TYPE,
PROP_DOCUMENT_URI
};
#define GET_DOCUMENT(i) GOM_WRAPPED_GET (i, nsIDOMDocument, mDoc)
static void
gom_wrapped_document_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
GET_DOCUMENT (object);
switch (property_id) {
case PROP_DOCUMENT_ELEMENT:
GOM_WRAPPED_GET_OBJECT (mDoc, GetDocumentElement, nsIDOMElement, GOM_TYPE_ELEMENT, GomElement);
break;
case PROP_DOCTYPE:
GOM_WRAPPED_GET_OBJECT (mDoc, GetDoctype, nsIDOMDocumentType, GOM_TYPE_DOCUMENT_TYPE, GomDocumentType);
break;
case PROP_IMPLEMENTATION:
GOM_WRAPPED_GET_OBJECT (mDoc, GetImplementation, nsIDOMDOMImplementation, GOM_TYPE_DOM_IMPLEMENTATION, GomDOMImplementation);
break;
#if 0
case PROP_DOCUMENT_URI:
GOM_WRAPPED_GET_STRING (mDoc, GetDocumentURI);
break;
#endif
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
gom_wrapped_document_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
GET_DOCUMENT (object);
switch (property_id) {
case PROP_DOCTYPE:
case PROP_IMPLEMENTATION:
case PROP_DOCUMENT_URI:
GOM_NOT_IMPLEMENTED;
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static GomElement *
gom_wrapped_document_create_element (GomDocument *doc,
const char *tag_name,
GError **error)
{
GOM_NOT_IMPLEMENTED_ERROR (error);
return NULL;
}
static GomDocumentFragment *
gom_wrapped_document_create_document_fragment (GomDocument *doc)
{
GOM_NOT_IMPLEMENTED;
return NULL;
}
static GomText *
gom_wrapped_document_create_text_node (GomDocument *doc,
const char *data)
{
GOM_NOT_IMPLEMENTED;
return NULL;
}
static GomComment *
gom_wrapped_document_create_comment (GomDocument *doc,
const char *data)
{
GOM_NOT_IMPLEMENTED;
return NULL;
}
static GomCDATASection *
gom_wrapped_document_create_cdata_section (GomDocument *doc,
const char *data,
GError **error)
{
GOM_NOT_IMPLEMENTED_ERROR (error);
return NULL;
}
static GomProcessingInstruction *
gom_wrapped_document_create_processing_instruction (GomDocument *doc,
const char *target,
const char *data,
GError **error)
{
GOM_NOT_IMPLEMENTED_ERROR (error);
return NULL;
}
static GomAttr *
gom_wrapped_document_create_attribute (GomDocument *doc,
const char *name,
GError **error)
{
GOM_NOT_IMPLEMENTED_ERROR (error);
return NULL;
}
static GomEntityReference *
gom_wrapped_document_create_entity_reference (GomDocument *doc,
const char *name,
GError **error)
{
GOM_NOT_IMPLEMENTED_ERROR (error);
return NULL;
}
static GomNodeList *
gom_wrapped_document_get_elements_by_tag_name (GomDocument *doc,
const char *tag_name)
{
GOM_NOT_IMPLEMENTED;
return NULL;
}
/* Introduced in DOM Level 2: */
static GomNode *
gom_wrapped_document_import_node (GomDocument *doc,
GomNode *node,
gboolean deep,
GError **error)
{
GOM_NOT_IMPLEMENTED_ERROR (error);
return NULL;
}
static GomElement *
gom_wrapped_document_create_element_ns (GomDocument *doc,
const char *namespace_uri,
const char *qualified_name,
GError **error)
{
GOM_NOT_IMPLEMENTED_ERROR (error);
return NULL;
}
static GomAttr *
gom_wrapped_document_create_attribute_ns (GomDocument *doc,
const char *namespace_uri,
const char *qualified_name,
GError **error)
{
GOM_NOT_IMPLEMENTED_ERROR (error);
return NULL;
}
static GomNodeList *
gom_wrapped_document_get_elements_by_tag_name_ns (GomDocument *doc,
const char *namespace_uri,
const char *local_name)
{
GOM_NOT_IMPLEMENTED;
return NULL;
}
static GomElement *
gom_wrapped_document_get_element_by_id (GomDocument *doc,
const char *element_id)
{
GOM_NOT_IMPLEMENTED;
return NULL;
}
GOM_WRAPPED_CONSTRUCTOR_INIT (xgDocument, Init)
GOM_IMPLEMENT (DOCUMENT, document, gom_wrapped_document);
G_DEFINE_TYPE_WITH_CODE (GomWrappedDocument, gom_wrapped_document, GOM_TYPE_WRAPPED_NODE,
GOM_IMPLEMENT_INTERFACE (DOCUMENT, document, gom_wrapped_document));
static void gom_wrapped_document_init (GomWrappedDocument *document) { }
static void
gom_wrapped_document_class_init (GomWrappedDocumentClass *klass)
{
GObjectClass *oclass = G_OBJECT_CLASS (klass);
oclass->get_property = gom_wrapped_document_get_property;
oclass->set_property = gom_wrapped_document_set_property;
g_object_class_override_property (oclass, PROP_DOCTYPE, "doctype");
g_object_class_override_property (oclass, PROP_IMPLEMENTATION, "implementation");
g_object_class_override_property (oclass, PROP_DOCUMENT_ELEMENT, "document-element");
g_object_class_override_property (oclass, PROP_NODE_NAME, "node-name");
g_object_class_override_property (oclass, PROP_NODE_TYPE, "node-type");
g_object_class_override_property (oclass, PROP_DOCUMENT_URI, "document-u-r-i");
gom_wrapped_register_interface (GOM_TYPE_DOCUMENT, GOM_TYPE_WRAPPED_DOCUMENT,
NS_GET_IID (nsIDOMDocument), xgDocumentConstructor);
}
| 27.573705
| 126
| 0.742956
|
jberkman
|
fd724fb6359a073343a734b542d42d39b738094e
| 2,446
|
hpp
|
C++
|
3rdParty/occa/include/occa/lang/transforms/builtins/replacer.hpp
|
krowe-alcf/nekBench
|
d314ca6b942076620dd7dab8f11df97be977c5db
|
[
"BSD-3-Clause"
] | 4
|
2020-02-26T19:33:16.000Z
|
2020-12-06T07:50:11.000Z
|
3rdParty/occa/include/occa/lang/transforms/builtins/replacer.hpp
|
krowe-alcf/nekBench
|
d314ca6b942076620dd7dab8f11df97be977c5db
|
[
"BSD-3-Clause"
] | 12
|
2020-05-13T03:50:11.000Z
|
2021-09-16T16:26:06.000Z
|
3rdParty/occa/include/occa/lang/transforms/builtins/replacer.hpp
|
krowe-alcf/nekBench
|
d314ca6b942076620dd7dab8f11df97be977c5db
|
[
"BSD-3-Clause"
] | 10
|
2020-03-02T15:55:02.000Z
|
2021-12-03T02:44:10.000Z
|
#ifndef OCCA_LANG_TRANSFORMS_BUILTINS_REPLACER_HEADER
#define OCCA_LANG_TRANSFORMS_BUILTINS_REPLACER_HEADER
#include <occa/lang/transforms/exprTransform.hpp>
#include <occa/lang/transforms/builtins/finders.hpp>
namespace occa {
namespace lang {
namespace transforms {
class typeReplacer_t : public statementExprTransform {
private:
const type_t *from;
type_t *to;
public:
typeReplacer_t();
virtual exprNode* transformExprNode(exprNode &node);
void set(const type_t &from_,
type_t &to_);
bool applyToExpr(exprNode *&expr);
};
class variableReplacer_t : public statementExprTransform {
private:
const variable_t *from;
variable_t *to;
public:
variableReplacer_t();
virtual exprNode* transformExprNode(exprNode &node);
void set(const variable_t &from_,
variable_t &to_);
bool applyToExpr(exprNode *&expr);
};
class functionReplacer_t : public statementExprTransform {
private:
const function_t *from;
function_t *to;
public:
functionReplacer_t();
virtual exprNode* transformExprNode(exprNode &node);
void set(const function_t &from_,
function_t &to_);
bool applyToExpr(exprNode *&expr);
};
}
void replaceTypes(statement_t &smnt,
const type_t &from,
type_t &to);
void replaceTypes(exprNode &expr,
const type_t &from,
type_t &to);
void replaceVariables(statement_t &smnt,
const variable_t &from,
variable_t &to);
void replaceVariables(exprNode &expr,
const variable_t &from,
variable_t &to);
void replaceFunctions(statement_t &smnt,
const function_t &from,
function_t &to);
void replaceFunctions(exprNode &expr,
const function_t &from,
function_t &to);
void replaceKeywords(statement_t &smnt,
const keyword_t &from,
keyword_t &to);
void replaceKeywords(exprNode &expr,
const keyword_t &from,
keyword_t &to);
}
}
#endif
| 26.021277
| 64
| 0.560098
|
krowe-alcf
|
fd7fdf512126c8ab72e0761c16fac614a8a22989
| 1,547
|
cpp
|
C++
|
Zork/Creature.cpp
|
GBMiro/Zork
|
219683b488c09592d0bc94deef4457524c6df1a8
|
[
"MIT"
] | null | null | null |
Zork/Creature.cpp
|
GBMiro/Zork
|
219683b488c09592d0bc94deef4457524c6df1a8
|
[
"MIT"
] | null | null | null |
Zork/Creature.cpp
|
GBMiro/Zork
|
219683b488c09592d0bc94deef4457524c6df1a8
|
[
"MIT"
] | null | null | null |
#include "Creature.h"
#include "Player.h"
Creature::Creature(const string& name, const string& description, int HP, int damage, int defense)
: Entity(name, description)
{
type = creature;
this->HP = HP;
this->currentHP = HP;
this->damage = damage;
this->defense = defense;
}
Creature::~Creature()
{
}
void Creature::showDescription() const
{
cout << name << ": " << description << endl;
}
bool Creature::isAlive() const
{
return currentHP > 0;
}
void Creature::attack(const vector<string>& action) const
{
}
void Creature::showStats() const
{
cout << "Name: " << name << endl;
cout << "Total health points: " << HP << endl;
cout << "Current health points: " << currentHP << endl;
cout << "Damage: " << damage << endl;
cout << "Defense: " << defense << endl;
cout << "Status: " << (this->isAlive() ? "Alive" : "Dead") << endl;
}
void Creature::update()
{
if (isAlive()) {
attackPlayer();
}
}
void Creature::attackPlayer() const
{
Player* playerFound = (Player*)getRoom()->getPlayer();
if (playerFound != NULL) {
int damageDealt = damage - playerFound->getTotalDefense() > 0 ? damage - playerFound->getTotalDefense() : 0;
playerFound->currentHP = playerFound->currentHP - damageDealt < 0 ? 0 : playerFound->currentHP - damageDealt;
cout << this->name << " attack you! You lost " << damageDealt << " health points." << endl;
if (!playerFound->isAlive()) {
cout << "You were killed by the " << this->name << ". Game Over" << endl;
}
}
}
Room* Creature::getRoom() const
{
return (Room*)location;
}
| 23.439394
| 112
| 0.634777
|
GBMiro
|
fd814491c924a81cee52114c28548a74daa214c4
| 13,078
|
cpp
|
C++
|
training/supplements/src/dx100/src/joint_trajectory_action.cpp
|
asct/industrial_training
|
f69c54cad966382ce93b34138696a99abc66f444
|
[
"Apache-2.0"
] | null | null | null |
training/supplements/src/dx100/src/joint_trajectory_action.cpp
|
asct/industrial_training
|
f69c54cad966382ce93b34138696a99abc66f444
|
[
"Apache-2.0"
] | null | null | null |
training/supplements/src/dx100/src/joint_trajectory_action.cpp
|
asct/industrial_training
|
f69c54cad966382ce93b34138696a99abc66f444
|
[
"Apache-2.0"
] | null | null | null |
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Southwest Research Institute
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Southwest Research Institute, nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <actionlib/server/action_server.h>
#include <trajectory_msgs/JointTrajectory.h>
#include <control_msgs/FollowJointTrajectoryAction.h>
#include <control_msgs/FollowJointTrajectoryFeedback.h>
#include <industrial_msgs/RobotStatus.h>
const double DEFAULT_GOAL_THRESHOLD = 0.01;
class JointTrajectoryExecuter
{
private:
typedef actionlib::ActionServer<control_msgs::FollowJointTrajectoryAction> JTAS;
typedef JTAS::GoalHandle GoalHandle;
public:
JointTrajectoryExecuter(ros::NodeHandle &n) :
node_(n), action_server_(node_, "joint_trajectory_action",
boost::bind(&JointTrajectoryExecuter::goalCB, this, _1),
boost::bind(&JointTrajectoryExecuter::cancelCB, this, _1), false), has_active_goal_(
false)
{
using namespace XmlRpc;
ros::NodeHandle pn("~");
joint_names_.push_back("joint_s");
joint_names_.push_back("joint_l");
joint_names_.push_back("joint_e");
joint_names_.push_back("joint_u");
joint_names_.push_back("joint_r");
joint_names_.push_back("joint_b");
joint_names_.push_back("joint_t");
pn.param("constraints/goal_time", goal_time_constraint_, 0.0);
// Gets the constraints for each joint.
for (size_t i = 0; i < joint_names_.size(); ++i)
{
std::string ns = std::string("constraints/") + joint_names_[i];
double g, t;
pn.param(ns + "/goal", g, DEFAULT_GOAL_THRESHOLD);
pn.param(ns + "/trajectory", t, -1.0);
goal_constraints_[joint_names_[i]] = g;
trajectory_constraints_[joint_names_[i]] = t;
}
pn.param("constraints/stopped_velocity_tolerance", stopped_velocity_tolerance_, 0.01);
pub_controller_command_ = node_.advertise<trajectory_msgs::JointTrajectory>("command", 1);
sub_controller_state_ = node_.subscribe("feedback_states", 1, &JointTrajectoryExecuter::controllerStateCB, this);
sub_robot_status_ = node_.subscribe("robot_status", 1, &JointTrajectoryExecuter::robotStatusCB, this);
action_server_.start();
}
~JointTrajectoryExecuter()
{
pub_controller_command_.shutdown();
sub_controller_state_.shutdown();
watchdog_timer_.stop();
}
void robotStatusCB(const industrial_msgs::RobotStatusConstPtr &msg)
{
last_robot_status_ = *msg; //caching robot status for later use.
}
bool withinGoalConstraints(const control_msgs::FollowJointTrajectoryFeedbackConstPtr &msg,
const std::map<std::string, double>& constraints,
const trajectory_msgs::JointTrajectory& traj)
{
ROS_DEBUG("Checking goal contraints");
int last = traj.points.size() - 1;
for (size_t i = 0; i < msg->joint_names.size(); ++i)
{
double abs_error = fabs(msg->actual.positions[i] - traj.points[last].positions[i]);
double goal_constraint = constraints.at(msg->joint_names[i]);
if (goal_constraint >= 0 && abs_error > goal_constraint)
{
ROS_DEBUG("Bad constraint: %f, abs_errs: %f", goal_constraint, abs_error);
return false;
}
ROS_DEBUG("Checking constraint: %f, abs_errs: %f", goal_constraint, abs_error);
}
return true;
}
private:
static bool setsEqual(const std::vector<std::string> &a, const std::vector<std::string> &b)
{
if (a.size() != b.size())
return false;
for (size_t i = 0; i < a.size(); ++i)
{
if (count(b.begin(), b.end(), a[i]) != 1)
return false;
}
for (size_t i = 0; i < b.size(); ++i)
{
if (count(a.begin(), a.end(), b[i]) != 1)
return false;
}
return true;
}
void watchdog(const ros::TimerEvent &e)
{
ros::Time now = ros::Time::now();
// Aborts the active goal if the controller does not appear to be active.
if (has_active_goal_)
{
bool should_abort = false;
if (!last_controller_state_)
{
should_abort = true;
ROS_WARN("Aborting goal because we have never heard a controller state message.");
}
else if ((now - last_controller_state_->header.stamp) > ros::Duration(5.0))
{
should_abort = true;
ROS_WARN(
"Aborting goal because we haven't heard from the controller in %.3lf seconds", (now - last_controller_state_->header.stamp).toSec());
}
if (should_abort)
{
// Stops the controller.
trajectory_msgs::JointTrajectory empty;
empty.joint_names = joint_names_;
pub_controller_command_.publish(empty);
// Marks the current goal as aborted.
active_goal_.setAborted();
has_active_goal_ = false;
}
}
}
void goalCB(GoalHandle gh)
{
// Ensures that the joints in the goal match the joints we are commanding.
ROS_DEBUG("Received goal: goalCB");
if (!setsEqual(joint_names_, gh.getGoal()->trajectory.joint_names))
{
ROS_ERROR("Joints on incoming goal don't match our joints");
gh.setRejected();
return;
}
// Cancels the currently active goal.
if (has_active_goal_)
{
ROS_DEBUG("Received new goal, canceling current goal");
// Stops the controller.
trajectory_msgs::JointTrajectory empty;
empty.joint_names = joint_names_;
pub_controller_command_.publish(empty);
// Marks the current goal as canceled.
active_goal_.setCanceled();
has_active_goal_ = false;
}
// Sends the trajectory along to the controller
if (withinGoalConstraints(last_controller_state_, goal_constraints_, gh.getGoal()->trajectory))
{
ROS_INFO_STREAM("Already within goal constraints");
gh.setAccepted();
gh.setSucceeded();
}
else
{
gh.setAccepted();
active_goal_ = gh;
has_active_goal_ = true;
ROS_INFO("Publishing trajectory");
current_traj_ = active_goal_.getGoal()->trajectory;
pub_controller_command_.publish(current_traj_);
}
}
void cancelCB(GoalHandle gh)
{
ROS_DEBUG("Received action cancel request");
if (active_goal_ == gh)
{
// Stops the controller.
trajectory_msgs::JointTrajectory empty;
empty.joint_names = joint_names_;
pub_controller_command_.publish(empty);
// Marks the current goal as canceled.
active_goal_.setCanceled();
has_active_goal_ = false;
}
}
ros::NodeHandle node_;
JTAS action_server_;
ros::Publisher pub_controller_command_;
ros::Subscriber sub_controller_state_;
ros::Subscriber sub_robot_status_;
ros::Timer watchdog_timer_;
bool has_active_goal_;
GoalHandle active_goal_;
trajectory_msgs::JointTrajectory current_traj_;
std::vector<std::string> joint_names_;
std::map<std::string, double> goal_constraints_;
std::map<std::string, double> trajectory_constraints_;
double goal_time_constraint_;
double stopped_velocity_tolerance_;
control_msgs::FollowJointTrajectoryFeedbackConstPtr last_controller_state_;
industrial_msgs::RobotStatus last_robot_status_;
void controllerStateCB(const control_msgs::FollowJointTrajectoryFeedbackConstPtr &msg)
{
//ROS_DEBUG("Checking controller state feedback");
last_controller_state_ = msg;
ros::Time now = ros::Time::now();
if (!has_active_goal_)
{
//ROS_DEBUG("No active goal, ignoring feedback");
return;
}
if (current_traj_.points.empty())
{
ROS_DEBUG("Current trajectory is empty, ignoring feedback");
return;
}
/* NOT CONCERNED ABOUT TRAJECTORY TIMING AT THIS POINT
if (now < current_traj_.header.stamp + current_traj_.points[0].time_from_start)
return;
*/
if (!setsEqual(joint_names_, msg->joint_names))
{
ROS_ERROR("Joint names from the controller don't match our joint names.");
return;
}
// Checking for goal constraints
// Checks that we have ended inside the goal constraints and has motion stopped
ROS_DEBUG("Checking goal constraints");
if (withinGoalConstraints(msg, goal_constraints_, current_traj_))
{
// Additional check for motion stoppage since the controller goal may still
// be moving. The current robot driver calls a motion stop if it receives
// a new trajectory while it is still moving. If the driver is not publishing
// the motion state (i.e. old driver), this will still work, but it warns you.
if (last_robot_status_.in_motion.val == industrial_msgs::TriState::FALSE)
{
ROS_INFO("Inside goal constraints, stopped moving, return success for action");
active_goal_.setSucceeded();
has_active_goal_ = false;
}
else if (last_robot_status_.in_motion.val == industrial_msgs::TriState::UNKNOWN)
{
ROS_INFO("Inside goal constraints, return success for action");
ROS_WARN("Robot status: in motion unknown, the robot driver node and controller code should be updated");
active_goal_.setSucceeded();
has_active_goal_ = false;
}
else
{
ROS_DEBUG("Within goal constraints but robot is still moving");
}
}
// Verifies that the controller has stayed within the trajectory constraints.
/* DISABLING THIS MORE COMPLICATED GOAL CHECKING AND ERROR DETECTION
int last = current_traj_.points.size() - 1;
ros::Time end_time = current_traj_.header.stamp + current_traj_.points[last].time_from_start;
if (now < end_time)
{
// Checks that the controller is inside the trajectory constraints.
for (size_t i = 0; i < msg->joint_names.size(); ++i)
{
double abs_error = fabs(msg->error.positions[i]);
double constraint = trajectory_constraints_[msg->joint_names[i]];
if (constraint >= 0 && abs_error > constraint)
{
// Stops the controller.
trajectory_msgs::JointTrajectory empty;
empty.joint_names = joint_names_;
pub_controller_command_.publish(empty);
active_goal_.setAborted();
has_active_goal_ = false;
ROS_WARN("Aborting because we would up outside the trajectory constraints");
return;
}
}
}
else
{
// Checks that we have ended inside the goal constraints
bool inside_goal_constraints = true;
for (size_t i = 0; i < msg->joint_names.size() && inside_goal_constraints; ++i)
{
double abs_error = fabs(msg->error.positions[i]);
double goal_constraint = goal_constraints_[msg->joint_names[i]];
if (goal_constraint >= 0 && abs_error > goal_constraint)
inside_goal_constraints = false;
// It's important to be stopped if that's desired.
if (fabs(msg->desired.velocities[i]) < 1e-6)
{
if (fabs(msg->actual.velocities[i]) > stopped_velocity_tolerance_)
inside_goal_constraints = false;
}
}
if (inside_goal_constraints)
{
active_goal_.setSucceeded();
has_active_goal_ = false;
}
else if (now < end_time + ros::Duration(goal_time_constraint_))
{
// Still have some time left to make it.
}
else
{
ROS_WARN("Aborting because we wound up outside the goal constraints");
active_goal_.setAborted();
has_active_goal_ = false;
}
}
*/
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "joint_trajectory_action_node");
ros::NodeHandle node; //("~");
JointTrajectoryExecuter jte(node);
ros::spin();
return 0;
}
| 33.793282
| 145
| 0.678238
|
asct
|
fd835969c4cb9bef93e515b2d29662f1f6643f98
| 4,773
|
cpp
|
C++
|
src/rendering/nodes/CullingNode.cpp
|
Shimmen/ArkoseRenderer
|
d39e1b3d5f5b669370b8aeed5cd1cfada5216763
|
[
"MIT"
] | 7
|
2020-11-02T22:27:27.000Z
|
2022-01-11T04:25:48.000Z
|
src/rendering/nodes/CullingNode.cpp
|
Shimmen/ArkoseRenderer
|
d39e1b3d5f5b669370b8aeed5cd1cfada5216763
|
[
"MIT"
] | null | null | null |
src/rendering/nodes/CullingNode.cpp
|
Shimmen/ArkoseRenderer
|
d39e1b3d5f5b669370b8aeed5cd1cfada5216763
|
[
"MIT"
] | 2
|
2020-12-09T03:40:05.000Z
|
2021-09-14T03:12:40.000Z
|
#include "CullingNode.h"
#include "SceneNode.h"
#include "geometry/Frustum.h"
#include "utility/Logging.h"
#include "utility/Profiling.h"
#include <imgui.h>
// Shared shader headers
using uint = uint32_t;
#include "IndirectData.h"
#include "LightData.h"
CullingNode::CullingNode(Scene& scene)
: m_scene(scene)
{
}
RenderPipelineNode::ExecuteCallback CullingNode::constructFrame(Registry& reg) const
{
SCOPED_PROFILE_ZONE();
// todo: maybe default to smaller, and definitely actually grow when needed!
static constexpr size_t initialBufferCount = 1024;
Buffer& frustumPlaneBuffer = reg.createBuffer(6 * sizeof(vec4), Buffer::Usage::StorageBuffer, Buffer::MemoryHint::TransferOptimal);
Buffer& indirectDrawableBuffer = reg.createBuffer(initialBufferCount * sizeof(IndirectShaderDrawable), Buffer::Usage::StorageBuffer, Buffer::MemoryHint::TransferOptimal);
Buffer& drawableBuffer = reg.createBuffer(initialBufferCount * sizeof(ShaderDrawable), Buffer::Usage::StorageBuffer, Buffer::MemoryHint::GpuOnly);
drawableBuffer.setName("MainViewCulledDrawables");
BindingSet& drawableBindingSet = reg.createBindingSet({ { 0, ShaderStageVertex, &drawableBuffer } });
reg.publish("MainViewCulledDrawablesSet", drawableBindingSet);
Buffer& indirectCmdBuffer = reg.createBuffer(initialBufferCount * sizeof(IndexedDrawCmd), Buffer::Usage::IndirectBuffer, Buffer::MemoryHint::GpuOnly);
reg.publish("MainViewIndirectDrawCmds", indirectCmdBuffer);
Buffer& indirectCountBuffer = reg.createBuffer(sizeof(uint), Buffer::Usage::IndirectBuffer, Buffer::MemoryHint::TransferOptimal);
reg.publish("MainViewIndirectDrawCount", indirectCountBuffer);
BindingSet& cullingBindingSet = reg.createBindingSet({ { 0, ShaderStageCompute, &frustumPlaneBuffer },
{ 1, ShaderStageCompute, &indirectDrawableBuffer },
{ 2, ShaderStageCompute, &drawableBuffer },
{ 3, ShaderStageCompute, &indirectCmdBuffer },
{ 4, ShaderStageCompute, &indirectCountBuffer } });
ComputeState& cullingState = reg.createComputeState(Shader::createCompute("culling/culling.comp"), { &cullingBindingSet });
cullingState.setName("MainViewCulling");
return [&](const AppState& appState, CommandList& cmdList) {
mat4 cameraViewProjection = m_scene.camera().projectionMatrix() * m_scene.camera().viewMatrix();
auto cameraFrustum = geometry::Frustum::createFromProjectionMatrix(cameraViewProjection);
size_t planesByteSize;
const geometry::Plane* planesData = cameraFrustum.rawPlaneData(&planesByteSize);
ASSERT(planesByteSize == frustumPlaneBuffer.size());
frustumPlaneBuffer.updateData(planesData, planesByteSize);
std::vector<IndirectShaderDrawable> indirectDrawableData {};
int numInputDrawables = m_scene.forEachMesh([&](size_t, Mesh& mesh) {
DrawCallDescription drawCall = mesh.drawCallDescription({ VertexComponent::Position3F }, m_scene);
indirectDrawableData.push_back({ .drawable = { .worldFromLocal = mesh.transform().worldMatrix(),
.worldFromTangent = mat4(mesh.transform().worldNormalMatrix()),
.materialIndex = mesh.materialIndex().value_or(0) },
.localBoundingSphere = vec4(mesh.boundingSphere().center(), mesh.boundingSphere().radius()),
.indexCount = drawCall.indexCount,
.firstIndex = drawCall.firstIndex,
.vertexOffset = drawCall.vertexOffset });
});
size_t newSize = numInputDrawables * sizeof(IndirectShaderDrawable);
ASSERT(newSize <= indirectDrawableBuffer.size()); // fixme: grow instead of failing!
indirectDrawableBuffer.updateData(indirectDrawableData.data(), newSize);
uint32_t zero = 0u;
indirectCountBuffer.updateData(&zero, sizeof(zero));
cmdList.setComputeState(cullingState);
cmdList.bindSet(cullingBindingSet, 0);
cmdList.setNamedUniform("numInputDrawables", numInputDrawables);
cmdList.dispatch(Extent3D(numInputDrawables, 1, 1), Extent3D(64, 1, 1));
cmdList.bufferWriteBarrier({ &drawableBuffer, &indirectCmdBuffer, &indirectCountBuffer });
// It would be nice if we could do GPU readback from last frame's count buffer
//ImGui::Text("Issued draw calls: %i", numDrawCallsIssued);
};
}
| 54.862069
| 174
| 0.662057
|
Shimmen
|
fd873b7017c2da82d0993c9d7a5275bda9ca1c29
| 2,196
|
cpp
|
C++
|
Source/Runtime/Private/Scripting/Components/LuaModule_ComHingeJoint.cpp
|
ValtoForks/BlueshiftEngine
|
a6684aa3bf9b4bd22d5cc4d4b6647fea6b074fee
|
[
"Apache-2.0"
] | 410
|
2017-03-03T08:56:54.000Z
|
2022-03-29T07:18:46.000Z
|
Source/Runtime/Private/Scripting/Components/LuaModule_ComHingeJoint.cpp
|
kbb-uran/BlueshiftEngine
|
beb690093ca643c38437831c93581e29686ff508
|
[
"Apache-2.0"
] | 31
|
2017-03-05T11:37:44.000Z
|
2021-09-15T21:28:34.000Z
|
Source/Runtime/Private/Scripting/Components/LuaModule_ComHingeJoint.cpp
|
kbb-uran/BlueshiftEngine
|
beb690093ca643c38437831c93581e29686ff508
|
[
"Apache-2.0"
] | 48
|
2017-03-18T05:28:21.000Z
|
2022-03-05T12:27:17.000Z
|
// Copyright(c) 2017 POLYGONTEK
//
// 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 "Precompiled.h"
#include "Scripting/LuaVM.h"
#include "Components/ComHingeJoint.h"
BE_NAMESPACE_BEGIN
void LuaVM::RegisterHingeJointComponent(LuaCpp::Module &module) {
LuaCpp::Selector _ComHingeJoint = module["ComHingeJoint"];
_ComHingeJoint.SetClass<ComHingeJoint>(module["ComJoint"]);
_ComHingeJoint.AddClassMembers<ComHingeJoint>(
"local_anchor", &ComHingeJoint::GetLocalAnchor,
"set_local_anchor", &ComHingeJoint::SetLocalAnchor,
"local_angles", &ComHingeJoint::GetLocalAngles,
"set_local_angles", &ComHingeJoint::SetLocalAngles,
"connected_anchor", &ComHingeJoint::GetConnectedAnchor,
"set_connected_anchor", &ComHingeJoint::SetConnectedAnchor,
"connected_angles", &ComHingeJoint::GetConnectedAngles,
"set_connected_angles", &ComHingeJoint::SetConnectedAngles,
"enable_limit_angles", &ComHingeJoint::GetEnableLimitAngles,
"set_enable_limit_angles", &ComHingeJoint::SetEnableLimitAngles,
"minimum_angle", &ComHingeJoint::GetMinimumAngle,
"set_minimum_angle", &ComHingeJoint::SetMinimumAngle,
"maximum_angle", &ComHingeJoint::GetMaximumAngle,
"set_maximum_angle", &ComHingeJoint::SetMaximumAngle,
"motor_target_velocity", &ComHingeJoint::GetMotorTargetVelocity,
"set_motor_target_velocity", &ComHingeJoint::SetMotorTargetVelocity,
"max_motor_impulse", &ComHingeJoint::GetMaxMotorImpulse,
"set_max_motor_impulse", &ComHingeJoint::SetMaxMotorImpulse);
_ComHingeJoint["meta_object"] = ComHingeJoint::metaObject;
}
BE_NAMESPACE_END
| 44.816327
| 76
| 0.747723
|
ValtoForks
|
fd89b6628bd423088f7f2f3fc81e295ea971659f
| 1,084
|
cpp
|
C++
|
Project/PanelScene.cpp
|
JaimeBea/UPCMasterEngine
|
5989dcb77af734993e424d0a40289d922b356519
|
[
"MIT"
] | null | null | null |
Project/PanelScene.cpp
|
JaimeBea/UPCMasterEngine
|
5989dcb77af734993e424d0a40289d922b356519
|
[
"MIT"
] | null | null | null |
Project/PanelScene.cpp
|
JaimeBea/UPCMasterEngine
|
5989dcb77af734993e424d0a40289d922b356519
|
[
"MIT"
] | null | null | null |
#include "PanelScene.h"
#include "Globals.h"
#include "Application.h"
#include "ModuleEditor.h"
#include "ModuleCamera.h"
#include "ModuleRender.h"
#include "imgui.h"
#include "Math/float3x3.h"
#include "SDL_mouse.h"
#include "SDL_scancode.h"
#include "Leaks.h"
PanelScene::PanelScene() : Panel("Scene", true) {}
void PanelScene::Update()
{
ImGui::SetNextWindowDockID(App->editor->dock_main_id, ImGuiCond_FirstUseEver);
if (ImGui::Begin(name, &enabled))
{
// Update viewport size
ImVec2 size = ImGui::GetContentRegionAvail();
if (App->renderer->viewport_width != size.x || App->renderer->viewport_height != size.y)
{
App->camera->ViewportResized((int)size.x, (int)size.y);
App->renderer->ViewportResized((int)size.x, (int)size.y);
}
// Draw
ImGui::Image((void*)App->renderer->render_texture, size, ImVec2(0, 1), ImVec2(1, 0));
// Capture input
if (ImGui::IsWindowFocused())
{
ImGui::CaptureKeyboardFromApp(false);
if (ImGui::IsAnyMouseDown() || ImGui::IsItemHovered())
{
ImGui::CaptureMouseFromApp(false);
}
}
}
ImGui::End();
}
| 23.565217
| 90
| 0.685424
|
JaimeBea
|
fd8e7a8949b4f9c74c8d28a1fc6f497742ad0116
| 24,678
|
cpp
|
C++
|
tests/functional/olp-cpp-sdk-dataservice-read/DataserviceReadVersionedLayerClientTest.cpp
|
fermeise/here-data-sdk-cpp
|
e0ebd7bd74463fa3958eb0447b90227a4f322643
|
[
"Apache-2.0"
] | 21
|
2019-07-03T07:26:52.000Z
|
2019-09-04T08:35:07.000Z
|
tests/functional/olp-cpp-sdk-dataservice-read/DataserviceReadVersionedLayerClientTest.cpp
|
fermeise/here-data-sdk-cpp
|
e0ebd7bd74463fa3958eb0447b90227a4f322643
|
[
"Apache-2.0"
] | 639
|
2019-09-13T17:14:24.000Z
|
2020-05-13T11:49:14.000Z
|
tests/functional/olp-cpp-sdk-dataservice-read/DataserviceReadVersionedLayerClientTest.cpp
|
fermeise/here-data-sdk-cpp
|
e0ebd7bd74463fa3958eb0447b90227a4f322643
|
[
"Apache-2.0"
] | 21
|
2020-05-14T15:32:28.000Z
|
2022-03-15T13:52:33.000Z
|
/*
* Copyright (C) 2019-2021 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
#include <gtest/gtest.h>
#include <chrono>
#include <string>
#include <olp/authentication/AuthenticationCredentials.h>
#include <olp/authentication/Settings.h>
#include <olp/authentication/TokenProvider.h>
#include <olp/core/client/OlpClientSettings.h>
#include <olp/core/client/OlpClientSettingsFactory.h>
#include <olp/core/logging/Log.h>
#include <olp/core/porting/make_unique.h>
#include <olp/dataservice/read/VersionedLayerClient.h>
#include <testutils/CustomParameters.hpp>
#include "Utils.h"
namespace http = olp::http;
namespace dataservice_read = olp::dataservice::read;
namespace {
constexpr auto kWaitTimeout = std::chrono::seconds(10);
class DataserviceReadVersionedLayerClientTest : public ::testing::Test {
protected:
void SetUp() override {
auto network = olp::client::OlpClientSettingsFactory::
CreateDefaultNetworkRequestHandler();
auto appid =
CustomParameters::getArgument("dataservice_read_test_versioned_appid");
auto secret =
CustomParameters::getArgument("dataservice_read_test_versioned_secret");
olp::authentication::Settings auth_settings({appid, secret});
auth_settings.network_request_handler = network;
olp::authentication::TokenProviderDefault provider(auth_settings);
olp::client::AuthenticationSettings auth_client_settings;
auth_client_settings.token_provider = provider;
settings_ = std::make_shared<olp::client::OlpClientSettings>();
settings_->network_request_handler = network;
settings_->authentication_settings = auth_client_settings;
settings_->task_scheduler =
olp::client::OlpClientSettingsFactory::CreateDefaultTaskScheduler();
}
void TearDown() override {
auto network = std::move(settings_->network_request_handler);
settings_.reset();
// when test ends we must be sure that network pointer is not captured
// anywhere
ASSERT_EQ(network.use_count(), 1);
}
std::string GetTestCatalog() {
return CustomParameters::getArgument("dataservice_read_test_catalog");
}
template <typename T>
T GetExecutionTime(std::function<T()> func) {
auto start_time = std::chrono::high_resolution_clock::now();
auto result = func();
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> time = end - start_time;
std::cout << "duration: " << time.count() * 1000000 << " us" << std::endl;
return result;
}
std::shared_ptr<olp::client::OlpClientSettings> settings_;
};
TEST_F(DataserviceReadVersionedLayerClientTest, PrefetchWideRange) {
const auto catalog =
olp::client::HRN::FromString(CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_catalog"));
const auto kLayerId = CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_layer");
const auto kTileId = CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_tile");
auto client = std::make_unique<olp::dataservice::read::VersionedLayerClient>(
catalog, kLayerId, boost::none, *settings_);
{
SCOPED_TRACE("Prefetch tiles online and store them in memory cache");
std::vector<olp::geo::TileKey> tile_keys = {
olp::geo::TileKey::FromHereTile(kTileId)};
auto request = olp::dataservice::read::PrefetchTilesRequest()
.WithTileKeys(tile_keys)
.WithMinLevel(6)
.WithMaxLevel(12);
std::promise<dataservice_read::PrefetchTilesResponse> promise;
auto future = promise.get_future();
auto token = client->PrefetchTiles(
request, [&promise](dataservice_read::PrefetchTilesResponse response) {
promise.set_value(std::move(response));
});
ASSERT_NE(future.wait_for(kWaitTimeout), std::future_status::timeout);
dataservice_read::PrefetchTilesResponse response = future.get();
EXPECT_SUCCESS(response);
ASSERT_FALSE(response.GetResult().empty());
const auto& result = response.GetResult();
for (auto tile_result : result) {
EXPECT_SUCCESS(*tile_result);
ASSERT_TRUE(tile_result->tile_key_.IsValid());
}
}
{
SCOPED_TRACE("Read cached data from the same partition");
std::promise<dataservice_read::DataResponse> promise;
auto future = promise.get_future();
client->GetData(olp::dataservice::read::TileRequest()
.WithTileKey(olp::geo::TileKey::FromHereTile(kTileId))
.WithFetchOption(dataservice_read::CacheOnly),
[&promise](dataservice_read::DataResponse resp) {
promise.set_value(std::move(resp));
});
auto response = future.get();
EXPECT_SUCCESS(response);
ASSERT_TRUE(response.GetResult() != nullptr);
ASSERT_NE(response.GetResult()->size(), 0u);
}
}
TEST_F(DataserviceReadVersionedLayerClientTest, PrefetchWrongLevels) {
const auto catalog =
olp::client::HRN::FromString(CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_catalog"));
const auto kLayerId = CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_layer");
const auto kTileId = CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_tile");
auto client = std::make_unique<olp::dataservice::read::VersionedLayerClient>(
catalog, kLayerId, boost::none, *settings_);
{
SCOPED_TRACE("Prefetch tiles online and store them in memory cache");
std::vector<olp::geo::TileKey> tile_keys = {
olp::geo::TileKey::FromHereTile(kTileId)};
{
SCOPED_TRACE("min/max levels default");
auto request =
olp::dataservice::read::PrefetchTilesRequest().WithTileKeys(
tile_keys);
std::promise<dataservice_read::PrefetchTilesResponse> promise;
auto future = promise.get_future();
auto token = client->PrefetchTiles(
request,
[&promise](dataservice_read::PrefetchTilesResponse response) {
promise.set_value(std::move(response));
});
ASSERT_NE(future.wait_for(kWaitTimeout), std::future_status::timeout);
dataservice_read::PrefetchTilesResponse response = future.get();
EXPECT_SUCCESS(response);
const auto& result = response.GetResult();
for (auto tile_result : result) {
EXPECT_SUCCESS(*tile_result);
ASSERT_TRUE(tile_result->tile_key_.IsValid());
}
ASSERT_EQ(tile_keys.size(), result.size());
}
{
SCOPED_TRACE(" min level greater than max level");
auto request = olp::dataservice::read::PrefetchTilesRequest()
.WithTileKeys(tile_keys)
.WithMinLevel(-1)
.WithMaxLevel(0);
std::promise<dataservice_read::PrefetchTilesResponse> promise;
auto future = promise.get_future();
auto token = client->PrefetchTiles(
request,
[&promise](dataservice_read::PrefetchTilesResponse response) {
promise.set_value(std::move(response));
});
ASSERT_NE(future.wait_for(kWaitTimeout), std::future_status::timeout);
dataservice_read::PrefetchTilesResponse response = future.get();
EXPECT_TRUE(response.IsSuccessful());
const auto& result = response.GetResult();
for (auto tile_result : result) {
EXPECT_SUCCESS(*tile_result);
ASSERT_TRUE(tile_result->tile_key_.IsValid());
}
ASSERT_EQ(tile_keys.size(), result.size());
}
{
SCOPED_TRACE(" min/max levels invalid, but not equal");
auto request = olp::dataservice::read::PrefetchTilesRequest()
.WithTileKeys(tile_keys)
.WithMinLevel(0)
.WithMaxLevel(-1);
std::promise<dataservice_read::PrefetchTilesResponse> promise;
auto future = promise.get_future();
auto token = client->PrefetchTiles(
request,
[&promise](dataservice_read::PrefetchTilesResponse response) {
promise.set_value(std::move(response));
});
ASSERT_NE(future.wait_for(kWaitTimeout), std::future_status::timeout);
dataservice_read::PrefetchTilesResponse response = future.get();
EXPECT_SUCCESS(response);
const auto& result = response.GetResult();
for (auto tile_result : result) {
EXPECT_SUCCESS(*tile_result);
ASSERT_TRUE(tile_result->tile_key_.IsValid());
}
ASSERT_EQ(tile_keys.size(), result.size());
}
{
SCOPED_TRACE(" min level is zero");
auto request = olp::dataservice::read::PrefetchTilesRequest()
.WithTileKeys(tile_keys)
.WithMinLevel(0)
.WithMaxLevel(3);
std::promise<dataservice_read::PrefetchTilesResponse> promise;
auto future = promise.get_future();
auto token = client->PrefetchTiles(
request,
[&promise](dataservice_read::PrefetchTilesResponse response) {
promise.set_value(std::move(response));
});
ASSERT_NE(future.wait_for(kWaitTimeout), std::future_status::timeout);
dataservice_read::PrefetchTilesResponse response = future.get();
ASSERT_TRUE(response.IsSuccessful());
ASSERT_TRUE(response.GetResult().empty());
}
}
}
TEST_F(DataserviceReadVersionedLayerClientTest, PrefetchWithCancellableFuture) {
const auto catalog =
olp::client::HRN::FromString(CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_catalog"));
const auto kLayerId = CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_layer");
const auto kTileId = CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_tile");
auto client = std::make_unique<olp::dataservice::read::VersionedLayerClient>(
catalog, kLayerId, boost::none, *settings_);
std::vector<olp::geo::TileKey> tile_keys = {
olp::geo::TileKey::FromHereTile(kTileId)};
auto request = olp::dataservice::read::PrefetchTilesRequest()
.WithTileKeys(tile_keys)
.WithMinLevel(10)
.WithMaxLevel(12);
auto cancel_future = client->PrefetchTiles(std::move(request));
auto raw_future = cancel_future.GetFuture();
ASSERT_NE(raw_future.wait_for(kWaitTimeout), std::future_status::timeout);
dataservice_read::PrefetchTilesResponse response = raw_future.get();
EXPECT_SUCCESS(response);
ASSERT_FALSE(response.GetResult().empty());
const auto& result = response.GetResult();
for (auto tile_result : result) {
EXPECT_SUCCESS(*tile_result);
ASSERT_TRUE(tile_result->tile_key_.IsValid());
}
// one tile on level 10 and 11 and 4 on level 12
ASSERT_EQ(6u, result.size());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetPartitionsWithInvalidHrn) {
olp::client::HRN hrn("hrn:here:data::olp-here-test:nope-test-v2");
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "testlayer", boost::none, *settings_);
auto request = olp::dataservice::read::PartitionsRequest();
auto partitions_response =
GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] {
auto future = catalog_client->GetPartitions(request);
return future.GetFuture().get();
});
ASSERT_FALSE(partitions_response.IsSuccessful());
ASSERT_EQ(http::HttpStatusCode::FORBIDDEN,
partitions_response.GetError().GetHttpStatusCode());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetPartitions) {
olp::client::HRN hrn(GetTestCatalog());
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "testlayer", boost::none, *settings_);
auto request = olp::dataservice::read::PartitionsRequest();
auto partitions_response =
GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] {
auto future = catalog_client->GetPartitions(request);
return future.GetFuture().get();
});
EXPECT_SUCCESS(partitions_response);
ASSERT_EQ(4u, partitions_response.GetResult().GetPartitions().size());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetPartitionsForInvalidLayer) {
olp::client::HRN hrn(GetTestCatalog());
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "invalidLayer", boost::none, *settings_);
auto request = olp::dataservice::read::PartitionsRequest();
auto partitions_response =
GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] {
auto future = catalog_client->GetPartitions(request);
return future.GetFuture().get();
});
ASSERT_FALSE(partitions_response.IsSuccessful());
ASSERT_EQ(olp::client::ErrorCode::BadRequest,
partitions_response.GetError().GetErrorCode());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetDataWithInvalidHrn) {
olp::client::HRN hrn("hrn:here:data::olp-here-test:nope-test-v2");
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "testlayer", boost::none, *settings_);
auto request = olp::dataservice::read::DataRequest();
request.WithDataHandle("d5d73b64-7365-41c3-8faf-aa6ad5bab135");
auto data_response = GetExecutionTime<dataservice_read::DataResponse>([&] {
auto future = catalog_client->GetData(request);
return future.GetFuture().get();
});
ASSERT_FALSE(data_response.IsSuccessful());
ASSERT_EQ(http::HttpStatusCode::FORBIDDEN,
data_response.GetError().GetHttpStatusCode());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetDataHandleWithInvalidLayer) {
olp::client::HRN hrn(GetTestCatalog());
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "invalidLayer", boost::none, *settings_);
auto request = olp::dataservice::read::DataRequest();
request.WithDataHandle("invalidDataHandle");
auto data_response = GetExecutionTime<dataservice_read::DataResponse>([&] {
auto future = catalog_client->GetData(request);
return future.GetFuture().get();
});
ASSERT_FALSE(data_response.IsSuccessful());
ASSERT_EQ(olp::client::ErrorCode::NotFound,
data_response.GetError().GetErrorCode());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetDataWithPartitionId) {
olp::client::HRN hrn(GetTestCatalog());
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "testlayer", boost::none, *settings_);
auto request = olp::dataservice::read::DataRequest();
request.WithPartitionId("269");
auto data_response = GetExecutionTime<dataservice_read::DataResponse>([&] {
auto future = catalog_client->GetData(request);
return future.GetFuture().get();
});
EXPECT_SUCCESS(data_response);
ASSERT_TRUE(data_response.GetResult() != nullptr);
ASSERT_LT(0, data_response.GetResult()->size());
std::string data_string(data_response.GetResult()->begin(),
data_response.GetResult()->end());
ASSERT_EQ("DT_2_0031", data_string);
}
TEST_F(DataserviceReadVersionedLayerClientTest,
GetDataWithPartitionIdInvalidVersion) {
olp::client::HRN hrn(GetTestCatalog());
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "testlayer", 10, *settings_);
auto request = olp::dataservice::read::DataRequest();
request.WithPartitionId("269");
auto data_response = GetExecutionTime<dataservice_read::DataResponse>([&] {
auto future = catalog_client->GetData(request);
return future.GetFuture().get();
});
ASSERT_FALSE(data_response.IsSuccessful());
ASSERT_EQ(olp::client::ErrorCode::BadRequest,
data_response.GetError().GetErrorCode());
ASSERT_EQ(http::HttpStatusCode::BAD_REQUEST,
data_response.GetError().GetHttpStatusCode());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetPartitionsVersion2) {
olp::client::HRN hrn(GetTestCatalog());
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "testlayer", 2, *settings_);
auto request = olp::dataservice::read::PartitionsRequest();
auto partitions_response =
GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] {
auto future = catalog_client->GetPartitions(request);
return future.GetFuture().get();
});
EXPECT_SUCCESS(partitions_response);
ASSERT_LT(0, partitions_response.GetResult().GetPartitions().size());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetPartitionsInvalidVersion) {
olp::client::HRN hrn(GetTestCatalog());
{
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "testlayer", 10, *settings_);
auto request = olp::dataservice::read::PartitionsRequest();
auto partitions_response =
GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] {
auto future = catalog_client->GetPartitions(request);
return future.GetFuture().get();
});
ASSERT_FALSE(partitions_response.IsSuccessful());
ASSERT_EQ(olp::client::ErrorCode::BadRequest,
partitions_response.GetError().GetErrorCode());
ASSERT_EQ(http::HttpStatusCode::BAD_REQUEST,
partitions_response.GetError().GetHttpStatusCode());
}
{
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "testlayer", -2, *settings_);
auto request = olp::dataservice::read::PartitionsRequest();
auto partitions_response =
GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] {
auto future = catalog_client->GetPartitions(request);
return future.GetFuture().get();
});
ASSERT_FALSE(partitions_response.IsSuccessful());
ASSERT_EQ(olp::client::ErrorCode::BadRequest,
partitions_response.GetError().GetErrorCode());
ASSERT_EQ(http::HttpStatusCode::BAD_REQUEST,
partitions_response.GetError().GetHttpStatusCode());
}
}
TEST_F(DataserviceReadVersionedLayerClientTest,
GetDataWithNonExistentPartitionId) {
olp::client::HRN hrn(GetTestCatalog());
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "testlayer", boost::none, *settings_);
auto request = olp::dataservice::read::DataRequest();
request.WithPartitionId("noPartition");
auto data_response = GetExecutionTime<dataservice_read::DataResponse>([&] {
auto future = catalog_client->GetData(request);
return future.GetFuture().get();
});
EXPECT_FALSE(data_response.IsSuccessful());
ASSERT_EQ(olp::client::ErrorCode::NotFound,
data_response.GetError().GetErrorCode());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetDataWithEmptyField) {
olp::client::HRN hrn(GetTestCatalog());
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "testlayer", boost::none, *settings_);
auto request = olp::dataservice::read::DataRequest();
request.WithPartitionId("1");
auto data_response = GetExecutionTime<dataservice_read::DataResponse>([&] {
auto future = catalog_client->GetData(request);
return future.GetFuture().get();
});
EXPECT_FALSE(data_response.IsSuccessful());
ASSERT_EQ(olp::client::ErrorCode::NotFound,
data_response.GetError().GetErrorCode());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetDataCompressed) {
olp::client::HRN hrn(GetTestCatalog());
auto catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "testlayer", boost::none, *settings_);
auto request = olp::dataservice::read::DataRequest();
request.WithPartitionId("here_van_wc2018_pool");
auto data_response = GetExecutionTime<dataservice_read::DataResponse>([&] {
auto future = catalog_client->GetData(request);
return future.GetFuture().get();
});
EXPECT_SUCCESS(data_response);
ASSERT_TRUE(data_response.GetResult() != nullptr);
ASSERT_LT(0u, data_response.GetResult()->size());
catalog_client =
std::make_unique<olp::dataservice::read::VersionedLayerClient>(
hrn, "testlayer_gzip", boost::none, *settings_);
auto request_compressed = olp::dataservice::read::DataRequest();
request_compressed.WithPartitionId("here_van_wc2018_pool");
auto data_response_compressed =
GetExecutionTime<dataservice_read::DataResponse>([&] {
auto future = catalog_client->GetData(request_compressed);
return future.GetFuture().get();
});
EXPECT_SUCCESS(data_response_compressed);
ASSERT_TRUE(data_response_compressed.GetResult() != nullptr);
ASSERT_LT(0u, data_response_compressed.GetResult()->size());
ASSERT_EQ(data_response.GetResult()->size(),
data_response_compressed.GetResult()->size());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetTile) {
const auto catalog =
olp::client::HRN::FromString(CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_catalog"));
const auto kLayerId = CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_layer");
const auto kTileId = CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_tile");
auto client = std::make_unique<olp::dataservice::read::VersionedLayerClient>(
catalog, kLayerId, boost::none, *settings_);
auto request = olp::dataservice::read::TileRequest().WithTileKey(
olp::geo::TileKey::FromHereTile(kTileId));
auto data_response_compressed =
GetExecutionTime<dataservice_read::DataResponse>([&] {
auto future = client->GetData(request);
return future.GetFuture().get();
});
EXPECT_SUCCESS(data_response_compressed);
ASSERT_TRUE(data_response_compressed.GetResult() != nullptr);
ASSERT_EQ(140u, data_response_compressed.GetResult()->size());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetTileWithInvalidLayerId) {
const auto catalog =
olp::client::HRN::FromString(CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_catalog"));
const auto kTileId = CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_tile");
auto client = std::make_unique<olp::dataservice::read::VersionedLayerClient>(
catalog, "invalidLayer", boost::none, *settings_);
auto request = olp::dataservice::read::TileRequest().WithTileKey(
olp::geo::TileKey::FromHereTile(kTileId));
auto data_response = GetExecutionTime<dataservice_read::DataResponse>([&] {
auto future = client->GetData(request);
return future.GetFuture().get();
});
ASSERT_FALSE(data_response.IsSuccessful());
ASSERT_EQ(olp::client::ErrorCode::BadRequest,
data_response.GetError().GetErrorCode());
}
TEST_F(DataserviceReadVersionedLayerClientTest, GetTileEmptyField) {
const auto catalog =
olp::client::HRN::FromString(CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_catalog"));
const auto kLayerId = CustomParameters::getArgument(
"dataservice_read_test_versioned_prefetch_layer");
auto client = std::make_unique<olp::dataservice::read::VersionedLayerClient>(
catalog, kLayerId, boost::none, *settings_);
auto request = olp::dataservice::read::TileRequest().WithTileKey(
olp::geo::TileKey::FromHereTile(""));
auto data_response_compressed =
GetExecutionTime<dataservice_read::DataResponse>([&] {
auto future = client->GetData(request);
return future.GetFuture().get();
});
EXPECT_FALSE(data_response_compressed.IsSuccessful());
ASSERT_EQ(olp::client::ErrorCode::InvalidArgument,
data_response_compressed.GetError().GetErrorCode());
}
} // namespace
| 37.561644
| 80
| 0.702569
|
fermeise
|
fd8e839d79ce0755493098e8bb0a7fc04e6f71e2
| 1,996
|
cpp
|
C++
|
tests/CommandTest.cpp
|
Superbition/Bakup-Agent
|
ed6beba6e14bdf7c63faef1ba70a2590419fa505
|
[
"Apache-2.0"
] | 5
|
2020-03-06T13:34:16.000Z
|
2021-04-12T15:34:36.000Z
|
tests/CommandTest.cpp
|
Superbition/Bakup-Agent
|
ed6beba6e14bdf7c63faef1ba70a2590419fa505
|
[
"Apache-2.0"
] | 2
|
2020-03-26T18:17:47.000Z
|
2021-05-30T16:02:43.000Z
|
tests/CommandTest.cpp
|
Superbition/Bakup-Agent
|
ed6beba6e14bdf7c63faef1ba70a2590419fa505
|
[
"Apache-2.0"
] | 2
|
2021-07-07T05:53:11.000Z
|
2021-07-30T16:46:02.000Z
|
#include <gtest/gtest.h>
#include <Command.h>
#include <Agent.h>
class CommandTest : public ::testing::Test
{
protected:
CommandTest()
{
this->commandString = "echo \"Hello World\"";
this->commandValue = "Hello World";
}
public:
string commandString;
string commandValue;
Agent agent;
};
TEST_F(CommandTest, PipeSuccessfullyOpened)
{
Debug debug(true, "version");
Command command(debug, this->agent.getUserID());
ASSERT_TRUE(command.setupEnvironment());
}
TEST_F(CommandTest, PipeFailsOnInvalidShell)
{
Debug debug(true, "version");
// Pass an invalid shell that crashes child
Command command(debug, this->agent.getUserID(), "ABadShell");
ASSERT_FALSE(command.setupEnvironment());
}
TEST_F(CommandTest, PipeFailsOnBadShell)
{
Debug debug(true, "version");
// Pass an invalid shell that doesn't crash the child
Command command(debug, this->agent.getUserID(), "/bin/touch");
ASSERT_FALSE(command.setupEnvironment());
}
TEST_F(CommandTest, CommandSuccessTest)
{
Debug debug(true, "version");
Command command(debug, this->agent.getUserID());
command.setupEnvironment();
ASSERT_EQ(command.runCommand(this->commandString).first, this->commandValue);
}
TEST_F(CommandTest, GenerateDelimiter)
{
Debug debug(true, "version");
Command command(debug, this->agent.getUserID());
string delimiter = command.generateDelimiter();
ASSERT_EQ(delimiter.size(), 128);
}
TEST_F(CommandTest, CommandFailureTest)
{
Debug debug(true, "version");
Command command(debug, this->agent.getUserID());
command.setupEnvironment();
ASSERT_GT(command.runCommand("notAValidCommand").second, EXIT_SUCCESS);
}
TEST_F(CommandTest, WhoAmIBakupAgent)
{
Debug debug(true, "version");
Command command(debug, this->agent.getUserID());
ASSERT_TRUE(command.setupEnvironment());
ASSERT_EQ(command.runCommand("whoami").first, "bakupagent");
}
| 25.922078
| 81
| 0.690381
|
Superbition
|
fd8f93141e43de333e55df704da361cb5f147c11
| 5,673
|
cpp
|
C++
|
rd-cpp/src/rd_core_cpp/src/test/cases/ViewableSetTest.cpp
|
yvvan/rd
|
87ce10eb012af398689fe0a5b9100a2ef8edfdcc
|
[
"Apache-2.0"
] | null | null | null |
rd-cpp/src/rd_core_cpp/src/test/cases/ViewableSetTest.cpp
|
yvvan/rd
|
87ce10eb012af398689fe0a5b9100a2ef8edfdcc
|
[
"Apache-2.0"
] | null | null | null |
rd-cpp/src/rd_core_cpp/src/test/cases/ViewableSetTest.cpp
|
yvvan/rd
|
87ce10eb012af398689fe0a5b9100a2ef8edfdcc
|
[
"Apache-2.0"
] | 1
|
2020-06-02T12:08:09.000Z
|
2020-06-02T12:08:09.000Z
|
#include <gtest/gtest.h>
#include "reactive/ViewableSet.h"
#include "test_util.h"
using namespace rd;
TEST (viewable_set, advise) {
std::unique_ptr<IViewableSet<int>> set = std::make_unique<ViewableSet<int>>();
std::vector<int> logAdvise;
std::vector<int> logView1;
std::vector<int> logView2;
LifetimeDefinition::use([&](Lifetime lt) {
set->advise(lt, [&](AddRemove kind, int const &v) {
logAdvise.push_back(kind == AddRemove::ADD ? v : -v);
});
set->view(lt, [&](Lifetime inner, int const &v) {
logView1.push_back(v);
inner->add_action([&]() { logView1.push_back(-v); });
});
set->view(Lifetime::Eternal(), [&](Lifetime inner, int const &v) {
logView2.push_back(v);
inner->add_action([&logView2, v]() { logView2.push_back(-v); });
});
EXPECT_TRUE(set->add(1));//1
//EXPECT_TRUE(set.add(arrayOf(1, 2)) } //1, 2
EXPECT_FALSE(set->add(1)); //1
EXPECT_TRUE(set->add(2)); //1, 2
//EXPECT_TRUE(set.add(arrayOf(1, 2)) } //1, 2
EXPECT_FALSE(set->add(1)); //1, 2
EXPECT_FALSE(set->add(2)); //1, 2
// EXPECT_TRUE{set.removeAll(arrayOf(2, 3))} // 1
EXPECT_TRUE(set->remove(2)); // 1
EXPECT_FALSE(set->remove(3)); // 1
EXPECT_TRUE(set->add(2)); // 1, 2
EXPECT_FALSE(set->add(2)); // 1, 2
// EXPECT_TRUE(set.retainAll(arrayOf(2, 3)) // 2
EXPECT_TRUE(set->remove(1)); // 2
EXPECT_FALSE(set->remove(3)); // 2
});
EXPECT_TRUE(set->add(1));
std::vector<int> expectedAdvise{1, 2, -2, 2, -1};
EXPECT_EQ(expectedAdvise, logAdvise);
std::vector<int> expectedView1{1, 2, -2, 2, -1, -2};
EXPECT_EQ(expectedView1, logView1);
std::vector<int> expectedView2{1, 2, -2, 2, -1, 1};
EXPECT_EQ(expectedView2, logView2);
}
TEST (viewable_set, view) {
using listOf = std::vector<int>;
listOf elementsView{2, 0, 1, 8, 3};
listOf elementsUnView{1, 3, 8, 0, 2};
size_t C = elementsView.size();
std::unique_ptr<IViewableSet<int>> set = std::make_unique<ViewableSet<int>>();
std::vector<std::string> log;
auto x = LifetimeDefinition::use([&](Lifetime lifetime) {
set->view(lifetime, [&](Lifetime lt, int const &value) {
log.push_back("View " + std::to_string(value));
lt->add_action([&]() { log.push_back("UnView " + std::to_string(value)); });
}
);
for (auto x : elementsView) {
set->add(x);
}
return set->remove(1);
});
EXPECT_TRUE(x);
EXPECT_EQ(C - 1, set->size());
std::vector<std::string> expected(2 * C);
for (size_t i = 0; i < C; ++i) {
expected[i] = "View " + std::to_string(elementsView[i]);
expected[C + i] = "UnView " + std::to_string(elementsUnView[i]);
}
EXPECT_EQ(expected, log);
log.clear();
LifetimeDefinition::use([&](Lifetime lifetime) {
set->view(lifetime, [&](Lifetime lt, int const &value) {
log.push_back("View " + std::to_string(value));
lt->add_action([&]() { log.push_back("UnView " + std::to_string(value)); });
}
);
set->clear();
});
EXPECT_TRUE(set->empty());
listOf rest_elements{2, 0, 8, 3};
size_t K = C - 1;
std::vector<std::string> expected2(2 * K);
for (size_t i = 0; i < K; ++i) {
expected2[i] = "View " + std::to_string(rest_elements[i]);
expected2[K + i] = "UnView " + std::to_string(rest_elements[i]);
}
EXPECT_EQ(expected2, log);
}
TEST(viewable_set, add_remove_fuzz) {
std::unique_ptr<IViewableSet<int> > set = std::make_unique<ViewableSet<int>>();
std::vector<std::string> log;
const int C = 10;
LifetimeDefinition::use([&](Lifetime lifetime) {
set->view(lifetime, [&log](Lifetime lt, int const &value) {
log.push_back("View " + std::to_string(value));
lt->add_action([&]() { log.push_back("UnView " + std::to_string(value)); });
});
for (int i = 0; i < C; ++i) {
set->add(i);
}
});
for (int i = 0; i < C; ++i) {
EXPECT_EQ("View " + std::to_string(i), log[i]);
EXPECT_EQ("UnView " + std::to_string(C - i - 1), log[C + i]);
}
}
TEST (viewable_set, move) {
ViewableSet<int> set1;
ViewableSet<int> set2(std::move(set1));
}
using container = ViewableSet<int>;
static_assert(!std::is_constructible<container::iterator, std::nullptr_t>::value,
"iterator should not be constructible from nullptr");
TEST(viewable_set_iterators, end_iterator) {
container c;
container::iterator i = c.end();
EXPECT_EQ(c.begin(), i);
}
TEST(viewable_set_iterators, reverse_iterators) {
container c;
c.addAll({4, 3, 2, 1});
EXPECT_EQ(1, *c.rbegin());
EXPECT_EQ(2, *std::next(c.rbegin()));
EXPECT_EQ(4, *std::prev(c.rend()));
}
TEST(viewable_set_iterators, iterators_postfix) {
container s;
s.addAll({1, 2, 3});
container::iterator i = s.begin();
EXPECT_EQ(1, *i);
container::iterator j = i++;
EXPECT_EQ(2, *i);
EXPECT_EQ(1, *j);
j = i++;
EXPECT_EQ(3, *i);
EXPECT_EQ(2, *j);
j = i++;
EXPECT_EQ(s.end(), i);
EXPECT_EQ(3, *j);
j = i--;
EXPECT_EQ(3, *i);
EXPECT_EQ(s.end(), j);
}
std::vector<int> const perm4 = {2, 0, 1, 9};
TEST(viewable_set_iterators, fori) {
const container c;
c.addAll(perm4);
std::vector<int> log;
for (auto const &item : c) {
log.push_back(item);
}
EXPECT_EQ(log, perm4);
}
TEST(viewable_set_iterators, random_access) {
container c;
c.addAll(perm4);
EXPECT_EQ(*(c.begin() + 2), 1);
EXPECT_EQ(*(c.rbegin() + 2), 0);
}
/*TEST(viewable_set_iterators, insert_return_value) {
container c;
c.addAll({1, 2, 3, 4});
container::iterator i = c.add(std::next(c.begin(), 2), 5);
EXPECT_EQ(5, *i);
EXPECT_EQ(2, *std::prev(i));
EXPECT_EQ(3, *std::next(i));
}
TEST(viewable_set_iterators, erase_return_value) {
container c;
c.addAll({1, 2, 3, 4});
container::iterator i = c.remove(std::next(c.begin()));
EXPECT_EQ(3, *i);
i = c.remove(i);
EXPECT_EQ(4, *i);
}*/
| 25.554054
| 83
| 0.623656
|
yvvan
|
fd9047123c4345707dee2d51554214c76598917b
| 4,032
|
cpp
|
C++
|
test/sql/parallelism/interquery/test_concurrentappend.cpp
|
littlelittlehorse/duckdb
|
22ba76e4151bb3b0556e44cef3fcf6fb64747364
|
[
"MIT"
] | null | null | null |
test/sql/parallelism/interquery/test_concurrentappend.cpp
|
littlelittlehorse/duckdb
|
22ba76e4151bb3b0556e44cef3fcf6fb64747364
|
[
"MIT"
] | 1
|
2022-03-20T03:34:29.000Z
|
2022-03-20T03:34:29.000Z
|
test/sql/parallelism/interquery/test_concurrentappend.cpp
|
littlelittlehorse/duckdb
|
22ba76e4151bb3b0556e44cef3fcf6fb64747364
|
[
"MIT"
] | null | null | null |
#include "catch.hpp"
#include "duckdb/common/value_operations/value_operations.hpp"
#include "test_helpers.hpp"
#include <atomic>
#include <thread>
using namespace duckdb;
using namespace std;
static constexpr int CONCURRENT_APPEND_THREAD_COUNT = 10;
static constexpr int CONCURRENT_APPEND_INSERT_ELEMENTS = 1000;
TEST_CASE("Sequential append", "[interquery][.]") {
unique_ptr<MaterializedQueryResult> result;
DuckDB db(nullptr, nullptr, nullptr);
Connection con(db);
vector<unique_ptr<Connection>> connections;
// enable detailed profiling
con.Query("PRAGMA enable_profiling");
auto detailed_profiling_output = TestCreatePath("detailed_profiling_output");
con.Query("PRAGMA profiling_output='" + detailed_profiling_output + "'");
con.Query("PRAGMA profiling_mode = detailed");
// initialize the database
REQUIRE_NO_FAIL(con.Query("CREATE TABLE integers(i INTEGER);"));
for (size_t i = 0; i < CONCURRENT_APPEND_THREAD_COUNT; i++) {
connections.push_back(make_unique<Connection>(db));
connections[i]->Query("BEGIN TRANSACTION;");
}
for (size_t i = 0; i < CONCURRENT_APPEND_THREAD_COUNT; i++) {
result = connections[i]->Query("SELECT COUNT(*) FROM integers");
D_ASSERT(result->collection.Count() > 0);
Value count = result->collection.GetValue(0, 0);
REQUIRE(count == 0);
for (size_t j = 0; j < CONCURRENT_APPEND_INSERT_ELEMENTS; j++) {
connections[i]->Query("INSERT INTO integers VALUES (3)");
result = connections[i]->Query("SELECT COUNT(*) FROM integers");
Value new_count = result->collection.GetValue(0, 0);
REQUIRE(new_count == j + 1);
count = new_count;
}
}
for (size_t i = 0; i < CONCURRENT_APPEND_THREAD_COUNT; i++) {
connections[i]->Query("COMMIT;");
}
result = con.Query("SELECT COUNT(*) FROM integers");
Value count = result->collection.GetValue(0, 0);
REQUIRE(count == CONCURRENT_APPEND_THREAD_COUNT * CONCURRENT_APPEND_INSERT_ELEMENTS);
}
static volatile std::atomic<int> append_finished_threads;
static void insert_random_elements(DuckDB *db, bool *correct, int threadnr) {
correct[threadnr] = true;
Connection con(*db);
// initial count
con.Query("BEGIN TRANSACTION;");
auto result = con.Query("SELECT COUNT(*) FROM integers");
Value count = result->collection.GetValue(0, 0);
auto start_count = count.GetValue<int64_t>();
for (size_t i = 0; i < CONCURRENT_APPEND_INSERT_ELEMENTS; i++) {
// count should increase by one for every append we do
con.Query("INSERT INTO integers VALUES (3)");
result = con.Query("SELECT COUNT(*) FROM integers");
Value new_count = result->collection.GetValue(0, 0);
if (new_count != start_count + i + 1) {
correct[threadnr] = false;
}
count = new_count;
}
append_finished_threads++;
while (append_finished_threads != CONCURRENT_APPEND_THREAD_COUNT)
;
con.Query("COMMIT;");
}
TEST_CASE("Concurrent append", "[interquery][.]") {
unique_ptr<QueryResult> result;
DuckDB db(nullptr, nullptr, nullptr);
Connection con(db);
// enable detailed profiling
con.Query("PRAGMA enable_profiling");
auto detailed_profiling_output = TestCreatePath("detailed_profiling_output");
con.Query("PRAGMA profiling_output='" + detailed_profiling_output + "'");
con.Query("PRAGMA profiling_mode = detailed");
// initialize the database
REQUIRE_NO_FAIL(con.Query("CREATE TABLE integers(i INTEGER);"));
append_finished_threads = 0;
bool correct[CONCURRENT_APPEND_THREAD_COUNT];
thread threads[CONCURRENT_APPEND_THREAD_COUNT];
for (size_t i = 0; i < CONCURRENT_APPEND_THREAD_COUNT; i++) {
threads[i] = thread(insert_random_elements, &db, correct, i);
}
for (size_t i = 0; i < CONCURRENT_APPEND_THREAD_COUNT; i++) {
threads[i].join();
REQUIRE(correct[i]);
}
result = con.Query("SELECT COUNT(*), SUM(i) FROM integers");
REQUIRE(
CHECK_COLUMN(result, 0, {Value::BIGINT(CONCURRENT_APPEND_THREAD_COUNT * CONCURRENT_APPEND_INSERT_ELEMENTS)}));
REQUIRE(CHECK_COLUMN(result, 1,
{Value::BIGINT(3 * CONCURRENT_APPEND_THREAD_COUNT * CONCURRENT_APPEND_INSERT_ELEMENTS)}));
}
| 35.06087
| 115
| 0.730655
|
littlelittlehorse
|
fd9430f26909f35ddaddcaf069507d03370fe4df
| 675
|
cpp
|
C++
|
OJ/GDUT/C.cpp
|
Tomotoes/Algorithm
|
8291a7ed498a0a9d763e7e50fffacf78db101a7e
|
[
"Unlicense"
] | 6
|
2018-09-06T06:46:43.000Z
|
2022-03-17T11:34:56.000Z
|
OJ/GDUT/C.cpp
|
Tomotoes/Algorithm
|
8291a7ed498a0a9d763e7e50fffacf78db101a7e
|
[
"Unlicense"
] | 4
|
2020-04-18T02:32:10.000Z
|
2020-04-18T04:03:56.000Z
|
OJ/GDUT/C.cpp
|
Tomotoes/Algorithm
|
8291a7ed498a0a9d763e7e50fffacf78db101a7e
|
[
"Unlicense"
] | 1
|
2020-02-10T18:57:34.000Z
|
2020-02-10T18:57:34.000Z
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
const int mod = 10007;
const int N = 51;
int f[N];
void solve()
{
f[0] = 1;
for(int i = 1; i < N; ++ i)
{
f[i] = f[i-1];
if(i > 1) f[i] += f[i-2];
if(i > 2) f[i] += f[i-3];
f[i] %= mod;
}
int n;
scanf("%d", &n);
int ans = 1;
for(int i = 1; i < n; ++ i)
{
int x;
scanf("%d", &x);
ans = ans*f[x]%mod;
}
printf("%d\n", ans);
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
solve();
}
return 0;
}
| 15
| 34
| 0.376296
|
Tomotoes
|
fd97e21efc889fb8d4db2a2c904ed4586051092b
| 17,866
|
cpp
|
C++
|
test.cpp
|
chessai/pltest
|
c5d821e86cfaac88d4905d5d5170026b66706d2c
|
[
"MIT"
] | 1
|
2022-01-24T22:39:46.000Z
|
2022-01-24T22:39:46.000Z
|
test.cpp
|
chessai/pltest
|
c5d821e86cfaac88d4905d5d5170026b66706d2c
|
[
"MIT"
] | null | null | null |
test.cpp
|
chessai/pltest
|
c5d821e86cfaac88d4905d5d5170026b66706d2c
|
[
"MIT"
] | 1
|
2022-01-24T03:52:32.000Z
|
2022-01-24T03:52:32.000Z
|
#include "souffle/CompiledSouffle.h"
extern "C" {
}
namespace souffle {
static const RamDomain RAM_BIT_SHIFT_MASK = RAM_DOMAIN_SIZE - 1;
struct t_btree_ii__0_1__11 {
using t_tuple = Tuple<RamDomain, 2>;
struct t_comparator_0{
int operator()(const t_tuple& a, const t_tuple& b) const {
return (ramBitCast<RamSigned>(a[0]) < ramBitCast<RamSigned>(b[0])) ? -1 : (ramBitCast<RamSigned>(a[0]) > ramBitCast<RamSigned>(b[0])) ? 1 :((ramBitCast<RamSigned>(a[1]) < ramBitCast<RamSigned>(b[1])) ? -1 : (ramBitCast<RamSigned>(a[1]) > ramBitCast<RamSigned>(b[1])) ? 1 :(0));
}
bool less(const t_tuple& a, const t_tuple& b) const {
return (ramBitCast<RamSigned>(a[0]) < ramBitCast<RamSigned>(b[0]))|| (ramBitCast<RamSigned>(a[0]) == ramBitCast<RamSigned>(b[0])) && ((ramBitCast<RamSigned>(a[1]) < ramBitCast<RamSigned>(b[1])));
}
bool equal(const t_tuple& a, const t_tuple& b) const {
return (ramBitCast<RamSigned>(a[0]) == ramBitCast<RamSigned>(b[0]))&&(ramBitCast<RamSigned>(a[1]) == ramBitCast<RamSigned>(b[1]));
}
};
using t_ind_0 = btree_set<t_tuple,t_comparator_0>;
t_ind_0 ind_0;
using iterator = t_ind_0::iterator;
struct context {
t_ind_0::operation_hints hints_0_lower;
t_ind_0::operation_hints hints_0_upper;
};
context createContext() { return context(); }
bool insert(const t_tuple& t) {
context h;
return insert(t, h);
}
bool insert(const t_tuple& t, context& h) {
if (ind_0.insert(t, h.hints_0_lower)) {
return true;
} else return false;
}
bool insert(const RamDomain* ramDomain) {
RamDomain data[2];
std::copy(ramDomain, ramDomain + 2, data);
const t_tuple& tuple = reinterpret_cast<const t_tuple&>(data);
context h;
return insert(tuple, h);
}
bool insert(RamDomain a0,RamDomain a1) {
RamDomain data[2] = {a0,a1};
return insert(data);
}
bool contains(const t_tuple& t, context& h) const {
return ind_0.contains(t, h.hints_0_lower);
}
bool contains(const t_tuple& t) const {
context h;
return contains(t, h);
}
std::size_t size() const {
return ind_0.size();
}
iterator find(const t_tuple& t, context& h) const {
return ind_0.find(t, h.hints_0_lower);
}
iterator find(const t_tuple& t) const {
context h;
return find(t, h);
}
range<iterator> lowerUpperRange_00(const t_tuple& /* lower */, const t_tuple& /* upper */, context& /* h */) const {
return range<iterator>(ind_0.begin(),ind_0.end());
}
range<iterator> lowerUpperRange_00(const t_tuple& /* lower */, const t_tuple& /* upper */) const {
return range<iterator>(ind_0.begin(),ind_0.end());
}
range<t_ind_0::iterator> lowerUpperRange_11(const t_tuple& lower, const t_tuple& upper, context& h) const {
t_comparator_0 comparator;
int cmp = comparator(lower, upper);
if (cmp == 0) {
auto pos = ind_0.find(lower, h.hints_0_lower);
auto fin = ind_0.end();
if (pos != fin) {fin = pos; ++fin;}
return make_range(pos, fin);
}
if (cmp > 0) {
return make_range(ind_0.end(), ind_0.end());
}
return make_range(ind_0.lower_bound(lower, h.hints_0_lower), ind_0.upper_bound(upper, h.hints_0_upper));
}
range<t_ind_0::iterator> lowerUpperRange_11(const t_tuple& lower, const t_tuple& upper) const {
context h;
return lowerUpperRange_11(lower,upper,h);
}
bool empty() const {
return ind_0.empty();
}
std::vector<range<iterator>> partition() const {
return ind_0.getChunks(400);
}
void purge() {
ind_0.clear();
}
iterator begin() const {
return ind_0.begin();
}
iterator end() const {
return ind_0.end();
}
void printStatistics(std::ostream& o) const {
o << " arity 2 direct b-tree index 0 lex-order [0,1]\n";
ind_0.printStats(o);
}
};
struct t_btree_ii__0_1__11__10 {
using t_tuple = Tuple<RamDomain, 2>;
struct t_comparator_0{
int operator()(const t_tuple& a, const t_tuple& b) const {
return (ramBitCast<RamSigned>(a[0]) < ramBitCast<RamSigned>(b[0])) ? -1 : (ramBitCast<RamSigned>(a[0]) > ramBitCast<RamSigned>(b[0])) ? 1 :((ramBitCast<RamSigned>(a[1]) < ramBitCast<RamSigned>(b[1])) ? -1 : (ramBitCast<RamSigned>(a[1]) > ramBitCast<RamSigned>(b[1])) ? 1 :(0));
}
bool less(const t_tuple& a, const t_tuple& b) const {
return (ramBitCast<RamSigned>(a[0]) < ramBitCast<RamSigned>(b[0]))|| (ramBitCast<RamSigned>(a[0]) == ramBitCast<RamSigned>(b[0])) && ((ramBitCast<RamSigned>(a[1]) < ramBitCast<RamSigned>(b[1])));
}
bool equal(const t_tuple& a, const t_tuple& b) const {
return (ramBitCast<RamSigned>(a[0]) == ramBitCast<RamSigned>(b[0]))&&(ramBitCast<RamSigned>(a[1]) == ramBitCast<RamSigned>(b[1]));
}
};
using t_ind_0 = btree_set<t_tuple,t_comparator_0>;
t_ind_0 ind_0;
using iterator = t_ind_0::iterator;
struct context {
t_ind_0::operation_hints hints_0_lower;
t_ind_0::operation_hints hints_0_upper;
};
context createContext() { return context(); }
bool insert(const t_tuple& t) {
context h;
return insert(t, h);
}
bool insert(const t_tuple& t, context& h) {
if (ind_0.insert(t, h.hints_0_lower)) {
return true;
} else return false;
}
bool insert(const RamDomain* ramDomain) {
RamDomain data[2];
std::copy(ramDomain, ramDomain + 2, data);
const t_tuple& tuple = reinterpret_cast<const t_tuple&>(data);
context h;
return insert(tuple, h);
}
bool insert(RamDomain a0,RamDomain a1) {
RamDomain data[2] = {a0,a1};
return insert(data);
}
bool contains(const t_tuple& t, context& h) const {
return ind_0.contains(t, h.hints_0_lower);
}
bool contains(const t_tuple& t) const {
context h;
return contains(t, h);
}
std::size_t size() const {
return ind_0.size();
}
iterator find(const t_tuple& t, context& h) const {
return ind_0.find(t, h.hints_0_lower);
}
iterator find(const t_tuple& t) const {
context h;
return find(t, h);
}
range<iterator> lowerUpperRange_00(const t_tuple& /* lower */, const t_tuple& /* upper */, context& /* h */) const {
return range<iterator>(ind_0.begin(),ind_0.end());
}
range<iterator> lowerUpperRange_00(const t_tuple& /* lower */, const t_tuple& /* upper */) const {
return range<iterator>(ind_0.begin(),ind_0.end());
}
range<t_ind_0::iterator> lowerUpperRange_11(const t_tuple& lower, const t_tuple& upper, context& h) const {
t_comparator_0 comparator;
int cmp = comparator(lower, upper);
if (cmp == 0) {
auto pos = ind_0.find(lower, h.hints_0_lower);
auto fin = ind_0.end();
if (pos != fin) {fin = pos; ++fin;}
return make_range(pos, fin);
}
if (cmp > 0) {
return make_range(ind_0.end(), ind_0.end());
}
return make_range(ind_0.lower_bound(lower, h.hints_0_lower), ind_0.upper_bound(upper, h.hints_0_upper));
}
range<t_ind_0::iterator> lowerUpperRange_11(const t_tuple& lower, const t_tuple& upper) const {
context h;
return lowerUpperRange_11(lower,upper,h);
}
range<t_ind_0::iterator> lowerUpperRange_10(const t_tuple& lower, const t_tuple& upper, context& h) const {
t_comparator_0 comparator;
int cmp = comparator(lower, upper);
if (cmp > 0) {
return make_range(ind_0.end(), ind_0.end());
}
return make_range(ind_0.lower_bound(lower, h.hints_0_lower), ind_0.upper_bound(upper, h.hints_0_upper));
}
range<t_ind_0::iterator> lowerUpperRange_10(const t_tuple& lower, const t_tuple& upper) const {
context h;
return lowerUpperRange_10(lower,upper,h);
}
bool empty() const {
return ind_0.empty();
}
std::vector<range<iterator>> partition() const {
return ind_0.getChunks(400);
}
void purge() {
ind_0.clear();
}
iterator begin() const {
return ind_0.begin();
}
iterator end() const {
return ind_0.end();
}
void printStatistics(std::ostream& o) const {
o << " arity 2 direct b-tree index 0 lex-order [0,1]\n";
ind_0.printStats(o);
}
};
class Sf_test : public SouffleProgram {
private:
static inline bool regex_wrapper(const std::string& pattern, const std::string& text) {
bool result = false;
try { result = std::regex_match(text, std::regex(pattern)); } catch(...) {
std::cerr << "warning: wrong pattern provided for match(\"" << pattern << "\",\"" << text << "\").\n";
}
return result;
}
private:
static inline std::string substr_wrapper(const std::string& str, size_t idx, size_t len) {
std::string result;
try { result = str.substr(idx,len); } catch(...) {
std::cerr << "warning: wrong index position provided by substr(\"";
std::cerr << str << "\"," << (int32_t)idx << "," << (int32_t)len << ") functor.\n";
} return result;
}
public:
// -- initialize symbol table --
SymbolTable symTable;// -- initialize record table --
RecordTable recordTable;
// -- Table: @delta_path
Own<t_btree_ii__0_1__11> rel_1_delta_path = mk<t_btree_ii__0_1__11>();
// -- Table: @new_path
Own<t_btree_ii__0_1__11> rel_2_new_path = mk<t_btree_ii__0_1__11>();
// -- Table: edge
Own<t_btree_ii__0_1__11__10> rel_3_edge = mk<t_btree_ii__0_1__11__10>();
souffle::RelationWrapper<0,t_btree_ii__0_1__11__10,Tuple<RamDomain,2>,2,0> wrapper_rel_3_edge;
// -- Table: path
Own<t_btree_ii__0_1__11> rel_4_path = mk<t_btree_ii__0_1__11>();
souffle::RelationWrapper<1,t_btree_ii__0_1__11,Tuple<RamDomain,2>,2,0> wrapper_rel_4_path;
public:
Sf_test() :
wrapper_rel_3_edge(*rel_3_edge,symTable,"edge",std::array<const char *,2>{{"i:number","i:number"}},std::array<const char *,2>{{"x","y"}}),
wrapper_rel_4_path(*rel_4_path,symTable,"path",std::array<const char *,2>{{"i:number","i:number"}},std::array<const char *,2>{{"x","y"}}){
addRelation("edge",&wrapper_rel_3_edge,true,false);
addRelation("path",&wrapper_rel_4_path,false,true);
}
~Sf_test() {
}
private:
std::string inputDirectory;
std::string outputDirectory;
bool performIO;
std::atomic<RamDomain> ctr{};
std::atomic<size_t> iter{};
void runFunction(std::string inputDirectoryArg = "", std::string outputDirectoryArg = "", bool performIOArg = false) {
this->inputDirectory = inputDirectoryArg;
this->outputDirectory = outputDirectoryArg;
this->performIO = performIOArg;
SignalHandler::instance()->set();
#if defined(_OPENMP)
if (getNumThreads() > 0) {omp_set_num_threads(getNumThreads());}
#endif
// -- query evaluation --
{
std::vector<RamDomain> args, ret;
subroutine_0(args, ret);
}
{
std::vector<RamDomain> args, ret;
subroutine_1(args, ret);
}
// -- relation hint statistics --
SignalHandler::instance()->reset();
}
public:
void run() override { runFunction("", "", false); }
public:
void runAll(std::string inputDirectoryArg = "", std::string outputDirectoryArg = "") override { runFunction(inputDirectoryArg, outputDirectoryArg, true);
}
public:
void printAll(std::string outputDirectoryArg = "") override {
try {std::map<std::string, std::string> directiveMap({{"IO","file"},{"attributeNames","x\ty"},{"name","path"},{"operation","output"},{"output-dir","src"},{"params","{\"records\": {}, \"relation\": {\"arity\": 2, \"auxArity\": 0, \"params\": [\"x\", \"y\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 2, \"auxArity\": 0, \"types\": [\"i:number\", \"i:number\"]}}"}});
if (!outputDirectoryArg.empty()) {directiveMap["output-dir"] = outputDirectoryArg;}
IOSystem::getInstance().getWriter(directiveMap, symTable, recordTable)->writeAll(*rel_4_path);
} catch (std::exception& e) {std::cerr << e.what();exit(1);}
}
public:
void loadAll(std::string inputDirectoryArg = "") override {
try {std::map<std::string, std::string> directiveMap({{"IO","file"},{"attributeNames","x\ty"},{"fact-dir","gen"},{"name","edge"},{"operation","input"},{"params","{\"records\": {}, \"relation\": {\"arity\": 2, \"auxArity\": 0, \"params\": [\"x\", \"y\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 2, \"auxArity\": 0, \"types\": [\"i:number\", \"i:number\"]}}"}});
if (!inputDirectoryArg.empty()) {directiveMap["fact-dir"] = inputDirectoryArg;}
IOSystem::getInstance().getReader(directiveMap, symTable, recordTable)->readAll(*rel_3_edge);
} catch (std::exception& e) {std::cerr << "Error loading data: " << e.what() << '\n';}
}
public:
void dumpInputs() override {
try {std::map<std::string, std::string> rwOperation;
rwOperation["IO"] = "stdout";
rwOperation["name"] = "edge";
rwOperation["types"] = "{\"relation\": {\"arity\": 2, \"auxArity\": 0, \"types\": [\"i:number\", \"i:number\"]}}";
IOSystem::getInstance().getWriter(rwOperation, symTable, recordTable)->writeAll(*rel_3_edge);
} catch (std::exception& e) {std::cerr << e.what();exit(1);}
}
public:
void dumpOutputs() override {
try {std::map<std::string, std::string> rwOperation;
rwOperation["IO"] = "stdout";
rwOperation["name"] = "path";
rwOperation["types"] = "{\"relation\": {\"arity\": 2, \"auxArity\": 0, \"types\": [\"i:number\", \"i:number\"]}}";
IOSystem::getInstance().getWriter(rwOperation, symTable, recordTable)->writeAll(*rel_4_path);
} catch (std::exception& e) {std::cerr << e.what();exit(1);}
}
public:
SymbolTable& getSymbolTable() override {
return symTable;
}
void executeSubroutine(std::string name, const std::vector<RamDomain>& args, std::vector<RamDomain>& ret) override {
if (name == "stratum_0") {
subroutine_0(args, ret);
return;}
if (name == "stratum_1") {
subroutine_1(args, ret);
return;}
fatal("unknown subroutine");
}
#ifdef _MSC_VER
#pragma warning(disable: 4100)
#endif // _MSC_VER
void subroutine_0(const std::vector<RamDomain>& args, std::vector<RamDomain>& ret) {
if (performIO) {
try {std::map<std::string, std::string> directiveMap({{"IO","file"},{"attributeNames","x\ty"},{"fact-dir","gen"},{"name","edge"},{"operation","input"},{"params","{\"records\": {}, \"relation\": {\"arity\": 2, \"auxArity\": 0, \"params\": [\"x\", \"y\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 2, \"auxArity\": 0, \"types\": [\"i:number\", \"i:number\"]}}"}});
if (!inputDirectory.empty()) {directiveMap["fact-dir"] = inputDirectory;}
IOSystem::getInstance().getReader(directiveMap, symTable, recordTable)->readAll(*rel_3_edge);
} catch (std::exception& e) {std::cerr << "Error loading data: " << e.what() << '\n';}
}
}
#ifdef _MSC_VER
#pragma warning(default: 4100)
#endif // _MSC_VER
#ifdef _MSC_VER
#pragma warning(disable: 4100)
#endif // _MSC_VER
void subroutine_1(const std::vector<RamDomain>& args, std::vector<RamDomain>& ret) {
SignalHandler::instance()->setMsg(R"_(path(x,y) :-
edge(x,y).
in file /home/pree/Code/Haskell/pltest/src/sema.dl [7:1-7:26])_");
if(!(rel_3_edge->empty())) {
[&](){
CREATE_OP_CONTEXT(rel_4_path_op_ctxt,rel_4_path->createContext());
CREATE_OP_CONTEXT(rel_3_edge_op_ctxt,rel_3_edge->createContext());
for(const auto& env0 : *rel_3_edge) {
Tuple<RamDomain,2> tuple{{ramBitCast(env0[0]),ramBitCast(env0[1])}};
rel_4_path->insert(tuple,READ_OP_CONTEXT(rel_4_path_op_ctxt));
}
}
();}
[&](){
CREATE_OP_CONTEXT(rel_4_path_op_ctxt,rel_4_path->createContext());
CREATE_OP_CONTEXT(rel_1_delta_path_op_ctxt,rel_1_delta_path->createContext());
for(const auto& env0 : *rel_4_path) {
Tuple<RamDomain,2> tuple{{ramBitCast(env0[0]),ramBitCast(env0[1])}};
rel_1_delta_path->insert(tuple,READ_OP_CONTEXT(rel_1_delta_path_op_ctxt));
}
}
();iter = 0;
for(;;) {
SignalHandler::instance()->setMsg(R"_(path(x,y) :-
path(x,z),
edge(z,y).
in file /home/pree/Code/Haskell/pltest/src/sema.dl [8:1-8:38])_");
if(!(rel_1_delta_path->empty()) && !(rel_3_edge->empty())) {
[&](){
CREATE_OP_CONTEXT(rel_4_path_op_ctxt,rel_4_path->createContext());
CREATE_OP_CONTEXT(rel_2_new_path_op_ctxt,rel_2_new_path->createContext());
CREATE_OP_CONTEXT(rel_3_edge_op_ctxt,rel_3_edge->createContext());
CREATE_OP_CONTEXT(rel_1_delta_path_op_ctxt,rel_1_delta_path->createContext());
for(const auto& env0 : *rel_1_delta_path) {
auto range = rel_3_edge->lowerUpperRange_10(Tuple<RamDomain,2>{{ramBitCast(env0[1]), ramBitCast<RamDomain>(MIN_RAM_SIGNED)}},Tuple<RamDomain,2>{{ramBitCast(env0[1]), ramBitCast<RamDomain>(MAX_RAM_SIGNED)}},READ_OP_CONTEXT(rel_3_edge_op_ctxt));
for(const auto& env1 : range) {
if( !(rel_4_path->contains(Tuple<RamDomain,2>{{ramBitCast(env0[0]),ramBitCast(env1[1])}},READ_OP_CONTEXT(rel_4_path_op_ctxt)))) {
Tuple<RamDomain,2> tuple{{ramBitCast(env0[0]),ramBitCast(env1[1])}};
rel_2_new_path->insert(tuple,READ_OP_CONTEXT(rel_2_new_path_op_ctxt));
}
}
}
}
();}
if(rel_2_new_path->empty()) break;
[&](){
CREATE_OP_CONTEXT(rel_4_path_op_ctxt,rel_4_path->createContext());
CREATE_OP_CONTEXT(rel_2_new_path_op_ctxt,rel_2_new_path->createContext());
for(const auto& env0 : *rel_2_new_path) {
Tuple<RamDomain,2> tuple{{ramBitCast(env0[0]),ramBitCast(env0[1])}};
rel_4_path->insert(tuple,READ_OP_CONTEXT(rel_4_path_op_ctxt));
}
}
();std::swap(rel_1_delta_path, rel_2_new_path);
rel_2_new_path->purge();
iter++;
}
iter = 0;
rel_1_delta_path->purge();
rel_2_new_path->purge();
if (performIO) {
try {std::map<std::string, std::string> directiveMap({{"IO","file"},{"attributeNames","x\ty"},{"name","path"},{"operation","output"},{"output-dir","src"},{"params","{\"records\": {}, \"relation\": {\"arity\": 2, \"auxArity\": 0, \"params\": [\"x\", \"y\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 2, \"auxArity\": 0, \"types\": [\"i:number\", \"i:number\"]}}"}});
if (!outputDirectory.empty()) {directiveMap["output-dir"] = outputDirectory;}
IOSystem::getInstance().getWriter(directiveMap, symTable, recordTable)->writeAll(*rel_4_path);
} catch (std::exception& e) {std::cerr << e.what();exit(1);}
}
if (performIO) rel_3_edge->purge();
if (performIO) rel_4_path->purge();
}
#ifdef _MSC_VER
#pragma warning(default: 4100)
#endif // _MSC_VER
};
SouffleProgram *newInstance_test(){return new Sf_test;}
SymbolTable *getST_test(SouffleProgram *p){return &reinterpret_cast<Sf_test*>(p)->symTable;}
#ifdef __EMBEDDED_SOUFFLE__
class factory_Sf_test: public souffle::ProgramFactory {
SouffleProgram *newInstance() {
return new Sf_test();
};
public:
factory_Sf_test() : ProgramFactory("test"){}
};
extern "C" {
factory_Sf_test __factory_Sf_test_instance;
}
}
#else
}
int main(int argc, char** argv)
{
try{
souffle::CmdOptions opt(R"(src/sema.dl)",
R"()",
R"()",
false,
R"()",
1);
if (!opt.parse(argc,argv)) return 1;
souffle::Sf_test obj;
#if defined(_OPENMP)
obj.setNumThreads(opt.getNumJobs());
#endif
obj.runAll(opt.getInputFileDir(), opt.getOutputFileDir());
return 0;
} catch(std::exception &e) { souffle::SignalHandler::instance()->error(e.what());}
}
#endif
| 37.612632
| 394
| 0.696463
|
chessai
|
fd9aad3497be9e9e744748a5ffb9e075298fbd87
| 1,372
|
cpp
|
C++
|
games/saloon/impl/saloon.cpp
|
JackLimes/Joueur.cpp
|
d7dc45b5f95d9b3fc8c9cb846d63d6f44c83a61b
|
[
"MIT"
] | null | null | null |
games/saloon/impl/saloon.cpp
|
JackLimes/Joueur.cpp
|
d7dc45b5f95d9b3fc8c9cb846d63d6f44c83a61b
|
[
"MIT"
] | null | null | null |
games/saloon/impl/saloon.cpp
|
JackLimes/Joueur.cpp
|
d7dc45b5f95d9b3fc8c9cb846d63d6f44c83a61b
|
[
"MIT"
] | null | null | null |
// DO NOT MODIFY THIS FILE
// Never try to directly create an instance of this class, or modify its member variables.
// This contains implementation details, written by code, and only useful to code
#include "saloon.hpp"
#include "../../../joueur/src/register.hpp"
#include "../../../joueur/src/exceptions.hpp"
namespace cpp_client
{
namespace saloon
{
//register the game
Game_registry registration("Saloon",
std::unique_ptr<Saloon>(new Saloon));
std::unique_ptr<Base_ai> Saloon::generate_ai()
{
return std::unique_ptr<Base_ai>(new AI);
}
std::shared_ptr<Base_object> Saloon::generate_object(const std::string& type)
{
if(type == "Bottle")
{
return std::make_shared<Bottle_>();
}
else if(type == "Cowboy")
{
return std::make_shared<Cowboy_>();
}
else if(type == "Furnishing")
{
return std::make_shared<Furnishing_>();
}
else if(type == "GameObject")
{
return std::make_shared<Game_object_>();
}
else if(type == "Player")
{
return std::make_shared<Player_>();
}
else if(type == "Tile")
{
return std::make_shared<Tile_>();
}
else if(type == "YoungGun")
{
return std::make_shared<Young_gun_>();
}
throw Unknown_type("Unknown type " + type + " encountered.");
}
} // saloon
} // cpp_client
| 22.491803
| 90
| 0.612245
|
JackLimes
|
fd9cc246d6b4fd6b14364e65c8d42f34d4ced63f
| 316
|
cpp
|
C++
|
src/main.cpp
|
hamlyn-centre/daVinciToolTrack
|
01f1a17abbe2859b70e323780ec69a112a8c7d7c
|
[
"BSD-3-Clause"
] | 2
|
2017-08-25T14:11:18.000Z
|
2021-09-07T11:47:34.000Z
|
src/main.cpp
|
magnumye/daVinciToolTrack
|
01f1a17abbe2859b70e323780ec69a112a8c7d7c
|
[
"BSD-3-Clause"
] | null | null | null |
src/main.cpp
|
magnumye/daVinciToolTrack
|
01f1a17abbe2859b70e323780ec69a112a8c7d7c
|
[
"BSD-3-Clause"
] | 6
|
2017-08-16T16:19:08.000Z
|
2020-08-05T06:13:20.000Z
|
#include <QApplication>
#include "GraphicalUserInterface.h"
int main(int argc, char** argv)
{
std::string config_path;
config_path = "../config/sim_config_win.xml"; // Change here
QApplication app(argc, argv);
GraphicalUserInterface gui (config_path);
gui.show();
return app.exec();
}
| 18.588235
| 66
| 0.677215
|
hamlyn-centre
|
fd9deced51df97b4f190ad3254755eaae6594c15
| 1,231
|
hpp
|
C++
|
tests/unit/coherence/util/filter/InFilterTest.hpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 6
|
2020-07-01T21:38:30.000Z
|
2021-11-03T01:35:11.000Z
|
tests/unit/coherence/util/filter/InFilterTest.hpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 1
|
2020-07-24T17:29:22.000Z
|
2020-07-24T18:29:04.000Z
|
tests/unit/coherence/util/filter/InFilterTest.hpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 6
|
2020-07-10T18:40:58.000Z
|
2022-02-18T01:23:40.000Z
|
/*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "cxxtest/TestSuite.h"
#include "coherence/lang.ns"
#include "coherence/util/extractor/IdentityExtractor.hpp"
#include "coherence/util/filter/InFilter.hpp"
#include "coherence/util/HashSet.hpp"
using namespace coherence::lang;
using coherence::util::extractor::IdentityExtractor;
using coherence::util::filter::InFilter;
using coherence::util::HashSet;
/**
* Test Suite for the InFilter.
*/
class InFilterSuite : public CxxTest::TestSuite
{
public:
/**
* Test InFilter
*/
void testInFilter()
{
HashSet::Handle hHS = HashSet::create();
hHS->add(String::create("Noah"));
hHS->add(String::create("Mark"));
hHS->add(String::create("Jason"));
IdentityExtractor::View hExtract = IdentityExtractor::create();
InFilter::Handle hFilter = InFilter::create(hExtract, hHS);
TS_ASSERT(!hFilter->evaluate(String::create("David")));
TS_ASSERT(hFilter->evaluate(String::create("Mark")));
}
};
| 29.309524
| 75
| 0.637693
|
chpatel3
|
fd9efeba0053a243ea42698513461126c66ac1bf
| 568
|
cpp
|
C++
|
app/src/main/cpp/lab1/main1.cpp
|
kinteg/y4eba
|
3edb28653a26e9e634be786ca05cc4bc315ba228
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/cpp/lab1/main1.cpp
|
kinteg/y4eba
|
3edb28653a26e9e634be786ca05cc4bc315ba228
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/cpp/lab1/main1.cpp
|
kinteg/y4eba
|
3edb28653a26e9e634be786ca05cc4bc315ba228
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by kinteg on 01.11.2021.
//
#include "lab1/main1.h"
void main1() Жи
обнуляем
cppLabMain1::Lab1 lab1;
int length;
System_out_println "Input length: ";
scanner_next length;
int *arr = new int[length];
System_out_println "Your random arr is: ";
for (int i = 0; i < length; ++i) Жи
arr[i] = newRand
System_out_println arr[i] concat " ";
есть
int monoLength = lab1.monoLength(arr, length);
System_out_println "\nYour monoLength value is: " concat monoLength concat ln;
delete[] arr;
есть
| 20.285714
| 82
| 0.635563
|
kinteg
|
fda012ff62c32ca8c90eac0705f7cdf9a37a1c6c
| 4,569
|
cpp
|
C++
|
cocos2dx_playground/Classes/step_defender_tool_TileSheetNode.cpp
|
R2Road/cocos2dx_playground
|
6e6f349b5c9fc702558fe8720ba9253a8ba00164
|
[
"Apache-2.0"
] | 9
|
2020-06-11T17:09:44.000Z
|
2021-12-25T00:34:33.000Z
|
cocos2dx_playground/Classes/step_defender_tool_TileSheetNode.cpp
|
R2Road/cocos2dx_playground
|
6e6f349b5c9fc702558fe8720ba9253a8ba00164
|
[
"Apache-2.0"
] | 9
|
2019-12-21T15:01:01.000Z
|
2020-12-05T15:42:43.000Z
|
cocos2dx_playground/Classes/step_defender_tool_TileSheetNode.cpp
|
R2Road/cocos2dx_playground
|
6e6f349b5c9fc702558fe8720ba9253a8ba00164
|
[
"Apache-2.0"
] | 1
|
2020-09-07T01:32:16.000Z
|
2020-09-07T01:32:16.000Z
|
#include "step_defender_tool_TileSheetNode.h"
#include <new>
#include <numeric>
#include "2d/CCLayer.h"
#include "2d/CCSprite.h"
#include "base/CCDirector.h"
#include "renderer/CCTextureCache.h"
#include "ui/UIButton.h"
#include "ui/UIScale9Sprite.h"
#include "cpg_Clamp.h"
USING_NS_CC;
namespace step_defender
{
namespace tool
{
TileSheetNode::TileSheetNode( const cpg::TileSheetConfiguration& config ) :
mConfig( config )
, mPosition2GridIndexConverter( mConfig.GetBlockWidth(), mConfig.GetBlockHeight() )
, mSelectCallback( nullptr )
, mIndicator( nullptr )
, mLastSelectedPoint()
{}
TileSheetNode* TileSheetNode::create( const cpg::TileSheetConfiguration& config )
{
CCASSERT( 0 < config.GetTileWidth() && 0 < config.GetTileHeight(), "Failed - TileSheetNode::create" );
auto ret = new ( std::nothrow ) TileSheetNode( config );
if( !ret || !ret->init() )
{
delete ret;
ret = nullptr;
}
else
{
ret->autorelease();
}
return ret;
}
bool TileSheetNode::init()
{
if( !Node::init() )
{
return false;
}
auto texture = _director->getTextureCache()->addImage( mConfig.GetTexturePath() );
CCASSERT( nullptr != texture, "Texture Nothing" );
texture->setAliasTexParameters();
setContentSize( texture->getContentSize() );
//
// Pivot
//
{
auto pivot = Sprite::createWithSpriteFrameName( "helper_pivot.png" );
pivot->setScale( 2.f );
addChild( pivot, std::numeric_limits<int>::max() );
}
//
// Sheet View
//
{
auto sprite = Sprite::createWithTexture( texture );
sprite->setAnchorPoint( Vec2::ZERO );
addChild( sprite );
// Guide
auto guide = LayerColor::create( Color4B( 0u, 0u, 0u, 60u ), sprite->getContentSize().width, sprite->getContentSize().height );
addChild( guide, -1 );
}
//
// Mouse Interface
//
{
const Size Margin( 10.f, 10.f );
auto button = ui::Button::create( "guide_01_3.png", "guide_01_3.png", "guide_01_3.png", ui::Widget::TextureResType::PLIST );
button->setAnchorPoint( Vec2::ZERO );
button->setScale9Enabled( true );
button->setContentSize( Margin + getContentSize() + Margin );
button->addTouchEventListener( CC_CALLBACK_2( TileSheetNode::onButton, this ) );
button->setPosition( Vec2( -Margin.width, -Margin.height ) );
addChild( button, std::numeric_limits<int>::min() );
}
//
// Indicator
//
{
auto sprite = ui::Scale9Sprite::createWithSpriteFrameName( "s9_guide_01_0.png" );
sprite->setAnchorPoint( Vec2::ZERO );
sprite->setScale9Enabled( true );
sprite->setContentSize( CC_SIZE_PIXELS_TO_POINTS( Size( mConfig.GetBlockWidth(), mConfig.GetBlockHeight() ) ) );
sprite->setColor( Color3B::GREEN );
addChild( sprite, std::numeric_limits<int>::max() );
mIndicator = sprite;
}
//
// Setup
//
updateSelectedPoint( Vec2::ZERO );
updateIndicatorPosition();
return true;
}
void TileSheetNode::onButton( Ref* sender, ui::Widget::TouchEventType touch_event_type )
{
auto button = static_cast<ui::Button*>( sender );
if( ui::Widget::TouchEventType::BEGAN == touch_event_type )
{
updateSelectedPoint( button->getTouchBeganPosition() );
}
else if( ui::Widget::TouchEventType::MOVED == touch_event_type )
{
updateSelectedPoint( button->getTouchMovePosition() );
}
else if( ui::Widget::TouchEventType::ENDED == touch_event_type || ui::Widget::TouchEventType::CANCELED == touch_event_type )
{
updateSelectedPoint( button->getTouchEndPosition() );
}
if( mSelectCallback )
{
mSelectCallback( mLastSelectedPoint.x, mLastSelectedPoint.y );
}
updateIndicatorPosition();
}
void TileSheetNode::updateSelectedPoint( const cocos2d::Vec2& world_position )
{
const auto node_space_position = convertToNodeSpace( world_position );
const Vec2 fixed_position( cpg::clamp( node_space_position.x, 0.f, getContentSize().width - 1.f ), cpg::clamp( node_space_position.y, 0.f, getContentSize().height - 1.f ) );
const auto scaled_position = fixed_position * _director->getContentScaleFactor();
const auto touch_point = mPosition2GridIndexConverter.Position2Point( scaled_position.x, scaled_position.y );
mLastSelectedPoint.x = touch_point.x;
mLastSelectedPoint.y = touch_point.y;
}
void TileSheetNode::updateIndicatorPosition()
{
mIndicator->setPosition(
mLastSelectedPoint.x * mIndicator->getContentSize().width
, mLastSelectedPoint.y * mIndicator->getContentSize().height
);
}
}
}
| 27.859756
| 176
| 0.678923
|
R2Road
|
fdacd38f340efc247046d26fd3a5a7d394638d98
| 129
|
cc
|
C++
|
tensorflow-yolo-ios/dependencies/tensorflow/core/platform/default/logging.cc
|
initialz/tensorflow-yolo-face-ios
|
ba74cf39168d0128e91318e65a1b88ce4d65a167
|
[
"MIT"
] | 27
|
2017-06-07T19:07:32.000Z
|
2020-10-15T10:09:12.000Z
|
tensorflow-yolo-ios/dependencies/tensorflow/core/platform/default/logging.cc
|
initialz/tensorflow-yolo-face-ios
|
ba74cf39168d0128e91318e65a1b88ce4d65a167
|
[
"MIT"
] | 3
|
2017-08-25T17:39:46.000Z
|
2017-11-18T03:40:55.000Z
|
tensorflow-yolo-ios/dependencies/tensorflow/core/platform/default/logging.cc
|
initialz/tensorflow-yolo-face-ios
|
ba74cf39168d0128e91318e65a1b88ce4d65a167
|
[
"MIT"
] | 10
|
2017-06-16T18:04:45.000Z
|
2018-07-05T17:33:01.000Z
|
version https://git-lfs.github.com/spec/v1
oid sha256:64cf444726b38c066432a37af00bfb70d2a1064b2f36407cc2d280832bacfa37
size 5787
| 32.25
| 75
| 0.883721
|
initialz
|
fdad47490a163b7fa69f954408ba0e3f566aba07
| 1,631
|
cpp
|
C++
|
src/arch/arm/handlers.cpp
|
qookei/tart
|
e039f9c493560f306904793ac9143810aabbf68e
|
[
"Zlib"
] | 11
|
2020-06-20T19:05:08.000Z
|
2021-04-07T17:49:18.000Z
|
src/arch/arm/handlers.cpp
|
qookei/tart
|
e039f9c493560f306904793ac9143810aabbf68e
|
[
"Zlib"
] | null | null | null |
src/arch/arm/handlers.cpp
|
qookei/tart
|
e039f9c493560f306904793ac9143810aabbf68e
|
[
"Zlib"
] | null | null | null |
#include "handlers.hpp"
#include <tart/time.hpp>
#include <stdint.h>
#include <tart/log.hpp>
namespace tart {
struct irq_state {
uintptr_t r0, r1, r2, r3, r12;
uintptr_t lr, pc, psr;
void log() {
info() << "r0 = " << frg::hex_fmt{r0} << frg::endlog;
info() << "r1 = " << frg::hex_fmt{r1} << frg::endlog;
info() << "r2 = " << frg::hex_fmt{r2} << frg::endlog;
info() << "r3 = " << frg::hex_fmt{r3} << frg::endlog;
info() << "r12 = " << frg::hex_fmt{r12} << frg::endlog;
info() << "lr = " << frg::hex_fmt{lr} << frg::endlog;
info() << "pc = " << frg::hex_fmt{pc} << frg::endlog;
info() << "psr = " << frg::hex_fmt{psr} << frg::endlog;
}
};
void nmi(void *ctx) {
static_cast<irq_state *>(ctx)->log();
fatal() << "tart: unexpected nmi" << frg::endlog;
}
void hard_fault(void *ctx) {
static_cast<irq_state *>(ctx)->log();
fatal() << "tart: unexpected hard fault" << frg::endlog;
}
void mm_fault(void *ctx) {
static_cast<irq_state *>(ctx)->log();
fatal() << "tart: unexpected mm fault" << frg::endlog;
}
void bus_fault(void *ctx) {
static_cast<irq_state *>(ctx)->log();
fatal() << "tart: unexpected bus fault" << frg::endlog;
}
void usage_fault(void *ctx) {
static_cast<irq_state *>(ctx)->log();
fatal() << "tart: unexpected usage fault" << frg::endlog;
}
void sv_call(void *ctx) {
static_cast<irq_state *>(ctx)->log();
fatal() << "tart: unexpected sv call" << frg::endlog;
}
void pend_sv_call(void *ctx) {
static_cast<irq_state *>(ctx)->log();
fatal() << "tart: unexpected pending sv call" << frg::endlog;
}
void systick(void *) {
current_time_ = current_time_ + 1;
}
} // namespace tart
| 24.712121
| 62
| 0.603311
|
qookei
|
fdade2822b19689a35a633d30ad866f893c4e64b
| 2,409
|
cpp
|
C++
|
hiro/core/keyboard.cpp
|
CasualPokePlayer/ares
|
58690cd5fc7bb6566c22935c5b80504a158cca29
|
[
"BSD-3-Clause"
] | 153
|
2020-07-25T17:55:29.000Z
|
2021-10-01T23:45:01.000Z
|
hiro/core/keyboard.cpp
|
CasualPokePlayer/ares
|
58690cd5fc7bb6566c22935c5b80504a158cca29
|
[
"BSD-3-Clause"
] | 245
|
2021-10-08T09:14:46.000Z
|
2022-03-31T08:53:13.000Z
|
hiro/core/keyboard.cpp
|
CasualPokePlayer/ares
|
58690cd5fc7bb6566c22935c5b80504a158cca29
|
[
"BSD-3-Clause"
] | 44
|
2020-07-25T08:51:55.000Z
|
2021-09-25T16:09:01.000Z
|
#if defined(Hiro_Keyboard)
Keyboard::State Keyboard::state;
const vector<string> Keyboard::keys = {
//physical keyboard buttons
"Escape", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
"PrintScreen", "ScrollLock", "Pause",
"Insert", "Delete", "Home", "End", "PageUp", "PageDown",
"Up", "Down", "Left", "Right",
"Grave", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "Dash", "Equal", "Backspace",
"Tab", "CapsLock", "LeftEnter", "LeftShift", "RightShift",
"LeftControl", "RightControl", "LeftAlt", "RightAlt", "LeftSuper", "RightSuper", "Menu", "Space",
"OpenBracket", "CloseBracket", "Backslash", "Semicolon", "Apostrophe", "Comma", "Period", "Slash",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"NumLock", "Divide", "Multiply", "Subtract", "Add", "RightEnter", "Point",
"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Zero",
//group aliases
"Shift", //"LeftShift" | "RightShift"
"Control", //"LeftControl" | "RightControl"
"Alt", //"LeftAlt" | "RightAlt"
"Super", //"LeftSuper" | "RightSuper"
"Enter", //"LeftEnter" | "RightEnter"
};
auto Keyboard::append(Hotkey hotkey) -> void {
state.hotkeys.append(hotkey);
}
auto Keyboard::hotkey(u32 position) -> Hotkey {
if(position < hotkeyCount()) return state.hotkeys[position];
return {};
}
auto Keyboard::hotkeyCount() -> u32 {
return state.hotkeys.size();
}
auto Keyboard::hotkeys() -> vector<Hotkey> {
return state.hotkeys;
}
auto Keyboard::poll() -> vector<bool> {
auto pressed = pKeyboard::poll();
for(auto& hotkey : state.hotkeys) {
bool active = hotkey.state->sequence.size() > 0;
for(auto& key : hotkey.state->keys) {
if(pressed[key]) continue;
active = false;
break;
}
if(hotkey.state->active != active) {
hotkey.state->active = active;
active ? hotkey.doPress() : hotkey.doRelease();
}
}
return pressed;
}
auto Keyboard::pressed(const string& key) -> bool {
if(auto code = keys.find(key)) return pKeyboard::pressed(*code);
return false;
}
auto Keyboard::released(const string& key) -> bool {
return !pressed(key);
}
auto Keyboard::remove(Hotkey hotkey) -> void {
if(auto offset = state.hotkeys.find(hotkey)) {
state.hotkeys.remove(*offset);
}
}
#endif
| 30.1125
| 100
| 0.58572
|
CasualPokePlayer
|
fdb199ce8cd576f9768198c646e29f03455b5180
| 6,060
|
cpp
|
C++
|
source/playlunky/mod/character_sticker_gen.cpp
|
C-ffeeStain/Playlunky
|
c0df8a993712192fb44048c8542776ead110441d
|
[
"MIT"
] | 1
|
2020-12-25T19:42:22.000Z
|
2020-12-25T19:42:22.000Z
|
source/playlunky/mod/character_sticker_gen.cpp
|
C-ffeeStain/Playlunky
|
c0df8a993712192fb44048c8542776ead110441d
|
[
"MIT"
] | 1
|
2021-01-01T18:32:41.000Z
|
2021-01-02T09:22:09.000Z
|
source/playlunky/mod/character_sticker_gen.cpp
|
C-ffeeStain/Playlunky
|
c0df8a993712192fb44048c8542776ead110441d
|
[
"MIT"
] | 1
|
2020-12-25T18:02:55.000Z
|
2020-12-25T18:02:55.000Z
|
#include "character_sticker_gen.h"
#include "png_dds_conversion.h"
#include "virtual_filesystem.h"
#include "util/algorithms.h"
#include "util/image.h"
#include <fmt/format.h>
#include <span>
static constexpr struct { std::uint32_t x, y; } s_CharacterStickerIndex{ .x{ 8 }, .y{ 14 } };
static constexpr struct { std::uint32_t x, y; } s_CharacterJournalIndex{ .x{ 9 }, .y{ 14 } };
static constexpr struct { std::uint32_t x, y; } s_NumCharacterTiles{ .x{ 16 }, .y{ 16 } };
static constexpr struct { std::uint32_t x, y; } s_NumStickerTiles{ .x{ 10 }, .y{ 10 } };
static constexpr struct { std::uint32_t x, y; } s_NumJournalTiles{ .x{ 10 }, .y{ 5 } };
static constexpr std::uint32_t s_DefaultStickerTileSize{ 80 };
static constexpr std::uint32_t s_DefaultJournalTileSize{ 160 };
bool CharacterStickerGenerator::RegisterCharacter(std::string_view character_color, bool outdated) {
if (const auto* info = algo::find_if(mInfos, [character_color](const CharacterInfo& info) { return info.Color == character_color; })) {
mNeedsRegen = mNeedsRegen || outdated;
if (!algo::contains(mModdedCharacters, info->Color)) {
mModdedCharacters.push_back(info->Color);
}
return true;
}
return false;
}
bool CharacterStickerGenerator::GenerateStickers(const std::filesystem::path& source_folder, const std::filesystem::path& destination_folder,
const std::filesystem::path& sticker_file, const std::filesystem::path& journal_file, VirtualFilesystem& vfs) {
const auto source_sticker = vfs.GetFilePath(sticker_file).value_or(source_folder / sticker_file);
const auto source_journal = vfs.GetFilePath(journal_file).value_or(source_folder / journal_file);
Image sticker_image;
sticker_image.LoadFromPng(source_sticker);
const TileDimensions sticker_tile_size{
.x{ sticker_image.GetWidth() / s_NumStickerTiles.x },
.y{ sticker_image.GetHeight() / s_NumStickerTiles.y }
};
Image journal_image;
journal_image.LoadFromPng(source_journal);
const TileDimensions journal_tile_size{
.x{ journal_image.GetWidth() / s_NumJournalTiles.x },
.y{ journal_image.GetHeight() / s_NumJournalTiles.y }
};
for (std::string_view character_color : mModdedCharacters) {
const std::string character_path = fmt::format("Data/Textures/char_{}.png", character_color);
if (const auto& char_file = vfs.GetFilePath(character_path)) {
if (const auto* info = algo::find_if(mInfos, [character_color](const CharacterInfo& info) { return info.Color == character_color; })) {
Image modded_stickers_image;
modded_stickers_image.LoadFromPng(char_file.value().parent_path() / sticker_file.filename());
const TileDimensions modded_sticker_tile_size{
.x{ modded_stickers_image.GetWidth() / s_NumStickerTiles.x },
.y{ modded_stickers_image.GetHeight() / s_NumStickerTiles.y }
};
Image modded_journal_image;
modded_journal_image.LoadFromPng(char_file.value().parent_path() / journal_file.filename());
const TileDimensions modded_journal_tile_size{
.x{ modded_journal_image.GetWidth() / s_NumJournalTiles.x },
.y{ modded_journal_image.GetHeight() / s_NumJournalTiles.y }
};
std::optional<Image> char_image;
TileDimensions char_tile_size{};
if (modded_stickers_image.IsEmpty() || modded_journal_image.IsEmpty()) {
char_image.emplace();
char_image->LoadFromPng(char_file.value());
char_tile_size = TileDimensions{
.x{ char_image->GetWidth() / s_NumCharacterTiles.x },
.y{ char_image->GetHeight() / s_NumCharacterTiles.y }
};
}
{
std::optional<Image> sticker_tile;
if (!modded_stickers_image.IsEmpty()) {
sticker_tile = modded_stickers_image.GetSubImage(
ImageTiling{ modded_sticker_tile_size },
ImageSubRegion{ info->TileIndex.x, info->TileIndex.y, 1, 1 });
}
else {
sticker_tile = char_image->GetSubImage(
ImageTiling{ char_tile_size },
ImageSubRegion{ s_CharacterStickerIndex.x, s_CharacterStickerIndex.y, 1, 1 });
}
if (sticker_tile == std::nullopt || sticker_tile->IsEmpty()) {
Image standing_tile = char_image->GetSubImage(
ImageTiling{ char_tile_size },
ImageSubRegion{ 0, 0, 1, 1 });
sticker_tile = std::move(standing_tile);
}
sticker_tile->Resize(ImageSize{ .x{ sticker_tile_size.x }, .y{ sticker_tile_size.y } });
sticker_image.Blit(sticker_tile.value(),
ImageTiling{ sticker_tile_size },
ImageSubRegion{ info->TileIndex.x, info->TileIndex.y, 1, 1 });
}
{
std::optional<Image> entry_tile;
if (!modded_journal_image.IsEmpty()) {
entry_tile = modded_journal_image.GetSubImage(
ImageTiling{ modded_journal_tile_size },
ImageSubRegion{ info->TileIndex.x, info->TileIndex.y, 1, 1 });
}
else {
entry_tile = char_image->GetSubImage(
ImageTiling{ char_tile_size },
ImageSubRegion{ s_CharacterStickerIndex.x, s_CharacterStickerIndex.y, 2, 2 });
}
if (entry_tile == std::nullopt || entry_tile->IsEmpty()) {
Image standing_tile = char_image->GetSubImage(
ImageTiling{ char_tile_size },
ImageSubRegion{ 0, 0, 1, 1 });
entry_tile = std::move(standing_tile);
}
entry_tile->Resize(ImageSize{ .x{ journal_tile_size.x }, .y{ journal_tile_size.y } });
journal_image.Blit(entry_tile.value(),
ImageTiling{ journal_tile_size },
ImageSubRegion{ info->TileIndex.x, info->TileIndex.y, 1, 1 });
}
}
}
}
namespace fs = std::filesystem;
const auto destination_sticker_file = fs::path{ destination_folder / sticker_file }.replace_extension(".DDS");
bool wrote_sticker_file = ConvertRBGAToDds(sticker_image.GetData(), sticker_image.GetWidth(), sticker_image.GetHeight(), destination_sticker_file);
const auto destination_journal_file = fs::path{ destination_folder / journal_file }.replace_extension(".DDS");
bool wrote_journal_file = ConvertRBGAToDds(journal_image.GetData(), journal_image.GetWidth(), journal_image.GetHeight(), destination_journal_file);
return wrote_sticker_file && wrote_journal_file;
}
| 40.13245
| 148
| 0.716997
|
C-ffeeStain
|
fdb1bec94b9f22aa049b832744290f22a87d02cd
| 59
|
cpp
|
C++
|
Source/Tutorial/Components/TutorialMovementComponent.cpp
|
PsichiX/Unreal-Systems-Architecture
|
fb2ccb243c8e79b0890736d611db7ba536937a93
|
[
"Apache-2.0"
] | 5
|
2022-02-09T21:19:03.000Z
|
2022-03-03T01:53:03.000Z
|
Source/Tutorial/Components/TutorialMovementComponent.cpp
|
PsichiX/Unreal-Systems-Architecture
|
fb2ccb243c8e79b0890736d611db7ba536937a93
|
[
"Apache-2.0"
] | null | null | null |
Source/Tutorial/Components/TutorialMovementComponent.cpp
|
PsichiX/Unreal-Systems-Architecture
|
fb2ccb243c8e79b0890736d611db7ba536937a93
|
[
"Apache-2.0"
] | null | null | null |
#include "Tutorial/Components/TutorialMovementComponent.h"
| 29.5
| 58
| 0.864407
|
PsichiX
|
fdb2069f751b81eb9524e27b380325cf8de6c810
| 3,774
|
cpp
|
C++
|
Engine/source/T3D/sceneComponent/T3DSceneClient.cpp
|
vbillet/Torque3D
|
ece8823599424ea675e5f79d9bcb44e42cba8cae
|
[
"MIT"
] | 2,113
|
2015-01-01T11:23:01.000Z
|
2022-03-28T04:51:46.000Z
|
Engine/source/T3D/sceneComponent/T3DSceneClient.cpp
|
Ashry00/Torque3D
|
33e3e41c8b7eb41c743a589558bc21302207ef97
|
[
"MIT"
] | 948
|
2015-01-02T01:50:00.000Z
|
2022-02-27T05:56:40.000Z
|
Engine/source/T3D/sceneComponent/T3DSceneClient.cpp
|
Ashry00/Torque3D
|
33e3e41c8b7eb41c743a589558bc21302207ef97
|
[
"MIT"
] | 944
|
2015-01-01T09:33:53.000Z
|
2022-03-15T22:23:03.000Z
|
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "T3DSceneClient.h"
//---------------------------------------------------
// T3DSceneClient
//---------------------------------------------------
void T3DSceneClient::setSceneGroupName(const char * name)
{
_sceneGroupName = StringTable->insert(name);
if (getOwner() != NULL)
{
if (_sceneGroup != NULL)
_sceneGroup->RemoveClientObject(this);
_sceneGroup = NULL;
ValueWrapperInterface<T3DSceneComponent*> * iface = getInterface<ValueWrapperInterface<T3DSceneComponent*> >("sceneComponent", _sceneGroupName);
if (iface != NULL)
{
_sceneGroup = iface->get();
_sceneGroup->AddSceneClient(this);
}
}
}
bool T3DSceneClient::onComponentRegister(SimComponent * owner)
{
if (!Parent::onComponentRegister(owner))
return false;
// lookup scene group and add ourself
setSceneGroupName(_sceneGroupName);
if (_sceneGroupName != NULL && dStricmp(_sceneGroupName, "none") && _sceneGroup == NULL)
// tried to add ourself to a scene group but failed, fail to add component
return false;
return true;
}
void T3DSceneClient::registerInterfaces(SimComponent * owner)
{
Parent::registerInterfaces(owner);
registerCachedInterface("sceneClient", NULL, this, new ValueWrapperInterface<T3DSceneClient>());
}
//---------------------------------------------------
// T3DSceneClient
//---------------------------------------------------
Box3F T3DSolidSceneClient::getWorldBox()
{
MatrixF mat = getTransform();
Box3F box = _objectBox->get();
mat.mul(box);
return box;
}
const MatrixF & T3DSolidSceneClient::getTransform()
{
if (_transform != NULL)
return _transform->getWorldMatrix();
else if (getSceneGroup() != NULL)
return getSceneGroup()->getTransform3D()->getWorldMatrix();
else
return MatrixF::smIdentity;
}
void T3DSolidSceneClient::setTransform3D(Transform3D * transform)
{
if (_transform != NULL)
_transform->setDirtyListener(NULL);
_transform = transform;
_transform->setDirtyListener(this);
OnTransformDirty();
}
void T3DSolidSceneClient::OnTransformDirty()
{
// TODO: need a way to skip this...a flag, but we don't want to add a bool just for that
// reason we might want to skip it is if we have a renderable that orbits an object but always
// stays within object box. Want to be able to use that info to skip object box updates.
if (getSceneGroup() != NULL)
getSceneGroup()->setDirtyObjectBox(true);
}
| 34.944444
| 150
| 0.649709
|
vbillet
|
fdb6a5da320659fc592139a49a30867bb6302410
| 4,016
|
cpp
|
C++
|
Blizzlike/Trinity/Scripts/PvP/AlteracValley/boss_vanndar.cpp
|
499453466/Lua-Other
|
43fd2b72405faf3f2074fd2a2706ef115d16faa6
|
[
"Unlicense"
] | 2
|
2015-06-23T16:26:32.000Z
|
2019-06-27T07:45:59.000Z
|
Blizzlike/Trinity/Scripts/PvP/AlteracValley/boss_vanndar.cpp
|
Eduardo-Silla/Lua-Other
|
db610f946dbcaf81b3de9801f758e11a7bf2753f
|
[
"Unlicense"
] | null | null | null |
Blizzlike/Trinity/Scripts/PvP/AlteracValley/boss_vanndar.cpp
|
Eduardo-Silla/Lua-Other
|
db610f946dbcaf81b3de9801f758e11a7bf2753f
|
[
"Unlicense"
] | 3
|
2015-01-10T18:22:59.000Z
|
2021-04-27T21:28:28.000Z
|
/*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
enum Yells
{
YELL_AGGRO = 0,
YELL_EVADE = 1,
YELL_RESPAWN1 = -1810010, // no creature_text
YELL_RESPAWN2 = -1810011, // no creature_text
YELL_RANDOM = 2,
YELL_SPELL = 3,
};
enum Spells
{
SPELL_AVATAR = 19135,
SPELL_THUNDERCLAP = 15588,
SPELL_STORMBOLT = 20685 // not sure
};
class boss_vanndar : public CreatureScript
{
public:
boss_vanndar() : CreatureScript("boss_vanndar") { }
struct boss_vanndarAI : public ScriptedAI
{
boss_vanndarAI(Creature* creature) : ScriptedAI(creature) {}
uint32 AvatarTimer;
uint32 ThunderclapTimer;
uint32 StormboltTimer;
uint32 ResetTimer;
uint32 YellTimer;
void Reset()
{
AvatarTimer = 3 * IN_MILLISECONDS;
ThunderclapTimer = 4 * IN_MILLISECONDS;
StormboltTimer = 6 * IN_MILLISECONDS;
ResetTimer = 5 * IN_MILLISECONDS;
YellTimer = urand(20 * IN_MILLISECONDS, 30 * IN_MILLISECONDS);
}
void EnterCombat(Unit* /*who*/)
{
Talk(YELL_AGGRO);
}
void JustRespawned()
{
Reset();
DoScriptText(RAND(YELL_RESPAWN1, YELL_RESPAWN2), me);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (AvatarTimer <= diff)
{
DoCast(me->getVictim(), SPELL_AVATAR);
AvatarTimer = urand(15 * IN_MILLISECONDS, 20 * IN_MILLISECONDS);
} else AvatarTimer -= diff;
if (ThunderclapTimer <= diff)
{
DoCast(me->getVictim(), SPELL_THUNDERCLAP);
ThunderclapTimer = urand(5 * IN_MILLISECONDS, 15 * IN_MILLISECONDS);
} else ThunderclapTimer -= diff;
if (StormboltTimer <= diff)
{
DoCast(me->getVictim(), SPELL_STORMBOLT);
StormboltTimer = urand(10 * IN_MILLISECONDS, 25 * IN_MILLISECONDS);
} else StormboltTimer -= diff;
if (YellTimer <= diff)
{
Talk(YELL_RANDOM);
YellTimer = urand(20 * IN_MILLISECONDS, 30 * IN_MILLISECONDS); //20 to 30 seconds
} else YellTimer -= diff;
// check if creature is not outside of building
if (ResetTimer <= diff)
{
if (me->GetDistance2d(me->GetHomePosition().GetPositionX(), me->GetHomePosition().GetPositionY()) > 50)
{
EnterEvadeMode();
Talk(YELL_EVADE);
}
ResetTimer = 5 * IN_MILLISECONDS;
} else ResetTimer -= diff;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_vanndarAI(creature);
}
};
void AddSC_boss_vanndar()
{
new boss_vanndar;
}
| 31.873016
| 119
| 0.538596
|
499453466
|
fdb808e50aa17d00acbe8a0719bd27044d20376b
| 7,642
|
hpp
|
C++
|
plugins/node_watercolor.hpp
|
Yleroimar/3D-Comic-Rendering
|
8c3221625dfbb5a4d5efc92b235d547a4e6e66ad
|
[
"MIT"
] | 1
|
2021-10-05T09:22:39.000Z
|
2021-10-05T09:22:39.000Z
|
plugins/node_watercolor.hpp
|
Yleroimar/3D-Comic-Rendering
|
8c3221625dfbb5a4d5efc92b235d547a4e6e66ad
|
[
"MIT"
] | null | null | null |
plugins/node_watercolor.hpp
|
Yleroimar/3D-Comic-Rendering
|
8c3221625dfbb5a4d5efc92b235d547a4e6e66ad
|
[
"MIT"
] | null | null | null |
#pragma once
///////////////////////////////////////////////////////////////////////////////////
// _ _ _
// __ ____ _| |_ ___ _ __ ___ ___ | | ___ _ __ _ __ ___ __| | ___
// \ \ /\ / / _` | __/ _ \ '__/ __/ _ \| |/ _ \| '__| | '_ \ / _ \ / _` |/ _ \
// \ V V / (_| | || __/ | | (_| (_) | | (_) | | | | | | (_) | (_| | __/
// \_/\_/ \__,_|\__\___|_| \___\___/|_|\___/|_| |_| |_|\___/ \__,_|\___|
//
// \brief Watercolor config node
// Contains the attributes and node computation for the watercolor stylization
//
// Developed by: Santiago Montesdeoca
//
///////////////////////////////////////////////////////////////////////////////////
#include "mnpr_renderer.h"
#include "mnpr_nodes.h"
// stylization attributes
static MObject aBleedingThreshold;
static MObject aBleedingRadius;
static MObject aEdgeDarkeningIntensity;
static MObject aEdgeDarkeningWidth;
static MObject aGapsOverlapsWidth;
static MObject aPigmentDensity;
static MObject aDryBrushThreshold;
namespace wc {
void initializeParameters(FXParameters *mFxParams, EngineSettings *mEngSettings) {
// adds parameters in the config node
MStatus status;
float renderScale = mEngSettings->renderScale[0];
// MFn helpers
MFnEnumAttribute eAttr;
MFnTypedAttribute tAttr;
MFnNumericAttribute nAttr;
// disable/enable engine settings
mEngSettings->velocityPV[0] = 0.0;
// color bleeding threshold
aBleedingThreshold = nAttr.create("bleedingThreshold", "bleedingThreshold",
MFnNumericData::kFloat, mFxParams->bleedingThreshold[0], &status);
MAKE_INPUT(nAttr);
nAttr.setMin(0.0);
nAttr.setSoftMax(0.003);
nAttr.setMax(1.0);
ConfigNode::enableAttribute(aBleedingThreshold);
// color bleeding radius
aBleedingRadius = nAttr.create("bleedingRadius", "bleedingRadius",
MFnNumericData::kInt, mFxParams->bleedingRadius[0], &status);
MAKE_INPUT(nAttr);
nAttr.setMin(1.0);
nAttr.setMax(40.0);
ConfigNode::enableAttribute(aBleedingRadius);
// edge darkening intensity
aEdgeDarkeningIntensity = nAttr.create("edgeDarkeningIntensity", "edgeDarkeningIntensity",
MFnNumericData::kFloat, mFxParams->edgeDarkeningIntensity[0], &status);
MAKE_INPUT(nAttr);
nAttr.setMin(0.0);
nAttr.setSoftMax(3.0);
nAttr.setMax(25.0);
ConfigNode::enableAttribute(aEdgeDarkeningIntensity);
// edge darkening width
aEdgeDarkeningWidth = nAttr.create("edgeDarkeningWidth", "edgeDarkeningWidth",
MFnNumericData::kInt, mFxParams->edgeDarkeningWidth[0], &status);
MAKE_INPUT(nAttr);
nAttr.setMin(1);
nAttr.setMax(50);
ConfigNode::enableAttribute(aEdgeDarkeningWidth);
// gaps and overlaps width
aGapsOverlapsWidth = nAttr.create("maxGapsOverlapsWidth", "maxGapsOverlapsWidth",
MFnNumericData::kInt, mFxParams->gapsOverlapsWidth[0], &status);
MAKE_INPUT(nAttr);
nAttr.setMin(1);
nAttr.setSoftMax(5);
nAttr.setMax(10);
ConfigNode::enableAttribute(aGapsOverlapsWidth);
// pigment density
aPigmentDensity = nAttr.create("pigmentDensity", "pigmentDensity",
MFnNumericData::kFloat, mFxParams->pigmentDensity[0]);
MAKE_INPUT(nAttr);
nAttr.setSoftMin(0.0);
nAttr.setSoftMax(10.0);
ConfigNode::enableAttribute(aPigmentDensity);
// drybrush threshold
aDryBrushThreshold = nAttr.create("drybrushThreshold", "drybrushThreshold",
MFnNumericData::kFloat, mFxParams->dryBrushThreshold[0]);
MAKE_INPUT(nAttr);
nAttr.setMin(0.0);
nAttr.setSoftMax(20.0);
ConfigNode::enableAttribute(aDryBrushThreshold);
}
void computeParameters(MNPROverride* mmnpr_renderer,
MDataBlock data,
FXParameters *mFxParams,
EngineSettings *mEngSettings) {
MStatus status;
// BLEEDING
mFxParams->bleedingThreshold[0] = data.inputValue(aBleedingThreshold, &status).asFloat();
int bleedingRadius = (int) (data.inputValue(aBleedingRadius, &status).asShort()
* mEngSettings->renderScale[0]);
if ((mFxParams->bleedingRadius[0] != bleedingRadius) || (!mEngSettings->initialized)) {
mFxParams->bleedingRadius[0] = (float) bleedingRadius;
float sigma = (float) bleedingRadius * 2.0f;
// calculate new bleeding kernel
float normDivisor = 0;
for (int x = -bleedingRadius; x <= bleedingRadius; x++) {
float weight = (float) (0.15915*exp(-0.5*x*x / (sigma*sigma)) / sigma);
//float weight = (float)(pow((6.283185*sigma*sigma), -0.5) * exp((-0.5*x*x) / (sigma*sigma)));
normDivisor += weight;
mFxParams->bleedingWeigths[x + bleedingRadius] = weight;
}
// normalize weights
for (int x = -bleedingRadius; x <= bleedingRadius; x++)
mFxParams->bleedingWeigths[x + bleedingRadius] /= normDivisor;
// send weights to shaders
MOperationShader* opShader;
QuadRender* quadOp = (QuadRender*) mmnpr_renderer->renderOperation("[quad] separable H");
opShader = quadOp->getOperationShader();
MHWRender::MShaderInstance* shaderInstance = opShader->shaderInstance();
if (shaderInstance) {
shaderInstance->setParameter("gBleedingRadius", &mFxParams->bleedingRadius[0]);
shaderInstance->setArrayParameter("gGaussianWeights",
&mFxParams->bleedingWeigths[0], (bleedingRadius * 2) + 1);
}
quadOp = (QuadRender*) mmnpr_renderer->renderOperation("[quad] separable V");
opShader = quadOp->getOperationShader();
shaderInstance = opShader->shaderInstance();
if (shaderInstance) {
shaderInstance->setParameter("gBleedingRadius", &mFxParams->bleedingRadius[0]);
shaderInstance->setArrayParameter("gGaussianWeights",
&mFxParams->bleedingWeigths[0], (bleedingRadius * 2) + 1);
}
}
// EDGE DARKENING
mFxParams->edgeDarkeningIntensity[0] =
data.inputValue(aEdgeDarkeningIntensity, &status).asFloat() * mEngSettings->renderScale[0];
mFxParams->edgeDarkeningWidth[0] =
roundf(data.inputValue(aEdgeDarkeningWidth, &status).asShort() * mEngSettings->renderScale[0]);
// GAPS & OVERLAPS
mFxParams->gapsOverlapsWidth[0] =
roundf(data.inputValue(aGapsOverlapsWidth, &status).asShort() * mEngSettings->renderScale[0]);
// PIGMENT EFFECTS
mFxParams->pigmentDensity[0] = data.inputValue(aPigmentDensity, &status).asFloat();
float drybrushThresholdInput = data.inputValue(aDryBrushThreshold, &status).asFloat();
mFxParams->dryBrushThreshold[0] = (float)20.0 - drybrushThresholdInput;
}
};
| 44.690058
| 118
| 0.572232
|
Yleroimar
|
fdb8c9f1854f747348ce72942bc082a336ccd511
| 8,084
|
cpp
|
C++
|
imp_bridge_opencv/src/image_cv.cpp
|
rockenbf/ze_oss
|
ee04158e2d51acb07a267196f618e9afbc3ffd83
|
[
"BSD-3-Clause"
] | 6
|
2018-12-02T03:03:32.000Z
|
2021-01-19T11:20:35.000Z
|
imp_bridge_opencv/src/image_cv.cpp
|
rockenbf/ze_oss
|
ee04158e2d51acb07a267196f618e9afbc3ffd83
|
[
"BSD-3-Clause"
] | null | null | null |
imp_bridge_opencv/src/image_cv.cpp
|
rockenbf/ze_oss
|
ee04158e2d51acb07a267196f618e9afbc3ffd83
|
[
"BSD-3-Clause"
] | 2
|
2019-04-09T20:02:42.000Z
|
2021-04-27T13:05:24.000Z
|
// Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the ETH Zurich, Wyss Zurich, Zurich Eye 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 ETH Zurich, Wyss Zurich, Zurich Eye 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 <imp/bridge/opencv/image_cv.hpp>
#include <iostream>
#include <imp/core/memory_storage.hpp>
#include <imp/bridge/opencv/cv_connector_pixel_types.hpp>
namespace ze {
//-----------------------------------------------------------------------------
template<typename Pixel>
ImageCv<Pixel>::ImageCv(const ze::Size2u& size, ze::PixelOrder pixel_order)
: Base(size, pixel_order)
, mat_(size[1], size[0], ze::pixelTypeToCv(pixel_type<Pixel>::type))
{
this->header_.pitch = mat_.step;
this->header_.memory_type = (MemoryStorage<Pixel>::isAligned(data())) ?
MemoryType::CpuAligned : MemoryType::Cpu;}
//-----------------------------------------------------------------------------
template<typename Pixel>
ImageCv<Pixel>::ImageCv(uint32_t width, uint32_t height,
ze::PixelOrder pixel_order)
: ImageCv(ze::Size2u(width, height), pixel_order)
{
}
//-----------------------------------------------------------------------------
template<typename Pixel>
ImageCv<Pixel>::ImageCv(const ImageCv<Pixel>& from)
: Base(from)
, mat_(from.cvMat())
{
this->header_.pitch = mat_.step;
this->header_.memory_type = (MemoryStorage<Pixel>::isAligned(data())) ?
MemoryType::CpuAligned : MemoryType::Cpu;
}
//-----------------------------------------------------------------------------
template<typename Pixel>
ImageCv<Pixel>::ImageCv(const Image<Pixel>& from)
: Base(from)
, mat_(from.height(), from.width(), ze::pixelTypeToCv(pixel_type<Pixel>::type))
{
this->header_.pitch = mat_.step;
this->header_.memory_type = (MemoryStorage<Pixel>::isAligned(data())) ?
MemoryType::CpuAligned : MemoryType::Cpu;
from.copyTo(*this);
}
//-----------------------------------------------------------------------------
template<typename Pixel>
ImageCv<Pixel>::ImageCv(cv::Mat mat, ze::PixelOrder pixel_order)
: Base(ze::Size2u(mat.cols, mat.rows), pixel_order)
, mat_(mat)
{
this->header_.pitch = mat_.step;
this->header_.memory_type = (MemoryStorage<Pixel>::isAligned(data())) ?
MemoryType::CpuAligned : MemoryType::Cpu;
CHECK(this->pixelType() == ze::pixelTypeFromCv(mat_.type()))
<< "OpenCV pixel type does not match to the internally used one.";
if (this->pixelOrder() == ze::PixelOrder::undefined)
{
switch (this->pixelType())
{
case ze::PixelType::i8uC1:
case ze::PixelType::i16uC1:
case ze::PixelType::i32fC1:
case ze::PixelType::i32sC1:
this->header_.pixel_order = ze::PixelOrder::gray;
break;
case ze::PixelType::i8uC3:
case ze::PixelType::i16uC3:
case ze::PixelType::i32fC3:
case ze::PixelType::i32sC3:
this->header_.pixel_order = ze::PixelOrder::bgr;
break;
case ze::PixelType::i8uC4:
case ze::PixelType::i16uC4:
case ze::PixelType::i32fC4:
case ze::PixelType::i32sC4:
this->header_.pixel_order = ze::PixelOrder::bgra;
break;
default:
// if we have something else than 1,3 or 4-channel images, we do not set the
// pixel order automatically.
VLOG(100) << "Undefined default order for given pixel type. "
<< "Only 1, 3 and 4 channel images have a default order.";
break;
}
}
}
////-----------------------------------------------------------------------------
//template<typename Pixel, imp::PixelType pixel_type>
//ImageCv<Pixel>
//::ImageCv(Pixel* data, uint32_t width, uint32_t height,
// uint32_t pitch, bool use_ext_data_pointer)
// : Base(width, height)
//{
// if (data == nullptr)
// {
// throw imp::Exception("input data not valid", __FILE__, __FUNCTION__, __LINE__);
// }
// if(use_ext_data_pointer)
// {
// // This uses the external data pointer as internal data pointer.
// auto dealloc_nop = [](Pixel* p) { ; };
// data_ = std::unique_ptr<pixel_storage_t, Deallocator>(
// data, Deallocator(dealloc_nop));
// pitch_ = pitch;
// }
// else
// {
// data_.reset(MemoryStorage<Pixel>::alignedAlloc(this->width(), this->height(), &pitch_));
// size_t stride = pitch / sizeof(pixel_storage_t);
// if (this->bytes() == pitch*height)
// {
// std::copy(data, data+stride*height, data_.get());
// }
// else
// {
// for (uint32_t y=0; y<height; ++y)
// {
// for (uint32_t x=0; x<width; ++x)
// {
// data_.get()[y*this->stride()+x] = data[y*stride + x];
// }
// }
// }
// }
//}
//-----------------------------------------------------------------------------
template<typename Pixel>
cv::Mat& ImageCv<Pixel>::cvMat()
{
return mat_;
}
//-----------------------------------------------------------------------------
template<typename Pixel>
const cv::Mat& ImageCv<Pixel>::cvMat() const
{
return mat_;
}
//-----------------------------------------------------------------------------
template<typename Pixel>
Pixel* ImageCv<Pixel>::data(uint32_t ox, uint32_t oy)
{
CHECK_LT(ox, this->width());
CHECK_LT(oy, this->height());
Pixel* buffer = (Pixel*)mat_.data;
return &buffer[oy*this->stride() + ox];
}
//-----------------------------------------------------------------------------
template<typename Pixel>
const Pixel* ImageCv<Pixel>::data(uint32_t ox, uint32_t oy) const
{
CHECK_LT(ox, this->width());
CHECK_LT(oy, this->height());
Pixel* buffer = (Pixel*)mat_.data;
return reinterpret_cast<const Pixel*>(&buffer[oy*this->stride() + ox]);
}
//-----------------------------------------------------------------------------
template<typename Pixel>
void ImageCv<Pixel>::setValue(const Pixel& value)
{
mat_ = cv::Scalar::all(value);
}
//=============================================================================
// Explicitely instantiate the desired classes
// (sync with typedefs at the end of the hpp file)
template class ImageCv<ze::Pixel8uC1>;
template class ImageCv<ze::Pixel8uC2>;
template class ImageCv<ze::Pixel8uC3>;
template class ImageCv<ze::Pixel8uC4>;
template class ImageCv<ze::Pixel16uC1>;
template class ImageCv<ze::Pixel16uC2>;
template class ImageCv<ze::Pixel16uC3>;
template class ImageCv<ze::Pixel16uC4>;
template class ImageCv<ze::Pixel32sC1>;
template class ImageCv<ze::Pixel32sC2>;
template class ImageCv<ze::Pixel32sC3>;
template class ImageCv<ze::Pixel32sC4>;
template class ImageCv<ze::Pixel32fC1>;
template class ImageCv<ze::Pixel32fC2>;
template class ImageCv<ze::Pixel32fC3>;
template class ImageCv<ze::Pixel32fC4>;
} // namespace ze
| 34.695279
| 94
| 0.605764
|
rockenbf
|
fdbf8a5b581c044b1de4946cd7f96d73af8637b6
| 502
|
cpp
|
C++
|
leetcode/leetcode198.cpp
|
KevinYang515/C-Projects
|
1bf95a09a0ffc18102f12263c9163619ce6dba55
|
[
"MIT"
] | null | null | null |
leetcode/leetcode198.cpp
|
KevinYang515/C-Projects
|
1bf95a09a0ffc18102f12263c9163619ce6dba55
|
[
"MIT"
] | null | null | null |
leetcode/leetcode198.cpp
|
KevinYang515/C-Projects
|
1bf95a09a0ffc18102f12263c9163619ce6dba55
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
int rob(vector<int>& nums);
int main(){
vector<vector<int>> nums_v = {{1,2,3,1}, {2,7,9,3,1}}; //4, 12
for (vector<int> nums : nums_v){
printf("%d, ", rob(nums));
}
return 0;
}
int rob(vector<int>& nums) {
int rob = 0, not_rob = 0;
for (int i = 0; i < nums.size(); i++){
int prev = max(rob, not_rob);
rob = not_rob + nums[i];
not_rob = prev;
}
return max(rob, not_rob);
}
| 18.592593
| 67
| 0.525896
|
KevinYang515
|
fdc4230be0acd4c9ffca60485d5e428f197d2f0b
| 3,073
|
cpp
|
C++
|
Sid's Levels/Level - 2/Binary Search Tree/Predecessor And Successor.cpp
|
Tiger-Team-01/DSA-A-Z-Practice
|
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
|
[
"MIT"
] | 14
|
2021-08-22T18:21:14.000Z
|
2022-03-08T12:04:23.000Z
|
Sid's Levels/Level - 2/Binary Search Tree/Predecessor And Successor.cpp
|
Tiger-Team-01/DSA-A-Z-Practice
|
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
|
[
"MIT"
] | 1
|
2021-10-17T18:47:17.000Z
|
2021-10-17T18:47:17.000Z
|
Sid's Levels/Level - 2/Binary Search Tree/Predecessor And Successor.cpp
|
Tiger-Team-01/DSA-A-Z-Practice
|
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
|
[
"MIT"
] | 5
|
2021-09-01T08:21:12.000Z
|
2022-03-09T12:13:39.000Z
|
// { Driver Code Starts
// C++ program to find predecessor and successor in a BST
#include <iostream>
using namespace std;
// BST Node
struct Node
{
int key;
struct Node *left;
struct Node *right;
Node(int x){
key = x;
left = NULL;
right = NULL;
}
};
int key=0;
// This function finds predecessor and successor of key in BST.
// It sets pre and suc as predecessor and successor respectively
void findPreSuc(Node* root, Node*& pre, Node*& suc, int key);
void insert(struct Node *root,int n1,int n2,char lr)
{
if(root==NULL)
return;
if(root->key==n1)
{
switch(lr)
{
case 'L': root->left=new Node(n2);
break;
case 'R': root->right=new Node(n2);
break;
}
}
else
{
insert(root->left,n1,n2,lr);
insert(root->right,n1,n2,lr);
}
}
// Driver program to test above functions
int main()
{
/* Let us construct the tree shown in above diagram */
int t,k;
cin>>t;
while(t--)
{
int n;
cin>>n;
struct Node *root=NULL;
Node *pre=NULL;
Node *suc=NULL;
while(n--)
{
char lr;
int n1,n2;
cin>>n1>>n2;
cin>>lr;
if(root==NULL)
{
root=new Node(n1);
switch(lr){
case 'L': root->left=new Node(n2);
break;
case 'R': root->right=new Node(n2);
break;
}
}
else
{
insert(root,n1,n2,lr);
}
}
// Inorder(root);
//Node * target =ptr;
//printkdistanceNode(root, target, k);
//cout<<endl;
cin>>key;
findPreSuc(root, pre, suc, key);
if (pre != NULL)
cout << pre->key;
else
cout << "-1";
if (suc != NULL)
cout <<" "<<suc->key<<endl;
else
cout << " "<<"-1"<<endl;
}
return 0;
}// } Driver Code Ends
/* BST Node
struct Node
{
int key;
struct Node *left, *right;
};
*/
// This function finds predecessor and successor of key in BST.
// It sets pre and suc as predecessor and successor respectively
void findPreSuc(Node* root, Node*& pre, Node*& suc, int key)
{
//OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
if(root == NULL) return;
if(root->key == key)
{
//max value in left subtree
Node *cur = root;
if(root->left != NULL)
{
Node *cur = root->left;
while(cur->right != NULL)
cur = cur->right;
pre = cur;
}
if(root->right != NULL)
{
Node *cur = root->right;
while(cur->left != NULL)
{
cur = cur->left;
}
suc = cur;
}
}
else if(root->key > key)
{
suc = root;
findPreSuc(root->left, pre, suc, key);
}
else
{
pre = root;
findPreSuc(root->right, pre, suc, key);
}
}
| 20.763514
| 69
| 0.493329
|
Tiger-Team-01
|
fdc58e14f6959e4d31fdd33886e2ecd1073b15b1
| 13,337
|
hpp
|
C++
|
platform/kernel.hpp
|
zhaozhangjian/ROCclr
|
5cefcaf62893fcd86c8feed6bb1ebb84850fcd2f
|
[
"MIT"
] | 7
|
2022-03-23T07:04:20.000Z
|
2022-03-30T02:44:42.000Z
|
reef-env/rocclr/platform/kernel.hpp
|
SJTU-IPADS/reef-artifacts
|
8750974f2d6655525a2cc317bf2471914fe68dab
|
[
"Apache-2.0"
] | null | null | null |
reef-env/rocclr/platform/kernel.hpp
|
SJTU-IPADS/reef-artifacts
|
8750974f2d6655525a2cc317bf2471914fe68dab
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright (c) 2008-present Advanced Micro Devices, Inc.
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. */
#ifndef KERNEL_HPP_
#define KERNEL_HPP_
#include "top.hpp"
#include "platform/object.hpp"
#include "amdocl/cl_kernel.h"
#include <vector>
#include <cstdlib> // for malloc
#include <string>
#include "device/device.hpp"
enum FGSStatus {
FGS_DEFAULT, //!< The default kernel fine-grained system pointer support
FGS_NO, //!< no support of kernel fine-grained system pointer
FGS_YES //!< have support of kernel fine-grained system pointer
};
namespace amd {
class Symbol;
class Program;
/*! \addtogroup Runtime
* @{
*
* \addtogroup Program Programs and Kernel functions
* @{
*/
class KernelSignature : public HeapObject {
private:
std::vector<KernelParameterDescriptor> params_;
std::string attributes_; //!< The kernel attributes
uint32_t numParameters_; //!< Number of OCL arguments in the kernel
uint32_t paramsSize_; //!< The size of all arguments
uint32_t numMemories_; //!< The number of memory objects used in the kernel
uint32_t numSamplers_; //!< The number of sampler objects used in the kernel
uint32_t numQueues_; //!< The number of queue objects used in the kernel
uint32_t version_; //!< The ABI version
public:
enum {
ABIVersion_0 = 0, //! ABI constructed based on the OCL semantics
ABIVersion_1 = 1, //! ABI constructed based on the HW ABI returned from HSAIL
ABIVersion_2 = 2 //! ABI constructed based on the HW ABI returned from LC
};
//! Default constructor
KernelSignature():
numParameters_(0), paramsSize_(0), numMemories_(0), numSamplers_(0),
numQueues_(0), version_(ABIVersion_0) {}
//! Construct a new signature.
KernelSignature(const std::vector<KernelParameterDescriptor>& params,
const std::string& attrib,
uint32_t numParameters,
uint32_t version);
//! Return the number of parameters
uint32_t numParameters() const { return numParameters_; }
//! Return the total number of parameters, including hidden
uint32_t numParametersAll() const { return params_.size(); }
//! Return the parameter descriptor at the given index.
const KernelParameterDescriptor& at(size_t index) const {
assert(index < params_.size() && "index is out of bounds");
return params_[index];
}
std::vector<KernelParameterDescriptor>& params() { return params_; }
//! Return the size in bytes required for the arguments on the stack.
uint32_t paramsSize() const { return paramsSize_; }
//! Returns the number of memory objects.
uint32_t numMemories() const { return numMemories_; }
//! Returns the number of sampler objects.
uint32_t numSamplers() const { return numSamplers_; }
//! Returns the number of queue objects.
uint32_t numQueues() const { return numQueues_; }
//! Returns the signature version
uint32_t version() const { return version_; }
//! Return the kernel attributes
const std::string& attributes() const { return attributes_; }
const std::vector<KernelParameterDescriptor>& parameters() const
{ return params_; }
};
// @todo: look into a copy-on-write model instead of copy-on-read.
//
class KernelParameters : protected HeapObject {
private:
//! The signature describing these parameters.
KernelSignature& signature_;
address values_; //!< pointer to the base of the values stack.
uint32_t execInfoOffset_; //!< The offset of execInfo
std::vector<void*> execSvmPtr_; //!< The non argument svm pointers for kernel
FGSStatus svmSystemPointersSupport_; //!< The flag for the status of the kernel
// support of fine-grain system sharing.
uint32_t memoryObjOffset_; //!< The number of memory objects
uint32_t samplerObjOffset_; //!< The number of sampler objects
uint32_t queueObjOffset_; //!< The number of queue objects
amd::Memory** memoryObjects_; //!< Memory objects, associated with the kernel
amd::Sampler** samplerObjects_; //!< Sampler objects, associated with the kernel
amd::DeviceQueue** queueObjects_; //!< Queue objects, associated with the kernel
uint32_t totalSize_; //!< The total size of all captured parameters
struct {
uint32_t validated_ : 1; //!< True if all parameters are defined.
uint32_t execNewVcop_ : 1; //!< special new VCOP for kernel execution
uint32_t execPfpaVcop_ : 1; //!< special PFPA VCOP for kernel execution
uint32_t unused : 29; //!< unused
};
public:
//! Construct a new instance of parameters for the given signature.
KernelParameters(KernelSignature& signature)
: signature_(signature),
execInfoOffset_(0),
svmSystemPointersSupport_(FGS_DEFAULT),
memoryObjects_(nullptr),
samplerObjects_(nullptr),
queueObjects_(nullptr),
validated_(0),
execNewVcop_(0),
execPfpaVcop_(0) {
totalSize_ = signature.paramsSize() + (signature.numMemories() +
signature.numSamplers() + signature.numQueues()) * sizeof(void*);
values_ = reinterpret_cast<address>(this) + alignUp(sizeof(KernelParameters), 16);
memoryObjOffset_ = signature_.paramsSize();
memoryObjects_ = reinterpret_cast<amd::Memory**>(values_ + memoryObjOffset_);
samplerObjOffset_ = memoryObjOffset_ + signature_.numMemories() * sizeof(amd::Memory*);
samplerObjects_ = reinterpret_cast<amd::Sampler**>(values_ + samplerObjOffset_);
queueObjOffset_ = samplerObjOffset_ + signature_.numSamplers() * sizeof(amd::Sampler*);
queueObjects_ = reinterpret_cast<amd::DeviceQueue**>(values_ + queueObjOffset_);
address limit = reinterpret_cast<address>(&queueObjects_[signature_.numQueues()]);
::memset(values_, '\0', limit - values_);
}
explicit KernelParameters(const KernelParameters& rhs)
: signature_(rhs.signature_),
execInfoOffset_(rhs.execInfoOffset_),
execSvmPtr_(rhs.execSvmPtr_),
svmSystemPointersSupport_(rhs.svmSystemPointersSupport_),
memoryObjects_(nullptr),
samplerObjects_(nullptr),
queueObjects_(nullptr),
totalSize_(rhs.totalSize_),
validated_(rhs.validated_),
execNewVcop_(rhs.execNewVcop_),
execPfpaVcop_(rhs.execPfpaVcop_) {
values_ = reinterpret_cast<address>(this) + alignUp(sizeof(KernelParameters), 16);
memoryObjOffset_ = signature_.paramsSize();
memoryObjects_ = reinterpret_cast<amd::Memory**>(values_ + memoryObjOffset_);
samplerObjOffset_ = memoryObjOffset_ + signature_.numMemories() * sizeof(amd::Memory*);
samplerObjects_ = reinterpret_cast<amd::Sampler**>(values_ + samplerObjOffset_);
queueObjOffset_ = samplerObjOffset_ + signature_.numSamplers() * sizeof(amd::Sampler*);
queueObjects_ = reinterpret_cast<amd::DeviceQueue**>(values_ + queueObjOffset_);
address limit = reinterpret_cast<address>(&queueObjects_[signature_.numQueues()]);
::memcpy(values_, rhs.values_, limit - values_);
}
//! Reset the parameter at the given \a index (becomes undefined).
void reset(size_t index) {
signature_.params()[index].info_.defined_ = false;
validated_ = 0;
}
//! Set the parameter at the given \a index to the value pointed by \a value
// \a svmBound indicates that \a value is a SVM pointer.
void set(size_t index, size_t size, const void* value, bool svmBound = false);
//! Return true if the parameter at the given \a index is defined.
bool test(size_t index) const { return signature_.at(index).info_.defined_; }
//! Return true if all the parameters have been defined.
bool check();
//! The amount of memory required for local memory needed
size_t localMemSize(size_t minDataTypeAlignment) const;
//! Capture the state of the parameters and return the stack base pointer.
address capture(const Device& device, uint64_t lclMemSize, int32_t* error);
//! Release the captured state of the parameters.
void release(address parameters, const amd::Device& device) const;
//! Allocate memory for this instance as well as the required storage for
// the values_, defined_, and rawPointer_ arrays.
void* operator new(size_t size, const KernelSignature& signature) {
size_t requiredSize = alignUp(size, 16) + signature.paramsSize() +
(signature.numMemories() + signature.numSamplers() + signature.numQueues()) *
sizeof(void*);
return AlignedMemory::allocate(requiredSize, PARAMETERS_MIN_ALIGNMENT);
}
//! Deallocate the memory reserved for this instance.
void operator delete(void* ptr) { AlignedMemory::deallocate(ptr); }
//! Deallocate the memory reserved for this instance,
// matching overloaded operator new.
void operator delete(void* ptr, const KernelSignature& signature) {
AlignedMemory::deallocate(ptr);
}
//! Returns raw kernel parameters without capture
address values() const { return values_; }
//! Return true if the captured parameter at the given \a index is bound to
// SVM pointer.
bool boundToSvmPointer(const Device& device, const_address capturedAddress, size_t index) const;
//! add the svmPtr execInfo into container
void addSvmPtr(void* const* execInfoArray, size_t count) {
execSvmPtr_.clear();
for (size_t i = 0; i < count; i++) {
execSvmPtr_.push_back(execInfoArray[i]);
}
}
//! get the number of svmPtr in the execInfo container
size_t getNumberOfSvmPtr() const { return execSvmPtr_.size(); }
//! get the offset of svmPtr in the parameters
uint32_t getExecInfoOffset() const { return execInfoOffset_; }
//! get the offset of memory objects in the parameters
uint32_t memoryObjOffset() const { return memoryObjOffset_; }
//! get the offset of sampler objects in the parameters
uint32_t samplerObjOffset() const { return samplerObjOffset_; }
//! get the offset of memory objects in the parameters
uint32_t queueObjOffset() const { return queueObjOffset_; }
//! set the status of kernel support fine-grained SVM system pointer sharing
void setSvmSystemPointersSupport(FGSStatus svmSystemSupport) {
svmSystemPointersSupport_ = svmSystemSupport;
}
//! return the status of kernel support fine-grained SVM system pointer sharing
FGSStatus getSvmSystemPointersSupport() const { return svmSystemPointersSupport_; }
//! set the new VCOP in the execInfo container
void setExecNewVcop(const bool newVcop) { execNewVcop_ = (newVcop == true); }
//! set the PFPA VCOP in the execInfo container
void setExecPfpaVcop(const bool pfpaVcop) { execPfpaVcop_ = (pfpaVcop == true); }
//! get the new VCOP in the execInfo container
bool getExecNewVcop() const { return (execNewVcop_ == 1); }
//! get the PFPA VCOP in the execInfo container
bool getExecPfpaVcop() const { return (execPfpaVcop_ == 1); }
};
/*! \brief Encapsulates a __kernel function and the argument values
* to be used when invoking this function.
*/
class Kernel : public RuntimeObject {
private:
//! The program where this kernel is defined.
SharedReference<Program> program_;
const Symbol& symbol_; //!< The symbol for this kernel.
std::string name_; //!< The kernel's name.
KernelParameters* parameters_; //!< The parameters.
protected:
//! Destroy this kernel
~Kernel();
public:
/*! \brief Construct a kernel object from the __kernel function
* \a kernelName in the given \a program.
*/
Kernel(Program& program, const Symbol& symbol, const std::string& name);
//! Construct a new kernel object from an existing one. Used by CloneKernel.
explicit Kernel(const Kernel& rhs);
//! Return the program containing this kernel.
Program& program() const { return program_(); }
//! Return this kernel's signature.
const KernelSignature& signature() const;
//! Return the kernel entry point for the given device.
const device::Kernel* getDeviceKernel(const Device& device //!< Device object
) const;
//! Return the parameters.
KernelParameters& parameters() const { return *parameters_; }
//! Return the kernel's name.
const std::string& name() const { return name_; }
virtual ObjectType objectType() const { return ObjectTypeKernel; }
};
/*! @}
* @}
*/
} // namespace amd
#endif /*KERNEL_HPP_*/
| 39.931138
| 98
| 0.714179
|
zhaozhangjian
|
fdc78960e8089d424fdfc5f6e0281b122fb07e6e
| 3,396
|
cpp
|
C++
|
src/SolARDescriptorsExtractorSIFTOpencv.cpp
|
geekyfox90/SolARModuleNonFreeOpenCV
|
6b84f668b5c958f15ac66cce5821d268ea50e976
|
[
"Apache-2.0"
] | null | null | null |
src/SolARDescriptorsExtractorSIFTOpencv.cpp
|
geekyfox90/SolARModuleNonFreeOpenCV
|
6b84f668b5c958f15ac66cce5821d268ea50e976
|
[
"Apache-2.0"
] | null | null | null |
src/SolARDescriptorsExtractorSIFTOpencv.cpp
|
geekyfox90/SolARModuleNonFreeOpenCV
|
6b84f668b5c958f15ac66cce5821d268ea50e976
|
[
"Apache-2.0"
] | null | null | null |
/**
* @copyright Copyright (c) 2017 B-com http://www.b-com.com/
*
* 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 "SolARDescriptorsExtractorSIFTOpencv.h"
#include "SolARImageConvertorOpencv.h"
#include <iostream>
#include "SolAROpenCVHelper.h"
#include "core/Log.h"
#include <utility>
#include <core/Log.h>
#include <array>
//#include <boost/thread/thread.hpp>
XPCF_DEFINE_FACTORY_CREATE_INSTANCE(SolAR::MODULES::NONFREEOPENCV::SolARDescriptorsExtractorSIFTOpencv);
namespace xpcf = org::bcom::xpcf;
using namespace cv;
using namespace cv::xfeatures2d;
using namespace SolAR::MODULES::OPENCV;
namespace SolAR {
using namespace datastructure;
namespace MODULES {
namespace NONFREEOPENCV {
SolARDescriptorsExtractorSIFTOpencv::SolARDescriptorsExtractorSIFTOpencv():ComponentBase(xpcf::toUUID<SolARDescriptorsExtractorSIFTOpencv>())
{
addInterface<api::features::IDescriptorsExtractor>(this);
LOG_DEBUG(" SolARDescriptorsExtractorSIFTOpencv constructor");
// m_extractor must have a default implementation : initialize default extractor type
m_extractor=SIFT::create();
}
SolARDescriptorsExtractorSIFTOpencv::~SolARDescriptorsExtractorSIFTOpencv()
{
LOG_DEBUG(" SolARDescriptorsExtractorSIFTOpencv destructor");
}
void SolARDescriptorsExtractorSIFTOpencv::extract(const SRef<Image> image, const std::vector<SRef<Keypoint> > &keypoints, SRef<DescriptorBuffer>& descriptors){
//transform all SolAR data to openCv data
SRef<Image> convertedImage = image;
if (image->getImageLayout() != Image::ImageLayout::LAYOUT_GREY) {
// input Image not in grey levels : convert it !
SolARImageConvertorOpencv convertor;
convertedImage = xpcf::utils::make_shared<Image>(Image::ImageLayout::LAYOUT_GREY,Image::PixelOrder::INTERLEAVED,image->getDataType());
convertor.convert(image,convertedImage);
}
cv::Mat opencvImage;
SolAROpenCVHelper::mapToOpenCV(convertedImage,opencvImage);
cv::Mat out_mat_descps;
std::vector<cv::KeyPoint> transform_to_data;
for(unsigned int k =0; k < keypoints.size(); ++k)
{
transform_to_data.push_back(
//instantiate keypoint
cv::KeyPoint(keypoints[k]->getX(),
keypoints[k]->getY(),
keypoints[k]->getSize(),
keypoints[k]->getAngle(),
keypoints[k]->getResponse(),
keypoints[k]->getOctave(),
keypoints[k]->getClassId())
);
}
m_extractor->compute(opencvImage, transform_to_data, out_mat_descps);
descriptors.reset( new DescriptorBuffer(out_mat_descps.data,DescriptorBuffer::SIFT, DescriptorBuffer::TYPE_32F, 128, out_mat_descps.rows)) ;
}
}
}
} // end of namespace SolAR
| 34.30303
| 159
| 0.694052
|
geekyfox90
|
fdcf4655a2e24b845da4f02565b73193ddadc403
| 2,744
|
cpp
|
C++
|
aws-cpp-sdk-cloudformation/source/model/DescribePublisherResult.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-12T08:09:30.000Z
|
2022-02-12T08:09:30.000Z
|
aws-cpp-sdk-cloudformation/source/model/DescribePublisherResult.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2021-10-14T16:57:00.000Z
|
2021-10-18T10:47:24.000Z
|
aws-cpp-sdk-cloudformation/source/model/DescribePublisherResult.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-11-09T11:58:03.000Z
|
2021-11-09T11:58:03.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/cloudformation/model/DescribePublisherResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <utility>
using namespace Aws::CloudFormation::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;
DescribePublisherResult::DescribePublisherResult() :
m_publisherStatus(PublisherStatus::NOT_SET),
m_identityProvider(IdentityProvider::NOT_SET)
{
}
DescribePublisherResult::DescribePublisherResult(const Aws::AmazonWebServiceResult<XmlDocument>& result) :
m_publisherStatus(PublisherStatus::NOT_SET),
m_identityProvider(IdentityProvider::NOT_SET)
{
*this = result;
}
DescribePublisherResult& DescribePublisherResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode;
if (!rootNode.IsNull() && (rootNode.GetName() != "DescribePublisherResult"))
{
resultNode = rootNode.FirstChild("DescribePublisherResult");
}
if(!resultNode.IsNull())
{
XmlNode publisherIdNode = resultNode.FirstChild("PublisherId");
if(!publisherIdNode.IsNull())
{
m_publisherId = Aws::Utils::Xml::DecodeEscapedXmlText(publisherIdNode.GetText());
}
XmlNode publisherStatusNode = resultNode.FirstChild("PublisherStatus");
if(!publisherStatusNode.IsNull())
{
m_publisherStatus = PublisherStatusMapper::GetPublisherStatusForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(publisherStatusNode.GetText()).c_str()).c_str());
}
XmlNode identityProviderNode = resultNode.FirstChild("IdentityProvider");
if(!identityProviderNode.IsNull())
{
m_identityProvider = IdentityProviderMapper::GetIdentityProviderForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(identityProviderNode.GetText()).c_str()).c_str());
}
XmlNode publisherProfileNode = resultNode.FirstChild("PublisherProfile");
if(!publisherProfileNode.IsNull())
{
m_publisherProfile = Aws::Utils::Xml::DecodeEscapedXmlText(publisherProfileNode.GetText());
}
}
if (!rootNode.IsNull()) {
XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
m_responseMetadata = responseMetadataNode;
AWS_LOGSTREAM_DEBUG("Aws::CloudFormation::Model::DescribePublisherResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
}
return *this;
}
| 37.081081
| 184
| 0.755831
|
perfectrecall
|
fdcfd055eb1a2dfcae98d3ab7786164e8008e0bd
| 1,414
|
cpp
|
C++
|
src/falclib/msgsrc/weaponusagemsg.cpp
|
Terebinth/freefalcon-central
|
c28d807183ab447ef6a801068aa3769527d55deb
|
[
"BSD-2-Clause"
] | 117
|
2015-01-13T14:48:49.000Z
|
2022-03-16T01:38:19.000Z
|
src/falclib/msgsrc/weaponusagemsg.cpp
|
darongE/freefalcon-central
|
c28d807183ab447ef6a801068aa3769527d55deb
|
[
"BSD-2-Clause"
] | 4
|
2015-05-01T13:09:53.000Z
|
2017-07-22T09:11:06.000Z
|
src/falclib/msgsrc/weaponusagemsg.cpp
|
darongE/freefalcon-central
|
c28d807183ab447ef6a801068aa3769527d55deb
|
[
"BSD-2-Clause"
] | 78
|
2015-01-13T09:27:47.000Z
|
2022-03-18T14:39:09.000Z
|
#if 0
/*
* Machine Generated source file for message "Weapon Use Message".
* NOTE: The functions here must be completed by hand.
* Generated on 18-August-1997 at 15:21:10
* Generated from file EVENTS.XLS by MicroProse
*/
#include "MsgInc/WeaponUsageMsg.h"
#include "mesg.h"
#include "falclib.h"
#include "falcmesg.h"
#include "falcgame.h"
#include "falcsess.h"
#include "InvalidBufferException.h"
/* Unused... REMOVE
FalconWeaponUsageMessage::FalconWeaponUsageMessage(VU_ID entityId, VuTargetEntity *target, VU_BOOL loopback) : FalconEvent (WeaponUsageMsg, FalconEvent::CampaignThread, entityId, target, loopback)
{
// Your Code Goes Here
}
FalconWeaponUsageMessage::FalconWeaponUsageMessage(VU_MSG_TYPE type, VU_ID senderid, VU_ID target) : FalconEvent (WeaponUsageMsg, FalconEvent::CampaignThread, senderid, target)
{
// Your Code Goes Here
}
FalconWeaponUsageMessage::~FalconWeaponUsageMessage(void)
{
// Your Code Goes Here
}
int FalconWeaponUsageMessage::Process(uchar autodisp)
{
Squadron sq = (Squadron)FindUnit(EntityId());
int i,n;
long f;
if (autodisp or not sq)
return 0;
for (i=0; i<HARDPOINT_MAX; i++)
{
n = sq->GetStores(dataBlock.ids[i]) - dataBlock.num[i]*dataBlock.vehicles;
if (n < 0)
n = 0;
sq->SetStores(dataBlock.ids[i], n);
}
f = sq->GetFuel() - ((dataBlock.fuel * dataBlock.vehicles) / 100);
if (f < 0)
f = 0;
sq->SetFuel (f);
return 1;
}
*/
#endif
| 23.966102
| 196
| 0.722065
|
Terebinth
|
fdd4b852c109a8711c8121fe37eef2b07df1494e
| 14,332
|
cpp
|
C++
|
con512tpl/nv.cpp
|
seliv55/mito
|
5be5849cae120b2942b05c3c3a29c41358c5daea
|
[
"CECILL-B"
] | null | null | null |
con512tpl/nv.cpp
|
seliv55/mito
|
5be5849cae120b2942b05c3c3a29c41358c5daea
|
[
"CECILL-B"
] | null | null | null |
con512tpl/nv.cpp
|
seliv55/mito
|
5be5849cae120b2942b05c3c3a29c41358c5daea
|
[
"CECILL-B"
] | null | null | null |
#include <iostream>
#include "nr.h"
#include "nums.hh"
#include "tk.hh"
#include "nv.hh"
#include "modlab.h"
#include "solvers.h"
#include "analis.h"
using namespace std;
const int hk=0, pfk=hk+1, fbpase=pfk+1, t3pep=fbpase+1, pept3=t3pep+1, pk=pept3+1, pyrlac=pk+1, lacpyr=pyrlac+1, pyrdcm=lacpyr+1, pyrdmc=pyrdcm+1, pdh=pyrdmc+1, citakg=pdh+1, akgsuc=citakg+1, sucmal=akgsuc+1, maloa=sucmal+1, oamal=maloa+1, pc=oamal+1, malicm=pc+1, malicc=malicm+1, ppp=malicc+1, oacd=ppp+1, mald=oacd+1, citdmc=mald+1, citdcm=citdmc+1, akgdmc=citdcm+1, akgdcm=akgdmc+1, coaout=akgdcm+1, citakg1=coaout+1, akgcit1=citakg1+1, gln_in=akgcit1+1, gln_out=gln_in+1, gluin=gln_out+1, gluout=gluin+1, t3ser=gluout+1, serpyr=t3ser+1, asp_o=serpyr+1, asp_i=asp_o+1, ala_o=asp_i+1, ala_i=ala_o+1, r5_o=ala_i+1, r5_i=r5_o+1, glycogin=r5_i+1, glycogout=glycogin+1, cystin=glycogout+1, proin=cystin+1, proout=proin+1, kgin=proout+1, coain=kgin+1, gln_pr=coain+1, ser_pr=gln_pr+1, asp_pr=ser_pr+1, ala_pr=asp_pr+1, pro_pr=ala_pr+1, trpala=pro_pr+1, mthf=trpala+1, thf=mthf+1, sergly=thf+1, glyser=sergly+1, cs0=glyser+1, D=cs0+1, atpase=D+1, resp=atpase+1, rdt=resp+1, rald=rdt+1, rta=rald+1, rtk=rta+1, nrea=rtk+1;
const int aldfl=rald, aldrev=aldfl+1, aldfli=aldrev+1, aldi1=aldfli+1, tafl=aldi1+1, s7f6a=tafl+1, f6g3a=s7f6a+1, s7e4a=f6g3a+1, tkfl=s7e4a+1, s7p5=tkfl+1, f6p5=s7p5+1, p5f6=f6p5+1, f6s7=p5f6+1, s7f6=f6s7+1, p5g3i=s7f6+1, f6e4i=p5g3i+1, s7p5i=f6e4i+1, nflx=s7p5i+1;
const int nfbp=0, nt3=nfbp+1, npep=nt3+1, npyr=npep+1, npyrm=npyr+1, ncoa=npyrm+1, ncoac=ncoa+1, nagl=ncoac+1, noa=nagl+1, noac=noa+1, ncit=noac+1, ncitc=ncit+1, nakg=ncitc+1, nakgc=nakg+1, nsuc=nakgc+1, nmal=nsuc+1, ne4=nmal+1, ncthf=ne4+1, ngae=ncthf+1, ndhe=ngae+1, ns7=ndhe+1, nh6=ns7+1, np5=nh6+1, n_atp=np5+1, n_nad=n_atp+1, ngl=n_nad+1, nlac=ngl+1, nglu=nlac+1, ngln=nglu+1, nala=ngln+1, nasp=nala+1, nser=nasp+1, ngly=nser+1, npro=ngly+1, nrna=npro+1, nglycog=nrna+1, nmet=nglycog+1;
const int numx=ngl;
Metab Ldistr::fbp(6,"fbp"), Ldistr::t3(3,"t3"), Ldistr::pep(3,"pep"), Ldistr::pyr(3,"pyr"), Ldistr::pyrm(3,"Pyr"), Ldistr::coa(2,"CoA"), Ldistr::coac(2,"coac"), Ldistr::agl(3,"Glycerol"), Ldistr::oa(4,"Oaa"), Ldistr::oac(4,"oac"), Ldistr::cit(6,"Cit"), Ldistr::citc(6,"citc"), Ldistr::akg(5,"aKg"), Ldistr::akgc(5,"akgc"), Ldistr::suc(4,"Suc"), Ldistr::mal(4,"Mal"), Ldistr::e4(4,"ne4"), Ldistr::cthf(1,"cthf"), Ldistr::gae(2,"gae"), Ldistr::dhe(3,"dhe"), Ldistr::gl(6,"Gluc"), Ldistr::lac(3,"Lac"), Ldistr::glu(5,"Glutamate2-5"), Ldistr::gln(5,"Glutamin"), Ldistr::ala(3,"Ala"), Ldistr::asp(4,"Asp"), Ldistr::ser(3,"Ser"), Ldistr::gly(2,"Gly"), Ldistr::pro(5,"Pro"), Ldistr::rna(5,"Rib"), Ldistr::glycog(6,"Glycog");
ketose Ldistr::s7(7,"s7"), Ldistr::h6(6,"h6"), Ldistr::p5(5,"rib");
Fit Problem;
const double thft(1.);
double xx[nmet],flx[nflx],fluxes[nflx];
double xinit1[nmet],xinit2[nmet];
string Parray::fid[nflx],Parray::fname[nflx],Parray::fschem[nflx], Parray::namex[numx];
Reapar Parray::rea[nrea];
double Analis::nv1[nrea], Analis::nv2[nrea];
//Metab *Ldistr::met[31];
// ketose *Ldistr::metk[3];
void Ldistr::setmet(){met[0]=&fbp; met[1]=&t3; met[2]=&pep; met[3]=&pyr; met[4]=&pyrm; met[5]=&coa; met[6]=&coac; met[7]=&agl; met[8]=&oa; met[9]=&oac; met[10]=&cit; met[11]=&citc; met[12]=&akg; met[13]=&akgc; met[14]=&suc; met[15]=&mal; met[16]=&e4; met[17]=≷ met[18]=&lac; met[19]=&glu; met[20]=&gln; met[21]=&ala; met[22]=&asp; met[23]=&ser; met[24]=&gly; met[25]=&pro; met[26]=&rna; met[27]=&glycog; met[28]=&cthf; met[29]=&gae; met[30]=&dhe; metk[0]=&s7; metk[1]=&h6; metk[2]=&p5;
lmet=31; lmetk=3; }
void Ldistr::setcon(){fbp.setconc(xx[nfbp]); t3.setconc(xx[nt3]); pep.setconc(xx[npep]); pyr.setconc(xx[npyr]); pyrm.setconc(xx[npyrm]); coa.setconc(xx[ncoa]); coac.setconc(xx[ncoac]); agl.setconc(xx[nagl]); oa.setconc(xx[noa]); oac.setconc(xx[noac]); cit.setconc(xx[ncit]); citc.setconc(xx[ncitc]); akg.setconc(xx[nakg]); akgc.setconc(xx[nakgc]); suc.setconc(xx[nsuc]); mal.setconc(xx[nmal]); e4.setconc(xx[ne4]); cthf.setconc(xx[ncthf]); gae.setconc(xx[ngae]); dhe.setconc(xx[ndhe]); gl.setconc(xx[ngl]); lac.setconc(xx[nlac]); glu.setconc(xx[nglu]); gln.setconc(xx[ngln]); ala.setconc(xx[nala]); asp.setconc(xx[nasp]); ser.setconc(xx[nser]); gly.setconc(xx[ngly]); pro.setconc(xx[npro]); rna.setconc(xx[nrna]); glycog.setconc(xx[nglycog]); s7.setconc(xx[ns7]); h6.setconc(xx[nh6]); p5.setconc(xx[np5]); }
double Parray::sdh(double sss){return rea[D].v()*rea[sucmal].v(sss);}
void Fit::f(const double *y,double *dydx) {
for(int i=0;i<numx;i++) dydx[i]=0.;
for(int i=0;i<nflx;i++) flx[i]=0.;
double amp = -(sqrt(4.*xx[n_atp]*tan-3.*xx[n_atp]*xx[n_atp])-2.*tan+xx[n_atp])/2.;
double a_dp = (sqrt(xx[n_atp])*sqrt(4.*tan-3.*xx[n_atp])-xx[n_atp])/2.;
double h_nad = tnad-xx[n_nad];
xthf=thft-xx[ncthf];
flx[hk]= rea[hk].v( y[n_atp]); dydx[n_atp] -= flx[hk]; dydx[nh6] += flx[hk];
flx[pfk]= rea[pfk].v( y[nh6], y[n_atp]); dydx[nh6] -= flx[pfk]; dydx[n_atp] -= flx[pfk]; dydx[nfbp] += flx[pfk];
flx[fbpase]= rea[fbpase].v( y[nfbp]); dydx[nfbp] -= flx[fbpase]; dydx[nh6] += flx[fbpase];
flx[t3pep]= rea[t3pep].v( y[nt3], y[n_nad], a_dp); dydx[nt3] -= flx[t3pep]; dydx[n_nad] -= flx[t3pep]; dydx[n_atp] += flx[t3pep]; dydx[npep] += flx[t3pep];
flx[pept3]= rea[pept3].v( y[npep], y[n_atp], h_nad); dydx[npep] -= flx[pept3]; dydx[n_atp] -= flx[pept3]; dydx[n_nad] += flx[pept3]; dydx[nt3] += flx[pept3];
flx[pk]= rea[pk].v( y[npep], a_dp); dydx[npep] -= flx[pk]; dydx[n_atp] += flx[pk]; dydx[npyr] += flx[pk];
flx[pyrlac]= rea[pyrlac].v( y[npyr], h_nad); dydx[npyr] -= flx[pyrlac]; dydx[n_nad] += flx[pyrlac];
flx[lacpyr]= rea[lacpyr].v( y[n_nad], xx[nlac]); dydx[n_nad] -= flx[lacpyr]; dydx[npyr] += flx[lacpyr];
flx[pyrdcm]= rea[pyrdcm].v( y[npyr]); dydx[npyr] -= flx[pyrdcm]; dydx[npyrm] += flx[pyrdcm];
flx[pyrdmc]= rea[pyrdmc].v( y[npyrm]); dydx[npyrm] -= flx[pyrdmc]; dydx[npyr] += flx[pyrdmc];
flx[pdh]= rea[pdh].v( y[npyrm], y[n_nad]); dydx[npyrm] -= flx[pdh]; dydx[n_nad] -= flx[pdh]; dydx[ncoa] += flx[pdh];
flx[citakg]= rea[D].v()*rea[citakg].v( y[ncit], y[n_nad]); dydx[ncit] -= flx[citakg]; dydx[n_nad] -= flx[citakg]; dydx[nakg] += flx[citakg];
flx[akgsuc]= rea[D].v()*rea[akgsuc].v( y[nakg], y[n_nad], a_dp); dydx[nakg] -= flx[akgsuc]; dydx[n_nad] -= flx[akgsuc]; dydx[n_atp] += flx[akgsuc]; dydx[nsuc] += flx[akgsuc];
flx[sucmal]= sdh( y[nsuc]); dydx[nsuc] -= flx[sucmal]; dydx[nmal] += flx[sucmal];
flx[maloa]= rea[maloa].v( y[nmal], y[n_nad]); dydx[nmal] -= flx[maloa]; dydx[n_nad] -= flx[maloa]; dydx[noa] += flx[maloa];
flx[oamal]= rea[oamal].v( y[noa], h_nad); dydx[noa] -= flx[oamal]; dydx[n_nad] += flx[oamal]; dydx[nmal] += flx[oamal];
flx[pc]= rea[pc].v( y[npyrm], y[n_atp]); dydx[npyrm] -= flx[pc]; dydx[n_atp] -= flx[pc]; dydx[noa] += flx[pc];
flx[malicm]= rea[malicm].v( y[nmal], y[n_nad]); dydx[nmal] -= flx[malicm]; dydx[n_nad] -= flx[malicm]; dydx[npyrm] += flx[malicm];
flx[malicc]= rea[malicc].v( y[noac], y[n_nad]); dydx[noac] -= flx[malicc]; dydx[n_nad] -= flx[malicc]; dydx[npyr] += flx[malicc];
flx[ppp]= rea[ppp].v( y[nh6]); dydx[nh6] -= flx[ppp]; dydx[np5] += flx[ppp];
flx[oacd]= rea[oacd].v( y[noac]); dydx[noac] -= flx[oacd]; dydx[nmal] += flx[oacd];
flx[mald]= rea[mald].v( y[nmal]); dydx[nmal] -= flx[mald]; dydx[noac] += flx[mald];
flx[citdmc]= rea[citdmc].v( y[ncit]); dydx[ncit] -= flx[citdmc]; dydx[ncitc] += flx[citdmc];
flx[citdcm]= rea[citdcm].v( y[ncitc]); dydx[ncitc] -= flx[citdcm]; dydx[ncit] += flx[citdcm];
flx[akgdmc]= rea[akgdmc].v( y[nakg]); dydx[nakg] -= flx[akgdmc]; dydx[nakgc] += flx[akgdmc];
flx[akgdcm]= rea[akgdcm].v( y[nakgc]); dydx[nakgc] -= flx[akgdcm]; dydx[nakg] += flx[akgdcm];
flx[coaout]= rea[coaout].v( y[ncitc], y[n_atp]); dydx[ncitc] -= flx[coaout]; dydx[n_atp] -= flx[coaout]; dydx[noac] += flx[coaout];
flx[citakg1]= rea[citakg1].v( y[ncitc], y[n_nad]); dydx[ncitc] -= flx[citakg1]; dydx[n_nad] -= flx[citakg1]; dydx[nakgc] += flx[citakg1];
flx[akgcit1]= rea[akgcit1].v( y[nakgc], h_nad); dydx[nakgc] -= flx[akgcit1]; dydx[n_nad] += flx[akgcit1]; dydx[ncitc] += flx[akgcit1];
flx[gln_in]= rea[gln_in].v( xx[ngln]); dydx[nakgc] += flx[gln_in];
flx[gln_out]= rea[gln_out].v( y[nakgc]); dydx[nakgc] -= flx[gln_out];
flx[gluin]= rea[gluin].v( xx[nglu]); dydx[nakgc] += flx[gluin];
flx[gluout]= rea[gluout].v( y[nakgc]); dydx[nakgc] -= flx[gluout];
flx[t3ser]= rea[t3ser].v( y[nt3]); dydx[nt3] -= flx[t3ser];
flx[serpyr]= rea[serpyr].v( xx[nser]); dydx[npyrm] += flx[serpyr];
flx[asp_o]= rea[asp_o].v( y[noac]); dydx[noac] -= flx[asp_o];
flx[asp_i]= rea[asp_i].v(); dydx[noac] += flx[asp_i];
flx[ala_o]= rea[ala_o].v( y[npyr]); dydx[npyr] -= flx[ala_o];
flx[ala_i]= rea[ala_i].v(); dydx[npyr] += flx[ala_i];
flx[r5_o]= rea[r5_o].v( y[np5]); dydx[np5] -= flx[r5_o];
flx[r5_i]= rea[r5_i].v(); dydx[np5] += flx[r5_i];
flx[glycogin]= rea[glycogin].v( y[nh6]); dydx[nh6] -= flx[glycogin];
flx[glycogout]= rea[glycogout].v(); dydx[nh6] += flx[glycogout];
flx[cystin]= rea[cystin].v(); dydx[npyrm] += flx[cystin];
flx[proin]= rea[proin].v(); dydx[nakgc] += flx[proin];
flx[proout]= rea[proout].v( y[nakgc]); dydx[nakgc] -= flx[proout];
flx[kgin]= rea[kgin].v(); dydx[nakg] += flx[kgin];
flx[coain]= rea[coain].v(); dydx[ncoa] += flx[coain];
flx[gln_pr]= rea[gln_pr].v( xx[ngln]);
flx[ser_pr]= rea[ser_pr].v( xx[nser]);
flx[asp_pr]= rea[asp_pr].v( xx[nasp]);
flx[ala_pr]= rea[ala_pr].v( xx[nala]);
flx[pro_pr]= rea[pro_pr].v( xx[npro]);
flx[trpala]= rea[trpala].v();
flx[mthf]= rea[mthf].v( y[ncthf]); dydx[ncthf] -= flx[mthf];
flx[thf]= rea[thf].v( y[ncthf]); dydx[ncthf] -= flx[thf];
flx[sergly]= rea[sergly].v( xx[nser], xthf);
flx[glyser]= rea[glyser].v( xx[ngly], y[ncthf]); dydx[ncthf] -= flx[glyser];
flx[cs0]= rea[D].v()*rea[cs0].v( y[noa], y[ncoa]); dydx[noa] -= flx[cs0]; dydx[ncoa] -= flx[cs0]; dydx[ncit] += flx[cs0];
flx[D]= rea[D].v();
flx[atpase]= rea[atpase].v( y[n_atp]); dydx[n_atp] -= flx[atpase];
flx[resp]= rea[resp].v( h_nad, a_dp); dydx[n_nad] += flx[resp]; dydx[n_atp] += flx[resp]; dydx[n_atp] += flx[resp]; dydx[n_atp] += flx[resp];
flx[rdt]= rea[rdt].v();
aldolase.st1fl(&flx[aldfl], y[nfbp], y[nt3]); dydx[nfbp] -= flx[aldfl]; dydx[nt3] += 2.*flx[aldfl];
ta.st1fl(&flx[tafl], y[nh6]/fh6, y[nt3]/ft3, y[ne4], y[ns7]);
dydx[nh6] -= flx[tafl]; dydx[nt3] += flx[tafl];
dydx[ne4] -= flx[tafl]; dydx[ns7] += flx[tafl];
tk.st1fl(&flx[tkfl], y[nt3]/ft3, y[np5], y[ne4], y[nh6]/fh6, y[np5], y[ns7]);
dydx[np5] -= flx[tkfl]; dydx[nt3] += flx[tkfl];
dydx[ns7] -= flx[tkfl+1]; dydx[np5] += flx[tkfl+1];
dydx[nh6] -= flx[tkfl+2]; dydx[ne4] += flx[tkfl+2];
for(int i=0;i<numx;i++) dydx[i]*=(flx[rdt]/Vi);
}
void Fit::ff(const double *y,double *dydx) {
dydx[ngl] = (- flx[hk])*flx[rdt];
dydx[nlac] = (+flx[pyrlac]- flx[lacpyr])*flx[rdt];
dydx[nglu] = (+flx[gluout]- flx[gluin])*flx[rdt];
dydx[ngln] = (+flx[gln_out]- flx[gln_in]- flx[gln_pr])*flx[rdt];
dydx[nala] = (+flx[ala_o]- flx[ala_i]+flx[trpala]- flx[ala_pr])*flx[rdt];
dydx[nasp] = (+flx[asp_o]- flx[asp_i]- flx[asp_pr])*flx[rdt];
dydx[nser] = (+flx[t3ser]- flx[serpyr]- flx[ser_pr]+flx[glyser]- flx[sergly])*flx[rdt];
dydx[ngly] = (+flx[sergly]- flx[glyser])*flx[rdt];
dydx[npro] = (+flx[proout]- flx[proin]- flx[pro_pr])*flx[rdt];
dydx[nrna] = (+flx[r5_o]- flx[r5_i])*flx[rdt];
dydx[nglycog] = (+flx[glycogin]- flx[glycogout])*flx[rdt];
}
void Parray::init(){ft3=10.; fh6=7.;
tk.setk(rea[rtk].getpar());
ta.setk(rea[rta].getpar());
aldolase.setk(rea[rald].getpar());}
void Parray::fin(double y[]){
aldolase.st1fl(&flx[aldfl], y[nfbp], y[nt3]);
tk.st1fl(&flx[tkfl], y[nt3]/ft3, y[np5], y[ne4], y[nh6]/fh6, y[np5], y[ns7]);
ta.st1fl(&flx[tafl], y[nh6]/fh6, y[nt3]/ft3, y[ne4], y[ns7]);
aldolase.st2fl(&flx[aldfl], y[nfbp], y[nt3]);
tk.st2fl(&flx[tkfl], y[nt3]/ft3, y[np5], y[ne4], y[nh6]/fh6, y[np5], y[ns7]);
ta.st2fl(&flx[tafl], y[nh6]/fh6, y[nt3]/ft3, y[ne4], y[ns7]);
flfor(y);
}
void Parray::flfor(double *y){
for(int i=0;i<nflx;i++) fluxes[i] = flx[i] * flx[rdt]/Vi;
fluxes[pfk] /= y[nh6];
fluxes[fbpase] /= y[nfbp];
fluxes[t3pep] /= y[nt3];
fluxes[pept3] /= y[npep];
fluxes[pk] /= y[npep];
fluxes[pyrlac] /= y[npyr];
fluxes[lacpyr] /= xx[nlac];
fluxes[pyrdcm] /= y[npyr];
fluxes[pyrdmc] /= y[npyrm];
fluxes[pdh] /= y[npyrm];
fluxes[citakg] /= y[ncit];
fluxes[akgsuc] /= y[nakg];
fluxes[sucmal] /= y[nsuc];
fluxes[maloa] /= y[nmal];
fluxes[oamal] /= y[noa];
fluxes[pc] /= y[npyrm];
fluxes[malicm] /= y[nmal];
fluxes[malicc] /= y[noac];
fluxes[ppp] /= y[nh6];
fluxes[oacd] /= y[noac];
fluxes[mald] /= y[nmal];
fluxes[citdmc] /= y[ncit];
fluxes[citdcm] /= y[ncitc];
fluxes[akgdmc] /= y[nakg];
fluxes[akgdcm] /= y[nakgc];
fluxes[coaout] /= y[ncitc];
fluxes[citakg1] /= y[ncitc];
fluxes[akgcit1] /= y[nakgc];
fluxes[gln_in] /= xx[ngln];
fluxes[gln_out] /= y[nakgc];
fluxes[gluin] /= xx[nglu];
fluxes[gluout] /= y[nakgc];
fluxes[t3ser] /= y[nt3];
fluxes[serpyr] /= xx[nser];
fluxes[asp_o] /= y[noac];
fluxes[ala_o] /= y[npyr];
fluxes[r5_o] /= y[np5];
fluxes[glycogin] /= y[nh6];
fluxes[proout] /= y[nakgc];
fluxes[gln_pr] /= xx[ngln];
fluxes[ser_pr] /= xx[nser];
fluxes[asp_pr] /= xx[nasp];
fluxes[ala_pr] /= xx[nala];
fluxes[pro_pr] /= xx[npro];
fluxes[mthf] /= y[ncthf];
fluxes[thf] /= y[ncthf];
fluxes[sergly] /= xx[nser]*xthf;
fluxes[glyser] /= xx[ngly]*y[ncthf];
fluxes[cs0] /= y[noa]*y[ncoa];
fluxes[rald] /= xx[nfbp];
fluxes[rald+1] /= (xx[nt3]*xx[nt3]);
fluxes[rald+2] /= xx[nfbp];
}
| 72.383838
| 1,017
| 0.59252
|
seliv55
|
fdd56d8951746cd949d5593c4c852ecfc2492fe0
| 1,727
|
cpp
|
C++
|
FirmwareSource/libraries/MF_Modules/MFEncoder.cpp
|
rofl-er/MobiFlight-Connector
|
1f0fd45fe1c29fe48a2cb60683d9446e1bc7dcc2
|
[
"Unlicense"
] | null | null | null |
FirmwareSource/libraries/MF_Modules/MFEncoder.cpp
|
rofl-er/MobiFlight-Connector
|
1f0fd45fe1c29fe48a2cb60683d9446e1bc7dcc2
|
[
"Unlicense"
] | null | null | null |
FirmwareSource/libraries/MF_Modules/MFEncoder.cpp
|
rofl-er/MobiFlight-Connector
|
1f0fd45fe1c29fe48a2cb60683d9446e1bc7dcc2
|
[
"Unlicense"
] | null | null | null |
// MFEncoder.cpp
//
// Copyright (C) 2013-2014
#include "MFEncoder.h"
MFEncoder::MFEncoder() : _encoder() {
_initialized = false;
}
void MFEncoder::attach(uint8_t pin1, uint8_t pin2, uint8_t encoderType, const char * name)
{
_pos = 0;
_name = name;
_pin1 = pin1;
_pin2 = pin2;
_encoderType = encoderType;
_encoder.initialize(_pin1, _pin2, _encoderType);
_encoder.setMinMax(-1000,1000);
_encoder.setPosition(_pos);
_initialized = true;
}
void MFEncoder::update()
{
if (!_initialized) return;
//_encoder.update();
_encoder.tick();
long pos = _encoder.getPosition();
if (pos == _pos) {
// nothing happened
return;
}
long delta = pos - _pos;
long dir = 1;
if (delta<0) dir = -1;
long absDelta = abs(delta);
if (absDelta < _fastLimit) {
// slow turn detected
if (dir==1 && _handlerList[encLeft]!= NULL) {
(*_handlerList[encLeft])(encLeft, _pin1, _name);
} else if(_handlerList[encRight]!= NULL) {
(*_handlerList[encRight])(encRight, _pin2, _name);
}
} else {
// fast turn detected
if (dir==1 && _handlerList[encLeftFast]!= NULL) {
(*_handlerList[encLeftFast])(encLeftFast, _pin1, _name);
} else if(_handlerList[encRightFast]!= NULL) {
(*_handlerList[encRightFast])(encRightFast, _pin2, _name);
}
}
// protect from overflow
if ( (dir > 0 && (pos + delta*2) > MF_ENC_MAX) || (dir < 0 && (pos - delta*2) < -MF_ENC_MAX))
{
_encoder.setPosition(0);
pos = 0;
}
_pos = pos;
}
void MFEncoder::attachHandler(uint8_t eventId, encoderEvent newHandler)
{
_handlerList[eventId] = newHandler;
}
| 23.657534
| 97
| 0.598147
|
rofl-er
|
fdd5d49389fac9849f3d12f1dbc7420e50cfe26d
| 1,390
|
hpp
|
C++
|
re_common.hpp
|
userpro/mini_regexp
|
c77ebb488357e2ddbb5496a948f7a2c8d0eca964
|
[
"MIT"
] | 1
|
2020-09-07T07:35:45.000Z
|
2020-09-07T07:35:45.000Z
|
re_common.hpp
|
userpro/mini_regexp
|
c77ebb488357e2ddbb5496a948f7a2c8d0eca964
|
[
"MIT"
] | null | null | null |
re_common.hpp
|
userpro/mini_regexp
|
c77ebb488357e2ddbb5496a948f7a2c8d0eca964
|
[
"MIT"
] | 1
|
2021-06-18T05:37:58.000Z
|
2021-06-18T05:37:58.000Z
|
#ifndef MINI_REGEXP_COMMON_H_
#define MINI_REGEXP_COMMON_H_
#include <string>
#include <algorithm>
namespace mini_regexp_common
{
inline int is_ANY(char c, bool dotall = false)
{
return dotall ? 1 : (c != '\n');
}
inline int is_range_in(char c, char start, char end)
{
return (c - start >= 0 && end - c >= 0);
}
inline std::ptrdiff_t str2int(std::string& s)
{
return std::stoll(s);
}
inline std::ptrdiff_t __str2hex(char c)
{
if (is_range_in(c, 'a', 'z'))
return c - 'a' + 10;
else
return c - '0';
}
inline std::ptrdiff_t str2hex(std::string& s)
{
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
std::ptrdiff_t num = 0;
for (int i = 0; i < s.length(); ++i)
num = num * 16 + __str2hex(s[i]);
return num;
}
inline std::ptrdiff_t str2oct(std::string& s)
{
std::ptrdiff_t num = 0;
for (int i = 0; i < s.length(); i++)
num = num * 8 + s[i] - '0';
return num;
}
inline std::ptrdiff_t str_get_digit(const std::string& s, std::ptrdiff_t _index, std::string& num)
{
auto _start = _index;
while (is_range_in(s[_index++], '0', '9'))
;
num = s.substr(_start, _index - _start);
return _index - _start;
}
}
#endif
| 23.559322
| 102
| 0.521583
|
userpro
|
fdd6c4c21ec41f39eaa107b0328cf150cd2a2a2d
| 4,956
|
cpp
|
C++
|
OrionUO/Party.cpp
|
BryanNoller/OrionUO
|
5985315969c5f3c7c7552392d9d40d4b24b718e2
|
[
"MIT"
] | 169
|
2016-09-16T22:24:34.000Z
|
2022-03-27T09:58:20.000Z
|
OrionUO/Party.cpp
|
BryanNoller/OrionUO
|
5985315969c5f3c7c7552392d9d40d4b24b718e2
|
[
"MIT"
] | 104
|
2016-10-26T23:02:52.000Z
|
2021-10-02T17:36:04.000Z
|
OrionUO/Party.cpp
|
BryanNoller/OrionUO
|
5985315969c5f3c7c7552392d9d40d4b24b718e2
|
[
"MIT"
] | 111
|
2016-09-16T22:25:30.000Z
|
2022-03-28T07:01:40.000Z
|
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/***********************************************************************************
**
** Party.cpp
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "stdafx.h"
//----------------------------------------------------------------------------------
CParty g_Party;
//----------------------------------------------------------------------------------
CParty::CParty()
{
}
//----------------------------------------------------------------------------------
CParty::~CParty()
{
}
//----------------------------------------------------------------------------------
bool CParty::Contains(int serial)
{
WISPFUN_DEBUG("c196_f1");
bool result = false;
if (Leader != 0)
{
IFOR (i, 0, 10)
{
if (Member[i].Serial == serial)
{
result = true;
break;
}
}
}
return result;
}
//----------------------------------------------------------------------------------
void CParty::Clear()
{
WISPFUN_DEBUG("c196_f2");
IFOR (i, 0, 10)
{
Member[i].Serial = 0;
Member[i].Character = NULL;
}
}
//----------------------------------------------------------------------------------
void CParty::ParsePacketData(WISP_DATASTREAM::CDataReader &reader)
{
WISPFUN_DEBUG("c196_f3");
uchar code = reader.ReadUInt8();
switch (code)
{
case 1: //Add member
{
}
case 2: //Remove member
{
uchar count = reader.ReadUInt8();
if (count <= 1)
{
Leader = 0;
Inviter = 0;
IFOR (i, 0, 10)
{
CPartyObject &member = Member[i];
if (member.Character == NULL)
break;
CGumpStatusbar *gump = (CGumpStatusbar *)g_GumpManager.UpdateContent(
member.Character->Serial, 0, GT_STATUSBAR);
if (gump != NULL)
gump->WantRedraw = true;
}
Clear();
g_GumpManager.UpdateContent(0, 0, GT_PARTY_MANIFEST);
break;
}
Clear();
WISP_GEOMETRY::CPoint2Di oldPos = g_MouseManager.Position;
WISP_GEOMETRY::CPoint2Di mousePos(76, 30);
g_MouseManager.Position = mousePos;
CGumpStatusbar *prevGump = NULL;
IFOR (i, 0, count)
{
uint serial = reader.ReadUInt32BE();
Member[i].Serial = serial;
Member[i].Character = g_World->FindWorldCharacter(serial);
if (i == 0)
g_Party.Leader = serial;
CGumpStatusbar *gump =
(CGumpStatusbar *)g_GumpManager.UpdateContent(serial, 0, GT_STATUSBAR);
if (gump == NULL)
{
g_Orion.OpenStatus(serial);
gump = (CGumpStatusbar *)g_GumpManager.UpdateContent(serial, 0, GT_STATUSBAR);
if (serial == g_PlayerSerial)
{
gump->Minimized = false;
}
if (prevGump != NULL)
prevGump->AddStatusbar(gump);
prevGump = gump;
mousePos.Y += 59;
g_MouseManager.Position = mousePos;
}
else
{
CPacketStatusRequest(serial).Send();
gump->WantRedraw = true;
}
}
g_MouseManager.Position = oldPos;
g_GumpManager.UpdateContent(0, 0, GT_PARTY_MANIFEST);
break;
}
case 3: //Private party message
case 4: //Party message
{
uint serial = reader.ReadUInt32BE();
wstring name = reader.ReadWString(0, true);
IFOR (i, 0, 10)
{
if (Member[i].Serial == serial)
{
string str = "[" + Member[i].GetName((int)i) + "]: " + ToString(name);
g_Orion.CreateTextMessage(
TT_SYSTEM, serial, 3, g_ConfigManager.PartyMessageColor, str);
break;
}
}
break;
}
case 7: //Party invition
{
g_Party.Inviter = reader.ReadUInt32BE();
break;
}
default:
break;
}
}
//----------------------------------------------------------------------------------
| 29.325444
| 98
| 0.375101
|
BryanNoller
|
fdd7f3abe3ec2632ba1366b6a831520068eae9ec
| 3,467
|
cpp
|
C++
|
Sunny-Core/01_FRAMEWORK/graphics/cameras/FPSCamera.cpp
|
adunStudio/Sunny
|
9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7
|
[
"Apache-2.0"
] | 20
|
2018-01-19T06:28:36.000Z
|
2021-08-06T14:06:13.000Z
|
Sunny-Core/01_FRAMEWORK/graphics/cameras/FPSCamera.cpp
|
adunStudio/Sunny
|
9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7
|
[
"Apache-2.0"
] | null | null | null |
Sunny-Core/01_FRAMEWORK/graphics/cameras/FPSCamera.cpp
|
adunStudio/Sunny
|
9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7
|
[
"Apache-2.0"
] | 3
|
2019-01-29T08:58:04.000Z
|
2021-01-02T06:33:20.000Z
|
#include "FPSCamera.h"
#include "../../app/Input.h"
#include "../../app/Application.h"
namespace sunny
{
namespace graphics
{
FPSCamera::FPSCamera(const maths::mat4& projectionMatrix)
: Camera(projectionMatrix), m_mouseSensitivity(0.002f), m_speed(0.4f), m_sprintSpeed(m_speed * 4.0f), m_mouseWasGrabbed(false)
{
// http://www.teamliquid.net/forum/sc2-maps/513741-create-your-own-camera-map
m_position = maths::vec3(0.0f, 25.0f, 65.0f);
m_rotation = maths::vec3(0.0f, 0.0f, 0.0f);
m_yaw = 0.0f;
m_pitch = 0.3f;
}
FPSCamera::~FPSCamera()
{
}
void FPSCamera::Focus()
{
Input::GetInputManager()->SetMouseCursor(SUNNY_NO_CURSOR);
}
void FPSCamera::Update()
{
maths::vec2 windowSize = Application::GetApplication().GetWindowSize();
maths::vec2 windowCenter = maths::vec2((float)(int)(windowSize.x / 2.0f), (float)(int)(windowSize.y / 2.0f));
if (Input::IsMouseButtonPressed(SUNNY_MOUSE_RIGHT))
{
if (!Input::GetInputManager()->IsMouseGrabbed())
{
Input::GetInputManager()->SetMouseGrabbed(true);
Input::GetInputManager()->SetMouseCursor(SUNNY_NO_CURSOR);
}
}
if (Input::GetInputManager()->IsMouseGrabbed())
{
maths::vec2 mouse = Input::GetInputManager()->GetMousePosition();
mouse.x -= windowCenter.x;
mouse.y -= windowCenter.y;
if (m_mouseWasGrabbed)
{
m_yaw += mouse.x * m_mouseSensitivity;
m_pitch += mouse.y * m_mouseSensitivity;
}
m_mouseWasGrabbed = true;
Input::GetInputManager()->SetMousePosition(windowCenter);
maths::Quaternion orientation = GetOrientation();
m_rotation = orientation.ToEulerAngles() * (180.0f / maths::SUNNY_PI);
maths::vec3 forward = GetForwardDirection(orientation);
maths::vec3 right = GetRightDirection(orientation);
maths::vec3 up = maths::vec3::YAxis();
float speed = Input::IsKeyPressed(SUNNY_KEY_SHIFT) ? m_sprintSpeed : m_speed;
if (Input::IsKeyPressed(SUNNY_KEY_W))
m_position += forward * speed;
else if (Input::IsKeyPressed(SUNNY_KEY_S))
m_position -= forward * speed;
if (Input::IsKeyPressed(SUNNY_KEY_A))
m_position -= right * speed;
else if (Input::IsKeyPressed(SUNNY_KEY_D))
m_position += right * speed;
if (Input::IsKeyPressed(SUNNY_KEY_SPACE))
m_position += up * speed;
else if (Input::IsKeyPressed(SUNNY_KEY_CONTROL))
m_position -= up * speed;
maths::mat4 rotation = maths::mat4::Rotate(orientation.Conjugate());
maths::mat4 translation = maths::mat4::Translate(-m_position);
m_viewMatrix = rotation * translation;
}
if (Input::IsKeyPressed(SUNNY_KEY_ESCAPE))
{
Input::GetInputManager()->SetMouseGrabbed(false);
Input::GetInputManager()->SetMouseCursor(1);
m_mouseWasGrabbed = false;
}
}
maths::Quaternion FPSCamera::GetOrientation() const
{
return maths::Quaternion::RotationY(-m_yaw) * maths::Quaternion::RotationX(-m_pitch);
}
maths::vec3 FPSCamera::GetForwardDirection(const maths::Quaternion& orientation) const
{
return maths::Quaternion::Rotate(orientation, -maths::vec3::ZAxis());
}
maths::vec3 FPSCamera::GetUpDirection(const maths::Quaternion& orientation) const
{
return maths::Quaternion::Rotate(orientation, maths::vec3::YAxis());
}
maths::vec3 FPSCamera::GetRightDirection(const maths::Quaternion& orientation) const
{
return maths::Quaternion::Rotate(orientation, maths::vec3::XAxis());
}
}
}
| 29.134454
| 128
| 0.684165
|
adunStudio
|
fddccfe11f21f0c7f69c2db9256da375102d9c79
| 726
|
cpp
|
C++
|
interface/source/texturemanager_bind.cpp
|
fire-archive/llcoi
|
e0d2c30ba231e62e98b1322f1a1b01a89b9abb00
|
[
"MIT"
] | null | null | null |
interface/source/texturemanager_bind.cpp
|
fire-archive/llcoi
|
e0d2c30ba231e62e98b1322f1a1b01a89b9abb00
|
[
"MIT"
] | null | null | null |
interface/source/texturemanager_bind.cpp
|
fire-archive/llcoi
|
e0d2c30ba231e62e98b1322f1a1b01a89b9abb00
|
[
"MIT"
] | 1
|
2021-11-30T23:13:38.000Z
|
2021-11-30T23:13:38.000Z
|
/* __ __ _
* / // /_____ ____ (_)
* / // // ___// __ \ / /
* / // // /__ / /_/ // /
* /_//_/ \___/ \____//_/
* https://bitbucket.org/galaktor/llcoi
* copyright (c) 2011, llcoi Team
* MIT license applies - see file "LICENSE" for details.
*/
#include "texturemanager_bind.h"
#include <OgreTextureManager.h>
DLL TextureManagerHandle texturemanager_singleton()
{
return reinterpret_cast<TextureManagerHandle>(Ogre::TextureManager::getSingletonPtr());
}
DLL void texturemanager_set_default_num_mipmaps(TextureManagerHandle tm_hande, int number)
{
Ogre::TextureManager* tm = reinterpret_cast<Ogre::TextureManager*>(tm_hande);
tm->setDefaultNumMipmaps(static_cast<size_t>(number));
}
| 30.25
| 90
| 0.676309
|
fire-archive
|
fddcd227235f35667907890d45e34d9265832380
| 634
|
cpp
|
C++
|
FDTD/PhysicalConstants.cpp
|
plisdku/trogdor6
|
d77eb137dd0c03635c0016801ada54117697e521
|
[
"MIT"
] | null | null | null |
FDTD/PhysicalConstants.cpp
|
plisdku/trogdor6
|
d77eb137dd0c03635c0016801ada54117697e521
|
[
"MIT"
] | null | null | null |
FDTD/PhysicalConstants.cpp
|
plisdku/trogdor6
|
d77eb137dd0c03635c0016801ada54117697e521
|
[
"MIT"
] | null | null | null |
/*
* PhysicalConstants.cpp
* TROGDOR
*
* Created by Paul Hansen on 7/14/06.
* Copyright 2007 Stanford University. All rights reserved.
*
* This file is covered by the MIT license. See LICENSE.txt.
*/
#include "PhysicalConstants.h"
#include <cmath>
//#define SI_UNITS
#ifdef SI_UNITS
const double Constants::c = 2.99792458e8;
const double Constants::eps0 = 8.854187817e-12;
const double Constants::mu0 = 4*M_PI*1e-7;
const double Constants::eta0 = 376.730313461;
#else
const double Constants::c = 1.0;
const double Constants::eps0 = 1.0;
const double Constants::mu0 = 1.0;
const double Constants::eta0 = 1.0;
#endif
| 21.862069
| 62
| 0.717666
|
plisdku
|
fde5a2ba311d2e2ac93981669ab5983850ec99ad
| 4,055
|
cpp
|
C++
|
hphp/runtime/ext/debugger/ext_debugger.cpp
|
kkopachev/hhvm
|
a9f242ec029c37b1e9d1715b13661e66293d87ab
|
[
"PHP-3.01",
"Zend-2.0"
] | 1
|
2021-06-19T23:31:58.000Z
|
2021-06-19T23:31:58.000Z
|
hphp/runtime/ext/debugger/ext_debugger.cpp
|
alisha/hhvm
|
523dc33b444bd5b59695eff2b64056629b0ed523
|
[
"PHP-3.01",
"Zend-2.0"
] | null | null | null |
hphp/runtime/ext/debugger/ext_debugger.cpp
|
alisha/hhvm
|
523dc33b444bd5b59695eff2b64056629b0ed523
|
[
"PHP-3.01",
"Zend-2.0"
] | null | null | null |
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/debugger/ext_debugger.h"
#include "hphp/runtime/ext/sockets/ext_sockets.h"
#include "hphp/runtime/ext/vsdebug/debugger.h"
#include "hphp/runtime/ext/vsdebug/ext_vsdebug.h"
#include "hphp/runtime/debugger/debugger.h"
#include "hphp/runtime/debugger/debugger_proxy.h"
#include "hphp/runtime/vm/jit/translator-inline.h"
#include "hphp/runtime/vm/unwind.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
TRACE_SET_MOD(debugger);
using namespace Eval;
struct DebuggerExtension final : Extension {
DebuggerExtension() : Extension("debugger", NO_EXTENSION_VERSION_YET) {}
void moduleInit() override {
HHVM_NAMED_FE(__SystemLib\\debugger_get_info, HHVM_FN(debugger_get_info));
HHVM_FE(hphpd_auth_token);
HHVM_FE(hphpd_break);
HHVM_FE(hphp_debugger_attached);
HHVM_FE(hphp_debug_break);
loadSystemlib();
}
} s_debugger_extension;
///////////////////////////////////////////////////////////////////////////////
String HHVM_FUNCTION(hphpd_auth_token) {
TRACE(5, "in f_hphpd_auth_token()\n");
if (auto proxy = Debugger::GetProxy()) {
return String(proxy->requestAuthToken());
}
return String();
}
void HHVM_FUNCTION(hphpd_break, bool condition /* = true */) {
TRACE(5, "in f_hphpd_break()\n");
if (!RuntimeOption::EnableHphpdDebugger || !condition ||
g_context->m_dbgNoBreak) {
TRACE(5, "bail !%d || !%d || %d\n", RuntimeOption::EnableHphpdDebugger,
condition, g_context->m_dbgNoBreak);
return;
}
VMRegAnchor _;
Debugger::InterruptVMHook(HardBreakPoint);
if (RuntimeOption::EvalJit && DEBUGGER_FORCE_INTR) {
TRACE(5, "switch mode\n");
throw VMSwitchModeBuiltin();
}
TRACE(5, "out f_hphpd_break()\n");
}
// Hard breakpoint for the VSDebug extension debugger.
bool HHVM_FUNCTION(hphp_debug_break, bool condition /* = true */) {
if (!condition) {
return false;
}
auto debugger = HPHP::VSDEBUG::VSDebugExtension::getDebugger();
if (debugger == nullptr) {
return false;
}
return debugger->onHardBreak();
}
// Quickly determine if a debugger is attached to the current thread.
bool HHVM_FUNCTION(hphp_debugger_attached) {
if (RuntimeOption::EnableHphpdDebugger && (Debugger::GetProxy() != nullptr)) {
return true;
}
auto debugger = HPHP::VSDEBUG::VSDebugExtension::getDebugger();
return (debugger != nullptr && debugger->clientConnected());
}
const StaticString
s_clientIP("clientIP"),
s_clientPort("clientPort");
Array HHVM_FUNCTION(debugger_get_info) {
Array ret(Array::Create());
if (!RuntimeOption::EnableHphpdDebugger) return ret;
DebuggerProxyPtr proxy = Debugger::GetProxy();
if (!proxy) return ret;
Variant address;
Variant port;
if (proxy->getClientConnectionInfo(ref(address), ref(port))) {
ret.set(s_clientIP, address);
ret.set(s_clientPort, port);
}
return ret;
}
///////////////////////////////////////////////////////////////////////////////
}
| 34.65812
| 80
| 0.58619
|
kkopachev
|
fdeac03952590b3318262e86d4a04b75ccb03f9c
| 2,511
|
hpp
|
C++
|
src/mlpack/methods/ann/layer/alpha_dropout_impl.hpp
|
abinezer/mlpack
|
8002e49150742acea4e76deef8161653b8350936
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1
|
2019-11-07T14:34:37.000Z
|
2019-11-07T14:34:37.000Z
|
src/mlpack/methods/ann/layer/alpha_dropout_impl.hpp
|
876arham/mlpack
|
1379831e578037c9d0ed3a1683ce76e3d1c8247e
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2
|
2020-04-10T17:39:50.000Z
|
2020-04-11T14:56:25.000Z
|
src/mlpack/methods/ann/layer/alpha_dropout_impl.hpp
|
876arham/mlpack
|
1379831e578037c9d0ed3a1683ce76e3d1c8247e
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
/**
* @file alpha_dropout_impl.hpp
* @author Dakshit Agrawal
*
* Definition of the Alpha-Dropout class, which implements a regularizer that
* randomly sets units to alpha-dash to prevent them from co-adapting and
* makes an affine transformation so as to keep the mean and variance of
* outputs at their original values.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_ANN_LAYER_ALPHA_DROPOUT_IMPL_HPP
#define MLPACK_METHODS_ANN_LAYER_ALPHA_DROPOUT_IMPL_HPP
// In case it hasn't yet been included.
#include "alpha_dropout.hpp"
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
template<typename InputDataType, typename OutputDataType>
AlphaDropout<InputDataType, OutputDataType>::AlphaDropout(
const double ratio,
const double alphaDash) :
ratio(ratio),
alphaDash(alphaDash),
deterministic(false)
{
Ratio(ratio);
}
template<typename InputDataType, typename OutputDataType>
template<typename eT>
void AlphaDropout<InputDataType, OutputDataType>::Forward(
const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
// The dropout mask will not be multiplied in the deterministic mode
// (during testing).
if (deterministic)
{
output = input;
}
else
{
// Set values to alphaDash with probability ratio. Then apply affine
// transformation so as to keep mean and variance of outputs to their
// original values.
mask = arma::randu< arma::Mat<eT> >(input.n_rows, input.n_cols);
mask.transform( [&](double val) { return (val > ratio); } );
output = (input % mask + alphaDash * (1 - mask)) * a + b;
}
}
template<typename InputDataType, typename OutputDataType>
template<typename eT>
void AlphaDropout<InputDataType, OutputDataType>::Backward(
const arma::Mat<eT>& /* input */, const arma::Mat<eT>& gy, arma::Mat<eT>& g)
{
g = gy % mask * a;
}
template<typename InputDataType, typename OutputDataType>
template<typename Archive>
void AlphaDropout<InputDataType, OutputDataType>::serialize(
Archive& ar, const unsigned int /* version */)
{
ar & BOOST_SERIALIZATION_NVP(ratio);
ar & BOOST_SERIALIZATION_NVP(alphaDash);
ar & BOOST_SERIALIZATION_NVP(a);
ar & BOOST_SERIALIZATION_NVP(b);
}
} // namespace ann
} // namespace mlpack
#endif
| 31
| 80
| 0.72959
|
abinezer
|
fdeb3e132f6d1dae77d257c7dfea29e1e2e37e64
| 1,622
|
cpp
|
C++
|
src/Detectors/FaceEmbedder.cpp
|
maciejjaskiewicz/FacelinkStudio
|
4bcb4ed06932546e58af4a01ee2b17e3dc45f366
|
[
"MIT"
] | 1
|
2020-08-11T02:40:32.000Z
|
2020-08-11T02:40:32.000Z
|
src/Detectors/FaceEmbedder.cpp
|
maciejjaskiewicz/FacelinkStudio
|
4bcb4ed06932546e58af4a01ee2b17e3dc45f366
|
[
"MIT"
] | null | null | null |
src/Detectors/FaceEmbedder.cpp
|
maciejjaskiewicz/FacelinkStudio
|
4bcb4ed06932546e58af4a01ee2b17e3dc45f366
|
[
"MIT"
] | null | null | null |
#include "FaceEmbedder.hpp"
#include "Utils/DataUtils.hpp"
#include <dlib/opencv/to_open_cv.h>
namespace Fls
{
void FaceEmbedder::init(const std::string& embedderPath)
{
mInitializedFuture = std::async(std::launch::async,
[this, embedderPath]()
{
mEmbeddingNetwork = cv::dnn::readNetFromTorch(embedderPath);
mInitialized.store(true);
});
}
std::vector<std::vector<float>> FaceEmbedder::embed(const UserResource* userResource,
const std::vector<std::shared_ptr<FaceAlignmentResult>>& faces)
{
std::vector<std::vector<float>> result;
if (!mInitialized.load() || !userResource || faces.empty())
return result;
if (mLastFrameId != userResource->id)
{
for(const auto& face : faces)
{
auto embeddings = embed(dlib::toMat(face->alignedFace));
result.emplace_back(embeddings);
}
mLastFrameId = userResource->id;
mLastFrameEmbeddingResult = result;
return result;
}
return mLastFrameEmbeddingResult;
}
std::vector<float> FaceEmbedder::embed(const cv::Mat& alignedFace)
{
const auto faceBlob = cv::dnn::blobFromImage(alignedFace, 1.0f / 255,
cv::Size(96, 96), cv::Scalar(), true, false);
mEmbeddingNetwork.setInput(faceBlob);
const auto embeddings = mEmbeddingNetwork.forward();
std::vector<float> embeddingsVec;
DataUtils::matToVector(embeddings, embeddingsVec);
return embeddingsVec;
}
}
| 27.491525
| 89
| 0.601726
|
maciejjaskiewicz
|
fdeca9d1ef907794fc1ece24e2940cf1f7fe0948
| 4,445
|
cpp
|
C++
|
Algorithms/sorting/priorityQueue/priorityQueue/priorityQueue/main.cpp
|
mingyuefly/geekTimeCode
|
d97c5f29a429ac9cc7289ac34e049ea43fa58822
|
[
"MIT"
] | 1
|
2019-05-01T04:51:14.000Z
|
2019-05-01T04:51:14.000Z
|
Algorithms/sorting/priorityQueue/priorityQueue/priorityQueue/main.cpp
|
mingyuefly/geekTimeCode
|
d97c5f29a429ac9cc7289ac34e049ea43fa58822
|
[
"MIT"
] | null | null | null |
Algorithms/sorting/priorityQueue/priorityQueue/priorityQueue/main.cpp
|
mingyuefly/geekTimeCode
|
d97c5f29a429ac9cc7289ac34e049ea43fa58822
|
[
"MIT"
] | null | null | null |
//
// main.cpp
// priorityQueue
//
// Created by mingyue on 2021/10/19.
// Copyright © 2021 Gmingyue. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
typedef struct Comparable {
public:
int value;
int compareTo(Comparable a) {
return value - a.value;
}
}Comparable;
class MaxPQ {
private:
vector<Comparable > *pq;
size_t N;
public:
MaxPQ(size_t maxN) {
pq = new vector<Comparable>(maxN + 1);
for (int i = 0; i < maxN + 1; i++) {
Comparable c;
c.value = 0;
pq->at(i) = c;
}
N = 0;
cout << "pq size = " << pq->size() << endl;
}
~MaxPQ() {
cout << "~MaxPQ()" << endl;
delete pq;
}
bool isEmpty() {
return N == 0;
}
size_t size() {
return N;
}
void insert(Comparable v) {
pq->at(++N) = v;
swim(N);
}
Comparable delMax() {
Comparable max = pq->at(1);
exch(1, N--);
Comparable c;
c.value = 0;
pq->at(N + 1) = c;
sink(1);
return max;
}
void show() {
size_t count = pq->size();
for (int i = 1; i < count; i++) {
cout << pq->at(i).value << ' ';
}
cout << endl;
}
private:
bool less(size_t i, size_t j) {
return pq->at(i).compareTo(pq->at(j)) < 0;
}
void exch(size_t i, size_t j) {
Comparable tmp = pq->at(i);
pq->at(i) = pq->at(j);
pq->at(j) = tmp;
}
void swim(size_t k) {
while (k > 1 && less(k / 2, k)) {
exch(k / 2, k);
k = k / 2;
}
}
void sink(size_t k) {
while (2 * k <= N) {
size_t j = 2 * k;
if (j < N && less(j, j + 1)) {
j++;
}
if (!less(k, j)) {
break;
}
exch(k, j);
k = j;
}
}
};
class MinPQ {
private:
vector<Comparable > *pq;
size_t N;
public:
MinPQ(size_t maxN) {
pq = new vector<Comparable>(maxN + 1);
for (int i = 0; i < maxN + 1; i++) {
Comparable c;
c.value = 0;
pq->at(i) = c;
}
N = 0;
cout << "pq size = " << pq->size() << endl;
}
~MinPQ() {
cout << "~MinPQ()" << endl;
delete pq;
}
bool isEmpty() {
return N == 0;
}
size_t size() {
return N;
}
void insert(Comparable v) {
pq->at(++N) = v;
swim(N);
}
Comparable delMin() {
Comparable min = pq->at(1);
exch(1, N--);
Comparable c;
c.value = 0;
pq->at(N + 1) = c;
sink(1);
return min;
}
void show() {
size_t count = pq->size();
for (int i = 1; i < count; i++) {
cout << pq->at(i).value << ' ';
}
cout << endl;
}
private:
bool more(size_t i, size_t j) {
return pq->at(i).compareTo(pq->at(j)) > 0;
}
void exch(size_t i, size_t j) {
Comparable tmp = pq->at(i);
pq->at(i) = pq->at(j);
pq->at(j) = tmp;
}
void swim(size_t k) {
while (k > 1 && more(k / 2, k)) {
exch(k / 2, k);
k = k / 2;
}
}
void sink(size_t k) {
while (2 * k <= N) {
size_t j = 2 * k;
if (j < N && more(j, j + 1)) {
j++;
}
if (!more(k, j)) {
break;
}
exch(k, j);
k = j;
}
}
};
int main(int argc, const char * argv[]) {
vector<int> a = {5, 3, 1, 10, 2, 18, 38, 17, 16, 25};
vector<Comparable> params;
for (int i = 0; i < a.size(); i++) {
Comparable c;
c.value = a[i];
params.push_back(c);
}
MaxPQ maxPQ = MaxPQ(a.size());
maxPQ.show();
for (int i = 0; i < a.size(); i++) {
maxPQ.insert(params[i]);
}
maxPQ.show();
maxPQ.delMax();
maxPQ.show();
maxPQ.delMax();
maxPQ.show();
cout << endl;
MinPQ minPQ = MinPQ(a.size());
minPQ.show();
for (int i = 0; i < a.size(); i++) {
minPQ.insert(params[i]);
}
minPQ.show();
minPQ.delMin();
minPQ.show();
minPQ.delMin();
minPQ.show();
Comparable c1;
c1.value = 1;
minPQ.insert(c1);
minPQ.show();
return 0;
}
| 21.066351
| 57
| 0.410349
|
mingyuefly
|
fdf55212c7afc380a953a21a61637e974b46e18e
| 8,320
|
cpp
|
C++
|
Source/Tools/ShaderConductorCmd.cpp
|
KawBuma/ShaderConductor
|
7577fedb39dcc6eb09d5883b23bd3ad922ba4897
|
[
"MIT"
] | 881
|
2019-05-07T13:46:16.000Z
|
2022-03-31T11:16:15.000Z
|
Source/Tools/ShaderConductorCmd.cpp
|
Jorgemagic/ShaderConductor
|
1b30a7f357d7f55963a142f6756849979727fd8f
|
[
"MIT"
] | 41
|
2018-11-09T05:08:02.000Z
|
2019-05-06T18:55:12.000Z
|
Source/Tools/ShaderConductorCmd.cpp
|
Jorgemagic/ShaderConductor
|
1b30a7f357d7f55963a142f6756849979727fd8f
|
[
"MIT"
] | 114
|
2019-05-24T11:50:58.000Z
|
2022-03-30T09:20:11.000Z
|
/*
* ShaderConductor
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*
* MIT License
*
* 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 <ShaderConductor/ShaderConductor.hpp>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4819)
#endif
#include <cxxopts.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
int main(int argc, char** argv)
{
cxxopts::Options options("ShaderConductorCmd", "A tool for compiling HLSL to many shader languages.");
// clang-format off
options.add_options()
("E,entry", "Entry point of the shader", cxxopts::value<std::string>()->default_value("main"))
("I,input", "Input file name", cxxopts::value<std::string>())("O,output", "Output file name", cxxopts::value<std::string>())
("S,stage", "Shader stage: vs, ps, gs, hs, ds, cs", cxxopts::value<std::string>())
("T,target", "Target shading language: dxil, spirv, hlsl, glsl, essl, msl_macos, msl_ios", cxxopts::value<std::string>()->default_value("dxil"))
("V,version", "The version of target shading language", cxxopts::value<std::string>()->default_value(""))
("D,define", "Macro define as name=value", cxxopts::value<std::vector<std::string>>());
// clang-format on
auto opts = options.parse(argc, argv);
if ((opts.count("input") == 0) || (opts.count("stage") == 0))
{
std::cerr << "COULDN'T find <input> or <stage> in command line parameters." << std::endl;
std::cerr << options.help() << std::endl;
return 1;
}
using namespace ShaderConductor;
Compiler::SourceDesc sourceDesc{};
Compiler::TargetDesc targetDesc{};
const auto fileName = opts["input"].as<std::string>();
const auto targetName = opts["target"].as<std::string>();
const auto targetVersion = opts["version"].as<std::string>();
sourceDesc.fileName = fileName.c_str();
targetDesc.version = targetVersion.empty() ? nullptr : targetVersion.c_str();
const auto stageName = opts["stage"].as<std::string>();
if (stageName == "vs")
{
sourceDesc.stage = ShaderStage::VertexShader;
}
else if (stageName == "ps")
{
sourceDesc.stage = ShaderStage::PixelShader;
}
else if (stageName == "gs")
{
sourceDesc.stage = ShaderStage::GeometryShader;
}
else if (stageName == "hs")
{
sourceDesc.stage = ShaderStage::HullShader;
}
else if (stageName == "ds")
{
sourceDesc.stage = ShaderStage::DomainShader;
}
else if (stageName == "cs")
{
sourceDesc.stage = ShaderStage::ComputeShader;
}
else
{
std::cerr << "Invalid shader stage: " << stageName << std::endl;
return 1;
}
const auto entryPoint = opts["entry"].as<std::string>();
sourceDesc.entryPoint = entryPoint.c_str();
if (targetName == "dxil")
{
targetDesc.language = ShadingLanguage::Dxil;
}
else if (targetName == "spirv")
{
targetDesc.language = ShadingLanguage::SpirV;
}
else if (targetName == "hlsl")
{
targetDesc.language = ShadingLanguage::Hlsl;
}
else if (targetName == "glsl")
{
targetDesc.language = ShadingLanguage::Glsl;
}
else if (targetName == "essl")
{
targetDesc.language = ShadingLanguage::Essl;
}
else if (targetName == "msl_macos")
{
targetDesc.language = ShadingLanguage::Msl_macOS;
}
else if (targetName == "msl_ios")
{
targetDesc.language = ShadingLanguage::Msl_iOS;
}
else
{
std::cerr << "Invalid target shading language: " << targetName << std::endl;
return 1;
}
std::string outputName;
if (opts.count("output") == 0)
{
static const std::string extMap[] = {"dxil", "spv", "hlsl", "glsl", "essl", "msl", "msl"};
static_assert(sizeof(extMap) / sizeof(extMap[0]) == static_cast<uint32_t>(ShadingLanguage::NumShadingLanguages),
"extMap doesn't match with the number of shading languages.");
outputName = fileName + "." + extMap[static_cast<uint32_t>(targetDesc.language)];
}
else
{
outputName = opts["output"].as<std::string>();
}
std::string source;
{
std::ifstream inputFile(sourceDesc.fileName, std::ios_base::binary);
if (!inputFile)
{
std::cerr << "COULDN'T load the input file: " << sourceDesc.fileName << std::endl;
return 1;
}
inputFile.seekg(0, std::ios::end);
source.resize(static_cast<size_t>(inputFile.tellg()));
inputFile.seekg(0, std::ios::beg);
inputFile.read(&source[0], source.size());
}
sourceDesc.source = source.c_str();
size_t numberOfDefines = opts.count("define");
std::vector<MacroDefine> macroDefines;
std::vector<std::string> macroStrings;
if (numberOfDefines > 0)
{
macroDefines.reserve(numberOfDefines);
macroStrings.reserve(numberOfDefines * 2);
auto& defines = opts["define"].as<std::vector<std::string>>();
for (const auto& define : defines)
{
MacroDefine macroDefine;
macroDefine.name = nullptr;
macroDefine.value = nullptr;
size_t splitPosition = define.find('=');
if (splitPosition != std::string::npos)
{
std::string macroName = define.substr(0, splitPosition);
std::string macroValue = define.substr(splitPosition + 1, define.size() - splitPosition - 1);
macroStrings.push_back(macroName);
macroDefine.name = macroStrings.back().c_str();
macroStrings.push_back(macroValue);
macroDefine.value = macroStrings.back().c_str();
}
else
{
macroStrings.push_back(define);
macroDefine.name = macroStrings.back().c_str();
}
macroDefines.push_back(macroDefine);
}
sourceDesc.defines = macroDefines.data();
sourceDesc.numDefines = static_cast<uint32_t>(macroDefines.size());
}
try
{
const auto result = Compiler::Compile(sourceDesc, {}, targetDesc);
if (result.errorWarningMsg.Size() > 0)
{
const char* msg = reinterpret_cast<const char*>(result.errorWarningMsg.Data());
std::cerr << "Error or warning from shader compiler: " << std::endl
<< std::string(msg, msg + result.errorWarningMsg.Size()) << std::endl;
}
if (result.target.Size() > 0)
{
std::ofstream outputFile(outputName, std::ios_base::binary);
if (!outputFile)
{
std::cerr << "COULDN'T open the output file: " << outputName << std::endl;
return 1;
}
outputFile.write(reinterpret_cast<const char*>(result.target.Data()), result.target.Size());
std::cout << "The compiled file is saved to " << outputName << std::endl;
}
}
catch (std::exception& ex)
{
std::cerr << ex.what() << std::endl;
}
return 0;
}
| 34.238683
| 152
| 0.611178
|
KawBuma
|
fdf559f14a2d365b04af4a2fdd067e215da004ce
| 1,962
|
cc
|
C++
|
CaloCluster/src/ClusterMoments.cc
|
bonventre/Offline
|
77db9d6368f27ab9401c690c2c2a4257ade6c231
|
[
"Apache-2.0"
] | 1
|
2021-06-25T00:00:12.000Z
|
2021-06-25T00:00:12.000Z
|
CaloCluster/src/ClusterMoments.cc
|
bonventre/Offline
|
77db9d6368f27ab9401c690c2c2a4257ade6c231
|
[
"Apache-2.0"
] | 1
|
2019-11-22T14:45:51.000Z
|
2019-11-22T14:50:03.000Z
|
CaloCluster/src/ClusterMoments.cc
|
bonventre/Offline
|
77db9d6368f27ab9401c690c2c2a4257ade6c231
|
[
"Apache-2.0"
] | 2
|
2019-10-14T17:46:58.000Z
|
2020-03-30T21:05:15.000Z
|
//
// Utility to compute the cluster moments
//
// Original author B. Echenard
//
// Mu2e includes
#include "CaloCluster/inc/ClusterMoments.hh"
#include "CalorimeterGeom/inc/Calorimeter.hh"
#include "RecoDataProducts/inc/CaloCrystalHitCollection.hh"
#include "RecoDataProducts/inc/CaloCluster.hh"
//#include "CLHEP/Units/SystemOfUnits.h"
#include <iostream>
#include <list>
namespace mu2e {
void ClusterMoments::calculate(cogtype mode)
{
auto const& main = caloCluster_.caloCrystalHitsPtrVector();
//calculate first and second moments in one pass
double sxi(0),sxi2(0),syi(0),syi2(0),sxyi(0),szi(0),szi2(0),swi(0);
for (auto it = main.begin(); it !=main.end(); ++it)
{
int crId((*it)->id());
double energy((*it)->energyDep());
if (cal_.crystal(crId).diskId() != iSection_) continue;
double xCrystal = cal_.crystal(crId).position().x();
double yCrystal = cal_.crystal(crId).position().y();
double zCrystal = cal_.crystal(crId).position().z();
double weight = energy;
if (mode == Logarithm) weight = log(energy);
sxi += xCrystal*weight;
sxi2 += xCrystal*xCrystal*weight;
syi += yCrystal*weight;
syi2 += yCrystal*yCrystal*weight;
sxyi += xCrystal*yCrystal*weight;
szi += zCrystal*weight;
szi2 += zCrystal*yCrystal*weight;
swi += weight;
}
CLHEP::Hep3Vector cogMu2eFrame(sxi/swi,syi/swi,szi/swi);
cog_ = cal_.geomUtil().mu2eToDiskFF(iSection_,cogMu2eFrame);
secondMoment_ = sxi2 -sxi*sxi/swi + syi2 -syi*syi/swi;
double beta = (sxyi - sxi*syi/swi)/(sxi2-sxi*sxi/swi);
angle_ = atan(beta);
if (angle_ < 0) angle_ += CLHEP::pi;
}
}
| 27.633803
| 78
| 0.56371
|
bonventre
|
fdf69bb525e25e5fccebd93c125b44d81602ea00
| 368
|
cpp
|
C++
|
classwork/05_assign/main.cpp
|
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-ArbazMalik1
|
c6a2e46fbf92ee8c4babaf1c455f4474ab158366
|
[
"MIT"
] | null | null | null |
classwork/05_assign/main.cpp
|
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-ArbazMalik1
|
c6a2e46fbf92ee8c4babaf1c455f4474ab158366
|
[
"MIT"
] | null | null | null |
classwork/05_assign/main.cpp
|
acc-cosc-1337-spring-2019/acc-cosc-1337-spring-2019-ArbazMalik1
|
c6a2e46fbf92ee8c4babaf1c455f4474ab158366
|
[
"MIT"
] | null | null | null |
#include "rectangle.h"
#include<iostream>
/*
Create a vector of rectangles
Add 3 Rectangle classes to the vector:
Width Height Area
4 5 20
10 10 100
100 10 1000
Iterate the vector and display the Area for each Rectangle on one line and the total area for the
3 rectangles.
*/
int main()
{
//std::cout << return_val();
return 0;
}
| 20.444444
| 99
| 0.663043
|
acc-cosc-1337-spring-2019
|
fdf6e5f4a5bf5a1b79d005857d0ae5e88d54ae23
| 983
|
hpp
|
C++
|
include/KernelsBandwidth.hpp
|
viroulep/replay_tool
|
6eeae5fee1dfc2fe1a96977aa16e06ecdf8fa2e1
|
[
"MIT"
] | null | null | null |
include/KernelsBandwidth.hpp
|
viroulep/replay_tool
|
6eeae5fee1dfc2fe1a96977aa16e06ecdf8fa2e1
|
[
"MIT"
] | null | null | null |
include/KernelsBandwidth.hpp
|
viroulep/replay_tool
|
6eeae5fee1dfc2fe1a96977aa16e06ecdf8fa2e1
|
[
"MIT"
] | null | null | null |
#ifndef KERNELSBANDWIDTH_H
#define KERNELSBANDWIDTH_H
#include <random>
#include <hwloc.h>
#include "kernel.hpp"
extern hwloc_topology_t topo;
template<typename T>
T *alloc_init_array(T *array, int n_elems, bool random)
{
hwloc_nodeset_t aff = hwloc_bitmap_alloc();
hwloc_bitmap_fill(aff);
if (array)
hwloc_free(topo, array, n_elems*sizeof(T));
array = (T*)hwloc_alloc_membind(topo, n_elems*sizeof(T), aff, HWLOC_MEMBIND_FIRSTTOUCH, 0);
hwloc_bitmap_free(aff);
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0, 1.0);
auto roll = std::bind(distribution, generator);
if (random) {
for (int i = 0; i < n_elems; i++)
array[i] = (T)roll();
} else {
for (int i = 0; i < n_elems; i++)
array[i] = i;
}
return array;
}
void init_array(const std::vector<Param *> *VP);
void copy_array(const std::vector<Param *> *VP);
void readidi(const std::vector<Param *> *VP);
void flush_cache();
#endif
| 23.404762
| 93
| 0.690743
|
viroulep
|
fdf9718d51fc0fd21f715575e30f6382cdf301aa
| 3,731
|
cc
|
C++
|
test/performance/symbol_names.cc
|
diegoferigo/ign-physics
|
8f0d8ce3229f53fbf4e05cb0273530169e6d9fef
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
test/performance/symbol_names.cc
|
diegoferigo/ign-physics
|
8f0d8ce3229f53fbf4e05cb0273530169e6d9fef
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
test/performance/symbol_names.cc
|
diegoferigo/ign-physics
|
8f0d8ce3229f53fbf4e05cb0273530169e6d9fef
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2019 Open Source Robotics Foundation
*
* 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 <gtest/gtest.h>
#include <ignition/physics/FeatureList.hh>
#include <ignition/physics/FeaturePolicy.hh>
#include <ignition/physics/BoxShape.hh>
#include <ignition/physics/CylinderShape.hh>
#include <ignition/physics/ForwardStep.hh>
#include <ignition/physics/FrameSemantics.hh>
#include <ignition/physics/Link.hh>
#include <ignition/physics/RevoluteJoint.hh>
/////////////////////////////////////////////////
struct CylinderFeaturesClass : ignition::physics::FeatureList<
ignition::physics::GetCylinderShapeProperties,
ignition::physics::SetCylinderShapeProperties,
ignition::physics::AttachCylinderShapeFeature
> { };
using CylinderFeaturesAlias = ignition::physics::FeatureList<
ignition::physics::GetCylinderShapeProperties,
ignition::physics::SetCylinderShapeProperties,
ignition::physics::AttachCylinderShapeFeature
>;
/////////////////////////////////////////////////
struct JointFeaturesClass : ignition::physics::FeatureList<
ignition::physics::GetRevoluteJointProperties,
ignition::physics::SetRevoluteJointProperties
> { };
using JointFeaturesAlias = ignition::physics::FeatureList<
ignition::physics::GetRevoluteJointProperties,
ignition::physics::SetRevoluteJointProperties
>;
/////////////////////////////////////////////////
struct BoxFeaturesClass : ignition::physics::FeatureList<
ignition::physics::GetBoxShapeProperties,
ignition::physics::SetBoxShapeProperties,
ignition::physics::AttachBoxShapeFeature
> { };
using BoxFeaturesAlias = ignition::physics::FeatureList<
ignition::physics::GetBoxShapeProperties,
ignition::physics::SetBoxShapeProperties,
ignition::physics::AttachBoxShapeFeature
>;
/////////////////////////////////////////////////
struct FeatureSetClass : ignition::physics::FeatureList<
CylinderFeaturesClass,
JointFeaturesClass,
BoxFeaturesClass
> { };
using FeatureSetAlias = ignition::physics::FeatureList<
CylinderFeaturesAlias,
JointFeaturesAlias,
BoxFeaturesAlias
>;
TEST(symbol_names, Length)
{
const std::string composite_featurelist_name =
typeid(ignition::physics::Link3dPtr<FeatureSetClass>).name();
const std::string aliased_featurelist_name =
typeid(ignition::physics::Link3dPtr<FeatureSetAlias>).name();
// The size of the feature list that uses inheritance composition should be
// less than a third of the size of the feature list that uses aliasing.
EXPECT_LT(composite_featurelist_name.size(),
aliased_featurelist_name.size()/3);
// We instantiate these so we can observe the kinds of symbols that get
// created when these classes are instantiated. This isn't tested explicitly,
// but the symbols can be seen by running
// $ nm PERFORMANCE_symbol_names
auto engineClass = ignition::physics::RequestEngine3d<FeatureSetClass>::From(
ignition::plugin::PluginPtr());
auto engineAlias = ignition::physics::RequestEngine3d<FeatureSetAlias>::From(
ignition::plugin::PluginPtr());
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 33.918182
| 79
| 0.719378
|
diegoferigo
|
fdfcf9767c118da648ea8f6c29d4c2f02eb2a95f
| 440
|
cpp
|
C++
|
stack_main.cpp
|
gtmills/algorithms
|
1fc8ec7e5772082e33cbba54538032253cfc56d8
|
[
"Apache-2.0"
] | null | null | null |
stack_main.cpp
|
gtmills/algorithms
|
1fc8ec7e5772082e33cbba54538032253cfc56d8
|
[
"Apache-2.0"
] | 1
|
2021-11-13T01:27:05.000Z
|
2021-11-13T01:27:05.000Z
|
stack_main.cpp
|
gtmills/algorithms
|
1fc8ec7e5772082e33cbba54538032253cfc56d8
|
[
"Apache-2.0"
] | null | null | null |
#include <assert.h>
#include "stack.hpp"
int main()
{
StackWithMax stack;
stack.push(1);
stack.push(2);
stack.push(3);
assert(stack.peak() == 3);
assert(stack.getMax() == 3);
assert(stack.pop() == 3);
assert(stack.getMax() == 2);
assert(stack.pop() == 2);
assert(stack.getMax() == 1);
assert(stack.pop() == 1);
assert(stack.pop() == -1);
assert(stack.getMax() == -1);
return 0;
}
| 18.333333
| 33
| 0.540909
|
gtmills
|
fdfd40b0dbe5ec02d9874c2c7b76156d8b3bd13b
| 31,091
|
cpp
|
C++
|
dwarf/SB/Game/zGrid.cpp
|
stravant/bfbbdecomp
|
2126be355a6bb8171b850f829c1f2731c8b5de08
|
[
"OLDAP-2.7"
] | 1
|
2021-01-05T11:28:55.000Z
|
2021-01-05T11:28:55.000Z
|
dwarf/SB/Game/zGrid.cpp
|
sonich2401/bfbbdecomp
|
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
|
[
"OLDAP-2.7"
] | null | null | null |
dwarf/SB/Game/zGrid.cpp
|
sonich2401/bfbbdecomp
|
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
|
[
"OLDAP-2.7"
] | 1
|
2022-03-30T15:15:08.000Z
|
2022-03-30T15:15:08.000Z
|
typedef struct xBaseAsset;
typedef struct RwObjectHasFrame;
typedef struct xModelPool;
typedef struct xScene;
typedef struct xAnimFile;
typedef struct xPortalAsset;
typedef struct RwResEntry;
typedef struct xShadowSimpleCache;
typedef struct RxPipelineNode;
typedef struct xAnimPlay;
typedef struct xEntCollis;
typedef struct rxHeapFreeBlock;
typedef struct RpGeometry;
typedef struct xAnimEffect;
typedef struct xEnt;
typedef struct RxPipelineNodeTopSortData;
typedef struct RpAtomic;
typedef struct iEnv;
typedef struct xAnimTransition;
typedef struct zScene;
typedef struct xAnimTransitionList;
typedef struct RxNodeDefinition;
typedef struct xAnimState;
typedef struct RpWorld;
typedef struct RpLight;
typedef struct RpClump;
typedef struct rxHeapSuperBlockDescriptor;
typedef struct xEntFrame;
typedef struct RxPipeline;
typedef struct RxPipelineCluster;
typedef struct RxPipelineNodeParam;
typedef struct xCollis;
typedef struct RxHeap;
typedef struct RwBBox;
typedef struct RwRGBA;
typedef struct xBase;
typedef struct xBound;
typedef struct xJSPHeader;
typedef struct xQuat;
typedef enum RpWorldRenderOrder;
typedef struct RwV3d;
typedef struct RwTexCoords;
typedef struct RpMaterial;
typedef struct rxHeapBlockHeader;
typedef struct RpTriangle;
typedef struct xFFX;
typedef struct RwFrame;
typedef struct xSurface;
typedef struct xAnimMultiFile;
typedef struct RwTexture;
typedef struct xLightKitLight;
typedef struct RxPipelineRequiresCluster;
typedef struct RpSector;
typedef struct xGrid;
typedef struct xModelBucket;
typedef struct xQCData;
typedef struct RpMeshHeader;
typedef struct xBBox;
typedef struct xEntShadow;
typedef struct RpWorldSector;
typedef struct RpMorphTarget;
typedef struct xModelInstance;
typedef struct xVec3;
typedef struct anim_coll_data;
typedef struct xLightKit;
typedef struct RwSurfaceProperties;
typedef struct RwMatrixTag;
typedef struct rxReq;
typedef struct xAnimTable;
typedef struct RwRaster;
typedef enum RxClusterValidityReq;
typedef struct xGridBound;
typedef struct xClumpCollBSPTree;
typedef struct zEnt;
typedef struct xMat4x3;
typedef struct xClumpCollBSPVertInfo;
typedef enum RxNodeDefEditable;
typedef struct xClumpCollBSPBranchNode;
typedef enum RxClusterValid;
typedef struct xRot;
typedef struct RwLLLink;
typedef struct xClumpCollBSPTriangle;
typedef struct xAnimMultiFileEntry;
typedef struct xAnimActiveEffect;
typedef enum rxEmbeddedPacketState;
typedef struct xSphere;
typedef struct xEnvAsset;
typedef struct _class_0;
typedef struct xBox;
typedef struct xAnimSingle;
typedef struct RpVertexNormal;
typedef struct tri_data;
typedef enum RxClusterForcePresent;
typedef struct xLinkAsset;
typedef struct xCylinder;
typedef struct _zPortal;
typedef struct RxClusterDefinition;
typedef struct RpInterpolator;
typedef struct xAnimMultiFileBase;
typedef struct _class_1;
typedef struct RwSphere;
typedef struct RpPolygon;
typedef struct RwTexDictionary;
typedef struct _class_2;
typedef struct RxOutputSpec;
typedef struct RpMaterialList;
typedef struct xMat3x3;
typedef struct RxClusterRef;
typedef struct xJSPNodeInfo;
typedef struct RwObject;
typedef struct xEntAsset;
typedef struct RxIoSpec;
typedef struct xMemPool;
typedef struct RxNodeMethods;
typedef struct RxCluster;
typedef struct xEnv;
typedef struct _zEnv;
typedef struct xShadowSimplePoly;
typedef struct RxPacket;
typedef struct RwRGBAReal;
typedef struct RwLinkList;
typedef void(*type_0)(xEnt*, xScene*, float32);
typedef RwObjectHasFrame*(*type_1)(RwObjectHasFrame*);
typedef void(*type_3)(RxPipelineNode*);
typedef void(*type_4)(xEnt*, xScene*, float32, xEntCollis*);
typedef void(*type_5)(xEnt*, xVec3*);
typedef void(*type_6)(xEnt*, xScene*, float32, xEntFrame*);
typedef void(*type_7)(xEnt*);
typedef uint32(*type_8)(xAnimTransition*, xAnimSingle*, void*);
typedef int32(*type_9)(RxPipelineNode*, RxPipeline*);
typedef RpAtomic*(*type_10)(RpAtomic*);
typedef uint32(*type_11)(xEnt*, xEnt*, xScene*, float32, xCollis*);
typedef void(*type_13)(xEnt*, xVec3*, xMat4x3*);
typedef uint32(*type_14)(RxPipelineNode*, uint32, uint32, void*);
typedef int32(*type_16)(RxPipelineNode*, RxPipelineNodeParam*);
typedef void(*type_19)(xAnimPlay*, xAnimState*);
typedef int32(*type_20)(RxNodeDefinition*);
typedef void(*type_21)(xAnimState*, xAnimSingle*, void*);
typedef void(*type_22)(RxNodeDefinition*);
typedef void(*type_23)(xAnimPlay*, xQuat*, xVec3*, int32);
typedef int32(*type_24)(RxPipelineNode*);
typedef RpWorldSector*(*type_25)(RpWorldSector*);
typedef xBase*(*type_28)(uint32);
typedef int8*(*type_30)(xBase*);
typedef int8*(*type_31)(uint32);
typedef uint32(*type_32)(uint32, xAnimActiveEffect*, xAnimSingle*, void*);
typedef RpClump*(*type_41)(RpClump*, void*);
typedef void(*type_42)(xMemPool*, void*);
typedef int32(*type_43)(xBase*, xBase*, uint32, float32*, xBase*);
typedef void(*type_50)(RwResEntry*);
typedef float32 type_2[16];
typedef RpLight* type_12[2];
typedef RwFrame* type_15[2];
typedef RwTexCoords* type_17[8];
typedef xVec3 type_18[4];
typedef uint8 type_26[3];
typedef xCollis type_27[18];
typedef uint32 type_29[25];
typedef float32 type_33[2];
typedef uint8 type_34[3];
typedef uint32 type_35[4];
typedef float32 type_36[4];
typedef float32 type_37[2];
typedef uint16 type_38[3];
typedef uint8 type_39[2];
typedef xAnimMultiFileEntry type_40[1];
typedef int8 type_44[32];
typedef uint32 type_45[72];
typedef RwTexCoords* type_46[8];
typedef int8 type_47[4];
typedef int8 type_48[32];
typedef xBase* type_49[72];
typedef xVec3 type_51[3];
typedef uint16 type_52[3];
typedef RxCluster type_53[1];
struct xBaseAsset
{
uint32 id;
uint8 baseType;
uint8 linkCount;
uint16 baseFlags;
};
struct RwObjectHasFrame
{
RwObject object;
RwLLLink lFrame;
RwObjectHasFrame*(*sync)(RwObjectHasFrame*);
};
struct xModelPool
{
xModelPool* Next;
uint32 NumMatrices;
xModelInstance* List;
};
struct xScene
{
uint32 sceneID;
uint16 flags;
uint16 num_ents;
uint16 num_trigs;
uint16 num_stats;
uint16 num_dyns;
uint16 num_npcs;
uint16 num_act_ents;
uint16 num_nact_ents;
float32 gravity;
float32 drag;
float32 friction;
uint16 num_ents_allocd;
uint16 num_trigs_allocd;
uint16 num_stats_allocd;
uint16 num_dyns_allocd;
uint16 num_npcs_allocd;
xEnt** trigs;
xEnt** stats;
xEnt** dyns;
xEnt** npcs;
xEnt** act_ents;
xEnt** nact_ents;
xEnv* env;
xMemPool mempool;
xBase*(*resolvID)(uint32);
int8*(*base2Name)(xBase*);
int8*(*id2Name)(uint32);
};
struct xAnimFile
{
xAnimFile* Next;
int8* Name;
uint32 ID;
uint32 FileFlags;
float32 Duration;
float32 TimeOffset;
uint16 BoneCount;
uint8 NumAnims[2];
void** RawData;
};
struct xPortalAsset : xBaseAsset
{
uint32 assetCameraID;
uint32 assetMarkerID;
float32 ang;
uint32 sceneID;
};
struct RwResEntry
{
RwLLLink link;
int32 size;
void* owner;
RwResEntry** ownerRef;
void(*destroyNotify)(RwResEntry*);
};
struct xShadowSimpleCache
{
uint16 flags;
uint8 alpha;
uint8 pad;
uint32 collPriority;
xVec3 pos;
xVec3 at;
xEnt* castOnEnt;
xShadowSimplePoly poly;
float32 envHeight;
float32 shadowHeight;
uint32 raster;
float32 dydx;
float32 dydz;
xVec3 corner[4];
};
struct RxPipelineNode
{
RxNodeDefinition* nodeDef;
uint32 numOutputs;
uint32* outputs;
RxPipelineCluster** slotClusterRefs;
uint32* slotsContinue;
void* privateData;
uint32* inputToClusterSlot;
RxPipelineNodeTopSortData* topSortData;
void* initializationData;
uint32 initializationDataSize;
};
struct xAnimPlay
{
xAnimPlay* Next;
uint16 NumSingle;
uint16 BoneCount;
xAnimSingle* Single;
void* Object;
xAnimTable* Table;
xMemPool* Pool;
xModelInstance* ModelInst;
void(*BeforeAnimMatrices)(xAnimPlay*, xQuat*, xVec3*, int32);
};
struct xEntCollis
{
uint8 chk;
uint8 pen;
uint8 env_sidx;
uint8 env_eidx;
uint8 npc_sidx;
uint8 npc_eidx;
uint8 dyn_sidx;
uint8 dyn_eidx;
uint8 stat_sidx;
uint8 stat_eidx;
uint8 idx;
xCollis colls[18];
void(*post)(xEnt*, xScene*, float32, xEntCollis*);
uint32(*depenq)(xEnt*, xEnt*, xScene*, float32, xCollis*);
};
struct rxHeapFreeBlock
{
uint32 size;
rxHeapBlockHeader* ptr;
};
struct RpGeometry
{
RwObject object;
uint32 flags;
uint16 lockedSinceLastInst;
int16 refCount;
int32 numTriangles;
int32 numVertices;
int32 numMorphTargets;
int32 numTexCoordSets;
RpMaterialList matList;
RpTriangle* triangles;
RwRGBA* preLitLum;
RwTexCoords* texCoords[8];
RpMeshHeader* mesh;
RwResEntry* repEntry;
RpMorphTarget* morphTarget;
};
struct xAnimEffect
{
xAnimEffect* Next;
uint32 Flags;
float32 StartTime;
float32 EndTime;
uint32(*Callback)(uint32, xAnimActiveEffect*, xAnimSingle*, void*);
};
struct xEnt : xBase
{
xEntAsset* asset;
uint16 idx;
uint16 num_updates;
uint8 flags;
uint8 miscflags;
uint8 subType;
uint8 pflags;
uint8 moreFlags;
uint8 isCulled;
uint8 driving_count;
uint8 num_ffx;
uint8 collType;
uint8 collLev;
uint8 chkby;
uint8 penby;
xModelInstance* model;
xModelInstance* collModel;
xModelInstance* camcollModel;
xLightKit* lightKit;
void(*update)(xEnt*, xScene*, float32);
void(*endUpdate)(xEnt*, xScene*, float32);
void(*bupdate)(xEnt*, xVec3*);
void(*move)(xEnt*, xScene*, float32, xEntFrame*);
void(*render)(xEnt*);
xEntFrame* frame;
xEntCollis* collis;
xGridBound gridb;
xBound bound;
void(*transl)(xEnt*, xVec3*, xMat4x3*);
xFFX* ffx;
xEnt* driver;
int32 driveMode;
xShadowSimpleCache* simpShadow;
xEntShadow* entShadow;
anim_coll_data* anim_coll;
void* user_data;
};
struct RxPipelineNodeTopSortData
{
uint32 numIns;
uint32 numInsVisited;
rxReq* req;
};
struct RpAtomic
{
RwObjectHasFrame object;
RwResEntry* repEntry;
RpGeometry* geometry;
RwSphere boundingSphere;
RwSphere worldBoundingSphere;
RpClump* clump;
RwLLLink inClumpLink;
RpAtomic*(*renderCallBack)(RpAtomic*);
RpInterpolator interpolator;
uint16 renderFrame;
uint16 pad;
RwLinkList llWorldSectorsInAtomic;
RxPipeline* pipeline;
};
struct iEnv
{
RpWorld* world;
RpWorld* collision;
RpWorld* fx;
RpWorld* camera;
xJSPHeader* jsp;
RpLight* light[2];
RwFrame* light_frame[2];
int32 memlvl;
};
struct xAnimTransition
{
xAnimTransition* Next;
xAnimState* Dest;
uint32(*Conditional)(xAnimTransition*, xAnimSingle*, void*);
uint32(*Callback)(xAnimTransition*, xAnimSingle*, void*);
uint32 Flags;
uint32 UserFlags;
float32 SrcTime;
float32 DestTime;
uint16 Priority;
uint16 QueuePriority;
float32 BlendRecip;
uint16* BlendOffset;
};
struct zScene : xScene
{
_zPortal* pendingPortal;
union
{
uint32 num_ents;
uint32 num_base;
};
union
{
xBase** base;
zEnt** ents;
};
uint32 num_update_base;
xBase** update_base;
uint32 baseCount[72];
xBase* baseList[72];
_zEnv* zen;
};
struct xAnimTransitionList
{
xAnimTransitionList* Next;
xAnimTransition* T;
};
struct RxNodeDefinition
{
int8* name;
RxNodeMethods nodeMethods;
RxIoSpec io;
uint32 pipelineNodePrivateDataSize;
RxNodeDefEditable editable;
int32 InputPipesCnt;
};
struct xAnimState
{
xAnimState* Next;
int8* Name;
uint32 ID;
uint32 Flags;
uint32 UserFlags;
float32 Speed;
xAnimFile* Data;
xAnimEffect* Effects;
xAnimTransitionList* Default;
xAnimTransitionList* List;
float32* BoneBlend;
float32* TimeSnap;
float32 FadeRecip;
uint16* FadeOffset;
void* CallbackData;
xAnimMultiFile* MultiFile;
void(*BeforeEnter)(xAnimPlay*, xAnimState*);
void(*StateCallback)(xAnimState*, xAnimSingle*, void*);
void(*BeforeAnimMatrices)(xAnimPlay*, xQuat*, xVec3*, int32);
};
struct RpWorld
{
RwObject object;
uint32 flags;
RpWorldRenderOrder renderOrder;
RpMaterialList matList;
RpSector* rootSector;
int32 numTexCoordSets;
int32 numClumpsInWorld;
RwLLLink* currentClumpLink;
RwLinkList clumpList;
RwLinkList lightList;
RwLinkList directionalLightList;
RwV3d worldOrigin;
RwBBox boundingBox;
RpWorldSector*(*renderCallBack)(RpWorldSector*);
RxPipeline* pipeline;
};
struct RpLight
{
RwObjectHasFrame object;
float32 radius;
RwRGBAReal color;
float32 minusCosAngle;
RwLinkList WorldSectorsInLight;
RwLLLink inWorld;
uint16 lightFrame;
uint16 pad;
};
struct RpClump
{
RwObject object;
RwLinkList atomicList;
RwLinkList lightList;
RwLinkList cameraList;
RwLLLink inWorldLink;
RpClump*(*callback)(RpClump*, void*);
};
struct rxHeapSuperBlockDescriptor
{
void* start;
uint32 size;
rxHeapSuperBlockDescriptor* next;
};
struct xEntFrame
{
xMat4x3 mat;
xMat4x3 oldmat;
xVec3 oldvel;
xRot oldrot;
xRot drot;
xRot rot;
xVec3 dpos;
xVec3 dvel;
xVec3 vel;
uint32 mode;
};
struct RxPipeline
{
int32 locked;
uint32 numNodes;
RxPipelineNode* nodes;
uint32 packetNumClusterSlots;
rxEmbeddedPacketState embeddedPacketState;
RxPacket* embeddedPacket;
uint32 numInputRequirements;
RxPipelineRequiresCluster* inputRequirements;
void* superBlock;
uint32 superBlockSize;
uint32 entryPoint;
uint32 pluginId;
uint32 pluginData;
};
struct RxPipelineCluster
{
RxClusterDefinition* clusterRef;
uint32 creationAttributes;
};
struct RxPipelineNodeParam
{
void* dataParam;
RxHeap* heap;
};
struct xCollis
{
uint32 flags;
uint32 oid;
void* optr;
xModelInstance* mptr;
float32 dist;
xVec3 norm;
xVec3 tohit;
xVec3 depen;
xVec3 hdng;
union
{
_class_2 tuv;
tri_data tri;
};
};
struct RxHeap
{
uint32 superBlockSize;
rxHeapSuperBlockDescriptor* head;
rxHeapBlockHeader* headBlock;
rxHeapFreeBlock* freeBlocks;
uint32 entriesAlloced;
uint32 entriesUsed;
int32 dirty;
};
struct RwBBox
{
RwV3d sup;
RwV3d inf;
};
struct RwRGBA
{
uint8 red;
uint8 green;
uint8 blue;
uint8 alpha;
};
struct xBase
{
uint32 id;
uint8 baseType;
uint8 linkCount;
uint16 baseFlags;
xLinkAsset* link;
int32(*eventFunc)(xBase*, xBase*, uint32, float32*, xBase*);
};
struct xBound
{
xQCData qcd;
uint8 type;
uint8 pad[3];
union
{
xSphere sph;
xBBox box;
xCylinder cyl;
};
xMat4x3* mat;
};
struct xJSPHeader
{
int8 idtag[4];
uint32 version;
uint32 jspNodeCount;
RpClump* clump;
xClumpCollBSPTree* colltree;
xJSPNodeInfo* jspNodeList;
};
struct xQuat
{
xVec3 v;
float32 s;
};
enum RpWorldRenderOrder
{
rpWORLDRENDERNARENDERORDER,
rpWORLDRENDERFRONT2BACK,
rpWORLDRENDERBACK2FRONT,
rpWORLDRENDERORDERFORCEENUMSIZEINT = 0x7fffffff
};
struct RwV3d
{
float32 x;
float32 y;
float32 z;
};
struct RwTexCoords
{
float32 u;
float32 v;
};
struct RpMaterial
{
RwTexture* texture;
RwRGBA color;
RxPipeline* pipeline;
RwSurfaceProperties surfaceProps;
int16 refCount;
int16 pad;
};
struct rxHeapBlockHeader
{
rxHeapBlockHeader* prev;
rxHeapBlockHeader* next;
uint32 size;
rxHeapFreeBlock* freeEntry;
uint32 pad[4];
};
struct RpTriangle
{
uint16 vertIndex[3];
int16 matIndex;
};
struct xFFX
{
};
struct RwFrame
{
RwObject object;
RwLLLink inDirtyListLink;
RwMatrixTag modelling;
RwMatrixTag ltm;
RwLinkList objectList;
RwFrame* child;
RwFrame* next;
RwFrame* root;
};
struct xSurface
{
};
struct xAnimMultiFile : xAnimMultiFileBase
{
xAnimMultiFileEntry Files[1];
};
struct RwTexture
{
RwRaster* raster;
RwTexDictionary* dict;
RwLLLink lInDictionary;
int8 name[32];
int8 mask[32];
uint32 filterAddressing;
int32 refCount;
};
struct xLightKitLight
{
uint32 type;
RwRGBAReal color;
float32 matrix[16];
float32 radius;
float32 angle;
RpLight* platLight;
};
struct RxPipelineRequiresCluster
{
RxClusterDefinition* clusterDef;
RxClusterValidityReq rqdOrOpt;
uint32 slotIndex;
};
struct RpSector
{
int32 type;
};
struct xGrid
{
uint8 ingrid_id;
uint8 pad[3];
uint16 nx;
uint16 nz;
float32 minx;
float32 minz;
float32 maxx;
float32 maxz;
float32 csizex;
float32 csizez;
float32 inv_csizex;
float32 inv_csizez;
float32 maxr;
xGridBound** cells;
xGridBound* other;
};
struct xModelBucket
{
RpAtomic* Data;
RpAtomic* OriginalData;
xModelInstance* List;
int32 ClipFlags;
uint32 PipeFlags;
};
struct xQCData
{
int8 xmin;
int8 ymin;
int8 zmin;
int8 zmin_dup;
int8 xmax;
int8 ymax;
int8 zmax;
int8 zmax_dup;
xVec3 min;
xVec3 max;
};
struct RpMeshHeader
{
uint32 flags;
uint16 numMeshes;
uint16 serialNum;
uint32 totalIndicesInMesh;
uint32 firstMeshOffset;
};
struct xBBox
{
xVec3 center;
xBox box;
};
struct xEntShadow
{
xVec3 pos;
xVec3 vec;
RpAtomic* shadowModel;
float32 dst_cast;
float32 radius[2];
};
struct RpWorldSector
{
int32 type;
RpPolygon* polygons;
RwV3d* vertices;
RpVertexNormal* normals;
RwTexCoords* texCoords[8];
RwRGBA* preLitLum;
RwResEntry* repEntry;
RwLinkList collAtomicsInWorldSector;
RwLinkList noCollAtomicsInWorldSector;
RwLinkList lightsInWorldSector;
RwBBox boundingBox;
RwBBox tightBoundingBox;
RpMeshHeader* mesh;
RxPipeline* pipeline;
uint16 matListWindowBase;
uint16 numVertices;
uint16 numPolygons;
uint16 pad;
};
struct RpMorphTarget
{
RpGeometry* parentGeom;
RwSphere boundingSphere;
RwV3d* verts;
RwV3d* normals;
};
struct xModelInstance
{
xModelInstance* Next;
xModelInstance* Parent;
xModelPool* Pool;
xAnimPlay* Anim;
RpAtomic* Data;
uint32 PipeFlags;
float32 RedMultiplier;
float32 GreenMultiplier;
float32 BlueMultiplier;
float32 Alpha;
float32 FadeStart;
float32 FadeEnd;
xSurface* Surf;
xModelBucket** Bucket;
xModelInstance* BucketNext;
xLightKit* LightKit;
void* Object;
uint16 Flags;
uint8 BoneCount;
uint8 BoneIndex;
uint8* BoneRemap;
RwMatrixTag* Mat;
xVec3 Scale;
uint32 modelID;
uint32 shadowID;
RpAtomic* shadowmapAtomic;
_class_0 anim_coll;
};
struct xVec3
{
float32 x;
float32 y;
float32 z;
};
struct anim_coll_data
{
};
struct xLightKit
{
uint32 tagID;
uint32 groupID;
uint32 lightCount;
xLightKitLight* lightList;
};
struct RwSurfaceProperties
{
float32 ambient;
float32 specular;
float32 diffuse;
};
struct RwMatrixTag
{
RwV3d right;
uint32 flags;
RwV3d up;
uint32 pad1;
RwV3d at;
uint32 pad2;
RwV3d pos;
uint32 pad3;
};
struct rxReq
{
};
struct xAnimTable
{
xAnimTable* Next;
int8* Name;
xAnimTransition* TransitionList;
xAnimState* StateList;
uint32 AnimIndex;
uint32 MorphIndex;
uint32 UserFlags;
};
struct RwRaster
{
RwRaster* parent;
uint8* cpPixels;
uint8* palette;
int32 width;
int32 height;
int32 depth;
int32 stride;
int16 nOffsetX;
int16 nOffsetY;
uint8 cType;
uint8 cFlags;
uint8 privateFlags;
uint8 cFormat;
uint8* originalPixels;
int32 originalWidth;
int32 originalHeight;
int32 originalStride;
};
enum RxClusterValidityReq
{
rxCLREQ_DONTWANT,
rxCLREQ_REQUIRED,
rxCLREQ_OPTIONAL,
rxCLUSTERVALIDITYREQFORCEENUMSIZEINT = 0x7fffffff
};
struct xGridBound
{
void* data;
uint16 gx;
uint16 gz;
uint8 ingrid;
uint8 oversize;
uint8 deleted;
uint8 gpad;
xGridBound** head;
xGridBound* next;
};
struct xClumpCollBSPTree
{
uint32 numBranchNodes;
xClumpCollBSPBranchNode* branchNodes;
uint32 numTriangles;
xClumpCollBSPTriangle* triangles;
};
struct zEnt : xEnt
{
xAnimTable* atbl;
};
struct xMat4x3 : xMat3x3
{
xVec3 pos;
uint32 pad3;
};
struct xClumpCollBSPVertInfo
{
uint16 atomIndex;
uint16 meshVertIndex;
};
enum RxNodeDefEditable
{
rxNODEDEFCONST,
rxNODEDEFEDITABLE,
rxNODEDEFEDITABLEFORCEENUMSIZEINT = 0x7fffffff
};
struct xClumpCollBSPBranchNode
{
uint32 leftInfo;
uint32 rightInfo;
float32 leftValue;
float32 rightValue;
};
enum RxClusterValid
{
rxCLVALID_NOCHANGE,
rxCLVALID_VALID,
rxCLVALID_INVALID,
rxCLUSTERVALIDFORCEENUMSIZEINT = 0x7fffffff
};
struct xRot
{
xVec3 axis;
float32 angle;
};
struct RwLLLink
{
RwLLLink* next;
RwLLLink* prev;
};
struct xClumpCollBSPTriangle
{
_class_1 v;
uint8 flags;
uint8 platData;
uint16 matIndex;
};
struct xAnimMultiFileEntry
{
uint32 ID;
xAnimFile* File;
};
struct xAnimActiveEffect
{
xAnimEffect* Effect;
uint32 Handle;
};
enum rxEmbeddedPacketState
{
rxPKST_PACKETLESS,
rxPKST_UNUSED,
rxPKST_INUSE,
rxPKST_PENDING,
rxEMBEDDEDPACKETSTATEFORCEENUMSIZEINT = 0x7fffffff
};
struct xSphere
{
xVec3 center;
float32 r;
};
struct xEnvAsset : xBaseAsset
{
uint32 bspAssetID;
uint32 startCameraAssetID;
uint32 climateFlags;
float32 climateStrengthMin;
float32 climateStrengthMax;
uint32 bspLightKit;
uint32 objectLightKit;
float32 padF1;
uint32 bspCollisionAssetID;
uint32 bspFXAssetID;
uint32 bspCameraAssetID;
uint32 bspMapperID;
uint32 bspMapperCollisionID;
uint32 bspMapperFXID;
float32 loldHeight;
};
struct _class_0
{
xVec3* verts;
};
struct xBox
{
xVec3 upper;
xVec3 lower;
};
struct xAnimSingle
{
uint32 SingleFlags;
xAnimState* State;
float32 Time;
float32 CurrentSpeed;
float32 BilinearLerp[2];
xAnimEffect* Effect;
uint32 ActiveCount;
float32 LastTime;
xAnimActiveEffect* ActiveList;
xAnimPlay* Play;
xAnimTransition* Sync;
xAnimTransition* Tran;
xAnimSingle* Blend;
float32 BlendFactor;
uint32 pad;
};
struct RpVertexNormal
{
int8 x;
int8 y;
int8 z;
uint8 pad;
};
struct tri_data
{
uint32 index;
float32 r;
float32 d;
};
enum RxClusterForcePresent
{
rxCLALLOWABSENT,
rxCLFORCEPRESENT,
rxCLUSTERFORCEPRESENTFORCEENUMSIZEINT = 0x7fffffff
};
struct xLinkAsset
{
uint16 srcEvent;
uint16 dstEvent;
uint32 dstAssetID;
float32 param[4];
uint32 paramWidgetAssetID;
uint32 chkAssetID;
};
struct xCylinder
{
xVec3 center;
float32 r;
float32 h;
};
struct _zPortal : xBase
{
xPortalAsset* passet;
};
struct RxClusterDefinition
{
int8* name;
uint32 defaultStride;
uint32 defaultAttributes;
int8* attributeSet;
};
struct RpInterpolator
{
int32 flags;
int16 startMorphTarget;
int16 endMorphTarget;
float32 time;
float32 recipTime;
float32 position;
};
struct xAnimMultiFileBase
{
uint32 Count;
};
struct _class_1
{
union
{
xClumpCollBSPVertInfo i;
RwV3d* p;
};
};
struct RwSphere
{
RwV3d center;
float32 radius;
};
struct RpPolygon
{
uint16 matIndex;
uint16 vertIndex[3];
};
struct RwTexDictionary
{
RwObject object;
RwLinkList texturesInDict;
RwLLLink lInInstance;
};
struct _class_2
{
float32 t;
float32 u;
float32 v;
};
struct RxOutputSpec
{
int8* name;
RxClusterValid* outputClusters;
RxClusterValid allOtherClusters;
};
struct RpMaterialList
{
RpMaterial** materials;
int32 numMaterials;
int32 space;
};
struct xMat3x3
{
xVec3 right;
int32 flags;
xVec3 up;
uint32 pad1;
xVec3 at;
uint32 pad2;
};
struct RxClusterRef
{
RxClusterDefinition* clusterDef;
RxClusterForcePresent forcePresent;
uint32 reserved;
};
struct xJSPNodeInfo
{
int32 originalMatIndex;
int32 nodeFlags;
};
struct RwObject
{
uint8 type;
uint8 subType;
uint8 flags;
uint8 privateFlags;
void* parent;
};
struct xEntAsset : xBaseAsset
{
uint8 flags;
uint8 subtype;
uint8 pflags;
uint8 moreFlags;
uint8 pad;
uint32 surfaceID;
xVec3 ang;
xVec3 pos;
xVec3 scale;
float32 redMult;
float32 greenMult;
float32 blueMult;
float32 seeThru;
float32 seeThruSpeed;
uint32 modelInfoID;
uint32 animListID;
};
struct RxIoSpec
{
uint32 numClustersOfInterest;
RxClusterRef* clustersOfInterest;
RxClusterValidityReq* inputRequirements;
uint32 numOutputs;
RxOutputSpec* outputs;
};
struct xMemPool
{
void* FreeList;
uint16 NextOffset;
uint16 Flags;
void* UsedList;
void(*InitCB)(xMemPool*, void*);
void* Buffer;
uint16 Size;
uint16 NumRealloc;
uint32 Total;
};
struct RxNodeMethods
{
int32(*nodeBody)(RxPipelineNode*, RxPipelineNodeParam*);
int32(*nodeInit)(RxNodeDefinition*);
void(*nodeTerm)(RxNodeDefinition*);
int32(*pipelineNodeInit)(RxPipelineNode*);
void(*pipelineNodeTerm)(RxPipelineNode*);
int32(*pipelineNodeConfig)(RxPipelineNode*, RxPipeline*);
uint32(*configMsgHandler)(RxPipelineNode*, uint32, uint32, void*);
};
struct RxCluster
{
uint16 flags;
uint16 stride;
void* data;
void* currentData;
uint32 numAlloced;
uint32 numUsed;
RxPipelineCluster* clusterRef;
uint32 attributes;
};
struct xEnv
{
iEnv* geom;
iEnv ienv;
xLightKit* lightKit;
};
struct _zEnv : xBase
{
xEnvAsset* easset;
};
struct xShadowSimplePoly
{
xVec3 vert[3];
xVec3 norm;
};
struct RxPacket
{
uint16 flags;
uint16 numClusters;
RxPipeline* pipeline;
uint32* inputToClusterSlot;
uint32* slotsContinue;
RxPipelineCluster** slotClusterRefs;
RxCluster clusters[1];
};
struct RwRGBAReal
{
float32 red;
float32 green;
float32 blue;
float32 alpha;
};
struct RwLinkList
{
RwLLLink link;
};
xGrid colls_grid;
xGrid colls_oso_grid;
xGrid npcs_grid;
int32 zGridInitted;
int32 gGridIterActive;
void zGridUpdateEnt(xEnt* ent);
void zGridExit();
void zGridInit(zScene* s);
void zGridReset(zScene* s);
void hack_flag_shadows(zScene* s);
// zGridUpdateEnt__FP4xEnt
// Start address: 0x306050
void zGridUpdateEnt(xEnt* ent)
{
int32 oversize;
xGrid* grid;
// Line 163, Address: 0x306050, Func Offset: 0
// Line 165, Address: 0x30605c, Func Offset: 0xc
// Line 172, Address: 0x306068, Func Offset: 0x18
// Line 170, Address: 0x306070, Func Offset: 0x20
// Line 172, Address: 0x306074, Func Offset: 0x24
// Line 174, Address: 0x306098, Func Offset: 0x48
// Line 175, Address: 0x30609c, Func Offset: 0x4c
// Line 176, Address: 0x3060a4, Func Offset: 0x54
// Line 178, Address: 0x3060a8, Func Offset: 0x58
// Line 177, Address: 0x3060ac, Func Offset: 0x5c
// Line 178, Address: 0x3060b4, Func Offset: 0x64
// Line 179, Address: 0x3060b8, Func Offset: 0x68
// Line 182, Address: 0x3060c0, Func Offset: 0x70
// Line 181, Address: 0x3060c4, Func Offset: 0x74
// Line 182, Address: 0x3060cc, Func Offset: 0x7c
// Line 184, Address: 0x3060d4, Func Offset: 0x84
// Line 187, Address: 0x3060d8, Func Offset: 0x88
// Line 189, Address: 0x3060f8, Func Offset: 0xa8
// Line 191, Address: 0x306100, Func Offset: 0xb0
// Line 192, Address: 0x306108, Func Offset: 0xb8
// Line 194, Address: 0x306110, Func Offset: 0xc0
// Line 196, Address: 0x306118, Func Offset: 0xc8
// Line 197, Address: 0x306128, Func Offset: 0xd8
// Line 198, Address: 0x30613c, Func Offset: 0xec
// Line 199, Address: 0x306140, Func Offset: 0xf0
// Line 200, Address: 0x306148, Func Offset: 0xf8
// Line 201, Address: 0x30614c, Func Offset: 0xfc
// Line 202, Address: 0x306150, Func Offset: 0x100
// Line 203, Address: 0x306160, Func Offset: 0x110
// Line 204, Address: 0x306168, Func Offset: 0x118
// Line 205, Address: 0x306180, Func Offset: 0x130
// Line 206, Address: 0x306194, Func Offset: 0x144
// Line 207, Address: 0x306198, Func Offset: 0x148
// Line 208, Address: 0x3061a0, Func Offset: 0x150
// Line 210, Address: 0x3061a8, Func Offset: 0x158
// Line 211, Address: 0x3061b8, Func Offset: 0x168
// Line 212, Address: 0x3061c0, Func Offset: 0x170
// Line 217, Address: 0x3061d0, Func Offset: 0x180
// Line 219, Address: 0x3061d8, Func Offset: 0x188
// Line 220, Address: 0x3061e0, Func Offset: 0x190
// Line 223, Address: 0x3061e8, Func Offset: 0x198
// Func End, Address: 0x3061f8, Func Offset: 0x1a8
}
// zGridExit__FP6zScene
// Start address: 0x306200
void zGridExit()
{
// Line 154, Address: 0x306200, Func Offset: 0
// Line 155, Address: 0x306204, Func Offset: 0x4
// Line 154, Address: 0x306208, Func Offset: 0x8
// Line 155, Address: 0x30620c, Func Offset: 0xc
// Line 156, Address: 0x306214, Func Offset: 0x14
// Line 157, Address: 0x306220, Func Offset: 0x20
// Line 158, Address: 0x30622c, Func Offset: 0x2c
// Line 159, Address: 0x306230, Func Offset: 0x30
// Line 160, Address: 0x306234, Func Offset: 0x34
// Func End, Address: 0x306240, Func Offset: 0x40
}
// zGridInit__FP6zScene
// Start address: 0x306240
void zGridInit(zScene* s)
{
xBox* ebox;
float32 min_csize;
xBox osobox;
// Line 109, Address: 0x306240, Func Offset: 0
// Line 115, Address: 0x306268, Func Offset: 0x28
// Line 117, Address: 0x30627c, Func Offset: 0x3c
// Line 118, Address: 0x3062a4, Func Offset: 0x64
// Line 117, Address: 0x3062a8, Func Offset: 0x68
// Line 118, Address: 0x3062ac, Func Offset: 0x6c
// Line 120, Address: 0x3062cc, Func Offset: 0x8c
// Line 121, Address: 0x3062e4, Func Offset: 0xa4
// Line 127, Address: 0x30649c, Func Offset: 0x25c
// Line 128, Address: 0x3064a0, Func Offset: 0x260
// Line 127, Address: 0x3064a4, Func Offset: 0x264
// Line 128, Address: 0x3064b8, Func Offset: 0x278
// Line 130, Address: 0x3064c0, Func Offset: 0x280
// Line 127, Address: 0x3064d0, Func Offset: 0x290
// Line 132, Address: 0x3064d8, Func Offset: 0x298
// Line 127, Address: 0x3064dc, Func Offset: 0x29c
// Line 132, Address: 0x3064e0, Func Offset: 0x2a0
// Line 127, Address: 0x3064e4, Func Offset: 0x2a4
// Line 132, Address: 0x3064f0, Func Offset: 0x2b0
// Line 127, Address: 0x3064f4, Func Offset: 0x2b4
// Line 128, Address: 0x3064fc, Func Offset: 0x2bc
// Line 129, Address: 0x306508, Func Offset: 0x2c8
// Line 130, Address: 0x306514, Func Offset: 0x2d4
// Line 131, Address: 0x306520, Func Offset: 0x2e0
// Line 132, Address: 0x306538, Func Offset: 0x2f8
// Line 133, Address: 0x30654c, Func Offset: 0x30c
// Line 132, Address: 0x306550, Func Offset: 0x310
// Line 133, Address: 0x306554, Func Offset: 0x314
// Line 135, Address: 0x306574, Func Offset: 0x334
// Line 136, Address: 0x306590, Func Offset: 0x350
// Line 141, Address: 0x306754, Func Offset: 0x514
// Line 146, Address: 0x30690c, Func Offset: 0x6cc
// Line 149, Address: 0x306910, Func Offset: 0x6d0
// Line 150, Address: 0x30691c, Func Offset: 0x6dc
// Func End, Address: 0x306944, Func Offset: 0x704
}
// zGridReset__FP6zScene
// Start address: 0x306950
void zGridReset(zScene* s)
{
uint32 i;
xBase* base;
xEnt* ent;
// Line 83, Address: 0x306950, Func Offset: 0
// Line 84, Address: 0x306968, Func Offset: 0x18
// Line 88, Address: 0x306970, Func Offset: 0x20
// Line 89, Address: 0x306988, Func Offset: 0x38
// Line 91, Address: 0x306994, Func Offset: 0x44
// Line 96, Address: 0x3069d8, Func Offset: 0x88
// Line 97, Address: 0x3069dc, Func Offset: 0x8c
// Line 98, Address: 0x3069e4, Func Offset: 0x94
// Line 99, Address: 0x3069f8, Func Offset: 0xa8
// Line 100, Address: 0x306a00, Func Offset: 0xb0
// Line 101, Address: 0x306a14, Func Offset: 0xc4
// Line 103, Address: 0x306a18, Func Offset: 0xc8
// Line 105, Address: 0x306a20, Func Offset: 0xd0
// Line 106, Address: 0x306a38, Func Offset: 0xe8
// Func End, Address: 0x306a54, Func Offset: 0x104
}
// hack_flag_shadows__FP6zScene
// Start address: 0x306a60
void hack_flag_shadows(zScene* s)
{
uint32* end_special_models;
zEnt** it;
zEnt** end;
xEnt* ent;
uint32* id;
uint32 special_models[25];
int8 @3381;
// Line 24, Address: 0x306a60, Func Offset: 0
// Line 25, Address: 0x306a6c, Func Offset: 0xc
// Line 58, Address: 0x306c78, Func Offset: 0x218
// Line 53, Address: 0x306c80, Func Offset: 0x220
// Line 58, Address: 0x306c84, Func Offset: 0x224
// Line 59, Address: 0x306c8c, Func Offset: 0x22c
// Line 61, Address: 0x306c98, Func Offset: 0x238
// Line 62, Address: 0x306c9c, Func Offset: 0x23c
// Line 64, Address: 0x306cc0, Func Offset: 0x260
// Line 66, Address: 0x306cd0, Func Offset: 0x270
// Line 68, Address: 0x306cdc, Func Offset: 0x27c
// Line 69, Address: 0x306ce8, Func Offset: 0x288
// Line 70, Address: 0x306cf4, Func Offset: 0x294
// Line 71, Address: 0x306d00, Func Offset: 0x2a0
// Line 73, Address: 0x306d08, Func Offset: 0x2a8
// Line 74, Address: 0x306d14, Func Offset: 0x2b4
// Line 75, Address: 0x306d28, Func Offset: 0x2c8
// Func End, Address: 0x306d38, Func Offset: 0x2d8
}
| 19.591052
| 74
| 0.756682
|
stravant
|
fdfe8d63fd26e2fe0786810be04c304c768a425d
| 12,952
|
hpp
|
C++
|
src/IO/H5/File.hpp
|
trami18/spectre
|
6b1f6497bf2e26d1474bfadf143b3321942c40b4
|
[
"MIT"
] | 2
|
2021-04-11T04:07:42.000Z
|
2021-04-11T05:07:54.000Z
|
src/IO/H5/File.hpp
|
trami18/spectre
|
6b1f6497bf2e26d1474bfadf143b3321942c40b4
|
[
"MIT"
] | 1
|
2022-03-25T18:26:16.000Z
|
2022-03-25T19:30:39.000Z
|
src/IO/H5/File.hpp
|
isaaclegred/spectre
|
5765da85dad680cad992daccd479376c67458a8c
|
[
"MIT"
] | null | null | null |
// Distributed under the MIT License.
// See LICENSE.txt for details.
/// \file
/// Defines class h5::H5File
#pragma once
#include <algorithm>
#include <exception>
#include <hdf5.h>
#include <memory>
#include <ostream>
#include <string>
#include <tuple>
#include <type_traits>
#include <typeinfo>
#include <vector>
#include "IO/H5/AccessType.hpp"
#include "IO/H5/CheckH5.hpp"
#include "IO/H5/Header.hpp" // IWYU pragma: keep
#include "IO/H5/Helpers.hpp"
#include "IO/H5/Object.hpp"
#include "IO/H5/OpenGroup.hpp"
#include "Utilities/ErrorHandling/Error.hpp"
#include "Utilities/FileSystem.hpp"
#include "Utilities/PrettyType.hpp"
namespace h5 {
/*!
* \ingroup HDF5Group
* \brief Opens an HDF5 file for access and allows manipulation of data
*
* Opens an HDF5 file either in ReadOnly or ReadWrite mode depending on the
* template parameter `Access_t`. In ReadWrite mode h5::Object's can be inserted
* into the file, and objects can be retrieved to have their data manipulated.
* Example objects are dat files, text files, and volume data files. A single
* H5File can contain many different objects so that the number of files stored
* during a simulation is reduced.
*
* When an h5::object inside an H5File is opened or created the H5File object
* holds a copy of the h5::object. Only one object can be open at a time, which
* means if a reference to the object is kept around after the H5File's current
* object is closed there is a dangling reference.
*
* \example
* To open a file for read-write access:
* \snippet Test_H5.cpp h5file_readwrite_file
*
* \note The dangling reference issue could be fixed by having a function in
* addition to `get` that takes a lambda. The lambda takes exactly one parameter
* of the type of the h5::Object it will be operating on. While this approach is
* likely to be syntactically strange for many users it will most likely be more
* performant than the `shared_ptr` solution.
*
* @tparam Access_t either h5::AccessType::ReadWrite or h5::AccessType::ReadOnly
*/
template <AccessType Access_t>
class H5File {
public:
// empty constructor for classes which store an H5File and need to be
// charm-compatible.
H5File() noexcept = default;
/*!
* \requires `file_name` is a valid path and ends in `.h5`.
* \effects On object creation opens the HDF5 file at `file_name`
*
* @param file_name the path to the file to open or create
* @param append_to_file if true allow appending to the file, otherwise abort
* the simulation if the file exists
*/
explicit H5File(std::string file_name, bool append_to_file = false);
/// \cond HIDDEN_SYMBOLS
~H5File();
/// \endcond
// @{
/*!
* \brief It does not make sense to copy an object referring to a file, only
* to move it.
*/
H5File(const H5File& /*rhs*/) = delete;
H5File& operator=(const H5File& /*rhs*/) = delete;
// @}
/// \cond HIDDEN_SYMBOLS
H5File(H5File&& rhs) noexcept; // NOLINT
H5File& operator=(H5File&& rhs) noexcept; // NOLINT
/// \endcond
/// Get name of the H5 file
const std::string& name() const noexcept { return file_name_; }
/// Get a std::vector of the names of all immediate subgroups of the file
const std::vector<std::string> groups() const noexcept {
return h5::get_group_names(file_id_, "/");
}
// @{
/*!
* \requires `ObjectType` is a valid h5::Object derived class, `path`
* is a valid path in the HDF5 file
* \return a reference to the object inside the HDF5 file.
*
* @tparam ObjectType the type of the h5::Object to be retrieved, e.g. Dat
* @param path the path of the retrieved object
* @param args arguments forwarded to the ObjectType constructor
*/
template <
typename ObjectType, typename... Args,
typename std::enable_if_t<((void)sizeof(ObjectType),
Access_t == AccessType::ReadWrite)>* = nullptr>
ObjectType& get(const std::string& path, Args&&... args);
template <typename ObjectType, typename... Args>
const ObjectType& get(const std::string& path, Args&&... args) const;
// @}
/*!
* \brief Insert an object into an H5 file.
*
* \requires `ObjectType` is a valid h5::Object derived class, `path` is a
* valid path in the HDF5 file, and `args` are valid arguments to be forwarded
* to the constructor of `ObjectType`.
* \effects Creates a new H5 object of type `ObjectType` at the location
* `path` in the HDF5 file.
*
* \return a reference the created object.
*
* @tparam ObjectType the type of the h5::Object to be inserted, e.g. Dat
* @param path the path of the inserted object
* @param args additional arguments to be passed to the constructor of the
* object
*/
template <typename ObjectType, typename... Args>
ObjectType& insert(const std::string& path, Args&&... args);
/*!
* \brief Inserts an object like `insert` if it does not exist, returns the
* object if it does.
*/
template <typename ObjectType, typename... Args>
ObjectType& try_insert(const std::string& path, Args&&... args) noexcept;
/*!
* \effects Closes the current object, if there is none then has no effect
*/
void close_current_object() const noexcept { current_object_ = nullptr; }
template <typename ObjectType>
bool exists(const std::string& path) const noexcept {
auto exists_group_name = check_if_object_exists<ObjectType>(path);
return std::get<0>(exists_group_name);
}
private:
/// \cond HIDDEN_SYMBOLS
template <typename ObjectType,
std::enable_if_t<((void)sizeof(ObjectType),
Access_t == AccessType::ReadWrite)>* = nullptr>
ObjectType& convert_to_derived(
std::unique_ptr<h5::Object>& current_object); // NOLINT
template <typename ObjectType>
const ObjectType& convert_to_derived(
const std::unique_ptr<h5::Object>& current_object) const;
void insert_header();
void insert_source_archive() noexcept;
template <typename ObjectType>
std::tuple<bool, detail::OpenGroup, std::string> check_if_object_exists(
const std::string& path) const;
std::string file_name_;
hid_t file_id_{-1};
mutable std::unique_ptr<h5::Object> current_object_{nullptr};
std::vector<std::string> h5_groups_;
/// \endcond HIDDEN_SYMBOLS
};
// ======================================================================
// H5File Definitions
// ======================================================================
template <AccessType Access_t>
template <typename ObjectType, typename... Args,
typename std::enable_if_t<((void)sizeof(ObjectType),
Access_t == AccessType::ReadWrite)>*>
ObjectType& H5File<Access_t>::get(const std::string& path, Args&&... args) {
// Ensure we call the const version of the get function to avoid infinite
// recursion. The reason this is implemented in this manner is to avoid code
// duplication.
// clang-tidy: do not use const_cast
return const_cast<ObjectType&>( // NOLINT
static_cast<H5File<Access_t> const*>(this)->get<ObjectType>(
path, std::forward<Args>(args)...));
}
template <AccessType Access_t>
template <typename ObjectType, typename... Args>
const ObjectType& H5File<Access_t>::get(const std::string& path,
Args&&... args) const {
try {
current_object_ = nullptr;
// C++17: structured bindings
auto exists_group_name = check_if_object_exists<ObjectType>(path);
hid_t group_id = std::get<1>(exists_group_name).id();
if (not std::get<0>(exists_group_name)) {
current_object_ = nullptr;
CHECK_H5(H5Fclose(file_id_),
"Failed to close file: '" << file_name_ << "'");
ERROR("Cannot open the object '" << path + ObjectType::extension()
<< "' because it does not exist.");
}
current_object_ = std::make_unique<ObjectType>(
std::get<0>(exists_group_name),
std::move(std::get<1>(exists_group_name)), group_id,
std::move(std::get<2>(exists_group_name)), std::forward<Args>(args)...);
return dynamic_cast<const ObjectType&>(*current_object_);
// LCOV_EXCL_START
} catch (const std::bad_cast& e) {
current_object_ = nullptr;
CHECK_H5(H5Fclose(file_id_),
"Failed to close file: '" << file_name_ << "'");
ERROR("Failed to cast " << path << " to "
<< pretty_type::get_name<ObjectType>()
<< ".\nCast error: " << e.what());
} catch (const std::exception& e) {
current_object_ = nullptr;
CHECK_H5(H5Fclose(file_id_),
"Failed to close file: '" << file_name_ << "'");
ERROR("Unknown exception caught: " << e.what());
// LCOV_EXCL_STOP
}
}
template <AccessType Access_t>
template <typename ObjectType, typename... Args>
ObjectType& H5File<Access_t>::insert(const std::string& path, Args&&... args) {
static_assert(AccessType::ReadWrite == Access_t,
"Can only insert into ReadWrite access H5 files.");
current_object_ = nullptr;
// C++17: structured bindings
auto exists_group_name = check_if_object_exists<ObjectType>(path);
if (std::get<0>(exists_group_name)) {
current_object_ = nullptr;
CHECK_H5(H5Fclose(file_id_),
"Failed to close file: '" << file_name_ << "'");
ERROR(
"Cannot insert an Object that already exists. Failed to add Object "
"named: "
<< path);
}
hid_t group_id = std::get<1>(exists_group_name).id();
return convert_to_derived<ObjectType>(
current_object_ = std::make_unique<ObjectType>(
std::get<0>(exists_group_name),
std::move(std::get<1>(exists_group_name)), group_id,
std::move(std::get<2>(exists_group_name)),
std::forward<Args>(args)...));
}
template <AccessType Access_t>
template <typename ObjectType, typename... Args>
ObjectType& H5File<Access_t>::try_insert(const std::string& path,
Args&&... args) noexcept {
static_assert(AccessType::ReadWrite == Access_t,
"Can only insert into ReadWrite access H5 files.");
current_object_ = nullptr;
// C++17: structured bindings
auto exists_group_name = check_if_object_exists<ObjectType>(path);
hid_t group_id = std::get<1>(exists_group_name).id();
return convert_to_derived<ObjectType>(
current_object_ = std::make_unique<ObjectType>(
std::get<0>(exists_group_name),
std::move(std::get<1>(exists_group_name)), group_id,
std::move(std::get<2>(exists_group_name)),
std::forward<Args>(args)...));
}
/// \cond HIDDEN_SYMBOLS
template <AccessType Access_t>
template <typename ObjectType,
typename std::enable_if_t<((void)sizeof(ObjectType),
Access_t == AccessType::ReadWrite)>*>
ObjectType& H5File<Access_t>::convert_to_derived(
std::unique_ptr<h5::Object>& current_object) {
if (nullptr == current_object) {
ERROR("No object to convert."); // LCOV_EXCL_LINE
}
try {
return dynamic_cast<ObjectType&>(*current_object);
// LCOV_EXCL_START
} catch (const std::bad_cast& e) {
ERROR("Failed to cast to object.\nCast error: " << e.what());
// LCOV_EXCL_STOP
}
}
template <AccessType Access_t>
template <typename ObjectType>
const ObjectType& H5File<Access_t>::convert_to_derived(
const std::unique_ptr<h5::Object>& current_object) const {
if (nullptr == current_object) {
ERROR("No object to convert.");
}
try {
return dynamic_cast<const ObjectType&>(*current_object);
} catch (const std::bad_cast& e) {
ERROR("Failed to cast to object.\nCast error: " << e.what());
}
}
template <AccessType Access_t>
template <typename ObjectType>
std::tuple<bool, detail::OpenGroup, std::string>
H5File<Access_t>::check_if_object_exists(const std::string& path) const {
std::string name_only = "/";
if (path != "/") {
name_only = file_system::get_file_name(path);
}
const std::string name_with_extension = name_only + ObjectType::extension();
detail::OpenGroup group(file_id_, file_system::get_parent_path(path),
Access_t);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
const bool object_exists =
name_with_extension == "/" or
H5Lexists(group.id(), name_with_extension.c_str(), H5P_DEFAULT) or
H5Aexists(group.id(), name_with_extension.c_str());
#pragma GCC diagnostic pop
return std::make_tuple(object_exists, std::move(group), std::move(name_only));
}
template <>
inline void H5File<AccessType::ReadWrite>::insert_header() {
insert<h5::Header>("/header");
}
// Not tested because it is only required to get code to compile, if statement
// in constructor prevents call.
template <>
inline void H5File<AccessType::ReadOnly>::insert_header() {} // LCOV_EXCL_LINE
/// \endcond
} // namespace h5
| 37.111748
| 80
| 0.664839
|
trami18
|
fdff134d7d08080d5bc88d93be6880aac87a2946
| 698
|
cpp
|
C++
|
src/tri.cpp
|
JulianNeeleman/kattis
|
035c1113ffb397c2d8538af8ba16b7ee4160393d
|
[
"MIT"
] | null | null | null |
src/tri.cpp
|
JulianNeeleman/kattis
|
035c1113ffb397c2d8538af8ba16b7ee4160393d
|
[
"MIT"
] | 1
|
2017-05-16T15:57:29.000Z
|
2017-05-17T19:43:56.000Z
|
src/tri.cpp
|
JulianNeeleman/kattis
|
035c1113ffb397c2d8538af8ba16b7ee4160393d
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>
using namespace std;
int main() {
int a, b, c;
cin >> a >> b >> c;
if(a == b + c) cout << a << '=' << b << '+' << c << endl;
else if(a == b - c) cout << a << '=' << b << '-' << c << endl;
else if(a == b * c) cout << a << '=' << b << '*' << c << endl;
else if(a == b / c) cout << a << '=' << b << '/' << c << endl;
else if(a + b == c) cout << a << '+' << b << '=' << c << endl;
else if(a - b == c) cout << a << '-' << b << '=' << c << endl;
else if(a * b == c) cout << a << '*' << b << '=' << c << endl;
else if(a / b == c) cout << a << '/' << b << '=' << c << endl;
return 0;
}
| 29.083333
| 63
| 0.393983
|
JulianNeeleman
|
a900e7e0ed9fec6bc2e7d5a0648a1dadcc4d25a7
| 492
|
cpp
|
C++
|
src/src/agent/TaskVssWorker.cpp
|
pytf/intelligent-protector
|
0d454b54fc91e42accf402c5584f8526cdb7a170
|
[
"Apache-2.0"
] | 5
|
2017-03-21T09:11:55.000Z
|
2018-11-19T14:44:36.000Z
|
src/src/agent/TaskVssWorker.cpp
|
pytf/intelligent-protector
|
0d454b54fc91e42accf402c5584f8526cdb7a170
|
[
"Apache-2.0"
] | 3
|
2018-02-06T06:17:10.000Z
|
2020-07-10T17:29:47.000Z
|
src/src/agent/TaskVssWorker.cpp
|
pytf/intelligent-protector
|
0d454b54fc91e42accf402c5584f8526cdb7a170
|
[
"Apache-2.0"
] | 7
|
2018-02-06T03:54:13.000Z
|
2021-09-08T10:51:38.000Z
|
/*******************************************************************************
* Copyright @ Huawei Technologies Co., Ltd. 2017-2018. All rights reserved.
********************************************************************************/
#ifdef WIN32
#include "agent/TaskVssWorker.h"
#include "common/Log.h"
#include "common/Utils.h"
#include "common/ErrorCode.h"
#include "agent/Communication.h"
CTaskVssWorker::CTaskVssWorker()
{
}
CTaskVssWorker::~CTaskVssWorker()
{
}
#endif //WIN32
| 23.428571
| 81
| 0.495935
|
pytf
|
a9011963e3fb57b0cbe2fcaaae6d72be5b2d8ad2
| 5,336
|
hpp
|
C++
|
src/core/DistributedRegionHash.hpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | null | null | null |
src/core/DistributedRegionHash.hpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | null | null | null |
src/core/DistributedRegionHash.hpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | 1
|
2021-07-21T06:48:19.000Z
|
2021-07-21T06:48:19.000Z
|
// Copyright (c) 2020 Matthew J. Smith and Overkit contributors
// License: MIT (http://opensource.org/licenses/MIT)
#ifndef OVK_CORE_DISTRIBUTED_REGION_HASH_HPP_INCLUDED
#define OVK_CORE_DISTRIBUTED_REGION_HASH_HPP_INCLUDED
#include <ovk/core/Array.hpp>
#include <ovk/core/ArrayView.hpp>
#include <ovk/core/Box.hpp>
#include <ovk/core/Comm.hpp>
#include <ovk/core/CommunicationOps.hpp>
#include <ovk/core/DataType.hpp>
#include <ovk/core/Elem.hpp>
#include <ovk/core/Field.hpp>
#include <ovk/core/Global.hpp>
#include <ovk/core/HashableRegionTraits.hpp>
#include <ovk/core/Indexer.hpp>
#include <ovk/core/Interval.hpp>
#include <ovk/core/Map.hpp>
#include <ovk/core/Math.hpp>
#include <ovk/core/MPISerializableTraits.hpp>
#include <ovk/core/Range.hpp>
#include <ovk/core/Requires.hpp>
#include <ovk/core/Set.hpp>
#include <ovk/core/Tuple.hpp>
#include <mpi.h>
#include <cmath>
#include <cstring>
#include <memory>
#include <numeric>
#include <type_traits>
#include <utility>
namespace ovk {
namespace core {
template <typename RegionType> class distributed_region_hash;
template <typename RegionType> class distributed_region_data {
public:
using region_type = RegionType;
const region_type &Region() const { return Region_; }
int Rank() const { return Rank_; }
private:
region_type Region_;
int Rank_;
friend class distributed_region_hash<RegionType>;
};
template <typename RegionType> class distributed_region_hash_retrieved_bins {
public:
using region_data = distributed_region_data<RegionType>;
const region_data &RegionData(int iRegion) const { return RegionData_(iRegion); }
array_view<const int> BinRegionIndices(int iBin) const {
const interval<long long> &Interval = BinRegionIndicesIntervals_(iBin);
return {BinRegionIndices_.Data(Interval.Begin()), Interval};
}
private:
array<region_data> RegionData_;
map<int,interval<long long>> BinRegionIndicesIntervals_;
array<int> BinRegionIndices_;
friend class distributed_region_hash<RegionType>;
};
template <typename RegionType> class distributed_region_hash {
public:
static_assert(IsHashableRegion<RegionType>(), "Invalid region type (not hashable).");
static_assert(IsMPISerializable<RegionType>(), "Invalid region type (not MPI-serializable).");
using region_type = RegionType;
using region_traits = hashable_region_traits<region_type>;
using coord_type = typename region_traits::coord_type;
using mpi_traits = mpi_serializable_traits<region_type>;
static_assert(std::is_same<coord_type, int>::value || std::is_same<coord_type, double>::value,
"Coord type must be int or double.");
using extents_type = interval<coord_type,MAX_DIMS>;
using region_data = distributed_region_data<region_type>;
using retrieved_bins = distributed_region_hash_retrieved_bins<region_type>;
distributed_region_hash(int NumDims, comm_view Comm);
distributed_region_hash(int NumDims, comm_view Comm, array_view<const region_type> LocalRegions);
distributed_region_hash(const distributed_region_hash &Other) = delete;
distributed_region_hash(distributed_region_hash &&Other) noexcept = default;
distributed_region_hash &operator=(const distributed_region_hash &Other) = delete;
distributed_region_hash &operator=(distributed_region_hash &&Other) noexcept = default;
elem<int,2> MapToBin(const tuple<coord_type> &Point) const;
map<int,retrieved_bins> RetrieveBins(array_view<const elem<int,2>> BinIDs) const;
private:
int NumDims_;
comm_view Comm_;
extents_type GlobalExtents_;
range ProcRange_;
range_indexer<int> ProcIndexer_;
tuple<coord_type> ProcSize_;
array<int> ProcToBinMultipliers_;
array<region_data> RegionData_;
range BinRange_;
field<int> NumRegionsPerBin_;
field<long long> BinRegionIndicesStarts_;
array<int> BinRegionIndices_;
template <hashable_region_maps_to MapsTo> struct maps_to_tag {};
template <typename IndexerType> set<typename IndexerType::index_type> MapToBins_(const range
&BinRange, const IndexerType &BinIndexer, const tuple<coord_type> &LowerCorner, const
tuple<coord_type> &BinSize, const region_type &Region, maps_to_tag<
hashable_region_maps_to::SET>) const;
template <typename IndexerType> set<typename IndexerType::index_type> MapToBins_(const range
&BinRange, const IndexerType &BinIndexer, const tuple<coord_type> &LowerCorner, const
tuple<coord_type> &BinSize, const region_type &Region, maps_to_tag<
hashable_region_maps_to::RANGE>) const;
template <typename T> struct coord_type_tag {};
static interval<int,MAX_DIMS> MakeEmptyExtents_(int NumDims, coord_type_tag<int>);
static interval<double,MAX_DIMS> MakeEmptyExtents_(int NumDims, coord_type_tag<double>);
static interval<int,MAX_DIMS> UnionExtents_(const interval<int,MAX_DIMS> &Left, const
interval<int,MAX_DIMS> &Right);
static interval<double,MAX_DIMS> UnionExtents_(const interval<double,MAX_DIMS> &Left, const
interval<double,MAX_DIMS> &Right);
static tuple<int> BinDecomp_(int NumDims, const extents_type &Extents, int MaxBins);
static tuple<int> GetBinSize_(const interval<int,MAX_DIMS> &Extents, const tuple<int> &NumBins);
static tuple<double> GetBinSize_(const interval<double,MAX_DIMS> &Extents, const tuple<int>
&NumBins);
};
}}
#include <ovk/core/DistributedRegionHash.inl>
#endif
| 31.204678
| 99
| 0.778298
|
gyzhangqm
|
a909a4cbefadf621a42d3bde37f5db0177572fbd
| 6,218
|
cpp
|
C++
|
Applications/flux/misstypes.cpp
|
ronichoudhury/mtvx
|
379cfbfd7a55440e6862526c1817dfad5c6ce171
|
[
"Apache-2.0"
] | 2
|
2018-07-30T17:02:50.000Z
|
2020-06-12T03:01:21.000Z
|
Applications/flux/misstypes.cpp
|
waxlamp/mtvx
|
379cfbfd7a55440e6862526c1817dfad5c6ce171
|
[
"Apache-2.0"
] | null | null | null |
Applications/flux/misstypes.cpp
|
waxlamp/mtvx
|
379cfbfd7a55440e6862526c1817dfad5c6ce171
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2011 A.N.M. Imroz Choudhury
//
// misstypes.cpp - Reads in a family of hit-level output files,
// determining the miss type of each cache miss.
// MTV headers.
#include <Core/Dataflow/TraceReader.h>
using MTV::TraceReader;
// TCLAP headers.
#include <tclap/CmdLine.h>
// System headers.
#include <cstdlib>
#include <string>
#include <vector>
struct MissCounts{
MissCounts()
: compulsory(0),
capacity(0),
mapping(0),
replacement(0)
{}
uint64_t compulsory;
uint64_t capacity;
uint64_t mapping;
uint64_t replacement;
};
int main(int argc, char *argv[]){
std::string tracefile;
std::vector<std::string> hitlevelfiles;
unsigned blocksize, misslevel;
try{
TCLAP::CmdLine cmd("Determine miss types from a family of hit-level data files.");
// Reference trace file.
TCLAP::ValueArg<std::string> tracefileArg("t",
"trace-file",
"Reference trace file - needed for addresses.",
true,
"",
"filename",
cmd);
// Hit-level data files.
TCLAP::MultiArg<std::string> hitlevelfilesArg("l",
"hit-level-file",
"Hit level file - needed for determining miss types.",
true,
"filenames",
cmd);
// Block size.
TCLAP::ValueArg<unsigned> blocksizeArg("b",
"block-size",
"Block size of the cache, in bytes",
true,
0,
"positive integer",
cmd);
// Miss level - the level of cache hit that represents an actual
// miss (a "hit" to main memory).
TCLAP::ValueArg<unsigned> misslevelArg("m",
"miss-level",
"The number in the hit-level data that corresponds to a cache miss.",
0,
true,
"positive integer",
cmd);
cmd.parse(argc, argv);
tracefile = tracefileArg.getValue();
hitlevelfiles = hitlevelfilesArg.getValue();
blocksize = blocksizeArg.getValue();
misslevel = misslevelArg.getValue();
}
catch(TCLAP::ArgException& e){
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
exit(1);
}
// Check for three hit-level files.
if(hitlevelfiles.size() != 3){
std::cerr << "error: expected 3 hit-level data files, got " << hitlevelfiles.size() << std::endl;
exit(1);
}
// Open the hit level files.
std::ifstream capacity(hitlevelfiles[0].c_str());
std::ifstream associative(hitlevelfiles[1].c_str());
std::ifstream real(hitlevelfiles[2].c_str());
if(!capacity or !associative or !real){
std::cerr << "error: could not open hit-level files for reading." << std::endl;
exit(1);
}
// Open the trace file.
TraceReader reader;
if(!reader.open(tracefile)){
std::cerr << "error: cannot open trace file '" << tracefile << "' for reading." << std::endl;
exit(1);
}
// Instantiate a set object, used to watch for previously unseen
// block addresses.
boost::unordered_set<uint64_t> blocks;
// Use this to count the miss types.
MissCounts counts;
// Begin reading addresses from the trace.
uint64_t trace_size;
try{
for(trace_size = 0; ; trace_size++){
// Grab a record and compute its block address.
const uint64_t block_addr = reader.nextRecord().addr / blocksize;
// Read out one record from each of the hit level files - this
// needs to be done even if the miss is compulsory, so just do
// it here.
unsigned cap_hit, assoc_hit, real_hit;
capacity.read(reinterpret_cast<char *>(&cap_hit), sizeof(cap_hit));
associative.read(reinterpret_cast<char *>(&assoc_hit), sizeof(cap_hit));
real.read(reinterpret_cast<char *>(&real_hit), sizeof(cap_hit));
// Check whether this is the first time this block has been
// accessed - if so, it is a compulsory miss.
boost::unordered_set<uint64_t>::const_iterator i = blocks.find(block_addr);
if(i == blocks.end()){
counts.compulsory++;
blocks.insert(block_addr);
}
else{
// If the access is not a hit, then this filter of if-else
// statements will determine what the type is.
if(cap_hit == misslevel){
// Capacity miss.
counts.capacity++;
}
else if(assoc_hit == misslevel){
// Mapping miss (i.e. due to associativity).
counts.mapping++;
}
else if(real_hit == misslevel){
// Replacement miss (i.e. due to replacement policy).
counts.replacement++;
}
else{
// Cache hit.
//
// NOTE(choudhury): this block is intentionally blank, as it
// could be used to create a report of a hit at that point
// in the trace, etc.
}
}
}
}
catch(TraceReader::End){}
// The total number of accesses in the trace minus
// the sum total of all misses gives the total number of hits.
const uint64_t num_hits = trace_size - (counts.compulsory + counts.capacity + counts.mapping + counts.replacement);
// Write a report on stdout.
std::cout << "Compulsory: " << counts.compulsory << std::endl
<< "Capacity: " << counts.capacity << std::endl
<< "Mapping: " << counts.mapping << std::endl
<< "Replacement: " << counts.replacement << std::endl
<< "Hits: " << num_hits << std::endl;
return 0;
}
| 34.73743
| 117
| 0.527822
|
ronichoudhury
|
a90a90460c8d2189a6b1d7b148fe019aed7c9231
| 2,445
|
hpp
|
C++
|
testspr/singleton.hpp
|
thinkoid/Sprout
|
a5a5944bb1779d3bb685087c58c20a4e18df2f39
|
[
"BSL-1.0"
] | 4
|
2021-12-29T22:17:40.000Z
|
2022-03-23T11:53:44.000Z
|
dsp/lib/sprout/testspr/singleton.hpp
|
TheSlowGrowth/TapeLooper
|
ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264
|
[
"MIT"
] | 16
|
2021-10-31T21:41:09.000Z
|
2022-01-22T10:51:34.000Z
|
testspr/singleton.hpp
|
thinkoid/Sprout
|
a5a5944bb1779d3bb685087c58c20a4e18df2f39
|
[
"BSL-1.0"
] | null | null | null |
/*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef TESTSPR_SINGLETON_HPP
#define TESTSPR_SINGLETON_HPP
#include <sprout/config.hpp>
#include <sprout/utility/noncopyable.hpp>
#include <sprout/assert.hpp>
namespace testspr {
//
// singleton_module
//
class singleton_module
: public sprout::noncopyable
{
private:
static inline SPROUT_NON_CONSTEXPR bool& get_lock() {
static bool lock = false;
return lock;
}
public:
static inline SPROUT_NON_CONSTEXPR void lock() {
get_lock() = true;
}
static inline SPROUT_NON_CONSTEXPR void unlock() {
get_lock() = false;
}
static inline SPROUT_NON_CONSTEXPR bool is_locked() {
return get_lock();
}
};
namespace detail {
template<typename T>
class singleton_wrapper
: public T
{
public:
static bool m_is_destroyed;
public:
~singleton_wrapper() {
m_is_destroyed = true;
}
};
template<typename T>
bool testspr::detail::singleton_wrapper<T>::m_is_destroyed = false;
} // namespace detail
//
// singleton
//
template<typename T>
class singleton
: public testspr::singleton_module
{
public:
typedef T instance_type;
private:
static instance_type& instance;
private:
static inline SPROUT_NON_CONSTEXPR void use(const instance_type&) {}
static inline SPROUT_NON_CONSTEXPR instance_type& get_instance() {
static detail::singleton_wrapper<instance_type> t;
SPROUT_ASSERT(!testspr::detail::singleton_wrapper<instance_type>::m_is_destroyed);
use(instance);
return static_cast<instance_type&>(t);
}
public:
static inline SPROUT_NON_CONSTEXPR instance_type& get_mutable_instance() {
SPROUT_ASSERT(!is_locked());
return get_instance();
}
static inline SPROUT_NON_CONSTEXPR instance_type const& get_const_instance() {
return get_instance();
}
static inline SPROUT_NON_CONSTEXPR bool is_destroyed() {
return testspr::detail::singleton_wrapper<instance_type>::m_is_destroyed;
}
};
template<typename T>
T& singleton<T>::instance = testspr::singleton<T>::get_instance();
} // namespace testspr
#endif // #ifndef TESTSPR_SINGLETON_HPP
| 26.868132
| 85
| 0.690798
|
thinkoid
|
a90b1792951d132fe2e1862648695e4798798c98
| 6,444
|
cpp
|
C++
|
ares/ws/apu/io.cpp
|
CasualPokePlayer/ares
|
58690cd5fc7bb6566c22935c5b80504a158cca29
|
[
"BSD-3-Clause"
] | 153
|
2020-07-25T17:55:29.000Z
|
2021-10-01T23:45:01.000Z
|
ares/ws/apu/io.cpp
|
CasualPokePlayer/ares
|
58690cd5fc7bb6566c22935c5b80504a158cca29
|
[
"BSD-3-Clause"
] | 245
|
2021-10-08T09:14:46.000Z
|
2022-03-31T08:53:13.000Z
|
ares/ws/apu/io.cpp
|
CasualPokePlayer/ares
|
58690cd5fc7bb6566c22935c5b80504a158cca29
|
[
"BSD-3-Clause"
] | 44
|
2020-07-25T08:51:55.000Z
|
2021-09-25T16:09:01.000Z
|
auto APU::readIO(n16 address) -> n8 {
n8 data;
switch(address) {
case 0x004a ... 0x004c: //SDMA_SRC
data = dma.state.source.byte(address - 0x004a);
break;
case 0x004e ... 0x0050: //SDMA_LEN
data = dma.state.length.byte(address - 0x004e);
break;
case 0x0052: //SDMA_CTRL
data.bit(0,1) = dma.io.rate;
data.bit(2) = dma.io.unknown;
data.bit(3) = dma.io.loop;
data.bit(4) = dma.io.target;
data.bit(6) = dma.io.direction;
data.bit(7) = dma.io.enable;
break;
case 0x006a: //SND_HYPER_CTRL
data.bit(0,1) = channel5.io.volume;
data.bit(2,3) = channel5.io.scale;
data.bit(4,6) = channel5.io.speed;
data.bit(7) = channel5.io.enable;
break;
case 0x006b: //SND_HYPER_CHAN_CTRL
data.bit(0,3) = channel5.io.unknown;
data.bit(5) = channel5.io.leftEnable;
data.bit(6) = channel5.io.rightEnable;
break;
case 0x0080 ... 0x0081: //SND_CH1_PITCH
data = channel1.io.pitch.byte(address - 0x0080);
break;
case 0x0082 ... 0x0083: //SND_CH2_PITCH
data = channel2.io.pitch.byte(address - 0x0082);
break;
case 0x0084 ... 0x0085: //SND_CH3_PITCH
data = channel3.io.pitch.byte(address - 0x0084);
break;
case 0x0086 ... 0x0087: //SND_CH4_PITCH
data = channel4.io.pitch.byte(address - 0x0086);
break;
case 0x0088: //SND_CH1_VOL
data.bit(0,3) = channel1.io.volumeRight;
data.bit(4,7) = channel1.io.volumeLeft;
break;
case 0x0089: //SND_CH2_VOL
data.bit(0,3) = channel2.io.volumeRight;
data.bit(4,7) = channel2.io.volumeLeft;
break;
case 0x008a: //SND_CH3_VOL
data.bit(0,3) = channel3.io.volumeRight;
data.bit(4,7) = channel3.io.volumeLeft;
break;
case 0x008b: //SND_CH4_VOL
data.bit(0,3) = channel4.io.volumeRight;
data.bit(4,7) = channel4.io.volumeLeft;
break;
case 0x008c: //SND_SWEEP_VALUE
data = channel3.io.sweepValue;
break;
case 0x008d: //SND_SWEEP_TIME
data = channel3.io.sweepTime;
break;
case 0x008e: //SND_NOISE
data.bit(0,2) = channel4.io.noiseMode;
data.bit(3) = 0; //noiseReset always reads as zero
data.bit(4) = channel4.io.noiseUpdate;
break;
case 0x008f: //SND_WAVE_BASE
data = io.waveBase;
break;
case 0x0090: //SND_CTRL
data.bit(0) = channel1.io.enable;
data.bit(1) = channel2.io.enable;
data.bit(2) = channel3.io.enable;
data.bit(3) = channel4.io.enable;
data.bit(5) = channel2.io.voice;
data.bit(6) = channel3.io.sweep;
data.bit(7) = channel4.io.noise;
break;
case 0x0091: //SND_OUTPUT
data.bit(0) = io.speakerEnable;
data.bit(1,2) = io.speakerShift;
data.bit(3) = io.headphonesEnable;
data.bit(7) = io.headphonesConnected;
break;
case 0x0092 ... 0x0093: //SND_RANDOM
data = channel4.state.noiseLFSR.byte(address - 0x0092);
break;
case 0x0094: //SND_VOICE_CTRL
data.bit(0,1) = channel2.io.voiceEnableRight;
data.bit(2,3) = channel2.io.voiceEnableLeft;
break;
case 0x0095: //SND_HYPERVOICE
data = channel5.state.data;
break;
case 0x009e: //SND_VOLUME
if(!SoC::ASWAN()) {
data.bit(0,1) = io.masterVolume;
}
break;
}
return data;
}
auto APU::writeIO(n16 address, n8 data) -> void {
switch(address) {
case 0x004a ... 0x004c: //SDMA_SRC
dma.io.source.byte(address - 0x004a) = data;
break;
case 0x004e ... 0x0050: //SDMA_LEN
dma.io.length.byte(address - 0x004e) = data;
break;
case 0x0052: { //SDMA_CTRL
bool trigger = !dma.io.enable && data.bit(7);
dma.io.rate = data.bit(0,1);
dma.io.unknown = data.bit(2);
dma.io.loop = data.bit(3);
dma.io.target = data.bit(4);
dma.io.direction = data.bit(6);
dma.io.enable = data.bit(7);
if(trigger) {
dma.state.source = dma.io.source;
dma.state.length = dma.io.length;
}
} break;
case 0x006a: //SND_HYPER_CTRL
channel5.io.volume = data.bit(0,1);
channel5.io.scale = data.bit(2,3);
channel5.io.speed = data.bit(4,6);
channel5.io.enable = data.bit(7);
break;
case 0x006b: //SND_HYPER_CHAN_CTRL
channel5.io.unknown = data.bit(0,3);
channel5.io.leftEnable = data.bit(5);
channel5.io.rightEnable = data.bit(6);
break;
case 0x0080 ... 0x0081: //SND_CH1_PITCH
channel1.io.pitch.byte(address - 0x0080) = data;
break;
case 0x0082 ... 0x0083: //SND_CH2_PITCH
channel2.io.pitch.byte(address - 0x0082) = data;
break;
case 0x0084 ... 0x0085: //SND_CH3_PITCH
channel3.io.pitch.byte(address - 0x0084) = data;
break;
case 0x0086 ... 0x0087: //SND_CH4_PITCH
channel4.io.pitch.byte(address - 0x0086) = data;
break;
case 0x0088: //SND_CH1_VOL
channel1.io.volumeRight = data.bit(0,3);
channel1.io.volumeLeft = data.bit(4,7);
break;
case 0x0089: //SND_CH2_VOL
channel2.io.volumeRight = data.bit(0,3);
channel2.io.volumeLeft = data.bit(4,7);
break;
case 0x008a: //SND_CH3_VOL
channel3.io.volumeRight = data.bit(0,3);
channel3.io.volumeLeft = data.bit(4,7);
break;
case 0x008b: //SND_CH4_VOL
channel4.io.volumeRight = data.bit(0,3);
channel4.io.volumeLeft = data.bit(4,7);
break;
case 0x008c: //SND_SWEEP_VALUE
channel3.io.sweepValue = data;
break;
case 0x008d: //SND_SWEEP_TIME
channel3.io.sweepTime = data.bit(0,4);
break;
case 0x008e: //SND_NOISE
channel4.io.noiseMode = data.bit(0,2);
channel4.io.noiseReset = data.bit(3);
channel4.io.noiseUpdate = data.bit(4);
break;
case 0x008f: //SND_WAVE_BASE
io.waveBase = data;
break;
case 0x0090: //SND_CTRL
channel1.io.enable = data.bit(0);
channel2.io.enable = data.bit(1);
channel3.io.enable = data.bit(2);
channel4.io.enable = data.bit(3);
channel2.io.voice = data.bit(5);
channel3.io.sweep = data.bit(6);
channel4.io.noise = data.bit(7);
break;
case 0x0091: //SND_OUTPUT
io.speakerEnable = data.bit(0);
io.speakerShift = data.bit(1,2);
io.headphonesEnable = data.bit(3);
break;
case 0x0094: //SND_VOICE_CTRL
channel2.io.voiceEnableRight = data.bit(0,1);
channel2.io.voiceEnableLeft = data.bit(2,3);
break;
case 0x009e: //SND_VOLUME
if(!SoC::ASWAN()) {
io.masterVolume = data.bit(0,1);
ppu.updateIcons();
}
break;
}
return;
}
| 25.270588
| 59
| 0.624767
|
CasualPokePlayer
|
a915359fe2da71a4df880b6f0250201f035d0e6e
| 252
|
cpp
|
C++
|
010.cpp
|
LeeYiyuan/projecteuler
|
81a0b65f73b47fbb9bfe99cb5ff72da7e0ba0d74
|
[
"MIT"
] | null | null | null |
010.cpp
|
LeeYiyuan/projecteuler
|
81a0b65f73b47fbb9bfe99cb5ff72da7e0ba0d74
|
[
"MIT"
] | null | null | null |
010.cpp
|
LeeYiyuan/projecteuler
|
81a0b65f73b47fbb9bfe99cb5ff72da7e0ba0d74
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <cstdint>
#include "prime_util.h"
int main()
{
std::vector<int> primes = util::get_primes(1999999);
uint64_t sum = 0;
for (int &prime : primes)
sum += prime;
std::cout << sum;
}
| 15.75
| 56
| 0.607143
|
LeeYiyuan
|
a91543c6029d3d3765597e5a0d570b602ed8a41e
| 2,457
|
cpp
|
C++
|
widgets/demos/ex-tree-model/main.cpp
|
sfaure-witekio/qt-training-material
|
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
|
[
"BSD-3-Clause"
] | 16
|
2017-01-11T17:28:03.000Z
|
2021-09-27T16:12:01.000Z
|
widgets/demos/ex-tree-model/main.cpp
|
sfaure-witekio/qt-training-material
|
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
|
[
"BSD-3-Clause"
] | null | null | null |
widgets/demos/ex-tree-model/main.cpp
|
sfaure-witekio/qt-training-material
|
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
|
[
"BSD-3-Clause"
] | 4
|
2017-03-17T02:44:32.000Z
|
2021-01-22T07:57:34.000Z
|
/*************************************************************************
*
* Copyright (c) 2016 The Qt Company
* All rights reserved.
*
* See the LICENSE.txt file shipped along with this file for the license.
*
*************************************************************************/
#include <QtWidgets>
#include "node.h"
#include "readonlymodel.h"
#include "editablemodel.h"
#include "insertremovemodel.h"
#include "lazymodel.h"
#include "dndmodel.h"
Node *createData() {
Node *root = new Node("Root");
for(int i=0; i<10; i++) {
Node *node1 = new Node(QString("Item %1").arg(i), root);
for(int ii=0; ii<5; ii++) {
Node *node2 = new Node(QString("Item %1/%2").arg(i).arg(ii), node1);
for(int iii=0; iii<3; iii++) {
new Node(QString("Item %1/%2/%3").arg(i).arg(ii).arg(iii), node2);
}
}
}
return root;
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
// [Enable for ReadOnlyModel]
// ReadOnlyModel *model = new ReadOnlyModel();
// [Enable for EditableModel]
// EditableModel *model = new EditableModel();
// [Enable for InsertRemoveModel]
// InsertRemoveModel *model = new InsertRemoveModel();
// [Enable for LazyModel]
// LazyModel *model = new LazyModel();
// [Enable for DndModel]
DndModel *model = new DndModel();
Node *root = createData();
model->setRootNode(root);
// [Enable for InsertRemoveModel]
// model->insertNode(root, 2, new Node("Inserted", root));
// model->removeNode(root->children.value(1));
QWidget window;
QGridLayout *layout = new QGridLayout(&window);
QListView *listView = new QListView(&window);
listView->setModel(model);
QTableView *tableView = new QTableView(&window);
tableView->setModel(model);
QTreeView *treeView = new QTreeView(&window);
treeView->setModel(model);
// [Enable for DndModel]
listView->setDragDropMode(QAbstractItemView::DragDrop);
tableView->setDragDropMode(QAbstractItemView::DragDrop);
treeView->setDragDropMode(QAbstractItemView::DragDrop);
layout->addWidget(new QLabel("QListView"), 0, 0);
layout->addWidget(listView, 1, 0);
layout->addWidget(new QLabel("QTableView"), 0, 1);
layout->addWidget(tableView, 1, 1);
layout->addWidget(new QLabel("QTreeView"), 0, 2);
layout->addWidget(treeView, 1, 2);
window.show();
return app.exec();
}
| 27.920455
| 82
| 0.597884
|
sfaure-witekio
|
a918dc5ea37cbd47854c459685e7b760b959ab5f
| 2,422
|
cpp
|
C++
|
Graph/FloodFill_DFS.cpp
|
scortier/DSA-Complete-Sheet
|
925a5cb148d9addcb32192fe676be76bfb2915c7
|
[
"MIT"
] | 1
|
2021-07-20T06:08:26.000Z
|
2021-07-20T06:08:26.000Z
|
Graph/FloodFill_DFS.cpp
|
scortier/DSA-Complete-Sheet
|
925a5cb148d9addcb32192fe676be76bfb2915c7
|
[
"MIT"
] | null | null | null |
Graph/FloodFill_DFS.cpp
|
scortier/DSA-Complete-Sheet
|
925a5cb148d9addcb32192fe676be76bfb2915c7
|
[
"MIT"
] | null | null | null |
// QUARANTINE DAYS..;)
//image is made up of pixels(box) so tis like ek block ko bhara aur vo continue row
//ya column ko fill karta rahega jab tak koi restriction na ho.
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define test long long int tt;cin>>tt;while(tt--)
#define rep(i,a,b) for(long long int i=a;i<b;i++)
#define rev(i,a,b) for(long long int i=b-1;i>=a;i--)
#define reep(i,a,b) for(long long int i=a;i<=b;i++)
#define ll long long int
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define MOD 1000000007
#define PI acos(-1.0)
#define assign(x,val) memset(x,val,sizeof(x))
#define prec(val, dig) fixed << setprecision(dig) << val
#define vec(vct) vector < ll > vct
#define vecpi(vct) vector < pair < ll, ll > > vct
#define pi pair < ll , ll >
#define lower(str) transform(str.begin(), str.end(), str.begin(), ::tolower);
#define upper(str) transform(str.begin(), str.end(), str.begin(), ::toupper);
#define mk(arr,n,type) type *arr=new type[n];
const int maxm = 2e6 + 10;
void fast() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
/**********====================########################=================***********/
int r, c;
void print(char mat[][50]) {
rep(i, 0, r) {
rep(j, 0, c) {
cout << mat[i][j];
}
cout << endl;
}
cout << endl;
}
//Recursion=DFS
//'.' is replaced by 'R' ie Red.
void floofill(char mat[][50], int i, int j, char ch, char color) //konse cell p color drop karna hai and konse char ko replace krna hai.
{
//base case - boundary & matrix k andar rehna hai
//and agr . k alawa koi bhi operator aya toh matrix k anadar return hona hai.
if (i < 0 || j < 0 || i >= r || j >= c || mat[i][j] != ch)
return; //vha p color fill nhi karna hai
mat [i][j] = color; //on right cell color filling
//then call on neighbouring cell
//call to fill the color on neighbouring cells
floofill(mat, i + 1, j, ch, color);
floofill(mat, i, j + 1, ch, color);
floofill(mat, i - 1, j, ch, color);
floofill(mat, i, j - 1, ch, color);
}
int32_t main()
{
fast();
char mat[50][50];
cin >> r >> c;
rep(i, 0, r) {
rep(j, 0, c) {
cin >> mat[i][j];
}
}
print(mat);
floofill(mat, 8, 13, '.', 'R');
print(mat);
return 0;
}
| 29.536585
| 136
| 0.586292
|
scortier
|
a91f7f98296d79d8827283465caf618fb3a7f2e5
| 4,459
|
hpp
|
C++
|
include/lbann/data_readers/data_reader_multi_images.hpp
|
andy-yoo/lbann-andy
|
237c45c392e7a5548796ac29537ab0a374e7e825
|
[
"Apache-2.0"
] | null | null | null |
include/lbann/data_readers/data_reader_multi_images.hpp
|
andy-yoo/lbann-andy
|
237c45c392e7a5548796ac29537ab0a374e7e825
|
[
"Apache-2.0"
] | null | null | null |
include/lbann/data_readers/data_reader_multi_images.hpp
|
andy-yoo/lbann-andy
|
237c45c392e7a5548796ac29537ab0a374e7e825
|
[
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2016, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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.
//
// data_reader_multi_images .hpp .cpp - generic data reader class for datasets
// employing multiple images per sample
////////////////////////////////////////////////////////////////////////////////
#ifndef DATA_READER_MULTI_IMAGES_HPP
#define DATA_READER_MULTI_IMAGES_HPP
#include "data_reader_imagenet.hpp"
#include "cv_process.hpp"
#include <vector>
#include <string>
#include <utility>
#include <iostream>
namespace lbann {
class data_reader_multi_images : public imagenet_reader {
public:
using img_src_t = std::vector<std::string>;
using sample_t = std::pair<img_src_t, label_t>;
data_reader_multi_images(bool shuffle) = delete;
data_reader_multi_images(const std::shared_ptr<cv_process>& pp, bool shuffle = true);
data_reader_multi_images(const data_reader_multi_images&);
data_reader_multi_images& operator=(const data_reader_multi_images&);
~data_reader_multi_images() override;
data_reader_multi_images* copy() const override {
return new data_reader_multi_images(*this);
}
std::string get_type() const override {
return "data_reader_multi_images";
}
/** Set up imagenet specific input parameters
* If argument is set to 0, then this method does not change the value of
* the corresponding parameter. However, width and height can only be both
* zero or both non-zero.
*/
void set_input_params(const int width, const int height, const int num_ch,
const int num_labels, const int num_img_srcs);
void set_input_params(const int width, const int height, const int num_ch,
const int num_labels) override;
// dataset specific functions
void load() override;
int get_linearized_data_size() const override {
return m_image_linearized_size * m_num_img_srcs;
}
const std::vector<int> get_data_dims() const override {
return {static_cast<int>(m_num_img_srcs)*m_image_num_channels, m_image_height, m_image_width};
}
/// Return the sample list of current minibatch
std::vector<sample_t> get_image_list_of_current_mb() const;
/// Allow read-only access to the entire sample list
const std::vector<sample_t>& get_image_list() const {
return m_image_list;
}
sample_t get_sample(size_t idx) const {
return m_image_list.at(idx);
}
/// The number of image sources or the number of siamese heads. e.g., 2;
/// this method is added to support data_store functionality
unsigned int get_num_img_srcs() const {
return m_num_img_srcs;
}
/// sets up a data_store.
void setup_data_store(model *m) override;
protected:
void set_defaults() override;
virtual std::vector<::Mat> create_datum_views(::Mat& X, const int mb_idx) const;
bool fetch_datum(CPUMat& X, int data_id, int mb_idx, int tid) override;
bool fetch_label(CPUMat& Y, int data_id, int mb_idx, int tid) override;
bool read_text_stream(std::istream& text_stream, std::vector<sample_t>& list);
bool load_list(const std::string file_name, std::vector<sample_t>& list,
const bool fetch_list_at_once = false);
protected:
std::vector<sample_t> m_image_list; ///< list of image files and labels
/// The number of image sources or the number of siamese heads. e.g., 2
unsigned int m_num_img_srcs;
};
} // namespace lbann
#endif // DATA_READER_MULTI_IMAGES_HPP
| 36.85124
| 98
| 0.704867
|
andy-yoo
|
a925dc760f8fe4cd129a75802cf84f5aee7060cc
| 1,511
|
cpp
|
C++
|
src/main.cpp
|
Floaddy/SFML-Nonogram
|
81dc67ccb378a5b251c4bb7b355b6f266d3c95a6
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
Floaddy/SFML-Nonogram
|
81dc67ccb378a5b251c4bb7b355b6f266d3c95a6
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
Floaddy/SFML-Nonogram
|
81dc67ccb378a5b251c4bb7b355b6f266d3c95a6
|
[
"MIT"
] | null | null | null |
#include <ctime>
#include <cstdlib>
#include <vector>
#include <SFML/Graphics.hpp>
#include "EventManager.hpp"
#include "FontManager.hpp"
#include "GameManager.hpp"
#include "LevelManager.hpp"
#include "ScreenManager.hpp"
#include "TextureManager.hpp"
#include "WindowManager.hpp"
#include "Header.hpp"
#define LEVEL "level1"
int main(int argc, char* argv[]) {
sf::RenderWindow window(
sf::VideoMode(800, 800),
"UltimatePix",
sf::Style::Titlebar | sf::Style::Close
);
window.setVerticalSyncEnabled(1);
WindowManager::getInstance().setWindow(&window);
GameManager::getInstance().loadGameAssets();
ScreenManager::getInstance().createScreens();
ScreenManager::getInstance().setActiveScreen(Screen::PlayScreen);
if (argc != 1) { // Carrega o nível se ele foi passado por parâmetro na execução
LevelManager::getInstance().loadCustomLevel(argv[1]);
GameManager::getInstance().generatePlayArea(argv[1]);
} else { // Carrega o nível do #define se nenhum parâmetro foi passado (tem que ser carregado no GameManager::getInstance().loadGameAssets())
GameManager::getInstance().generatePlayArea(LEVEL);
}
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
EventManager::getInstance().handleEvent(event);
}
window.clear();
ScreenManager::getInstance().drawScreen(*WindowManager::getInstance().getWindow());
window.display();
}
return 0;
}
| 26.982143
| 144
| 0.680344
|
Floaddy
|
a928eff0d85bc2db6606ee7b7badeb002a2891e8
| 2,393
|
hpp
|
C++
|
libraries/touchgfx_lib/Middlewares/ST/touchgfx/framework/include/touchgfx/transforms/TouchCalibration.hpp
|
LIGHT1213/H750_TouchGFX
|
d38acec2f2d28eaac07ef6316d6f008fb574488d
|
[
"MIT"
] | null | null | null |
libraries/touchgfx_lib/Middlewares/ST/touchgfx/framework/include/touchgfx/transforms/TouchCalibration.hpp
|
LIGHT1213/H750_TouchGFX
|
d38acec2f2d28eaac07ef6316d6f008fb574488d
|
[
"MIT"
] | null | null | null |
libraries/touchgfx_lib/Middlewares/ST/touchgfx/framework/include/touchgfx/transforms/TouchCalibration.hpp
|
LIGHT1213/H750_TouchGFX
|
d38acec2f2d28eaac07ef6316d6f008fb574488d
|
[
"MIT"
] | 1
|
2021-12-04T02:58:52.000Z
|
2021-12-04T02:58:52.000Z
|
/**
******************************************************************************
* This file is part of the TouchGFX 4.16.0 distribution.
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/**
* @file touchgfx/transforms/TouchCalibration.hpp
*
* Declares the touchgfx::TouchCalibration class.
*/
#ifndef TOUCHCALIBRATION_HPP
#define TOUCHCALIBRATION_HPP
#include <touchgfx/hal/Types.hpp>
namespace touchgfx
{
/**
* Calibrates a touch coordinate.
*
* Class TouchCalibraiton is responsible for translating coordinates (Point) based on
* matrix of calibration values.
*/
class TouchCalibration
{
public:
TouchCalibration()
{
matrix.Divider = 0;
}
/**
* Initializes the calibration matrix based on reference and measured values.
*
* @param ref Pointer to array of three reference points.
* @param scr Pointer to array of three measured points.
*/
static void setCalibrationMatrix(const Point* ref, const Point* scr);
/**
* Translates the specified point using the matrix. If matrix has not been initialized,
* p is not modified.
*
* @param [in,out] p The point to translate.
*/
static void translatePoint(Point& p);
private:
static int32_t muldiv(int32_t factor1, int32_t clzu1, int32_t factor2, int32_t divisor, int32_t& remainder);
static uint32_t muldivu(const uint32_t factor1, const uint32_t clzu1, const uint32_t factor2, const uint32_t clzu2, const uint32_t divisor, uint32_t& remainder);
static int32_t clzu(uint32_t x);
/**
* A matrix. See http://www.embedded.com/design/system-integration/4023968/How-To-Calibrate-Touch-Screens
* for calibration technique by Carlos E. Vidales.
*/
struct Matrix
{
int32_t An, Bn, Cn, Dn, En, Fn, Divider;
int32_t clzuAn, clzuBn, clzuDn, clzuEn;
};
typedef struct Matrix Matrix;
static Matrix matrix;
};
} // namespace touchgfx
#endif // TOUCHCALIBRATION_HPP
| 29.182927
| 165
| 0.638529
|
LIGHT1213
|
a92b3d12c2e111ff4f4f4a0dcc4147d57045b0d4
| 8,556
|
cc
|
C++
|
wrappers/8.1.1/vtkGeoSourceWrap.cc
|
axkibe/node-vtk
|
900ad7b5500f672519da5aa24c99aa5a96466ef3
|
[
"BSD-3-Clause"
] | 6
|
2016-02-03T12:48:36.000Z
|
2020-09-16T15:07:51.000Z
|
wrappers/8.1.1/vtkGeoSourceWrap.cc
|
axkibe/node-vtk
|
900ad7b5500f672519da5aa24c99aa5a96466ef3
|
[
"BSD-3-Clause"
] | 4
|
2016-02-13T01:30:43.000Z
|
2020-03-30T16:59:32.000Z
|
wrappers/8.1.1/vtkGeoSourceWrap.cc
|
axkibe/node-vtk
|
900ad7b5500f672519da5aa24c99aa5a96466ef3
|
[
"BSD-3-Clause"
] | null | null | null |
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>
#include "vtkObjectWrap.h"
#include "vtkGeoSourceWrap.h"
#include "vtkObjectBaseWrap.h"
#include "vtkGeoTreeNodeWrap.h"
#include "vtkCollectionWrap.h"
#include "vtkAbstractTransformWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkGeoSourceWrap::ptpl;
VtkGeoSourceWrap::VtkGeoSourceWrap()
{ }
VtkGeoSourceWrap::VtkGeoSourceWrap(vtkSmartPointer<vtkGeoSource> _native)
{ native = _native; }
VtkGeoSourceWrap::~VtkGeoSourceWrap()
{ }
void VtkGeoSourceWrap::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("vtkGeoSource").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("GeoSource").ToLocalChecked(), ConstructorGetter);
}
void VtkGeoSourceWrap::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void VtkGeoSourceWrap::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkObjectWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkObjectWrap::ptpl));
tpl->SetClassName(Nan::New("VtkGeoSourceWrap").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "GetRequestedNodes", GetRequestedNodes);
Nan::SetPrototypeMethod(tpl, "getRequestedNodes", GetRequestedNodes);
Nan::SetPrototypeMethod(tpl, "GetTransform", GetTransform);
Nan::SetPrototypeMethod(tpl, "getTransform", GetTransform);
Nan::SetPrototypeMethod(tpl, "Initialize", Initialize);
Nan::SetPrototypeMethod(tpl, "initialize", Initialize);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "RequestChildren", RequestChildren);
Nan::SetPrototypeMethod(tpl, "requestChildren", RequestChildren);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "ShutDown", ShutDown);
Nan::SetPrototypeMethod(tpl, "shutDown", ShutDown);
Nan::SetPrototypeMethod(tpl, "WorkerThread", WorkerThread);
Nan::SetPrototypeMethod(tpl, "workerThread", WorkerThread);
#ifdef VTK_NODE_PLUS_VTKGEOSOURCEWRAP_INITPTPL
VTK_NODE_PLUS_VTKGEOSOURCEWRAP_INITPTPL
#endif
ptpl.Reset( tpl );
}
void VtkGeoSourceWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
Nan::ThrowError("Cannot create instance of abstract class.");
return;
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void VtkGeoSourceWrap::GetRequestedNodes(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkGeoSourceWrap *wrapper = ObjectWrap::Unwrap<VtkGeoSourceWrap>(info.Holder());
vtkGeoSource *native = (vtkGeoSource *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkGeoTreeNodeWrap::ptpl))->HasInstance(info[0]))
{
VtkGeoTreeNodeWrap *a0 = ObjectWrap::Unwrap<VtkGeoTreeNodeWrap>(info[0]->ToObject());
vtkCollection * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetRequestedNodes(
(vtkGeoTreeNode *) a0->native.GetPointer()
);
VtkCollectionWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkCollectionWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkCollectionWrap *w = new VtkCollectionWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkGeoSourceWrap::GetTransform(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkGeoSourceWrap *wrapper = ObjectWrap::Unwrap<VtkGeoSourceWrap>(info.Holder());
vtkGeoSource *native = (vtkGeoSource *)wrapper->native.GetPointer();
vtkAbstractTransform * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTransform();
VtkAbstractTransformWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkAbstractTransformWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkAbstractTransformWrap *w = new VtkAbstractTransformWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkGeoSourceWrap::Initialize(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkGeoSourceWrap *wrapper = ObjectWrap::Unwrap<VtkGeoSourceWrap>(info.Holder());
vtkGeoSource *native = (vtkGeoSource *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Initialize(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkGeoSourceWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkGeoSourceWrap *wrapper = ObjectWrap::Unwrap<VtkGeoSourceWrap>(info.Holder());
vtkGeoSource *native = (vtkGeoSource *)wrapper->native.GetPointer();
vtkGeoSource * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
VtkGeoSourceWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkGeoSourceWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkGeoSourceWrap *w = new VtkGeoSourceWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkGeoSourceWrap::RequestChildren(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkGeoSourceWrap *wrapper = ObjectWrap::Unwrap<VtkGeoSourceWrap>(info.Holder());
vtkGeoSource *native = (vtkGeoSource *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkGeoTreeNodeWrap::ptpl))->HasInstance(info[0]))
{
VtkGeoTreeNodeWrap *a0 = ObjectWrap::Unwrap<VtkGeoTreeNodeWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->RequestChildren(
(vtkGeoTreeNode *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkGeoSourceWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkGeoSourceWrap *wrapper = ObjectWrap::Unwrap<VtkGeoSourceWrap>(info.Holder());
vtkGeoSource *native = (vtkGeoSource *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject());
vtkGeoSource * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObjectBase *) a0->native.GetPointer()
);
VtkGeoSourceWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkGeoSourceWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkGeoSourceWrap *w = new VtkGeoSourceWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkGeoSourceWrap::ShutDown(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkGeoSourceWrap *wrapper = ObjectWrap::Unwrap<VtkGeoSourceWrap>(info.Holder());
vtkGeoSource *native = (vtkGeoSource *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->ShutDown();
}
void VtkGeoSourceWrap::WorkerThread(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkGeoSourceWrap *wrapper = ObjectWrap::Unwrap<VtkGeoSourceWrap>(info.Holder());
vtkGeoSource *native = (vtkGeoSource *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->WorkerThread();
}
| 30.666667
| 107
| 0.720079
|
axkibe
|
a92ce641fc6c3c281c09f35fa8a6a24951b611be
| 861
|
cpp
|
C++
|
Applications/DataExplorer/VtkVis/QVtkDataSetMapper.cpp
|
OlafKolditz/ogs
|
e33400e1d9503d33ce80509a3441a873962ad675
|
[
"BSD-4-Clause"
] | 1
|
2016-09-02T11:49:52.000Z
|
2016-09-02T11:49:52.000Z
|
Applications/DataExplorer/VtkVis/QVtkDataSetMapper.cpp
|
OlafKolditz/ogs
|
e33400e1d9503d33ce80509a3441a873962ad675
|
[
"BSD-4-Clause"
] | 13
|
2015-01-09T13:08:57.000Z
|
2018-01-25T12:56:17.000Z
|
Applications/DataExplorer/VtkVis/QVtkDataSetMapper.cpp
|
OlafKolditz/ogs
|
e33400e1d9503d33ce80509a3441a873962ad675
|
[
"BSD-4-Clause"
] | 2
|
2019-08-13T13:37:03.000Z
|
2021-02-01T10:19:03.000Z
|
/**
* \file
* \author Lars Bilke
* \date 2010-11-12
* \brief Implementation of the QVtkDataSetMapper class.
*
* \copyright
* Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
// ** INCLUDES **
#include "QVtkDataSetMapper.h"
#include <vtkObjectFactory.h>
vtkStandardNewMacro(QVtkDataSetMapper);
QVtkDataSetMapper::QVtkDataSetMapper() : QObject(nullptr)
{
}
QVtkDataSetMapper::~QVtkDataSetMapper() = default;
void QVtkDataSetMapper::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
void QVtkDataSetMapper::SetScalarVisibility( bool on )
{
vtkDataSetMapper::SetScalarVisibility(static_cast<int>(on));
}
| 22.657895
| 76
| 0.704994
|
OlafKolditz
|
a92dd66336aef918fbb90ee121d16477f9d4df05
| 2,255
|
cpp
|
C++
|
utag/app/src/TagEditor/eventSaveTagButton.cpp
|
ronald112/utag
|
277af8cec0a2f429a76f52e322d423e3c5af595a
|
[
"MIT"
] | null | null | null |
utag/app/src/TagEditor/eventSaveTagButton.cpp
|
ronald112/utag
|
277af8cec0a2f429a76f52e322d423e3c5af595a
|
[
"MIT"
] | null | null | null |
utag/app/src/TagEditor/eventSaveTagButton.cpp
|
ronald112/utag
|
277af8cec0a2f429a76f52e322d423e3c5af595a
|
[
"MIT"
] | 1
|
2020-11-09T18:59:00.000Z
|
2020-11-09T18:59:00.000Z
|
#include "TagEditor.h"
#include <MiscHeaders.h>
void TagEditor::save() {
if ((QMessageBox::question(this, tr("uTag"),
tr("Do you really want to save changes?"),
QMessageBox::Ok | QMessageBox::Cancel),
QMessageBox::Ok) == QMessageBox::Ok) {
auto edit = m_audioFilesMap.find(m_curEditableFilePath.toStdString());
if (edit != m_audioFilesMap.end() && m_curSelectedRow != -1) {
if (m_lineEditArtist->isModified()) {
edit->second.saveFieldWithValue('a', m_lineEditArtist->text().toStdString());
}
if (m_lineEditTitle->isModified()) {
edit->second.saveFieldWithValue('t', m_lineEditTitle->text().toStdString());
}
if (m_lineEditAlbum->isModified()) {
edit->second.saveFieldWithValue('A', m_lineEditAlbum->text().toStdString());
}
if (m_lineEditGenre->isModified()) {
edit->second.saveFieldWithValue('g', m_lineEditGenre->text().toStdString());
}
if (m_lineEditYear->isModified()) {
string text = m_lineEditYear->text().toStdString();
edit->second.saveFieldWithValue('y', text.size() == 0 ? "0" : text);
}
if (m_lineEditTrack->isModified()) {
string text = m_lineEditTrack->text().toStdString();
edit->second.saveFieldWithValue('T', text.size() == 0 ? "0" : text);
}
if (m_lineEditComment->isModified()) {
edit->second.saveFieldWithValue('c', m_lineEditComment->text().toStdString());
}
m_filesTable->removeRow(m_curSelectedRow);
m_audioFilesMap.erase(edit);
addItemToTableHandler(false, m_curEditableFilePath, tr(edit->second.fileName.c_str()));
m_editSongWidget->hide();
m_lineEditArtist->clear();
m_lineEditTitle->clear();
m_lineEditAlbum->clear();
m_lineEditGenre->clear();
m_lineEditFilePath->clear();
m_lineEditYear->clear();
m_lineEditTrack->clear();
m_lineEditComment->clear();
m_imageLabel->clear();
m_infoLabel->show();
}
}
}
| 43.365385
| 99
| 0.564967
|
ronald112
|
a92e719895de35344ed7bfd628fce1c0c16dec71
| 230
|
cpp
|
C++
|
Signal Flow Simulation/truetime-2.0/examples/advanced_demos/RUNES_demo/node/nwrcvcode.cpp
|
raulest50/MicroGrid_GITCoD
|
885001242c8e581a6998afb4be2ae1c0b923e9c4
|
[
"MIT"
] | 1
|
2019-08-31T08:06:48.000Z
|
2019-08-31T08:06:48.000Z
|
Signal Flow Simulation/truetime-2.0/examples/advanced_demos/RUNES_demo/node/nwrcvcode.cpp
|
raulest50/MicroGrid_GITCoD
|
885001242c8e581a6998afb4be2ae1c0b923e9c4
|
[
"MIT"
] | null | null | null |
Signal Flow Simulation/truetime-2.0/examples/advanced_demos/RUNES_demo/node/nwrcvcode.cpp
|
raulest50/MicroGrid_GITCoD
|
885001242c8e581a6998afb4be2ae1c0b923e9c4
|
[
"MIT"
] | 1
|
2020-01-07T10:46:23.000Z
|
2020-01-07T10:46:23.000Z
|
double nwrcvcode(int seg, void* data) {
switch (seg) {
case 1:
// Let AODV layer deal with network message
ttCreateJob("AODVRcvTask");
return 0.0001;
case 2:
return FINISHED;
}
return FINISHED;
}
| 16.428571
| 47
| 0.621739
|
raulest50
|
a92f5030c2905728fd51c92885689e37f32ae210
| 1,337
|
cpp
|
C++
|
OpenGL_GLFW_Project/MathFunctions.cpp
|
millerf1234/OpenGL_Windows_Projects
|
26161ba3c820df366a83baaf6e2a275d874c6acd
|
[
"MIT"
] | null | null | null |
OpenGL_GLFW_Project/MathFunctions.cpp
|
millerf1234/OpenGL_Windows_Projects
|
26161ba3c820df366a83baaf6e2a275d874c6acd
|
[
"MIT"
] | null | null | null |
OpenGL_GLFW_Project/MathFunctions.cpp
|
millerf1234/OpenGL_Windows_Projects
|
26161ba3c820df366a83baaf6e2a275d874c6acd
|
[
"MIT"
] | null | null | null |
//Created by Forrest Miller on 7/24/2018
//See header file also for templated-function definitions
#include "MathFunctions.h"
namespace MathFunc {
//This function seems really inefficient since it looks like it has to recreate the twister each time it runs...
float getRandomInRangef(float min, float max) {
long long seed;
if (randomUseCustomSeed)
seed = customRandomSeed;
else
seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); //Gets a number representing the current time
std::mt19937 mt_rand(static_cast<unsigned int>(seed));
auto real_rand = std::bind(std::uniform_real_distribution<float>(min, max), mt_rand);
return real_rand();
}
int getRandomInRangei(int min, int max) {
long long seed;
if (randomUseCustomSeed)
seed = customRandomSeed;
else
seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); //Gets a number representing the current time
std::mt19937 mt_rand(static_cast<unsigned int>(seed));
auto int_rand = std::bind(std::uniform_int_distribution<int>(min, max), mt_rand);
return int_rand();
}
void setCustomRandomSeed(const long long seed) {
randomUseCustomSeed = true;
customRandomSeed = seed;
}
void unsetCustomRandomSeed() {
randomUseCustomSeed = false;
customRandomSeed = 0ll;
}
} //namespace MathFunc
| 31.093023
| 125
| 0.741212
|
millerf1234
|
a9322be321fbe86f168d33610b8de3366a2dfd4e
| 908
|
cpp
|
C++
|
07.ArraysQuestions/maxCircularSubarraySum.cpp
|
Sarthaknegigit/Open-DSAProblems
|
246166f4127210ccb82d9cb6f5f736148c0975a4
|
[
"MIT"
] | 1
|
2021-06-11T08:21:52.000Z
|
2021-06-11T08:21:52.000Z
|
07.ArraysQuestions/maxCircularSubarraySum.cpp
|
Sarthaknegigit/Open-DSAProblems
|
246166f4127210ccb82d9cb6f5f736148c0975a4
|
[
"MIT"
] | 1
|
2021-08-07T13:12:09.000Z
|
2021-08-07T13:12:09.000Z
|
07.ArraysQuestions/maxCircularSubarraySum.cpp
|
Sarthaknegigit/Open-DSAProblems
|
246166f4127210ccb82d9cb6f5f736148c0975a4
|
[
"MIT"
] | 10
|
2021-06-11T07:41:00.000Z
|
2022-01-18T08:24:45.000Z
|
#include <iostream>
using namespace std;
int kadane(int arr[], int n)
{
int sum = 0;
int maxSum = INT_MIN;
for (int i = 0; i < n; i++)
{
sum = sum + arr[i];
if (sum < 0)
{
sum = 0;
}
maxSum = max(sum, maxSum);
}
return maxSum;
}
int main()
{
int n;
cin >> n;
int A[n];
int totalSum = 0;
for (int i = 0; i < n; i++)
{
cin >> A[i];
totalSum += A[i];
}
int nonWrapSum;
int wrapSum;
// for nonWrapSum
nonWrapSum = kadane(A, n);
// for WrapSum
int B[n];
for (int i = 0; i < n; i++)
{
B[i] = A[i] * (-1);
}
int nonContributer = kadane(B, n) * (-1);
wrapSum = totalSum - (nonContributer); // Wrap Sum = Total sum - (Non contributing elemnts)
// final answer
int ans = max(wrapSum, nonWrapSum);
cout << ans << endl;
}
| 15.655172
| 96
| 0.460352
|
Sarthaknegigit
|
a939b2e612373d6c8de7a7410c951b75248ff5b3
| 1,060
|
cpp
|
C++
|
tests/test14.cpp
|
varnie/giraffe
|
0448536cdca5dad66110aa64fdf24688b2a0050a
|
[
"MIT"
] | null | null | null |
tests/test14.cpp
|
varnie/giraffe
|
0448536cdca5dad66110aa64fdf24688b2a0050a
|
[
"MIT"
] | 1
|
2020-06-16T14:25:17.000Z
|
2020-06-16T14:25:17.000Z
|
tests/test14.cpp
|
varnie/giraffe
|
0448536cdca5dad66110aa64fdf24688b2a0050a
|
[
"MIT"
] | null | null | null |
//
// Created by varnie on 2/23/16.
//
#include <gtest/gtest.h>
#include "../include/Giraffe.h"
TEST(StorageTest, EntityHasComponents) {
struct Foo {
Foo() { }
};
struct Bar {
Bar() { }
};
struct Fred {
Fred() { }
};
using StorageT = Giraffe::Storage<Foo, Bar, Fred>;
using EntityT = Giraffe::Entity<StorageT>;
StorageT storage;
EntityT e1 = storage.addEntity();
e1.addComponent<Foo>();
e1.addComponent<Bar>();
EXPECT_EQ(e1.hasComponent<Foo>(), true);
EXPECT_EQ(e1.hasComponent<Bar>(), true);
EXPECT_EQ(e1.hasComponent<Fred>(), false);
//now add that absent component
e1.addComponent<Fred>();
EXPECT_EQ(e1.hasComponent<Fred>(), true);
//now remove some component, Fred
e1.removeComponent<Fred>();
EXPECT_EQ(e1.hasComponent<Fred>(), false);
//now remove entity
storage.removeEntity(e1);
EXPECT_EQ(e1.isValid(), false);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 20
| 54
| 0.615094
|
varnie
|
a93a0af8e1ba4f52236eb79e07de2a26657726fc
| 16,430
|
hpp
|
C++
|
include/sick_scan/tcp/SopasBase.hpp
|
Kaju-Bubanja/sick_scan2
|
9a518b8e88d8515e25168b1860e7bee3af79f1da
|
[
"Apache-2.0"
] | 123
|
2018-01-11T05:47:13.000Z
|
2022-03-03T04:24:24.000Z
|
include/sick_scan/tcp/SopasBase.hpp
|
Kaju-Bubanja/sick_scan2
|
9a518b8e88d8515e25168b1860e7bee3af79f1da
|
[
"Apache-2.0"
] | 142
|
2018-01-04T14:46:28.000Z
|
2022-02-28T09:57:32.000Z
|
include/sick_scan/tcp/SopasBase.hpp
|
Kaju-Bubanja/sick_scan2
|
9a518b8e88d8515e25168b1860e7bee3af79f1da
|
[
"Apache-2.0"
] | 107
|
2018-03-01T05:42:39.000Z
|
2022-03-15T08:06:59.000Z
|
//
// SopasBase.h
//
// Created on: 18.07.2011
// Author: sick
//
#ifndef SOPASBASE_H
#define SOPASBASE_H
#include "sick_scan/tcp/BasicDatatypes.hpp"
// #include "sick_scan/tcp/datatypes/Scan.hpp"
#include "sick_scan/tcp/interfaces/tcp.hpp"
#include "colaa.hpp"
#include "colab.hpp"
#include <map> // for std::map
#include "sick_scan/tcp/tools/Mutex.hpp"
namespace devices
{
class SopasEventMessage;
class SopasAnswer;
/**
* Class SopasBase encapsuls the communication to a sensor via SopasProtocol. It offers the functions:
* - invokeMethode
* - readVariable
* - writeVariable
* - (un)registerEvent
*
* Callback functions are used to inform you about incoming events (scans or eval cases).
*/
class SopasBase
{
public:
static const std::string EVENTNAME_SUBSCRIBE_EVALCASES;
static const std::string EVENTNAME_SUBSCRIBE_SCANS;
static const std::string METHODNAME_LOGIN;
static const std::string METHODNAME_LOGOUT;
static const std::string METHODNAME_SET_SCANCONFIG;
static const std::string METHODNAME_START_MEASURE;
static const std::string METHODNAME_STOP_MEASURE;
static const std::string VARIABLENAME_DEVICEIDENT;
static const std::string VARIABLENAME_SCANCONFIG;
static const std::string VARIABLENAME_DATAOUTPUTRANGE;
static const std::string VARIABLENAME_SCANDATACONFIG;
// sopas commands
static const std::string COMMAND_Read_Variable_ByIndex;
static const std::string COMMAND_Write_Variable_ByIndex;
static const std::string COMMAND_Invoke_Method_ByIndex;
static const std::string COMMAND_Method_Result_ByIndex;
static const std::string COMMAND_Register_Event_ByIndex;
static const std::string COMMAND_Send_Event_ByIndex; // receive data event
static const std::string COMMAND_Read_Variable_Answer;
static const std::string COMMAND_Write_Variable_Answer;
static const std::string COMMAND_Invoke_Method_Answer;
static const std::string COMMAND_Method_Result_Answer;
static const std::string COMMAND_Register_Event_Answer;
static const std::string COMMAND_Event_Acknowledge;
static const std::string COMMAND_Read_Variable_ByName;
static const std::string COMMAND_Write_Variable_ByName;
static const std::string COMMAND_Invoke_Method_ByName;
static const std::string COMMAND_Method_Result_ByName;
static const std::string COMMAND_Register_Event_ByName;
static const std::string COMMAND_Send_Event_ByName; // receive data event
static const UINT16 INDEX_DEVICE_IDENT;
enum SopasProtocol
{
CoLa_A, ///< Command Language ASCI
CoLa_B ///< Command Language binary
};
enum SopasEncoding
{
ByName, ///< read/write variable, invoke methods by name
ByIndex ///< read/write variable, invoke methods by index (indexes will be generated !!!)
};
/// types of answers of the sensor
enum SopasMessageType
{
MSG_UNKNOWN, ///< Unknown message
// MSG_READ_VARIABLE, ///< Read Variable
// MSG_WRITE_VARIABLE, ///< Write Variable
// MSG_INVOKE_METHOD, ///< Invoke Method
// MSG_METHOD_RESULT, ///< Method Result
// MSG_REGISTER_EVENT, ///< Register Event
MSG_SEND_EVENT, ///< Send Event
MSG_READ_VARIABLE_ANSWER, ///< Read Variable Answer
MSG_WRITE_VARIABLE_ANSWER, ///< Write Variable Answer
MSG_INVOKE_METHOD_ANSWER, ///< Invoke Method Answer
MSG_METHOD_RESULT_ANSWER, ///< Method Result Answer
MSG_REGISTER_EVENT_ANSWER, ///< Register Event Answer
MSG_EVENT_ACKNOWLEDGE, ///< Event Acknowledge -Answer to register event
MSG_ERROR
///< Error
};
typedef void (*DecoderFunction)(SopasEventMessage& frame); // Decoder for events
/// Default constructor.
SopasBase();
/// Destructor
virtual ~SopasBase();
/// Initialization
/**
* \brief
* \param protocol
* \param ipAddress IP-adress of the Scanner
* \param portNumber port for SOPAS comunication
* \param weWantScanData
* \param weWantFieldData
* \param readOnlyMode
* \param disconnectFunction Function to be called on disconnect events.
* \param obj = pointer to the object that holds the disconnectFunction
* \return
*/
virtual bool init(SopasProtocol protocol,
std::string ipAddress,
UINT16 portNumber,
bool weWantScanData,
bool weWantFieldData,
bool readOnlyMode,
Tcp::DisconnectFunction disconnectFunction,
void* obj);
/// Connects to a sensor via tcp and reads the device name.
bool connect();
/// Returns true if the tcp connection is established.
bool isConnected();
/** \brief Closes the connection to the LMS. This is the opposite of init().
*
* Switches this device from the CONNECTED state back in the
* CONSTRUCTED state.
*
* \return True if the device is now in the CONSTRUCTED state
*/
bool disconnect();
/**
* \brief Reads the scanner type and version variable from the sensor and stores it in the
* member variables. This is done always by name.
* \return true if no errors occurred.
*/
bool action_getScannerTypeAndVersion();
void setReadOnlyMode(bool mode);
bool isReadOnly();
/**
* @brief Invoke a method on the sensor.
* @param methodeName name of the method to call
* @param parameters byte buffer with parameter (NOTE: you have to fill this buffer with the correct protocol - cola-a or cola-b)
* @param parametersLength length of the byte buffer
* @param answer pointer to an answer message (NOTE: memory for this object will be allocated - free this after usage !!!)
* @return true if no errors occurred.
*/
bool invokeMethod(const std::string& methodeName, BYTE* parameters, UINT16 parametersLength, SopasAnswer*& answer);
/**
* @brief Invoke a method on the sensor.
* @param index index of the method to call
* @param parameters byte buffer with parameter (NOTE: you have to fill this buffer with the correct protocol - cola-a or cola-b)
* @param parametersLength length of the byte buffer
* @param answer pointer to an answer message (NOTE: memory for this object will be allocated - free this after usage !!!)
* @return true if no errors occurred.
*/
bool invokeMethod(UINT16 index, BYTE* parameters, UINT16 parametersLength, SopasAnswer*& answer);
/**
* @brief Reads a variable from the sensor by name.
* @param variableName name of the variable
* @param answer pointer to an answer message (NOTE: memory for this object will be allocated - free this after usage !!!)
* @return true if no errors occurred.
*/
bool readVariable(const std::string& variableName, SopasAnswer*& answer);
/**
* @brief Reads a variable from the sensor by index.
* @param index of the variable
* @param answer
* @return true if no errors occurred.
*/
bool readVariable(UINT16 index, SopasAnswer*& answer);
/**
* @brief Write a variable to the sensor by name.
* @param variableName name of the variable.
* @param parameters byte buffer with parameter (NOTE: you have to fill this buffer with the correct protocol - cola-a or cola-b)
* @param parametersLength length of the byte buffer
* @return true if no errors occurred.
*/
bool writeVariable(const std::string& variableName, BYTE* parameters, UINT16 parametersLength);
/**
* @brief Write a variable to the sensor by index.
* @param index of the variable
* @param parameters byte buffer with parameter (NOTE: you have to fill this buffer with the correct protocol - cola-a or cola-b)
* @param parametersLength length of the byte buffer
* @return true if no errors occurred.
*/
bool writeVariable(UINT16 index, BYTE* parameters, UINT16 parametersLength);
/**
* @brief Registers an event by name.
* @param eventName name of the event
* @return true if no errors occurred.
*/
bool registerEvent(const std::string& eventName);
/**
* @brief Registers an event by index.
* @param index of the event.
* @return true if no errors occurred.
*/
bool registerEvent(UINT16 index);
/**
* @brief Unregisters an event by name.
* @param eventName name of the event
* @return true if no errors occurred.
*/
bool unregisterEvent(const std::string& eventName);
/**
* @brief Unregisters an event by index.
* @param index of the event
* @return true if no errors occurred.
*/
bool unregisterEvent(UINT16 index);
/**
*
* @param decoderFunction
* @param eventName
*/
void setEventCallbackFunction(DecoderFunction decoderFunction, const std::string& eventName)
{
m_decoderFunctionMapByName[eventName] = decoderFunction;
}
/**
*
* @param decoderFunction
* @param eventIndex
*/
void setEventCallbackFunction(DecoderFunction decoderFunction, UINT16 eventIndex)
{
m_decoderFunctionMapByIndex[eventIndex] = decoderFunction;
}
double makeAngleValid(double angle);
const std::string& getScannerName() const { return m_scannerName; }
const std::string& getScannerVersion() const { return m_scannerVersion; }
// Convert a SOPAS error code to readable text
static std::string convertSopasErrorCodeToText(UINT16 errorCode);
protected:
enum SopasCommand
{
CMD_UNKNOWN = 0, ///< Unknown command
RI = 1, ///< Read Variable
WI = 2, ///< Write Variable
MI = 3, ///< Invoke Method
AI = 4, ///< Method Result
EI = 5, ///< Register Event
SI = 6, ///< Send Event
RA = 7, ///< Read Variable Answer
WA = 8, ///< Write Variable Answer
MA = 9, ///< Invoke Method Answer
AA = 10, ///< Method Result Answer
EA = 11, ///< Register Event Answer
SA = 12, ///< Event Acknowledge
RN = 20, ///< Read Variable (by name)
AN = 21, ///< Method Result (ny name)
SN = 22, ///< Send Event (by name, receive)
FA = 50
///< Error
};
enum State
{
/// Object has been constructed. Use init() to go into CONNECTED state.
CONSTRUCTED
/// Object is now connected. Use run() to go into RUNNING
/// state, or disconnect() to go back into CONSTRUCTED state.
,
CONNECTED
/// Object is connected and emitting data. Use stop() to go back into CONNECTED,
/// or disconnect() to go back into CONSTRUCTED state.
// , RUNNING
};
/**
* @brief Take answer from read thread and decode it.
* Waits for a certain answer by name. Event data (scans) are filtered and processed
* by read thread.
* @param cmd Waits for the answer to this command.
* @param name name of the method/variable.
* @param timeout in [ms]
* @param answer Pointer to answer. Will be filled if answer contains parameter.
* @return true if no error occurred.
*/
bool receiveAnswer(SopasCommand cmd, std::string name, UINT32 timeout, SopasAnswer*& answer);
bool receiveAnswer_CoLa_A(SopasCommand cmd, std::string name, UINT32 timeout, SopasAnswer*& answer );
bool receiveAnswer_CoLa_B(SopasCommand cmd, std::string name, UINT32 timeout, SopasAnswer*& answer );
bool receiveAnswer(SopasCommand cmd, UINT16 index, UINT32 timeout, SopasAnswer*& answer );
bool receiveAnswer_CoLa_A(SopasCommand cmd, UINT16 index, UINT32 timeout, SopasAnswer*& answer);
bool receiveAnswer_CoLa_B(SopasCommand cmd, UINT16 index, UINT32 timeout, SopasAnswer*& answer);
/**
* @brief Sends the content of the buffer via TCP to the sensor.
* @param buffer pointer to the buffer
* @param len length of buffer to be sent.
*/
void sendCommandBuffer(UINT8* buffer, UINT16 len);
SopasCommand colaA_decodeCommand(std::string* rxData);
/// Converts strings in sopas answer buffer to SopasCommand enum.
SopasCommand stringToSopasCommand(const std::string& cmdString);
std::string sopasCommandToString(SopasCommand cmd);
protected:
// Decoder functions that need to be overwritten by derived classes
virtual void evalCaseResultDecoder(SopasEventMessage& msg) = 0;
virtual void scanDataDecoder(SopasEventMessage& msg) = 0;
bool m_scanEventIsRegistered;
bool m_fieldEventIsRegistered;
bool m_weWantScanData; ///< Flag to enable/disable scan data reception
bool m_weWantFieldData; ///< Flag to enable/disable protection field data reception
/// Device info
State m_state;
std::string m_scannerName; ///< Read from scanner
std::string m_scannerVersion; ///< Read from scanner
bool m_beVerbose; // true = Show extended status traces
bool m_isLoggedIn;
private:
// TCP
bool openTcpConnection();
void closeTcpConnection();
/// Function that will be called on incomming data via tcp.
static void readCallbackFunctionS(void* obj, UINT8* buffer, UINT32& numOfBytes);
void readCallbackFunction(UINT8* buffer, UINT32& numOfBytes);
/// Depending on the protocol the start and end of a frame will be found.
SopasEventMessage findFrameInReceiveBuffer();
/// Reads one frame from receive buffer and decodes it.
void processFrame(SopasEventMessage& frame);
void processFrame_CoLa_A(SopasEventMessage& frame);
void processFrame_CoLa_B(SopasEventMessage& frame);
void copyFrameToResposeBuffer(UINT32 frameLength);
void removeFrameFromReceiveBuffer(UINT32 frameLength);
// SOPAS / Cola
SopasProtocol m_protocol; ///< Used protocol (ColaA oder ColaB)
SopasEncoding m_encoding; ///< ByName or ByIndex
void colaA_decodeScannerTypeAndVersion(std::string* rxData);
void colaB_decodeScannerTypeAndVersion(UINT8* buffer, UINT16 pos);
private:
typedef std::map<std::string, DecoderFunction> DecoderFunctionMapByName;
typedef std::map<UINT16, DecoderFunction> DecoderFunctionMapByIndex;
DecoderFunctionMapByName m_decoderFunctionMapByName;
DecoderFunctionMapByIndex m_decoderFunctionMapByIndex;
// DecoderFunction m_scanDecoderFunction;
// DecoderFunction m_evalCaseDecoderFunction;
typedef std::map<UINT16, std::string> IndexToNameMap;
IndexToNameMap m_indexToNameMap;
// Response buffer
UINT32 m_numberOfBytesInResponseBuffer; ///< Number of bytes in buffer
UINT8 m_responseBuffer[1024]; ///< Receive buffer for everything except scan data and eval case data.
Mutex m_receiveDataMutex; ///< Access mutex for buffer
// Receive buffer
UINT32 m_numberOfBytesInReceiveBuffer; ///< Number of bytes in buffer
UINT8 m_receiveBuffer[25000]; ///< Low-Level receive buffer for all data (25000 should be enough for NAV300 Events)
// TCP
Tcp m_tcp;
std::string m_ipAddress;
UINT16 m_portNumber;
bool m_readOnlyMode;
};
/// Class that represents a message that was sent by a sensor. (Event message)
class SopasEventMessage
{
public:
/// Default constructor
SopasEventMessage();
/// Destructor
~SopasEventMessage() {}
/**
* @brief Constructor. This class will only store a pointer to the byte buffer. It will not deallocate the
* memory. Please make sure that the buffer is not deallocated while you are working with this class.
* @param buffer byte buffer with the message (Sopas frame)
* @param protocol type of protocol (Cola-A, Cola-B)
* @param frameLength length of the frame
*/
SopasEventMessage(BYTE* buffer, SopasBase::SopasProtocol protocol, UINT32 frameLength);
SopasBase::SopasProtocol getProtocolType() const
{
return m_protocol;
}
SopasBase::SopasEncoding getEncodingType() const
{
return m_encoding;
}
SopasBase::SopasMessageType getMessageType() const
{
return m_messageType;
}
UINT32 size() const
{
return m_frameLength;
}
/// contains 's' + command string(2 byte) + content(payload length - 3)
UINT32 getPayLoadLength() const;
std::string getCommandString() const;
/// contains 's' + command string(2 byte) + content(payload length - 3)
BYTE* getPayLoad();
/// Returns the index of a variable (answer to read variable by index). In case of error a negative value will be returned
INT32 getVariableIndex();
/// Returns the name of a variable (answer to read variable by name). In case of error an empty value will be returned
std::string getVariableName();
bool isValid() const { return (m_buffer != NULL); }
private:
void detectEncoding();
void detectMessageType();
private:
BYTE* m_buffer;
SopasBase::SopasProtocol m_protocol;
UINT32 m_frameLength;
SopasBase::SopasEncoding m_encoding;
SopasBase::SopasMessageType m_messageType;
};
/// Class that encapsulates a buffer that was sent as return to a sync call. (variable / method)
class SopasAnswer
{
public:
/// Constructor. Copies the content of the answer into the buffer of this object.
SopasAnswer(const BYTE* answer, UINT32 answerLength);
/// Destructor. Frees the memory for the copied buffer.
~SopasAnswer();
BYTE* getBuffer() { return m_answerBuffer; }
UINT32 size() { return m_answerLength; }
bool isValid() { return (m_answerBuffer != NULL); }
private:
UINT32 m_answerLength;
BYTE* m_answerBuffer;
};
} // namespace devices
#endif // SOPASBASE_H
| 32.406312
| 130
| 0.741327
|
Kaju-Bubanja
|
a93bd6d1c92eed5587035482698de8c1943426bc
| 2,990
|
cpp
|
C++
|
vox.render/physics/joint/joint.cpp
|
SummerTree/DigitalVox4
|
2eb718abcaccc4cd1dde3b0f28090c197c1905d4
|
[
"MIT"
] | 8
|
2022-02-15T12:54:57.000Z
|
2022-03-30T16:35:58.000Z
|
vox.render/physics/joint/joint.cpp
|
yangfengzzz/DigitalArche
|
da6770edd4556a920b3f7298f38176107caf7e3a
|
[
"MIT"
] | null | null | null |
vox.render/physics/joint/joint.cpp
|
yangfengzzz/DigitalArche
|
da6770edd4556a920b3f7298f38176107caf7e3a
|
[
"MIT"
] | 1
|
2022-01-20T05:53:59.000Z
|
2022-01-20T05:53:59.000Z
|
// Copyright (c) 2022 Feng Yang
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include "joint.h"
#include "../collider.h"
namespace vox {
namespace physics {
void Joint::setActors(Collider *actor0, Collider *actor1) {
_nativeJoint->setActors(actor0->handle(), actor1->handle());
}
void Joint::setLocalPose(PxJointActorIndex::Enum actor, const Transform3F &localPose) {
const auto &p = localPose.translation();
const auto &q = localPose.orientation();
_nativeJoint->setLocalPose(actor, PxTransform(PxVec3(p.x, p.y, p.z), PxQuat(q.x, q.y, q.z, q.w)));
}
Transform3F Joint::localPose(PxJointActorIndex::Enum actor) const {
const auto pose = _nativeJoint->getLocalPose(actor);
Transform3F trans;
trans.setTranslation(Vector3F(pose.p.x, pose.p.y, pose.p.z));
trans.setOrientation(QuaternionF(pose.q.x, pose.q.y, pose.q.z, pose.q.w));
return trans;
}
Transform3F Joint::relativeTransform() const {
const auto pose = _nativeJoint->getRelativeTransform();
Transform3F trans;
trans.setTranslation(Vector3F(pose.p.x, pose.p.y, pose.p.z));
trans.setOrientation(QuaternionF(pose.q.x, pose.q.y, pose.q.z, pose.q.w));
return trans;
}
Vector3F Joint::relativeLinearVelocity() const {
const auto vel = _nativeJoint->getRelativeLinearVelocity();
return Vector3F(vel.x, vel.y, vel.z);
}
Vector3F Joint::relativeAngularVelocity() const {
const auto vel = _nativeJoint->getRelativeAngularVelocity();
return Vector3F(vel.x, vel.y, vel.z);
}
void Joint::setBreakForce(float force, float torque) {
_nativeJoint->setBreakForce(force, torque);
}
void Joint::getBreakForce(float &force, float &torque) const {
_nativeJoint->getBreakForce(force, torque);
}
void Joint::setConstraintFlags(PxConstraintFlags flags) {
_nativeJoint->setConstraintFlags(flags);
}
void Joint::setConstraintFlag(PxConstraintFlag::Enum flag, bool value) {
_nativeJoint->setConstraintFlag(flag, value);
}
PxConstraintFlags Joint::constraintFlags() const {
return _nativeJoint->getConstraintFlags();
}
void Joint::setInvMassScale0(float invMassScale) {
_nativeJoint->setInvMassScale0(invMassScale);
}
float Joint::invMassScale0() const {
return _nativeJoint->getInvMassScale0();
}
void Joint::setInvInertiaScale0(float invInertiaScale) {
_nativeJoint->setInvInertiaScale0(invInertiaScale);
}
float Joint::invInertiaScale0() const {
return _nativeJoint->getInvInertiaScale0();
}
void Joint::setInvMassScale1(float invMassScale) {
_nativeJoint->setInvMassScale1(invMassScale);
}
float Joint::invMassScale1() const {
return _nativeJoint->getInvMassScale1();
}
void Joint::setInvInertiaScale1(float invInertiaScale) {
_nativeJoint->setInvInertiaScale1(invInertiaScale);
}
float Joint::invInertiaScale1() const {
return _nativeJoint->getInvInertiaScale1();
}
}
}
| 29.313725
| 102
| 0.738796
|
SummerTree
|
a93c139c4281e7061148a5e515ea02d48cdb2483
| 2,989
|
cpp
|
C++
|
dynamic_programming/longest_increasing_subsequence.cpp
|
icbdubey/C-Plus-Plus
|
d51947a9d5a96695ea52db4394db6518d777bddf
|
[
"MIT"
] | 20,295
|
2016-07-17T06:29:04.000Z
|
2022-03-31T23:32:16.000Z
|
dynamic_programming/longest_increasing_subsequence.cpp
|
icbdubey/C-Plus-Plus
|
d51947a9d5a96695ea52db4394db6518d777bddf
|
[
"MIT"
] | 1,399
|
2017-06-02T05:59:45.000Z
|
2022-03-31T00:55:00.000Z
|
dynamic_programming/longest_increasing_subsequence.cpp
|
icbdubey/C-Plus-Plus
|
d51947a9d5a96695ea52db4394db6518d777bddf
|
[
"MIT"
] | 5,775
|
2016-10-14T08:10:18.000Z
|
2022-03-31T18:26:39.000Z
|
/**
* @file
* @brief Calculate the length of the [longest increasing
* subsequence](https://en.wikipedia.org/wiki/Longest_increasing_subsequence) in
* an array
*
* @details
* In computer science, the longest increasing subsequence problem is to find a
* subsequence of a given sequence in which the subsequence's elements are in
* sorted order, lowest to highest, and in which the subsequence is as long as
* possible. This subsequence is not necessarily contiguous, or unique. Longest
* increasing subsequences are studied in the context of various disciplines
* related to mathematics, including algorithmics, random matrix theory,
* representation theory, and physics. The longest increasing subsequence
* problem is solvable in time O(n log n), where n denotes the length of the
* input sequence.
*
* @author [Krishna Vedala](https://github.com/kvedala)
* @author [David Leal](https://github.com/Panquesito7)
*/
#include <cassert> /// for assert
#include <climits> /// for std::max
#include <iostream> /// for IO operations
#include <vector> /// for std::vector
/**
* @namespace dynamic_programming
* @brief Dynamic Programming algorithms
*/
namespace dynamic_programming {
/**
* @brief Calculate the longest increasing subsequence for the specified numbers
* @param a the array used to calculate the longest increasing subsequence
* @param n the size used for the arrays
* @returns the length of the longest increasing
* subsequence in the `a` array of size `n`
*/
uint64_t LIS(const std::vector<uint64_t> &a, const uint32_t &n) {
std::vector<int> lis(n);
for (int i = 0; i < n; ++i) {
lis[i] = 1;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (a[i] > a[j] && lis[i] < lis[j] + 1) {
lis[i] = lis[j] + 1;
}
}
}
int res = 0;
for (int i = 0; i < n; ++i) {
res = std::max(res, lis[i]);
}
return res;
}
} // namespace dynamic_programming
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
std::vector<uint64_t> a = {15, 21, 2, 3, 4, 5, 8, 4, 1, 1};
uint32_t n = a.size();
uint32_t result = dynamic_programming::LIS(a, n);
assert(result ==
5); ///< The longest increasing subsequence is `{2,3,4,5,8}`
std::cout << "Self-test implementations passed!" << std::endl;
}
/**
* @brief Main function
* @param argc commandline argument count (ignored)
* @param argv commandline array of arguments (ignored)
* @returns 0 on exit
*/
int main(int argc, char const *argv[]) {
uint32_t n = 0;
std::cout << "Enter size of array: ";
std::cin >> n;
std::vector<uint64_t> a(n);
std::cout << "Enter array elements: ";
for (int i = 0; i < n; ++i) {
std::cin >> a[i];
}
std::cout << "\nThe result is: " << dynamic_programming::LIS(a, n)
<< std::endl;
test(); // run self-test implementations
return 0;
}
| 30.191919
| 80
| 0.629642
|
icbdubey
|
a93e290ec4f0b51e7525528d63cd5724f974bc9f
| 1,176
|
hpp
|
C++
|
include/gridtools/stencil_composition/icosahedral_grids/backend_x86/iterate_domain_x86.hpp
|
mbianco/gridtools
|
1abef09881a31495a3d02a15d3fe21620c6dde98
|
[
"BSD-3-Clause"
] | null | null | null |
include/gridtools/stencil_composition/icosahedral_grids/backend_x86/iterate_domain_x86.hpp
|
mbianco/gridtools
|
1abef09881a31495a3d02a15d3fe21620c6dde98
|
[
"BSD-3-Clause"
] | null | null | null |
include/gridtools/stencil_composition/icosahedral_grids/backend_x86/iterate_domain_x86.hpp
|
mbianco/gridtools
|
1abef09881a31495a3d02a15d3fe21620c6dde98
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* GridTools
*
* Copyright (c) 2014-2019, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include <type_traits>
#include <utility>
#include "../../../common/defs.hpp"
#include "../../../common/host_device.hpp"
#include "../../iterate_domain_fwd.hpp"
#include "../iterate_domain.hpp"
namespace gridtools {
/**
* @brief iterate domain class for the Host backend
*/
template <typename IterateDomainArguments>
struct iterate_domain_x86 : iterate_domain<iterate_domain_x86<IterateDomainArguments>, IterateDomainArguments> {
template <class Arg>
GT_FORCE_INLINE iterate_domain_x86(Arg &&arg)
: iterate_domain<iterate_domain_x86<IterateDomainArguments>, IterateDomainArguments>(
std::forward<Arg>(arg)) {}
template <class Arg, class T>
static GT_FORCE_INLINE auto deref_impl(T &&ptr) GT_AUTO_RETURN(*ptr);
};
template <typename IterateDomainArguments>
struct is_iterate_domain<iterate_domain_x86<IterateDomainArguments>> : std::true_type {};
} // namespace gridtools
| 30.153846
| 116
| 0.69898
|
mbianco
|
a942f019ca762eb657e2bc15ba084139ad5a5e9f
| 705
|
cc
|
C++
|
dsfmapping/sensor/feature_map_io.cc
|
dustinksi/DsFMapping
|
474cdda0d9ff5e571f894f814d83ae49987e54dc
|
[
"Apache-2.0"
] | null | null | null |
dsfmapping/sensor/feature_map_io.cc
|
dustinksi/DsFMapping
|
474cdda0d9ff5e571f894f814d83ae49987e54dc
|
[
"Apache-2.0"
] | null | null | null |
dsfmapping/sensor/feature_map_io.cc
|
dustinksi/DsFMapping
|
474cdda0d9ff5e571f894f814d83ae49987e54dc
|
[
"Apache-2.0"
] | null | null | null |
/**
* @file feature_map_io.cc
* @author DustinKsi (dustinksi@126.com)
* @brief
* @version 0.1
* @date 2019-12-24
*
* @copyright Copyright (c) 2019
*
*/
#include "dsfmapping/sensor/feature_map_io.h"
namespace DsFMapping {
namespace Sensor {
bool feature_map_saver(Feature2DList& map_data, string& map_filename) {
fstream map_writer(map_filename, ios::out | ios::binary | ios::ate);
map_data.SerializePartialToOstream(&map_writer);
map_writer.close();
return true;
}
bool feature_map_loader(string& map_filename, Feature2DList* map_data) {
fstream map_reader(map_filename, ios::in | ios::binary);
map_data -> ParseFromIstream(&map_reader);
map_reader.close();
return true;
}
}
}
| 22.741935
| 72
| 0.726241
|
dustinksi
|
a94455b8a90f03f696f2a5e462c19c8d98cb9efd
| 7,515
|
cc
|
C++
|
gearbox/t/core/SchemaObject.t.cc
|
coryb/gearbox
|
88027f2f101c2d1fab16093928963052b9d3294d
|
[
"Artistic-1.0-Perl",
"BSD-3-Clause"
] | 3
|
2015-06-26T15:37:40.000Z
|
2016-05-22T07:42:39.000Z
|
gearbox/t/core/SchemaObject.t.cc
|
coryb/gearbox
|
88027f2f101c2d1fab16093928963052b9d3294d
|
[
"Artistic-1.0-Perl",
"BSD-3-Clause"
] | null | null | null |
gearbox/t/core/SchemaObject.t.cc
|
coryb/gearbox
|
88027f2f101c2d1fab16093928963052b9d3294d
|
[
"Artistic-1.0-Perl",
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2012, Yahoo! Inc. All rights reserved.
// Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
#include <tap/trivial.h>
#include <gearbox/core/Json.h>
#include <gearbox/core/JsonSchema.h>
#include <gearbox/core/logger.h>
using namespace Gearbox;
int main() {
chdir(TESTDIR);
TEST_START(59);
log_init("./unit.conf");
JsonSchema s;
Json j;
j.setSchema(&s);
// empty object, any properties
s.parse("{\"type\":\"object\"}");
NOTHROW( j.parse("{}") );
NOTHROW( j.parse("{\"key\":1}") );
// requires 1 key of type number
s.parse("{\"type\":\"object\",\"properties\":{\"key\":{\"type\":\"number\"}}}");
NOTHROW( j.parse("{\"key\":1}") );
THROWS( j.parse("{\"key\":\"string\"}"), "Json Exception: schema does not allow for type \"string\" at: [\"key\"]" );
THROWS( j.parse("{}"), "Json Exception: non-optional property \"key\" is missing" );
s.parse("{\"type\":\"object\",\"properties\":{\"key\":{\"type\":\"number\",\"optional\":true}}}");
NOTHROW( j.parse("{}") );
OK( ! j.hasKey("key") );
NOTHROW( j.parse("{\"key\":1}") );
OK( j.hasKey("key") );
THROWS( j.parse("{\"key\":\"string\"}"), "Json Exception: schema does not allow for type \"string\" at: [\"key\"]" );
s.parse("{\"type\":\"object\",\"properties\":{\"key\":{\"type\":\"number\",\"optional\":false}}}");
NOTHROW( j.parse("{\"key\":1}") );
THROWS( j.parse("{\"key\":\"string\"}"), "Json Exception: schema does not allow for type \"string\" at: [\"key\"]" );
THROWS( j.parse("{}"), "Json Exception: non-optional property \"key\" is missing" );
s.parse("{\"type\":\"object\",\"properties\":{\"key\":{\"type\":\"number\",\"default\":123}}}");
NOTHROW( j.parse("{}") );
IS( j["key"].as<double>(), 123 );
NOTHROW( j.parse("{\"key\":1}") );
IS( j["key"].as<double>(), 1 );
NOTHROW( j.parse("{\"key\":1.1234}") );
IS( j["key"].as<double>(), 1.1234 );
THROWS( j.parse("{\"key\":\"string\"}"), "Json Exception: schema does not allow for type \"string\" at: [\"key\"]" );
// set up object to have 2 keys, and "key" requires "otherkey"
s.parse("{\"type\":\"object\",\"properties\":{\"key\":{\"type\":\"number\",\"optional\":true,\"requires\":\"otherkey\"},\"otherkey\":{\"type\":\"string\",\"optional\":true}}}");
NOTHROW( j.parse("{}") );
// key not required
NOTHROW( j.parse("{\"otherkey\":\"string\"}" ) );
// err, otherkey is required if key is set
THROWS( j.parse("{\"key\":42}"),
"Json Exception: property \"key\" requires additional property \"otherkey\" to be set according to schema" );
// ok if both keys set
NOTHROW( j.parse("{\"otherkey\":\"string\",\"key\":24}" ) );
// now otherkey has default, so you can use "key" by itself, even those key requires otherkey
s.parse("{\"type\":\"object\",\"properties\":{\"key\":{\"type\":\"number\",\"optional\":true,\"requires\":\"otherkey\"},\"otherkey\":{\"type\":\"string\",\"optional\":true,\"default\":\"abc\"}}}");
NOTHROW( j.parse("{\"otherkey\":\"string\"}" ) );
NOTHROW( j.parse("{\"key\":42}") );
// verify the default value
IS( j["otherkey"].as<std::string>(), "abc" );
// test additionalProperties (as bool, allow any)
s.parse("{\"type\":\"object\",\"additionalProperties\":true}");
NOTHROW( j.parse("{}") );
NOTHROW( j.parse("{\"foo\":true}") );
NOTHROW( j.parse("{\"foo\":1}") );
NOTHROW( j.parse("{\"foo\":1.1}") );
NOTHROW( j.parse("{\"foo\":\"string\"}") );
NOTHROW( j.parse("{\"foo\":[]}") );
NOTHROW( j.parse("{\"foo\":{}}") );
NOTHROW( j.parse("{\"foo\":1,\"bar\":2}") );
// test additionalProperties (as bool false, allow none)
s.parse("{\"type\":\"object\",\"additionalProperties\":false}");
NOTHROW( j.parse("{}") );
THROWS( j.parse("{\"foo\":true}"), "Json Exception: invalid property \"foo\": schema allows for no properties" );
THROWS( j.parse("{\"foo\":1}"), "Json Exception: invalid property \"foo\": schema allows for no properties" );
THROWS( j.parse("{\"foo\":1.1}"), "Json Exception: invalid property \"foo\": schema allows for no properties" );
THROWS( j.parse("{\"foo\":\"string\"}"), "Json Exception: invalid property \"foo\": schema allows for no properties" );
THROWS( j.parse("{\"foo\":[]}"), "Json Exception: invalid property \"foo\": schema allows for no properties" );
THROWS( j.parse("{\"foo\":{}}"), "Json Exception: invalid property \"foo\": schema allows for no properties" );
THROWS( j.parse("{\"foo\":1,\"bar\":2}"), "Json Exception: invalid property \"foo\": schema allows for no properties" );
// test additionalProperties (as object, allow only ints)
s.parse("{\"type\":\"object\",\"additionalProperties\":{\"type\":\"integer\"}}");
NOTHROW( j.parse("{}") );
NOTHROW( j.parse("{\"foo\":1}") );
NOTHROW( j.parse("{\"foo\":1,\"bar\":2}") );
THROWS( j.parse("{\"foo\":1.1}"), "Json Exception: schema does not allow for type \"number\" at: [\"foo\"]" );
// object of objects
s.parse(
"{"
"\"type\":\"object\","
"\"properties\":{"
" \"A\":{"
" \"type\":\"object\","
" \"optional\":true,"
" \"requires\":\"B\","
" \"properties\":{"
" \"C\":{"
" \"type\":\"number\","
" \"optional\":true"
" },"
" \"D\":{"
" \"type\":\"any\","
" \"requires\":\"C\","
" \"optional\":true"
" },"
" \"E\":{"
" \"type\":\"object\","
" \"optional\":true,"
" \"additionalProperties\":{"
" \"type\":\"integer\""
" }"
" }"
" }"
" },"
" \"B\":{"
" \"type\":\"string\","
" \"optional\":true"
" }"
"}"
"}"
);
NOTHROW( j.parse("{}") );
NOTHROW( j.parse("{\"B\":\"value\"}") );
NOTHROW( j.parse("{\"A\":{\"C\":123},\"B\":\"value\"}") );
NOTHROW( j.parse("{\"A\":{\"C\":123,\"D\":true},\"B\":\"value\"}") );
NOTHROW( j.parse("{\"A\":{\"C\":123,\"D\":true,\"E\":{\"a\":1,\"b\":2,\"c\":3}},\"B\":\"value\"}") );
NOTHROW( j.parse("{\"A\":{\"C\":123,\"D\":true,\"E\":{}},\"B\":\"value\"}") );
THROWS( j.parse("{\"A\":{\"C\":123,\"D\":true,\"E\":{\"a\":1.1}},\"B\":\"value\"}"),
"Json Exception: schema does not allow for type \"number\" at: [\"A\"][\"E\"][\"a\"]" );
THROWS( j.parse("{\"A\":{\"C\":false,\"D\":true},\"B\":\"value\"}"),
"Json Exception: schema does not allow for type \"boolean\" at: [\"A\"][\"C\"]" );
THROWS( j.parse("{\"A\":{\"D\":true},\"B\":\"value\"}"),
"Json Exception: property \"D\" requires additional property \"C\" to be set according to schema at: [\"A\"]" );
THROWS( j.parse("{\"A\":{\"C\":123,\"D\":true}}"),
"Json Exception: property \"A\" requires additional property \"B\" to be set according to schema" );
s.parse("{\"type\":\"object\",\"properties\":{\"array\":{\"type\":\"array\",\"default\":[]}}}");
NOTHROW( j.parse("{}") );
IS( j.serialize(), "{\"array\":[]}" );
TEST_END;
}
| 45.271084
| 201
| 0.488756
|
coryb
|
a944e2f9cd384016998f8b90d8f03bcce737b4d1
| 9,486
|
hxx
|
C++
|
Modules/IO/RAW/include/itkRawImageIO.hxx
|
Kronephon/itktest
|
a34e46226638c08bba315a257e33550a68203d97
|
[
"Apache-2.0"
] | null | null | null |
Modules/IO/RAW/include/itkRawImageIO.hxx
|
Kronephon/itktest
|
a34e46226638c08bba315a257e33550a68203d97
|
[
"Apache-2.0"
] | null | null | null |
Modules/IO/RAW/include/itkRawImageIO.hxx
|
Kronephon/itktest
|
a34e46226638c08bba315a257e33550a68203d97
|
[
"Apache-2.0"
] | null | null | null |
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 itkRawImageIO_hxx
#define itkRawImageIO_hxx
#include "itkRawImageIO.h"
#include "itkIntTypes.h"
namespace itk
{
template< typename TPixel, unsigned int VImageDimension >
RawImageIO< TPixel, VImageDimension >::RawImageIO():
ImageIOBase()
{
this->SetNumberOfComponents(1);
this->SetPixelTypeInfo( static_cast<const PixelType *>(nullptr) );
this->SetNumberOfDimensions(VImageDimension);
for ( unsigned int idx = 0; idx < VImageDimension; ++idx )
{
m_Spacing.insert(m_Spacing.begin() + idx, 1.0);
m_Origin.insert(m_Origin.begin() + idx, 0.0);
}
m_HeaderSize = 0;
m_ManualHeaderSize = false;
// Left over from short reader
m_ImageMask = 0xffff;
m_ByteOrder = ImageIOBase::BigEndian;
m_FileDimensionality = 2;
m_FileType = Binary;
}
template< typename TPixel, unsigned int VImageDimension >
RawImageIO< TPixel, VImageDimension >::~RawImageIO()
{}
template< typename TPixel, unsigned int VImageDimension >
void RawImageIO< TPixel, VImageDimension >::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "ImageMask: " << m_ImageMask << std::endl;
os << indent << "FileDimensionality: " << m_FileDimensionality << std::endl;
}
template< typename TPixel, unsigned int VImageDimension >
SizeValueType RawImageIO< TPixel, VImageDimension >::GetHeaderSize()
{
std::ifstream file;
if ( m_FileName == "" )
{
itkExceptionMacro(<< "A FileName must be specified.");
}
if ( !m_ManualHeaderSize )
{
if ( m_FileType == ASCII )
{
return 0; //cannot determine it
}
this->ComputeStrides();
// make sure we figure out a filename to open
this->OpenFileForReading( file, m_FileName );
// Get the size of the header from the size of the image
file.seekg(0, std::ios::end);
m_HeaderSize = static_cast<SizeValueType>(
static_cast<typename ::itk::intmax_t>( file.tellg() )
- static_cast<typename ::itk::intmax_t>( this->m_Strides[m_FileDimensionality + 1] )
);
}
return m_HeaderSize;
}
template< typename TPixel, unsigned int VImageDimension >
void RawImageIO< TPixel, VImageDimension >
::SetHeaderSize(SizeValueType size)
{
if ( size != m_HeaderSize )
{
m_HeaderSize = size;
this->Modified();
}
m_ManualHeaderSize = true;
}
template< typename TPixel, unsigned int VImageDimension >
void RawImageIO< TPixel, VImageDimension >
::Read(void *buffer)
{
std::ifstream file;
// Open the file
this->OpenFileForReading( file, m_FileName );
this->ComputeStrides();
// Offset into file
SizeValueType streamStart = this->GetHeaderSize();
file.seekg( (OffsetValueType)streamStart, std::ios::beg );
if ( file.fail() )
{
itkExceptionMacro(<< "File seek failed");
}
const auto numberOfBytesToBeRead = static_cast< SizeValueType >( this->GetImageSizeInBytes() );
itkDebugMacro(<< "Reading " << numberOfBytesToBeRead << " bytes");
if ( m_FileType == Binary )
{
if ( !this->ReadBufferAsBinary(file, buffer, numberOfBytesToBeRead) )
{
itkExceptionMacro(<< "Read failed: Wanted "
<< numberOfBytesToBeRead
<< " bytes, but read "
<< file.gcount() << " bytes.");
}
}
else
{
this->ReadBufferAsASCII( file, buffer, this->GetComponentType(),
this->GetImageSizeInComponents() );
}
itkDebugMacro(<< "Reading Done");
#define itkReadRawBytesAfterSwappingMacro(StrongType, WeakType) \
( this->GetComponentType() == WeakType ) \
{ \
using InternalByteSwapperType = ByteSwapper< StrongType >; \
if ( m_ByteOrder == LittleEndian ) \
{ \
InternalByteSwapperType::SwapRangeFromSystemToLittleEndian( \
(StrongType *)buffer, this->GetImageSizeInComponents() ); \
} \
else if ( m_ByteOrder == BigEndian ) \
{ \
InternalByteSwapperType::SwapRangeFromSystemToBigEndian( \
(StrongType *)buffer, this->GetImageSizeInComponents() ); \
} \
}
// Swap bytes if necessary
if itkReadRawBytesAfterSwappingMacro(unsigned short, USHORT)
else if itkReadRawBytesAfterSwappingMacro(short, SHORT)
else if itkReadRawBytesAfterSwappingMacro(char, CHAR)
else if itkReadRawBytesAfterSwappingMacro(unsigned char, UCHAR)
else if itkReadRawBytesAfterSwappingMacro(unsigned int, UINT)
else if itkReadRawBytesAfterSwappingMacro(int, INT)
else if itkReadRawBytesAfterSwappingMacro(long, LONG)
else if itkReadRawBytesAfterSwappingMacro(unsigned long, ULONG)
else if itkReadRawBytesAfterSwappingMacro(float, FLOAT)
else if itkReadRawBytesAfterSwappingMacro(double, DOUBLE)
}
template< typename TPixel, unsigned int VImageDimension >
bool RawImageIO< TPixel, VImageDimension >
::CanWriteFile(const char *fname)
{
std::string filename(fname);
if ( filename == "" )
{
return false;
}
return true;
}
template< typename TPixel, unsigned int VImageDimension >
void RawImageIO< TPixel, VImageDimension >
::Write(const void *buffer)
{
std::ofstream file;
// Open the file
//
this->OpenFileForWriting( file, m_FileName );
// Set up for reading
this->ComputeStrides();
// Actually do the writing
//
if ( m_FileType == ASCII )
{
this->WriteBufferAsASCII( file, buffer, this->GetComponentType(),
this->GetImageSizeInComponents() );
}
else //binary
{
const SizeValueType numberOfBytes = this->GetImageSizeInBytes();
const SizeValueType numberOfComponents = this->GetImageSizeInComponents();
#define itkWriteRawBytesAfterSwappingMacro(StrongType, WeakType) \
( this->GetComponentType() == WeakType ) \
{ \
using InternalByteSwapperType = ByteSwapper< StrongType >; \
const SizeValueType numberOfPixels = numberOfBytes/(sizeof(StrongType)); \
if ( m_ByteOrder == LittleEndian ) \
{ \
StrongType *tempBuffer = new StrongType[numberOfPixels]; \
memcpy((char *)tempBuffer, buffer, numberOfBytes); \
InternalByteSwapperType::SwapRangeFromSystemToLittleEndian( \
(StrongType *)tempBuffer, numberOfComponents); \
file.write((char *)tempBuffer, numberOfBytes); \
delete[] tempBuffer; \
} \
else if ( m_ByteOrder == BigEndian ) \
{ \
StrongType *tempBuffer = new StrongType[numberOfPixels]; \
memcpy((char *)tempBuffer, buffer, numberOfBytes); \
InternalByteSwapperType::SwapRangeFromSystemToBigEndian( \
(StrongType *)tempBuffer, numberOfComponents); \
file.write((char *)tempBuffer, numberOfBytes); \
delete[] tempBuffer; \
} \
else \
{ \
file.write(static_cast< const char * >( buffer ), numberOfBytes); \
} \
}
// Swap bytes if necessary
if itkWriteRawBytesAfterSwappingMacro(unsigned short, USHORT)
else if itkWriteRawBytesAfterSwappingMacro(short, SHORT)
else if itkWriteRawBytesAfterSwappingMacro(char, CHAR)
else if itkWriteRawBytesAfterSwappingMacro(unsigned char, UCHAR)
else if itkWriteRawBytesAfterSwappingMacro(unsigned int, UINT)
else if itkWriteRawBytesAfterSwappingMacro(int, INT)
else if itkWriteRawBytesAfterSwappingMacro(long, LONG)
else if itkWriteRawBytesAfterSwappingMacro(unsigned long, ULONG)
else if itkWriteRawBytesAfterSwappingMacro(float, FLOAT)
else if itkWriteRawBytesAfterSwappingMacro(double, DOUBLE)
}
}
} // namespace itk
#endif
| 36.484615
| 97
| 0.589817
|
Kronephon
|
a9450e9d0ad7bda58e9854119446c6f5efe15ec3
| 8,348
|
cpp
|
C++
|
libnd4j/tests_cpu/layers_tests/ThreadsTests.cpp
|
bpossolo/deeplearning4j
|
722d5a052af17f19dcd42ef923b9a5b63ab2cbee
|
[
"Apache-2.0"
] | 13,006
|
2015-02-13T18:35:31.000Z
|
2022-03-18T12:11:44.000Z
|
libnd4j/tests_cpu/layers_tests/ThreadsTests.cpp
|
bpossolo/deeplearning4j
|
722d5a052af17f19dcd42ef923b9a5b63ab2cbee
|
[
"Apache-2.0"
] | 5,319
|
2015-02-13T08:21:46.000Z
|
2019-06-12T14:56:50.000Z
|
libnd4j/tests_cpu/layers_tests/ThreadsTests.cpp
|
bpossolo/deeplearning4j
|
722d5a052af17f19dcd42ef923b9a5b63ab2cbee
|
[
"Apache-2.0"
] | 4,719
|
2015-02-13T22:48:55.000Z
|
2022-03-22T07:25:36.000Z
|
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author raver119@gmail.com
//
#include "testlayers.h"
#include <ops/declarable/CustomOperations.h>
#include <loops/type_conversions.h>
#include <execution/Threads.h>
#include <chrono>
#include <execution/ThreadPool.h>
using namespace samediff;
using namespace sd;
using namespace sd::ops;
using namespace sd::graph;
class ThreadsTests : public testing::Test {
public:
ThreadsTests() {
nd4j_printf("\n","");
}
};
TEST_F(ThreadsTests, th_test_1) {
ASSERT_EQ(1, ThreadsHelper::numberOfThreads(6, 1023));
ASSERT_EQ(1, ThreadsHelper::numberOfThreads(6, 1024));
ASSERT_EQ(1, ThreadsHelper::numberOfThreads(6, 1026));
ASSERT_EQ(1, ThreadsHelper::numberOfThreads(6, 2043));
ASSERT_EQ(2, ThreadsHelper::numberOfThreads(6, 2048));
}
TEST_F(ThreadsTests, th_test_2) {
// in this case we'll get better split over second loop - exactly 32 elements per thread
ASSERT_EQ(2, ThreadsHelper::pickLoop2d(32, 48, 1024));
ASSERT_EQ(2, ThreadsHelper::pickLoop2d(6, 4, 16384));
// in this case we'll get better split over first loop - 2 loops/2048 elements per thread
ASSERT_EQ(1, ThreadsHelper::pickLoop2d(32, 64, 1024));
ASSERT_EQ(1, ThreadsHelper::pickLoop2d(6, 6, 16384));
// in this case none of loops are good enough, but second loop is too small for split
ASSERT_EQ(1, ThreadsHelper::pickLoop2d(6, 64, 32));
// all loops are good enough, but we go with bigger one, since small
ASSERT_EQ(1, ThreadsHelper::pickLoop2d(2, 64, 32));
// obviously split goes into second loop, to give 1024 elements per thread
ASSERT_EQ(2, ThreadsHelper::pickLoop2d(2, 1, 2048));
}
TEST_F(ThreadsTests, th_test_3) {
// typical conv cases
ASSERT_EQ(1, ThreadsHelper::pickLoop3d(4, 32, 3, 128));
ASSERT_EQ(2, ThreadsHelper::pickLoop3d(4, 1, 128, 64));
ASSERT_EQ(3, ThreadsHelper::pickLoop3d(4, 1, 3, 128));
// checking for optimal threads for conv inference
ASSERT_EQ(6, ThreadsHelper::numberOfThreads3d(6, 1, 3, 128));
ASSERT_EQ(4, ThreadsHelper::numberOfThreads3d(4, 1, 3, 128));
ASSERT_EQ(8, ThreadsHelper::numberOfThreads3d(8, 1, 3, 128));
// checking for optimal threads for conv training
ASSERT_EQ(6, ThreadsHelper::numberOfThreads3d(6, 16, 3, 128));
ASSERT_EQ(6, ThreadsHelper::numberOfThreads3d(6, 8, 3, 128));
ASSERT_EQ(6, ThreadsHelper::numberOfThreads3d(6, 8, 3, 64));
ASSERT_EQ(1, ThreadsHelper::pickLoop3d(6, 8, 3, 64));
}
TEST_F(ThreadsTests, th_test_5) {
ASSERT_EQ(6, ThreadsHelper::numberOfThreads3d(6, 32, 112, 112));
ASSERT_EQ(1, ThreadsHelper::pickLoop3d(6, 32, 112, 112));
for (auto e = 0; e < 6; e++) {
auto span = Span3::build(1, e, 6, 0, 32, 1, 0, 112, 1, 0, 112, 1);
nd4j_printf("Span start: %lld; stop: %lld\n", span.startX(), span.stopX());
}
}
TEST_F(ThreadsTests, th_test_4) {
// typical conv cases
ASSERT_EQ(2, ThreadsHelper::numberOfThreads2d(2, 32, 3));
ASSERT_EQ(4, ThreadsHelper::numberOfThreads2d(4, 32, 3));
ASSERT_EQ(6, ThreadsHelper::numberOfThreads2d(6, 32, 1));
ASSERT_EQ(8, ThreadsHelper::numberOfThreads2d(8, 16, 64));
ASSERT_EQ(1, ThreadsHelper::pickLoop2d(4, 32, 1));
ASSERT_EQ(1, ThreadsHelper::pickLoop2d(8, 19, 17));
// primes edge cases
ASSERT_EQ(6, ThreadsHelper::numberOfThreads2d(6, 19, 17));
ASSERT_EQ(8, ThreadsHelper::numberOfThreads2d(8, 19, 17));
ASSERT_EQ(1, ThreadsHelper::pickLoop2d(8, 19, 17));
for (auto e = 0; e < 6; e++) {
auto span = Span2::build(1, e, 6, 0, 19, 1, 0, 17, 1);
nd4j_printf("Span start: %lld; stop: %lld\n", span.startX(), span.stopX());
}
nd4j_printf("-----------------------\n","");
for (auto e = 0; e < 6; e++) {
auto span = Span2::build(1, e, 6, 0, 32, 1, 0, 3, 1);
nd4j_printf("Span start: %lld; stop: %lld\n", span.startX(), span.stopX());
}
}
TEST_F(ThreadsTests, test_span_converage_1) {
for (int b = 1; b <= 128; b++) {
for (int c = 1; c <= 64; c++) {
for (int t = 1; t <= 64; t++) {
auto threads = ThreadsHelper::numberOfThreads2d(t, b, c);
auto loop = ThreadsHelper::pickLoop2d(threads, b, c);
if (t > 1 && threads == 1 && (b > 1 && c > 1)) {
nd4j_printf("Got 1 thread for [%i, %i] loop; initial max threads: %i\n", b, c, t)
}
auto sum = 0;
for (auto a = 0; a < threads; a++) {
auto span = Span2::build(loop, a,threads, 0, b, 1, 0, c, 1);
if (loop == 1)
sum += span.stopX() - span.startX();
else if (loop == 2)
sum += span.stopY() - span.startY();
else
throw std::runtime_error("Bad loop!");
}
if (loop == 1)
ASSERT_EQ(b, sum);
else
ASSERT_EQ(c, sum);
}
}
}
}
TEST_F(ThreadsTests, validation_test_2d_1) {
if (1 > 0)
return;
std::vector<int> threads({1, 2, 4, 6, 8, 12, 16, 20, 32, 48, 64});
for (int e = 1; e < 1024; e++) {
for (int i = 1; i <= 1024; i++ ) {
for (auto t:threads) {
std::atomic<int64_t> sum;
sum.store(0);
auto func = PRAGMA_THREADS_FOR_2D {
for (auto x = start_x; x < stop_x; x += inc_x) {
for (auto y = start_y; y < stop_y; y += inc_y) {
sum++;
}
}
};
samediff::Threads::parallel_for(func, 0, e, 1, 0, i, 1, t, true);
ASSERT_EQ(e * i, sum.load());
}
}
nd4j_printf("Finished iteration %i\n", e);
}
}
TEST_F(ThreadsTests, reduction_test_1) {
auto func = PRAGMA_REDUCE_LONG {
int64_t sum = 0;
for (auto e = start; e < stop; e++) {
sum++;
};
return sum;
};
auto sum = samediff::Threads::parallel_long(func, LAMBDA_AL {return _old + _new;}, 0, 8192, 1, 4);
ASSERT_EQ(8192, sum);
}
/*
TEST_F(ThreadsTests, basic_test_1) {
if (!Environment::getInstance()->isCPU())
return;
auto instance = samediff::ThreadPool::getInstance();
auto array = NDArrayFactory::create<float>('c', {512, 768});
auto like = array.like();
auto buffer = array.bufferAsT<float>();
auto lbuffer = like.bufferAsT<float>();
auto func = PRAGMA_THREADS_FOR {
PRAGMA_OMP_SIMD
for (uint64_t e = start; e < stop; e += increment) {
buffer[e] += 1.0f;
}
};
auto timeStartThreads = std::chrono::system_clock::now();
samediff::Threads::parallel_for(func, 0, array.lengthOf());
auto timeEndThreads = std::chrono::system_clock::now();
auto outerTimeThreads = std::chrono::duration_cast<std::chrono::microseconds> (timeEndThreads - timeStartThreads).count();
auto timeStartOmp = std::chrono::system_clock::now();
PRAGMA_OMP_PARALLEL_FOR_SIMD
for (uint64_t e = 0; e < array.lengthOf(); e ++) {
lbuffer[e] += 1.0f;
}
auto timeEndOmp = std::chrono::system_clock::now();
auto outerTimeOmp = std::chrono::duration_cast<std::chrono::microseconds> (timeEndOmp - timeStartOmp).count();
ASSERT_NEAR((float) array.lengthOf(), array.sumNumber().e<float>(0), 1e-5f);
nd4j_printf("Threads time: %lld us; OMP time: %lld us; %p\n", outerTimeThreads, outerTimeOmp, instance)
}
*/
| 33.797571
| 126
| 0.582774
|
bpossolo
|
a94517aa17a2ce44603d0b81c20776b7e3453071
| 13,174
|
cxx
|
C++
|
PWGLF/FORWARD/analysis2/AliBaseMCTrackDensity.cxx
|
amveen/AliPhysics
|
bef49dc8e7f8ad5f656d54430031eb67abcf3243
|
[
"BSD-3-Clause"
] | null | null | null |
PWGLF/FORWARD/analysis2/AliBaseMCTrackDensity.cxx
|
amveen/AliPhysics
|
bef49dc8e7f8ad5f656d54430031eb67abcf3243
|
[
"BSD-3-Clause"
] | null | null | null |
PWGLF/FORWARD/analysis2/AliBaseMCTrackDensity.cxx
|
amveen/AliPhysics
|
bef49dc8e7f8ad5f656d54430031eb67abcf3243
|
[
"BSD-3-Clause"
] | null | null | null |
#include "AliBaseMCTrackDensity.h"
#include "AliForwardFlowWeights.h"
#include <AliMCEvent.h>
#include <AliTrackReference.h>
//#include <AliStack.h>
#include <TMath.h>
#include <AliLog.h>
#include <TH2D.h>
#include <TH1D.h>
#include <TList.h>
#include <TROOT.h>
#include <TVector3.h>
#include <iostream>
#include "AliCollisionGeometry.h"
#include "AliGenEventHeader.h"
#include "AliForwardUtil.h"
#include <TF1.h>
#include <TGraph.h>
//____________________________________________________________________
AliBaseMCTrackDensity::AliBaseMCTrackDensity()
: TNamed(),
fUseOnlyPrimary(false),
fBinFlow(0),
fEtaBinFlow(0),
fPhiBinFlow(0),
fNRefs(0),
fWeights(0),
fTruthWeights(0),
fIP(0,0,0),
fB(0),
fPhiR(0),
fDebug(false),
fTrackGammaToPi0(false)
{
// Default constructor
DGUARD(fDebug, 3,"Default CTOR of AliBasMCTrackDensity");
}
//____________________________________________________________________
AliBaseMCTrackDensity::AliBaseMCTrackDensity(const char* name)
: TNamed(name,"mcTrackDensity"),
fUseOnlyPrimary(false),
fBinFlow(0),
fEtaBinFlow(0),
fPhiBinFlow(0),
fNRefs(0),
fWeights(0),
fTruthWeights(0),
fIP(0,0,0),
fB(0),
fPhiR(0),
fDebug(false),
fTrackGammaToPi0(false)
{
// Normal constructor constructor
DGUARD(fDebug, 3,"Named CTOR of AliBasMCTrackDensity: %s", name);
}
//____________________________________________________________________
AliBaseMCTrackDensity::AliBaseMCTrackDensity(const AliBaseMCTrackDensity& o)
: TNamed(o),
fUseOnlyPrimary(o.fUseOnlyPrimary),
fBinFlow(o.fBinFlow),
fEtaBinFlow(o.fEtaBinFlow),
fPhiBinFlow(o.fPhiBinFlow),
fNRefs(o.fNRefs),
fWeights(o.fWeights),
fTruthWeights(o.fTruthWeights),
fIP(o.fIP),
fB(o.fB),
fPhiR(o.fPhiR),
fDebug(o.fDebug),
fTrackGammaToPi0(o.fTrackGammaToPi0)
{
// Normal constructor constructor
DGUARD(fDebug, 3,"Copy CTOR of AliBasMCTrackDensity");
}
//____________________________________________________________________
AliBaseMCTrackDensity&
AliBaseMCTrackDensity::operator=(const AliBaseMCTrackDensity& o)
{
// Assignment operator
DGUARD(fDebug,3,"MC track density assignmetn");
if (&o == this) return *this;
TNamed::operator=(o);
fUseOnlyPrimary = o.fUseOnlyPrimary;
fBinFlow = o.fBinFlow;
fEtaBinFlow = o.fEtaBinFlow;
fPhiBinFlow = o.fPhiBinFlow;
fNRefs = o.fNRefs;
fDebug = o.fDebug;
fWeights = o.fWeights;
fTruthWeights = o.fTruthWeights;
fIP.SetXYZ(o.fIP.X(), o.fIP.Y(), o.fIP.Z());
fB = o.fB;
fPhiR = o.fPhiR;
fTrackGammaToPi0 = o.fTrackGammaToPi0;
return *this;
}
//____________________________________________________________________
void
AliBaseMCTrackDensity::SetWeights(AliBaseMCWeights* w)
{
if (fWeights) {
delete fWeights;
fWeights = 0;
}
fWeights = w;
}
//____________________________________________________________________
void
AliBaseMCTrackDensity::SetTruthWeights(AliBaseMCWeights* w)
{
if (fTruthWeights) {
delete fTruthWeights;
fTruthWeights = 0;
}
fTruthWeights = w;
}
//____________________________________________________________________
void
AliBaseMCTrackDensity::SetUseFlowWeights(Bool_t use)
{
if (!use) return;
SetWeights(new AliForwardFlowWeights());
}
//____________________________________________________________________
void
AliBaseMCTrackDensity::CreateOutputObjects(TList* l)
{
DGUARD(fDebug,1,"MC track defines output");
TList* ll = new TList;
ll->SetName(GetTitle());
ll->SetOwner();
l->Add(ll);
fBinFlow = new TH2D("binFlow", "#eta and #varphi bin flow",
200, -5, 5, 40, -180, 180);
fBinFlow->SetXTitle("#Delta#eta");
fBinFlow->SetYTitle("#Delta#varphi");
fBinFlow->SetOption("colz");
fBinFlow->SetDirectory(0);
ll->Add(fBinFlow);
fEtaBinFlow = new TH2D("binFlowEta", "#eta bin flow vs #eta",
200, -4, 6, 200, -5, 5);
fEtaBinFlow->SetXTitle("#eta");
fEtaBinFlow->SetYTitle("#Delta#eta");
fEtaBinFlow->SetOption("colz");
fEtaBinFlow->SetDirectory(0);
ll->Add(fEtaBinFlow);
fPhiBinFlow = new TH2D("binFlowPhi", "#phi bin flow vs #phi",
40, 0, 360, 40, -180, 180);
fPhiBinFlow->SetXTitle("#varphi");
fPhiBinFlow->SetYTitle("#Delta#varphi");
fPhiBinFlow->SetOption("colz");
fPhiBinFlow->SetDirectory(0);
ll->Add(fPhiBinFlow);
fNRefs = new TH1D("nRefs", "# references per track", 21, -.5, 20.5);
fNRefs->SetXTitle("# references");
fNRefs->SetFillColor(kMagenta+1);
fNRefs->SetFillStyle(3001);
fNRefs->SetDirectory(0);
ll->Add(fNRefs);
if(fWeights) fWeights->Init(ll);
}
//____________________________________________________________________
Double_t
AliBaseMCTrackDensity::StoreParticle(AliMCParticle* particle,
const AliMCParticle* mother,
AliTrackReference* ref) const
{
// Store this particle
//
// Note: If particle refers to a primary, then particle and mother
// refers to the same particle (the address are the same)
//
DGUARD(fDebug,3,"MC track density store particle");
// Store a particle.
if (!ref) return 0;
Double_t weight = 1;
if (fWeights)
weight = CalculateWeight(mother, (mother == particle));
// Get track-reference stuff
Double_t x = ref->X()-fIP.X();
Double_t y = ref->Y()-fIP.Y();
Double_t z = ref->Z()-fIP.Z();
Double_t rr = TMath::Sqrt(x*x+y*y);
Double_t thetaR = TMath::ATan2(rr,z);
Double_t phiR = TMath::ATan2(y,x);
Double_t etaR = -TMath::Log(TMath::Tan(thetaR/2));
// Correct angle and convert to degrees
if (thetaR < 0) thetaR += 2*TMath::Pi();
thetaR *= 180. / TMath::Pi();
if (phiR < 0) phiR += 2*TMath::Pi();
phiR *= 180. / TMath::Pi();
const AliMCParticle* mp = (mother ? mother : particle);
Double_t dEta = mp->Eta() - etaR;
Double_t dPhi = mp->Phi() * 180 / TMath::Pi() - phiR;
if (dPhi > 180) dPhi -= 360;
if (dPhi < -180) dPhi += 360;
fBinFlow->Fill(dEta, dPhi);
fEtaBinFlow->Fill(etaR, dEta);
fPhiBinFlow->Fill(phiR, dPhi);
return weight;
}
//____________________________________________________________________
Double_t
AliBaseMCTrackDensity::GetTrackRefTheta(const AliTrackReference* ref) const
{
// Get the incidient angle of the track reference.
Double_t x = ref->X()-fIP.X();
Double_t y = ref->Y()-fIP.Y();
Double_t z = ref->Z()-fIP.Z();
Double_t rr = TMath::Sqrt(x*x+y*y);
Double_t theta= TMath::ATan2(rr,z);
Double_t ang = TMath::Abs(TMath::Pi()-theta);
return ang;
}
//____________________________________________________________________
const AliMCParticle*
AliBaseMCTrackDensity::GetMother(Int_t iTr, const AliMCEvent& event) const
{
//
// Track down primary mother
//
Int_t i = iTr;
Bool_t gammaSeen = false;
const AliMCParticle* candidate = 0;
do {
const AliMCParticle* p = static_cast<AliMCParticle*>(event.GetTrack(i));
if (!p) break;
if (gammaSeen && TMath::Abs(p->PdgCode()) == 111)
// If we're looking for a mother pi0 of gamma, and we find it
// here, we return it - irrespective of whether it's flagged as
// a primary or not.
return p;
if (const_cast<AliMCEvent&>(event).IsPhysicalPrimary(i)) {
candidate = p;
if (fTrackGammaToPi0 && TMath::Abs(p->PdgCode()) == 22)
// If we want to track gammas back to a possible pi0, we flag
// the gamma seen, and store it as a candidate in case we do
// not find a pi0 in the stack
gammaSeen = true;
else
break;
}
// We get here if the current track isn't a primary, or it was a
// primary gamma and we want to track back to a pi0.
i = p->GetMother();
} while (i > 0);
// Return our candidate (gamma) if we find no mother pi0. Note, we
// should never get here with a null pointer, so we issue a warning
// in that case.
if (!candidate)
AliWarningF("No mother found for track # %d", iTr);
return candidate;
}
//____________________________________________________________________
Bool_t
AliBaseMCTrackDensity::GetCollisionParameters(const AliMCEvent& event)
{
DGUARD(fDebug,3,"MC track density get collision parameters");
AliCollisionGeometry* hd =
dynamic_cast<AliCollisionGeometry*>(event.GenEventHeader());
fPhiR = (hd ? hd->ReactionPlaneAngle() : 0.);
fB = (hd ? hd->ImpactParameter() : -1 );
return hd != 0;
}
//____________________________________________________________________
Bool_t
AliBaseMCTrackDensity::ProcessTrack(AliMCParticle* particle,
const AliMCParticle* mother)
{
// Check the returned particle
//
// Note: If particle refers to a primary, then particle and mother
// refers to the same particle (the address are the same)
//
DGUARD(fDebug,3,"MC track density Process a track");
if (!particle) return false;
Int_t nTrRef = particle->GetNumberOfTrackReferences();
AliTrackReference* store = 0;
BeginTrackRefs();
// Double_t oTheta= 0;
Int_t nRefs = 0;
for (Int_t iTrRef = 0; iTrRef < nTrRef; iTrRef++) {
AliTrackReference* ref = particle->GetTrackReference(iTrRef);
// Check existence
if (!ref) continue;
// Check that we hit an Base element
if (ref->DetectorId() != GetDetectorId()) continue;
if (!CheckTrackRef(ref)) continue;
nRefs++;
AliTrackReference* test = ProcessRef(particle, mother, ref);
if (test) store = test;
} // Loop over track references
if (!store) return true; // Nothing found
StoreParticle(particle, mother, store);
fNRefs->Fill(nRefs);
EndTrackRefs(nRefs);
return true;
}
//____________________________________________________________________
Bool_t
AliBaseMCTrackDensity::ProcessTracks(const AliMCEvent& event,
const TVector3& ip,
TH2D* primary)
{
//
// Filter the input kinematics and track references, using
// some of the ESD information
//
// Parameters:
// input Input ESD event
// event Input MC event
// vz Vertex position
// output Output ESD-like object
// primary Per-event histogram of primaries
//
// Return:
// True on succes, false otherwise
//
DGUARD(fDebug,3,"MC track density Process a tracks");
fIP.SetXYZ(ip.X(), ip.Y(), ip.Z());
GetCollisionParameters(event);
// AliStack* stack = const_cast<AliMCEvent&>(event).Stack();
// if (!stack) return kFALSE;
Int_t nTracks = /*stack->GetNtrack();*/event.GetNumberOfTracks();
// temporary remove constness, since event.GetNumberOfPrimaries() was not const
Int_t nPrim = /*stack->GetNprimary();*/((AliMCEvent&)event).GetNumberOfPrimaries();
for (Int_t iTr = 0; iTr < nTracks; iTr++) {
AliMCParticle* particle =
static_cast<AliMCParticle*>(event.GetTrack(iTr));
// Check if this charged and a primary
if (!particle->Charge() != 0) continue;
Bool_t isPrimary = event.IsPhysicalPrimary(iTr) && iTr < nPrim;
// Fill 'dn/deta' histogram
if (isPrimary && primary) {
Double_t w = 1;
if (fTruthWeights) w = CalculateTruthWeight(particle);
primary->Fill(particle->Eta(), particle->Phi(), w);
}
// Bail out if we're only processing primaries - perhaps we should
// track back to the original primary?
if (fUseOnlyPrimary && !isPrimary) continue;
const AliMCParticle* mother = isPrimary ? particle : GetMother(iTr, event);
// IF the track corresponds to a primary, pass that as both
// arguments.
ProcessTrack(particle, mother);
} // Loop over tracks
return kTRUE;
}
//____________________________________________________________________
Double_t
AliBaseMCTrackDensity::CalculateWeight(const AliMCParticle* p,
Bool_t isPrimary) const
{
// Note, it is always the ultimate mother that is passed here.
if (!p) return 0;
return fWeights->CalcWeight(p, isPrimary, fPhiR, fB);
}
//____________________________________________________________________
Double_t
AliBaseMCTrackDensity::CalculateTruthWeight(const AliMCParticle* p) const
{
// Note, it is always the ultimate mother that is passed here.
return fTruthWeights->CalcWeight(p, true, fPhiR, fB);
}
#define PF(N,V,...) \
AliForwardUtil::PrintField(N,V, ## __VA_ARGS__)
#define PFB(N,FLAG) \
do { \
AliForwardUtil::PrintName(N); \
std::cout << std::boolalpha << (FLAG) << std::noboolalpha << std::endl; \
} while(false)
#define PFV(N,VALUE) \
do { \
AliForwardUtil::PrintName(N); \
std::cout << (VALUE) << std::endl; } while(false)
//____________________________________________________________________
void
AliBaseMCTrackDensity::Print(Option_t* option) const
{
AliForwardUtil::PrintTask(*this);
gROOT->IncreaseDirLevel();
PFB("Only primary tracks", fUseOnlyPrimary);
PFB("Use weights", fWeights);
if (fWeights) fWeights->Print(option);
gROOT->DecreaseDirLevel();
}
//____________________________________________________________________
//
// EOF
//
| 29.604494
| 89
| 0.677698
|
amveen
|
a9468a817025b35dc7d43899bf3ccc4e489dd248
| 1,032
|
hpp
|
C++
|
include/unordered_set.hpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 7
|
2018-04-14T14:55:51.000Z
|
2022-01-31T10:49:49.000Z
|
include/unordered_set.hpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 5
|
2018-04-14T14:28:49.000Z
|
2019-05-11T02:22:10.000Z
|
include/unordered_set.hpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include "container.hpp"
#include <unordered_set>
template <typename T>
class UnorderedSet : public Container<std::unordered_set<T>> {
public:
UnorderedSet() : Container<std::unordered_set<T>>() {}
template <typename Itr>
UnorderedSet(Itr first, Itr last)
: Container<std::unordered_set<T>>(first, last) {}
UnorderedSet(const std::initializer_list<T> &s)
: Container<std::unordered_set<T>>(s) {}
UnorderedSet(int n, Input &in) : Container<std::unordered_set<T>>(n, in) {}
template <typename S> UnorderedSet<T> &operator&=(const S &a) {
UnorderedSet<T> r;
if (this->size() < a.size()) {
for (const auto &i : *this) {
if (a.in(i)) {
r.emplace(i);
}
}
} else {
for (const auto &i : a) {
if (this->in(i)) {
r.emplace(i);
}
}
}
*this = r;
return *this;
}
int count(const T &a) const { return std::unordered_set<T>::count(a); }
int contains(const T &a) const { return count(a) > 0; }
};
| 24
| 77
| 0.580426
|
not522
|
a9476e38b5d1771834b1b15bcb53e2a8f0b20418
| 1,422
|
cpp
|
C++
|
SerialPrograms/Source/PokemonLA/Programs/PokemonLA_FlagNavigationTest.cpp
|
BlizzardHero/Arduino-Source
|
bc4ce6433651b0feef488735098900f8bf4144f8
|
[
"MIT"
] | null | null | null |
SerialPrograms/Source/PokemonLA/Programs/PokemonLA_FlagNavigationTest.cpp
|
BlizzardHero/Arduino-Source
|
bc4ce6433651b0feef488735098900f8bf4144f8
|
[
"MIT"
] | null | null | null |
SerialPrograms/Source/PokemonLA/Programs/PokemonLA_FlagNavigationTest.cpp
|
BlizzardHero/Arduino-Source
|
bc4ce6433651b0feef488735098900f8bf4144f8
|
[
"MIT"
] | null | null | null |
/* Flag Navigation Test
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#include "CommonFramework/Globals.h"
#include "PokemonLA_FlagNavigationAir.h"
#include "PokemonLA_FlagNavigationTest.h"
namespace PokemonAutomation{
namespace NintendoSwitch{
namespace PokemonLA{
FlagNavigationTest_Descriptor::FlagNavigationTest_Descriptor()
: RunnableSwitchProgramDescriptor(
"PokemonLA:FlagNavigationTest",
STRING_POKEMON + " LA", "Flag Navigation Test",
"",
"Navigate to the flag pin.",
FeedbackType::REQUIRED, false,
PABotBaseLevel::PABOTBASE_12KB
)
{}
FlagNavigationTest::FlagNavigationTest(const FlagNavigationTest_Descriptor& descriptor)
: SingleSwitchProgramInstance(descriptor)
, STOP_DISTANCE(
"<b>Stop Distance:</b><br>Don't reset until you come within this distance of the flag.",
30, 10, 999
)
, NAVIGATION_TIMEOUT(
"<b>Navigation Timeout:</b><br>Give up if flag is not reached after this many seconds.",
180, 0
)
{
PA_ADD_OPTION(NAVIGATION_TIMEOUT);
PA_ADD_OPTION(SHINY_DETECTED);
}
void FlagNavigationTest::program(SingleSwitchProgramEnvironment& env){
FlagNavigationAir session(
env, env.console,
SHINY_DETECTED.stop_on_shiny(),
STOP_DISTANCE,
std::chrono::seconds(NAVIGATION_TIMEOUT)
);
session.run_session();
}
}
}
}
| 23.311475
| 96
| 0.699015
|
BlizzardHero
|
a949770d142f1bead74062711799f4740ee5e07b
| 21
|
cpp
|
C++
|
Source/Services/Common/Unix/pch_unix.cpp
|
blgrossMS/xbox-live-api
|
17c586336e11f0fa3a2a3f3acd665b18c5487b24
|
[
"MIT"
] | 2
|
2021-07-17T13:34:20.000Z
|
2022-01-09T00:55:51.000Z
|
Source/Services/Common/Unix/pch_unix.cpp
|
blgrossMS/xbox-live-api
|
17c586336e11f0fa3a2a3f3acd665b18c5487b24
|
[
"MIT"
] | null | null | null |
Source/Services/Common/Unix/pch_unix.cpp
|
blgrossMS/xbox-live-api
|
17c586336e11f0fa3a2a3f3acd665b18c5487b24
|
[
"MIT"
] | 1
|
2018-11-18T08:32:40.000Z
|
2018-11-18T08:32:40.000Z
|
#include "pch_unix.h"
| 21
| 21
| 0.761905
|
blgrossMS
|
a94a4109f478568f52fe9769f1c20ad190a61644
| 2,821
|
cpp
|
C++
|
src/games/common/HexBlocks_Common_Render.cpp
|
Press-Play-On-Tape/TheHex
|
ad2876e1de0d09dbe8123201ecc88bcd4a0d7c5c
|
[
"BSD-3-Clause"
] | 1
|
2021-07-05T15:55:59.000Z
|
2021-07-05T15:55:59.000Z
|
src/games/common/HexBlocks_Common_Render.cpp
|
Press-Play-On-Tape/TheHex
|
ad2876e1de0d09dbe8123201ecc88bcd4a0d7c5c
|
[
"BSD-3-Clause"
] | null | null | null |
src/games/common/HexBlocks_Common_Render.cpp
|
Press-Play-On-Tape/TheHex
|
ad2876e1de0d09dbe8123201ecc88bcd4a0d7c5c
|
[
"BSD-3-Clause"
] | null | null | null |
#include "../../HexBlocks.h"
using PC = Pokitto::Core;
using PD = Pokitto::Display;
#include "../../utils/Constants.h"
#include "../../utils/Utils.h"
#include "../../images/Images.h"
#include "../../entities/Entities.h"
void Game::renderScreen_Common() {
for (uint8_t y = 0; y < Constants::GridSize; y++) {
for (uint8_t x = 0; x < Constants::Cell_Count[y]; x++) {
uint8_t xCell = Constants::Cell_Min_X[y] + x;
uint8_t value = gamePlayVariables.board[xCell][y];
PD::drawBitmap(Constants::Cell_xPos[y] + (x * 18), Constants::Cell_yPos[y], Images::Hex_Combined[value]);
}
}
}
void Game::renderBackground_Common() {
uint8_t rightLimit = (this->gameState == GameState::Title || this->gameState == GameState::Intro_Hexon || this->gameState == GameState::Intro_Hexer || this->gameState == GameState::Intro_Hexic ? 220 : 171);
if (Utils::isFrameCount(2) == 0) {
this->backgroundVariables.titleOffsetTop = this->backgroundVariables.titleOffsetTop - 1;
if (this->backgroundVariables.titleOffsetTop < - 220) this->backgroundVariables.titleOffsetTop = 0;
}
this->backgroundVariables.titleOffsetTop = this->backgroundVariables.titleOffsetTop - 1;
if (this->backgroundVariables.titleOffsetTop < - 220) this->backgroundVariables.titleOffsetTop = 0;
this->backgroundVariables.titleOffsetBottom = this->backgroundVariables.titleOffsetBottom + 1;
if (this->backgroundVariables.titleOffsetBottom == 0) this->backgroundVariables.titleOffsetBottom = -220;
for (uint8_t i = 0; i < 6; i++) {
int16_t x = this->backgroundVariables.titleOffsetBottom + Constants::Background_xBlue[i];
if (x > -28 && x < rightLimit) PD::drawBitmap(x, Constants::Background_yBlue[i], Images::BG_Blue);
if (x + 220 > -28 && x + 220 < rightLimit) PD::drawBitmap(x + 220, Constants::Background_yBlue[i], Images::BG_Blue);
}
for (uint8_t i = 0; i < 19; i++) {
int16_t x = this->backgroundVariables.titleOffsetTop + Constants::Background_xBurgundy[i];
if (x > -28 && x < rightLimit) PD::drawBitmap(x, Constants::Background_yBurgundy[i], Images::BG_Burgundy);
if (x + 220 > -28 && x + 220 < rightLimit) PD::drawBitmap(x + 220, Constants::Background_yBurgundy[i], Images::BG_Burgundy);
}
}
void Game::renderFlowers() {
for (FoundFlower &flower : this->gamePlayVariables.foundFlowers.flower) {
if (flower.active) {
uint8_t xCentre = 0;
uint8_t yCentre = 0;
this->getCentreOfTile_Common(flower.x, flower.y, xCentre, yCentre);
PD::drawBitmap(Constants::Cell_xPos[flower.y] + (flower.x * 18) - 20, Constants::Cell_yPos[flower.y] - 13 + 9, Images::Flower);
}
}
}
| 34.402439
| 210
| 0.641971
|
Press-Play-On-Tape
|
a94a61473e9402285d616af3b06a94df90a4423a
| 63,866
|
cc
|
C++
|
riegeli/chunk_encoding/transpose_decoder.cc
|
micahcc/riegeli
|
d8cc64857253037d4f022e860b7b86cbe7d4b8d8
|
[
"Apache-2.0"
] | null | null | null |
riegeli/chunk_encoding/transpose_decoder.cc
|
micahcc/riegeli
|
d8cc64857253037d4f022e860b7b86cbe7d4b8d8
|
[
"Apache-2.0"
] | null | null | null |
riegeli/chunk_encoding/transpose_decoder.cc
|
micahcc/riegeli
|
d8cc64857253037d4f022e860b7b86cbe7d4b8d8
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "riegeli/chunk_encoding/transpose_decoder.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <cstring>
#include <iterator>
#include <limits>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/base/optimization.h"
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "riegeli/base/base.h"
#include "riegeli/base/chain.h"
#include "riegeli/base/memory.h"
#include "riegeli/base/object.h"
#include "riegeli/bytes/backward_writer.h"
#include "riegeli/bytes/chain_reader.h"
#include "riegeli/bytes/limiting_backward_writer.h"
#include "riegeli/bytes/reader.h"
#include "riegeli/bytes/string_reader.h"
#include "riegeli/chunk_encoding/constants.h"
#include "riegeli/chunk_encoding/decompressor.h"
#include "riegeli/chunk_encoding/field_projection.h"
#include "riegeli/chunk_encoding/transpose_internal.h"
#include "riegeli/messages/message_wire_format.h"
#include "riegeli/varint/varint_reading.h"
#include "riegeli/varint/varint_writing.h"
namespace riegeli {
namespace {
Reader* kEmptyReader() {
static NoDestructor<StringReader<>> kStaticEmptyReader((absl::string_view()));
RIEGELI_ASSERT(kStaticEmptyReader->healthy())
<< "kEmptyReader() has been closed";
return kStaticEmptyReader.get();
}
constexpr uint32_t kInvalidPos = std::numeric_limits<uint32_t>::max();
// Information about one data bucket used in projection.
struct DataBucket {
// Raw bucket data, valid if not all buffers are already decompressed,
// otherwise empty.
Chain compressed_data;
// Sizes of data buffers in the bucket, valid if not all buffers are already
// decompressed, otherwise empty.
std::vector<size_t> buffer_sizes;
// Decompressor for the remaining data, valid if some but not all buffers are
// already decompressed, otherwise closed.
internal::Decompressor<ChainReader<>> decompressor;
// A prefix of decompressed data buffers, lazily extended.
std::vector<ChainReader<Chain>> buffers;
};
// Should the data content of the field be decoded?
enum class FieldIncluded {
kYes,
kNo,
kExistenceOnly,
};
// Returns `true` if `tag` is a valid protocol buffer tag.
bool ValidTag(uint32_t tag) {
switch (GetTagWireType(tag)) {
case WireType::kVarint:
case WireType::kFixed32:
case WireType::kFixed64:
case WireType::kLengthDelimited:
case WireType::kStartGroup:
case WireType::kEndGroup:
return tag >= 8;
default:
return false;
}
}
} // namespace
namespace internal {
// The types of callbacks in state machine states.
enum class CallbackType : uint8_t {
kNoOp,
kMessageStart,
kSubmessageStart,
kSubmessageEnd,
kSelectCallback,
kSkippedSubmessageStart,
kSkippedSubmessageEnd,
kNonProto,
kFailure,
// `kCopyTag_*` has to be the first `CallbackType` in `TYPES_FOR_TAG_LEN` for
// `GetCopyTagCallbackType()` to work.
#define TYPES_FOR_TAG_LEN(tag_length) \
kCopyTag_##tag_length, kVarint_1_##tag_length, kVarint_2_##tag_length, \
kVarint_3_##tag_length, kVarint_4_##tag_length, kVarint_5_##tag_length, \
kVarint_6_##tag_length, kVarint_7_##tag_length, kVarint_8_##tag_length, \
kVarint_9_##tag_length, kVarint_10_##tag_length, kFixed32_##tag_length, \
kFixed64_##tag_length, kFixed32Existence_##tag_length, \
kFixed64Existence_##tag_length, kString_##tag_length, \
kStartProjectionGroup_##tag_length, kEndProjectionGroup_##tag_length
TYPES_FOR_TAG_LEN(1),
TYPES_FOR_TAG_LEN(2),
TYPES_FOR_TAG_LEN(3),
TYPES_FOR_TAG_LEN(4),
TYPES_FOR_TAG_LEN(5),
#undef TYPES_FOR_TAG_LEN
// We need `kCopyTag_*` callback for length 6 as well because of inline
// numerics. `kCopyTag_6` has to be the first `CallbackType` after
// `TYPES_FOR_TAG_LEN` for `GetCopyTagCallbackType()` to work.
kCopyTag_6,
kUnknown,
// Implicit callback type is added to any of the above types if the transition
// from the node should go to `node->next_node` without reading the transition
// byte.
kImplicit = 0x80,
};
constexpr CallbackType operator+(CallbackType a, uint8_t b) {
return static_cast<CallbackType>(static_cast<uint8_t>(a) + b);
}
constexpr uint8_t operator-(CallbackType a, CallbackType b) {
return static_cast<uint8_t>(a) - static_cast<uint8_t>(b);
}
constexpr CallbackType operator|(CallbackType a, CallbackType b) {
return static_cast<CallbackType>(static_cast<uint8_t>(a) |
static_cast<uint8_t>(b));
}
constexpr CallbackType operator&(CallbackType a, CallbackType b) {
return static_cast<CallbackType>(static_cast<uint8_t>(a) &
static_cast<uint8_t>(b));
}
inline CallbackType& operator|=(CallbackType& a, CallbackType b) {
return a = a | b;
}
// Returns copy tag callback type for `tag_length`.
inline CallbackType GetCopyTagCallbackType(size_t tag_length) {
RIEGELI_ASSERT_GT(tag_length, 0u) << "Zero tag length";
RIEGELI_ASSERT_LE(tag_length, kMaxLengthVarint32 + 1)
<< "Tag length too large";
return CallbackType::kCopyTag_1 +
(tag_length - 1) *
(CallbackType::kCopyTag_2 - CallbackType::kCopyTag_1);
}
// Returns varint callback type for `subtype` and `tag_length`.
inline CallbackType GetVarintCallbackType(Subtype subtype, size_t tag_length) {
RIEGELI_ASSERT_GT(tag_length, 0u) << "Zero tag length";
RIEGELI_ASSERT_LE(tag_length, kMaxLengthVarint32) << "Tag length too large";
if (subtype > Subtype::kVarintInlineMax) return CallbackType::kUnknown;
if (subtype >= Subtype::kVarintInline0) {
return GetCopyTagCallbackType(tag_length + 1);
}
return CallbackType::kVarint_1_1 +
(subtype - Subtype::kVarint1) *
(CallbackType::kVarint_2_1 - CallbackType::kVarint_1_1) +
(tag_length - 1) *
(CallbackType::kVarint_1_2 - CallbackType::kVarint_1_1);
}
// Returns fixed32 callback type for `tag_length`.
inline CallbackType GetFixed32CallbackType(size_t tag_length) {
RIEGELI_ASSERT_GT(tag_length, 0u) << "Zero tag length";
RIEGELI_ASSERT_LE(tag_length, kMaxLengthVarint32) << "Tag length too large";
return CallbackType::kFixed32_1 +
(tag_length - 1) *
(CallbackType::kFixed32_2 - CallbackType::kFixed32_1);
}
// Returns fixed64 callback type for `tag_length`.
inline CallbackType GetFixed64CallbackType(size_t tag_length) {
RIEGELI_ASSERT_GT(tag_length, 0u) << "Zero tag length";
RIEGELI_ASSERT_LE(tag_length, kMaxLengthVarint32) << "Tag length too large";
return CallbackType::kFixed64_1 +
(tag_length - 1) *
(CallbackType::kFixed64_2 - CallbackType::kFixed64_1);
}
// Returns fixed32 existence callback type for `tag_length`.
inline CallbackType GetFixed32ExistenceCallbackType(size_t tag_length) {
RIEGELI_ASSERT_GT(tag_length, 0u) << "Zero tag length";
RIEGELI_ASSERT_LE(tag_length, kMaxLengthVarint32) << "Tag length too large";
return CallbackType::kFixed32Existence_1 +
(tag_length - 1) * (CallbackType::kFixed32Existence_2 -
CallbackType::kFixed32Existence_1);
}
// Returns fixed64 existence callback type for `tag_length`.
inline CallbackType GetFixed64ExistenceCallbackType(size_t tag_length) {
RIEGELI_ASSERT_GT(tag_length, 0u) << "Zero tag length";
RIEGELI_ASSERT_LE(tag_length, kMaxLengthVarint32) << "Tag length too large";
return CallbackType::kFixed64Existence_1 +
(tag_length - 1) * (CallbackType::kFixed64Existence_2 -
CallbackType::kFixed64Existence_1);
}
// Returns string callback type for `subtype` and `tag_length`.
inline CallbackType GetStringCallbackType(Subtype subtype, size_t tag_length) {
RIEGELI_ASSERT_GT(tag_length, 0u) << "Zero tag length";
RIEGELI_ASSERT_LE(tag_length, kMaxLengthVarint32) << "Tag length too large";
switch (subtype) {
case Subtype::kLengthDelimitedString:
return CallbackType::kString_1 +
(tag_length - 1) *
(CallbackType::kString_2 - CallbackType::kString_1);
case Subtype::kLengthDelimitedEndOfSubmessage:
return CallbackType::kSubmessageEnd;
default:
// Note: Nodes with `kLengthDelimitedStartOfSubmessage` are not created.
// Start of submessage is indicated with `MessageId::kStartOfSubmessage`
// and uses `CallbackType::kSubmessageStart`.
return CallbackType::kUnknown;
}
}
// Returns string callback type for `subtype` and `tag_length` to exclude field.
inline CallbackType GetStringExcludeCallbackType(Subtype subtype,
size_t tag_length) {
RIEGELI_ASSERT_GT(tag_length, 0u) << "Zero tag length";
RIEGELI_ASSERT_LE(tag_length, kMaxLengthVarint32) << "Tag length too large";
switch (subtype) {
case Subtype::kLengthDelimitedString:
return CallbackType::kNoOp;
case Subtype::kLengthDelimitedEndOfSubmessage:
return CallbackType::kSkippedSubmessageEnd;
default:
return CallbackType::kUnknown;
}
}
// Returns string existence callback type for `subtype` and `tag_length`.
inline CallbackType GetStringExistenceCallbackType(Subtype subtype,
size_t tag_length) {
RIEGELI_ASSERT_GT(tag_length, 0u) << "Zero tag length";
RIEGELI_ASSERT_LE(tag_length, kMaxLengthVarint32) << "Tag length too large";
switch (subtype) {
case Subtype::kLengthDelimitedString:
// We use the fact that there is a zero stored in TagData. This decodes as
// an empty string in proto decoder.
return GetCopyTagCallbackType(tag_length + 1);
case Subtype::kLengthDelimitedEndOfSubmessage:
return CallbackType::kSubmessageEnd;
default:
return CallbackType::kUnknown;
}
}
inline CallbackType GetStartProjectionGroupCallbackType(size_t tag_length) {
RIEGELI_ASSERT_GT(tag_length, 0u) << "Zero tag length";
RIEGELI_ASSERT_LE(tag_length, kMaxLengthVarint32) << "Tag length too large";
return CallbackType::kStartProjectionGroup_1 +
(tag_length - 1) * (CallbackType::kStartProjectionGroup_2 -
CallbackType::kStartProjectionGroup_1);
}
inline CallbackType GetEndProjectionGroupCallbackType(size_t tag_length) {
RIEGELI_ASSERT_GT(tag_length, 0u) << "Zero tag length";
RIEGELI_ASSERT_LE(tag_length, kMaxLengthVarint32) << "Tag length too large";
return CallbackType::kEndProjectionGroup_1 +
(tag_length - 1) * (CallbackType::kEndProjectionGroup_2 -
CallbackType::kEndProjectionGroup_1);
}
// Get callback for node.
inline CallbackType GetCallbackType(FieldIncluded field_included, uint32_t tag,
Subtype subtype, size_t tag_length,
bool projection_enabled) {
RIEGELI_ASSERT_GT(tag_length, 0u) << "Zero tag length";
RIEGELI_ASSERT_LE(tag_length, kMaxLengthVarint32) << "Tag length too large";
switch (field_included) {
case FieldIncluded::kYes:
switch (GetTagWireType(tag)) {
case WireType::kVarint:
return GetVarintCallbackType(subtype, tag_length);
case WireType::kFixed32:
return GetFixed32CallbackType(tag_length);
case WireType::kFixed64:
return GetFixed64CallbackType(tag_length);
case WireType::kLengthDelimited:
return GetStringCallbackType(subtype, tag_length);
case WireType::kStartGroup:
return projection_enabled
? GetStartProjectionGroupCallbackType(tag_length)
: GetCopyTagCallbackType(tag_length);
case WireType::kEndGroup:
return projection_enabled
? GetEndProjectionGroupCallbackType(tag_length)
: GetCopyTagCallbackType(tag_length);
default:
return CallbackType::kUnknown;
}
case FieldIncluded::kNo:
switch (GetTagWireType(tag)) {
case WireType::kVarint:
case WireType::kFixed32:
case WireType::kFixed64:
return CallbackType::kNoOp;
case WireType::kLengthDelimited:
return GetStringExcludeCallbackType(subtype, tag_length);
case WireType::kStartGroup:
return CallbackType::kSkippedSubmessageStart;
case WireType::kEndGroup:
return CallbackType::kSkippedSubmessageEnd;
default:
return CallbackType::kUnknown;
}
case FieldIncluded::kExistenceOnly:
switch (GetTagWireType(tag)) {
case WireType::kVarint:
return GetCopyTagCallbackType(tag_length + 1);
case WireType::kFixed32:
return GetFixed32ExistenceCallbackType(tag_length);
case WireType::kFixed64:
return GetFixed64ExistenceCallbackType(tag_length);
case WireType::kLengthDelimited:
return GetStringExistenceCallbackType(subtype, tag_length);
case WireType::kStartGroup:
return GetStartProjectionGroupCallbackType(tag_length);
case WireType::kEndGroup:
return GetEndProjectionGroupCallbackType(tag_length);
default:
return CallbackType::kUnknown;
}
}
RIEGELI_ASSERT_UNREACHABLE()
<< "Unknown FieldIncluded: " << static_cast<int>(field_included);
}
inline bool IsImplicit(CallbackType callback_type) {
return (callback_type & CallbackType::kImplicit) == CallbackType::kImplicit;
}
} // namespace internal
struct TransposeDecoder::Context {
// Compression type of the input.
CompressionType compression_type = CompressionType::kNone;
// Buffer containing all the data.
// Note: Used only when projection is disabled.
std::vector<ChainReader<Chain>> buffers;
// Buffer for lengths of nonproto messages.
Reader* nonproto_lengths = nullptr;
// State machine read from the input.
std::vector<StateMachineNode> state_machine_nodes;
// Node to start decoding from.
uint32_t first_node = 0;
// State machine transitions. One byte = one transition.
internal::Decompressor<> transitions;
enum class IncludeType : uint8_t {
// Field is included.
kIncludeFully,
// Some child fields are included.
kIncludeChild,
// Field is existence only.
kExistenceOnly,
};
// --- Fields used in projection. ---
// Holds information about included field.
struct IncludedField {
// IDs are sequentially assigned to fields from FieldProjection.
uint32_t field_id;
IncludeType include_type;
};
// Fields form a tree structure stored in `include_fields` map. If `p` is
// the ID of parent submessage then `include_fields[std::make_pair(p, f)]`
// holds the include information of the child with field number `f`. The root
// ID is assumed to be `kInvalidPos` and the root `IncludeType` is assumed to
// be `kIncludeChild`.
absl::flat_hash_map<std::pair<uint32_t, int>, IncludedField> include_fields;
// Data buckets.
std::vector<DataBucket> buckets;
// Template that can later be used later to finalize `StateMachineNode`.
std::vector<StateMachineNodeTemplate> node_templates;
};
bool TransposeDecoder::Decode(uint64_t num_records, uint64_t decoded_data_size,
const FieldProjection& field_projection,
Reader& src, BackwardWriter& dest,
std::vector<size_t>& limits) {
RIEGELI_ASSERT_EQ(dest.pos(), 0u)
<< "Failed precondition of TransposeDecoder::Reset(): "
"non-zero destination position";
Object::Reset(kInitiallyOpen);
if (ABSL_PREDICT_FALSE(num_records > limits.max_size())) {
return Fail(absl::ResourceExhaustedError("Too many records"));
}
if (ABSL_PREDICT_FALSE(decoded_data_size >
std::numeric_limits<size_t>::max())) {
return Fail(absl::ResourceExhaustedError("Records too large"));
}
Context context;
if (ABSL_PREDICT_FALSE(!Parse(context, src, field_projection))) return false;
LimitingBackwardWriter<> limiting_dest(&dest, decoded_data_size);
if (ABSL_PREDICT_FALSE(
!Decode(context, num_records, limiting_dest, limits))) {
limiting_dest.Close();
return false;
}
if (ABSL_PREDICT_FALSE(!limiting_dest.Close())) return Fail(limiting_dest);
RIEGELI_ASSERT_LE(dest.pos(), decoded_data_size)
<< "Decoded data size larger than expected";
if (field_projection.includes_all() &&
ABSL_PREDICT_FALSE(dest.pos() != decoded_data_size)) {
return Fail(
absl::InvalidArgumentError("Decoded data size smaller than expected"));
}
return true;
}
inline bool TransposeDecoder::Parse(Context& context, Reader& src,
const FieldProjection& field_projection) {
bool projection_enabled = true;
for (const Field& include_field : field_projection.fields()) {
if (include_field.path().empty()) {
projection_enabled = false;
break;
}
size_t path_len = include_field.path().size();
bool existence_only =
include_field.path()[path_len - 1] == Field::kExistenceOnly;
if (existence_only) {
--path_len;
if (path_len == 0) continue;
}
uint32_t current_id = kInvalidPos;
for (size_t i = 0; i < path_len; ++i) {
const int field_number = include_field.path()[i];
if (field_number == Field::kExistenceOnly) {
return false;
}
uint32_t next_id = context.include_fields.size();
Context::IncludeType include_type = Context::IncludeType::kIncludeChild;
if (i + 1 == path_len) {
include_type = existence_only ? Context::IncludeType::kExistenceOnly
: Context::IncludeType::kIncludeFully;
}
Context::IncludedField& val =
context.include_fields
.emplace(std::make_pair(current_id, field_number),
Context::IncludedField{next_id, include_type})
.first->second;
current_id = val.field_id;
static_assert(Context::IncludeType::kExistenceOnly >
Context::IncludeType::kIncludeChild &&
Context::IncludeType::kIncludeChild >
Context::IncludeType::kIncludeFully,
"Statement below assumes this ordering");
val.include_type = std::min(val.include_type, include_type);
}
}
const absl::optional<uint8_t> compression_type_byte = src.ReadByte();
if (ABSL_PREDICT_FALSE(compression_type_byte == absl::nullopt)) {
src.Fail(absl::InvalidArgumentError("Reading compression type failed"));
return Fail(src);
}
context.compression_type =
static_cast<CompressionType>(*compression_type_byte);
const absl::optional<uint64_t> header_size = ReadVarint64(src);
if (ABSL_PREDICT_FALSE(header_size == absl::nullopt)) {
src.Fail(absl::InvalidArgumentError("Reading header size failed"));
return Fail(src);
}
Chain header;
if (ABSL_PREDICT_FALSE(!src.Read(*header_size, header))) {
src.Fail(absl::InvalidArgumentError("Reading header failed"));
return Fail(src);
}
internal::Decompressor<ChainReader<>> header_decompressor(
std::forward_as_tuple(&header), context.compression_type);
if (ABSL_PREDICT_FALSE(!header_decompressor.healthy())) {
return Fail(header_decompressor);
}
uint32_t num_buffers;
std::vector<uint32_t> first_buffer_indices;
std::vector<uint32_t> bucket_indices;
if (projection_enabled) {
if (ABSL_PREDICT_FALSE(!ParseBuffersForFiltering(
context, header_decompressor.reader(), src, first_buffer_indices,
bucket_indices))) {
return false;
}
num_buffers = IntCast<uint32_t>(bucket_indices.size());
} else {
if (ABSL_PREDICT_FALSE(
!ParseBuffers(context, header_decompressor.reader(), src))) {
return false;
}
num_buffers = IntCast<uint32_t>(context.buffers.size());
}
const absl::optional<uint32_t> state_machine_size =
ReadVarint32(header_decompressor.reader());
if (ABSL_PREDICT_FALSE(state_machine_size == absl::nullopt)) {
header_decompressor.reader().Fail(
absl::InvalidArgumentError("Reading state machine size failed"));
return Fail(header_decompressor.reader());
}
// Additional `0xff` nodes to correctly handle invalid/malicious inputs.
// TODO: Handle overflow.
context.state_machine_nodes.resize(*state_machine_size + 0xff);
if (projection_enabled) context.node_templates.resize(*state_machine_size);
std::vector<StateMachineNode>& state_machine_nodes =
context.state_machine_nodes;
bool has_nonproto_op = false;
size_t num_subtypes = 0;
std::vector<uint32_t> tags;
tags.reserve(*state_machine_size);
for (size_t i = 0; i < *state_machine_size; ++i) {
const absl::optional<uint32_t> tag =
ReadVarint32(header_decompressor.reader());
if (ABSL_PREDICT_FALSE(tag == absl::nullopt)) {
header_decompressor.reader().Fail(
absl::InvalidArgumentError("Reading field tag failed"));
return Fail(header_decompressor.reader());
}
tags.push_back(*tag);
if (ValidTag(*tag) && internal::HasSubtype(*tag)) ++num_subtypes;
}
std::vector<uint32_t> next_node_indices;
next_node_indices.reserve(*state_machine_size);
for (size_t i = 0; i < *state_machine_size; ++i) {
const absl::optional<uint32_t> next_node =
ReadVarint32(header_decompressor.reader());
if (ABSL_PREDICT_FALSE(next_node == absl::nullopt)) {
header_decompressor.reader().Fail(
absl::InvalidArgumentError("Reading next node index failed"));
return Fail(header_decompressor.reader());
}
next_node_indices.push_back(*next_node);
}
std::string subtypes;
if (ABSL_PREDICT_FALSE(
!header_decompressor.reader().Read(num_subtypes, subtypes))) {
header_decompressor.reader().Fail(
absl::InvalidArgumentError("Reading subtypes failed"));
return Fail(header_decompressor.reader());
}
size_t subtype_index = 0;
for (size_t i = 0; i < *state_machine_size; ++i) {
uint32_t tag = tags[i];
StateMachineNode& state_machine_node = state_machine_nodes[i];
state_machine_node.buffer = nullptr;
switch (static_cast<internal::MessageId>(tag)) {
case internal::MessageId::kNoOp:
state_machine_node.callback_type = internal::CallbackType::kNoOp;
break;
case internal::MessageId::kNonProto: {
state_machine_node.callback_type = internal::CallbackType::kNonProto;
const absl::optional<uint32_t> buffer_index =
ReadVarint32(header_decompressor.reader());
if (ABSL_PREDICT_FALSE(buffer_index == absl::nullopt)) {
header_decompressor.reader().Fail(
absl::InvalidArgumentError("Reading buffer index failed"));
return Fail(header_decompressor.reader());
}
if (ABSL_PREDICT_FALSE(*buffer_index >= num_buffers)) {
return Fail(absl::InvalidArgumentError("Buffer index too large"));
}
if (projection_enabled) {
const uint32_t bucket = bucket_indices[*buffer_index];
state_machine_node.buffer = GetBuffer(
context, bucket, *buffer_index - first_buffer_indices[bucket]);
if (ABSL_PREDICT_FALSE(state_machine_node.buffer == nullptr)) {
return false;
}
} else {
state_machine_node.buffer = &context.buffers[*buffer_index];
}
has_nonproto_op = true;
} break;
case internal::MessageId::kStartOfMessage:
state_machine_node.callback_type =
internal::CallbackType::kMessageStart;
break;
case internal::MessageId::kStartOfSubmessage:
if (projection_enabled) {
context.node_templates[i].tag =
static_cast<uint32_t>(internal::MessageId::kStartOfSubmessage);
state_machine_node.node_template = &context.node_templates[i];
state_machine_node.callback_type =
internal::CallbackType::kSelectCallback;
} else {
state_machine_node.callback_type =
internal::CallbackType::kSubmessageStart;
}
break;
default: {
internal::Subtype subtype = internal::Subtype::kTrivial;
static_assert(
internal::Subtype::kLengthDelimitedString ==
internal::Subtype::kTrivial,
"Subtypes kLengthDelimitedString and kTrivial must be equal");
// End of submessage is encoded as `kSubmessageWireType`.
if (GetTagWireType(tag) == internal::kSubmessageWireType) {
tag -= static_cast<uint32_t>(internal::kSubmessageWireType) -
static_cast<uint32_t>(WireType::kLengthDelimited);
subtype = internal::Subtype::kLengthDelimitedEndOfSubmessage;
}
if (ABSL_PREDICT_FALSE(!ValidTag(tag))) {
return Fail(absl::InvalidArgumentError("Invalid tag"));
}
char* const tag_end =
WriteVarint32(tag, state_machine_node.tag_data.data);
const size_t tag_length =
PtrDistance(state_machine_node.tag_data.data, tag_end);
if (internal::HasSubtype(tag)) {
subtype = static_cast<internal::Subtype>(subtypes[subtype_index++]);
}
if (projection_enabled) {
if (internal::HasDataBuffer(tag, subtype)) {
const absl::optional<uint32_t> buffer_index =
ReadVarint32(header_decompressor.reader());
if (ABSL_PREDICT_FALSE(buffer_index == absl::nullopt)) {
header_decompressor.reader().Fail(
absl::InvalidArgumentError("Reading buffer index failed"));
return Fail(header_decompressor.reader());
}
if (ABSL_PREDICT_FALSE(*buffer_index >= num_buffers)) {
return Fail(absl::InvalidArgumentError("Buffer index too large"));
}
const uint32_t bucket = bucket_indices[*buffer_index];
context.node_templates[i].bucket_index = bucket;
context.node_templates[i].buffer_within_bucket_index =
*buffer_index - first_buffer_indices[bucket];
} else {
context.node_templates[i].bucket_index = kInvalidPos;
}
context.node_templates[i].tag = tag;
context.node_templates[i].subtype = subtype;
context.node_templates[i].tag_length = IntCast<uint8_t>(tag_length);
state_machine_node.node_template = &context.node_templates[i];
state_machine_node.callback_type =
internal::CallbackType::kSelectCallback;
} else {
if (internal::HasDataBuffer(tag, subtype)) {
const absl::optional<uint32_t> buffer_index =
ReadVarint32(header_decompressor.reader());
if (ABSL_PREDICT_FALSE(buffer_index == absl::nullopt)) {
header_decompressor.reader().Fail(
absl::InvalidArgumentError("Reading buffer index failed"));
return Fail(header_decompressor.reader());
}
if (ABSL_PREDICT_FALSE(*buffer_index >= num_buffers)) {
return Fail(absl::InvalidArgumentError("Buffer index too large"));
}
state_machine_node.buffer = &context.buffers[*buffer_index];
}
state_machine_node.callback_type =
internal::GetCallbackType(FieldIncluded::kYes, tag, subtype,
tag_length, projection_enabled);
if (ABSL_PREDICT_FALSE(state_machine_node.callback_type ==
internal::CallbackType::kUnknown)) {
return Fail(absl::InvalidArgumentError("Invalid node"));
}
}
// Store subtype right past tag in case this is inline numeric.
if (GetTagWireType(tag) == WireType::kVarint &&
subtype >= internal::Subtype::kVarintInline0) {
state_machine_node.tag_data.data[tag_length] =
subtype - internal::Subtype::kVarintInline0;
} else {
state_machine_node.tag_data.data[tag_length] = 0;
}
state_machine_node.tag_data.size = IntCast<uint8_t>(tag_length);
}
}
uint32_t next_node_id = next_node_indices[i];
if (next_node_id >= *state_machine_size) {
// Callback is implicit.
next_node_id -= *state_machine_size;
state_machine_node.callback_type =
state_machine_node.callback_type | internal::CallbackType::kImplicit;
}
if (ABSL_PREDICT_FALSE(next_node_id >= *state_machine_size)) {
return Fail(absl::InvalidArgumentError("Node index too large"));
}
state_machine_node.next_node = &state_machine_nodes[next_node_id];
}
if (has_nonproto_op) {
// If non-proto state exists then the last buffer is the
// `nonproto_lengths` buffer.
if (ABSL_PREDICT_FALSE(num_buffers == 0)) {
return Fail(
absl::InvalidArgumentError("Missing buffer for non-proto records"));
}
if (projection_enabled) {
const uint32_t bucket = bucket_indices[num_buffers - 1];
context.nonproto_lengths = GetBuffer(
context, bucket, num_buffers - 1 - first_buffer_indices[bucket]);
if (ABSL_PREDICT_FALSE(context.nonproto_lengths == nullptr)) {
return false;
}
} else {
context.nonproto_lengths = &context.buffers.back();
}
}
const absl::optional<uint32_t> first_node =
ReadVarint32(header_decompressor.reader());
if (ABSL_PREDICT_FALSE(first_node == absl::nullopt)) {
header_decompressor.reader().Fail(
absl::InvalidArgumentError("Reading first node index failed"));
return Fail(header_decompressor.reader());
}
if (ABSL_PREDICT_FALSE(*first_node >= *state_machine_size)) {
return Fail(absl::InvalidArgumentError("First node index too large"));
}
context.first_node = *first_node;
// Add `0xff` failure nodes so we never overflow this array.
for (uint64_t i = *state_machine_size; i < *state_machine_size + 0xff; ++i) {
state_machine_nodes[i].callback_type = internal::CallbackType::kFailure;
}
if (ABSL_PREDICT_FALSE(ContainsImplicitLoop(&state_machine_nodes))) {
return Fail(absl::InvalidArgumentError("Nodes contain an implicit loop"));
}
if (ABSL_PREDICT_FALSE(!header_decompressor.VerifyEndAndClose())) {
return Fail(header_decompressor);
}
context.transitions.Reset(&src, context.compression_type);
if (ABSL_PREDICT_FALSE(!context.transitions.healthy())) {
return Fail(context.transitions);
}
return true;
}
inline bool TransposeDecoder::ParseBuffers(Context& context,
Reader& header_reader, Reader& src) {
const absl::optional<uint32_t> num_buckets = ReadVarint32(header_reader);
if (ABSL_PREDICT_FALSE(num_buckets == absl::nullopt)) {
header_reader.Fail(
absl::InvalidArgumentError("Reading number of buckets failed"));
return Fail(header_reader);
}
const absl::optional<uint32_t> num_buffers = ReadVarint32(header_reader);
if (ABSL_PREDICT_FALSE(num_buffers == absl::nullopt)) {
header_reader.Fail(
absl::InvalidArgumentError("Reading number of buffers failed"));
return Fail(header_reader);
}
if (ABSL_PREDICT_FALSE(*num_buffers > context.buffers.max_size())) {
return Fail(absl::InvalidArgumentError("Too many buffers"));
}
if (*num_buckets == 0) {
if (ABSL_PREDICT_FALSE(*num_buffers != 0)) {
return Fail(absl::InvalidArgumentError("Too few buckets"));
}
return true;
}
context.buffers.reserve(*num_buffers);
std::vector<internal::Decompressor<ChainReader<Chain>>> bucket_decompressors;
if (ABSL_PREDICT_FALSE(*num_buckets > bucket_decompressors.max_size())) {
return Fail(absl::ResourceExhaustedError("Too many buckets"));
}
bucket_decompressors.reserve(*num_buckets);
for (uint32_t bucket_index = 0; bucket_index < *num_buckets; ++bucket_index) {
const absl::optional<uint64_t> bucket_length = ReadVarint64(header_reader);
if (ABSL_PREDICT_FALSE(bucket_length == absl::nullopt)) {
header_reader.Fail(
absl::InvalidArgumentError("Reading bucket length failed"));
return Fail(header_reader);
}
if (ABSL_PREDICT_FALSE(*bucket_length >
std::numeric_limits<size_t>::max())) {
return Fail(absl::ResourceExhaustedError("Bucket too large"));
}
Chain bucket;
if (ABSL_PREDICT_FALSE(
!src.Read(IntCast<size_t>(*bucket_length), bucket))) {
src.Fail(absl::InvalidArgumentError("Reading bucket failed"));
return Fail(src);
}
bucket_decompressors.emplace_back(std::forward_as_tuple(std::move(bucket)),
context.compression_type);
if (ABSL_PREDICT_FALSE(!bucket_decompressors.back().healthy())) {
return Fail(bucket_decompressors.back());
}
}
uint32_t bucket_index = 0;
for (size_t buffer_index = 0; buffer_index < *num_buffers; ++buffer_index) {
const absl::optional<uint64_t> buffer_length = ReadVarint64(header_reader);
if (ABSL_PREDICT_FALSE(buffer_length == absl::nullopt)) {
header_reader.Fail(
absl::InvalidArgumentError("Reading buffer length failed"));
return Fail(header_reader);
}
if (ABSL_PREDICT_FALSE(*buffer_length >
std::numeric_limits<size_t>::max())) {
return Fail(absl::ResourceExhaustedError("Buffer too large"));
}
Chain buffer;
if (ABSL_PREDICT_FALSE(!bucket_decompressors[bucket_index].reader().Read(
IntCast<size_t>(*buffer_length), buffer))) {
bucket_decompressors[bucket_index].reader().Fail(
absl::InvalidArgumentError("Reading buffer failed"));
return Fail(bucket_decompressors[bucket_index].reader());
}
context.buffers.emplace_back(std::move(buffer));
while (!bucket_decompressors[bucket_index].reader().Pull() &&
bucket_index + 1 < *num_buckets) {
if (ABSL_PREDICT_FALSE(
!bucket_decompressors[bucket_index].VerifyEndAndClose())) {
return Fail(bucket_decompressors[bucket_index].status());
}
++bucket_index;
}
}
if (ABSL_PREDICT_FALSE(bucket_index + 1 < *num_buckets)) {
return Fail(absl::InvalidArgumentError("Too few buckets"));
}
if (ABSL_PREDICT_FALSE(
!bucket_decompressors[bucket_index].VerifyEndAndClose())) {
return Fail(bucket_decompressors[bucket_index]);
}
return true;
}
inline bool TransposeDecoder::ParseBuffersForFiltering(
Context& context, Reader& header_reader, Reader& src,
std::vector<uint32_t>& first_buffer_indices,
std::vector<uint32_t>& bucket_indices) {
const absl::optional<uint32_t> num_buckets = ReadVarint32(header_reader);
if (ABSL_PREDICT_FALSE(num_buckets == absl::nullopt)) {
header_reader.Fail(
absl::InvalidArgumentError("Reading number of buckets failed"));
return Fail(header_reader);
}
if (ABSL_PREDICT_FALSE(*num_buckets > context.buckets.max_size())) {
return Fail(absl::ResourceExhaustedError("Too many buckets"));
}
const absl::optional<uint32_t> num_buffers = ReadVarint32(header_reader);
if (ABSL_PREDICT_FALSE(num_buffers == absl::nullopt)) {
header_reader.Fail(
absl::InvalidArgumentError("Reading number of buffers failed"));
return Fail(header_reader);
}
if (ABSL_PREDICT_FALSE(*num_buffers > bucket_indices.max_size())) {
return Fail(absl::ResourceExhaustedError("Too many buffers"));
}
if (*num_buckets == 0) {
if (ABSL_PREDICT_FALSE(*num_buffers != 0)) {
return Fail(absl::InvalidArgumentError("Too few buckets"));
}
return true;
}
first_buffer_indices.reserve(*num_buckets);
bucket_indices.reserve(*num_buffers);
context.buckets.reserve(*num_buckets);
for (uint32_t bucket_index = 0; bucket_index < *num_buckets; ++bucket_index) {
const absl::optional<uint64_t> bucket_length = ReadVarint64(header_reader);
if (ABSL_PREDICT_FALSE(bucket_length == absl::nullopt)) {
header_reader.Fail(
absl::InvalidArgumentError("Reading bucket length failed"));
return Fail(header_reader);
}
if (ABSL_PREDICT_FALSE(*bucket_length >
std::numeric_limits<size_t>::max())) {
return Fail(absl::ResourceExhaustedError("Bucket too large"));
}
context.buckets.emplace_back();
if (ABSL_PREDICT_FALSE(!src.Read(IntCast<size_t>(*bucket_length),
context.buckets.back().compressed_data))) {
src.Fail(absl::InvalidArgumentError("Reading bucket failed"));
return Fail(src);
}
}
uint32_t bucket_index = 0;
first_buffer_indices.push_back(0);
absl::optional<uint64_t> remaining_bucket_size = internal::UncompressedSize(
context.buckets[0].compressed_data, context.compression_type);
if (ABSL_PREDICT_FALSE(remaining_bucket_size == absl::nullopt)) {
return Fail(absl::InvalidArgumentError("Reading uncompressed size failed"));
}
for (uint32_t buffer_index = 0; buffer_index < *num_buffers; ++buffer_index) {
const absl::optional<uint64_t> buffer_length = ReadVarint64(header_reader);
if (ABSL_PREDICT_FALSE(buffer_length == absl::nullopt)) {
header_reader.Fail(
absl::InvalidArgumentError("Reading buffer length failed"));
return Fail(header_reader);
}
if (ABSL_PREDICT_FALSE(*buffer_length >
std::numeric_limits<size_t>::max())) {
return Fail(absl::ResourceExhaustedError("Buffer too large"));
}
context.buckets[bucket_index].buffer_sizes.push_back(
IntCast<size_t>(*buffer_length));
if (ABSL_PREDICT_FALSE(*buffer_length > *remaining_bucket_size)) {
return Fail(absl::InvalidArgumentError("Buffer does not fit in bucket"));
}
*remaining_bucket_size -= *buffer_length;
bucket_indices.push_back(bucket_index);
while (*remaining_bucket_size == 0 && bucket_index + 1 < *num_buckets) {
++bucket_index;
first_buffer_indices.push_back(buffer_index + 1);
remaining_bucket_size = internal::UncompressedSize(
context.buckets[bucket_index].compressed_data,
context.compression_type);
if (ABSL_PREDICT_FALSE(remaining_bucket_size == absl::nullopt)) {
return Fail(
absl::InvalidArgumentError("Reading uncompressed size failed"));
}
}
}
if (ABSL_PREDICT_FALSE(bucket_index + 1 < *num_buckets)) {
return Fail(absl::InvalidArgumentError("Too few buckets"));
}
if (ABSL_PREDICT_FALSE(*remaining_bucket_size > 0)) {
return Fail(absl::InvalidArgumentError("End of data expected"));
}
return true;
}
inline Reader* TransposeDecoder::GetBuffer(Context& context,
uint32_t bucket_index,
uint32_t index_within_bucket) {
RIEGELI_ASSERT_LT(bucket_index, context.buckets.size())
<< "Bucket index out of range";
DataBucket& bucket = context.buckets[bucket_index];
RIEGELI_ASSERT_LT(index_within_bucket, !bucket.buffer_sizes.empty()
? bucket.buffer_sizes.size()
: bucket.buffers.size())
<< "Index within bucket out of range";
while (index_within_bucket >= bucket.buffers.size()) {
if (bucket.buffers.empty()) {
// This is the first buffer to be decompressed from this bucket.
bucket.decompressor.Reset(std::forward_as_tuple(&bucket.compressed_data),
context.compression_type);
if (ABSL_PREDICT_FALSE(!bucket.decompressor.healthy())) {
Fail(bucket.decompressor);
return nullptr;
}
// Important to prevent invalidating pointers by `emplace_back()`.
bucket.buffers.reserve(bucket.buffer_sizes.size());
}
Chain buffer;
if (ABSL_PREDICT_FALSE(!bucket.decompressor.reader().Read(
bucket.buffer_sizes[bucket.buffers.size()], buffer))) {
bucket.decompressor.reader().Fail(
absl::InvalidArgumentError("Reading buffer failed"));
Fail(bucket.decompressor.reader());
return nullptr;
}
bucket.buffers.emplace_back(std::move(buffer));
if (bucket.buffers.size() == bucket.buffer_sizes.size()) {
// This was the last decompressed buffer from this bucket.
if (ABSL_PREDICT_FALSE(!bucket.decompressor.VerifyEndAndClose())) {
Fail(bucket.decompressor);
return nullptr;
}
// Free memory of fields which are no longer needed.
bucket.compressed_data = Chain();
bucket.buffer_sizes = std::vector<size_t>();
}
}
return &bucket.buffers[index_within_bucket];
}
inline bool TransposeDecoder::ContainsImplicitLoop(
std::vector<StateMachineNode>* state_machine_nodes) {
std::vector<size_t> implicit_loop_ids(state_machine_nodes->size(), 0);
size_t next_loop_id = 1;
for (size_t i = 0; i < state_machine_nodes->size(); ++i) {
if (implicit_loop_ids[i] != 0) continue;
StateMachineNode* node = &(*state_machine_nodes)[i];
implicit_loop_ids[i] = next_loop_id;
while (internal::IsImplicit(node->callback_type)) {
node = node->next_node;
const size_t j = node - state_machine_nodes->data();
if (implicit_loop_ids[j] == next_loop_id) return true;
if (implicit_loop_ids[j] != 0) break;
implicit_loop_ids[j] = next_loop_id;
}
++next_loop_id;
}
return false;
}
// Copy tag from `*node` to `dest`.
#define COPY_TAG_CALLBACK(tag_length) \
do { \
if (ABSL_PREDICT_FALSE(!dest.Write( \
absl::string_view(node->tag_data.data, tag_length)))) { \
return Fail(dest); \
} \
} while (false)
// Decode varint value from `*node` to `dest`.
#define VARINT_CALLBACK(tag_length, data_length) \
do { \
if (ABSL_PREDICT_FALSE(!dest.Push(tag_length + data_length))) { \
return Fail(dest); \
} \
dest.move_cursor(tag_length + data_length); \
char* const buffer = dest.cursor(); \
if (ABSL_PREDICT_FALSE( \
!node->buffer->Read(data_length, buffer + tag_length))) { \
node->buffer->Fail( \
absl::InvalidArgumentError("Reading varint field failed")); \
return Fail(*node->buffer); \
} \
for (size_t i = 0; i < data_length - 1; ++i) { \
buffer[tag_length + i] |= 0x80; \
} \
std::memcpy(buffer, node->tag_data.data, tag_length); \
} while (false)
// Decode fixed32 or fixed64 value from `*node` to `dest`.
#define FIXED_CALLBACK(tag_length, data_length) \
do { \
if (ABSL_PREDICT_FALSE(!dest.Push(tag_length + data_length))) { \
return Fail(dest); \
} \
dest.move_cursor(tag_length + data_length); \
char* const buffer = dest.cursor(); \
if (ABSL_PREDICT_FALSE( \
!node->buffer->Read(data_length, buffer + tag_length))) { \
node->buffer->Fail( \
absl::InvalidArgumentError("Reading fixed field failed")); \
return Fail(*node->buffer); \
} \
std::memcpy(buffer, node->tag_data.data, tag_length); \
} while (false)
// Create zero fixed32 or fixed64 value in `dest`.
#define FIXED_EXISTENCE_CALLBACK(tag_length, data_length) \
do { \
if (ABSL_PREDICT_FALSE(!dest.Push(tag_length + data_length))) { \
return Fail(dest); \
} \
dest.move_cursor(tag_length + data_length); \
char* const buffer = dest.cursor(); \
std::memset(buffer + tag_length, '\0', data_length); \
std::memcpy(buffer, node->tag_data.data, tag_length); \
} while (false)
// Decode string value from `*node` to `dest`.
#define STRING_CALLBACK(tag_length) \
do { \
node->buffer->Pull(kMaxLengthVarint32); \
const absl::optional<ReadFromStringResult<uint32_t>> length = \
ReadVarint32(node->buffer->cursor(), node->buffer->limit()); \
if (ABSL_PREDICT_FALSE(length == absl::nullopt)) { \
node->buffer->Fail( \
absl::InvalidArgumentError("Reading string length failed")); \
return Fail(*node->buffer); \
} \
const size_t length_length = \
PtrDistance(node->buffer->cursor(), length->cursor); \
if (ABSL_PREDICT_FALSE(length->value > \
std::numeric_limits<uint32_t>::max() - \
length_length)) { \
return Fail(absl::InvalidArgumentError("String length overflow")); \
} \
if (ABSL_PREDICT_FALSE(!node->buffer->Copy( \
length_length + size_t{length->value}, dest))) { \
if (!dest.healthy()) return Fail(dest); \
node->buffer->Fail( \
absl::InvalidArgumentError("Reading string field failed")); \
return Fail(*node->buffer); \
} \
if (ABSL_PREDICT_FALSE(!dest.Write( \
absl::string_view(node->tag_data.data, tag_length)))) { \
return Fail(dest); \
} \
} while (false)
inline bool TransposeDecoder::Decode(Context& context, uint64_t num_records,
BackwardWriter& dest,
std::vector<size_t>& limits) {
// For now positions reported by `dest` are pushed to `limits` directly.
// Later `limits` will be reversed and complemented.
limits.clear();
limits.reserve(num_records);
// Set current node to the initial node.
StateMachineNode* node = &context.state_machine_nodes[context.first_node];
// The depth of the current field relative to the parent submessage that
// was excluded in projection.
int skipped_submessage_level = 0;
Reader& transitions_reader = context.transitions.reader();
// Stack of all open sub-messages.
std::vector<SubmessageStackElement> submessage_stack;
submessage_stack.reserve(16);
// Number of following iteration that go directly to `node->next_node`
// without reading transition byte.
int num_iters = 0;
if (internal::IsImplicit(node->callback_type)) ++num_iters;
for (;;) {
switch (static_cast<riegeli::internal::CallbackType>(
static_cast<uint8_t>(node->callback_type) &
~static_cast<uint8_t>(internal::CallbackType::kImplicit))) {
case internal::CallbackType::kSelectCallback:
if (ABSL_PREDICT_FALSE(!SetCallbackType(
context, skipped_submessage_level, submessage_stack, *node))) {
return false;
}
continue;
case internal::CallbackType::kSkippedSubmessageEnd:
++skipped_submessage_level;
goto do_transition;
case internal::CallbackType::kSkippedSubmessageStart:
if (ABSL_PREDICT_FALSE(skipped_submessage_level == 0)) {
return Fail(
absl::InvalidArgumentError("Skipped submessage stack underflow"));
}
--skipped_submessage_level;
goto do_transition;
case internal::CallbackType::kSubmessageEnd:
submessage_stack.push_back(
{IntCast<size_t>(dest.pos()), node->tag_data});
goto do_transition;
case internal::CallbackType::kSubmessageStart: {
if (ABSL_PREDICT_FALSE(submessage_stack.empty())) {
return Fail(absl::InvalidArgumentError("Submessage stack underflow"));
}
const SubmessageStackElement& elem = submessage_stack.back();
RIEGELI_ASSERT_GE(dest.pos(), elem.end_of_submessage)
<< "Destination position decreased";
const size_t length =
IntCast<size_t>(dest.pos()) - elem.end_of_submessage;
if (ABSL_PREDICT_FALSE(length > std::numeric_limits<uint32_t>::max())) {
return Fail(absl::InvalidArgumentError("Message too large"));
}
if (ABSL_PREDICT_FALSE(
!WriteVarint32(IntCast<uint32_t>(length), dest))) {
return Fail(dest);
}
if (ABSL_PREDICT_FALSE(!dest.Write(
absl::string_view(elem.tag_data.data, elem.tag_data.size)))) {
return Fail(dest);
}
submessage_stack.pop_back();
}
goto do_transition;
#define ACTIONS_FOR_TAG_LEN(tag_length) \
case internal::CallbackType::kCopyTag_##tag_length: \
COPY_TAG_CALLBACK(tag_length); \
goto do_transition; \
case internal::CallbackType::kVarint_1_##tag_length: \
VARINT_CALLBACK(tag_length, 1); \
goto do_transition; \
case internal::CallbackType::kVarint_2_##tag_length: \
VARINT_CALLBACK(tag_length, 2); \
goto do_transition; \
case internal::CallbackType::kVarint_3_##tag_length: \
VARINT_CALLBACK(tag_length, 3); \
goto do_transition; \
case internal::CallbackType::kVarint_4_##tag_length: \
VARINT_CALLBACK(tag_length, 4); \
goto do_transition; \
case internal::CallbackType::kVarint_5_##tag_length: \
VARINT_CALLBACK(tag_length, 5); \
goto do_transition; \
case internal::CallbackType::kVarint_6_##tag_length: \
VARINT_CALLBACK(tag_length, 6); \
goto do_transition; \
case internal::CallbackType::kVarint_7_##tag_length: \
VARINT_CALLBACK(tag_length, 7); \
goto do_transition; \
case internal::CallbackType::kVarint_8_##tag_length: \
VARINT_CALLBACK(tag_length, 8); \
goto do_transition; \
case internal::CallbackType::kVarint_9_##tag_length: \
VARINT_CALLBACK(tag_length, 9); \
goto do_transition; \
case internal::CallbackType::kVarint_10_##tag_length: \
VARINT_CALLBACK(tag_length, 10); \
goto do_transition; \
case internal::CallbackType::kFixed32_##tag_length: \
FIXED_CALLBACK(tag_length, 4); \
goto do_transition; \
case internal::CallbackType::kFixed64_##tag_length: \
FIXED_CALLBACK(tag_length, 8); \
goto do_transition; \
case internal::CallbackType::kFixed32Existence_##tag_length: \
FIXED_EXISTENCE_CALLBACK(tag_length, 4); \
goto do_transition; \
case internal::CallbackType::kFixed64Existence_##tag_length: \
FIXED_EXISTENCE_CALLBACK(tag_length, 8); \
goto do_transition; \
case internal::CallbackType::kString_##tag_length: \
STRING_CALLBACK(tag_length); \
goto do_transition; \
case internal::CallbackType::kStartProjectionGroup_##tag_length: \
if (ABSL_PREDICT_FALSE(submessage_stack.empty())) { \
return Fail(absl::InvalidArgumentError("Submessage stack underflow")); \
} \
submessage_stack.pop_back(); \
COPY_TAG_CALLBACK(tag_length); \
goto do_transition; \
case internal::CallbackType::kEndProjectionGroup_##tag_length: \
submessage_stack.push_back({IntCast<size_t>(dest.pos()), node->tag_data}); \
COPY_TAG_CALLBACK(tag_length); \
goto do_transition
ACTIONS_FOR_TAG_LEN(1);
ACTIONS_FOR_TAG_LEN(2);
ACTIONS_FOR_TAG_LEN(3);
ACTIONS_FOR_TAG_LEN(4);
ACTIONS_FOR_TAG_LEN(5);
#undef ACTIONS_FOR_TAG_LEN
case internal::CallbackType::kCopyTag_6:
COPY_TAG_CALLBACK(6);
goto do_transition;
case internal::CallbackType::kUnknown:
case internal::CallbackType::kFailure:
return Fail(absl::InvalidArgumentError("Invalid node index"));
case internal::CallbackType::kNonProto: {
const absl::optional<uint32_t> length =
ReadVarint32(*context.nonproto_lengths);
if (ABSL_PREDICT_FALSE(length == absl::nullopt)) {
context.nonproto_lengths->Fail(absl::InvalidArgumentError(
"Reading non-proto record length failed"));
return Fail(*context.nonproto_lengths);
}
if (ABSL_PREDICT_FALSE(!node->buffer->Copy(*length, dest))) {
if (!dest.healthy()) return Fail(dest);
node->buffer->Fail(
absl::InvalidArgumentError("Reading non-proto record failed"));
return Fail(*node->buffer);
}
}
ABSL_FALLTHROUGH_INTENDED;
case internal::CallbackType::kMessageStart:
if (ABSL_PREDICT_FALSE(!submessage_stack.empty())) {
return Fail(absl::InvalidArgumentError("Submessages still open"));
}
if (ABSL_PREDICT_FALSE(limits.size() == num_records)) {
return Fail(absl::InvalidArgumentError("Too many records"));
}
limits.push_back(IntCast<size_t>(dest.pos()));
ABSL_FALLTHROUGH_INTENDED;
case internal::CallbackType::kNoOp:
do_transition:
node = node->next_node;
if (num_iters == 0) {
const absl::optional<uint8_t> transition_byte =
transitions_reader.ReadByte();
if (ABSL_PREDICT_FALSE(transition_byte == absl::nullopt)) goto done;
node += (*transition_byte >> 2);
num_iters = *transition_byte & 3;
if (internal::IsImplicit(node->callback_type)) ++num_iters;
} else {
if (!internal::IsImplicit(node->callback_type)) --num_iters;
}
continue;
case internal::CallbackType::kImplicit:
RIEGELI_ASSERT_UNREACHABLE() << "kImplicit is masked out";
}
}
done:
if (ABSL_PREDICT_FALSE(!context.transitions.VerifyEndAndClose())) {
return Fail(context.transitions);
}
if (ABSL_PREDICT_FALSE(!submessage_stack.empty())) {
return Fail(absl::InvalidArgumentError("Submessages still open"));
}
if (ABSL_PREDICT_FALSE(skipped_submessage_level != 0)) {
return Fail(absl::InvalidArgumentError("Skipped submessages still open"));
}
if (ABSL_PREDICT_FALSE(limits.size() != num_records)) {
return Fail(absl::InvalidArgumentError("Too few records"));
}
const size_t size = limits.empty() ? size_t{0} : limits.back();
if (ABSL_PREDICT_FALSE(size != dest.pos())) {
return Fail(absl::InvalidArgumentError("Unfinished message"));
}
// Reverse `limits` and complement them, but keep the last limit unchanged
// (because both old and new limits exclude 0 at the beginning and include
// size at the end), e.g. for records of sizes {10, 20, 30, 40}:
// {40, 70, 90, 100} -> {10, 30, 60, 100}.
std::vector<size_t>::iterator first = limits.begin();
std::vector<size_t>::iterator last = limits.end();
if (first != last) {
--last;
while (first < last) {
--last;
const size_t tmp = size - *first;
*first = size - *last;
*last = tmp;
++first;
}
}
return true;
}
// Do not inline this function. This helps Clang to generate better code for
// the main loop in `Decode()`.
ABSL_ATTRIBUTE_NOINLINE inline bool TransposeDecoder::SetCallbackType(
Context& context, int skipped_submessage_level,
const std::vector<SubmessageStackElement>& submessage_stack,
StateMachineNode& node) {
const bool is_implicit = internal::IsImplicit(node.callback_type);
StateMachineNodeTemplate* node_template = node.node_template;
if (node_template->tag ==
static_cast<uint32_t>(internal::MessageId::kStartOfSubmessage)) {
if (skipped_submessage_level > 0) {
node.callback_type = internal::CallbackType::kSkippedSubmessageStart;
} else {
node.callback_type = internal::CallbackType::kSubmessageStart;
}
} else {
FieldIncluded field_included = FieldIncluded::kNo;
uint32_t field_id = kInvalidPos;
if (skipped_submessage_level == 0) {
field_included = FieldIncluded::kExistenceOnly;
for (const SubmessageStackElement& elem : submessage_stack) {
const absl::optional<ReadFromStringResult<uint32_t>> tag = ReadVarint32(
elem.tag_data.data, elem.tag_data.data + kMaxLengthVarint32);
if (tag == absl::nullopt) RIEGELI_ASSERT_UNREACHABLE() << "Invalid tag";
const absl::flat_hash_map<std::pair<uint32_t, int>,
Context::IncludedField>::const_iterator iter =
context.include_fields.find(
std::make_pair(field_id, GetTagFieldNumber(tag->value)));
if (iter == context.include_fields.end()) {
field_included = FieldIncluded::kNo;
break;
}
if (iter->second.include_type == Context::IncludeType::kIncludeFully) {
field_included = FieldIncluded::kYes;
break;
}
field_id = iter->second.field_id;
}
}
// If tag is a `kStartGroup`, there are two options:
// 1. Either related `kEndGroup` was skipped and
// `skipped_submessage_level > 0`.
// In this case `field_included` is already set to `kNo`.
// 2. If `kEndGroup` was not skipped, then its tag is on the top of the
// `submessage_stack` and in that case we already checked its tag in
// `include_fields` in the loop above.
const bool start_group_tag =
GetTagWireType(node_template->tag) == WireType::kStartGroup;
if (!start_group_tag && field_included == FieldIncluded::kExistenceOnly) {
const absl::optional<ReadFromStringResult<uint32_t>> tag = ReadVarint32(
node.tag_data.data, node.tag_data.data + kMaxLengthVarint32);
if (tag == absl::nullopt) RIEGELI_ASSERT_UNREACHABLE() << "Invalid tag";
const absl::flat_hash_map<std::pair<uint32_t, int>,
Context::IncludedField>::const_iterator iter =
context.include_fields.find(
std::make_pair(field_id, GetTagFieldNumber(tag->value)));
if (iter == context.include_fields.end()) {
field_included = FieldIncluded::kNo;
} else {
if (iter->second.include_type == Context::IncludeType::kIncludeFully ||
iter->second.include_type == Context::IncludeType::kIncludeChild) {
field_included = FieldIncluded::kYes;
}
}
}
if (node_template->bucket_index != kInvalidPos) {
switch (field_included) {
case FieldIncluded::kYes:
node.buffer = GetBuffer(context, node_template->bucket_index,
node_template->buffer_within_bucket_index);
if (ABSL_PREDICT_FALSE(node.buffer == nullptr)) return false;
break;
case FieldIncluded::kNo:
node.buffer = kEmptyReader();
break;
case FieldIncluded::kExistenceOnly:
node.buffer = kEmptyReader();
break;
}
} else {
node.buffer = kEmptyReader();
}
node.callback_type = GetCallbackType(field_included, node_template->tag,
node_template->subtype,
node_template->tag_length, true);
if (field_included == FieldIncluded::kExistenceOnly &&
GetTagWireType(node_template->tag) == WireType::kVarint) {
// The tag in `TagData` was followed by a subtype but must be followed by
// zero now.
node.tag_data.data[node_template->tag_length] = 0;
}
}
if (is_implicit) node.callback_type |= internal::CallbackType::kImplicit;
return true;
}
} // namespace riegeli
| 44.228532
| 80
| 0.625012
|
micahcc
|
a9535ad47f6b89cf6a3acf5dd0e465351471bf41
| 2,450
|
cpp
|
C++
|
src/renderer/framebuffer/framebuffer.cpp
|
LwRuan/RainEngine
|
0bf3c009190e86cf1b81a692ce26eb26646aca3c
|
[
"MIT"
] | null | null | null |
src/renderer/framebuffer/framebuffer.cpp
|
LwRuan/RainEngine
|
0bf3c009190e86cf1b81a692ce26eb26646aca3c
|
[
"MIT"
] | null | null | null |
src/renderer/framebuffer/framebuffer.cpp
|
LwRuan/RainEngine
|
0bf3c009190e86cf1b81a692ce26eb26646aca3c
|
[
"MIT"
] | null | null | null |
#include "framebuffer.h"
#include <array>
namespace Rain {
VkResult Framebuffer::Init(Device* device, const VkExtent2D& extent,
VkImageView swap_image_view,
VkRenderPass render_pass) {
VkResult result;
result = depth_image_.InitDepthImage(device, extent.width, extent.height);
if (result != VK_SUCCESS) return result;
swap_image_view_ = swap_image_view;
std::array<VkImageView, 2> attachments = {swap_image_view_,
depth_image_.view_};
VkFramebufferCreateInfo framebuffer_info{};
framebuffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebuffer_info.renderPass = render_pass;
framebuffer_info.attachmentCount = static_cast<uint32_t>(attachments.size());
framebuffer_info.pAttachments = attachments.data();
framebuffer_info.width = extent.width;
framebuffer_info.height = extent.height;
framebuffer_info.layers = 1;
result = vkCreateFramebuffer(device->device_, &framebuffer_info, nullptr,
&framebuffer_);
if (result != VK_SUCCESS) {
spdlog::error("framebuffer creation failed");
}
return result;
};
void Framebuffer::Destroy(VkDevice device) {
depth_image_.Destroy(device);
if (framebuffer_ != VK_NULL_HANDLE) {
vkDestroyFramebuffer(device, framebuffer_, nullptr);
}
}
VkResult ImGuiFramebuffer::Init(Device* device, const VkExtent2D& extent,
VkImageView swap_image_view,
VkRenderPass render_pass) {
VkResult result;
swap_image_view_ = swap_image_view;
VkFramebufferCreateInfo framebuffer_info{};
framebuffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebuffer_info.renderPass = render_pass;
framebuffer_info.attachmentCount = 1;
framebuffer_info.pAttachments = &swap_image_view_;
framebuffer_info.width = extent.width;
framebuffer_info.height = extent.height;
framebuffer_info.layers = 1;
result = vkCreateFramebuffer(device->device_, &framebuffer_info, nullptr,
&framebuffer_);
if (result != VK_SUCCESS) {
spdlog::error("framebuffer creation failed");
}
return result;
};
void ImGuiFramebuffer::Destroy(VkDevice device) {
if (framebuffer_ != VK_NULL_HANDLE) {
vkDestroyFramebuffer(device, framebuffer_, nullptr);
}
}
}; // namespace Rain
| 35.507246
| 80
| 0.686122
|
LwRuan
|
a95712a2a03874c7e67627c172c11dd6add22efe
| 4,952
|
cpp
|
C++
|
src/Time/TimeSteppers/AdamsBashforthN.cpp
|
AntoniRamosBuades/spectre
|
85dbdb5889e6ac7251e37b570495b0a601763ec8
|
[
"MIT"
] | null | null | null |
src/Time/TimeSteppers/AdamsBashforthN.cpp
|
AntoniRamosBuades/spectre
|
85dbdb5889e6ac7251e37b570495b0a601763ec8
|
[
"MIT"
] | 1
|
2022-03-25T18:26:16.000Z
|
2022-03-25T19:30:39.000Z
|
src/Time/TimeSteppers/AdamsBashforthN.cpp
|
isaaclegred/spectre
|
5765da85dad680cad992daccd479376c67458a8c
|
[
"MIT"
] | null | null | null |
// Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Time/TimeSteppers/AdamsBashforthN.hpp"
#include <algorithm>
#include "Time/TimeStepId.hpp"
#include "Utilities/Math.hpp"
namespace TimeSteppers {
AdamsBashforthN::AdamsBashforthN(const size_t order) noexcept : order_(order) {
if (order_ < 1 or order_ > maximum_order) {
ERROR("The order for Adams-Bashforth Nth order must be 1 <= order <= "
<< maximum_order);
}
}
size_t AdamsBashforthN::order() const noexcept { return order_; }
size_t AdamsBashforthN::error_estimate_order() const noexcept {
return order_ - 1;
}
size_t AdamsBashforthN::number_of_past_steps() const noexcept {
return order_ - 1;
}
double AdamsBashforthN::stable_step() const noexcept {
if (order_ == 1) {
return 1.;
}
// This is the condition that the characteristic polynomial of the
// recurrence relation defined by the method has the correct sign at
// -1. It is not clear whether this is actually sufficient.
const auto& coefficients = constant_coefficients(order_);
double invstep = 0.;
double sign = 1.;
for (const auto coef : coefficients) {
invstep += sign * coef;
sign = -sign;
}
return 1. / invstep;
}
TimeStepId AdamsBashforthN::next_time_id(
const TimeStepId& current_id,
const TimeDelta& time_step) const noexcept {
ASSERT(current_id.substep() == 0, "Adams-Bashforth should not have substeps");
return {current_id.time_runs_forward(), current_id.slab_number(),
current_id.step_time() + time_step};
}
std::vector<double> AdamsBashforthN::get_coefficients_impl(
const std::vector<double>& steps) noexcept {
const size_t order = steps.size();
ASSERT(order >= 1 and order <= maximum_order, "Bad order" << order);
if (std::all_of(steps.begin(), steps.end(),
[&steps](const double s) { return s == steps[0]; })) {
return constant_coefficients(order);
}
return variable_coefficients(steps);
}
std::vector<double> AdamsBashforthN::variable_coefficients(
const std::vector<double>& steps) noexcept {
const size_t order = steps.size(); // "k" in below equations
std::vector<double> result;
result.reserve(order);
// The `steps` vector contains the step sizes:
// steps = {dt_{n-k+1}, ..., dt_n}
// Our goal is to calculate, for each j, the coefficient given by
// \int_0^1 dt ell_j(t dt_n; dt_n, dt_n + dt_{n-1}, ...,
// dt_n + ... + dt_{n-k+1})
// (Where the ell_j are the Lagrange interpolating polynomials.)
std::vector<double> poly(order);
double step_sum_j = 0.0;
for (size_t j = 0; j < order; ++j) {
// Calculate coefficients of the Lagrange interpolating polynomials,
// in the standard a_0 + a_1 t + a_2 t^2 + ... form.
std::fill(poly.begin(), poly.end(), 0.0);
step_sum_j += steps[order - j - 1];
poly[0] = 1.0;
double step_sum_m = 0.0;
for (size_t m = 0; m < order; ++m) {
step_sum_m += steps[order - m - 1];
if (m == j) {
continue;
}
const double denom = 1.0 / (step_sum_j - step_sum_m);
for (size_t i = m < j ? m + 1 : m; i > 0; --i) {
poly[i] = (poly[i - 1] - poly[i] * step_sum_m) * denom;
}
poly[0] *= -step_sum_m * denom;
}
// Integrate p(t dt_n), term by term.
for (size_t m = 0; m < order; ++m) {
poly[m] /= m + 1.0;
}
result.push_back(evaluate_polynomial(poly, steps.back()));
}
return result;
}
std::vector<double> AdamsBashforthN::constant_coefficients(
const size_t order) noexcept {
switch (order) {
case 1: return {1.};
case 2: return {1.5, -0.5};
case 3: return {23.0 / 12.0, -4.0 / 3.0, 5.0 / 12.0};
case 4: return {55.0 / 24.0, -59.0 / 24.0, 37.0 / 24.0, -3.0 / 8.0};
case 5: return {1901.0 / 720.0, -1387.0 / 360.0, 109.0 / 30.0,
-637.0 / 360.0, 251.0 / 720.0};
case 6: return {4277.0 / 1440.0, -2641.0 / 480.0, 4991.0 / 720.0,
-3649.0 / 720.0, 959.0 / 480.0, -95.0 / 288.0};
case 7: return {198721.0 / 60480.0, -18637.0 / 2520.0, 235183.0 / 20160.0,
-10754.0 / 945.0, 135713.0 / 20160.0, -5603.0 / 2520.0,
19087.0 / 60480.0};
case 8: return {16083.0 / 4480.0, -1152169.0 / 120960.0, 242653.0 / 13440.0,
-296053.0 / 13440.0, 2102243.0 / 120960.0, -115747.0 / 13440.0,
32863.0 / 13440.0, -5257.0 / 17280.0};
default:
ERROR("Bad order: " << order);
}
}
void AdamsBashforthN::pup(PUP::er& p) noexcept {
LtsTimeStepper::Inherit::pup(p);
p | order_;
}
bool operator==(const AdamsBashforthN& lhs,
const AdamsBashforthN& rhs) noexcept {
return lhs.order_ == rhs.order_;
}
bool operator!=(const AdamsBashforthN& lhs,
const AdamsBashforthN& rhs) noexcept {
return not(lhs == rhs);
}
} // namespace TimeSteppers
/// \cond
PUP::able::PUP_ID TimeSteppers::AdamsBashforthN::my_PUP_ID = // NOLINT
0;
/// \endcond
| 31.948387
| 80
| 0.621567
|
AntoniRamosBuades
|
a9642c0a926c70c35c32e649897d45e1f63de7e6
| 7,390
|
cpp
|
C++
|
src/lib/analysis/TextUtil.cpp
|
jqswang/txsampler
|
19d2b188e712dd86be84d84c75e08af320304c2c
|
[
"BSD-3-Clause"
] | 1
|
2018-11-18T17:44:22.000Z
|
2018-11-18T17:44:22.000Z
|
src/lib/analysis/TextUtil.cpp
|
jqswang/txsampler
|
19d2b188e712dd86be84d84c75e08af320304c2c
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/analysis/TextUtil.cpp
|
jqswang/txsampler
|
19d2b188e712dd86be84d84c75e08af320304c2c
|
[
"BSD-3-Clause"
] | null | null | null |
// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2016, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//
// File:
// $HeadURL$
//
// Purpose:
// [The purpose of this file]
//
// Description:
// [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************
//************************* System Include Files ****************************
#include <iostream>
using std::ostream;
#include <iomanip>
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <algorithm>
#include <typeinfo>
#include <cmath> // pow
//*************************** User Include Files ****************************
#include "TextUtil.hpp"
#include <lib/support/diagnostics.h>
//*************************** Forward Declarations ***************************
//****************************************************************************
namespace Analysis {
namespace TextUtil {
ColumnFormatter::ColumnFormatter(const Prof::Metric::Mgr& metricMgr,
ostream& os,
int numDecPct, int numDecVal)
: m_mMgr(metricMgr),
m_os(os),
m_numDecPct(numDecPct),
m_numDecVal(numDecVal),
m_annotWidthTot(0)
{
m_annotWidth.resize(m_mMgr.size(), 0);
m_sciFmtLoThrsh_pct.resize(m_mMgr.size(), 0.0);
m_sciFmtHiThrsh_pct.resize(m_mMgr.size(), 0.0);
m_sciFmtLoThrsh_val.resize(m_mMgr.size(), 0.0);
m_sciFmtHiThrsh_val.resize(m_mMgr.size(), 0.0);
m_dispPercent.resize(m_mMgr.size(), false);
m_isForceable.resize(m_mMgr.size(), false);
for (uint mId = 0; mId < m_mMgr.size(); ++mId) {
const Prof::Metric::ADesc* m = m_mMgr.metric(mId);
if (!m->isVisible()) {
continue;
}
m_isForceable[mId] = (typeid(*m) == typeid(Prof::Metric::SampledDesc)
|| !m->isPercent());
// Compute annotation widths.
// NOTE: decimal digits shown as 'd' below
if (m->doDispPercent()) {
m_dispPercent[mId] = true;
if (m_numDecPct >= 1) {
// xxx.dd% or x.dE-yy% (latter for small values)
m_annotWidth[mId] = std::max(8, 5 + m_numDecPct);
}
else {
// xxx%
m_annotWidth[mId] = 4;
}
}
else {
// x.dd or x.dE+yy (latter for large numbers)
m_annotWidth[mId] = std::max(7, 2 + m_numDecVal);
}
// compute threshholds
int nNonUnitsPct = (m_numDecPct == 0) ? 1 : m_numDecPct + 2; // . + %
int nNonUnitsVal = (m_numDecVal == 0) ? 0 : m_numDecVal + 1; // .
int nUnitsPct = std::max(0, m_annotWidth[mId] - nNonUnitsPct);
int nUnitsVal = std::max(0, m_annotWidth[mId] - nNonUnitsVal);
m_sciFmtHiThrsh_pct[mId] = std::pow(10.0, (double)nUnitsPct);
m_sciFmtHiThrsh_val[mId] = std::pow(10.0, (double)nUnitsVal);
m_sciFmtLoThrsh_pct[mId] = std::pow(10.0, (double)-m_numDecPct);
m_sciFmtLoThrsh_val[mId] = std::pow(10.0, (double)-m_numDecVal);
m_annotWidthTot += m_annotWidth[mId] + 1/*space*/;
}
m_os.setf(std::ios_base::fmtflags(0), std::ios_base::floatfield);
m_os << std::right << std::noshowpos;
m_os << std::showbase;
}
void
ColumnFormatter::genColHeaderSummary()
{
m_os << "Metric definitions. column: name (nice-name) [units] {details}:\n";
uint colId = 1;
for (uint mId = 0; mId < m_mMgr.size(); ++mId) {
const Prof::Metric::ADesc* m = m_mMgr.metric(mId);
m_os << std::fixed << std::setw(4) << std::setfill(' ');
if (m->isVisible()) {
m_os << colId;
colId++;
}
else {
m_os << "-";
}
m_os << ": " << m->toString() << std::endl;
}
}
void
ColumnFormatter::genCol(uint mId, double metricVal, double metricTot,
ColumnFormatter::Flag flg)
{
if (!isDisplayed(mId)) {
return;
}
bool dispPercent = m_dispPercent[mId];
if (flg != Flag_NULL && m_isForceable[mId]) {
dispPercent = (flg == Flag_ForcePct);
}
double val = metricVal;
if (dispPercent) {
// convert 'val' to a percent if necessary
const Prof::Metric::ADesc* m = m_mMgr.metric(mId);
if (!m->isPercent() && metricTot != 0.0) {
val = (metricVal / metricTot) * 100.0; // make the percent
}
m_os << std::showpoint << std::setw(m_annotWidth[mId] - 1);
if (val != 0.0 &&
(val < m_sciFmtLoThrsh_pct[mId] || val >= m_sciFmtHiThrsh_pct[mId])) {
m_os << std::scientific
<< std::setprecision(m_annotWidth[mId] - 7); // x.dE-yy%
}
else {
m_os << std::fixed
<< std::setprecision(m_numDecPct);
}
m_os << std::setfill(' ') << val << "%";
}
else {
m_os << std::setw(m_annotWidth[mId]);
if (val != 0.0 &&
(val < m_sciFmtLoThrsh_val[mId] || val >= m_sciFmtHiThrsh_val[mId])) {
m_os << std::scientific
<< std::setprecision(m_annotWidth[mId] - 6); // x.dE+yy
}
else {
m_os << std::fixed;
if (m_numDecVal == 0) {
m_os << std::noshowpoint << std::setprecision(0);
}
else {
m_os << std::setprecision(m_numDecVal);
}
}
m_os << std::setfill(' ') << val;
}
m_os << " ";
}
void
ColumnFormatter::genBlankCol(uint mId)
{
//const PerfMetric* m = m_mMgr.metric(mId);
if (!isDisplayed(mId)) {
return;
}
m_os << std::setw(m_annotWidth[mId]) << std::setfill(' ') << " " << " ";
}
//****************************************************************************
} // namespace TextUtil
} // namespace Analysis
| 28.980392
| 78
| 0.58065
|
jqswang
|
a965effac86ca241c16790a4171f1f5111331927
| 706
|
cpp
|
C++
|
sources/src/structure/object.cpp
|
sydelity-net/EDACurry
|
20cbf9835827e42efeb0b3686bf6b3e9d72417e9
|
[
"MIT"
] | null | null | null |
sources/src/structure/object.cpp
|
sydelity-net/EDACurry
|
20cbf9835827e42efeb0b3686bf6b3e9d72417e9
|
[
"MIT"
] | null | null | null |
sources/src/structure/object.cpp
|
sydelity-net/EDACurry
|
20cbf9835827e42efeb0b3686bf6b3e9d72417e9
|
[
"MIT"
] | null | null | null |
/// @file object.cpp
/// @author Enrico Fraccaroli (enrico.fraccaroli@gmail.com)
/// @copyright Copyright (c) 2021 sydelity.net (info@sydelity.com)
/// Distributed under the MIT License (MIT) (See accompanying LICENSE file or
/// copy at http://opensource.org/licenses/MIT)
#include "structure/object.hpp"
namespace edacurry::structure
{
Object::Object(Object *parent)
: _parent(parent)
{
// Nothing to do.
}
Object *Object::getParent() const
{
return _parent;
}
Object *Object::setParent(Object *parent)
{
Object *old_parent = _parent;
_parent = parent;
return old_parent;
}
std::string Object::toString() const
{
return "Object";
}
} // namespace edacurry::structure
| 20.171429
| 77
| 0.695467
|
sydelity-net
|
a965f76c4cfa7496db45c18395d37947f25d4011
| 7,106
|
cpp
|
C++
|
inspire/thread/thdMgr.cpp
|
tynia/tynia
|
9dd2a09faafa9d38c2679fa32e25a4db1317095e
|
[
"MIT"
] | null | null | null |
inspire/thread/thdMgr.cpp
|
tynia/tynia
|
9dd2a09faafa9d38c2679fa32e25a4db1317095e
|
[
"MIT"
] | null | null | null |
inspire/thread/thdMgr.cpp
|
tynia/tynia
|
9dd2a09faafa9d38c2679fa32e25a4db1317095e
|
[
"MIT"
] | null | null | null |
#include "thdMgr.h"
namespace inspire {
const int thdMgr::thdInnerTask::run()
{
LogEvent("starting MAIN PROCESS LOOP: %s", name());
while (_thd->running())
{
_thdMgr->_process();
}
LogEvent("ending MAIN PROCESS LOOP: %s", name());
return _thd->error();
}
thdMgr* thdMgr::instance()
{
static thdMgr mgr;
return &mgr;
}
thdMgr::thdMgr() : _maxIdleCount(10)
{
_taskMgr = thdTaskMgr::instance();
}
thdMgr::~thdMgr()
{
_taskMgr = NULL;
}
void thdMgr::initialize()
{
thdTask* t = new thdInnerTask(this);
STRONG_ASSERT(NULL != t, "Failed to allocate event processing task");
thread* thd = create();
STRONG_ASSERT(NULL != thd, "cannot start event processing thread, exit");
detach(thd);
_thdMain = thd;
_thdMain->assigned(t);
}
void thdMgr::active()
{
STRONG_ASSERT(NULL != _thdMain, "event processing thread is NULL");
_thdMain->active();
}
void thdMgr::destroy()
{
LogEvent("signal to exit, program is going stopping");
_thdMain->join();
while (!_eventQueue.empty())
{
_process();
}
{
std::set<thread*>& rset = _totalSet.raw();
std::set<thread*>::iterator it = rset.begin();
for (; rset.end() != it; ++it)
{
thread* thd = (*it);
thd->join();
delete thd;
}
}
delete _thdMain;
_thdMain = NULL;
}
void thdMgr::_process()
{
thdEvent ev;
if (_eventQueue.pop_front(ev))
{
switch (ev.evType)
{
case EVENT_DISPATCH_TASK:
{
thdTask* task = (thdTask*)ev.evObject;
_dispatch(task);
}
break;
case EVENT_THREAD_SUSPEND:
{
thread* thd = (thread*)ev.evObject;
thd->suspend();
break;
}
case EVENT_THREAD_RUNNING:
{
thread* thd = (thread*)ev.evObject;
thd->active();
}
break;
case EVENT_THREAD_RESUME:
{
thread* thd = (thread*)ev.evObject;
thd->resume();
}
break;
case EVENT_THREAD_RELEASE:
{
thread* thd = (thread*)ev.evObject;
_release(thd);
}
break;
case EVENT_DUMMY:
default:
LogError("receive a dummy or unknown event, type: %d", ev.evType);
break;
}
}
else
{
utilSleep(100);
}
}
void thdMgr::reverseIdleCount(const uint maxCount)
{
_maxIdleCount = maxCount;
}
thread* thdMgr::_fetchIdle()
{
thread* thd = NULL;
if (_idleQueue.pop_front(thd))
{
if (THREAD_IDLE != thd->state())
{
// when a thread pooled and pushed to idle queue
// its state may not be THREAD_IDLE
// so we need to fetch next to support request
_enIdle(thd);
}
else
{
LogEvent("fetch a idle thread from idle queue, thread id: %lld", thd->tid());
return thd;
}
}
return thd;
}
thread* thdMgr::create()
{
int rc = 0;
thread* thd = _acquire();
if (NULL == thd)
{
thd = new thread(this);
if (NULL == thd)
{
LogError("failed to create thread, out of memory");
// if hit there, log had been written
return NULL;
}
LogEvent("allocate a thread object");
}
rc = thd->create();
if (rc)
{
LogError("create thread failed in start thread");
return NULL;
}
// let's record it
// if object is existed already, it cannot be inserted
_totalSet.insert(thd);
return thd;
}
void thdMgr::recycle(thread* thd)
{
INSPIRE_ASSERT(NULL != thd, "try to recycle a NULL thread");
thdTask* task = thd->fetch();
if (NULL != task)
{
// clean task attached in thread
thd->assigned(NULL);
// we should notify task manager to release task
_taskMgr->over(task);
}
if (!thd->detached())
{
// signal to manager to destroy the thread
postEvent(EVENT_THREAD_RELEASE, thd);
// suspend the thread
thd->suspend();
}
}
bool thdMgr::postEvent(const char t, void* pObj)
{
INSPIRE_ASSERT(EVENT_DUMMY < t && t < EVENT_THREAD_UPBOUND,
"notify with an dummy or unknown type: %d", t);
INSPIRE_ASSERT(NULL != pObj, "notify with invalid object");
if (!_thdMain->running() && EVENT_DISPATCH_TASK == t)
{
thdTask* task = (thdTask*)pObj;
LogError("a exit signal received, do not accept task dispatch event "
"any more, task id: %lld, name:[%s]", task->id(), task->name());
}
else
{
thdEvent ev(t, pObj);
_eventQueue.push_back(ev);
return true;
}
return false;
}
bool thdMgr::postEvent(thdTask* task)
{
return postEvent(EVENT_DISPATCH_TASK, task);
}
void thdMgr::_enIdle(thread* thd)
{
_idleQueue.push_back(thd);
}
void thdMgr::_release(thread* thd)
{
INSPIRE_ASSERT(NULL != thd, "try to recycle a NULL thread");
if (_thdMain->running() && _idleQueue.size() < _maxIdleCount)
{
// push the thread to idle
LogEvent("recycle a thread into idle queue, thread id: %lld", thd->tid());
_enIdle(thd);
}
else
{
// join thread until it exit
thd->join();
// now the thread object didn't contains real thread process function
// we store it into thread queue
// until it acquired and start new thread process for next use
_thdQueue.push_back(thd);
}
}
thread* thdMgr::_acquire()
{
thread* thd = NULL;
if (_thdQueue.pop_front(thd))
{
LogEvent("fetch a thread object from thread queue");
return thd;
}
return NULL;
}
void thdMgr::_dispatch(thdTask* task)
{
INSPIRE_ASSERT(NULL != task, "try to despatch a NULL task");
if (task)
{
thread* thd = _fetchIdle();
if (NULL == thd)
{
thd = create();
if (NULL == thd)
{
LogError("cannot allocate a new thread object");
// we failed to allocate a thread object,
// now we should push the task into task queue
postEvent(EVENT_DISPATCH_TASK, task);
}
}
LogEvent("dispatch task: %lld to thread: %lld", task->id(), thd->tid());
thd->assigned(task);
thd->active();
}
}
void thdMgr::detach(thread* thd)
{
LogEvent("detach thread: %lld from manager map", thd->tid());
_totalSet.erase(thd);
thd->detach();
}
}
| 24.088136
| 89
| 0.513791
|
tynia
|
a9685065ca5dc50d3c30e5bb0986e2268a7b5e21
| 2,855
|
cpp
|
C++
|
pub/SharedNativeUtils/FileImage.cpp
|
AndreGleichner/UniversalModuleHost
|
a8434ad712295a9ff156c3344ed9faedae75ca14
|
[
"MIT"
] | null | null | null |
pub/SharedNativeUtils/FileImage.cpp
|
AndreGleichner/UniversalModuleHost
|
a8434ad712295a9ff156c3344ed9faedae75ca14
|
[
"MIT"
] | null | null | null |
pub/SharedNativeUtils/FileImage.cpp
|
AndreGleichner/UniversalModuleHost
|
a8434ad712295a9ff156c3344ed9faedae75ca14
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "FileImage.h"
#include <cstdint>
#include <share.h>
#include <vector>
#include <wil/resource.h>
#include <magic_enum.hpp>
using namespace magic_enum::bitwise_operators;
namespace
{
uint16_t ReadWord(const std::vector<uint8_t>& buffer, uint32_t offset)
{
if (offset + 2 > buffer.size())
throw std::exception();
return *(uint16_t*)&buffer[offset];
}
uint16_t ReadDWord(const std::vector<uint8_t>& buffer, uint32_t offset)
{
if (offset + 4 > buffer.size())
throw std::exception();
return *(uint32_t*)&buffer[offset];
}
}
namespace FileImage
{
Kind GetKind(PCWSTR path)
{
// https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
// The offset of the PE header pointer in the DOS header as a DWORD.
const uint32_t PeHeaderFileOffset = 0x3C;
// The PE header starts with a signature "PE\0\0".
const uint32_t PeFileSignature = 0x5A4D;
// The offset in the PE header to a WORD with bits like IMAGE_FILE_EXECUTABLE_IMAGE and IMAGE_FILE_DLL
const uint32_t CharacteristicsPeOffset = sizeof(PeFileSignature) + 18;
// The offset in the PE header where the optional header starts
const uint32_t OptionalHeaderPeOffset = 24;
// The optional header starts with a magic WORD:
const uint16_t MagicPe32 = 0x010B;
const uint16_t MagicPe64 = 0x020B;
// The offset in the PE header where the CLR header RVA is located,
const uint32_t ClrHeaderPeOffset32 = OptionalHeaderPeOffset + 208;
const uint32_t ClrHeaderPeOffset64 = OptionalHeaderPeOffset + 224;
try
{
wil::unique_file file(_wfsopen(path, L"rb", _SH_DENYNO));
if (!file)
return Kind::Unknown;
std::vector<uint8_t> buffer;
buffer.resize(1024);
size_t bytesRead = ::fread(&buffer[0], 1, buffer.size(), file.get());
buffer.resize(bytesRead);
uint32_t peStart = ReadDWord(buffer, PeHeaderFileOffset);
uint16_t characteristic = ReadWord(buffer, peStart + CharacteristicsPeOffset);
if ((characteristic & IMAGE_FILE_EXECUTABLE_IMAGE) == 0)
return Kind::Unknown;
Kind kind = (characteristic & IMAGE_FILE_DLL) != 0 ? Kind::Dll : Kind::Exe;
uint16_t magic = ReadWord(buffer, peStart + OptionalHeaderPeOffset);
if (magic != MagicPe32 && magic != MagicPe64)
return Kind::Unknown;
bool isPe32 = magic == MagicPe32;
kind |= isPe32 ? Kind::Bitness32 : Kind::Bitness64;
uint32_t clrHeaderRva = ReadDWord(buffer, peStart + (isPe32 ? ClrHeaderPeOffset32 : ClrHeaderPeOffset64));
kind |= clrHeaderRva != 0 ? Kind::Managed : Kind::Native;
return kind;
}
catch (...)
{
return Kind::Unknown;
}
}
}
| 30.698925
| 115
| 0.646935
|
AndreGleichner
|
a96c53f9cad3a1cbf019391e897376b82ae7f881
| 659
|
hpp
|
C++
|
foreign.hpp
|
lechos22/PSON
|
507721136c38c306fab633ea3d50f73c65a4c16e
|
[
"BSD-3-Clause"
] | 1
|
2021-12-09T20:27:28.000Z
|
2021-12-09T20:27:28.000Z
|
foreign.hpp
|
lechos22/PSON
|
507721136c38c306fab633ea3d50f73c65a4c16e
|
[
"BSD-3-Clause"
] | null | null | null |
foreign.hpp
|
lechos22/PSON
|
507721136c38c306fab633ea3d50f73c65a4c16e
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef PSON__FOREIGN_HPP
#define PSON__FOREIGN_HPP
#include <PSON_PY.hpp>
extern void* parse(const char* s);
extern char get_type(void* obj);
extern int get_int(void* obj);
extern float get_float(void* obj);
extern const char* get_str(void* obj);
extern unsigned get_len(void* obj);
extern void* get_at(void* obj, unsigned idx);
extern void* get_map_at(void* obj, const char* idx);
extern const char* get_map_next(void* iter);
extern bool get_map_iter_alive(void* obj, void* iter);
extern bool get_map_contains(void* obj, const char* idx);
extern void* get_map_iter(void* iter);
extern void destroy_iter(void* iter);
extern void destroy(void* obj);
#endif
| 31.380952
| 57
| 0.766313
|
lechos22
|
a975ace87094dfeed41d04926bfd599091aea35f
| 614
|
cpp
|
C++
|
src/xcroscpp/src/libros/xcroscpp_common.cpp
|
dogchenya/xc-ros
|
43c8b773a552ea610bd03750c9c32d7732f8ea69
|
[
"Unlicense"
] | null | null | null |
src/xcroscpp/src/libros/xcroscpp_common.cpp
|
dogchenya/xc-ros
|
43c8b773a552ea610bd03750c9c32d7732f8ea69
|
[
"Unlicense"
] | null | null | null |
src/xcroscpp/src/libros/xcroscpp_common.cpp
|
dogchenya/xc-ros
|
43c8b773a552ea610bd03750c9c32d7732f8ea69
|
[
"Unlicense"
] | null | null | null |
#include "ros/xcroscpp_common.h"
#include <cstdlib>
#include <cstdio>
#include <cerrno>
#include <cassert>
#include <sys/types.h>
#if !defined(WIN32)
#include <unistd.h>
#include <pthread.h>
#endif
#include <signal.h>
using std::string;
void xcros::disableAllSignalsInThisThread()
{
#if !defined(WIN32)
// pthreads_win32, despite having an implementation of pthread_sigmask,
// doesn't have an implementation of sigset_t, and also doesn't expose its
// pthread_sigmask externally.
sigset_t signal_set;
/* block all signals */
sigfillset( &signal_set );
pthread_sigmask( SIG_BLOCK, &signal_set, NULL );
#endif
}
| 21.928571
| 74
| 0.754072
|
dogchenya
|
a97ab59cbb36d1c7e887d13c463612a942e9105e
| 19,462
|
cc
|
C++
|
packages/solver/test/tst_Pincell.cc
|
brbass/ibex
|
5a4cc5b4d6d46430d9667970f8a34f37177953d4
|
[
"MIT"
] | 2
|
2020-04-13T20:06:41.000Z
|
2021-02-12T17:55:54.000Z
|
packages/solver/test/tst_Pincell.cc
|
brbass/ibex
|
5a4cc5b4d6d46430d9667970f8a34f37177953d4
|
[
"MIT"
] | 1
|
2018-10-22T21:03:35.000Z
|
2018-10-22T21:03:35.000Z
|
packages/solver/test/tst_Pincell.cc
|
brbass/ibex
|
5a4cc5b4d6d46430d9667970f8a34f37177953d4
|
[
"MIT"
] | 3
|
2019-04-03T02:15:37.000Z
|
2022-01-04T05:50:23.000Z
|
#include <cmath>
#include <iomanip>
#include <iostream>
#include <mpi.h>
#include "Angular_Discretization.hh"
#include "Angular_Discretization_Factory.hh"
#include "Angular_Discretization_Parser.hh"
#include "Boundary_Source.hh"
#include "Boundary_Source_Parser.hh"
#include "Cartesian_Plane.hh"
#include "Check_Equality.hh"
#include "Constructive_Solid_Geometry.hh"
#include "Constructive_Solid_Geometry_Parser.hh"
#include "Cross_Section.hh"
#include "Cylinder_2D.hh"
#include "Discrete_Value_Operator.hh"
#include "Energy_Discretization.hh"
#include "Energy_Discretization_Parser.hh"
#include "Krylov_Eigenvalue.hh"
#include "Krylov_Steady_State.hh"
#include "Linf_Convergence.hh"
#include "Material.hh"
#include "Material_Factory.hh"
#include "Material_Parser.hh"
#include "Region.hh"
#include "Solver_Factory.hh"
#include "Source_Iteration.hh"
#include "Timer.hh"
#include "Transport_Discretization.hh"
#include "Weak_Spatial_Discretization.hh"
#include "Weak_Spatial_Discretization_Factory.hh"
#include "Weak_Spatial_Discretization_Parser.hh"
#include "Weak_Meshless_Sweep.hh"
namespace ce = Check_Equality;
using namespace std;
void get_pincell(bool basis_mls,
bool weight_mls,
string basis_type,
string weight_type,
shared_ptr<Weight_Function_Options> weight_options,
shared_ptr<Weak_Spatial_Discretization_Options> weak_options,
string method,
int dimension,
int angular_rule,
int num_dimensional_points,
double radius_num_intervals,
shared_ptr<Weak_Spatial_Discretization> &spatial,
shared_ptr<Angular_Discretization> &angular,
shared_ptr<Energy_Discretization> &energy,
shared_ptr<Transport_Discretization> &transport,
shared_ptr<Constructive_Solid_Geometry> &solid,
vector<shared_ptr<Material> > &materials,
vector<shared_ptr<Boundary_Source> > &boundary_sources,
shared_ptr<Meshless_Sweep> &sweeper,
shared_ptr<Convergence_Measure> &convergence,
shared_ptr<Solver> &solver)
{
// Set constants
double length = 4.0;
// Get angular discretization
int number_of_moments = 1;
Angular_Discretization_Factory angular_factory;
angular = angular_factory.get_angular_discretization(dimension,
number_of_moments,
angular_rule);
// Get energy discretization
int number_of_groups = 1;
energy = make_shared<Energy_Discretization>(number_of_groups);
// Get material
materials.resize(2);
Material_Factory material_factory(angular,
energy);
materials[0]
= material_factory.get_standard_material(0, // index
{1.0}, // sigma_t
{0.84}, // sigma_s
{2.4}, // nu
{0.1}, // sigma_f
{1}, // chi
{0.0}); // internal source
materials[1]
= material_factory.get_standard_material(1, // index
{2.0}, // sigma_t
{1.9}, // sigma_s
{0.0}, // nu
{0.0}, // sigma_f
{0.0}, // chi
{0.0}); // internal source
// Get boundary source
Boundary_Source::Dependencies boundary_dependencies;
if (dimension == 1)
{
boundary_sources.resize(2);
boundary_sources[0]
= make_shared<Boundary_Source>(0, // index
boundary_dependencies,
angular,
energy,
vector<double>(number_of_groups, 0), // boundary source
vector<double>(number_of_groups, 1.0)); // alpha
boundary_sources[1]
= make_shared<Boundary_Source>(1, // index
boundary_dependencies,
angular,
energy,
vector<double>(number_of_groups, 0), // boundary source
vector<double>(number_of_groups, 0.0)); // alpha
}
else
{
boundary_sources.resize(1);
boundary_sources[0]
= make_shared<Boundary_Source>(1, // index
boundary_dependencies,
angular,
energy,
vector<double>(number_of_groups, 0), // boundary source
vector<double>(number_of_groups, 0.0)); // alpha
}
// Get solid geometry
vector<shared_ptr<Surface> > surfaces(2 * dimension + 1);
vector<shared_ptr<Region> > regions(2);
// Get Cartesian boundaries
for (int d = 0; d < dimension; ++d)
{
int index1 = 0 + 2 * d;
surfaces[index1]
= make_shared<Cartesian_Plane>(index1,
dimension,
Surface::Surface_Type::BOUNDARY,
d,
-0.5 * length,
-1);
int index2 = 1 + 2 * d;
surfaces[index2]
= make_shared<Cartesian_Plane>(index2,
dimension,
Surface::Surface_Type::BOUNDARY,
d,
0.5 * length,
1);
}
// Get internal boundaries: plane for 1D, cylinder for 2D
if (dimension == 1)
{
surfaces[2]
= make_shared<Cartesian_Plane>(2, // index
dimension,
Surface::Surface_Type::INTERNAL,
0, // dimension of surface
0., // position of surface
1.); // normal
surfaces[0]->set_boundary_source(boundary_sources[0]);
surfaces[1]->set_boundary_source(boundary_sources[1]);
}
else
{
vector<double> origin = {0, 0};
surfaces[2 * dimension]
= make_shared<Cylinder_2D>(2 * dimension, // index
Surface::Surface_Type::INTERNAL,
length / 4, // radius
origin);
for (int i = 0; i < 2 * dimension; ++i)
{
surfaces[i]->set_boundary_source(boundary_sources[0]);
}
}
// Create regions
if (dimension == 1)
{
// Fuel region
vector<Surface::Relation> fuel_relations
= {Surface::Relation::NEGATIVE,
Surface::Relation::NEGATIVE};
vector<shared_ptr<Surface> > fuel_surfaces
= {surfaces[0],
surfaces[2]};
regions[0]
= make_shared<Region>(0, // index
materials[0],
fuel_relations,
fuel_surfaces);
// Moderator region
vector<Surface::Relation> mod_relations
= {Surface::Relation::POSITIVE,
Surface::Relation::NEGATIVE};
vector<shared_ptr<Surface> > mod_surfaces
= {surfaces[2],
surfaces[1]};
regions[1]
= make_shared<Region>(1, // index
materials[1],
mod_relations,
mod_surfaces);
}
else // dimension == 2
{
// Fuel region
vector<Surface::Relation> fuel_relations
= {Surface::Relation::INSIDE};
vector<shared_ptr<Surface> > fuel_surfaces
= {surfaces[4]};
regions[0]
= make_shared<Region>(0, // index
materials[0],
fuel_relations,
fuel_surfaces);
// Moderator region: all surfaces used
vector<Surface::Relation> mod_relations
= {Surface::Relation::NEGATIVE,
Surface::Relation::NEGATIVE,
Surface::Relation::NEGATIVE,
Surface::Relation::NEGATIVE,
Surface::Relation::OUTSIDE};
regions[1]
= make_shared<Region>(1, // index
materials[1],
mod_relations,
surfaces);
}
// Create solid geometry
solid
= make_shared<Constructive_Solid_Geometry>(dimension,
surfaces,
regions,
materials,
boundary_sources);
// Get spatial discretization
Weak_Spatial_Discretization_Factory spatial_factory(solid,
solid->cartesian_boundary_surfaces());
spatial = spatial_factory.get_simple_discretization(num_dimensional_points,
radius_num_intervals,
basis_mls,
weight_mls,
basis_type,
weight_type,
weight_options,
weak_options);
// Get transport discretization
transport
= make_shared<Transport_Discretization>(spatial,
angular,
energy);
// Get weak RBF sweep
Meshless_Sweep::Options options;
options.solver = Meshless_Sweep::Options::Solver::AZTEC_IFPACK;
sweeper
= make_shared<Weak_Meshless_Sweep>(options,
spatial,
angular,
energy,
transport);
// Get convergence method
convergence
= make_shared<Linf_Convergence>();
// Get source iteration
Solver_Factory solver_factory(spatial,
angular,
energy,
transport);
if (method == "krylov_eigenvalue")
{
solver
= solver_factory.get_krylov_eigenvalue(sweeper);
}
else
{
AssertMsg(false, "iteration method not found");
}
}
int test_pincell(bool basis_mls,
bool weight_mls,
string basis_type,
string weight_type,
shared_ptr<Weight_Function_Options> weight_options,
shared_ptr<Weak_Spatial_Discretization_Options> weak_options,
string method,
int dimension,
int angular_rule,
int num_dimensional_points,
double radius_num_intervals,
double tolerance)
{
int checksum = 0;
Timer timer1;
timer1.start();
Timer timer2;
timer2.start();
int w = 16;
bool print = true;
// Initialize pointers
shared_ptr<Weak_Spatial_Discretization> spatial;
shared_ptr<Angular_Discretization> angular;
shared_ptr<Energy_Discretization> energy;
shared_ptr<Transport_Discretization> transport;
shared_ptr<Constructive_Solid_Geometry> solid;
vector<shared_ptr<Material> > materials;
vector<shared_ptr<Boundary_Source> > boundary_sources;
shared_ptr<Meshless_Sweep> sweeper;
shared_ptr<Convergence_Measure> convergence;
shared_ptr<Solver> solver;
// Get problem
get_pincell(basis_mls,
weight_mls,
basis_type,
weight_type,
weight_options,
weak_options,
method,
dimension,
angular_rule,
num_dimensional_points,
radius_num_intervals,
spatial,
angular,
energy,
transport,
solid,
materials,
boundary_sources,
sweeper,
convergence,
solver);
timer2.stop();
// Solve problem
solver->solve();
shared_ptr<Solver::Result> result
= solver->result();
// Eigenvalue problem
double expected = dimension == 1 ? 1.13928374494 : 0.48246;
double calculated = result->k_eigenvalue;
if (!ce::approx(expected, calculated, tolerance))
{
cerr << setw(w) << "FAILED" << endl;
checksum += 1;
}
timer1.stop();
// Print results
if (print)
{
cout << setprecision(10);
cout << setw(w) << "init time" << setw(w) << timer2.time() << endl;
cout << setw(w) << "total time" << setw(w) << timer1.time() << endl;
cout << setw(w) << "expected" << setw(w) << expected << endl;
cout << setw(w) << "eigenvalue" << setw(w) << result->k_eigenvalue << endl;
cout << setw(w) << "pcm" << setw(w) << (expected - result->k_eigenvalue) * 1e5 << endl;
}
cout << endl;
return checksum;
}
int run_tests(bool mls_basis,
bool mls_weight,
bool supg,
string basis_type,
string weight_type)
{
int checksum = 0;
shared_ptr<Weight_Function_Options> weight_options
= make_shared<Weight_Function_Options>();
shared_ptr<Weak_Spatial_Discretization_Options> weak_options
= make_shared<Weak_Spatial_Discretization_Options>();
weak_options->include_supg = supg;
// Test 1D eigenvalue
{
double number_of_intervals = 3.0;
weak_options->integration_ordinates = 16;
weak_options->external_integral_calculation = true;
weight_options->tau_const = 1.0;
weak_options->tau_scaling = Weak_Spatial_Discretization_Options::Tau_Scaling::NONE;
string description = (!weak_options->include_supg
? "1D, standard, "
: "1D, SUPG, ");
description += basis_type + ", " + weight_type + ", ";
description += to_string(number_of_intervals) + ", ";
description += to_string(mls_basis) + ", ";
description += to_string(mls_weight) + ", ";
vector<int> point_vals = {256, 512};
for (int number_of_points : point_vals)
{
cout << description << "eigenvalue, krylov, n = " << number_of_points << endl;
checksum += test_pincell(mls_basis,
mls_weight,
basis_type,
weight_type,
weight_options,
weak_options,
"krylov_eigenvalue",
1, // dimension
256, // ordinates
number_of_points, // number of points
number_of_intervals, // number of intervals
1e-3); // tolerance
}
}
// Run 2D problems
{
double number_of_intervals = 1.5;
weak_options->integration_ordinates = 16;
weak_options->external_integral_calculation = true;
weight_options->tau_const = 1.0;
weak_options->tau_scaling = Weak_Spatial_Discretization_Options::Tau_Scaling::NONE;
string description = (!weak_options->include_supg
? "2D, standard, "
: "2D, SUPG, ");
description += basis_type + ", " + weight_type + ", ";
description += to_string(number_of_intervals) + ", ";
description += to_string(mls_basis) + ", ";
description += to_string(mls_weight) + ", ";
// Test 2D eigenvalue
vector<int> point_vals = {32, 48};
for (int number_of_points : point_vals)
{
cout << description << "eigenvalue, krylov, n = " << number_of_points << endl;
checksum += test_pincell(mls_basis,
mls_weight,
basis_type,
weight_type,
weight_options,
weak_options,
"krylov_eigenvalue",
2, // dimension
2, // angular rule
number_of_points, // number of points
number_of_intervals, // number of intervals
1e-3); // tolerance
}
}
return checksum;
}
int main(int argc, char **argv)
{
int checksum = 0;
if (argc != 2)
{
cerr << "tst_pincell [test_num]" << endl;
return -1;
}
// Initialize MPI
MPI_Init(&argc, &argv);
int test_num = atoi(argv[1]);
switch (test_num)
{
case 0:
checksum += run_tests(false,
false,
false,
"wendland11",
"wendland11");
break;
case 1:
checksum += run_tests(false,
false,
true,
"wendland11",
"wendland11");
break;
case 2:
checksum += run_tests(true,
true,
false,
"wendland11",
"wendland11");
break;
case 3:
checksum += run_tests(true,
true,
true,
"wendland11",
"wendland11");
break;
}
// Close MPI
MPI_Finalize();
return checksum;
}
| 37.863813
| 98
| 0.462902
|
brbass
|
a97bd313294dc528d0e37ed0cec0ffa5de0d4078
| 1,391
|
cpp
|
C++
|
source/examples/HelloWorld/HelloWorld.cpp
|
MrHands/Panini
|
464999debf6ad6ee9f2184514ba719062f8375b5
|
[
"MIT-0"
] | null | null | null |
source/examples/HelloWorld/HelloWorld.cpp
|
MrHands/Panini
|
464999debf6ad6ee9f2184514ba719062f8375b5
|
[
"MIT-0"
] | null | null | null |
source/examples/HelloWorld/HelloWorld.cpp
|
MrHands/Panini
|
464999debf6ad6ee9f2184514ba719062f8375b5
|
[
"MIT-0"
] | null | null | null |
/*
MIT No Attribution
Copyright 2021-2022 Mr. Hands
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.
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 <Panini.hpp>
int main(int argc, char** argv)
{
using namespace panini;
ConsoleWriter writer;
writer << Include("iostream", IncludeStyle::AngularBrackets) << NextLine();
writer << NextLine();
writer << Scope("int main(int argc, char** argv)", [](WriterBase& writer)
{
writer << R"(std::cout << "Hello, World!" << std::endl;)" << NextLine();
writer << NextLine();
writer << "return 0;" << NextLine();
}) << NextLine();
return 0;
}
| 30.911111
| 77
| 0.728972
|
MrHands
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.