hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
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
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
6bbafe361a24d13f13f2ce88299b158674dcc6e7
4,654
cpp
C++
tools/utilities/print/src/PrintGraph.cpp
harshmittal2210/ELL
83ee904a638badb922febd8b9d6f3a1155679181
[ "MIT" ]
null
null
null
tools/utilities/print/src/PrintGraph.cpp
harshmittal2210/ELL
83ee904a638badb922febd8b9d6f3a1155679181
[ "MIT" ]
null
null
null
tools/utilities/print/src/PrintGraph.cpp
harshmittal2210/ELL
83ee904a638badb922febd8b9d6f3a1155679181
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: PrintGraph.cpp (print) // Authors: Chris Lovett // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "LayerInspector.h" #include "PrintModel.h" #include <utilities/include/Exception.h> #include <utilities/include/Graph.h> #include <utilities/include/OutputStreamImpostor.h> #include <model/include/InputPort.h> #include <model/include/Model.h> #include <model/include/Node.h> #include <nodes/include/NeuralNetworkPredictorNode.h> #include <iostream> #include <string> using namespace ell::utilities; using namespace ell::model; namespace ell { extern std::string PaddingSchemeToString(ell::predictors::neural::PaddingScheme scheme); std::string PrintActiveSize(const Port* port) { std::string shape; if (port != nullptr) { auto layout = port->GetMemoryLayout(); auto memoryShape = layout.GetActiveSize().ToVector(); for (int i : memoryShape) { if (shape.size() > 0) { shape += ","; } shape += std::to_string(i); } } return shape; } std::vector<NameValue> InspectNodeProperties(const Node& node) { std::vector<NameValue> result; utilities::PropertyBag properties = node.GetMetadata(); for (auto key : properties.Keys()) { std::string value = properties[key].ToString(); result.push_back(NameValue{ key, value }); } if (node.NumInputPorts() > 0) { std::string inputShape = PrintActiveSize(node.GetInputPort(0)); result.push_back(NameValue{ "input", inputShape }); } if (node.NumOutputPorts() > 0) { std::string outputShape = PrintActiveSize(node.GetOutputPort(0)); result.push_back(NameValue{ "output", outputShape }); } return result; } void PrintGraph(const Model& model, const std::string& outputFormat, std::ostream& out, bool includeNodeId) { // dump DGML graph of model Graph graph; model.Visit([&](const Node& node) { std::string typeName = node.GetRuntimeTypeName(); std::string label = typeName; GraphNode& childNode = graph.GetOrCreateNode(to_string(node.GetId()), label); if (typeName == "NeuralNetworkPredictorNode<float>") { const ell::nodes::NeuralNetworkPredictorNode<float>& predictorNode = dynamic_cast<const ell::nodes::NeuralNetworkPredictorNode<float>&>(node); auto predictor = predictorNode.GetPredictor(); auto layers = predictor.GetLayers(); GraphNode& previousLayer = childNode; int layerId = 0; for (auto ptr = layers.begin(), end = layers.end(); ptr != end; ptr++, layerId++) { std::shared_ptr<ell::predictors::neural::Layer<float>> layer = *ptr; std::string layerName = layer->GetRuntimeTypeName(); GraphNode& layerNode = graph.GetOrCreateNode(layerName + "(" + std::to_string(layerId) + ")", layerName); std::vector<NameValue> result = InspectLayerParameters<float>(*layer); for (auto ptr = result.begin(), end = result.end(); ptr != end; ptr++) { NameValue nv = *ptr; layerNode.SetProperty(nv.name, nv.value); } graph.GetOrCreateLink(previousLayer, layerNode, "dependson"); previousLayer = layerNode; // chain them together. } } else { std::vector<NameValue> result = InspectNodeProperties(node); for (auto ptr = result.begin(), end = result.end(); ptr != end; ptr++) { NameValue nv = *ptr; childNode.SetProperty(nv.name, nv.value); } auto dependencies = node.GetDependentNodes(); for (auto ptr = dependencies.begin(), end = dependencies.end(); ptr != end; ptr++) { const Node* upstream = *ptr; if (upstream != nullptr) { label = upstream->GetRuntimeTypeName(); GraphNode& nextNode = graph.GetOrCreateNode(to_string(upstream->GetId()), label); graph.GetOrCreateLink(childNode, nextNode, ""); } } } }); if (outputFormat == "dgml") { graph.SaveDgml(out); } else { graph.SaveDot(out); } } } // namespace ell
33.724638
154
0.5578
[ "shape", "vector", "model" ]
6bc6eb123535d580fc7cfc8a1ba7e2cbe67a832d
12,901
cpp
C++
lib/straight/synthesis/main.cpp
qingyundou/tacotron_qdou
aca014e8ea73bbab617029b81368cee235f47ce2
[ "MIT" ]
2
2020-12-16T12:53:52.000Z
2021-09-18T06:52:05.000Z
lib/straight/synthesis/main.cpp
qingyundou/tacotron_qdou
aca014e8ea73bbab617029b81368cee235f47ce2
[ "MIT" ]
null
null
null
lib/straight/synthesis/main.cpp
qingyundou/tacotron_qdou
aca014e8ea73bbab617029b81368cee235f47ce2
[ "MIT" ]
1
2021-03-05T03:44:39.000Z
2021-03-05T03:44:39.000Z
/* * main.c : main function of straight * * coded by H.Banno 1996/12/25 * coded by H.Banno 1996/12/25 * * modified by T. Toda 2001/2/12 * V30k18 (matlab) * * modified by J. Yamagishi from 2007 to 2010 * * STRAIGHT Synthesis applied to HMM Speech Synthesis * coded by T. Toda * * Tomoki Toda (tomoki.toda@atr.co.jp) * From Mar. 2001 to Sep. 2003 * * Junichi Yamagishi (jyamagis@inf.ed.ac.uk) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "fileio.h" #include "option.h" #include "voperate.h" #include "straight_sub.h" #include "straight_body_sub.h" #include "straight_synth_sub.h" #include "straight_synth_tb06.h" typedef struct CONDITION_STRUCT { double fs; /* Sampling frequency [Hz] */ double shiftm; /* Frame shift (ms) */ long fftl; /* FFT length */ long dim; /* dimension of cepstrum */ double sigp; double delsp; /* Standard deviation of group delay (ms) */ double gdbw; /* Finest resolution in group delay (Hz) */ double cornf; /* Lower corner frequency for random phase (Hz) */ double delfrac; /* Ratio of standard deviation of group delay */ double pc; double fc; double sc; char *apfile; /* Aperiodic energy */ XBOOL df_flag; /* Proportional group delay */ XBOOL mel_flag; /* Use Mel cepstrum */ double alpha; /* Frequency warping factor for all-pass filter used for mel-cepstrum */ XBOOL spec_flag; /* Use spectrum (disable mel_flag) */ XBOOL bap_flag; /* Band-limited aperiodicity flag */ XBOOL float_flag; /* float format */ XBOOL wav_flag; /* wav file */ XBOOL msg_flag; /* print message */ XBOOL help_flag; } CONDITION; CONDITION cond = {16000.0, 5.0, 1024, 24, 0.0, 0.5, 70.0, 3500.0, 0.2, 1.0, 1.0, 1.0, NULL, XFALSE, XFALSE, 0.42, XFALSE, XFALSE, XFALSE, XTRUE, XTRUE, XFALSE}; #define NUM_ARGFILE 3 ARGFILE argfile_struct[] = { {"[f0file]", NULL}, {"[cepfile]", NULL}, {"[outputfile]", NULL}, }; #define NUM_OPTION 20 OPTION option_struct[] = { {"-f", NULL, "sampling frequency [Hz]", "samp_freq", NULL, TYPE_DOUBLE, &cond.fs, XFALSE}, {"-shift", NULL, "frame shift [ms]", "shift", NULL, TYPE_DOUBLE, &cond.shiftm, XFALSE}, {"-fftl", NULL, "fft length", "fft_length", NULL, TYPE_LONG, &cond.fftl, XFALSE}, {"-order", NULL, "cepstrum order", "order", NULL, TYPE_LONG, &cond.dim, XFALSE}, {"-sigp", NULL, "sigmoid parameter", "sigp", NULL, TYPE_DOUBLE, &cond.sigp, XFALSE}, {"-sd", NULL, "standard deviation of group delay", "sd", NULL, TYPE_DOUBLE, &cond.delsp, XFALSE}, {"-bw", NULL, "band width of group delay ", "bw", NULL, TYPE_DOUBLE, &cond.gdbw, XFALSE}, {"-cornf", NULL, "corner frequency for random phase", "cornf", NULL, TYPE_DOUBLE, &cond.cornf, XFALSE}, {"-delfrac", NULL, "ratio of stand. dev. of group delay", "delfrac", NULL, TYPE_DOUBLE, &cond.delfrac, XFALSE}, {"-pc", NULL, "pitch scale conversion", "pc", NULL, TYPE_DOUBLE, &cond.pc, XFALSE}, {"-fc", NULL, "frequency scale conversion", "fc", NULL, TYPE_DOUBLE, &cond.fc, XFALSE}, {"-sc", NULL, "time scale conversion", "sc", NULL, TYPE_DOUBLE, &cond.sc, XFALSE}, {"-apfile", NULL, "aperiodic energy file", "apfile", NULL, TYPE_STRING, &cond.apfile, XFALSE}, {"-df", NULL, "using proportional group delay", NULL, NULL, TYPE_BOOLEAN, &cond.df_flag, XFALSE}, {"-mel", NULL, "Use mel cepstrum", NULL, NULL, TYPE_BOOLEAN, &cond.mel_flag, XFALSE}, {"-alpha", NULL, "warping factor", "alpha", NULL, TYPE_DOUBLE, &cond.alpha, XFALSE}, {"-spec", NULL, "Use spectrum", NULL, NULL, TYPE_BOOLEAN, &cond.spec_flag, XFALSE}, {"-bap", NULL, "Band-limited aperiodicity", NULL, NULL, TYPE_BOOLEAN, &cond.bap_flag, XFALSE}, {"-float", NULL, "input float cepstrogram", NULL, NULL, TYPE_BOOLEAN, &cond.float_flag, XFALSE}, {"-raw", NULL, "output raw file (16 bit short)", NULL, NULL, TYPE_BOOLEAN, &cond.wav_flag, XFALSE}, {"-nmsg", NULL, "no message", NULL, NULL, TYPE_BOOLEAN, &cond.msg_flag, XFALSE}, {"-help", "-h", "display this message", NULL, NULL, TYPE_BOOLEAN, &cond.help_flag, XFALSE}, }; OPTIONS options_struct = { NULL, 1, NUM_OPTION, option_struct, NUM_ARGFILE, argfile_struct, }; /* main */ int main(int argc, char *argv[]) { int i, fc; long k; SVECTOR xo = NODATA; DVECTOR sy = NODATA; DVECTORS f0info = NODATA; DMATRIX spg = NODATA; /* DMATRIX dapv = NODATA; */ DMATRIX ap = NODATA; /* get program name */ options_struct.progname = xgetbasicname(argv[0]); /* get option */ for (i = 1, fc = 0; i < argc; i++) { if (getoption(argc, argv, &i, &options_struct) == UNKNOWN) getargfile(argv[i], &fc, &options_struct); } /* display message */ if (cond.help_flag == XTRUE) printhelp(options_struct, "Speech Transformation and Representation using Adaptive Interpolaiton of weiGHTed spectrogram"); if (fc != options_struct.num_file) printerr(options_struct, "not enough files"); if((cond.mel_flag == XTRUE) && (cond.spec_flag == XTRUE)){ fprintf(stderr, "straight: can't use mel flag and spec flag at the same time. Please choose one of them.\n"); exit(1); } /* read f0 file */ f0info = xdvsalloc(2); if ((f0info->vector[0] = xreaddvector_txt(options_struct.file[0].name)) == NODATA) { fprintf(stderr, "straight: can't read F0 file\n"); exit(1); } if (cond.msg_flag == XTRUE) fprintf(stderr, "read F0[%ld]\n", f0info->vector[0]->length); if(cond.spec_flag == XTRUE){ /* read spectrum directly */ if (cond.float_flag == XFALSE) { // double binary if ((spg = xreaddmatrix(options_struct.file[1].name, cond.fftl / 2 + 1, 0)) == NODATA) { fprintf(stderr, "straight: can't read spectrum file\n"); exit(1); } } else { // float binary if ((spg=xreadf2dmatrix(options_struct.file[1].name, cond.fftl / 2 + 1, 0)) == NODATA) { fprintf(stderr, "straight: can't read spectrum file\n"); exit(1); } } fprintf(stderr, "read spectrum[%ld][%ld]\n", spg->row, spg->col); }else{ /* read mel-cepstrum or cepstrum file and convert to spectrum */ if ((spg = xread_dfcep2spg(options_struct.file[1].name, cond.dim + 1, cond.fftl, cond.mel_flag, cond.float_flag, XFALSE, 20.0, cond.fs, cond.alpha)) == NODATA) { fprintf(stderr, "straight: can't read cepstrogram file\n"); exit(1); }else{ if (cond.msg_flag == XTRUE) { if(cond.mel_flag==XTRUE) fprintf(stderr, "read Mel Cepstrogram [%f]-> ",cond.alpha); else fprintf(stderr, "read Cepstrogram -> "); fprintf(stderr, " Spectrogram[%ld][%ld]\n", spg->row, spg->col); } } } // if (0) { // writedmatrix(options_struct.file[2].name, spg, 0); // exit(1); //} // read aperiodic energy file if (!strnone(cond.apfile)) { /* aperiodicity files --> mixed exciation */ if (cond.bap_flag == XTRUE) { // band-limited aperiodicity case /* Calc number of critical bands and their edge frequency from sampling frequency Added by J. Yamagishi (28 March 2010) Reference http://en.wikipedia.org/wiki/Bark_scale Zwicker, E. (1961), "Subdivision of the audible frequency range into critical bands," The Journal of the Acoustical Society of America, 33, Feb., 1961. H. Traunmuller (1990) "Analytical expressions for the tonotopic sensory scale" J. Acoust. Soc. Am. 88: 97-100. */ int nq, numbands; float fbark; // Calc the number of critical bands required for sampling frequency nq = cond.fs / 2; fbark = 26.81 * nq / (1960 + nq ) - 0.53; if(fbark<2) fbark += 0.15*(2-fbark); if(fbark>20.1) fbark += 0.22*(fbark-20.1); numbands = (int) (fbark + 0.5); if (cond.float_flag == XFALSE) { // double if ( ((ap = xreaddmatrix(cond.apfile, numbands, 0))==NODATA) || ( ap->row != f0info->vector[0]->length ) ) { // do the classic mode (5 bands) if ((ap = xreaddmatrix(cond.apfile, 5, 0)) == NODATA) { fprintf(stderr, "straight: can't read aperiodic energy file\n"); exit(1); } } } else { // float if ((ap = xreadf2dmatrix(cond.apfile, numbands, 0)) == NODATA) { fprintf(stderr, "straight: can't read aperiodic energy file\n"); exit(1); } } /* if frame-shift periods of F0 and aperiodicty are different, do interpolation */ /* if ((ap = aperiodiccomp(dapv, cond.shiftm, f0info->vector[0], cond.shiftm)) == NODATA) { fprintf(stderr, "straight: aperiodic energy interpolation failed\n"); exit(1); }*/ /* memory free */ /* xdmfree(dapv); */ }else{ // Aperiodicity case (fft/2 + 1) if (cond.float_flag == XFALSE) { // double if ((ap = xreaddmatrix(cond.apfile, cond.fftl / 2 + 1, 0)) == NODATA) { fprintf(stderr, "straight: can't read aperiodic energy file\n"); exit(1); } } else { // float if ((ap=xreadf2dmatrix(cond.apfile, cond.fftl / 2 + 1, 0)) == NODATA) { fprintf(stderr, "straight: can't read aperiodic energy file\n"); exit(1); } } } if (cond.msg_flag == XTRUE) fprintf(stderr, "read aperiodic energy[%ld][%ld]\n", ap->row, ap->col); /* synthesize speech */ if (cond.msg_flag == XTRUE) fprintf(stderr, " === STRAIGHT synthesis (graded excitation) ===\n"); if ((sy = straight_synth_tb06ca(spg, f0info->vector[0], cond.fs, cond.shiftm, cond.sigp, cond.pc, cond.fc, cond.sc, cond.gdbw, cond.delsp, cond.cornf, cond.delfrac, ap, NODATA, cond.bap_flag, XTRUE, XFALSE, XTRUE, cond.df_flag)) == NODATA){ fprintf(stderr, "straight: straight synth failed\n"); exit(1); } else { if (cond.msg_flag == XTRUE) fprintf(stderr, "straight synthesis done\n"); } /* memory free */ xdmfree(ap); } else { /* No aperiodicity files --> Simple exciation */ /* f0 variation (voiced / unvoiced) */ f0info->vector[1] = xdvalloc(f0info->vector[0]->length); for (k = 0; k < f0info->vector[0]->length; k++) { if (f0info->vector[0]->data[k] != 0.0) { f0info->vector[1]->data[k] = 0.0; } else { f0info->vector[1]->data[k] = 1.0; } } /* synthesize speech */ if (cond.msg_flag == XTRUE) fprintf(stderr, " === STRAIGHT Synthesis ===\n"); if ((sy = straight_synth_tb06(spg, f0info->vector[0], f0info->vector[1], cond.fs, cond.shiftm, cond.pc, cond.fc, cond.sc, cond.gdbw, cond.delsp, cond.cornf, cond.delfrac, XTRUE, XFALSE, XTRUE, cond.df_flag)) == NODATA) { fprintf(stderr, "straight: straight synth failed\n"); exit(1); } else { if (cond.msg_flag == XTRUE) fprintf(stderr, "straight synthesis done\n"); } } /* write wave data */ xo = xdvtos(sy); if (cond.wav_flag == XTRUE) { writessignal_wav(options_struct.file[2].name, xo, cond.fs); } else { writessignal(options_struct.file[2].name, xo, 0); } if (cond.msg_flag == XTRUE) fprintf(stderr, "write wave: %s\n", options_struct.file[2].name); /* memory free */ xdmfree(spg); xdvfree(sy); xdvsfree(f0info); xsvfree(xo); return 0; }
36.754986
135
0.53895
[ "vector" ]
6bc9a93cc6df67384a15822586863e93b9ad82b4
3,490
cpp
C++
Classes/SpriteWithFilter.cpp
luwei2012/Filters
d9cd4dc60f2e90643723999d0b6184307bb409b6
[ "MIT" ]
1
2015-08-13T07:54:25.000Z
2015-08-13T07:54:25.000Z
Classes/SpriteWithFilter.cpp
luwei2012/Filters
d9cd4dc60f2e90643723999d0b6184307bb409b6
[ "MIT" ]
null
null
null
Classes/SpriteWithFilter.cpp
luwei2012/Filters
d9cd4dc60f2e90643723999d0b6184307bb409b6
[ "MIT" ]
2
2018-04-14T06:11:22.000Z
2019-06-25T02:17:08.000Z
// // SpriteWithFilterWithFilter.cpp // MyPlane // // Created by 陆伟 on 15-1-17. // // #include "SpriteWithFilter.h" SpriteWithFilter::SpriteWithFilter(){ _filter = nullptr; } SpriteWithFilter::~SpriteWithFilter() { CC_SAFE_RELEASE_NULL(_filter); } SpriteWithFilter* SpriteWithFilter::createWithTexture(Texture2D *texture) { SpriteWithFilter *spriteWithFilter = new (std::nothrow) SpriteWithFilter(); if (spriteWithFilter && spriteWithFilter->initWithTexture(texture)) { spriteWithFilter->autorelease(); return spriteWithFilter; } CC_SAFE_DELETE(spriteWithFilter); return nullptr; } SpriteWithFilter* SpriteWithFilter::createWithTexture(Texture2D *texture, const Rect& rect, bool rotated) { SpriteWithFilter *spriteWithFilter = new (std::nothrow) SpriteWithFilter(); if (spriteWithFilter && spriteWithFilter->initWithTexture(texture, rect, rotated)) { spriteWithFilter->autorelease(); return spriteWithFilter; } CC_SAFE_DELETE(spriteWithFilter); return nullptr; } SpriteWithFilter* SpriteWithFilter::create(const std::string& filename) { SpriteWithFilter *spriteWithFilter = new (std::nothrow) SpriteWithFilter(); if (spriteWithFilter && spriteWithFilter->initWithFile(filename)) { spriteWithFilter->autorelease(); return spriteWithFilter; } CC_SAFE_DELETE(spriteWithFilter); return nullptr; } SpriteWithFilter* SpriteWithFilter::create(const std::string& filename, const Rect& rect) { SpriteWithFilter *spriteWithFilter = new (std::nothrow) SpriteWithFilter(); if (spriteWithFilter && spriteWithFilter->initWithFile(filename, rect)) { spriteWithFilter->autorelease(); return spriteWithFilter; } CC_SAFE_DELETE(spriteWithFilter); return nullptr; } SpriteWithFilter* SpriteWithFilter::createWithSpriteFrame(SpriteFrame *spriteFrame) { SpriteWithFilter *spriteWithFilter = new (std::nothrow) SpriteWithFilter(); if (spriteWithFilter && spriteWithFilter && spriteWithFilter->initWithSpriteFrame(spriteFrame)) { spriteWithFilter->autorelease(); return spriteWithFilter; } CC_SAFE_DELETE(spriteWithFilter); return nullptr; } SpriteWithFilter* SpriteWithFilter::createWithSpriteFrameName(const std::string& spriteFrameName) { SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); #if COCOS2D_DEBUG > 0 char msg[256] = {0}; sprintf(msg, "Invalid SpriteFrameName: %s", spriteFrameName.c_str()); CCASSERT(frame != nullptr, msg); #endif return createWithSpriteFrame(frame); } SpriteWithFilter* SpriteWithFilter::create() { SpriteWithFilter *spriteWithFilter = new (std::nothrow) SpriteWithFilter(); if (spriteWithFilter && spriteWithFilter->init()) { spriteWithFilter->autorelease(); return spriteWithFilter; } CC_SAFE_DELETE(spriteWithFilter); return nullptr; } void SpriteWithFilter::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags){ //do somthing if (_filter) { _filter->update(); } Sprite::draw(renderer, transform, flags); } void SpriteWithFilter::setFilter(Filter *var){ if (_filter != var) { CC_SAFE_RETAIN(var); CC_SAFE_RELEASE(_filter); _filter = var; } if(_filter){ _filter->initWithSprite(this); } } Filter* SpriteWithFilter::getFilter(){ return _filter; }
26.044776
105
0.707736
[ "transform" ]
6bd57c7ad1691e561ce8e2a73ea42361cea42130
688
cpp
C++
examples/02Physics/LevelEnd.cpp
Galhad/firestorm
3c1584b1e5b95f21d963b9cf226f6ec1a469d7af
[ "MIT" ]
null
null
null
examples/02Physics/LevelEnd.cpp
Galhad/firestorm
3c1584b1e5b95f21d963b9cf226f6ec1a469d7af
[ "MIT" ]
null
null
null
examples/02Physics/LevelEnd.cpp
Galhad/firestorm
3c1584b1e5b95f21d963b9cf226f6ec1a469d7af
[ "MIT" ]
null
null
null
#include "LevelEnd.hpp" #include "Labels.hpp" namespace fs::scene { void LevelEnd::create(io::InputManager& inputManager, fs::physics::PhysicsManager& physicsManager, const core::Vector2f& point1, const core::Vector2f& point2) { SceneNode::create(inputManager); b2BodyDef bodyDef; bodyDef.type = b2_staticBody; b2EdgeShape shape; shape.Set(b2Vec2(point1.x, point1.y), b2Vec2(point2.x, point2.y)); b2FixtureDef fixtureDef; fixtureDef.shape = &shape; createBodyComponent(physicsManager, bodyDef, fixtureDef); labels.insert(LABEL_LEVEL_END); } void LevelEnd::destroy() { SceneNode::destroy(); } }
20.235294
98
0.671512
[ "shape" ]
6bd956cea4603c5d62d68f87d937b1750df93f44
4,348
cpp
C++
pa/algorithm/lu_cpp_11.cpp
jsimck/uni
42ea184ccf3d9ecbffdea19b74ed13f3bc583137
[ "MIT" ]
null
null
null
pa/algorithm/lu_cpp_11.cpp
jsimck/uni
42ea184ccf3d9ecbffdea19b74ed13f3bc583137
[ "MIT" ]
null
null
null
pa/algorithm/lu_cpp_11.cpp
jsimck/uni
42ea184ccf3d9ecbffdea19b74ed13f3bc583137
[ "MIT" ]
null
null
null
#include <iostream> #include <functional> #include <mutex> #include "lu_cpp_11.h" #include "../utils/timer.h" void LUCpp11::swapCol(Mat &mat, ulong i1, ulong i2) { // Init threads in equal size of max HW concurrency std::vector<std::thread> threads(nThreads); const ulong N = mat.size; // Bind function using lambda expression to each thread for (size_t t = 0; t < nThreads; ++t) { threads[t] = std::thread(std::bind( [&](const ulong start, const ulong end) { // Start each thread for different parts of the array for (ulong i = start; i < end; ++i) { auto tmp = mat[i][i1]; mat[i][i1] = mat[i][i2]; mat[i][i2] = tmp; } }, t * (N / nThreads), (t + 1 == nThreads) ? N : (t + 1) * (N / nThreads)) ); } // Wait for all threads to finish (join) for (auto &thread : threads) { thread.join(); } } void LUCpp11::checkDiagonal(Mat &mat, Mat &permutation) { const ulong N = mat.size; bool valid; do { valid = true; for (ulong i = 0; i < N; ++i) { if (mat[i][i] == 0) { // Swap cols for (ulong j = i + 1; j < N; j++) { if (mat[j][j] != 0 && mat[i][j] != 0) { swapCol(mat, i, j); swapCol(permutation, i, j); break; } } } } // Check again for (ulong i = 0; i < N; ++i) { if (mat[i][i] == 0) { valid = false; break; } } } while (!valid); } void LUCpp11::computeGauss(Mat &mat, Mat &unit) { // Init threads array const ulong N = mat.size; std::vector<std::thread> threads(nThreads); auto *multipliers = new float[N + 1]; for (ulong k = 0; k < N - 1; k++) { // Get upper val const ulong kN = N - k; const ulong normNThreads = (nThreads > kN) ? kN : nThreads; float upperVal = (mat[k][k] == 0) ? 1 : mat[k][k]; // Calculate multipliers for each row const ulong nK = k + 1; for (size_t t = 0; t < normNThreads; ++t) { threads[t] = std::thread(std::bind( [&](const ulong start, const ulong end) { for (ulong i = start; i < end; i++) { multipliers[i] = -(mat[i][k] / upperVal); } }, t * (kN / normNThreads) + nK, (t + 1 == normNThreads) ? N : (t + 1) * (kN / normNThreads) + nK) ); } // Wait for all threads to finish (join) for (ulong j = 0; j < normNThreads; ++j) { threads[j].join(); } // Calc matrices for (size_t t = 0; t < normNThreads; ++t) { threads[t] = std::thread(std::bind( [&](const ulong start, const ulong end) { for (ulong y = start; y < end; y++) { for (ulong x = 0; x < N; x++) { mat[y][x] = mat[y][x] + (multipliers[y] * mat[k][x]); unit[y][x] = unit[y][x] + (multipliers[y] * unit[k][x]); } } }, t * (kN / normNThreads) + nK, (t + 1 == normNThreads) ? N : (t + 1) * (kN / normNThreads) + nK) ); } // Wait for all threads to finish (join) for (ulong j = 0; j < normNThreads; ++j) { threads[j].join(); } } delete[] multipliers; } void LUCpp11::calc(Mat &mat, Mat &upper, Mat &lower, Mat &permutation) { // Init matrices Mat unit = Mat::generateUnitMatrix(mat.size); permutation = unit; lower = unit; upper = mat; // Check if there are no zeros at diagonal, if yes fix it Timer t1; checkDiagonal(upper, permutation); std::cout << std::endl << "checkDiagonal() took: " << t1.elapsed() << "s" << std::endl; // Upper matrix Timer t2; computeGauss(upper, unit); std::cout << "computeGauss() took: " << t2.elapsed() << "s" << std::endl; // Lower matrix Timer t3; computeGauss(unit, lower); std::cout << "computeGauss() took: " << t3.elapsed() << "s" << std::endl; }
32.207407
114
0.455842
[ "vector" ]
6bdb6497b0beed007f0a903a3d891b8e99cc3439
2,596
cpp
C++
Spectrogram/SpectrogramWork.cpp
pothosware/PothosPlotters
4a9e7d1fa95915998856481f4180ee637497996f
[ "BSL-1.0" ]
9
2017-10-28T08:40:19.000Z
2021-12-06T03:30:22.000Z
Spectrogram/SpectrogramWork.cpp
BelmY/PothosPlotters
d77318ac56fec8204c07551b772dfc848461f3bf
[ "BSL-1.0" ]
13
2015-08-25T21:17:08.000Z
2017-08-19T18:11:03.000Z
Spectrogram/SpectrogramWork.cpp
pothosware/pothos-plotters
4a9e7d1fa95915998856481f4180ee637497996f
[ "BSL-1.0" ]
12
2018-01-03T15:32:34.000Z
2022-03-24T06:19:29.000Z
// Copyright (c) 2014-2016 Josh Blum // SPDX-License-Identifier: BSL-1.0 #include "SpectrogramDisplay.hpp" #include <qwt_plot.h> #include <QTimer> #include <complex> /*********************************************************************** * initialization functions **********************************************************************/ void SpectrogramDisplay::activate(void) { QMetaObject::invokeMethod(_replotTimer, "start", Qt::QueuedConnection); } void SpectrogramDisplay::deactivate(void) { QMetaObject::invokeMethod(_replotTimer, "stop", Qt::QueuedConnection); } /*********************************************************************** * work function **********************************************************************/ void SpectrogramDisplay::work(void) { auto updateRate = this->height()/_timeSpan; if (updateRate != _lastUpdateRate) this->call("updateRateChanged", updateRate); _lastUpdateRate = updateRate; auto inPort = this->input(0); if (not inPort->hasMessage()) return; const auto msg = inPort->popMessage(); //label-based messages have in-line commands if (msg.type() == typeid(Pothos::Label)) { const auto &label = msg.convert<Pothos::Label>(); if (label.id == _freqLabelId and label.data.canConvert(typeid(double))) { this->setCenterFrequency(label.data.convert<double>()); } if (label.id == _rateLabelId and label.data.canConvert(typeid(double))) { this->setSampleRate(label.data.convert<double>()); } } //packet-based messages have payloads to FFT if (msg.type() == typeid(Pothos::Packet)) { const auto &buff = msg.convert<Pothos::Packet>().payload; auto floatBuff = buff.convert(Pothos::DType(typeid(std::complex<float>)), buff.elements()); //safe guard against FFT size changes, old buffers could still be in-flight if (floatBuff.elements() != this->numFFTBins()) return; //handle automatic FFT mode if (_fftModeAutomatic) { const bool isComplex = buff.dtype.isComplex(); const bool changed = _fftModeComplex != isComplex; _fftModeComplex = isComplex; if (changed) QMetaObject::invokeMethod(this, "handleUpdateAxis", Qt::QueuedConnection); } //power bins to points on the curve CArray fftBins(floatBuff.as<const std::complex<float> *>(), this->numFFTBins()); const auto powerBins = _fftPowerSpectrum.transform(fftBins, _fullScale); this->appendBins(powerBins); } }
35.561644
99
0.581664
[ "transform" ]
6bdea206a7b4f3cfae92a96c310aab0b79c80a0c
29,293
cpp
C++
src/axom/sidre/tests/sidre_mfem_datacollection.cpp
bmhan12/axom
fbee125aec6357340f35b6fd5d0d4a62a3c80733
[ "BSD-3-Clause" ]
86
2019-04-12T20:39:37.000Z
2022-01-28T17:06:08.000Z
src/axom/sidre/tests/sidre_mfem_datacollection.cpp
bmhan12/axom
fbee125aec6357340f35b6fd5d0d4a62a3c80733
[ "BSD-3-Clause" ]
597
2019-04-25T22:36:16.000Z
2022-03-31T20:21:54.000Z
src/axom/sidre/tests/sidre_mfem_datacollection.cpp
bmhan12/axom
fbee125aec6357340f35b6fd5d0d4a62a3c80733
[ "BSD-3-Clause" ]
21
2019-06-27T15:53:08.000Z
2021-09-30T20:17:41.000Z
// Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level LICENSE file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "axom/config.hpp" #include "axom/slic.hpp" #ifndef AXOM_USE_MFEM #error This file requires MFEM #endif #include "mfem.hpp" #include "gtest/gtest.h" #include "axom/sidre/core/sidre.hpp" #include "axom/sidre/core/MFEMSidreDataCollection.hpp" #ifdef AXOM_USE_MPI #include "mpi.h" #endif using axom::sidre::Group; using axom::sidre::MFEMSidreDataCollection; const double EPSILON = 1.0e-6; std::string testName() { return ::testing::UnitTest::GetInstance()->current_test_info()->name(); } TEST(sidre_datacollection, dc_alloc_no_mesh) { MFEMSidreDataCollection sdc(testName()); EXPECT_TRUE(sdc.verifyMeshBlueprint()); } TEST(sidre_datacollection, dc_alloc_owning_mesh) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); bool owns_mesh = true; MFEMSidreDataCollection sdc(testName(), &mesh, owns_mesh); EXPECT_TRUE(sdc.verifyMeshBlueprint()); } TEST(sidre_datacollection, dc_alloc_nonowning_mesh) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); bool owns_mesh = false; MFEMSidreDataCollection sdc(testName(), &mesh, owns_mesh); EXPECT_TRUE(sdc.verifyMeshBlueprint()); } TEST(sidre_datacollection, dc_register_empty_field) { MFEMSidreDataCollection sdc(testName()); mfem::GridFunction gf; sdc.RegisterField("test_field", &gf); EXPECT_TRUE(sdc.verifyMeshBlueprint()); } TEST(sidre_datacollection, dc_register_partial_field) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); mfem::H1_FECollection fec(2); mfem::FiniteElementSpace fes(&mesh, &fec); mfem::GridFunction gf(&fes); MFEMSidreDataCollection sdc(testName(), &mesh); sdc.RegisterField("test_field", &gf); EXPECT_TRUE(sdc.verifyMeshBlueprint()); } TEST(sidre_datacollection, dc_update_state) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); MFEMSidreDataCollection sdc(testName(), &mesh); // Arbitrary values for the "state" part of blueprint sdc.SetCycle(3); sdc.SetTime(1.1); sdc.SetTimeStep(0.4); // Force refresh from the superclass sdc.UpdateStateToDS(); EXPECT_TRUE(sdc.verifyMeshBlueprint()); } TEST(sidre_datacollection, dc_save) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); MFEMSidreDataCollection sdc(testName(), &mesh); #if defined(AXOM_USE_MPI) && defined(MFEM_USE_MPI) sdc.SetComm(MPI_COMM_WORLD); #endif sdc.Save(); EXPECT_TRUE(sdc.verifyMeshBlueprint()); } TEST(sidre_datacollection, dc_reload_gf) { const std::string field_name = "test_field"; // 2D mesh divided into triangles mfem::Mesh mesh(10, 10, mfem::Element::TRIANGLE); mfem::H1_FECollection fec(1, mesh.Dimension()); mfem::FiniteElementSpace fes(&mesh, &fec); // The mesh and field(s) must be owned by Sidre to properly manage data in case of // a simulated restart (save -> load) bool owns_mesh = true; MFEMSidreDataCollection sdc_writer(testName(), &mesh, owns_mesh); mfem::GridFunction gf_write(&fes, nullptr); // Register to allocate storage internally, then write to it sdc_writer.RegisterField(field_name, &gf_write); mfem::ConstantCoefficient three_and_a_half(3.5); gf_write.ProjectCoefficient(three_and_a_half); EXPECT_TRUE(sdc_writer.verifyMeshBlueprint()); #if defined(AXOM_USE_MPI) && defined(MFEM_USE_MPI) sdc_writer.SetComm(MPI_COMM_WORLD); #endif sdc_writer.SetCycle(0); sdc_writer.Save(); // No mesh is used here MFEMSidreDataCollection sdc_reader(testName()); #if defined(AXOM_USE_MPI) && defined(MFEM_USE_MPI) sdc_reader.SetComm(MPI_COMM_WORLD); #endif sdc_reader.Load(); // No need to reregister, it already exists auto gf_read = sdc_reader.GetField(field_name); // Make sure the gridfunction was actually read in EXPECT_LT(gf_read->ComputeL2Error(three_and_a_half), EPSILON); EXPECT_TRUE(sdc_reader.verifyMeshBlueprint()); } TEST(sidre_datacollection, dc_reload_gf_vdim) { const std::string field_name = "test_field"; const int vdim = 2; // 2D mesh divided into triangles mfem::Mesh mesh(10, 10, mfem::Element::TRIANGLE); mfem::H1_FECollection fec(1, mesh.Dimension()); mfem::FiniteElementSpace fes(&mesh, &fec, vdim, mfem::Ordering::byVDIM); // The mesh and field(s) must be owned by Sidre to properly manage data in case of // a simulated restart (save -> load) bool owns_mesh = true; MFEMSidreDataCollection sdc_writer(testName(), &mesh, owns_mesh); mfem::GridFunction gf_write(&fes, nullptr); // Register to allocate storage internally, then write to it sdc_writer.RegisterField(field_name, &gf_write); mfem::ConstantCoefficient three_and_a_half(3.5); gf_write.ProjectCoefficient(three_and_a_half); EXPECT_TRUE(sdc_writer.verifyMeshBlueprint()); #if defined(AXOM_USE_MPI) && defined(MFEM_USE_MPI) sdc_writer.SetComm(MPI_COMM_WORLD); #endif sdc_writer.SetCycle(0); sdc_writer.Save(); // No mesh is used here MFEMSidreDataCollection sdc_reader(testName()); #if defined(AXOM_USE_MPI) && defined(MFEM_USE_MPI) sdc_reader.SetComm(MPI_COMM_WORLD); #endif sdc_reader.Load(); // No need to reregister, it already exists auto gf_read = sdc_reader.GetField(field_name); // Make sure the gridfunction was actually read in EXPECT_LT(gf_read->ComputeL2Error(three_and_a_half), EPSILON); EXPECT_EQ(gf_read->FESpace()->GetOrdering(), mfem::Ordering::byVDIM); EXPECT_EQ(gf_read->FESpace()->GetVDim(), vdim); EXPECT_TRUE(sdc_reader.verifyMeshBlueprint()); } TEST(sidre_datacollection, dc_reload_mesh) { const std::string field_name = "test_field"; // 2D mesh divided into triangles mfem::Mesh mesh(10, 10, mfem::Element::TRIANGLE); mfem::H1_FECollection fec(1, mesh.Dimension()); mfem::FiniteElementSpace fes(&mesh, &fec); // The mesh and field(s) must be owned by Sidre to properly manage data in case of // a simulated restart (save -> load) bool owns_mesh = true; MFEMSidreDataCollection sdc_writer(testName(), &mesh, owns_mesh); #if defined(AXOM_USE_MPI) && defined(MFEM_USE_MPI) sdc_writer.SetComm(MPI_COMM_WORLD); #endif EXPECT_TRUE(sdc_writer.verifyMeshBlueprint()); // Save some basic info about the mesh const int n_verts = sdc_writer.GetMesh()->GetNV(); const int n_ele = sdc_writer.GetMesh()->GetNE(); const int n_bdr_ele = sdc_writer.GetMesh()->GetNBE(); sdc_writer.SetCycle(0); sdc_writer.Save(); // No mesh is used here to construct as it will be read in MFEMSidreDataCollection sdc_reader(testName()); #if defined(AXOM_USE_MPI) && defined(MFEM_USE_MPI) sdc_reader.SetComm(MPI_COMM_WORLD); #endif sdc_reader.Load(); // Make sure the mesh was actually reconstructed EXPECT_EQ(sdc_reader.GetMesh()->GetNV(), n_verts); EXPECT_EQ(sdc_reader.GetMesh()->GetNE(), n_ele); EXPECT_EQ(sdc_reader.GetMesh()->GetNBE(), n_bdr_ele); EXPECT_TRUE(sdc_reader.verifyMeshBlueprint()); } TEST(sidre_datacollection, dc_reload_qf) { //Set up a small mesh and a couple of grid function on that mesh mfem::Mesh mesh(2, 3, mfem::Element::QUADRILATERAL, 0, 2.0, 3.0); mfem::LinearFECollection fec; mfem::FiniteElementSpace fes(&mesh, &fec); const int intOrder = 3; const int qs_vdim = 1; const int qv_vdim = 2; mfem::QuadratureSpace qspace(&mesh, intOrder); // We want Sidre to allocate the data for us and to own the internal data. // If we don't do the below then the data collection doesn't save off the data // structure. mfem::QuadratureFunction qs(&qspace, nullptr, qs_vdim); mfem::QuadratureFunction qv(&qspace, nullptr, qv_vdim); int Nq = qs.Size(); // The mesh and field(s) must be owned by Sidre to properly manage data in case of // a simulated restart (save -> load) bool owns_mesh = true; MFEMSidreDataCollection sdc_writer(testName(), &mesh, owns_mesh); #if defined(AXOM_USE_MPI) && defined(MFEM_USE_MPI) sdc_writer.SetComm(MPI_COMM_WORLD); #endif // sdc_writer owns the quadrature function fields and the underlying data sdc_writer.RegisterQField("qs", &qs); sdc_writer.RegisterQField("qv", &qv); // The data needs to be instantiated before we save it off for(int i = 0; i < Nq; ++i) { qs(i) = double(i); qv(2 * i + 0) = double(i); qv(2 * i + 1) = double(Nq - i - 1); } sdc_writer.SetCycle(5); sdc_writer.SetTime(8.0); sdc_writer.Save(); MFEMSidreDataCollection sdc_reader(testName()); #if defined(AXOM_USE_MPI) && defined(MFEM_USE_MPI) sdc_reader.SetComm(MPI_COMM_WORLD); #endif sdc_reader.Load(sdc_writer.GetCycle()); ASSERT_TRUE(sdc_reader.HasQField("qs")); ASSERT_TRUE(sdc_reader.HasQField("qv")); mfem::QuadratureFunction* reader_qs = sdc_reader.GetQField("qs"); mfem::QuadratureFunction* reader_qv = sdc_reader.GetQField("qv"); // order_qs should also equal order_qv in this trivial case // FIXME: QF order can be retrieved directly as of MFEM 4.3 EXPECT_EQ(reader_qs->GetSpace()->GetElementIntRule(0).GetOrder(), intOrder); EXPECT_EQ(reader_qv->GetSpace()->GetElementIntRule(0).GetOrder(), intOrder); EXPECT_EQ(reader_qs->GetVDim(), qs_vdim); EXPECT_EQ(reader_qv->GetVDim(), qv_vdim); *(reader_qs) -= qs; *(reader_qv) -= qv; EXPECT_LT(reader_qs->Norml2(), 1e-15); EXPECT_LT(reader_qv->Norml2(), 1e-15); } // Helper function to check for the existence of two sidre::Views and to check // that they each refer to the same block of data void checkReferentialEquality(axom::sidre::Group* grp, const std::string& first, const std::string& second) { const bool has_first = grp->hasView(first); const bool has_second = grp->hasView(second); EXPECT_TRUE(has_first); EXPECT_TRUE(has_second); if(has_first && has_second) { // Conduct a pointer comparison to make sure that the two views actually // refer to the same block of memory const double* first_data = grp->getView(first)->getData(); const double* second_data = grp->getView(second)->getData(); EXPECT_EQ(first_data, second_data); } } TEST(sidre_datacollection, create_matset) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); MFEMSidreDataCollection sdc(testName(), &mesh); sdc.AssociateMaterialSet("volume_fraction", "matset"); mfem::H1_FECollection fec(1, mesh.Dimension()); mfem::FiniteElementSpace fes(&mesh, &fec); mfem::GridFunction vol_frac_1(&fes); vol_frac_1 = 1.0; sdc.RegisterField("volume_fraction_001", &vol_frac_1); EXPECT_TRUE(sdc.verifyMeshBlueprint()); const auto bp_grp = sdc.GetBPGroup(); EXPECT_TRUE(bp_grp->hasGroup("matsets")); EXPECT_TRUE(bp_grp->hasGroup("matsets/matset")); checkReferentialEquality(bp_grp, "matsets/matset/volume_fractions/001", "fields/volume_fraction_001/values"); } TEST(sidre_datacollection, create_matset_multi_fraction) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); MFEMSidreDataCollection sdc(testName(), &mesh); sdc.AssociateMaterialSet("volume_fraction", "matset"); mfem::H1_FECollection fec(1, mesh.Dimension()); mfem::FiniteElementSpace fes(&mesh, &fec); mfem::GridFunction vol_frac_1(&fes); vol_frac_1 = 0.7; sdc.RegisterField("volume_fraction_001", &vol_frac_1); mfem::GridFunction vol_frac_2(&fes); vol_frac_2 = 0.3; sdc.RegisterField("volume_fraction_002", &vol_frac_2); EXPECT_TRUE(sdc.verifyMeshBlueprint()); const auto bp_grp = sdc.GetBPGroup(); EXPECT_TRUE(bp_grp->hasGroup("matsets")); EXPECT_TRUE(bp_grp->hasGroup("matsets/matset")); checkReferentialEquality(bp_grp, "matsets/matset/volume_fractions/001", "fields/volume_fraction_001/values"); checkReferentialEquality(bp_grp, "matsets/matset/volume_fractions/002", "fields/volume_fraction_002/values"); } TEST(sidre_datacollection, create_specset) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); MFEMSidreDataCollection sdc(testName(), &mesh); mfem::H1_FECollection fec(1, mesh.Dimension()); mfem::FiniteElementSpace fes(&mesh, &fec); // Add a material set so we can associate the specset with it sdc.AssociateMaterialSet("volume_fraction", "matset"); mfem::GridFunction vol_frac_1(&fes); vol_frac_1 = 1.0; sdc.RegisterField("volume_fraction_001", &vol_frac_1); // Then add the species set const bool volume_dependent = false; sdc.AssociateSpeciesSet("partial_density", "specset", "matset", volume_dependent); mfem::GridFunction partial_density_1_1(&fes); partial_density_1_1 = 1.0; sdc.RegisterField("partial_density_001_001", &partial_density_1_1); EXPECT_TRUE(sdc.verifyMeshBlueprint()); const auto bp_grp = sdc.GetBPGroup(); EXPECT_TRUE(bp_grp->hasGroup("specsets")); EXPECT_TRUE(bp_grp->hasGroup("specsets/specset")); EXPECT_TRUE(bp_grp->hasView("specsets/specset/volume_dependent")); EXPECT_FALSE(static_cast<axom::int8>( bp_grp->getView("specsets/specset/volume_dependent")->getScalar())); EXPECT_TRUE(bp_grp->hasView("specsets/specset/matset")); EXPECT_EQ(std::string(bp_grp->getView("specsets/specset/matset")->getString()), "matset"); EXPECT_TRUE(bp_grp->hasView("specsets/specset/matset_values/001/001")); checkReferentialEquality(bp_grp, "matsets/matset/volume_fractions/001", "fields/volume_fraction_001/values"); checkReferentialEquality(bp_grp, "specsets/specset/matset_values/001/001", "fields/partial_density_001_001/values"); } TEST(sidre_datacollection, create_specset_multi_fraction) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); MFEMSidreDataCollection sdc(testName(), &mesh); mfem::H1_FECollection fec(1, mesh.Dimension()); mfem::FiniteElementSpace fes(&mesh, &fec); // Add a material set so we can associate the specset with it sdc.AssociateMaterialSet("volume_fraction", "matset"); mfem::GridFunction vol_frac_1(&fes); vol_frac_1 = 0.7; sdc.RegisterField("volume_fraction_001", &vol_frac_1); mfem::GridFunction vol_frac_2(&fes); vol_frac_2 = 0.3; sdc.RegisterField("volume_fraction_002", &vol_frac_2); // Then add the species set const bool volume_dependent = false; sdc.AssociateSpeciesSet("partial_density", "specset", "matset", volume_dependent); mfem::GridFunction partial_density_1_1(&fes); partial_density_1_1 = 0.4; sdc.RegisterField("partial_density_001_001", &partial_density_1_1); mfem::GridFunction partial_density_1_2(&fes); partial_density_1_2 = 0.3; sdc.RegisterField("partial_density_001_002", &partial_density_1_2); mfem::GridFunction partial_density_2_1(&fes); partial_density_2_1 = 0.2; sdc.RegisterField("partial_density_002_001", &partial_density_2_1); mfem::GridFunction partial_density_2_2(&fes); partial_density_2_2 = 0.1; sdc.RegisterField("partial_density_002_002", &partial_density_2_2); EXPECT_TRUE(sdc.verifyMeshBlueprint()); const auto bp_grp = sdc.GetBPGroup(); EXPECT_TRUE(bp_grp->hasGroup("specsets")); EXPECT_TRUE(bp_grp->hasGroup("specsets/specset")); EXPECT_TRUE(bp_grp->hasView("specsets/specset/volume_dependent")); EXPECT_FALSE(static_cast<axom::int8>( bp_grp->getView("specsets/specset/volume_dependent")->getScalar())); EXPECT_TRUE(bp_grp->hasView("specsets/specset/matset")); EXPECT_EQ(std::string(bp_grp->getView("specsets/specset/matset")->getString()), "matset"); checkReferentialEquality(bp_grp, "matsets/matset/volume_fractions/001", "fields/volume_fraction_001/values"); checkReferentialEquality(bp_grp, "matsets/matset/volume_fractions/002", "fields/volume_fraction_002/values"); checkReferentialEquality(bp_grp, "specsets/specset/matset_values/001/001", "fields/partial_density_001_001/values"); checkReferentialEquality(bp_grp, "specsets/specset/matset_values/001/002", "fields/partial_density_001_002/values"); checkReferentialEquality(bp_grp, "specsets/specset/matset_values/002/001", "fields/partial_density_002_001/values"); checkReferentialEquality(bp_grp, "specsets/specset/matset_values/002/002", "fields/partial_density_002_002/values"); } TEST(sidre_datacollection, create_material_dependent_field) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); MFEMSidreDataCollection sdc(testName(), &mesh); mfem::H1_FECollection fec(1, mesh.Dimension()); mfem::FiniteElementSpace fes(&mesh, &fec); // Add a material set so we can associate the field with it sdc.AssociateMaterialSet("volume_fraction", "matset"); mfem::GridFunction vol_frac_1(&fes); vol_frac_1 = 1.0; sdc.RegisterField("volume_fraction_001", &vol_frac_1); // Then mark the field as material-dependent sdc.AssociateMaterialDependentField("density", "matset"); mfem::GridFunction density_independent(&fes); density_independent = 1.0; sdc.RegisterField("density", &density_independent); mfem::GridFunction density_dependent(&fes); density_dependent = 0.2; sdc.RegisterField("density_001", &density_dependent); EXPECT_TRUE(sdc.verifyMeshBlueprint()); const auto bp_grp = sdc.GetBPGroup(); EXPECT_TRUE(bp_grp->hasGroup("fields/density")); EXPECT_TRUE(bp_grp->hasGroup("fields/density/matset_values")); checkReferentialEquality(bp_grp, "matsets/matset/volume_fractions/001", "fields/volume_fraction_001/values"); checkReferentialEquality(bp_grp, "fields/density/matset_values/001", "fields/density_001/values"); } TEST(sidre_datacollection, create_material_dependent_field_multi_fraction) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); MFEMSidreDataCollection sdc(testName(), &mesh); mfem::H1_FECollection fec(1, mesh.Dimension()); mfem::FiniteElementSpace fes(&mesh, &fec); // Add a material set so we can associate the field with it sdc.AssociateMaterialSet("volume_fraction", "matset"); mfem::GridFunction vol_frac_1(&fes); vol_frac_1 = 0.65; sdc.RegisterField("volume_fraction_001", &vol_frac_1); mfem::GridFunction vol_frac_2(&fes); vol_frac_2 = 0.35; sdc.RegisterField("volume_fraction_002", &vol_frac_2); // Then mark the field as material-dependent sdc.AssociateMaterialDependentField("density", "matset"); mfem::GridFunction density_indenpendent(&fes); density_indenpendent = 1.0; sdc.RegisterField("density", &density_indenpendent); mfem::GridFunction density_dependent_1(&fes); density_dependent_1 = 0.2; sdc.RegisterField("density_001", &density_dependent_1); mfem::GridFunction density_dependent_2(&fes); density_dependent_2 = 0.3; sdc.RegisterField("density_002", &density_dependent_2); EXPECT_TRUE(sdc.verifyMeshBlueprint()); const auto bp_grp = sdc.GetBPGroup(); EXPECT_TRUE(bp_grp->hasGroup("fields/density")); EXPECT_TRUE(bp_grp->hasGroup("fields/density/matset_values")); checkReferentialEquality(bp_grp, "matsets/matset/volume_fractions/001", "fields/volume_fraction_001/values"); checkReferentialEquality(bp_grp, "matsets/matset/volume_fractions/002", "fields/volume_fraction_002/values"); checkReferentialEquality(bp_grp, "fields/density/matset_values/001", "fields/density_001/values"); checkReferentialEquality(bp_grp, "fields/density/matset_values/002", "fields/density_002/values"); } #if defined(AXOM_USE_MPI) && defined(MFEM_USE_MPI) TEST(sidre_datacollection, dc_alloc_owning_parmesh) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); mfem::ParMesh parmesh(MPI_COMM_WORLD, mesh); bool owns_mesh = true; MFEMSidreDataCollection sdc(testName(), &parmesh, owns_mesh); EXPECT_TRUE(sdc.verifyMeshBlueprint()); } TEST(sidre_datacollection, dc_alloc_nonowning_parmesh) { // 1D mesh divided into 10 segments mfem::Mesh mesh(10); mfem::ParMesh parmesh(MPI_COMM_WORLD, mesh); bool owns_mesh = false; MFEMSidreDataCollection sdc(testName(), &parmesh, owns_mesh); EXPECT_TRUE(sdc.verifyMeshBlueprint()); } struct ParMeshGroupData { int n_verts = 0; int n_edges = 0; int n_triangles = 0; int n_quads = 0; bool operator==(const ParMeshGroupData& other) const { return (n_verts == other.n_verts) && (n_edges == other.n_edges) && (n_triangles == other.n_triangles) && (n_quads == other.n_quads); } }; static std::vector<ParMeshGroupData> getGroupData(const mfem::ParMesh& parmesh) { const int dim = parmesh.Dimension(); // Zeroth group doesn't matter std::vector<ParMeshGroupData> result(parmesh.GetNGroups() - 1); // remove when marked const in MFEM auto& non_const_parmesh = const_cast<mfem::ParMesh&>(parmesh); for(std::size_t i = 1; i <= result.size(); i++) { result[i - 1].n_verts = non_const_parmesh.GroupNVertices(i); if(dim >= 2) { result[i - 1].n_edges = non_const_parmesh.GroupNEdges(i); if(dim >= 3) { result[i - 1].n_triangles = non_const_parmesh.GroupNTriangles(i); result[i - 1].n_quads = non_const_parmesh.GroupNQuadrilaterals(i); } } } return result; } /** * @brief Helper method for testing that a parallel mesh is reconstructed correctly * @param [in] base_mesh The serial mesh object to distribute, save, and then reload * @param [in] part_method The partitioning method to use - in [0, 5] */ static void testParallelMeshReload(mfem::Mesh& base_mesh, const int part_method = 1) { mfem::ParMesh parmesh(MPI_COMM_WORLD, base_mesh, nullptr, part_method); // Use second-order elements to ensure that the nodal gridfunction gets set up properly as well mfem::H1_FECollection fec(2, base_mesh.Dimension()); mfem::ParFiniteElementSpace parfes(&parmesh, &fec); // The mesh must be owned by Sidre to properly manage data in case of // a simulated restart (save -> load) const bool owns_mesh = true; MFEMSidreDataCollection sdc_writer(testName(), &parmesh, owns_mesh); // Save some basic info about the mesh const int n_verts = sdc_writer.GetMesh()->GetNV(); const int n_ele = sdc_writer.GetMesh()->GetNE(); const int n_bdr_ele = sdc_writer.GetMesh()->GetNBE(); // ParMesh-specific info auto writer_pmesh = dynamic_cast<mfem::ParMesh*>(sdc_writer.GetMesh()); ASSERT_NE(writer_pmesh, nullptr); const int n_groups = writer_pmesh->GetNGroups(); const int n_face_neighbors = writer_pmesh->GetNFaceNeighbors(); const int n_shared_faces = writer_pmesh->GetNSharedFaces(); // Group-specific info auto writer_group_data = getGroupData(*writer_pmesh); sdc_writer.SetCycle(0); sdc_writer.Save(); MFEMSidreDataCollection sdc_reader(testName()); // Needs to be set "manually" in order for everything to be loaded in properly sdc_reader.SetComm(MPI_COMM_WORLD); sdc_reader.Load(); // Make sure the mesh was actually reconstructed EXPECT_EQ(sdc_reader.GetMesh()->GetNV(), n_verts); EXPECT_EQ(sdc_reader.GetMesh()->GetNE(), n_ele); EXPECT_EQ(sdc_reader.GetMesh()->GetNBE(), n_bdr_ele); // Make sure the ParMesh was reconstructed - even on one rank, this // will still be a ParMesh auto reader_pmesh = dynamic_cast<mfem::ParMesh*>(sdc_reader.GetMesh()); ASSERT_NE(reader_pmesh, nullptr); EXPECT_EQ(reader_pmesh->GetNGroups(), n_groups); EXPECT_EQ(reader_pmesh->GetNFaceNeighbors(), n_face_neighbors); EXPECT_EQ(reader_pmesh->GetNSharedFaces(), n_shared_faces); auto reader_group_data = getGroupData(*reader_pmesh); EXPECT_EQ(writer_group_data, reader_group_data); EXPECT_TRUE(sdc_reader.verifyMeshBlueprint()); // Make sure that orientation checks pass // These checks assume that the test mesh is orientable and are intended to make sure // that Mesh::Nodes was set up correctly - otherwise these can fail for periodic (and HO?) meshes // QUESTION: What does this method do for a non-orientable mesh? EXPECT_EQ(sdc_reader.GetMesh()->CheckElementOrientation(), 0); EXPECT_EQ(sdc_reader.GetMesh()->CheckBdrElementOrientation(), 0); } /** * @brief Wrapper for testing mesh reconstruction across all partitioning methods * @param [in] base_mesh The serial mesh object to distribute, save, and then reload */ static void testParallelMeshReloadAllPartitionings(mfem::Mesh& base_mesh) { static constexpr int MAX_PART_METHOD = 5; // MFEM supports partition methods [0, 5] for(int part_method = 0; part_method <= MAX_PART_METHOD; part_method++) { testParallelMeshReload(base_mesh, part_method); } } TEST(sidre_datacollection, dc_par_reload_gf) { const std::string field_name = "test_field"; // 3D tet mesh mfem::Mesh mesh(2, 2, 2, mfem::Element::TETRAHEDRON); mfem::ParMesh parmesh(MPI_COMM_WORLD, mesh); mfem::H1_FECollection fec(1, mesh.Dimension()); mfem::ParFiniteElementSpace parfes(&parmesh, &fec); // The mesh must be owned by Sidre to properly manage data in case of // a simulated restart (save -> load) bool owns_mesh = true; MFEMSidreDataCollection sdc_writer(testName(), &parmesh, owns_mesh); // The mesh and field(s) must be owned by Sidre to properly manage data in case of // a simulated restart (save -> load) mfem::ParGridFunction gf_write(&parfes, static_cast<double*>(nullptr)); // Register to allocate storage internally, then write to it sdc_writer.RegisterField(field_name, &gf_write); mfem::ConstantCoefficient three_and_a_half(3.5); gf_write.ProjectCoefficient(three_and_a_half); sdc_writer.SetCycle(0); sdc_writer.Save(); MFEMSidreDataCollection sdc_reader(testName()); // Needs to be set "manually" in order for everything to be loaded in properly sdc_reader.SetComm(MPI_COMM_WORLD); sdc_reader.Load(); auto gf_read = sdc_reader.GetField(field_name); EXPECT_TRUE(dynamic_cast<mfem::ParGridFunction*>(gf_read)); // Make sure the gridfunction was actually read in EXPECT_LT(gf_read->ComputeL2Error(three_and_a_half), EPSILON); EXPECT_TRUE(sdc_reader.verifyMeshBlueprint()); } TEST(sidre_datacollection, dc_par_reload_mesh_1D_small) { // 1D mesh divided into segments mfem::Mesh mesh(10); testParallelMeshReloadAllPartitionings(mesh); } TEST(sidre_datacollection, dc_par_reload_mesh_2D_small) { // 2D mesh divided into triangles mfem::Mesh mesh(10, 10, mfem::Element::TRIANGLE); testParallelMeshReloadAllPartitionings(mesh); } TEST(sidre_datacollection, dc_par_reload_mesh_2D_large) { // 2D mesh divided into triangles mfem::Mesh mesh(100, 100, mfem::Element::TRIANGLE); testParallelMeshReloadAllPartitionings(mesh); } // The following test requires a function from mfem@4.3 #if(MFEM_VERSION >= 40300) TEST(sidre_datacollection, dc_par_reload_mesh_2D_periodic) { // periodic 2D mesh divided into triangles mfem::Mesh base_mesh(10, 10, mfem::Element::Type::QUADRILATERAL, false, 1.0, 1.0); // FIXME: MFEM 4.3 // mfem::Mesh::MakeCartesian2D(10, // 10, // mfem::Element::Type::QUADRILATERAL, // false, // 1.0, // 1.0); std::vector<mfem::Vector> translations = {mfem::Vector({1.0, 0.0}), mfem::Vector({0.0, 1.0})}; auto vertex_map = base_mesh.CreatePeriodicVertexMapping(translations); auto mesh = mfem::Mesh::MakePeriodic(base_mesh, vertex_map); testParallelMeshReloadAllPartitionings(mesh); } #endif TEST(sidre_datacollection, dc_par_reload_mesh_3D_small_tet) { // 3D mesh divided into tetrahedra mfem::Mesh mesh(2, 2, 2, mfem::Element::TETRAHEDRON); testParallelMeshReloadAllPartitionings(mesh); } TEST(sidre_datacollection, dc_par_reload_mesh_3D_medium_tet) { // 3D mesh divided into tetrahedra mfem::Mesh mesh(10, 10, 10, mfem::Element::TETRAHEDRON); testParallelMeshReloadAllPartitionings(mesh); } TEST(sidre_datacollection, dc_par_reload_mesh_3D_small_hex) { // 3D mesh divided into hexahedra mfem::Mesh mesh(3, 3, 3, mfem::Element::HEXAHEDRON); testParallelMeshReloadAllPartitionings(mesh); } TEST(sidre_datacollection, dc_par_reload_mesh_3D_medium_hex) { // 3D mesh divided into hexahedra mfem::Mesh mesh(10, 10, 10, mfem::Element::HEXAHEDRON); testParallelMeshReloadAllPartitionings(mesh); } #endif // defined(AXOM_USE_MPI) && defined(MFEM_USE_MPI) //---------------------------------------------------------------------- int main(int argc, char* argv[]) { int result = 0; ::testing::InitGoogleTest(&argc, argv); axom::slic::SimpleLogger logger; // create & initialize test logger, #ifdef AXOM_USE_MPI MPI_Init(&argc, &argv); #endif result = RUN_ALL_TESTS(); #ifdef AXOM_USE_MPI MPI_Finalize(); #endif return result; }
33.708861
99
0.712969
[ "mesh", "object", "vector", "3d" ]
6bf4005aa6d332ca7024d1f8c998bb8f0863e011
2,177
hpp
C++
src/Parser.hpp
mserdarsanli/QuantumJson
7aa8c7e17d2ff6677264edd20f54d7ee20821213
[ "MIT" ]
6
2016-09-28T21:05:46.000Z
2019-03-26T16:58:49.000Z
src/Parser.hpp
mserdarsanli/QuantumJson
7aa8c7e17d2ff6677264edd20f54d7ee20821213
[ "MIT" ]
null
null
null
src/Parser.hpp
mserdarsanli/QuantumJson
7aa8c7e17d2ff6677264edd20f54d7ee20821213
[ "MIT" ]
null
null
null
// The MIT License (MIT) // // Copyright (c) 2016 Mustafa Serdar Sanli // // 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. #pragma once #include <map> #include <sstream> #include <string> #include <vector> #include "Tokenizer.hpp" struct VariableTypeDef { std::string typeName; std::vector<VariableTypeDef> of; // template parameters std::string Render() const { std::stringstream out; RenderInto(out); return out.str(); } private: void RenderInto(std::ostream &out) const { out << this->typeName; if (this->of.size()) { out << "< "; for (size_t i = 0; i < this->of.size(); ++i) { if (i != 0) { out << " , "; } this->of[i].RenderInto(out); } out << " >"; } } }; struct AttributeDef { std::string name; std::vector<std::string> args; }; struct VariableDef { VariableTypeDef type; std::string name; std::map< std::string, AttributeDef > attributes; }; struct StructDef { std::vector<std::string> inNamespace; std::string name; std::vector<VariableDef> variables; }; struct ParsedFile { std::vector<StructDef> structs; }; ParsedFile Parse(const std::vector<Token> &tokens);
22.915789
81
0.700965
[ "render", "vector" ]
6bf7af8413f7f75f403f4cf6b6224e27db3c05a2
1,027
hpp
C++
src/Objects/WorldLight.hpp
NuroDev/vision
611eae0717da8062865bcd3001229ecfafd9b7b1
[ "MIT" ]
1
2022-01-25T05:30:11.000Z
2022-01-25T05:30:11.000Z
src/Objects/WorldLight.hpp
NuroDev/vision
611eae0717da8062865bcd3001229ecfafd9b7b1
[ "MIT" ]
6
2020-07-21T13:56:27.000Z
2020-08-03T08:36:54.000Z
src/Objects/WorldLight.hpp
NuroDev/vision
611eae0717da8062865bcd3001229ecfafd9b7b1
[ "MIT" ]
null
null
null
#pragma once #include <d3d11.h> #include "../Util/Structures.hpp" #include "WorldObject.hpp" class WorldLight : public WorldObject { public: WorldLight( std::string name, const unsigned int id, Transform* pTransform = new Transform() ) : WorldObject(name, id, pTransform) {} ~WorldLight() { WorldLight::Release(); }; /// [OBJECT LIGHT] Initialize any core object data HRESULT Init() override; /// [OBJECT LIGHT] Draw the contents of the object to the screen void Draw() override; /// [OBJECT LIGHT] Draw the custom imgui ui to the screen void Ui() override; /// [OBJECT LIGHT] Update the object every tick void Update(float t) override; /// [OBJECT LIGHT] Cleanup & release the object when it is done void Release() override; /// [LIGHT] Get the light object Light GetLight() const { return m_light; }; /// [LIGHT] Set the light object void SetLight(Light light) { m_light = light; }; private: /// [BUFFERS] ID3D11Buffer *m_pLightConstantBuffer = nullptr; /// [LIGHT] Light m_light; };
21.851064
65
0.695229
[ "object", "transform" ]
6bf81fc68d4a4d8b6eb81ccc718d492a534ee0bf
1,369
cpp
C++
backup/2/codewars/c++/maximum-length-difference.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/codewars/c++/maximum-length-difference.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/codewars/c++/maximum-length-difference.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/codewars/maximum-length-difference.html . #include <algorithm> #include <functional> #include <string> class MaxDiffLength { public: static int mxdiflg(std::vector<std::string> &a1, std::vector<std::string> &a2) { using namespace std; if (a1.empty() || a2.empty()) { return -1; } function<bool(string, string)> cmp = [](string item1, string item2) { return item1.size() < item2.size(); }; int maxi1 = max_element(a1.begin(), a1.end(), cmp)->size(); int mini1 = min_element(a1.begin(), a1.end(), cmp)->size(); int maxi2 = max_element(a2.begin(), a2.end(), cmp)->size(); int mini2 = min_element(a2.begin(), a2.end(), cmp)->size(); return max(abs(maxi1 - mini2), abs(maxi2 - mini1)); } };
48.892857
345
0.642805
[ "vector" ]
6bff5ffbc0b00db6610d7368fd073c5341374862
13,704
hpp
C++
include/baxter_cartesian_controller/mocap_servoing_controller.hpp
WPI-ARC/baxter_cartesian_controller
629367eee0e995298a8a7eddbb819869982b1c70
[ "BSD-2-Clause" ]
1
2015-05-30T06:29:30.000Z
2015-05-30T06:29:30.000Z
include/baxter_cartesian_controller/mocap_servoing_controller.hpp
WPI-ARC/baxter_cartesian_controller
629367eee0e995298a8a7eddbb819869982b1c70
[ "BSD-2-Clause" ]
1
2016-03-29T16:50:08.000Z
2016-03-30T00:13:12.000Z
include/baxter_cartesian_controller/mocap_servoing_controller.hpp
WPI-ARC/baxter_cartesian_controller
629367eee0e995298a8a7eddbb819869982b1c70
[ "BSD-2-Clause" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <vector> #include <map> #include <string> #include <iostream> #include <random> #include <Eigen/Geometry> #include <time.h> #include <chrono> #include <ros/ros.h> #include <urdf_model/model.h> #include <moveit/robot_model_loader/robot_model_loader.h> #include <moveit/robot_state/robot_state.h> #include <std_srvs/Empty.h> #include <geometry_msgs/PoseStamped.h> #include <sensor_msgs/JointState.h> #include <control_msgs/FollowJointTrajectoryAction.h> #include <actionlib/client/simple_action_client.h> #include <baxter_cartesian_controller/prettyprint.h> #define _USE_MATH_DEFINES #define BAXTER_ARM_JOINTS 7 #define TWIST_DOF 6 // Set the level of debugging verbosity #define VERBOSE_DEBUGGING // Set the "unit" maximum joint change/sec #define MAXIMUM_JOINT_VELOCITY 1.0 // Set the control rate #define CONTROL_RATE 5.0 // From the control rate, set the other core operating values #define CONTROL_INTERVAL (1.0 / CONTROL_RATE) #define EXECUTION_INTERVAL (2.0 * CONTROL_INTERVAL) #define WATCHDOG_INTERVAL (3.0 * CONTROL_INTERVAL) #define MAXIMUM_JOINT_CORRECTION (MAXIMUM_JOINT_VELOCITY * CONTROL_INTERVAL) // Set the default PID gains #define DEFAULT_KP 1.0 #define DEFAULT_KI 0.0 #define DEFAULT_KD 0.0 // Set damping for each of the arm joints #define SHOULDER_0_DAMPING 0.5 #define SHOULDER_1_DAMPING 0.5 #define ELBOW_0_DAMPING 0.75 #define ELBOW_1_DAMPING 0.75 #define WRIST_0_DAMPING 1.0 #define WRIST_1_DAMPING 1.0 #define WRIST_2_DAMPING 1.0 // Set additional offsets for each of the arm joints #define SHOULDER_0_OFFSET 0.0 #define SHOULDER_1_OFFSET 0.0 #define ELBOW_0_OFFSET 0.0 #define ELBOW_1_OFFSET 0.0 #define WRIST_0_OFFSET 0.0 #define WRIST_1_OFFSET 0.0 #define WRIST_2_OFFSET 0.0 #ifndef MOCAP_SERVOING_CONTROLLER_HPP #define MOCAP_SERVOING_CONTROLLER_HPP namespace baxter_mocap_servoing { typedef Eigen::Affine3d Pose; typedef Eigen::Matrix<double, TWIST_DOF, 1> Twist; class MocapServoingController { protected: enum OPERATING_MODE {INTERNAL_POSE, EXTERNAL_POSE}; OPERATING_MODE mode_; enum OPERATING_STATE {PAUSED, RUNNING}; OPERATING_STATE state_; enum OPERATING_SIDE {LEFT, RIGHT}; OPERATING_SIDE side_; std::vector<std::string> joint_names_; double max_joint_correction_; double execution_timestep_; double watchdog_timeout_; ros::NodeHandle nh_; robot_model::RobotModelPtr baxter_model_; robot_model::RobotStatePtr baxter_kinematic_state_; std::unique_ptr<robot_model::JointModelGroup> baxter_arm_group_; std::unique_ptr<const robot_model::LinkModel> baxter_arm_link_; std::unique_ptr<const robot_model::LinkModel> baxter_base_link_; bool arm_pose_valid_; bool target_pose_valid_; bool arm_config_valid_; Pose current_arm_pose_; Pose current_target_pose_; std::vector<double> current_arm_config_; // Storage for PID control Twist pose_error_integral_; Twist last_pose_error_; double kp_; double ki_; double kd_; ros::Subscriber arm_pose_sub_; ros::Subscriber target_pose_sub_; ros::Subscriber robot_config_sub_; ros::Publisher arm_controller_state_pub_; ros::ServiceServer abort_server_; std::unique_ptr<actionlib::SimpleActionClient<control_msgs::FollowJointTrajectoryAction>> arm_client_; ros::Timer arm_pose_watchdog_; ros::Timer target_pose_watchdog_; ros::Timer robot_config_watchdog_; inline void ArmPoseCB(geometry_msgs::PoseStamped arm_pose) { // First, check to make sure the frame is correct (someday, we'll use TF to make this more general) if (arm_pose.header.frame_id != std::string("/base") && arm_pose.header.frame_id != std::string("base")) { ROS_ERROR("Invalid frame for arm pose update - pose must be in /base frame"); } // If the pose is safe, handle it else { // Convert to Eigen Eigen::Translation3d translation(arm_pose.pose.position.x, arm_pose.pose.position.y, arm_pose.pose.position.z); Eigen::Quaterniond rotation(arm_pose.pose.orientation.w, arm_pose.pose.orientation.x, arm_pose.pose.orientation.y, arm_pose.pose.orientation.z); Pose new_arm_pose = translation * rotation; // Set the pose current_arm_pose_ = new_arm_pose; // Set the status arm_pose_valid_ = true; // Check and set global status RefreshGlobalStatus(); // Reset watchdog timer arm_pose_watchdog_ = nh_.createTimer(ros::Duration(watchdog_timeout_), &MocapServoingController::ArmPoseWatchdogCB, this, true); } } inline void ArmPoseWatchdogCB(const ros::TimerEvent& e) { ROS_WARN("Arm pose hasn't been updated in %f seconds - pausing execution until a new pose update received", watchdog_timeout_); arm_pose_valid_ = false; state_ = PAUSED; } inline void TargetPoseCB(geometry_msgs::PoseStamped target_pose) { // First, check to make sure the frame is correct (someday, we'll use TF to make this more general) if (target_pose.header.frame_id != std::string("/base") && target_pose.header.frame_id != std::string("base")) { ROS_ERROR("Invalid frame for target pose update - pose must be in /base frame"); } // Check if the provided pose is a special "cancel target" message else if (target_pose.pose.orientation.x == 0.0 && target_pose.pose.orientation.y == 0.0 && target_pose.pose.orientation.z == 0.0 && target_pose.pose.orientation.w == 0.0) { ROS_INFO("Cancelling pose target, switching to PAUSED mode"); // Set the status target_pose_valid_ = false; // Check and set the global status RefreshGlobalStatus(); // We don't reset the timer, instead we cancel it target_pose_watchdog_.stop(); } // If the pose is safe, handle it else { // Convert to Eigen Eigen::Translation3d translation(target_pose.pose.position.x, target_pose.pose.position.y, target_pose.pose.position.z); Eigen::Quaterniond rotation(target_pose.pose.orientation.w, target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z); Pose new_target_pose = translation * rotation; // Set the pose current_target_pose_ = new_target_pose; // Set the status target_pose_valid_ = true; // Check and set global status RefreshGlobalStatus(); // Reset watchdog timer target_pose_watchdog_ = nh_.createTimer(ros::Duration(watchdog_timeout_), &MocapServoingController::TargetPoseWatchdogCB, this, true); } } inline void TargetPoseWatchdogCB(const ros::TimerEvent& e) { ROS_WARN("Target pose hasn't been updated in %f seconds - continuing to current target", watchdog_timeout_); } inline void RobotStateCB(sensor_msgs::JointState msg) { if (msg.name.size() != msg.position.size()) { ROS_ERROR("Malformed configuration update - skipping update"); return; } std::map<std::string, double> joint_positions; for (size_t idx = 0; idx < msg.name.size(); idx++) { joint_positions[msg.name[idx]] = msg.position[idx]; } // Set the config std::vector<double> new_arm_config(BAXTER_ARM_JOINTS); new_arm_config[0] = joint_positions[joint_names_[0]]; new_arm_config[1] = joint_positions[joint_names_[1]]; new_arm_config[2] = joint_positions[joint_names_[2]]; new_arm_config[3] = joint_positions[joint_names_[3]]; new_arm_config[4] = joint_positions[joint_names_[4]]; new_arm_config[5] = joint_positions[joint_names_[5]]; new_arm_config[6] = joint_positions[joint_names_[6]]; current_arm_config_ = new_arm_config; // If we're in INTERNAL_POSE mode, compute the arm pose if (mode_ == INTERNAL_POSE) { current_arm_pose_ = ComputeArmPose(current_arm_config_); } // Set the status arm_config_valid_ = true; // Check and set global status RefreshGlobalStatus(); // Reset watchdog timer robot_config_watchdog_ = nh_.createTimer(ros::Duration(watchdog_timeout_), &MocapServoingController::RobotConfigWatchdogCB, this, true); } inline void RobotConfigWatchdogCB(const ros::TimerEvent& e) { ROS_WARN("Robot config hasn't been updated in %f seconds - pausing execution until a new config update received", watchdog_timeout_); arm_config_valid_ = false; state_ = PAUSED; } inline bool AbortCB(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res) { // Cancel the current pose target ROS_INFO("Cancelling pose target, switching to PAUSED mode"); // Set the status target_pose_valid_ = false; // Check and set the global status RefreshGlobalStatus(); // We don't reset the timer, instead we cancel it target_pose_watchdog_.stop(); return true; } inline Pose ComputeArmPose(std::vector<double>& current_configuration) { // Update joint values baxter_kinematic_state_->setJointGroupPositions(baxter_arm_group_.get(), current_configuration); // Update the joint transforms baxter_kinematic_state_->update(true); // Get the transform from base to torso Pose current_base_pose = baxter_kinematic_state_->getGlobalLinkTransform(baxter_base_link_.get()); // Get the transform from base to wrist Pose current_base_to_wrist_pose = baxter_kinematic_state_->getGlobalLinkTransform(baxter_arm_link_.get()); // Get the arm pose Pose current_arm_pose = current_base_pose.inverse() * current_base_to_wrist_pose; return current_arm_pose; } inline Eigen::MatrixXd ComputeJacobian(std::vector<double>& current_configuration) { // Update joint values baxter_kinematic_state_->setJointGroupPositions(baxter_arm_group_.get(), current_configuration); // Update the joint transforms baxter_kinematic_state_->update(true); // Compute the Jacobian Eigen::MatrixXd current_jacobian = baxter_kinematic_state_->getJacobian(baxter_arm_group_.get()); return current_jacobian; } inline Twist ComputePoseError(Pose& arm_pose, Pose& target_pose) { std::cout << "Current arm pose:\n" << arm_pose.translation() << std::endl; std::cout << "Current target pose:\n" << target_pose.translation() << std::endl; Twist pose_error; pose_error.head<3>() = arm_pose.translation() - target_pose.translation(); pose_error.tail<3>() = 0.5 * (target_pose.linear().col(0).cross(arm_pose.linear().col(0)) + target_pose.linear().col(1).cross(arm_pose.linear().col(1)) + target_pose.linear().col(2).cross(arm_pose.linear().col(2))); pose_error = -1.0 * pose_error; std::cout << "Computed pose error:\n" << pose_error << std::endl; return pose_error; } inline void RefreshGlobalStatus() { if (mode_ == INTERNAL_POSE) { if (target_pose_valid_ && arm_config_valid_) { state_ = RUNNING; } else { state_ = PAUSED; } } else { if (arm_pose_valid_ && target_pose_valid_ && arm_config_valid_) { state_ = RUNNING; } else { state_ = PAUSED; } } } std::vector<double> ComputeNextStep(Pose& current_arm_pose, Pose& current_target_pose, std::vector<double>& current_configuration); void CommandToTarget(std::vector<double>& current_config, std::vector<double>& target_config); public: MocapServoingController(ros::NodeHandle& nh, std::string group_name, std::string arm_pose_topic, std::string target_pose_topic, std::string robot_config_topic, std::string arm_command_action, std::string arm_controller_state_topic, std::string abort_service, double kp, double ki, double kd); MocapServoingController(ros::NodeHandle &nh, std::string group_name, std::string target_pose_topic, std::string robot_config_topic, std::string arm_command_action, std::string arm_controller_state_topic, std::string abort_service, double kp, double ki, double kd); ~MocapServoingController() {} void Loop(); }; } #endif // MOCAP_SERVOING_CONTROLLER_HPP
40.785714
300
0.636238
[ "geometry", "vector", "model", "transform" ]
d4137be0776a98610c44cecdfcf521b3689bead5
2,904
cpp
C++
FalloutStrategy/FalloutEngine/FowEntity.cpp
Kalima-Entertainment/Fallout_Strategy
5985589c75fa4559e061b9e848f906ee7ebafd7b
[ "MIT" ]
7
2020-06-01T10:22:47.000Z
2020-12-22T13:50:39.000Z
FalloutStrategy/FalloutEngine/FowEntity.cpp
Kalima-Entertainment/Fallout_Strategy
5985589c75fa4559e061b9e848f906ee7ebafd7b
[ "MIT" ]
108
2020-03-16T09:34:19.000Z
2020-06-15T15:16:42.000Z
FalloutStrategy/FalloutEngine/FowEntity.cpp
Kalima-Entertainment/Fallout_Strategy
5985589c75fa4559e061b9e848f906ee7ebafd7b
[ "MIT" ]
2
2020-02-24T08:51:19.000Z
2020-02-24T14:05:31.000Z
#include "j1App.h" #include "FoWManager.h" #include "FoWEntity.h" #include "FoWBitDefs.h" #include "j1Map.h" FoWEntity::FoWEntity(iPoint WorldPos, bool providesVisibility) :boundingBoxRadius(3), deleteEntity(false), providesVisibility(providesVisibility), posInMap({ 0,0 }), isVisible(false) { SetNewPosition(WorldPos); } FoWEntity::~FoWEntity() { CleanUp(); } bool FoWEntity::CleanUp() { bool ret = true; return ret; } void FoWEntity::SetNewPosition(iPoint pos) { posInMap = App->map->WorldToMap(pos.x, pos.y); App->fowManager->MapNeedsUpdate(); } void FoWEntity::SetNewVisionRadius(uint radius) { //Changes the vision radius of the entity if there's a precomputed shape with that radius if (radius >= fow_MIN_CIRCLE_RADIUS && radius <= fow_MAX_CIRCLE_RADIUS) { boundingBoxRadius = radius; App->fowManager->MapNeedsUpdate(); } } std::vector<iPoint> FoWEntity::GetTilesInsideRadius()const { std::vector<iPoint> ret; int length = (boundingBoxRadius * 2) + 1; iPoint startingPos; startingPos.x = posInMap.x - boundingBoxRadius; startingPos.y = posInMap.y - boundingBoxRadius; iPoint finishingPos; finishingPos.x = startingPos.x + length; finishingPos.y = startingPos.y + length; //Creates a vector with all the tiles inside a bounding box delimited by the radius for(int i = startingPos.y; i < finishingPos.y; i++) { for(int j = startingPos.x; j < finishingPos.x; j++) { ret.push_back({ j,i }); } } return ret; } // Comprehend and complete this function: (this is the function that does the magic for us) void FoWEntity::ApplyMaskToTiles(std::vector<iPoint>tilesAffected) { //We first take the correct precomputed mask and store it in the precMask variable (it is recommended to see what they are made of. You can find the masks at the FoWManager.h module) //Note that it is an array unsigned short* precMask = &App->fowManager->circleMasks[boundingBoxRadius - fow_MIN_CIRCLE_RADIUS][0]; //You have to complete the code inside this for for(int i = 0; i < tilesAffected.size(); i++) { //You have to request the fog & shroud values of each affected tile. Hint:(You can take both with a single function call) FoWDataStruct* tileValue = App->fowManager->GetFoWTileState(tilesAffected[i]); //And (bitwise AND) them with the mask if the tile FoW values are not nullptr //To bitwise AND values you just simply do this: value1 &= value2 //the operation result will be stored in the variable on the left side. //In this case you want to modify the fog and shroud values that you have requested above if (tileValue != nullptr) { tileValue->tileShroudBits &= *precMask; tileValue->tileFogBits &= *precMask; } precMask++; } } //Applies the Mask to all tiles inside the radius void FoWEntity::Update() { if (providesVisibility) ApplyMaskToTiles(GetTilesInsideRadius()); } iPoint FoWEntity::GetPos()const { return posInMap; }
27.396226
183
0.731749
[ "shape", "vector" ]
d41cc7c67ef8a03658204cb07b8739867275d4f3
3,285
cc
C++
lib/dag/Record.cc
fabriquer/fabrique
d141ef698ddbeddb5b800f7f906d93751a06f809
[ "BSD-2-Clause" ]
2
2018-11-12T22:51:37.000Z
2019-03-13T12:46:03.000Z
lib/dag/Record.cc
fabriquer/fabrique
d141ef698ddbeddb5b800f7f906d93751a06f809
[ "BSD-2-Clause" ]
23
2015-03-06T16:14:49.000Z
2019-04-04T18:08:52.000Z
lib/dag/Record.cc
fabriquer/fabrique
d141ef698ddbeddb5b800f7f906d93751a06f809
[ "BSD-2-Clause" ]
null
null
null
//! @file dag/Record.cc Definition of @ref fabrique::dag::Record /* * Copyright (c) 2014 Jonathan Anderson * All rights reserved. * * This software was developed by SRI International and the University of * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237) * ("CTSRD"), as part of the DARPA CRASH research programme. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 <fabrique/Bytestream.hh> #include <fabrique/dag/Record.hh> #include <fabrique/dag/Visitor.hh> #include <fabrique/types/RecordType.hh> #include <fabrique/types/TypeContext.hh> #include <cassert> using namespace fabrique::dag; using std::string; using std::vector; Record* Record::Create(const ValueMap& fields, TypeContext& types, SourceRange src) { if (not src and not fields.empty()) { src = SourceRange::Over(fields); } RecordType::NamedTypeVec fieldTypes; for (const auto& field : fields) { fieldTypes.emplace_back(field.first, field.second->type()); } const RecordType& t = types.recordType(fieldTypes); return new Record(fields, t, src); } Record::Record(const ValueMap& fields, const Type& t, SourceRange src) : Value(t, src), fields_(fields) { } Record::~Record() {} ValuePtr Record::field(const std::string& name) const { for (auto& i : fields_) { if (i.first == name) return i.second; } return ValuePtr(); } void Record::PrettyPrint(Bytestream& out, unsigned int indent) const { const string tab(indent, '\t'); const string innerTab(indent + 1, '\t'); out << Bytestream::Operator << "{\n" ; for (auto& i : fields_) { out << innerTab << Bytestream::Definition << i.first << Bytestream::Operator << ":" << Bytestream::Reset << i.second->type() << Bytestream::Operator << " = " ; i.second->PrettyPrint(out, indent + 1); out << Bytestream::Reset << "\n" ; } out << Bytestream::Operator << tab << "}" << Bytestream::Reset ; } void Record::Accept(Visitor& v) const { if (v.Visit(*this)) for (auto& i : fields_) i.second->Accept(v); }
26.92623
83
0.70898
[ "vector" ]
d42b6fa281023b60d5dc5b85c7a1a7d67a411d3d
2,260
hpp
C++
src/SelbaWard/Common.hpp
thomoncik/public-transport
06b5ab5d45f551ad24f35642c39fae24a2462f95
[ "MIT" ]
null
null
null
src/SelbaWard/Common.hpp
thomoncik/public-transport
06b5ab5d45f551ad24f35642c39fae24a2462f95
[ "MIT" ]
null
null
null
src/SelbaWard/Common.hpp
thomoncik/public-transport
06b5ab5d45f551ad24f35642c39fae24a2462f95
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // // Selba Ward (https://github.com/Hapaxia/SelbaWard) // // Copyright(c) 2015-2018 M.J.Silk // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions : // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software.If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // // M.J.Silk // MJSilk2@gmail.com // ////////////////////////////////////////////////////////////////////////////// #ifndef SELBAWARD_COMMON_HPP #define SELBAWARD_COMMON_HPP #include <exception> #include <string> #if defined(_MSC_VER) && (_MSC_VER < 1900) #define SELBAWARD_NOEXCEPT #else #define SELBAWARD_NOEXCEPT noexcept #endif namespace selbaward { class Exception : public std::exception { public: Exception(const std::string& errorMessage = "Unknown error.") : m_errorMessage("[Selba Ward] " + errorMessage) { } virtual const char* what() const SELBAWARD_NOEXCEPT override { return m_errorMessage.c_str(); } private: std::string m_errorMessage; }; } // namespace selbaward #ifndef SELBAWARD_NO_NAMESPACE_SHORTCUT namespace sw = selbaward; // create shortcut namespace #endif // SELBAWARD_NO_NAMESPACE_SHORTCUT #include <vector> #include <SFML/Graphics/Drawable.hpp> #include <SFML/Graphics/Transformable.hpp> #include <SFML/Graphics/Vertex.hpp> #include <SFML/Graphics/Color.hpp> #include <SFML/Graphics/RenderTarget.hpp> #include <SFML/Graphics/RenderStates.hpp> #if (SFML_VERSION_MAJOR == 2) #if (SFML_VERSION_MINOR < 4) #define USE_SFML_PRE_2_4 #endif #endif #endif // SELBAWARD_COMMON_HPP
27.228916
78
0.703097
[ "vector" ]
2d6c53c5c2001837dcb9b7160ecb17fecdf9df56
14,738
cxx
C++
StRoot/StEmcCalibrationMaker/StEmcEqualMaker.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/StEmcCalibrationMaker/StEmcEqualMaker.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/StEmcCalibrationMaker/StEmcEqualMaker.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
#include "StEmcEqualMaker.h" #include "TFile.h" #include "TROOT.h" #include "TF1.h" #include "StEventTypes.h" #include "StEvent.h" #include "StEmcUtil/geometry/StEmcGeom.h" #include "StDbLib/StDbManager.hh" #include "StDbLib/StDbTable.h" #include "StDbLib/StDbConfigNode.hh" #include "tables/St_emcCalib_Table.h" ClassImp(StEmcEqualMaker) //_____________________________________________________________________________ StEmcEqualMaker::StEmcEqualMaker(const char *name):StEmcCalibMaker(name) { setRange(700); } //_____________________________________________________________________________ StEmcEqualMaker::~StEmcEqualMaker() { } //_____________________________________________________________________________ Int_t StEmcEqualMaker::Init() { float pi = 3.1415926; mA = new TH1F("mA","",getNChannel(),0.5,getNChannel()+0.5); mB = new TH1F("mB","",getNChannel(),0.5,getNChannel()+0.5); mADistr = new TH1F("mADistr","",200,0,10); mBDistr = new TH1F("mBDistr","",200,-10,10); mStatus = new TH1F("mStatus","",getNChannel(),0.5,getNChannel()+0.5); mRefSlopes = new TH1F("mRefSlopes","",getNChannel(),0.5,getNChannel()+0.5); mRefAmps = new TH1F("mRefAmps","",getNChannel(),0.5,getNChannel()+0.5); mSlopes = new TH1F("mSlopes","",getNChannel(),0.5,getNChannel()+0.5); mAmps = new TH1F("mAmps","",getNChannel(),0.5,getNChannel()+0.5); mSlopesTheta = new TH2F("mSlopesTheta","",40,45*pi/180,135*pi/180,100,0,100); mSpecName ="mSpecEqual"; mAcceptName = "mAcceptEqual"; return StEmcCalibMaker::Init(); } //_____________________________________________________________________________ void StEmcEqualMaker::Clear(Option_t *option) { } //_____________________________________________________________________________ Int_t StEmcEqualMaker::Make() { if(!accept()) return kStOk; for(int i=0;i<mNChannel;i++) { int id = i+1; float rms = getCalib()->getPedRms(mDetector,id); float adc = (float) getCalib()->getADCPedSub(mDetector,id); if(adc!=0 && adc>3*rms) fill(id,adc); } return kStOK; } //_____________________________________________________________________________ Int_t StEmcEqualMaker::Finish() { saveHist((char*)mFileName.Data()); return StMaker::Finish(); } //_____________________________________________________________________________ void StEmcEqualMaker::equalize(int mode,int DeltaEta,bool Et) { mADistr->Reset(); mBDistr->Reset(); StEmcGeom *g = getGeom(); int Neta = g->NEta(); int Nsub = g->NSub(); int etabin = 0; float avg[18000]; float MIN = 20; float MAX = 500; TF1 *f= new TF1("slopes","22*TMath::Sin(x)"); for(int eta0 = -Neta; eta0<Neta; eta0+=DeltaEta) { etabin++; float sum = 0; float n = 0; int m1 = 1; int m2 = 60; if(eta0<0) { m1 = 61; m2 = 120; } if(DeltaEta == 2*Neta){ m1=1; m2=120;} for(int j = 0;j<DeltaEta;j++) { int eta = eta0+j; if(eta>=0) eta+=1; cout <<"etabin = "<<etabin<<" eta = "<<eta<<endl; eta = abs(eta); //cout <<"Calculating averages ..."<<endl; for(int m = m1;m<=m2;m++) { for(int sub = 1;sub<=Nsub;sub++) { int id; g->getId(m,eta,sub,id); TH1D * h = getSpec(id); if(h->Integral()>0) { float m1,r1; getMeanAndRms(h,MIN,MAX,&m1,&r1); sum+=m1; n++; avg[id-1] = m1; } } } } float AVG = 0; if(n>0) AVG=sum/n; if(AVG>0) { int ID = 0; float DCA = 99999; //cout <<"Looking for reference ..."<<endl; for(int m = m1;m<=m2;m++) for(int j = 0;j<DeltaEta;j++) for(int sub = 1;sub<=Nsub;sub++) { int id; int eta = eta0+j; if(eta>=0) eta+=1; eta = abs(eta); g->getId(m,eta,sub,id); if(avg[id-1]>0 && fabs(avg[id-1]-AVG)<DCA) { DCA = fabs(avg[id-1]-AVG); ID = id;} } if(ID>0) { cout <<"Reference found id = "<<ID<<" avg = "<<avg[ID-1]<<endl; cout <<"Equalizing eta bin ..."<<endl; for(int m = m1;m<=m2;m++) for(int j = 0;j<DeltaEta;j++) for(int sub = 1;sub<=Nsub;sub++) { int eta = eta0+j; if(eta>=0) eta+=1; eta = abs(eta); int id; g->getId(m,eta,sub,id); if(mode!=5) equalizeRelative(ID,id,mode,Et); else equalizeToFunction(id,f); } } } } delete f; return; } //_____________________________________________________________________________ void StEmcEqualMaker::equalizeRelative(int ref, int channel,int mode, bool Et) { // mean and RMS modes // 0 - mean and RMS with liear average // 1 - mean with linear average // 2 - mean and rms with log average // 3 - mean with log average // 4 - exponential fit TH1D *h1 = getSpec(ref,"ref"); TH1D *h2 = getSpec(channel,"channel"); float integral1 = h1->Integral(); float integral2 = h2->Integral(); mA->SetBinContent(channel,0); mB->SetBinContent(channel,0); mStatus->SetBinContent(channel,0); mRefSlopes->SetBinContent(channel,0); mRefAmps->SetBinContent(channel,0); mSlopes->SetBinContent(channel,0); mAmps->SetBinContent(channel,0); float MIN = 20; float MAX = 500; //cout <<"ref = "<<ref<<" channel = "<<channel<<endl; //cout <<"h1 = "<<h1<<" h2 = "<<h2<<endl; //cout <<"integral 1 = "<<integral1<<" integral 2 = "<<integral2<<endl; if((integral1==0 || integral2==0) && h1!=h2) { delete h1; delete h2; return; } if((integral1==0 || integral2==0) && h1==h2) { delete h1; return; } bool EqDone=kFALSE; float a=0,b=0; if(mode==-1) { a = 1; b = 0; EqDone=true; } if(mode>=0 && mode <=3) { float m1,r1,m2,r2; if(mode==0 || mode==1) { getMeanAndRms(h1,MIN,MAX,&m1,&r1); getMeanAndRms(h2,MIN,MAX,&m2,&r2); } if(mode==2 || mode==3) { getLogMeanAndRms(h1,MIN,MAX,&m1,&r1); getLogMeanAndRms(h2,MIN,MAX,&m2,&r2); } if(mode==0 || mode==2) { a=r1/r2; b=m1-a*m2; } if(mode==1 || mode==3) { a=m1/m2; b=0; } EqDone=kTRUE; cout <<" id = "<<channel<<" ref = "<<ref<<" mean = "<<m1<<" , "<<m2 <<" rms = "<<r1<<" , "<<r2 <<" a = "<<a<<" b = "<<b<<endl; } float m1=0,m2=0,A1=0,A2=0; if(mode==4) { TF1 *f=new TF1("ff","[0]*exp(-x/[1])",MIN,MAX); float I1 = h1->Integral(h1->FindBin(MIN),h1->FindBin(MAX)); f->SetParameter(1,10); h1->Fit(f,"RQN"); m1 = f->GetParameter(1); A1 = f->GetParameter(0); mRefSlopes->SetBinContent(channel,m1); mRefAmps->SetBinContent(channel,A1); float I2 = h2->Integral(h2->FindBin(MIN),h2->FindBin(MAX)); h2->Fit(f,"RQN"); m2 = f->GetParameter(1); A2 = f->GetParameter(0); mSlopes->SetBinContent(channel,m2); mAmps->SetBinContent(channel,A2); a=m1/m2; b=-::log((A2*I1)/(A1*I2)); EqDone=true; if(!finite(a) || !finite(b) || a<=0 || b>1000) {EqDone = false; a = 0;} b=0; cout <<" id = "<<channel<<" ref = "<<ref<<" slopes = "<<m2<<" , "<<m1 <<" a = "<<a<<" b = "<<b<<" EQDONE = "<<(Int_t)EqDone<<endl; delete f; } if (EqDone) { mA->SetBinContent(channel,a); mB->SetBinContent(channel,b); mADistr->Fill(a); mBDistr->Fill(b); mStatus->SetBinContent(channel,1); float theta; int mod,eta,sub; getGeom()->getBin(channel,mod,eta,sub); getGeom()->getTheta(mod,eta,theta); mSlopesTheta->Fill(theta,m2); } else mStatus->SetBinContent(channel,2); delete h1; delete h2; return; } //_____________________________________________________________________________ void StEmcEqualMaker::equalizeToFunction(int channel,TF1 *func) { TH1D *h2 = getSpec(channel,"channel"); float integral2 = h2->Integral(); mA->SetBinContent(channel,0); mB->SetBinContent(channel,0); mStatus->SetBinContent(channel,0); mRefSlopes->SetBinContent(channel,0); mRefAmps->SetBinContent(channel,0); mSlopes->SetBinContent(channel,0); mAmps->SetBinContent(channel,0); float MIN = 20; float MAX = 500; if(integral2==0) { delete h2; mA->SetBinContent(channel,0); mB->SetBinContent(channel,0); return; } bool EqDone=kFALSE; float a=0,b=0; float theta; int mod,eta,sub; getGeom()->getBin(channel,mod,eta,sub); getGeom()->getTheta(mod,eta,theta); float m1=0,m2=0,A1=0,A2=0; TF1 *f=new TF1("ff","[0]*exp(-x/[1])",MIN,MAX); f->SetParameter(1,10); m1 = func->Eval(theta); mRefSlopes->SetBinContent(channel,m1); mRefAmps->SetBinContent(channel,A1); if(channel<=2400) { //float I2 = h2->Integral(h2->FindBin(MIN),h2->FindBin(MAX)); h2->Fit(f,"RQN"); m2 = f->GetParameter(1); A2 = f->GetParameter(0); mSlopes->SetBinContent(channel,m2); mAmps->SetBinContent(channel,A2); a=m1/m2; } //else a =1; //protection because crates in the east side are not timed EqDone=true; if(!finite(a) || !finite(b) || a<=0.01 || b>1000 || a > 10) { EqDone = false; a = 0;} b=0; cout <<" id = "<<channel<<" slopes = "<<m2<<" , "<<m1 <<" a = "<<a<<" b = "<<b<<" EQDONE = "<<(Int_t)EqDone<<endl; delete f; if (EqDone) { mA->SetBinContent(channel,a); mB->SetBinContent(channel,b); mADistr->Fill(a); mBDistr->Fill(b); mStatus->SetBinContent(channel,1); mSlopesTheta->Fill(theta,m2); } else mStatus->SetBinContent(channel,2); delete h2; return; } //_____________________________________________________________________________ void StEmcEqualMaker::calcSlopes() { float MIN = 20; float MAX = 500; mSlopes->Reset(); mAmps->Reset(); mSlopesTheta->Reset(); TF1 *f=new TF1("ff","[0]*exp(-x/[1])",MIN,MAX); StEmcGeom *g = getGeom(); for(int channel = 1;channel<=getNChannel();channel++) { TH1D *h2 = getSpec(channel,"channel"); float I2 = h2->Integral(h2->FindBin(MIN),h2->FindBin(MAX)); if(I2>0) { float theta; int mod,eta,sub; g->getBin(channel,mod,eta,sub); g->getTheta(mod,eta,theta); float m2=0,A2=0; f->SetParameter(1,10); h2->Fit(f,"RQN"); m2 = f->GetParameter(1); A2 = f->GetParameter(0); mSlopes->SetBinContent(channel,m2); mAmps->SetBinContent(channel,A2); mSlopesTheta->Fill(theta,m2); cout <<"Slope for channel "<<channel<<" is "<<m2<<endl; } delete h2; } delete f; return; } //_____________________________________________________________________________ void StEmcEqualMaker::saveEqual(int date,int time) { char ts[100]; TString n[] = {"bemcEqual","bprsEqual","bsmdeEqual","bsmdpEqual"}; sprintf(ts,"%s.%08d.%06d.root",n[getDetector()-1].Data(),date,time); TFile *f = new TFile(ts,"RECREATE"); if(getSpec()) getSpec()->Write(); if(mA) mA->Write(); if(mB) mB->Write(); if(mADistr) mADistr->Write(); if(mBDistr) mBDistr->Write(); if(mStatus) mStatus->Write(); if(mRefSlopes) mRefSlopes->Write(); if(mRefAmps) mRefAmps->Write(); if(mSlopes) mSlopes->Write(); if(mAmps) mAmps->Write(); if(mSlopesTheta) mSlopesTheta->Write(); f->Close(); delete f; return; } //_____________________________________________________________________________ void StEmcEqualMaker::loadEqual(char* file) { TFile *f = new TFile(file); mA->Reset(); mB->Reset(); mADistr->Reset(); mBDistr->Reset(); mStatus->Reset(); mRefSlopes->Reset(); mRefAmps->Reset(); mSlopes->Reset(); mAmps->Reset(); mSlopesTheta->Reset(); getSpec()->Reset(); if(f->Get("mSpec;1")) getSpec()->Add((TH2F*)f->Get("mSpec;1"),1); if(f->Get("mA;1")) mA->Add((TH1F*)f->Get("mA;1"),1); if(f->Get("mB;1")) mB->Add((TH1F*)f->Get("mB;1"),1); if(f->Get("mADistr;1")) mADistr->Add((TH1F*)f->Get("mADistr;1"),1); if(f->Get("mBDistr;1")) mBDistr->Add((TH1F*)f->Get("mBDistr;1"),1); if(f->Get("mStatus;1")) mStatus->Add((TH1F*)f->Get("mStatus;1"),1); if(f->Get("mRefSlopes;1")) mRefSlopes->Add((TH1F*)f->Get("mRefSlopes;1"),1); if(f->Get("mRefAmps;1")) mRefAmps->Add((TH1F*)f->Get("mRefAmps;1"),1); if(f->Get("mSlopes;1")) mSlopes->Add((TH1F*)f->Get("mSlopes;1"),1); if(f->Get("mAmps;1")) mAmps->Add((TH1F*)f->Get("mAmps;1"),1); if(f->Get("mSlopesTheta;1")) mSlopesTheta->Add((TH2F*)f->Get("mSlopesTheta;1"),1); f->Close(); delete f; return; } //_____________________________________________________________________________ TH1F* StEmcEqualMaker::getEtaBinSpec(int eta0, int eta1,TH2F* SPEC) { TH2F *spec = NULL; if(!SPEC) spec = getSpec(); else spec = SPEC; if(!spec) return NULL; int mi = 1; int mf = 60; if(eta0<0 && eta1<0) { mi = 61; mf = 120; } if(eta0*eta1<0) { mi =1; mf = 120; } int ns = getGeom()->NSub(); int e0 = abs(eta0); int e1 = abs(eta1); TH1F *hist = (TH1F*)spec->ProjectionY("etabin",1,1); hist->Reset(); for(int m=mi;m<=mf;m++) { for(int e=e0;e<=e1;e++) { for(int s=1;s<=ns;s++) { int id; getGeom()->getId(m,e,s,id); char name[30]; sprintf(name,"Tower %d",id); TH1F* tmp = rebin(id,name,spec); if(tmp) { hist->Add(tmp,1); delete tmp; tmp = NULL; } } } } return hist; } //_____________________________________________________________________________ TH1F* StEmcEqualMaker::rebin(int id,const char *name, TH2F* SPEC) { TH2F *spec = NULL; if(!SPEC) spec = getSpec(); else spec = SPEC; if(!spec) return NULL; float seg = 50; float a = mA->GetBinContent(id); float b = mB->GetBinContent(id); //cout <<"A = "<<a<<" B = "<<b<<endl; if(a<=0) return NULL; TH1F *h = (TH1F*)spec->ProjectionY(name,id,id); if(a==1 && b==0) return h; float deltaBin=h->GetBinWidth(1)/seg; int nbins=h->GetNbinsX(); float Y[4096]; for(int i=0;i<4096;i++) Y[i] = 0; for(int i=1;i<=nbins;i++) Y[i] = h->GetBinContent(i); h->Reset(); for(int i=1;i<=nbins;i++) { float x = h->GetBinLowEdge(i); float y = Y[i]; for(int j=0;j<(int)seg;j++) { float x1 = x+((float)j+0.5)*deltaBin; float x2 = x1*a+b; //if (a>1) cout <<position<<" "<<a<<" "<<x1<<" "<<x2<<endl; h->Fill(x2,y/seg); } } return h; } //_____________________________________________________________________________ // this method leaks memory because it draws a lot of histograms // use it with care // AASPSUAIDE void StEmcEqualMaker::drawEtaBin(int eta0, int eta1,TH2F* SPEC) { TH2F *spec = NULL; if(!SPEC) spec = getSpec(); else spec = SPEC; if(!spec) return; int mi = 1; int mf = 60; if(eta0<0 && eta1<0) { mi = 61; mf = 120; } if(eta0*eta1<0) { mi =1; mf = 120; } int ns = getGeom()->NSub(); int e0 = abs(eta0); int e1 = abs(eta1); bool first = true; for(int m=mi;m<=mf;m++) { for(int e=e0;e<=e1;e++) { for(int s=1;s<=ns;s++) { int id; getGeom()->getId(m,e,s,id); char name[30]; sprintf(name,"Tower %d",id); TH1F* tmp = rebin(id,name,spec); if(tmp) { if(first) { tmp->Draw(); first = false;} else tmp->Draw("same"); } } } } return; }
24.811448
93
0.611616
[ "geometry" ]
2d74f1d5e444b69dcea8812c765807ffa5c881b0
18,433
cc
C++
chrome/browser/media_galleries/linux/mtp_device_delegate_impl_linux.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:51:34.000Z
2018-02-15T03:11:54.000Z
chrome/browser/media_galleries/linux/mtp_device_delegate_impl_linux.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-12-13T19:44:12.000Z
2021-12-13T19:44:12.000Z
chrome/browser/media_galleries/linux/mtp_device_delegate_impl_linux.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:52:03.000Z
2022-02-13T17:58:45.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/media_galleries/linux/mtp_device_delegate_impl_linux.h" #include "base/bind.h" #include "base/files/file_path.h" #include "base/strings/string_util.h" #include "chrome/browser/media_galleries/linux/mtp_device_task_helper.h" #include "chrome/browser/media_galleries/linux/mtp_device_task_helper_map_service.h" #include "chrome/browser/media_galleries/linux/snapshot_file_details.h" #include "content/public/browser/browser_thread.h" namespace { // File path separator constant. const char kRootPath[] = "/"; // Returns the device relative file path given |file_path|. // E.g.: If the |file_path| is "/usb:2,2:12345/DCIM" and |registered_dev_path| // is "/usb:2,2:12345", this function returns the device relative path which is // "/DCIM". std::string GetDeviceRelativePath(const base::FilePath& registered_dev_path, const base::FilePath& file_path) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); DCHECK(!registered_dev_path.empty()); DCHECK(!file_path.empty()); if (registered_dev_path == file_path) return kRootPath; base::FilePath relative_path; if (!registered_dev_path.AppendRelativePath(file_path, &relative_path)) return std::string(); DCHECK(!relative_path.empty()); return relative_path.value(); } // Returns the MTPDeviceTaskHelper object associated with the MTP device // storage. // // |storage_name| specifies the name of the storage device. // Returns NULL if the |storage_name| is no longer valid (e.g. because the // corresponding storage device is detached, etc). MTPDeviceTaskHelper* GetDeviceTaskHelperForStorage( const std::string& storage_name) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); return MTPDeviceTaskHelperMapService::GetInstance()->GetDeviceTaskHelper( storage_name); } // Opens the storage device for communication. // // Called on the UI thread to dispatch the request to the // MediaTransferProtocolManager. // // |storage_name| specifies the name of the storage device. // |reply_callback| is called when the OpenStorage request completes. // |reply_callback| runs on the IO thread. void OpenStorageOnUIThread( const std::string& storage_name, const base::Callback<void(bool)>& reply_callback) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); MTPDeviceTaskHelper* task_helper = GetDeviceTaskHelperForStorage(storage_name); if (!task_helper) { task_helper = MTPDeviceTaskHelperMapService::GetInstance()->CreateDeviceTaskHelper( storage_name); } task_helper->OpenStorage(storage_name, reply_callback); } // Enumerates the |root| directory file entries. // // Called on the UI thread to dispatch the request to the // MediaTransferProtocolManager. // // |storage_name| specifies the name of the storage device. // |success_callback| is called when the ReadDirectory request succeeds. // |error_callback| is called when the ReadDirectory request fails. // |success_callback| and |error_callback| runs on the IO thread. void ReadDirectoryOnUIThread( const std::string& storage_name, const std::string& root, const base::Callback< void(const fileapi::AsyncFileUtil::EntryList&)>& success_callback, const base::Callback<void(base::PlatformFileError)>& error_callback) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); MTPDeviceTaskHelper* task_helper = GetDeviceTaskHelperForStorage(storage_name); if (!task_helper) return; task_helper->ReadDirectoryByPath(root, success_callback, error_callback); } // Gets the |file_path| details. // // Called on the UI thread to dispatch the request to the // MediaTransferProtocolManager. // // |storage_name| specifies the name of the storage device. // |success_callback| is called when the GetFileInfo request succeeds. // |error_callback| is called when the GetFileInfo request fails. // |success_callback| and |error_callback| runs on the IO thread. void GetFileInfoOnUIThread( const std::string& storage_name, const std::string& file_path, const base::Callback<void(const base::PlatformFileInfo&)>& success_callback, const base::Callback<void(base::PlatformFileError)>& error_callback) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); MTPDeviceTaskHelper* task_helper = GetDeviceTaskHelperForStorage(storage_name); if (!task_helper) return; task_helper->GetFileInfoByPath(file_path, success_callback, error_callback); } // Copies the contents of |device_file_path| to |snapshot_file_path|. // // Called on the UI thread to dispatch the request to the // MediaTransferProtocolManager. // // |storage_name| specifies the name of the storage device. // |device_file_path| specifies the media device file path. // |snapshot_file_path| specifies the platform path of the snapshot file. // |file_size| specifies the number of bytes that will be written to the // snapshot file. // |success_callback| is called when the copy operation succeeds. // |error_callback| is called when the copy operation fails. // |success_callback| and |error_callback| runs on the IO thread. void WriteDataIntoSnapshotFileOnUIThread( const std::string& storage_name, const SnapshotRequestInfo& request_info, const base::PlatformFileInfo& snapshot_file_info) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); MTPDeviceTaskHelper* task_helper = GetDeviceTaskHelperForStorage(storage_name); if (!task_helper) return; task_helper->WriteDataIntoSnapshotFile(request_info, snapshot_file_info); } // Closes the device storage specified by the |storage_name| and destroys the // MTPDeviceTaskHelper object associated with the device storage. // // Called on the UI thread to dispatch the request to the // MediaTransferProtocolManager. void CloseStorageAndDestroyTaskHelperOnUIThread( const std::string& storage_name) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); MTPDeviceTaskHelper* task_helper = GetDeviceTaskHelperForStorage(storage_name); if (!task_helper) return; task_helper->CloseStorage(); MTPDeviceTaskHelperMapService::GetInstance()->DestroyDeviceTaskHelper( storage_name); } } // namespace MTPDeviceDelegateImplLinux::PendingTaskInfo::PendingTaskInfo( const tracked_objects::Location& location, const base::Closure& task) : location(location), task(task) { } MTPDeviceDelegateImplLinux::PendingTaskInfo::~PendingTaskInfo() { } MTPDeviceDelegateImplLinux::MTPDeviceDelegateImplLinux( const std::string& device_location) : init_state_(UNINITIALIZED), task_in_progress_(false), device_path_(device_location), weak_ptr_factory_(this) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); DCHECK(!device_path_.empty()); RemoveChars(device_location, kRootPath, &storage_name_); DCHECK(!storage_name_.empty()); } MTPDeviceDelegateImplLinux::~MTPDeviceDelegateImplLinux() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); } void MTPDeviceDelegateImplLinux::GetFileInfo( const base::FilePath& file_path, const GetFileInfoSuccessCallback& success_callback, const ErrorCallback& error_callback) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); DCHECK(!file_path.empty()); base::Closure call_closure = base::Bind(&GetFileInfoOnUIThread, storage_name_, GetDeviceRelativePath(device_path_, file_path), base::Bind(&MTPDeviceDelegateImplLinux::OnDidGetFileInfo, weak_ptr_factory_.GetWeakPtr(), success_callback), base::Bind(&MTPDeviceDelegateImplLinux::HandleDeviceFileError, weak_ptr_factory_.GetWeakPtr(), error_callback)); EnsureInitAndRunTask(PendingTaskInfo(FROM_HERE, call_closure)); } void MTPDeviceDelegateImplLinux::ReadDirectory( const base::FilePath& root, const ReadDirectorySuccessCallback& success_callback, const ErrorCallback& error_callback) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); DCHECK(!root.empty()); std::string device_file_relative_path = GetDeviceRelativePath(device_path_, root); base::Closure call_closure = base::Bind( &GetFileInfoOnUIThread, storage_name_, device_file_relative_path, base::Bind( &MTPDeviceDelegateImplLinux::OnDidGetFileInfoToReadDirectory, weak_ptr_factory_.GetWeakPtr(), device_file_relative_path, success_callback, error_callback), base::Bind(&MTPDeviceDelegateImplLinux::HandleDeviceFileError, weak_ptr_factory_.GetWeakPtr(), error_callback)); EnsureInitAndRunTask(PendingTaskInfo(FROM_HERE, call_closure)); } void MTPDeviceDelegateImplLinux::CreateSnapshotFile( const base::FilePath& device_file_path, const base::FilePath& snapshot_file_path, const CreateSnapshotFileSuccessCallback& success_callback, const ErrorCallback& error_callback) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); DCHECK(!device_file_path.empty()); DCHECK(!snapshot_file_path.empty()); std::string device_file_relative_path = GetDeviceRelativePath(device_path_, device_file_path); scoped_ptr<SnapshotRequestInfo> request_info( new SnapshotRequestInfo(device_file_relative_path, snapshot_file_path, success_callback, error_callback)); base::Closure call_closure = base::Bind( &GetFileInfoOnUIThread, storage_name_, device_file_relative_path, base::Bind( &MTPDeviceDelegateImplLinux::OnDidGetFileInfoToCreateSnapshotFile, weak_ptr_factory_.GetWeakPtr(), base::Passed(&request_info)), base::Bind(&MTPDeviceDelegateImplLinux::HandleDeviceFileError, weak_ptr_factory_.GetWeakPtr(), error_callback)); EnsureInitAndRunTask(PendingTaskInfo(FROM_HERE, call_closure)); } void MTPDeviceDelegateImplLinux::CancelPendingTasksAndDeleteDelegate() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); // To cancel all the pending tasks, destroy the MTPDeviceTaskHelper object. content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&CloseStorageAndDestroyTaskHelperOnUIThread, storage_name_)); delete this; } void MTPDeviceDelegateImplLinux::EnsureInitAndRunTask( const PendingTaskInfo& task_info) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); if ((init_state_ == INITIALIZED) && !task_in_progress_) { task_in_progress_ = true; content::BrowserThread::PostTask(content::BrowserThread::UI, task_info.location, task_info.task); return; } pending_tasks_.push(task_info); if (init_state_ == UNINITIALIZED) { init_state_ = PENDING_INIT; task_in_progress_ = true; content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&OpenStorageOnUIThread, storage_name_, base::Bind(&MTPDeviceDelegateImplLinux::OnInitCompleted, weak_ptr_factory_.GetWeakPtr()))); } } void MTPDeviceDelegateImplLinux::WriteDataIntoSnapshotFile( const base::PlatformFileInfo& file_info) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); DCHECK(current_snapshot_request_info_.get()); DCHECK_GT(file_info.size, 0); task_in_progress_ = true; SnapshotRequestInfo request_info( current_snapshot_request_info_->device_file_path, current_snapshot_request_info_->snapshot_file_path, base::Bind( &MTPDeviceDelegateImplLinux::OnDidWriteDataIntoSnapshotFile, weak_ptr_factory_.GetWeakPtr()), base::Bind( &MTPDeviceDelegateImplLinux::OnWriteDataIntoSnapshotFileError, weak_ptr_factory_.GetWeakPtr())); base::Closure task_closure = base::Bind(&WriteDataIntoSnapshotFileOnUIThread, storage_name_, request_info, file_info); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, task_closure); } void MTPDeviceDelegateImplLinux::ProcessNextPendingRequest() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); DCHECK(!task_in_progress_); if (pending_tasks_.empty()) return; task_in_progress_ = true; const PendingTaskInfo& task_info = pending_tasks_.front(); content::BrowserThread::PostTask(content::BrowserThread::UI, task_info.location, task_info.task); pending_tasks_.pop(); } void MTPDeviceDelegateImplLinux::OnInitCompleted(bool succeeded) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); init_state_ = succeeded ? INITIALIZED : UNINITIALIZED; task_in_progress_ = false; ProcessNextPendingRequest(); } void MTPDeviceDelegateImplLinux::OnDidGetFileInfo( const GetFileInfoSuccessCallback& success_callback, const base::PlatformFileInfo& file_info) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); success_callback.Run(file_info); task_in_progress_ = false; ProcessNextPendingRequest(); } void MTPDeviceDelegateImplLinux::OnDidGetFileInfoToReadDirectory( const std::string& root, const ReadDirectorySuccessCallback& success_callback, const ErrorCallback& error_callback, const base::PlatformFileInfo& file_info) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); DCHECK(task_in_progress_); if (!file_info.is_directory) { return HandleDeviceFileError(error_callback, base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY); } base::Closure task_closure = base::Bind(&ReadDirectoryOnUIThread, storage_name_, root, base::Bind(&MTPDeviceDelegateImplLinux::OnDidReadDirectory, weak_ptr_factory_.GetWeakPtr(), success_callback), base::Bind(&MTPDeviceDelegateImplLinux::HandleDeviceFileError, weak_ptr_factory_.GetWeakPtr(), error_callback)); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, task_closure); } void MTPDeviceDelegateImplLinux::OnDidGetFileInfoToCreateSnapshotFile( scoped_ptr<SnapshotRequestInfo> snapshot_request_info, const base::PlatformFileInfo& file_info) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); DCHECK(!current_snapshot_request_info_.get()); DCHECK(snapshot_request_info.get()); DCHECK(task_in_progress_); base::PlatformFileError error = base::PLATFORM_FILE_OK; if (file_info.is_directory) error = base::PLATFORM_FILE_ERROR_NOT_A_FILE; else if (file_info.size < 0 || file_info.size > kuint32max) error = base::PLATFORM_FILE_ERROR_FAILED; if (error != base::PLATFORM_FILE_OK) return HandleDeviceFileError(snapshot_request_info->error_callback, error); base::PlatformFileInfo snapshot_file_info(file_info); // Modify the last modified time to null. This prevents the time stamp // verfication in LocalFileStreamReader. snapshot_file_info.last_modified = base::Time(); current_snapshot_request_info_.reset(snapshot_request_info.release()); if (file_info.size == 0) { // Empty snapshot file. return OnDidWriteDataIntoSnapshotFile( snapshot_file_info, current_snapshot_request_info_->snapshot_file_path); } WriteDataIntoSnapshotFile(snapshot_file_info); } void MTPDeviceDelegateImplLinux::OnDidReadDirectory( const ReadDirectorySuccessCallback& success_callback, const fileapi::AsyncFileUtil::EntryList& file_list) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); success_callback.Run(file_list, false /*no more entries*/); task_in_progress_ = false; ProcessNextPendingRequest(); } void MTPDeviceDelegateImplLinux::OnDidWriteDataIntoSnapshotFile( const base::PlatformFileInfo& file_info, const base::FilePath& snapshot_file_path) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); DCHECK(current_snapshot_request_info_.get()); DCHECK(task_in_progress_); current_snapshot_request_info_->success_callback.Run( file_info, snapshot_file_path); task_in_progress_ = false; current_snapshot_request_info_.reset(); ProcessNextPendingRequest(); } void MTPDeviceDelegateImplLinux::OnWriteDataIntoSnapshotFileError( base::PlatformFileError error) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); DCHECK(current_snapshot_request_info_.get()); DCHECK(task_in_progress_); current_snapshot_request_info_->error_callback.Run(error); task_in_progress_ = false; current_snapshot_request_info_.reset(); ProcessNextPendingRequest(); } void MTPDeviceDelegateImplLinux::HandleDeviceFileError( const ErrorCallback& error_callback, base::PlatformFileError error) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); error_callback.Run(error); task_in_progress_ = false; ProcessNextPendingRequest(); } void CreateMTPDeviceAsyncDelegate( const std::string& device_location, const CreateMTPDeviceAsyncDelegateCallback& callback) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); callback.Run(new MTPDeviceDelegateImplLinux(device_location)); }
40.334792
84
0.723756
[ "object" ]
2d769ecfff13451100c0e9134390498ac5111be9
2,137
hpp
C++
src/calc/models/bleCalc.hpp
erythrocyte/ble
b9e00bd02a3493de24fdb8d4edff4effcd62daa8
[ "MIT" ]
null
null
null
src/calc/models/bleCalc.hpp
erythrocyte/ble
b9e00bd02a3493de24fdb8d4edff4effcd62daa8
[ "MIT" ]
5
2020-09-03T13:56:53.000Z
2020-09-04T01:50:15.000Z
src/calc/models/bleCalc.hpp
erythrocyte/ble
b9e00bd02a3493de24fdb8d4edff4effcd62daa8
[ "MIT" ]
null
null
null
#ifndef BLE_SRC_CALC_MODELS_BLECALC_H_ #define BLE_SRC_CALC_MODELS_BLECALC_H_ #include <functional> #include <iostream> #include <memory> #include <vector> #include "bleResultData.hpp" #include "calc/models/averFwSaveData.hpp" #include "common/models/fwData.hpp" #include "common/models/solverData.hpp" #include "common/models/tauData.hpp" #include "common/models/wellWorkParams.hpp" #include "mesh/models/grid.hpp" namespace ble::src::calc::models { class BleCalc { public: BleCalc(); ~BleCalc(); void calc(const std::shared_ptr<mesh::models::Grid> grd, const std::shared_ptr<common::models::SolverData> data, std::function<void(double)> set_progress, bool clear_aver); size_t get_data_len() { return _results->data.size(); } std::shared_ptr<common::models::DynamicData> get_data(int index) const { return _results->data[index]; } std::shared_ptr<BleResultData> get_result() { return _results; } std::vector<std::shared_ptr<common::models::WellWorkParams>> get_well_work_params() { return _wellWorkParams; } std::vector<std::shared_ptr<common::models::TauData>> get_tau_data() { return m_tau_data; } std::vector<std::shared_ptr<common::models::FwData>> get_aver_fw_data() { return m_fw_data; } double get_period(); private: std::shared_ptr<BleResultData> _results; std::vector<std::shared_ptr<common::models::WellWorkParams>> _wellWorkParams; std::vector<std::shared_ptr<common::models::TauData>> m_tau_data; std::vector<std::shared_ptr<common::models::FwData>> m_fw_data; double m_sum_t; std::shared_ptr<mesh::models::Grid> m_grd; std::shared_ptr<common::models::SolverData> m_data; void set_initial_cond(); void save_press(int index, const std::vector<double> p); void save_any_vector(const std::vector<std::tuple<double, double>>& v, const std::string& fn); void save_faces_val(); void add_aver_fw(double pv, double fw, double fw_shore, const std::vector<double> s); void check_conservative(); void save_aver_fw(const char* fn, const std::shared_ptr<AverFwSaveData> data); }; } // namespace ble::src #endif
39.574074
115
0.727188
[ "mesh", "vector" ]
2d7b62e5e0adfea3d8b621e27ad3ffd72d793137
7,378
cc
C++
src/developer/debug/zxdb/client/process_symbol_data_provider.cc
liexusong/fuchsia
81897680af92a1848a063e3c20ff3a4892ccff07
[ "BSD-2-Clause" ]
3
2021-09-02T07:21:06.000Z
2022-03-12T03:20:10.000Z
src/developer/debug/zxdb/client/process_symbol_data_provider.cc
liexusong/fuchsia
81897680af92a1848a063e3c20ff3a4892ccff07
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/developer/debug/zxdb/client/process_symbol_data_provider.cc
liexusong/fuchsia
81897680af92a1848a063e3c20ff3a4892ccff07
[ "BSD-2-Clause" ]
2
2022-02-25T12:22:49.000Z
2022-03-12T03:20:10.000Z
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/developer/debug/zxdb/client/process_symbol_data_provider.h" #include <inttypes.h> #include <lib/syslog/cpp/macros.h> #include "src/developer/debug/shared/message_loop.h" #include "src/developer/debug/zxdb/client/frame.h" #include "src/developer/debug/zxdb/client/memory_dump.h" #include "src/developer/debug/zxdb/client/process.h" #include "src/developer/debug/zxdb/client/session.h" #include "src/developer/debug/zxdb/client/thread.h" #include "src/developer/debug/zxdb/common/err.h" #include "src/developer/debug/zxdb/symbols/dwarf_expr_eval.h" #include "src/developer/debug/zxdb/symbols/loaded_module_symbols.h" #include "src/developer/debug/zxdb/symbols/process_symbols.h" #include "src/developer/debug/zxdb/symbols/symbol_context.h" #include "src/lib/fxl/strings/string_printf.h" namespace zxdb { namespace { Err ProcessDestroyedErr() { return Err("Process destroyed."); } debug_ipc::Arch ArchForProcess(Process* process) { if (!process) return debug_ipc::Arch::kUnknown; return process->session()->arch(); } } // namespace ProcessSymbolDataProvider::ProcessSymbolDataProvider(Process* process) : process_(process), arch_(ArchForProcess(process)) {} ProcessSymbolDataProvider::~ProcessSymbolDataProvider() = default; void ProcessSymbolDataProvider::Disown() { process_ = nullptr; } debug_ipc::Arch ProcessSymbolDataProvider::GetArch() { return arch_; } void ProcessSymbolDataProvider::GetMemoryAsync(uint64_t address, uint32_t size, GetMemoryCallback callback) { if (!process_) { debug_ipc::MessageLoop::Current()->PostTask(FROM_HERE, [cb = std::move(callback)]() mutable { cb(ProcessDestroyedErr(), std::vector<uint8_t>()); }); return; } // Mistakes may make extremely large memory requests which can OOM the system. Prevent those. if (size > 1024 * 1024) { debug_ipc::MessageLoop::Current()->PostTask( FROM_HERE, [address, size, cb = std::move(callback)]() mutable { cb(Err(fxl::StringPrintf("Memory request for %u bytes at 0x%" PRIx64 " is too large.", size, address)), std::vector<uint8_t>()); }); return; } process_->ReadMemory( address, size, [address, size, cb = std::move(callback)](const Err& err, MemoryDump dump) mutable { if (err.has_error()) { cb(err, std::vector<uint8_t>()); return; } FX_DCHECK(size == 0 || dump.address() == address); FX_DCHECK(dump.size() == size); if (dump.blocks().size() == 1 || (dump.blocks().size() > 1 && !dump.blocks()[1].valid)) { // Common case: came back as one block OR it read until an invalid memory boundary and the // second block is invalid. // // In both these cases we can directly return the first data block. We don't have to check // the first block's valid flag since if it's not valid it will be empty, which is what // our API specifies. cb(Err(), std::move(dump.blocks()[0].data)); } else { // The debug agent doesn't guarantee that a memory dump will exist in only one block even // if the memory is all valid. Flatten all contiguous valid regions to a single buffer. std::vector<uint8_t> flat; flat.reserve(dump.size()); for (const auto block : dump.blocks()) { if (!block.valid) break; flat.insert(flat.end(), block.data.begin(), block.data.end()); } cb(Err(), std::move(flat)); } }); } void ProcessSymbolDataProvider::WriteMemory(uint64_t address, std::vector<uint8_t> data, WriteCallback cb) { if (!process_) { debug_ipc::MessageLoop::Current()->PostTask( FROM_HERE, [cb = std::move(cb)]() mutable { cb(ProcessDestroyedErr()); }); return; } process_->WriteMemory(address, std::move(data), std::move(cb)); } std::optional<uint64_t> ProcessSymbolDataProvider::GetDebugAddressForContext( const SymbolContext& context) const { if (process_) { if (auto syms = process_->GetSymbols()) { if (auto lms = syms->GetModuleForAddress(context.load_address())) { return lms->debug_address(); } } } return std::nullopt; } void ProcessSymbolDataProvider::GetTLSSegment(const SymbolContext& symbol_context, GetTLSSegmentCallback cb) { if (!process_) { return cb(Err("Thread-local storage requires a current process.")); } auto syms = process_->GetSymbols(); if (!syms) { return cb(Err("Could not load symbols for process when resolving TLS segment.")); } auto lms = syms->GetModuleForAddress(symbol_context.load_address()); if (!lms) { return cb(Err("Could not find current module when resolving TLS segment.")); } process_->GetTLSHelpers([debug_address = lms->debug_address(), this_ref = RefPtrTo(this), symbol_context, cb = std::move(cb)](ErrOr<const Process::TLSHelpers*> helpers) mutable { if (helpers.has_error()) { return cb(helpers.err()); } std::vector<uint8_t> program; program.reserve(helpers.value()->link_map_tls_modid.size() + helpers.value()->tlsbase.size() + 1); std::copy(helpers.value()->link_map_tls_modid.begin(), helpers.value()->link_map_tls_modid.end(), std::back_inserter(program)); std::copy(helpers.value()->tlsbase.begin(), helpers.value()->tlsbase.end(), std::back_inserter(program)); // This code manually creates a DwarfExprEval rather that use the AsyncDwarfExprEval (which // makes things a little simpler) because we want to get the exact stack value (this is called // in the context of another DwarfExprEval). auto dwarf_eval = std::make_shared<DwarfExprEval>(); dwarf_eval->Push(static_cast<DwarfExprEval::StackEntry>(debug_address)); dwarf_eval->Eval(this_ref, symbol_context, DwarfExpr(std::move(program)), [dwarf_eval, cb = std::move(cb)](DwarfExprEval*, const Err& err) mutable { // Prevent the DwarfExprEval from getting reentrantly deleted from within its // own callback by posting a reference back to the message loop. This creates // an owning reference to the DwarfExprEval to the message loop to force it // to get deleted in the future when that's executed rather than from within // this stack frame. debug_ipc::MessageLoop::Current()->PostTask(FROM_HERE, [dwarf_eval]() {}); if (err.has_error()) { return cb(err); } if (dwarf_eval->GetResultType() != DwarfExprEval::ResultType::kPointer) { return cb(Err("TLS DWARF expression did not produce a pointer.")); } cb(static_cast<uint64_t>(dwarf_eval->GetResult())); }); }); } } // namespace zxdb
40.538462
100
0.629439
[ "vector" ]
2d8153afc4adefdc4bfc698e5a150a498f6ba06d
3,880
cc
C++
aegis/src/model/DescribeSuspEventQuaraFilesResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
aegis/src/model/DescribeSuspEventQuaraFilesResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
aegis/src/model/DescribeSuspEventQuaraFilesResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/aegis/model/DescribeSuspEventQuaraFilesResult.h> #include <json/json.h> using namespace AlibabaCloud::Aegis; using namespace AlibabaCloud::Aegis::Model; DescribeSuspEventQuaraFilesResult::DescribeSuspEventQuaraFilesResult() : ServiceResult() {} DescribeSuspEventQuaraFilesResult::DescribeSuspEventQuaraFilesResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeSuspEventQuaraFilesResult::~DescribeSuspEventQuaraFilesResult() {} void DescribeSuspEventQuaraFilesResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allQuaraFilesNode = value["QuaraFiles"]["QuaraFile"]; for (auto valueQuaraFilesQuaraFile : allQuaraFilesNode) { QuaraFile quaraFilesObject; if(!valueQuaraFilesQuaraFile["Path"].isNull()) quaraFilesObject.path = valueQuaraFilesQuaraFile["Path"].asString(); if(!valueQuaraFilesQuaraFile["EventName"].isNull()) quaraFilesObject.eventName = valueQuaraFilesQuaraFile["EventName"].asString(); if(!valueQuaraFilesQuaraFile["Id"].isNull()) quaraFilesObject.id = std::stoi(valueQuaraFilesQuaraFile["Id"].asString()); if(!valueQuaraFilesQuaraFile["EventType"].isNull()) quaraFilesObject.eventType = valueQuaraFilesQuaraFile["EventType"].asString(); if(!valueQuaraFilesQuaraFile["Tag"].isNull()) quaraFilesObject.tag = valueQuaraFilesQuaraFile["Tag"].asString(); if(!valueQuaraFilesQuaraFile["Uuid"].isNull()) quaraFilesObject.uuid = valueQuaraFilesQuaraFile["Uuid"].asString(); if(!valueQuaraFilesQuaraFile["InstanceName"].isNull()) quaraFilesObject.instanceName = valueQuaraFilesQuaraFile["InstanceName"].asString(); if(!valueQuaraFilesQuaraFile["InternetIp"].isNull()) quaraFilesObject.internetIp = valueQuaraFilesQuaraFile["InternetIp"].asString(); if(!valueQuaraFilesQuaraFile["Ip"].isNull()) quaraFilesObject.ip = valueQuaraFilesQuaraFile["Ip"].asString(); if(!valueQuaraFilesQuaraFile["Status"].isNull()) quaraFilesObject.status = valueQuaraFilesQuaraFile["Status"].asString(); if(!valueQuaraFilesQuaraFile["Md5"].isNull()) quaraFilesObject.md5 = valueQuaraFilesQuaraFile["Md5"].asString(); if(!valueQuaraFilesQuaraFile["ModifyTime"].isNull()) quaraFilesObject.modifyTime = valueQuaraFilesQuaraFile["ModifyTime"].asString(); quaraFiles_.push_back(quaraFilesObject); } if(!value["Count"].isNull()) count_ = std::stoi(value["Count"].asString()); if(!value["PageSize"].isNull()) pageSize_ = std::stoi(value["PageSize"].asString()); if(!value["TotalCount"].isNull()) totalCount_ = std::stoi(value["TotalCount"].asString()); if(!value["CurrentPage"].isNull()) currentPage_ = std::stoi(value["CurrentPage"].asString()); } int DescribeSuspEventQuaraFilesResult::getTotalCount()const { return totalCount_; } int DescribeSuspEventQuaraFilesResult::getPageSize()const { return pageSize_; } int DescribeSuspEventQuaraFilesResult::getCurrentPage()const { return currentPage_; } std::vector<DescribeSuspEventQuaraFilesResult::QuaraFile> DescribeSuspEventQuaraFilesResult::getQuaraFiles()const { return quaraFiles_; } int DescribeSuspEventQuaraFilesResult::getCount()const { return count_; }
35.925926
113
0.769845
[ "vector", "model" ]
2d83d2080c4f69363585495e47755fdc36df6754
9,686
cpp
C++
cpgf/test/reflection/test_reflection_cast.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
187
2015-01-19T06:05:30.000Z
2022-03-27T14:28:21.000Z
cpgf/test/reflection/test_reflection_cast.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
37
2015-01-16T04:15:11.000Z
2020-03-31T23:42:55.000Z
cpgf/test/reflection/test_reflection_cast.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
50
2015-01-13T13:50:10.000Z
2022-01-25T17:16:51.000Z
#include "test_reflection_common.h" using namespace std; using namespace cpgf; #define PTREQUAL(pa, pb) GEQUAL((void *)pa, (void *)pb) #define PTRDIFF(pa, pb) GDIFF((void *)pa, (void *)pb) namespace Test_Cast { namespace { class R { public: virtual ~R() {} int r[20]; }; class A : public R { public: virtual ~A() {} int a; }; class B : virtual public A { public: virtual ~B() {} virtual void c1() {} double c; }; class C : virtual public A { public: virtual ~C() {} long long d[20]; }; class D : virtual public B, virtual public C { public: virtual ~D() {} int e[10]; }; template <typename Meta> void reflectCast(Meta define) { define._class(GDefineMetaClass<R>::declare("R")); define._class(GDefineMetaClass<A, R>::declare("A")); define._class(GDefineMetaClass<B, A>::declare("B")); define._class(GDefineMetaClass<C, A>::declare("C")); define._class(GDefineMetaClass<D, B, C>::declare("D")); } // not really test, but to ensure we can have different pointers on same object GTEST(testCastForLayout) { GCHECK(IsPolymorphic<A>::Result); GCHECK(IsPolymorphic<B>::Result); GCHECK(IsPolymorphic<C>::Result); GCHECK(IsPolymorphic<D>::Result); D d; D * pd = &d; C * pc = pd; B * pb = pd; A * pa = pd; PTRDIFF(pa, pd); PTRDIFF(pb, pd); PTRDIFF(pc, pd); } GTEST(testCastBetweenBaseLib) { GDefineMetaNamespace ns = GDefineMetaNamespace::declare("ns"); reflectCast(ns); const GMetaClass * nsClass = ns.getMetaClass(); const GMetaClass * classB = nsClass->getClass("B"); const GMetaClass * classC = nsClass->getClass("C"); const GMetaClass * classD = nsClass->getClass("D"); D d; D * pd = &d; A * pa = pd; void * p; p = pd; p = classD->castToBase(p, 0); // B PTREQUAL(p, (B *)pd); p = classB->castToBase(p, 0); // A PTREQUAL(p, pa); p = pd; p = classD->castToBase(p, 1); // C PTREQUAL(p, (C *)pd); p = classC->castToBase(p, 0); // A PTREQUAL(p, pa); p = pa; p = classB->castFromBase(p, 0); // B PTREQUAL(p, dynamic_cast<B *>(pa)); p = classD->castFromBase(p, 0); // D PTREQUAL(p, pd); p = pa; p = classC->castFromBase(p, 0); // C PTREQUAL(p, dynamic_cast<C *>(pa)); p = classD->castFromBase(p, 1); // D PTREQUAL(p, pd); } GTEST(testCastBetweenBaseLibApi) { GDefineMetaNamespace ns = GDefineMetaNamespace::declare("ns"); reflectCast(ns); GScopedInterface<IMetaClass> nsClass(static_cast<IMetaClass *>(metaItemToInterface(ns.getMetaClass()))); GScopedInterface<IMetaClass> classB(nsClass->getClass("B")); GScopedInterface<IMetaClass> classC(nsClass->getClass("C")); GScopedInterface<IMetaClass> classD(nsClass->getClass("D")); D d; D * pd = &d; A * pa = pd; void * p; p = pd; p = classD->castToBase(p, 0); // B PTREQUAL(p, (B *)pd); p = classB->castToBase(p, 0); // A PTREQUAL(p, pa); p = pd; p = classD->castToBase(p, 1); // C PTREQUAL(p, (C *)pd); p = classC->castToBase(p, 0); // A PTREQUAL(p, pa); p = pa; p = classB->castFromBase(p, 0); // B PTREQUAL(p, dynamic_cast<B *>(pa)); p = classD->castFromBase(p, 0); // D PTREQUAL(p, pd); p = pa; p = classC->castFromBase(p, 0); // C PTREQUAL(p, dynamic_cast<C *>(pa)); p = classD->castFromBase(p, 1); // D PTREQUAL(p, pd); } GTEST(testCastBetweenDerivedLib) { GDefineMetaNamespace ns = GDefineMetaNamespace::declare("ns"); reflectCast(ns); const GMetaClass * nsClass = ns.getMetaClass(); const GMetaClass * classA = nsClass->getClass("A"); const GMetaClass * classB = nsClass->getClass("B"); const GMetaClass * classC = nsClass->getClass("C"); D d; D * pd = &d; A * pa = pd; void * p; p = pa; p = classA->castToDerived(p, 0); // B PTREQUAL(p, dynamic_cast<B *>(pa)); p = classB->castToDerived(p, 0); // D PTREQUAL(p, pd); p = pa; p = classA->castToDerived(p, 1); // C PTREQUAL(p, dynamic_cast<C *>(pa)); p = classC->castToDerived(p, 0); // D PTREQUAL(p, pd); p = pd; p = classC->castFromDerived(p, 0); // C PTREQUAL(p, dynamic_cast<C *>(pa)); p = classA->castFromDerived(p, 1); // A PTREQUAL(p, pa); p = pd; p = classB->castFromDerived(p, 0); // B PTREQUAL(p, dynamic_cast<B *>(pa)); p = classA->castFromDerived(p, 0); // A PTREQUAL(p, pa); } GTEST(testCastBetweenDerivedApi) { GDefineMetaNamespace ns = GDefineMetaNamespace::declare("ns"); reflectCast(ns); GScopedInterface<IMetaClass> nsClass(static_cast<IMetaClass *>(metaItemToInterface(ns.getMetaClass()))); GScopedInterface<IMetaClass> classA(nsClass->getClass("A")); GScopedInterface<IMetaClass> classB(nsClass->getClass("B")); GScopedInterface<IMetaClass> classC(nsClass->getClass("C")); D d; D * pd = &d; A * pa = pd; void * p; p = pa; p = classA->castToDerived(p, 0); // B PTREQUAL(p, dynamic_cast<B *>(pa)); p = classB->castToDerived(p, 0); // D PTREQUAL(p, pd); p = pa; p = classA->castToDerived(p, 1); // C PTREQUAL(p, dynamic_cast<C *>(pa)); p = classC->castToDerived(p, 0); // D PTREQUAL(p, pd); p = pd; p = classC->castFromDerived(p, 0); // C PTREQUAL(p, dynamic_cast<C *>(pa)); p = classA->castFromDerived(p, 1); // A PTREQUAL(p, pa); p = pd; p = classB->castFromDerived(p, 0); // B PTREQUAL(p, dynamic_cast<B *>(pa)); p = classA->castFromDerived(p, 0); // A PTREQUAL(p, pa); } GTEST(testFindAppropriateDerivedClassLib) { GDefineMetaNamespace ns = GDefineMetaNamespace::declare("ns"); reflectCast(ns); const GMetaClass * nsClass = ns.getMetaClass(); const GMetaClass * classR = nsClass->getClass("R"); const GMetaClass * classA = nsClass->getClass("A"); const GMetaClass * classD = nsClass->getClass("D"); const GMetaClass * resultClass; R r; A a; D d; R * pr = &r; A * pa = &a; D * pd = &d; void * p; void * result; p = pr; resultClass = findAppropriateDerivedClass(p, classR, &result); GCHECK(resultClass->equals(classR)); PTREQUAL(result, pr); p = pa; resultClass = findAppropriateDerivedClass(p, classA, &result); GCHECK(resultClass->equals(classA)); PTREQUAL(result, pa); p = (A *)pd; // must cast to A * first, otherwise, p will point to D directly, not point to A resultClass = findAppropriateDerivedClass(p, classA, &result); GCHECK(resultClass->equals(classD)); PTREQUAL(result, pd); } GTEST(testFindAppropriateDerivedClassApi) { GDefineMetaNamespace ns = GDefineMetaNamespace::declare("ns"); reflectCast(ns); GScopedInterface<IMetaClass> nsClass(static_cast<IMetaClass *>(metaItemToInterface(ns.getMetaClass()))); GScopedInterface<IMetaClass> classR(nsClass->getClass("R")); GScopedInterface<IMetaClass> classA(nsClass->getClass("A")); GScopedInterface<IMetaClass> classB(nsClass->getClass("B")); GScopedInterface<IMetaClass> classC(nsClass->getClass("C")); GScopedInterface<IMetaClass> classD(nsClass->getClass("D")); GScopedInterface<IMetaClass> resultClass; R r; A a; D d; R * pr = &r; A * pa = &a; D * pd = &d; void * p; void * result; p = pr; resultClass.reset(findAppropriateDerivedClass(p, classR.get(), &result)); GCHECK(resultClass->equals(classR.get())); PTREQUAL(result, pr); p = pa; resultClass.reset(findAppropriateDerivedClass(p, classA.get(), &result)); GCHECK(resultClass->equals(classA.get())); PTREQUAL(result, pa); p = (A *)pd; // must cast to A * first, otherwise, p will point to D directly, not point to A resultClass.reset(findAppropriateDerivedClass(p, classA.get(), &result)); GCHECK(resultClass->equals(classD.get())); PTREQUAL(result, pd); } GTEST(testMetaCastToBase) { GDefineMetaNamespace ns = GDefineMetaNamespace::declare("ns"); reflectCast(ns); GScopedInterface<IMetaClass> nsClass(static_cast<IMetaClass *>(metaItemToInterface(ns.getMetaClass()))); GScopedInterface<IMetaClass> classR(nsClass->getClass("R")); GScopedInterface<IMetaClass> classA(nsClass->getClass("A")); GScopedInterface<IMetaClass> classB(nsClass->getClass("B")); GScopedInterface<IMetaClass> classC(nsClass->getClass("C")); GScopedInterface<IMetaClass> classD(nsClass->getClass("D")); D d; R * pr = &d; A * pa = &d; B * pb = &d; C * pc = &d; D * pd = &d; void * result; result = metaCastToBase(pd, classD.get(), classR.get()); PTREQUAL(result, pr); result = metaCastToBase(pd, classD.get(), classA.get()); PTREQUAL(result, pa); result = metaCastToBase(pd, classD.get(), classB.get()); PTREQUAL(result, pb); result = metaCastToBase(pd, classD.get(), classC.get()); PTREQUAL(result, pc); } GTEST(testMetaCastToDerived) { GDefineMetaNamespace ns = GDefineMetaNamespace::declare("ns"); reflectCast(ns); GScopedInterface<IMetaClass> nsClass(static_cast<IMetaClass *>(metaItemToInterface(ns.getMetaClass()))); GScopedInterface<IMetaClass> classR(nsClass->getClass("R")); GScopedInterface<IMetaClass> classA(nsClass->getClass("A")); GScopedInterface<IMetaClass> classB(nsClass->getClass("B")); GScopedInterface<IMetaClass> classC(nsClass->getClass("C")); GScopedInterface<IMetaClass> classD(nsClass->getClass("D")); D d; R * pr = &d; A * pa = &d; B * pb = &d; C * pc = &d; D * pd = &d; void * result; result = metaCastToDerived(pr, classR.get(), classA.get()); PTREQUAL(result, pa); result = metaCastToDerived(pr, classR.get(), classB.get()); PTREQUAL(result, pb); result = metaCastToDerived(pr, classR.get(), classC.get()); PTREQUAL(result, pc); result = metaCastToDerived(pr, classR.get(), classD.get()); PTREQUAL(result, pd); } } }
24.336683
106
0.643093
[ "object" ]
2d854d9014105d7d6232209b67d179f3b5dddf31
10,638
cpp
C++
platform/Windows/src.Windows/SYS_SharedMemory.cpp
slajerek/MTEngineSDL
19b5295d875c197ec03bc20ddacd48c228920365
[ "MIT" ]
4
2021-12-16T11:22:30.000Z
2022-01-05T11:20:32.000Z
platform/Windows/src.Windows/SYS_SharedMemory.cpp
slajerek/MTEngineSDL
19b5295d875c197ec03bc20ddacd48c228920365
[ "MIT" ]
1
2022-01-07T10:41:38.000Z
2022-01-09T12:04:03.000Z
platform/Windows/src.Windows/SYS_SharedMemory.cpp
slajerek/MTEngineSDL
19b5295d875c197ec03bc20ddacd48c228920365
[ "MIT" ]
null
null
null
#include <windows.h> #include "SYS_SharedMemory.h" #include "SYS_Threading.h" #include "SYS_FileSystem.h" //#include "SYS_CommandLine.h" #include "SYS_Funct.h" #include "CSlrString.h" #include "SYS_Startup.h" #include <windows.h> #include <signal.h> #include <sys/stat.h> #include <psapi.h> #include <list> #include <tchar.h> #include <Shlwapi.h> #pragma comment(lib, "Shlwapi.lib") #define MAX_PROCESSES 4096 DWORD FindOtherProcessInstance(__in_z LPCTSTR lpcszFileName); HWND FindWindowFromPid(DWORD pidToFind); void *mtSharedMemoryDescriptor = NULL; uint8 *mtSharedMemory = NULL; u32 mtSharedMemorySize = 0; u32 mtSharedMemoryKey = 0; std::list<CSharedMemorySignalCallback *> mtSharedMemoryCallbacks; CSlrMutex *mtSharedMemoryMutex; void mtEngineHandleWM_USER(); void SYS_InitSharedMemory(u32 sharedMemoryKey, u32 sharedMemorySize) { LOGD("SYS_InitSharedMemory: key=%d size=%d", sharedMemoryKey, sharedMemorySize); mtSharedMemoryMutex = new CSlrMutex("mtSharedMemoryMutex"); mtSharedMemory = SYS_MapSharedMemory(sharedMemorySize, sharedMemoryKey, &mtSharedMemoryDescriptor); if (mtSharedMemory == NULL) { LOGError("SYS_InitSharedMemory: mtSharedMemory is NULL!"); return; } mtSharedMemorySize = sharedMemorySize; mtSharedMemoryKey = sharedMemoryKey; memset(mtSharedMemory, 0, sharedMemorySize); } void SYS_InitSharedMemorySignalHandlers() { } void SYS_SharedMemoryRegisterCallback(CSharedMemorySignalCallback *callback) { mtSharedMemoryMutex->Lock(); mtSharedMemoryCallbacks.push_back(callback); mtSharedMemoryMutex->Unlock(); } void SYS_SharedMemoryUnregisterCallback(CSharedMemorySignalCallback *callback) { mtSharedMemoryMutex->Lock(); mtSharedMemoryCallbacks.remove(callback); mtSharedMemoryMutex->Unlock(); } void mtEngineHandleWM_USER() { LOGD("mtEngineHandleWM_USER"); //if (signo == SIGINT) { // load new configuration from shared memory uint32 dataSize; uint8 *data = SYS_ReadFromSharedMemory(&dataSize); CByteBuffer *byteBuffer = new CByteBuffer(data, dataSize); mtSharedMemoryMutex->Lock(); for (std::list<CSharedMemorySignalCallback *>::iterator it = mtSharedMemoryCallbacks.begin(); it != mtSharedMemoryCallbacks.end(); it++) { CSharedMemorySignalCallback *callback = *it; byteBuffer->Rewind(); callback->SharedMemorySignalCallback(byteBuffer); } mtSharedMemoryMutex->Unlock(); delete byteBuffer; memset(mtSharedMemory, 0, mtSharedMemorySize); } LOGD("mtEngineHandleWM_USER done"); } void SYS_StoreToSharedMemory(uint8 *data, uint32 dataSize) { LOGD("SYS_StoreToSharedMemory: length=%d", dataSize); if (mtSharedMemory == NULL) { LOGError("SYS_StoreToSharedMemory: sharedMemory is NULL!"); return; } if (dataSize >= mtSharedMemorySize) { LOGError("SYS_StoreToSharedMemory: dataSize=%d > max=%d", dataSize, mtSharedMemorySize); return; } mtSharedMemory[0] = (uint8) (((dataSize) >> 24) & 0x00FF); mtSharedMemory[1] = (uint8) (((dataSize) >> 16) & 0x00FF); mtSharedMemory[2] = (uint8) (((dataSize) >> 8) & 0x00FF); mtSharedMemory[3] = (uint8) ((dataSize) & 0x00FF); memcpy(mtSharedMemory + 4, data, dataSize); LOGD("SYS_StoreToSharedMemory: stored %d bytes", dataSize); } uint8 *SYS_ReadFromSharedMemory(uint32 *dataSize) { LOGD("SYS_ReadFromSharedMemory"); if (mtSharedMemory == NULL) { LOGError("SYS_ReadFromSharedMemory: sharedMemory is NULL!"); *dataSize = 0; return NULL; } *dataSize = mtSharedMemory[3] | (mtSharedMemory[2] << 8) | (mtSharedMemory[1] << 16) | (mtSharedMemory[0] << 24); if (*dataSize >= mtSharedMemorySize) { LOGError("SYS_ReadFromSharedMemory: dataSize=%d > max=%d", *dataSize, mtSharedMemorySize); *dataSize = 0; return NULL; } uint8 *data = new uint8[*dataSize]; memcpy(data, mtSharedMemory + 4, *dataSize); LOGD("SYS_ReadFromSharedMemory: read %d bytes", *dataSize); return data; } int SYS_SendConfigurationToOtherAppInstance(CByteBuffer *byteBuffer) { LOGM("SYS_SendConfigurationToOtherAppInstance"); // Find other instance pid, store data to shared memory and raise signal SIGUSR1 TCHAR buffer[MAX_PATH]={0}; TCHAR *out; DWORD bufSize=sizeof(buffer)/sizeof(*buffer); // Get the fully-qualified path of the executable if(GetModuleFileName(NULL, buffer, bufSize)==bufSize) { LOGError("SYS_SendConfigurationToOtherAppInstance: EXE file path too long"); return -1; } // Go to the beginning of the file name out = PathFindFileName(buffer); // Set the dot before the extension to 0 (terminate the string there) //*(PathFindExtension(out)) = 0; DWORD bundlePid = FindOtherProcessInstance(out); if (bundlePid == 0) { LOGD("Other instance not found"); return -1; } LOGD("Found other instance of app, pid=%d", bundlePid); // Store new configuration to shared memory LOGD("Send byteBuffer to pid=%d", bundlePid); byteBuffer->DebugPrint(); SYS_StoreToSharedMemory(byteBuffer->data, byteBuffer->length); // Send signal to instance to flag new data HWND hWnd = FindWindowFromPid(bundlePid); if (hWnd == NULL) { LOGError("Other instance found pid=%d, but window not found", bundlePid); return -1; } LOGM("PostMessage WM_USER to hWnd=%x", hWnd); PostMessage(hWnd, WM_USER, WM_USER_TRIGGER_WPARAM, WM_USER_TRIGGER_LPARAM); //SYS_Sleep(15000); return bundlePid; } //bool SYS_SharedMemoryExists(int memoryKeyId, int memorySize) //{ // return true; //} uint8 *SYS_MapSharedMemory(int memorySize, int memoryKeyId, void **fileDescriptor) { LOGD("SYS_MapSharedMemory: memoryKeyId=%d", memoryKeyId); TCHAR szName[]=TEXT("RetroDebugger"); HANDLE *hMapFile = (HANDLE*)malloc(sizeof(HANDLE)); LPCTSTR pBuf; *hMapFile = CreateFileMapping( INVALID_HANDLE_VALUE, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) memorySize, // maximum object size (low-order DWORD) szName); // name of mapping object if (*hMapFile == NULL) { LOGError("Could not create file mapping object (%d)", GetLastError()); return NULL; } pBuf = (LPTSTR) MapViewOfFile(*hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, memorySize); if (pBuf == NULL) { LOGError("Could not map view of file (%d)", GetLastError()); CloseHandle(*hMapFile); return NULL; } LOGD("SYS_MapSharedMemory: mapped memory to %x", pBuf); *fileDescriptor = hMapFile; return (uint8*)pBuf; } void SYS_UnMapSharedMemory(void **fileDescriptor, uint8 *memory) { LOGD("SYS_UnMapSharedMemory: memory=%x", memory); if (memory == NULL) { LOGError("SYS_UnMapSharedMemory: memory is NULL"); return; } LPCTSTR pBuf = (LPCTSTR)memory; HANDLE *hMapFile = (HANDLE*)*fileDescriptor; UnmapViewOfFile(memory); CloseHandle(hMapFile); return; } void CSharedMemorySignalCallback::SharedMemorySignalCallback(CByteBuffer *sharedMemoryData) { } DWORD FindOtherProcessInstance(__in_z LPCTSTR lpcszFileName) { LPDWORD lpdwProcessIds; LPTSTR lpszBaseName; HANDLE hProcess; DWORD i, cdwProcesses, dwProcessId = 0; DWORD currentProcessId = GetCurrentProcessId(); lpdwProcessIds = (LPDWORD)HeapAlloc(GetProcessHeap(), 0, MAX_PROCESSES*sizeof(DWORD)); if (lpdwProcessIds != NULL) { if (EnumProcesses(lpdwProcessIds, MAX_PROCESSES*sizeof(DWORD), &cdwProcesses)) { lpszBaseName = (LPTSTR)HeapAlloc(GetProcessHeap(), 0, MAX_PATH*sizeof(TCHAR)); if (lpszBaseName != NULL) { cdwProcesses /= sizeof(DWORD); for (i = 0; i < cdwProcesses; i++) { if (currentProcessId == lpdwProcessIds[i]) continue; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, lpdwProcessIds[i]); if (hProcess != NULL) { if (GetModuleBaseName(hProcess, NULL, lpszBaseName, MAX_PATH) > 0) { LOGD("lpszBaseName='%s'", lpszBaseName); if (!lstrcmpi(lpszBaseName, lpcszFileName)) { dwProcessId = lpdwProcessIds[i]; CloseHandle(hProcess); break; } } CloseHandle(hProcess); } } HeapFree(GetProcessHeap(), 0, (LPVOID)lpszBaseName); } } HeapFree(GetProcessHeap(), 0, (LPVOID)lpdwProcessIds); } return dwProcessId; } HWND FindWindowFromPid(DWORD pidToFind) { LOGD("FindWindowFromPid"); HWND hCurWnd = GetTopWindow(0); while (hCurWnd != NULL) { DWORD cur_pid; DWORD dwTheardId = GetWindowThreadProcessId(hCurWnd, &cur_pid); if (cur_pid == pidToFind) { if (IsWindowVisible(hCurWnd) != 0) { TCHAR szClassName[256]; GetClassName(hCurWnd, szClassName, 256); LOGD("...hCurWnd=%x szClassName='%s' HWND_CLASS_NAME='%s'", hCurWnd, szClassName, HWND_CLASS_NAME); if (_tcscmp(szClassName,HWND_CLASS_NAME)==0) return hCurWnd; } } hCurWnd = GetNextWindow(hCurWnd, GW_HWNDNEXT); } return NULL; } // CSlrString *SYS_GetClipboardAsSlrString() { // Try opening the clipboard if (! OpenClipboard(NULL)) { LOGError("SYS_GetClipboardAsSlrString: Error while OpenClipboard"); return NULL; } // Get handle of clipboard object for ANSI text HANDLE hData = GetClipboardData(CF_TEXT); if (hData == NULL) { return NULL; } // Lock the handle to get the actual text pointer char * pszText = static_cast<char*>( GlobalLock(hData) ); if (pszText == NULL) { GlobalUnlock( hData ); return NULL; } // Save text in a string class instance CSlrString *str = new CSlrString(pszText); LOGD("SYS_GetClipboardAsSlrString: Clipboard text='%s'", pszText); str->DebugPrint("str="); // Release the lock GlobalUnlock( hData ); // Release the clipboard CloseClipboard(); return str; } bool SYS_SetClipboardAsSlrString(CSlrString *str) { // Try opening the clipboard if (! OpenClipboard(NULL)) { LOGError("SYS_SetClipboardAsSlrString: Error while OpenClipboard"); return false; } char *output = str->GetStdASCII(); const size_t len = strlen(output) + 1; HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len); memcpy(GlobalLock(hMem), output, len); GlobalUnlock(hMem); EmptyClipboard(); SetClipboardData(CF_TEXT, hMem); delete [] output; // Release the clipboard CloseClipboard(); return true; }
24.455172
138
0.687535
[ "object" ]
2d85efa0c7095184a46fcca0dd7640b03ab13102
3,134
cpp
C++
drv_search/src/targetselect.cpp
DrawZeroPoint/drv_package_v2
fc4b83e1a7ee4a3e007e32358a5e0035e0dcf5cb
[ "MIT" ]
13
2017-09-06T13:33:19.000Z
2021-09-20T08:53:05.000Z
drv_search/src/targetselect.cpp
DrawZeroPoint/drv_package_v2
fc4b83e1a7ee4a3e007e32358a5e0035e0dcf5cb
[ "MIT" ]
null
null
null
drv_search/src/targetselect.cpp
DrawZeroPoint/drv_package_v2
fc4b83e1a7ee4a3e007e32358a5e0035e0dcf5cb
[ "MIT" ]
5
2017-11-02T13:09:33.000Z
2018-06-07T01:08:29.000Z
#include "targetselect.h" TargetSelect::TargetSelect() : rgb_it(nh) { searchPubImage_ = rgb_it.advertise("search/labeled_image", 1); searchPubInfo_ = nh.advertise<std_msgs::String>("/comm/vision/info", 1); client = nh.serviceClient<drv_msgs::user_select>("drv_user"); } int TargetSelect::select(string targetLabel, drv_msgs::recognizeResponse response, sensor_msgs::Image img_in, cv_bridge::CvImagePtr &img_out, int &choosed_id) { int selectedNum = 0; // 0 represent no target // get scene image try { img_out = cv_bridge::toCvCopy(img_in, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); } vector<int> id_candidate; // fetch target(s) number and paint on image int fc = 0; for (size_t i = 0; i < response.obj_info.labels.size(); i++) { if (targetLabel == response.obj_info.labels[i].data) { id_candidate.push_back(i); fc++; paintTarget(img_out->image, i, fc, response.obj_info.bbox_arrays); } } searchPubImage_.publish(img_out->toImageMsg()); if (fc == 0) selectedNum = 0; else { ROS_INFO("Found %d object(s) that may be the target!", fc); selectedNum = callService(fc); // value range [0,inf) } if (selectedNum > 0) choosed_id = id_candidate[selectedNum - 1]; return selectedNum; } int TargetSelect::callService(int num) { drv_msgs::user_select srv; // Target number to be selected, starts from 1 srv.request.select_num = num; int result = 0; if (client.call(srv)) { result = srv.response.selected_id; if (result == 0) ROS_INFO("You have confirmed current scene have no target."); else { if (result <= num && result >= 1) ROS_INFO("The number %d object confirmed to be the target!", result); else { result = 0; ROS_ERROR("Invalid target number, the selectd number should between 1 to %d!", num); } } } else ROS_ERROR("Failed to call user select service."); return result; } void TargetSelect::paintTarget(Mat &img, int id, int fc, vector<std_msgs::UInt16MultiArray> box_array) { // Array index starts from 0, while num starts from 1 std_msgs::UInt16MultiArray array = box_array[id]; int x = (array.data[0] + array.data[2]) / 2; int y = (array.data[1] + array.data[3]) / 2; Scalar color = Scalar(195, 42, 242); // In bgr order, don't miss 'Scalar' circle(img, Point(x,y), 12, color, 2); if(y - 25 > 0) line(img, Point(x,y), Point(x,y - 25), color, 2); else line(img, Point(x,y), Point(x, 0), color, 2); if(y + 25 < 480) line(img, Point(x, y), Point(x, y + 25), color, 2); else line(img, Point(x, y), Point(x, 480), color, 2); if(x - 25 > 0) line(img, Point(x, y), Point(x - 25,y), color, 2); else line(img, Point(x, y), Point(0, y), color, 2); if(x + 25 < 640) line(img, Point(x,y), Point(x + 25,y), color, 2); else line(img, Point(x,y), Point(640, y), color, 2); putText(img, intToString(fc), Point(x + 10, y - 10), 1, 2, color, 2); }
28.752294
92
0.620932
[ "object", "vector" ]
2d8c3f1ecc55238ee00b8741a9b2c0c05bb51bdf
6,326
cc
C++
chrome/browser/net/cookie_store_sameparty_browsertest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/net/cookie_store_sameparty_browsertest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/net/cookie_store_sameparty_browsertest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright (c) 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/path_service.h" #include "base/strings/strcat.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/common/content_paths.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "net/cookies/canonical_cookie_test_helpers.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "services/network/public/cpp/network_switches.h" #include "services/network/public/mojom/cookie_manager.mojom.h" #include "testing/gmock/include/gmock/gmock-matchers.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const char* kSamePartySameSiteLaxCookieName = "sameparty_samesite_lax_cookie"; const char* kSamePartySameSiteNoneCookieName = "sameparty_samesite_none_cookie"; const char* kSamePartySameSiteUnspecifiedCookieName = "sameparty_samesite_unspecified_cookie"; const char* kSameSiteNoneCookieName = "samesite_none_cookie"; class CookieStoreSamePartyTest : public InProcessBrowserTest { public: CookieStoreSamePartyTest() : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {} CookieStoreSamePartyTest(const CookieStoreSamePartyTest&) = delete; CookieStoreSamePartyTest& operator=(const CookieStoreSamePartyTest&) = delete; void SetUpCommandLine(base::CommandLine* command_line) override { InProcessBrowserTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII(network::switches::kUseFirstPartySet, "https://a.test,https://b.test"); } void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); base::FilePath path; base::PathService::Get(content::DIR_TEST_DATA, &path); https_server_.ServeFilesFromDirectory(path); https_server_.AddDefaultHandlers(GetChromeTestDataDir()); https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES); ASSERT_TRUE(https_server_.Start()); } content::WebContents* contents() { return browser()->tab_strip_model()->GetActiveWebContents(); } content::RenderFrameHost* GetDescendantFrame( const std::vector<int>& indices) { content::RenderFrameHost* frame = contents()->GetMainFrame(); for (int index : indices) { frame = ChildFrameAt(frame, index); } return frame; } std::string GetCookiesViaCookieStore(content::RenderFrameHost* frame) { std::string script = R"( (async () => { const cookies = await cookieStore.getAll(); return cookies.map(c => `${c.name}=${c.value}`).join(';'); })(); )"; return content::EvalJs(frame, script).ExtractString(); } void SetSamePartyCookies(const std::string& host) { Profile* profile = browser()->profile(); ASSERT_TRUE(content::SetCookie( profile, https_server().GetURL(host, "/"), base::StrCat({kSamePartySameSiteLaxCookieName, "=1; samesite=lax; secure; sameparty"}))); ASSERT_TRUE(content::SetCookie( profile, https_server().GetURL(host, "/"), base::StrCat({kSamePartySameSiteNoneCookieName, "=1; samesite=none; secure; sameparty"}))); ASSERT_TRUE(content::SetCookie( profile, https_server().GetURL(host, "/"), base::StrCat({kSamePartySameSiteUnspecifiedCookieName, "=1; secure; sameparty"}))); ASSERT_TRUE(content::SetCookie( profile, https_server().GetURL(host, "/"), base::StrCat({kSameSiteNoneCookieName, "=1; samesite=none; secure"}))); } const net::test_server::EmbeddedTestServer& https_server() const { return https_server_; } private: net::test_server::EmbeddedTestServer https_server_; }; IN_PROC_BROWSER_TEST_F(CookieStoreSamePartyTest, ReadCookies_SamePartyContext) { SetSamePartyCookies("b.test"); ASSERT_TRUE(NavigateToURL( contents(), https_server().GetURL("a.test", base::StrCat({"/cross_site_iframe_factory.html?", "a.test(b.test)"})))); EXPECT_THAT(GetCookiesViaCookieStore(GetDescendantFrame({0})), net::CookieStringIs(testing::UnorderedElementsAre( testing::Key(kSamePartySameSiteLaxCookieName), testing::Key(kSamePartySameSiteNoneCookieName), testing::Key(kSamePartySameSiteUnspecifiedCookieName), testing::Key(kSameSiteNoneCookieName)))); } IN_PROC_BROWSER_TEST_F(CookieStoreSamePartyTest, ReadCookies_CrossPartyContext) { SetSamePartyCookies("c.test"); ASSERT_TRUE(NavigateToURL( contents(), https_server().GetURL("a.test", base::StrCat({"/cross_site_iframe_factory.html?", "a.test(c.test)"})))); // c.test isn't in the FPS, so SameParty is ignored, so we get SameSite=None // cookies. EXPECT_THAT(GetCookiesViaCookieStore(GetDescendantFrame({0})), net::CookieStringIs(testing::UnorderedElementsAre( testing::Key(kSamePartySameSiteNoneCookieName), testing::Key(kSameSiteNoneCookieName)))); ASSERT_EQ(4U, content::DeleteCookies(browser()->profile(), network::mojom::CookieDeletionFilter())); SetSamePartyCookies("b.test"); ASSERT_TRUE(NavigateToURL( contents(), https_server().GetURL("a.test", base::StrCat({"/cross_site_iframe_factory.html?", "a.test(c.test(b.test))"})))); // SameParty is not ignored, so we get the SameSite=None cookie. EXPECT_THAT(GetCookiesViaCookieStore(GetDescendantFrame({0, 0})), net::CookieStringIs(testing::UnorderedElementsAre( testing::Key(kSameSiteNoneCookieName)))); } } // namespace
40.551282
80
0.680841
[ "vector" ]
2d90bf7b72e5aa97f5663dcdc3c041bd0ec41735
12,803
hpp
C++
include/staticlib/pion/tcp_connection.hpp
staticlibs/staticlib_pion
ce3633f7c2c0838b0fffea8d2edc65329986024c
[ "Apache-2.0" ]
9
2017-10-18T13:46:29.000Z
2020-03-20T05:31:27.000Z
include/staticlib/pion/tcp_connection.hpp
staticlibs/staticlib_pion
ce3633f7c2c0838b0fffea8d2edc65329986024c
[ "Apache-2.0" ]
1
2017-03-05T01:55:35.000Z
2017-03-05T01:55:35.000Z
include/staticlib/pion/tcp_connection.hpp
staticlibs/staticlib_httpserver
ce3633f7c2c0838b0fffea8d2edc65329986024c
[ "Apache-2.0" ]
2
2016-05-09T08:49:53.000Z
2017-03-04T23:12:01.000Z
/* * Copyright 2015, alex at staticlibs.net * * 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. */ // --------------------------------------------------------------------- // pion: a Boost C++ framework for building lightweight HTTP interfaces // --------------------------------------------------------------------- // Copyright (C) 2007-2014 Splunk Inc. (https://github.com/splunk/pion) // // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt // #ifndef STATICLIB_PION_TCP_CONNECTION_HPP #define STATICLIB_PION_TCP_CONNECTION_HPP #include <array> #include <functional> #include <memory> #include <string> #include "asio.hpp" #include "asio/ssl.hpp" #include "staticlib/config.hpp" #include "staticlib/pion/algorithm.hpp" namespace staticlib { namespace pion { /** * Represents a single tcp connection */ class tcp_connection : public std::enable_shared_from_this<tcp_connection> { public: /** * Data type for the connection's current_lifecycle state */ enum class lifecycle { close, keepalive, pipelined }; /** * Data type for a function that handles TCP connection objects */ using connection_handler = std::function<void(std::shared_ptr<tcp_connection>&)>; /** * Data type for an I/O read buffer */ using read_buffer_type = std::array<char, 8192>; /** * Data type for a socket connection */ using socket_type = asio::ip::tcp::socket; /** * Data type for an SSL socket connection */ using ssl_socket_type = asio::ssl::stream<asio::ip::tcp::socket>; /** * Data type for SSL configuration context */ using ssl_context_type = asio::ssl::context; private: /** * SSL connection socket */ ssl_socket_type ssl_socket; /** * True if the connection is encrypted using SSL */ bool ssl_flag; /** * Buffer used for reading data from the TCP connection */ read_buffer_type read_buffer; /** * Saved read position bookmark */ std::pair<const char*, const char*> read_position; /** * Lifecycle state for the connection */ lifecycle current_lifecycle; /** * Function called when a server has finished handling the connection */ connection_handler finished_handler; /** * Strand used to synchronize all async operations over this connection */ asio::io_service::strand strand; /** * Timer that can be used with IO operations over this connection */ asio::steady_timer timer; public: /** * Constructor to be used with `std::make_shared` * * @param io_service asio service associated with the connection * @param ssl_context asio ssl context associated with the connection * @param ssl_flag if true then the connection will be encrypted using SSL * @param finished_handler function called when a server has finished * handling the connection */ tcp_connection(asio::io_service& io_service, ssl_context_type& ssl_context, const bool ssl_flag_in, connection_handler finished_handler_in) : ssl_socket(io_service, ssl_context), ssl_flag(ssl_flag_in), current_lifecycle(lifecycle::close), finished_handler(finished_handler_in), strand(io_service), timer(io_service) { save_read_pos(nullptr, nullptr); } /** * Deleted copy constructor */ tcp_connection(const tcp_connection&) = delete; /** * Deleted copy assignment operator */ tcp_connection& operator=(const tcp_connection&) = delete; /** * Virtual destructor */ virtual ~tcp_connection() { close(); } /** * Returns true if the connection is currently open * * @return true if the connection is currently open */ bool is_open() const { return const_cast<ssl_socket_type&> (ssl_socket).lowest_layer().is_open(); } /** * Closes the tcp socket and cancels any pending asynchronous operations */ void close() { if (is_open()) { try { // shutting down SSL will wait forever for a response from the remote end, // which causes it to hang indefinitely if the other end died unexpectedly // if (get_ssl_flag()) ssl_socket.shutdown(); // windows seems to require this otherwise it doesn't // recognize that connections have been closed ssl_socket.next_layer().shutdown(asio::ip::tcp::socket::shutdown_both); } catch (...) { } // ignore exceptions // close the underlying socket (ignore errors) std::error_code ec; ssl_socket.next_layer().close(ec); } } /** * Cancels any asynchronous operations pending on the socket. */ void cancel() { // there is no good way to do this on windows until vista or later (0x0600) // http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/basic_stream_socket/cancel/overload2.html // note that the asio docs are misleading because close() is not thread-safe, // and the suggested #define statements cause WAY too much trouble and heartache #if !defined(_MSC_VER) || (_WIN32_WINNT >= 0x0600) std::error_code ec; ssl_socket.next_layer().cancel(ec); #endif // !WINXP } /** * Cancels timer */ void cancel_timer() { #if !defined(_MSC_VER) || (_WIN32_WINNT >= 0x0600) std::error_code ec; timer.cancel(ec); #endif // !WINXP } /** * Asynchronously accepts a new tcp connection * * @param tcp_acceptor object used to accept new connections * @param handler called after a new connection has been accepted * * @see asio::basic_socket_acceptor::async_accept() */ template <typename AcceptHandler> void async_accept(asio::ip::tcp::acceptor& tcp_acceptor, AcceptHandler handler) { tcp_acceptor.async_accept(ssl_socket.lowest_layer(), handler); } /** * Asynchronously performs server-side SSL handshake for a new connection * * @param handler called after the ssl handshake has completed * * @see asio::ssl::stream::async_handshake() */ template <typename SSLHandshakeHandler> void async_handshake_server(SSLHandshakeHandler handler) { ssl_socket.async_handshake(asio::ssl::stream_base::server, handler); ssl_flag = true; } /** * Asynchronously reads some data into the connection's read buffer * * @param handler called after the read operation has completed * * @see asio::basic_stream_socket::async_read_some() */ template <typename ReadHandler> void async_read_some(ReadHandler handler) { if (get_ssl_flag()) { ssl_socket.async_read_some(asio::buffer(read_buffer), handler); } else { ssl_socket.next_layer().async_read_some(asio::buffer(read_buffer), handler); } } /** * Asynchronously writes data to the connection * * @param buffers one or more buffers containing the data to be written * @param handler called after the data has been written * * @see asio::async_write() */ template <typename ConstBufferSequence, typename write_handler_t> void async_write(const ConstBufferSequence& buffers, write_handler_t handler) { if (get_ssl_flag()) { asio::async_write(ssl_socket, buffers, handler); } else { asio::async_write(ssl_socket.next_layer(), buffers, handler); } } /** * This function should be called when a server has finished handling the connection */ void finish() { auto conn = shared_from_this(); if (finished_handler) { finished_handler(conn); } } /** * Returns true if the connection is encrypted using SSL * * @return true if the connection is encrypted using SSL */ bool get_ssl_flag() const { return ssl_flag; } /** * Sets the lifecycle for the connection * * @param lcycle lifecycle type name */ void set_lifecycle(lifecycle lcycle) { current_lifecycle = lcycle; } /** * Returns true if the connection should be kept alive * * @return */ bool get_keep_alive() const { return current_lifecycle != lifecycle::close; } /** * Returns true if the HTTP requests are pipelined * * @return true if the HTTP requests are pipelined */ bool is_pipelined() const { return current_lifecycle == lifecycle::pipelined; } /** * Returns the buffer used for reading data from the TCP connection * * @return buffer used for reading data from the TCP connection */ read_buffer_type& get_read_buffer() { return read_buffer; } /** * Saves a read position bookmark * * @param read_ptr points to the next character to be consumed in the read_buffer * @param read_end_ptr points to the end of the read_buffer (last byte + 1) */ void save_read_pos(const char *read_ptr, const char *read_end_ptr) { read_position.first = read_ptr; read_position.second = read_end_ptr; } /** * Loads a read position bookmark * * @param read_ptr points to the next character to be consumed in the read_buffer * @param read_end_ptr points to the end of the read_buffer (last byte + 1) */ void load_read_pos(const char *&read_ptr, const char *&read_end_ptr) const { read_ptr = read_position.first; read_end_ptr = read_position.second; } /** * Returns an ASIO endpoint for the client connection * * @return endpoint */ asio::ip::tcp::endpoint get_remote_endpoint() const { asio::ip::tcp::endpoint remote_endpoint; try { // const_cast is required since lowest_layer() is only defined non-const in asio remote_endpoint = const_cast<ssl_socket_type&> (ssl_socket).lowest_layer().remote_endpoint(); } catch (asio::system_error& /* e */) { // do nothing } return remote_endpoint; } /** * Returns the client's IP address * * @return client's IP address */ asio::ip::address get_remote_ip() const { return get_remote_endpoint().address(); } /** * Returns the client's port number * * @return client's port number */ unsigned short get_remote_port() const { return get_remote_endpoint().port(); } /** * Returns reference to the io_service used for async operations * * @return io_service used for async operations */ asio::io_service& get_io_service() { #if ASIO_VERSION >= 101400 return static_cast<asio::io_service&>(ssl_socket.lowest_layer().get_executor().context()); #else return ssl_socket.lowest_layer().get_io_service(); #endif } /** * Returns non-const reference to underlying TCP socket object * * @return underlying TCP socket object */ socket_type& get_socket() { return ssl_socket.next_layer(); } /** * Returns non-const reference to underlying SSL socket object * * @return underlying SSL socket object */ ssl_socket_type& get_ssl_socket() { return ssl_socket; } /** * Returns the strand that can be used with this connection * * @return the strand that can be used with this connection */ asio::io_service::strand& get_strand() { return strand; } /** * Returns the timer that can be used with this connection * * @return the timer that can be used with this connection */ asio::steady_timer& get_timer() { return timer; } }; /** * Data type for a connection pointer */ using tcp_connection_ptr = std::shared_ptr<tcp_connection>; } // namespace } #endif // STATICLIB_PION_TCP_CONNECTION_HPP
28.388027
119
0.627119
[ "object" ]
2d90f38c7fc2bb21487110f10aa1241f92d188f3
21,824
cpp
C++
accera/ir/src/value/ValueDialect.cpp
microsoft/Accera
4ec583857853cfb318634aef9e671f73cedba662
[ "MIT" ]
19
2022-01-26T18:12:54.000Z
2022-03-25T10:37:21.000Z
accera/ir/src/value/ValueDialect.cpp
microsoft/Accera
4ec583857853cfb318634aef9e671f73cedba662
[ "MIT" ]
4
2022-01-28T00:31:48.000Z
2022-02-25T14:28:32.000Z
accera/ir/src/value/ValueDialect.cpp
microsoft/Accera
4ec583857853cfb318634aef9e671f73cedba662
[ "MIT" ]
2
2022-01-26T14:14:45.000Z
2022-02-01T06:08:17.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // Authors: Kern Handa //////////////////////////////////////////////////////////////////////////////////////////////////// #include "value/ValueDialect.h" #include "value/ValueAttributes.h" #include "value/ValueDialect.cpp.inc" #include "value/ValueEnums.h" #include "value/ValueFuncOp.h" #include "IRUtil.h" #include <mlir/Dialect/GPU/GPUDialect.h> #include <mlir/Dialect/StandardOps/IR/Ops.h> #include <mlir/IR/AffineMap.h> #include <mlir/IR/Builders.h> #include <mlir/IR/FunctionImplementation.h> #include <mlir/Interfaces/CallInterfaces.h> #include <llvm/ADT/BitVector.h> #include <llvm/ADT/StringSwitch.h> #include <llvm/ADT/TypeSwitch.h> #include "value/ValueAttrs.cpp.inc" #include "value/ValueOpsEnums.cpp.inc" #include <numeric> namespace accera::ir::value { void ValueDialect::initialize() { addOperations< accera::ir::value::ValueFuncOp, #define GET_OP_LIST #include "value/ValueOps.cpp.inc" >(); } } // namespace accera::ir::value using namespace llvm; using namespace mlir; using namespace accera::ir::value; //===----------------------------------------------------------------------===// // General helpers for comparison ops //===----------------------------------------------------------------------===// static void buildCmpOp(OpBuilder& build, OperationState& result, CmpOpPredicate predicate, Value lhs, Value rhs) { result.addOperands({ lhs, rhs }); auto boolType = build.getI1Type(); if (auto vectorType = lhs.getType().dyn_cast<VectorType>()) { auto shape = vectorType.getShape(); auto resultType = mlir::VectorType::get(shape, boolType); result.types.push_back(resultType); } else { result.types.push_back(boolType); } result.addAttribute( CmpOp::getPredicateAttrName(), build.getI64IntegerAttr(static_cast<int64_t>(predicate))); } static void buildBinOp(OpBuilder& build, OperationState& result, BinaryOpPredicate predicate, Value lhs, Value rhs) { result.addOperands({ lhs, rhs }); result.types.push_back(lhs.getType()); result.addAttribute( BinOp::getPredicateAttrName(), build.getI64IntegerAttr(static_cast<int64_t>(predicate))); } static void buildUnaryOp(OpBuilder& build, OperationState& result, UnaryOpPredicate predicate, Value input) { result.addOperands({ input }); result.types.push_back(input.getType().cast<ShapedType>().getElementType()); result.addAttribute( UnaryOp::getPredicateAttrName(), build.getI64IntegerAttr(static_cast<int64_t>(predicate))); } void ValueFuncOp::build(OpBuilder& builder, OperationState& result, StringRef name, FunctionType type, ExecutionTarget target) { result.addAttribute(mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)); result.addAttribute(getTypeAttrName(), TypeAttr::get(type)); result.addAttribute(getExecTargetAttrName(), ExecutionTargetAttr::get(builder.getContext(), target)); Region* body = result.addRegion(); Block* entryBlock = new Block; entryBlock->addArguments(type.getInputs()); body->getBlocks().push_back(entryBlock); } void ValueFuncOp::build(OpBuilder& builder, OperationState& result, StringRef name, FunctionType type, ExecutionTarget target, ValueFuncOp::ExternalFuncTag) { build(builder, result, name, type, target); result.addAttribute("external", builder.getUnitAttr()); OpBuilder::InsertionGuard guard{ builder }; builder.setInsertionPointToEnd(&result.regions[0]->front()); builder.create<ir::value::ReturnOp>(result.location); } /// Hook for FunctionLike verifier. LogicalResult ValueFuncOp::verifyType() { Type type = getTypeAttr().getValue(); if (!type.isa<FunctionType>()) { return emitOpError("requires '" + getTypeAttrName() + "' attribute of function type"); } return success(); } // CallableOpInterface Region* ValueFuncOp::getCallableRegion() { return isExternal() ? nullptr : &getBody(); } // CallableOpInterface ArrayRef<Type> ValueFuncOp::getCallableResults() { return getType().getResults(); } ParseResult ValueFuncOp::parse(OpAsmParser& parser, OperationState& result) { auto buildFuncType = [](Builder& builder, ArrayRef<Type> argTypes, ArrayRef<Type> results, function_like_impl::VariadicFlag, std::string&) { return builder.getFunctionType(argTypes, results); }; return function_like_impl::parseFunctionLikeOp(parser, result, /*allowVariadic=*/false, buildFuncType); } void ValueFuncOp::print(OpAsmPrinter& p) { FunctionType fnType = getType(); function_like_impl::printFunctionLikeOp(p, *this, fnType.getInputs(), /*isVariadic=*/false, fnType.getResults()); } LogicalResult ValueFuncOp::verify() { // If this function is external there is nothing to do. if (isExternal()) return success(); // Verify that the argument list of the function and the arg list of the entry // block line up. The trait already verified that the number of arguments is // the same between the signature and the block. auto fnInputTypes = getType().getInputs(); Block& entryBlock = front(); for (unsigned i = 0, e = entryBlock.getNumArguments(); i != e; ++i) if (fnInputTypes[i] != entryBlock.getArgument(i).getType()) return emitOpError("type of entry block argument #") << i << '(' << entryBlock.getArgument(i).getType() << ") must match the type of the corresponding argument in " << "function signature(" << fnInputTypes[i] << ')'; return success(); } // cf: mlir/lib/IR/Function.cpp void ValueFuncOp::eraseArguments(ArrayRef<unsigned> argIndices) { auto oldType = getType(); int originalNumArgs = oldType.getNumInputs(); llvm::BitVector eraseIndices(originalNumArgs); for (auto index : argIndices) { eraseIndices.set(index); } auto shouldEraseArg = [&](int i) { return eraseIndices.test(i); }; // There are 3 things that need to be updated: // - Function type. // - Arg attrs. // - Block arguments of entry block. // Update the function type and arg attrs. SmallVector<Type, 4> newInputTypes; SmallVector<DictionaryAttr, 4> newArgAttrs; for (int i = 0; i < originalNumArgs; i++) { if (shouldEraseArg(i)) { continue; } newInputTypes.emplace_back(oldType.getInput(i)); newArgAttrs.emplace_back(getArgAttrDict(i)); } setType(FunctionType::get(getContext(), newInputTypes, oldType.getResults())); setAllArgAttrs(newArgAttrs); // Update the entry block's arguments. // We do this in reverse so that we erase later indices before earlier // indices, to avoid shifting the later indices. Block& entry = front(); for (int i = 0; i < originalNumArgs; i++) { if (shouldEraseArg(originalNumArgs - i - 1)) { entry.eraseArgument(originalNumArgs - i - 1); } } } void ValueLambdaOp::build(OpBuilder& builder, OperationState& result, StringRef name, FunctionType type, ExecutionTarget target) { result.addAttribute(mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)); result.addAttribute(getTypeAttrName(), TypeAttr::get(type)); result.addAttribute(getExecTargetAttrName(), ExecutionTargetAttr::get(builder.getContext(), target)); Region* body = result.addRegion(); Block* entryBlock = new Block; entryBlock->addArguments(type.getInputs()); body->getBlocks().push_back(entryBlock); } /// Hook for FunctionLike verifier. LogicalResult ValueLambdaOp::verifyType() { Type type = getTypeAttr().getValue(); if (!type.isa<FunctionType>()) { return emitOpError("requires '" + getTypeAttrName() + "' attribute of function type"); } return success(); } // CallableOpInterface Region* ValueLambdaOp::getCallableRegion() { return &body(); } // CallableOpInterface ArrayRef<Type> ValueLambdaOp::getCallableResults() { return getType().getResults(); } void ValueModuleOp::build(OpBuilder& builder, OperationState& result, StringRef name) { Region* r = result.addRegion(); ensureTerminator(*r, builder, result.location); result.attributes.push_back(builder.getNamedAttr(::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name))); } void GlobalOp::build( OpBuilder& builder, OperationState& result, MemRefType type, bool isConstant, StringRef name, Attribute value, unsigned addrSpace, bool isExternal) { result.addAttribute(SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)); result.addAttribute("type", TypeAttr::get(type)); if (isConstant) result.addAttribute("constant", builder.getUnitAttr()); if (isExternal) result.addAttribute("external", builder.getUnitAttr()); if (value) result.addAttribute("value", value); if (addrSpace != 0) result.addAttribute("addr_space", builder.getI32IntegerAttr(addrSpace)); } static bool satisfiesModule(Operation* op) { return op->hasTrait<OpTrait::SymbolTable>() && op->hasTrait<OpTrait::IsIsolatedFromAbove>(); } GlobalOp ReferenceGlobalOp::getGlobal() { Operation* module = (*this)->getParentOp(); while (module && !satisfiesModule(module)) module = module->getParentOp(); assert(module && "unexpected operation outside of a module"); return dyn_cast_or_null<GlobalOp>( mlir::SymbolTable::lookupSymbolIn(module, global_name())); } FunctionType accera::ir::value::CallOp::getCalleeType() { SmallVector<Type, 8> argTypes(getOperandTypes()); return FunctionType::get(getContext(), argTypes, getResultTypes()); } OpFoldResult GetElementOp::fold(ArrayRef<Attribute> operands) { if (getOperand().getType() == getType()) return getOperand(); return {}; } void ReorderOp::build(OpBuilder& builder, OperationState& result, Value source, ArrayAttr orderAttr) { auto context = builder.getContext(); // Compute the result memref type // Assume (for now) that source hasn't been permuted auto sourceType = source.getType().cast<MemRefType>(); auto originalSizes = sourceType.getShape(); // Compute permuted sizes and affine map permutation std::vector<int64_t> dimOrder = util::ConvertArrayAttrToIntVector(orderAttr); std::vector<int64_t> permutedSizes(dimOrder.size()); std::vector<unsigned> affineMapOrder(dimOrder.size()); for (auto en : llvm::enumerate(dimOrder)) { permutedSizes[en.index()] = originalSizes[en.value()]; affineMapOrder[en.value()] = en.index(); } auto permutationMap = AffineMap::getPermutationMap(affineMapOrder, context); assert(permutationMap); // Compute permuted strides. int64_t offset; SmallVector<int64_t, 4> strides; [[maybe_unused]] auto res = getStridesAndOffset(sourceType, strides, offset); assert(succeeded(res)); auto map = makeStridedLinearLayoutMap(strides, offset, context); map = map.compose(permutationMap); // Compute result type. MemRefType resultType = MemRefType::Builder(sourceType).setShape(permutedSizes).setAffineMaps(map); build(builder, result, resultType, source, orderAttr); } void ReduceOp::build(OpBuilder& builder, OperationState& result, Value input, Value initArg, BodyBuilderFn bodyBuilder) { [[maybe_unused]] auto elementType = input.getType().cast<ShapedType>().getElementType(); result.addOperands(input); result.addOperands(initArg); result.addTypes(initArg.getType()); Region* bodyRegion = result.addRegion(); bodyRegion->push_back(new Block); Block& bodyBlock = bodyRegion->front(); bodyBlock.addArgument(initArg.getType()); bodyBlock.addArgument(initArg.getType()); OpBuilder::InsertionGuard guard(builder); builder.setInsertionPointToStart(&bodyBlock); if (bodyBuilder) bodyBuilder(builder, result.location, bodyBlock.getArgument(0), bodyBlock.getArgument(1)); } void MapReduceOp::build(OpBuilder& builder, OperationState& result, Value input, Value initArg, MapBodyBuilderFn mapBodyBuilder, ReduceBodyBuilderFn reduceBodyBuilder) { [[maybe_unused]] auto elementType = input.getType().cast<ShapedType>().getElementType(); result.addOperands(input); result.addOperands(initArg); result.addTypes(initArg.getType()); // Map body Region* mapBodyRegion = result.addRegion(); mapBodyRegion->push_back(new Block); Block& mapBodyBlock = mapBodyRegion->front(); mapBodyBlock.addArgument(initArg.getType()); { OpBuilder::InsertionGuard guard(builder); builder.setInsertionPointToStart(&mapBodyBlock); if (mapBodyBuilder) mapBodyBuilder(builder, result.location, mapBodyBlock.getArgument(0)); } // Reduce body Region* reduceBodyRegion = result.addRegion(); reduceBodyRegion->push_back(new Block); Block& reduceBodyBlock = reduceBodyRegion->front(); reduceBodyBlock.addArgument(initArg.getType()); reduceBodyBlock.addArgument(initArg.getType()); { OpBuilder::InsertionGuard guard(builder); builder.setInsertionPointToStart(&reduceBodyBlock); if (reduceBodyBuilder) reduceBodyBuilder(builder, result.location, reduceBodyBlock.getArgument(0), reduceBodyBlock.getArgument(1)); } } MMAOp::MMAOp(MMAShape shape_) : shape{ shape_ } { switch (shape) { case MMAShape::M64xN64xK1_B4: m = 64; n = 64; k = 1; blocks = 4; break; case MMAShape::M64xN64xK1_B2: m = 64; n = 64; k = 1; blocks = 2; break; case MMAShape::M64xN64xK4_B4: m = 64; n = 64; k = 4; blocks = 4; break; case MMAShape::M64xN64xK4_B2: m = 64; n = 64; k = 4; blocks = 2; break; case MMAShape::M32xN32xK2_B1: m = 32; n = 32; k = 2; blocks = 1; break; case MMAShape::M32xN32xK8_B1: m = 32; n = 32; k = 8; blocks = 1; break; case MMAShape::M16xN16xK4_B1: m = 16; n = 16; k = 4; blocks = 1; break; case MMAShape::M16xN16xK16_B1: m = 16; n = 16; k = 16; blocks = 1; break; default: assert(false && "Invalid MMA shape."); break; } } MMAShape MMAOp::getShapeType() const { return shape; } int64_t MMAOp::getInElementsPerThread(const int64_t warpSize) const { return m * k / warpSize; } int64_t MMAOp::getOutElementsPerThread(const int64_t warpSize) const { return getM() * getN() / warpSize; } int64_t MMAOp::getNumBlocks() const { return blocks; } int64_t MMAOp::getTileFactor() const { if (getNumBlocks() == 2) return 4; if (getNumBlocks() == 4) return 2; return 1; } std::pair<int, int> MMAOp::getTileShape(const int warpSizeX, const int warpSizeY) const { return { m / warpSizeX, n / warpSizeY }; } std::vector<uint8_t> MMAOp::getOffsetMap() const { // These index offsets are calculated based on the data layout in which // AMD mfma operation maps them to different threads. if (getNumBlocks() == 2 || m == 32) // M64xN64xK1_B2, M64xN64xK4_B2, M32xN32xK2_B1, M32xN32xK8_B1 return { 0, 4, 1, 5, 2, 6, 3, 7, 8, 12, 9, 13, 10, 14, 11, 15, 16, 20, 17, 21, 18, 22, 19, 23, 24, 28, 25, 29, 26, 30, 27, 31 }; return { 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15 }; // M64xN64xK1_B4, M64xN64xK4_B4, M16xN16xK4_B1, M16xN16xK16_B1 } std::array<int64_t, 2> MMAOp::getOffsetMapSize() const { // The offset map is organised in this layout so that it can be indexed by thread id. if (getNumBlocks() == 2 || m == 32) // M64xN64xK1_B2, M64xN64xK4_B2, M32xN32xK2_B1, M32xN32xK8_B1 return { 16, 2 }; return { 4, 4 }; // M64xN64xK1_B4, M64xN64xK4_B4, M16xN16xK4_B1, M16xN16xK16_B1 } std::pair<mlir::MemRefType, mlir::RankedTensorType> MMAOp::GetMFMAThreadOffsetMapType(IntegerType mlirElemType) const { auto vecSize = getOffsetMapSize(); return std::make_pair(mlir::MemRefType::get(vecSize, mlirElemType, {}, mlir::gpu::GPUDialect::getPrivateAddressSpace()), mlir::RankedTensorType::get(vecSize, mlirElemType)); } std::pair<mlir::Value, mlir::Value> MMAOp::GetThreadBlockOffsets(mlir::Operation* op, mlir::OpBuilder& builder, mlir::Location& loc) const { const auto [warpSizeX, warpSizeY] = util::ResolveWarpSize(util::ResolveExecutionRuntime(op).value()).value(); auto warpSize = builder.create<mlir::ConstantIndexOp>(loc, warpSizeX * warpSizeY); auto leadingDim = builder.create<mlir::ConstantIndexOp>(loc, getM()); auto tileFactor = builder.create<mlir::ConstantIndexOp>(loc, getTileFactor()); auto tidX = util::GetGPUIndex(op, value::Processor::ThreadX, builder, loc); auto tidY = util::GetGPUIndex(op, value::Processor::ThreadY, builder, loc); auto bidX = util::GetGPUIndex(op, value::Processor::BlockX, builder, loc); auto bidY = util::GetGPUIndex(op, value::Processor::BlockY, builder, loc); auto bdimX = util::GetGPUIndex(op, value::Processor::BlockDimX, builder, loc); auto bdimY = util::GetGPUIndex(op, value::Processor::BlockDimY, builder, loc); // We reshape the physical block dimensions to compute the correct offsets. // Multiplying blockDim.x and dividing blockDim.y by tile factor to keep the size same. auto reshapedBlockDimX = builder.create<mlir::MulIOp>(loc, bdimX, tileFactor); auto reshapedBlockDimY = builder.create<mlir::UnsignedDivIOp>(loc, bdimY, tileFactor); auto blockTid = builder.create<mlir::AddIOp>(loc, tidX, builder.create<mlir::MulIOp>(loc, tidY, bdimX)); auto warpId = builder.create<mlir::UnsignedDivIOp>(loc, blockTid, warpSize); auto warpsX = builder.create<mlir::UnsignedDivIOp>(loc, reshapedBlockDimX, builder.create<mlir::ConstantIndexOp>(loc, warpSizeX)); auto warpsY = builder.create<mlir::UnsignedDivIOp>(loc, reshapedBlockDimY, builder.create<mlir::ConstantIndexOp>(loc, warpSizeY)); auto warpIdX = builder.create<mlir::UnsignedRemIOp>(loc, warpId, warpsX); auto warpIdY = builder.create<mlir::UnsignedDivIOp>(loc, warpId, warpsX); auto singleBlockOffsetCol = builder.create<mlir::MulIOp>(loc, warpsX, leadingDim); auto singleBlockOffsetRow = builder.create<mlir::MulIOp>(loc, warpsY, leadingDim); auto rowOffset = builder.create<mlir::AddIOp>(loc, builder.create<mlir::MulIOp>(loc, warpIdY, leadingDim), builder.create<mlir::MulIOp>(loc, bidY, singleBlockOffsetRow)); auto colOffset = builder.create<mlir::AddIOp>(loc, builder.create<mlir::MulIOp>(loc, warpIdX, leadingDim), builder.create<mlir::MulIOp>(loc, bidX, singleBlockOffsetCol)); return std::make_pair(rowOffset, colOffset); } //===----------------------------------------------------------------------===// // MFMA Ops //===----------------------------------------------------------------------===// static const auto kGenericMemorySpace = 0; static const auto kGlobalMemorySpace = 1; static const auto kSharedMemorySpace = mlir::gpu::GPUDialect::getWorkgroupAddressSpace(); static LogicalResult verify(MMAComputeSyncOp op) { auto opAType = op.opA().getType().cast<MemRefType>().getElementType(); auto opBType = op.opB().getType().cast<MemRefType>().getElementType(); auto opCType = op.opC().getType().cast<MemRefType>().getElementType(); if (!(opAType.isF32() && opBType.isF32() && opCType.isF32()) || (opAType.isF16() && opBType.isF16() && opCType.isF32())) return op.emitError("Invalid data types for arguments."); return success(); } static LogicalResult verify(MMAFillSyncOp op) { auto value = op.value(); auto valueType = value.getType(); if (valueType != op.result().getType().cast<MemRefType>().getElementType()) return op.emitError("value type must match matrix element type"); return success(); } static LogicalResult verify(MMALoadSyncOp op) { auto srcType = op.getMemRefType(); MMAOperandType operand{ op.operandType() }; auto srcMemSpace = srcType.getMemorySpaceAsInt(); if (srcMemSpace != kGenericMemorySpace && srcMemSpace != kSharedMemorySpace && srcMemSpace != kGlobalMemorySpace) return op.emitError( "source memorySpace kGenericMemorySpace, kSharedMemorySpace or " "kGlobalMemorySpace only allowed"); if (operand != MMAOperandType::A && operand != MMAOperandType::B && operand != MMAOperandType::Acc) return op.emitError("only AOp, BOp and COp can be loaded"); return success(); } static LogicalResult verify(MMAStoreSyncOp op) { auto dstMemrefType = op.getMemRefType(); auto dstMemSpace = dstMemrefType.getMemorySpaceAsInt(); if (dstMemSpace != kGenericMemorySpace && dstMemSpace != kSharedMemorySpace && dstMemSpace != kGlobalMemorySpace) return op.emitError( "destination memorySpace of kGenericMemorySpace, " "kGlobalMemorySpace or kSharedMemorySpace only allowed"); return success(); } // TableGen'd op method definitions #define GET_OP_CLASSES #include "value/ValueOps.cpp.inc"
34.974359
177
0.662757
[ "shape", "vector" ]
2d9d95e8c385cf99582bead0f6612cdf49543801
1,741
cpp
C++
RenderCore/UniformsStream.cpp
pocketgems/XLE2
82771e9ab1fc3b12927f1687bbe05d4f7dce8765
[ "MIT" ]
3
2018-05-17T08:39:39.000Z
2020-12-09T13:20:26.000Z
RenderCore/UniformsStream.cpp
pocketgems/XLE2
82771e9ab1fc3b12927f1687bbe05d4f7dce8765
[ "MIT" ]
null
null
null
RenderCore/UniformsStream.cpp
pocketgems/XLE2
82771e9ab1fc3b12927f1687bbe05d4f7dce8765
[ "MIT" ]
1
2021-11-14T08:50:15.000Z
2021-11-14T08:50:15.000Z
// Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "UniformsStream.h" #include "Types.h" #include "Format.h" #include "../Utility/MemoryUtils.h" #include "../Core/SelectConfiguration.h" namespace RenderCore { void UniformsStreamInterface::BindConstantBuffer(unsigned slot, const CBBinding& binding) { if (_cbBindings.size() <= slot) _cbBindings.resize(slot+1); _cbBindings[slot] = RetainedCBBinding { binding._hashName, std::vector<ConstantBufferElementDesc>(binding._elements.begin(), binding._elements.end()) }; _hash = 0; } void UniformsStreamInterface::BindShaderResource(unsigned slot, uint64_t hashName) { if (_srvBindings.size() <= slot) _srvBindings.resize(slot+1); _srvBindings[slot] = hashName; _hash = 0; } uint64_t UniformsStreamInterface::GetHash() const { if (expect_evaluation(_hash==0, false)) { _hash = DefaultSeed64; // to prevent some oddities when the same hash value could be in either a CB or SRV // we need to include the count of the first array we look through in the hash _hash = HashCombine((uint64_t)_cbBindings.size(), _hash); for (const auto& c:_cbBindings) _hash = HashCombine(c._hashName, _hash); _hash = HashCombine(Hash64(AsPointer(_srvBindings.begin()), AsPointer(_srvBindings.end())), _hash); } return _hash; } UniformsStreamInterface::UniformsStreamInterface() : _hash(0) {} UniformsStreamInterface::~UniformsStreamInterface() {} }
32.240741
111
0.649052
[ "vector" ]
2d9dd8431244dcd96fc0e91b4d2272d2737058a7
41,891
cpp
C++
Source/Libraries/TTF/TTFFont.cpp
nathanlink169/3D-Shaders-Test
2493fb71664d75100fbb4a80ac70f657a189593d
[ "MIT" ]
null
null
null
Source/Libraries/TTF/TTFFont.cpp
nathanlink169/3D-Shaders-Test
2493fb71664d75100fbb4a80ac70f657a189593d
[ "MIT" ]
null
null
null
Source/Libraries/TTF/TTFFont.cpp
nathanlink169/3D-Shaders-Test
2493fb71664d75100fbb4a80ac70f657a189593d
[ "MIT" ]
null
null
null
#include "CommonHeader.h" // ************************************************************************************* // TTFFont.cpp // // True type (*.ttf) and OpenType (*.otf) font loading/rendering implementation. // // Ryan Bogean // April 2012 // January 2014 // // ************************************************************************************* # include <vector> # include <map> # include <fstream> # include <algorithm> # include <limits> # include <utility> # include <cmath> # include <sstream> # include <iterator> # include "TTFExceptions.h" # include "TTFMath.h" # include "TTFTypes.h" # include "TTFFont.h" using namespace TTFCore; // --------------------------------------------------------------------------------------------------------------------------- // Font internal types // --------------------------------------------------------------------------------------------------------------------------- // ----- TableEntry ----- TableEntry::TableEntry() { tag = 0; tagstr[0] = 0; check_sum = 0; begin = nullptr; end = nullptr; } bool TableEntry::IsValid() const { return tag != 0; } // ----- CodePoint ----- CodePoint::CodePoint(uint32_t code_) : code(code_), platform(3), encoding(1), language(0) {} CodePoint::CodePoint(uint32_t code_, uint16_t platform_, uint16_t encoding_, uint16_t language_) : code(code_), platform(platform_), encoding(encoding_), language(language_) {} // --------------------------------------------------------------------------------------------------------------------------- // Font // --------------------------------------------------------------------------------------------------------------------------- // ----- constructor/destructor ----- Font::Font(std::string file_name) { // load font file std::fstream file(file_name, std::fstream::in | std::fstream::binary); file.seekg(0,std::ios::end); size_t length = static_cast<size_t>(file.tellg()); if (file.fail()) throw FileFailure(file_name); if (length == 0) throw FileLengthError(file_name); file.seekg(0,std::ios::beg); buffer_cache.resize(length,0); file.read(&*buffer_cache.begin(),length); if (file.fail()) throw FileFailure(file_name); // intialize variables buffer = &buffer_cache.front(); // parse font CreateTableMap(); VerifyTableCheckSums(); VerifyRequiredTables(); VerifyTrueTypeTables(); } Font::Font(const void* raw_data, MapFromData) { // intialize variables buffer = reinterpret_cast<const char*>(raw_data); // parse font CreateTableMap(); VerifyTableCheckSums(); VerifyRequiredTables(); VerifyTrueTypeTables(); } Font::Font(const void* raw_data, size_t length) { // sanity check if (length == 0) throw FileLengthError(); // 'load' font data buffer_cache.assign(reinterpret_cast<const char*>(raw_data),reinterpret_cast<const char*>(raw_data) + length); buffer = &buffer_cache.front(); // parse font CreateTableMap(); VerifyTableCheckSums(); VerifyRequiredTables(); VerifyTrueTypeTables(); } Font::Font(const Font& f) : buffer_cache(f.buffer_cache), buffer(buffer_cache.empty() ? f.buffer : buffer_cache.data()) { CreateTableMap(); // recreate the table map } Font::Font(Font&& f) : table_map(std::move(f.table_map)), buffer_cache(std::move(f.buffer_cache)), buffer(buffer_cache.empty() ? f.buffer : buffer_cache.data()) { } Font& Font::operator=(const Font& f) { if (this != &f) { buffer_cache = f.buffer_cache; buffer = buffer_cache.empty() ? f.buffer : buffer_cache.data(); CreateTableMap(); // recreate the table map } return *this; } Font& Font::operator=(Font&& f) { if (this != &f) { table_map = std::move(f.table_map); buffer_cache = std::move(f.buffer_cache); buffer = buffer_cache.empty() ? f.buffer : buffer_cache.data(); } return *this; } Font::~Font() {} // ----- read helpers ----- uint8_t Font::ReadBYTE(FItr& itr) const { uint8_t r = *reinterpret_cast<const uint8_t*>(itr); itr += 1; return r; } int8_t Font::ReadCHAR(FItr& itr) const { int8_t r = *reinterpret_cast<const int8_t*>(itr); itr += 1; return r; } uint16_t Font::ReadUSHORT(FItr& itr) const { uint16_t r = ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); return r; } int16_t Font::ReadSHORT(FItr& itr) const { int16_t r = 0; uint8_t i = ReadBYTE(itr); if (i & 128) r = -1; r <<= 8; r += i; r <<= 8; r += ReadBYTE(itr); return r; } uint32_t Font::ReadUINT24(FItr& itr) const { uint32_t r = ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); return r; } uint32_t Font::ReadULONG(FItr& itr) const { uint32_t r = ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); return r; } int32_t Font::ReadLONG(FItr& itr) const { int32_t r = 0; uint8_t i = ReadBYTE(itr); if (i & 128) r = -1; r <<= 8; r += i; r <<= 8; r += ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); return r; } int32_t Font::ReadFIXED32(FItr& itr) const { return ReadLONG(itr); } int64_t Font::ReadLONGDATETIME(FItr& itr) const { int64_t r = 0; uint8_t i = ReadBYTE(itr); if (i & 128) r = -1; r <<= 8; r += i; r <<= 8; r += ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); r <<= 8; r += ReadBYTE(itr); return r; } int32_t Font::ReadFIXED16(FItr& itr) const { return static_cast<int32_t>(ReadSHORT(itr) << 2); // convert from 2.14 to 16.16 } uint8_t Font::ReadBYTE(FItr&& itr) const { return *reinterpret_cast<const uint8_t*>(itr); } int8_t Font::ReadCHAR(FItr&& itr) const { return *reinterpret_cast<const int8_t*>(itr); } uint16_t Font::ReadUSHORT(FItr&& itr_) const { FItr itr = itr_; return ReadUSHORT(itr); } int16_t Font::ReadSHORT(FItr&& itr_) const { FItr itr = itr_; return ReadSHORT(itr); } uint32_t Font::ReadUINT24(FItr&& itr_) const { FItr itr = itr_; return ReadUINT24(itr); } uint32_t Font::ReadULONG(FItr&& itr_) const { FItr itr = itr_; return ReadULONG(itr); } int32_t Font::ReadLONG(FItr&& itr_) const { FItr itr = itr_; return ReadLONG(itr); } int32_t Font::ReadFIXED32(FItr&& itr_) const { FItr itr = itr_; return ReadLONG(itr); } int64_t Font::ReadLONGDATETIME(FItr&& itr_) const { FItr itr = itr_; return ReadLONGDATETIME(itr); } int32_t Font::ReadFIXED16(FItr&& itr_) const { FItr itr = itr_; return ReadSHORT(itr); } // ----- more read helpers ----- TTFHeader Font::ReadTTFHeader(FItr& itr) const { TTFHeader header; header.version = ReadFIXED32(itr); header.num_tables = ReadUSHORT(itr); header.search_range = ReadUSHORT(itr); header.entry_selector = ReadUSHORT(itr); header.range_shift = ReadUSHORT(itr); return header; } TableEntry Font::ReadTableEntry(FItr& itr) const { TableEntry te; te.tag = ReadULONG(itr); DecomposeTag(te.tag,te.tagstr); te.check_sum = ReadULONG(itr); te.begin = buffer + ReadULONG(itr); te.end = te.begin + ReadULONG(itr); return te; } HeadTable Font::ReadHeadTable() const { FItr itr = GetTableEntry(CreateTag('h','e','a','d')).begin; HeadTable ht; ht.table_version = ReadFIXED32(itr); ht.font_revision = ReadFIXED32(itr); ht.check_sum_adjustment = ReadULONG(itr); ht.magic_number = ReadULONG(itr); ht.flags = ReadUSHORT(itr); ht.units_per_em = ReadUSHORT(itr); ht.created_date = ReadLONGDATETIME(itr); ht.modified_date = ReadLONGDATETIME(itr); ht.xmin = ReadSHORT(itr); ht.ymin = ReadSHORT(itr); ht.xmax = ReadSHORT(itr); ht.ymax = ReadSHORT(itr); ht.mac_style = ReadUSHORT(itr); ht.lowest_rec_PPEM = ReadUSHORT(itr); ht.font_direction_hint = ReadSHORT(itr); ht.index_to_loc_format = ReadSHORT(itr); ht.glyph_data_format = ReadSHORT(itr); return ht; } GlyphProfile Font::ReadMAXPTable() const { FItr itr = GetTableEntry(CreateTag('m','a','x','p')).begin; GlyphProfile gp; gp.version = ReadULONG(itr); gp.num_glyphs = ReadUSHORT(itr); if (gp.version == 1) { gp.max_points = ReadUSHORT(itr); gp.max_contours = ReadUSHORT(itr); gp.max_composite_points = ReadUSHORT(itr); gp.max_composite_contours = ReadUSHORT(itr); gp.max_zones = ReadUSHORT(itr); gp.max_twilight_points = ReadUSHORT(itr); gp.max_storage = ReadUSHORT(itr); gp.max_function_defs = ReadUSHORT(itr); gp.max_instruction_defs = ReadUSHORT(itr); gp.max_stack_elements = ReadUSHORT(itr); gp.max_size_of_instructions = ReadUSHORT(itr); gp.max_component_elements = ReadUSHORT(itr); gp.max_component_depth = ReadUSHORT(itr); } return gp; } int16_t Font::GetIndexToLocFormat() const { FItr itr = GetTableEntry(CreateTag('h','e','a','d')).begin; return ReadSHORT(itr + 50); } uint16_t Font::GetNumGlyphs() const { FItr itr = GetTableEntry(CreateTag('m','a','x','p')).begin; return ReadUSHORT(itr + 4); } // ----- table helpers ----- uint32_t Font::CreateTag(char c0, char c1, char c2, char c3) const { uint32_t r; r = static_cast<uint32_t>(c0); r <<= 8; r |= static_cast<uint32_t>(c1); r <<= 8; r |= static_cast<uint32_t>(c2); r <<= 8; r |= static_cast<uint32_t>(c3); return r; } uint32_t Font::CreateTag(const char* s) const { uint32_t r; r = static_cast<uint32_t>(s[0]); r <<= 8; r |= static_cast<uint32_t>(s[1]); r <<= 8; r |= static_cast<uint32_t>(s[2]); r <<= 8; r |= static_cast<uint32_t>(s[3]); return r; } void Font::DecomposeTag(uint32_t tag, char* s) const { s[0] = static_cast<char>((tag >> 24) & 0xff); s[1] = static_cast<char>((tag >> 16) & 0xff); s[2] = static_cast<char>((tag >> 8) & 0xff); s[3] = static_cast<char>(tag & 0xff); s[4] = 0; } std::string Font::DecomposeTag(uint32_t tag) const { char str[5]; DecomposeTag(tag,str); return str; } TableEntry Font::GetTableEntry(uint32_t tag) const { auto i = table_map.find(tag); if (i == table_map.end()) throw TableDoesNotExist(DecomposeTag(tag)); return i->second; } bool Font::VerifyTableCheckSum(const TableEntry& te) const { if (te.tag == CreateTag('h','e','a','d')) return VerifyHeadCheckSum(te); else return VerifyNormalCheckSum(te); } bool Font::VerifyNormalCheckSum(const TableEntry& te) const { uint32_t check_sum = 0; FItr i = te.begin; while (i < te.end) check_sum += ReadULONG(i); return check_sum == te.check_sum; } bool Font::VerifyHeadCheckSum(const TableEntry& te) const { uint32_t check_sum = 0; FItr i = te.begin; check_sum += ReadULONG(i); check_sum += ReadULONG(i); i += 4; // check_sum_adjustment member of head table, must be skipped or set to 0 for correct checksum while (i < te.end) check_sum += ReadULONG(i); return check_sum == te.check_sum; } // ----- intial loading functions ----- void Font::CreateTableMap() { // intialize FItr itr = buffer; table_map.clear(); // read in table entries TTFHeader header = ReadTTFHeader(itr); for (uint16_t i = 0; i < header.num_tables; ++i) { TableEntry te = ReadTableEntry(itr); table_map[te.tag] = te; } } void Font::VerifyTableCheckSums() const { for (auto i = table_map.begin(); i != table_map.end(); ++i) { if (VerifyTableCheckSum(i->second) == false) throw ChecksumException(i->second.tagstr); } } void Font::VerifyRequiredTables() const { uint32_t required_tables[] = { CreateTag('c','m','a','p'), CreateTag('h','e','a','d'), CreateTag('h','h','e','a'), CreateTag('h','m','t','x'), CreateTag('m','a','x','p'), //CreateTag('n','a','m','e'), // in theory required, but I don't use it //CreateTag('O','S','/','2'), //CreateTag('p','o','s','t'), }; size_t table_length = sizeof(required_tables) / sizeof(uint32_t); for (size_t i = 0; i < table_length; ++i) { if (table_map.find(required_tables[i]) == table_map.end()) { throw TableDoesNotExist(DecomposeTag(required_tables[i])); } } } void Font::VerifyTrueTypeTables() const { uint32_t required_tables[] = { //CreateTag('c','v','t',' '), // in theory required, but I don't use it //CreateTag('f','p','g','m'), CreateTag('g','l','y','f'), CreateTag('l','o','c','a'), //CreateTag('p','r','e','p'), }; size_t table_length = sizeof(required_tables) / sizeof(uint32_t); for (size_t i = 0; i < table_length; ++i) { if (table_map.find(required_tables[i]) == table_map.end()) { throw TableDoesNotExist(DecomposeTag(required_tables[i])); } } } // ----- CodePoint to glyph index mappings ----- uint16_t Font::GetGlyphIndexF0(FItr itr, uint16_t langid, uint32_t code) const { // load header uint16_t format = ReadUSHORT(itr); uint16_t length = ReadUSHORT(itr); uint16_t language = ReadUSHORT(itr); if (format != 0) throw FontException("Internal error, calling GetGlyphIndexF0() on a 'cmap' table that isn't format 0."); if (language != langid) return 0; // map code point if (code < 256) return ReadBYTE(itr + code); return 0; } uint16_t Font::GetGlyphIndexF2(FItr itr, uint16_t langid, uint32_t code) const { // variable sized 1 or 2 byte character encoding // the docs are are very unclear on how to decode this // on top of that I have no easy way to indicate how many bytes were consumed // I have no real intention to support variable sized codeId's so this is pretty much here as a 'just in case' /* // load header ushort format = ReadUSHORT(itr); ushort length = ReadUSHORT(itr); ushort language = ReadUSHORT(itr); if (language != langId) return 0; // get high and low bytes ulong lo = codeId & 0xff; ulong hi = (codeId >> 8) & 0xff; // load sub header index (also called sub header key in docs) size_t k = static_cast<size_t>(ReadUSHORT(itr + hi*2)); // don't modify itr itr += 256 + k*8; // advance itr to sub header // load sub header ushort firstCode = ReadUSHORT(itr); ushort entryCount = ReadUSHORT(itr); short idDelta = ReadSHORT(itr); ushort idRangeOffset = ReadUSHORT(itr); // map to glyph index if (k == 0) {} // special case, 1-byte character */ return 0; } uint16_t Font::GetGlyphIndexF4(FItr itr, uint16_t langid, uint32_t code) const { // I have code for both linear and binary search // tbh, I don't think either choice really matters given how fast it executes // load header uint16_t format = ReadUSHORT(itr); uint16_t length = ReadUSHORT(itr); uint16_t language = ReadUSHORT(itr); uint16_t seg_count_x2 = ReadUSHORT(itr); uint16_t search_range = ReadUSHORT(itr); uint16_t entry_selector = ReadUSHORT(itr); uint16_t range_shift = ReadUSHORT(itr); uint16_t seg_count = seg_count_x2 >> 1; // why not just store seg_count?, this file format is retarded if (format != 4) throw FontException("Internal error, calling GetGlyphIndexF4() on a 'cmap' table that isn't format 4."); if (language != langid) return 0; // map arrays FItr end_codes = itr; FItr start_codes = itr + 2 + seg_count*1*2; FItr id_deltas = itr + 2 + seg_count*2*2; FItr id_range_offsets = itr + 2 + seg_count*3*2; if (ReadUSHORT(end_codes + (seg_count - 1) * 2) != 0xffff) throw InvalidFontException("Last end code of format 4 'cmap' table is not 0xffff."); if (ReadUSHORT(end_codes + (seg_count) * 2) != 0) throw InvalidFontException("Variable 'reservePad' following end code data of format 4 'cmap' table is not 0."); // serach variables uint16_t i; // if successful, i = matching index uint32_t start_code, end_code; // binary search uint16_t imin = 0, imax = seg_count - 1; // inclusive range while (imin < imax) { uint16_t imid = (imin + imax) >> 1; if (code > ReadUSHORT(end_codes + imid*2)) imin = imid + 1; // just need to check for greater than, so only need to read end code else imax = imid; } start_code = ReadUSHORT(start_codes + imin*2); end_code = ReadUSHORT(end_codes + imin*2); if (code >= start_code && code <= end_code) i = imin; else return 0; /* // linear search for (i = 0; i < seg_count; ++i) { start_code = ReadUSHORT(start_codes + i*2); end_code = ReadUSHORT(end_codes + i*2); if (code >= start_code && code <= end_code) break; } if (i == seg_count) return 0; */ // calculate glyph index uint16_t id_delta = ReadUSHORT(id_deltas + i*2); // apple docs say unsigned, MS say signed uint16_t id_range_offset = ReadUSHORT(id_range_offsets + i*2); FItr id_range_offset_addr = id_range_offsets + i*2; // map code to its glyph index uint16_t glyph_index = 0; if (id_range_offset == 0) { glyph_index = (id_delta + static_cast<uint16_t>(code & 0xffff)) & 0xffff; // obviously this only works for smaller codes } else { FItr glyph_index_array_addr = id_range_offset_addr + id_range_offset + 2*(code - start_code); glyph_index = ReadUSHORT(glyph_index_array_addr); } return glyph_index; } uint16_t Font::GetGlyphIndexF6(FItr itr, uint16_t langid, uint32_t code) const { // load header uint16_t format = ReadUSHORT(itr); uint16_t length = ReadUSHORT(itr); uint16_t language = ReadUSHORT(itr); uint32_t first_code = ReadUSHORT(itr); uint32_t entry_count = ReadUSHORT(itr); FItr glyph_id_array = itr; if (format != 6) throw FontException("Internal error, calling GetGlyphIndexF6() on a 'cmap' table that isn't format 6."); if (language != langid) return 0; // map code point if (code >= first_code && code < first_code + entry_count) { uint32_t i = code - first_code; return ReadUSHORT(glyph_id_array + i*2); } return 0; } uint16_t Font::GetGlyphIndexF8(FItr itr, uint16_t langid, uint32_t code) const { // variable sized format not supported return 0; } uint16_t Font::GetGlyphIndexF10(FItr itr, uint16_t langid, uint32_t code) const { // 32 bit dense format, same as format 6 with just a few changes to the types int32_t format = ReadFIXED32(itr); // 10.0 (unlike the other formats, this is in FIXED32 format) uint32_t length = ReadULONG(itr); // byte length of this subtable (including the header) uint32_t language = ReadULONG(itr); uint32_t first_code = ReadULONG(itr); // First character code covered uint32_t entry_count = ReadULONG(itr); // Number of character codes covered FItr glyph_id_array = itr; // Array of glyph indices for the character codes covered (ushorts) const int32_t required_format = 10 << 16; if (format != required_format) throw FontException("Internal error, calling GetGlyphIndexF10() on a 'cmap' table that isn't format 10.0."); if (language != langid) return 0; // map code point if (code >= first_code && code < first_code + entry_count) { uint32_t i = code - first_code; return ReadUSHORT(glyph_id_array + i*2); } return 0; } uint16_t Font::GetGlyphIndexF12(FItr itr, uint16_t langid, uint32_t code) const { // 32 bit sparse format, similar to format 4 (actually much simpler and makes more sense) uint16_t format = ReadUSHORT(itr); uint16_t reserved = ReadUSHORT(itr); // should be 0 uint32_t length = ReadULONG(itr); // byte length of this subtable (including the header) uint32_t language = ReadULONG(itr); uint32_t ngroups = ReadULONG(itr); // number of groupings which follow if (format != 12) throw FontException("Internal error, calling GetGlyphIndexF12() on a 'cmap' table that isn't format 12."); if (language != langid) return 0; // binary search uint32_t imin = 0, imax = ngroups - 1; // inclusive range while (imin < imax) { uint32_t imid = (imin + imax) >> 1; if (code > ReadULONG(itr + imid*12 + 8)) imin = imid + 1; // just need to check for greater than, so only need to read end code else imax = imid; } itr += imin*12; // map code to glyph_id uint32_t start_code = ReadULONG(itr); uint32_t end_code = ReadULONG(itr); if (code >= start_code && code <= end_code) { uint32_t glyph_id = ReadULONG(itr); return static_cast<uint16_t>(code - start_code + glyph_id); } return 0; } uint16_t Font::GetGlyphIndexF13(FItr itr, uint16_t langid, uint32_t code) const { // 32 bit 'many to one' format, similar to format 12 uint16_t format = ReadUSHORT(itr); uint16_t reserved = ReadUSHORT(itr); // should be 0 uint32_t length = ReadULONG(itr); // byte length of this subtable (including the header) uint32_t language = ReadULONG(itr); uint32_t nGroups = ReadULONG(itr); // number of groupings which follow if (format != 13) throw FontException("Internal error, calling GetGlyphIndexF13() on a 'cmap' table that isn't format 13."); if (language != langid) return 0; // binary search uint32_t imin = 0, imax = nGroups - 1; // inclusive range while (imin < imax) { uint32_t imid = (imin + imax) >> 1; if (code > ReadULONG(itr + imid*12 + 8)) imin = imid + 1; // just need to check for greater than, so only need to read end code else imax = imid; } itr += imin*12; // map codeId to glyphId uint32_t start_code = ReadULONG(itr); uint32_t end_code = ReadULONG(itr); if (code >= start_code && code <= end_code) { uint32_t glyph_id = ReadULONG(itr); return static_cast<uint16_t>(glyph_id); } return 0; } uint16_t Font::GetGlyphIndexF14(FItr itr, uint16_t langid, uint32_t code) const { // unicode variation sequences // not supported return 0; } // ----- data range mappings ----- Font::FRange Font::GetGlyphRange(uint16_t glyph_index) const { // intialize variables int16_t ilf = GetIndexToLocFormat(); uint16_t num_glyps = GetNumGlyphs(); TableEntry loca = GetTableEntry(CreateTag('l','o','c','a')); TableEntry glyf = GetTableEntry(CreateTag('g','l','y','f')); // sanity check if (glyph_index >= num_glyps) throw InvalidFontException("Invalid glyph mapping, attempting to map a glyph index that exceeds the maximum number of glyphs in the font."); // find glyph data range if (ilf == 0) { FRange range; FItr itr = loca.begin + static_cast<size_t>(glyph_index) * 2; range.first = glyf.begin + static_cast<size_t>(ReadUSHORT(itr)) * 2; range.second = glyf.begin + static_cast<size_t>(ReadUSHORT(itr)) * 2; return range; } else if (ilf == 1) { FRange range; FItr itr = loca.begin + static_cast<size_t>(glyph_index) * 4; range.first = glyf.begin + static_cast<size_t>(ReadULONG(itr)); range.second = glyf.begin + static_cast<size_t>(ReadULONG(itr)); return range; } // done throw InvalidFontException("Invalid 'head' indexToLocFormat value."); } // ----- metrics helpers ----- vec2t Font::GetKerning(uint16_t g0, uint16_t g1, bool hk) const { // intialize variables vec2t kv = vec2t(static_cast<int16_t>(GetGlyphMetrics(g0).advance_width),0); // get default advance width // get kerning table (not a required table, so we have to manually check) auto ti = table_map.find(CreateTag('k','e','r','n')); if (ti == table_map.end()) return kv; FItr itr = ti->second.begin; // parse kerning sub-tables uint16_t version = ReadUSHORT(itr); if (version == 0) { uint16_t ntables = ReadUSHORT(itr); for (uint16_t i = 0; i < ntables; ++i) itr += ParseMSKernTable(itr,g0,g1,hk,kv); } else if (version == 1) { uint16_t version_lo = ReadUSHORT(itr); // apple uses a different header, with the version being 4 bytes, so this is the last 2 bytes of version uint32_t ntables = ReadULONG(itr); for (uint32_t i = 0; i < ntables; ++i) itr += ParseAppleKernTable(itr,g0,g1,hk,kv); } // done return kv; } int16_t Font::ParseKernTableF0(FItr itr, uint16_t g0, uint16_t g1) const { // read header uint16_t npairs = ReadUSHORT(itr); uint16_t search_range = ReadUSHORT(itr); // The largest power of two less than or equal to the value of nPairs, multiplied by the size in bytes of an entry in the table. uint16_t entry_selector = ReadUSHORT(itr); // number of iterations required uint16_t range_shift = ReadUSHORT(itr); // sanity check if (npairs == 0) return 0; // perform binary search // "Deferred detection of equality" algorithm from: http://en.wikipedia.org/wiki/Binary_search_algorithm uint32_t key = static_cast<uint32_t>(g0) << 16 | static_cast<uint32_t>(g1); uint32_t imin = 0, imax = npairs - 1; // inclusive range while (imin < imax) { uint16_t imid = (imin + imax) >> 1; if (key > ReadULONG(itr + imid*6)) imin = imid + 1; else imax = imid; } if (ReadULONG(itr + imin*6) == key) return ReadSHORT(itr + imin*6 + 4); else return 0; } int16_t Font::ParseKernTableF2(FItr itr, uint16_t g0, uint16_t g1) const { uint16_t left_class_offset = 0; uint16_t right_class_offset = 0; // read header FItr begin_itr = itr; uint16_t row_width = ReadUSHORT(itr); uint16_t left_offset_table = ReadUSHORT(itr); uint16_t right_offset_table = ReadUSHORT(itr); uint16_t kern_array = ReadUSHORT(itr); // get left glyph class itr = begin_itr + left_offset_table; uint16_t left_first_glyph = ReadUSHORT(itr); uint16_t left_nglyphs = ReadUSHORT(itr); if (g0 >= left_first_glyph && g0 < left_first_glyph + left_nglyphs) { left_class_offset = ReadUSHORT(itr + (g0 - left_first_glyph) * 2); } // get right glyph class itr = begin_itr + right_offset_table; uint16_t right_first_glyph = ReadUSHORT(itr); uint16_t right_nglyphs = ReadUSHORT(itr); if (g0 >= right_first_glyph && g0 < right_first_glyph + right_nglyphs) { right_class_offset = ReadUSHORT(itr + (g0 - right_first_glyph) * 2); } // get kerning value itr = begin_itr + kern_array; return ReadSHORT(itr + left_class_offset + right_class_offset); } uint16_t Font::ParseMSKernTable(FItr itr, uint16_t g0, uint16_t g1, bool hk, vec2t& kv) const { // read table header uint16_t version = ReadUSHORT(itr); uint16_t length = ReadUSHORT(itr); uint16_t coverage = ReadUSHORT(itr); bool horizontal = (coverage & 1) != 0; // != 0 to prevent silly warnings bool minimum = (coverage & 2) != 0; bool xstream = (coverage & 4) != 0; bool replace = (coverage & 8) != 0; uint16_t format = coverage >> 8; // direction check if (horizontal != hk) return length; // get kern modifier int16_t km = 0; switch (format) { case 0: km = ParseKernTableF0(itr,g0,g1); break; case 2: km = ParseKernTableF2(itr,g0,g1); break; } // adjust kv if (horizontal && !xstream || !horizontal && xstream) { if (minimum) kv.x = (km >= 0) ? npw::Minimum(kv.x,km) : npw::Maximum(kv.x,km); else if (replace) kv.x = km; else kv.x += km; } else { if (minimum) kv.y = (km >= 0) ? npw::Minimum(kv.y,km) : npw::Maximum(kv.y,km); else if (replace) kv.y = km; else kv.y += km; } // done return length; } uint32_t Font::ParseAppleKernTable(FItr itr, uint16_t g0, uint16_t g1, bool hk, vec2t& kv) const { // read table header uint32_t length = ReadULONG(itr); uint16_t coverage = ReadUSHORT(itr); uint16_t tupleIndex = ReadUSHORT(itr); bool horizontal = (coverage & 0x8000) == 0; bool xstream = (coverage & 0x4000) != 0; bool variation = (coverage & 0x2000) != 0; uint16_t format = coverage & 0xff; // direction check if (horizontal != hk) return length; // no support for variation values if (variation) return length; // get kern modifier int16_t km = 0; switch (format) { case 0: km = ParseKernTableF0(itr,g0,g1); break; case 2: km = ParseKernTableF2(itr,g0,g1); break; } // adjust kv if (horizontal && !xstream || !horizontal && xstream) kv.x += km; else kv.y += km; // done return length; } // ----- triangulation functions ----- void Font::FillContours(FItr itr, ContourData& contours) const { using namespace std; // read header uint16_t contour_count = ReadUSHORT(itr); // safe because its already been checked itr += 8; // create contour points contours.clear(); for (uint16_t i = 0; i < contour_count; ++i) { uint16_t endpt = ReadUSHORT(itr); if (endpt >= contours.size()) contours.resize(endpt + 1); // assumes zero based index contours[endpt].end_point = true; } size_t point_count = contours.size(); // skip instructions (not used) uint16_t instruction_count = ReadUSHORT(itr); itr += instruction_count; // read flags for (size_t i = 0; i < point_count;) { uint8_t f = ReadBYTE(itr); // flags uint16_t r = 1; // repeat count if ( (f & 8) != 0 ) r += ReadBYTE(itr); // 1 + ReadBYTE(itr) for (uint16_t j = 0; j < r; ++j) { contours[i].flags = f; ++i; } } // read x coords for (size_t i = 0; i < point_count; ++i) { ContourPoint& cp = contours[i]; // read offset int16_t offset; if (cp.XShortVector()) { offset = ReadBYTE(itr); if (cp.XIsNegative()) offset = -offset; } else { if (cp.XIsSame()) offset = 0; else offset = ReadSHORT(itr); } // store offset for later cp.pos.x = offset; } // read y coords for (size_t i = 0; i < point_count; ++i) { ContourPoint& cp = contours[i]; // read offset int16_t offset; if (cp.YShortVector()) { offset = ReadBYTE(itr); if (cp.YIsNegative()) offset = -offset; } else { if (cp.YIsSame()) offset = 0; else offset = ReadSHORT(itr); } // store offset for later cp.pos.y = offset; } // adjust x/y offsets vec2t pre_point = vec2t(0,0); for (auto i = begin(contours); i != end(contours); ++i) { i->pos += pre_point; pre_point = i->pos; } } bool Font::ReadGlyphFlags(FItr& itr, matrix3x2t& matrix, uint16_t& glyph_index) const { using std::max; using std::abs; // define composite flags const uint16_t ARG_1_AND_2_ARE_WORDS = 0x0001; // If this is set, the arguments are words; otherwise, they are bytes. const uint16_t ARGS_ARE_XY_VALUES = 0x0002; // If this is set, the arguments are xy values; otherwise, they are points. const uint16_t ROUND_XY_TO_GRID = 0x0004; // For the xy values if the preceding is true. const uint16_t WE_HAVE_A_SCALE = 0x0008; // This indicates that there is a simple scale for the component. Otherwise, scale = 1.0. const uint16_t RESERVED = 0x0010; // This bit is reserved. Set it to 0. const uint16_t MORE_COMPONENTS = 0x0020; // Indicates at least one more glyph after this one. const uint16_t WE_HAVE_AN_X_AND_Y_SCALE = 0x0040; // The x direction will use a different scale from the y direction. const uint16_t WE_HAVE_A_TWO_BY_TWO = 0x0080; // There is a 2 by 2 transformation that will be used to scale the component. const uint16_t WE_HAVE_INSTRUCTIONS = 0x0100; // Following the last component are instructions for the composite character. const uint16_t USE_MY_METRICS = 0x0200; // If set, this forces the aw and lsb (and rsb) for the composite to be equal to those from this original glyph. This works for hinted and unhinted characters. const uint16_t OVERLAP_COMPOUND = 0x0400; // Used by Apple in GX fonts. const uint16_t SCALED_COMPONENT_OFFSET = 0x0800; // Composite designed to have the component offset scaled (designed for Apple rasterizer). const uint16_t UNSCALED_COMPONENT_OFFSET = 0x1000; // Composite designed not to have the component offset scaled (designed for the Microsoft TrueType rasterizer). // intialize variables int32_t& a = matrix.a; int32_t& b = matrix.b; int32_t& c = matrix.c; int32_t& d = matrix.d; int32_t& e = matrix.e; int32_t& f = matrix.f; // read flags/glyph index uint16_t flags = ReadUSHORT(itr); glyph_index = ReadUSHORT(itr); // read 'e' and 'f' values if (flags & ARGS_ARE_XY_VALUES) { if (flags & ARG_1_AND_2_ARE_WORDS) { e = static_cast<int32_t>(ReadSHORT(itr)) << 16; f = static_cast<int32_t>(ReadSHORT(itr)) << 16; } else { e = static_cast<int32_t>(ReadCHAR(itr)) << 16; f = static_cast<int32_t>(ReadCHAR(itr)) << 16; } } else throw UnsupportedCap("Compound glyph contains point/anchor offsets, which is currently unsupported."); // read transform data if (flags & WE_HAVE_A_SCALE) { a = d = ReadFIXED16(itr); } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) { a = ReadFIXED16(itr); d = ReadFIXED16(itr); } else if (flags & WE_HAVE_A_TWO_BY_TWO) { a = ReadFIXED16(itr); b = ReadFIXED16(itr); c = ReadFIXED16(itr); d = ReadFIXED16(itr); } // adjust 'e' and 'f' by the screwy TTF algorithm that makes absolutely no sense const int32_t k = 33; // 33.0f / 65536.0f; int32_t m = max(abs(a),abs(b)); int32_t n = max(abs(c),abs(d)); if (abs(abs(a) - abs(c)) <= k) m <<= 1; // * 2.0f if (abs(abs(c) - abs(d)) <= k) n <<= 1; // * 2.0f e = RoundBy16Large(e * m); f = RoundBy16Large(f * n); // done return (flags & MORE_COMPONENTS) != 0; } // ----- font info ----- vec4t Font::GetMasterRect() const { FItr itr = GetTableEntry(CreateTag('h','e','a','d')).begin; itr += 36; return vec4t(ReadSHORT(itr), ReadSHORT(itr), ReadSHORT(itr), ReadSHORT(itr)); } FontMetrics Font::GetFontMetrics() const { // read hhea data FItr itr = GetTableEntry(CreateTag('h','h','e','a')).begin; uint32_t version = ReadULONG(itr); int16_t ascent = ReadSHORT(itr); int16_t descent = ReadSHORT(itr); int16_t line_gap = ReadSHORT(itr); uint16_t advance_width_max = ReadUSHORT(itr); int16_t min_left_side_bearing = ReadSHORT(itr); int16_t min_right_side_bearing = ReadSHORT(itr); int16_t x_max_extent = ReadSHORT(itr); int16_t caret_slope_rise = ReadSHORT(itr); int16_t caret_slope_run = ReadSHORT(itr); int16_t caret_offset = ReadSHORT(itr); int16_t reserved0 = ReadSHORT(itr); int16_t reserved1 = ReadSHORT(itr); int16_t reserved2 = ReadSHORT(itr); int16_t reserved3 = ReadSHORT(itr); int16_t metric_data_format = ReadSHORT(itr); uint16_t num_of_long_hor_metrics = ReadUSHORT(itr); // sanity check if (version != 0x00010000) throw VersionException("Invalid 'hhea' table version."); if (metric_data_format != 0) throw VersionException("Invalid 'hhea' metricDataFormat."); // translate FontMetrics fm; fm.ascent = ascent; fm.descent = descent; fm.line_gap = line_gap; fm.caret_slope = vec2t(caret_slope_run,caret_slope_rise); fm.caret_offset = caret_offset; fm.min_left_side_bearing = min_left_side_bearing; fm.min_right_side_bearing = min_right_side_bearing; fm.advance_width_max = advance_width_max; return fm; } VFontMetrics Font::GetVFontMetrics() const { // get vhea table data VFontMetrics vfm; auto i = table_map.find(CreateTag('v','h','e','a')); if (i == table_map.end()) { vfm.has_vertical_font_metrics = false; return vfm; } vfm.has_vertical_font_metrics = true; FItr itr = i->second.begin; // read table uint16_t version = ReadULONG(itr); int16_t vert_typo_ascender = ReadSHORT(itr); int16_t vert_typo_descender = ReadSHORT(itr); int16_t vert_typo_line_gap = ReadSHORT(itr); int16_t advance_height_max = ReadSHORT(itr); int16_t min_top_side_bearing = ReadSHORT(itr); int16_t min_bottom_side_bearing = ReadSHORT(itr); int16_t y_max_extent = ReadSHORT(itr); int16_t caret_slope_rise = ReadSHORT(itr); int16_t caret_slope_run = ReadSHORT(itr); int16_t caret_offset = ReadSHORT(itr); int16_t reserved0 = ReadSHORT(itr); int16_t reserved1 = ReadSHORT(itr); int16_t reserved2 = ReadSHORT(itr); int16_t reserved3 = ReadSHORT(itr); int16_t metric_data_format = ReadSHORT(itr); int16_t num_of_long_ver_metrics = ReadSHORT(itr); // sanity check if (version != 0x00010000) throw VersionException("Invalid 'vhea' table version."); if (metric_data_format != 0) throw VersionException("Invalid 'vhea' metricDataFormat."); // translate vfm.vert_typo_descender = vert_typo_ascender; vfm.vert_typo_ascender = vert_typo_descender; vfm.vert_typo_line_gap = vert_typo_line_gap; vfm.caret_slope = vec2t(caret_slope_run,caret_slope_rise); vfm.caret_offset = caret_offset; vfm.min_top_side_bearing = min_top_side_bearing; vfm.min_bottom_side_bearing = min_bottom_side_bearing; vfm.advance_height_max = advance_height_max; return vfm; } uint16_t Font::GlyphCount() const { return GetNumGlyphs(); } uint16_t Font::UnitsPerEM() const { FItr itr = GetTableEntry(CreateTag('h','e','a','d')).begin; itr += 18; return ReadUSHORT(itr); } // ----- glyph info ----- uint16_t Font::GetGlyphIndex(CodePoint code_point) const { // convenience variables uint32_t code = code_point.code; uint16_t rpid = code_point.platform; uint16_t reid = code_point.encoding; uint16_t langid = code_point.language; // intialize variables FItr begin = GetTableEntry(CreateTag('c','m','a','p')).begin; FItr itr = begin; uint32_t glyph_index = 0; // read cmap 'header' uint16_t version = ReadUSHORT(itr); if (version != 0) throw VersionException("Table 'cmap' version is unsupported."); uint16_t numTables = ReadUSHORT(itr); // iterate over tables for (uint16_t i = 0; i < numTables; ++i) { // load table info uint16_t platform = ReadUSHORT(itr); uint16_t encoding = ReadUSHORT(itr); FItr table_itr = begin + ReadULONG(itr); // check platform/encoding id if (rpid == platform && reid == encoding) { // load format and language info uint16_t format = ReadUSHORT(table_itr + 0); // don't advance iterator // branch on format uint16_t glyph_index = 0; switch (format) { case 0: glyph_index = GetGlyphIndexF0(table_itr,langid,code); if (glyph_index != 0) return glyph_index; break; case 2: glyph_index = GetGlyphIndexF2(table_itr,langid,code); if (glyph_index != 0) return glyph_index; break; case 4: glyph_index = GetGlyphIndexF4(table_itr,langid,code); if (glyph_index != 0) return glyph_index; break; case 6: glyph_index = GetGlyphIndexF6(table_itr,langid,code); if (glyph_index != 0) return glyph_index; break; case 8: glyph_index = GetGlyphIndexF8(table_itr,langid,code); if (glyph_index != 0) return glyph_index; break; case 10: glyph_index = GetGlyphIndexF10(table_itr,langid,code); if (glyph_index != 0) return glyph_index; break; case 12: glyph_index = GetGlyphIndexF12(table_itr,langid,code); if (glyph_index != 0) return glyph_index; break; case 13: glyph_index = GetGlyphIndexF13(table_itr,langid,code); if (glyph_index != 0) return glyph_index; break; case 14: glyph_index = GetGlyphIndexF14(table_itr,langid,code); if (glyph_index != 0) return glyph_index; break; } } } return 0; // the 0 glyph is always the 'cannot find' glyph } vec4t Font::GetGlyphRect(uint16_t glyph_index) const { // get glyph data FRange glyph_data = GetGlyphRange(glyph_index); FItr itr = glyph_data.first; // read glyph header int16_t num_contours = ReadSHORT(itr); vec4t r(ReadSHORT(itr), ReadSHORT(itr), ReadSHORT(itr), ReadSHORT(itr)); // done return r; //return vec4t(r.z, r.w, r.x, r.y); // reorder coordinates } vec4t Font::GetGlyphRect(CodePoint code_point) const { return GetGlyphRect(GetGlyphIndex(code_point)); } GlyphMetrics Font::GetGlyphMetrics(uint16_t glyph_index) const { // read hhea data FItr itr = GetTableEntry(CreateTag('h','h','e','a')).begin; uint32_t version = ReadULONG(itr); itr += 28; // skip rest of hhea table int16_t metric_data_format = ReadSHORT(itr); uint32_t num_of_long_hor_metrics = ReadUSHORT(itr); // sanity check if (version != 0x00010000) throw VersionException("Invalid 'hhea' table version."); if (metric_data_format != 0) throw VersionException("Invalid 'hhea' metricDataFormat."); // read hmtx uint16_t advance_width; int16_t left_side_bearing; itr = GetTableEntry(CreateTag('h','m','t','x')).begin; if (glyph_index < num_of_long_hor_metrics) { itr += glyph_index * 4; advance_width = ReadUSHORT(itr); left_side_bearing = ReadSHORT(itr); } else { // get advance_width from last entry itr += (num_of_long_hor_metrics - 1) * 4; advance_width = ReadUSHORT(itr); itr += 2; // get lsb itr += (glyph_index - num_of_long_hor_metrics) * 2; left_side_bearing = ReadSHORT(itr); } // convert to GlyphMetrics GlyphMetrics gm; gm.left_side_bearing = left_side_bearing; gm.advance_width = advance_width; return gm; } GlyphMetrics Font::GetGlyphMetrics(CodePoint code_point) const { return GetGlyphMetrics(GetGlyphIndex(code_point)); } VGlyphMetrics Font::GetVGlyphMetrics(uint16_t glyph_index) const { VGlyphMetrics vgm; vgm.has_vertical_font_metrics = false; // get vhea table auto i = table_map.find(CreateTag('v','h','e','a')); if (i == table_map.end()) return vgm; FItr itr = i->second.begin; // read vhea data uint32_t version = ReadULONG(itr); itr += 28; // skip rest of vhea table int16_t metric_data_format = ReadSHORT(itr); uint32_t num_of_long_ver_metrics = ReadUSHORT(itr); // sanity check if (version != 0x00010000) throw VersionException("Invalid 'vhea' table version."); if (metric_data_format != 0) throw VersionException("Invalid 'vhea' metricDataFormat."); // get vmtx table i = table_map.find(CreateTag('v','m','t','x')); if (i == table_map.end()) return vgm; vgm.has_vertical_font_metrics = true; itr = i->second.begin; // read vmtx table uint16_t advance_height; int16_t top_side_bearing; if (glyph_index < num_of_long_ver_metrics) { itr += glyph_index * 4; advance_height = ReadUSHORT(itr); top_side_bearing = ReadSHORT(itr); } else { // get advanceWidth from last entry itr += (num_of_long_ver_metrics - 1) * 4; advance_height = ReadUSHORT(itr); itr += 2; // get lsb itr += (glyph_index - num_of_long_ver_metrics) * 2; top_side_bearing = ReadSHORT(itr); } // convert to VGlyphMetrics vgm.top_side_bearing = top_side_bearing; vgm.advance_height = advance_height; return vgm; } VGlyphMetrics Font::GetVGlyphMetrics(CodePoint code_point) const { return GetVGlyphMetrics(GetGlyphIndex(code_point)); } // ----- kerning info ----- vec2t Font::GetKerning(uint16_t g0, uint16_t g1) const { return GetKerning(g0,g1,true); } vec2t Font::GetKerning(CodePoint cp0, CodePoint cp1) const { return GetKerning(GetGlyphIndex(cp0),GetGlyphIndex(cp1),true); } vec2t Font::GetVKerning(uint16_t g0, uint16_t g1) const { return GetKerning(g0,g1,false); } vec2t Font::GetVKerning(CodePoint cp0, CodePoint cp1) const { return GetKerning(GetGlyphIndex(cp0),GetGlyphIndex(cp1),false); }
29.459212
207
0.673558
[ "vector", "transform" ]
2da33222494cc6c43a711b11ef7aeeec1f603522
893
cpp
C++
Other/Codechef/Problems/Paying-up.cpp
shashankkmciv18/dsa
6feba269292d95d36e84f1adb910fe2ed5467f71
[ "MIT" ]
54
2020-07-31T14:50:23.000Z
2022-03-14T11:03:02.000Z
Other/Codechef/Problems/Paying-up.cpp
SahilMund/dsa
a94151b953b399ea56ff50cf30dfe96100e8b9a7
[ "MIT" ]
null
null
null
Other/Codechef/Problems/Paying-up.cpp
SahilMund/dsa
a94151b953b399ea56ff50cf30dfe96100e8b9a7
[ "MIT" ]
30
2020-08-15T17:39:02.000Z
2022-03-10T06:50:18.000Z
#include <bits/stdc++.h> using namespace std; typedef long long int ll; bool makeSets(vector<ll> &a , int n, int k) { int i = 0; int sum = 0; while(n) { if(n & 1) { sum+=a[i]; } i++; n = n >> 1; } if (sum == k) return true; return false; // cout << a[i] << endl; // cout << k << endl; } void solve() { int n, k; cin >> n >> k; vector <ll> a(n); for(int i=0; i<n ; i++) { cin >> a[i]; } // cout << n << endl; // cout << k << endl; // int i=0; int range = (1<<n) - 1; int ans = 0; for( int i=0; i<=range; i++) { if(makeSets(a,i,k)) { ans = 1; cout << "Yes\n"; break; } } if(ans == 0) cout << "No\n"; } int main() { int t; cin >> t; while(t--) solve(); }
15.946429
45
0.368421
[ "vector" ]
2dab2614e896df3f6439b25e5869356ef3031e0c
5,592
cpp
C++
debug/moc_edit_profile_dia.cpp
mmahdibarghi/codana
fdb016a67d3e45728cc6e49ea2147ad2d97ce6e1
[ "MIT" ]
null
null
null
debug/moc_edit_profile_dia.cpp
mmahdibarghi/codana
fdb016a67d3e45728cc6e49ea2147ad2d97ce6e1
[ "MIT" ]
null
null
null
debug/moc_edit_profile_dia.cpp
mmahdibarghi/codana
fdb016a67d3e45728cc6e49ea2147ad2d97ce6e1
[ "MIT" ]
1
2021-06-23T19:11:26.000Z
2021-06-23T19:11:26.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'edit_profile_dia.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../edit_profile_dia.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'edit_profile_dia.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.12.8. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_edit_profile_dia_t { QByteArrayData data[11]; char stringdata0[109]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_edit_profile_dia_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_edit_profile_dia_t qt_meta_stringdata_edit_profile_dia = { { QT_MOC_LITERAL(0, 0, 16), // "edit_profile_dia" QT_MOC_LITERAL(1, 17, 14), // "editing_signal" QT_MOC_LITERAL(2, 32, 0), // "" QT_MOC_LITERAL(3, 33, 5), // "_name" QT_MOC_LITERAL(4, 39, 9), // "_lastname" QT_MOC_LITERAL(5, 49, 9), // "_username" QT_MOC_LITERAL(6, 59, 9), // "_password" QT_MOC_LITERAL(7, 69, 6), // "_email" QT_MOC_LITERAL(8, 76, 3), // "_id" QT_MOC_LITERAL(9, 80, 6), // "_birth" QT_MOC_LITERAL(10, 87, 21) // "on_buttonBox_accepted" }, "edit_profile_dia\0editing_signal\0\0_name\0" "_lastname\0_username\0_password\0_email\0" "_id\0_birth\0on_buttonBox_accepted" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_edit_profile_dia[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 7, 24, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 10, 0, 39, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, QMetaType::QString, QMetaType::QString, QMetaType::QString, QMetaType::QString, QMetaType::QString, QMetaType::QString, QMetaType::QDate, 3, 4, 5, 6, 7, 8, 9, // slots: parameters QMetaType::Void, 0 // eod }; void edit_profile_dia::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<edit_profile_dia *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->editing_signal((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3])),(*reinterpret_cast< QString(*)>(_a[4])),(*reinterpret_cast< QString(*)>(_a[5])),(*reinterpret_cast< QString(*)>(_a[6])),(*reinterpret_cast< QDate(*)>(_a[7]))); break; case 1: _t->on_buttonBox_accepted(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { using _t = void (edit_profile_dia::*)(QString , QString , QString , QString , QString , QString , QDate ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&edit_profile_dia::editing_signal)) { *result = 0; return; } } } } QT_INIT_METAOBJECT const QMetaObject edit_profile_dia::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_edit_profile_dia.data, qt_meta_data_edit_profile_dia, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *edit_profile_dia::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *edit_profile_dia::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_edit_profile_dia.stringdata0)) return static_cast<void*>(this); return QDialog::qt_metacast(_clname); } int edit_profile_dia::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } // SIGNAL 0 void edit_profile_dia::editing_signal(QString _t1, QString _t2, QString _t3, QString _t4, QString _t5, QString _t6, QDate _t7) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)), const_cast<void*>(reinterpret_cast<const void*>(&_t4)), const_cast<void*>(reinterpret_cast<const void*>(&_t5)), const_cast<void*>(reinterpret_cast<const void*>(&_t6)), const_cast<void*>(reinterpret_cast<const void*>(&_t7)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } QT_WARNING_POP QT_END_MOC_NAMESPACE
37.033113
421
0.640021
[ "object" ]
2db2170ba8a8e46996adaf9e7220edbb5388d525
24,361
cpp
C++
src/ppmdu/pmd2/pmd2_asm.cpp
SkyTemple/ppmdu
9731ea103affd66f2e8c1202c9acb2ebfd4c9924
[ "CC0-1.0" ]
37
2015-10-30T21:56:26.000Z
2021-11-30T15:33:26.000Z
src/ppmdu/pmd2/pmd2_asm.cpp
SkyTemple/ppmdu
9731ea103affd66f2e8c1202c9acb2ebfd4c9924
[ "CC0-1.0" ]
27
2015-01-06T05:45:55.000Z
2020-01-29T21:40:22.000Z
src/ppmdu/pmd2/pmd2_asm.cpp
SkyTemple/ppmdu
9731ea103affd66f2e8c1202c9acb2ebfd4c9924
[ "CC0-1.0" ]
8
2016-02-07T23:31:03.000Z
2020-07-12T08:51:41.000Z
#include "pmd2_asm.hpp" #include <utils/utility.hpp> #include <utils/gbyteutils.hpp> #include <ppmdu/pmd2/pmd2_hcdata.hpp> #include <ppmdu/fmts/sir0.hpp> #include <sstream> #include <vector> #include <fstream> #include <iomanip> #include <iostream> #include <iterator> using namespace std; using namespace utils; namespace pmd2 { const std::string FName_ARM9Bin = "arm9.bin"; const std::string ASM_ModdedTag = "PATCH"; const int ASM_ModdedTaDescgMaxLen = 4096; //======================================================================================= // Exceptions //======================================================================================= ExBinaryIsModded::ExBinaryIsModded(const std::string & msg, const std::string & binpath, uint32_t binoff) :std::runtime_error(msg),m_binoff(binoff),m_binpath(binpath) {} //======================================================================================= // Implementation //======================================================================================= class PMD2_ASM_Impl { public: /* PMD2_ASM_Impl */ PMD2_ASM_Impl(const std::string & romroot, ConfigLoader & conf) :m_conf(conf), m_romroot(romroot) {} /* MakeBinPathString Assemble the path to a binary within the current rom's directory structure. */ std::string MakeBinPathString(const binarylocatioinfo & info)const { stringstream binpath; binpath <<utils::TryAppendSlash(m_romroot) <<info.fpath; return std::move(binpath.str()); } /* MakeLooseBinFileOutPath Assemble the path to a binary loose file within the rom's directory structure. */ std::string MakeLooseBinFileOutPath( eBinaryLocations loc ) { auto found = m_conf.GetASMPatchData().lfentry.find(loc); if(found == m_conf.GetASMPatchData().lfentry.end()) throw std::runtime_error("PMD2_ASM_Impl::MakeLooseBinFileOutPath(): Couldn't find the entity file output path for the actor list!"); stringstream outfpath; outfpath <<TryAppendSlash(m_romroot) <<DirName_DefData <<"/" <<found->second.path ; return std::move(outfpath.str()); } PMD2_ASM::modinfo CheckBlockModdedTag(const binarylocatioinfo & locinfo) { ifstream binf; OpenBinFile(binf,locinfo); return CheckBlockModdedTag(binf, locinfo); } /* CheckBlockModdedTag Verifies if the PATCH tag is at an expected bin location offset within a binary. */ PMD2_ASM::modinfo CheckBlockModdedTag(istream & binf, const binarylocatioinfo & locinfo) { PMD2_ASM::modinfo minfo; //stringstream binpath; //binpath <<utils::TryAppendSlash(m_romroot) <<binppathrel; try { //ifstream binf( binpath.str(), ios::in | ios::binary ); binf.seekg(locinfo.location.beg); std::istreambuf_iterator<char> init(binf); std::istreambuf_iterator<char> initend; if( std::equal( ASM_ModdedTag.begin(), ASM_ModdedTag.end(), init ) ) { //Read the mod tag for at least 4096 bytes or until we hit a terminating 0 or reach the end of the file! for( size_t cnt = 0; cnt < ASM_ModdedTaDescgMaxLen && init != initend; ++cnt ) { char ch = *init; ++init; if(ch == 0) break; minfo.modstring.push_back(ch); } } } catch(const std::exception&) { throw_with_nested( std::runtime_error("PMD2_ASM_Impl::CheckBlockModdedTag() : Failure while reading file " + locinfo.fpath + "!") ); } return std::move(minfo); } /* LoadData */ template<class _DataTy, class _TransType> void LoadData( eBinaryLocations binloc, _DataTy & out_data) { const binarylocatioinfo bininfo = m_conf.GetGameBinaryOffset(binloc); ifstream binf; OpenBinFile(binf, bininfo); //Check if modded tag is there, then load from the correct source! PMD2_ASM::modinfo modinfo = CheckBlockModdedTag( binf, bininfo ); binf.seekg(0); binf.clear(); if(modinfo.ismodded()) { ifstream loosebin; OpenLooseBinFile(loosebin,binloc); LoadDataFromLooseBin<_DataTy,_TransType>(out_data, loosebin); //Open lose file } else LoadDataFromBin<_DataTy,_TransType>(out_data, bininfo, binf); } /* LoadDataFromLooseBin */ template<class _DataTy, class _TransType> void LoadDataFromLooseBin( _DataTy & out_data, std::ifstream & binstrm ) { filetypes::sir0_header hdr; hdr.ReadFromContainer( istreambuf_iterator<char>(binstrm), istreambuf_iterator<char>() ); if(hdr.magic != filetypes::MagicNumber_SIR0) throw std::runtime_error( "PMD2_ASM_Impl::LoadDataFromLooseBin(): File is not a SIR0 container!" ); //Move to the beginning of the list binstrm.seekg(hdr.subheaderptr); uint32_t ptrtbl = utils::ReadIntFromBytes<uint32_t>( istreambuf_iterator<char>(binstrm), istreambuf_iterator<char>() ); uint32_t nbentries = utils::ReadIntFromBytes<uint32_t>( istreambuf_iterator<char>(binstrm), istreambuf_iterator<char>() ); binstrm.seekg(ptrtbl); //Read each entries for( size_t cntentry = 0; cntentry < nbentries; ++cntentry ) { _TransType entry; entry.Read(binstrm, 0); //No offset applied to what is loaded from loose binaries!! out_data.PushEntryPair(entry.name, entry); } } /* LoadDataFromBin */ template<class _DataTy, class _TransType> void LoadDataFromBin( _DataTy & out_data, const binarylocatioinfo & bininfo, std::ifstream & binstrm ) { //2. If no modded tag, we go ahead and dump the list binstrm.seekg(bininfo.location.beg); while(static_cast<std::streamoff>(binstrm.tellg()) < bininfo.location.end) { _TransType entry; entry.Read(binstrm, bininfo.loadaddress); out_data.PushEntryPair(entry.name, entry); } } /* DumpStringAndList Generic function for writing a SIR0 file containing a consecutive list of entries, and a consecutive block of null terminated c strings referred to by each entry. */ template<class _EntryType, class _TransType, class _infwdit, class _outfwdit> _outfwdit DumpStringAndList( _infwdit itbeg, _infwdit itend, _outfwdit itw, bool bputsubheader = true )const { using std::vector; using std::back_inserter; static_assert( std::is_same<_EntryType&, typename decltype(*itbeg)>::value || std::is_same<const _EntryType&, typename decltype(*itbeg)>::value, "PMD2_ASM_Impl::DumpStringAndList(): Iterators weren't iterators on expected type!!" ); static const size_t entrysz = _TransType::Size; //Size of an entry // ----------------------------------------- // === 1st pass pile up strings in order === // ----------------------------------------- ::filetypes::FixedSIR0DataWrapper<std::vector<uint8_t>> sir0anddat; const size_t nbentries = std::distance(itbeg, itend); vector<uint8_t> & outdata = sir0anddat.Data(); vector<uint32_t> stroffsets; stroffsets.reserve(nbentries); sir0anddat.Data().reserve((nbentries * 8) + (nbentries * entrysz)); auto itbackins = std::back_inserter(sir0anddat.Data()); for( auto itstr = itbeg; itstr != itend; ++itstr) { const _EntryType & inf = *itstr; stroffsets.push_back(outdata.size()); std::copy( inf.name.begin(), inf.name.end(), itbackins ); outdata.push_back(0); utils::AppendPaddingBytes( itbackins, outdata.size(), 4, 0 ); } utils::AppendPaddingBytes(itbackins, outdata.size(), 16, 0); //Pad the strings, because I'm a perfectionist // ----------------------------------------- // === 2nd pass, write the table entries === // ----------------------------------------- uint32_t ptrdatatbl = outdata.size(); size_t cntptr = 0; for( auto itentry = itbeg; itentry != itend; ++itentry, ++cntptr ) { //WriteEntryType_impl<_EntryType>::WriteEntry(*itentry, stroffsets[cntptr], sir0anddat, itbackins); _TransType trans; trans = (*itentry); trans.WriteEntry(stroffsets[cntptr], sir0anddat, itbackins); } utils::AppendPaddingBytes(itbackins, outdata.size(), 16, 0xAA); if(bputsubheader) { sir0anddat.SetDataPointerOffset(outdata.size()); //Append a subheader sir0anddat.pushpointer(ptrdatatbl); itbackins = utils::WriteIntToBytes( static_cast<uint32_t>(nbentries), itbackins ); utils::AppendPaddingBytes(itbackins, outdata.size(), 16, 0xAA); } else sir0anddat.SetDataPointerOffset(ptrdatatbl); //Then write out! sir0anddat.Write(itw); return itw; } /* LoadLevelList */ GameScriptData::lvlinf_t LoadLevelList() { GameScriptData::lvlinf_t data; LoadData<GameScriptData::lvlinf_t, LevelEntry>(eBinaryLocations::Events, data); return std::move(data); } /* LoadActorList */ GameScriptData::livesent_t LoadActorList() { GameScriptData::livesent_t data; LoadData<GameScriptData::livesent_t, EntitySymbolListEntry>(eBinaryLocations::Entities, data); return std::move(data); } /* LoadObjectList */ GameScriptData::objinf_t LoadObjectList() { GameScriptData::objinf_t data; LoadData<GameScriptData::objinf_t, ObjectFileListEntry>(eBinaryLocations::Objects, data); return std::move(data); } /* LoadGameVariableList */ GameScriptData::gvar_t LoadGameVariableList() { GameScriptData::gvar_t data; LoadData<GameScriptData::gvar_t, ScriptVariablesEntry>(eBinaryLocations::ScriptVariables, data); return std::move(data); } /* Write the data to a loose file at the locations indicated in the configuration files, since there's no way to guarantee any changes would fit into the initial binaries. */ void WriteLevelList( const GameScriptData::lvlinf_t & src ) { const string outfpath = MakeLooseBinFileOutPath(eBinaryLocations::Events); try { std::ofstream out(outfpath, std::ios::out|std::ios::binary); out.exceptions(std::ios::badbit); DumpStringAndList<pmd2::level_info,LevelEntry>(src.begin(), src.end(), std::ostreambuf_iterator<char>(out) ); } catch(const std::exception &) { std::throw_with_nested( std::runtime_error("PMD2_ASM_Impl::WriteLevelList(): IO error writing to file " + outfpath) ); } } /* */ void WriteActorList( const GameScriptData::livesent_t & src ) { const string outfpath = MakeLooseBinFileOutPath(eBinaryLocations::Entities); try { std::ofstream out(outfpath, std::ios::out|std::ios::binary); out.exceptions(std::ios::badbit); DumpStringAndList<pmd2::livesent_info, EntitySymbolListEntry>(src.begin(), src.end(), std::ostreambuf_iterator<char>(out) ); } catch(const std::exception &) { std::throw_with_nested( std::runtime_error("PMD2_ASM_Impl::WriteActorList(): IO error writing to file " + outfpath) ); } } /* */ void WriteObjectList( const GameScriptData::objinf_t & src ) { const string outfpath = MakeLooseBinFileOutPath(eBinaryLocations::Objects); try { std::ofstream out(outfpath, std::ios::out|std::ios::binary); out.exceptions(std::ios::badbit); DumpStringAndList<pmd2::object_info, ObjectFileListEntry>(src.begin(), src.end(), std::ostreambuf_iterator<char>(out) ); } catch(const std::exception &) { std::throw_with_nested( std::runtime_error("PMD2_ASM_Impl::WriteObjectList(): IO error writing to file " + outfpath) ); } } /* */ void WriteGameVariableList( const GameScriptData::gvar_t & src ) { const string outfpath = MakeLooseBinFileOutPath(eBinaryLocations::ScriptVariables); try { std::ofstream out(outfpath, std::ios::out|std::ios::binary); out.exceptions(std::ios::badbit); DumpStringAndList<pmd2::gamevariable_info, ScriptVariablesEntry>(src.begin(), src.end(), std::ostreambuf_iterator<char>(out) ); } catch(const std::exception &) { std::throw_with_nested( std::runtime_error("PMD2_ASM_Impl::WriteGameVariableList(): IO error writing to file " + outfpath) ); } } /* LoadAllToConfig Replaces what was currently loaded as script data with what was loaded from the binaries. */ void LoadAllToConfig() { m_conf.GetGameScriptData().LevelInfo() = LoadLevelList(); m_conf.GetGameScriptData().LivesEnt() = LoadActorList(); m_conf.GetGameScriptData().ObjectsInfo() = LoadObjectList(); m_conf.GetGameScriptData().GameVariables() = LoadGameVariableList(); } /* WriteAllFromConfig Writes the hardcoded data parsed from the config file, into loose files. */ void WriteAllFromConfig() { WriteLevelList(m_conf.GetGameScriptData().LevelInfo()); WriteActorList(m_conf.GetGameScriptData().LivesEnt()); WriteObjectList(m_conf.GetGameScriptData().ObjectsInfo()); WriteGameVariableList(m_conf.GetGameScriptData().GameVariables()); } private: /* */ void OpenBinFile( std::ifstream & out_strm, const binarylocatioinfo & locinfo) { const std::string binpath = MakeBinPathString(locinfo); out_strm.open(binpath, ios::in | ios::binary ); if( out_strm.bad() || !out_strm.is_open() ) throw std::runtime_error("PMD2_ASM_Impl::OpenBinFile(): Couldn't open file " + binpath + "!"); out_strm.exceptions(ios::badbit); } /* */ void OpenLooseBinFile( std::ifstream & out_strm, eBinaryLocations loc ) { const string binpath = MakeLooseBinFileOutPath(loc); out_strm.open(binpath, ios::in | ios::binary ); if( out_strm.bad() || !out_strm.is_open() ) throw std::runtime_error("PMD2_ASM_Impl::OpenLooseBinFile(): Couldn't open file " + binpath + " !"); out_strm.exceptions(ios::badbit); } // // std::string FetchString( size_t strpos, size_t fsize, ifstream & ifstr ) // { // string str; // streampos posbef = ifstr.tellg(); // if( strpos < fsize ) // { // ifstr.seekg( strpos, ios::beg ); // str = std::move(utils::ReadCStrFromBytes( std::istreambuf_iterator<char>(ifstr), std::istreambuf_iterator<char>() )); // ifstr.seekg( posbef, ios::beg ); // } // else // { // clog << "<!>- PMD2_ASM_Impl::FetchString(): Warning: Got invalid string pointer!!!\n"; //#ifdef _DEBUG // assert(false); //#endif // } // // return std::move(str); // } // // void LoadEntityData() // { // binarylocatioinfo locinfo = m_bininfo.FindInfoByLocation( eBinaryLocations::Entities ); // size_t fsize = 0; // // if(!locinfo) // throw std::runtime_error("PMD2_ASM_Impl::LoadEntityData(): Invalid entity data in the config file!"); // // ifstream indata = std::move(OpenFile(locinfo,fsize)); // m_entdata.reserve( (locinfo.location.end - locinfo.location.beg) / RawEntityDataEntry::LEN ); // // auto itentry = std::istreambuf_iterator<char>(indata); // indata.seekg(locinfo.location.beg); // for( auto & entry : m_entdata ) // { // RawEntityDataEntry rawent; // rawent.Read(std::istreambuf_iterator<char>(indata), std::istreambuf_iterator<char>()); // entry.entityid = rawent.entityid; // entry.type = rawent.type; // entry.unk3 = rawent.unk3; // entry.unk4 = rawent.unk4; // entry.name = FetchString( (rawent.ptrstring - locinfo.loadaddress), fsize, indata ); // } // } // // void LoadStarters() // { // binarylocatioinfo heroids = m_bininfo.FindInfoByLocation( eBinaryLocations::StartersHeroIds ); // binarylocatioinfo partnerids = m_bininfo.FindInfoByLocation( eBinaryLocations::StartersPartnerIds ); // binarylocatioinfo startstr = m_bininfo.FindInfoByLocation( eBinaryLocations::StartersStrings ); // if( heroids && partnerids && startstr ) // { // size_t flen = 0; // ifstream inf = std::move(OpenFile( heroids, flen )); // // //Load hero // const size_t nbheroentries = (heroids.location.end - heroids.location.beg) / sizeof(uint16_t); // const size_t nbstr = (startstr.location.end - startstr.location.beg) / sizeof(uint16_t); // // if(nbstr != nbheroentries || nbheroentries % 2 != 0 || nbheroentries != static_cast<size_t>(eStarterNatures::NbNatures) ) // throw std::runtime_error("PMD2_ASM_Impl::LoadStarters(): mismatch between number of starter strings id and starters OR nb of starters not divisible by 2!!"); // // m_startertable.HeroEntries.reserve( nbheroentries ); // inf.seekg(heroids.location.beg); // // //Load Heroes // for( size_t cntentry = 0; cntentry < nbheroentries; cntentry+=2 ) // { // StarterPKmList::StarterPkData cur; // cur.pokemon1 = utils::ReadIntFromBytes<uint16_t>( std::istreambuf_iterator<char>(inf), std::istreambuf_iterator<char>() ); // cur.pokemon2 = utils::ReadIntFromBytes<uint16_t>( std::istreambuf_iterator<char>(inf), std::istreambuf_iterator<char>() ); // streampos befpos = inf.tellg(); // // //Get string id // //size_t stroff = startstr.location.beg + (cntentry * 2); // //inf.seekg(stroff,ios::beg); // //cur.textidpkm1 = utils::ReadIntFromBytes<uint16_t>( std::istreambuf_iterator<char>(inf), std::istreambuf_iterator<char>() ); // //cur.textidpkm2 = utils::ReadIntFromBytes<uint16_t>( std::istreambuf_iterator<char>(inf), std::istreambuf_iterator<char>() ); // //inf.seekg(befpos,ios::beg); // m_startertable.HeroEntries.emplace( std::forward<eStarterNatures>(static_cast<eStarterNatures>(cntentry)), std::forward<StarterPKmList::StarterPkData>(cur) ); // } // // //Load Hero strings id // inf.seekg(startstr.location.beg,ios::beg); // for( size_t cntstr = 0; cntstr < nbstr; cntstr+=2 ) // { // StarterPKmList::StarterPkData & cur = m_startertable.HeroEntries.at( static_cast<eStarterNatures>(cntstr) ); // cur.textidpkm1 = utils::ReadIntFromBytes<uint16_t>( std::istreambuf_iterator<char>(inf), std::istreambuf_iterator<char>() ); // cur.textidpkm2 = utils::ReadIntFromBytes<uint16_t>( std::istreambuf_iterator<char>(inf), std::istreambuf_iterator<char>() ); // } // // //Load partners // const size_t nbpartnerentries = (partnerids.location.end - partnerids.location.beg) / sizeof(uint16_t); // m_startertable.PartnerEntries.resize(nbpartnerentries); // inf.seekg(partnerids.location.beg,ios::beg); // // for( size_t cntptner = 0; cntptner < nbpartnerentries; ++cntptner ) // { // m_startertable.PartnerEntries[cntptner] = utils::ReadIntFromBytes<uint16_t>( std::istreambuf_iterator<char>(inf), std::istreambuf_iterator<char>() ); // } // // } // else // throw std::runtime_error("PMD2_ASM_Impl::LoadStarters(): Invalid starters data in the config file!"); // } private: ConfigLoader & m_conf; eGameVersion m_version; eGameRegion m_region; std::string m_romroot; }; //======================================================================================= // PMD2_ASM_Manip //======================================================================================= PMD2_ASM::PMD2_ASM( const std::string & romroot, ConfigLoader & conf ) :m_pimpl(new PMD2_ASM_Impl(romroot, conf)) {} PMD2_ASM::~PMD2_ASM() { } GameScriptData::lvlinf_t PMD2_ASM::LoadLevelList() { return m_pimpl->LoadLevelList(); } GameScriptData::livesent_t PMD2_ASM::LoadActorList() { //assert(false); return m_pimpl->LoadActorList(); } GameScriptData::objinf_t PMD2_ASM::LoadObjectList() { //assert(false); return m_pimpl->LoadObjectList(); } GameScriptData::gvar_t PMD2_ASM::LoadGameVariableList() { //assert(false); return m_pimpl->LoadGameVariableList(); } void PMD2_ASM::WriteLevelList(const GameScriptData::lvlinf_t & src) { m_pimpl->WriteLevelList(src); } void PMD2_ASM::WriteActorList(const GameScriptData::livesent_t & src) { m_pimpl->WriteActorList(src); } void PMD2_ASM::WriteObjectList(const GameScriptData::objinf_t & src) { m_pimpl->WriteObjectList(src); } void PMD2_ASM::WriteGameVariableList(const GameScriptData::gvar_t & src) { m_pimpl->WriteGameVariableList(src); } void PMD2_ASM::LoadAllToConfig() { m_pimpl->LoadAllToConfig(); } void PMD2_ASM::WriteAllFromConfig() { m_pimpl->WriteAllFromConfig(); } PMD2_ASM::modinfo PMD2_ASM::CheckBlockModdedTag(const binarylocatioinfo & locinfo) { return m_pimpl->CheckBlockModdedTag(locinfo); } };
40.737458
180
0.549813
[ "vector" ]
2db55421ef21a06b0557e6f131375e0e165f80c2
111,548
cxx
C++
PWGHF/vertexingHF/AliAnalysisTaskSESigmacTopK0Spi.cxx
giacomoalocco/AliPhysics
c346260f677a5fc75068726c3662fd9952c96c97
[ "BSD-3-Clause" ]
1
2019-10-03T15:11:04.000Z
2019-10-03T15:11:04.000Z
PWGHF/vertexingHF/AliAnalysisTaskSESigmacTopK0Spi.cxx
abarreirALICE/AliPhysics
b2cd6e45bb7fc1b76fec02fe20c70a828a30cb6d
[ "BSD-3-Clause" ]
null
null
null
PWGHF/vertexingHF/AliAnalysisTaskSESigmacTopK0Spi.cxx
abarreirALICE/AliPhysics
b2cd6e45bb7fc1b76fec02fe20c70a828a30cb6d
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appeuear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: */ // // // Base class for Lc2V0 Analysis to be used with TMVA // // //------------------------------------------------------------------------------------------ // // Author: C. Zampolli, A. Alici // //------------------------------------------------------------------------------------------ #include <TSystem.h> #include <TParticle.h> #include <TParticlePDG.h> #include <TH1F.h> #include <TH1I.h> #include <TProfile.h> #include <TH2F.h> #include <TH3F.h> #include <TTree.h> #include "TROOT.h" #include <TDatabasePDG.h> #include <TMath.h> #include <TVector3.h> #include <TLorentzVector.h> #include <THnSparse.h> #include <TObjArray.h> #include <AliAnalysisDataSlot.h> #include <AliAnalysisDataContainer.h> #include "AliMCEvent.h" #include "AliAnalysisManager.h" #include "AliAODMCHeader.h" #include "AliAODHandler.h" #include "AliLog.h" #include "AliAODVertex.h" #include "AliAODRecoDecay.h" #include "AliAODRecoDecayHF.h" #include "AliAODRecoCascadeHF.h" #include "AliAnalysisVertexingHF.h" #include "AliESDtrack.h" #include "AliAODTrack.h" #include "AliAODv0.h" #include "AliAODMCParticle.h" #include "AliAnalysisTaskSE.h" #include "AliAnalysisTaskSESigmacTopK0Spi.h" #include "AliNormalizationCounter.h" #include "AliAODPidHF.h" #include "AliPIDResponse.h" #include "AliPIDCombined.h" #include "AliTOFPIDResponse.h" #include "AliInputEventHandler.h" #include "AliAODRecoDecayHF3Prong.h" #include "AliKFParticle.h" #include "AliKFVertex.h" #include "AliExternalTrackParam.h" #include "AliESDUtils.h" #include "AliDataFile.h" #include <TMVA/Tools.h> #include <TMVA/Reader.h> #include <TMVA/MethodCuts.h> #include "IClassifierReader.h" using std::cout; using std::endl; #include <dlfcn.h> /// \cond CLASSIMP ClassImp(AliAnalysisTaskSESigmacTopK0Spi); /// \endcond //__________________________________________________________________________ AliAnalysisTaskSESigmacTopK0Spi::AliAnalysisTaskSESigmacTopK0Spi(): AliAnalysisTaskSE(), fUseMCInfo(kFALSE), fOutput(0), fPIDResponse(0), fPIDCombined(0), fIsK0sAnalysis(kFALSE), fCounter(0), fCounterC(0), fAnalCuts(0), fListCuts(0), fListWeight(0), fListCounters(0), fListProfiles(0), fUseOnTheFlyV0(kFALSE), fIsEventSelected(kFALSE), fVariablesTreeSgn(0), fVariablesTreeBkg(0), fCandidateVariables(), fHistoCentrality(0), fHistoEvents(0), fHistoTracklets_1(0), fHistoTracklets_1_cent(0), fHistoTracklets_All(0), fHistoTracklets_All_cent(0), fHistoLc(0), fHistoLcOnTheFly(0), fFillOnlySgn(kFALSE), fHistoLcBeforeCuts(0), fHistoFiducialAcceptance(0), fHistoCodesSgn(0), fHistoCodesBkg(0), fVtx1(0), fmcLabelLc(-1), fKeepingOnlyHIJINGBkg(kFALSE), fUtils(0), fHistoBackground(0), fCurrentEvent(-1), fBField(0), fKeepingOnlyPYTHIABkg(kFALSE), fHistoMCLcK0SpGen(0), fHistoMCLcK0SpGenAcc(0), fHistoMCLcK0SpGenLimAcc(0), fTriggerMask(0), fFuncWeightPythia(0), fFuncWeightFONLL5overLHC13d3(0), fFuncWeightFONLL5overLHC13d3Lc(0), fHistoMCNch(0), fNTracklets_1(0), fNTracklets_All(0), fCentrality(0), fFillTree(0), fUseWeightsLibrary(kFALSE), fBDTReader(0), fTMVAlibName(""), fTMVAlibPtBin(""), fNamesTMVAVar(""), fBDTHisto(0), fBDTHistoVsMassK0S(0), fBDTHistoVstImpParBach(0), fBDTHistoVstImpParV0(0), fBDTHistoVsBachelorPt(0), fBDTHistoVsCombinedProtonProb(0), fBDTHistoVsCtau(0), fBDTHistoVsCosPAK0S(0), fBDTHistoVsSignd0(0), fBDTHistoVsCosThetaStar(0), fBDTHistoVsnSigmaTPCpr(0), fBDTHistoVsnSigmaTOFpr(0), fBDTHistoVsnSigmaTPCpi(0), fBDTHistoVsnSigmaTPCka(0), fBDTHistoVsBachelorP(0), fBDTHistoVsBachelorTPCP(0), fHistoNsigmaTPC(0), fHistoNsigmaTOF(0), fDebugHistograms(kFALSE), fAODProtection(1), fUsePIDresponseForNsigma(kFALSE), fNVars(14), fTimestampCut(0), fUseXmlWeightsFile(kTRUE), fReader(0), fVarsTMVA(0), fNVarsSpectators(0), fVarsTMVASpectators(0), fNamesTMVAVarSpectators(""), fXmlWeightsFile(""), fBDTHistoTMVA(0), fRefMult(9.26), fYearNumber(16), fHistoNtrUnCorr(0), fHistoNtrCorr(0), fHistoVzVsNtrUnCorr(0), fHistoVzVsNtrCorr(0), fUseMultCorrection(kFALSE), fMultiplicityEstimator(kNtrk10), fDoVZER0ParamVertexCorr(1), fUseMultiplicityCut(kFALSE), fMultiplicityCutMin(0.), fMultiplicityCutMax(99999.), fUseXmlFileFromCVMFS(kFALSE), fXmlFileFromCVMFS(""), ftrackArraySelSoftPi(0x0), fnSelSoftPi(), fESDtrackCutsSoftPion(0x0), fhistMCSpectrumAccLc(0x0), fhistMCSpectrumAccLcFromSc(0x0), fhistMCSpectrumAccSc(0x0), fhSparseAnalysisSigma(0x0), fLcMassWindowForSigmaC(0.20), fSigmaCDeltaMassWindow(0.230), fNRotations(0), fMinAngleForRot(5*TMath::Pi()/6), fMaxAngleForRot(7*TMath::Pi()/6), fMinPtSigmacCand(0), fMaxPtSigmacCand(999), fOutputSparse(0), isLcAnalysis(0) { /// Default ctor // for(Int_t i=0; i<14; i++) fMultEstimatorAvg[i]=0; } //___________________________________________________________________________ AliAnalysisTaskSESigmacTopK0Spi::AliAnalysisTaskSESigmacTopK0Spi(const Char_t* name, AliRDHFCutsLctoV0* analCuts, Bool_t useOnTheFly) : AliAnalysisTaskSE(name), fUseMCInfo(kFALSE), fOutput(0), fPIDResponse(0), fPIDCombined(0), fIsK0sAnalysis(kFALSE), fCounter(0), fCounterC(0), fAnalCuts(analCuts), fListCuts(0), fListWeight(0), fListCounters(0), fListProfiles(0), fUseOnTheFlyV0(useOnTheFly), fIsEventSelected(kFALSE), fVariablesTreeSgn(0), fVariablesTreeBkg(0), fCandidateVariables(), fHistoCentrality(0), fHistoEvents(0), fHistoTracklets_1(0), fHistoTracklets_1_cent(0), fHistoTracklets_All(0), fHistoTracklets_All_cent(0), fHistoLc(0), fHistoLcOnTheFly(0), fFillOnlySgn(kFALSE), fHistoLcBeforeCuts(0), fHistoFiducialAcceptance(0), fHistoCodesSgn(0), fHistoCodesBkg(0), fVtx1(0), fmcLabelLc(-1), fKeepingOnlyHIJINGBkg(kFALSE), fUtils(0), fHistoBackground(0), fCurrentEvent(-1), fBField(0), fKeepingOnlyPYTHIABkg(kFALSE), fHistoMCLcK0SpGen(0), fHistoMCLcK0SpGenAcc(0), fHistoMCLcK0SpGenLimAcc(0), fTriggerMask(0), fFuncWeightPythia(0), fFuncWeightFONLL5overLHC13d3(0), fFuncWeightFONLL5overLHC13d3Lc(0), fHistoMCNch(0), fNTracklets_1(0), fNTracklets_All(0), fCentrality(0), fFillTree(0), fUseWeightsLibrary(kFALSE), fBDTReader(0), fTMVAlibName(""), fTMVAlibPtBin(""), fNamesTMVAVar(""), fBDTHisto(0), fBDTHistoVsMassK0S(0), fBDTHistoVstImpParBach(0), fBDTHistoVstImpParV0(0), fBDTHistoVsBachelorPt(0), fBDTHistoVsCombinedProtonProb(0), fBDTHistoVsCtau(0), fBDTHistoVsCosPAK0S(0), fBDTHistoVsSignd0(0), fBDTHistoVsCosThetaStar(0), fBDTHistoVsnSigmaTPCpr(0), fBDTHistoVsnSigmaTOFpr(0), fBDTHistoVsnSigmaTPCpi(0), fBDTHistoVsnSigmaTPCka(0), fBDTHistoVsBachelorP(0), fBDTHistoVsBachelorTPCP(0), fHistoNsigmaTPC(0), fHistoNsigmaTOF(0), fDebugHistograms(kFALSE), fAODProtection(1), fUsePIDresponseForNsigma(kFALSE), fNVars(14), fTimestampCut(0), fUseXmlWeightsFile(kTRUE), fReader(0), fVarsTMVA(0), fNVarsSpectators(0), fVarsTMVASpectators(0), fNamesTMVAVarSpectators(""), fXmlWeightsFile(""), fBDTHistoTMVA(0), fRefMult(9.26), fYearNumber(16), fHistoNtrUnCorr(0), fHistoNtrCorr(0), fHistoVzVsNtrUnCorr(0), fHistoVzVsNtrCorr(0), fUseMultCorrection(kFALSE), fMultiplicityEstimator(kNtrk10), fDoVZER0ParamVertexCorr(1), fUseMultiplicityCut(kFALSE), fMultiplicityCutMin(0.), fMultiplicityCutMax(99999.), fUseXmlFileFromCVMFS(kFALSE), fXmlFileFromCVMFS(""), ftrackArraySelSoftPi(0x0), fnSelSoftPi(), fESDtrackCutsSoftPion(0x0), fhistMCSpectrumAccLc(0x0), fhistMCSpectrumAccLcFromSc(0x0), fhistMCSpectrumAccSc(0x0), fhSparseAnalysisSigma(0x0), fLcMassWindowForSigmaC(0.20), fSigmaCDeltaMassWindow(0.230), fNRotations(0), fMinAngleForRot(5*TMath::Pi()/6), fMaxAngleForRot(7*TMath::Pi()/6), fMinPtSigmacCand(0), fMaxPtSigmacCand(999), fOutputSparse(0), isLcAnalysis(0) { // /// Constructor. Initialization of Inputs and Outputs // Info("AliAnalysisTaskSESigmacTopK0Spi","Calling Constructor"); for(Int_t i=0; i<14; i++) fMultEstimatorAvg[i]=0; DefineOutput(1, TList::Class()); // Tree signal + Tree Bkg + histoEvents DefineOutput(2, TList::Class()); // normalization counter object DefineOutput(3, TList::Class()); // Cuts DefineOutput(4, TTree::Class()); // Tree signal + Tree Bkg + histoEvents DefineOutput(5, TTree::Class()); // Tree signal + Tree Bkg + histoEvents DefineOutput(6, TList::Class()); // Sparse DefineOutput(7, TList::Class()); // weights } //___________________________________________________________________________ AliAnalysisTaskSESigmacTopK0Spi::~AliAnalysisTaskSESigmacTopK0Spi() { // /// destructor // Info("~AliAnalysisTaskSESigmacTopK0Spi","Calling Destructor"); if (fOutput) { delete fOutput; fOutput = 0; } if (fPIDResponse) { delete fPIDResponse; } if (fPIDCombined) { delete fPIDCombined; } if (fCounter) { delete fCounter; fCounter = 0; } if (fCounterC) { delete fCounterC; fCounterC = 0; } if (fAnalCuts) { delete fAnalCuts; fAnalCuts = 0; } if (fListCuts) { delete fListCuts; fListCuts = 0; } if (fListCounters) { delete fListCounters; fListCounters = 0; } if (fListWeight) { delete fListWeight; fListWeight = 0; } if(fVariablesTreeSgn){ delete fVariablesTreeSgn; fVariablesTreeSgn = 0; } if(fVariablesTreeBkg){ delete fVariablesTreeBkg; fVariablesTreeBkg = 0; } if (fUtils) { delete fUtils; fUtils = 0; } if (fBDTReader) { //delete fBDTReader; fBDTReader = 0; } if (fReader) { delete fReader; fReader = 0; } if (fVarsTMVA) { delete fVarsTMVA; fVarsTMVA = 0; } if (fVarsTMVASpectators) { delete fVarsTMVASpectators; fVarsTMVASpectators = 0; } for(Int_t i=0; i<14; i++){ if (fMultEstimatorAvg[i]) delete fMultEstimatorAvg[i]; } if (fOutputSparse) { delete fOutputSparse; fOutputSparse = 0; } if(ftrackArraySelSoftPi) delete ftrackArraySelSoftPi; if(fESDtrackCutsSoftPion) delete fESDtrackCutsSoftPion; if(fhistMCSpectrumAccLc) delete fhistMCSpectrumAccLc; if(fhistMCSpectrumAccLcFromSc) delete fhistMCSpectrumAccLcFromSc; if(fhistMCSpectrumAccSc) delete fhistMCSpectrumAccSc; if(fhSparseAnalysisSigma) delete fhSparseAnalysisSigma; } //_________________________________________________ void AliAnalysisTaskSESigmacTopK0Spi::Init() { // /// Initialization // fIsEventSelected = kFALSE; if (fDebug > 1) AliInfo("Init"); fListCuts = new TList(); fListCuts->SetOwner(); fListCuts->Add(new AliRDHFCutsLctoV0(*fAnalCuts)); PostData(3, fListCuts); // Save the weight functions or histograms fListWeight = new TList(); fListWeight->SetOwner(); fListWeight->Add(fHistoMCNch); PostData(7, fListWeight); if (fUseMCInfo && (fKeepingOnlyHIJINGBkg || fKeepingOnlyPYTHIABkg)) fUtils = new AliVertexingHFUtils(); if(!fESDtrackCutsSoftPion){ fESDtrackCutsSoftPion = new AliESDtrackCuts("AliESDtrackCuts", "default"); fESDtrackCutsSoftPion->SetMinNClustersITS(3); fESDtrackCutsSoftPion->SetMaxDCAToVertexXY(0.065); fESDtrackCutsSoftPion->SetPtRange(0.05, 1.e10); fESDtrackCutsSoftPion->SetMaxDCAToVertexZ(0.15); fESDtrackCutsSoftPion->SetEtaRange(-0.9, +0.9); } return; } //________________________________________ terminate ___________________________ void AliAnalysisTaskSESigmacTopK0Spi::Terminate(Option_t*) { /// The Terminate() function is the last function to be called during /// a query. It always runs on the client, it can be used to present /// the results graphically or save the results to file. AliInfo("Terminate"); AliAnalysisTaskSE::Terminate(); fOutput = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutput) { AliError("fOutput not available"); return; } if(fHistoMCLcK0SpGen) { AliInfo(Form("At MC level, %f Lc --> K0S + p were found", fHistoMCLcK0SpGen->GetEntries())); } else { AliInfo("fHistoMCLcK0SpGen not available"); } if(fHistoMCLcK0SpGenAcc) { AliInfo(Form("At MC level, %f Lc --> K0S + p were found in the acceptance", fHistoMCLcK0SpGenAcc->GetEntries())); } else { AliInfo("fHistoMCLcK0SpGenAcc not available"); } if(fVariablesTreeSgn) { AliInfo(Form("At Reco level, %lld Lc --> K0S + p were found", fVariablesTreeSgn->GetEntries())); } else { AliInfo("fVariablesTreeSgn not available"); } fOutputSparse = dynamic_cast<TList*> (GetOutputData(6)); if (!fOutputSparse) { AliError("fOutputSparse not available"); return; } return; } //___________________________________________________________________________ void AliAnalysisTaskSESigmacTopK0Spi::UserCreateOutputObjects() { AliInfo(Form("CreateOutputObjects of task %s\n", GetName())); fOutput = new TList(); fOutput->SetOwner(); fOutput->SetName("listTrees"); // Output slot 1: list of 2 trees (Sgn + Bkg) of the candidate variables const char* nameoutput = GetOutputSlot(1)->GetContainer()->GetName(); fVariablesTreeSgn = new TTree(Form("%s_Sgn", nameoutput), "Candidates variables tree, Signal"); fVariablesTreeBkg = new TTree(Form("%s_Bkg", nameoutput), "Candidates variables tree, Background"); Int_t nVar; if (fUseMCInfo) nVar = 54; //"full" tree if MC else nVar = 38; //"reduced" tree if data fCandidateVariables = new Float_t [nVar]; TString * fCandidateVariableNames = new TString[nVar]; if (fUseMCInfo) { // "full tree" for MC fCandidateVariableNames[0] = "massLc2K0Sp"; fCandidateVariableNames[1] = "massLc2Lambdapi"; fCandidateVariableNames[2] = "massK0S"; fCandidateVariableNames[3] = "massLambda"; fCandidateVariableNames[4] = "massLambdaBar"; fCandidateVariableNames[5] = "cosPAK0S"; fCandidateVariableNames[6] = "dcaV0"; fCandidateVariableNames[7] = "tImpParBach"; fCandidateVariableNames[8] = "tImpParV0"; fCandidateVariableNames[9] = "nSigmaTPCpr"; fCandidateVariableNames[10] = "nSigmaTOFpr"; fCandidateVariableNames[11] = "bachelorPt"; fCandidateVariableNames[12] = "V0positivePt"; fCandidateVariableNames[13] = "V0negativePt"; fCandidateVariableNames[14] = "dcaV0pos"; fCandidateVariableNames[15] = "dcaV0neg"; fCandidateVariableNames[16] = "v0Pt"; fCandidateVariableNames[17] = "massGamma"; fCandidateVariableNames[18] = "LcPt"; fCandidateVariableNames[19] = "combinedProtonProb"; fCandidateVariableNames[20] = "LcEta"; fCandidateVariableNames[21] = "V0positiveEta"; fCandidateVariableNames[22] = "V0negativeEta"; fCandidateVariableNames[23] = "TPCProtonProb"; fCandidateVariableNames[24] = "TOFProtonProb"; fCandidateVariableNames[25] = "bachelorEta"; fCandidateVariableNames[26] = "LcP"; fCandidateVariableNames[27] = "bachelorP"; fCandidateVariableNames[28] = "v0P"; fCandidateVariableNames[29] = "V0positiveP"; fCandidateVariableNames[30] = "V0negativeP"; fCandidateVariableNames[31] = "v0Eta"; fCandidateVariableNames[32] = "LcPtMC"; fCandidateVariableNames[33] = "DecayLengthK0S"; fCandidateVariableNames[34] = "bachCode"; fCandidateVariableNames[35] = "k0SCode"; fCandidateVariableNames[36] = "alphaArm"; fCandidateVariableNames[37] = "ptArm"; fCandidateVariableNames[38] = "CosThetaStar"; fCandidateVariableNames[39] = "weightPtFlat"; //fCandidateVariableNames[40] = "weightFONLL5overLHC13d3"; //fCandidateVariableNames[41] = "weightFONLL5overLHC13d3Lc"; //fCandidateVariableNames[40] = "CosPALc"; fCandidateVariableNames[40] = "SigmacPt"; fCandidateVariableNames[41] = "CosThetaStarSoftPi"; fCandidateVariableNames[42] = "weightNch"; fCandidateVariableNames[43] = "NtrkRaw"; fCandidateVariableNames[44] = "NtrkCorr"; fCandidateVariableNames[45] = "signd0"; fCandidateVariableNames[46] = "centrality"; fCandidateVariableNames[47] = "NtrkAll"; fCandidateVariableNames[48] = "origin"; fCandidateVariableNames[49] = "nSigmaTPCpi"; fCandidateVariableNames[50] = "nSigmaTPCka"; //fCandidateVariableNames[51] = "bachTPCmom"; fCandidateVariableNames[51] = "deltaM"; fCandidateVariableNames[52] = "nSigmaTOFpi"; fCandidateVariableNames[53] = "nSigmaTOFka"; } else { // "light mode" fCandidateVariableNames[0] = "massLc2K0Sp"; fCandidateVariableNames[1] = "alphaArm"; fCandidateVariableNames[2] = "massK0S"; fCandidateVariableNames[3] = "massLambda"; fCandidateVariableNames[4] = "massLambdaBar"; fCandidateVariableNames[5] = "cosPAK0S"; fCandidateVariableNames[6] = "dcaV0"; fCandidateVariableNames[7] = "tImpParBach"; fCandidateVariableNames[8] = "tImpParV0"; fCandidateVariableNames[9] = "nSigmaTPCpr"; fCandidateVariableNames[10] = "nSigmaTOFpr"; fCandidateVariableNames[11] = "bachelorPt"; fCandidateVariableNames[12] = "V0positivePt"; fCandidateVariableNames[13] = "V0negativePt"; fCandidateVariableNames[14] = "dcaV0pos"; fCandidateVariableNames[15] = "dcaV0neg"; fCandidateVariableNames[16] = "v0Pt"; //fCandidateVariableNames[17] = "bachTPCmom"; fCandidateVariableNames[17] = "SigmacPt"; fCandidateVariableNames[18] = "LcPt"; fCandidateVariableNames[19] = "combinedProtonProb"; fCandidateVariableNames[20] = "V0positiveEta"; //fCandidateVariableNames[21] = "bachelorP"; // we replaced the V0negativeEta with the bachelor P as this is more useful (for PID) while the V0 daughters' eta we don't use... And are practically the same (positive and negative) fCandidateVariableNames[21] = "nSigmaTOFpi"; fCandidateVariableNames[22] = "bachelorEta"; fCandidateVariableNames[23] = "v0P"; fCandidateVariableNames[24] = "DecayLengthK0S"; fCandidateVariableNames[25] = "nSigmaTPCpi"; fCandidateVariableNames[26] = "nSigmaTPCka"; fCandidateVariableNames[27] = "NtrkRaw"; fCandidateVariableNames[28] = "NtrkCorr"; fCandidateVariableNames[29] = "CosThetaStar"; fCandidateVariableNames[30] = "signd0"; fCandidateVariableNames[31] = "centrality"; fCandidateVariableNames[32] = "NtrkAll"; fCandidateVariableNames[33] = "origin"; fCandidateVariableNames[34] = "ptArm"; fCandidateVariableNames[35] = "deltaM"; //fCandidateVariableNames[36] = "CosPALc"; fCandidateVariableNames[36] = "CosThetaStarSoftPi"; fCandidateVariableNames[37] = "nSigmaTOFka"; } for(Int_t ivar=0; ivar < nVar; ivar++){ fVariablesTreeSgn->Branch(fCandidateVariableNames[ivar].Data(), &fCandidateVariables[ivar], Form("%s/f",fCandidateVariableNames[ivar].Data())); fVariablesTreeBkg->Branch(fCandidateVariableNames[ivar].Data(), &fCandidateVariables[ivar], Form("%s/f",fCandidateVariableNames[ivar].Data())); } fHistoCentrality = new TH1F("fHistoCentrality", "fHistoCentrality", 100, 0., 100.); fHistoEvents = new TH1F("fHistoEvents", "fHistoEvents", 6, -0.5, 5.5); TString labelEv[6] = {"RejectedDeltaMismatch", "AcceptedDeltaMismatch", "NotSelected", "TimeStampCut", "Selected", "AcceptedMultCut"}; for (Int_t ibin = 1; ibin <= fHistoEvents->GetNbinsX(); ibin++){ fHistoEvents->GetXaxis()->SetBinLabel(ibin, labelEv[ibin-1].Data()); } fHistoTracklets_1 = new TH1F("fHistoTracklets_1", "fHistoTracklets_1", 1000, 0, 5000); fHistoTracklets_1_cent = new TH2F("fHistoTracklets_1_cent", "fHistoTracklets_1_cent; centrality; SPD tracklets [-1, 1]", 100, 0., 100., 1000, 0, 5000); fHistoTracklets_All = new TH1F("fHistoTracklets_All", "fHistoTracklets_All", 1000, 0, 5000); fHistoTracklets_All_cent = new TH2F("fHistoTracklets_All_cent", "fHistoTracklets_All_cent; centrality; SPD tracklets [-999, 999]", 100, 0., 100., 1000, 0, 5000); fHistoLc = new TH1F("fHistoLc", "fHistoLc", 2, -0.5, 1.5); fHistoLcOnTheFly = new TH1F("fHistoLcOnTheFly", "fHistoLcOnTheFly", 4, -0.5, 3.5); TString labelOnTheFly[4] = {"OnTheFly-Bkg", "OfflineBkg", "OnTheFly-Sgn", "OfflineSgn"}; for (Int_t ibin = 1; ibin <= fHistoLcOnTheFly->GetNbinsX(); ibin++){ fHistoLcOnTheFly->GetXaxis()->SetBinLabel(ibin, labelOnTheFly[ibin-1].Data()); } fHistoLcBeforeCuts = new TH1F("fHistoLcBeforeCuts", "fHistoLcBeforeCuts", 2, -0.5, 1.5); TString labelBeforeCuts[2] = {"Bkg", "Sgn"}; for (Int_t ibin = 1; ibin <= fHistoLcBeforeCuts->GetNbinsX(); ibin++){ fHistoLcBeforeCuts->GetXaxis()->SetBinLabel(ibin, labelBeforeCuts[ibin-1].Data()); fHistoLc->GetXaxis()->SetBinLabel(ibin, labelBeforeCuts[ibin-1].Data()); } fHistoFiducialAcceptance = new TH1F("fHistoFiducialAcceptance", "fHistoFiducialAcceptance", 4, -0.5, 3.5); TString labelAcc[4] = {"NotOk-Bkg", "Ok-Bkg", "NotOk-Sgn", "Ok-Sgn"}; for (Int_t ibin = 1; ibin <= fHistoFiducialAcceptance->GetNbinsX(); ibin++){ fHistoFiducialAcceptance->GetXaxis()->SetBinLabel(ibin, labelAcc[ibin-1].Data()); } fHistoCodesSgn = new TH2F("fHistoCodesSgn", "fHistoCodes for Signal; bachelor; K0S", 7, -1.5, 5.5, 9, -1.5, 7.5); fHistoCodesBkg = new TH2F("fHistoCodesBkg", "fHistoCodes for Background; bachelor; K0S", 7, -1.5, 5.5, 9, -1.5, 7.5); TString labelx[7] = { "kBachInvalid", "kBachFake", "kBachNoProton", "kBachPrimary", "kBachNoLambdaMother", "kBachDifferentLambdaMother", "kBachCorrectLambdaMother"}; TString labely[9] = { "kK0SInvalid", "kK0SFake", "kK0SNoK0S", "kK0SWithoutMother", "kK0SNotFromK0", "kK0Primary", "kK0NoLambdaMother", "kK0DifferentLambdaMother", "kK0CorrectLambdaMother"}; for (Int_t ibin = 1; ibin <= fHistoCodesSgn->GetNbinsX(); ibin++){ fHistoCodesSgn->GetXaxis()->SetBinLabel(ibin, labelx[ibin-1].Data()); fHistoCodesBkg->GetXaxis()->SetBinLabel(ibin, labelx[ibin-1].Data()); } for (Int_t ibin = 1; ibin <= fHistoCodesSgn->GetNbinsY(); ibin++){ fHistoCodesSgn->GetYaxis()->SetBinLabel(ibin, labely[ibin-1].Data()); fHistoCodesBkg->GetYaxis()->SetBinLabel(ibin, labely[ibin-1].Data()); } fHistoBackground = new TH1F("fHistoBackground", "fHistoBackground", 4, -0.5, 3.5); TString labelBkg[4] = {"Injected", "Non-injected", "Non-PYTHIA", "PYTHIA"}; for (Int_t ibin = 1; ibin <= fHistoBackground->GetNbinsX(); ibin++){ fHistoBackground->GetXaxis()->SetBinLabel(ibin, labelBkg[ibin-1].Data()); } const Float_t ptbins[15] = {0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 12., 17., 25., 35.}; fHistoMCLcK0SpGen = new TH1F("fHistoMCLcK0SpGen", "fHistoMCLcK0SpGen", 14, ptbins); fHistoMCLcK0SpGenAcc = new TH1F("fHistoMCLcK0SpGenAcc", "fHistoMCLcK0SpGenAcc", 14, ptbins); fHistoMCLcK0SpGenLimAcc = new TH1F("fHistoMCLcK0SpGenLimAcc", "fHistoMCLcK0SpGenLimAcc", 14, ptbins); fBDTHisto = new TH2D("fBDTHisto", "Lc inv mass vs bdt output; bdt; m_{inv}(pK^{0}_{S})[GeV/#it{c}^{2}]", 10000, -1, 1, 1000, 2.05, 2.55); fBDTHistoTMVA = new TH2D("fBDTHistoTMVA", "Lc inv mass vs bdt output; bdt; m_{inv}(pK^{0}_{S})[GeV/#it{c}^{2}]", 10000, -1, 1, 1000, 2.05, 2.55); if (fDebugHistograms) { fBDTHistoVsMassK0S = new TH2D("fBDTHistoVsMassK0S", "K0S inv mass vs bdt output; bdt; m_{inv}(#pi^{+}#pi^{#minus})[GeV/#it{c}^{2}]", 1000, -1, 1, 1000, 0.485, 0.51); fBDTHistoVstImpParBach = new TH2D("fBDTHistoVstImpParBach", "d0 bachelor vs bdt output; bdt; d_{0, bachelor}[cm]", 1000, -1, 1, 100, -1, 1); fBDTHistoVstImpParV0 = new TH2D("fBDTHistoVstImpParV0", "d0 K0S vs bdt output; bdt; d_{0, V0}[cm]", 1000, -1, 1, 100, -1, 1); fBDTHistoVsBachelorPt = new TH2D("fBDTHistoVsBachelorPt", "bachelor pT vs bdt output; bdt; p_{T, bachelor}[GeV/#it{c}]", 1000, -1, 1, 100, 0, 20); fBDTHistoVsCombinedProtonProb = new TH2D("fBDTHistoVsCombinedProtonProb", "combined proton probability vs bdt output; bdt; Bayesian PID_{bachelor}", 1000, -1, 1, 100, 0, 1); fBDTHistoVsCtau = new TH2D("fBDTHistoVsCtau", "K0S ctau vs bdt output; bdt; c#tau_{V0}[cm]", 1000, -1, 1, 1000, 0, 100); fBDTHistoVsCosPAK0S = new TH2D("fBDTHistoVsCosPAK0S", "V0 cosine pointing angle vs bdt output; bdt; CosPAK^{0}_{S}", 1000, -1, 1, 100, 0.9, 1); fBDTHistoVsCosThetaStar = new TH2D("fBDTHistoVsCosThetaStar", "proton emission angle in pK0s pair rest frame vs bdt output; bdt; Cos#Theta*", 1000, -1, 1, 100, -1, 1); fBDTHistoVsSignd0 = new TH2D("fBDTHistoVsSignd0", "signed d0 bachelor vs bdt output; bdt; signd_{0, bachelor}[cm]", 1000, -1, 1, 100, -1, 1); fBDTHistoVsnSigmaTPCpr = new TH2D("fBDTHistoVsnSigmaTPCpr", "nSigmaTPCpr vs bdt output; bdt; n_{#sigma}^{TPC}_{pr}", 1000, -1, 1, 1000, -10, 10); fBDTHistoVsnSigmaTOFpr = new TH2D("fBDTHistoVsnSigmaTOFpr", "nSigmaTOFpr vs bdt output; bdt; n_{#sigma}^{TOF}_{pr}", 1000, -1, 1, 1000, -10, 10); fBDTHistoVsnSigmaTPCpi = new TH2D("fBDTHistoVsnSigmaTPCpi", "nSigmaTPCpi vs bdt output; bdt; n_{#sigma}^{TPC}_{pi}", 1000, -1, 1, 1000, -10, 10); fBDTHistoVsnSigmaTPCka = new TH2D("fBDTHistoVsnSigmaTPCka", "nSigmaTPCka vs bdt output; bdt; n_{#sigma}^{TPC}_{ka}", 1000, -1, 1, 1000, -10, 10); fBDTHistoVsBachelorP = new TH2D("fBDTHistoVsBachelorP", "bachelor p vs bdt output; bdt; p_{bachelor}[GeV/#it{c}]", 1000, -1, 1, 100, 0, 20); fBDTHistoVsBachelorTPCP = new TH2D("fBDTHistoVsBachelorTPCP", "bachelor TPC momentum vs bdt output; bdt; p_{TPC, bachelor}[GeV/#it{c}]", 1000, -1, 1, 100, 0, 20); fHistoNsigmaTPC = new TH2D("fHistoNsigmaTPC", "; #it{p} (GeV/#it{c}); n_{#sigma}^{TPC} (proton hypothesis)", 500, 0, 5, 1000, -5, 5); fHistoNsigmaTOF = new TH2D("fHistoNsigmaTOF", "; #it{p} (GeV/#it{c}); n_{#sigma}^{TOF} (proton hypothesis)", 500, 0, 5, 1000, -5, 5); } fOutput->Add(fHistoEvents); fOutput->Add(fHistoTracklets_1); fOutput->Add(fHistoTracklets_1_cent); fOutput->Add(fHistoTracklets_All); fOutput->Add(fHistoTracklets_All_cent); fOutput->Add(fHistoLc); fOutput->Add(fHistoLcOnTheFly); fOutput->Add(fHistoLcBeforeCuts); fOutput->Add(fHistoFiducialAcceptance); fOutput->Add(fHistoCodesSgn); fOutput->Add(fHistoCodesBkg); fOutput->Add(fHistoBackground); fOutput->Add(fHistoMCLcK0SpGen); fOutput->Add(fHistoMCLcK0SpGenAcc); fOutput->Add(fHistoMCLcK0SpGenLimAcc); fOutput->Add(fHistoCentrality); fOutput->Add(fBDTHisto); fOutput->Add(fBDTHistoTMVA); if (fDebugHistograms) { fOutput->Add(fBDTHistoVsMassK0S); fOutput->Add(fBDTHistoVstImpParBach); fOutput->Add(fBDTHistoVstImpParV0); fOutput->Add(fBDTHistoVsBachelorPt); fOutput->Add(fBDTHistoVsCombinedProtonProb); fOutput->Add(fBDTHistoVsCtau); fOutput->Add(fBDTHistoVsCosPAK0S); fOutput->Add(fBDTHistoVsCosThetaStar); fOutput->Add(fBDTHistoVsSignd0); fOutput->Add(fBDTHistoVsnSigmaTPCpr); fOutput->Add(fBDTHistoVsnSigmaTOFpr); fOutput->Add(fBDTHistoVsnSigmaTPCpi); fOutput->Add(fBDTHistoVsnSigmaTPCka); fOutput->Add(fBDTHistoVsBachelorP); fOutput->Add(fBDTHistoVsBachelorTPCP); fOutput->Add(fHistoNsigmaTPC); fOutput->Add(fHistoNsigmaTOF); } if(fUseMultCorrection){ Int_t nMultBins = 200; Float_t firstMultBin = -0.5; Float_t lastMultBin = 199.5; const char *estimatorName="tracklets"; if(fMultiplicityEstimator==kVZERO || fMultiplicityEstimator==kVZEROA || fMultiplicityEstimator==kVZEROEq || fMultiplicityEstimator==kVZEROAEq) { nMultBins = 400; lastMultBin = 799.5; estimatorName = "vzero"; } fHistoNtrUnCorr = new TH1F("fHistoNtrUnCorr", Form("Uncorrected %s mulitplicity; %s; Entries",estimatorName,estimatorName),nMultBins, firstMultBin, lastMultBin); fHistoNtrCorr = new TH1F("fHistoNtrCorr", Form("Corrected %s mulitplicity; %s; Entries",estimatorName,estimatorName),nMultBins, firstMultBin, lastMultBin); fHistoVzVsNtrUnCorr = new TH2F("fHistoVzVsNtrUnCorr", Form("VtxZ vs Uncorrected %s mulitplicity; VtxZ; %s; Entries",estimatorName,estimatorName), 300,-15.,15., nMultBins, firstMultBin, lastMultBin); fHistoVzVsNtrCorr = new TH2F("fHistoVzVsNtrCorr", Form("VtxZ vs Corrected %s mulitplicity; VtxZ; %s; Entries",estimatorName,estimatorName), 300,-15.,15., nMultBins, firstMultBin, lastMultBin); fOutput->Add(fHistoNtrUnCorr); fOutput->Add(fHistoNtrCorr); fOutput->Add(fHistoVzVsNtrUnCorr); fOutput->Add(fHistoVzVsNtrCorr); } PostData(1, fOutput); PostData(4, fVariablesTreeSgn); PostData(5, fVariablesTreeBkg); AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager(); AliInputEventHandler* inputHandler = (AliInputEventHandler*) (man->GetInputEventHandler()); fPIDResponse = inputHandler->GetPIDResponse(); // Setting properties of PID fPIDCombined = new AliPIDCombined; fPIDCombined->SetDefaultTPCPriors(); fPIDCombined->SetDetectorMask(AliPIDResponse::kDetTPC+AliPIDResponse::kDetTOF); //fPIDCombined->SetPriorDistribution((AliPID::EParticleType)ispec,fPriors[ispec]); fCounter = new AliNormalizationCounter("NormalizationCounter"); fCounter->Init(); fCounterC = new AliNormalizationCounter("NormalizationCounterCorrMult"); fCounterC->SetStudyMultiplicity(kTRUE,1.); fCounterC->Init(); fListCounters = new TList(); fListCounters->SetOwner(); fListCounters->SetName("ListCounters"); fListCounters->Add(fCounter); fListCounters->Add(fCounterC); PostData(2, fListCounters); // weight function from ratio of flat value (1/30) to pythia // use to normalise to flat distribution (should lead to flat pT distribution) fFuncWeightPythia = new TF1("funcWeightPythia","1./(30. *[0]*x/TMath::Power(1.+(TMath::Power((x/[1]),[3])),[2]))", 0.15, 30); fFuncWeightPythia->SetParameters(0.36609, 1.94635, 1.40463,2.5); // weight function from the ratio of the LHC13d3 MC // and FONLL calculations for pp data //fFuncWeightFONLL5overLHC13d3 = new TF1("funcWeightFONLL5overLHC13d3","([0]*x)/TMath::Power([2],(1+TMath::Power([3],x/[1])))+[4]*TMath::Exp([5]+[6]*x)+[7]*TMath::Exp([8]*x)", 0.15, 30.); //fFuncWeightFONLL5overLHC13d3->SetParameters(2.94999e+00, 3.47032e+00, 2.81278e+00, 2.5, 1.93370e-02, 3.86865e+00, -1.54113e-01, 8.86944e-02, 2.56267e-02); //fFuncWeightFONLL5overLHC13d3Lc = new TF1("funcWeightFONLL5overLHC13d3Lc","([0]*x)/TMath::Power([2],(1+TMath::Power([3],x/[1])))+[4]*TMath::Exp([5]+[6]*x)+[7]*TMath::Exp([8]*x)", 0.15, 20.); //fFuncWeightFONLL5overLHC13d3Lc->SetParameters(5.94428e+01, 1.63585e+01, 9.65555e+00, 6.71944e+00, 8.88338e-02, 2.40477e+00, -4.88649e-02, -6.78599e-01, -2.10951e-01); //PostData(6, fOutputKF); PostData(7, fListWeight); if (!fFillTree) { Printf("Booking methods"); // creating the BDT and TMVA reader fVarsTMVA = new Float_t[fNVars]; fVarsTMVASpectators = new Float_t[fNVarsSpectators]; fReader = new TMVA::Reader( "!Color:!Silent" ); std::vector<std::string> inputNamesVec; TObjArray *tokens = fNamesTMVAVar.Tokenize(","); for(Int_t i = 0; i < tokens->GetEntries(); i++){ TString variable = ((TObjString*)(tokens->At(i)))->String(); std::string tmpvar = variable.Data(); inputNamesVec.push_back(tmpvar); if (fUseXmlWeightsFile || fUseXmlFileFromCVMFS) fReader->AddVariable(variable.Data(), &fVarsTMVA[i]); } delete tokens; TObjArray *tokensSpectators = fNamesTMVAVarSpectators.Tokenize(","); for(Int_t i = 0; i < tokensSpectators->GetEntries(); i++){ TString variable = ((TObjString*)(tokensSpectators->At(i)))->String(); if (fUseXmlWeightsFile || fUseXmlFileFromCVMFS) fReader->AddSpectator(variable.Data(), &fVarsTMVASpectators[i]); } delete tokensSpectators; if (fUseWeightsLibrary) { void* lib = dlopen(fTMVAlibName.Data(), RTLD_NOW); void* p = dlsym(lib, Form("%s", fTMVAlibPtBin.Data())); IClassifierReader* (*maker1)(std::vector<std::string>&) = (IClassifierReader* (*)(std::vector<std::string>&)) p; fBDTReader = maker1(inputNamesVec); } if (fUseXmlWeightsFile) fReader->BookMVA("BDT method", fXmlWeightsFile); if (fUseXmlFileFromCVMFS){ TString pathToFileCVMFS = AliDataFile::GetFileName(fXmlFileFromCVMFS.Data()); if (pathToFileCVMFS.IsNull()){ AliFatal("Cannot access data files from CVMFS"); } fReader->BookMVA("BDT method", pathToFileCVMFS); } } ftrackArraySelSoftPi = new TArrayI(10000); fhistMCSpectrumAccLc = new TH3F("fhistMCSpectrumAccLc", "fhistMCSpectrumAccLc", 250, 0, 50, 20, -0.5, 19.5, 2, 3.5, 5.5); // fhistMCSpectrumAccSc = new TH3F("fhistMCSpectrumAccSc", "fhistMCSpectrumAccSc", 250, 0, 50, 20, -0.5, 19.5, 2, 3.5, 5.5); // const Int_t nbinsAccLcFromSc = 6; Int_t binsAccLcFromSc[nbinsAccLcFromSc] = {250, 20, 2, 20, 250, 40}; Double_t lowedgesAccLcFromSc[nbinsAccLcFromSc] = {0, -0.5, 3.5, -1, 0, -2}; Double_t upedgesAccLcFromSc[nbinsAccLcFromSc] = {50, 19.5, 5.5, 1, 50, 2}; fhistMCSpectrumAccLcFromSc = new THnSparseF("fhistMCSpectrumAccLcFromSc", "fhistMCSpectrumAccLcFromSc; ptLc; codeLc; Qorigin; yLc; ptSc; ySc", nbinsAccLcFromSc, binsAccLcFromSc, lowedgesAccLcFromSc, upedgesAccLcFromSc); // Int_t nbinsSparseSigma[10] = {250, 400, 400, 20, 250, 2, 1, 200, 2, 2}; Double_t lowEdgesSigma[10] = {0, 0.130, 2.100, -1, 0, 3.5, 0.5, -1, 0, 0}; Double_t upEdgesSigma[10] = {25, 0.330, 2.500, 1, 25, 5.5, 1.5, 1, 2, 2}; if(!fFillTree) fhSparseAnalysisSigma = new THnSparseF("fhSparseAnalysisSigma", "fhSparseAnalysis; pt; deltamass; LcMass; CosThetaStarSoftPion; ptsigmac; checkorigin; isRotated; bdtresp; softPiITSrefit; isSigmacMC", 10, nbinsSparseSigma, lowEdgesSigma, upEdgesSigma); fOutputSparse = new TList(); fOutputSparse->SetOwner(); fOutputSparse->SetName("listOutputSparse"); fOutputSparse->Add(fhistMCSpectrumAccLc); fOutputSparse->Add(fhistMCSpectrumAccSc); fOutputSparse->Add(fhistMCSpectrumAccLcFromSc); if(fhSparseAnalysisSigma) fOutputSparse->Add(fhSparseAnalysisSigma); PostData(6, fOutputSparse); return; } //_________________________________________________ void AliAnalysisTaskSESigmacTopK0Spi::UserExec(Option_t *) { /// user exec if (!fInputEvent) { AliError("NO EVENT FOUND!"); return; } fCurrentEvent++; AliDebug(2, Form("Processing event = %d", fCurrentEvent)); AliAODEvent* aodEvent = dynamic_cast<AliAODEvent*>(fInputEvent); if(fAODProtection >= 0){ // Protection against different number of events in the AOD and deltaAOD // In case of discrepancy the event is rejected. Int_t matchingAODdeltaAODlevel = AliRDHFCuts::CheckMatchingAODdeltaAODevents(); if (matchingAODdeltaAODlevel < 0 || (matchingAODdeltaAODlevel == 0 && fAODProtection == 1)) { // AOD/deltaAOD trees have different number of entries || TProcessID do not match while it was required fHistoEvents->Fill(0); return; } fHistoEvents->Fill(1); } TClonesArray *arrayLctopKos=0; if (!aodEvent && AODEvent() && IsStandardAOD()) { // In case there is an AOD handler writing a standard AOD, use the AOD // event in memory rather than the input (ESD) event. aodEvent = dynamic_cast<AliAODEvent*> (AODEvent()); // in this case the braches in the deltaAOD (AliAOD.VertexingHF.root) // have to taken from the AOD event hold by the AliAODExtension AliAODHandler* aodHandler = (AliAODHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (aodHandler->GetExtensions()) { AliAODExtension *ext = (AliAODExtension*)aodHandler->GetExtensions()->FindObject("AliAOD.VertexingHF.root"); AliAODEvent *aodFromExt = ext->GetAOD(); arrayLctopKos = (TClonesArray*)aodFromExt->GetList()->FindObject("CascadesHF"); } } else { arrayLctopKos = (TClonesArray*)aodEvent->GetList()->FindObject("CascadesHF"); } if (!fUseMCInfo) { fAnalCuts->SetTriggerClass(""); fAnalCuts->SetTriggerMask(fTriggerMask); } Int_t runnumber = aodEvent->GetRunNumber(); if (aodEvent->GetTriggerMask() == 0 && (runnumber >= 195344 && runnumber <= 195677)){ AliDebug(3, "Event rejected because of null trigger mask"); return; } fCounter->StoreEvent(aodEvent, fAnalCuts, fUseMCInfo); // mc analysis TClonesArray *mcArray = 0; AliAODMCHeader *mcHeader = 0; // multiplicity definition with tracklets fNTracklets_1 = static_cast<Int_t>(AliVertexingHFUtils::GetNumberOfTrackletsInEtaRange(aodEvent, -1., 1.)); fNTracklets_All = static_cast<Int_t>(AliVertexingHFUtils::GetNumberOfTrackletsInEtaRange(aodEvent, -999., 999.)); if (fUseMCInfo) { // MC array need for matching mcArray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName())); if (!mcArray) { AliError("Could not find Monte-Carlo in AOD"); return; } // load MC header mcHeader = (AliAODMCHeader*)aodEvent->GetList()->FindObject(AliAODMCHeader::StdBranchName()); if (!mcHeader) { AliError("AliAnalysisTaskSESigmacTopK0Spi::UserExec: MC header branch not found!\n"); return; } Double_t zMCVertex = mcHeader->GetVtxZ(); if (TMath::Abs(zMCVertex) > fAnalCuts->GetMaxVtxZ()){ AliDebug(3, Form("z coordinate of MC vertex = %f, it was required to be within [-%f, +%f], skipping event", zMCVertex, fAnalCuts->GetMaxVtxZ(), fAnalCuts->GetMaxVtxZ())); return; } FillMCHisto(mcArray); LoopOverGenParticles(mcArray); } //centrality fCentrality = fAnalCuts->GetCentrality(aodEvent, AliRDHFCuts::kCentV0M); // AOD primary vertex fVtx1 = (AliAODVertex*)aodEvent->GetPrimaryVertex(); if (!fVtx1) { AliDebug(2, "No primary vertex found, returning"); return; } if (fVtx1->GetNContributors()<1) { AliDebug(2, "Number of contributors to vertex < 1, returning"); return; } Int_t fNTracklets_03=AliVertexingHFUtils::GetNumberOfTrackletsInEtaRange(aodEvent,-0.3,0.3); Int_t fNTracklets_05=AliVertexingHFUtils::GetNumberOfTrackletsInEtaRange(aodEvent,-0.5,0.5); Int_t fNTracklets_16=AliVertexingHFUtils::GetNumberOfTrackletsInEtaRange(aodEvent,-1.6,1.6); Int_t vzeroMult=0, vzeroMultA=0, vzeroMultC=0; Int_t vzeroMultEq=0, vzeroMultAEq=0, vzeroMultCEq=0; AliAODVZERO *vzeroAOD = (AliAODVZERO*)aodEvent->GetVZEROData(); if(vzeroAOD) { vzeroMultA = static_cast<Int_t>(vzeroAOD->GetMTotV0A()); vzeroMultC = static_cast<Int_t>(vzeroAOD->GetMTotV0C()); vzeroMult = vzeroMultA + vzeroMultC; vzeroMultAEq = static_cast<Int_t>(AliVertexingHFUtils::GetVZEROAEqualizedMultiplicity(aodEvent)); vzeroMultCEq = static_cast<Int_t>(AliVertexingHFUtils::GetVZEROCEqualizedMultiplicity(aodEvent)); vzeroMultEq = vzeroMultAEq + vzeroMultCEq; } Int_t countMult = fNTracklets_1; if(fMultiplicityEstimator==kNtrk03) { countMult = fNTracklets_03; } else if(fMultiplicityEstimator==kNtrk05) { countMult = fNTracklets_05; } else if(fMultiplicityEstimator==kNtrk10to16) { countMult = fNTracklets_16 - fNTracklets_1; } else if(fMultiplicityEstimator==kVZERO) { countMult = vzeroMult; } else if(fMultiplicityEstimator==kVZEROA) { countMult = vzeroMultA; } else if(fMultiplicityEstimator==kVZEROEq) { countMult = vzeroMultEq; } else if(fMultiplicityEstimator==kVZEROAEq) { countMult = vzeroMultAEq; } // Double_t countTreta1corr = fNTracklets_1; Double_t countCorr=countMult; if(fUseMultCorrection){ // In case of VZERO multiplicity, consider the zvtx correction flag // fDoVZER0ParamVertexCorr: 0= none, 1= usual d2h, 2=AliESDUtils Bool_t isDataDrivenZvtxCorr=kTRUE; Int_t vzeroMultACorr=vzeroMultA, vzeroMultCCorr=vzeroMultC, vzeroMultCorr=vzeroMult; Int_t vzeroMultAEqCorr=vzeroMultAEq, vzeroMultCEqCorr=vzeroMultCEq, vzeroMultEqCorr=vzeroMultEq; if( (fMultiplicityEstimator==kVZERO) || (fMultiplicityEstimator==kVZEROA) || (fMultiplicityEstimator==kVZEROEq) || (fMultiplicityEstimator==kVZEROAEq) ) { if(fDoVZER0ParamVertexCorr==0){ // do not correct isDataDrivenZvtxCorr=kFALSE; } else if (fDoVZER0ParamVertexCorr==2){ // use AliESDUtils correction Float_t zvtx = fVtx1->GetZ(); isDataDrivenZvtxCorr=kFALSE; vzeroMultACorr = static_cast<Int_t>(AliESDUtils::GetCorrV0A(vzeroMultA,zvtx)); vzeroMultCCorr = static_cast<Int_t>(AliESDUtils::GetCorrV0C(vzeroMultC,zvtx)); vzeroMultCorr = vzeroMultACorr + vzeroMultCCorr; vzeroMultAEqCorr = static_cast<Int_t>(AliESDUtils::GetCorrV0A(vzeroMultAEq,zvtx)); vzeroMultCEqCorr =static_cast<Int_t>( AliESDUtils::GetCorrV0C(vzeroMultCEq,zvtx)); vzeroMultEqCorr = vzeroMultAEqCorr + vzeroMultCEqCorr; if(fMultiplicityEstimator==kVZERO) { countCorr = vzeroMultCorr; } else if(fMultiplicityEstimator==kVZEROA) { countCorr = vzeroMultACorr; } else if(fMultiplicityEstimator==kVZEROEq) { countCorr = vzeroMultEqCorr; } else if(fMultiplicityEstimator==kVZEROAEq) { countCorr = vzeroMultAEqCorr; } } } if(isDataDrivenZvtxCorr){ TProfile* estimatorAvg = GetEstimatorHistogram(aodEvent); if(estimatorAvg){ // countTreta1corr = static_cast<Int_t>(AliVertexingHFUtils::GetCorrectedNtracklets(estimatorAvg,fNTracklets_1,vtx1->GetZ(),fRefMult)); countCorr = static_cast<Int_t>(AliVertexingHFUtils::GetCorrectedNtracklets(estimatorAvg,countMult,fVtx1->GetZ(),fRefMult)); } } } fCounterC->StoreEvent(aodEvent, fAnalCuts, fUseMCInfo,countCorr); Bool_t isSelectedMultCut = kTRUE; if(fUseMultiplicityCut){ // Multiplicity cut used if(countCorr >= fMultiplicityCutMin && countCorr < fMultiplicityCutMax){ // Within multiplicity range fHistoEvents->Fill(5); } else{ // Outside multiplicity range isSelectedMultCut = kFALSE; } } fIsEventSelected = fAnalCuts->IsEventSelected(aodEvent); if ( !fIsEventSelected || !isSelectedMultCut) { fHistoEvents->Fill(2); return; // don't take into account not selected events } // check on the timestamp AliVHeader* h = aodEvent->GetHeader(); UInt_t timestamp = h->GetTimeStamp(); //Printf("timestamp = %d, cut = %u", timestamp, fTimestampCut); if (fTimestampCut != 0) { //Printf("timestamp = %d, cut = %u", timestamp, fTimestampCut); if (timestamp > fTimestampCut) { fHistoEvents->Fill(3); return; } } fHistoEvents->Fill(4); fHistoTracklets_1->Fill(fNTracklets_1); fHistoTracklets_All->Fill(fNTracklets_All); fHistoTracklets_1_cent->Fill(fCentrality, fNTracklets_1); fHistoTracklets_All_cent->Fill(fCentrality, fNTracklets_All); fHistoCentrality->Fill(fCentrality); if(fUseMultCorrection){ fHistoNtrUnCorr->Fill(countMult); fHistoNtrCorr->Fill(countCorr); fHistoVzVsNtrUnCorr->Fill(fVtx1->GetZ(),countMult); fHistoVzVsNtrCorr->Fill(fVtx1->GetZ(),countCorr); } //Setting magnetic field for KF vertexing fBField = aodEvent->GetMagneticField(); AliKFParticle::SetField(fBField); PrepareTracks(aodEvent); //needed for SigmaC loop Int_t nSelectedAnal = 0; if (fIsK0sAnalysis) { MakeAnalysisForLc2prK0S(aodEvent, arrayLctopKos, mcArray, nSelectedAnal, fAnalCuts, mcHeader); } fCounter->StoreCandidates(aodEvent, nSelectedAnal, kFALSE); Double_t nchWeight = 1.; if (fNTracklets_1 > 0) { if(!fHistoMCNch) AliInfo("Input histos to evaluate Nch weights missing"); if(fHistoMCNch) nchWeight *= fHistoMCNch->GetBinContent(fHistoMCNch->FindBin(fNTracklets_1)); } PostData(1, fOutput); PostData(2, fListCounters); PostData(4, fVariablesTreeSgn); PostData(5, fVariablesTreeBkg); PostData(6, fOutputSparse); PostData(7, fListWeight); } //------------------------------------------------------------------------------- void AliAnalysisTaskSESigmacTopK0Spi::FillMCHisto(TClonesArray *mcArray){ /// method to fill MC histo: how many Lc --> K0S + p are there at MC level for (Int_t iPart = 0; iPart < mcArray->GetEntriesFast(); iPart++) { AliAODMCParticle* mcPart = dynamic_cast<AliAODMCParticle*>(mcArray->At(iPart)); if (!mcPart){ AliError("Failed casting particle from MC array!, Skipping particle"); continue; } Int_t pdg = mcPart->GetPdgCode(); if (TMath::Abs(pdg) != 4122){ AliDebug(2, Form("MC particle %d is not a Lc: its pdg code is %d", iPart, pdg)); continue; } AliDebug(2, Form("Step 0 ok: MC particle %d is a Lc: its pdg code is %d", iPart, pdg)); Int_t labeldaugh0 = mcPart->GetDaughterLabel(0); Int_t labeldaugh1 = mcPart->GetDaughterLabel(1); if (labeldaugh0 <= 0 || labeldaugh1 <= 0){ AliDebug(2, Form("The MC particle doesn't have correct daughters, skipping!!")); continue; } else if (labeldaugh1 - labeldaugh0 == 1){ AliDebug(2, Form("Step 1 ok: The MC particle has correct daughters!!")); AliAODMCParticle* daugh0 = dynamic_cast<AliAODMCParticle*>(mcArray->At(labeldaugh0)); AliAODMCParticle* daugh1 = dynamic_cast<AliAODMCParticle*>(mcArray->At(labeldaugh1)); if(!daugh0 || !daugh1){ AliDebug(2,"Particle daughters not properly retrieved!"); return; } Int_t pdgCodeDaugh0 = TMath::Abs(daugh0->GetPdgCode()); Int_t pdgCodeDaugh1 = TMath::Abs(daugh1->GetPdgCode()); AliAODMCParticle* bachelorMC = daugh0; AliAODMCParticle* v0MC = daugh1; AliDebug(2, Form("pdgCodeDaugh0 = %d, pdgCodeDaugh1 = %d", pdgCodeDaugh0, pdgCodeDaugh1)); if ((pdgCodeDaugh0 == 311 && pdgCodeDaugh1 == 2212) || (pdgCodeDaugh0 == 2212 && pdgCodeDaugh1 == 311)){ // we are in the case of Lc --> K0 + p; now we have to check if the K0 decays in K0S, and if this goes in pi+pi- /// first, we set the bachelor and the v0: above we assumed first proton and second V0, but we could have to change it: if (pdgCodeDaugh0 == 311 && pdgCodeDaugh1 == 2212) { bachelorMC = daugh1; v0MC = daugh0; } AliDebug(2, Form("Number of Daughters of v0 = %d", v0MC->GetNDaughters())); if (v0MC->GetNDaughters() != 1) { AliDebug(2, "The K0 does not decay in 1 body only! Impossible... Continuing..."); continue; } else { // So far: Lc --> K0 + p, K0 with 1 daughter AliDebug(2, "Step 2 ok: The K0 does decay in 1 body only! "); Int_t labelK0daugh = v0MC->GetDaughterLabel(0); AliAODMCParticle* partK0S = dynamic_cast<AliAODMCParticle*>(mcArray->At(labelK0daugh)); if(!partK0S){ AliError("Error while casting particle! returning a NULL array"); continue; } else { // So far: Lc --> K0 + p, K0 with 1 daughter that we can access if (partK0S->GetNDaughters() != 2 || TMath::Abs(partK0S->GetPdgCode() != 310)){ AliDebug(2, "The K0 daughter is not a K0S or does not decay in 2 bodies"); continue; } else { // So far: Lc --> K0 + p, K0 --> K0S, K0S in 2 bodies AliDebug(2, "Step 3 ok: The K0 daughter is a K0S and does decay in 2 bodies"); Int_t labelK0Sdaugh0 = partK0S->GetDaughterLabel(0); Int_t labelK0Sdaugh1 = partK0S->GetDaughterLabel(1); AliAODMCParticle* daughK0S0 = dynamic_cast<AliAODMCParticle*>(mcArray->At(labelK0Sdaugh0)); AliAODMCParticle* daughK0S1 = dynamic_cast<AliAODMCParticle*>(mcArray->At(labelK0Sdaugh1)); if (!daughK0S0 || ! daughK0S1){ AliDebug(2, "Could not access K0S daughters, continuing..."); continue; } else { // So far: Lc --> K0 + p, K0 --> K0S, K0S in 2 bodies that we can access AliDebug(2, "Step 4 ok: Could access K0S daughters, continuing..."); Int_t pdgK0Sdaugh0 = daughK0S0->GetPdgCode(); Int_t pdgK0Sdaugh1 = daughK0S1->GetPdgCode(); if (TMath::Abs(pdgK0Sdaugh0) != 211 || TMath::Abs(pdgK0Sdaugh1) != 211){ AliDebug(2, "The K0S does not decay in pi+pi-, continuing"); //AliInfo("The K0S does not decay in pi+pi-, continuing"); } else { // Full chain: Lc --> K0 + p, K0 --> K0S, K0S --> pi+pi- if (fAnalCuts->IsInFiducialAcceptance(mcPart->Pt(), mcPart->Y())) { AliDebug(2, Form("----> Filling histo with pt = %f", mcPart->Pt())); if(TMath::Abs(mcPart->Y()) < 0.5) fHistoMCLcK0SpGenLimAcc->Fill(mcPart->Pt()); //AliInfo(Form("\nparticle = %d, Filling MC Gen histo\n", iPart)); fHistoMCLcK0SpGen->Fill(mcPart->Pt()); if(!(TMath::Abs(bachelorMC->Eta()) > 0.9 || bachelorMC->Pt() < 0.1 || TMath::Abs(daughK0S0->Eta()) > 0.9 || daughK0S0->Pt() < 0.1 || TMath::Abs(daughK0S1->Eta()) > 0.9 || daughK0S1->Pt() < 0.1)) { fHistoMCLcK0SpGenAcc->Fill(mcPart->Pt()); } } else { AliDebug(2, "not in fiducial acceptance! Skipping"); continue; } } } } } } } } } // closing loop over mcArray return; } //------------------------------------------------------------------------------- void AliAnalysisTaskSESigmacTopK0Spi::MakeAnalysisForLc2prK0S(AliAODEvent *aodEvent, TClonesArray *arrayLctopKos, TClonesArray *mcArray, Int_t &nSelectedAnal, AliRDHFCutsLctoV0 *cutsAnal, AliAODMCHeader* aodheader){ /// Lc prong needed to MatchToMC method Int_t pdgCand = 4122; Int_t pdgDgLctoV0bachelor[2] = {2212, 310}; Int_t pdgDgV0toDaughters[2] = {211, 211}; // loop to search for candidates Lc->K0sp Int_t nCascades= arrayLctopKos->GetEntriesFast(); // loop over cascades to search for candidates Lc->p+K0S Int_t mcLabel = -1; AliAnalysisVertexingHF *vHF = new AliAnalysisVertexingHF(); for (Int_t iLctopK0s = 0; iLctopK0s < nCascades; iLctopK0s++) { // Lc candidates and K0s from Lc AliAODRecoCascadeHF* lcK0spr = dynamic_cast<AliAODRecoCascadeHF*>(arrayLctopKos->At(iLctopK0s)); if (!lcK0spr) { AliDebug(2, Form("Cascade %d doens't exist, skipping",iLctopK0s)); continue; } if (!(lcK0spr->CheckCascadeFlags())) { AliDebug(2, Form("Cascade %d is not flagged as Lc candidate",iLctopK0s)); continue; } // use Preselect to filter out the tracks according to the pT if (cutsAnal->GetUsePreselect()){ TObjArray arrTracks(2); for(Int_t ipr = 0; ipr < 2; ipr++){ AliAODTrack *tr; if (ipr == 0) tr = vHF->GetProng(aodEvent, lcK0spr, ipr); else tr = (AliAODTrack*)(aodEvent->GetV0(lcK0spr->GetProngID(1))); arrTracks.AddAt(tr, ipr); } Int_t preSelectLc = cutsAnal->PreSelect(arrTracks); if (preSelectLc == 0) continue; } if(!vHF->FillRecoCasc(aodEvent, lcK0spr, kFALSE)){ //Fill the data members of the candidate only if they are empty. continue; } //if (!(vHF->RecoSecondaryVertexForCascades(aodEvent, lcK0spr))) continue; if (!lcK0spr->GetSecondaryVtx()) { AliInfo("No secondary vertex"); continue; } if (lcK0spr->GetNDaughters()!=2) { AliDebug(2, Form("Cascade %d has not 2 daughters (nDaughters=%d)", iLctopK0s, lcK0spr->GetNDaughters())); continue; } AliAODv0 * v0part = dynamic_cast<AliAODv0*>(lcK0spr->Getv0()); AliAODTrack * bachPart = dynamic_cast<AliAODTrack*>(lcK0spr->GetBachelor()); if (!v0part || !bachPart) { AliDebug(2, Form("Cascade %d has no V0 or no bachelor object", iLctopK0s)); continue; } if (!v0part->GetSecondaryVtx()) { AliDebug(2, Form("No secondary vertex for V0 by cascade %d", iLctopK0s)); continue; } if (v0part->GetNDaughters()!=2) { AliDebug(2, Form("current V0 has not 2 daughters (onTheFly=%d, nDaughters=%d)", v0part->GetOnFlyStatus(), v0part->GetNDaughters())); continue; } AliAODTrack * v0Pos = dynamic_cast<AliAODTrack*>(lcK0spr->Getv0PositiveTrack()); AliAODTrack * v0Neg = dynamic_cast<AliAODTrack*>(lcK0spr->Getv0NegativeTrack()); if (!v0Neg || !v0Pos) { AliDebug(2, Form("V0 by cascade %d has no V0positive of V0negative object", iLctopK0s)); continue; } if (v0Pos->Charge() == v0Neg->Charge()) { AliDebug(2, Form("V0 by cascade %d has daughters with the same sign: IMPOSSIBLE!", iLctopK0s)); continue; } //Filling a control histogram with no cuts if (fUseMCInfo) { Int_t pdgCode=-2; // find associated MC particle for Lc -> p+K0 and K0S->pi+pi fmcLabelLc = lcK0spr->MatchToMC(pdgCand, pdgDgLctoV0bachelor[1], pdgDgLctoV0bachelor, pdgDgV0toDaughters, mcArray, kTRUE); //if (fmcLabelLc>=0) { if (fmcLabelLc != -1) { AliDebug(2, Form("----> cascade number %d (total cascade number = %d) is a Lc!", iLctopK0s, nCascades)); AliAODMCParticle *partLc = dynamic_cast<AliAODMCParticle*>(mcArray->At(fmcLabelLc)); if(partLc){ pdgCode = partLc->GetPdgCode(); if (pdgCode<0) AliDebug(2,Form(" ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ MClabel=%d ~~~~~~~~~~ pdgCode=%d", fmcLabelLc, pdgCode)); pdgCode = TMath::Abs(pdgCode); fHistoLcBeforeCuts->Fill(1); } } else { fHistoLcBeforeCuts->Fill(0); pdgCode = -1; } } Int_t isLc = 0; if (fUseMCInfo) { Int_t pdgCode = -2; // find associated MC particle for Lc -> p+K0 and K0S->pi+pi mcLabel = lcK0spr->MatchToMC(pdgCand, pdgDgLctoV0bachelor[1], pdgDgLctoV0bachelor, pdgDgV0toDaughters, mcArray, kTRUE); if (mcLabel >= 0) { AliDebug(2, Form(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~cascade number %d (total cascade number = %d)", iLctopK0s, nCascades)); AliAODMCParticle *partLc = dynamic_cast<AliAODMCParticle*>(mcArray->At(mcLabel)); if(partLc){ pdgCode = partLc->GetPdgCode(); if (pdgCode < 0) AliDebug(2, Form(" ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ MClabel=%d ~~~~~~~~~~ pdgCode=%d", mcLabel, pdgCode)); pdgCode = TMath::Abs(pdgCode); isLc = 1; fHistoLc->Fill(1); } } else { fHistoLc->Fill(0); pdgCode = -1; } } AliDebug(2, Form("\n\n\n Analysing candidate %d\n", iLctopK0s)); AliDebug(2, Form(">>>>>>>>>> Candidate is background, fFillOnlySgn = %d --> SKIPPING", fFillOnlySgn)); if (!isLc) { if (fFillOnlySgn) { // if it is background, and we want only signal, we do not fill the tree continue; } else { // checking if we want to fill the background if (fKeepingOnlyHIJINGBkg){ // we have decided to fill the background only when the candidate has the daugthers that all come from HIJING underlying event! Bool_t isCandidateInjected = fUtils->HasCascadeCandidateAnyDaughInjected(lcK0spr, aodheader, mcArray); if (!isCandidateInjected){ AliDebug(2, "The candidate is from HIJING (i.e. not injected), keeping it to fill background"); fHistoBackground->Fill(1); } else { AliDebug(2, "The candidate is NOT from HIJING, we skip it when filling background"); fHistoBackground->Fill(0); continue; } } else if (fKeepingOnlyPYTHIABkg){ // we have decided to fill the background only when the candidate has the daugthers that all come from PYTHIA underlying event! AliAODTrack *bachelor = (AliAODTrack*)lcK0spr->GetBachelor(); AliAODTrack *v0pos = (AliAODTrack*)lcK0spr->Getv0PositiveTrack(); AliAODTrack *v0neg = (AliAODTrack*)lcK0spr->Getv0NegativeTrack(); if (!bachelor || !v0pos || !v0neg) { AliDebug(2, "Cannot retrieve one of the tracks while checking origin, continuing"); continue; } else { Int_t labelbachelor = TMath::Abs(bachelor->GetLabel()); Int_t labelv0pos = TMath::Abs(v0pos->GetLabel()); Int_t labelv0neg = TMath::Abs(v0neg->GetLabel()); AliAODMCParticle* MCbachelor = (AliAODMCParticle*)mcArray->At(labelbachelor); AliAODMCParticle* MCv0pos = (AliAODMCParticle*)mcArray->At(labelv0pos); AliAODMCParticle* MCv0neg = (AliAODMCParticle*)mcArray->At(labelv0neg); if (!MCbachelor || !MCv0pos || !MCv0neg) { AliDebug(2, "Cannot retrieve MC particle for one of the tracks while checking origin, continuing"); continue; } else { Int_t isBachelorFromPythia = fUtils->CheckOrigin(mcArray, MCbachelor, kTRUE); Int_t isv0posFromPythia = fUtils->CheckOrigin(mcArray, MCv0pos, kTRUE); Int_t isv0negFromPythia = fUtils->CheckOrigin(mcArray, MCv0neg, kTRUE); if (isBachelorFromPythia != 0 && isv0posFromPythia != 0 && isv0negFromPythia != 0){ AliDebug(2, "The candidate is from PYTHIA (i.e. all daughters originate from a quark), keeping it to fill background"); fHistoBackground->Fill(2); } else { AliDebug(2, "The candidate is NOT from PYTHIA, we skip it when filling background"); fHistoBackground->Fill(3); continue; } } } } } } //FillLc2pK0Sspectrum(lcK0spr, isLc, nSelectedAnal, cutsAnal, mcArray, iLctopK0s); //FillLc2pK0Sspectrum(lcK0spr, isLc, nSelectedAnal, cutsAnal, mcArray, mcLabel); FillLc2pK0Sspectrum(lcK0spr, isLc, nSelectedAnal, cutsAnal, mcArray, mcLabel, aodEvent); } delete vHF; return; } //________________________________________________________________________ void AliAnalysisTaskSESigmacTopK0Spi::FillLc2pK0Sspectrum(AliAODRecoCascadeHF *part, Int_t isLc, Int_t &nSelectedAnal, AliRDHFCutsLctoV0 *cutsAnal, TClonesArray *mcArray, Int_t iLctopK0s, AliAODEvent *aod){ // /// Fill histos for Lc -> K0S+proton // /* if (!part->GetOwnPrimaryVtx()) { //Printf("No primary vertex for Lc found!!"); part->SetOwnPrimaryVtx(fVtx1); } else { //Printf("Yu-huuuu!!! primary vertex for Lc found!!"); } */ Double_t invmassLc = part->InvMassLctoK0sP(); AliAODv0 * v0part = part->Getv0(); Bool_t onFlyV0 = v0part->GetOnFlyStatus(); // on-the-flight V0s if (onFlyV0){ // on-the-fly V0 if (isLc) { // Lc fHistoLcOnTheFly->Fill(2.); } else { // not Lc fHistoLcOnTheFly->Fill(0.); } } else { // offline V0 if (isLc) { // Lc fHistoLcOnTheFly->Fill(3.); } else { // not Lc fHistoLcOnTheFly->Fill(1.); } } Double_t dcaV0 = v0part->GetDCA(); Double_t invmassK0s = v0part->MassK0Short(); if ( (cutsAnal->IsInFiducialAcceptance(part->Pt(), part->Y(4122))) ) { if (isLc) { fHistoFiducialAcceptance->Fill(3.); } else { fHistoFiducialAcceptance->Fill(1.); } } else { if (isLc) { fHistoFiducialAcceptance->Fill(2.); } else { fHistoFiducialAcceptance->Fill(0.); } } Int_t isInV0window = (((cutsAnal->IsSelectedSingleCut(part, AliRDHFCuts::kCandidate, 2, aod)) & (AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr)); // cut on V0 invMass if (isInV0window == 0) { AliDebug(2, "No: The candidate has NOT passed the V0 window cuts!"); if (isLc) AliDebug(2, "SIGNAL candidate rejected: V0 window cuts"); return; } else AliDebug(2, "Yes: The candidate has passed the mass cuts!"); Bool_t isInCascadeWindow = (((cutsAnal->IsSelectedSingleCut(part, AliRDHFCuts::kCandidate, 0, aod)) & (AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr)); // cut on Lc->p+K0S invMass if (!isInCascadeWindow) { AliDebug(2, "No: The candidate has NOT passed the cascade window cuts!"); if (isLc) AliDebug(2, "SIGNAL candidate rejected: cascade window cuts"); return; } else AliDebug(2, "Yes: The candidate has passed the cascade window cuts!"); Bool_t isCandidateSelectedCuts = (((cutsAnal->IsSelected(part, AliRDHFCuts::kCandidate, aod)) & (AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr)); // kinematic/topological cuts AliDebug(2, Form("recoAnalysisCuts = %d", cutsAnal->IsSelected(part, AliRDHFCuts::kCandidate, aod) & (AliRDHFCutsLctoV0::kLcToK0Spr))); if (!isCandidateSelectedCuts){ AliDebug(2, "No: Analysis cuts kCandidate level NOT passed"); if (isLc) AliDebug(2, "SIGNAL candidate rejected"); return; } else { AliDebug(2, "Yes: Analysis cuts kCandidate level passed"); } AliAODTrack *bachelor = (AliAODTrack*)part->GetBachelor(); if (!bachelor) { AliDebug(2, Form("Very weird, the bachelor is not there... returning for this candidate")); return; } //Bool_t isBachelorID = (((cutsAnal->IsSelected(part,AliRDHFCuts::kPID, aod))&(AliRDHFCutsLctoV0::kLcToK0Spr))==(AliRDHFCutsLctoV0::kLcToK0Spr)); // ID x bachelor Double_t probTPCTOF[AliPID::kSPECIES] = {-1.}; UInt_t detUsed = fPIDCombined->ComputeProbabilities(bachelor, fPIDResponse, probTPCTOF); AliDebug(2, Form("detUsed (TPCTOF case) = %d", detUsed)); Double_t probProton = -1.; // Double_t probPion = -1.; // Double_t probKaon = -1.; if (detUsed == (UInt_t)fPIDCombined->GetDetectorMask() ) { AliDebug(2, Form("We have found the detector mask for TOF + TPC: probProton will be set to %f", probTPCTOF[AliPID::kProton])); probProton = probTPCTOF[AliPID::kProton]; // probPion = probTPCTOF[AliPID::kPion]; // probKaon = probTPCTOF[AliPID::kKaon]; } else { // if you don't have both TOF and TPC, try only TPC fPIDCombined->SetDetectorMask(AliPIDResponse::kDetTPC); AliDebug(2, "We did not find the detector mask for TOF + TPC, let's see only TPC"); detUsed = fPIDCombined->ComputeProbabilities(bachelor, fPIDResponse, probTPCTOF); AliDebug(2, Form(" detUsed (TPC case) = %d", detUsed)); if (detUsed == (UInt_t)fPIDCombined->GetDetectorMask()) { probProton = probTPCTOF[AliPID::kProton]; // probPion = probTPCTOF[AliPID::kPion]; // probKaon = probTPCTOF[AliPID::kKaon]; AliDebug(2, Form("TPC only worked: probProton will be set to %f", probTPCTOF[AliPID::kProton])); } else { AliDebug(2, "Only TPC did not work..."); } // resetting mask to ask for both TPC+TOF fPIDCombined->SetDetectorMask(AliPIDResponse::kDetTPC+AliPIDResponse::kDetTOF); } AliDebug(2, Form("probProton = %f", probProton)); // now we get the TPC and TOF single PID probabilities (only for Proton, or the tree will explode :) ) Double_t probProtonTPC = -1.; Double_t probProtonTOF = -1.; Double_t pidTPC[AliPID::kSPECIES]={-1.}; Double_t pidTOF[AliPID::kSPECIES]={-1.}; Int_t respTPC = fPIDResponse->ComputePIDProbability(AliPIDResponse::kDetTPC, bachelor, AliPID::kSPECIES, pidTPC); Int_t respTOF = fPIDResponse->ComputePIDProbability(AliPIDResponse::kDetTOF, bachelor, AliPID::kSPECIES, pidTOF); if (respTPC == AliPIDResponse::kDetPidOk) probProtonTPC = pidTPC[AliPID::kProton]; if (respTOF == AliPIDResponse::kDetPidOk) probProtonTOF = pidTOF[AliPID::kProton]; // checking V0 status (on-the-fly vs offline) if ( !( !onFlyV0 || (onFlyV0 && fUseOnTheFlyV0) ) ) { AliDebug(2, "On-the-fly discarded"); return; } if ( (((cutsAnal->IsSelected(part,AliRDHFCuts::kAll, aod)) & (AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr)) ) { nSelectedAnal++; } if ( !(cutsAnal->IsInFiducialAcceptance(part->Pt(), part->Y(4122))) ) return; if ( !( ( (cutsAnal->IsSelected(part, AliRDHFCuts::kTracks, aod)) & (AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) ) { // esd track cuts if (isLc) AliDebug(2, "SIGNAL candidate rejected"); AliDebug(2, "No: Analysis cuts kTracks level NOT passed"); return; } else { AliDebug(2, "Yes: Analysis cuts kTracks level passed"); } Int_t pdgCand = 4122; Int_t pdgDgLctoV0bachelor[2] = {211, 3122}; // case of wrong decay! Lc --> L + pi Int_t pdgDgV0toDaughters[2] = {2212, 211}; // case of wrong decay! Lc --> L + pi Int_t isLc2LBarpi = 0, isLc2Lpi = 0; Int_t currentLabel = part->GetLabel(); Int_t mcLabel = 0; if (fUseMCInfo) { mcLabel = part->MatchToMC(pdgCand, pdgDgLctoV0bachelor[1], pdgDgLctoV0bachelor, pdgDgV0toDaughters, mcArray, kTRUE); if (mcLabel >= 0) { if (bachelor->Charge() == -1) isLc2LBarpi=1; if (bachelor->Charge() == +1) isLc2Lpi=1; } } Int_t pdgDg2prong[2] = {211, 211}; Int_t labelK0S = 0; Int_t isK0S = 0; if (fUseMCInfo) { labelK0S = v0part->MatchToMC(310, mcArray, 2, pdgDg2prong); if (labelK0S>=0) isK0S = 1; } pdgDg2prong[0] = 211; pdgDg2prong[1] = 2212; Int_t isLambda = 0; Int_t isLambdaBar = 0; Int_t lambdaLabel = 0; if (fUseMCInfo) { lambdaLabel = v0part->MatchToMC(3122, mcArray, 2, pdgDg2prong); if (lambdaLabel >= 0) { AliAODMCParticle *lambdaTrack = (AliAODMCParticle*)mcArray->At(lambdaLabel); if (lambdaTrack->GetPdgCode() == 3122) isLambda = 1; else if (lambdaTrack->GetPdgCode() == -3122) isLambdaBar = 1; } } pdgDg2prong[0] = 11; pdgDg2prong[1] = 11; Int_t isGamma = 0; Int_t gammaLabel = 0; if (fUseMCInfo) { gammaLabel = v0part->MatchToMC(22, mcArray, 2, pdgDg2prong); if (gammaLabel>=0) { AliAODMCParticle *gammaTrack = (AliAODMCParticle*)mcArray->At(gammaLabel); if (gammaTrack->GetPdgCode() == 22) isGamma = 1; } } Int_t pdgTemp = -1; if (currentLabel != -1){ AliAODMCParticle *tempPart = (AliAODMCParticle*)mcArray->At(currentLabel); pdgTemp = tempPart->GetPdgCode(); } if (isLc) AliDebug(2, Form("Signal: Candidate is a Lc in K0s+p")); else if (isLc2LBarpi) AliDebug(2, Form("Background: Candidate is a Lc in Lbar + pi")); else if (isLc2Lpi) AliDebug(2, Form("Background: Candidate is a Lc in L + pi")); else AliDebug(2, Form("Pure bkg: Candidate has pdg = %d", pdgTemp)); if (isK0S) AliDebug(2, Form("V0 is a K0S")); else if (isLambda) AliDebug(2, Form("V0 is a Lambda")); else if (isLambdaBar) AliDebug(2, Form("V0 is a LambdaBar")); else if (isGamma) AliDebug(2, Form("V0 is a Gamma")); //else AliDebug(2, Form("V0 is something else!!")); Double_t invmassLc2Lpi = part->InvMassLctoLambdaPi(); Double_t invmassLambda = v0part->MassLambda(); Double_t invmassLambdaBar = v0part->MassAntiLambda(); //Double_t nSigmaITSpr = -999.; Double_t nSigmaTPCpr = -999.; Double_t nSigmaTOFpr = -999.; //Double_t nSigmaITSpi = -999.; Double_t nSigmaTPCpi = -999.; Double_t nSigmaTOFpi = -999.; //Double_t nSigmaITSka = -999.; Double_t nSigmaTPCka = -999.; Double_t nSigmaTOFka = -999.; /* cutsAnal->GetPidHF()->GetnSigmaITS(bachelor, 4, nSigmaITSpr); cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor, 4, nSigmaTPCpr); cutsAnal->GetPidHF()->GetnSigmaTOF(bachelor, 4, nSigmaTOFpr); cutsAnal->GetPidHF()->GetnSigmaITS(bachelor, 2, nSigmaITSpi); cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor, 2, nSigmaTPCpi); cutsAnal->GetPidHF()->GetnSigmaTOF(bachelor, 2, nSigmaTOFpi); cutsAnal->GetPidHF()->GetnSigmaITS(bachelor, 3, nSigmaITSka); cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor, 3, nSigmaTPCka); cutsAnal->GetPidHF()->GetnSigmaTOF(bachelor, 3, nSigmaTOFka); */ if (fUsePIDresponseForNsigma) { nSigmaTPCpi = fPIDResponse->NumberOfSigmasTPC(bachelor, (AliPID::kPion)); nSigmaTPCka = fPIDResponse->NumberOfSigmasTPC(bachelor, (AliPID::kKaon)); nSigmaTPCpr = fPIDResponse->NumberOfSigmasTPC(bachelor, (AliPID::kProton)); nSigmaTOFpi = fPIDResponse->NumberOfSigmasTOF(bachelor, (AliPID::kPion)); nSigmaTOFka = fPIDResponse->NumberOfSigmasTOF(bachelor, (AliPID::kKaon)); nSigmaTOFpr = fPIDResponse->NumberOfSigmasTOF(bachelor, (AliPID::kProton)); } else { cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor, (AliPID::kPion), nSigmaTPCpi); cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor, (AliPID::kKaon), nSigmaTPCka); cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor, (AliPID::kProton), nSigmaTPCpr); cutsAnal->GetPidHF()->GetnSigmaTOF(bachelor, (AliPID::kPion), nSigmaTOFpi); cutsAnal->GetPidHF()->GetnSigmaTOF(bachelor, (AliPID::kKaon), nSigmaTOFka); cutsAnal->GetPidHF()->GetnSigmaTOF(bachelor, (AliPID::kProton), nSigmaTOFpr); } Double_t ptLcMC = -1; Double_t weightPythia = -1, weight5LHC13d3 = -1, weight5LHC13d3Lc = -1; AliAODMCParticle *partLcMC = 0x0; if (fUseMCInfo) { if (iLctopK0s >= 0) { partLcMC = (AliAODMCParticle*)mcArray->At(iLctopK0s); ptLcMC = partLcMC->Pt(); //Printf("--------------------- Reco pt = %f, MC particle pt = %f", part->Pt(), ptLcMC); weightPythia = fFuncWeightPythia->Eval(ptLcMC); //weight5LHC13d3 = fFuncWeightFONLL5overLHC13d3->Eval(ptLcMC); //weight5LHC13d3Lc = fFuncWeightFONLL5overLHC13d3Lc->Eval(ptLcMC); } } Double_t weightNch = 1; if (fUseMCInfo) { //Int_t nChargedMCPhysicalPrimary=AliVertexingHFUtils::GetGeneratedPhysicalPrimariesInEtaRange(mcArray,-1.0,1.0); // if(nChargedMCPhysicalPrimary > 0) if(fNTracklets_1 > 0){ if(!fHistoMCNch) AliDebug(2, "Input histos to evaluate Nch weights missing"); if(fHistoMCNch) weightNch *= fHistoMCNch->GetBinContent(fHistoMCNch->FindBin(fNTracklets_1)); } } // Fill candidate variable Tree (track selection, V0 invMass selection) // if (!onFlyV0 && isInV0window && isInCascadeWindow && part->CosV0PointingAngle()>0.99 && TMath::Abs(nSigmaTPCpr) <= 3 && // TMath::Abs(nSigmaTOFpr) <= 3 && v0part->Getd0Prong(0) < 20 && v0part->Getd0Prong(1) < 20) { if (!onFlyV0 && isInV0window && isInCascadeWindow){ EBachelor bachCode = kBachInvalid; EK0S k0SCode = kK0SInvalid; if (fUseMCInfo) { bachCode = CheckBachelor(part, bachelor, mcArray); k0SCode = CheckK0S(part, v0part, mcArray); } AliAODTrack *v0pos = (AliAODTrack*)part->Getv0PositiveTrack(); AliAODTrack *v0neg = (AliAODTrack*)part->Getv0NegativeTrack(); //Int_t kfResult; TVector3 mom1(bachelor->Px(), bachelor->Py(), bachelor->Pz()); TVector3 mom2(v0part->Px(), v0part->Py(), v0part->Pz()); TVector3 momTot(part->Px(), part->Py(), part->Pz()); Double_t Ql1 = mom1.Dot(momTot)/momTot.Mag(); Double_t Ql2 = mom2.Dot(momTot)/momTot.Mag(); Double_t alphaArmLc = (Ql1 - Ql2)/(Ql1 + Ql2); Double_t alphaArmLcCharge = ( bachelor->Charge() > 0 ? (Ql1 - Ql2)/(Ql1 + Ql2) : (Ql2 - Ql1)/(Ql1 + Ql2) ); Double_t ptArmLc = mom1.Perp(momTot); Double_t massK0SPDG = TDatabasePDG::Instance()->GetParticle(310)->Mass(); // mass K0S PDG Double_t massPrPDG = TDatabasePDG::Instance()->GetParticle(2212)->Mass(); // mass Proton PDG Double_t massLcPDG = TDatabasePDG::Instance()->GetParticle(4122)->Mass(); // mass Lc PDG // Cosine of proton emission angle (theta*) in the rest frame of the mother particle // for prong ip (0 or 1) with mass hypotheses massLcPDG for mother particle (from AliAODRecoDecay) Double_t pStar = TMath::Sqrt((massLcPDG*massLcPDG - massPrPDG*massPrPDG - massK0SPDG*massK0SPDG)*(massLcPDG*massLcPDG - massPrPDG*massPrPDG - massK0SPDG*massK0SPDG) - 4.*massPrPDG*massPrPDG*massK0SPDG*massK0SPDG)/(2.*massLcPDG); Double_t e = part->E(4122); Double_t beta = part->P()/e; Double_t gamma = e/massLcPDG; //Double_t cts = (Ql1/gamma-beta*TMath::Sqrt(pStar*pStar+massPrPDG*massPrPDG))/pStar; // Cosine of proton emission angle (theta*) in the rest frame of the mother particle // (from AliRDHFCutsLctoV0) TLorentzVector vpr, vk0s,vlc; vpr.SetXYZM(part->PxProng(0), part->PyProng(0), part->PzProng(0), massPrPDG); vk0s.SetXYZM(part->PxProng(1), part->PyProng(1), part->PzProng(1), massK0SPDG); vlc = vpr + vk0s; TVector3 vboost = vlc.BoostVector(); vpr.Boost(-vboost); Double_t cts = TMath::Cos(vpr.Angle(vlc.Vect())); Double_t countTreta1corr = fNTracklets_1; AliAODEvent* aodEvent = dynamic_cast<AliAODEvent*>(fInputEvent); if(fUseMultCorrection){ TProfile* estimatorAvg = GetEstimatorHistogram(aodEvent); if(estimatorAvg) { countTreta1corr = static_cast<Int_t>(AliVertexingHFUtils::GetCorrectedNtracklets(estimatorAvg, fNTracklets_1, fVtx1->GetZ(), fRefMult)); } } //AliAODVertex *primvert = dynamic_cast<AliAODVertex*>(part->GetPrimaryVtx()); Double_t d0z0bach[2], covd0z0bach[3]; //bachelor->PropagateToDCA(primvert, fBField, kVeryBig, d0z0bach, covd0z0bach); bachelor->PropagateToDCA(fVtx1, fBField, kVeryBig, d0z0bach, covd0z0bach); Double_t tx[3]; bachelor->GetXYZ(tx); //tx[0] -= primvert->GetX(); //tx[1] -= primvert->GetY(); //tx[2] -= primvert->GetZ(); tx[0] -= fVtx1->GetX(); tx[1] -= fVtx1->GetY(); tx[2] -= fVtx1->GetZ(); Double_t innerpro = tx[0]*part->Px() + tx[1]*part->Py(); Double_t signd0 = 1.; if(innerpro < 0.) signd0 = -1.; signd0 = signd0*TMath::Abs(d0z0bach[0]); Double_t BDTResponse = -1; Double_t tmva = -1; if(!fFillTree){ std::vector<Double_t> inputVars(fNVars); if (fNVars == 12) { inputVars[0] = invmassK0s; inputVars[1] = part->Getd0Prong(0); inputVars[2] = part->Getd0Prong(1); inputVars[3] = (part->DecayLengthV0())*0.497/(v0part->P()); inputVars[4] = part->CosV0PointingAngle(); inputVars[5] = cts; inputVars[6] = nSigmaTOFpr; inputVars[7] = nSigmaTOFpi; inputVars[8] = nSigmaTOFka; inputVars[9] = nSigmaTPCpr; inputVars[10] = nSigmaTPCpi; inputVars[11] = nSigmaTPCka; } else if (fNVars == 11) { inputVars[0] = invmassK0s; inputVars[1] = part->Getd0Prong(0); inputVars[2] = part->Getd0Prong(1); inputVars[3] = (part->DecayLengthV0())*0.497/(v0part->P()); inputVars[4] = part->CosV0PointingAngle(); inputVars[5] = cts; inputVars[6] = signd0; inputVars[7] = nSigmaTOFpr; inputVars[8] = nSigmaTPCpr; inputVars[9] = nSigmaTPCpi; inputVars[10] = nSigmaTPCka; } else if (fNVars == 10) { inputVars[0] = invmassK0s; inputVars[1] = part->Getd0Prong(0); inputVars[2] = part->Getd0Prong(1); inputVars[3] = (part->DecayLengthV0())*0.497/(v0part->P()); inputVars[4] = part->CosV0PointingAngle(); inputVars[5] = cts; inputVars[6] = nSigmaTOFpr; inputVars[7] = nSigmaTPCpr; inputVars[8] = nSigmaTPCpi; inputVars[9] = nSigmaTPCka; } else if (fNVars == 9) { inputVars[0] = invmassK0s; inputVars[1] = part->Getd0Prong(0); inputVars[2] = part->Getd0Prong(1); inputVars[3] = (part->DecayLengthV0())*0.497/(v0part->P()); inputVars[4] = part->CosV0PointingAngle(); inputVars[5] = nSigmaTOFpr; inputVars[6] = nSigmaTPCpr; inputVars[7] = nSigmaTPCpi; inputVars[8] = nSigmaTPCka; } else if (fNVars == 8) { inputVars[0] = invmassK0s; inputVars[1] = part->Getd0Prong(0); inputVars[2] = part->Getd0Prong(1); inputVars[3] = (part->DecayLengthV0())*0.497/(v0part->P()); inputVars[4] = part->CosV0PointingAngle(); inputVars[5] = cts; inputVars[6] = signd0; inputVars[7] = probProton; } for (Int_t i = 0; i < fNVars; i++) { fVarsTMVA[i] = inputVars[i]; } if (fUseXmlWeightsFile || fUseXmlFileFromCVMFS) tmva = fReader->EvaluateMVA("BDT method"); if (fUseWeightsLibrary) BDTResponse = fBDTReader->GetMvaValue(inputVars); //Printf("BDTResponse = %f, invmassLc = %f", BDTResponse, invmassLc); //Printf("tmva = %f", tmva); fBDTHisto->Fill(BDTResponse, invmassLc); fBDTHistoTMVA->Fill(tmva, invmassLc); if (fDebugHistograms) { if (fUseXmlWeightsFile || fUseXmlFileFromCVMFS) BDTResponse = tmva; // we fill the debug histogram with the output from the xml file fBDTHistoVsMassK0S->Fill(BDTResponse, invmassK0s); fBDTHistoVstImpParBach->Fill(BDTResponse, part->Getd0Prong(0)); fBDTHistoVstImpParV0->Fill(BDTResponse, part->Getd0Prong(1)); fBDTHistoVsBachelorPt->Fill(BDTResponse, bachelor->Pt()); fBDTHistoVsCombinedProtonProb->Fill(BDTResponse, probProton); fBDTHistoVsCtau->Fill(BDTResponse, (part->DecayLengthV0())*0.497/(v0part->P())); fBDTHistoVsCosPAK0S->Fill(BDTResponse, part->CosV0PointingAngle()); fBDTHistoVsSignd0->Fill(BDTResponse, signd0); fBDTHistoVsCosThetaStar->Fill(BDTResponse, cts); fBDTHistoVsnSigmaTPCpr->Fill(BDTResponse, nSigmaTPCpr); fBDTHistoVsnSigmaTOFpr->Fill(BDTResponse, nSigmaTOFpr); fBDTHistoVsnSigmaTPCpi->Fill(BDTResponse, nSigmaTPCpi); fBDTHistoVsnSigmaTPCka->Fill(BDTResponse, nSigmaTPCka); fBDTHistoVsBachelorP->Fill(BDTResponse, bachelor->P()); fBDTHistoVsBachelorTPCP->Fill(BDTResponse, bachelor->GetTPCmomentum()); fHistoNsigmaTPC->Fill(bachelor->P(), nSigmaTPCpr); fHistoNsigmaTOF->Fill(bachelor->P(), nSigmaTOFpr); } } Int_t checkOrigin = -1; Bool_t isFromSigmaC = kFALSE; AliAODMCParticle *mcpartMum = 0x0; Double_t sigmaCpt = -1; Double_t cosThetaStarSoftPi = -1.1; Int_t labelSoftPi = -1; Double_t ptsigmacMC = -1; Double_t ptlambdacMC = -1; Double_t ysigmacMC = -9; Double_t ylambdacMC = -9; Double_t pointlcsc[6]; if(partLcMC){ checkOrigin = AliVertexingHFUtils::CheckOrigin(mcArray, partLcMC, kTRUE); fhistMCSpectrumAccLc->Fill(partLcMC->Pt(), kRecoPID, checkOrigin); Int_t indSc = partLcMC->GetMother(); if(indSc >= 0){ mcpartMum = (AliAODMCParticle*)mcArray->At(indSc); // Sigmac candidate Int_t pdgLcMum = TMath::Abs(mcpartMum->GetPdgCode()); if(pdgLcMum == 4112 || pdgLcMum == 4222) isFromSigmaC = kTRUE; } if(isFromSigmaC){ pointlcsc[0] = partLcMC->Pt(); pointlcsc[1] = kRecoLcPID; pointlcsc[2] = checkOrigin; pointlcsc[3] = partLcMC->Y(); pointlcsc[4] = mcpartMum->Pt(); pointlcsc[5] = mcpartMum->Y(); fhistMCSpectrumAccLcFromSc->Fill(pointlcsc); // !!!! really needed? }// end is from sigmaC }// end if partLcMC if(mcpartMum && isFromSigmaC){ //if(mcpartMum){ ptsigmacMC = mcpartMum->Pt(); //if(mcpartMum->GetNDaughters() != 2) return; if(mcpartMum->GetNDaughters() == 2) { for(Int_t k = mcpartMum->GetDaughterLabel(0); k <= mcpartMum->GetDaughterLabel(1); k++){ if(k >= 0){ AliAODMCParticle *mcpartScdau = (AliAODMCParticle*)mcArray->At(k); if(TMath::Abs(mcpartScdau->GetPdgCode()) == 211){ // daughter is soft pion labelSoftPi = k; } else if(TMath::Abs(mcpartScdau->GetPdgCode()) == 4122){ // daughter is LambdaC //mcpartLc = mcpartScdau; //partLcMC = mcpartScdau; //ptlambdacMC = partLcMC->Pt(); //ylambdacMC = partLcMC->Y(); ptlambdacMC = mcpartScdau->Pt(); ylambdacMC = mcpartScdau->Y(); } } } } } if(isLcAnalysis){ //fill the tree with only Lc candidates if(fFillTree && isLcAnalysis){ if (fUseMCInfo) { // save full tree if on MC fCandidateVariables[0] = invmassLc; fCandidateVariables[1] = invmassLc2Lpi; fCandidateVariables[2] = invmassK0s; fCandidateVariables[3] = invmassLambda; fCandidateVariables[4] = invmassLambdaBar; fCandidateVariables[5] = part->CosV0PointingAngle(); fCandidateVariables[6] = dcaV0; fCandidateVariables[7] = part->Getd0Prong(0); fCandidateVariables[8] = part->Getd0Prong(1); fCandidateVariables[9] = nSigmaTPCpr; fCandidateVariables[10] = nSigmaTOFpr; fCandidateVariables[11] = bachelor->Pt(); fCandidateVariables[12] = v0pos->Pt(); fCandidateVariables[13] = v0neg->Pt(); fCandidateVariables[14] = v0part->Getd0Prong(0); fCandidateVariables[15] = v0part->Getd0Prong(1); fCandidateVariables[16] = v0part->Pt(); fCandidateVariables[17] = v0part->InvMass2Prongs(0,1,11,11); fCandidateVariables[18] = part->Pt(); fCandidateVariables[19] = probProton; fCandidateVariables[20] = part->Eta(); fCandidateVariables[21] = v0pos->Eta(); fCandidateVariables[22] = v0neg->Eta(); fCandidateVariables[23] = probProtonTPC; fCandidateVariables[24] = probProtonTOF; fCandidateVariables[25] = bachelor->Eta(); fCandidateVariables[26] = part->P(); fCandidateVariables[27] = bachelor->P(); fCandidateVariables[28] = v0part->P(); fCandidateVariables[29] = v0pos->P(); fCandidateVariables[30] = v0neg->P(); fCandidateVariables[31] = v0part->Eta(); fCandidateVariables[32] = ptLcMC; fCandidateVariables[33] = part->DecayLengthV0(); fCandidateVariables[34] = bachCode; fCandidateVariables[35] = k0SCode; fCandidateVariables[36] = v0part->AlphaV0(); fCandidateVariables[37] = v0part->PtArmV0(); fCandidateVariables[38] = cts; fCandidateVariables[39] = weightPythia; fCandidateVariables[40] = sigmaCpt; fCandidateVariables[41] = cosThetaStarSoftPi; fCandidateVariables[42] = weightNch; fCandidateVariables[43] = fNTracklets_1; fCandidateVariables[44] = countTreta1corr; fCandidateVariables[45] = signd0; fCandidateVariables[46] = fCentrality; fCandidateVariables[47] = fNTracklets_All; fCandidateVariables[48] = checkOrigin; fCandidateVariables[49] = nSigmaTPCpi; fCandidateVariables[50] = nSigmaTPCka; fCandidateVariables[51] = 0; fCandidateVariables[52] = nSigmaTOFpi; fCandidateVariables[53] = nSigmaTOFka; } else { //remove MC-only variables from tree if data fCandidateVariables[0] = invmassLc; fCandidateVariables[1] = v0part->AlphaV0(); fCandidateVariables[2] = invmassK0s; fCandidateVariables[3] = invmassLambda; fCandidateVariables[4] = invmassLambdaBar; fCandidateVariables[5] = part->CosV0PointingAngle(); fCandidateVariables[6] = dcaV0; fCandidateVariables[7] = part->Getd0Prong(0); fCandidateVariables[8] = part->Getd0Prong(1); fCandidateVariables[9] = nSigmaTPCpr; fCandidateVariables[10] = nSigmaTOFpr; fCandidateVariables[11] = bachelor->Pt(); fCandidateVariables[12] = v0pos->Pt(); fCandidateVariables[13] = v0neg->Pt(); fCandidateVariables[14] = v0part->Getd0Prong(0); fCandidateVariables[15] = v0part->Getd0Prong(1); fCandidateVariables[16] = v0part->Pt(); fCandidateVariables[17] = sigmaCpt; fCandidateVariables[18] = part->Pt(); fCandidateVariables[19] = probProton; fCandidateVariables[20] = v0pos->Eta(); fCandidateVariables[21] = nSigmaTOFpi; fCandidateVariables[22] = bachelor->Eta(); fCandidateVariables[23] = v0part->P(); fCandidateVariables[24] = part->DecayLengthV0(); fCandidateVariables[25] = nSigmaTPCpi; fCandidateVariables[26] = nSigmaTPCka; fCandidateVariables[27] = fNTracklets_1; fCandidateVariables[28] = countTreta1corr; fCandidateVariables[29] = cts; fCandidateVariables[30] = signd0; fCandidateVariables[31] = fCentrality; fCandidateVariables[32] = fNTracklets_All; fCandidateVariables[33] = -1; fCandidateVariables[34] = v0part->PtArmV0(); fCandidateVariables[35] = 0; fCandidateVariables[36] = cosThetaStarSoftPi; fCandidateVariables[37] = nSigmaTOFka; } } if (fUseMCInfo) { if (isLc){ AliDebug(2, Form("Reco particle %d --> Filling Sgn", iLctopK0s)); if(fFillTree) fVariablesTreeSgn->Fill(); fHistoCodesSgn->Fill(bachCode, k0SCode); } else { if (fFillOnlySgn == kFALSE){ AliDebug(2, "Filling Bkg"); if(fFillTree) fVariablesTreeBkg->Fill(); fHistoCodesBkg->Fill(bachCode, k0SCode); } } } else { if(fFillTree) fVariablesTreeSgn->Fill(); } } else { //isLcAnalysis //if(TMath::Abs(mass - 2.28646) > fLcMassWindowForSigmaC) return; //Lc mass window selection //AliDebug(2, Form("Good Lc candidate , will loop over %d pions",fnSelSoftPi)); Double_t pointSigma[10]; //Lcpt, deltam, Lcmass, cosThetaStarSoftPi, Sigmapt, origin, isRotated, bdtresp, softPiITSrefit, isSigmacMC pointSigma[0] = part->Pt(); //pointSigma[2] = part->CosPointingAngle(); pointSigma[2] = invmassLc; pointSigma[5] = checkOrigin; pointSigma[6] = 1; pointSigma[7] = -1; pointSigma[8] = 0; pointSigma[9] = 0; if(isFromSigmaC) pointSigma[9] = 1; // Loop over soft pions Double_t p2 = part->P2(); for(Int_t isoft = 0; isoft < fnSelSoftPi; isoft++){ Int_t indsof = ftrackArraySelSoftPi->At(isoft); AliAODTrack *tracksoft = (AliAODTrack*)aodEvent->GetTrack(indsof); if(mcpartMum){ if(TMath::Abs(tracksoft->GetLabel()) != labelSoftPi) continue; } Bool_t skip = kFALSE; for(Int_t k = 0; k < 2; k++){ if((Int_t)(part->GetProngID(k)) == tracksoft->GetID()){ //Printf("Skipping Lc candidate with itself"); skip = kTRUE; break; } } if(skip) continue; Double_t psoft[3], psoftOrig[3]; tracksoft->PxPyPz(psoftOrig); psoft[0] = psoftOrig[0]; psoft[1] = psoftOrig[1]; psoft[2] = psoftOrig[2]; Double_t pcand[3]; part->PxPyPz(pcand); Double_t rotStep = 0.; if(tracksoft->TestFilterBit(AliAODTrack::kITSrefit)) pointSigma[8] = 1; //pointSigma[7] = 1; //if(fNRotations>1) rotStep=(fMaxAngleForRot-fMinAngleForRot)/(fNRotations-1); // -1 is to ensure that the last rotation is done with angle=fMaxAngleForRot //for(Int_t irot = -1; irot < fNRotations; irot++){ // tracks are rotated to provide further background, if required // ASSUMPTIONS: there is no need to repeat single track selection after rotation, because we just rotate in the transverse plane (-> pt and eta does not change; the aspects related to the detector are, like potential intersection of dead modules in the roated direction are not considered) //if(irot >= 0){ //Double_t phirot = fMinAngleForRot + rotStep*irot; //psoft[0] = psoftOrig[0]*TMath::Cos(phirot) - psoftOrig[1]*TMath::Sin(phirot); //psoft[1] = psoftOrig[0]*TMath::Sin(phirot) + psoftOrig[1]*TMath::Cos(phirot); //pointSigma[7] = 0; //} Double_t psigma[3] = {pcand[0]+psoft[0], pcand[1]+psoft[1], pcand[2]+psoft[2]}; Double_t e1, e2; //Double_t cosThetaStarSoftPi = -1.1; if(TMath::Abs(invmassLc - 2.28646) < fLcMassWindowForSigmaC){// here we may be more restrictive and check also resp_only_pid, given that later is done before filling the histogram e1 = TMath::Sqrt(invmassLc*invmassLc + p2); e2 = TMath::Sqrt(0.019479785 + psoft[0]*psoft[0] + psoft[1]*psoft[1] + psoft[2]*psoft[2]);// 0.019479785 = 0.13957*0.13957 TLorentzVector lsum(psoft[0] + part->Px(), psoft[1] + part->Py(), psoft[2] + part->Pz(), e1 + e2); sigmaCpt = lsum.Pt(); pointSigma[4] = sigmaCpt; if(sigmaCpt < fMinPtSigmacCand || sigmaCpt > fMaxPtSigmacCand) continue; pointlcsc[0] = ptlambdacMC; pointlcsc[1] = kRecoPID; pointlcsc[2] = checkOrigin; pointlcsc[3] = ylambdacMC; pointlcsc[4] = ptsigmacMC; pointlcsc[5] = ysigmacMC; if(mcpartMum && isFromSigmaC){ fhistMCSpectrumAccSc->Fill(ptsigmacMC, kRecoPID, checkOrigin); fhistMCSpectrumAccLcFromSc->Fill(pointlcsc); } cosThetaStarSoftPi = CosThetaStar(psigma, psoft, TDatabasePDG::Instance()->GetParticle(4222)->Mass(), TDatabasePDG::Instance()->GetParticle(211)->Mass()); pointSigma[3] = cosThetaStarSoftPi; Double_t deltaM = lsum.M() - invmassLc; pointSigma[1] = deltaM; if(deltaM < fSigmaCDeltaMassWindow){ // good candidate if(fFillTree){ if (fUseMCInfo) { // save full tree if on MC fCandidateVariables[0] = invmassLc; fCandidateVariables[1] = invmassLc2Lpi; fCandidateVariables[2] = invmassK0s; fCandidateVariables[3] = invmassLambda; fCandidateVariables[4] = invmassLambdaBar; fCandidateVariables[5] = part->CosV0PointingAngle(); fCandidateVariables[6] = dcaV0; fCandidateVariables[7] = part->Getd0Prong(0); fCandidateVariables[8] = part->Getd0Prong(1); fCandidateVariables[9] = nSigmaTPCpr; fCandidateVariables[10] = nSigmaTOFpr; fCandidateVariables[11] = bachelor->Pt(); fCandidateVariables[12] = v0pos->Pt(); fCandidateVariables[13] = v0neg->Pt(); fCandidateVariables[14] = v0part->Getd0Prong(0); fCandidateVariables[15] = v0part->Getd0Prong(1); fCandidateVariables[16] = v0part->Pt(); fCandidateVariables[17] = v0part->InvMass2Prongs(0,1,11,11); fCandidateVariables[18] = part->Pt(); fCandidateVariables[19] = probProton; fCandidateVariables[20] = part->Eta(); fCandidateVariables[21] = v0pos->Eta(); fCandidateVariables[22] = v0neg->Eta(); fCandidateVariables[23] = probProtonTPC; fCandidateVariables[24] = probProtonTOF; fCandidateVariables[25] = bachelor->Eta(); fCandidateVariables[26] = part->P(); fCandidateVariables[27] = bachelor->P(); fCandidateVariables[28] = v0part->P(); fCandidateVariables[29] = v0pos->P(); fCandidateVariables[30] = v0neg->P(); fCandidateVariables[31] = v0part->Eta(); fCandidateVariables[32] = ptLcMC; fCandidateVariables[33] = part->DecayLengthV0(); fCandidateVariables[34] = bachCode; fCandidateVariables[35] = k0SCode; fCandidateVariables[36] = v0part->AlphaV0(); fCandidateVariables[37] = v0part->PtArmV0(); AliDebug(2, Form("v0pos->GetStatus() & AliESDtrack::kITSrefit= %d, v0neg->GetStatus() & AliESDtrack::kITSrefit = %d, v0pos->GetTPCClusterInfo(2, 1)= %f, v0neg->GetTPCClusterInfo(2, 1) = %f", (Int_t)(v0pos->GetStatus() & AliESDtrack::kITSrefit), (Int_t)(v0pos->GetStatus() & AliESDtrack::kITSrefit), v0pos->GetTPCClusterInfo(2, 1), v0neg->GetTPCClusterInfo(2, 1))); fCandidateVariables[38] = cts; fCandidateVariables[39] = weightPythia; fCandidateVariables[40] = sigmaCpt; fCandidateVariables[41] = cosThetaStarSoftPi; fCandidateVariables[42] = weightNch; fCandidateVariables[43] = fNTracklets_1; fCandidateVariables[44] = countTreta1corr; fCandidateVariables[45] = signd0; fCandidateVariables[46] = fCentrality; fCandidateVariables[47] = fNTracklets_All; fCandidateVariables[48] = checkOrigin; fCandidateVariables[49] = nSigmaTPCpi; fCandidateVariables[50] = nSigmaTPCka; //fCandidateVariables[51] = bachelor->GetTPCmomentum(); fCandidateVariables[51] = deltaM; fCandidateVariables[52] = nSigmaTOFpi; fCandidateVariables[53] = nSigmaTOFka; } else { //remove MC-only variables from tree if data fCandidateVariables[0] = invmassLc; fCandidateVariables[1] = v0part->AlphaV0(); fCandidateVariables[2] = invmassK0s; fCandidateVariables[3] = invmassLambda; fCandidateVariables[4] = invmassLambdaBar; fCandidateVariables[5] = part->CosV0PointingAngle(); fCandidateVariables[6] = dcaV0; fCandidateVariables[7] = part->Getd0Prong(0); fCandidateVariables[8] = part->Getd0Prong(1); fCandidateVariables[9] = nSigmaTPCpr; fCandidateVariables[10] = nSigmaTOFpr; fCandidateVariables[11] = bachelor->Pt(); fCandidateVariables[12] = v0pos->Pt(); fCandidateVariables[13] = v0neg->Pt(); fCandidateVariables[14] = v0part->Getd0Prong(0); fCandidateVariables[15] = v0part->Getd0Prong(1); fCandidateVariables[16] = v0part->Pt(); fCandidateVariables[17] = sigmaCpt; fCandidateVariables[18] = part->Pt(); fCandidateVariables[19] = probProton; fCandidateVariables[20] = v0pos->Eta(); //fCandidateVariables[21] = bachelor->P(); fCandidateVariables[21] = nSigmaTOFpi; fCandidateVariables[22] = bachelor->Eta(); fCandidateVariables[23] = v0part->P(); fCandidateVariables[24] = part->DecayLengthV0(); fCandidateVariables[25] = nSigmaTPCpi; fCandidateVariables[26] = nSigmaTPCka; fCandidateVariables[27] = fNTracklets_1; fCandidateVariables[28] = countTreta1corr; fCandidateVariables[29] = cts; fCandidateVariables[30] = signd0; fCandidateVariables[31] = fCentrality; fCandidateVariables[32] = fNTracklets_All; fCandidateVariables[33] = -1; fCandidateVariables[34] = v0part->PtArmV0(); fCandidateVariables[35] = deltaM; fCandidateVariables[36] = cosThetaStarSoftPi; fCandidateVariables[37] = nSigmaTOFka; } } // fill multiplicity histograms for events with a candidate //fHistNtrUnCorrEvWithCand->Fill(fNTracklets_1, weightNch); //fHistNtrCorrEvWithCand->Fill(countTreta1corr, weightNch); if (fUseMCInfo) { if (isLc){ AliDebug(2, Form("Reco particle %d --> Filling Sgn", iLctopK0s)); if(fFillTree) fVariablesTreeSgn->Fill(); fHistoCodesSgn->Fill(bachCode, k0SCode); } else { if (fFillOnlySgn == kFALSE){ AliDebug(2, "Filling Bkg"); if(fFillTree) fVariablesTreeBkg->Fill(); fHistoCodesBkg->Fill(bachCode, k0SCode); } } } else { if(fFillTree) fVariablesTreeSgn->Fill(); } if(!fFillTree){ if (fUseXmlWeightsFile || fUseXmlFileFromCVMFS) pointSigma[7] = tmva; if (fUseWeightsLibrary) pointSigma[7] = BDTResponse; if(fhSparseAnalysisSigma) { if(!fUseMCInfo) fhSparseAnalysisSigma->Fill(pointSigma); else { AliAODTrack *trkd = (AliAODTrack*)part->GetDaughter(0); // Daughter(0) of Cascade is always a proton AliAODMCParticle* pProt = (AliAODMCParticle*)mcArray->At(TMath::Abs(trkd->GetLabel())); if(TMath::Abs(pProt->GetPdgCode()) == 2212){ pointSigma[4] = ptsigmacMC; pointSigma[0] = ptlambdacMC; fhSparseAnalysisSigma->Fill(pointSigma); //fhistMCSpectrumAccSc->Fill(ptsigmacMC, kRecoPID, checkOrigin); //pointlcsc[0] = ptlambdacMC; //pointlcsc[1] = kRecoPID; //pointlcsc[2] = checkOrigin; //pointlcsc[3] = ylambdacMC; //pointlcsc[4] = ptsigmacMC; //pointlcsc[5] = ysigmacMC; //fhistMCSpectrumAccLcFromSc->Fill(pointlcsc); } } } } } } } } } return; } //________________________________________________________________________ AliAnalysisTaskSESigmacTopK0Spi::EBachelor AliAnalysisTaskSESigmacTopK0Spi::CheckBachelor( AliAODRecoCascadeHF *part, AliAODTrack* bachelor, TClonesArray *mcArray ){ //Printf("In CheckBachelor"); /// function to check if the bachelor is a p, if it is a p but not from Lc /// to be filled for background candidates Int_t label = bachelor->GetLabel(); if (label == -1) { return kBachFake; } AliAODMCParticle *mcpart = dynamic_cast<AliAODMCParticle*>(mcArray->At(TMath::Abs(label))); if (!mcpart) return kBachInvalid; Int_t pdg = mcpart->PdgCode(); if (TMath::Abs(pdg) != 2212) { AliDebug(2, Form("Bachelor is not a p, but a particle with pdg code = %d", pdg)); return kBachNoProton; } else { // it is a proton //Int_t labelLc = part->GetLabel(); Int_t labelLc = FindLcLabel(part, mcArray); //Printf(">>>>>>>>>>>>> label for Lc = %d", labelLc); Int_t bachelorMotherLabel = mcpart->GetMother(); //Printf(">>>>>>>>>>>>> label for bachelorMother = %d", bachelorMotherLabel); if (bachelorMotherLabel == -1) { return kBachPrimary; } AliAODMCParticle *bachelorMother = dynamic_cast<AliAODMCParticle*>(mcArray->At(bachelorMotherLabel)); if (!bachelorMother) return kBachInvalid; Int_t pdgMother = bachelorMother->PdgCode(); if (TMath::Abs(pdgMother) != 4122) { AliDebug(2, Form("The proton does not come from a Lc, but from a particle with pdgcode = %d", pdgMother)); return kBachNoLambdaMother; } else { // it comes from Lc if (labelLc != bachelorMotherLabel){ //AliInfo(Form("The proton comes from a Lc, but it is not the candidate we are analyzing (label Lc = %d, label p mother = %d", labelLc, bachelorMotherLabel)); AliDebug(2, Form("The proton comes from a Lc, but it is not the candidate we are analyzing")); return kBachDifferentLambdaMother; } else { // it comes from the correct Lc AliDebug(2, Form("The proton comes from a Lc, and it is EXACTLY the candidate we are analyzing")); return kBachCorrectLambdaMother; } } } return kBachInvalid; } //________________________________________________________________________ AliAnalysisTaskSESigmacTopK0Spi::EK0S AliAnalysisTaskSESigmacTopK0Spi::CheckK0S( AliAODRecoCascadeHF *part, AliAODv0* v0part, //AliAODTrack* v0part, TClonesArray *mcArray ){ /// function to check if the K0Spart is a p, if it is a p but not from Lc /// to be filled for background candidates //Printf(" CheckK0S"); //Int_t labelMatchToMC = v0part->MatchToMC(310, mcArray); //Int_t label = v0part->GetLabel(); Int_t labelFind = FindV0Label(v0part, mcArray); //Printf("\n >>>>>>>>>>>>> label for V0 = %d, from MatchToMC = %d, from Find = %d", label, labelMatchToMC, labelFind); if (labelFind == -1) { return kK0SFake; } AliAODMCParticle *mcpart = dynamic_cast<AliAODMCParticle*>(mcArray->At(labelFind)); if (!mcpart) return kK0SInvalid; Int_t pdg = mcpart->PdgCode(); if (TMath::Abs(pdg) != 310) { AliDebug(2, Form("K0Spart is not a K0S, but a particle with pdg code = %d", pdg)); //AliInfo(Form("K0Spart is not a K0S, but a particle with pdg code = %d", pdg)); return kK0SNoK0S; } else { // it is a K0S //Int_t labelLc = part->GetLabel(); Int_t labelLc = FindLcLabel(part, mcArray); Int_t K0SpartMotherLabel = mcpart->GetMother(); if (K0SpartMotherLabel == -1) { return kK0SWithoutMother; } AliAODMCParticle *K0SpartMother = dynamic_cast<AliAODMCParticle*>(mcArray->At(K0SpartMotherLabel)); // should be a K0 in case of signal if (!K0SpartMother) return kK0SInvalid; Int_t pdgMotherK0S = K0SpartMother->PdgCode(); if (TMath::Abs(pdgMotherK0S) != 311) { AliDebug(2, Form("The K0S does not come from a K0, but from a particle with pdgcode = %d", pdgMotherK0S)); //AliInfo(Form("The K0S does not come from a K0, but from a particle with pdgcode = %d", pdgMotherK0S)); return kK0SNotFromK0; } else { // the K0S comes from a K0 Int_t K0MotherLabel = K0SpartMother->GetMother(); // mother of K0 --> Lc in case of signal if (K0MotherLabel == -1) { return kK0Primary; } AliAODMCParticle *K0Mother = dynamic_cast<AliAODMCParticle*>(mcArray->At(K0MotherLabel)); if (!K0Mother) return kK0SInvalid; Int_t pdgK0Mother = K0Mother->PdgCode(); if (TMath::Abs(pdgK0Mother) != 4122) { // the K0 does not come from a Lc AliDebug(2, Form("The K0 does not come from a Lc, but from a particle with pdgcode = %d", pdgK0Mother)); //AliInfo(Form("The K0 does not come from a Lc, but from a particle with pdgcode = %d", pdgK0Mother)); return kK0NoLambdaMother; } else { // the K0 comes from Lc if (labelLc != K0MotherLabel){ // The K0 comes from a different Lc AliDebug(2, Form("The K0S comes from a Lc, but it is not the candidate we are analyzing")); //AliInfo(Form("The K0S comes from a Lc, but it is not the candidate we are analyzing")); return kK0DifferentLambdaMother; } else { // it comes from the correct Lc AliDebug(2, Form("The K0S comes from a Lc, and it is EXACTLY the candidate we are analyzing")); //AliInfo(Form("The K0S comes from a Lc, and it is EXACTLY the candidate we are analyzing")); return kK0CorrectLambdaMother; } } } } return kK0SInvalid; } //---------------------------------------------------------------------------- Int_t AliAnalysisTaskSESigmacTopK0Spi::FindV0Label(AliAODRecoDecay* v0part, TClonesArray *mcArray) const { //Printf(" FindV0Label"); /// finding the label of teh V0; inspired from AliAODRecoDecay::MatchToMC Int_t labMother[2] = {-1, -1}; AliAODMCParticle *part = 0; AliAODMCParticle *mother = 0; Int_t dgLabels = -1; Int_t ndg = v0part->GetNDaughters(); if (ndg != 2) { AliFatal(Form("IMPOSSIBLE!! There are %d daughters, but they should be 2!", ndg)); } for(Int_t i = 0; i < 2; i++) { AliAODTrack *trk = (AliAODTrack*)v0part->GetDaughter(i); dgLabels = trk->GetLabel(); if (dgLabels == -1) { //printf("daughter with negative label %d\n", dgLabels); return -1; } part = (AliAODMCParticle*)mcArray->At(TMath::Abs(dgLabels)); if (!part) { //printf("no MC particle\n"); return -1; } labMother[i] = part->GetMother(); if (labMother[i] != -1){ mother = (AliAODMCParticle*)mcArray->At(labMother[i]); if(!mother) { //printf("no MC mother particle\n"); return -1; } } else { return -1; } } if (labMother[0] == labMother[1]) return labMother[0]; else return -1; } //_____________________________________________________________________________ Int_t AliAnalysisTaskSESigmacTopK0Spi::FindLcLabel(AliAODRecoCascadeHF* cascade, TClonesArray *mcArray) const { /// finding the label of teh V0; inspired from AliAODRecoDecay::MatchToMC //Printf(" FindLcLabel"); AliAODMCParticle *part = 0; AliAODMCParticle *mother = 0; AliAODMCParticle *grandmother = 0; Int_t dgLabels = -1; Int_t ndg = cascade->GetNDaughters(); if (ndg != 2) { AliFatal(Form("IMPOSSIBLE!! There are %d daughters, but they should be 2!", ndg)); } // daughter 0 --> bachelor, daughter 1 --> V0 AliAODTrack *trk = (AliAODTrack*)cascade->GetDaughter(0); // bachelor dgLabels = trk->GetLabel(); if (dgLabels == -1 ) { //printf("daughter with negative label %d\n", dgLabels); return -1; } part = (AliAODMCParticle*)mcArray->At(TMath::Abs(dgLabels)); if (!part) { //printf("no MC particle\n"); return -1; } Int_t labMotherBach = part->GetMother(); if (labMotherBach == -1){ return -1; } mother = (AliAODMCParticle*)mcArray->At(labMotherBach); if(!mother) { //printf("no MC mother particle\n"); return -1; } AliAODv0 *v0 = (AliAODv0*)cascade->GetDaughter(1); // V0 dgLabels = FindV0Label(v0, mcArray); if (dgLabels == -1 ) { //printf("daughter with negative label (v0 was a fake) %d\n", dgLabels); return -1; } part = (AliAODMCParticle*)mcArray->At(TMath::Abs(dgLabels)); if (!part) { //printf("no MC particle\n"); return -1; } Int_t labMotherv0 = part->GetMother(); if (labMotherv0 == -1){ return -1; } mother = (AliAODMCParticle*)mcArray->At(labMotherv0); if(!mother) { //printf("no MC mother particle\n"); return -1; } Int_t labGrandMotherv0 = mother->GetMother(); if (labGrandMotherv0 == -1){ return -1; } grandmother = (AliAODMCParticle*)mcArray->At(labGrandMotherv0); if(!grandmother) { //printf("no MC mother particle\n"); return -1; } //Printf("labMotherBach = %d, labMotherv0 = %d, labGrandMotherv0 = %d", labMotherBach, labMotherv0, labGrandMotherv0); if (labGrandMotherv0 == labMotherBach) return labMotherBach; else return -1; } //____________________________________________________________________________ TProfile* AliAnalysisTaskSESigmacTopK0Spi::GetEstimatorHistogram(const AliVEvent* event){ /// Get Estimator Histogram from period event->GetRunNumber(); /// /// If you select SPD tracklets in |eta|<1 you should use type == 1 Int_t runNo = event->GetRunNumber(); Int_t period = -1; // pp: 0-LHC10b, 1-LHC10c, 2-LHC10d, 3-LHC10e if(fYearNumber==10){ if(runNo>114930 && runNo<117223) period = 0;//10b if(runNo>119158 && runNo<120830) period = 1;//10c if(runNo>122373 && runNo<126438) period = 2;//10d if(runNo>127711 && runNo<130851) period = 3;//10e if(period<0 || period>3) return 0; }else if(fYearNumber==16){ if(runNo>=252235 && runNo<=252375)period = 0;//16d if(runNo>=252603 && runNo<=253591)period = 1;//16e if(runNo>=254124 && runNo<=254332)period = 2;//16g if(runNo>=254378 && runNo<=255469 )period = 3;//16h_1 if(runNo>=254418 && runNo<=254422 )period = 4;//16h_2 negative mag if(runNo>=256146 && runNo<=256420 )period = 5;//16j if(runNo>=256504 && runNo<=258537 )period = 6;//16k if(runNo>=258883 && runNo<=260187)period = 7;//16l if(runNo>=262395 && runNo<=264035 )period = 8;//16o if(runNo>=264076 && runNo<=264347 )period = 9;//16p }else if(fYearNumber==17){ if(runNo>=270822 && runNo<=270830)period = 0;//17e if(runNo>=270854 && runNo<=270865)period = 1;//17f if(runNo>=271868 && runNo<=273103)period = 2;//17h if(runNo>=273591 && runNo<=274442)period = 3;//17i if(runNo>=274593 && runNo<=274671)period = 4;//17j if(runNo>=274690 && runNo<=276508)period = 5;//17k if(runNo>=276551 && runNo<=278216)period = 6;//17l if(runNo>=278914 && runNo<=280140)period = 7;//17m if(runNo>=280282 && runNo<=281961)period = 8;//17o if(runNo>=282504 && runNo<=282704)period = 9;//17r }else if(fYearNumber==18){ if(runNo>=285008 && runNo<=285447)period = 0;//18b if(runNo>=285978 && runNo<=286350)period = 1;//18d if(runNo>=286380 && runNo<=286937)period = 2;//18e if(runNo>=287000 && runNo<=287977)period = 3;//18f if(runNo>=288619 && runNo<=288750)period = 4;//18g if(runNo>=288804 && runNo<=288806)period = 5;//18h if(runNo>=288861 && runNo<=288909 )period = 6;//18i if(runNo==288943)period = 7;//18j if(runNo>=289165 && runNo<=289201)period = 8;//18k if(runNo>=289240 && runNo<=289971)period = 9;//18l if(runNo>=290222 && runNo<=292839)period = 10;//18m if(runNo>=293357 && runNo<=293359)period = 11;//18n if(runNo>=293368 && runNo<=293898)period = 12;//18o if(runNo>=294009 && runNo<=294925)period = 13;//18p } return fMultEstimatorAvg[period]; } //________________________________________________________________________ void AliAnalysisTaskSESigmacTopK0Spi::PrepareTracks(AliAODEvent *aod){ // SELECT TRACKS and flag them: could consider to include common tracks (dca) to reduce cpu time (call once propagatetodca) ftrackArraySelSoftPi->Reset(); fnSelSoftPi=0; for(Int_t itrack = 0; itrack < aod->GetNumberOfTracks(); itrack++){ Int_t iSelSoftPionCuts = -1; AliAODTrack *track = dynamic_cast<AliAODTrack*>(aod->GetTrack(itrack)); if(!track) AliFatal("Not a standard AOD"); //Printf("selecting track"); AliESDtrack *trackESD = SelectTrack(track, iSelSoftPionCuts, fESDtrackCutsSoftPion); //select soft-pion candidates if(!trackESD) continue; //Printf("good track"); if(iSelSoftPionCuts>=0){ ftrackArraySelSoftPi->AddAt(itrack, fnSelSoftPi); fnSelSoftPi++; } delete trackESD; } } ///_______________________________________________________________________________________ AliESDtrack* AliAnalysisTaskSESigmacTopK0Spi::SelectTrack(AliAODTrack *aodtr, Int_t &isSelSoftPion, AliESDtrackCuts *cutsSoftPion){ isSelSoftPion = -1; if(aodtr->GetID() < 0) return 0x0; if(TMath::Abs(aodtr->Charge()) != 1) return 0x0; AliESDtrack *esdTrack=new AliESDtrack(aodtr); // set the TPC cluster info esdTrack->SetTPCClusterMap(aodtr->GetTPCClusterMap()); esdTrack->SetTPCSharedMap(aodtr->GetTPCSharedMap()); esdTrack->SetTPCPointsF(aodtr->GetTPCNclsF()); // needed to calculate the impact parameters Double_t pos[3], cov[6]; fVtx1->GetXYZ(pos); fVtx1->GetCovarianceMatrix(cov); const AliESDVertex vESD(pos, cov, 100., 100); esdTrack->RelateToVertex(&vESD, 0., 3.); if(cutsSoftPion){ if(cutsSoftPion->IsSelected(esdTrack)){ isSelSoftPion = 0; } } if(isSelSoftPion < 0){ delete esdTrack; return 0x0; } return esdTrack; } //________________________________________________________________________ Double_t AliAnalysisTaskSESigmacTopK0Spi::CosThetaStar(Double_t mumVector[3],Double_t daughtVector[3],Double_t massMum,Double_t massDaught){ Double_t mumP2=mumVector[0]*mumVector[0]+mumVector[1]*mumVector[1]+mumVector[2]*mumVector[2]; Double_t mumP=TMath::Sqrt(mumP2); Double_t eMum=TMath::Sqrt(mumP2+massMum*massMum); Double_t daughtP2=daughtVector[0]*daughtVector[0]+daughtVector[1]*daughtVector[1]+daughtVector[2]*daughtVector[2]; Double_t eDaugh=TMath::Sqrt(daughtP2+massDaught*massDaught); Double_t plLab=(mumVector[0]*daughtVector[0]+mumVector[1]*daughtVector[1]+mumVector[2]*daughtVector[2])/mumP; Double_t beta = mumP/eMum; Double_t gamma = eMum/massMum; Double_t plStar=gamma*(plLab-beta*eDaugh); Double_t daughtpT2=daughtP2-plLab*plLab; return plStar/TMath::Sqrt(plStar*plStar+daughtpT2); } //______________________________________________________ void AliAnalysisTaskSESigmacTopK0Spi::LoopOverGenParticles(TClonesArray *mcArray){ for(Int_t kmc = 0; kmc < mcArray->GetEntries(); kmc++){ AliAODMCParticle *mcpart = (AliAODMCParticle*)mcArray->At(kmc); Int_t pdg = mcpart->GetPdgCode(); Int_t arrayDauLab[3]; Double_t pointLcSc[6]; Double_t ptpartSc; Double_t ypartSc; if(TMath::Abs(pdg) == 4122){ if(AliVertexingHFUtils::CheckLcV0bachelorDecay(mcArray, mcpart, arrayDauLab) == 1) { Int_t checkOrigin = AliVertexingHFUtils::CheckOrigin(mcArray, mcpart, kTRUE); if(checkOrigin == 0)continue; Double_t ptpart = mcpart->Pt(); Double_t ypart = mcpart->Y(); Bool_t isFromSigmaC = kFALSE; Int_t indSc = mcpart->GetMother(); AliAODMCParticle *mcpartMum = 0x0; if(indSc >= 0){ mcpartMum = (AliAODMCParticle*)mcArray->At(indSc); Int_t pdgLcMum = TMath::Abs(mcpartMum->GetPdgCode()); if(pdgLcMum == 4112 || pdgLcMum == 4222) isFromSigmaC = kTRUE; } if(isFromSigmaC){ ptpartSc = mcpartMum->Pt(); ypartSc = mcpartMum->Y(); pointLcSc[0] = ptpart; pointLcSc[1] = -1; pointLcSc[2] = checkOrigin; pointLcSc[3] = ypart; pointLcSc[4] = ptpartSc; pointLcSc[5] = ypartSc; } if(TMath::Abs(ypart) < 0.5){ fhistMCSpectrumAccLc->Fill(ptpart, kGenLimAcc, checkOrigin);// Gen Level if(isFromSigmaC){ pointLcSc[1] = kGenLimAcc; fhistMCSpectrumAccLcFromSc->Fill(pointLcSc); } } Bool_t isInAcc = kTRUE; // check GenAcc level if(fAnalCuts){ if(!fAnalCuts->IsInFiducialAcceptance( ptpart, ypart)){ isInAcc = kFALSE; } } else { if(TMath::Abs(ypart) > 0.8){ isInAcc = kFALSE; } } if(isInAcc){ fhistMCSpectrumAccLc->Fill(ptpart, kGenAccMother, checkOrigin);// Gen Acc Mother if(isFromSigmaC){ pointLcSc[1] = kGenAccMother; fhistMCSpectrumAccLcFromSc->Fill(pointLcSc); } for(Int_t k = 0; k < 2; k++){ AliAODMCParticle *mcpartdau=(AliAODMCParticle*)mcArray->At(arrayDauLab[k]); if(TMath::Abs(mcpartdau->Eta()) > 0.9){ isInAcc = kFALSE; } } if(isInAcc){ fhistMCSpectrumAccLc->Fill(mcpart->Pt(), kGenAcc, checkOrigin);// Gen Acc if(isFromSigmaC){ pointLcSc[1] = kGenAcc; fhistMCSpectrumAccLcFromSc->Fill(pointLcSc); } } } if(isFromSigmaC){ // LimAcc level if(TMath::Abs(ypartSc) < 0.5){ fhistMCSpectrumAccSc->Fill(ptpartSc, kGenLimAcc, checkOrigin);// Gen Level } // check GenAcc level Bool_t isInAccSc = kTRUE; if(fAnalCuts){ if(!fAnalCuts->IsInFiducialAcceptance(ptpartSc, ypartSc)){ isInAccSc = kFALSE; } } else { if(TMath::Abs(mcpartMum->Y()) > 0.8){ isInAccSc = kFALSE; } } if(isInAccSc){ fhistMCSpectrumAccSc->Fill(ptpartSc, kGenAccMother, checkOrigin);// Gen Acc Mother if(isInAcc){// both Sc and Lc in fiducial acceptance + Lc daughter in Acc for(Int_t k = mcpartMum->GetDaughterLabel(0); k < mcpartMum->GetDaughterLabel(1); k++){ if(k >= 0){ AliAODMCParticle *mcpartMumdau = (AliAODMCParticle*)mcArray->At(k); if(TMath::Abs(mcpartMumdau->GetPdgCode() == 211) && TMath::Abs(mcpartMumdau->Eta()) > 0.9){ isInAccSc = kFALSE; } } } if(isInAccSc){ fhistMCSpectrumAccSc->Fill(ptpartSc, kGenAcc, checkOrigin);// Gen Acc } } } } } } } }
38.319478
366
0.682513
[ "object", "vector" ]
2db55b2c53ef454185356184a3692741f3df7f88
862
cpp
C++
Ch 12/12.26.cpp
Felon03/CppPrimer
7dc2daf59f0ae7ec5670def15cb5fab174fe9780
[ "Apache-2.0" ]
null
null
null
Ch 12/12.26.cpp
Felon03/CppPrimer
7dc2daf59f0ae7ec5670def15cb5fab174fe9780
[ "Apache-2.0" ]
null
null
null
Ch 12/12.26.cpp
Felon03/CppPrimer
7dc2daf59f0ae7ec5670def15cb5fab174fe9780
[ "Apache-2.0" ]
null
null
null
/* 用allocator重写第427页中的程序*/ #include<iostream> #include<string> #include<memory> #include<vector> #include<stack> using namespace std; void print_string_allocator(int n) { allocator<string> alloc; vector<string> svec; stack<string> sstack; string str; auto const p = alloc.allocate(n); auto q = p; while (cin >> str && q != p + n) alloc.construct(q++, str); const size_t size = q - p; cout << "The difference between p and q: " << size << endl; cout << "Out put strings: " << endl; while (q != p) { sstack.push(*--q); alloc.destroy(q); } alloc.deallocate(p, n); while (!sstack.empty()) { cout << sstack.top() << endl; sstack.pop(); } } int main() { int size = 0; cout << "Please enter the number of strings you want entered: "; cin >> size; cout << "Input the strings:" << endl; print_string_allocator(size); return 0; }
17.958333
65
0.635731
[ "vector" ]
2db8ffa3ccb531f2e0e64ac3189e6428994fc810
898
cpp
C++
5.Inheritance/i-Design/Q4/Main.cpp
Concept-Team/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
26
2021-03-17T03:15:22.000Z
2021-06-09T13:29:41.000Z
5.Inheritance/i-Design/Q4/Main.cpp
Servatom/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
6
2021-03-16T19:04:05.000Z
2021-06-03T13:41:04.000Z
5.Inheritance/i-Design/Q4/Main.cpp
Concept-Team/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
42
2021-03-17T03:16:22.000Z
2021-06-14T21:11:20.000Z
#include <iostream> #include<string> using namespace std; #include "Truck.cpp" int main(void){ string model,manufacturer,gearType,fuelType,size; int year,cargoCapacity; cout<<"Enter the model of the vehicle"<<endl; cin>>model; cout<<"Enter the manufactured year"<<endl; cin>>year; cin.ignore(); cout<<"Enter the name of the manufacturer"<<endl; getline(cin,manufacturer); cout<<"Enter the gear type of the four wheeler"<<endl; cin>>gearType; cout<<"Enter the fuel type of the four wheeler"<<endl; cin>>fuelType; cout<<"Enter the cargo capacity of the truck"<<endl; cin>>cargoCapacity; cout<<"Enter the size of the truck"<<endl; cin>>size; Truck t(model,year,manufacturer,gearType,fuelType,cargoCapacity,size); t.displayDetails(); return 0; }
24.944444
75
0.621381
[ "model" ]
2dbfcd2b23803638b0a1f8f9d060f00edee0f264
2,164
cpp
C++
header.cpp
whoshuu/cpt
91414d961d50a60b68da86ba15ae119e759e1d2a
[ "MIT" ]
null
null
null
header.cpp
whoshuu/cpt
91414d961d50a60b68da86ba15ae119e759e1d2a
[ "MIT" ]
null
null
null
header.cpp
whoshuu/cpt
91414d961d50a60b68da86ba15ae119e759e1d2a
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <sstream> #include <string> #include <cctype> #include <vector> int main(int argc, char** argv) { std::vector<std::string> args; if (argc == 1) { std::cerr << "Usage: header [namespace] [namespace] ... [class name]" << std::endl; return -1; } for (int i = 1; i < argc; ++i) { args.push_back(argv[i]); } std::string class_name = args.back(); // Keep only the namespaces in args args.pop_back(); // Produce the file name std::string file_name; for (const auto c : class_name) { if (!file_name.empty()) { if (isupper(c)) { file_name.push_back('-'); file_name.push_back(tolower(c)); } else { file_name.push_back(c); } } else { file_name.push_back(tolower(c)); } } file_name.append(".h"); // Produce the header guard std::string header_guard; for (const auto& ns : args) { for (const auto c : ns) { header_guard.push_back(toupper(c)); } header_guard.push_back('_'); } header_guard.append(class_name); header_guard.append("_H_"); std::stringstream output; output << "#ifndef " << header_guard << std::endl; output << "#define " << header_guard << std::endl << std::endl; for (const auto& ns : args) { output << "namespace " << ns << " {" << std::endl; } output << std::endl; output << "class " << class_name << " {" << std::endl; output << "};" << std::endl << std::endl; for (auto ns_iterator = args.rbegin(); ns_iterator != args.rend(); ++ns_iterator) { output << "} // namespace " << *ns_iterator << std::endl; } output << std::endl; output << "#endif // " << header_guard; std::cout << "Class name: " << class_name << std::endl; std::cout << "File name: " << file_name << std::endl; std::cout << "Header guard: " << header_guard << std::endl << std::endl; std::cout << output.str() << std::endl; std::ofstream file(file_name); file << output.str(); }
25.761905
91
0.531885
[ "vector" ]
2dcff3e7cb048ac8e76e184f89f721b147728a22
203
cpp
C++
headers/common/json.cpp
SamBuckberry/readslam
47c5cd0e407f17db08a70488913905f86cffe054
[ "CC-BY-3.0" ]
null
null
null
headers/common/json.cpp
SamBuckberry/readslam
47c5cd0e407f17db08a70488913905f86cffe054
[ "CC-BY-3.0" ]
null
null
null
headers/common/json.cpp
SamBuckberry/readslam
47c5cd0e407f17db08a70488913905f86cffe054
[ "CC-BY-3.0" ]
null
null
null
#include "_json.h" int main() { json::Object obj = JSON::load("/tmp/test1.json"); obj["age"] = json::Number(32); obj["field"] = json::Boolean(true); JSON::save(obj, "/tmp/test2.json"); return 0; }
18.454545
50
0.610837
[ "object" ]
2dd1be2048ed7c17704b00eca4f22bd408cf2a6b
23,988
cpp
C++
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/primitives/blockcache/filebuffermgr.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/primitives/blockcache/filebuffermgr.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/primitives/blockcache/filebuffermgr.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
2
2022-02-27T14:00:01.000Z
2022-03-31T06:24:22.000Z
/* Copyright (C) 2014 InfiniDB, Inc. Copyright (C) 2016 MariaDB Corporation 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /*************************************************************************** * * $Id: filebuffermgr.cpp 2045 2013-01-30 20:26:59Z pleblanc $ * * jrodriguez@calpont.com * * * ***************************************************************************/ /** * InitialDBBCSize - the starting number of elements the unordered set used to store disk blocks. This does not instantiate InitialDBBCSize disk blocks but only the initial size of the unordered_set **/ //#define NDEBUG #include <cassert> #include <limits> #include <boost/thread.hpp> #ifndef _MSC_VER #include <pthread.h> #endif #include "stats.h" #include "configcpp.h" #include "filebuffermgr.h" #include "mcsconfig.h" using namespace config; using namespace boost; using namespace std; using namespace BRM; extern dbbc::Stats* gPMStatsPtr; extern bool gPMProfOn; extern uint32_t gSession; namespace dbbc { const uint32_t gReportingFrequencyMin(32768); FileBufferMgr::FileBufferMgr(const uint32_t numBlcks, const uint32_t blkSz, const uint32_t deleteBlocks) : fMaxNumBlocks(numBlcks), fBlockSz(blkSz), fWLock(), fbSet(), fbList(), fCacheSize(0), fFBPool(), fDeleteBlocks(deleteBlocks), fEmptyPoolSlots(), fReportFrequency(0) { fFBPool.reserve(numBlcks); fConfig = Config::makeConfig(); setReportingFrequency(0); #ifdef _MSC_VER fLog.open("C:/Calpont/log/trace/bc", ios_base::app | ios_base::ate); #else fLog.open(string(MCSLOGDIR) + "/trace/bc", ios_base::app | ios_base::ate); #endif } FileBufferMgr::~FileBufferMgr() { flushCache(); } // param d is used as a togle only void FileBufferMgr::setReportingFrequency(const uint32_t d) { if (d == 0) { fReportFrequency = 0; return; } const string val = fConfig->getConfig("DBBC", "ReportFrequency"); uint32_t temp = 0; if (val.length() > 0) temp = static_cast<int>(Config::fromText(val)); if (temp > 0 && temp <= gReportingFrequencyMin) fReportFrequency = gReportingFrequencyMin; else fReportFrequency = temp; } void FileBufferMgr::flushCache() { boost::mutex::scoped_lock lk(fWLock); { filebuffer_uset_t sEmpty; filebuffer_list_t lEmpty; emptylist_t vEmpty; fbList.swap(lEmpty); fbSet.swap(sEmpty); fEmptyPoolSlots.swap(vEmpty); } fCacheSize = 0; // the block pool should not be freed in the above block to allow us // to continue doing concurrent unprotected-but-"safe" memcpys // from that memory if (fReportFrequency) { fLog << "Clearing entire cache" << endl; } fFBPool.clear(); // fFBPool.reserve(fMaxNumBlocks); } void FileBufferMgr::flushOne(const BRM::LBID_t lbid, const BRM::VER_t ver) { //similar in function to depleteCache() boost::mutex::scoped_lock lk(fWLock); filebuffer_uset_iter_t iter = fbSet.find(HashObject_t(lbid, ver, 0)); if (iter != fbSet.end()) { //remove it from fbList uint32_t idx = iter->poolIdx; fbList.erase(fFBPool[idx].listLoc()); //add to fEmptyPoolSlots fEmptyPoolSlots.push_back(idx); //remove it from fbSet fbSet.erase(iter); //adjust fCacheSize fCacheSize--; } } void FileBufferMgr::flushMany(const LbidAtVer* laVptr, uint32_t cnt) { boost::mutex::scoped_lock lk(fWLock); BRM::LBID_t lbid; BRM::VER_t ver; filebuffer_uset_iter_t iter; if (fReportFrequency) { fLog << "flushMany " << cnt << " items: "; for (uint32_t j = 0; j < cnt; j++) { fLog << "lbid: " << laVptr[j].LBID << " ver: " << laVptr[j].Ver << ", "; } fLog << endl; } for (uint32_t j = 0; j < cnt; j++) { lbid = static_cast<BRM::LBID_t>(laVptr->LBID); ver = static_cast<BRM::VER_t>(laVptr->Ver); iter = fbSet.find(HashObject_t(lbid, ver, 0)); if (iter != fbSet.end()) { if (fReportFrequency) { fLog << "flushMany hit, lbid: " << lbid << " index: " << iter->poolIdx << endl; } //remove it from fbList uint32_t idx = iter->poolIdx; fbList.erase(fFBPool[idx].listLoc()); //add to fEmptyPoolSlots fEmptyPoolSlots.push_back(idx); //remove it from fbSet fbSet.erase(iter); //adjust fCacheSize fCacheSize--; } ++laVptr; } } void FileBufferMgr::flushManyAllversion(const LBID_t* laVptr, uint32_t cnt) { filebuffer_uset_t::iterator it, tmpIt; tr1::unordered_set<LBID_t> uniquer; tr1::unordered_set<LBID_t>::iterator uit; boost::mutex::scoped_lock lk(fWLock); if (fReportFrequency) { fLog << "flushManyAllversion " << cnt << " items: "; for (uint32_t i = 0; i < cnt; i++) { fLog << laVptr[i] << ", "; } fLog << endl; } if (fCacheSize == 0 || cnt == 0) return; for (uint32_t i = 0; i < cnt; i++) uniquer.insert(laVptr[i]); for (it = fbSet.begin(); it != fbSet.end();) { if (uniquer.find(it->lbid) != uniquer.end()) { if (fReportFrequency) { fLog << "flushManyAllversion hit: " << it->lbid << " index: " << it->poolIdx << endl; } const uint32_t idx = it->poolIdx; fbList.erase(fFBPool[idx].listLoc()); fEmptyPoolSlots.push_back(idx); tmpIt = it; ++it; fbSet.erase(tmpIt); fCacheSize--; } else ++it; } } void FileBufferMgr::flushOIDs(const uint32_t* oids, uint32_t count) { DBRM dbrm; uint32_t i; vector<EMEntry> extents; int err; uint32_t currentExtent; LBID_t currentLBID; typedef tr1::unordered_multimap<LBID_t, filebuffer_uset_t::iterator> byLBID_t; byLBID_t byLBID; pair<byLBID_t::iterator, byLBID_t::iterator> itList; filebuffer_uset_t::iterator it; if (fReportFrequency) { fLog << "flushOIDs " << count << " items: "; for (uint32_t i = 0; i < count; i++) { fLog << oids[i] << ", "; } fLog << endl; } // If there are more than this # of extents to drop, the whole cache will be cleared const uint32_t clearThreshold = 50000; boost::mutex::scoped_lock lk(fWLock); if (fCacheSize == 0 || count == 0) return; /* Index the cache by LBID */ for (it = fbSet.begin(); it != fbSet.end(); it++) byLBID.insert(pair<LBID_t, filebuffer_uset_t::iterator>(it->lbid, it)); for (i = 0; i < count; i++) { extents.clear(); err = dbrm.getExtents(oids[i], extents, true, true, true); // @Bug 3838 Include outofservice extents if (err < 0 || (i == 0 && (extents.size() * count) > clearThreshold)) { // (The i == 0 should ensure it's not a dictionary column) lk.unlock(); flushCache(); return; } for (currentExtent = 0; currentExtent < extents.size(); currentExtent++) { EMEntry& range = extents[currentExtent]; LBID_t lastLBID = range.range.start + (range.range.size * 1024); for (currentLBID = range.range.start; currentLBID < lastLBID; currentLBID++) { itList = byLBID.equal_range(currentLBID); for (byLBID_t::iterator tmpIt = itList.first; tmpIt != itList.second; tmpIt++) { fbList.erase(fFBPool[tmpIt->second->poolIdx].listLoc()); fEmptyPoolSlots.push_back(tmpIt->second->poolIdx); fbSet.erase(tmpIt->second); fCacheSize--; } } } } } void FileBufferMgr::flushPartition(const vector<OID_t>& oids, const set<BRM::LogicalPartition>& partitions) { DBRM dbrm; uint32_t i; vector<EMEntry> extents; int err; uint32_t currentExtent; LBID_t currentLBID; typedef tr1::unordered_multimap<LBID_t, filebuffer_uset_t::iterator> byLBID_t; byLBID_t byLBID; pair<byLBID_t::iterator, byLBID_t::iterator> itList; filebuffer_uset_t::iterator it; uint32_t count = oids.size(); boost::mutex::scoped_lock lk(fWLock); if (fReportFrequency) { std::set<BRM::LogicalPartition>::iterator sit; fLog << "flushPartition oids: "; for (uint32_t i = 0; i < count; i++) { fLog << oids[i] << ", "; } fLog << "flushPartition partitions: "; for (sit = partitions.begin(); sit != partitions.end(); ++sit) { fLog << (*sit).toString() << ", "; } fLog << endl; } if (fCacheSize == 0 || oids.size() == 0 || partitions.size() == 0) return; /* Index the cache by LBID */ for (it = fbSet.begin(); it != fbSet.end(); it++) byLBID.insert(pair<LBID_t, filebuffer_uset_t::iterator>(it->lbid, it)); for (i = 0; i < count; i++) { extents.clear(); err = dbrm.getExtents(oids[i], extents, true, true, true); // @Bug 3838 Include outofservice extents if (err < 0) { lk.unlock(); flushCache(); // better than returning an error code to the user return; } for (currentExtent = 0; currentExtent < extents.size(); currentExtent++) { EMEntry& range = extents[currentExtent]; LogicalPartition logicalPartNum(range.dbRoot, range.partitionNum, range.segmentNum); if (partitions.find(logicalPartNum) == partitions.end()) continue; LBID_t lastLBID = range.range.start + (range.range.size * 1024); for (currentLBID = range.range.start; currentLBID < lastLBID; currentLBID++) { itList = byLBID.equal_range(currentLBID); for (byLBID_t::iterator tmpIt = itList.first; tmpIt != itList.second; tmpIt++) { fbList.erase(fFBPool[tmpIt->second->poolIdx].listLoc()); fEmptyPoolSlots.push_back(tmpIt->second->poolIdx); fbSet.erase(tmpIt->second); fCacheSize--; } } } } } bool FileBufferMgr::exists(const BRM::LBID_t& lbid, const BRM::VER_t& ver) const { const HashObject_t fb(lbid, ver, 0); const bool b = exists(fb); return b; } FileBuffer* FileBufferMgr::findPtr(const HashObject_t& keyFb) { boost::mutex::scoped_lock lk(fWLock); filebuffer_uset_iter_t it = fbSet.find(keyFb); if (fbSet.end() != it) { FileBuffer* fb = &(fFBPool[it->poolIdx]); fFBPool[it->poolIdx].listLoc()->hits++; fbList.splice( fbList.begin(), fbList, (fFBPool[it->poolIdx]).listLoc() ); return fb; } return NULL; } bool FileBufferMgr::find(const HashObject_t& keyFb, FileBuffer& fb) { bool ret = false; boost::mutex::scoped_lock lk(fWLock); filebuffer_uset_iter_t it = fbSet.find(keyFb); if (fbSet.end() != it) { fFBPool[it->poolIdx].listLoc()->hits++; fbList.splice( fbList.begin(), fbList, (fFBPool[it->poolIdx]).listLoc() ); fb = fFBPool[it->poolIdx]; ret = true; } return ret; } bool FileBufferMgr::find(const HashObject_t& keyFb, void* bufferPtr) { bool ret = false; if (gPMProfOn && gPMStatsPtr) #ifdef _MSC_VER gPMStatsPtr->markEvent(keyFb.lbid, GetCurrentThreadId(), gSession, 'L'); #else gPMStatsPtr->markEvent(keyFb.lbid, pthread_self(), gSession, 'L'); #endif boost::mutex::scoped_lock lk(fWLock); if (gPMProfOn && gPMStatsPtr) #ifdef _MSC_VER gPMStatsPtr->markEvent(keyFb.lbid, GetCurrentThreadId(), gSession, 'M'); #else gPMStatsPtr->markEvent(keyFb.lbid, pthread_self(), gSession, 'M'); #endif filebuffer_uset_iter_t it = fbSet.find(keyFb); if (fbSet.end() != it) { uint32_t idx = it->poolIdx; //@bug 669 LRU cache, move block to front of list as last recently used. fFBPool[idx].listLoc()->hits++; fbList.splice(fbList.begin(), fbList, (fFBPool[idx]).listLoc()); lk.unlock(); memcpy(bufferPtr, (fFBPool[idx]).getData(), 8192); if (gPMProfOn && gPMStatsPtr) #ifdef _MSC_VER gPMStatsPtr->markEvent(keyFb.lbid, GetCurrentThreadId(), gSession, 'U'); #else gPMStatsPtr->markEvent(keyFb.lbid, pthread_self(), gSession, 'U'); #endif ret = true; } return ret; } uint32_t FileBufferMgr::bulkFind(const BRM::LBID_t* lbids, const BRM::VER_t* vers, uint8_t** buffers, bool* wasCached, uint32_t count) { uint32_t i, ret = 0; filebuffer_uset_iter_t* it = (filebuffer_uset_iter_t*) alloca(count * sizeof(filebuffer_uset_iter_t)); uint32_t* indexes = (uint32_t*) alloca(count * 4); if (gPMProfOn && gPMStatsPtr) { for (i = 0; i < count; i++) { #ifdef _MSC_VER gPMStatsPtr->markEvent(lbids[i], GetCurrentThreadId(), gSession, 'L'); #else gPMStatsPtr->markEvent(lbids[i], pthread_self(), gSession, 'L'); #endif } } boost::mutex::scoped_lock lk(fWLock); if (gPMProfOn && gPMStatsPtr) { for (i = 0; i < count; i++) { #ifdef _MSC_VER gPMStatsPtr->markEvent(lbids[i], GetCurrentThreadId(), gSession, 'M'); #else gPMStatsPtr->markEvent(lbids[i], pthread_self(), gSession, 'M'); #endif } } for (i = 0; i < count; i++) { new ((void*) &it[i]) filebuffer_uset_iter_t(); it[i] = fbSet.find(HashObject_t(lbids[i], vers[i], 0)); if (it[i] != fbSet.end()) { indexes[i] = it[i]->poolIdx; wasCached[i] = true; fFBPool[it[i]->poolIdx].listLoc()->hits++; fbList.splice(fbList.begin(), fbList, (fFBPool[it[i]->poolIdx]).listLoc()); } else { wasCached[i] = false; indexes[i] = 0; } } lk.unlock(); for (i = 0; i < count; i++) { if (wasCached[i]) { memcpy(buffers[i], fFBPool[indexes[i]].getData(), 8192); ret++; if (gPMProfOn && gPMStatsPtr) { #ifdef _MSC_VER gPMStatsPtr->markEvent(lbids[i], GetCurrentThreadId(), gSession, 'U'); #else gPMStatsPtr->markEvent(lbids[i], pthread_self(), gSession, 'U'); #endif } } it[i].filebuffer_uset_iter_t::~filebuffer_uset_iter_t(); } return ret; } bool FileBufferMgr::exists(const HashObject_t& fb) const { bool find_bool = false; boost::mutex::scoped_lock lk(fWLock); filebuffer_uset_iter_t it = fbSet.find(fb); if (it != fbSet.end()) { find_bool = true; fFBPool[it->poolIdx].listLoc()->hits++; fbList.splice(fbList.begin(), fbList, (fFBPool[it->poolIdx]).listLoc()); } return find_bool; } // default insert operation. // add a new fb into fbMgr and to fbList // add to the front and age out from the back // so add new fbs to the front of the list //@bug 665: keep filebuffer in a vector. HashObject keeps the index of the filebuffer int FileBufferMgr::insert(const BRM::LBID_t lbid, const BRM::VER_t ver, const uint8_t* data) { int ret = 0; if (gPMProfOn && gPMStatsPtr) #ifdef _MSC_VER gPMStatsPtr->markEvent(lbid, GetCurrentThreadId(), gSession, 'I'); #else gPMStatsPtr->markEvent(lbid, pthread_self(), gSession, 'I'); #endif boost::mutex::scoped_lock lk(fWLock); HashObject_t fbIndex(lbid, ver, 0); filebuffer_pair_t pr = fbSet.insert(fbIndex); if (pr.second) { // It was inserted (it wasn't there before) // Right now we have an invalid cache: we have inserted an entry with a -1 index. // We need to fix this quickly... fCacheSize++; FBData_t fbdata = {lbid, ver, 0}; fbList.push_front(fbdata); fBlksLoaded++; if (fReportFrequency && (fBlksLoaded % fReportFrequency) == 0) { struct timespec tm; clock_gettime(CLOCK_MONOTONIC, &tm); fLog << "insert: " << left << fixed << ((double)(tm.tv_sec + (1.e-9 * tm.tv_nsec))) << " " << right << setw(12) << fBlksLoaded << " " << right << setw(12) << fBlksNotUsed << endl; } } else { // if it's a duplicate there's nothing to do if (gPMProfOn && gPMStatsPtr) #ifdef _MSC_VER gPMStatsPtr->markEvent(lbid, GetCurrentThreadId(), gSession, 'D'); #else gPMStatsPtr->markEvent(lbid, pthread_self(), gSession, 'D'); #endif return ret; } uint32_t pi = numeric_limits<int>::max(); if (fCacheSize > maxCacheSize()) { // If the insert above caused the cache to exceed its max size, find the lru block in // the cache and use its pool index to store the block data. FBData_t& fbdata = fbList.back(); //the lru block HashObject_t lastFB(fbdata.lbid, fbdata.ver, 0); filebuffer_uset_iter_t iter = fbSet.find( lastFB ); //should be there idbassert(iter != fbSet.end()); pi = iter->poolIdx; idbassert(pi < maxCacheSize()); idbassert(pi < fFBPool.size()); // set iters are always const. We are not changing the hash here, and this gets us // the pointer we need cheaply... HashObject_t& ref = const_cast<HashObject_t&>(*pr.first); ref.poolIdx = pi; //replace the lru block with this block FileBuffer fb(lbid, ver, NULL, 0); fFBPool[pi] = fb; fFBPool[pi].setData(data, 8192); fbSet.erase(iter); if (fbList.back().hits == 0) fBlksNotUsed++; fbList.pop_back(); fCacheSize--; depleteCache(); ret = 1; } else { if ( ! fEmptyPoolSlots.empty() ) { pi = fEmptyPoolSlots.front(); fEmptyPoolSlots.pop_front(); FileBuffer fb(lbid, ver, NULL, 0); fFBPool[pi] = fb; fFBPool[pi].setData(data, 8192); } else { pi = fFBPool.size(); FileBuffer fb(lbid, ver, NULL, 0); fFBPool.push_back(fb); fFBPool[pi].setData(data, 8192); } // See comment above HashObject_t& ref = const_cast<HashObject_t&>(*pr.first); ref.poolIdx = pi; ret = 1; } idbassert(pi < fFBPool.size()); fFBPool[pi].listLoc(fbList.begin()); if (gPMProfOn && gPMStatsPtr) #ifdef _MSC_VER gPMStatsPtr->markEvent(lbid, GetCurrentThreadId(), gSession, 'J'); #else gPMStatsPtr->markEvent(lbid, pthread_self(), gSession, 'J'); #endif idbassert(fCacheSize <= maxCacheSize()); // idbassert(fCacheSize == fbSet.size()); // idbassert(fCacheSize == fbList.size()); return ret; } void FileBufferMgr::depleteCache() { for (uint32_t i = 0; i < fDeleteBlocks && !fbList.empty(); ++i) { FBData_t fbdata(fbList.back()); //the lru block HashObject_t lastFB(fbdata.lbid, fbdata.ver, 0); filebuffer_uset_iter_t iter = fbSet.find( lastFB ); idbassert(iter != fbSet.end()); uint32_t idx = iter->poolIdx; idbassert(idx < fFBPool.size()); //Save position in FileBuffer pool for reuse. fEmptyPoolSlots.push_back(idx); fbSet.erase(iter); if (fbList.back().hits == 0) fBlksNotUsed++; fbList.pop_back(); fCacheSize--; } } ostream& FileBufferMgr::formatLRUList(ostream& os) const { filebuffer_list_t::const_iterator iter = fbList.begin(); filebuffer_list_t::const_iterator end = fbList.end(); while (iter != end) { os << iter->lbid << '\t' << iter->ver << endl; ++iter; } return os; } // puts the new entry at the front of the list void FileBufferMgr::updateLRU(const FBData_t& f) { if (fCacheSize > maxCacheSize()) { list<FBData_t>::iterator last = fbList.end(); last--; FBData_t& fbdata = *last; HashObject_t lastFB(fbdata.lbid, fbdata.ver, 0); filebuffer_uset_iter_t iter = fbSet.find(lastFB); fEmptyPoolSlots.push_back(iter->poolIdx); if (fbdata.hits == 0) fBlksNotUsed++; fbSet.erase(iter); fbList.splice(fbList.begin(), fbList, last); fbdata = f; fCacheSize--; //cout << "booted an entry\n"; } else { //cout << "new entry\n"; fbList.push_front(f); } } uint32_t FileBufferMgr::doBlockCopy(const BRM::LBID_t& lbid, const BRM::VER_t& ver, const uint8_t* data) { uint32_t poolIdx; if (!fEmptyPoolSlots.empty()) { poolIdx = fEmptyPoolSlots.front(); fEmptyPoolSlots.pop_front(); } else { poolIdx = fFBPool.size(); fFBPool.resize(poolIdx + 1); //shouldn't trigger a 'real' resize b/c of the reserve call } fFBPool[poolIdx].Lbid(lbid); fFBPool[poolIdx].Verid(ver); fFBPool[poolIdx].setData(data); return poolIdx; } int FileBufferMgr::bulkInsert(const vector<CacheInsert_t>& ops) { uint32_t i; int32_t pi; int ret = 0; boost::mutex::scoped_lock lk(fWLock); if (fReportFrequency) { fLog << "bulkInsert: "; } for (i = 0; i < ops.size(); i++) { const CacheInsert_t &op = ops[i]; if (gPMProfOn && gPMStatsPtr) #ifdef _MSC_VER gPMStatsPtr->markEvent(op.lbid, GetCurrentThreadId(), gSession, 'I'); #else gPMStatsPtr->markEvent(op.lbid, pthread_self(), gSession, 'I'); #endif HashObject_t fbIndex(op.lbid, op.ver, 0); filebuffer_pair_t pr = fbSet.insert(fbIndex); if (!pr.second) { if (gPMProfOn && gPMStatsPtr) #ifdef _MSC_VER gPMStatsPtr->markEvent(op.lbid, GetCurrentThreadId(), gSession, 'D'); #else gPMStatsPtr->markEvent(op.lbid, pthread_self(), gSession, 'D'); #endif continue; } if (fReportFrequency) { fLog << op.lbid << " " << op.ver << ", "; } fCacheSize++; fBlksLoaded++; FBData_t fbdata = {op.lbid, op.ver, 0}; updateLRU(fbdata); pi = doBlockCopy(op.lbid, op.ver, op.data); HashObject_t& ref = const_cast<HashObject_t&>(*pr.first); ref.poolIdx = pi; fFBPool[pi].listLoc(fbList.begin()); if (gPMProfOn && gPMStatsPtr) #ifdef _MSC_VER gPMStatsPtr->markEvent(op.lbid, GetCurrentThreadId(), gSession, 'J'); #else gPMStatsPtr->markEvent(op.lbid, pthread_self(), gSession, 'J'); #endif ret++; } if (fReportFrequency) { fLog << endl; } idbassert(fCacheSize <= maxCacheSize()); return ret; } }
27.66782
108
0.574787
[ "vector" ]
2dd2a51e3356e772b1309388015c350727256219
3,782
hpp
C++
pse/TGUI-0.7.7/include/TGUI/Clipping.hpp
ValtoLibraries/PUtils
f30ebf21416654743ad2a05b14974acd27257da8
[ "MIT" ]
4
2020-10-06T12:48:22.000Z
2020-12-09T16:08:47.000Z
pse/TGUI-0.7.7/include/TGUI/Clipping.hpp
ValtoLibraries/PUtils
f30ebf21416654743ad2a05b14974acd27257da8
[ "MIT" ]
1
2020-11-24T15:41:11.000Z
2020-11-24T15:41:11.000Z
pse/TGUI-0.7.7/include/TGUI/Clipping.hpp
ValtoLibraries/PUtils
f30ebf21416654743ad2a05b14974acd27257da8
[ "MIT" ]
2
2020-11-19T20:29:14.000Z
2020-12-02T12:55:58.000Z
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TGUI - Texus' Graphical User Interface // Copyright (C) 2012-2017 Bruno Van de Velde (vdv_b@tgui.eu) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef TGUI_CLIPPING_HPP #define TGUI_CLIPPING_HPP #include <TGUI/Global.hpp> #include <SFML/Graphics/RenderTarget.hpp> #include <SFML/Graphics/View.hpp> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace tgui { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class TGUI_API Clipping { public: ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Creates a clipping object which will define a clipping region until the object is destroyed /// /// @param target Target to which we are drawing /// @param states Current render states /// @param topLeft Position of the top left corner of the clipping area relative to the view /// @param size Size of the clipping area relative to the view ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Clipping(sf::RenderTarget& target, const sf::RenderStates& states, sf::Vector2f topLeft, sf::Vector2f size); // The clipping object cannot be copied Clipping(const Clipping& copy) = delete; Clipping& operator=(const Clipping& right) = delete; // When the clipping object is destroyed, the old clipping is restored ~Clipping(); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @internal // Sets the view used by the gui, which the calculations have to take into account when changing the view for clipping ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void setGuiView(const sf::View& view); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private: sf::RenderTarget& m_target; sf::View m_oldView; static sf::View m_originalView; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif // TGUI_CLIPPING_HPP
44.494118
129
0.433369
[ "render", "object" ]
2dd32fc3185c3e6d7c02f25d2a963c549b94be73
590
hpp
C++
graphics/RenderBuffer.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
graphics/RenderBuffer.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
graphics/RenderBuffer.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#ifndef ___INANITY_GRAPHICS_RENDER_BUFFER_HPP___ #define ___INANITY_GRAPHICS_RENDER_BUFFER_HPP___ #include "graphics.hpp" BEGIN_INANITY_GRAPHICS class Texture; /// Абстрактный класс рендербуфера. class RenderBuffer : public Object { public: /// Получить текстуру, соответствующую рендербуферу. /** Может возвращать 0, если рендербуфер не имеет возможности быть источником данных. */ virtual ptr<Texture> GetTexture() = 0; /// Получить текстурную координату, соответствующую "верху" при рендеринге. virtual float GetScreenTopTexcoord() const = 0; }; END_INANITY_GRAPHICS #endif
22.692308
76
0.798305
[ "object" ]
2dd59e9f4fef6a5a0cd05b144d73617f8001f085
33,774
cpp
C++
src/main.cpp
J0Nreynolds/cs425-mp2
1b58ec40f22a900c0bb6327e728b552f3af74696
[ "MIT" ]
2
2018-10-29T16:20:42.000Z
2018-10-29T16:59:23.000Z
src/main.cpp
J0Nreynolds/cs425-mp2
1b58ec40f22a900c0bb6327e728b552f3af74696
[ "MIT" ]
null
null
null
src/main.cpp
J0Nreynolds/cs425-mp2
1b58ec40f22a900c0bb6327e728b552f3af74696
[ "MIT" ]
null
null
null
#include <iostream> #include <list> #include <queue> #include <thread> #include <mutex> #include <chrono> #include <stdio.h> #include <signal.h> #include <time.h> #include <sys/types.h> #include <sys/event.h> #include <math.h> #include "server.h" #include "client.h" #include "common.h" #include "color.h" using namespace std; struct connection { // Declare connection struct type std::string ip; std::string port; Client* client; int server_fd; int timestamp; }; struct fd_information { int pid; bool server_owned; int event_idx; }; struct message { std::string text; int pid; int* V; int id; int value; __int64_t time; }; std::unordered_map<unsigned int, struct connection> processes; std::unordered_map<unsigned int, struct fd_information> fd_info; std::unordered_map<int, int>* decisions; std::queue<struct message> hold_back_queue; unsigned int process_id; static Server* s; static bool end_session = false; static int kq; static int event_idx = 0; static struct kevent* chlist; static struct kevent* evlist; static const struct timespec tmout = { 0, 100000000 }; /* return after 100ms */ static int max_delay, min_delay = 0; static bool is_causally_ordered = false; static int counter = 0; static int message_counter = 0; static bool sequencer = false; static bool kvstore = false; std::ofstream ofs; int W, R; struct valtime { int value; __int64_t time; }; std::unordered_map<char, struct valtime> dict; struct reply { int num; int value; __int64_t time; }; std::unordered_map<int, struct reply> reply_dict; __int64_t ms_start = std::chrono::duration_cast< std::chrono::milliseconds >(std::chrono::system_clock::now().time_since_epoch()).count(); /** * Initializes the unordered_map holding the information needed to connect to each process. */ void parse_config(){ std::ifstream config_file("multicast.config"); std::string line; bool first_line = true; while (std::getline(config_file, line)){ std::istringstream iss(line); if(first_line){ first_line = false; // Get the delay arguments from the first line if (!(iss >> min_delay >> max_delay)) { // error std::cout << "Error parsing config file!" << std::endl; break; } } else{ unsigned int pid; std::string ip, port; // Get three arguments from each line if (!(iss >> pid >> ip >> port)) { // error std::cout << "Error parsing config file!" << std::endl; break; } // Create connection struct instance for hashmap struct connection connection_info; connection_info.ip = ip; connection_info.port = port; connection_info.client = NULL; connection_info.server_fd = -1; connection_info.timestamp = 0; // Create pair for insertion std::pair<unsigned int, struct connection> entry(pid, connection_info); //Insert processes.insert(entry); } } } /** * Helper to print the current changelist we're watching through kqueue */ void print_kevents(){ std::cout << event_idx << " fds: "; for(int i = 0; i < event_idx; i++){ std::cout << chlist[i].ident << " "; } std::cout << std::endl; } /** * Removes kevent listener for file descriptor */ void remove_fd_from_kqueue(int fd){ int idx = fd_info[fd].event_idx; fd_info.erase(fd); event_idx -= 1; unsigned int temp_fd = chlist[event_idx].ident; if(temp_fd != fd){ // We want to swap current event for last event, unless the current event is last // Deleting last event EV_SET(&chlist[event_idx], temp_fd, EVFILT_READ, EV_DELETE, 0, 0, 0); // Reenable last event's fd in event we just deleted EV_SET(&chlist[idx], temp_fd, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, 0); } // else event we want to remove is at end // -> do nothing, we already decremented the event_idx to exclude it from kevent call } /** * Adds kevent listener for file descriptor * If pid of process is unknown, a pid of -1 should be used to indicate that */ void add_fd_to_kqueue(int fd, int pid, bool server_owned){ // Create entry in fd_info for passed fd if(fd == -1) return; fd_information f_info; f_info.pid = pid; f_info.server_owned = server_owned; f_info.event_idx = event_idx; std::pair<unsigned int, struct fd_information> entry(fd, f_info); fd_info.insert(entry); /* Initialize kevent structure. */ EV_SET(&chlist[event_idx++], fd, EVFILT_READ, EV_ADD, 0, 0, 0); } /** * Prepends an message size integer's bytes to a char array, as well as * a char indicating the message protocol */ char* create_message(const char* message, int len, char protocol){ char* output = new char[len + sizeof(int) + sizeof(char)]; memcpy(output, &len, sizeof(int)); memcpy(output+sizeof(int), &protocol, sizeof(char)); memcpy(output+sizeof(int)+sizeof(char), message, len); return output; } /** * Thread function for sending delayed unicast message. Sends particular protocol header and * increments necessary counter. */ void delayed_usend(const char* cstr_message, int len, int fd) { //Format message char* formatted_message = create_message(cstr_message, len+1, 'u'); int delay = rand()%(max_delay - min_delay) + min_delay; //Sleep if not sending to self if(fd_info[fd].pid != process_id) std::this_thread::sleep_for(std::chrono::milliseconds(delay)); //Write message to socket write_all_to_socket(fd, formatted_message, len+1 + sizeof(char) + sizeof(int)); delete[] formatted_message; } /** * Thread function for sending delayed multicast message. Sends particular protocol header and * increments necessary counter. */ void delayed_msend(const char* cstr_message, int len, int fd) { char* formatted_message; if(is_causally_ordered){ // Write the vector timestamp char* output = new char[len + sizeof(int)*processes.size()]; for(int i = 1; i <= processes.size(); i++){ int timestamp = processes[i].timestamp; memcpy(output+(i-1)*sizeof(int), &timestamp, sizeof(int)); } // Write the message memcpy(output + processes.size()*sizeof(int), cstr_message, len); len = processes.size()*sizeof(int) + len; formatted_message = create_message(output, len, 'm'); delete[] output; } else { // Write the message id char* output = new char[len + sizeof(int)]; int id = message_counter; memcpy(output, &id, sizeof(int)); memcpy(output + sizeof(int), (void*) cstr_message, len); // Write the message len = sizeof(int) + len; formatted_message = create_message(output, len, 'm'); delete[] output; } //Format message int delay = rand()%(max_delay - min_delay + 1) + min_delay; //Sleep if not sending to self if(fd_info[fd].pid != process_id) std::this_thread::sleep_for(std::chrono::milliseconds(delay)); //Write message to socket len = len + sizeof(int) + sizeof(char); write_all_to_socket(fd, formatted_message, len); delete[] formatted_message; } void delay(int delay){ std::this_thread::sleep_for(std::chrono::milliseconds(delay)); } /** * Prints the contents of the key-value store to standard out */ void dump(){ for(auto kv : dict){ char key = kv.first; struct valtime vt = kv.second; std::cout << KCYN << "{" << key << ", " << vt.value << "}" << RST << std::endl; } } /** * Returns a string representing the current time in hrs:min:sec:ms */ std::string get_time(){ __int64_t ms_past_epoch = std::chrono::duration_cast< std::chrono::milliseconds >(std::chrono::system_clock::now().time_since_epoch()).count(); __int64_t seconds_past_epoch = time(0); int ms = ms_past_epoch - seconds_past_epoch*1000; time_t theTime = time(NULL); struct tm *aTime = localtime(&theTime); int hour=aTime->tm_hour; int min=aTime->tm_min; int sec=aTime->tm_sec; std::ostringstream oss; oss << hour <<":"<< (min<10 ? "0" : "") << min <<":"<< (sec<10 ? "0" : "") << sec <<":"<< (ms<10 ? "0" : "") << ms; return oss.str(); } /** * Returns the number of ms since the beginning of execution */ __int64_t get_ms(){ __int64_t ms_past_epoch = std::chrono::duration_cast< std::chrono::milliseconds >(std::chrono::system_clock::now().time_since_epoch()).count(); return ms_past_epoch - ms_start; } /** * Thread function for sending delayed sequencer message. Sends particular protocol header and * increments necessary counter. */ void delayed_sequencer_msend(int message_id, int fd, int pid){ int len = sizeof(int)*3; char* formatted_message; //Write info char* output = new char[len]; int decision = decisions[pid - 1][message_id]; memcpy(output, &pid, sizeof(int)); memcpy(output+sizeof(int), &message_id, sizeof(int)); memcpy(output+2*sizeof(int), &decision, sizeof(int)); formatted_message = create_message(output, len, 'o'); delete[] output; int delay = rand()%(max_delay - min_delay + 1) + min_delay; //Sleep if not sending to self if(fd_info[fd].pid != process_id) std::this_thread::sleep_for(std::chrono::milliseconds(delay)); //Write message to socket write_all_to_socket(fd, formatted_message, len + sizeof(char) + sizeof(int)); delete[] formatted_message; } /** * Receives a unicast message */ void unicast_receive(int source, std::string message){ std::cout << KGRN << "Received \"" << message << "\" from process " << source << ", system time is " << get_time() << RST << std::endl; } /** * Unicast sends a message to the group */ void unicast_send(int dest, const char* message, int len){ std::unordered_map<unsigned int, struct connection>::const_iterator result = processes.find(dest); if(result == processes.end()){ std::cout << "Error: could not unicast send to non-existent pid" << std::endl; return; } struct connection info = result->second; std::cout << KRED << "Sent \"" << message << "\" to process " << dest << ", system time is " << get_time() << RST << std::endl; // Send a message with simulated delay std::thread t(delayed_usend, message, len, info.server_fd); t.detach(); } /** * Prints messages as they are delivered */ void delivered(int source, std::string message){ std::cout << KYEL << "Message \"" << message << "\" from process " << source << " delivered. System time is " << get_time() << RST << std::endl; } /** * Receives a multicast message */ void multicast_receive(int source, std::string message){ unicast_receive(source, message); if(is_causally_ordered){ if(source != process_id) processes[source].timestamp += 1; } else { counter += 1; } } /** * Sends a sequencer message to the group */ void sequencer_send(int message_id, int pid){ std::pair<int, int> entry(message_id, counter); decisions[pid-1].insert(entry); for(auto x: processes){ int dest = x.first; struct connection info = x.second; if(info.server_fd == -1) continue; std::cout << KCYN << "Sent sequence for message " << message_id << " to process " << dest << ", system time is " << get_time() << RST << std::endl; // Send a message with simulated delay std::thread t(delayed_sequencer_msend, message_id, info.server_fd, pid); t.detach(); } // Increment the sequence number counter += 1; } /** * Multicast sends a message to the group */ void multicast_send(const char * message, int len){ //Increment this process's timestamp processes[process_id].timestamp += 1; message_counter+=1; for(auto x: processes){ int dest = x.first; struct connection info = x.second; if(info.server_fd == -1) continue; std::cout << KRED << "Sent \"" << message << "\" to process " << dest << ", system time is " << get_time() << RST << std::endl; // Send a message with simulated delay std::thread t(delayed_msend, message, len, info.server_fd); t.detach(); } } /** * The multicast method used for eventual-consistency read and write messages */ void eventual_send(const char* message, int len, int num_replicas){ int i = 0; //Increment this process's timestamp processes[process_id].timestamp += 1; message_counter+=1; num_replicas-=1; for(auto kv : processes){ int dest = kv.first; if (dest == process_id) continue; struct connection info = kv.second; if(info.server_fd == -1) continue; std::cout << KRED << "Sent \"" << message << "\" to process " << dest << ", system time is " << get_time() << RST << std::endl; // Send a message with simulated delay std::thread t(delayed_usend, message, len, info.server_fd); t.detach(); i+=1; if(i == num_replicas) break; } std::thread t(delayed_usend, message, len, processes[process_id].server_fd); t.detach(); } /** * The unicast method used for replying to eventual-consistency read messages */ void eventual_reply(struct message m){ std::cout << m.pid << " " << m.text << " " << m.id << std::endl; struct connection info = processes[m.pid]; char* message = new char[2 + 2*sizeof(int) + sizeof(__int64_t)]; message[0] = 'R'; message[1] = m.text[1]; if(dict.find(m.text[1]) == dict.end()){ *((int*)(message + 2)) = 0; *((int*)(message + 2 + sizeof(int))) = m.id; *((__int64_t*)(message + 2 + 2*sizeof(int))) = 0; } else { *((int*)(message + 2)) = dict[m.text[1]].value; *((int*)(message + 2 + sizeof(int))) = m.id; *((__int64_t*)(message + 2 + 2*sizeof(int))) = dict[m.text[1]].time; } std::thread t(delayed_usend, message, 2 + 2*sizeof(int) + sizeof(__int64_t), info.server_fd); t.detach(); } /** * Issue a GET command to the distributed key-value store */ void kvstore_get(std::string keyname){ std::cout << KRED << "GET \"" << keyname << "\", system time is " << get_time() << RST << std::endl; if(is_causally_ordered){ // Log beginning of GET request ofs << 425 << ',' << process_id << ',' << "get" << ',' << keyname << ',' << get_ms() << ',' << "req" << std::endl; } else { // Log beginning of GET request ofs << 425 << ',' << process_id << ',' << "get" << ',' << keyname << ',' << counter << ',' << "req" << std::endl; } // Create message char* message = new char[2 + sizeof(int)]; message[0] = 'r'; message[1] = keyname[0]; if(is_causally_ordered){ // If we're using eventual *((int*)(message+2)) = message_counter; struct reply r; r.num = 0; r.value = 0; r.time = 0; std::pair<int, struct reply> entry(message_counter, r); reply_dict.insert(entry); eventual_send(message, 2+sizeof(int), R); } else { multicast_send(message, 2); } } /** * Issue a PUT command to the distributed key-value store */ void kvstore_put(std::string keyname, int value){ std::cout << KRED << "PUT {\"" << keyname << "\", " << value << "} system time is " << get_time() << RST << std::endl; if(is_causally_ordered){ // If we're using eventual // Log beginning of PUT request ofs << 425 << ',' << process_id << ',' << "put" << ',' << keyname << ',' << get_ms() << ',' << "req" << ',' << value << std::endl; } else { // Log beginning of PUT request ofs << 425 << ',' << process_id << ',' << "put" << ',' << keyname << ',' << counter << ',' << "req" << ',' << value << std::endl; } // Create message char* message = new char[2 + sizeof(int)]; message[0] = 'w'; message[1] = keyname[0]; *((int*)(message + 2)) = value; *((__int64_t*)(message + 2 + sizeof(int))) = get_ms(); if(is_causally_ordered){ // If we're using eventual eventual_send(message, 2+sizeof(int)+sizeof(__int64_t), W); } else { multicast_send(message, 2+sizeof(int)); } free(message); } /** * Fill message member values and print delivery messages to standard out */ void kvstore_delivered(struct message& m, char* read_bytes, int offset){ m.text = m.text.substr(0,2); if(m.text[0] == 'w'){ m.value = *((int*) (read_bytes+offset+2) ); if(is_causally_ordered){ m.time = *((__int64_t*) (read_bytes+offset+2+sizeof(int))); delivered(m.pid, "Write(" + m.text.substr(1,1) + ", " + std::to_string(m.value) + ") at " + std::to_string(m.time)); } else{ delivered(m.pid, "Write(" + m.text.substr(1,1) + ", " + std::to_string(m.value) + ")"); } } else if (m.text[0] == 'r'){ if(is_causally_ordered){ m.id = *((int*) (read_bytes+offset+2) ); delivered(m.pid, "Read(" + m.text.substr(1,1) + ")" + " with id " + std::to_string(m.id)); } else { delivered(m.pid, "Read(" + m.text.substr(1,1) + ")"); } } else if(m.text[0] == 'R'){ m.value = *((int*) (read_bytes+offset+2) ); m.id = *((int*) (read_bytes+offset+2+sizeof(int)) ); m.time = *((__int64_t*) (read_bytes+offset+2+2*sizeof(int))); std::cout << m.pid << " " << m.text << " " << m.id << " " << m.value << " " << m.time << std::endl; delivered(m.pid, "Reply(" + m.text.substr(1,1) + "," + std::to_string(m.value) +")" + " with id " + std::to_string(m.id) + " time " + std::to_string(m.time)); } } /** * Handle message receivals and print receival messages to standard out */ void kvstore_receive(struct message m){ if(m.text[0] == 'r'){ multicast_receive(m.pid, "Read(" + m.text.substr(1,1) + ")"); //Read from keystore if(dict.find(m.text[1]) == dict.end()){ //Handle non-existent case if(!is_causally_ordered){ if(m.pid == process_id){ ofs << 425 << ',' << process_id << ',' << "get" << ',' << m.text[1] << ',' << counter << ',' << "resp" << ',' << 0 << std::endl; } } else { eventual_reply(m); } } else { struct valtime result = dict[m.text[1]]; // Ack if(!is_causally_ordered){ if(m.pid == process_id){ ofs << 425 << ',' << process_id << ',' << "get" << ',' << m.text[1] << ',' << counter << ',' << "resp" << ',' << result.value << std::endl; } } else { eventual_reply(m); } } } else if (m.text[0] == 'w'){ multicast_receive(m.pid, "Write(" + m.text.substr(1,1) + ", " + std::to_string(m.value) + ")"); bool write = false; if(!is_causally_ordered){ write = true; } else if(dict.find(m.text[1]) == dict.end()){ write = true; } else { write = dict[m.text[1]].time < m.time; } if(write){ dict[m.text[1]].value = m.value; if(is_causally_ordered) dict[m.text[1]].time = m.time; // Ack if(m.pid == process_id){ if(!is_causally_ordered) ofs << 425 << ',' << process_id << ',' << "put" << ',' << m.text[1] << ',' << counter << ',' << "resp" << ',' << dict[m.text[1]].value << std::endl; else ofs << 425 << ',' << process_id << ',' << "put" << ',' << m.text[1] << ',' << get_ms() << ',' << "resp" << ',' << dict[m.text[1]].value << std::endl; } } } else if (m.text[0] == 'R'){ if(reply_dict.find(m.id) != reply_dict.end()){ reply_dict[m.id].num += 1; if(m.time > reply_dict[m.id].time){ reply_dict[m.id].time = m.time; reply_dict[m.id].value = m.value; std::cout << "Updated reply : {" << reply_dict[m.id].num << "," << reply_dict[m.id].value << "," << reply_dict[m.id].time << "}" << std::endl; } if(reply_dict[m.id].num == R){ ofs << 425 << ',' << process_id << ',' << "get" << ',' << m.text[1] << ',' << get_ms() << ',' << "resp" << ',' << reply_dict[m.id].value << std::endl; reply_dict.erase(m.id); } } } } /** * Processes any updated file descriptors */ void process_fds(){ int nev = kevent(kq, chlist, event_idx, evlist, event_idx, &tmout); if (nev == -1) { perror("kevent()"); exit(1); } for(int i = 0; i < nev; i ++){ // For each event triggered int fd = evlist[i].ident; // Get the file descriptor if (evlist[i].flags & EV_ERROR) { // report errors if any fprintf(stderr, "EV_ERROR: %s\n%d\n", strerror(evlist[i].data), fd); exit(1); }; if(evlist[i].flags & EV_EOF){ // Handle disconnects // std::cout << "Socket fd " << fd << " for process " << fd_info[fd].pid << " disconnected." << std::endl; if(!fd_info[fd].server_owned){ processes[fd_info[fd].pid].client->close(); } // Close fd and set connected false else { ::close(fd); } // Otherwise close fd and wait for new client to connect remove_fd_from_kqueue(fd); return; } if(fd_info[fd].server_owned){ // Then it's a remote client telling us their ID so we can connect to them // Read the process id sent from the client unsigned int pid = 0; int read_bytes = read_all_from_socket(fd, (char *) &pid, sizeof(int)); if(read_bytes == -1){ // Error case std::cout << "Error reading from socket" <<read_bytes<<std::endl; exit(1); } // std::cout << "Got id: " << pid << " from client with fd: " << fd << std::endl; // Update process info with server file descriptor struct connection& info = processes[pid]; info.server_fd = fd; fd_info[fd].pid = pid; if(pid != process_id && !processes[pid].client->is_connected()){ // If we don't already have a client for pid // std::cout << "Attempting to connect back to server " << pid << " at port " << info.port << std::endl; int client_fd = info.client->connect_to_server(info.ip, info.port); if(client_fd >= 0){ // Success add_fd_to_kqueue(client_fd, pid, false); } } } else { //Then there is an update from another server. // Get the num of bytes to read int read_len; read_all_from_socket(fd, (char *) &read_len, sizeof(int)); // Get the protocol (msend or usend) char protocol; read_all_from_socket(fd, &protocol, sizeof(char)); if(protocol == 'm'){ if(is_causally_ordered){ struct message m; m.pid = fd_info[fd].pid; m.V = new int[processes.size()]; char* read_bytes = new char[read_len]; read_all_from_socket(fd, read_bytes, read_len); int timestamp; for(int i = 0; i < processes.size(); i ++){ memcpy(&timestamp, read_bytes+i*sizeof(int), sizeof(int)); m.V[i] = timestamp; } m.text = std::string(read_bytes+sizeof(int)*processes.size()); delivered(m.pid, m.text); free(read_bytes); hold_back_queue.push(m); } else { struct message m; m.pid = fd_info[fd].pid; char* read_bytes = new char[read_len]; read_all_from_socket(fd, read_bytes, read_len); int id; memcpy(&id, read_bytes, sizeof(int)); m.id = id; m.text = std::string(read_bytes+sizeof(int)); if(kvstore){ kvstore_delivered(m, read_bytes, sizeof(int)); } else{ delivered(m.pid, m.text); } if(sequencer) sequencer_send(m.id, m.pid); else hold_back_queue.push(m); } } else if(protocol == 'u'){ // Read the message if(kvstore){ struct message m; m.pid = fd_info[fd].pid; char* read_bytes = new char[read_len]; read_all_from_socket(fd, read_bytes, read_len); m.text = std::string(read_bytes); kvstore_delivered(m, read_bytes, 0); kvstore_receive(m); } else { char buf[read_len]; read_all_from_socket(fd, buf, read_len); unicast_receive(fd_info[fd].pid, std::string(buf)); } } else { int pid, id, decision; char buf[read_len]; read_all_from_socket(fd, buf, read_len); memcpy(&pid, buf, sizeof(int)); memcpy(&id, buf+sizeof(int), sizeof(int)); memcpy(&decision, buf+2*sizeof(int), sizeof(int)); // std::cout << "Decision: " << decision << " for message " << id << std::endl; std::pair<int, int> entry(id, decision); decisions[pid-1].insert(entry); } } } } /** * Checks the hold-back queue for any messages that can be received */ void check_queue(){ for(int j = 0; j < hold_back_queue.size(); j ++){ struct message m = hold_back_queue.front(); hold_back_queue.pop(); if(is_causally_ordered){ bool failed = false; for(int i = 0 ; i < processes.size(); i ++){ int timestamp = m.V[i]; int pid = i+1; if(m.pid == process_id) break; if(pid == m.pid && timestamp != (processes[pid].timestamp + 1) ){ // Guarantees V_q[i] == V_p[i] + 1 failed = true; break; } if(pid != m.pid && timestamp > (processes[pid].timestamp) ){ // Guarantees V_q[i] <= V_p[i] failed = true; break; } } if(!failed){ delete[] m.V; if(kvstore){ kvstore_receive(m); } else { multicast_receive(m.pid, m.text); } } else { hold_back_queue.push(m); } } else { std::unordered_map<int, int>::const_iterator result = decisions[m.pid-1].find(m.id); // std::cout << m.text << " " << m.pid << " " << m.id <<std::endl; //If there hasn't been a sequencer decision yet if(result == decisions[m.pid-1].end()){ hold_back_queue.push(m); } else { int decision = result->second; if(counter == decision){ if(kvstore){ kvstore_receive(m); } else { multicast_receive(m.pid, m.text); } decisions[m.pid-1].erase(m.id); } else { // Wait till later hold_back_queue.push(m); } } } } } /** * Checks if there is user input to process and handles it if so */ void process_input(){ std::string command, dest_string, message, keyname, value_string; int value; // Used for scanning integers into (e.g. unicast-send destination, kvstore-get value) std::string line; std::getline( std::cin, line ); if(line.empty()){ std::cin.clear(); return; } int space1_idx = line.find(' ', 0); if(space1_idx == std::string::npos){ return; } // incorrect command format - must have at least one space int space2_idx = line.find(' ', space1_idx+1); command = line.substr(0, space1_idx); if(command.compare("msend") == 0){ // Must be a multicast send message = line.substr(space1_idx + 1, std::string::npos); multicast_send(message.c_str(), message.size()); } else if(command.compare("send") == 0){ //Assume it's a unicast send dest_string = line.substr(space1_idx+1, space2_idx-space1_idx-1); message = line.substr(space2_idx + 1, std::string::npos); sscanf(dest_string.c_str(), "%d", &value); unicast_send(value, message.c_str(), message.size()); } else if(command.compare("get") == 0){ keyname = line.substr(space1_idx + 1, std::string::npos); kvstore_get(keyname); } else if(command.compare("put") == 0){ keyname = line.substr(space1_idx+1, space2_idx-space1_idx-1); value_string = line.substr(space2_idx + 1, std::string::npos); sscanf(value_string.c_str(), "%d", &value); kvstore_put(keyname, value); } else if(command.compare("delay") == 0){ value_string = line.substr(space1_idx + 1, std::string::npos); sscanf(value_string.c_str(), "%d", &value); delay(value); } else if(command.compare("dump") == 0){ dump(); } else { std::cout << "Error: invalid command!" << std::endl; } } /** * Frees memory and closes all file descriptors still in use */ void close_process(int sig){ delete[] chlist; delete[] evlist; for(auto x: fd_info){ int fd = x.first; struct fd_information info = x.second; if(info.server_owned){ shutdown(fd, SHUT_RDWR); ::close(fd); remove_fd_from_kqueue(fd); } else { ::close(fd); } } s->close(); delete s; for(auto x: processes){ struct connection info = x.second; delete info.client; } delete[] decisions; end_session = true; } /** * Runs the program */ int main(int argc, char **argv) { std::string filename = "log"+std::string(argv[1])+".txt"; ofs = std::ofstream(filename.c_str(), std::ofstream::trunc); if(argc >= 3){ std::cout << "Starting process with id " << argv[1] << " using " << argv[2] << " ordering." << std::endl; std::string protocol = argv[2]; if(protocol.compare("causal") == 0){ is_causally_ordered = true; } else if(protocol.compare("linearizable") == 0){ kvstore = true; is_causally_ordered = false; } else if(protocol.compare("eventual") == 0){ kvstore = true; is_causally_ordered = true; sscanf(argv[3], "%d", &R); sscanf(argv[4], "%d", &W); } else { is_causally_ordered = false; } } else { std::cout << "Starting process with id " << argv[1] << std::endl; } if(argc == 4 && !is_causally_ordered){ sequencer = true; } sscanf(argv[1], "%d", &process_id); // Set cin to be non-blocking int flags = fcntl(0, F_GETFL, 0); fcntl(0, F_SETFL, flags | O_NONBLOCK); struct sigaction act; memset(&act, '\0', sizeof(act)); act.sa_handler = close_process; if (sigaction(SIGINT, &act, NULL) < 0) { perror("sigaction"); return 1; } parse_config(); decisions = new std::unordered_map<int, int>[processes.size()]; chlist = new struct kevent[2*processes.size()]; // 2 fds per process evlist = new struct kevent[2*processes.size()]; // 2 fds per process if ((kq = kqueue()) == -1) { perror("kqueue"); exit(1); } s = new Server(processes[process_id].port, processes.size()); // Set up kevent to fire events for new connections on server's listening socket struct kevent server_event, server_result; EV_SET(&server_event, s->get_socket_fd(), EVFILT_READ, EV_ADD, 0, 0, 0); for(auto x: processes){ unsigned int pid = x.first; processes[pid].client = new Client(processes[pid].ip, processes[pid].port, process_id); if(processes[pid].client->is_connected()){ // If client connection attempt was successful add_fd_to_kqueue(processes[pid].client->get_socket_fd(), pid, false); } } while(!end_session){ EV_SET(&server_event, s->get_socket_fd(), EVFILT_READ, EV_ENABLE, 0, 0, 0); int nev = kevent(kq, &server_event, 1, &server_result, 1, &tmout); // Check for new connections to server EV_SET(&server_event, s->get_socket_fd(), EVFILT_READ, EV_DISABLE, 0, 0, 0); if(nev == 1){ for(int i = 0; i < server_result.data; i++){ int fd = s->accept_client(); if(fd >= 0){ add_fd_to_kqueue(fd, -1, true); } } } process_fds(); if(!sequencer){ process_input(); if(!hold_back_queue.empty()){ check_queue(); } } } }
34.926577
170
0.549298
[ "vector" ]
2ddce13c3c84bf1519c3aca06209d5d87f49404c
13,004
cc
C++
src/cpu/inorder/resource.cc
volnxebec/CC_Fused
e2b805e3475bd275409379c41eaeeb1a565cbdef
[ "BSD-3-Clause" ]
null
null
null
src/cpu/inorder/resource.cc
volnxebec/CC_Fused
e2b805e3475bd275409379c41eaeeb1a565cbdef
[ "BSD-3-Clause" ]
null
null
null
src/cpu/inorder/resource.cc
volnxebec/CC_Fused
e2b805e3475bd275409379c41eaeeb1a565cbdef
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2007 MIPS Technologies, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Korey Sewell * */ #include <list> #include <vector> #include "base/str.hh" #include "cpu/inorder/cpu.hh" #include "cpu/inorder/resource.hh" #include "cpu/inorder/resource_pool.hh" #include "debug/ExecFaulting.hh" #include "debug/RefCount.hh" #include "debug/ResReqCount.hh" #include "debug/Resource.hh" using namespace std; Resource::Resource(string res_name, int res_id, int res_width, int res_latency, InOrderCPU *_cpu) : resName(res_name), id(res_id), width(res_width), latency(res_latency), cpu(_cpu), resourceEvent(NULL) { reqs.resize(width); // Use to deny a instruction a resource. deniedReq = new ResourceRequest(this); deniedReq->valid = true; } Resource::~Resource() { if (resourceEvent) { delete [] resourceEvent; } delete deniedReq; for (int i = 0; i < width; i++) { delete reqs[i]; } } void Resource::init() { // If the resource has a zero-cycle (no latency) // function, then no reason to have events // that will process them for the right tick if (latency > 0) resourceEvent = new ResourceEvent[width]; for (int i = 0; i < width; i++) reqs[i] = new ResourceRequest(this); initSlots(); } void Resource::initSlots() { // Add available slot numbers for resource for (int slot_idx = 0; slot_idx < width; slot_idx++) { availSlots.push_back(slot_idx); if (resourceEvent) { resourceEvent[slot_idx].init(this, slot_idx); } } } std::string Resource::name() { return cpu->name() + "." + resName; } int Resource::slotsAvail() { return availSlots.size(); } int Resource::slotsInUse() { return width - availSlots.size(); } void Resource::freeSlot(int slot_idx) { DPRINTF(Resource, "Deallocating [slot:%i].\n", slot_idx); // Put slot number on this resource's free list availSlots.push_back(slot_idx); // Invalidate Request & Reset it's flags reqs[slot_idx]->clearRequest(); } int Resource::findSlot(DynInstPtr inst) { int slot_num = -1; for (int i = 0; i < width; i++) { if (reqs[i]->valid && reqs[i]->getInst()->seqNum == inst->seqNum) { slot_num = reqs[i]->getSlot(); } } return slot_num; } int Resource::getSlot(DynInstPtr inst) { int slot_num = -1; if (slotsAvail() != 0) { slot_num = availSlots[0]; vector<int>::iterator vect_it = availSlots.begin(); assert(slot_num == *vect_it); availSlots.erase(vect_it); } return slot_num; } ResReqPtr Resource::request(DynInstPtr inst) { // See if the resource is already serving this instruction. // If so, use that request; bool try_request = false; int slot_num = -1; int stage_num; ResReqPtr inst_req = findRequest(inst); if (inst_req) { // If some preprocessing has to be done on instruction // that has already requested once, then handle it here. // update the 'try_request' variable if we should // re-execute the request. requestAgain(inst, try_request); slot_num = inst_req->getSlot(); stage_num = inst_req->getStageNum(); } else { // Get new slot # for instruction slot_num = getSlot(inst); if (slot_num != -1) { DPRINTF(Resource, "Allocating [slot:%i] for [tid:%i]: [sn:%i]\n", slot_num, inst->readTid(), inst->seqNum); // Get Stage # from Schedule Entry stage_num = inst->curSkedEntry->stageNum; unsigned cmd = inst->curSkedEntry->cmd; // Generate Resource Request inst_req = getRequest(inst, stage_num, id, slot_num, cmd); if (inst->staticInst) { DPRINTF(Resource, "[tid:%i]: [sn:%i] requesting this " "resource.\n", inst->readTid(), inst->seqNum); } else { DPRINTF(Resource, "[tid:%i]: instruction requesting this " "resource.\n", inst->readTid()); } try_request = true; } else { DPRINTF(Resource, "No slot available for [tid:%i]: [sn:%i]\n", inst->readTid(), inst->seqNum); } } if (try_request) { // Schedule execution of resource scheduleExecution(slot_num); } else { inst_req = deniedReq; rejectRequest(inst); } return inst_req; } void Resource::requestAgain(DynInstPtr inst, bool &do_request) { do_request = true; if (inst->staticInst) { DPRINTF(Resource, "[tid:%i]: [sn:%i] requesting this resource " "again.\n", inst->readTid(), inst->seqNum); } else { DPRINTF(Resource, "[tid:%i]: requesting this resource again.\n", inst->readTid()); } } ResReqPtr Resource::getRequest(DynInstPtr inst, int stage_num, int res_idx, int slot_num, unsigned cmd) { reqs[slot_num]->setRequest(inst, stage_num, id, slot_num, cmd); return reqs[slot_num]; } ResReqPtr Resource::findRequest(DynInstPtr inst) { for (int i = 0; i < width; i++) { if (reqs[i]->valid && reqs[i]->getInst() == inst) { return reqs[i]; } } return NULL; } void Resource::rejectRequest(DynInstPtr inst) { DPRINTF(RefCount, "[tid:%i]: Unable to grant request for [sn:%i].\n", inst->readTid(), inst->seqNum); } void Resource::execute(int slot_idx) { //@todo: have each resource print out command their executing DPRINTF(Resource, "[tid:%i]: Executing %s resource.\n", reqs[slot_idx]->getTid(), name()); reqs[slot_idx]->setCompleted(true); reqs[slot_idx]->done(); } void Resource::deactivateThread(ThreadID tid) { // In the most basic case, deactivation means squashing everything // from a particular thread DynInstPtr dummy_inst = new InOrderDynInst(cpu, NULL, 0, tid, tid); squash(dummy_inst, 0, 0, tid); } void Resource::setupSquash(DynInstPtr inst, int stage_num, ThreadID tid) { // Squash In Pipeline Stage cpu->pipelineStage[stage_num]->setupSquash(inst, tid); // Schedule Squash Through-out Resource Pool cpu->resPool->scheduleEvent( (InOrderCPU::CPUEventType)ResourcePool::SquashAll, inst, 0); } void Resource::squash(DynInstPtr inst, int stage_num, InstSeqNum squash_seq_num, ThreadID tid) { //@todo: check squash seq num before squashing. can save time going // through this function. for (int i = 0; i < width; i++) { ResReqPtr req_ptr = reqs[i]; DynInstPtr inst = req_ptr->getInst(); if (req_ptr->valid && inst->readTid() == tid && inst->seqNum > squash_seq_num) { DPRINTF(Resource, "[tid:%i]: Squashing [sn:%i].\n", req_ptr->getInst()->readTid(), req_ptr->getInst()->seqNum); req_ptr->setSquashed(); int req_slot_num = req_ptr->getSlot(); if (latency > 0) { if (resourceEvent[req_slot_num].scheduled()) unscheduleEvent(req_slot_num); } freeSlot(req_slot_num); } } } void Resource::squashDueToMemStall(DynInstPtr inst, int stage_num, InstSeqNum squash_seq_num, ThreadID tid) { squash(inst, stage_num, squash_seq_num, tid); } void Resource::squashThenTrap(int stage_num, DynInstPtr inst) { ThreadID tid = inst->readTid(); inst->setSquashInfo(stage_num); setupSquash(inst, stage_num, tid); if (inst->traceData) { if (inst->staticInst && inst->fault != NoFault && DTRACE(ExecFaulting)) { inst->traceData->setStageCycle(stage_num, curTick()); inst->traceData->setFetchSeq(inst->seqNum); inst->traceData->dump(); } delete inst->traceData; inst->traceData = NULL; } cpu->trapContext(inst->fault, tid, inst); } Tick Resource::ticks(int num_cycles) { return cpu->ticks(num_cycles); } void Resource::scheduleExecution(int slot_num) { if (latency >= 1) { scheduleEvent(slot_num, latency); } else { execute(slot_num); } } void Resource::scheduleEvent(int slot_idx, int delay) { DPRINTF(Resource, "[tid:%i]: Scheduling event for [sn:%i] on tick %i.\n", reqs[slot_idx]->inst->readTid(), reqs[slot_idx]->inst->seqNum, cpu->ticks(delay) + curTick()); resourceEvent[slot_idx].scheduleEvent(delay); } bool Resource::scheduleEvent(DynInstPtr inst, int delay) { int slot_idx = findSlot(inst); if(slot_idx != -1) resourceEvent[slot_idx].scheduleEvent(delay); return slot_idx; } void Resource::unscheduleEvent(int slot_idx) { resourceEvent[slot_idx].unscheduleEvent(); } bool Resource::unscheduleEvent(DynInstPtr inst) { int slot_idx = findSlot(inst); if(slot_idx != -1) resourceEvent[slot_idx].unscheduleEvent(); return slot_idx; } int ResourceRequest::resReqID = 0; int ResourceRequest::maxReqCount = 0; ResourceRequest::ResourceRequest(Resource *_res) : res(_res), inst(NULL), stagePasses(0), valid(false), doneInResource(false), completed(false), squashed(false), processing(false), memStall(false) { } ResourceRequest::~ResourceRequest() { #ifdef DEBUG res->cpu->resReqCount--; DPRINTF(ResReqCount, "Res. Req %i deleted. resReqCount=%i.\n", reqID, res->cpu->resReqCount); #endif inst = NULL; } std::string ResourceRequest::name() { return csprintf("%s[slot:%i]:", res->name(), slotNum); } void ResourceRequest::setRequest(DynInstPtr _inst, int stage_num, int res_idx, int slot_num, unsigned _cmd) { valid = true; inst = _inst; stageNum = stage_num; resIdx = res_idx; slotNum = slot_num; cmd = _cmd; } void ResourceRequest::clearRequest() { valid = false; inst = NULL; stagePasses = 0; completed = false; doneInResource = false; squashed = false; memStall = false; } void ResourceRequest::freeSlot() { assert(res); // Free Slot So Another Instruction Can Use This Resource res->freeSlot(slotNum); } void ResourceRequest::done(bool completed) { DPRINTF(Resource, "done with request from " "[sn:%i] [tid:%i].\n", inst->seqNum, inst->readTid()); setCompleted(completed); doneInResource = true; } ResourceEvent::ResourceEvent() : Event((Event::Priority)Resource_Event_Pri) { } ResourceEvent::ResourceEvent(Resource *res, int slot_idx) : Event((Event::Priority)Resource_Event_Pri), resource(res), slotIdx(slot_idx) { } void ResourceEvent::init(Resource *res, int slot_idx) { resource = res; slotIdx = slot_idx; } void ResourceEvent::process() { resource->execute(slotIdx); } const char * ResourceEvent::description() const { string desc = resource->name() + "-event:slot[" + to_string(slotIdx) + "]"; return desc.c_str(); } void ResourceEvent::scheduleEvent(int delay) { assert(!scheduled() || squashed()); resource->cpu->reschedule(this, curTick() + resource->ticks(delay), true); }
24.535849
81
0.622962
[ "vector" ]
2ddda9ed5153f90d9d741d40b5be66e72c20b7b1
237
hpp
C++
src/Client/Engine/Vignette.hpp
fqhd/BuildBattle
f85ec857aa232313f4678514aa317af73c37de10
[ "MIT" ]
10
2021-08-17T20:55:52.000Z
2022-03-28T00:45:14.000Z
src/Client/Engine/Vignette.hpp
fqhd/BuildBattle
f85ec857aa232313f4678514aa317af73c37de10
[ "MIT" ]
null
null
null
src/Client/Engine/Vignette.hpp
fqhd/BuildBattle
f85ec857aa232313f4678514aa317af73c37de10
[ "MIT" ]
2
2021-07-05T18:49:56.000Z
2021-07-10T22:03:17.000Z
#pragma once #include "VignetteQuad.hpp" #include "Shader.hpp" class Vignette { public: void init(); void render(); // Renders a quad with the vignette shader void destroy(); private: VignetteQuad m_quad; Shader m_shader; };
11.85
58
0.708861
[ "render" ]
2de89302759a127e6a66815187b3bdb9bab82775
1,803
hpp
C++
src/User/User.hpp
hallainea/ft_irc
389ff7c1c93e72739e373c74b69ec826535216e4
[ "Apache-2.0" ]
6
2021-12-10T18:35:26.000Z
2022-03-23T21:46:14.000Z
src/User/User.hpp
Assxios/ft_irc
389ff7c1c93e72739e373c74b69ec826535216e4
[ "Apache-2.0" ]
null
null
null
src/User/User.hpp
Assxios/ft_irc
389ff7c1c93e72739e373c74b69ec826535216e4
[ "Apache-2.0" ]
3
2021-12-19T18:11:13.000Z
2022-02-02T13:29:31.000Z
#ifndef USER_HPP #define USER_HPP #include <netinet/in.h> #include <string> #include <vector> #include <map> namespace irc { enum UserStatus { PASSWORD, REGISTER, ONLINE, DELETE }; class Command; class Server; class User { friend class Server; private: std::map<std::string, void (*)(Command *)> command_function; int fd; std::string buffer; std::vector<Command *> commands; std::vector<std::string> waitingToSend; UserStatus status; time_t last_ping; std::string hostaddr; std::string hostname; std::string nickname; std::string username; std::string realname; std::string mode; std::string pastnick; std::string lastChannel; std::string deleteMessage; std::string awayMessage; void dispatch(); void receive(Server *server); void write(std::string message); void push(); public: User(int fd, struct sockaddr_in address); ~User(); void sendTo(User &toUser, std::string message); void setStatus(UserStatus status); void setLastPing(time_t last_ping); void setNickname(std::string nickname); void setUsername(std::string username); void setRealname(std::string realname); int getFd(); UserStatus getStatus(); time_t getLastPing(); std::string getPrefix(); std::string getHostaddr(); std::string getHostname(); std::string getHost(); std::string getNickname(); std::string getUsername(); std::string getRealname(); void setMode(std::string mode); void setPastnick(std::string pastnick); void setLastChannel(std::string lastChannel); void setDeleteMessage(std::string message); void setAwayMessage(std::string message); std::string getMode(); std::string getPastnick(); std::string getLastChannel(); std::string getDeleteMessage(); std::string getAwayMessage(); }; } #endif
20.033333
62
0.705491
[ "vector" ]
2ded46ccaf5530957733325dd7a9136432072e7e
785
cc
C++
accepted/701A.cc
cbarnson/codeforces-cpp
adf0ee2d71a8abbec1e111013bf9bfa7cda02395
[ "MIT" ]
1
2019-06-14T02:21:30.000Z
2019-06-14T02:21:30.000Z
accepted/701A.cc
cbarnson/codeforces-cpp
adf0ee2d71a8abbec1e111013bf9bfa7cda02395
[ "MIT" ]
null
null
null
accepted/701A.cc
cbarnson/codeforces-cpp
adf0ee2d71a8abbec1e111013bf9bfa7cda02395
[ "MIT" ]
null
null
null
// Problem # : 701A // Created on : 2018-Nov-01 10:37:01 #include <bits/stdc++.h> #define FR(i, n) for (int i = 0; i < (int)(n); ++i) using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vi a(n); FR (i, n) cin >> a[i]; // value we need per player int x = accumulate(begin(a), end(a), 0) * 2 / (n); vi used(n, 0); FR (i, n / 2) { FR (k, n) { if (!used[k]) { for (int j = k + 1; j < n; j++) { if (!used[j] && a[k] + a[j] == x) { cout << k + 1 << " " << j + 1 << endl; used[k] = used[j] = 1; break; } } } } } }
20.657895
53
0.42293
[ "vector" ]
2def1ed7535cbf04e778436b73991e3b07804244
4,441
hpp
C++
src/Core/Animation/Sequence/Sequence.hpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
src/Core/Animation/Sequence/Sequence.hpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
src/Core/Animation/Sequence/Sequence.hpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
#ifndef RADIUMENGINE_SEQUENCE_HPP #define RADIUMENGINE_SEQUENCE_HPP #include <vector> #include <Core/CoreMacros.hpp> #include <Core/Index/CircularIndex.hpp> #include <Core/Animation/Pose/Pose.hpp> namespace Ra { namespace Core { namespace Animation { typedef Pose Frame; typedef std::vector< Frame > FrameSet; /** * The class Sequence is a container for an animation sequence. * **/ class Sequence { public: /// ENUM // Specify if the sequence stores trasformations to be applied or // poses to be assigned. enum class PoseType { Pose_RELATIVE, Pose_ABSOLUTE }; /// CONSTRUCTOR Sequence(); // Default constructor Sequence( const Sequence& sequence ); // Copy constructor /// DESTRUCTOR virtual ~Sequence(); /// SIZE INTERFACE virtual uint size() const = 0; // Return the size of the sequence virtual void clear(); // Clear the sequence. By default does nothing /// QUERY inline bool isEmpty() const; // Return true if the size of the sequence is equal to zero /// POSE TYPE inline PoseType getPoseType() const; // Get the type of the poses stored inline void setPoseType( const PoseType& type ); // Set the type of the poses stored /// SEQUENCE INTERFACE virtual FrameSet getSequence() const = 0; // Return the set of frames virtual void setSequence( const FrameSet& set ); // Set the frame set /// POSE INTERFACE virtual Frame frame( const int i ) const = 0; // Get the i-th frame. virtual void setFrame( const int i, const Frame& frame ); // Set the i-th frame to frame inline Frame nextFrame() const; // Return the frame in the next position inline Frame prevFrame() const; // Return the frame in the prev position inline Frame currentFrame() const; // Return the frame in the current position inline Frame firstFrame() const; // Return the frame in the first position inline Frame lastFrame() const; // Return the frame in the last position /// INDEX inline uint nextFrameIndex() const; // Return the index of the next frame inline uint prevFrameIndex() const; // Return the index of the prev frame inline uint currentFrameIndex() const; // Return the index of the current frame inline uint firstFrameIndex() const; // Return the index of the first frame inline uint lastFrameIndex() const; // Return the index of the last frame /// INSERT POSE virtual void insertFrame( const Frame& frame, const int i ); // Insert a frame at the i-th position inline void insertNext( const Frame& frame ); // Insert a frame at the next position inline void insertPrev( const Frame& frame ); // Insert a frame at the prev position inline void insertCurrent( const Frame& frame ); // Insert a frame at the current position inline void insertFirst( const Frame& frame ); // Insert a frame at the first position inline void insertLast( const Frame& frame ); // Insert a frame at the last position /// REMOVE POSE virtual void removeFrame( const int i ); // Remove the frame at the i-th position inline void removeNext(); // Remove the frame at the next position inline void removePrev(); // Remove the frame at the prev position inline void removeCurrent(); // Remove the frame at the current position inline void removeFirst(); // Remove the frame at the first position inline void removeLast(); // Remove the frame at the last position /// SEQUENCE FLOW inline void moveToFrame( const int i ); // Move to frame i inline void moveToNextFrame(); // Move to next frame inline void moveToPrevFrame(); // Move to prev frame inline void moveToFirstFrame(); // Move to first frame inline void moveToLastFrame(); // Move to last frame inline void reset(); // Reset the sequence private: /// VARAIBLE CircularIndex m_idx; PoseType m_type; }; } // namespace Animation } // namespace Core } // namespace Ra #endif // RADIUMENGINE_SEQUENCE_HPP
42.295238
108
0.629363
[ "vector" ]
2def3f683a563d0dd566666f065919a5206f444b
2,370
cpp
C++
EU4toV2/Source/Mappers/RGORandomization/Bucket.cpp
ParadoxGameConverters/EU4toVic2
17a61d5662da02abcb976403cb50da365ef7061d
[ "MIT" ]
42
2018-12-22T03:59:43.000Z
2022-02-03T10:45:42.000Z
EU4toV2/Source/Mappers/RGORandomization/Bucket.cpp
danpolitte/EU4toVic2
ab21607d7936caf9ad6ef1b6fc4e3529f0cf8aee
[ "MIT" ]
336
2018-12-22T17:15:27.000Z
2022-03-02T11:19:32.000Z
EU4toV2/Source/Mappers/RGORandomization/Bucket.cpp
klorpa/EU4toVic2
e3068eb2aa459f884c1929f162d0047a4cb5f4d4
[ "MIT" ]
56
2018-12-22T19:13:23.000Z
2022-01-01T23:08:53.000Z
#include "Bucket.h" #include "Log.h" #include "ParserHelpers.h" mappers::Bucket::Bucket(std::istream& theStream) { registerKeyword("name", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleString nameStr(theStream); name = nameStr.getString(); }); registerKeyword("climate", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleString climateStr(theStream); if (climateStr.getString() == "any") { wildClimate = true; } else { climates.push_back(climateStr.getString()); } }); registerKeyword("terrain", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleString terrainStr(theStream); if (terrainStr.getString() == "any") { wildTerrain = true; } else { terrains.push_back(terrainStr.getString()); } }); registerKeyword("fraction", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleDouble fractionDbl(theStream); fraction = fractionDbl.getDouble(); }); registerRegex("[a-zA-Z0-9\\_.:]+", commonItems::ignoreItem); parseStream(theStream); clearRegisteredKeywords(); } bool mappers::Bucket::match(const std::string& provClimate, const std::string& provTerrain) { auto climateMatch = wildClimate; if (!climateMatch) { for (const auto& climate: climates) { if (provClimate == climate) { climateMatch = true; break; } } } if (!climateMatch) { return false; } auto terrainMatch = wildTerrain; if (!terrainMatch) { for (const auto& terrain: terrains) { if (provTerrain == terrain) { terrainMatch = true; break; } } } return terrainMatch; } void mappers::Bucket::shuffle(std::default_random_engine& shuffler) { std::shuffle(provinces.begin(), provinces.end(), shuffler); const auto numToShuffle = lround(fraction * provinces.size()); if (numToShuffle < 2) { Log(LogLevel::Debug) << "Skipping empty bucket " << name; return; } std::vector<std::string> rgos; rgos.reserve(numToShuffle); for (auto i = 0; i < numToShuffle; ++i) { rgos.push_back(provinces[i]->getRgoType()); } std::shuffle(rgos.begin(), rgos.end(), shuffler); for (auto i = 0; i < numToShuffle; ++i) { provinces[i]->setRgoType(rgos[i]); } Log(LogLevel::Debug) << "Shuffled " << numToShuffle << " provinces in bucket " << name; }
23.7
91
0.674684
[ "vector" ]
2df9b45ba7dc0e8b2492b26410a31f6c68af0791
12,757
cpp
C++
internal/query/test/test_base.cpp
mingkaic/tenncor
f2fa9652e55e9ca206de5e9741fe41bde43791c1
[ "BSL-1.0", "MIT" ]
1
2020-12-29T20:38:08.000Z
2020-12-29T20:38:08.000Z
internal/query/test/test_base.cpp
mingkaic/tenncor
f2fa9652e55e9ca206de5e9741fe41bde43791c1
[ "BSL-1.0", "MIT" ]
16
2018-01-28T04:20:19.000Z
2021-01-23T09:38:52.000Z
internal/query/test/test_base.cpp
mingkaic/tenncor
f2fa9652e55e9ca206de5e9741fe41bde43791c1
[ "BSL-1.0", "MIT" ]
null
null
null
#ifndef DISABLE_QUERY_BASE_TEST #include "gtest/gtest.h" #include "testutil/tutil.hpp" #include "dbg/print/teq.hpp" #include "internal/teq/mock/mock.hpp" #include "internal/query/querier.hpp" #include "internal/query/parse.hpp" using ::testing::_; using ::testing::Return; using ::testing::ReturnRef; using ::testing::Throw; using ::testing::Const; TEST(BASE, BadParse) { auto* logger = new exam::MockLogger(); global::set_logger(logger); std::stringstream badjson; query::Node cond; std::string fatalmsg = "failed to parse json condition"; EXPECT_CALL(*logger, supports_level(logs::fatal_level)).WillOnce(Return(true)); EXPECT_CALL(*logger, log(logs::fatal_level, fatalmsg, _)).Times(1).WillOnce(Throw(exam::TestException(fatalmsg))); EXPECT_FATAL(query::json_parse(cond, badjson), fatalmsg.c_str()); global::set_logger(new exam::NoSupportLogger()); } TEST(BASE, ErasedNode) { auto c1 = make_var(teq::Shape(), "3.2"); auto c2 = make_var(teq::Shape(), "3.5"); auto x = make_var(teq::Shape(), "X"); auto interm = make_fnc("SUB", 0, teq::TensptrsT{c1,x}); auto root = make_fnc("SUB", 0, teq::TensptrsT{c2, interm}); query::Query matcher; root->accept(matcher); matcher.erase(interm.get()); std::stringstream condjson; condjson << "{\"op\":{" "\"opname\":\"SUB\"," "\"args\":[{\"op\":{" "\"opname\":\"SUB\"," "\"args\":[{\"symb\":\"A\"},{\"symb\":\"B\"}]" "}},{\"symb\":\"C\"}]" "}}"; query::Node cond; query::json_parse(cond, condjson); auto detections = matcher.match(cond); EXPECT_EQ(0, detections.size()); std::stringstream condjson2; condjson2 << "{\"op\":{" "\"opname\":\"SUB\"," "\"args\":[{\"symb\":\"A\"},{\"symb\":\"B\"}]" "}}"; query::Node cond2; query::json_parse(cond2, condjson2); auto detections2 = matcher.match(cond2); ASSERT_EQ(1, detections2.size()); teq::iTensor* res = detections2.front(); EXPECT_EQ(root.get(), res); } TEST(BASE, BadNode) { auto logger = new exam::MockLogger(); global::set_logger(logger); auto c1 = make_var(teq::Shape(), "3.2"); auto c2 = make_var(teq::Shape(), "3.5"); auto x = make_var(teq::Shape(), "X"); auto f1 = make_fnc("SUB", 0, teq::TensptrsT{c1,x}); auto root = make_fnc("SUB", 0, teq::TensptrsT{c2, f1}); query::Query matcher; root->accept(matcher); std::stringstream badjson; badjson << "{}"; { query::Node cond; query::json_parse(cond, badjson); std::string fatalmsg = "cannot look for unknown node"; EXPECT_CALL(*logger, supports_level(logs::fatal_level)).WillOnce(Return(true)); EXPECT_CALL(*logger, log(logs::fatal_level, fatalmsg, _)).Times(1).WillOnce(Throw(exam::TestException(fatalmsg))); EXPECT_FATAL(matcher.match(cond), fatalmsg.c_str()); } std::stringstream badjson2; badjson2 << "{\"op\":{" "\"opname\":\"SUB\"," "\"args\":[{\"symb\":\"A\"},{}]" "}}"; { query::Node cond; query::json_parse(cond, badjson2); std::string fatalmsg = "cannot look for unknown node"; EXPECT_CALL(*logger, supports_level(logs::fatal_level)).WillOnce(Return(true)); EXPECT_CALL(*logger, log(logs::fatal_level, fatalmsg, _)).Times(1).WillOnce(Throw(exam::TestException(fatalmsg))); EXPECT_FATAL(matcher.match(cond), fatalmsg.c_str()); } global::set_logger(new exam::NoSupportLogger()); } TEST(BASE, DirectConstants) { auto c1 = make_var(teq::Shape(), "3.2"); auto c2 = make_var(teq::Shape(), "3.5"); auto x = make_var(teq::Shape(), "X"); auto f1 = make_fnc("SUB", 0, teq::TensptrsT{c1,x}); auto root = make_fnc("SUB", 0, teq::TensptrsT{c2,f1}); std::stringstream condjson; condjson << "{\"cst\":3.5}"; query::Node cond; query::json_parse(cond, condjson); query::Query matcher; root->accept(matcher); auto detections = matcher.match(cond); teq::TensSetT roots(detections.begin(), detections.end()); ASSERT_EQ(1, roots.size()); EXPECT_EQ(c2.get(), *roots.begin()); } TEST(BASE, Constants) { auto c1 = make_var(teq::Shape(), "3.2"); auto c2 = make_var(teq::Shape(), "3.5"); auto x = make_var(teq::Shape(), "X"); auto f1 = make_fnc("SUB", 0, teq::TensptrsT{c1,x}); auto root = make_fnc("SUB", 0, teq::TensptrsT{c2,f1}); std::stringstream condjson; condjson << "{\"op\":{" "\"opname\":\"SUB\"," "\"args\":[{\"cst\":3.5},{\"symb\":\"A\"}]" "}}"; query::Node cond; query::json_parse(cond, condjson); query::Query matcher; root->accept(matcher); auto detections = matcher.match(cond); teq::TensSetT roots(detections.begin(), detections.end()); ASSERT_EQ(1, roots.size()); char expected[] = "(SUB)\n" "_`--(constant:3.5)\n" "_`--(SUB)\n" "_____`--(constant:3.2)\n" "_____`--(constant:X)\n"; PrettyEquation peq; std::stringstream ss; peq.print(ss, *roots.begin()); EXPECT_STREQ(expected, ss.str().c_str()); } TEST(BASE, DirectLeafs) { auto c1 = make_var(teq::Shape({1, 2}), "X"); auto c2 = make_var(teq::Shape(), "X"); auto x = make_var(teq::Shape({1, 2}), "X"); auto f1 = make_fnc("SUB", 0, teq::TensptrsT{c1,x}); auto root = make_fnc("SUB", 0, teq::TensptrsT{c2,f1}); MockMeta mockmeta; MockMeta mockmeta2; EXPECT_CALL(*x, get_meta()).WillRepeatedly(ReturnRef(mockmeta)); EXPECT_CALL(*c1, get_meta()).WillRepeatedly(ReturnRef(mockmeta2)); EXPECT_CALL(*c2, get_meta()).WillRepeatedly(ReturnRef(mockmeta2)); EXPECT_CALL(Const(*x), get_meta()).WillRepeatedly(ReturnRef(mockmeta)); EXPECT_CALL(Const(*c1), get_meta()).WillRepeatedly(ReturnRef(mockmeta2)); EXPECT_CALL(Const(*c2), get_meta()).WillRepeatedly(ReturnRef(mockmeta2)); EXPECT_CALL(mockmeta, type_label()).WillRepeatedly(Return("specops")); EXPECT_CALL(mockmeta2, type_label()).WillRepeatedly(Return("")); std::stringstream condjson; condjson << "{\"leaf\":{" "\"label\":\"X\"," "\"shape\":[1,2]," "\"dtype\":\"specops\"" "}}"; query::Node cond; query::json_parse(cond, condjson); query::Query matcher; root->accept(matcher); auto detections = matcher.match(cond); teq::TensSetT roots(detections.begin(), detections.end()); ASSERT_EQ(1, roots.size()); EXPECT_EQ(x.get(), *roots.begin()); } TEST(BASE, Leafs) { auto c1 = make_var(teq::Shape({1, 2}), "X"); auto c2 = make_var(teq::Shape(), "X"); auto x = make_var(teq::Shape(), "X"); auto f1 = make_fnc("SUB", 0, teq::TensptrsT{c1,x}); auto root = make_fnc("SUB", 0, teq::TensptrsT{c2,f1}); std::stringstream condjson; condjson << "{\"op\":{" "\"opname\":\"SUB\"," "\"args\":[" "{" "\"leaf\":{" "\"label\":\"X\"," "\"shape\":[1,2]" "}" "},{\"symb\":\"A\"}]" "}}"; query::Node cond; query::json_parse(cond, condjson); query::Query matcher; root->accept(matcher); auto detections = matcher.match(cond); teq::TensSetT roots(detections.begin(), detections.end()); ASSERT_EQ(1, roots.size()); char expected[] = "(SUB)\n" "_`--(constant:X)\n" "_`--(constant:X)\n"; PrettyEquation peq; std::stringstream ss; peq.print(ss, *roots.begin()); EXPECT_STREQ(expected, ss.str().c_str()); } TEST(BASE, NoComNoSymbs) { auto x = make_var(teq::Shape(), "X"); auto f1 = make_fnc("SIN", 0, teq::TensptrsT{x}); auto f2 = make_fnc("SUB", 0, teq::TensptrsT{x,x}); auto root = make_fnc("SUB", 0, teq::TensptrsT{f1,f2}); std::stringstream condjson; condjson << "{\"op\":{" "\"opname\":\"SUB\"," "\"args\":[{\"symb\":\"A\"},{\"symb\":\"B\"}]" "}}"; query::Node cond; query::json_parse(cond, condjson); query::Query matcher; root->accept(matcher); auto detections = matcher.match(cond); teq::TensSetT roots(detections.begin(), detections.end()); ASSERT_EQ(2, roots.size()); char expected[] = "(SUB)\n" "_`--(SIN)\n" "_|___`--(constant:X)\n" "_`--(SUB)\n" "_____`--(constant:X)\n" "_____`--(constant:X)\n\n" "(SUB)\n" "_`--(constant:X)\n" "_`--(constant:X)\n"; PrettyEquation peq; types::StringsT dets; for (auto& det : roots) { std::stringstream ss; peq.print(ss, det); dets.push_back(ss.str()); } std::sort(dets.begin(), dets.end()); std::string got_det = fmts::join("\n", dets.begin(), dets.end()); EXPECT_STREQ(expected, got_det.c_str()); } TEST(BASE, NoComBadStruct) { auto x = make_var(teq::Shape(), "X"); auto f1 = make_fnc("SIN", 0, teq::TensptrsT{x}); auto f2 = make_fnc("SUB", 0, teq::TensptrsT{x,x}); auto root = make_fnc("SUB", 0, teq::TensptrsT{f1,f2}); std::stringstream condjson; condjson << "{\"op\":{" "\"opname\":\"SUB\"," "\"args\":[{\"op\":{" "\"opname\":\"SUB\"," "\"args\":[{\"symb\":\"A\"},{\"symb\":\"B\"}]" "}},{\"symb\":\"C\"}]" "}}"; query::Node cond; query::json_parse(cond, condjson); query::Query matcher; root->accept(matcher); auto detections = matcher.match(cond); ASSERT_EQ(0, detections.size()); } TEST(BASE, NoComSymbOnly) { auto x = make_var(teq::Shape(), "X"); auto f1 = make_fnc("SIN", 0, teq::TensptrsT{x}); auto f2 = make_fnc("SUB", 0, teq::TensptrsT{x,x}); auto root = make_fnc("SUB", 0, teq::TensptrsT{f1,f2}); std::stringstream condjson; condjson << "{\"op\":{" "\"opname\":\"SUB\"," "\"args\":[{\"symb\":\"A\"},{\"symb\":\"A\"}]" "}}"; query::Node cond; query::json_parse(cond, condjson); query::Query matcher; root->accept(matcher); auto detections = matcher.match(cond); teq::TensSetT roots(detections.begin(), detections.end()); ASSERT_EQ(1, roots.size()); char expected[] = "(SUB)\n" "_`--(constant:X)\n" "_`--(constant:X)\n"; PrettyEquation peq; std::stringstream ss; peq.print(ss, *roots.begin()); EXPECT_STREQ(expected, ss.str().c_str()); } TEST(BASE, CommNoSymbs) { auto x = make_var(teq::Shape(), "X"); auto f1 = make_fnc("SIN", 0, teq::TensptrsT{x}); auto f2 = make_fnc("ADD", 0, teq::TensptrsT{x,x}); auto root = make_fnc("ADD", 0, teq::TensptrsT{f1,f2}); std::stringstream condjson; condjson << "{\"op\":{" "\"opname\":\"ADD\"," "\"args\":[{\"op\":{" "\"opname\":\"ADD\"," "\"args\":[{\"symb\":\"A\"},{\"symb\":\"B\"}]" "}},{\"symb\":\"C\"}]" "}}"; query::Node cond; query::json_parse(cond, condjson); query::Query matcher; root->accept(matcher); auto detections = matcher.match(cond); teq::TensSetT roots(detections.begin(), detections.end()); ASSERT_EQ(1, roots.size()); char expected[] = "(ADD)\n" "_`--(SIN)\n" "_|___`--(constant:X)\n" "_`--(ADD)\n" "_____`--(constant:X)\n" "_____`--(constant:X)\n"; PrettyEquation peq; std::stringstream ss; peq.print(ss, *roots.begin()); EXPECT_STREQ(expected, ss.str().c_str()); } TEST(BASE, CommBadStruct) { auto x = make_var(teq::Shape(), "X"); auto f1 = make_fnc("SIN", 0, teq::TensptrsT{x}); auto f2 = make_fnc("ADD", 0, teq::TensptrsT{x,x}); auto root = make_fnc("ADD", 0, teq::TensptrsT{f1,f2}); std::stringstream condjson; condjson << "{\"op\":{" "\"opname\":\"ADD\"," "\"args\":[{\"op\":{" "\"opname\":\"SUB\"," "\"args\":[{\"symb\":\"A\"},{\"symb\":\"B\"}]" "}},{\"symb\":\"C\"}]" "}}"; query::Node cond; query::json_parse(cond, condjson); query::Query matcher; root->accept(matcher); auto detections = matcher.match(cond); ASSERT_EQ(0, detections.size()); } TEST(BASE, CommSymbOnly) { auto x = make_var(teq::Shape(), "X"); auto f1 = make_fnc("SIN", 0, teq::TensptrsT{x}); auto f2 = make_fnc("ADD", 0, teq::TensptrsT{x,x}); auto root = make_fnc("ADD", 0, teq::TensptrsT{f1,f2}); std::stringstream condjson; condjson << "{\"op\":{" "\"opname\":\"ADD\"," "\"args\":[{\"symb\":\"A\"},{\"symb\":\"A\"}]" "}}"; query::Node cond; query::json_parse(cond, condjson); query::Query matcher; root->accept(matcher); auto detections = matcher.match(cond); teq::TensSetT roots(detections.begin(), detections.end()); ASSERT_EQ(1, roots.size()); char expected[] = "(ADD)\n" "_`--(constant:X)\n" "_`--(constant:X)\n"; PrettyEquation peq; std::stringstream ss; peq.print(ss, *roots.begin()); EXPECT_STREQ(expected, ss.str().c_str()); } TEST(BASE, Capture) { auto x = make_var(teq::Shape(), "X"); auto f1 = make_fnc("SIN", 0, teq::TensptrsT{x}); auto f2 = make_fnc("SUB", 0, teq::TensptrsT{x,x}); auto root = make_fnc("SUB", 0, teq::TensptrsT{f1,f2}); std::stringstream condjson; condjson << "{\"op\":{" "\"opname\":\"SUB\"," "\"args\":[{\"symb\":\"A\"}," "{\"op\":{" "\"opname\":\"SUB\"," "\"capture\":\"stuff\"," "\"args\":[{\"symb\":\"B\"},{\"symb\":\"C\"}]" "}}]" "}}"; query::Node cond; query::json_parse(cond, condjson); query::Query matcher; root->accept(matcher); auto detections = matcher.match(cond); ASSERT_EQ(1, detections.size()); ASSERT_HAS(detections.front().symbs_, "stuff"); char expected[] = "(SUB)\n" "_`--(constant:X)\n" "_`--(constant:X)\n"; PrettyEquation peq; std::stringstream ss; peq.print(ss, detections.front().symbs_["stuff"]); EXPECT_STREQ(expected, ss.str().c_str()); } #endif // DISABLE_QUERY_BASE_TEST
25.771717
116
0.616132
[ "shape" ]
2dff8cd753695fa6931da4a2f95e6ca3fb4ffdfd
8,980
cpp
C++
dnn/test/common/dct_ref.cpp
gedoensmax/MegEngine
dfb9d9801bd101970024e50865ec99a0048f53d7
[ "Apache-2.0" ]
5,168
2020-03-19T06:10:04.000Z
2022-03-31T11:11:54.000Z
dnn/test/common/dct_ref.cpp
gedoensmax/MegEngine
dfb9d9801bd101970024e50865ec99a0048f53d7
[ "Apache-2.0" ]
286
2020-03-25T01:36:23.000Z
2022-03-31T10:26:33.000Z
dnn/test/common/dct_ref.cpp
gedoensmax/MegEngine
dfb9d9801bd101970024e50865ec99a0048f53d7
[ "Apache-2.0" ]
515
2020-03-19T06:10:05.000Z
2022-03-30T09:15:59.000Z
/** * \file * dnn/test/common/dct_ref.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. */ #include "test/common/dct_ref.h" namespace megdnn { namespace test { struct FixCase { std::vector<int> mask_offset; std::vector<int> mask_val; }; using Param = DctChannelSelectForward::Param; static inline FixCase get_fix_mask(Param::FastImpl impl) { std::vector<int> fix_32_mask_offset{0, 16, 24, 32}; std::vector<int> fix_32_mask_val{0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 0, 1, 8, 16, 9, 2, 3, 10, 0, 1, 8, 16, 9, 2, 3, 10}; megdnn_assert(impl == Param::FastImpl::FIX_32_MASK, "only support gen FIX_32_MASK"); return {fix_32_mask_offset, fix_32_mask_val}; } CheckerHelper::TensorsConstriant gen_dct_constriant( const size_t /* n */, const size_t ic, const size_t ih, const size_t iw, const size_t oc, Param param) { auto constraint = [=](CheckerHelper::TensorValueArray& tensors_orig) { const size_t block = param.dct_block_size; const int block_c = param.format == Param::Format::NCHW4 ? 4 : 1; megdnn_assert(oc % block_c == 0, "oc mod block_c must == 0"); std::shared_ptr<DctTestcase> test_case_ptr = DctTestcase::make(); DctTestcase& test_case = *test_case_ptr.get(); UniformIntRNG rng(0, 255); UniformIntRNG mask_rng(0, 64 / block_c - 1); const size_t no_mask_oc = ic * block * block; megdnn_assert(ih % block == 0, "%zu mod %zu == 0", ih, block); megdnn_assert(iw % block == 0, "%zu mod %zu == 0", iw, block); TensorND mask_offset; TensorND mask_val; std::vector<int>& mask_offset_vec = test_case.mask_offset_vec; std::vector<int>& mask_val_vec = test_case.mask_val_vec; UniformIntRNG rng_oc(0, oc); if (param.fastImpl == Param::FastImpl::FIX_32_MASK) { auto fix_32_mask = get_fix_mask(Param::FastImpl::FIX_32_MASK); mask_offset_vec = fix_32_mask.mask_offset; mask_val_vec = fix_32_mask.mask_val; megdnn_assert(oc == 32, "oc must eq 32"); } else if (no_mask_oc > oc) { size_t remain_oc = oc; mask_offset_vec.resize(ic + 1); mask_val_vec.resize(oc); mask_offset_vec[0] = 0; for (size_t ic_idx = 0; ic_idx < ic; ++ic_idx) { size_t random_len = (int)rng_oc.gen_single_val() * block_c; size_t mask_len = (ic_idx == ic - 1) || (remain_oc == 0) ? remain_oc : random_len % remain_oc; megdnn_assert( mask_len % block_c == 0, "mask_len mod block_c == 0, but %zu mod %d ", mask_len, block_c); const size_t oc_idx = mask_offset_vec[ic_idx]; remain_oc -= mask_len; mask_offset_vec[ic_idx + 1] = oc_idx + mask_len; for (size_t mask_idx = 0; mask_idx < mask_len; ++mask_idx) { mask_val_vec[oc_idx + mask_idx] = (int)mask_rng.gen_single_val(); } } } mask_offset = TensorND( mask_offset_vec.data(), {{mask_offset_vec.size()}, dtype::Int32()}); mask_val = TensorND(mask_val_vec.data(), {{mask_val_vec.size()}, dtype::Int32()}); if (tensors_orig.size() > 1) { megdnn_assert(tensors_orig.size() == 4, "tensors_orig.size() == 4"); megdnn_assert(mask_offset_vec.size() >= 2, "mask_offset_vec.size() >= 2"); megdnn_assert( tensors_orig[1].layout == mask_offset.layout, "tensors_orig[1].layout == mask_offset.layout"); megdnn_assert( tensors_orig[2].layout == mask_val.layout, "tensors_orig[2].layout == mask_val.layout"); auto naive_handle = create_cpu_handle(2, false); megdnn_memcpy_D2D( naive_handle.get(), tensors_orig[1].raw_ptr, mask_offset.raw_ptr, mask_offset.layout.span().dist_byte()); megdnn_memcpy_D2D( naive_handle.get(), tensors_orig[2].raw_ptr, mask_val.raw_ptr, mask_val.layout.span().dist_byte()); } }; return constraint; } std::shared_ptr<DctTestcase> gen_dct_case( const size_t n, const size_t ic, const size_t ih, const size_t iw, const size_t oc, Param param, DType dst_dtype, bool correct_result) { const size_t block = param.dct_block_size; const int block_c = param.format == Param::Format::NCHW4 ? 4 : 1; megdnn_assert(oc % block_c == 0, "oc mod block_c must == 0"); std::shared_ptr<DctTestcase> test_case_ptr = DctTestcase::make(); DctTestcase& test_case = *test_case_ptr.get(); UniformIntRNG rng(0, 255); UniformIntRNG mask_rng(0, 64 / block_c - 1); const size_t input_elements = n * ic * ih * iw; const size_t no_mask_oc = ic * block * block; megdnn_assert(ih % block == 0, "%zu mod %zu == 0", ih, block); megdnn_assert(iw % block == 0, "%zu mod %zu == 0", iw, block); std::vector<uint8_t>& inp_vec = test_case.inp_vec; inp_vec.resize(input_elements); TensorShape input_shape{n, ic, ih, iw}; for (auto& elm : inp_vec) { elm = (uint8_t)rng.gen_single_val(); } auto src = TensorND(inp_vec.data(), {input_shape, dtype::Uint8()}); TensorND mask_offset; TensorND mask_val; std::vector<int>& mask_offset_vec = test_case.mask_offset_vec; std::vector<int>& mask_val_vec = test_case.mask_val_vec; UniformIntRNG rng_oc(0, oc); if (param.fastImpl == Param::FastImpl::FIX_32_MASK) { auto fix_32_mask = get_fix_mask(Param::FastImpl::FIX_32_MASK); mask_offset_vec = fix_32_mask.mask_offset; mask_val_vec = fix_32_mask.mask_val; megdnn_assert(oc == 32, "oc must eq 32"); } else if (no_mask_oc > oc) { size_t remain_oc = oc; mask_offset_vec.resize(ic + 1); mask_val_vec.resize(oc); mask_offset_vec[0] = 0; for (size_t ic_idx = 0; ic_idx < ic; ++ic_idx) { size_t random_len = (int)rng_oc.gen_single_val() * block_c; size_t mask_len = (ic_idx == ic - 1) || (remain_oc == 0) ? remain_oc : random_len % remain_oc; megdnn_assert( mask_len % block_c == 0, "mask_len mod block_c == 0, but %zu mod %d ", mask_len, block_c); const size_t oc_idx = mask_offset_vec[ic_idx]; remain_oc -= mask_len; mask_offset_vec[ic_idx + 1] = oc_idx + mask_len; for (size_t mask_idx = 0; mask_idx < mask_len; ++mask_idx) { mask_val_vec[oc_idx + mask_idx] = (int)mask_rng.gen_single_val(); } } } mask_offset = TensorND( mask_offset_vec.data(), {{mask_offset_vec.size()}, dtype::Int32()}); mask_val = TensorND(mask_val_vec.data(), {{mask_val_vec.size()}, dtype::Int32()}); if (mask_offset_vec.size() >= 2) { test_case.testcase_in = { src, mask_offset, mask_val, {nullptr, {{}, dst_dtype}}}; } else { test_case.testcase_in = {src, {}, {}, {nullptr, {{}, dst_dtype}}}; } auto naive_handle = create_cpu_handle(2, false); auto opr_naive = naive_handle->create_operator<DctChannelSelectForward>(); opr_naive->param() = param; using Proxy = OprProxy<DctChannelSelectForward>; Proxy naive_proxy; TensorLayout temp_dst_layout; temp_dst_layout.dtype = dst_dtype; TensorLayoutArray layouts{ src.layout, mask_offset.layout, mask_val.layout, temp_dst_layout}; naive_proxy.deduce_layout(opr_naive.get(), layouts); const size_t output_elements = layouts[3].total_nr_elems(); std::vector<float>& output_vec = test_case.output_vec; output_vec.resize(output_elements); auto dst = TensorND(output_vec.data(), layouts[3]); DctTestcase::TensorValueArray testcase_naive; testcase_naive.emplace_back(test_case.testcase_in[0]); testcase_naive.emplace_back(test_case.testcase_in[1]); testcase_naive.emplace_back(test_case.testcase_in[2]); testcase_naive.emplace_back(dst); if (correct_result) { naive_proxy.exec(opr_naive.get(), testcase_naive); } test_case.testcase_out = {{}, {}, {}, dst}; return test_case_ptr; } } // namespace test } // namespace megdnn // vim: syntax=cpp.doxygen
46.28866
88
0.601559
[ "vector" ]
930173af5594ef0a5954a135f5f376b249be18d3
6,065
cc
C++
api/dumbaes.cc
JacobFischer/CS6001-Course-Project
603523dc93ae90975e7a016222719a1d09360361
[ "BSD-2-Clause" ]
null
null
null
api/dumbaes.cc
JacobFischer/CS6001-Course-Project
603523dc93ae90975e7a016222719a1d09360361
[ "BSD-2-Clause" ]
null
null
null
api/dumbaes.cc
JacobFischer/CS6001-Course-Project
603523dc93ae90975e7a016222719a1d09360361
[ "BSD-2-Clause" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (c) 2016 Michael Catanzaro <michael.catanzaro@mst.edu> * Copyright (c) 2016 Jacob Fischer <jtf3m8@mst.edu> * Copyright (c) 2016 Christian Storer <cs9yb@mst.edu> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "dumbaes.h" #include "src/dumbaes.h" #include <cstdlib> #include <cstring> using namespace dumbaes; unsigned char* dumbaes_128_encrypt_block(const unsigned char* plaintext, const unsigned char* key) { Block datablock; Key keyblock; std::memcpy(datablock.data(), plaintext, 16); std::memcpy(keyblock.data(), key, 16); Block ciphertext = encrypt_block(datablock, keyblock); auto result = static_cast<unsigned char*>(std::malloc(16)); std::memcpy(result, ciphertext.data(), 16); return result; } unsigned char* dumbaes_128_decrypt_block(const unsigned char* ciphertext, const unsigned char* key) { Block datablock; Key keyblock; std::memcpy(datablock.data(), ciphertext, 16); std::memcpy(keyblock.data(), key, 16); Block plaintext = decrypt_block(datablock, keyblock); auto result = static_cast<unsigned char*>(std::malloc(16)); std::memcpy(result, plaintext.data(), 16); return result; } unsigned char* dumbaes_128_encrypt_cbc(const unsigned char* plaintext, size_t* length, const unsigned char* key, const unsigned char* iv) { Key keyblock; std::memcpy(keyblock.data(), key, 16); Block iv_block; std::memcpy(iv_block.data(), iv, 16); size_t num_blocks = (*length / 16) + 1; std::vector<Block> plaintext_vector(num_blocks); std::memcpy(plaintext_vector[0].data(), plaintext, *length); std::vector<Block> ciphertext_vector = encrypt_cbc(plaintext_vector, *length, keyblock, iv_block); auto result = static_cast<unsigned char*>(std::malloc(*length)); std::memcpy(result, ciphertext_vector.data(), *length); return result; } unsigned char* dumbaes_128_decrypt_cbc(const unsigned char* ciphertext, size_t* length, const unsigned char* key, const unsigned char* iv) { Key keyblock; std::memcpy(keyblock.data(), key, 16); Block iv_block; std::memcpy(iv_block.data(), iv, 16); size_t num_blocks = *length / 16; std::vector<Block> ciphertext_vector(num_blocks); std::memcpy(ciphertext_vector[0].data(), ciphertext, *length); std::vector<Block> plaintext_vector = decrypt_cbc(ciphertext_vector, *length, keyblock, iv_block); auto result = static_cast<unsigned char*>(std::malloc(*length)); std::memcpy(result, plaintext_vector.data(), *length); return result; } unsigned char* dumbaes_128_encrypt_ecb(const unsigned char* plaintext, size_t* length, const unsigned char* key) { Key keyblock; std::memcpy(keyblock.data(), key, 16); size_t num_blocks = *length / 16 + 1; std::vector<Block> plaintext_vector(num_blocks); std::memcpy(plaintext_vector[0].data(), plaintext, *length); std::vector<Block> ciphertext_vector = encrypt_ecb(plaintext_vector, *length, keyblock); auto result = static_cast<unsigned char*>(std::malloc(*length)); std::memcpy(result, ciphertext_vector[0].data(), *length); return result; } unsigned char* dumbaes_128_decrypt_ecb(const unsigned char* ciphertext, size_t* length, const unsigned char* key) { Key keyblock; std::memcpy(keyblock.data(), key, 16); size_t num_blocks = *length / 16; std::vector<Block> ciphertext_vector(num_blocks); std::memcpy(&ciphertext_vector[0], ciphertext, *length); std::vector<Block> plaintext_vector = decrypt_ecb(ciphertext_vector, *length, keyblock); auto result = static_cast<unsigned char*>(std::malloc(*length)); std::memcpy(result, &plaintext_vector[0], *length); return result; } unsigned char* dumbaes_128_generate_iv() { Block iv = generate_iv(); auto result = static_cast<unsigned char*>(std::malloc(16)); std::memcpy(result, iv.data(), 16); return result; }
36.536145
81
0.623578
[ "vector" ]
930912d29e4587b0c3dab9d22aa98c4f7fc2c20b
921
cpp
C++
genfile/src/Pedigree.cpp
gavinband/bingwa
d52e166b3bb6bc32cd32ba63bf8a4a147275eca1
[ "BSL-1.0" ]
3
2021-04-21T05:42:24.000Z
2022-01-26T14:59:43.000Z
genfile/src/Pedigree.cpp
gavinband/bingwa
d52e166b3bb6bc32cd32ba63bf8a4a147275eca1
[ "BSL-1.0" ]
2
2020-04-09T16:11:04.000Z
2020-11-10T11:18:56.000Z
genfile/src/Pedigree.cpp
gavinband/qctool
8d8adb45151c91f953fe4a9af00498073b1132ba
[ "BSL-1.0" ]
null
null
null
// Copyright Gavin Band 2008 - 2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <memory> #include <string> #include <vector> #include "genfile/Pedigree.hpp" #include "genfile/FromPedFilePedigree.hpp" #include "genfile/string_utils.hpp" #include "genfile/Error.hpp" namespace genfile { Pedigree::UniquePtr Pedigree::create( std::string const& pedigree_spec ) { if( pedigree_spec.size() < 6 || pedigree_spec.substr(0, 5) != "file:" ) { throw BadArgumentError( "genfile::Pedigree::create()", "pedigree_spec = \"" + pedigree_spec + "\"." ) ; } std::string spec = pedigree_spec.substr( 5, pedigree_spec.size() ) ; return Pedigree::UniquePtr( new FromPedFilePedigree( string_utils::strip( pedigree_spec.substr( 5, pedigree_spec.size() ), " \t" ) ) ) ; } }
32.892857
106
0.686211
[ "vector" ]
930ec0b2ccb08de05320671320fe6778a4946f53
6,396
cpp
C++
source/RocketPlugin/GameModes/KeepAway.cpp
urlocaluwu/RocketPlugin
ec31a5239e6552bbd8e6ed981da8cc2d5b84e687
[ "MIT" ]
15
2020-07-15T13:06:23.000Z
2022-02-24T22:19:14.000Z
source/RocketPlugin/GameModes/KeepAway.cpp
urlocaluwu/RocketPlugin
ec31a5239e6552bbd8e6ed981da8cc2d5b84e687
[ "MIT" ]
15
2020-07-26T18:06:55.000Z
2022-02-12T22:16:16.000Z
source/RocketPlugin/GameModes/KeepAway.cpp
urlocaluwu/RocketPlugin
ec31a5239e6552bbd8e6ed981da8cc2d5b84e687
[ "MIT" ]
12
2020-07-15T17:05:42.000Z
2021-11-20T14:19:06.000Z
// GameModes/KeepAway.cpp // Touch the ball to get points. // // Author: Stanbroek // Version: 0.2.3 28/08/21 // BMSDK version: 95 // BUG's: // - Clients still get normal points. #include "KeepAway.h" /// <summary>Renders the available options for the game mode.</summary> void KeepAway::RenderOptions() { ImGui::Checkbox("Count Rumble Touches", &enableRumbleTouches); ImGui::SameLine(); ImGui::Checkbox("Count Normal Points", &enableNormalScore); if (ImGui::SliderFloat("##SecondsPerPoint", &secPerPoint, 0.1f, 10, "%.1f seconds delay per point")) { if (secPerPoint < 0.1f) { secPerPoint = 0.1f; } } if (ImGui::Button("Reset points")) { Execute([this](GameWrapper*) { resetPoints(); }); } ImGui::Separator(); ImGui::TextWrapped("Game mode suggested by: kennyak90"); } /// <summary>Gets if the game mode is active.</summary> /// <returns>Bool with if the game mode is active</returns> bool KeepAway::IsActive() { return isActive; } /// <summary>Activates the game mode.</summary> void KeepAway::Activate(const bool active) { if (active && !isActive) { lastTouched = emptyPlayer; timeSinceLastPoint = 0; HookEventWithCaller<ServerWrapper>( "Function GameEvent_Soccar_TA.Active.Tick", [this](const ServerWrapper& caller, void* params, const std::string&) { onTick(caller, params); }); HookEventWithCaller<ActorWrapper>( "Function TAGame.PRI_TA.GiveScore", [this](const ActorWrapper& caller, void*, const std::string&) { onGiveScorePre(caller); }); HookEventWithCallerPost<ActorWrapper>( "Function TAGame.PRI_TA.GiveScore", [this](const ActorWrapper& caller, void*, const std::string&) { onGiveScorePost(caller); }); HookEventWithCaller<BallWrapper>( "Function TAGame.Ball_TA.EventCarTouch", [this](const BallWrapper&, void* params, const std::string&) { onCarTouch(params); }); HookEventWithCaller<CarWrapper>( "Function TAGame.Car_TA.OnHitBall", [this](const CarWrapper& car, void*, const std::string&) { onBallTouch(car); }); HookEventWithCaller<ActorWrapper>( "Function TAGame.GameEvent_Soccar_TA.EventGoalScored", [this](const ActorWrapper&, void*, const std::string&) { lastTouched = emptyPlayer; }); } else if (!active && isActive) { UnhookEvent("Function GameEvent_Soccar_TA.Active.Tick"); UnhookEvent("Function TAGame.PRI_TA.GiveScore"); UnhookEventPost("Function TAGame.PRI_TA.GiveScore"); UnhookEvent("Function TAGame.Ball_TA.EventCarTouch"); UnhookEvent("Function TAGame.Car_TA.OnHitBall"); UnhookEvent("Function TAGame.GameEvent_Soccar_TA.EventGoalScored"); } isActive = active; } /// <summary>Gets the game modes name.</summary> /// <returns>The game modes name</returns> std::string KeepAway::GetGameModeName() { return "Keep Away"; } /// <summary>Updates the game every game tick.</summary> /// <remarks>Gets called on 'Function GameEvent_Soccar_TA.Active.Tick'.</remarks> /// <param name="server"><see cref="ServerWrapper"/> instance of the server</param> /// <param name="params">Delay since last update</param> void KeepAway::onTick(ServerWrapper server, void* params) { BMCHECK(server); if (lastTouched == emptyPlayer) { return; } // dt since last tick in seconds const float dt = *static_cast<float*>(params); timeSinceLastPoint += dt; if (timeSinceLastPoint < secPerPoint) { return; } const int points = static_cast<int>(floorf(timeSinceLastPoint / secPerPoint)); const std::vector<PriWrapper> players = Outer()->playerMods.GetPlayers(true); for (PriWrapper player : players) { if (player.GetUniqueIdWrapper().GetUID() == lastTouched) { player.SetMatchScore(player.GetMatchScore() + points); player.ForceNetUpdate2(); TeamInfoWrapper team = player.GetTeam(); BMCHECK_LOOP(team); Outer()->matchSettings.SetScore(player.GetTeamNum(), team.GetScore() + points); } } timeSinceLastPoint -= static_cast<float>(points) * secPerPoint; } /// <summary>Disables getting score from normal events.</summary> /// <remarks>Gets called on 'Function TAGame.PRI_TA.GiveScore'.</remarks> /// <param name="caller">instance of the PRI as <see cref="ActorWrapper"/></param> void KeepAway::onGiveScorePre(ActorWrapper caller) { if (enableNormalScore) { return; } PriWrapper player = PriWrapper(caller.memory_address); BMCHECK(player); lastNormalScore = player.GetMatchScore(); } /// <summary>Disables getting score from normal events.</summary> /// <remarks>Gets called on 'Function TAGame.PRI_TA.GiveScore'.</remarks> /// <param name="caller">instance of the PRI as <see cref="ActorWrapper"/></param> void KeepAway::onGiveScorePost(ActorWrapper caller) const { if (enableNormalScore) { return; } PriWrapper player = PriWrapper(caller.memory_address); BMCHECK(player); player.SetMatchScore(lastNormalScore); player.ForceNetUpdate2(); } /// <summary>Update who touched the ball last.</summary> /// <remarks>Gets called on 'Function TAGame.Ball_TA.EventCarTouch'.</remarks> /// <param name="car"><see cref="CarWrapper"/> that touched the ball</param> void KeepAway::onBallTouch(CarWrapper car) { BMCHECK(car); PriWrapper pri = car.GetPRI(); BMCHECK(pri); lastTouched = pri.GetUniqueIdWrapper().GetUID(); BM_TRACE_LOG("{:s} touched the ball", quote(car.GetOwnerName())); timeSinceLastPoint = 0; } /// <summary>Resets the points off all players in the game.</summary> void KeepAway::resetPoints() { lastTouched = emptyPlayer; timeSinceLastPoint = 0; ServerWrapper game = Outer()->GetGame(); BMCHECK(game); for (PriWrapper player : game.GetPRIs()) { BMCHECK_LOOP(player); player.SetMatchScore(0); player.ForceNetUpdate2(); } for (TeamWrapper team : game.GetTeams()) { BMCHECK_LOOP(team); team.SetScore(0); } }
30.75
106
0.642433
[ "vector" ]
9319f97320111fe9842acadd745372ba29fba405
4,866
cpp
C++
src/compiler/syntax/build_syntax_tree.cpp
mbeckem/tiro
b3d729fce46243f25119767c412c6db234c2d938
[ "MIT" ]
10
2020-01-23T20:41:19.000Z
2021-12-28T20:24:44.000Z
src/compiler/syntax/build_syntax_tree.cpp
mbeckem/tiro
b3d729fce46243f25119767c412c6db234c2d938
[ "MIT" ]
22
2021-03-25T16:22:08.000Z
2022-03-17T12:50:38.000Z
src/compiler/syntax/build_syntax_tree.cpp
mbeckem/tiro
b3d729fce46243f25119767c412c6db234c2d938
[ "MIT" ]
null
null
null
#include "compiler/syntax/build_syntax_tree.hpp" #include "compiler/syntax/parser_event.hpp" namespace tiro { namespace { struct SyntaxNodeBuilder final { SyntaxType type_; bool has_error_ = false; SyntaxNode::ChildStorage children_; u32 pos_ = 0; // End offset of the preceding token, as a fallback when a node has 0 children. SyntaxNodeBuilder(SyntaxType type, u32 pos) : type_(type) , pos_(pos) {} void add_child(SyntaxChild&& child); SyntaxNode build(SyntaxTree& tree); }; class SyntaxTreeBuilder final : public ParserEventConsumer { public: SyntaxTreeBuilder(std::string_view source); SyntaxTreeBuilder(const SyntaxTreeBuilder&) = delete; SyntaxTreeBuilder& operator=(const SyntaxTreeBuilder&) = delete; void start_root(); void finish_root(); SyntaxTree&& take_tree() { return std::move(tree_); } void start_node(SyntaxType type) override; void token(Token& token) override; void error(std::string& message) override; void finish_node() override; private: void link_parents(); private: SyntaxTree tree_; SourceRange last_token_range_; // Stack of open but not yet closed nodes. // The first entry (the top) is the builder for the root node. std::vector<SyntaxNodeBuilder> nodes_; }; } // namespace static SourceRange child_range(const SyntaxChild& child, const SyntaxTree& tree); SyntaxTree build_syntax_tree(std::string_view source, Span<ParserEvent> events) { SyntaxTreeBuilder builder(source); builder.start_root(); consume_events(events, builder); builder.finish_root(); return builder.take_tree(); } SyntaxTreeBuilder::SyntaxTreeBuilder(std::string_view source) : tree_(source) , last_token_range_(0, 0) {} void SyntaxTreeBuilder::start_root() { TIRO_DEBUG_ASSERT(nodes_.empty(), "Builder was already started."); nodes_.emplace_back(SyntaxType::Root, 0); } void SyntaxTreeBuilder::finish_root() { TIRO_DEBUG_ASSERT(nodes_.size() >= 1, "Builder was not started."); while (nodes_.size() > 1) { finish_node(); } auto root_id = tree_.make(nodes_.front().build(tree_)); tree_.root_id(root_id); link_parents(); } void SyntaxTreeBuilder::start_node(SyntaxType type) { auto& builder = nodes_.emplace_back(type, last_token_range_.end()); if (type == SyntaxType::Error) builder.has_error_ = true; } void SyntaxTreeBuilder::token(Token& token) { TIRO_DEBUG_ASSERT(!nodes_.empty(), "No open node exists for this token."); last_token_range_ = token.range(); auto& builder = nodes_.back(); builder.add_child(SyntaxChild::make_token(std::move(token))); } void SyntaxTreeBuilder::error(std::string& message) { TIRO_DEBUG_ASSERT(!nodes_.empty(), "No open node exists for this error."); auto& builder = nodes_.back(); builder.has_error_ = true; SyntaxError error(std::move(message), SourceRange::from_offset(last_token_range_.end())); tree_.errors().push_back(std::move(error)); } void SyntaxTreeBuilder::finish_node() { TIRO_DEBUG_ASSERT(nodes_.size() > 1, "Must not finish the root node because of an event."); auto child_id = tree_.make(nodes_.back().build(tree_)); nodes_.pop_back(); nodes_.back().add_child(child_id); } void SyntaxTreeBuilder::link_parents() { struct Item { SyntaxNodeId parent_id; SyntaxNodeId node_id; }; std::vector<Item> stack; stack.push_back({SyntaxNodeId(), tree_.root_id()}); while (!stack.empty()) { auto [parent_id, node_id] = stack.back(); stack.pop_back(); auto& node_data = tree_[node_id]; node_data.parent(parent_id); for (const auto& child : node_data.children()) { if (child.type() == SyntaxChildType::NodeId) { stack.push_back({node_id, child.as_node_id()}); } } } } void SyntaxNodeBuilder::add_child(SyntaxChild&& child) { children_.push_back(std::move(child)); } SyntaxNode SyntaxNodeBuilder::build(SyntaxTree& tree) { SourceRange node_range; if (!children_.empty()) { auto begin = child_range(children_.front(), tree).begin(); auto end = child_range(children_.back(), tree).end(); node_range = SourceRange(begin, end); } else { node_range = SourceRange(pos_, pos_); } return SyntaxNode(type_, node_range, has_error_, std::move(children_)); } SourceRange child_range(const SyntaxChild& child, const SyntaxTree& tree) { struct Visitor { const SyntaxTree& tree; SourceRange visit_token(const Token& token) { return token.range(); } SourceRange visit_node_id(SyntaxNodeId node_id) { const auto& node = tree[node_id]; return node.range(); } }; return child.visit(Visitor{tree}); } } // namespace tiro
28.45614
97
0.677764
[ "vector" ]
793b3af691b0a8f2177630584c6a729ad7db661a
896
cpp
C++
cpp_2018/Bachgold_problem.cpp
Razdeep/Codeforces-Solutions
e808575219ec15bc07720d6abafe3c4c8df036f4
[ "MIT" ]
2
2020-08-27T18:21:04.000Z
2020-08-30T13:24:39.000Z
cpp_2018/Bachgold_problem.cpp
Razdeep/Codeforces-Solutions
e808575219ec15bc07720d6abafe3c4c8df036f4
[ "MIT" ]
null
null
null
cpp_2018/Bachgold_problem.cpp
Razdeep/Codeforces-Solutions
e808575219ec15bc07720d6abafe3c4c8df036f4
[ "MIT" ]
null
null
null
// https://codeforces.com/contest/749/problem/A /** Explanation: * We are told to make such a combination that has the max number of prime numbers * and the sum of those prime numbers is n. * The key point here to observe here is that it can be only achieved by using * the smallest prime numbers 2 and 3. We have to use 2 as many times as possible. * At last if there is no other option, a 3 is to be put. */ #include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { cin.sync_with_stdio(false); cin.tie(0); int n; cin>>n; vector<int> result; while(n>0) { if(n==3) { result.push_back(3); break; } result.push_back(2); n-=2; } cout<<result.size()<<endl; for(int i=0;i<result.size();i++) { cout<<result[i]<<" "; } cout<<endl; return 0; }
24.888889
83
0.587054
[ "vector" ]
793c2bcc4d6b18a52f46e25f655734b58d72a34d
2,895
cpp
C++
cam/src/v20190116/model/GroupIdOfUidInfo.cpp
TencentCloud/tencentcloud-sdk-cpp
896da198abe6f75c0dc90901131d709143186b77
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
cam/src/v20190116/model/GroupIdOfUidInfo.cpp
TencentCloud/tencentcloud-sdk-cpp
896da198abe6f75c0dc90901131d709143186b77
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
cam/src/v20190116/model/GroupIdOfUidInfo.cpp
TencentCloud/tencentcloud-sdk-cpp
896da198abe6f75c0dc90901131d709143186b77
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cam/v20190116/model/GroupIdOfUidInfo.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cam::V20190116::Model; using namespace std; GroupIdOfUidInfo::GroupIdOfUidInfo() : m_uidHasBeenSet(false), m_groupIdHasBeenSet(false) { } CoreInternalOutcome GroupIdOfUidInfo::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Uid") && !value["Uid"].IsNull()) { if (!value["Uid"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `GroupIdOfUidInfo.Uid` IsUint64=false incorrectly").SetRequestId(requestId)); } m_uid = value["Uid"].GetUint64(); m_uidHasBeenSet = true; } if (value.HasMember("GroupId") && !value["GroupId"].IsNull()) { if (!value["GroupId"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `GroupIdOfUidInfo.GroupId` IsUint64=false incorrectly").SetRequestId(requestId)); } m_groupId = value["GroupId"].GetUint64(); m_groupIdHasBeenSet = true; } return CoreInternalOutcome(true); } void GroupIdOfUidInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_uidHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Uid"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_uid, allocator); } if (m_groupIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "GroupId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_groupId, allocator); } } uint64_t GroupIdOfUidInfo::GetUid() const { return m_uid; } void GroupIdOfUidInfo::SetUid(const uint64_t& _uid) { m_uid = _uid; m_uidHasBeenSet = true; } bool GroupIdOfUidInfo::UidHasBeenSet() const { return m_uidHasBeenSet; } uint64_t GroupIdOfUidInfo::GetGroupId() const { return m_groupId; } void GroupIdOfUidInfo::SetGroupId(const uint64_t& _groupId) { m_groupId = _groupId; m_groupIdHasBeenSet = true; } bool GroupIdOfUidInfo::GroupIdHasBeenSet() const { return m_groupIdHasBeenSet; }
25.848214
142
0.689119
[ "model" ]
793d1126f33ae7daa0a10bd7a37eaebf46df2ae2
23,033
cpp
C++
Source/src/main/native/cpp/Rev2mDistanceSensor.cpp
markebert/2m-Distance-Sensor
0752d9479ba80b243cbaec74c5681e4874da720f
[ "BSD-3-Clause" ]
null
null
null
Source/src/main/native/cpp/Rev2mDistanceSensor.cpp
markebert/2m-Distance-Sensor
0752d9479ba80b243cbaec74c5681e4874da720f
[ "BSD-3-Clause" ]
null
null
null
Source/src/main/native/cpp/Rev2mDistanceSensor.cpp
markebert/2m-Distance-Sensor
0752d9479ba80b243cbaec74c5681e4874da720f
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2018-2019 REV Robotics * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of REV Robotics 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 "rev/Rev2mDistanceSensor.h" #include "vl53l0x_api.h" #include <hal/HAL.h> #include <hal/I2C.h> #include <thread> #include <atomic> #include <vector> #include <memory> #include <frc/Timer.h> #include <frc/DriverStation.h> #include <frc/smartdashboard/SendableBase.h> #include <frc/smartdashboard/SendableBuilder.h> #include <frc/Utility.h> #include <wpi/SmallString.h> #include <wpi/raw_ostream.h> #include <wpi/Format.h> //#define _DEBUG_ #define VALIDATE_I2C_SUCCESS 0 #define VALIDATE_I2C_PARAM_ERR 1 #define VALIDATE_I2C_HAL_ERR 2 using namespace rev; int Rev2mDistanceSensorAddress = 0x53; constexpr double defaultMeasurementPeriod = 0.05; std::atomic<bool> Rev2mDistanceSensor::m_automaticEnabled{false}; std::atomic<double> Rev2mDistanceSensor::m_measurementPeriod{defaultMeasurementPeriod}; std::vector<Rev2mDistanceSensor*> Rev2mDistanceSensor::m_sensors; std::thread Rev2mDistanceSensor::m_thread; void print_pal_error(VL53L0X_Error Status){ char buf[VL53L0X_MAX_STRING_LENGTH]; VL53L0X_GetPalErrorString(Status, buf); printf("API Status: %i : %s\n", Status, buf); } void print_pal_state(VL53L0X_State PalState) { char buf[VL53L0X_MAX_STRING_LENGTH]; VL53L0X_GetPalStateString(PalState, buf); printf("Pal Status: %s\n", buf); } Rev2mDistanceSensor::Rev2mDistanceSensor(Port port, DistanceUnit units, RangeProfile profile, int i2cAddress) : m_port(static_cast<HAL_I2CPort>(port)) { Rev2mDistanceSensorAddress = i2cAddress; pDevice->I2cDevAddr = Rev2mDistanceSensorAddress; pDevice->port = m_port; m_units = units; int32_t status = 0; HAL_InitializeI2C(m_port, &status); HAL_Report(HALUsageReporting::kResourceType_I2C, Rev2mDistanceSensorAddress); if(!Initialize(profile)) { wpi::SmallString<255> buf; wpi::raw_svector_ostream errorString{buf}; errorString << "Error initializing Rev 2M device on port " << wpi::format("%s", port == Port::kMXP ? "MXP" : "Onboard") << ". Please check your connections."; frc::DriverStation::ReportError(errorString.str()); } } Rev2mDistanceSensor::~Rev2mDistanceSensor() { bool wasAutomaticMode = m_automaticEnabled; SetAutomaticMode(false); // No synchronization needed because the background task is stopped. m_sensors.erase(std::remove(m_sensors.begin(), m_sensors.end(), this), m_sensors.end()); if (!m_sensors.empty() && wasAutomaticMode) { SetAutomaticMode(true); } } bool Rev2mDistanceSensor::IsRangeValid() const { return m_rangeValid; } double Rev2mDistanceSensor::GetRange(DistanceUnit units) { if(units == kCurrent) units = m_units; switch (units) { case Rev2mDistanceSensor::kInches: return GetRangeInches(); case Rev2mDistanceSensor::kMilliMeters: return GetRangeMM(); default: return -1; } } double Rev2mDistanceSensor::GetTimestamp(void) { return m_timestamp; } double Rev2mDistanceSensor::GetRangeMM() { return m_currentRange; } double Rev2mDistanceSensor::GetRangeInches() { return m_currentRange / 25.4; } void Rev2mDistanceSensor::SetEnabled(bool enable) { m_enabled = enable; } bool Rev2mDistanceSensor::SetRangeProfile(RangeProfile profile) { if(profile == m_profile) return true; // ignore the case of no change m_newProfile = profile; if(m_stopped && !m_automaticEnabled) { #ifdef _DEBUG_ printf("Sensor stopped. Changing profile\n"); #endif if (profile == RangeProfile::kHighAccuracy) return SetProfileHighAccuracy(); else if (profile == RangeProfile::kLongRange) return SetProfileLongRange(); else if (profile == RangeProfile::kHighSpeed) return SetProfileHighSpeed(); else return SetProfileDefault(); } else { #ifdef _DEBUG_ printf("Sensor not stopped. Disabling\n"); #endif m_enabled = false; return false; } } void Rev2mDistanceSensor::SetMeasurementPeriod(double period) { if(period < 0.01) { period = 0.01; } else if(period > 1) { period = 1; } m_measurementPeriod = period; } double Rev2mDistanceSensor::GetMeasurementPeriod(void) { return m_measurementPeriod; } void Rev2mDistanceSensor::SetDistanceUnits(DistanceUnit units) { m_units = units; } Rev2mDistanceSensor::DistanceUnit Rev2mDistanceSensor::GetDistanceUnits() const { return m_units; } bool Rev2mDistanceSensor::Initialize(RangeProfile profile) { Status = VL53L0X_ERROR_NONE; VL53L0X_Version_t *pVersion = new VL53L0X_Version_t; VL53L0X_DeviceInfo_t *pDeviceInfo = new VL53L0X_DeviceInfo_t; uint32_t refSpadCount; uint8_t isApertureSpads; uint8_t VhvSettings; uint8_t PhaseCal; uint32_t I2C_status; #ifdef _DEBUG_ printf("Initializing device on port: "); if(m_port == HAL_I2C_kOnboard) printf("Onboard\n"); else printf("MXP\n"); #endif if((I2C_status = ValidateI2C()) != VALIDATE_I2C_SUCCESS) { wpi::SmallString<255> buf; wpi::raw_svector_ostream errorString{buf}; errorString << "Error " << wpi::format("0x%08X", I2C_status) << ": Could not communicate with Rev 2M sensor over I2C."; frc::DriverStation::ReportError(errorString.str()); } Status = VL53L0X_GetVersion(pVersion); #ifdef _DEBUG_ if(Status != VL53L0X_ERROR_NONE) { frc::DriverStation::ReportError("Version error."); print_pal_error(Status); } #endif if(Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_DataInit(pDevice); // Data initialization } #ifdef _DEBUG_ else { print_pal_error(Status); } #endif if(Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_GetDeviceInfo(pDevice, pDeviceInfo); } #ifdef _DEBUG_ else { print_pal_error(Status); } #endif if(Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_StaticInit(pDevice); // Device Initialization } #ifdef _DEBUG_ else { print_pal_error(Status); } #endif if(Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_PerformRefCalibration(pDevice, &VhvSettings, &PhaseCal); // Device Initialization } #ifdef _DEBUG_ else { print_pal_error(Status); } #endif if(Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_PerformRefSpadManagement(pDevice, &refSpadCount, &isApertureSpads); // Device Initialization } #ifdef _DEBUG_ else { print_pal_error(Status); } #endif if(Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetDeviceMode(pDevice, VL53L0X_DEVICEMODE_CONTINUOUS_RANGING); } #ifdef _DEBUG_ else { print_pal_error(Status); } #endif if(Status == VL53L0X_ERROR_NONE) { if(SetRangeProfile(profile)) { m_sensors.emplace_back(this); m_enabled = true; } #ifdef _DEBUG_ else { frc::DriverStation::ReportWarning("Error setting range profile\n"); } #endif } // return true if initialization was successful return Status >= 0; } int32_t Rev2mDistanceSensor::ValidateI2C(void) { uint8_t reg = 0xC0, res[2]; if(HAL_TransactionI2C(pDevice->port, pDevice->I2cDevAddr >> 1, &reg, 1, res, 1) < 0) return VALIDATE_I2C_HAL_ERR | (1 << 24); if(*res != 0xEE) return VALIDATE_I2C_PARAM_ERR | (((uint32_t) reg) << 8) | (((uint32_t) res[0]) << 16); reg = 0xC1; if(HAL_TransactionI2C(pDevice->port, pDevice->I2cDevAddr >> 1, &reg, 1, res, 1) < 0) return VALIDATE_I2C_HAL_ERR | (1 << 25); if(*res != 0xAA) return VALIDATE_I2C_PARAM_ERR | (((uint32_t) reg) << 8) | (((uint32_t) res[0]) << 16); reg = 0xC2; if(HAL_TransactionI2C(pDevice->port, pDevice->I2cDevAddr >> 1, &reg, 1, res, 1) < 0) return VALIDATE_I2C_HAL_ERR | (1 << 26); if(*res != 0x10) return VALIDATE_I2C_PARAM_ERR | (((uint32_t) reg) << 8) | (((uint32_t) res[0]) << 16); reg = 0x51; if(HAL_TransactionI2C(pDevice->port, pDevice->I2cDevAddr >> 1, &reg, 1, res, 2) < 0) return VALIDATE_I2C_HAL_ERR | (1 << 27); reg = 0x61; if(HAL_TransactionI2C(pDevice->port, pDevice->I2cDevAddr >> 1, &reg, 1, res, 2) < 0) return VALIDATE_I2C_HAL_ERR | (1 << 28); if((res[0] != 0x00) || (res[1] != 0x00)) return VALIDATE_I2C_PARAM_ERR | (((uint32_t) reg) << 8) | (((uint32_t) res[0]) << 16) | (((uint32_t) res[1]) << 24); return VALIDATE_I2C_SUCCESS; } bool Rev2mDistanceSensor::IsEnabled() const { return m_enabled; } void Rev2mDistanceSensor::SetAutomaticMode(bool enabling) { if (enabling == m_automaticEnabled) return; // ignore the case of no change m_automaticEnabled = enabling; // if automatic is being enabled if(enabling) { // if thread is not currently running, start it if(!m_thread.joinable()) { #ifdef _DEBUG_ printf("Starting thread\n"); #endif m_thread = std::thread(&Rev2mDistanceSensor::DoContinuous); } } // else automatic mode is being disabled else { m_automaticEnabled = false; // disable all sensors for(auto& sensor : m_sensors) sensor->SetEnabled(false); } } void Rev2mDistanceSensor::DoContinuous(void) { bool allStopped; #ifdef _DEBUG_ printf("Thread started\n"); #endif do { // used to stop loop. allStopped will be changed to false if any sensors still running allStopped = true; // iterate through sensors for(auto& sensor : m_sensors) { // if sensor is enabled if(sensor->IsEnabled()) { // if sensor has not been started yet if(sensor->m_stopped) { sensor->StartMeasurement(); } // else sensor has been started else { sensor->GetMeasurementData(); } } // else automatic is not enabled else if(!sensor->m_stopped) { // if sensor is not currently stopping if(!sensor->m_stopping) { // command device to stop measurements sensor->StopMeasurement(); } // else sensor is currently stopping else { // check if sensor has finished sensor->GetStopCompletedStatus(); } } // else if sensor is stopped and measurement timing budget needs to be changed else if(sensor->m_newProfile != sensor->m_profile) { allStopped = false; sensor->SetProfile(sensor->m_newProfile); } // check if there are any sensors still enabled if(!sensor->m_stopped) { allStopped = false; } #ifdef _DEBUG_ else { printf("All sensors stopped\n"); } #endif } frc::Wait(m_measurementPeriod); } while(!allStopped || m_automaticEnabled); #ifdef _DEBUG_ printf("Stopping thread\n"); #endif // all sensors stopped and automatic is disabled so detach thread m_thread.detach(); } void Rev2mDistanceSensor::StartMeasurement(void) { // command device to start measurement VL53L0X_Error stat = VL53L0X_StartMeasurement(pDevice); if(stat == VL53L0X_ERROR_NONE) { m_stopped = false; #ifdef _DEBUG_ printf("Sensor started\n"); #endif } } bool Rev2mDistanceSensor::GetMeasurementDataReady(void) { // check for new data uint8_t NewDatReady = 0; VL53L0X_Error stat = VL53L0X_GetMeasurementDataReady(pDevice, &NewDatReady); // if new data is ready return ((NewDatReady == 0x01) && (stat == VL53L0X_ERROR_NONE)); } void Rev2mDistanceSensor::GetMeasurementData(void) { if(GetMeasurementDataReady()) { VL53L0X_Error stat = VL53L0X_GetRangingMeasurementData(pDevice, pRangingMeasurementData); VL53L0X_ClearInterruptMask(pDevice, VL53L0X_REG_SYSTEM_INTERRUPT_GPIO_NEW_SAMPLE_READY); if(stat == VL53L0X_ERROR_NONE) { // range is valid when RangeStatus equals 0 m_rangeValid = pRangingMeasurementData->RangeStatus == 0; m_currentRange = pRangingMeasurementData->RangeMilliMeter; m_timestamp = frc::Timer::GetFPGATimestamp(); } else { m_rangeValid = false; } } else { m_rangeValid = false; } } void Rev2mDistanceSensor::StopMeasurement(void) { #ifdef _DEBUG_ printf("Sensor Stopping\n"); #endif VL53L0X_Error stat = VL53L0X_StopMeasurement(pDevice); if(stat == VL53L0X_ERROR_NONE) { m_stopping = true; } } void Rev2mDistanceSensor::GetStopCompletedStatus(void) { uint32_t StopCompleted = 0; VL53L0X_Error stat = VL53L0X_GetStopCompletedStatus(pDevice, &StopCompleted); if((StopCompleted == 0x00) || stat != VL53L0X_ERROR_NONE) { m_stopped = true; m_stopping = false; VL53L0X_ClearInterruptMask(pDevice, VL53L0X_REG_SYSTEM_INTERRUPT_GPIO_NEW_SAMPLE_READY); #ifdef _DEBUG_ printf("Sensor Stopped\n"); #endif } #ifdef _DEBUG_ else { printf("Sensor not stopped yet.\n"); } #endif } void Rev2mDistanceSensor::SetProfile(RangeProfile profile) { #ifdef _DEBUG_ printf("Changing profile in autonomous\n"); #endif if (m_newProfile == RangeProfile::kHighAccuracy) m_enabled = SetProfileHighAccuracy(); else if (m_newProfile == RangeProfile::kLongRange) m_enabled = SetProfileLongRange(); else if (m_newProfile == RangeProfile::kHighSpeed) m_enabled = SetProfileHighSpeed(); else m_enabled = SetProfileDefault(); #ifdef _DEBUG_ if(m_enabled) printf("Sensor reenabled\n"); #endif } void Rev2mDistanceSensor::InitSendable(frc::SendableBuilder& builder) { builder.SetSmartDashboardType("Distance"); builder.AddDoubleProperty("Value", [=]() { return GetRange(); }, nullptr); } double Rev2mDistanceSensor::PIDGet() { switch (m_units) { case Rev2mDistanceSensor::kInches: return GetRangeInches(); case Rev2mDistanceSensor::kMilliMeters: return GetRangeMM(); default: return 0.0; } } void Rev2mDistanceSensor::SetPIDSourceType(frc::PIDSourceType pidSource) { if (wpi_assert(pidSource == frc::PIDSourceType::kDisplacement)) { m_pidSource = pidSource; } } bool Rev2mDistanceSensor::SetProfileLongRange(void) { #ifdef _DEBUG_ printf("Setting profile to long range\n"); #endif Status = VL53L0X_SetLimitCheckEnable(pDevice, VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE, 1); if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckEnable(pDevice, VL53L0X_CHECKENABLE_SIGNAL_RATE_FINAL_RANGE, 1); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckEnable(pDevice, VL53L0X_CHECKENABLE_RANGE_IGNORE_THRESHOLD, 0); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckValue(pDevice, VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE, (FixPoint1616_t)(60*65536)); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckValue(pDevice, VL53L0X_CHECKENABLE_SIGNAL_RATE_FINAL_RANGE, (FixPoint1616_t)(0.1*65536)); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetMeasurementTimingBudgetMicroSeconds(pDevice, 33000); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetVcselPulsePeriod(pDevice, VL53L0X_VCSEL_PERIOD_PRE_RANGE, 18); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetVcselPulsePeriod(pDevice, VL53L0X_VCSEL_PERIOD_FINAL_RANGE, 14); } if (Status == VL53L0X_ERROR_NONE) { #ifdef _DEBUG_ printf("Profile changed to long range\n"); #endif m_profile = RangeProfile::kLongRange; } return Status == VL53L0X_ERROR_NONE; } bool Rev2mDistanceSensor::SetProfileHighAccuracy(void) { #ifdef _DEBUG_ printf("Setting profile to high accuracy\n"); #endif Status = VL53L0X_SetLimitCheckEnable(pDevice, VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE, 1); if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckEnable(pDevice, VL53L0X_CHECKENABLE_SIGNAL_RATE_FINAL_RANGE, 1); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckEnable(pDevice, VL53L0X_CHECKENABLE_RANGE_IGNORE_THRESHOLD, 0); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckValue(pDevice, VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE, (FixPoint1616_t)(18*65536)); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckValue(pDevice, VL53L0X_CHECKENABLE_SIGNAL_RATE_FINAL_RANGE, (FixPoint1616_t)(0.25*65536)); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetMeasurementTimingBudgetMicroSeconds(pDevice, 200000); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetVcselPulsePeriod(pDevice, VL53L0X_VCSEL_PERIOD_PRE_RANGE, 14); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetVcselPulsePeriod(pDevice, VL53L0X_VCSEL_PERIOD_FINAL_RANGE, 10); } if (Status == VL53L0X_ERROR_NONE) { #ifdef _DEBUG_ printf("Profile changed to high accuracy\n"); #endif m_profile = RangeProfile::kHighAccuracy; } return Status == VL53L0X_ERROR_NONE; } bool Rev2mDistanceSensor::SetProfileHighSpeed(void) { #ifdef _DEBUG_ printf("Setting profile to high speed\n"); #endif Status = VL53L0X_SetLimitCheckEnable(pDevice, VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE, 1); if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckEnable(pDevice, VL53L0X_CHECKENABLE_SIGNAL_RATE_FINAL_RANGE, 1); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckEnable(pDevice, VL53L0X_CHECKENABLE_RANGE_IGNORE_THRESHOLD, 0); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckValue(pDevice, VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE, (FixPoint1616_t)(32*65536)); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckValue(pDevice, VL53L0X_CHECKENABLE_SIGNAL_RATE_FINAL_RANGE, (FixPoint1616_t)(0.25*65536)); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetMeasurementTimingBudgetMicroSeconds(pDevice, 30000); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetVcselPulsePeriod(pDevice, VL53L0X_VCSEL_PERIOD_PRE_RANGE, 14); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetVcselPulsePeriod(pDevice, VL53L0X_VCSEL_PERIOD_FINAL_RANGE, 10); } if (Status == VL53L0X_ERROR_NONE) { #ifdef _DEBUG_ printf("Profile changed to high range\n"); #endif m_profile = RangeProfile::kHighSpeed; } return Status == VL53L0X_ERROR_NONE; } bool Rev2mDistanceSensor::SetProfileDefault(void) { #ifdef _DEBUG_ printf("Setting profile to default\n"); #endif Status = VL53L0X_SetLimitCheckEnable(pDevice, VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE, 1); if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckEnable(pDevice, VL53L0X_CHECKENABLE_SIGNAL_RATE_FINAL_RANGE, 1); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckEnable(pDevice, VL53L0X_CHECKENABLE_RANGE_IGNORE_THRESHOLD, 0); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckValue(pDevice, VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE, (FixPoint1616_t)(18*65536)); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetLimitCheckValue(pDevice, VL53L0X_CHECKENABLE_SIGNAL_RATE_FINAL_RANGE, (FixPoint1616_t)(0.25*65536)); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetMeasurementTimingBudgetMicroSeconds(pDevice, 33823); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetVcselPulsePeriod(pDevice, VL53L0X_VCSEL_PERIOD_PRE_RANGE, 14); } if (Status == VL53L0X_ERROR_NONE) { Status = VL53L0X_SetVcselPulsePeriod(pDevice, VL53L0X_VCSEL_PERIOD_FINAL_RANGE, 10); } if (Status == VL53L0X_ERROR_NONE) { #ifdef _DEBUG_ printf("Profile changed to default\n"); #endif m_profile = RangeProfile::kDefault; } return Status == VL53L0X_ERROR_NONE; }
30.147906
124
0.648895
[ "vector" ]
794b6a308e3c84acd655bec6f18feb6f67ca2f32
3,723
cc
C++
multibody/test_utilities/floating_body_plant.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
multibody/test_utilities/floating_body_plant.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
multibody/test_utilities/floating_body_plant.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
#include "drake/multibody/test_utilities/floating_body_plant.h" #include <vector> #include "drake/common/default_scalars.h" #include "drake/multibody/tree/uniform_gravity_field_element.h" namespace drake { namespace multibody { namespace test { using Eigen::Vector3d; template<typename T> AxiallySymmetricFreeBodyPlant<T>::AxiallySymmetricFreeBodyPlant( double mass, double I, double J, double g) : MultibodyPlant<T>(0.0), mass_(mass), I_(I), J_(J), g_(g) { // Create the MultibodyPlant model. // Create the spatial inertia M_Bcm of body B, about Bcm, expressed in B. UnitInertia<double> G_Bcm = UnitInertia<double>::AxiallySymmetric(J_, I_, Vector3<double>::UnitZ()); SpatialInertia<double> M_Bcm(mass_, Vector3<double>::Zero(), G_Bcm); body_ = &this->AddRigidBody("FreeBody", M_Bcm); this->mutable_gravity_field().set_gravity_vector( -g_ * Vector3<double>::UnitZ()); this->Finalize(); // Some sanity checks. By default MultibodyPlant uses a quternion free // mobilizer for bodies that are not connected by any joint. DRAKE_DEMAND(this->num_positions() == 7); DRAKE_DEMAND(this->num_velocities() == 6); DRAKE_DEMAND(this->num_multibody_states() == 13); } template<typename T> template<typename U> AxiallySymmetricFreeBodyPlant<T>::AxiallySymmetricFreeBodyPlant( const AxiallySymmetricFreeBodyPlant<U> &other) : AxiallySymmetricFreeBodyPlant<T>( other.mass_, other.I_, other.J_, other.g_) {} template<typename T> Vector3<double> AxiallySymmetricFreeBodyPlant<T>::get_default_initial_angular_velocity() { return Vector3d::UnitX() + Vector3d::UnitY() + Vector3d::UnitZ(); } template<typename T> Vector3<double> AxiallySymmetricFreeBodyPlant<T>::get_default_initial_translational_velocity() { return Vector3d::UnitX(); } template<typename T> void AxiallySymmetricFreeBodyPlant<T>::SetDefaultState( const systems::Context<T>& context, systems::State<T>* state) const { DRAKE_DEMAND(state != nullptr); MultibodyPlant<T>::SetDefaultState(context, state); const SpatialVelocity<T> V_WB( get_default_initial_angular_velocity().template cast<T>(), get_default_initial_translational_velocity().template cast<T>()); this->tree().SetFreeBodySpatialVelocityOrThrow(body(), V_WB, context, state); } template<typename T> Vector3<T> AxiallySymmetricFreeBodyPlant<T>::get_angular_velocity( const systems::Context<T>& context) const { return CalcSpatialVelocityInWorldFrame(context).rotational(); } template<typename T> Vector3<T> AxiallySymmetricFreeBodyPlant<T>::get_translational_velocity( const systems::Context<T>& context) const { return CalcSpatialVelocityInWorldFrame(context).translational(); } template<typename T> math::RigidTransform<T> AxiallySymmetricFreeBodyPlant<T>::CalcPoseInWorldFrame( const systems::Context<T>& context) const { internal::PositionKinematicsCache<T> pc(this->tree().get_topology()); this->tree().CalcPositionKinematicsCache(context, &pc); return math::RigidTransform<T>(pc.get_X_WB(body_->node_index())); } template<typename T> SpatialVelocity<T> AxiallySymmetricFreeBodyPlant<T>::CalcSpatialVelocityInWorldFrame( const systems::Context<T>& context) const { internal::PositionKinematicsCache<T> pc(this->tree().get_topology()); this->tree().CalcPositionKinematicsCache(context, &pc); internal::VelocityKinematicsCache<T> vc(this->tree().get_topology()); this->tree().CalcVelocityKinematicsCache(context, pc, &vc); return vc.get_V_WB(body_->node_index()); } } // namespace test } // namespace multibody } // namespace drake DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_NONSYMBOLIC_SCALARS( class ::drake::multibody::test::AxiallySymmetricFreeBodyPlant)
36.145631
80
0.761751
[ "vector", "model" ]
795479ac71a008dba18102c91799ce03479a02a3
4,209
cpp
C++
DotFlipGame.cpp
Soundsgoood/dot-flip-in-cplusplus
6042b4d2f5f04d359f9f33ea8243c77b8332e848
[ "MIT" ]
null
null
null
DotFlipGame.cpp
Soundsgoood/dot-flip-in-cplusplus
6042b4d2f5f04d359f9f33ea8243c77b8332e848
[ "MIT" ]
null
null
null
DotFlipGame.cpp
Soundsgoood/dot-flip-in-cplusplus
6042b4d2f5f04d359f9f33ea8243c77b8332e848
[ "MIT" ]
null
null
null
//Orion Guan //April 17th, 2017 //Ported from DotFlipGame.java, with implementation handled differently. #include <iostream> #include <vector> #include <string> #include <sstream> #include <time.h> #include <cstdlib> using namespace std; //The game itself, with the current state of the dots, the original state, and the goal "ideal" state. class DotFlipGame { private: static char const STATE_ONE = '+'; static char const STATE_TWO = '-'; vector<bool> gameSetup; vector<bool> gameState; vector<bool> idealState; int moveCounter; //Generates dot orientations to begin the game. vector<bool> generateGameSetup(int numberOfDots) { vector<bool> gameSetup(numberOfDots); //gameSetup.clear(); //how to prevent larger vectors? for (int i = 0; i < numberOfDots; i++) { if (rand() % 2 == 0) gameSetup[i] = true; else gameSetup[i] = false; } return gameSetup; } //Makes the ideal state the dots should be in. vector<bool> makeIdealSetup(int numberOfDots) { vector<bool> idealSetup(numberOfDots); //idealSetup.clear(); for (int i = 0; i < numberOfDots; i++) { idealSetup[i] = true; } return idealSetup; } //Turns a state of the dots into a string of characters. string gameStateToString(vector<bool> gameState) { string gameString = ""; for (int i = 0; i < gameState.size(); i++) { if (gameState[i]) gameString += STATE_ONE; else gameString += STATE_TWO; } return gameString; } //Flips a dot and adjacent dots. vector<bool> flip(vector<bool> gameState, int input) { int stateSize = gameState.size(); gameState[input] = !gameState[input]; gameState[(input + stateSize - 1) % stateSize] = !gameState[(input + stateSize - 1) % stateSize]; gameState[(input + 1) % stateSize] = !gameState[(input + 1) % stateSize]; return gameState; } public: //Creates a game. DotFlipGame(int numberOfDots) { idealState = makeIdealSetup(numberOfDots); gameSetup = idealState; while (gameSetup == idealState) { gameSetup = generateGameSetup(numberOfDots); } gameState = gameSetup; moveCounter = 0; } //Creates a game from an existing dot setup. DotFlipGame(vector<bool> gameSetup) { int numberOfDots = gameSetup.size(); idealState = makeIdealSetup(numberOfDots); this->gameSetup = gameSetup; while (gameSetup == idealState) { gameSetup = generateGameSetup(numberOfDots); } gameState = gameSetup; moveCounter = 0; } //Plays the game, giving the player appropriate prompts. void play() { int gameSize = gameSetup.size(); stringstream ss; for (int i = 1; i <= gameSize; i++) { ss << (i % 10); //to cut off more significant digits } string numberGuide = ss.str(); cout << "Enter a number to flip a dot and surrounding dots. Get all +'s!" << endl; while (gameState != idealState) { int input; cout << numberGuide << endl << gameStateToString(gameState) << endl; cin >> input; if (input >= 1 && input <= gameSize) { gameState = flip(gameState, input - 1); moveCounter++; } else { cout << "Pick a number in the range shown!" << endl; } } cout << gameStateToString(gameState) << endl << "You won! It took you " << moveCounter << " moves." << endl; } //Returns the original setup of the game. vector<bool> getGameSetup() const { return gameSetup; } }; int main() { void srand(unsigned int seed); srand(time(NULL)); static int const NUMBER_OF_DOTS = 8; bool playAgain = true; cout << "Welcome to DotFlip!" << endl; while(playAgain == true) { cout << "Generating game . . ." << endl; DotFlipGame currentGame(NUMBER_OF_DOTS); cout << "Game generated." << endl; currentGame.play(); cout << "Play again? Y/N " << endl; char yesOrNo; cin >> yesOrNo; if (yesOrNo == 'y' || yesOrNo == 'Y') playAgain = true; else if (yesOrNo == 'n' || yesOrNo == 'N') playAgain = false; else { cout << "Invalid input. I assume you don't want to play." << endl; playAgain = false; } } cout << "See ya!" << endl; }
23.779661
103
0.626039
[ "vector" ]
795d32077099cb022a0d3d935eaf169ed4c3d469
2,096
cpp
C++
src/ofxSollingerDSP.cpp
elliotwoods/ofxSollingerDSP
582ea7d475fc4290c3b51e9d5c3dc29f03a12263
[ "MIT" ]
1
2017-06-26T04:23:26.000Z
2017-06-26T04:23:26.000Z
src/ofxSollingerDSP.cpp
elliotwoods/ofxSollingerDSP
582ea7d475fc4290c3b51e9d5c3dc29f03a12263
[ "MIT" ]
null
null
null
src/ofxSollingerDSP.cpp
elliotwoods/ofxSollingerDSP
582ea7d475fc4290c3b51e9d5c3dc29f03a12263
[ "MIT" ]
null
null
null
#include "ofxSollingerDSP.h" //---------- string ofxSollingerDSP::selectDeviceDialog() { char buffer[256]; if (!LGDspDll_SelectDialog(buffer, 256)) { // Aborted by user => No error return ""; } return string(buffer); } //---------- bool ofxSollingerDSP::setup(const string & address) { if (!LGDspDll_Connect(address.c_str())) { this->printError(); this->isConnected = false; return false; } else { this->isConnected = true; return true; } } //---------- bool ofxSollingerDSP::getIsConnected() const { return this->isConnected; } //---------- vector<string> ofxSollingerDSP::getCatalogNames() const { if (!LGDspDll_GetCatalogNames()) { this->printError(); return vector<string>(); } char buffer[256]; vector<string> results; while (LGDspDll_GetNextCatalogName(buffer, 256)) { results.push_back(string(buffer)); } return results; } //---------- void ofxSollingerDSP::setPicture(const ofPolyline & line, const ofRectangle & bounds /*= ofGetCurrentViewport()*/) { vector<DspPoint> dspPoints; dspPoints.reserve(line.size()); for (const auto & point : line.getVertices()) { dspPoints.emplace_back( (short)ofMap(point.x , bounds.getLeft() , bounds.getRight() , numeric_limits<short>::min() , numeric_limits<short>::max() , true) , (short)ofMap(point.y , bounds.getTop() , bounds.getBottom() , numeric_limits<short>::max() , numeric_limits<short>::min() , true) , 0 , 0 , 1 , 0 , false , false , & point == & line.getVertices().back() ); } //if empty then add a blank point if (dspPoints.empty()) { dspPoints.push_back(DspPoint(0, 0, 0, 0, 0, 0, true, false, true)); } if (!LGDspDll_SetPicture("TestCat", "TestPic", dspPoints.size(), (DspPoint*) dspPoints.data())) { this->printError(); } } //---------- void ofxSollingerDSP::printError() const { char buffer[256]; if (LGDspDll_GetLastError(buffer, 256)) { ofLogError("ofxSollingerDSP") << buffer; } }
20.153846
117
0.604962
[ "vector" ]
795e58b2f7332093591ff8c0d69a53c808894de6
1,108
cpp
C++
457.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
457.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
457.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
#include <cstdio> #include <cmath> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #include <map> #define fi first #define se second #define pb push_back #define mp make_pair #define pi 2*acos(0.0) #define eps 1e-9 #define PII pair<int,int> #define PDD pair<double,double> #define LL long long #define INF 1000000000 using namespace std; char idx[]={' ','.','x','W'}; int T,x,y,z,next; int dna[15]; char seg[2][50]; int main() { scanf("%d",&T); for(x=0;x<T;x++) { for(y=0;y<10;y++) scanf("%d",&dna[y]); memset(seg[0],' ',sizeof(seg[0]));seg[0][19]='.'; if(x) printf("\n"); for(z=0;z<50;z++) { for(y=0;y<40;y++) { printf("%c",seg[z&1][y]); next=0; for(int i=-1;i<2;i++) if((y+i>=0)&&(y+i<40)) switch(seg[z&1][y+i]) { case('.') : next++;break; case('x') : next+=2;break; case('W') : next+=3;break; } seg[(z+1)&1][y]=idx[dna[next]]; } printf("\n"); } } return 0; }
18.466667
52
0.528881
[ "vector" ]
79624d3cac9ebd91cd6b6d824ddb8f68a8347dfa
20,770
cpp
C++
maku/render/opengl_canvas.cpp
shileiyu/maku
be07aa6f804c387aafbd79cdf952bd6a93c18771
[ "MIT" ]
10
2015-04-09T01:43:28.000Z
2021-03-29T15:59:01.000Z
maku/render/opengl_canvas.cpp
shileiyu/maku
be07aa6f804c387aafbd79cdf952bd6a93c18771
[ "MIT" ]
null
null
null
maku/render/opengl_canvas.cpp
shileiyu/maku
be07aa6f804c387aafbd79cdf952bd6a93c18771
[ "MIT" ]
1
2020-07-02T03:52:56.000Z
2020-07-02T03:52:56.000Z
#include "opengl_canvas.h" #include "opengl_common.h" #include "opengl_shader.h" #include "utils.h" namespace maku { namespace render { namespace opengl { #define GETADDRESS(x) T##x = (x##_T)TwglGetProcAddress(#x) #define CHECKADDR(x) if(!(x)) return false; // glDeleteTextures_T TglDeleteTextures = NULL; glGetString_T TglGetString = NULL; glGenTextures_T TglGenTextures = NULL; glBindTexture_T TglBindTexture = NULL; glTexParameteri_T TglTexParameteri = NULL; glTexImage2D_T TglTexImage2D = NULL; glViewport_T TglViewport = NULL; glEnable_T TglEnable = NULL; glDisable_T TglDisable = NULL; glGetTexLevelParameteriv_T TglGetTexLevelParameteriv= NULL; glTexSubImage2D_T TglTexSubImage2D = NULL; glPushAttrib_T TglPushAttrib = NULL; glPushClientAttrib_T TglPushClientAttrib = NULL; glPopClientAttrib_T TglPopClientAttrib = NULL; glPopAttrib_T TglPopAttrib = NULL; glBlendFunc_T TglBlendFunc = NULL; glGetIntegerv_T TglGetIntegerv = NULL; glMatrixMode_T TglMatrixMode = NULL; glPushMatrix_T TglPushMatrix = NULL; glPopMatrix_T TglPopMatrix = NULL; glLoadIdentity_T TglLoadIdentity = NULL; glOrtho_T TglOrtho = NULL; glDrawArrays_T TglDrawArrays = NULL; glBegin_T TglBegin= NULL; glColor3f_T TglColor3f = NULL; glTexCoord2f_T TglTexCoord2f = NULL; glVertex3f_T TglVertex3f = NULL; glEnd_T TglEnd = NULL; glColor4f_T TglColor4f = NULL; wglGetProcAddress_T TwglGetProcAddress = NULL; // glGenVertexArrays_T TglGenVertexArrays = NULL; glGenBuffers_T TglGenBuffers = NULL; glDeleteBuffers_T TglDeleteBuffers = NULL; glBindBuffer_T TglBindBuffer = NULL; glDeleteVertexArrays_T TglDeleteVertexArrays = NULL; glBindVertexArray_T TglBindVertexArray = NULL; glGetUniformLocation_T TglGetUniformLocation = NULL; glUniformMatrix4fv_T TglUniformMatrix4fv = NULL; glBufferData_T TglBufferData = NULL; glUseProgram_T TglUseProgram = NULL; glActiveTexture_T TglActiveTexture = NULL; glUniform1i_T TglUniform1i = NULL; glEnableVertexAttribArray_T TglEnableVertexAttribArray = NULL; glDisableVertexAttribArray_T TglDisableVertexAttribArray = NULL; glVertexAttribPointer_T TglVertexAttribPointer = NULL; // glCreateShader_T TglCreateShader = NULL; glShaderSource_T TglShaderSource = NULL; glCompileShader_T TglCompileShader = NULL; glGetShaderiv_T TglGetShaderiv = NULL; glCreateProgram_T TglCreateProgram = NULL; glDeleteProgram_T TglDeleteProgram = NULL; glAttachShader_T TglAttachShader = NULL; glLinkProgram_T TglLinkProgram = NULL; glGetProgramiv_T TglGetProgramiv = NULL; glDeleteShader_T TglDeleteShader = NULL; OpenGLCanvas::OpenGLCanvas(HGLRC hrc) { vertex_array_ = 0; program_id_ = 0; texture_id_ = 0; texture_name_ = 0; matrix_id_ = 0; old_array_ = 0; old_program_ = 0; old_texture_ = 0; vertex_buffer_ = 0; uv_buffer_ = 0; color_buffer_ = 0; hrc_ = hrc; ZeroMemory(vertex_data_, sizeof(vertex_data_)); ZeroMemory(uv_data_, sizeof(uv_data_)); ZeroMemory(color_data_, sizeof(color_data_)); ZeroMemory(old_viewport_, 4 * sizeof(GLint)); ZeroMemory(&ortho_, sizeof(ortho_)); ZeroMemory(&rect_, sizeof(rect_)); uv_data_[1][0] = uv_data_[2][1] = uv_data_[3][0] = uv_data_[3][1] = 1.0f; GetDllProcAddress(); shader_flag_ = IsShaderDraw(); } OpenGLCanvas::~OpenGLCanvas() { //delete buffer if (0 != texture_name_) TglDeleteTextures(1, &texture_name_); if(vertex_buffer_) TglDeleteBuffers(1, &vertex_buffer_); if(uv_buffer_) TglDeleteBuffers(1, &uv_buffer_); if(color_buffer_) TglDeleteBuffers(1, &color_buffer_); if(0 != vertex_array_) TglDeleteVertexArrays(1, &vertex_array_); if(0 != program_id_) TglDeleteProgram(program_id_); } void OpenGLCanvas::GetDllProcAddress() { HMODULE gl_mod = ::GetModuleHandle(L"opengl32.dll"); TglDeleteTextures = (glDeleteTextures_T)GetProcAddress(gl_mod, "glDeleteTextures"); TglGetString = (glGetString_T)GetProcAddress(gl_mod, "glGetString"); TglGenTextures = (glGenTextures_T)GetProcAddress(gl_mod, "glGenTextures"); TglBindTexture = (glBindTexture_T)GetProcAddress(gl_mod, "glBindTexture"); TglTexParameteri = (glTexParameteri_T)GetProcAddress(gl_mod, "glTexParameteri"); TglTexImage2D = (glTexImage2D_T)GetProcAddress(gl_mod, "glTexImage2D"); TglViewport = (glViewport_T)GetProcAddress(gl_mod, "glViewport"); TglEnable = (glEnable_T)GetProcAddress(gl_mod, "glEnable"); TglDisable = (glDisable_T)GetProcAddress(gl_mod, "glDisable"); TglGetTexLevelParameteriv= (glGetTexLevelParameteriv_T)GetProcAddress(gl_mod, "glGetTexLevelParameteriv"); TglTexSubImage2D = (glTexSubImage2D_T)GetProcAddress(gl_mod, "glTexSubImage2D"); TglPushAttrib = (glPushAttrib_T)GetProcAddress(gl_mod, "glPushAttrib"); TglPushClientAttrib = (glPushClientAttrib_T)GetProcAddress(gl_mod, "glPushClientAttrib"); TglPopClientAttrib = (glPopClientAttrib_T)GetProcAddress(gl_mod, "glPopClientAttrib"); TglPopAttrib = (glPopAttrib_T)GetProcAddress(gl_mod, "glPopAttrib"); TglBlendFunc = (glBlendFunc_T)GetProcAddress(gl_mod, "glBlendFunc"); TglGetIntegerv = (glGetIntegerv_T)GetProcAddress(gl_mod, "glGetIntegerv"); TglMatrixMode = (glMatrixMode_T)GetProcAddress(gl_mod, "glMatrixMode"); TglPushMatrix = (glPushMatrix_T)GetProcAddress(gl_mod, "glPushMatrix"); TglPopMatrix = (glPopMatrix_T)GetProcAddress(gl_mod, "glPopMatrix"); TglLoadIdentity = (glLoadIdentity_T)GetProcAddress(gl_mod, "glLoadIdentity"); TglOrtho = (glOrtho_T)GetProcAddress(gl_mod, "glOrtho"); TglDrawArrays = (glDrawArrays_T)GetProcAddress(gl_mod, "glDrawArrays"); TglBegin= (glBegin_T)GetProcAddress(gl_mod, "glBegin"); TglColor3f = (glColor3f_T)GetProcAddress(gl_mod, "glColor3f"); TglTexCoord2f = (glTexCoord2f_T)GetProcAddress(gl_mod, "glTexCoord2f"); TglVertex3f = (glVertex3f_T)GetProcAddress(gl_mod, "glVertex3f"); TglEnd = (glEnd_T)GetProcAddress(gl_mod, "glEnd"); TglColor4f = (glColor4f_T)GetProcAddress(gl_mod, "glColor4f"); TwglGetProcAddress = (wglGetProcAddress_T)GetProcAddress(gl_mod, "wglGetProcAddress"); } void OpenGLCanvas::GetAllProcAddress() { GETADDRESS(glGenVertexArrays); GETADDRESS(glGenBuffers); GETADDRESS(glDeleteBuffers); GETADDRESS(glBindBuffer); GETADDRESS(glBindVertexArray); GETADDRESS(glDeleteVertexArrays); GETADDRESS(glGetUniformLocation); GETADDRESS(glUniformMatrix4fv); GETADDRESS(glBufferData); GETADDRESS(glUseProgram); GETADDRESS(glActiveTexture); GETADDRESS(glUniform1i); GETADDRESS(glEnableVertexAttribArray); GETADDRESS(glDisableVertexAttribArray); GETADDRESS(glVertexAttribPointer); GETADDRESS(glCreateShader); GETADDRESS(glShaderSource); GETADDRESS(glCompileShader); GETADDRESS(glGetShaderiv); GETADDRESS(glCreateProgram); GETADDRESS(glDeleteProgram); GETADDRESS(glAttachShader); GETADDRESS(glLinkProgram); GETADDRESS(glGetProgramiv); GETADDRESS(glDeleteShader); } bool OpenGLCanvas::CheckAllProcAddress() { CHECKADDR(TglGenVertexArrays); CHECKADDR(TglGenBuffers); CHECKADDR(TglDeleteBuffers); CHECKADDR(TglBindBuffer); CHECKADDR(TglBindVertexArray); CHECKADDR(TglDeleteVertexArrays); CHECKADDR(TglGetUniformLocation); CHECKADDR(TglUniformMatrix4fv); CHECKADDR(TglBufferData); CHECKADDR(TglUseProgram); CHECKADDR(TglActiveTexture); CHECKADDR(TglUniform1i); CHECKADDR(TglEnableVertexAttribArray); CHECKADDR(TglDisableVertexAttribArray); CHECKADDR(TglVertexAttribPointer); CHECKADDR(TglCreateShader); CHECKADDR(TglShaderSource); CHECKADDR(TglCompileShader); CHECKADDR(TglGetShaderiv); CHECKADDR(TglCreateProgram); CHECKADDR(TglDeleteProgram); CHECKADDR(TglAttachShader); CHECKADDR(TglLinkProgram); CHECKADDR(TglGetProgramiv); CHECKADDR(TglDeleteShader); return true; } GLuint OpenGLCanvas::LoadShader() { // Create the shaders GLuint VertexShaderID = TglCreateShader(GL_VERTEX_SHADER); GLuint FragmentShaderID = TglCreateShader(GL_FRAGMENT_SHADER); // Read the Vertex Shader code from the file std::string VertexShaderCode(vertex_shader); // Read the Fragment Shader code from the file std::string FragmentShaderCode(fragment_shader); // Compile Vertex Shader char const * VertexSourcePointer = VertexShaderCode.c_str(); TglShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL); TglCompileShader(VertexShaderID); // Compile Fragment Shader char const * FragmentSourcePointer = FragmentShaderCode.c_str(); TglShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL); TglCompileShader(FragmentShaderID); // Link the program GLuint ProgramID = TglCreateProgram(); TglAttachShader(ProgramID, VertexShaderID); TglAttachShader(ProgramID, FragmentShaderID); TglLinkProgram(ProgramID); TglDeleteShader(VertexShaderID); TglDeleteShader(FragmentShaderID); return ProgramID; } bool OpenGLCanvas::IsShaderDraw() { if(TglGetString == 0) return false; int main_version = 0; bool result = false; const char* str = (const char*)TglGetString(GL_VERSION); if(NULL != str) sscanf_s(str, "%d", &main_version); if(main_version >= 3) result = true; return result; } void OpenGLCanvas::CreateTexture(uint32_t width, uint32_t height) { //gen empty texture TglGenTextures(1, &texture_name_); TglBindTexture(GL_TEXTURE_2D, texture_name_); TglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); TglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); TglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); TglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); TglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, NULL); } void OpenGLCanvas::SetColor(Float4 f) { for (int i = 0; i < 4; ++i) { color_data_[i][0] = f.x; color_data_[i][1] = f.y; color_data_[i][2] = f.z; color_data_[i][3] = f.w; } TglBindBuffer(GL_ARRAY_BUFFER, color_buffer_); TglBufferData(GL_ARRAY_BUFFER, sizeof(color_data_), color_data_, GL_STATIC_DRAW); TglEnableVertexAttribArray(2); TglBindBuffer(GL_ARRAY_BUFFER, color_buffer_); TglVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 0, (void*)0); } void OpenGLCanvas::CreateVertexAndUVBuffer() { TglGenVertexArrays(1, &vertex_array_); TglBindVertexArray(vertex_array_); //color buffer TglGenBuffers(1, &color_buffer_); //vertex TglGenBuffers(1, &vertex_buffer_); TglBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_); TglBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data_), vertex_data_, GL_STATIC_DRAW); //uv TglGenBuffers(1, &uv_buffer_); TglBindBuffer(GL_ARRAY_BUFFER, uv_buffer_); TglBufferData(GL_ARRAY_BUFFER, sizeof(uv_data_), uv_data_, GL_STATIC_DRAW); //vertex TglEnableVertexAttribArray(0); TglBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_); TglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); //uv TglEnableVertexAttribArray(1); TglBindBuffer(GL_ARRAY_BUFFER, uv_buffer_); TglVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); } void OpenGLCanvas::UpdateRect(RECT & rect) { int width = rect.right - rect.left; int height = rect.bottom - rect.top; if (width != rect_.width() || height != rect_.height()) { TransRect(rect, rect_); ortho_ = MatrixOrthographicOffCenterLH((float)rect_.left(), (float)rect_.right(), (float)rect_.bottom(), (float)rect_.top(), 0.0f, 100.0f); if (0 != texture_name_) TglDeleteTextures(1, &texture_name_); texture_name_ = 0; } } void OpenGLCanvas::Prepare() { if (0 == program_id_) Create(); if(0 == texture_name_) CreateTexture(rect_.width(), rect_.height()); TglViewport(rect_.left(), rect_.top(), rect_.width(), rect_.height()); if (shader_flag_) { //set status TglBindVertexArray(vertex_array_); TglActiveTexture(GL_TEXTURE0); TglEnable(GL_TEXTURE_2D); TglBindTexture(GL_TEXTURE_2D, texture_name_); TglUseProgram(program_id_); TglUniform1i(texture_id_, 0); } } void OpenGLCanvas::GetTextureWH(uint32_t & width, uint32_t & height) { GLint temp; TglGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &temp); width = temp; TglGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &temp); height = temp; } void OpenGLCanvas::SaveStatus() { //save status TglPushAttrib(GL_ALL_ATTRIB_BITS); TglPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS); //set status TglEnable(GL_BLEND); TglEnable(GL_ALPHA_TEST); TglDisable(GL_CULL_FACE); TglDisable(GL_SCISSOR_TEST); TglDisable(GL_DEPTH_TEST); TglEnable(GL_TEXTURE_2D); TglEnable(GL_TEXTURE); TglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); TglGetIntegerv(GL_VIEWPORT, old_viewport_); if (shader_flag_) { TglGetIntegerv(GL_VERTEX_ARRAY_BINDING, &old_array_); TglGetIntegerv(GL_TEXTURE_BINDING_2D, &old_texture_); TglGetIntegerv(GL_CURRENT_PROGRAM, &old_program_); } else { //push matrix TglMatrixMode(GL_PROJECTION); TglPushMatrix(); TglLoadIdentity(); TglOrtho(0.0, rect_.width() - 1.0, 0.0, rect_.height() - 1.0, -1.0, 1.0); TglMatrixMode(GL_MODELVIEW); TglPushMatrix(); TglLoadIdentity(); } //prepare Prepare(); } void OpenGLCanvas::RestoreStatus() { if (shader_flag_) { TglBindVertexArray(old_array_); TglBindTexture(GL_TEXTURE_2D, old_texture_); TglUseProgram(old_program_); } else { //pop matrix TglMatrixMode(GL_MODELVIEW); TglPopMatrix(); TglMatrixMode(GL_PROJECTION); TglPopMatrix(); //TglMatrixMode(GL_MODELVIEW); } //restore status TglViewport(old_viewport_[0], old_viewport_[1], old_viewport_[2], old_viewport_[3]); TglPopClientAttrib(); TglPopAttrib(); } void OpenGLCanvas::Create() { //prepare if (shader_flag_) { GetAllProcAddress(); if (!CheckAllProcAddress()) { shader_flag_ = false; return; } program_id_ = LoadShader(); texture_id_ = TglGetUniformLocation(program_id_, "myTextureSampler"); matrix_id_ = TglGetUniformLocation(program_id_, "MVP"); CreateVertexAndUVBuffer(); } } void OpenGLCanvas::UpdateVertexData(SimpleVertex * p, int n) { for (int i = 0; i < n; ++i) { vertex_data_[i][0] = static_cast<GLfloat>(p[i].x); vertex_data_[i][1] = static_cast<GLfloat>(p[i].y); vertex_data_[i][2] = static_cast<GLfloat>(p[i].z); uv_data_[i][0] = static_cast<GLfloat>(p[i].u); uv_data_[i][1] = static_cast<GLfloat>(p[i].v); }; TglBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_); TglBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data_), vertex_data_, GL_STATIC_DRAW); TglBindBuffer(GL_ARRAY_BUFFER, uv_buffer_); TglBufferData(GL_ARRAY_BUFFER, sizeof(uv_data_), uv_data_, GL_STATIC_DRAW); TglEnableVertexAttribArray(0); TglBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_); TglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); } void OpenGLCanvas::UpdateTexture(Bitmap & bmp_info) { TglTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bmp_info.width, bmp_info.height, GL_RGBA, GL_UNSIGNED_BYTE, bmp_info.bits); } void OpenGLCanvas::DrawBitmap(Bitmap & bmp_info, const Rect & dest) { // uint32_t width = 0; uint32_t height = 0; GetTextureWH(width, height); //create or update if (bmp_info.width > width || bmp_info.height > height) { TglDeleteTextures(1, &texture_name_); CreateTexture(bmp_info.width, bmp_info.height); } GetTextureWH(width, height); //update data UpdateTexture(bmp_info); float max_u = (float)(bmp_info.width) / width; float max_v = (float)(bmp_info.height) / height; //draw if (shader_flag_) { //vertex data SimpleVertex p[4] = { {rect_.left() + dest.left(), rect_.top() + dest.top(), 0, 0, 0}, {rect_.left() + dest.right(), rect_.top() + dest.top(), 0, max_u, 0}, {rect_.left() + dest.left(), rect_.top() + dest.bottom(), 0, 0, max_v}, {rect_.left() + dest.right(), rect_.top() + dest.bottom(), 0, max_u, max_v}, }; UpdateVertexData(p, 4); //set color Float4 color; color.x = 0.0f; color.y = 0.0f; color.z = 0.0f; color.w = 0.0f; SetColor(color); //draw TglUniformMatrix4fv(matrix_id_, 1, GL_FALSE, &ortho_.m0.x); TglDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } else {//may be error TglBegin(GL_QUADS); TglColor3f(1.0, 1.0, 1.0); TglTexCoord2f(0.0, max_v); TglVertex3f((float)(rect_.left() + dest.left()), (float)(rect_.top() + dest.top()), 0.0); TglTexCoord2f(max_u, max_v); TglVertex3f((float)(rect_.left() + dest.right()), (float)(rect_.top() + dest.top()), 0.0); TglTexCoord2f(max_u, 0.0); TglVertex3f((float)(rect_.left() + dest.left()), (float)(rect_.top() + dest.bottom()), 0.0); TglTexCoord2f(0.0, 0.0); TglVertex3f((float)(rect_.left() + dest.right()), (float)(rect_.top() + dest.bottom()), 0.0); TglEnd(); } } void OpenGLCanvas::DrawLine(const Point & p1, const Point & p2, const Paint & paint) { TglBindTexture(GL_TEXTURE_2D, 0); if (shader_flag_) { //update vertex data SimpleVertex p[2] = { {rect_.left() + p1.x(), rect_.top() + p1.y(), 0, 0, 0}, {rect_.left() + p2.x(), rect_.top() + p2.y(), 0, 0, 0}, }; UpdateVertexData(p, 2); //color buffer Float4 color; TransFloat(paint.color, color); SetColor(color); // TglUniformMatrix4fv(matrix_id_, 1, GL_FALSE, &ortho_.m0.x); TglDrawArrays(GL_LINES, 0, 2); } else { Float4 color; TransFloat(paint.color, color); TglBegin(GL_LINES); TglColor4f(color.x, color.y, color.z, color.w); TglVertex3f((float)p1.x(), (float)p1.y(), 0.0); TglVertex3f((float)p2.x(), (float)p2.y(), 0.0); TglEnd(); } } void OpenGLCanvas::DrawPoint(const Point & p1, const Paint & paint) { TglBindTexture(GL_TEXTURE_2D, 0); if (shader_flag_) { //update vertex data SimpleVertex p = {rect_.left() + p1.x(), rect_.top() + p1.y(), 0, 0, 0}; UpdateVertexData(&p, 1); //color buffer Float4 color; TransFloat(paint.color, color); SetColor(color); // TglUniformMatrix4fv(matrix_id_, 1, GL_FALSE, &ortho_.m0.x); TglDrawArrays(GL_POINT, 0, 1); } else { Float4 color; TransFloat(paint.color, color); TglBegin(GL_POINT); TglColor4f(color.x, color.y, color.z, color.w); TglVertex3f((float)p1.x(), (float)p1.y(), 0.0); TglEnd(); } } void OpenGLCanvas::DrawRect(const Rect & rect, const Paint & paint) { //update vertex data SimpleVertex p[4] = { {rect_.left() + rect.left(), rect_.top() + rect.top(), 0, 0, 0}, {rect_.left() + rect.right(), rect_.top() + rect.top(), 0, 0, 0}, {rect_.left() + rect.left(), rect_.top() + rect.bottom(), 0, 0, 0}, {rect_.left() + rect.right(), rect_.top() + rect.bottom(), 0, 0, 0}, }; //draw TglBindTexture(GL_TEXTURE_2D, 0); if (shader_flag_) { UpdateVertexData(p, 4); //color buffer Float4 color; TransFloat(paint.color, color); SetColor(color); // TglUniformMatrix4fv(matrix_id_, 1, GL_FALSE, &ortho_.m0.x); TglDrawArrays(GL_LINE_LOOP, 0, 4); } else { Float4 color; TransFloat(paint.color, color); TglBegin(GL_LINE_LOOP); TglColor4f(color.x, color.y, color.z, color.w); TglVertex3f((float)p[0].x, (float)p[0].y, 0.0); TglVertex3f((float)p[1].x, (float)p[1].y, 0.0); TglVertex3f((float)p[2].x, (float)p[2].y, 0.0); TglVertex3f((float)p[3].x, (float)p[3].y, 0.0); TglEnd(); } } } } }
33.232
110
0.674242
[ "render" ]
7962d5d33b4abfab7dcaf4f77b59b4528db3fd5b
6,498
hpp
C++
stapl_release/stapl/containers/graph/algorithms/triangle_count.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/containers/graph/algorithms/triangle_count.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/containers/graph/algorithms/triangle_count.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #ifndef STAPL_CONTAINERS_GRAPH_ALGORITHMS_TRIANGLE_COUNT_HPP #define STAPL_CONTAINERS_GRAPH_ALGORITHMS_TRIANGLE_COUNT_HPP #include <stapl/containers/graph/algorithms/execute.hpp> namespace stapl { namespace triangle_count_impl { ////////////////////////////////////////////////////////////////////// /// @brief Functor to add elements of a pair for triangle counting. /// @ingroup pgraphAlgoDetails ////////////////////////////////////////////////////////////////////// struct tc_add_pair { typedef std::pair<size_t, size_t> result_type; template <typename T> result_type operator()(T t1, T t2) const { return std::make_pair(t1.first+t2.first, t1.second+t2.second); } }; ////////////////////////////////////////////////////////////////////// /// @brief Work-function to initialize vertices for triangle counting. /// @ingroup pgraphAlgoDetails ////////////////////////////////////////////////////////////////////// struct triangle_count_init_wf { typedef void result_type; template <typename T> void operator()(T v) const { v.property().num_triangles(0); v.property().num_connected_triplets(0); } }; ////////////////////////////////////////////////////////////////////// /// @brief Work-function to return the number of triangles each vertex /// is a part of, along with the number of connected-tiplets. /// @ingroup pgraphAlgoDetails ////////////////////////////////////////////////////////////////////// struct get_count_and_triplets { typedef std::pair<size_t, size_t> result_type; template <typename T> result_type operator()(T v) const { return std::make_pair(v.property().num_triangles(), v.property().num_connected_triplets()); } }; ////////////////////////////////////////////////////////////////////// /// @brief Functor to compute triangles and connected-triplets and /// store the count on the target vertex. /// @ingroup pgraphAlgoDetails ////////////////////////////////////////////////////////////////////// struct update_func { typedef bool result_type; typedef size_t vd_type; vd_type m_second; std::vector<vd_type> m_thirds; update_func(vd_type const& second = std::numeric_limits<vd_type>::max()) : m_second(second), m_thirds() { } update_func(vd_type const& second, vd_type const& third) : m_second(second), m_thirds(1, third) { } update_func(vd_type const& second, std::vector<vd_type> const& thirds) : m_second(second), m_thirds(thirds) { } template <class Vertex> bool operator()(Vertex&& target) const { if (target.descriptor() <= m_second) return false; if (m_thirds.empty()) //second visit. target.property().waiting_queue_add(m_second); else { // third visit, search for closing edge. size_t num_triangles = target.property().num_triangles(); size_t num_connected_triplets = target.property().num_connected_triplets(); for (auto const& third : m_thirds) { for (auto const& e : target) { ++num_connected_triplets; if (e.target() == third) { ++num_triangles; // break; } } } target.property().num_triangles(num_triangles); target.property().num_connected_triplets(num_connected_triplets); return false; } return true; } void define_type(typer& t) { t.member(m_second); t.member(m_thirds); } }; std::ostream& operator<<(std::ostream& os, update_func const& uf) { const uint32_t phase = uf.m_thirds.empty() ? 2 : 3; os << "phase " << phase << ": " << uf.m_second << " {"; for (auto third : uf.m_thirds) os << third << " "; os << "}"; return os; } ////////////////////////////////////////////////////////////////////// /// @brief Work-function to compute the triangulation of each vertex /// and push it to the vertex's neighbors. /// @ingroup pgraphAlgoDetails ////////////////////////////////////////////////////////////////////// struct triangle_count_wf { typedef bool result_type; template<typename Vertex, typename GraphVisitor> bool operator()(Vertex&& v, GraphVisitor&& graph_visitor) const { if (graph_visitor.level() == 1) { // first visit. graph_visitor.visit_all_edges(v, update_func(v.descriptor())); return true; } else if (!v.property().waiting_queue_empty()) { // second visit. graph_visitor.visit_all_edges(v, update_func(v.descriptor(), v.property().waiting_queue())); v.property().waiting_queue_clear(); return true; } return false; } }; }; // namespace triangle_count_impl; ////////////////////////////////////////////////////////////////////// /// @brief Parallel Triangle Counting and Clustering Coefficient Algorithm. /// /// Counts the number of triangles in the input @ref graph_view, /// storing partial counts on vertices that are part of triangles. /// Also computes the clustering-coefficient of the input @ref graph_view, /// storing counts of connected triplets on vertices. /// Formula: /// C(G) = 3x#triangles / #connected-triplets-of-vertices. /// = #closed-triplets / #connected-triplets-of-vertices. /// /// @param graph The @ref graph_view over the input graph. /// @param k The maximum amount of asynchrony allowed in each phase. /// 0 <= k <= inf. /// k == 0 implies level-synchronous paradigm. /// k >= D implies fully asynchronous paradigm (D is diameter of graph). /// @return pair of the number of triangles detected and the /// clustering-coefficient of the graph. /// @ingroup pgraphAlgo ////////////////////////////////////////////////////////////////////// template<typename GView> std::pair<size_t, double> triangle_count(GView& graph, size_t k=0) { using namespace triangle_count_impl; map_func(triangle_count_init_wf(), graph); kla_paradigm(triangle_count_wf{}, update_func{}, graph, k); auto x = map_reduce(get_count_and_triplets(), tc_add_pair(), graph); return std::make_pair(x.first, double(3.0*x.first) / double(x.second)); } } // namespace stapl #endif
31.697561
79
0.592336
[ "vector" ]
7966ff93b9748e6350113b3131fe638254261da1
5,984
cc
C++
packages/kraken_webview/bridge/iframe_element.cc
ReverseScale/plugins
bda43270a7aa409c89e20e1ca5927b1eec98461a
[ "Apache-2.0" ]
null
null
null
packages/kraken_webview/bridge/iframe_element.cc
ReverseScale/plugins
bda43270a7aa409c89e20e1ca5927b1eec98461a
[ "Apache-2.0" ]
null
null
null
packages/kraken_webview/bridge/iframe_element.cc
ReverseScale/plugins
bda43270a7aa409c89e20e1ca5927b1eec98461a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2020 Alibaba Inc. All rights reserved. * Author: Kraken Team. */ #include "iframe_element.h" namespace kraken::binding::jsc { std::unordered_map<JSContext *, JSIframeElement *> JSIframeElement::instanceMap {}; JSIframeElement::~JSIframeElement() { instanceMap.erase(context); } JSIframeElement::JSIframeElement(JSContext *context) : JSElement(context) {} JSObjectRef JSIframeElement::instanceConstructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef *arguments, JSValueRef *exception) { auto instance = new IframeElementInstance(this); return instance->object; } JSIframeElement::IframeElementInstance::IframeElementInstance(JSIframeElement *jsAnchorElement) : ElementInstance(jsAnchorElement, "iframe", false), nativeIframeElement(new NativeIframeElement(nativeElement)) { std::string tagName = "iframe"; NativeString args_01{}; buildUICommandArgs(tagName, args_01); foundation::UICommandTaskMessageQueue::instance(context->getContextId()) ->registerCommand(eventTargetId, UICommand::createElement, args_01, nativeIframeElement); } JSValueRef JSIframeElement::IframeElementInstance::getProperty(std::string &name, JSValueRef *exception) { auto propertyMap = getIFrameElementPropertyMap(); auto prototypePropertyMap = getIFrameElementPrototypePropertyMap(); JSStringHolder nameStringHolder = JSStringHolder(context, name); if (prototypePropertyMap.count(name) > 0) { return JSObjectGetProperty(ctx, prototype<JSIframeElement>()->prototypeObject, nameStringHolder.getString(), exception); }; if (propertyMap.count(name) > 0) { auto property = propertyMap[name]; switch (property) { case IFrameElementProperty::width: return JSValueMakeNumber(_hostClass->ctx, _width); case IFrameElementProperty::height: return JSValueMakeNumber(_hostClass->ctx, _height); case IFrameElementProperty::contentWindow: // TODO: support contentWindow property. break; } } return ElementInstance::getProperty(name, exception); } bool JSIframeElement::IframeElementInstance::setProperty(std::string &name, JSValueRef value, JSValueRef *exception) { auto propertyMap = getIFrameElementPropertyMap(); auto prototypePropertyMap = getIFrameElementPrototypePropertyMap(); JSStringHolder nameStringHolder = JSStringHolder(context, name); if (prototypePropertyMap.count(name) > 0) { return JSObjectGetProperty(ctx, prototype<JSIframeElement>()->prototypeObject, nameStringHolder.getString(), exception); } if (propertyMap.count(name) > 0) { auto property = propertyMap[name]; switch (property) { case IFrameElementProperty::width: { _width = JSValueToNumber(_hostClass->ctx, value, exception); std::string widthString = std::to_string(_width); NativeString args_01{}; NativeString args_02{}; buildUICommandArgs(name, widthString, args_01, args_02); foundation::UICommandTaskMessageQueue::instance(_hostClass->contextId) ->registerCommand(eventTargetId, UICommand::setProperty, args_01, args_02, nullptr); break; } case IFrameElementProperty::height: { _height = JSValueToNumber(_hostClass->ctx, value, exception); std::string heightString = std::to_string(_height); NativeString args_01{}; NativeString args_02{}; buildUICommandArgs(name, heightString, args_01, args_02); foundation::UICommandTaskMessageQueue::instance(_hostClass->contextId) ->registerCommand(eventTargetId, UICommand::setProperty, args_01, args_02, nullptr); break; } default: break; } return true; } else { return ElementInstance::setProperty(name, value, exception); } } void JSIframeElement::IframeElementInstance::getPropertyNames(JSPropertyNameAccumulatorRef accumulator) { ElementInstance::getPropertyNames(accumulator); for (auto &property : getIFrameElementPropertyNames()) { JSPropertyNameAccumulatorAddName(accumulator, property); } for (auto &property : getIFrameElementPrototypePropertyNames()) { JSPropertyNameAccumulatorAddName(accumulator, property); } } JSIframeElement::IframeElementInstance::~IframeElementInstance() { ::foundation::UICommandCallbackQueue::instance()->registerCallback([](void *ptr) { delete reinterpret_cast<NativeIframeElement *>(ptr); }, nativeIframeElement); } JSValueRef JSIframeElement::postMessage(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef *arguments, JSValueRef *exception) { if (argumentCount < 1) { throwJSError(ctx, "Failed to execute 'postMessage' on 'IframeElement: 1 arguments required.'", exception); return nullptr; } if (!JSValueIsString(ctx, arguments[0])) { throwJSError(ctx, "Failed to execute 'postMessage' on 'IframeElement: first arguments should be string'", exception); return nullptr; } JSStringRef messageStringRef = JSValueToStringCopy(ctx, arguments[0], exception); NativeString message{}; message.string = JSStringGetCharactersPtr(messageStringRef); message.length = JSStringGetLength(messageStringRef); auto instance = reinterpret_cast<JSIframeElement::IframeElementInstance *>(JSObjectGetPrivate(thisObject)); assert_m(instance->nativeIframeElement->postMessage != nullptr, "Failed to execute postMessage(): dart method is nullptr."); instance->nativeIframeElement->postMessage(instance->nativeIframeElement, &message); return nullptr; } } // namespace kraken::binding::jsc void initBridge() { using namespace kraken::binding::jsc; JSElement::defineElement("iframe", [](JSContext *context) -> ElementInstance * { return new JSIframeElement::IframeElementInstance(JSIframeElement::instance(context)); }); }
38.606452
126
0.732286
[ "object" ]
796afd33d4edc2f11fd513c6e42c8c69898c962a
953
cpp
C++
1457. Pseudo-Palindromic Paths in a Binary Tree/main.cpp
amanchadha/LeetCode
20dddf0616351ad399f0fa03cb6a2b5cbdd25279
[ "MIT" ]
1
2021-07-18T06:18:40.000Z
2021-07-18T06:18:40.000Z
1457. Pseudo-Palindromic Paths in a Binary Tree/main.cpp
amanchadha/LeetCode
20dddf0616351ad399f0fa03cb6a2b5cbdd25279
[ "MIT" ]
null
null
null
1457. Pseudo-Palindromic Paths in a Binary Tree/main.cpp
amanchadha/LeetCode
20dddf0616351ad399f0fa03cb6a2b5cbdd25279
[ "MIT" ]
3
2020-09-27T05:48:30.000Z
2021-08-13T10:07:08.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { vector<int> count; int res = 0; bool check(){ int o = 0; for(int i=1; i<= 9; i++){ if(count[i] % 2 == 1) o++; } return o <= 1; } void inOrder(TreeNode* root){ if(!root) return; count[root->val]++; inOrder(root->left); inOrder(root->right); if(!root->left && !root->right && check()) res++; count[root->val]--; } public: int pseudoPalindromicPaths (TreeNode* root) { count.assign(10, 0); inOrder(root); return res; } };
25.078947
93
0.501574
[ "vector" ]
796d2acedb88c2cb74ddaa1934fd974e65fa9943
1,228
hpp
C++
include/zeabus/opencv/operations.hpp
zeabusTeam/zeabus_vision
bc58872ae4f02656bc153f32968e61a8f3d7cf15
[ "MIT" ]
1
2019-05-28T12:59:21.000Z
2019-05-28T12:59:21.000Z
include/zeabus/opencv/operations.hpp
zeabusTeam/zeabus_vision
bc58872ae4f02656bc153f32968e61a8f3d7cf15
[ "MIT" ]
2
2019-04-30T11:35:10.000Z
2019-10-22T10:00:18.000Z
include/zeabus/opencv/operations.hpp
zeabusTeam/zeabus_vision
bc58872ae4f02656bc153f32968e61a8f3d7cf15
[ "MIT" ]
null
null
null
// FILE : operations.hpp // AUTHOR : K.Supasan // CREATE ON : 2020, Febuary 27 (UTC+0) // MAINTAINER : K.Supasan // MACRO DETAIL // README // REFERENCE // This implement on vector of cpp // MACRO SET // MACRO CONDITION #include <cmath> #include <opencv2/core/types.hpp> #ifndef _ZEABUS_OPENCV_OPERATIONS_HPP__ #define _ZEABUS_OPENCV_OPERATIONS_HPP__ namespace zeabus_opencv { namespace operations { template< typename type_sorce , typename _Tp > void pull_center( const std::vector< type_sorce >& source , std::vector< cv::Point_< _Tp > >* ptr_dest ) { ptr_dest->clear(); for( auto it = source.cbegin() ; it != source.cend() ; it++ ) { ptr_dest->push_back( it->center ); } } template< typename _Tp > inline double size( const cv::Point_< _Tp >& point ) { return sqrt( pow( point.x , 2 ) + pow( point.y , 2 ) ); } template< typename _Tp > inline double ratio( const cv::Size_< _Tp >& size ) { double answer = size.width / size.height; if( answer > 1 ) answer = 1.0 / answer; return answer; } } // zeabus_opencv } // operations #endif //_ZEABUS_OPENCV_OPERATIONS_HPP__
20.466667
69
0.610749
[ "vector" ]
7971be9fe6e58cdfda2ded03a7dfbe13f4ca110b
2,958
cpp
C++
src/ttauri/GFX/RenderDoc.cpp
RustWorks/ttauri
4b093eb16465091d01d80159e23fd26e5d4e4c03
[ "BSL-1.0" ]
279
2021-02-17T09:53:40.000Z
2022-03-22T04:08:40.000Z
src/ttauri/GFX/RenderDoc.cpp
RustWorks/ttauri
4b093eb16465091d01d80159e23fd26e5d4e4c03
[ "BSL-1.0" ]
269
2021-02-17T12:53:15.000Z
2022-03-29T22:10:49.000Z
src/ttauri/GFX/RenderDoc.cpp
RustWorks/ttauri
4b093eb16465091d01d80159e23fd26e5d4e4c03
[ "BSL-1.0" ]
25
2021-02-17T17:14:10.000Z
2022-03-16T04:13:00.000Z
// Copyright Take Vos 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #include "RenderDoc.hpp" #include "../log.hpp" #include "../URL.hpp" #include <renderdoc/renderdoc_app.h> #if TT_OPERATING_SYSTEM == TT_OS_WINDOWS #include <Windows.h> #endif #include <type_traits> namespace tt::inline v1 { RenderDoc::RenderDoc() noexcept { #if TT_BUILD_TYPE == TT_BT_DEBUG #if TT_OPERATING_SYSTEM == TT_OS_WINDOWS ttlet dll_urls = std::vector{ URL{"file:renderdoc.dll"}, URL{"file:///C:/Program%20Files/RenderDoc/renderdoc.dll"}, URL{"file:///C:/Program%20Files%20(x86)/RenderDoc/renderdoc.dll"}}; HMODULE mod = nullptr; for (ttlet &dll_url : dll_urls) { tt_log_debug("Trying to load renderdoc.dll at: {}", dll_url.nativePath()); if ((mod = LoadLibraryW(dll_url.nativeWPath().c_str()))) { goto found_dll; } } tt_log_warning("Could not load renderdoc.dll"); return; found_dll: pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)GetProcAddress(mod, "RENDERDOC_GetAPI"); if (RENDERDOC_GetAPI == nullptr) { tt_log_error("Could not find RENDERDOC_GetAPI in renderdoc.dll"); return; } int ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_4_1, &api); if (ret != 1) { tt_log_error("RENDERDOC_GetAPI returns invalid value {}", ret); api = nullptr; } // At init, on linux/android. // For android replace librenderdoc.so with libVkLayer_GLES_RenderDoc.so // if(void *mod = dlopen("librenderdoc.so", RTLD_NOW | RTLD_NOLOAD)) //{ // pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)dlsym(mod, "RENDERDOC_GetAPI"); // int ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_1_2, (void **)&rdoc_api); // assert(ret == 1); //} set_overlay(false, false, false); #endif #endif } void RenderDoc::set_overlay(bool frameRate, bool frameNumber, bool captureList) noexcept { if (!api) { return; } uint32_t or_mask = eRENDERDOC_Overlay_None; uint32_t and_mask = eRENDERDOC_Overlay_None; if (frameRate || frameNumber || captureList) { or_mask |= eRENDERDOC_Overlay_Enabled; } else { and_mask |= eRENDERDOC_Overlay_Enabled; } if (frameRate) { or_mask |= eRENDERDOC_Overlay_FrameRate; } else { and_mask |= eRENDERDOC_Overlay_FrameRate; } if (frameNumber) { or_mask |= eRENDERDOC_Overlay_FrameNumber; } else { and_mask |= eRENDERDOC_Overlay_FrameNumber; } if (captureList) { or_mask |= eRENDERDOC_Overlay_CaptureList; } else { and_mask |= eRENDERDOC_Overlay_CaptureList; } auto *api_ = reinterpret_cast<RENDERDOC_API_1_4_1 *>(api); and_mask = ~and_mask; api_->MaskOverlayBits(and_mask, or_mask); } } // namespace tt::inline v1
28.442308
100
0.667681
[ "vector" ]
797542ffba234f19154e1917e50ac5ebf76816b6
33,695
cpp
C++
frameworks/src/core/modules/presets/test/unittest/common/timer_module_tdd_test.cpp
openharmony-gitee-mirror/ace_engine_lite
94ec4d9667f586888090342f231ae3c9294df621
[ "Apache-2.0" ]
null
null
null
frameworks/src/core/modules/presets/test/unittest/common/timer_module_tdd_test.cpp
openharmony-gitee-mirror/ace_engine_lite
94ec4d9667f586888090342f231ae3c9294df621
[ "Apache-2.0" ]
null
null
null
frameworks/src/core/modules/presets/test/unittest/common/timer_module_tdd_test.cpp
openharmony-gitee-mirror/ace_engine_lite
94ec4d9667f586888090342f231ae3c9294df621
[ "Apache-2.0" ]
1
2021-09-13T11:57:16.000Z
2021-09-13T11:57:16.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "timer_module_tdd_test.h" #include "js_fwk_common.h" namespace OHOS { namespace ACELite { const char SET_TIMEOUT_001[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('stack', {staticClass: ['stack']}, [\n" " _c('input', {'attrs': {'type': 'button','value': 'startTimer'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left': '30%','top': '25%'},\n" " 'onBubbleEvents' : {'click' : _vm.startTimer}}),\n" " _c('text', {'attrs' : {'value' : function () {return _vm.value}},\n" " 'staticClass' : ['text']})\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " stack: {\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " left: 0,\n" " right: 0,\n" " height: '100%',\n" " width: '100%'\n" " },\n" " button: {\n" " width:'25%',\n" " height:'20%',\n" " },\n" " text: {\n" " width:'50%',\n" " fontSize:38,\n" " textAlign: 'center',\n" " left:'20%',\n" " top: '50%',\n" " }\n" " }\n" " },\n" " data: {\n" " value: 'timer'\n" " },\n" " startTimer: function() {\n" " var _this = this;\n" " setTimeout(function() {\n" " _this.value = 'once_timer_success';\n" " }, 100);\n" " }\n" " });\n" "})();\n"; const char INTERVAL_TEST_002[] = "(function () {\n" "var index = 0;\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('stack', {staticClass: ['stack']}, [\n" " _c('input', {'attrs': {'type': 'button','value': 'startTimer'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left': '25%','top': '20%'},\n" " 'onBubbleEvents' : {'click' : _vm.startTimer}}),\n" " _c('text', {'attrs' : {'value' : function () {return _vm.value}},\n" " 'staticClass' : ['text']})\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " stack: {\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " left: 0,\n" " right: 0,\n" " height: '100%',\n" " width: '100%'\n" " },\n" " button: {\n" " width:'25%',\n" " height:'20%',\n" " },\n" " text: {\n" " width:'50%',\n" " fontSize:38,\n" " textAlign: 'center',\n" " left:'20%',\n" " top: '50%',\n" " }\n" " }\n" " },\n" " data: {\n" " value: 'timer'\n" " },\n" " startTimer: function() {\n" " var _this = this;\n" " var id = setInterval(function() {" " if (index >5) {\n" " _this.value = 'clearInterval';\n" " clearInterval(id);\n" " }\n" " index++;\n" " _this.value = index;\n" " }, 100);\n" " }\n" " });\n" "})();\n"; const char INTERVAL_TEST_003[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('stack', {staticClass: ['stack']}, [\n" " _c('input', {'attrs': {'type': 'button','value': 'startTimer'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left': '25%','top': '20%'},\n" " 'onBubbleEvents' : {'click' : _vm.startTimer}}),\n" " _c('text', {'attrs' : {'value' : function () {return _vm.value}},\n" " 'staticClass' : ['text']})\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " stack: {\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " left: 0,\n" " right: 0,\n" " height: '100%',\n" " width: '100%'\n" " },\n" " button: {\n" " width:'25%',\n" " height:'20%',\n" " },\n" " text: {\n" " width:'50%',\n" " fontSize:38,\n" " textAlign: 'center',\n" " left:'20%',\n" " top: '50%',\n" " }\n" " }\n" " },\n" " data: {\n" " value: 'timer'\n" " },\n" " startTimer: function() {\n" " var _this = this;\n" " var id = setInterval(function() {\n" " clearTimeout(id);\n" " _this.value = 'clearSuccess';\n" " }, 200);\n" " }\n" " });\n" "})();\n"; const char TIME_OUT_004[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('stack', {staticClass: ['stack']}, [\n" " _c('input', {'attrs': {type: 'button',value: 'triggerONo'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left': '5%','top': '10%'},\n" " 'onBubbleEvents' : {'click' : _vm.triggerNo}\n" " }),\n" " _c('input', {'attrs': {'type':'button', value:'One Arg'},\n" " 'staticClass':['button'],\n" " 'staticStyle':{'left':'35%', 'top':'10%'},\n" " 'onBubbleEvents':{'click':_vm.triggerOne}\n" " }),\n" " _c('input', {'attrs':{'type':'button', value:'Two Arg'},\n" " 'staticClass':['button'],\n" " 'staticStyle': {'left':'65%', 'top':'10%'},\n" " 'onBubbleEvents':{'click':_vm.triggerTwo}\n" " }),\n" " _c('text', {'attrs' : {'value' : function () {return _vm.value}},\n" " 'staticClass' : ['text']\n" " })\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " stack: {\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " left: 0,\n" " right: 0,\n" " height: '100%',\n" " width: '100%'\n" " },\n" " button: {\n" " width:'25%',\n" " height:'20%',\n" " },\n" " text: {\n" " width:'50%',\n" " fontSize:38,\n" " textAlign: 'center',\n" " left:'20%',\n" " top: '50%',\n" " }\n" " }\n" " },\n" " data: {\n" " value: 'timer'\n" " },\n" " triggerOne: function() {\n" " var _this = this;\n" " var id = setTimeout(function(a) {\n" " _this.value = a;\n" " }, 200, 'One Arg');\n" " },\n" " triggerNo: function(a) {\n" " var _this = this;\n" " setTimeout(function() {\n" " _this.value = a;\n" " }, 200);\n" " },\n" " triggerTwo: function(a) {\n" " var _this = this;" " setTimeout(function(a) {\n" " _this.value = a;\n" " }, 200, 'Two Arg', 'One Arg');\n" " }\n" " });\n" "})();\n"; const char ARG_TEST_005[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('stack', {staticClass: ['stack']}, [\n" " _c('input', {'attrs': {type: 'button',value: 'triggerNo'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left': '5%','top': '10%'},\n" " 'onBubbleEvents' : {'click' : _vm.triggerNo}\n" " }),\n" " _c('input', {'attrs': {'type':'button', value:'One Arg'},\n" " 'staticClass':['button'],\n" " 'staticStyle':{'left':'35%', 'top':'10%'},\n" " 'onBubbleEvents':{'click':_vm.triggerOne}\n" " }),\n" " _c('input', {'attrs':{'type':'button', value:'Two Arg'},\n" " 'staticClass':['button'],\n" " 'staticStyle': {'left':'65%', 'top':'10%'},\n" " 'onBubbleEvents':{'click':_vm.triggerTwo}\n" " }),\n" " _c('text', {'attrs' : {'value' : function () {return _vm.value}},\n" " 'staticClass' : ['text']\n" " })\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " stack: {\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " left: 0,\n" " right: 0,\n" " height: '100%',\n" " width: '100%'\n" " },\n" " button: {\n" " width:'25%',\n" " height:'20%',\n" " },\n" " text: {\n" " width:'50%',\n" " fontSize:38,\n" " textAlign: 'center',\n" " left:'20%',\n" " top: '50%',\n" " }\n" " }\n" " },\n" " data: {\n" " value: 'timer'\n" " },\n" " triggerOne: function() {\n" " var _this = this;\n" " var id = setInterval(function(a) {\n" " _this.value = a;\n" " clearInterval(id);\n" " }, 200, 'Interval One');\n" " },\n" " triggerNo: function(a) {\n" " var _this = this;\n" " var id = setInterval(function(a) {\n" " _this.value = a;\n" " clearInterval(id);\n" " }, 200);\n" " },\n" " triggerTwo: function(a) {\n" " var _this = this;\n" " var id = setInterval(function(a) {\n" " _this.value = a;\n" " clearInterval(id);\n" " }, 200, 'Interval Two', 'Interval One');\n" " }\n" " });\n" "})();\n"; const char CLEAR_TIME_OUT_006[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('stack', {staticClass: ['stack']}, [\n" " _c('input', {'attrs': {'type': 'button','value': 'setTimeout'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left': '25%','top': '20%'},\n" " 'onBubbleEvents' : {'click' : _vm.checkSetTimeout}}),\n" " _c('text', {'attrs' : {'value' : function () {return _vm.value}},\n" " 'staticClass' : ['text']})\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " stack: {\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " left: 0,\n" " right: 0,\n" " height: '100%',\n" " width: '100%'\n" " },\n" " button: {\n" " width:'25%',\n" " height:'20%',\n" " },\n" " text: {\n" " width:'50%',\n" " fontSize:38,\n" " textAlign: 'center',\n" " left:'20%',\n" " top: '50%',\n" " }\n" " }\n" " },\n" " data: {\n" " value: 'timer'\n" " },\n" " checkSetTimeout: function() {\n" " var _this = this;\n" " var id = setTimeout(function() {\n" " _this.value = 'trigger start';\n" " clearTimeout(id);\n" " _this.value = 'trigger success';\n" " }, 200);\n" " }\n" " });\n" "})();\n"; const char INTERVAL_TEST_007[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('stack', {staticClass: ['stack']}, [\n" " _c('input', {'attrs': {'type': 'button','value': 'setInterval'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left': '25%','top': '20%'},\n" " 'onBubbleEvents' : {'click' : _vm.checkSetInterval}}),\n" " _c('text', {'attrs' : {'value' : function () {return _vm.value}},\n" " 'staticClass' : ['text']})\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " stack: {\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " left: 0,\n" " right: 0,\n" " height: '100%',\n" " width: '100%'\n" " },\n" " button: {\n" " width:'25%',\n" " height:'20%',\n" " },\n" " text: {\n" " width:'50%',\n" " fontSize:38,\n" " textAlign: 'center',\n" " left:'20%',\n" " top: '50%',\n" " }\n" " }\n" " },\n" " data: {\n" " value: 'timer'\n" " },\n" " checkSetInterval: function() {\n" " var _this = this;\n" " var id = setInterval(function() {" " _this.value = 'trigger interval start';\n" " clearInterval(id);\n" " _this.value = 'trigger interval success';\n" " }, 200);\n" " }\n" " });\n" "})();\n"; const char CLEAR_TIME_OUT_008[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('stack', {staticClass: ['stack']}, [\n" " _c('input', {'attrs': {'type': 'button','value': 'clearInterval'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left': '30%','top': '15%'},\n" " 'onBubbleEvents' : {'click' : _vm.testClearInterval}}),\n" " _c('input', {'attrs':{'type':'button', value:'clearTimeout'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left':'30%', 'top':'45%'},\n" " 'onBubbleEvents': {'click': _vm.testClearTimeout}}),\n" " _c('text', {'attrs' : {'value' : function () {return _vm.value}},\n" " 'staticClass' : ['text']})\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " stack: {\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " left: 0,\n" " right: 0,\n" " height: '100%',\n" " width: '100%'\n" " },\n" " button: {\n" " width:'40%',\n" " height:'20%',\n" " },\n" " text: {\n" " width:'50%',\n" " fontSize:38,\n" " textAlign: 'center',\n" " left:'20%',\n" " top: '70%',\n" " }\n" " }\n" " },\n" " data: {\n" " value: 'timer'\n" " },\n" " testClearInterval: function() {\n" " clearInterval(1);\n" " console.log('testClearInterval');\n" " this.value = 'clearInterval';\n" " },\n" " testClearTimeout: function() {\n" " clearTimeout(1);\n" " console.log('clearSuccess');\n" " this.value = 'clearSuccess';\n" " }" " });\n" "})();\n"; const char BUNDLE_09[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('stack', {staticClass: ['stack']}, [\n" " _c('input', {'attrs': {'type': 'button','value': 'minTime'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left': '30%','top': '15%'},\n" " 'onBubbleEvents' : {'click' : _vm.testMinTime}}),\n" " _c('input', {'attrs':{'type':'button', value:'maxTime'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left':'60%', 'top':'15%'},\n" " 'onBubbleEvents': {'click': _vm.testMaxTime}}),\n" " _c('input', {'attrs':{'type':'button', value:'minInterval'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left':'30%', 'top':'40%'},\n" " 'onBubbleEvents': {'click': _vm.testMinInterval}}),\n" " _c('input', {'attrs':{'type':'button', value:'maxInterval'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left':'60%', 'top':'40%'},\n" " 'onBubbleEvents': {'click': _vm.testMaxInterval}}),\n" " _c('text', {'attrs' : {'value' : function () {return _vm.value}},\n" " 'staticClass' : ['text']})\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " stack: {\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " left: 0,\n" " right: 0,\n" " height: '100%',\n" " width: '100%'\n" " },\n" " button: {\n" " width:'25%',\n" " height:'20%',\n" " },\n" " text: {\n" " width:'50%',\n" " fontSize:38,\n" " textAlign: 'center',\n" " left:'20%',\n" " top: '50%',\n" " }\n" " }\n" " },\n" " data: {\n" " value: 'timer'\n" " },\n" " testMinTime: function() {\n" " var _this = this;" " setTimeout(function() {\n" " _this.value = 'min';" " }, -2);\n" " },\n" " testMaxTime: function() {\n" " var _this = this;\n" " setTimeout(function() {\n" " _this.value = 'max';\n" " }, 4294967297);" " }," " testMinInterval: function() {\n" " var _this = this;\n" " var id = setInterval(function() {\n" " _this.value = 'min';\n" " clearInterval(id);\n" " }, -1);\n" " },\n" " testMaxInterval: function() {\n" " var _this = this;\n" " var id = setInterval(function() {\n" " _this.value = 'max';\n" " clearInterval(id);\n" " }, 4294967295);\n" " }\n" " });\n" "})();\n"; const char BUNDLE_10[] = "(function () {\n" " return new ViewModel({\n" " render: function (vm) {\n" " var _vm = vm || this;\n" " return _c('stack', {staticClass: ['stack']}, [\n" " _c('input', {'attrs': {'type': 'button','value': 'maxTimer'},\n" " 'staticClass': ['button'],\n" " 'staticStyle': {'left': '30%','top': '25%'},\n" " 'onBubbleEvents' : {'click' : _vm.startMaxTimer}}),\n" " _c('text', {'attrs' : {'value' : function () {return _vm.value}},\n" " 'staticClass' : ['text']})\n" " ]);\n" " },\n" " styleSheet: {\n" " classSelectors: {\n" " stack: {\n" " justifyContent: 'center',\n" " alignItems: 'center',\n" " left: 0,\n" " right: 0,\n" " height: '100%',\n" " width: '100%'\n" " },\n" " button: {\n" " width:'25%',\n" " height:'20%',\n" " },\n" " text: {\n" " width:'50%',\n" " fontSize:38,\n" " textAlign: 'center',\n" " left:'20%',\n" " top: '50%',\n" " }\n" " }\n" " },\n" " data: {\n" " value: 'timer'\n" " },\n" " startMaxTimer: function() {\n" " var _this = this;\n" " setTimeout(function() {\n" " _this.value = 'timer1';\n" " }, 100);\n" " setTimeout(function() {\n" " _this.value = 'timer2';\n" " }, 200);\n" " setTimeout(function() {\n" " _this.value = 'timer3';\n" " }, 300);\n" " setTimeout(function() {\n" " _this.value = 'timer4';\n" " }, 400);\n" " }\n" " });\n" "})();\n"; char *TimerModuleTddTest::TriggerTimer(const double xRate, const double yRate, const uint8_t sleepSeconds, const JSValue page) const { const uint8_t offset = 50; const uint16_t centerX = GetHorizontalResolution() * xRate + offset; const uint16_t centerY = GetVerticalResolution() * yRate + offset; Click(centerX, centerY); sleep(sleepSeconds); if (!JSObject::Has(page, "value")) { return nullptr; } JSValue value = JSObject::Get(page, "value"); char *content = nullptr; if (!JSUndefined::Is(value)) { content = JSObject::GetString(page, "value"); } JSRelease(value); return content; } /** * @tc.name: SetTimeoutTest001 * @tc.desc: test setTimeout * @tc.require: AR000DT315 */ HWTEST_F(TimerModuleTddTest, SetTimeoutTest001, TestSize.Level1) { TDD_CASE_BEGIN(); /** * @tc.steps:step1.read js file, setTimeout_test001.js, and eval the js page * @tc.expected: step1. the js file eval success */ JSValue page = CreatePage(SET_TIMEOUT_001, strlen(SET_TIMEOUT_001)); EXPECT_FALSE(JSUndefined::Is(page)); /** * @tc.steps:step2.click startTimer button to trigger timer event and sleep 400 ms * @tc.expected: step2.the value of data is once_timer_success */ const double xrate = 0.25; const double yrate = 0.2; const uint8_t sleepTime = 1; char *content = TriggerTimer(xrate, yrate, sleepTime, page); EXPECT_TRUE((content != nullptr) && (!strcmp(content, "once_timer_success"))); ACE_FREE(content); DestroyPage(page); TDD_CASE_END(); } /** * @tc.name: SetIntervalTest001 * @tc.desc: test set interval * @tc.require: AR000DT315 */ HWTEST_F(TimerModuleTddTest, SetIntervalTest002, TestSize.Level0) { TDD_CASE_BEGIN(); /* * @tc.steps:step1.eval js file setInterval_test002.js * @tc.expected:step1.eval js file success */ JSValue page = CreatePage(INTERVAL_TEST_002, strlen(INTERVAL_TEST_002)); EXPECT_FALSE(JSUndefined::Is(page)); /** * @tc.steps:step2.click startTimer button to trigger timer event and sleep 400 ms * @tc.expected: step2.the value of data is interval_timer_success */ const double xRate = 0.25; const double yRate = 0.2; const uint8_t sleepTime = 2; char *content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_TRUE((content != nullptr) && (!strcmp(content, "7"))); ACE_FREE(content); DestroyPage(page); TDD_CASE_END(); } /** * @tc.name: SetTimeoutTest003 * @tc.desc: test clearTimeout * @tc.require: AR000DT315 */ HWTEST_F(TimerModuleTddTest, SetTimeoutTest003, TestSize.Level0) { TDD_CASE_BEGIN(); /** * @tc.steps: step1.eval js file setTimeout_test003.js * @tc.expected:step1.eval js file success */ JSValue page = CreatePage(INTERVAL_TEST_003, strlen(INTERVAL_TEST_003)); EXPECT_FALSE(JSUndefined::Is(page)); /** * @tc.steps:step2.click startTimer button and sleep 400 ms * @tc.expected: step2.the value of data is cleaSuccess */ const double xrate = 0.25; const double yrate = 0.2; const uint8_t sleepTime = 1; char *content = TriggerTimer(xrate, yrate, sleepTime, page); EXPECT_TRUE((content != nullptr) && (!strcmp(content, "clearSuccess"))); ACE_FREE(content); DestroyPage(page); TDD_CASE_END(); } /** * @tc.name: SetTimeoutTest004 * @tc.desc: test setTimeout args * @tc.require: AR000DT315 */ HWTEST_F(TimerModuleTddTest, SetTimeoutTest004, TestSize.Level1) { TDD_CASE_BEGIN(); /** * @tc.steps:step1.eval js file setTimeout_test004.js * @tc.expected:step1.eval js file success */ JSValue page = CreatePage(TIME_OUT_004, strlen(TIME_OUT_004)); EXPECT_FALSE(JSUndefined::Is(page)); /** * @tc.steps:step2.click the noArg button * @tc.expected:step2.the value attribute is timer */ double xRate = 0.05; const double yRate = 0.1; const uint8_t sleepTime = 1; char *content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_FALSE(content == nullptr); /** * @tc.steps:step3.click the oneArg button * @tc.expected:step3.the value attribute is One Arg */ xRate = 0.35; content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_TRUE((content != nullptr) && (!strcmp(content, "One Arg"))); ACE_FREE(content); /** * @tc.steps:step3.click two args button * @tc.steps:step3.the value attribute is Two Arg */ xRate = 0.65; content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_TRUE((content != nullptr) && (!strcmp(content, "Two Arg"))); ACE_FREE(content); DestroyPage(page); TDD_CASE_END(); } /** * @tc.name: SetIntervalTest005 * @tc.desc: test setInterval args * @tc.require: AR000DT315 */ HWTEST_F(TimerModuleTddTest, SetIntervalTest005, TestSize.Level1) { TDD_CASE_BEGIN(); /** * @tc.steps:step1.eval js file setInterval_test005.js * @tc.expected:step1.eval js file success */ JSValue page = CreatePage(ARG_TEST_005, strlen(ARG_TEST_005)); EXPECT_FALSE(JSUndefined::Is(page)); /** * @tc.steps:step2.click the noArg button * @tc.expected:step2.the value attribute is timer */ double xRate = 0.05; const double yRate = 0.1; const uint8_t sleepTime = 1; char *content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_TRUE(content == nullptr); /** * @tc.steps:step3.click the oneArg button * @tc.expected:step3.the value attribute is One Arg */ xRate = 0.35; content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_TRUE((content != nullptr) && (!strcmp(content, "Interval One"))); ACE_FREE(content); /** * @tc.steps:step3.click two args button * @tc.steps:step3.the value attribute is Two Arg */ xRate = 0.65; content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_TRUE((content != nullptr) && (!strcmp(content, "Interval Two"))); ACE_FREE(content); DestroyPage(page); TDD_CASE_END(); } /** * @tc.name: SetTimeoutTest006 * @tc.desc: test setTimeout and clearTimeout api * @tc.require: AR000DT315 */ HWTEST_F(TimerModuleTddTest, SetTimeoutTest006, TestSize.Level1) { TDD_CASE_BEGIN(); /** * @tc.steps:step1.eval js file setTimeout_test006.js * @tc.expected:step1.eval js file success */ JSValue page = CreatePage(CLEAR_TIME_OUT_006, strlen(CLEAR_TIME_OUT_006)); EXPECT_FALSE(JSUndefined::Is(page)); /** * @tc.steps:step2.click setTimeout button * @tc.expected:step2.the value attribute in data is trigger success */ const double xRate = 0.25; const double yRate = 0.2; const uint8_t sleepTime = 1; char *content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_FALSE((content == nullptr) || (strcmp(content, "trigger success"))); ACE_FREE(content); DestroyPage(page); TDD_CASE_END(); } /** * @tc.name: SetIntervalTest007 * @tc.desc: test setInterval and clearInterval api * @tc.require: AR000DT315 */ HWTEST_F(TimerModuleTddTest, SetIntervalTest007, TestSize.Level1) { TDD_CASE_BEGIN(); /** * @tc.steps:step1.eval js file setInterval_test007.js * @tc.expected:step1.eval js file success */ JSValue page = CreatePage(INTERVAL_TEST_007, strlen(INTERVAL_TEST_007)); EXPECT_FALSE(JSUndefined::Is(page)); /** * @tc.steps:step2.click setTimeout button * @tc.expected:step2.the value attribute in data is trigger interval success */ const double xRate = 0.25; const double yRate = 0.2; const uint8_t sleepTime = 1; char *content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_FALSE((content == nullptr) || (strcmp(content, "trigger interval success"))); ACE_FREE(content); DestroyPage(page); TDD_CASE_END(); } /** * @tc.name: ClearTimeoutTest008 * @tc.desc: test delete not exists timer * @tc.require: AR000DT315 */ HWTEST_F(TimerModuleTddTest, ClearTimeoutTest008, TestSize.Level1) { TDD_CASE_BEGIN(); /** * @tc.steps:step1.eval js page clearInterval_test008.js * @tc.expected:step1.eval js page success */ JSValue page = CreatePage(CLEAR_TIME_OUT_008, strlen(CLEAR_TIME_OUT_008)); EXPECT_FALSE(JSUndefined::Is(page)); /** * @tc.steps:step2.click the clearInterval button to clear not exist timer * @tc.expected:step2.the value attribute in data is clearSuccess */ const double xRate = 0.3; double yRate = 0.15; const uint8_t sleepTime = 1; char *content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_FALSE((content == nullptr) || (strcmp(content, "clearInterval"))); ACE_FREE(content); /** * @tc.steps:step2.click the clearTimeout button to clear not exist timer * @tc.expected: the value attribute in data is clearSuccess */ yRate = 0.45; content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_FALSE((content == nullptr) || (strcmp(content, "clearSuccess"))); ACE_FREE(content); DestroyPage(page); TDD_CASE_END(); } /** * @tc.name: ClearIntervalTest009 * @tc.desc: check boundary value in setTimeout and setInterval * @tc.require: AR000DT315 */ HWTEST_F(TimerModuleTddTest, ClearIntervalTest009, TestSize.Level1) { TDD_CASE_BEGIN(); /** * @tc.steps:step1.eval js page clearInterval_test009.js * @tc.expected:step1.eval js page success */ JSValue page = CreatePage(BUNDLE_09, strlen(BUNDLE_09)); EXPECT_FALSE(JSUndefined::Is(page)); /** * @tc.steps:step2.click minTime button and trigger timer * @tc.expected:step2.the value attribute in data is min */ double xRate = 0.3; double yRate = 0.15; const uint8_t sleepTime = 1; char *content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_FALSE((content == nullptr) || (strcmp(content, "min"))); ACE_FREE(content); /** * @tc.steps:step3.click maxTime button and trigger timer * @tc.expected:step3.the value attribute in data is max */ xRate = 0.6; content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_FALSE((content == nullptr) || (strcmp(content, "max"))); ACE_FREE(content); /** * @tc.steps:step4.click the minInterval button to trigger interval timer * @tc.expected:step4.the value attribue in data is min */ xRate = 0.3; yRate = 0.4; content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_FALSE((content == nullptr) || (strcmp(content, "min"))); ACE_FREE(content); /** * @tc.steps:step5.click the maxInterval button to trigger interval timer * @tc.expected:step5.the value attribute in data is max */ xRate = 0.6; content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_FALSE((content == nullptr) || (strcmp(content, "max"))); ACE_FREE(content); DestroyPage(page); TDD_CASE_END(); } /** * @tc.name: ClearIntervalTest009 * @tc.desc: test the timer limit * @tc.require: AR000DT315 */ HWTEST_F(TimerModuleTddTest, TimerLimitTest010, TestSize.Level0) { TDD_CASE_BEGIN(); /** * @tc.steps:step1.eval js file timerLimit_test010.js * @tc.expected:step1.eval js file success */ JSValue page = CreatePage(BUNDLE_10, strlen(BUNDLE_10)); EXPECT_FALSE(JSUndefined::Is(page)); /** * @tc.steps:step2.click timer button and trigger timer * @tc.expected:step2.the value attribute in data is timer4 */ const double xRate = 0.3; const double yRate = 0.25; const uint8_t sleepTime = 1; char *content = TriggerTimer(xRate, yRate, sleepTime, page); EXPECT_FALSE((content == nullptr) || (strcmp(content, "timer4"))); ACE_FREE(content); DestroyPage(page); TDD_CASE_END(); } #ifndef TDD_ASSERTIONS void TimerModuleTddTest::RunTests() { SetTimeoutTest001(); SetIntervalTest002(); SetTimeoutTest003(); SetTimeoutTest004(); SetIntervalTest005(); SetTimeoutTest006(); SetIntervalTest007(); ClearTimeoutTest008(); ClearIntervalTest009(); TimerLimitTest010(); } #endif } }
32.681862
88
0.481407
[ "render" ]
79802650974027deb409dd8028a54d8ca2071413
1,712
cxx
C++
src/Cxx/PolyData/Outline.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
81
2020-08-10T01:44:30.000Z
2022-03-23T06:46:36.000Z
src/Cxx/PolyData/Outline.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
2
2020-09-12T17:33:52.000Z
2021-04-15T17:33:09.000Z
src/Cxx/PolyData/Outline.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
27
2020-08-17T07:09:30.000Z
2022-02-15T03:44:58.000Z
#include <vtkActor.h> #include <vtkConeSource.h> #include <vtkNamedColors.h> #include <vtkNew.h> #include <vtkOutlineFilter.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> int main(int, char*[]) { vtkNew<vtkNamedColors> colors; // Create a cone vtkNew<vtkConeSource> source; source->SetCenter(0.0, 0.0, 0.0); source->SetResolution(100); source->Update(); vtkNew<vtkPolyDataMapper> mapper; mapper->SetInputConnection(source->GetOutputPort()); vtkNew<vtkActor> actor; actor->SetMapper(mapper); actor->GetProperty()->SetColor(colors->GetColor3d("MistyRose").GetData()); // Create the outline vtkNew<vtkOutlineFilter> outline; outline->SetInputConnection(source->GetOutputPort()); vtkNew<vtkPolyDataMapper> outlineMapper; outlineMapper->SetInputConnection(outline->GetOutputPort()); vtkNew<vtkActor> outlineActor; outlineActor->SetMapper(outlineMapper); outlineActor->GetProperty()->SetColor(colors->GetColor3d("Gold").GetData()); // Setup the window vtkNew<vtkRenderer> renderer; vtkNew<vtkRenderWindow> renderWindow; renderWindow->AddRenderer(renderer); renderWindow->SetWindowName("Outline"); vtkNew<vtkRenderWindowInteractor> renderWindowInteractor; renderWindowInteractor->SetRenderWindow(renderWindow); // Add the actors to the scene renderer->AddActor(actor); renderer->AddActor(outlineActor); renderer->SetBackground( colors->GetColor3d("MidnightBlue").GetData()); // Background color white // Render and interact renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; }
28.065574
78
0.754089
[ "render" ]
7980f558dbea848662afc38b2075ddfdd2d05bd9
3,244
cpp
C++
codechef/Jan17/Tourists in Mancunia.cpp
amarlearning/CodeForces
6625d3be21cb6a78b88c7521860d1da263e77121
[ "Unlicense" ]
3
2017-06-17T21:27:04.000Z
2020-08-07T04:56:56.000Z
codechef/Jan17/Tourists in Mancunia.cpp
amarlearning/Codeforces
6625d3be21cb6a78b88c7521860d1da263e77121
[ "Unlicense" ]
null
null
null
codechef/Jan17/Tourists in Mancunia.cpp
amarlearning/Codeforces
6625d3be21cb6a78b88c7521860d1da263e77121
[ "Unlicense" ]
2
2018-07-26T21:00:42.000Z
2019-11-30T19:33:57.000Z
/* Author : Amar Prakash Pandey contact : http://amarpandey.me */ #include <string.h> #include <fstream> #include <iostream> #include <string> #include <complex> #include <math.h> #include <set> #include <vector> #include <map> #include <queue> #include <stdio.h> #include <stack> #include <algorithm> #include <list> #include <ctime> #include <memory.h> #include <ctime> #include <assert.h> #define pi 3.14159 #define mod 1000000007 using namespace std; #ifndef LL #define LL long long #endif #ifndef L #define L long #endif struct reference { long long int start, end; }; LL int sideOne[100000]={0}; LL int sideTwo[100000]={0}; int main(int argc, char const *argv[]) { LL int N, E, flag = 0, temp; cin >> N >> E; reference game[200000], demo[200000], mix[200000]; for (L int i = 0; i < E; ++i) { cin >> game[i].start >> game[i].end; } if(E < N) { cout << "NO"; } else { for (L int i = 0; i < E; ) { if(i == E-1){ if(game[i].end == game[0].start) { i++; } else { if(game[i].end == game[0].end) { temp = game[0].end; game[0].end = game[0].start; game[0].start = temp; i++; } else { flag = 1; break; } } } else { if(game[i].end == game[i+1].start) { i++; } else { if(game[i].end == game[i+1].end) { temp = game[i+1].end; game[i+1].end = game[i+1].start; game[i+1].start = temp; i++; } else { flag = 1; break; } } } } if(flag == 1) { if(N < 21) { flag = 0; for (int i = 1; i <= N; ++i) { if(sideOne[i] != sideTwo[i]) { flag = 1; break; } } if(flag == 1) { cout << "NO"; } else { cout << "YES" << endl; for (int i = 0; i < E; ++i) { cout << game[i].start << " " << game[i].end << endl; } } } else { for (L int i = 0; i < E; ) { if(i == E-1){ if(demo[i].start == demo[0].end) { i++; } else { if(demo[i].start == demo[0].start) { temp = demo[0].start; demo[0].start = demo[0].end; demo[0].end = temp; i++; } else { flag = 1; break; } } } else { if(demo[i].start == demo[i+1].end) { i++; } else { if(demo[i].start == demo[i+1].start) { temp = demo[i+1].start; demo[i+1].start = demo[i+1].end; demo[i+1].end = temp; i++; } else { flag = 1; break; } } } } if(flag == 1) { flag = 0; for (int i = 1; i <= N; ++i) { if((sideOne[i] + sideTwo[i])%2 != 0) { flag = 1; break; } } if(flag == 1) { cout << "NO"; } else { cout << "YES" << endl; for (int i = 0; i < E; ++i) { cout << mix[i].start << " " << mix[i].end << endl; } } } else { cout << "YES" << endl; for (int i = 0; i < E; ++i) { cout << demo[i].start << " " << demo[i].end << endl; } } } } else { cout << "YES" << endl; for (int i = 0; i < E; ++i) { cout << game[i].start << " " << game[i].end << endl; } } } return 0; }
18.643678
58
0.432799
[ "vector" ]
7985ca2530f5d6a0d8254905c799d27c8907a3c1
2,457
cpp
C++
Dynamic Programming/140. Word Break II/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
1
2021-11-19T19:58:33.000Z
2021-11-19T19:58:33.000Z
Dynamic Programming/140. Word Break II/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
null
null
null
Dynamic Programming/140. Word Break II/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
2
2021-11-26T12:47:27.000Z
2022-01-13T16:14:46.000Z
// // main.cpp // 140. Word Break II // // Created by 边俊林 on 2019/8/22. // Copyright © 2019 Minecode.Link. All rights reserved. // /* ------------------------------------------------------ *\ https://leetcode-cn.com/problems/Sample/description/ \* ------------------------------------------------------ */ #include <map> #include <set> #include <queue> #include <stack> #include <vector> #include <cstdio> #include <cstdlib> #include <iostream> #include <algorithm> #include <unordered_map> #include <unordered_set> using namespace std; /// Solution: // // 需要增加cache class Solution { public: vector<string> wordBreak(string s, vector<string>& wordDict) { unordered_set<string> hasa (wordDict.begin(), wordDict.end()); return wordBreakCore(s, hasa); } private: unordered_map<string, vector<string>> breakMap; vector<string> wordBreakCore(string s, const unordered_set<string>& words) { if (breakMap.count(s)) return breakMap[s]; vector<string> res; if (words.count(s)) res.push_back(s); for (int i = 1; i < s.length(); ++i) { // 如果取prefix,“判断前面需不需要加空格”比较麻烦 string suffix = s.substr(i); if (words.count(suffix)) { vector<string> tmp = parse(suffix, wordBreakCore(s.substr(0, i), words)); res.insert(res.end(), tmp.begin(), tmp.end()); } } breakMap[s] = res; return res; } vector<string> parse(string suffix, vector<string> arr) { for (auto& elem : arr) { elem += " " + suffix; } return arr; } }; // Tool Function List void printVector(vector<string> v) { printf("[\n"); for (auto it = v.begin(); it != v.end(); ++it) { cout << *it << endl; } printf("]\n"); } int main() { Solution sol = Solution(); // string s = "catsanddog"; // vector<string> dict = {"cat", "cats", "and", "sand", "dog"}; string s = "pineapplepenapple"; vector<string> dict = {"apple", "pen", "applepen", "pine", "pineapple"}; // string s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // vector<string> dict = {"a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"}; auto res = sol.wordBreak(s, dict); printVector(res); return 0; }
27.920455
171
0.570615
[ "vector" ]
7987fd02ddc1c23b25a0dd31245c8def350d00dd
6,522
cpp
C++
projects/procjam-2020/2d-occluder-search.cpp
tmpvar/rawk
0dee2bdf9e11e9033988a0d9d1e52603263c6aca
[ "MIT" ]
9
2020-08-14T19:46:33.000Z
2021-10-13T09:33:20.000Z
projects/procjam-2020/2d-occluder-search.cpp
tmpvar/rawkit
0dee2bdf9e11e9033988a0d9d1e52603263c6aca
[ "MIT" ]
null
null
null
projects/procjam-2020/2d-occluder-search.cpp
tmpvar/rawkit
0dee2bdf9e11e9033988a0d9d1e52603263c6aca
[ "MIT" ]
null
null
null
#include <rawkit/rawkit.h> #include "glm/glm.hpp" #include "glm/gtx/compatibility.hpp" using namespace glm; #define TAU 6.2831853 const uint32_t grid_diameter = 16; #define occluder_list_len (2 * grid_diameter) #define volume_len (grid_diameter * grid_diameter) uint8_t volume[volume_len]; const vec2 grid_dims = {grid_diameter, grid_diameter}; void setup() { // fill the volume vec2 pos(0, 0); for (pos.x = 0.0f; pos.x<grid_dims.x; pos.x++) { for (pos.y = 0.0f; pos.y<grid_dims.y; pos.y++) { uint32_t loc = ( static_cast<uint32_t>(pos.x) + static_cast<uint32_t>(pos.y * grid_dims.x) ); float dist = glm::distance(pos + 0.5f, grid_dims * 0.5f); if (dist < (float)grid_diameter * 0.2f) { volume[loc] = 255; } else { volume[loc] = 0; } } } } void draw_camera(rawkit_vg_t *vg, vec2 eye, vec2 target) { // TODO: draw a camera that points at the target rawkit_vg_fill_color(vg, rawkit_vg_RGB(255, 255, 255)); rawkit_vg_begin_path(vg); rawkit_vg_arc(vg, eye.x, eye.y, 0.5f, 0.0f, TAU, 1); rawkit_vg_fill(vg); } struct edge_lookup { vec2 start; vec2 end; vec2 normal; }; uint8_t fire_ray(rawkit_vg_t *vg, vec2 eye, vec2 pos) { vec2 dir = glm::normalize(pos - eye); vec2 mapPos = vec2(floor(pos)); vec2 deltaDist = abs(vec2(length(dir)) / dir); vec2 rayStep = sign(dir); vec2 sideDist = (sign(dir) * (mapPos - pos) + (sign(dir) * 0.5f) + 0.5f) * deltaDist; vec2 mask = glm::step(sideDist, vec2(sideDist.y, sideDist.x)); float max_iterations = grid_diameter * 3.0; int hit_count = 0; for (int iterations = 0; iterations < max_iterations; iterations++) { if (all(greaterThanEqual(mapPos, vec2(0))) && all(lessThan(mapPos, grid_dims))) { uint32_t loc = ( static_cast<uint32_t>(mapPos.x) + static_cast<uint32_t>(mapPos.y * grid_dims.x) ); if (volume[loc]) { rawkit_vg_fill_color(vg, rawkit_vg_RGBA(64, 127, 64, 255)); rawkit_vg_begin_path(vg); rawkit_vg_rect(vg, mapPos.x, mapPos.y, 0.75, 0.75); rawkit_vg_fill(vg); return volume[loc]; } else { rawkit_vg_fill_color(vg, rawkit_vg_RGBA(255, 0, 0, 64)); rawkit_vg_begin_path(vg); rawkit_vg_rect(vg, mapPos.x, mapPos.y, 0.75, 0.75); rawkit_vg_fill(vg); } } mask = glm::step(sideDist, vec2(sideDist.y, sideDist.x)); sideDist += mask * deltaDist; mapPos += mask * rayStep; } return 0; } void trace_edge(rawkit_vg_t *vg, vec2 eye, edge_lookup *edge) { vec2 start = glm::min(grid_dims - 1.0f, edge->start); vec2 end = glm::min(grid_dims - 1.0f, edge->end); vec2 diff = end - start; int comp = diff.x == 0.0f ? 1 : 0; float dir = diff.x == 0.0f ? sign(diff.y) : sign(diff.x); float step = glm::distance(start, end)/(float)grid_diameter; igText("start(%0.3f, %0.3f) -> end(%0.3f, %0.3f) step: %0.3f, dist: %f", start.x, start.y, end.x, end.y, step, glm::distance(start, end) ); vec2 p = start; for (float i=0; i<(float)grid_diameter; i++) { p[comp] = start[comp] + dir * i; rawkit_vg_fill_color(vg, rawkit_vg_RGBA(255, 255, 255, 64)); rawkit_vg_begin_path(vg); rawkit_vg_rect(vg, p.x, p.y, 0.75, 0.75); rawkit_vg_fill(vg); rawkit_vg_stroke_color(vg, rawkit_vg_RGB(64, 64, 64)); rawkit_vg_begin_path(vg); rawkit_vg_move_to(vg, eye.x, eye.y); rawkit_vg_line_to(vg, floor(p.x) + 0.5, floor(p.y) + 0.5); rawkit_vg_stroke(vg); // fire_ray(vg, eye, p); // fire_ray(vg, eye, p + vec2(1.0, 0.0)); // fire_ray(vg, eye, p + vec2(1.0, 1.0)); // fire_ray(vg, eye, p + vec2(0.0, 1.0)); fire_ray(vg, eye, p + vec2(0.5)); } } typedef struct state_t { float t; } state_t; void loop() { vec2 window_dims( rawkit_window_width(), rawkit_window_height() ); rawkit_vg_t *vg = rawkit_default_vg(); rawkit_vg_translate(vg, window_dims.x/2.0f, window_dims.y/2.0f); rawkit_vg_scale(vg, 16.0f, -16.0f); rawkit_vg_translate(vg, -grid_dims.x/2.0f, -grid_dims.y/2.0f); rawkit_vg_stroke_width(vg, 1.0f/16.0f); float now = rawkit_now(); state_t *state = rawkit_hot_state("state_t", state_t); { float dmin = 0.0f; float dmax = 10.0f; igSliderScalar("##camera-time", ImGuiDataType_Float, &state->t, &dmin, &dmax, "time %f", 1.0f); } now = state->t; vec2 eye = vec2( sin(now) * 16.0f, cos(now) * 16.0f ) + grid_dims * 0.5f; vec2 target = grid_dims * 0.5f; draw_camera(vg, eye, target); uvec2 occluder_list[occluder_list_len] = {}; // render the grid { vec2 pos(0, 0); for (pos.x = 0.0f; pos.x<grid_dims.x; pos.x++) { for (pos.y = 0.0f; pos.y<grid_dims.y; pos.y++) { rawkit_vg_begin_path(vg); rawkit_vg_rect(vg, pos.x, pos.y, 0.75f, 0.75f); uint32_t loc = ( static_cast<uint32_t>(pos.x) + static_cast<uint32_t>(pos.y * grid_dims.x) ); if (volume[loc]) { rawkit_vg_stroke_color(vg, rawkit_vg_RGB(64, 127, 64)); } else { rawkit_vg_stroke_color(vg, rawkit_vg_RGB(127, 127, 127)); } rawkit_vg_stroke(vg); } } } // render the edges to be searched { edge_lookup edges[4] = { { .start = vec2(0.0f, 0.0f), .end = vec2(grid_dims.x, 0.0f), .normal = vec2(0.0f, -1.0f), }, { .start = vec2(grid_dims.x, 0.0f), .end = vec2(grid_dims.x, grid_dims.y), .normal = vec2(1.0f, 0.0f), }, { .start = vec2(grid_dims.x, grid_dims.y), .end = vec2(0.0f, grid_dims.y), .normal = vec2(0.0f, 1.0f), }, { .start = vec2(0.0f, grid_dims.y), .end = vec2(0.0f, 0.0f), .normal = vec2(-1.0f, 0.0f), }, }; // TODO: if inside the grid, the behavior changes // TODO: there is a faster way to compute which edges should be sampled.. vec2 dir = normalize(eye - target); for (int i=0; i<4; i++) { edge_lookup *edge = &edges[i]; float r = glm::dot(dir, edge->normal); if (r >= 0.5f) { rawkit_vg_stroke_color(vg, rawkit_vg_RGBf(r, 0, r)); rawkit_vg_begin_path(vg); rawkit_vg_move_to(vg, edge->start.x + edge->normal.x, edge->start.y + edge->normal.y); rawkit_vg_line_to(vg, edge->end.x + edge->normal.x, edge->end.y + edge->normal.y); rawkit_vg_stroke(vg); trace_edge(vg, eye, edge); } } } }
27.403361
100
0.591076
[ "render" ]
7999e80292dd74337f3975b05a7c4c2cfa2b721d
1,320
hpp
C++
lib/libcpp/Mesh/Mesh/interfacemeshinfo.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
lib/libcpp/Mesh/Mesh/interfacemeshinfo.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
1
2019-01-31T10:59:11.000Z
2019-01-31T10:59:11.000Z
lib/libcpp/Mesh/Mesh/interfacemeshinfo.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
#ifndef __Mesh_InterfaceMeshInfo_hpp #define __Mesh_InterfaceMeshInfo_hpp #include "geometryobject.hpp" /*--------------------------------------------------------------------------*/ namespace mesh { class InterfaceMeshInfo : public GeometryObject { public: alat::armaivec _nodes_to_plain; alat::armaivec _sides_to_plain; alat::armaivec _cells_to_plain; public: ~InterfaceMeshInfo(); InterfaceMeshInfo(); InterfaceMeshInfo( const InterfaceMeshInfo& interfacemeshinfo); InterfaceMeshInfo& operator=( const InterfaceMeshInfo& interfacemeshinfo); std::string getClassName() const; std::unique_ptr<GeometryObject> clone() const; const alat::armaivec& getNodesToPlain() const; alat::armaivec& getNodesToPlain(); const alat::armaivec& getCellsToPlain() const; alat::armaivec& getCellsToPlain(); const alat::armaivec& getSidesToPlain() const; alat::armaivec& getSidesToPlain(); alat::armaivec getSizes() const; void setSizes(alat::armaivec::const_iterator sizes); void send(int neighbor, int tag) const; void recv(int neighbor, int tag); void loadH5(const arma::hdf5_name& spec); void saveH5(const arma::hdf5_name& spec) const; }; } /*--------------------------------------------------------------------------*/ #endif
31.428571
78
0.640909
[ "mesh" ]
799a19add73c6ee777d006ff77a03771e8cb159b
1,790
hpp
C++
test/test_writer.hpp
wx9698/xviz
6a45a56a7e62489d2200182a3379bb76fbf71141
[ "MIT" ]
13
2020-02-10T07:25:31.000Z
2021-03-26T16:30:23.000Z
test/test_writer.hpp
ghy200692162/xviz
6a45a56a7e62489d2200182a3379bb76fbf71141
[ "MIT" ]
1
2020-07-28T18:12:46.000Z
2020-07-30T02:59:25.000Z
test/test_writer.hpp
ghy200692162/xviz
6a45a56a7e62489d2200182a3379bb76fbf71141
[ "MIT" ]
4
2021-06-08T06:38:20.000Z
2022-03-15T10:23:23.000Z
/* * File: test_writer.hpp * Author: Minjun Xu (mjxu96@gmail.com) * File Created: Tuesday, 17th March 2020 6:20:29 pm */ #ifndef XVIZ_TEST_WRITER_H_ #define XVIZ_TEST_WRITER_H_ #include "test_utils.h" #include "xviz/builder/xviz_builder.h" #include "xviz/io/glb_writer.h" #include <gtest/gtest.h> class XVIZWriterTest : public ::testing::Test { protected: xviz::XVIZBuilder GetInitialBuilderWithMetadata(xviz::XVIZMetadataBuilder& metadata_builder) { xviz::XVIZBuilder builder(metadata_builder.GetData()); builder.Pose("/vehicle_pose") .MapOrigin(0, 0, 0) .Orientation(0, 0, 0) .Position(0, 0, 0) .Timestamp(1000.0); return builder; } }; TEST_F(XVIZWriterTest, GLBTest) { auto metadata_builder = xviz::test::GetBuilderTestMetadataBuilderForPrimitive(); auto builder = GetInitialBuilderWithMetadata(metadata_builder); builder.Primitive("/primitive/IMAGE/copy") .Image("123"); builder.Primitive("/primitive/IMAGE/move") .Image("123", true); builder.Primitive("/primitive/IMAGE/pointer") .Image("", true); builder.Primitive("/primitive/POINT/copy") .Points({1, 2, 3}).Colors({0, 0, 0, 0}); std::vector<double> empty_points; std::vector<uint8_t> empty_colors; builder.Primitive("/primitive/POINT/move") .Points(empty_points).Colors(empty_colors); builder.Primitive("/primitive/POINT/pointer") .Points({1, 2, 3}).Colors({0, 0, 0, 0, 0, 0, 0, 0}); xviz::XVIZGLBWriter writer; std::string output; auto message = builder.GetMessage(); writer.WriteMessage(output, builder.GetMessage()); writer.WriteMessage(output, message); // TODO add EXPECT_EQ() auto readable_output = xviz::test::ConvertBinaryToReadableChar(output); // std::cerr << readable_output << std::endl; } #endif
27.538462
96
0.702235
[ "vector" ]
799ad5d183067fcd97189589bca522ceeb40d9c1
12,288
cpp
C++
hashmap.cpp
czh-123/hashmap_cis106L
c94627e0f0f61d5bf60adcc9129fbdc403f7e89d
[ "MIT" ]
null
null
null
hashmap.cpp
czh-123/hashmap_cis106L
c94627e0f0f61d5bf60adcc9129fbdc403f7e89d
[ "MIT" ]
null
null
null
hashmap.cpp
czh-123/hashmap_cis106L
c94627e0f0f61d5bf60adcc9129fbdc403f7e89d
[ "MIT" ]
null
null
null
/* * Assignment 2: HashMap template implementation (BASIC SOLUTION) * Notes: this file is what we call a .tpp file. It's not a .cpp file, * because it's not exactly a regular source code file. Instead, we are * defining the template definitions for our HashMap class. * * TODO: write a comment here. * * You'll notice that the commenting provided is absolutely stunning. * It was really fun to read through the starter code, right? * Please emulate this commenting style in your code, so your grader * can have an equally pleasant time reading your code. :) */ #include "hashmap.h" //each node in bucket represent a list template <typename K, typename M, typename H> HashMap<K, M, H>::HashMap() : HashMap(kDefaultBuckets) { } template <typename K, typename M, typename H> HashMap<K, M, H>::HashMap(size_t bucket_count, const H& hash) : _size(0), _hash_function(hash), _buckets_array(bucket_count, nullptr) { } template <typename K, typename M, typename H> HashMap<K, M, H>::~HashMap() { clear(); } template <typename K, typename M, typename H> inline size_t HashMap<K, M, H>::size() const noexcept { return _size; } template <typename K, typename M, typename H> inline bool HashMap<K, M, H>::empty() const noexcept { return size() == 0; } template <typename K, typename M, typename H> inline float HashMap<K, M, H>::load_factor() const noexcept { return static_cast<float>(size())/bucket_count(); }; template <typename K, typename M, typename H> inline size_t HashMap<K, M, H>::bucket_count() const noexcept { return _buckets_array.size(); }; template <typename K, typename M, typename H> bool HashMap<K, M, H>::contains(const K& key) const noexcept { return find_node(key).second != nullptr; } template <typename K, typename M, typename H> void HashMap<K, M, H>::clear() noexcept { for (auto& curr : _buckets_array) { while (curr != nullptr) { auto trash = curr; curr = curr->next; delete trash; } } _size = 0; } template <typename K, typename M, typename H> std::pair<typename HashMap<K, M, H>::value_type*, bool> HashMap<K, M, H>::insert(const value_type& value) { const auto& [key, mapped] = value; auto [prev, node_to_edit] = find_node(key); size_t index = _hash_function(key) % bucket_count(); if (node_to_edit != nullptr) return {&(node_to_edit->value), false}; _buckets_array[index] = new node(value, _buckets_array[index]); // !!!!!!!! 每次添加到头部 bucket记录头部 ++_size; return {&(_buckets_array[index]->value), true}; } template <typename K, typename M, typename H> M& HashMap<K, M, H>::at(const K& key) { auto [prev, node_found] = find_node(key); if (node_found == nullptr) { throw std::out_of_range("HashMap<K, M, H>::at: key not found"); } return node_found->value.second; } template <typename K, typename M, typename H> const M& HashMap<K, M, H>::at(const K& key) const { auto [prev, node_found] = find_node(key); if (node_found == nullptr) { throw std::out_of_range("HashMap<K, M, H>::at: key not found"); } return node_found->value.second; } template <typename K, typename M, typename H> typename HashMap<K, M, H>::node_pair HashMap<K, M, H>::find_node(const K& key) const { size_t index = _hash_function(key) % bucket_count(); auto curr = _buckets_array[index]; node* prev = nullptr; // if first node is the key, return {nullptr, front} while (curr != nullptr) { const auto& [found_key, found_mapped] = curr->value; if (found_key == key) return {prev, curr}; prev = curr; curr = curr->next; } return {nullptr, nullptr}; // key not found at all. } template <typename K, typename M, typename H> void HashMap<K, M, H>::debug() const { std::cout << std::setw(30) << std::setfill('-') << '\n' << std::setfill(' ') << "Printing debug information for your HashMap implementation\n" << "Size: " << size() << std::setw(15) << std::right << "Buckets: " << bucket_count() << std::setw(20) << std::right << "(load factor: " << std::setprecision(2) << load_factor() << ") \n\n"; for (size_t i = 0; i < bucket_count(); ++i) { std::cout << "[" << std::setw(3) << i << "]:"; auto curr = _buckets_array[i]; while (curr != nullptr) { const auto& [key, mapped] = curr->value; // next line will not compile if << not supported for K or M std::cout << " -> " << key << ":" << mapped; curr = curr->next; } std::cout << " /" << '\n'; } std::cout << std::setw(30) << std::setfill('-') << '\n'; } template <typename K, typename M, typename H> bool HashMap<K, M, H>::erase(const K& key) { auto [prev, node_to_erase] = find_node(key); if (node_to_erase == nullptr) { return false; } else { size_t index = _hash_function(key) % bucket_count(); (prev ? prev->next : _buckets_array[index]) = node_to_erase->next; delete node_to_erase; --_size; return true; } } template <typename K, typename M, typename H> void HashMap<K, M, H>::rehash(size_t new_bucket_count) { if (new_bucket_count == 0) { throw std::out_of_range("HashMap<K, M, H>::rehash: new_bucket_count must be positive."); } std::vector<node*> new_buckets_array(new_bucket_count); /* Optional Milestone 1: begin student code */ // Hint: you should NOT call insert, and you should not call // new or delete in this function. You must reuse existing nodes. //node.first (key) % new_count to get the list and "insert" "del" std::vector<node*> old_buckets = _buckets_array; this->_buckets_array = new_buckets_array; for (auto &bnode:old_buckets){ while(bnode != nullptr){ const auto &[key,mapped_key] = bnode->value; size_t index = _hash_function(key)%new_bucket_count; auto nxt_node = bnode->next; bnode->next = _buckets_array[index]; _buckets_array[index] = bnode; bnode = nxt_node; } } } template<typename K,typename M,typename H> M& HashMap<K,M,H>::operator[](const K &key){ auto [prev,curr] = find_node(key); if (curr == nullptr){ size_t index = _hash_function(key)%bucket_count(); _buckets_array[index] = new node({key,M()},_buckets_array[index]); _size++; //std::cout<<_buckets_array[index]->value.first<<" "<<_buckets_array[index]->value.second<<std::endl; return _buckets_array[index]->value.second; } else{ return curr->value.second; } } template<typename K,typename M,typename H> std::ostream& operator<<(std::ostream& os,const HashMap<K,M,H>& map){ os<<"{"; size_t count = 0; for ( auto node:map._buckets_array){ while (node != nullptr){ if (count != 0) os<<", "; else ++count; os<<node->value.first<<":"<<node->value.second; //std::cout<<node->value.first<<":"<<node->value.second<<std::endl; node = node->next; } } os<<"}"; return os; } template<typename K,typename M,typename H> bool operator==(const HashMap<K,M,H>& lhs,const HashMap<K,M,H>& rhs){ if (lhs.size() != rhs.size() ) return false; for (auto node:lhs._buckets_array){ while(node != nullptr){ auto key = node->value.first; auto [prev,curr] = rhs.find_node(key); if (curr == nullptr || curr->value.second != node->value.second) return false; //if (rhs.at(static_cast<const K>(node->value.first)) != node->value.second) // return false; node = node->next; } } for (auto node:rhs._buckets_array){ while(node != nullptr){ auto key = node->value.first; auto [prev,curr] = lhs.find_node(key); if (curr == nullptr || curr->value.second != node->value.second) return false; node = node->next; } } return true; } template<typename K,typename M,typename H> bool operator!= (const HashMap<K,M,H>& lhs,const HashMap<K,M,H>& rhs){ if (lhs.size() != rhs.size()) return true; for (auto node:lhs._buckets_array){ while(node != nullptr){ auto key = node->value.first; auto [prev,curr] = rhs.find_node(key); if (curr == nullptr || curr->value.second != node->value.second) return true; node = node->next; } } for (auto node:rhs._buckets_array){ while(node != nullptr){ auto key = node->value.first; auto [prev,curr] = lhs.find_node(key); if (curr == nullptr || curr->value.second != node->value.second) return true; node = node->next; } } return false; } // milestone 3 template<typename K,typename M,typename H> HashMap<K,M,H>::HashMap(const HashMap<K,M,H>& cpy) noexcept: _size(cpy.size()), _hash_function(cpy._hash_function), _buckets_array(std::vector<node*>(cpy.bucket_count(),nullptr)){ for (size_t index = 0;index<cpy.bucket_count();index++){ auto lnode = cpy._buckets_array[index]; while(lnode != nullptr){ _buckets_array[index] = new node(lnode->value,_buckets_array[index]); lnode = lnode->next; } } } template<typename K,typename M,typename H> HashMap<K,M,H>& HashMap<K,M,H>::operator= (const HashMap<K,M,H>& rhs){ if (this == &rhs) return *this; clear(); //HashMap(rhs); 为什么报错 redefi 和 shadows a parameter? _size = rhs.size(); _hash_function = rhs._hash_function; _buckets_array = std::vector<node*>(rhs.bucket_count(),nullptr); for (size_t index = 0;index<rhs.bucket_count();index++){ auto lnode = rhs._buckets_array[index]; while(lnode != nullptr){ _buckets_array[index] = new node(lnode->value,_buckets_array[index]); lnode = lnode->next; } } return *this; } template<typename K,typename M,typename H> HashMap<K,M,H>::HashMap(HashMap<K,M,H>&& other) noexcept : _size(other._size), _hash_function(other._hash_function){ if (this == &other) return ; _buckets_array = std::move(other._buckets_array); other._size = 0; } template<typename K,typename M,typename H> HashMap<K,M,H>& HashMap<K,M,H>::operator=(HashMap<K,M,H>&& rhs) noexcept { //实在不知道怎么优化了 if (this != &rhs){ _size = std::move(rhs._size); _buckets_array = std::move(rhs._buckets_array); /* _buckets_array = std::vector<node*>(rhs.bucket_count(),nullptr); //_buckets_array.clear(); for (size_t i=0;i<rhs.bucket_count();i++){ //_buckets_array.push_back(std::move(rhs._buckets_array[i])); _buckets_array[i] = rhs._buckets_array[i]; rhs._buckets_array[i] = nullptr; } */ } return *this; } template <typename K,typename M,typename H> HashMap<K,M,H>::HashMap(std::initializer_list<value_type> hl): _buckets_array(kDefaultBuckets,nullptr) { _size = 0; for (auto p:hl){ insert(p); } } template <typename K,typename M,typename H> HashMap<K,M,H>::HashMap(std::initializer_list<typename std::vector<std::pair<K,M>>::iterator > &&hl): _buckets_array(kDefaultBuckets,nullptr) { _size = 0; auto p = *hl.begin(); auto e = *(hl.end()-1); /* std::cout<<(*e).first<<" "<<(*e).second<<std::endl; std::cout<<"begin"<<std::endl; for (auto p:hl){ std::cout<<(*p).first<<" "<<(*p).second<<std::endl; } std::cout<<hl.size(); std::cout<<"end"<<std::endl; */ while (p != e){ insert(*p); p++; //std::cout<<(*p).first<<(*p).second<<std::endl; } } /* Milestone 2-3: begin student code Here is a list of functions you should implement: Milestone 2 - operator[] - operator<< - operator== and != - make existing functions const-correct Milestone 3 - copy constructor - copy assignment - move constructor - move assignment */
31.834197
110
0.596354
[ "vector" ]
79a140ff4c134dcd072aba627c311292677e8a07
17,298
cxx
C++
Modules/Filtering/ImageManipulation/test/otbClampImageFilter.cxx
liuxuvip/OTB
73ed482d62c2924aea158aac14d725dc9447083b
[ "Apache-2.0" ]
317
2015-01-19T08:40:58.000Z
2022-03-17T11:55:48.000Z
Modules/Filtering/ImageManipulation/test/otbClampImageFilter.cxx
guandd/OTB
707ce4c6bb4c7186e3b102b2b00493a5050872cb
[ "Apache-2.0" ]
18
2015-07-29T14:13:45.000Z
2021-03-29T12:36:24.000Z
Modules/Filtering/ImageManipulation/test/otbClampImageFilter.cxx
guandd/OTB
707ce4c6bb4c7186e3b102b2b00493a5050872cb
[ "Apache-2.0" ]
132
2015-02-21T23:57:25.000Z
2022-03-25T16:03:16.000Z
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbClampImageFilter.h" #include "otbImage.h" #include "otbVectorImage.h" #include <limits> #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "itkImageRegionConstIterator.h" /** Pixel typedefs */ typedef double InputPixelType; typedef unsigned int OutputPixelType; /** Image typedefs */ const unsigned int Dimension = 2; typedef otb::Image<InputPixelType, Dimension> InputImageType; typedef otb::Image<OutputPixelType, Dimension> OutputImageType; typedef otb::ClampImageFilter<InputImageType, OutputImageType> FilterType; int otbClampImageFilterTest(int itkNotUsed(argc), char* argv[]) { typedef otb::ImageFileReader<InputImageType> ReaderType; typedef otb::ImageFileWriter<OutputImageType> WriterType; /** instantiating the filter */ FilterType::Pointer filter = FilterType::New(); ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); reader->SetFileName(argv[1]); filter->SetInput(reader->GetOutput()); filter->SetThresholds(100, 400); writer->SetInput(filter->GetOutput()); writer->SetFileName(argv[2]); writer->Update(); return EXIT_SUCCESS; } template <class InImageType, class OutImageType> typename OutImageType::Pointer Cross(std::string const& inputFileName) { typedef otb::ImageFileReader<InImageType> ReaderType; typedef otb::ClampImageFilter<InImageType, OutImageType> ClampFilter; typename ReaderType::Pointer reader(ReaderType::New()); reader->SetFileName(inputFileName); typename ClampFilter::Pointer clamp(ClampFilter::New()); clamp->SetInput(reader->GetOutput()); clamp->Update(); return clamp->GetOutput(); } template <class OutImageType> typename OutImageType::Pointer Cross(otb::VectorImage<std::complex<float>>::Pointer input) { typedef otb::ClampImageFilter<otb::VectorImage<std::complex<float>>, OutImageType> ClampFilter; typename ClampFilter::Pointer clamp(ClampFilter::New()); clamp->SetInput(input); clamp->Update(); return clamp->GetOutput(); } template <class OutImageType> typename OutImageType::Pointer Cross(otb::Image<itk::FixedArray<std::complex<float>, 2>>::Pointer input) { typedef otb::ClampImageFilter<otb::Image<itk::FixedArray<std::complex<float>, 2>>, OutImageType> ClampFilter; typename ClampFilter::Pointer clamp(ClampFilter::New()); clamp->SetInput(input); clamp->Update(); return clamp->GetOutput(); } typedef otb::VectorImage<double> ImageRefType; template <class ImageType> bool CompareImageReal(const ImageRefType::Pointer imRef, const ImageType* im) { typedef typename ImageType::PixelType RealPixelType; RealPixelType min = std::numeric_limits<RealPixelType>::lowest(); RealPixelType max = std::numeric_limits<RealPixelType>::max(); auto itRef = itk::ImageRegionConstIterator<ImageRefType>(imRef, imRef->GetLargestPossibleRegion()); auto it = itk::ImageRegionConstIterator<ImageType>(im, im->GetLargestPossibleRegion()); itRef.GoToBegin(); it.GoToBegin(); RealPixelType val; double ref; while (!it.IsAtEnd()) { val = it.Get(); ref = itRef.Get()[0]; if (ref > static_cast<double>(max) && val != max) { return false; } else if (ref < static_cast<double>(min) && val != min) { return false; } else if (static_cast<RealPixelType>(ref) != val) { return false; } ++it; ++itRef; } return true; } template <class ImageType> bool CompareVectorReal(const ImageRefType::Pointer imRef, const ImageType* im) { typedef typename ImageType::InternalPixelType RealPixelType; RealPixelType min = std::numeric_limits<RealPixelType>::lowest(); RealPixelType max = std::numeric_limits<RealPixelType>::max(); auto itRef = itk::ImageRegionConstIterator<ImageRefType>(imRef, imRef->GetLargestPossibleRegion()); auto it = itk::ImageRegionConstIterator<ImageType>(im, im->GetLargestPossibleRegion()); itRef.GoToBegin(); it.GoToBegin(); unsigned int nbChanel = im->GetNumberOfComponentsPerPixel(); // unsigned int nbChanelRef = imRef->GetNumberOfComponentsPerPixel (); RealPixelType val; double ref; while (!it.IsAtEnd()) { // std::cout<<it.Get()<<std::endl; // std::cout<<itRef.Get()<<std::endl; for (unsigned int i = 0; i < nbChanel; i++) { val = it.Get()[i]; ref = itRef.Get()[i]; if (ref > static_cast<double>(max) && val != max) { std::cout << "ref : " << static_cast<RealPixelType>(ref) << std::endl; std::cout << "val : " << val << std::endl; return false; } else if (ref < static_cast<double>(min) && val != min) { std::cout << "ref : " << static_cast<RealPixelType>(ref) << std::endl; std::cout << "val : " << val << std::endl; return false; } else if (static_cast<RealPixelType>(ref) != val) { std::cout << "ref : " << static_cast<RealPixelType>(ref) << std::endl; std::cout << "val : " << val << std::endl; return false; } } ++it; ++itRef; } return true; } template <class ImageType> bool CompareImageComplex(const ImageRefType::Pointer imageRef, const ImageType* im) { typedef typename ImageType::PixelType ComplexType; typedef typename ComplexType::value_type RealType; RealType min = std::numeric_limits<RealType>::lowest(); RealType max = std::numeric_limits<RealType>::max(); auto itRef = itk::ImageRegionConstIterator<ImageRefType>(imageRef, imageRef->GetLargestPossibleRegion()); auto it = itk::ImageRegionConstIterator<ImageType>(im, im->GetLargestPossibleRegion()); itRef.GoToBegin(); it.GoToBegin(); ComplexType val; double reRef, imRef; while (!it.IsAtEnd()) { val = it.Get(); reRef = itRef.Get()[0]; imRef = itRef.Get()[1]; if ((reRef > static_cast<double>(max) && val.real() != max) || (imRef > static_cast<double>(max) && val.imag() != max)) { return false; } else if ((reRef < static_cast<double>(min) && val.real() != min) || (imRef < static_cast<double>(min) && val.imag() != min)) { return false; } else if (static_cast<RealType>(reRef) != val.real() || static_cast<RealType>(imRef) != val.imag()) { return false; } ++it; ++itRef; } return true; } template <class ImageType> bool CompareVectorComplex(const ImageRefType::Pointer imageRef, const ImageType* im) { typedef typename ImageType::InternalPixelType ComplexType; typedef typename ComplexType::value_type RealType; RealType min = std::numeric_limits<RealType>::lowest(); RealType max = std::numeric_limits<RealType>::max(); auto itRef = itk::ImageRegionConstIterator<ImageRefType>(imageRef, imageRef->GetLargestPossibleRegion()); auto it = itk::ImageRegionConstIterator<ImageType>(im, im->GetLargestPossibleRegion()); itRef.GoToBegin(); it.GoToBegin(); unsigned int nbChanel = im->GetNumberOfComponentsPerPixel(); ComplexType val; float reRef, imRef; while (!it.IsAtEnd()) { for (unsigned int i = 0; i < nbChanel; i++) { val = it.Get()[i]; reRef = itRef.Get()[2 * i]; imRef = itRef.Get()[2 * i + 1]; if ((reRef > static_cast<double>(max) && val.real() != max) || (imRef > static_cast<double>(max) && val.imag() != max)) { return false; } else if ((reRef < static_cast<double>(min) && val.real() != min) || (imRef < static_cast<double>(min) && val.imag() != min)) { return false; } else if (static_cast<RealType>(reRef) != val.real() || static_cast<RealType>(imRef) != val.imag()) { return false; } } ++it; ++itRef; } return true; } template <class ImageType> bool CompareArrayComplex(const ImageRefType::Pointer imageRef, const ImageType* im) { typedef typename ImageType::PixelType ArrayType; typedef typename ArrayType::ValueType ComplexType; typedef typename ComplexType::value_type RealType; RealType min = std::numeric_limits<RealType>::lowest(); RealType max = std::numeric_limits<RealType>::max(); auto itRef = itk::ImageRegionConstIterator<ImageRefType>(imageRef, imageRef->GetLargestPossibleRegion()); auto it = itk::ImageRegionConstIterator<ImageType>(im, im->GetLargestPossibleRegion()); itRef.GoToBegin(); it.GoToBegin(); unsigned int nbChanel = im->GetNumberOfComponentsPerPixel(); ComplexType val; float reRef, imRef; while (!it.IsAtEnd()) { for (unsigned int i = 0; i < nbChanel; i++) { val = it.Get()[i]; reRef = itRef.Get()[2 * i]; imRef = itRef.Get()[2 * i + 1]; if ((reRef > static_cast<double>(max) && val.real() != max) || (imRef > static_cast<double>(max) && val.imag() != max)) { return false; } else if ((reRef < static_cast<double>(min) && val.real() != min) || (imRef < static_cast<double>(min) && val.imag() != min)) { return false; } else if (static_cast<RealType>(reRef) != val.real() || static_cast<RealType>(imRef) != val.imag()) { return false; } } ++it; ++itRef; } return true; } int otbClampImageFilterConversionTest(int itkNotUsed(argc), char* argv[]) { typedef otb::ImageFileReader<ImageRefType> ReaderType; ReaderType::Pointer reader(ReaderType::New()); reader->SetFileName(argv[1]); reader->Update(); ImageRefType::Pointer imageRef = reader->GetOutput(); // vect<real> --> vect<real> otb::VectorImage<short>::Pointer image0 = Cross<otb::VectorImage<double>, otb::VectorImage<short>>(argv[1]); bool test0 = CompareVectorReal<otb::VectorImage<short>>(imageRef, image0); std::cout << "Test 0 : " << test0 << std::endl; image0 = nullptr; // vect<real> --> vect<complex> otb::VectorImage<std::complex<unsigned short>>::Pointer image1 = Cross<otb::VectorImage<float>, otb::VectorImage<std::complex<unsigned short>>>(argv[1]); bool test1 = CompareVectorComplex<otb::VectorImage<std::complex<unsigned short>>>(imageRef, image1); std::cout << "Test 1 : " << test1 << std::endl; image1 = nullptr; // vect<real> --> image<real> otb::Image<int>::Pointer image2 = Cross<otb::VectorImage<float>, otb::Image<int>>(argv[1]); bool test2 = CompareImageReal<otb::Image<int>>(imageRef, image2); std::cout << "Test 2 : " << test2 << std::endl; image2 = nullptr; // vect<real> --> image<complex> otb::Image<std::complex<float>>::Pointer image3 = Cross<otb::VectorImage<float>, otb::Image<std::complex<float>>>(argv[1]); bool test3 = CompareImageComplex<otb::Image<std::complex<float>>>(imageRef, image3); std::cout << "Test 3 : " << test3 << std::endl; image3 = nullptr; // image<real> --> image<real> otb::Image<unsigned short>::Pointer image4 = Cross<otb::Image<itk::FixedArray<double, 4>>, otb::Image<unsigned short>>(argv[1]); bool test4 = CompareImageReal<otb::Image<unsigned short>>(imageRef, image4); std::cout << "Test 4 : " << test4 << std::endl; image4 = nullptr; // image<real> --> image<complex> otb::Image<std::complex<int>>::Pointer image5 = Cross<otb::Image<itk::FixedArray<double, 4>>, otb::Image<std::complex<int>>>(argv[1]); bool test5 = CompareImageComplex<otb::Image<std::complex<int>>>(imageRef, image5); std::cout << "Test 5 : " << test5 << std::endl; image5 = nullptr; // image<real> --> vector<real> otb::VectorImage<float>::Pointer image6 = Cross<otb::Image<itk::FixedArray<double, 4>>, otb::VectorImage<float>>(argv[1]); bool test6 = CompareVectorReal<otb::VectorImage<float>>(imageRef, image6); std::cout << "Test 6 : " << test6 << std::endl; image6 = nullptr; // image<real> --> vector<complex> otb::VectorImage<std::complex<float>>::Pointer image7 = Cross<otb::Image<itk::FixedArray<double, 4>>, otb::VectorImage<std::complex<float>>>(argv[1]); bool test7 = CompareVectorComplex<otb::VectorImage<std::complex<float>>>(imageRef, image7); std::cout << "Test 7 : " << test7 << std::endl; // vector<complex> --> vector<real> otb::VectorImage<int>::Pointer image8 = Cross<otb::VectorImage<int>>(image7); bool test8 = CompareVectorReal<otb::VectorImage<int>>(imageRef, image8); std::cout << "Test 8 : " << test8 << std::endl; image8 = nullptr; // vector<complex> --> vector<complex> otb::VectorImage<std::complex<int>>::Pointer image9 = Cross<otb::VectorImage<std::complex<int>>>(image7); bool test9 = CompareVectorComplex<otb::VectorImage<std::complex<int>>>(imageRef, image9); std::cout << "Test 9 : " << test9 << std::endl; image9 = nullptr; // vector<complex> --> image<real> otb::Image<int>::Pointer image10 = Cross<otb::Image<int>>(image7); bool test10 = CompareImageReal<otb::Image<int>>(imageRef, image10); std::cout << "Test 10 : " << test10 << std::endl; image10 = nullptr; // vector<complex> --> image<complex> otb::Image<std::complex<unsigned short>>::Pointer image11 = Cross<otb::Image<std::complex<unsigned short>>>(image7); bool test11 = CompareImageComplex<otb::Image<std::complex<unsigned short>>>(imageRef, image11); std::cout << "Test 11 : " << test11 << std::endl; image11 = nullptr; // image<complex> --> vector<complex> otb::VectorImage<std::complex<float>>::Pointer image12 = Cross<otb::Image<std::complex<float>>, otb::VectorImage<std::complex<float>>>(argv[1]); bool test12 = CompareVectorComplex<otb::VectorImage<std::complex<float>>>(imageRef, image12); std::cout << "Test 12 : " << test12 << std::endl; image12 = nullptr; // image<complex> --> image<complex> otb::Image<std::complex<short>>::Pointer image13 = Cross<otb::Image<std::complex<float>>, otb::Image<std::complex<short>>>(argv[1]); bool test13 = CompareImageComplex<otb::Image<std::complex<short>>>(imageRef, image13); std::cout << "Test 13 : " << test13 << std::endl; image13 = nullptr; // image<complex> --> image<real> otb::Image<int>::Pointer image14 = Cross<otb::Image<std::complex<float>>, otb::Image<int>>(argv[1]); bool test14 = CompareImageReal<otb::Image<int>>(imageRef, image14); std::cout << "Test 14 : " << test14 << std::endl; image14 = nullptr; // image<complex> --> vector<real> otb::VectorImage<unsigned short>::Pointer image15 = Cross<otb::Image<std::complex<float>>, otb::VectorImage<unsigned short>>(argv[1]); bool test15 = CompareVectorReal<otb::VectorImage<unsigned short>>(imageRef, image15); std::cout << "Test 15 : " << test15 << std::endl; image15 = nullptr; // image<fixedarray<real>> --> image<fixedarray<complex>> otb::Image<itk::FixedArray<std::complex<float>, 2>>::Pointer image16 = Cross<otb::Image<itk::FixedArray<double, 4>>, otb::Image<itk::FixedArray<std::complex<float>, 2>>>(argv[1]); bool test16 = CompareArrayComplex<otb::Image<itk::FixedArray<std::complex<float>, 2>>>(imageRef, image16); std::cout << "Test 16 : " << test16 << std::endl; // image<fixedarray<complex>> --> vectorimage<real> otb::VectorImage<int>::Pointer image17 = Cross<otb::VectorImage<int>>(image16); bool test17 = CompareVectorReal<otb::VectorImage<int>>(imageRef, image17); std::cout << "Test 17 : " << test17 << std::endl; image17 = nullptr; // vector<real> --> image<fixedarray<complex>> otb::Image<itk::FixedArray<std::complex<float>, 2>>::Pointer image18 = Cross<otb::VectorImage<int>, otb::Image<itk::FixedArray<std::complex<float>, 2>>>(argv[1]); bool test18 = CompareArrayComplex<otb::Image<itk::FixedArray<std::complex<float>, 2>>>(imageRef, image18); image18 = nullptr; std::cout << "Test 18 : " << test18 << std::endl; if (test1 && test2 && test3 && test4 && test5 && test6 && test7 && test8 && test9 && test10 && test11 && test12 && test13 && test14 && test15 && test16 && test17 && test18) return EXIT_SUCCESS; return EXIT_FAILURE; }
40.227907
156
0.636548
[ "vector" ]
79a9dde8680a4b10d53c128265686d42c4c93ac5
771
cpp
C++
vox.render/physics/static_collider.cpp
SummerTree/DigitalVox4
2eb718abcaccc4cd1dde3b0f28090c197c1905d4
[ "MIT" ]
6
2022-01-23T04:58:50.000Z
2022-03-16T06:11:38.000Z
vox.render/physics/static_collider.cpp
SummerTree/DigitalVox4
2eb718abcaccc4cd1dde3b0f28090c197c1905d4
[ "MIT" ]
null
null
null
vox.render/physics/static_collider.cpp
SummerTree/DigitalVox4
2eb718abcaccc4cd1dde3b0f28090c197c1905d4
[ "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 "static_collider.h" #include "physics_manager.h" #include "../entity.h" namespace vox { namespace physics { StaticCollider::StaticCollider(Entity *entity) : Collider(entity) { const auto &p = entity->transform->worldPosition(); auto q = entity->transform->worldRotationQuaternion(); q.normalize(); _nativeActor = PhysicsManager::_nativePhysics()->createRigidStatic(PxTransform(PxVec3(p.x, p.y, p.z), PxQuat(q.x, q.y, q.z, q.w))); } } }
30.84
112
0.636835
[ "transform" ]
79aaf7565c4e3bca1b504934f25a1fd2f34e649d
2,940
cpp
C++
physicalrobots/calibration/main.cpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
physicalrobots/calibration/main.cpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
physicalrobots/calibration/main.cpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
#include <string> #include "calibration.h" #include "image-capture.h" #include "stereo-calibration.h" int main(const int _argc, const char* _argv[]) { const std::string instructions = "To create a good camera calibration, " "position a checkerboard target at various points in the field of view and " "take a calibration image with space. Try to get a uniform coverage of the " "view space from both a near (about 2ft) and a far (about 6ft) distance."; #if 1 // This version is for a single camera. // Ensure we got the right number of parameters. if(_argc != 5 and _argc != 6) { std::cerr << "usage: calibrate <camera index> <squares wide> <squares high> " << "<square size> [output xml filename]" << std::endl; std::exit(-1); } std::cout << instructions << std::endl; // Extract command-line parameters. const size_t camera_index = std::stoul(_argv[1]), squares_wide = std::stoul(_argv[2]), squares_high = std::stoul(_argv[3]); const double square_size = std::stod(_argv[4]); // Capture a set of calibration images. std::vector<cv::Mat> calibration_images = capture_images(camera_index); // Perform auto calibration. camera_calibration cal(calibration_images, squares_wide, squares_high, square_size); // If output was requested, generate it now. const std::string output_file = _argc == 6 ? _argv[5] : "calibration.xml"; cal.write_xml(output_file); #else // This version is for a stereo rig. // Ensure we got the right number of parameters. if(_argc != 6 and _argc != 7) { std::cerr << "usage: calibrate <camera 1 index> <camera 2 index> " << "<squares wide> <squares high> " << "<square size> [output xml filename]" << std::endl; std::exit(-1); } std::cout << instructions << std::endl; // Extract command-line parameters. const size_t camera_1_index = std::stoul(_argv[1]), camera_2_index = std::stoul(_argv[2]), squares_wide = std::stoul(_argv[3]), squares_high = std::stoul(_argv[4]); const double square_size = std::stod(_argv[5]); // Calibrate each camera. auto images_1 = capture_images(camera_1_index); auto images_2 = capture_images(camera_2_index); auto cal1 = camera_calibration(images_1, squares_wide, squares_high, square_size); auto cal2 = camera_calibration(images_2, squares_wide, squares_high, square_size); cal1.write_xml("cam1.xml"); cal2.write_xml("cam2.xml"); // Calibrate the rig. // Capture a set of calibration images. auto calibration_images = capture_images({camera_1_index, camera_2_index}); // Perform auto calibration. stereo_calibration cal(cal1, cal2, calibration_images[0], calibration_images[1], squares_wide, squares_high, square_size); cal.compute_rectify_maps(); cal.write_xml("rig.xml"); #endif }
31.276596
81
0.662585
[ "vector" ]
79ab36a7e2eed13fc1710f7b0f8ea773c6a63073
1,384
cpp
C++
leetcode.com/0015 3Sum/better.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0015 3Sum/better.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0015 3Sum/better.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { std::vector<vector<int>> result; if (nums.empty()) { return result; } std::size_t n_size = nums.size(); std::sort(nums.begin(), nums.end()); for (int i = 0; i < n_size; ++i) { // all numbers from now on will be greater than 0, no point in continuing if (nums[i] > 0) break; // we have seen this number & combo before; skip if (i > 0 and nums[i] == nums[i-1]) continue; int left = i+1, right = n_size - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum < 0) { ++left; } else if (sum > 0) { --right; } else { result.push_back({nums[i], nums[left], nums[right]}); int last_left = nums[left], last_right = nums[right]; // we have seen this number & combo before; skip while (left < right && nums[left] == last_left) ++left; while (left < right && nums[right] == last_right) --right; } } } return result; } };
31.454545
85
0.464595
[ "vector" ]
79acd95daf34ea6aaeac3db92721b3d5d0b529f4
943
cpp
C++
Dataset/Leetcode/test/78/167.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/test/78/167.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/test/78/167.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> XXX(vector<int>& nums) { if(nums.empty()) return vector<vector<int>>(); vector<vector<int>> ans; vector<vector<int>> signal; vector<int> temp; int length = nums.size(); traceback(0, signal, temp, length); for(int i = 0; i < signal.size(); i++) { temp.clear(); for(int j = 0; j < nums.size(); j++) { if(signal[i][j]) temp.push_back(nums[j]); } ans.push_back(temp); } return ans; } void traceback(int cur_level, vector<vector<int>>& signal, vector<int>& temp, int length) { if(cur_level == length) { signal.push_back(temp); return; } for(int i = 0; i < 2; i++) { temp.push_back(i); traceback(cur_level + 1, signal, temp, length); temp.pop_back(); } } };
28.575758
95
0.486744
[ "vector" ]
79b058f89fe7127537619e59882148b03b629308
1,035
hpp
C++
cpp/Autogarden/tests/utils/suites/iterable_test_suite.hpp
e-dang/Autogarden
b15217e5d4755fc028b8dc4255cbdcb77ead80f4
[ "MIT" ]
null
null
null
cpp/Autogarden/tests/utils/suites/iterable_test_suite.hpp
e-dang/Autogarden
b15217e5d4755fc028b8dc4255cbdcb77ead80f4
[ "MIT" ]
null
null
null
cpp/Autogarden/tests/utils/suites/iterable_test_suite.hpp
e-dang/Autogarden
b15217e5d4755fc028b8dc4255cbdcb77ead80f4
[ "MIT" ]
null
null
null
#pragma once #include <gmock/gmock.h> #include <gtest/gtest.h> #include <mocks/mock_terminal.hpp> #include <pins/terminal_pinset.hpp> using namespace ::testing; template <typename T> class PinSetTestSuite : public Test { protected: const int size = 5; std::vector<MockTerminalPin*> mockPins; std::vector<std::unique_ptr<ITerminalPin>> pinPtrs; std::unique_ptr<T> pinSet; void SetUp() { for (int i = 0; i < size; i++) { mockPins.push_back(new MockTerminalPin()); pinPtrs.emplace_back(mockPins[i]); } pinSet = std::make_unique<T>(std::move(pinPtrs)); } }; TYPED_TEST_SUITE_P(PinSetTestSuite); TYPED_TEST_P(PinSetTestSuite, at) { for (int i = 0; i < this->size; i++) { EXPECT_EQ(this->pinSet->at(i), this->mockPins[i]); } } TYPED_TEST_P(PinSetTestSuite, iterator) { auto i = 0; for (auto& pin : *(this->pinSet)) { EXPECT_EQ(pin.get(), this->mockPins[i++]); } } REGISTER_TYPED_TEST_SUITE_P(PinSetTestSuite, at, iterator);
23.522727
59
0.64058
[ "vector" ]
79b4d764ee97a28883e4857b4519545b219dd135
1,233
cpp
C++
Project_Euler/7/7.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
Project_Euler/7/7.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
Project_Euler/7/7.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int prime(int n, vector <int> &primes){ int len = primes.size(); if(n<=len){ return primes[n-1]; } else{ for(int i = primes[len-1] + 2 ; ;i=i+2){ int isprime=1; for(int j = 0 ; j < len ; j++){ if(i%primes[j]==0){ isprime = 0; break; } } if(isprime==1){ primes.push_back(i); return prime(n,primes); } } } } int main(){ vector <int> primes; primes.push_back(2); primes.push_back(3); int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ int n; cin >> n; cout << prime(n,primes) << endl; } return 0; }
19.265625
48
0.485807
[ "vector" ]
79b7b3a536a78b2e4dca868c8354608a2aec3dc4
3,002
cc
C++
Common/TestDyExpr/Source/TestTZip.cc
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
4
2019-03-17T19:46:54.000Z
2019-12-09T20:11:01.000Z
Common/TestDyExpr/Source/TestTZip.cc
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
null
null
null
Common/TestDyExpr/Source/TestTZip.cc
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
null
null
null
/// /// MIT License /// Copyright (c) 2018-2019 Jongmin Yun /// /// 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 <Catch2/catch.hpp> #include <Expr/TZip.h> #include <array> #include <string> namespace dy::expr { TEST_CASE("TZip helper test", "[TZip]" ) { SECTION("TZip initialization") { int value[5] = {1, 2, 3, 4, 5}; float value2[5] = {2.f, 3.f, 5.f, 7.f, 11.f}; auto zip = Zip(value, value2); auto& vvv = zip.GetItem<0>(); for (auto& item : vvv) { item += 10; } const int value3[5] = {11, 12, 13, 14, 15}; for (std::size_t va = 0; va < 5; ++va) { REQUIRE(value[va] == value3[va]); } auto [fff, eee] = zip[0]; REQUIRE(*fff == 11); REQUIRE(*eee == 2.f); } SECTION("TZip begin, end and ranged for loop") { int value[5] = {11, 12, 13, 14, 15}; float value2[5] = {2.f, 3.f, 5.f, 7.f, 11.f}; auto zip = Zip(value, value2); std::array<std::pair<int, float>, 5> result = { std::pair<int, float>{11, 2.f}, std::pair<int, float>{12, 3.f}, std::pair{13, 5.f}, std::pair{14, 7.f}, std::pair{15, 11.f}, }; int i = 0; for (auto it = zip.begin(); it != zip.end(); ++it) { const auto [lhs, rhs] = *it; REQUIRE(*lhs == result[i].first); REQUIRE(*rhs == result[i].second); ++i; } i = 0; for (auto& [lhs, rhs] : zip) { REQUIRE(*lhs == result[i].first); REQUIRE(*rhs == result[i].second); ++i; } } SECTION("TZip begin, end and ranged for loop") { int value[5] = {11, 12, 13, 14, 15}; float value2[5] = {2.f, 3.f, 5.f, 7.f, 11.f}; std::vector<std::string> value3 = {"Hello", "World", "My", "Name", "Neu."}; auto zip = Zip(value, value2, value3); std::array<std::tuple<int, float, std::string>, 5> result = { std::tuple{11, 2.f, "Hello"}, {12, 3.f, "World"}, {13, 5.f, "My"}, {14, 7.f, "Name"}, {15, 11.f, "Neu."}, }; int i = 0; for (auto it = zip.cbegin(); it != zip.cend(); ++it) { auto& [lhs, rhs, str] = *it; REQUIRE(*lhs == std::get<0>(result[i])); REQUIRE(*rhs == std::get<1>(result[i])); REQUIRE(*str == std::get<2>(result[i])); ++i; } i = 0; for (const auto& [lhs, rhs, str] : Zip(value, value2, value3)) { REQUIRE(*lhs == std::get<0>(result[i])); REQUIRE(*rhs == std::get<1>(result[i])); REQUIRE(*str == std::get<2>(result[i])); ++i; } } } } /// ::dy::expr namespace
25.226891
81
0.528648
[ "vector" ]
79bcd5aeb22a0341251c4e9a88c10a24d3931e52
1,131
cpp
C++
leetcode/october-challenge/week-4/132-Pattern.cpp
joaquinmd93/competitive-programming
681424abd777cc0a3059e1ee66ae2cee958178da
[ "MIT" ]
1
2020-10-08T19:28:40.000Z
2020-10-08T19:28:40.000Z
leetcode/october-challenge/week-4/132-Pattern.cpp
joaquinmd93/competitive-programming
681424abd777cc0a3059e1ee66ae2cee958178da
[ "MIT" ]
null
null
null
leetcode/october-challenge/week-4/132-Pattern.cpp
joaquinmd93/competitive-programming
681424abd777cc0a3059e1ee66ae2cee958178da
[ "MIT" ]
1
2020-10-24T02:32:27.000Z
2020-10-24T02:32:27.000Z
class Solution { public: bool find132pattern(vector<int>& nums) { int n = nums.size(); // Edge cases? if (n == 1) return false; if (n == 2) return false; // Get minimum from left to right vector<int> minLeft(n); for (int i = 0; i < n; ++i) { if (i == 0) minLeft[i] = nums[i]; else minLeft[i] = min(minLeft[i-1], nums[i]); } // Get minimum from right to left, conditional of being above minLeft[i-1] // Store the minimum (usefull) element at the top of the stack stack<int> minRight; for (int i = n-1; i >= 1; --i) { if (nums[i] >= minLeft[i-1]) { while (!minRight.empty() && minRight.top() <= minLeft[i-1]) minRight.pop(); if (!minRight.empty() && minRight.top() < nums[i]) return true; else minRight.push(nums[i]); } } return false; } };
29.763158
82
0.415561
[ "vector" ]
79c1e7618cdc8fe21f3b28e53ec25f9b80228cc9
14,626
cc
C++
components/assist_ranker/example_preprocessing_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/assist_ranker/example_preprocessing_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/assist_ranker/example_preprocessing_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/assist_ranker/example_preprocessing.h" #include "base/strings/string_number_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/protobuf/src/google/protobuf/map.h" #include "third_party/protobuf/src/google/protobuf/repeated_field.h" namespace assist_ranker { namespace { using ::google::protobuf::Map; using ::google::protobuf::RepeatedField; void EXPECT_EQUALS_EXAMPLE(const RankerExample& example1, const RankerExample& example2) { EXPECT_EQ(example1.features_size(), example2.features_size()); for (const auto& pair : example1.features()) { const Feature& feature1 = pair.second; const Feature& feature2 = example2.features().at(pair.first); EXPECT_EQ(feature1.feature_type_case(), feature2.feature_type_case()); EXPECT_EQ(feature1.bool_value(), feature2.bool_value()); EXPECT_EQ(feature1.int32_value(), feature2.int32_value()); EXPECT_EQ(feature1.float_value(), feature2.float_value()); EXPECT_EQ(feature1.string_value(), feature2.string_value()); EXPECT_EQ(feature1.string_list().string_value_size(), feature2.string_list().string_value_size()); for (int i = 0; i < feature1.string_list().string_value_size(); ++i) { EXPECT_EQ(feature1.string_list().string_value(i), feature2.string_list().string_value(i)); } } } } // namespace class ExamplePreprocessorTest : public ::testing::Test { protected: void SetUp() override { auto& features = *example_.mutable_features(); features[bool_name_].set_bool_value(bool_value_); features[int32_name_].set_int32_value(int32_value_); features[float_name_].set_float_value(float_value_); features[one_hot_name_].set_string_value(one_hot_value_); *features[sparse_name_].mutable_string_list()->mutable_string_value() = { sparse_values_.begin(), sparse_values_.end()}; } RankerExample example_; const std::string bool_name_ = "bool_feature"; const bool bool_value_ = true; const std::string int32_name_ = "int32_feature"; const int int32_value_ = 2; const std::string float_name_ = "float_feature"; const float float_value_ = 3.0; const std::string one_hot_name_ = "one_hot_feature"; const std::string elem1_ = "elem1"; const std::string elem2_ = "elem2"; const std::string one_hot_value_ = elem1_; const std::string sparse_name_ = "sparse_feature"; const std::vector<std::string> sparse_values_ = {elem1_, elem2_}; }; TEST_F(ExamplePreprocessorTest, AddMissingFeatures) { RankerExample expected = example_; ExamplePreprocessorConfig config; // Adding missing feature label to an existing feature has no effect. config.add_missing_features(bool_name_); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kSuccess); EXPECT_EQUALS_EXAMPLE(example_, expected); config.Clear(); // Adding missing feature label to non-existing feature returns a // "_MissingFeature" feature with a list of feature names. const std::string foo = "foo"; config.add_missing_features(foo); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kSuccess); (*expected .mutable_features())[ExamplePreprocessor::kMissingFeatureDefaultName] .mutable_string_list() ->add_string_value(foo); EXPECT_EQUALS_EXAMPLE(example_, expected); config.Clear(); } TEST_F(ExamplePreprocessorTest, AddBucketizeFeatures) { RankerExample expected = example_; ExamplePreprocessorConfig config; Map<std::string, ExamplePreprocessorConfig::Boundaries>& bucketizers = *config.mutable_bucketizers(); // Adding bucketized feature to non-existing feature returns the same example. const std::string foo = "foo"; bucketizers[foo].add_boundaries(0.5); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kSuccess); EXPECT_EQUALS_EXAMPLE(example_, expected); config.Clear(); // Bucketizing a bool feature returns same proto. bucketizers[bool_name_].add_boundaries(0.5); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kNonbucketizableFeatureType); EXPECT_EQUALS_EXAMPLE(example_, expected); config.Clear(); // Bucketizing a string feature returns same proto. bucketizers[one_hot_name_].add_boundaries(0.5); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kNonbucketizableFeatureType); EXPECT_EQUALS_EXAMPLE(example_, expected); config.Clear(); // Bucketizing an int32 feature with 3 boundary. bucketizers[int32_name_].add_boundaries(int32_value_ - 2); bucketizers[int32_name_].add_boundaries(int32_value_ - 1); bucketizers[int32_name_].add_boundaries(int32_value_ + 1); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kSuccess); (*expected.mutable_features())[int32_name_].set_string_value("2"); EXPECT_EQUALS_EXAMPLE(example_, expected); config.Clear(); // Bucketizing a float feature with 3 boundary. bucketizers[float_name_].add_boundaries(float_value_ - 0.2); bucketizers[float_name_].add_boundaries(float_value_ - 0.1); bucketizers[float_name_].add_boundaries(float_value_ + 0.1); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kSuccess); (*expected.mutable_features())[float_name_].set_string_value("2"); EXPECT_EQUALS_EXAMPLE(example_, expected); config.Clear(); // Bucketizing a float feature with value equal to a boundary. (*example_.mutable_features())[float_name_].set_float_value(float_value_); bucketizers[float_name_].add_boundaries(float_value_ - 0.2); bucketizers[float_name_].add_boundaries(float_value_ - 0.1); bucketizers[float_name_].add_boundaries(float_value_); bucketizers[float_name_].add_boundaries(float_value_ + 0.1); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kSuccess); (*expected.mutable_features())[float_name_].set_string_value("3"); EXPECT_EQUALS_EXAMPLE(example_, expected); config.Clear(); } // Tests normalization of float and int32 features. TEST_F(ExamplePreprocessorTest, NormalizeFeatures) { RankerExample expected = example_; ExamplePreprocessorConfig config; Map<std::string, float>& normalizers = *config.mutable_normalizers(); normalizers[int32_name_] = int32_value_ - 1.0f; normalizers[float_name_] = float_value_ + 1.0f; (*expected.mutable_features())[int32_name_].set_float_value(1.0f); (*expected.mutable_features())[float_name_].set_float_value( float_value_ / (float_value_ + 1.0f)); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kSuccess); EXPECT_EQUALS_EXAMPLE(example_, expected); // Zero normalizer returns an error. normalizers[float_name_] = 0.0f; EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kNormalizerIsZero); } // Zero normalizer returns an error. TEST_F(ExamplePreprocessorTest, ZeroNormalizerReturnsError) { ExamplePreprocessorConfig config; (*config.mutable_normalizers())[float_name_] = 0.0f; EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kNormalizerIsZero); } // Tests converts a bool or int32 feature to a string feature. TEST_F(ExamplePreprocessorTest, ConvertToStringFeatures) { RankerExample expected = example_; ExamplePreprocessorConfig config; auto& features_list = *config.mutable_convert_to_string_features(); *features_list.Add() = bool_name_; *features_list.Add() = int32_name_; *features_list.Add() = one_hot_name_; EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kSuccess); (*expected.mutable_features())[bool_name_].set_string_value( base::NumberToString(static_cast<int>(bool_value_))); (*expected.mutable_features())[int32_name_].set_string_value( base::NumberToString(int32_value_)); EXPECT_EQUALS_EXAMPLE(example_, expected); } // Float features can't be convert to string features. TEST_F(ExamplePreprocessorTest, ConvertFloatFeatureToStringFeatureReturnsError) { ExamplePreprocessorConfig config; config.add_convert_to_string_features(float_name_); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_), ExamplePreprocessor::kNonConvertibleToStringFeatureType); } TEST_F(ExamplePreprocessorTest, Vectorization) { ExamplePreprocessorConfig config; Map<std::string, int32_t>& feature_indices = *config.mutable_feature_indices(); RankerExample example_vec_expected = example_; RepeatedField<float>& feature_vector = *(*example_vec_expected.mutable_features()) [ExamplePreprocessor::kVectorizedFeatureDefaultName] .mutable_float_list() ->mutable_float_value(); // bool feature puts the value to the corresponding place. feature_indices[bool_name_] = 0; feature_vector.Add(1.0); // int32 feature puts the value to the corresponding place. feature_indices[int32_name_] = 1; feature_vector.Add(int32_value_); // float feature puts the value to the corresponding place. feature_indices[float_name_] = 2; feature_vector.Add(float_value_); // string value is vectorized as 1.0. feature_indices[ExamplePreprocessor::FeatureFullname(one_hot_name_, one_hot_value_)] = 3; feature_vector.Add(1.0); // string list value is vectorized as 1.0. feature_indices[ExamplePreprocessor::FeatureFullname(sparse_name_, elem1_)] = 4; feature_indices[ExamplePreprocessor::FeatureFullname(sparse_name_, elem2_)] = 5; feature_vector.Add(1.0); feature_vector.Add(1.0); // string list value with element not in the example sets the corresponding // place as 0.0; feature_indices[ExamplePreprocessor::FeatureFullname(sparse_name_, "foo")] = 5; feature_vector.Add(0.0); // Non-existing feature puts 0 to the corresponding place. feature_indices["bar"] = 6; feature_vector.Add(0.0); // Verify the propressing result. RankerExample example = example_; EXPECT_EQ(ExamplePreprocessor::Process(config, &example), ExamplePreprocessor::kSuccess); EXPECT_EQUALS_EXAMPLE(example, example_vec_expected); // Example with extra numeric feature gets kNoFeatureIndexFound error; RankerExample example_with_extra_numeric = example_; (*example_with_extra_numeric.mutable_features())["foo"].set_float_value(1.0); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_with_extra_numeric), ExamplePreprocessor::ExamplePreprocessor::kNoFeatureIndexFound); // Example with extra one-hot feature gets kNoFeatureIndexFound error; RankerExample example_with_extra_one_hot = example_; (*example_with_extra_one_hot.mutable_features())["foo"].set_string_value( "bar"); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_with_extra_one_hot), ExamplePreprocessor::ExamplePreprocessor::kNoFeatureIndexFound); // Example with extra sparse feature value gets kNoFeatureIndexFound error; RankerExample example_with_extra_sparse = example_; (*example_with_extra_sparse.mutable_features())[sparse_name_] .mutable_string_list() ->add_string_value("bar"); EXPECT_EQ(ExamplePreprocessor::Process(config, &example_with_extra_sparse), ExamplePreprocessor::ExamplePreprocessor::kNoFeatureIndexFound); } TEST_F(ExamplePreprocessorTest, MultipleErrorCode) { ExamplePreprocessorConfig config; (*config.mutable_feature_indices())[int32_name_] = 0; (*config.mutable_feature_indices())[float_name_] = 1; (*config.mutable_bucketizers())[one_hot_name_].add_boundaries(0.5); RankerExample example_vec_expected = example_; RepeatedField<float>& feature_vector = *(*example_vec_expected.mutable_features()) [ExamplePreprocessor::kVectorizedFeatureDefaultName] .mutable_float_list() ->mutable_float_value(); feature_vector.Add(int32_value_); feature_vector.Add(float_value_); const int error_code = ExamplePreprocessor::Process(config, &example_); // Error code contains features in example_ but not in feature_indices. EXPECT_TRUE(error_code & ExamplePreprocessor::kNoFeatureIndexFound); // Error code contains features that are not bucketizable. EXPECT_TRUE(error_code & ExamplePreprocessor::kNonbucketizableFeatureType); // No kInvalidFeatureType error. EXPECT_FALSE(error_code & ExamplePreprocessor::kInvalidFeatureType); // Only two elements is correctly vectorized. EXPECT_EQUALS_EXAMPLE(example_, example_vec_expected); } TEST_F(ExamplePreprocessorTest, ExampleFloatIterator) { RankerExample float_example; for (const auto& field : ExampleFloatIterator(example_)) { EXPECT_EQ(field.error, ExamplePreprocessor::kSuccess); (*float_example.mutable_features())[field.fullname].set_float_value( field.value); } RankerExample float_example_expected; auto& feature_map = *float_example_expected.mutable_features(); feature_map[bool_name_].set_float_value(bool_value_); feature_map[int32_name_].set_float_value(int32_value_); feature_map[float_name_].set_float_value(float_value_); feature_map[ExamplePreprocessor::FeatureFullname(one_hot_name_, one_hot_value_)] .set_float_value(1.0); feature_map[ExamplePreprocessor::FeatureFullname(sparse_name_, elem1_)] .set_float_value(1.0); feature_map[ExamplePreprocessor::FeatureFullname(sparse_name_, elem2_)] .set_float_value(1.0); EXPECT_EQUALS_EXAMPLE(float_example, float_example_expected); } TEST_F(ExamplePreprocessorTest, ExampleFloatIteratorError) { RankerExample example; example.mutable_features()->insert({"foo", Feature::default_instance()}); (*example.mutable_features())["bar"] .mutable_string_list() ->mutable_string_value(); int num_of_fields = 0; for (const auto& field : ExampleFloatIterator(example)) { if (field.fullname == "foo") { EXPECT_EQ(field.error, ExamplePreprocessor::kInvalidFeatureType); } if (field.fullname == "bar") { EXPECT_EQ(field.error, ExamplePreprocessor::kInvalidFeatureListIndex); } ++num_of_fields; } // Check the iterator indeed found the two fields. EXPECT_EQ(num_of_fields, 2); } } // namespace assist_ranker
40.740947
80
0.751333
[ "vector" ]
79ccb8e327602032a942feee3c3dd588b90daea6
1,417
cpp
C++
0054 - Spiral Matrix/cpp/main.cpp
xiaoswu/Leetcode
e4ae8b2f72a312ee247084457cf4e6dbcfd20e18
[ "MIT" ]
5
2018-10-18T06:47:19.000Z
2020-06-19T09:30:03.000Z
0054 - Spiral Matrix/cpp/main.cpp
xiaoswu/Leetcode
e4ae8b2f72a312ee247084457cf4e6dbcfd20e18
[ "MIT" ]
null
null
null
0054 - Spiral Matrix/cpp/main.cpp
xiaoswu/Leetcode
e4ae8b2f72a312ee247084457cf4e6dbcfd20e18
[ "MIT" ]
null
null
null
// // main.cpp // 54 - Spiral Matrix // // Created by ynfMac on 2019/12/2. // Copyright © 2019 ynfMac. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Solution { int R, C; int d[4][2] = {{0,1},{1,0},{0,-1},{-1,0}}; private: bool inArea(int x,int y){ return x >=0 && x < R && y >= 0 && y < C; } public: vector<int> spiralOrder(vector<vector<int>>& matrix) { R = matrix.size(); if (R == 0) { return vector<int>(); } C = matrix[0].size(); if (C == 0) { return vector<int>(); } vector<int> ans = vector<int>(); vector<vector<bool>> visited = vector<vector<bool>>(R,vector<bool>(C,false)); int r = 0, c = 0, di = 0; for (int i = 0; i < R * C; i++) { ans.push_back(matrix[r][c]); visited[r][c] = true; int cr = r + d[di][0]; int cc = c + d[di][1]; if (inArea(cr, cc) && !visited[cr][cc]) { r = cr; c = cc; } else { // di = (di + 1) % 4; r = r + d[di][0]; c = c + d[di][1]; } } return ans; } }; int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; return 0; }
24.016949
85
0.411433
[ "vector" ]
79ccf3b2e6b7ea968c206ea46062026c7f908cfe
2,516
cc
C++
cc/output/vulkan_renderer.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
cc/output/vulkan_renderer.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
cc/output/vulkan_renderer.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright (c) 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/output/vulkan_renderer.h" #include "cc/output/output_surface_frame.h" namespace cc { VulkanRenderer::~VulkanRenderer() {} void VulkanRenderer::SwapBuffers(std::vector<ui::LatencyInfo> latency_info) { OutputSurfaceFrame output_frame; output_frame.latency_info = std::move(latency_info); output_surface_->SwapBuffers(std::move(output_frame)); } VulkanRenderer::VulkanRenderer(const RendererSettings* settings, OutputSurface* output_surface, ResourceProvider* resource_provider, TextureMailboxDeleter* texture_mailbox_deleter, int highp_threshold_min) : DirectRenderer(settings, output_surface, resource_provider) {} void VulkanRenderer::DidChangeVisibility() { NOTIMPLEMENTED(); } void VulkanRenderer::BindFramebufferToOutputSurface(DrawingFrame* frame) { NOTIMPLEMENTED(); } bool VulkanRenderer::BindFramebufferToTexture(DrawingFrame* frame, const ScopedResource* resource) { NOTIMPLEMENTED(); return false; } void VulkanRenderer::SetScissorTestRect(const gfx::Rect& scissor_rect) { NOTIMPLEMENTED(); } void VulkanRenderer::PrepareSurfaceForPass( DrawingFrame* frame, SurfaceInitializationMode initialization_mode, const gfx::Rect& render_pass_scissor) { NOTIMPLEMENTED(); } void VulkanRenderer::DoDrawQuad(DrawingFrame* frame, const DrawQuad* quad, const gfx::QuadF* clip_region) { NOTIMPLEMENTED(); } void VulkanRenderer::BeginDrawingFrame(DrawingFrame* frame) { NOTIMPLEMENTED(); } void VulkanRenderer::FinishDrawingFrame(DrawingFrame* frame) { NOTIMPLEMENTED(); } void VulkanRenderer::FinishDrawingQuadList() { NOTIMPLEMENTED(); } bool VulkanRenderer::FlippedFramebuffer(const DrawingFrame* frame) const { NOTIMPLEMENTED(); return false; } void VulkanRenderer::EnsureScissorTestEnabled() { NOTIMPLEMENTED(); } void VulkanRenderer::EnsureScissorTestDisabled() { NOTIMPLEMENTED(); } void VulkanRenderer::CopyCurrentRenderPassToBitmap( DrawingFrame* frame, std::unique_ptr<CopyOutputRequest> request) { NOTIMPLEMENTED(); } bool VulkanRenderer::CanPartialSwap() { NOTIMPLEMENTED(); return false; } } // namespace cc
27.053763
79
0.707075
[ "vector" ]
79d3adbc5c81ccbdf247f67e9ab94d1435985a5f
2,502
cpp
C++
LeetCode/WordBreak2.cpp
Michael-Ma/Coding-Practice
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
[ "MIT" ]
null
null
null
LeetCode/WordBreak2.cpp
Michael-Ma/Coding-Practice
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
[ "MIT" ]
null
null
null
LeetCode/WordBreak2.cpp
Michael-Ma/Coding-Practice
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
[ "MIT" ]
null
null
null
#include <sstream> #include <stdio.h> #include <string> #include <cstring> #include <iostream> #include <vector> #include <map> #include <stack> #include <queue> #include <set> #include <cmath> #include <algorithm> #include <cfloat> #include <climits> #include <unordered_set> //#include <unordered_map> using namespace std; /* Time Complexity : O(n^2) Space Complexity : O(n) Trick: using DP to save previous result, to save some time! Special Cases : Summary: */ // Word Break class Solution { public: bool wordBreak(string s, unordered_set<string>& wordDict) { if(s.size()==0){ return true; } if(wordDict.size()==0){ return false; } bool isSegmentable[s.size()+1]; memset(isSegmentable, 0, sizeof(isSegmentable)); isSegmentable[0] = true; for(int i=0; i<s.size(); i++){ for(int j=i; j>=0; j--){ string tmp = s.substr(j, i-j+1); if(wordDict.find(tmp)!=wordDict.end() && isSegmentable[j]){ isSegmentable[i+1] = true; break; } } } return isSegmentable[s.size()]; } }; /* Time Complexity : O(n^2) Space Complexity : O(n^2) Trick: usint DP will need a lot of tmp storage, and more complex. It's better to use brute force here. Special Cases : Summary: */ // Word Break II class Solution2 { public: vector<string> wordBreak(string s, unordered_set<string>& wordDict) { vector<string> result; if(s.size()==0 || wordDict.size()==0){ return result; } getMatchedResult(s, wordDict, 0, "", result); return result; } void getMatchedResult(string& s, unordered_set<string>& wordDict, int start, string matched, vector<string>& result){ if(start == s.size()){ result.push_back(matched); return; } for(int i=start; i<s.size(); i++){ string tmp = s.substr(start, i-start+1); if(wordDict.find(tmp)!=wordDict.end()){ string newMatched = matched.size()>0 ? tmp:matched+" "+tmp; getMatchedResult(s, wordDict, i+1, newMatched, result); } } } }; int main(){ unordered_set<string> wordDict; wordDict.insert("a"); Solution test; cout<<test.wordBreak("a", wordDict)<<endl; }
23.828571
121
0.546763
[ "vector" ]
79d3af16a5541d695fd5dfd684cacf1338070ba2
2,949
hpp
C++
sources/cards/Card.hpp
angeluriot/Magic_royal
a337ce4ad6c3215bbdec8c376d6e88fe97f48f94
[ "MIT" ]
1
2022-02-02T21:41:59.000Z
2022-02-02T21:41:59.000Z
sources/cards/Card.hpp
angeluriot/Magic_royal
a337ce4ad6c3215bbdec8c376d6e88fe97f48f94
[ "MIT" ]
null
null
null
sources/cards/Card.hpp
angeluriot/Magic_royal
a337ce4ad6c3215bbdec8c376d6e88fe97f48f94
[ "MIT" ]
2
2022-02-01T12:59:57.000Z
2022-03-05T12:50:27.000Z
#ifndef CARD_HPP #define CARD_HPP #include <string> #include <map> #include <vector> #include "utils/PtrList.hpp" class Player; /** * @brief A class that represent a card. */ class Card { public: /** * @brief An enum that represent the card type. */ enum class Type { Creature, // Creature card. Land, // Land card. Spell // Spell card. }; /** * @brief An enum that represent the color of a card. */ enum class Color { Colorless, // Not a specific color. White, // White color. Blue, // Blue color. Black, // Black color. Red, // Red color. Green // Green color. }; typedef std::map<Card::Color, int> Cost; protected: Player* m_owner; // The owner of the card. bool m_engaged; // The engaged state of the card. public: /** * @brief Construct a new Card object. */ Card(); /** * @brief Construct a new Card object. * * @param other the card to copy */ Card(const Card& other) = default; /** * @brief Destroy the Card object. */ virtual ~Card(); /** * @brief Operator =. * * @param other the card to copy * @return a reference to the modified card */ Card& operator=(const Card& other) = default; /** * @brief Give the color of the card. * * @return the color of the card */ virtual Color get_color() const = 0; /** * @brief Give the type of the card. * * @return the type of the card */ virtual Type get_type() const = 0; /** * @brief Give the full type of the card. * * @return the full type of the card */ virtual std::string get_full_type() const = 0; /** * @brief Give the name of the card. * * @return the name of the card */ virtual std::string get_name() const = 0; /** * @brief Give the description of the card. * * @return the description of the card */ virtual std::string get_description() const = 0; /** * @brief Give the cost of the card. * * @return the cost of the card */ virtual Cost get_cost() const = 0; /** * @brief Set the owner of the card. * * @param player the new owner of the card */ virtual void set_owner(Player& player); /** * @brief Engage the card. */ virtual void engage(); /** * @brief Disengage the card. */ virtual void disengage(); /** * @brief Tell if the card is engaged. * * @return true if the card is engaged */ virtual bool is_engaged() const; /** * @brief Reset the card. */ virtual void reset(); /** * @brief Print the card. */ virtual void print() const; /** * @brief Clone the card. * * @return a pointer to the cloned card */ virtual Card* clone() const = 0; /** * @brief Give the cards from the card names. * * @param cards_string the list of card names * @return the list of cards */ static PtrList<Card> get_cards_from_string(const std::vector<std::string>& cards_string); /** * @brief All the cards of the game. */ static PtrList<Card> all_cards; }; #endif
17.046243
90
0.619193
[ "object", "vector" ]
79dc5566d90ab88a1d11d32ba29e1162fc9c3813
764
hpp
C++
Source/environment/cylinder_grid.hpp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
null
null
null
Source/environment/cylinder_grid.hpp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
null
null
null
Source/environment/cylinder_grid.hpp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
null
null
null
#pragma once #include <model/model.hpp> #include <object_types/imodelrender.hpp> #include <utilities/ShaderManager/shadermanager.hpp> class CylinderGrid : public IModelRender { public: CylinderGrid(); void Render(const glm::vec4& view_light_direction, const glm::mat4& view_matrix, const glm::mat4& projection_matrix); private: const int _num = 1000; const int _spread_distance = 1000; const int _line_radius = 500; oglplus::Program _program; std::unique_ptr<Model::Model> _model; oglplus::Uniform<oglplus::Vec4f> _view_light_direction_uniform; oglplus::Uniform<oglplus::Mat4f> _view_matrix_uniform; oglplus::Uniform<oglplus::Mat4f> _view_projection_matrix_uniform; oglplus::Buffer _line_positions; CylinderGrid(const CylinderGrid&) = delete; };
27.285714
118
0.787958
[ "render", "model" ]
076685812464a9f68a98709b535c91efa1a88437
13,170
cpp
C++
src/GLUL/GUI/Panel.cpp
RippeR37/GLUL
2e5cd72192d039d281c5df09a816901f6fea28f9
[ "MIT" ]
43
2015-09-15T18:07:23.000Z
2021-03-24T02:19:39.000Z
src/GLUL/GUI/Panel.cpp
RippeR37/Utility-Library
2e5cd72192d039d281c5df09a816901f6fea28f9
[ "MIT" ]
46
2015-01-09T18:03:40.000Z
2015-09-09T22:05:39.000Z
src/GLUL/GUI/Panel.cpp
RippeR37/GLUL
2e5cd72192d039d281c5df09a816901f6fea28f9
[ "MIT" ]
4
2017-01-27T21:35:44.000Z
2021-01-09T17:04:32.000Z
#include <GLUL/GL++/Context.h> #include <GLUL/GUI/Panel.h> #include <GLUL/GUI/Events/ValueChange.hpp> #include <iostream> namespace GLUL { namespace GUI { Panel::Panel(Container& parent, const glm::vec2& position, const glm::vec2& size) : Panel(&parent, position, size) { } Panel::Panel(Container& parent, const glm::vec2& position, const glm::vec2& size, const glm::vec2& totalSize) : Panel(&parent, position, size, totalSize) { } Panel::Panel(Container* const parent, const glm::vec2& position, const glm::vec2& size) : Panel(parent, position, size, size) { } Panel::Panel(Container* const parent, const glm::vec2& position, const glm::vec2& size, const glm::vec2& totalSize) : Container(nullptr), _glInitialized(false) { _initializeScrollbars(); bindTo(parent); setSize(size); setPosition(position); setTotalSize(totalSize); setBackgroundColor({ 0.0f, 0.0f, 0.0f, 0.1f }); setScrollbarsSize({ 12.0f, 12.0f }); setScrollbarsBackgroundColor({ 0.0f, 0.0f, 0.0f, 0.2f }); setScrollbarsHandleColor({ 0.0f, 0.0f, 0.0f, 0.2f }); setScrollbarsHandleSize({ 12.0f, 12.0f }); setScrollbarsBorder(1, 0, { 0.0f, 0.0f, 0.0f }); setScrollbarsHandleBorder(1, 0, { 0.0f, 0.0f, 0.0f }); } Panel::~Panel() { bindTo(nullptr); } void Panel::bindTo(Container& container) { bindTo(&container); } void Panel::bindTo(Container* container) { Container::bindTo(container); _scrollbarHorizontal.bindTo(container); _scrollbarVertical.bindTo(container); } const Panel& Panel::render() const { if(isVisible()) { if(!isValid()) validate(); getProgram().use(); _vao.bind(); _vao.drawArrays(); _vao.unbind(); getProgram().unbind(); } Container::render(); return *this; } Panel& Panel::update(double deltaTime) { if(!isValid()) validate(); Container::update(deltaTime); return *this; } const Panel& Panel::validate() const { Panel* thisConstless = const_cast<Panel*>(this); // (Re)build VBO GL::VertexBuffer::Data vertexData; std::vector<glm::vec4> vertices = getVertices(); vertexData.data = vertices.data(); vertexData.size = vertices.size() * sizeof(glm::vec4); vertexData.pointers.push_back(GL::VertexAttrib(0, 4, GL_FLOAT, sizeof(glm::vec4) * 2, nullptr)); vertexData.pointers.push_back(GL::VertexAttrib(1, 4, GL_FLOAT, sizeof(glm::vec4) * 2, sizeof(glm::vec4))); _vbo.bind(); thisConstless->_vbo.setUsage(GL::VertexBuffer::Usage::DynamicDraw); thisConstless->_vbo.setData(vertexData); _vbo.unbind(); // Set vertices draw count thisConstless->_vao.setDrawCount(vertices.size() / 2); // Initialize VAO if(_glInitialized == false) { thisConstless->_vao.setDrawTarget(GL::VertexArray::DrawTarget::Triangles); _vao.bind(); thisConstless->_vao.attachVBO(&_vbo); thisConstless->_vao.setAttribPointers(); _vao.unbind(); thisConstless->_glInitialized = true; } thisConstless->setValid(); return *this; } const glm::vec2 Panel::getScreenPosition() const { glm::vec2 scrPos = Container::getScreenPosition(); glm::vec2 offset = getOffset(); return scrPos - offset; } const glm::vec2 Panel::getOffset() const { return { _scrollbarHorizontal.getValue(), _scrollbarVertical.getMax() - _scrollbarVertical.getValue() }; } const glm::vec2& Panel::getTotalSize() const { return _totalSize; } const glm::vec4& Panel::getBackgroundColor() const { return _backgroundColor; } bool Panel::isHorizontalScrollbarVisible() const { return (getSize().x < getTotalSize().x); } bool Panel::isVerticalScrollbarVisible() const { return (getSize().y < getTotalSize().y); } const glm::vec2& Panel::getScrollbarsSize() const { return _scrollbarsSize; } const glm::vec2 Panel::getScrollbarsHandleSize() const { return _scrollbarHorizontal.getHandleSize(); } const glm::vec2 Panel::getScrollbarsLineSize() const { return _scrollbarHorizontal.getLineSize(); } const glm::vec4 Panel::getScrollbarsBackgroundColor() const { return _scrollbarHorizontal.getBackgroundColor(); } const glm::vec4 Panel::getScrollbarsHandleColor() const { return _scrollbarHorizontal.getHandleColor(); } const glm::vec4 Panel::getScrollbarsLineColor() const { return _scrollbarHorizontal.getLineColor(); } Panel& Panel::setSize(const glm::vec2& size) { Container::setSize(size); _updateScrollbarLogic(); return *this; } Panel& Panel::setTotalSize(const glm::vec2& totalSize) { _totalSize = totalSize; setInvalid(); validate(); _updateScrollbarLogic(); return *this; } Panel& Panel::setPosition(const glm::vec2& position) { Container::setPosition(position); _updateScrollbarLogic(); return *this; } Panel& Panel::setBackgroundColor(const glm::vec3& backgroundColor) { return setBackgroundColor(glm::vec4(backgroundColor, 1.0f)); } Panel& Panel::setBackgroundColor(const glm::vec4& backgroundColor) { _backgroundColor = backgroundColor; setInvalid(); return *this; } Panel& Panel::setScrollbarsSize(float scrollbarsSize) { return setScrollbarsSize({ scrollbarsSize, scrollbarsSize }); } Panel& Panel::setScrollbarsSize(const glm::vec2& scrollbarsSize) { _scrollbarsSize = scrollbarsSize; _updateScrollbarLogic(); return *this; } Panel& Panel::setScrollbarsBackgroundColor(const glm::vec3& scrollbarsBackgroundColor) { return setScrollbarsBackgroundColor(glm::vec4(scrollbarsBackgroundColor, 1.0f)); } Panel& Panel::setScrollbarsBackgroundColor(const glm::vec4& scrollbarsBackgroundColor) { _scrollbarHorizontal.setBackgroundColor(scrollbarsBackgroundColor); _scrollbarVertical.setBackgroundColor(scrollbarsBackgroundColor); return *this; } Panel& Panel::setScrollbarsHandleSize(const glm::vec2& scrollbarsHandleSize) { _scrollbarHorizontal.setHandleSize(scrollbarsHandleSize); _scrollbarVertical.setHandleSize({ scrollbarsHandleSize.y, scrollbarsHandleSize.x }); return *this; } Panel& Panel::setScrollbarsLineSize(const glm::vec2& scrollbarsLineSize) { _scrollbarHorizontal.setLineSize(scrollbarsLineSize); _scrollbarVertical.setLineSize({ scrollbarsLineSize.y, scrollbarsLineSize.x }); return *this; } Panel& Panel::setScrollbarsHandleColor(const glm::vec3& scrollbarsHandleColor) { return setScrollbarsHandleColor(glm::vec4(scrollbarsHandleColor, 1.0f)); } Panel& Panel::setScrollbarsHandleColor(const glm::vec4& scrollbarsHandleColor) { _scrollbarHorizontal.setHandleColor(scrollbarsHandleColor); _scrollbarVertical.setHandleColor(scrollbarsHandleColor); return *this; } Panel& Panel::setScrollbarsLineColor(const glm::vec3& scrollbarsLineColor) { return setScrollbarsLineColor(glm::vec4(scrollbarsLineColor, 1.0f)); } Panel& Panel::setScrollbarsLineColor(const glm::vec4& scrollbarsLineColor) { _scrollbarHorizontal.setLineColor(scrollbarsLineColor); _scrollbarVertical.setLineColor(scrollbarsLineColor); return *this; } Panel& Panel::setScrollbarsBorder(int width, int offset, const glm::vec3& color) { return setScrollbarsBorder(width, offset, glm::vec4(color, 1.0f)); } Panel& Panel::setScrollbarsBorder(int width, int offset, const glm::vec4& color) { _scrollbarHorizontal.border.set(width, offset, color); _scrollbarVertical.border.set(width, offset, color); return *this; } Panel& Panel::setScrollbarsHandleBorder(int width, int offset, const glm::vec3& color) { return setScrollbarsHandleBorder(width, offset, glm::vec4(color, 1.0f)); } Panel& Panel::setScrollbarsHandleBorder(int width, int offset, const glm::vec4& color) { _scrollbarHorizontal.handleBorder.set(width, offset, color); _scrollbarVertical.handleBorder.set(width, offset, color); return *this; } void Panel::_initializeScrollbars() { _scrollbarHorizontal.setOrientation(Style::Orientation::Horizontal); _scrollbarVertical.setOrientation(Style::Orientation::Vertical); _scrollbarHorizontal.onValueChange += Event::ValueChange<float>::Handler( "__GLUL::GUI::Panel::HorizontalScrollbar::ValueChange", [&](Component& component, const Event::ValueChange<float>& onValueChangeEvent) { (void) component; (void) onValueChangeEvent; this->setInvalid(); } ); _scrollbarVertical.onValueChange += Event::ValueChange<float>::Handler( "__GLUL::GUI::Panel::VerticalScrollbar::ValueChange", [&](Component& component, const Event::ValueChange<float>& onValueChangeEvent) { (void) component; (void) onValueChangeEvent; this->setInvalid(); } ); } void Panel::_updateScrollbarLogic() { _scrollbarHorizontal.setEnabled(isHorizontalScrollbarVisible()); _scrollbarHorizontal.setVisible(isHorizontalScrollbarVisible()); _scrollbarVertical.setEnabled(isVerticalScrollbarVisible()); _scrollbarVertical.setVisible(isVerticalScrollbarVisible()); glm::vec2 pos = getPosition(); // Horizontal scrollbar if(isHorizontalScrollbarVisible()) { _scrollbarHorizontal.setRange(0.0f, getTotalSize().x - getSize().x); _scrollbarHorizontal.setSize({ getSize().x - getScrollbarsSize().x, getScrollbarsSize().y }); _scrollbarHorizontal.setPosition(pos + glm::vec2(0.0f, getSize().y - getScrollbarsSize().y )); } // Vertical scrollbar if(isVerticalScrollbarVisible()) { _scrollbarVertical.setRange(0.0f, getTotalSize().y - getSize().y); _scrollbarVertical.setValue(_scrollbarVertical.getMax()); _scrollbarVertical.setSize({ getScrollbarsSize().x, getSize().y - getScrollbarsSize().y }); _scrollbarVertical.setPosition(pos + glm::vec2(getSize().x - getScrollbarsSize().x, 0.0f)); } } GL::Program& Panel::getProgram() { static GL::Program program( GL::Shader("assets/shaders/GLUL/GUI/Button.vp", GL::Shader::Type::VertexShader), GL::Shader("assets/shaders/GLUL/GUI/Button.fp", GL::Shader::Type::FragmentShader) ); return program; } std::vector<glm::vec4> Panel::getVertices() const { std::vector<glm::vec4> result; // Background position glm::vec2 scrPos = Container::getScreenPosition(); glm::vec2 posStart = glm::vec2(scrPos.x, GL::Context::Current->getViewportSize().y - scrPos.y); glm::vec2 posEnd = posStart + glm::vec2(getSize().x, -getSize().y); // Cube between scrollbars position glm::vec2 posCubeStart = posEnd; glm::vec2 posCubeEnd = posCubeStart - glm::vec2(getScrollbarsSize().x, -getScrollbarsSize().y); // Background vertices pushColoredRectangle(result, posStart, posEnd, getBackgroundColor()); // Small cube between horizontal and vertical scrollbars to fill void space pushColoredRectangle(result, posCubeStart, posCubeEnd, getScrollbarsBackgroundColor()); return result; } } }
34.84127
123
0.589446
[ "render", "vector" ]
07675ee67ef538ea9771e49cb0891b840a754be5
3,333
hpp
C++
third_party/CppADCodeGen/test/cppad/cg/dae_index_reduction/model/pendulum.hpp
eric-heiden/tds-merge
1e18447b0096efbb6df5d9ad7d69c8b0cc282747
[ "Apache-2.0" ]
null
null
null
third_party/CppADCodeGen/test/cppad/cg/dae_index_reduction/model/pendulum.hpp
eric-heiden/tds-merge
1e18447b0096efbb6df5d9ad7d69c8b0cc282747
[ "Apache-2.0" ]
null
null
null
third_party/CppADCodeGen/test/cppad/cg/dae_index_reduction/model/pendulum.hpp
eric-heiden/tds-merge
1e18447b0096efbb6df5d9ad7d69c8b0cc282747
[ "Apache-2.0" ]
null
null
null
#ifndef CPPAD_CG_TEST_PENDULUM_INCLUDED #define CPPAD_CG_TEST_PENDULUM_INCLUDED /* -------------------------------------------------------------------------- * CppADCodeGen: C++ Algorithmic Differentiation with Source Code Generation: * Copyright (C) 2012 Ciengis * * CppADCodeGen is distributed under multiple licenses: * * - Eclipse Public License Version 1.0 (EPL1), and * - GNU General Public License Version 3 (GPL3). * * EPL1 terms and conditions can be found in the file "epl-v10.txt", while * terms and conditions for the GPL3 can be found in the file "gpl3.txt". * ---------------------------------------------------------------------------- * Author: Joao Leal */ namespace CppAD { namespace cg { template<class Base> inline CppAD::ADFun<Base>* Pendulum2D(std::vector<DaeVarInfo>& daeVar) { using namespace CppAD; using namespace std; using ADB = CppAD::AD<Base>; std::vector<ADB> U(11); Independent(U); ADB x = U[0]; ADB y = U[1]; ADB vx = U[2]; // auxiliary variable ADB vy = U[3]; // auxiliary variable ADB T = U[4]; // tension ADB L = U[5]; // length (parameter) ADB t = U[6]; // time (not really used) ADB dxdt = U[7]; ADB dydt = U[8]; ADB dvxdt = U[9]; // auxiliary variable ADB dvydt = U[10]; // auxiliary variable daeVar.resize(U.size()); daeVar[0] = DaeVarInfo("x"); daeVar[1] = DaeVarInfo("y"); daeVar[2] = DaeVarInfo("w"); // vx daeVar[3] = DaeVarInfo("z"); // vy daeVar[4] = DaeVarInfo("T"); daeVar[5] = DaeVarInfo("l"); daeVar[5].makeConstant(); daeVar[6].makeIntegratedVariable(); daeVar[7] = 0; daeVar[8] = 1; daeVar[9] = 2; daeVar[10] = 3; double g = 9.80665; // gravity constant // dependent variable vector std::vector<ADB> Z(5); Z[0] = dxdt - vx; // dx/dt = //Z[0] = CppAD::CondExpLe<Base>(Z[0], 0, Z[0], 0); Z[1] = dydt - vy; // dy/dt = Z[2] = dvxdt - T * x; // dvx/dt = Z[3] = dvydt - (T * y - g); // dvy/dt = Z[4] = x * x + y * y - L * L; // create f: U -> Z and vectors used for derivative calculations return new ADFun<Base> (U, Z); } template<class Base> inline CppAD::ADFun<Base>* Pendulum3D() { using namespace CppAD; using namespace std; using ADB = CppAD::AD<Base>; std::vector<ADB> U(13); Independent(U); ADB x = U[0]; ADB y = U[1]; ADB z = U[2]; ADB vx = U[3]; // auxiliary variable ADB vy = U[4]; // auxiliary variable ADB vz = U[5]; // auxiliary variable ADB T = U[6]; // tension ADB dxdt = U[7]; ADB dydt = U[8]; ADB dzdt = U[9]; ADB dvxdt = U[10]; // auxiliary variable ADB dvydt = U[11]; // auxiliary variable ADB dvzdt = U[12]; // auxiliary variable double g = 9.80665; // gravity constant double L = 1.0; // fixed length // dependent variable vector std::vector<ADB> Z(7); Z[0] = dxdt - vx; // dx/dt = Z[1] = dydt - vy; // dy/dt = Z[2] = dzdt - vz; // dz/dt = Z[3] = dvxdt - T * x; // dvx/dt = Z[4] = dvydt - (T * y - g); // dvy/dt = Z[5] = dvzdt - T * z; // dvz/dt = Z[6] = x * x + y * y + z * z - L * L; // create f: U -> Z and vectors used for derivative calculations return new ADFun<Base> (U, Z); } } // END cg namespace } // END CppAD namespace #endif
28.982609
79
0.545455
[ "vector" ]
077caea2b6e5435664e504ef9173ae445cd11293
1,051
cpp
C++
A2OJ/B/010. DZY Love Strings.cpp
XitizVerma/Data-Structures-and-Algorithms-Advanced
610225eeb7e0b4ade229ec86355901ad1ca38784
[ "MIT" ]
1
2020-08-27T06:59:52.000Z
2020-08-27T06:59:52.000Z
A2OJ/B/010. DZY Love Strings.cpp
XitizVerma/Data-Structures-and-Algorithms-Advanced
610225eeb7e0b4ade229ec86355901ad1ca38784
[ "MIT" ]
null
null
null
A2OJ/B/010. DZY Love Strings.cpp
XitizVerma/Data-Structures-and-Algorithms-Advanced
610225eeb7e0b4ade229ec86355901ad1ca38784
[ "MIT" ]
null
null
null
// author : hrahul2605 #include <bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define ll long long #define int long long #define f first #define se second #define LB lower_bound #define UB upper_bound #define pb push_back #define mp make_pair #define vll vector<ll> #define vi vector<int> #define vc vector<char> #define vs vector<string> #define pll pair<ll,ll> #define vpll vector<pll> #define pie 3.14159265358979323846264338327950288 const unsigned int MOD = 1000000007; using namespace std; int32_t main() { IOS;int T;T=1; // cin>>T; while(T--) { string s;cin>>s; ll ans = 0,mx=-1; ll k;cin>>k; char key = 'a'; map<char,int>m; for(int i=0;i<26;i++) { ll x;cin>>x; mx = max(mx,x); m[key]=x; key++; } for(int i=0;i<s.size();i++) ans+=m[s[i]]*(i+1); for(int i=s.size()+1 ; i<=s.size()+k ; i++) ans+=i*mx; cout<<ans; } return 0; }
21.02
61
0.551855
[ "vector" ]
077cb99ffdc7667f353381a8ec2482b5a1ff2c3c
5,067
cpp
C++
src/jsonserializer/typeconverters/legacygeomconverter.cpp
ohmree/QtJsonSerializer
55449772798608a04f688dff430faf28ce38a99f
[ "BSD-3-Clause" ]
103
2017-11-16T09:23:30.000Z
2022-03-24T15:44:00.000Z
src/jsonserializer/typeconverters/legacygeomconverter.cpp
ohmree/QtJsonSerializer
55449772798608a04f688dff430faf28ce38a99f
[ "BSD-3-Clause" ]
47
2017-11-16T09:23:20.000Z
2022-01-04T21:11:37.000Z
src/jsonserializer/typeconverters/legacygeomconverter.cpp
ohmree/QtJsonSerializer
55449772798608a04f688dff430faf28ce38a99f
[ "BSD-3-Clause" ]
49
2017-11-18T08:39:05.000Z
2022-03-10T09:55:51.000Z
#include "legacygeomconverter_p.h" #include "exception.h" #include <QtCore/QCborMap> using namespace QtJsonSerializer; using namespace QtJsonSerializer::TypeConverters; LegacyGeomConverter::LegacyGeomConverter() { setPriority(Priority::VeryLow); } bool LegacyGeomConverter::canConvert(int metaTypeId) const { static const QVector<int> types { QMetaType::QSize, QMetaType::QSizeF, QMetaType::QPoint, QMetaType::QPointF, QMetaType::QLine, QMetaType::QLineF, QMetaType::QRect, QMetaType::QRectF, }; return types.contains(metaTypeId); } QList<QCborValue::Type> LegacyGeomConverter::allowedCborTypes(int metaTypeId, QCborTag tag) const { Q_UNUSED(metaTypeId) Q_UNUSED(tag) return {QCborValue::Map}; } QCborValue LegacyGeomConverter::serialize(int propertyType, const QVariant &value) const { Q_UNUSED(propertyType) Q_UNUSED(value) throw SerializationException{"The QJsonLegacyGeomConverter cannot serialize data"}; } QVariant LegacyGeomConverter::deserializeCbor(int propertyType, const QCborValue &value, QObject *parent) const { Q_UNUSED(propertyType) Q_UNUSED(value) Q_UNUSED(parent) throw DeserializationException{"The QJsonLegacyGeomConverter cannot deserialize CBOR data"}; } QVariant LegacyGeomConverter::deserializeJson(int propertyType, const QCborValue &value, QObject *parent) const { Q_UNUSED(parent) const auto map = value.toMap(); switch (propertyType) { case QMetaType::QSize: return deserializeSize<QSize>(map); case QMetaType::QSizeF: return deserializeSize<QSizeF>(map); case QMetaType::QPoint: return deserializePoint<QPoint>(map); case QMetaType::QPointF: return deserializePoint<QPointF>(map); case QMetaType::QLine: return deserializeLine<QLine>(map); case QMetaType::QLineF: return deserializeLine<QLineF>(map); case QMetaType::QRect: return deserializeRect<QRect>(map); case QMetaType::QRectF: return deserializeRect<QRectF>(map); default: throw DeserializationException{"Invalid type id"}; } } template<typename TSize> TSize LegacyGeomConverter::deserializeSize(const QCborMap &map) const { using TW = std::decay_t<decltype(TSize{}.width())>; using TH = std::decay_t<decltype(TSize{}.height())>; if (map.size() != 2 || !map.contains(QStringLiteral("width")) || !map.contains(QStringLiteral("height"))) throw DeserializationException("JSON object has no width or height properties or does have extra properties"); return { extract<TW>(map[QStringLiteral("width")]), extract<TH>(map[QStringLiteral("height")]) }; } template<typename TPoint> TPoint LegacyGeomConverter::deserializePoint(const QCborMap &map) const { using TX = std::decay_t<decltype(TPoint{}.x())>; using TY = std::decay_t<decltype(TPoint{}.y())>; if (map.size() != 2 || !map.contains(QStringLiteral("x")) || !map.contains(QStringLiteral("y"))) throw DeserializationException("JSON object has no x or y properties or does have extra properties"); return { extract<TX>(map[QStringLiteral("x")]), extract<TY>(map[QStringLiteral("y")]) }; } template<typename TLine> TLine LegacyGeomConverter::deserializeLine(const QCborMap &map) const { using TP1 = std::decay_t<decltype(TLine{}.p1())>; using TP2 = std::decay_t<decltype(TLine{}.p2())>; if (map.size() != 2 || !map.contains(QStringLiteral("p1")) || !map.contains(QStringLiteral("p2"))) throw DeserializationException("JSON object has no p1 or p2 properties or does have extra properties"); return { helper()->deserializeSubtype(qMetaTypeId<TP1>(), map[QStringLiteral("p1")], nullptr, "p1").template value<TP1>(), helper()->deserializeSubtype(qMetaTypeId<TP2>(), map[QStringLiteral("p2")], nullptr, "p2").template value<TP2>() }; } template<typename TRect> TRect LegacyGeomConverter::deserializeRect(const QCborMap &map) const { using TTL = std::decay_t<decltype(TRect{}.topLeft())>; using TBR = std::decay_t<decltype(TRect{}.bottomRight())>; if (map.size() != 2 || !map.contains(QStringLiteral("topLeft")) || !map.contains(QStringLiteral("bottomRight"))) throw DeserializationException("JSON object has no topLeft or bottomRight properties or does have extra properties"); return { helper()->deserializeSubtype(qMetaTypeId<TTL>(), map[QStringLiteral("topLeft")], nullptr, "topLeft").template value<TTL>(), helper()->deserializeSubtype(qMetaTypeId<TBR>(), map[QStringLiteral("bottomRight")], nullptr, "bottomRight").template value<TBR>() }; } template<> int LegacyGeomConverter::extract(const QCborValue &value) const { if (!value.isInteger()) throw DeserializationException{"Expected integer, but got type " + QByteArray::number(value.type())}; return static_cast<int>(value.toInteger()); } template<> qreal LegacyGeomConverter::extract(const QCborValue &value) const { if (!value.isDouble() && !value.isInteger()) throw DeserializationException{"Expected double, but got type " + QByteArray::number(value.type())}; return value.toDouble(); }
33.556291
133
0.724887
[ "object" ]
078284eaf5017060b88cdeae062956e9f800e4e1
6,288
cpp
C++
projects/USDExporter/source/StringUtil.cpp
ft-lab/Shade3D_USDExporter
981494219a510d679369726229decbb9c7dac36e
[ "MIT" ]
5
2019-10-13T00:53:45.000Z
2021-02-15T15:43:39.000Z
projects/USDExporter/source/StringUtil.cpp
ft-lab/Shade3D_USDExporter
981494219a510d679369726229decbb9c7dac36e
[ "MIT" ]
null
null
null
projects/USDExporter/source/StringUtil.cpp
ft-lab/Shade3D_USDExporter
981494219a510d679369726229decbb9c7dac36e
[ "MIT" ]
1
2021-08-13T10:54:47.000Z
2021-08-13T10:54:47.000Z
/** * 文字列操作関数. */ #include "StringUtil.h" #if _WINDOWS #include "windows.h" #endif #undef max #undef min #include <string> #include <sstream> #include <algorithm> #include <vector> /** * パスのセパレータを取得. */ const std::string StringUtil::getFileSeparator () { #if _WINDOWS return "\\"; #else return "/"; #endif } /** * ファイルパスからファイル名のみを取得. * @param[in] filePath ファイルフルパス. * @param[in] hasExtension trueの場合は拡張子も付ける. */ const std::string StringUtil::getFileName (const std::string& filePath, const bool hasExtension) { // ファイルパスからファイル名を取得. std::string fileNameS = filePath; int iPos = filePath.find_last_of("/"); int iPos2 = filePath.find_last_of("\\"); if (iPos != std::string::npos || iPos2 != std::string::npos) { if (iPos != std::string::npos && iPos2 != std::string::npos) { iPos = std::max(iPos, iPos2); } else if (iPos == std::string::npos) iPos = iPos2; if (iPos != std::string::npos) fileNameS = fileNameS.substr(iPos + 1); } if (hasExtension) return fileNameS; iPos = fileNameS.find_last_of("."); if (iPos != std::string::npos) { fileNameS = fileNameS.substr(0, iPos); } return fileNameS; } /** * ファイル名として使用できない文字('/'など)を"_"に置き換え. */ const std::string StringUtil::convAsFileName (const std::string& fileName) { std::string name = fileName; name = replaceString(name, "/", "_"); name = replaceString(name, "#", "_"); name = replaceString(name, "*", "_"); name = replaceString(name, "<", "_"); name = replaceString(name, ">", "_"); return name; } /** * ファイル名を除いたディレクトリを取得. * @param[in] filePath ファイルフルパス. */ const std::string StringUtil::getFileDir (const std::string& filePath) { int iPos = filePath.find_last_of("/"); int iPos2 = filePath.find_last_of("\\"); if (iPos == std::string::npos && iPos2 == std::string::npos) return filePath; if (iPos != std::string::npos && iPos2 != std::string::npos) { iPos = std::max(iPos, iPos2); } else if (iPos == std::string::npos) iPos = iPos2; if (iPos == std::string::npos) return filePath; return filePath.substr(0, iPos); } /** * ファイルパスから拡張子を取得. * @param[in] filePath ファイルフルパス. */ const std::string StringUtil::getFileExtension (const std::string& filePath) { if (filePath == "") return ""; std::string fileNameS = getFileName(filePath); const int iPos = fileNameS.find_last_of("."); if (iPos == std::string::npos) return ""; std::transform(fileNameS.begin(), fileNameS.end(), fileNameS.begin(), ::tolower); return fileNameS.substr(iPos + 1); } /** * 文字列内の全置換. * @param[in] targetStr 対象の文字列. * @param[in] srcStr 置き換え前の文字列. * @param[in] dstStr 置き換え後の文字列. * @return 変換された文字列. */ std::string StringUtil::replaceString (const std::string& targetStr, const std::string& srcStr, const std::string& dstStr) { std::string str = targetStr; std::string::size_type pos = 0; while ((pos = str.find(srcStr, pos)) != std::string::npos) { str.replace(pos, srcStr.length(), dstStr); pos += dstStr.length(); } return str; } /** * ASCII文字列で、0-9、a-Z、A-Z、以外は置き換え. * @param[in] targetStr 対象の文字列. * @param[in] dstChar 置き換え後の文字. * @param[in] useSeparator '/'をそのままにする場合はtrue. * @param[in] useDot '.'をそのままにする場合はtrue. * @return 変換された文字列. */ std::string StringUtil::replaceASCIIStringOtherThanAlphabetAndNumber (const std::string& targetStr, char* dstChar, const bool useSeparator, const bool useDot) { std::string retStr = targetStr; for (size_t i = 0; i < targetStr.length(); ++i) { const char chD = targetStr[i]; if ((chD >= '0' && chD <= '9') || (chD >= 'a' && chD <= 'z') || (chD >= 'A' && chD <= 'Z')) continue; if (useSeparator) { if (chD == '/') continue; } if (useDot) { if (chD == '.') continue; } retStr[i] = dstChar[0]; } return retStr; } /** * テキストをHTML用に変換. * & ==> &amp; < ==> &lt; など. */ std::string StringUtil::convHTMLEncode (const std::string& str) { std::string str2 = str; str2 = replaceString(str2, "&", "&amp;"); str2 = replaceString(str2, "\"", "&quot;"); str2 = replaceString(str2, "<", "&lt;"); str2 = replaceString(str2, ">", "&gt;"); return str2; } /** * HTML用のテキストを元に戻す. * &amp; ==> & &lt; ==> < など. */ std::string StringUtil::convHTMLDecode (const std::string& str) { std::string str2 = str; str2 = replaceString(str2, "&gt;", ">"); str2 = replaceString(str2, "&lt;", "<"); str2 = replaceString(str2, "&quot;", "\""); str2 = replaceString(str2, "&amp;", "&"); return str2; } /** * UTF-8の文字列をSJISに変換. */ int StringUtil::convUTF8ToSJIS (const std::string& utf8Str, std::string& sjisStr) { #if _WINDOWS // UTF-8の文字列サイズを取得. const int n1 = MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, 0, 0); if (n1 <= 0) return 0; const int size = n1 << 2; // WCHAR形式に変換(UTF-8 ==> WCHAR). std::vector<WCHAR> wideCharStr; wideCharStr.resize(size, 0); MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), -1, &(wideCharStr[0]), n1); // SJIS形式に変換. std::vector<char> strBuff; strBuff.resize(size, 0); const int n2 = WideCharToMultiByte(CP_OEMCP, 0, &(wideCharStr[0]), -1, &(strBuff[0]), size, 0, 0); strBuff[n2] = '\0'; sjisStr = std::string(&(strBuff[0])); if (n2 <= 0) return 0; return n2; #else sjisStr = utf8Str; return sjisStr.length(); #endif } /** * すべてがASCII文字列かどうか. */ bool StringUtil::checkASCII (const std::string& name) { const unsigned char *nameP = (const unsigned char *)name.c_str(); bool chkF = true; int i = 0; while (nameP[i]) { if (nameP[i] >= 0x20 && nameP[i] <= 0x7e) { i++; continue; } chkF = false; break; } return chkF; } /** * 画像ファイル名に拡張子(pngまたはjpg)がない場合は拡張子をつける. * @param[in] filePath ファイルフルパス. * @param[in] extension 拡張子(pngまたはjpg). * @param[in] forceF 強制的に指定の拡張子に置き換え. */ const std::string StringUtil::SetFileImageExtension (const std::string& filePath, const std::string& extension, const bool forceF) { std::string retFilePath = filePath; if (!forceF) { const std::string extStr = getFileExtension(filePath); if (extStr == "jpeg" || extStr == "jpg" || extStr == "png") return retFilePath; } { // 拡張子を除外. const int iPos = retFilePath.find_last_of("."); if (iPos != std::string::npos) { retFilePath = retFilePath.substr(0, iPos); } } retFilePath += std::string(".") + extension; return retFilePath; }
24.755906
158
0.630089
[ "vector", "transform" ]
0784602a0e581f2367a255236d3b52d35853ff7d
705
hh
C++
inc/client/player.hh
haileys/battlecars
e6cf3ca50d7695ce89ab2acab8a276279db508e6
[ "Zlib" ]
1
2022-02-06T10:36:59.000Z
2022-02-06T10:36:59.000Z
inc/client/player.hh
haileys/battlecars
e6cf3ca50d7695ce89ab2acab8a276279db508e6
[ "Zlib" ]
null
null
null
inc/client/player.hh
haileys/battlecars
e6cf3ca50d7695ce89ab2acab8a276279db508e6
[ "Zlib" ]
null
null
null
#ifndef PLAYER_HH #define PLAYER_HH #include <string> #include <stdint.h> #include <SFML/Network.hpp> #include <SFML/Graphics.hpp> #include "client/game.hh" class Player { public: Game& game; uint32_t id; std::string name; float x, y, velocity, heading; sf::Sprite car; sf::String label; sf::Shape label_background; int label_width; void Render(sf::RenderTarget& target, int mid_x, int mid_y); Player(Game& _game, uint32_t _id, std::string& _name, float _x = 0.0, float _y = 0.0, float _velocity = 0.0, float _heading = 0.0); void HandleInfoRemainder(sf::Packet& packet); void HandlePositionRemainder(sf::Packet& packet); }; #endif
23.5
135
0.66383
[ "render", "shape" ]
0791f65b6ed8be38d4bfd99eef10fe55b37e1c44
9,512
cc
C++
outboundbot/src/model/QueryJobsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
outboundbot/src/model/QueryJobsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
outboundbot/src/model/QueryJobsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/outboundbot/model/QueryJobsResult.h> #include <json/json.h> using namespace AlibabaCloud::OutboundBot; using namespace AlibabaCloud::OutboundBot::Model; QueryJobsResult::QueryJobsResult() : ServiceResult() {} QueryJobsResult::QueryJobsResult(const std::string &payload) : ServiceResult() { parse(payload); } QueryJobsResult::~QueryJobsResult() {} void QueryJobsResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto jobsNode = value["Jobs"]; if(!jobsNode["PageNumber"].isNull()) jobs_.pageNumber = std::stoi(jobsNode["PageNumber"].asString()); if(!jobsNode["PageSize"].isNull()) jobs_.pageSize = std::stoi(jobsNode["PageSize"].asString()); if(!jobsNode["TotalCount"].isNull()) jobs_.totalCount = std::stoi(jobsNode["TotalCount"].asString()); auto allListNode = jobsNode["List"]["Job"]; for (auto jobsNodeListJob : allListNode) { Jobs::Job jobObject; if(!jobsNodeListJob["FailureReason"].isNull()) jobObject.failureReason = jobsNodeListJob["FailureReason"].asString(); if(!jobsNodeListJob["JobGroupId"].isNull()) jobObject.jobGroupId = jobsNodeListJob["JobGroupId"].asString(); if(!jobsNodeListJob["JobId"].isNull()) jobObject.jobId = jobsNodeListJob["JobId"].asString(); if(!jobsNodeListJob["Priority"].isNull()) jobObject.priority = std::stoi(jobsNodeListJob["Priority"].asString()); if(!jobsNodeListJob["ReferenceId"].isNull()) jobObject.referenceId = jobsNodeListJob["ReferenceId"].asString(); if(!jobsNodeListJob["ScenarioId"].isNull()) jobObject.scenarioId = jobsNodeListJob["ScenarioId"].asString(); if(!jobsNodeListJob["Status"].isNull()) jobObject.status = jobsNodeListJob["Status"].asString(); if(!jobsNodeListJob["StrategyId"].isNull()) jobObject.strategyId = jobsNodeListJob["StrategyId"].asString(); auto allContactsNode = jobsNodeListJob["Contacts"]["Contact"]; for (auto jobsNodeListJobContactsContact : allContactsNode) { Jobs::Job::Contact contactsObject; if(!jobsNodeListJobContactsContact["ContactId"].isNull()) contactsObject.contactId = jobsNodeListJobContactsContact["ContactId"].asString(); if(!jobsNodeListJobContactsContact["ContactName"].isNull()) contactsObject.contactName = jobsNodeListJobContactsContact["ContactName"].asString(); if(!jobsNodeListJobContactsContact["Honorific"].isNull()) contactsObject.honorific = jobsNodeListJobContactsContact["Honorific"].asString(); if(!jobsNodeListJobContactsContact["JobId"].isNull()) contactsObject.jobId = jobsNodeListJobContactsContact["JobId"].asString(); if(!jobsNodeListJobContactsContact["PhoneNumber"].isNull()) contactsObject.phoneNumber = jobsNodeListJobContactsContact["PhoneNumber"].asString(); if(!jobsNodeListJobContactsContact["ReferenceId"].isNull()) contactsObject.referenceId = jobsNodeListJobContactsContact["ReferenceId"].asString(); if(!jobsNodeListJobContactsContact["Role"].isNull()) contactsObject.role = jobsNodeListJobContactsContact["Role"].asString(); if(!jobsNodeListJobContactsContact["State"].isNull()) contactsObject.state = jobsNodeListJobContactsContact["State"].asString(); jobObject.contacts.push_back(contactsObject); } auto allExtrasNode = jobsNodeListJob["Extras"]["KeyValuePair"]; for (auto jobsNodeListJobExtrasKeyValuePair : allExtrasNode) { Jobs::Job::KeyValuePair extrasObject; if(!jobsNodeListJobExtrasKeyValuePair["Key"].isNull()) extrasObject.key = jobsNodeListJobExtrasKeyValuePair["Key"].asString(); if(!jobsNodeListJobExtrasKeyValuePair["Value"].isNull()) extrasObject.value = jobsNodeListJobExtrasKeyValuePair["Value"].asString(); jobObject.extras.push_back(extrasObject); } auto allSummaryNode = jobsNodeListJob["Summary"]["SummaryItem"]; for (auto jobsNodeListJobSummarySummaryItem : allSummaryNode) { Jobs::Job::SummaryItem summaryObject; if(!jobsNodeListJobSummarySummaryItem["Category"].isNull()) summaryObject.category = jobsNodeListJobSummarySummaryItem["Category"].asString(); if(!jobsNodeListJobSummarySummaryItem["Content"].isNull()) summaryObject.content = jobsNodeListJobSummarySummaryItem["Content"].asString(); if(!jobsNodeListJobSummarySummaryItem["ConversationDetailId"].isNull()) summaryObject.conversationDetailId = jobsNodeListJobSummarySummaryItem["ConversationDetailId"].asString(); if(!jobsNodeListJobSummarySummaryItem["GroupId"].isNull()) summaryObject.groupId = jobsNodeListJobSummarySummaryItem["GroupId"].asString(); if(!jobsNodeListJobSummarySummaryItem["JobId"].isNull()) summaryObject.jobId = jobsNodeListJobSummarySummaryItem["JobId"].asString(); if(!jobsNodeListJobSummarySummaryItem["SummaryId"].isNull()) summaryObject.summaryId = jobsNodeListJobSummarySummaryItem["SummaryId"].asString(); if(!jobsNodeListJobSummarySummaryItem["SummaryName"].isNull()) summaryObject.summaryName = jobsNodeListJobSummarySummaryItem["SummaryName"].asString(); if(!jobsNodeListJobSummarySummaryItem["TaskId"].isNull()) summaryObject.taskId = jobsNodeListJobSummarySummaryItem["TaskId"].asString(); jobObject.summary.push_back(summaryObject); } auto allTasksNode = jobsNodeListJob["Tasks"]["Task"]; for (auto jobsNodeListJobTasksTask : allTasksNode) { Jobs::Job::Task tasksObject; if(!jobsNodeListJobTasksTask["ActualTime"].isNull()) tasksObject.actualTime = std::stol(jobsNodeListJobTasksTask["ActualTime"].asString()); if(!jobsNodeListJobTasksTask["Brief"].isNull()) tasksObject.brief = jobsNodeListJobTasksTask["Brief"].asString(); if(!jobsNodeListJobTasksTask["CallId"].isNull()) tasksObject.callId = jobsNodeListJobTasksTask["CallId"].asString(); if(!jobsNodeListJobTasksTask["CalledNumber"].isNull()) tasksObject.calledNumber = jobsNodeListJobTasksTask["CalledNumber"].asString(); if(!jobsNodeListJobTasksTask["CallingNumber"].isNull()) tasksObject.callingNumber = jobsNodeListJobTasksTask["CallingNumber"].asString(); if(!jobsNodeListJobTasksTask["ChatbotId"].isNull()) tasksObject.chatbotId = jobsNodeListJobTasksTask["ChatbotId"].asString(); if(!jobsNodeListJobTasksTask["Duration"].isNull()) tasksObject.duration = std::stoi(jobsNodeListJobTasksTask["Duration"].asString()); if(!jobsNodeListJobTasksTask["JobId"].isNull()) tasksObject.jobId = jobsNodeListJobTasksTask["JobId"].asString(); if(!jobsNodeListJobTasksTask["PlanedTime"].isNull()) tasksObject.planedTime = std::stol(jobsNodeListJobTasksTask["PlanedTime"].asString()); if(!jobsNodeListJobTasksTask["ScenarioId"].isNull()) tasksObject.scenarioId = jobsNodeListJobTasksTask["ScenarioId"].asString(); if(!jobsNodeListJobTasksTask["Status"].isNull()) tasksObject.status = jobsNodeListJobTasksTask["Status"].asString(); if(!jobsNodeListJobTasksTask["TaskId"].isNull()) tasksObject.taskId = jobsNodeListJobTasksTask["TaskId"].asString(); auto contact1Node = value["Contact"]; if(!contact1Node["ContactId"].isNull()) tasksObject.contact1.contactId = contact1Node["ContactId"].asString(); if(!contact1Node["ContactName"].isNull()) tasksObject.contact1.contactName = contact1Node["ContactName"].asString(); if(!contact1Node["Honorific"].isNull()) tasksObject.contact1.honorific = contact1Node["Honorific"].asString(); if(!contact1Node["JobId"].isNull()) tasksObject.contact1.jobId = contact1Node["JobId"].asString(); if(!contact1Node["PhoneNumber"].isNull()) tasksObject.contact1.phoneNumber = contact1Node["PhoneNumber"].asString(); if(!contact1Node["ReferenceId"].isNull()) tasksObject.contact1.referenceId = contact1Node["ReferenceId"].asString(); if(!contact1Node["Role"].isNull()) tasksObject.contact1.role = contact1Node["Role"].asString(); if(!contact1Node["State"].isNull()) tasksObject.contact1.state = contact1Node["State"].asString(); jobObject.tasks.push_back(tasksObject); } auto allCallingNumbers = value["CallingNumbers"]["String"]; for (auto value : allCallingNumbers) jobObject.callingNumbers.push_back(value.asString()); jobs_.list.push_back(jobObject); } if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["HttpStatusCode"].isNull()) httpStatusCode_ = std::stoi(value["HttpStatusCode"].asString()); if(!value["Message"].isNull()) message_ = value["Message"].asString(); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; } std::string QueryJobsResult::getMessage()const { return message_; } QueryJobsResult::Jobs QueryJobsResult::getJobs()const { return jobs_; } int QueryJobsResult::getHttpStatusCode()const { return httpStatusCode_; } std::string QueryJobsResult::getCode()const { return code_; } bool QueryJobsResult::getSuccess()const { return success_; }
45.080569
110
0.7541
[ "model" ]
0796a4e0f12f02532a8b86e1224dbd0ee402a060
650
cpp
C++
CPlusPlus-Class/04 - OOP - Exercise 9/04 - OOP - Exercise 9.cpp
AlieuFriggeri/SAE921-GRP4100-CPlusPlus-Class-A.Friggeri
137729b63d2f093bf8510faab79cd0c7a38e0f19
[ "MIT" ]
null
null
null
CPlusPlus-Class/04 - OOP - Exercise 9/04 - OOP - Exercise 9.cpp
AlieuFriggeri/SAE921-GRP4100-CPlusPlus-Class-A.Friggeri
137729b63d2f093bf8510faab79cd0c7a38e0f19
[ "MIT" ]
null
null
null
CPlusPlus-Class/04 - OOP - Exercise 9/04 - OOP - Exercise 9.cpp
AlieuFriggeri/SAE921-GRP4100-CPlusPlus-Class-A.Friggeri
137729b63d2f093bf8510faab79cd0c7a38e0f19
[ "MIT" ]
null
null
null
// 04 - OOP - Exercise 9.cpp : Ce fichier contient la fonction 'main'. L'exécution du programme commence et se termine à cet endroit. // #include <iostream> #include <vector> #include "Items.h" #include "Maps.h" #include "Inventory.h" #include "Potion.h" #include "ATKPotion.h" #include "HealthPotion.h" #include "Sword.h" int main() { Inventory myInventory; Sword mySword; Maps myMap; ATKPotion myATKPotion; HealthPotion myHealthPotion; Potion myPotion; myMap.use(); myInventory.add(&myMap); myInventory.add(&myHealthPotion); myInventory.add(&myPotion); myInventory.display(); }
16.25
133
0.670769
[ "vector" ]
079b237736e860f42f8960ccece8972726a80e2b
16,444
cpp
C++
earth_enterprise/src/fusion/autoingest/sysman/AssetOperation_unittest.cpp
seamusdunlop123/earthenterprise
a2651b1c00dd6230fd5d3d47502d228dbfca0f63
[ "Apache-2.0" ]
1
2020-02-12T10:28:29.000Z
2020-02-12T10:28:29.000Z
earth_enterprise/src/fusion/autoingest/sysman/AssetOperation_unittest.cpp
seamusdunlop123/earthenterprise
a2651b1c00dd6230fd5d3d47502d228dbfca0f63
[ "Apache-2.0" ]
null
null
null
earth_enterprise/src/fusion/autoingest/sysman/AssetOperation_unittest.cpp
seamusdunlop123/earthenterprise
a2651b1c00dd6230fd5d3d47502d228dbfca0f63
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 The Open GEE Contributors * * 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 "AssetOperation.h" #include "gee_version.h" #include "StateUpdater.h" #include "StorageManager.h" #include <gtest/gtest.h> using namespace std; // Declare the globals that AssetOperation functions use. This is cheating but // it lets us mock the classes that AssetOperation calls. extern std::unique_ptr<StateUpdater> stateUpdater; extern StorageManagerInterface<AssetVersionImpl> * assetOpStorageManager; const AssetKey REF = "a"; class MockVersion : public AssetVersionImpl { public: bool statePropagated; AssetDefs::State refAndDependentsState; std::function<bool(AssetDefs::State)> updateStateFunc; bool setProgress; bool setDone; bool setFailed; bool outFilesReset; mutable bool updatedWaiting; mutable AssetDefs::State oldState; mutable WaitingFor waitingFor; mutable bool updatedSucceeded; MockVersion() : statePropagated(false), refAndDependentsState(AssetDefs::Failed), updateStateFunc(nullptr), setProgress(false), setDone(false), setFailed(false), outFilesReset(false), updatedWaiting(false), oldState(AssetDefs::New), waitingFor({0, 0}), updatedSucceeded(false) { type = AssetDefs::Imagery; // Ensures that operator bool can return true taskid = 0; beginTime = 0; progressTime = 0; progress = 0.0; } MockVersion(const AssetKey & ref) : MockVersion() { name = ref; } MockVersion(const MockVersion & that) : MockVersion() { name = that.name; } virtual void ResetOutFiles(const vector<string> & newOutfiles) override { outFilesReset = true; outfiles = newOutfiles; } // Not used - only included to make MockVersion non-virtual string PluginName(void) const override { return string(); } void GetOutputFilenames(vector<string> &) const override {} string GetOutputFilename(uint) const override { return string(); } }; class MockStorageManager : public StorageManagerInterface<AssetVersionImpl> { private: // This storage only holds one version shared_ptr<MockVersion> version; PointerType GetRef(const AssetKey & ref) { assert(ref == REF); return version; } public: MockStorageManager() : version(make_shared<MockVersion>(REF)) {} virtual AssetHandle<const AssetVersionImpl> Get(const AssetKey &ref) { return AssetHandle<const AssetVersionImpl>(GetRef(ref), nullptr); } virtual AssetHandle<AssetVersionImpl> GetMutable(const AssetKey &ref) { return AssetHandle<AssetVersionImpl>(GetRef(ref), nullptr); } // The two functions below pull the pointer out of the AssetHandle and use it // directly, which is really bad. We can get away with it in test code, but we // should never do this in production code. Hopefully the production code will // never need to convert AssetHandles to different types, but if it does we // need to come up with a better way. const MockVersion * GetVersion() { AssetHandle<const AssetVersionImpl> handle = Get(REF); return dynamic_cast<const MockVersion *>(handle.operator->()); } MockVersion * GetMutableVersion() { AssetHandle<AssetVersionImpl> handle = GetMutable(REF); return dynamic_cast<MockVersion *>(handle.operator->()); } }; class MockStateUpdater : public StateUpdater { private: MockStorageManager * sm; public: MockStateUpdater(MockStorageManager * sm) : sm(sm) {} virtual void SetAndPropagateState( const SharedString & ref, AssetDefs::State newState, std::function<bool(AssetDefs::State)> updateStatePredicate) { assert(ref == REF); auto version = sm->GetMutableVersion(); version->statePropagated = true; version->refAndDependentsState = newState; version->updateStateFunc = updateStatePredicate; } virtual void SetInProgress(AssetHandle<AssetVersionImpl> & version) { auto v = dynamic_cast<MockVersion *>(version.operator->()); v->setProgress = true; } virtual void SetSucceeded(AssetHandle<AssetVersionImpl> & version) { auto v = dynamic_cast<MockVersion *>(version.operator->()); v->setDone = true; } virtual void SetFailed(AssetHandle<AssetVersionImpl> & version) { auto v = dynamic_cast<MockVersion *>(version.operator->()); v->setFailed = true; } virtual void UpdateWaitingAssets( AssetHandle<const AssetVersionImpl> version, AssetDefs::State oldState, const WaitingFor & waitingFor) { auto v = dynamic_cast<const MockVersion *>(version.operator->()); v->updatedWaiting = true; v->oldState = oldState; v->waitingFor = waitingFor; } virtual void UpdateSucceeded(AssetHandle<const AssetVersionImpl> version, bool propagate) { // AssetOperation should always set propagate to false, so we check that here ASSERT_FALSE(propagate); auto v = dynamic_cast<const MockVersion *>(version.operator->()); v->updatedSucceeded = true; } }; class AssetOperationTest : public testing::Test { protected: MockStorageManager sm; public: AssetOperationTest() { assetOpStorageManager = &sm; stateUpdater.reset(new MockStateUpdater(&sm)); } }; TEST_F(AssetOperationTest, Rebuild) { sm.GetMutableVersion()->state = AssetDefs::Canceled; RebuildVersion(REF, MiscConfig::ALL_GRAPH_OPS); ASSERT_TRUE(sm.GetVersion()->statePropagated); ASSERT_EQ(sm.GetVersion()->refAndDependentsState, AssetDefs::New); // Make sure the function that determines which states to update returns the // correct values. ASSERT_TRUE(sm.GetVersion()->updateStateFunc(AssetDefs::Canceled)); ASSERT_TRUE(sm.GetVersion()->updateStateFunc(AssetDefs::Failed)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::New)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::Waiting)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::Blocked)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::Queued)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::InProgress)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::Succeeded)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::Offline)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::Bad)); } void RebuildWrongState(MockStorageManager & sm, AssetDefs::State state) { sm.GetMutableVersion()->state = state; ASSERT_THROW(RebuildVersion(REF, MiscConfig::ALL_GRAPH_OPS), khException); } TEST_F(AssetOperationTest, RebuildWrongStateSucceeded) { RebuildWrongState(sm, AssetDefs::Succeeded); } TEST_F(AssetOperationTest, RebuildWrongStateOffline) { RebuildWrongState(sm, AssetDefs::Offline); } TEST_F(AssetOperationTest, RebuildWrongStateBad) { RebuildWrongState(sm, AssetDefs::Bad); } TEST_F(AssetOperationTest, RebuildBadVersion) { sm.GetMutableVersion()->type = AssetDefs::Invalid; RebuildVersion(REF, MiscConfig::ALL_GRAPH_OPS); ASSERT_FALSE(sm.GetVersion()->statePropagated); } TEST_F(AssetOperationTest, Cancel) { sm.GetMutableVersion()->state = AssetDefs::Waiting; CancelVersion(REF, MiscConfig::ALL_GRAPH_OPS); ASSERT_TRUE(sm.GetVersion()->statePropagated); ASSERT_EQ(sm.GetVersion()->refAndDependentsState, AssetDefs::Canceled); // Make sure the function that determines which states to update returns the // correct values. ASSERT_TRUE(sm.GetVersion()->updateStateFunc(AssetDefs::New)); ASSERT_TRUE(sm.GetVersion()->updateStateFunc(AssetDefs::Waiting)); ASSERT_TRUE(sm.GetVersion()->updateStateFunc(AssetDefs::Blocked)); ASSERT_TRUE(sm.GetVersion()->updateStateFunc(AssetDefs::Queued)); ASSERT_TRUE(sm.GetVersion()->updateStateFunc(AssetDefs::InProgress)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::Failed)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::Succeeded)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::Canceled)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::Offline)); ASSERT_FALSE(sm.GetVersion()->updateStateFunc(AssetDefs::Bad)); } void CancelWrongState(MockStorageManager & sm, AssetDefs::State state) { sm.GetMutableVersion()->state = state; ASSERT_THROW(CancelVersion(REF, MiscConfig::ALL_GRAPH_OPS), khException); } TEST_F(AssetOperationTest, CancelWrongStateSucceeded) { CancelWrongState(sm, AssetDefs::Succeeded); } TEST_F(AssetOperationTest, CancelWrongStateFailed) { CancelWrongState(sm, AssetDefs::Failed); } TEST_F(AssetOperationTest, CancelWrongStateCanceled) { CancelWrongState(sm, AssetDefs::Canceled); } TEST_F(AssetOperationTest, CancelWrongStateOffline) { CancelWrongState(sm, AssetDefs::Offline); } TEST_F(AssetOperationTest, CancelWrongStateBad) { CancelWrongState(sm, AssetDefs::Bad); } TEST_F(AssetOperationTest, CancelWrongStateNew) { CancelWrongState(sm, AssetDefs::New); } TEST_F(AssetOperationTest, CancelWrongSubtype) { sm.GetMutableVersion()->state = AssetDefs::InProgress; sm.GetMutableVersion()->subtype = "Source"; ASSERT_THROW(CancelVersion(REF, MiscConfig::ALL_GRAPH_OPS), khException); } TEST_F(AssetOperationTest, CancelBadVersion) { sm.GetMutableVersion()->type = AssetDefs::Invalid; CancelVersion(REF, MiscConfig::ALL_GRAPH_OPS); ASSERT_FALSE(sm.GetVersion()->statePropagated); } TEST_F(AssetOperationTest, Progress) { const uint32 TASKID = 123; const time_t BEGIN_TIME = 456; const time_t PROGRESS_TIME = 789; const double PROGRESS = 10.1112; auto msg = TaskProgressMsg(REF, TASKID, BEGIN_TIME, PROGRESS_TIME, PROGRESS); sm.GetMutableVersion()->taskid = TASKID; HandleTaskProgress(msg, MiscConfig::ALL_GRAPH_OPS); ASSERT_EQ(sm.GetVersion()->beginTime, BEGIN_TIME); ASSERT_EQ(sm.GetVersion()->progressTime, PROGRESS_TIME); ASSERT_EQ(sm.GetVersion()->progress, PROGRESS); ASSERT_TRUE(sm.GetVersion()->setProgress); } TEST_F(AssetOperationTest, ProgressWrongTaskId) { const uint32 TASKID = 123; const time_t BEGIN_TIME = 456; const time_t PROGRESS_TIME = 789; const double PROGRESS = 10.1112; auto msg = TaskProgressMsg(REF, TASKID, BEGIN_TIME, PROGRESS_TIME, PROGRESS); sm.GetMutableVersion()->taskid = TASKID + 1; HandleTaskProgress(msg, MiscConfig::ALL_GRAPH_OPS); ASSERT_NE(sm.GetVersion()->beginTime, BEGIN_TIME); ASSERT_NE(sm.GetVersion()->progressTime, PROGRESS_TIME); ASSERT_NE(sm.GetVersion()->progress, PROGRESS); ASSERT_FALSE(sm.GetVersion()->setProgress); } TEST_F(AssetOperationTest, ProgressBadVersion) { const uint32 TASKID = 123; const time_t BEGIN_TIME = 456; const time_t PROGRESS_TIME = 789; const double PROGRESS = 10.1112; sm.GetMutableVersion()->type = AssetDefs::Invalid; auto msg = TaskProgressMsg(REF, TASKID, BEGIN_TIME, PROGRESS_TIME, PROGRESS); sm.GetMutableVersion()->taskid = TASKID + 1; HandleTaskProgress(msg, MiscConfig::ALL_GRAPH_OPS); ASSERT_NE(sm.GetVersion()->beginTime, BEGIN_TIME); ASSERT_NE(sm.GetVersion()->progressTime, PROGRESS_TIME); ASSERT_NE(sm.GetVersion()->progress, PROGRESS); ASSERT_FALSE(sm.GetVersion()->setProgress); } TEST_F(AssetOperationTest, Done) { const uint32 TASKID = 123; const time_t BEGIN_TIME = 456; const time_t END_TIME = 789; const vector<string> OUTFILES = {"x", "y", "z"}; auto msg = TaskDoneMsg(REF, TASKID, true, BEGIN_TIME, END_TIME, OUTFILES); sm.GetMutableVersion()->taskid = TASKID; HandleTaskDone(msg, MiscConfig::ALL_GRAPH_OPS); ASSERT_EQ(sm.GetVersion()->beginTime, BEGIN_TIME); ASSERT_EQ(sm.GetVersion()->progressTime, END_TIME); ASSERT_EQ(sm.GetVersion()->endTime, END_TIME); ASSERT_EQ(sm.GetVersion()->outfiles, OUTFILES); ASSERT_TRUE(sm.GetVersion()->setDone); ASSERT_FALSE(sm.GetVersion()->setFailed); } TEST_F(AssetOperationTest, DoneWrongTaskId) { const uint32 TASKID = 123; const time_t BEGIN_TIME = 456; const time_t END_TIME = 789; const vector<string> OUTFILES = {"x", "y", "z"}; auto msg = TaskDoneMsg(REF, TASKID, true, BEGIN_TIME, END_TIME, OUTFILES); sm.GetMutableVersion()->taskid = TASKID + 1; HandleTaskDone(msg, MiscConfig::ALL_GRAPH_OPS); ASSERT_NE(sm.GetVersion()->beginTime, BEGIN_TIME); ASSERT_NE(sm.GetVersion()->progressTime, END_TIME); ASSERT_NE(sm.GetVersion()->endTime, END_TIME); ASSERT_NE(sm.GetVersion()->outfiles, OUTFILES); ASSERT_FALSE(sm.GetVersion()->setDone); ASSERT_FALSE(sm.GetVersion()->setFailed); } TEST_F(AssetOperationTest, DoneFailed) { const uint32 TASKID = 123; const time_t BEGIN_TIME = 456; const time_t END_TIME = 789; const vector<string> OUTFILES = {"x", "y", "z"}; auto msg = TaskDoneMsg(REF, TASKID, false, BEGIN_TIME, END_TIME, OUTFILES); sm.GetMutableVersion()->taskid = TASKID; HandleTaskDone(msg, MiscConfig::ALL_GRAPH_OPS); ASSERT_TRUE(sm.GetVersion()->setFailed); ASSERT_EQ(sm.GetVersion()->beginTime, BEGIN_TIME); ASSERT_EQ(sm.GetVersion()->progressTime, END_TIME); ASSERT_EQ(sm.GetVersion()->endTime, END_TIME); ASSERT_NE(sm.GetVersion()->outfiles, OUTFILES); ASSERT_FALSE(sm.GetVersion()->setDone); } TEST_F(AssetOperationTest, DoneBadVersion) { const uint32 TASKID = 123; const time_t BEGIN_TIME = 456; const time_t END_TIME = 789; const vector<string> OUTFILES = {"x", "y", "z"}; sm.GetMutableVersion()->type = AssetDefs::Invalid; auto msg = TaskDoneMsg(REF, TASKID, true, BEGIN_TIME, END_TIME, OUTFILES); sm.GetMutableVersion()->taskid = TASKID; HandleTaskDone(msg, MiscConfig::ALL_GRAPH_OPS); ASSERT_NE(sm.GetVersion()->beginTime, BEGIN_TIME); ASSERT_NE(sm.GetVersion()->progressTime, END_TIME); ASSERT_NE(sm.GetVersion()->endTime, END_TIME); ASSERT_NE(sm.GetVersion()->outfiles, OUTFILES); ASSERT_FALSE(sm.GetVersion()->setDone); ASSERT_FALSE(sm.GetVersion()->setFailed); } TEST_F(AssetOperationTest, HandleExternalStateChangeWaiting) { const AssetDefs::State OLD_STATE = AssetDefs::Failed; const WaitingFor WAITING_FOR = {123, 456}; sm.GetMutableVersion()->state = AssetDefs::Queued; HandleExternalStateChange(REF, OLD_STATE, WAITING_FOR.inputs, WAITING_FOR.children, MiscConfig::ALL_GRAPH_OPS); ASSERT_TRUE(sm.GetVersion()->updatedWaiting); ASSERT_EQ(sm.GetVersion()->oldState, OLD_STATE); ASSERT_EQ(sm.GetVersion()->waitingFor.inputs, WAITING_FOR.inputs); ASSERT_EQ(sm.GetVersion()->waitingFor.children, WAITING_FOR.children); ASSERT_FALSE(sm.GetVersion()->updatedSucceeded); } TEST_F(AssetOperationTest, HandleExternalStateChangeSucceeded) { const AssetDefs::State OLD_STATE = AssetDefs::Failed; const WaitingFor WAITING_FOR = {123, 456}; sm.GetMutableVersion()->state = AssetDefs::Succeeded; HandleExternalStateChange(REF, OLD_STATE, WAITING_FOR.inputs, WAITING_FOR.children, MiscConfig::ALL_GRAPH_OPS); ASSERT_TRUE(sm.GetVersion()->updatedWaiting); ASSERT_EQ(sm.GetVersion()->oldState, OLD_STATE); ASSERT_EQ(sm.GetVersion()->waitingFor.inputs, WAITING_FOR.inputs); ASSERT_EQ(sm.GetVersion()->waitingFor.children, WAITING_FOR.children); ASSERT_TRUE(sm.GetVersion()->updatedSucceeded); } TEST_F(AssetOperationTest, HandleExternalStateChangeBadVersion) { const AssetDefs::State OLD_STATE = AssetDefs::Failed; const WaitingFor WAITING_FOR = {123, 456}; sm.GetMutableVersion()->state = AssetDefs::Succeeded; sm.GetMutableVersion()->type = AssetDefs::Invalid; HandleExternalStateChange(REF, OLD_STATE, WAITING_FOR.inputs, WAITING_FOR.children, MiscConfig::ALL_GRAPH_OPS); ASSERT_FALSE(sm.GetVersion()->updatedWaiting); ASSERT_NE(sm.GetVersion()->oldState, OLD_STATE); ASSERT_NE(sm.GetVersion()->waitingFor.inputs, WAITING_FOR.inputs); ASSERT_NE(sm.GetVersion()->waitingFor.children, WAITING_FOR.children); ASSERT_FALSE(sm.GetVersion()->updatedSucceeded); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }
38.064815
113
0.737898
[ "vector" ]
079b834d535787fa42b81bb3c8112965462afb24
1,797
cpp
C++
MerryServer/ShootingHelperMP.cpp
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
MerryServer/ShootingHelperMP.cpp
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
MerryServer/ShootingHelperMP.cpp
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
/* ------------------------------------------------------------------------------------------ Copyright (c) 2014 Vinyl Games Studio Author: Mikhail Kutuzov Date: 9/15/2014 12:19:18 PM ------------------------------------------------------------------------------------------ */ #include "ShootingHelperMP.h" #include "CharacterEntity.h" #include "GameMode.h" #include "ServerEngine.h" #include "Level.h" #include "GameWorld.h" #include "../ToneArmEngine/SpacePartitionTree.h" #include "../ToneArmEngine/PhysicsModule.h" using namespace merrymen; using namespace vgs; // // calculates the direction of a particular shot // glm::vec3 ShootingHelperMP::CalculateShotDirection(CharacterEntity* const shooter, const WeaponStats<WeaponSS>& weaponStats) { return ShootingHelper::CalculateShotDirection<CharacterEntity, WeaponSS>(shooter, weaponStats); } // // fill the passed lists with data relevant for ray casting // void ShootingHelperMP::PreapareGeometryData(std::vector<ColliderComponent*>& geometryColliders, const std::vector<CharacterEntity*>& targets) { // create a bounding box around all enemies to exclude irrelevant colliders from the ray cacting check std::vector<TreeNode<ColliderComponent>*> treeNodes; std::shared_ptr<BoxShape> boxPtr = MathHelper::CreateBoundingBox<CharacterEntity>(targets); BoxShape* boundingBox = boxPtr.get(); // get geometry colliders from the level ServerEngine::GetInstance()->GetModuleByType<PhysicsModule>(EngineModuleType::PHYSICS)->GetSpacePartitionTree()->CullBox(*boundingBox, treeNodes); // transform into shapes for(std::vector<TreeNode<ColliderComponent>* const>::const_iterator iter = treeNodes.begin(); iter != treeNodes.end(); ++iter) { (*iter)->GetObjects(geometryColliders); } treeNodes.clear(); }
33.277778
147
0.685587
[ "geometry", "vector", "transform" ]
07a6738f40bd21d8be71e188664baadb21a65ab2
69,941
cpp
C++
src/dawn/Optimizer/StencilInstantiation.cpp
cosunae/dawn
dc54aee8403812b88df4533fe680e5b95b678411
[ "MIT" ]
null
null
null
src/dawn/Optimizer/StencilInstantiation.cpp
cosunae/dawn
dc54aee8403812b88df4533fe680e5b95b678411
[ "MIT" ]
null
null
null
src/dawn/Optimizer/StencilInstantiation.cpp
cosunae/dawn
dc54aee8403812b88df4533fe680e5b95b678411
[ "MIT" ]
null
null
null
//===--------------------------------------------------------------------------------*- C++ -*-===// // _ // | | // __| | __ ___ ___ ___ // / _` |/ _` \ \ /\ / / '_ | // | (_| | (_| |\ V V /| | | | // \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain // // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #include "dawn/Optimizer/StencilInstantiation.h" #include "dawn/Optimizer/AccessComputation.h" #include "dawn/Optimizer/OptimizerContext.h" #include "dawn/Optimizer/PassTemporaryType.h" #include "dawn/Optimizer/Renaming.h" #include "dawn/Optimizer/Replacing.h" #include "dawn/Optimizer/StatementAccessesPair.h" #include "dawn/SIR/AST.h" #include "dawn/SIR/ASTUtil.h" #include "dawn/SIR/ASTVisitor.h" #include "dawn/SIR/SIR.h" #include "dawn/Support/Casting.h" #include "dawn/Support/FileUtil.h" #include "dawn/Support/Format.h" #include "dawn/Support/Json.h" #include "dawn/Support/Logging.h" #include "dawn/Support/Printing.h" #include "dawn/Support/Twine.h" #include <cstdlib> #include <fstream> #include <functional> #include <iostream> #include <stack> namespace dawn { namespace { //===------------------------------------------------------------------------------------------===// // StatementMapper //===------------------------------------------------------------------------------------------===// /// @brief Map the statements of the AST to a flat list of statements and assign AccessIDs to all /// field, variable and literal accesses. In addition, stencil functions are instantiated. class StatementMapper : public ASTVisitor { /// @brief Representation of the current scope which keeps track of the binding of field and /// variable names struct Scope : public NonCopyable { Scope(const std::string& name, std::vector<std::shared_ptr<StatementAccessesPair>>& statementAccessesPairs, const Interval& interval) : StatementAccessesPairs(statementAccessesPairs), VerticalInterval(interval), ScopeDepth(0), Name(name), FunctionInstantiation(nullptr), ArgumentIndex(0) {} /// List of statement/accesses pair of the stencil function or stage std::vector<std::shared_ptr<StatementAccessesPair>>& StatementAccessesPairs; /// Statement accesses pair pointing to the statement we are currently working on. This might /// not be the top-level statement which was passed to the constructor but rather a /// sub-statement (child) of the top-level statement if decend into nested block statements. std::stack<std::shared_ptr<StatementAccessesPair>> CurentStmtAccessesPair; /// The current interval const Interval& VerticalInterval; /// Scope variable name to (global) AccessID std::unordered_map<std::string, int> LocalVarNameToAccessIDMap; /// Scope field name to (global) AccessID std::unordered_map<std::string, int> LocalFieldnameToAccessIDMap; /// Nesting of scopes int ScopeDepth; /// Name of the current stencil or stencil function std::string Name; /// Reference to the current stencil function (may be NULL) StencilFunctionInstantiation* FunctionInstantiation; /// Counter of the parsed arguments int ArgumentIndex; /// Druring traversal of an argument list of a stencil function, this will hold the scope of /// the new stencil function std::stack<std::shared_ptr<Scope>> CandiateScopes; }; StencilInstantiation* instantiation_; std::shared_ptr<std::vector<sir::StencilCall*>> stackTrace_; std::stack<std::shared_ptr<Scope>> scope_; public: StatementMapper(StencilInstantiation* instantiation, const std::shared_ptr<std::vector<sir::StencilCall*>>& stackTrace, std::string stencilName, std::vector<std::shared_ptr<StatementAccessesPair>>& statementAccessesPairs, const Interval& interval, const std::unordered_map<std::string, int>& localFieldnameToAccessIDMap) : instantiation_(instantiation), stackTrace_(stackTrace) { // Create the initial scope scope_.push(std::make_shared<Scope>(stencilName, statementAccessesPairs, interval)); scope_.top()->LocalFieldnameToAccessIDMap = localFieldnameToAccessIDMap; } Scope* getCurrentCandidateScope() { return (!scope_.top()->CandiateScopes.empty() ? scope_.top()->CandiateScopes.top().get() : nullptr); } void appendNewStatementAccessesPair(const std::shared_ptr<Stmt>& stmt) { if(scope_.top()->ScopeDepth == 1) { // The top-level block statement is collapsed thus we only insert at 1. Note that this works // because all AST have a block statement as root node. scope_.top()->StatementAccessesPairs.emplace_back( std::make_shared<StatementAccessesPair>(std::make_shared<Statement>(stmt, stackTrace_))); scope_.top()->CurentStmtAccessesPair.push(scope_.top()->StatementAccessesPairs.back()); } else if(scope_.top()->ScopeDepth > 1) { // We are inside a nested block statement, we add the stmt as a child of the parent statement scope_.top()->CurentStmtAccessesPair.top()->getChildren().emplace_back( std::make_shared<StatementAccessesPair>(std::make_shared<Statement>(stmt, stackTrace_))); scope_.top()->CurentStmtAccessesPair.push( scope_.top()->CurentStmtAccessesPair.top()->getChildren().back()); } } void removeLastChildStatementAccessesPair() { // The top-level pair is never removed if(scope_.top()->CurentStmtAccessesPair.size() <= 1) return; scope_.top()->CurentStmtAccessesPair.pop(); } void visit(const std::shared_ptr<BlockStmt>& stmt) override { scope_.top()->ScopeDepth++; for(const auto& s : stmt->getStatements()) s->accept(*this); scope_.top()->ScopeDepth--; } void visit(const std::shared_ptr<ExprStmt>& stmt) override { appendNewStatementAccessesPair(stmt); stmt->getExpr()->accept(*this); removeLastChildStatementAccessesPair(); } void visit(const std::shared_ptr<ReturnStmt>& stmt) override { DAWN_ASSERT(scope_.top()->FunctionInstantiation); StencilFunctionInstantiation* curFunc = scope_.top()->FunctionInstantiation; // We can only have 1 return statement if(curFunc->hasReturn()) { DiagnosticsBuilder diag(DiagnosticsKind::Error, curFunc->getStencilFunction()->Loc); diag << "multiple return-statement in stencil function '" << curFunc->getName() << "'"; instantiation_->getOptimizerContext()->getDiagnostics().report(diag); return; } scope_.top()->FunctionInstantiation->setReturn(true); appendNewStatementAccessesPair(stmt); stmt->getExpr()->accept(*this); removeLastChildStatementAccessesPair(); } void visit(const std::shared_ptr<IfStmt>& stmt) override { appendNewStatementAccessesPair(stmt); stmt->getCondExpr()->accept(*this); stmt->getThenStmt()->accept(*this); if(stmt->hasElse()) stmt->getElseStmt()->accept(*this); removeLastChildStatementAccessesPair(); } void visit(const std::shared_ptr<VarDeclStmt>& stmt) override { // This is the first time we encounter this variable. We have to make sure the name is not // already used in another scope! int AccessID = instantiation_->nextUID(); std::string globalName; if(instantiation_->getOptimizerContext()->getOptions().KeepVarnames) globalName = stmt->getName(); else globalName = StencilInstantiation::makeLocalVariablename(stmt->getName(), AccessID); // We generate a new AccessID and insert it into the AccessMaps (using the global name) auto& function = scope_.top()->FunctionInstantiation; if(function) { function->getAccessIDToNameMap().emplace(AccessID, globalName); function->getStmtToCallerAccessIDMap().emplace(stmt, AccessID); } else { instantiation_->setAccessIDNamePair(AccessID, globalName); instantiation_->getStmtToAccessIDMap().emplace(stmt, AccessID); } // Add the mapping to the local scope scope_.top()->LocalVarNameToAccessIDMap.emplace(stmt->getName(), AccessID); // Push back the statement and move on appendNewStatementAccessesPair(stmt); // Resolve the RHS for(const auto& expr : stmt->getInitList()) expr->accept(*this); removeLastChildStatementAccessesPair(); } void visit(const std::shared_ptr<VerticalRegionDeclStmt>& stmt) override { DAWN_ASSERT_MSG(0, "VerticalRegionDeclStmt not allowed in this context"); } void visit(const std::shared_ptr<StencilCallDeclStmt>& stmt) override { DAWN_ASSERT_MSG(0, "StencilCallDeclStmt not allowed in this context"); } void visit(const std::shared_ptr<BoundaryConditionDeclStmt>& stmt) override { DAWN_ASSERT_MSG(0, "StencilCallDeclStmt not allowed in this context"); } void visit(const std::shared_ptr<AssignmentExpr>& expr) override { for(auto& s : expr->getChildren()) s->accept(*this); } void visit(const std::shared_ptr<UnaryOperator>& expr) override { for(auto& s : expr->getChildren()) s->accept(*this); } void visit(const std::shared_ptr<BinaryOperator>& expr) override { for(auto& s : expr->getChildren()) s->accept(*this); } void visit(const std::shared_ptr<TernaryOperator>& expr) override { for(auto& s : expr->getChildren()) s->accept(*this); } void visit(const std::shared_ptr<FunCallExpr>& expr) override { for(auto& s : expr->getChildren()) s->accept(*this); } void visit(const std::shared_ptr<StencilFunCallExpr>& expr) override { // Find the referenced stencil function StencilFunctionInstantiation* stencilFun = nullptr; const Interval& interval = scope_.top()->VerticalInterval; for(auto& SIRStencilFun : instantiation_->getSIR()->StencilFunctions) { if(SIRStencilFun->Name == expr->getCallee()) { std::shared_ptr<AST> ast = nullptr; if(SIRStencilFun->isSpecialized()) { // Select the correct overload ast = SIRStencilFun->getASTOfInterval(interval.asSIRInterval()); if(ast == nullptr) { DiagnosticsBuilder diag(DiagnosticsKind::Error, expr->getSourceLocation()); diag << "no viable Do-Method overload for stencil function call '" << expr->getCallee() << "'"; instantiation_->getOptimizerContext()->getDiagnostics().report(diag); return; } } else { ast = SIRStencilFun->Asts.front(); } // Clone the AST s.t each stencil function has their own AST which is modifiable ast = ast->clone(); stencilFun = instantiation_->makeStencilFunctionInstantiation( expr, SIRStencilFun.get(), ast, interval, scope_.top()->FunctionInstantiation); break; } } DAWN_ASSERT(stencilFun); // If this is a nested function call (e.g the `bar` in `foo(bar(i+1, u))`) register the new // stencil function in the current stencil function if(Scope* candiateScope = getCurrentCandidateScope()) { candiateScope->FunctionInstantiation->setFunctionInstantiationOfArgField( candiateScope->ArgumentIndex, stencilFun); candiateScope->ArgumentIndex += 1; } // Create the scope of the stencil function scope_.top()->CandiateScopes.push(std::make_shared<Scope>( expr->getCallee(), stencilFun->getStatementAccessesPairs(), stencilFun->getInterval())); getCurrentCandidateScope()->FunctionInstantiation = stencilFun; // Resolve the arguments for(auto& arg : expr->getArguments()) arg->accept(*this); // Assign the AccessIDs of the fields in the stencil function Scope* candiateScope = getCurrentCandidateScope(); const auto& arguments = candiateScope->FunctionInstantiation->getArguments(); for(std::size_t argIdx = 0; argIdx < arguments.size(); ++argIdx) if(sir::Field* field = dyn_cast<sir::Field>(arguments[argIdx].get())) { if(candiateScope->FunctionInstantiation->isArgStencilFunctionInstantiation(argIdx)) { // The field is provided by a stencil function call, we create a new AccessID for this // "temporary" field int AccessID = instantiation_->nextUID(); candiateScope->FunctionInstantiation->setIsProvidedByStencilFunctionCall(AccessID); candiateScope->FunctionInstantiation->setCallerAccessIDOfArgField(argIdx, AccessID); candiateScope->FunctionInstantiation->setCallerInitialOffsetFromAccessID( AccessID, Array3i{{0, 0, 0}}); candiateScope->LocalFieldnameToAccessIDMap.emplace(field->Name, AccessID); } else { int AccessID = candiateScope->FunctionInstantiation->getCallerAccessIDOfArgField(argIdx); candiateScope->LocalFieldnameToAccessIDMap.emplace(field->Name, AccessID); } } // Resolve the function scope_.push(scope_.top()->CandiateScopes.top()); scope_.top()->FunctionInstantiation->getAST()->accept(*this); scope_.pop(); // We resolved the candiate function, move on ... scope_.top()->CandiateScopes.pop(); } virtual void visit(const std::shared_ptr<StencilFunArgExpr>& expr) override { DAWN_ASSERT(!scope_.top()->CandiateScopes.empty()); auto& function = scope_.top()->FunctionInstantiation; auto* stencilFun = getCurrentCandidateScope()->FunctionInstantiation; auto& argumentIndex = getCurrentCandidateScope()->ArgumentIndex; bool needsLazyEval = expr->getArgumentIndex() != -1; if(stencilFun->isArgOffset(argumentIndex)) { // Argument is an offset stencilFun->setCallerOffsetOfArgOffset( argumentIndex, needsLazyEval ? function->getCallerOffsetOfArgOffset(expr->getArgumentIndex()) : Array2i{{expr->getDimension(), expr->getOffset()}}); } else { // Argument is a direction stencilFun->setCallerDimensionOfArgDirection( argumentIndex, needsLazyEval ? function->getCallerDimensionOfArgDirection(expr->getArgumentIndex()) : expr->getDimension()); } argumentIndex += 1; } void visit(const std::shared_ptr<VarAccessExpr>& expr) override { auto& function = scope_.top()->FunctionInstantiation; const auto& varname = expr->getName(); if(expr->isExternal()) { DAWN_ASSERT(!function); DAWN_ASSERT_MSG(!expr->isArrayAccess(), "global array access is not supported"); const auto& value = instantiation_->getGlobalVariableValue(varname); if(value.isConstexpr()) { // Replace the variable access with the actual value DAWN_ASSERT_MSG(!value.empty(), "constant global variable with no value"); auto newExpr = std::make_shared<dawn::LiteralAccessExpr>( value.toString(), sir::Value::typeToBuiltinTypeID(value.getType())); replaceOldExprWithNewExprInStmt( scope_.top()->StatementAccessesPairs.back()->getStatement()->ASTStmt, expr, newExpr); int AccessID = instantiation_->nextUID(); instantiation_->getLiteralAccessIDToNameMap().emplace(AccessID, newExpr->getValue()); instantiation_->getExprToAccessIDMap().emplace(newExpr, AccessID); } else { int AccessID = 0; if(!instantiation_->isGlobalVariable(varname)) { AccessID = instantiation_->nextUID(); instantiation_->setAccessIDNamePairOfGlobalVariable(AccessID, varname); } else { AccessID = instantiation_->getAccessIDFromName(varname); } instantiation_->getExprToAccessIDMap().emplace(expr, AccessID); } } else { // Register the mapping between VarAccessExpr and AccessID. if(function) function->getExprToCallerAccessIDMap().emplace( expr, scope_.top()->LocalVarNameToAccessIDMap[varname]); else instantiation_->getExprToAccessIDMap().emplace( expr, scope_.top()->LocalVarNameToAccessIDMap[varname]); // Resolve the index if this is an array access if(expr->isArrayAccess()) expr->getIndex()->accept(*this); } } void visit(const std::shared_ptr<LiteralAccessExpr>& expr) override { // Register a literal access (Note: the negative AccessID we assign!) int AccessID = -instantiation_->nextUID(); auto& function = scope_.top()->FunctionInstantiation; if(function) { function->getLiteralAccessIDToNameMap().emplace(AccessID, expr->getValue()); function->getExprToCallerAccessIDMap().emplace(expr, AccessID); } else { instantiation_->getLiteralAccessIDToNameMap().emplace(AccessID, expr->getValue()); instantiation_->getExprToAccessIDMap().emplace(expr, AccessID); } } void visit(const std::shared_ptr<FieldAccessExpr>& expr) override { // Register the mapping between FieldAccessExpr and AccessID int AccessID = scope_.top()->LocalFieldnameToAccessIDMap[expr->getName()]; auto& function = scope_.top()->FunctionInstantiation; if(function) { function->getExprToCallerAccessIDMap().emplace(expr, AccessID); } else { instantiation_->getExprToAccessIDMap().emplace(expr, AccessID); } if(Scope* candiateScope = getCurrentCandidateScope()) { // We are currently traversing an argument list of a stencil function (create the mapping of // the arguments and compute the initial offset of the field) candiateScope->FunctionInstantiation->setCallerAccessIDOfArgField( candiateScope->ArgumentIndex, AccessID); candiateScope->FunctionInstantiation->setCallerInitialOffsetFromAccessID( AccessID, function ? function->evalOffsetOfFieldAccessExpr(expr) : expr->getOffset()); candiateScope->ArgumentIndex += 1; } } }; //===------------------------------------------------------------------------------------------===// // StencilDescStatementMapper //===------------------------------------------------------------------------------------------===// /// @brief Map the statements of the stencil description AST to a flat list of statements and inline /// all calls to other stencils class StencilDescStatementMapper : public ASTVisitor { /// @brief Record of the current scope (each StencilCall will create a new scope) struct Scope : public NonCopyable { Scope(const std::string& name, std::vector<std::shared_ptr<Statement>>& statements) : Name(name), ScopeDepth(0), Statements(statements), StackTrace(nullptr) {} /// Name of the current stencil std::string Name; /// Nesting of scopes int ScopeDepth; /// List of statements of the stencil description std::vector<std::shared_ptr<Statement>>& Statements; /// Scope fieldnames to to (global) AccessID std::unordered_map<std::string, int> LocalFieldnameToAccessIDMap; /// Scope variable name to (global) AccessID std::unordered_map<std::string, int> LocalVarNameToAccessIDMap; /// Map of known values of variables std::unordered_map<std::string, double> VariableMap; /// Current call stack of stencil calls (may be NULL) std::shared_ptr<std::vector<sir::StencilCall*>> StackTrace; }; StencilInstantiation* instantiation_; std::stack<std::shared_ptr<Scope>> scope_; /// We replace the first VerticalRegionDeclStmt with a dummy node which signals code-gen that it /// should insert a call to the gridtools stencil here std::shared_ptr<Stmt> stencilDescReplacement_; public: StencilDescStatementMapper(StencilInstantiation* instantiation, const std::string& name, std::vector<std::shared_ptr<Statement>>& statements, const std::unordered_map<std::string, int>& fieldnameToAccessIDMap) : instantiation_(instantiation) { // Create the initial scope scope_.push(std::make_shared<Scope>(name, statements)); scope_.top()->LocalFieldnameToAccessIDMap = fieldnameToAccessIDMap; // We add all global variables which have constant values for(const auto& keyValuePair : *instantiation->getSIR()->GlobalVariableMap) { const std::string& key = keyValuePair.first; const sir::Value& value = *keyValuePair.second; if(value.isConstexpr()) { switch(value.getType()) { case sir::Value::Boolean: scope_.top()->VariableMap[key] = value.getValue<bool>(); break; case sir::Value::Integer: scope_.top()->VariableMap[key] = value.getValue<int>(); break; case sir::Value::Double: scope_.top()->VariableMap[key] = value.getValue<double>(); break; default: break; } } } // We start with a single stencil makeNewStencil(); } /// @brief Create a new stencil in the instantiation and prepare the replacement node for the next /// VerticalRegionDeclStmt /// /// @see tryReplaceVerticalRegionDeclStmt void makeNewStencil() { int StencilID = instantiation_->nextUID(); instantiation_->getStencils().emplace_back( make_unique<Stencil>(instantiation_, instantiation_->getSIRStencil(), StencilID)); // We create a paceholder stencil-call for CodeGen to know wehere we need to insert calls to // this stencil auto placeholderStencil = std::make_shared<sir::StencilCall>( StencilInstantiation::makeStencilCallCodeGenName(StencilID)); auto stencilCallDeclStmt = std::make_shared<StencilCallDeclStmt>(placeholderStencil); // Register the call and set it as a replacement for the next vertical region instantiation_->getStencilCallToStencilIDMap().emplace(stencilCallDeclStmt, StencilID); stencilDescReplacement_ = stencilCallDeclStmt; } /// @brief Replace the first VerticalRegionDeclStmt or StencilCallDelcStmt with a dummy /// placeholder signaling code-gen that it should insert a call to the gridtools stencil. /// /// All remaining VerticalRegion/StencilCalls statements which are still in the stencil /// description AST are pruned at the end /// /// @see removeObsoleteStencilDescNodes void tryReplaceStencilDescStmt(const std::shared_ptr<Stmt>& stencilDescNode) { DAWN_ASSERT(stencilDescNode->isStencilDesc()); // Nothing to do, statement was already replaced if(!stencilDescReplacement_) return; // Instead of inserting the VerticalRegionDeclStmt we insert the call to the gridtools stencil if(scope_.top()->ScopeDepth == 1) scope_.top()->Statements.emplace_back( std::make_shared<Statement>(stencilDescReplacement_, scope_.top()->StackTrace)); else { // We need to replace the VerticalRegionDeclStmt in the current statement replaceOldStmtWithNewStmtInStmt(scope_.top()->Statements.back()->ASTStmt, stencilDescNode, stencilDescReplacement_); } stencilDescReplacement_ = nullptr; } /// @brief Remove all VerticalRegionDeclStmt and StencilCallDeclStmt (which do not start with /// `GridToolsStencilCallPrefix`) from the list of statements and remove empty stencils void cleanupStencilDeclAST() { // We only need to remove "nested" nodes as the top-level VerticalRegions or StencilCalls are // not inserted into the statement list in the frist place class RemoveStencilDescNodes : public ASTVisitorForwarding { public: bool needsRemoval(const std::shared_ptr<Stmt>& stmt) const { if(StencilCallDeclStmt* s = dyn_cast<StencilCallDeclStmt>(stmt.get())) { // StencilCallDeclStmt node, remove it if it is not one of our artificial stencil call // nodes if(!StencilInstantiation::isStencilCallCodeGenName(s->getStencilCall()->Callee)) return true; } else if(isa<VerticalRegionDeclStmt>(stmt.get())) // Remove all remaining vertical regions return true; return false; } void visit(const std::shared_ptr<BlockStmt>& stmt) override { for(auto it = stmt->getStatements().begin(); it != stmt->getStatements().end();) { if(needsRemoval(*it)) { it = stmt->getStatements().erase(it); } else { (*it)->accept(*this); ++it; } } } }; // Remove the nested VerticalRegionDeclStmts and StencilCallDeclStmts RemoveStencilDescNodes remover; for(auto& statement : scope_.top()->Statements) statement->ASTStmt->accept(remover); // Remove empty stencils for(auto it = instantiation_->getStencils().begin(); it != instantiation_->getStencils().end();) { Stencil& stencil = **it; if(stencil.isEmpty()) it = instantiation_->getStencils().erase(it); else ++it; } } /// @brief Push back a new statement to the end of the current statement list void pushBackStatement(const std::shared_ptr<Stmt>& stmt) { scope_.top()->Statements.emplace_back( std::make_shared<Statement>(stmt, scope_.top()->StackTrace)); } void visit(const std::shared_ptr<BlockStmt>& stmt) override { scope_.top()->ScopeDepth++; for(const auto& s : stmt->getStatements()) { s->accept(*this); } scope_.top()->ScopeDepth--; } void visit(const std::shared_ptr<ExprStmt>& stmt) override { if(scope_.top()->ScopeDepth == 1) pushBackStatement(stmt); stmt->getExpr()->accept(*this); } void visit(const std::shared_ptr<ReturnStmt>& stmt) override { DAWN_ASSERT_MSG(0, "ReturnStmt not allowed in this context"); } void visit(const std::shared_ptr<IfStmt>& stmt) override { bool result; if(evalExprAsBoolean(stmt->getCondExpr(), result, scope_.top()->VariableMap)) { if(scope_.top()->ScopeDepth == 1) { // The condition is known at compile time, we can remove this If statement completely by // just not inserting it into the statement list if(result) { BlockStmt* thenBody = dyn_cast<BlockStmt>(stmt->getThenStmt().get()); DAWN_ASSERT_MSG(thenBody, "then-body of if-statment should be a BlockStmt!"); for(auto& s : thenBody->getStatements()) s->accept(*this); } else if(stmt->hasElse()) { BlockStmt* elseBody = dyn_cast<BlockStmt>(stmt->getElseStmt().get()); DAWN_ASSERT_MSG(elseBody, "else-body of if-statment should be a BlockStmt!"); for(auto& s : elseBody->getStatements()) s->accept(*this); } } else { // We are inside a nested statement and we need to remove this if-statment and replace it // with either the then-block or the else-block or in case we evaluted to `false` and there // is no else-block we insert a `0` void statement. if(result) { // Replace the if-statement with the then-block replaceOldStmtWithNewStmtInStmt(scope_.top()->Statements.back()->ASTStmt, stmt, stmt->getThenStmt()); stmt->getThenStmt()->accept(*this); } else if(stmt->hasElse()) { // Replace the if-statement with the else-block replaceOldStmtWithNewStmtInStmt(scope_.top()->Statements.back()->ASTStmt, stmt, stmt->getElseStmt()); stmt->getElseStmt()->accept(*this); } else { // Replace the if-statement with a void `0` auto voidExpr = std::make_shared<LiteralAccessExpr>("0", BuiltinTypeID::Float); auto voidStmt = std::make_shared<ExprStmt>(voidExpr); int AccessID = -instantiation_->nextUID(); instantiation_->getLiteralAccessIDToNameMap().emplace(AccessID, "0"); instantiation_->getExprToAccessIDMap().emplace(voidExpr, AccessID); replaceOldStmtWithNewStmtInStmt(scope_.top()->Statements.back()->ASTStmt, stmt, voidStmt); } } } else { if(scope_.top()->ScopeDepth == 1) pushBackStatement(stmt); stmt->getCondExpr()->accept(*this); // The then-part needs to go into a separate stencil ... makeNewStencil(); stmt->getThenStmt()->accept(*this); if(stmt->hasElse()) { // ... same for the else-part makeNewStencil(); stmt->getElseStmt()->accept(*this); } // Everything that follows needs to go into a new stencil as well makeNewStencil(); } } void visit(const std::shared_ptr<VarDeclStmt>& stmt) override { // This is the first time we encounter this variable. We have to make sure the name is not // already used in another scope! int AccessID = instantiation_->nextUID(); std::string globalName; if(instantiation_->getOptimizerContext()->getOptions().KeepVarnames) globalName = stmt->getName(); else globalName = StencilInstantiation::makeLocalVariablename(stmt->getName(), AccessID); instantiation_->setAccessIDNamePair(AccessID, globalName); instantiation_->getStmtToAccessIDMap().emplace(stmt, AccessID); // Add the mapping to the local scope scope_.top()->LocalVarNameToAccessIDMap.emplace(stmt->getName(), AccessID); // Push back the statement and move on if(scope_.top()->ScopeDepth == 1) pushBackStatement(stmt); // Resolve the RHS for(const auto& expr : stmt->getInitList()) expr->accept(*this); // Check if we can evaluate the RHS to a constant expression if(stmt->getInitList().size() == 1) { double result; if(evalExprAsDouble(stmt->getInitList().front(), result, scope_.top()->VariableMap)) scope_.top()->VariableMap[stmt->getName()] = result; } } void visit(const std::shared_ptr<VerticalRegionDeclStmt>& stmt) override { sir::VerticalRegion* verticalRegion = stmt->getVerticalRegion().get(); tryReplaceStencilDescStmt(stmt); Interval interval(*verticalRegion->VerticalInterval); // Note that we may need to operate on copies of the ASTs because we want to have a *unique* // mapping of AST nodes to AccessIDs, hence we clone the ASTs of the vertical regions of // stencil calls bool cloneAST = scope_.size() > 1; std::shared_ptr<AST> ast = cloneAST ? verticalRegion->Ast->clone() : verticalRegion->Ast; // Create the new multi-stage std::shared_ptr<MultiStage> multiStage = std::make_shared<MultiStage>( instantiation_, verticalRegion->LoopOrder == sir::VerticalRegion::LK_Forward ? LoopOrderKind::LK_Forward : LoopOrderKind::LK_Backward); std::shared_ptr<Stage> stage = std::make_shared<Stage>(instantiation_, multiStage.get(), instantiation_->nextUID(), interval); DAWN_LOG(INFO) << "Processing vertical region at " << verticalRegion->Loc; // Here we convert the AST of the vertical region to a flat list of statements of the stage. // Further, we instantiate all referenced stencil functions. DAWN_LOG(INFO) << "Inserting statements ... "; DoMethod& doMethod = stage->getSingleDoMethod(); StatementMapper statementMapper(instantiation_, scope_.top()->StackTrace, scope_.top()->Name, doMethod.getStatementAccessesPairs(), doMethod.getInterval(), scope_.top()->LocalFieldnameToAccessIDMap); ast->accept(statementMapper); DAWN_LOG(INFO) << "Inserted " << doMethod.getStatementAccessesPairs().size() << " statements"; if(instantiation_->getOptimizerContext()->getDiagnostics().hasErrors()) return; // Here we compute the *actual* access of each statement and associate access to the AccessIDs // we set previously. DAWN_LOG(INFO) << "Filling accesses ..."; computeAccesses(instantiation_, doMethod.getStatementAccessesPairs()); // Now, we compute the fields of each stage (this will give us the IO-Policy of the fields) stage->update(); // Put the stage into a separate MultiStage ... multiStage->getStages().push_back(std::move(stage)); // ... and append the MultiStages of the current stencil instantiation_->getStencils().back()->getMultiStages().push_back(std::move(multiStage)); } void visit(const std::shared_ptr<StencilCallDeclStmt>& stmt) override { sir::StencilCall* stencilCall = stmt->getStencilCall().get(); tryReplaceStencilDescStmt(stmt); DAWN_LOG(INFO) << "Processing stencil call to `" << stencilCall->Callee << "` at " << stencilCall->Loc; // Prepare a new scope for the stencil call std::shared_ptr<Scope>& curScope = scope_.top(); std::shared_ptr<Scope> candiateScope = std::make_shared<Scope>(curScope->Name, curScope->Statements); // Variables are inherited from the parent scope (note that this *needs* to be a copy as we // cannot modify the parent scope) candiateScope->VariableMap = curScope->VariableMap; // Record the call if(!curScope->StackTrace) candiateScope->StackTrace = std::make_shared<std::vector<sir::StencilCall*>>(); else candiateScope->StackTrace = std::make_shared<std::vector<sir::StencilCall*>>(*curScope->StackTrace); candiateScope->StackTrace->push_back(stencilCall); // Get the sir::Stencil from the callee name auto stencilIt = std::find_if( instantiation_->getSIR()->Stencils.begin(), instantiation_->getSIR()->Stencils.end(), [&](const std::shared_ptr<sir::Stencil>& s) { return s->Name == stencilCall->Callee; }); DAWN_ASSERT(stencilIt != instantiation_->getSIR()->Stencils.end()); sir::Stencil& stencil = **stencilIt; // We need less or an equal amount of args as temporaries are added implicitly DAWN_ASSERT(stencilCall->Args.size() <= stencil.Fields.size()); // Map the field arguments for(std::size_t stencilArgIdx = 0, stencilCallArgIdx = 0; stencilArgIdx < stencil.Fields.size(); ++stencilArgIdx) { int AccessID = 0; if(stencil.Fields[stencilArgIdx]->IsTemporary) { // We add a new temporary field for each temporary field argument AccessID = instantiation_->nextUID(); instantiation_->setAccessIDNamePairOfField( AccessID, StencilInstantiation::makeTemporaryFieldname( stencil.Fields[stencilArgIdx]->Name, AccessID), true); } else { AccessID = curScope->LocalFieldnameToAccessIDMap.find(stencilCall->Args[stencilCallArgIdx]->Name) ->second; stencilCallArgIdx++; } candiateScope->LocalFieldnameToAccessIDMap.emplace(stencil.Fields[stencilArgIdx]->Name, AccessID); } // Process the stencil description AST of the callee. scope_.push(candiateScope); // As we *may* modify the AST we better make a copy here otherwise we get funny surprises if we // call this stencil multiple times ... stencil.StencilDescAst->clone()->accept(*this); scope_.pop(); DAWN_LOG(INFO) << "Done processing stencil call to `" << stencilCall->Callee << "`"; } void visit(const std::shared_ptr<BoundaryConditionDeclStmt>& stmt) override { DAWN_ASSERT_MSG(0, "BoundaryConditionDeclStmt not yet implemented"); } void visit(const std::shared_ptr<AssignmentExpr>& expr) override { for(auto& s : expr->getChildren()) s->accept(*this); // If the LHS is known to be a known constant, we need to update its value or remove it as // being compile time constant if(VarAccessExpr* var = dyn_cast<VarAccessExpr>(expr->getLeft().get())) { if(scope_.top()->VariableMap.count(var->getName())) { double result; if(evalExprAsDouble(expr->getRight(), result, scope_.top()->VariableMap)) { if(StringRef(expr->getOp()) == "=") scope_.top()->VariableMap[var->getName()] = result; else if(StringRef(expr->getOp()) == "+=") scope_.top()->VariableMap[var->getName()] += result; else if(StringRef(expr->getOp()) == "-=") scope_.top()->VariableMap[var->getName()] -= result; else if(StringRef(expr->getOp()) == "*=") scope_.top()->VariableMap[var->getName()] *= result; else if(StringRef(expr->getOp()) == "/=") scope_.top()->VariableMap[var->getName()] /= result; else // unknown operator scope_.top()->VariableMap.erase(var->getName()); } else scope_.top()->VariableMap.erase(var->getName()); } } } void visit(const std::shared_ptr<UnaryOperator>& expr) override { for(auto& s : expr->getChildren()) s->accept(*this); } void visit(const std::shared_ptr<BinaryOperator>& expr) override { for(auto& s : expr->getChildren()) s->accept(*this); } void visit(const std::shared_ptr<TernaryOperator>& expr) override { for(auto& s : expr->getChildren()) s->accept(*this); } void visit(const std::shared_ptr<FunCallExpr>& expr) override { for(auto& s : expr->getChildren()) s->accept(*this); } void visit(const std::shared_ptr<StencilFunCallExpr>& expr) override { DAWN_ASSERT_MSG(0, "StencilFunCallExpr not allowed in this context"); } void visit(const std::shared_ptr<StencilFunArgExpr>& expr) override { DAWN_ASSERT_MSG(0, "StencilFunArgExpr not allowed in this context"); } void visit(const std::shared_ptr<VarAccessExpr>& expr) override { const auto& varname = expr->getName(); if(expr->isExternal()) { DAWN_ASSERT_MSG(!expr->isArrayAccess(), "global array access is not supported"); const auto& value = instantiation_->getGlobalVariableValue(varname); if(value.isConstexpr()) { // Replace the variable access with the actual value DAWN_ASSERT_MSG(!value.empty(), "constant global variable with no value"); auto newExpr = std::make_shared<dawn::LiteralAccessExpr>( value.toString(), sir::Value::typeToBuiltinTypeID(value.getType())); replaceOldExprWithNewExprInStmt(scope_.top()->Statements.back()->ASTStmt, expr, newExpr); int AccessID = instantiation_->nextUID(); instantiation_->getLiteralAccessIDToNameMap().emplace(AccessID, newExpr->getValue()); instantiation_->getExprToAccessIDMap().emplace(newExpr, AccessID); } else { int AccessID = 0; if(!instantiation_->isGlobalVariable(varname)) { AccessID = instantiation_->nextUID(); instantiation_->setAccessIDNamePairOfGlobalVariable(AccessID, varname); } else { AccessID = instantiation_->getAccessIDFromName(varname); } instantiation_->getExprToAccessIDMap().emplace(expr, AccessID); } } else { // Register the mapping between VarAccessExpr and AccessID. instantiation_->getExprToAccessIDMap().emplace( expr, scope_.top()->LocalVarNameToAccessIDMap[varname]); // Resolve the index if this is an array access if(expr->isArrayAccess()) expr->getIndex()->accept(*this); } } void visit(const std::shared_ptr<LiteralAccessExpr>& expr) override { // Register a literal access (Note: the negative AccessID we assign!) int AccessID = -instantiation_->nextUID(); instantiation_->getLiteralAccessIDToNameMap().emplace(AccessID, expr->getValue()); instantiation_->getExprToAccessIDMap().emplace(expr, AccessID); } void visit(const std::shared_ptr<FieldAccessExpr>& expr) override {} }; } // anonymous namespace //===------------------------------------------------------------------------------------------===// // StencilInstantiation //===------------------------------------------------------------------------------------------===// StencilInstantiation::StencilInstantiation(OptimizerContext* context, const sir::Stencil* SIRStencil, const SIR* SIR) : context_(context), SIRStencil_(SIRStencil), SIR_(SIR) { DAWN_LOG(INFO) << "Intializing StencilInstantiation of `" << SIRStencil->Name << "`"; DAWN_ASSERT_MSG(SIRStencil, "Stencil does not exist"); // Map the fields of the "main stencil" to unique IDs (which are used in the access maps to // indentify the field). for(const auto& field : SIRStencil->Fields) { int AccessID = nextUID(); setAccessIDNamePairOfField(AccessID, field->Name, field->IsTemporary); } // Process the stencil description of the "main stencil" StencilDescStatementMapper stencilDeclMapper(this, getName(), stencilDescStatements_, NameToAccessIDMap_); // We need to operate on a copy of the AST as we may modify the nodes inplace auto AST = SIRStencil->StencilDescAst->clone(); AST->accept(stencilDeclMapper); // Cleanup the `stencilDescStatements` and remove the empty stencils which may have been inserted stencilDeclMapper.cleanupStencilDeclAST(); // Repair broken references to temporaries i.e promote them to real fields PassTemporaryType::fixTemporariesSpanningMultipleStencils(this, stencils_); if(context_->getOptions().ReportAccesses) reportAccesses(); DAWN_LOG(INFO) << "Done initializing StencilInstantiation"; } void StencilInstantiation::setAccessIDNamePair(int AccessID, const std::string& name) { AccessIDToNameMap_.emplace(AccessID, name); NameToAccessIDMap_.emplace(name, AccessID); } void StencilInstantiation::setAccessIDNamePairOfField(int AccessID, const std::string& name, bool isTemporary) { setAccessIDNamePair(AccessID, name); FieldAccessIDSet_.insert(AccessID); if(isTemporary) TemporaryFieldAccessIDSet_.insert(AccessID); } void StencilInstantiation::setAccessIDNamePairOfGlobalVariable(int AccessID, const std::string& name) { setAccessIDNamePair(AccessID, name); GlobalVariableAccessIDSet_.insert(AccessID); } void StencilInstantiation::removeAccessID(int AccesssID) { if(NameToAccessIDMap_.count(AccessIDToNameMap_[AccesssID])) NameToAccessIDMap_.erase(AccessIDToNameMap_[AccesssID]); AccessIDToNameMap_.erase(AccesssID); FieldAccessIDSet_.erase(AccesssID); TemporaryFieldAccessIDSet_.erase(AccesssID); auto fieldVersionIt = FieldVersionsMap_.find(AccesssID); if(fieldVersionIt != FieldVersionsMap_.end()) { std::vector<int>& versions = *fieldVersionIt->second; versions.erase( std::remove_if(versions.begin(), versions.end(), [&](int AID) { return AID == AccesssID; }), versions.end()); } } const std::string& StencilInstantiation::getName() const { return SIRStencil_->Name; } const std::unordered_map<std::shared_ptr<Expr>, int>& StencilInstantiation::getExprToAccessIDMap() const { return ExprToAccessIDMap_; } std::unordered_map<std::shared_ptr<Expr>, int>& StencilInstantiation::getExprToAccessIDMap() { return ExprToAccessIDMap_; } const std::unordered_map<std::shared_ptr<Stmt>, int>& StencilInstantiation::getStmtToAccessIDMap() const { return StmtToAccessIDMap_; } std::unordered_map<std::shared_ptr<Stmt>, int>& StencilInstantiation::getStmtToAccessIDMap() { return StmtToAccessIDMap_; } const std::string& StencilInstantiation::getNameFromAccessID(int AccessID) const { if(AccessID < 0) return getNameFromLiteralAccessID(AccessID); auto it = AccessIDToNameMap_.find(AccessID); DAWN_ASSERT_MSG(it != AccessIDToNameMap_.end(), "Invalid AccessID"); return it->second; } const std::string& StencilInstantiation::getNameFromStageID(int StageID) const { auto it = StageIDToNameMap_.find(StageID); DAWN_ASSERT_MSG(it != StageIDToNameMap_.end(), "Invalid StageID"); return it->second; } const std::string& StencilInstantiation::getNameFromLiteralAccessID(int AccessID) const { DAWN_ASSERT_MSG(isLiteral(AccessID), "Invalid literal"); return LiteralAccessIDToNameMap_.find(AccessID)->second; } bool StencilInstantiation::isGlobalVariable(const std::string& name) const { auto it = NameToAccessIDMap_.find(name); return it == NameToAccessIDMap_.end() ? false : isGlobalVariable(it->second); } const sir::Value& StencilInstantiation::getGlobalVariableValue(const std::string& name) const { auto it = getSIR()->GlobalVariableMap->find(name); DAWN_ASSERT(it != getSIR()->GlobalVariableMap->end()); return *it->second; } ArrayRef<int> StencilInstantiation::getFieldVersions(int AccessID) const { auto it = FieldVersionsMap_.find(AccessID); return it != FieldVersionsMap_.end() ? ArrayRef<int>(*it->second) : ArrayRef<int>{}; } int StencilInstantiation::createVersionAndRename(int AccessID, Stencil* stencil, int curStageIdx, int curStmtIdx, std::shared_ptr<Expr>& expr, RenameDirection dir) { int newAccessID = nextUID(); if(isField(AccessID)) { auto it = FieldVersionsMap_.find(AccessID); if(it != FieldVersionsMap_.end()) { // Field is already multi-versioned, append a new version std::vector<int>& versions = *it->second; // Set the second to last field to be a temporary (only the first and the last field will be // real storages, all other versions will be temporaries) int lastAccessID = versions.back(); TemporaryFieldAccessIDSet_.insert(lastAccessID); AllocatedFieldAccessIDSet_.erase(lastAccessID); // The field with version 0 contains the original name const std::string& originalName = getNameFromAccessID(versions.front()); // Register the new field setAccessIDNamePairOfField(newAccessID, originalName + "_" + std::to_string(versions.size()), false); AllocatedFieldAccessIDSet_.insert(newAccessID); versions.push_back(newAccessID); FieldVersionsMap_.emplace(newAccessID, it->second); } else { const std::string& originalName = getNameFromAccessID(AccessID); // Register the new *and* old field as being multi-versioned and indicate code-gen it has to // allocate the second version auto versionsVecPtr = std::make_shared<std::vector<int>>(); *versionsVecPtr = {AccessID, newAccessID}; setAccessIDNamePairOfField(newAccessID, originalName + "_1", false); AllocatedFieldAccessIDSet_.insert(newAccessID); FieldVersionsMap_.emplace(AccessID, versionsVecPtr); FieldVersionsMap_.emplace(newAccessID, versionsVecPtr); } } else { auto it = VariableVersionsMap_.find(AccessID); if(it != VariableVersionsMap_.end()) { // Variable is already multi-versioned, append a new version std::vector<int>& versions = *it->second; // The variable with version 0 contains the original name const std::string& originalName = getNameFromAccessID(versions.front()); // Register the new variable setAccessIDNamePair(newAccessID, originalName + "_" + std::to_string(versions.size())); versions.push_back(newAccessID); VariableVersionsMap_.emplace(newAccessID, it->second); } else { const std::string& originalName = getNameFromAccessID(AccessID); // Register the new *and* old variable as being multi-versioned auto versionsVecPtr = std::make_shared<std::vector<int>>(); *versionsVecPtr = {AccessID, newAccessID}; setAccessIDNamePair(newAccessID, originalName + "_1"); VariableVersionsMap_.emplace(AccessID, versionsVecPtr); VariableVersionsMap_.emplace(newAccessID, versionsVecPtr); } } // Rename the Expression renameAccessIDInExpr(this, AccessID, newAccessID, expr); // Recompute the accesses of the current statement (only works with single Do-Methods - for now) computeAccesses( this, stencil->getStage(curStageIdx)->getSingleDoMethod().getStatementAccessesPairs()[curStmtIdx]); // Rename the statement and accesses for(int stageIdx = curStageIdx; dir == RD_Above ? (stageIdx >= 0) : (stageIdx < stencil->getNumStages()); dir == RD_Above ? stageIdx-- : stageIdx++) { Stage& stage = *stencil->getStage(stageIdx); DoMethod& doMethod = stage.getSingleDoMethod(); if(stageIdx == curStageIdx) { for(int i = dir == RD_Above ? (curStmtIdx - 1) : (curStmtIdx + 1); dir == RD_Above ? (i >= 0) : (i < doMethod.getStatementAccessesPairs().size()); dir == RD_Above ? (--i) : (++i)) { renameAccessIDInStmts(this, AccessID, newAccessID, doMethod.getStatementAccessesPairs()[i]); renameAccessIDInAccesses(this, AccessID, newAccessID, doMethod.getStatementAccessesPairs()[i]); } } else { renameAccessIDInStmts(this, AccessID, newAccessID, doMethod.getStatementAccessesPairs()); renameAccessIDInAccesses(this, AccessID, newAccessID, doMethod.getStatementAccessesPairs()); } // Updat the fields of the stage stage.update(); } return newAccessID; } void StencilInstantiation::renameAllOccurrences(Stencil* stencil, int oldAccessID, int newAccessID) { // Rename the statements and accesses stencil->renameAllOccurrences(oldAccessID, newAccessID); // Remove form all AccessID maps removeAccessID(oldAccessID); } void StencilInstantiation::promoteLocalVariableToTemporaryField(Stencil* stencil, int AccessID, const Stencil::Lifetime& lifetime) { std::string varname = getNameFromAccessID(AccessID); std::string fieldname = StencilInstantiation::makeTemporaryFieldname( StencilInstantiation::extractLocalVariablename(varname), AccessID); // Replace all variable accesses with field accesses stencil->forEachStatementAccessesPair( [&](ArrayRef<std::shared_ptr<StatementAccessesPair>> statementAccessesPair) -> void { replaceVarWithFieldAccessInStmts(stencil, AccessID, fieldname, statementAccessesPair); }, lifetime); // Replace the the variable declaration with an assignment to the temporary field std::vector<std::shared_ptr<StatementAccessesPair>>& statementAccessesPairs = stencil->getStage(lifetime.Begin.StagePos) ->getDoMethods()[lifetime.Begin.DoMethodIndex] ->getStatementAccessesPairs(); std::shared_ptr<Statement> oldStatement = statementAccessesPairs[lifetime.Begin.StatementIndex]->getStatement(); // The oldStmt has to be a `VarDeclStmt`. For example // // double __local_foo = ... // // will be replaced with // // __tmp_foo(0, 0, 0) = ... // VarDeclStmt* varDeclStmt = dyn_cast<VarDeclStmt>(oldStatement->ASTStmt.get()); DAWN_ASSERT_MSG(varDeclStmt, "first access to variable (i.e lifetime.Begin) is not an `VarDeclStmt`"); DAWN_ASSERT_MSG(!varDeclStmt->isArray(), "cannot promote local array to temporary field"); auto fieldAccessExpr = std::make_shared<FieldAccessExpr>(fieldname); ExprToAccessIDMap_.emplace(fieldAccessExpr, AccessID); auto assignmentExpr = std::make_shared<AssignmentExpr>(fieldAccessExpr, varDeclStmt->getInitList().front()); auto exprStmt = std::make_shared<ExprStmt>(assignmentExpr); // Replace the statement statementAccessesPairs[lifetime.Begin.StatementIndex]->setStatement( std::make_shared<Statement>(exprStmt, oldStatement->StackTrace)); // Remove the variable removeAccessID(AccessID); StmtToAccessIDMap_.erase(oldStatement->ASTStmt); // Register the field setAccessIDNamePairOfField(AccessID, fieldname, true); // Update the fields of the stages we modified stencil->updateFields(lifetime); } void StencilInstantiation::promoteTemporaryFieldToAllocatedField(int AccessID) { DAWN_ASSERT(isTemporaryField(AccessID)); TemporaryFieldAccessIDSet_.erase(AccessID); AllocatedFieldAccessIDSet_.insert(AccessID); } void StencilInstantiation::demoteTemporaryFieldToLocalVariable(Stencil* stencil, int AccessID, const Stencil::Lifetime& lifetime) { std::string fieldname = getNameFromAccessID(AccessID); std::string varname = StencilInstantiation::makeLocalVariablename( StencilInstantiation::extractTemporaryFieldname(fieldname), AccessID); // Replace all field accesses with variable accesses stencil->forEachStatementAccessesPair( [&](ArrayRef<std::shared_ptr<StatementAccessesPair>> statementAccessesPairs) -> void { replaceFieldWithVarAccessInStmts(stencil, AccessID, varname, statementAccessesPairs); }, lifetime); // Replace the first access to the field with a VarDeclStmt std::vector<std::shared_ptr<StatementAccessesPair>>& statementAccessesPairs = stencil->getStage(lifetime.Begin.StagePos) ->getDoMethods()[lifetime.Begin.DoMethodIndex] ->getStatementAccessesPairs(); std::shared_ptr<Statement> oldStatement = statementAccessesPairs[lifetime.Begin.StatementIndex]->getStatement(); // The oldStmt has to be an `ExprStmt` with an `AssignmentExpr`. For example // // __tmp_foo(0, 0, 0) = ... // // will be replaced with // // double __local_foo = ... // ExprStmt* exprStmt = dyn_cast<ExprStmt>(oldStatement->ASTStmt.get()); DAWN_ASSERT_MSG(exprStmt, "first access of field (i.e lifetime.Begin) is not an `ExprStmt`"); AssignmentExpr* assignmentExpr = dyn_cast<AssignmentExpr>(exprStmt->getExpr().get()); DAWN_ASSERT_MSG(assignmentExpr, "first access of field (i.e lifetime.Begin) is not an `AssignmentExpr`"); // Create the new `VarDeclStmt` which will replace the old `ExprStmt` std::shared_ptr<Stmt> varDeclStmt = std::make_shared<VarDeclStmt>(Type(BuiltinTypeID::Float), varname, 0, "=", std::vector<std::shared_ptr<Expr>>{assignmentExpr->getRight()}); // Replace the statement statementAccessesPairs[lifetime.Begin.StatementIndex]->setStatement( std::make_shared<Statement>(varDeclStmt, oldStatement->StackTrace)); // Remove the field removeAccessID(AccessID); // Register the variable setAccessIDNamePair(AccessID, varname); StmtToAccessIDMap_.emplace(varDeclStmt, AccessID); // Update the fields of the stages we modified stencil->updateFields(lifetime); } int StencilInstantiation::getAccessIDFromName(const std::string& name) const { auto it = NameToAccessIDMap_.find(name); DAWN_ASSERT_MSG(it != NameToAccessIDMap_.end(), "Invalid name"); return it->second; } int StencilInstantiation::getAccessIDFromExpr(const std::shared_ptr<Expr>& expr) const { auto it = ExprToAccessIDMap_.find(expr); DAWN_ASSERT_MSG(it != ExprToAccessIDMap_.end(), "Invalid Expr"); return it->second; } int StencilInstantiation::getAccessIDFromStmt(const std::shared_ptr<Stmt>& stmt) const { auto it = StmtToAccessIDMap_.find(stmt); DAWN_ASSERT_MSG(it != StmtToAccessIDMap_.end(), "Invalid Stmt"); return it->second; } void StencilInstantiation::removeStencilFunctionInstantiation( const std::shared_ptr<StencilFunCallExpr>& expr, StencilFunctionInstantiation* callerStencilFunctionInstantiation) { StencilFunctionInstantiation* func = nullptr; if(callerStencilFunctionInstantiation) { func = callerStencilFunctionInstantiation->getStencilFunctionInstantiation(expr); callerStencilFunctionInstantiation->getExprToStencilFunctionInstantiationMap().erase(expr); } else { func = getStencilFunctionInstantiation(expr); ExprToStencilFunctionInstantiationMap_.erase(expr); } for(auto it = stencilFunctionInstantiations_.begin(); it != stencilFunctionInstantiations_.end();) { if(it->get() == func) it = stencilFunctionInstantiations_.erase(it); else ++it; } } StencilFunctionInstantiation* StencilInstantiation::getStencilFunctionInstantiation( const std::shared_ptr<StencilFunCallExpr>& expr) { auto it = ExprToStencilFunctionInstantiationMap_.find(expr); DAWN_ASSERT_MSG(it != ExprToStencilFunctionInstantiationMap_.end(), "Invalid stencil function"); return it->second; } const StencilFunctionInstantiation* StencilInstantiation::getStencilFunctionInstantiation( const std::shared_ptr<StencilFunCallExpr>& expr) const { auto it = ExprToStencilFunctionInstantiationMap_.find(expr); DAWN_ASSERT_MSG(it != ExprToStencilFunctionInstantiationMap_.end(), "Invalid stencil function"); return it->second; } std::unordered_map<std::shared_ptr<StencilFunCallExpr>, StencilFunctionInstantiation*>& StencilInstantiation::getExprToStencilFunctionInstantiationMap() { return ExprToStencilFunctionInstantiationMap_; } const std::unordered_map<std::shared_ptr<StencilFunCallExpr>, StencilFunctionInstantiation*>& StencilInstantiation::getExprToStencilFunctionInstantiationMap() const { return ExprToStencilFunctionInstantiationMap_; } StencilFunctionInstantiation* StencilInstantiation::makeStencilFunctionInstantiation( const std::shared_ptr<StencilFunCallExpr>& expr, sir::StencilFunction* SIRStencilFun, const std::shared_ptr<AST>& ast, const Interval& interval, StencilFunctionInstantiation* curStencilFunctionInstantiation) { stencilFunctionInstantiations_.emplace_back(make_unique<StencilFunctionInstantiation>( this, expr, SIRStencilFun, ast, interval, curStencilFunctionInstantiation != nullptr)); StencilFunctionInstantiation* stencilFun = stencilFunctionInstantiations_.back().get(); if(curStencilFunctionInstantiation) { curStencilFunctionInstantiation->getExprToStencilFunctionInstantiationMap().emplace(expr, stencilFun); } else { ExprToStencilFunctionInstantiationMap_.emplace(expr, stencilFun); } return stencilFun; } std::unordered_map<std::shared_ptr<StencilCallDeclStmt>, int>& StencilInstantiation::getStencilCallToStencilIDMap() { return StencilCallToStencilIDMap_; } const std::unordered_map<std::shared_ptr<StencilCallDeclStmt>, int>& StencilInstantiation::getStencilCallToStencilIDMap() const { return StencilCallToStencilIDMap_; } int StencilInstantiation::getStencilIDFromStmt( const std::shared_ptr<StencilCallDeclStmt>& stmt) const { auto it = StencilCallToStencilIDMap_.find(stmt); DAWN_ASSERT_MSG(it != StencilCallToStencilIDMap_.end(), "Invalid stencil call"); return it->second; } std::unordered_map<std::string, int>& StencilInstantiation::getNameToAccessIDMap() { return NameToAccessIDMap_; } const std::unordered_map<std::string, int>& StencilInstantiation::getNameToAccessIDMap() const { return NameToAccessIDMap_; } std::unordered_map<int, std::string>& StencilInstantiation::getAccessIDToNameMap() { return AccessIDToNameMap_; } const std::unordered_map<int, std::string>& StencilInstantiation::getAccessIDToNameMap() const { return AccessIDToNameMap_; } std::unordered_map<int, std::string>& StencilInstantiation::getLiteralAccessIDToNameMap() { return LiteralAccessIDToNameMap_; } const std::unordered_map<int, std::string>& StencilInstantiation::getLiteralAccessIDToNameMap() const { return LiteralAccessIDToNameMap_; } std::unordered_map<int, std::string>& StencilInstantiation::getStageIDToNameMap() { return StageIDToNameMap_; } const std::unordered_map<int, std::string>& StencilInstantiation::getStageIDToNameMap() const { return StageIDToNameMap_; } std::set<int>& StencilInstantiation::getFieldAccessIDSet() { return FieldAccessIDSet_; } const std::set<int>& StencilInstantiation::getFieldAccessIDSet() const { return FieldAccessIDSet_; } std::set<int>& StencilInstantiation::getGlobalVariableAccessIDSet() { return GlobalVariableAccessIDSet_; } const std::set<int>& StencilInstantiation::getGlobalVariableAccessIDSet() const { return GlobalVariableAccessIDSet_; } namespace { /// @brief Get the orignal name of the field (or variable) given by AccessID and a list of /// SourceLocations where this field (or variable) was accessed. class OriginalNameGetter : public ASTVisitorForwarding { const StencilInstantiation* instantiation_; const int AccessID_; const bool captureLocation_; std::string name_; std::vector<SourceLocation> locations_; public: OriginalNameGetter(const StencilInstantiation* instantiation, int AccessID, bool captureLocation) : instantiation_(instantiation), AccessID_(AccessID), captureLocation_(captureLocation) {} virtual void visit(const std::shared_ptr<VarDeclStmt>& stmt) override { if(instantiation_->getAccessIDFromStmt(stmt) == AccessID_) { name_ = stmt->getName(); if(captureLocation_) locations_.push_back(stmt->getSourceLocation()); } for(const auto& expr : stmt->getInitList()) expr->accept(*this); } void visit(const std::shared_ptr<VarAccessExpr>& expr) override { if(instantiation_->getAccessIDFromExpr(expr) == AccessID_) { name_ = expr->getName(); if(captureLocation_) locations_.push_back(expr->getSourceLocation()); } } void visit(const std::shared_ptr<LiteralAccessExpr>& expr) override { if(instantiation_->getAccessIDFromExpr(expr) == AccessID_) { name_ = expr->getValue(); if(captureLocation_) locations_.push_back(expr->getSourceLocation()); } } virtual void visit(const std::shared_ptr<FieldAccessExpr>& expr) override { if(instantiation_->getAccessIDFromExpr(expr) == AccessID_) { name_ = expr->getName(); if(captureLocation_) locations_.push_back(expr->getSourceLocation()); } } std::pair<std::string, std::vector<SourceLocation>> getNameLocationPair() const { return std::make_pair(name_, locations_); } bool hasName() const { return !name_.empty(); } std::string getName() const { return name_; } }; } // anonymous namespace std::pair<std::string, std::vector<SourceLocation>> StencilInstantiation::getOriginalNameAndLocationsFromAccessID( int AccessID, const std::shared_ptr<Stmt>& stmt) const { OriginalNameGetter orignalNameGetter(this, AccessID, true); stmt->accept(orignalNameGetter); return orignalNameGetter.getNameLocationPair(); } std::string StencilInstantiation::getOriginalNameFromAccessID(int AccessID) const { OriginalNameGetter orignalNameGetter(this, AccessID, true); for(const auto& stencil : stencils_) for(const auto& multistage : stencil->getMultiStages()) for(const auto& stage : multistage->getStages()) for(const auto& doMethod : stage->getDoMethods()) for(const auto& statementAccessesPair : doMethod->getStatementAccessesPairs()) { statementAccessesPair->getStatement()->ASTStmt->accept(orignalNameGetter); if(orignalNameGetter.hasName()) return orignalNameGetter.getName(); } // Best we can do... return getNameFromAccessID(AccessID); } namespace { template <int Level> struct PrintDescLine { PrintDescLine(const Twine& name) { std::cout << MakeIndent<Level>::value << format("\e[1;3%im", Level) << name.str() << "\n" << MakeIndent<Level>::value << "{\n\e[0m"; } ~PrintDescLine() { std::cout << MakeIndent<Level>::value << format("\e[1;3%im}\n\e[0m", Level); } }; } // anonymous namespace void StencilInstantiation::dump() const { std::cout << "StencilInstantiation : " << getName() << "\n"; for(std::size_t i = 0; i < stencils_.size(); ++i) { PrintDescLine<1> iline("Stencil_" + Twine(i)); int j = 0; const auto& multiStages = stencils_[i]->getMultiStages(); for(const auto& multiStage : multiStages) { PrintDescLine<2> jline(Twine("MultiStage_") + Twine(j) + " [" + loopOrderToString(multiStage->getLoopOrder()) + "]"); int k = 0; const auto& stages = multiStage->getStages(); for(const auto& stage : stages) { PrintDescLine<3> kline(Twine("Stage_") + Twine(k)); int l = 0; const auto& doMethods = stage->getDoMethods(); for(const auto& doMethod : doMethods) { PrintDescLine<4> lline(Twine("Do_") + Twine(l) + " " + doMethod->getInterval().toString()); const auto& statementAccessesPairs = doMethod->getStatementAccessesPairs(); for(std::size_t m = 0; m < statementAccessesPairs.size(); ++m) { std::cout << "\e[1m" << ASTStringifer::toString(statementAccessesPairs[m]->getStatement()->ASTStmt, 5 * DAWN_PRINT_INDENT) << "\e[0m"; std::cout << statementAccessesPairs[m]->getAccesses()->toString(this, 6 * DAWN_PRINT_INDENT) << "\n"; } l += 1; } k += 1; } j += 1; } } std::cout.flush(); } void StencilInstantiation::dumpAsJson(std::string filename, std::string passName) const { json::json jout; for(int i = 0; i < stencils_.size(); ++i) { json::json jStencil; int j = 0; const auto& multiStages = stencils_[i]->getMultiStages(); for(const auto& multiStage : multiStages) { json::json jMultiStage; jMultiStage["LoopOrder"] = loopOrderToString(multiStage->getLoopOrder()); int k = 0; const auto& stages = multiStage->getStages(); for(const auto& stage : stages) { json::json jStage; int l = 0; for(const auto& doMethod : stage->getDoMethods()) { json::json jDoMethod; jDoMethod["Interval"] = doMethod->getInterval().toString(); const auto& statementAccessesPairs = doMethod->getStatementAccessesPairs(); for(std::size_t m = 0; m < statementAccessesPairs.size(); ++m) { jDoMethod["Stmt_" + std::to_string(m)] = ASTStringifer::toString( statementAccessesPairs[m]->getStatement()->ASTStmt, 0, false); jDoMethod["Accesses_" + std::to_string(m)] = statementAccessesPairs[m]->getAccesses()->reportAccesses(this); } jStage["Do_" + std::to_string(l++)] = jDoMethod; } jMultiStage["Stage_" + std::to_string(k++)] = jStage; } jStencil["MultiStage_" + std::to_string(j++)] = jMultiStage; } if(passName.empty()) jout[getName()]["Stencil_" + std::to_string(i)] = jStencil; else jout[passName][getName()]["Stencil_" + std::to_string(i)] = jStencil; } std::ofstream fs(filename, std::ios::out | std::ios::trunc); if(!fs.is_open()) { DiagnosticsBuilder diag(DiagnosticsKind::Error, SourceLocation()); diag << "file system error: cannot open file: " << filename; context_->getDiagnostics().report(diag); } fs << jout.dump(2) << std::endl; fs.close(); } static std::string makeNameImpl(const char* prefix, const std::string& name, int AccessID) { return prefix + name + "_" + std::to_string(AccessID); } static std::string extractNameImpl(StringRef prefix, const std::string& name) { StringRef nameRef(name); // Remove leading `prefix` std::size_t leadingLocalPos = nameRef.find(prefix); nameRef = nameRef.drop_front(leadingLocalPos != StringRef::npos ? prefix.size() : 0); // Remove trailing `_X` where X is the AccessID std::size_t trailingAccessIDPos = nameRef.find_last_of('_'); nameRef = nameRef.drop_back( trailingAccessIDPos != StringRef::npos ? nameRef.size() - trailingAccessIDPos : 0); return nameRef.empty() ? name : nameRef.str(); } std::string StencilInstantiation::makeLocalVariablename(const std::string& name, int AccessID) { return makeNameImpl("__local_", name, AccessID); } std::string StencilInstantiation::makeTemporaryFieldname(const std::string& name, int AccessID) { return makeNameImpl("__tmp_", name, AccessID); } std::string StencilInstantiation::extractLocalVariablename(const std::string& name) { return extractNameImpl("__local_", name); } std::string StencilInstantiation::extractTemporaryFieldname(const std::string& name) { return extractNameImpl("__tmp_", name); } std::string StencilInstantiation::makeStencilCallCodeGenName(int StencilID) { return "__code_gen_" + std::to_string(StencilID); } bool StencilInstantiation::isStencilCallCodeGenName(const std::string& name) { return StringRef(name).startswith("__code_gen_"); } void StencilInstantiation::reportAccesses() const { // Stencil functions for(const auto& stencilFun : stencilFunctionInstantiations_) { const auto& statementAccessesPairs = stencilFun->getStatementAccessesPairs(); for(std::size_t i = 0; i < statementAccessesPairs.size(); ++i) { std::cout << "\nACCESSES: line " << statementAccessesPairs[i]->getStatement()->ASTStmt->getSourceLocation().Line << ": " << statementAccessesPairs[i]->getCalleeAccesses()->reportAccesses(stencilFun.get()) << "\n"; } } // Stages for(const auto& stencil : stencils_) for(const auto& multistage : stencil->getMultiStages()) for(const auto& stage : multistage->getStages()) { for(const auto& doMethod : stage->getDoMethods()) { const auto& statementAccessesPairs = doMethod->getStatementAccessesPairs(); for(std::size_t i = 0; i < statementAccessesPairs.size(); ++i) { std::cout << "\nACCESSES: line " << statementAccessesPairs[i]->getStatement()->ASTStmt->getSourceLocation().Line << ": " << statementAccessesPairs[i]->getAccesses()->reportAccesses(this) << "\n"; } } } } } // namespace dawn
39.784414
100
0.675727
[ "vector" ]
07ab0df110e086735515a4d7229eae1ac1ff1618
3,406
cpp
C++
0224-Basic Calculator/0224-Basic Calculator.cpp
zhuangli1987/LeetCode-1
e81788abf9e95e575140f32a58fe983abc97fa4a
[ "MIT" ]
null
null
null
0224-Basic Calculator/0224-Basic Calculator.cpp
zhuangli1987/LeetCode-1
e81788abf9e95e575140f32a58fe983abc97fa4a
[ "MIT" ]
null
null
null
0224-Basic Calculator/0224-Basic Calculator.cpp
zhuangli1987/LeetCode-1
e81788abf9e95e575140f32a58fe983abc97fa4a
[ "MIT" ]
1
2019-11-20T08:01:10.000Z
2019-11-20T08:01:10.000Z
class Solution { public: int calculate(string s) { stack<int> vals; stack<int> ops; int num = 0; int sign = 1; int res = 0; for (char c : s) { if (isdigit(c)) { num = num * 10 + (c - '0'); } else { res += sign * num; num = 0; if (c == '+') { sign = 1; } else if (c == '-') { sign = -1; } else if (c == '(') { vals.push(res); ops.push(sign); res = 0; sign = 1; } else if (c == ')') { res = vals.top() + ops.top() * res; vals.pop(); ops.pop(); } } } res += sign * num; return res; } }; // Convert to reversed polish notation class Solution { public: int calculate(string s) { vector<string> postexp = infixToPostfix(s); stack<int> St; for (string& exp : postexp) { if (isOperand(exp)) { St.push(stoi(exp)); } else { int data2 = St.top(); St.pop(); int data1 = St.top(); St.pop(); int result = 0; if (exp == "+") { result = data1 + data2; } else { result = data1 - data2; } St.push(result); } } return !St.empty() ? St.top() : 0; } private: bool isOperand(string s) { return s.size() && s[0] >= '0' && s[1] <= '9'; } vector<string> infixToPostfix(string& s) { stack<string> St; vector<string> result; int num = 0; bool hasNumber = false; for (char c : s) { if (isdigit(c)) { hasNumber = true; num = num * 10 + (c - '0'); } else { if (hasNumber) { result.push_back(to_string(num)); hasNumber = false; num = 0; } if (c == ' ') { continue; } if (c == '(') { St.push(string(1, c)); } else if (c == ')') { while (!St.empty() && St.top() != "(") { result.push_back(St.top()); St.pop(); } St.pop(); } else { while (!St.empty() && St.top() != "(") { result.push_back(St.top()); St.pop(); } St.push(string(1, c)); } } } if (hasNumber) { result.push_back(to_string(num)); hasNumber = false; num = 0; } while (!St.empty()) { result.push_back(St.top()); St.pop(); } return result; } };
26
60
0.296242
[ "vector" ]
07adba0196876f956f921e8dcd669d609b4a7f4b
927
hpp
C++
source/TextToSpeech/TTSManager.hpp
RobertDamerius/GroundControlStation
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
[ "MIT" ]
1
2021-12-26T12:48:18.000Z
2021-12-26T12:48:18.000Z
source/TextToSpeech/TTSManager.hpp
RobertDamerius/GroundControlStation
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
[ "MIT" ]
null
null
null
source/TextToSpeech/TTSManager.hpp
RobertDamerius/GroundControlStation
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
[ "MIT" ]
1
2021-12-26T12:48:25.000Z
2021-12-26T12:48:25.000Z
#pragma once class TTSManager { public: /** * @brief Initialize the text-to-speech manager. */ void Initialize(void); /** * @brief Terminate the text-to-speech manager. */ void Terminate(void); /** * @brief Add text to the queue. * @param [in] text The text to be spoken. */ void AddToQueue(std::string& text); private: std::queue<std::string> commandQueue; ///< The queue of system commands. std::mutex mtx; ///< Mutex to protect @ref commandQueue. std::condition_variable cv; ///< Condition variable for thread notification. std::atomic<bool> terminate; ///< True if @ref ConsumerThread should be terminated. std::thread t; ///< Consumer thread object. void ConsumerThread(void); };
28.96875
100
0.530744
[ "object" ]