bool S9xIsValidCheatCode(const char *codestring) { std::string codes(codestring); if (codes.empty() || codes[codes.length() - 1] == '+') return false; // std::getline cannot handle this case std::istringstream iss(codes); std::string code; while(std::getline(iss, code, '+')) { uint32 address; uint8 byte; if (S9xProActionReplayToRaw(code.c_str(), address, byte) != NULL && S9xGameGenieToRaw(code.c_str(), address, byte) != NULL) { uint8 bytes[3]; uint8 num_bytes; if (S9xGoldFingerToRaw(code.c_str(), address, num_bytes, bytes) != NULL) return false; // invalid format } } return true; }
void XC::SectionAggregator::setAddtions(const std::vector<std::string> &responseCodes,const std::vector<std::string> &nmbMats) { ResponseId codes(responseCodes); theAdditions.putMatCodes(codes); const size_t n= nmbMats.size(); if(n!= responseCodes.size()) std::cerr << getClassName() << "::" << __FUNCTION__ << "; error in number of materials: index number: " << responseCodes.size() << " number of materials: " << n << std::endl; for(size_t i= 0;i<n;i++) { const Material *ptr_mat= material_handler->find_ptr(nmbMats[i]); if(ptr_mat) { const UniaxialMaterial *tmp= dynamic_cast<const UniaxialMaterial *>(ptr_mat); if(tmp) theAdditions.push_back(tmp); else std::cerr << getClassName() << "::" << __FUNCTION__ << "; material with code: '" << nmbMats[i] << "' is not an uniaxial material.\n"; } else std::cerr << getClassName() << "::" << __FUNCTION__ << "; material: '" << nmbMats[i] << "' not found.\n"; } alloc_storage_ptrs(); }
TEST_F(TestXorCode, FullCode) { Bytes toTest(8,11); Bytes codes(4,42); XorCode(begin(toTest), end(toTest), codes); EXPECT_NE(toTest, Bytes(8,11)); }
TEST_F(TestXorCode, PartialCode) { Bytes toTest(8,11); Bytes codes(4,42); XorCode(begin(toTest) + 2, end(toTest)-2, codes); EXPECT_NE(toTest, Bytes(8,11)); }
TEST_F(TestXorCode, EmptyBuffer) { Bytes empty; Bytes codes(4,42); XorCode(begin(empty), end(empty), codes); // no execptions expected; EXPECT_TRUE(empty.empty()); }
TEST_F(TestXorCode, PartialCodeDecode32000) { Bytes toTest(32000,11); Bytes codes(16,42); XorCode(begin(toTest)+222, end(toTest)-222, codes); XorCode(begin(toTest)+222, end(toTest)-222, codes); EXPECT_EQ(toTest, Bytes(32000,11)); }
BehaviourSettingsPage::BehaviourSettingsPage(SettingsDialog* dialog) : SettingsPage(dialog), ui_(new Ui_BehaviourSettingsPage) { ui_->setupUi(this); connect(ui_->b_show_tray_icon_, SIGNAL(toggled(bool)), SLOT(ShowTrayIconToggled(bool))); ui_->doubleclick_addmode->setItemData(0, MainWindow::AddBehaviour_Append); ui_->doubleclick_addmode->setItemData(1, MainWindow::AddBehaviour_Load); ui_->doubleclick_addmode->setItemData(2, MainWindow::AddBehaviour_OpenInNew); ui_->doubleclick_addmode->setItemData(3, MainWindow::AddBehaviour_Enqueue); ui_->doubleclick_playmode->setItemData(0, MainWindow::PlayBehaviour_Never); ui_->doubleclick_playmode->setItemData(1, MainWindow::PlayBehaviour_IfStopped); ui_->doubleclick_playmode->setItemData(2, MainWindow::PlayBehaviour_Always); ui_->menu_playmode->setItemData(0, MainWindow::PlayBehaviour_Never); ui_->menu_playmode->setItemData(1, MainWindow::PlayBehaviour_IfStopped); ui_->menu_playmode->setItemData(2, MainWindow::PlayBehaviour_Always); // Populate the language combo box. We do this by looking at all the // compiled in translations. QDir dir(":/translations/"); QStringList codes(dir.entryList(QStringList() << "*.qm")); QRegExp lang_re("^clementine_(.*).qm$"); for (const QString& filename : codes) { // The regex captures the "ru" from "clementine_ru.qm" if (!lang_re.exactMatch(filename)) continue; QString code = lang_re.cap(1); QString language_name = QLocale::languageToString(QLocale(code).language()); #if QT_VERSION >= 0x040800 QString native_name = QLocale(code).nativeLanguageName(); if (!native_name.isEmpty()) { language_name = native_name; } #endif QString name = QString("%1 (%2)").arg(language_name, code); language_map_[name] = code; } language_map_["English (en)"] = "en"; // Sort the names and show them in the UI QStringList names = language_map_.keys(); qStableSort(names.begin(), names.end(), LocaleAwareCompare); ui_->language->addItems(names); #ifdef Q_OS_DARWIN ui_->b_show_tray_icon_->setEnabled(false); ui_->startup_group_->setEnabled(false); #endif }
/** Returns a set of integers giving the different parallel slicable * units for the inputs of a particular node. If */ std::vector<size_t> get_parallel_slicable_codes(const pnode_ptr& n) { std::map<pnode_ptr, size_t> memoizer; size_t counter = 1; std::vector<size_t> codes(n->inputs.size()); for(size_t i = 0; i < codes.size(); ++i) { codes[i] = _propagate_parallel_slicing(n, memoizer, counter); } return codes; }
/** * @brief main * @param argc * @param argv * @return a sum of all failed tests * * Minimal testing toolkit. All tests * can be executed at once by either specifiing nothin * or "runall". If tests are to be run individually, * the class name has to be specified. */ int main(int argc, char** argv){ QApplication app(argc, argv); int status = 0, statusSum = 0; struct Tests testcases[] = { {QStringLiteral("CodeEditor"), factory<CodeEditorTest>}, {QStringLiteral("EditorWindow"), factory<EditorWindowTest>}, {QStringLiteral("SettingsBackend"), factory<SettingsBackendTest>}, {QStringLiteral("Renderer"), factory<RendererTest>}, {QStringLiteral("Backend"), factory<BackendTest>}, {QStringLiteral("CodeHighlighter"), factory<CodeHighlighterTest>} }; unsigned int size = sizeof(testcases)/sizeof(Tests); std::unique_ptr<int[]> codes(new int[size]); auto testRun = [&status, &statusSum, &codes](QObject* testObject, QString name, int i) { try{ status = QTest::qExec(testObject, 0, 0); }catch(QException e){ qDebug() << name << "Test threw QException:" << e.what(); }catch(const std::exception& e){ qDebug() << name << "Test threw STL Exception:" << e.what(); } if(status != 0){ codes[i-1] = status; statusSum += status; status = 0; } qDebug() << ""; }; if(argc == 1 || QString(argv[1]) == "runall") for(unsigned int i = 0; i < size; i++) testRun((testcases[i].testclass()).get(), testcases[i].name, i); else for(int i = 1; i < argc; i++){ for(struct Tests &t: testcases) if(argv[i] == t.name){ testRun((testcases[i].testclass()).get(), t.name, i-1); break; } } for(unsigned int i = 0; i < size; i++) if(codes[i] != 0) qDebug() << "Testclass" << (testcases[i+1].name) << "failed" << codes[i] << "test(s)."; qDebug() << "Ran tests for" << size << "classes."; qDebug() << "Total failed tests:" << statusSum; return statusSum; }
void setEventCode(const epicsUInt8* arr, epicsUInt32 count) { codes_t codes(count); std::copy(arr, arr+count, codes.begin()); { SCOPED_LOCK(mutex); scratch.codes.swap(codes); is_committed = false; } DEBUG(4, ("Set events\n")); scanIoRequest(changed); }
std::ostream& RinexObsID::dumpCheck(std::ostream& s) throw(Exception) { try { const std::string types("CLDS"); std::map<char,std::string>::const_iterator it; for(size_t i=0; i<ObsID::validRinexSystems.size(); i++) { char csys = ObsID::validRinexSystems[i]; std::string sys = ObsID::validRinexSystems.substr(i,1); RinexSatID sat(sys); std::string system(sat.systemString()); s << "System " << sys << " = " << system << ", frequencies "; for(it = ObsID::validRinexTrackingCodes[sys[0]].begin(); it != ObsID::validRinexTrackingCodes[sys[0]].end(); ++it) s << it->first; s << std::endl; for(it = ObsID::validRinexTrackingCodes[sys[0]].begin(); it != ObsID::validRinexTrackingCodes[sys[0]].end(); ++it) { s << " " << system << "(" << sys << "), freq " << it->first << ", codes '" << it->second << "'" << std::endl; std::string codes(it->second), str; for(size_t j=0; j<codes.size(); ++j) { std::ostringstream oss1; for(size_t k=0; k<types.size(); ++k) { str = std::string(1,types[k]) + std::string(1,it->first) + std::string(1,codes[j]); std::ostringstream oss; if(!isValidRinexObsID(str,csys)) oss << str << " " << "-INVALID-"; else { RinexObsID robsid(sys+str); oss << str << " " << robsid; } oss1 << " " << StringUtils::leftJustify(oss.str(),34); } s << StringUtils::stripTrailing(oss1.str()) << std::endl; } } } } catch(Exception& e) { s << "Exception: " << e.what() << std::endl; GPSTK_RETHROW(e); } return s; }
static inline bool S9xCompileCheat(struct SCheatItem& cheat, bool8 save_current_value) { std::string codes(cheat.code); std::vector<SCheat> cheatVector; if (codes.empty() || codes[codes.length() - 1] == '+') return false; // std::getline cannot handle this case std::istringstream iss(codes); std::string code; while(std::getline(iss, code, '+')) { SCheat c; if (S9xProActionReplayToRaw(code.c_str(), c.address, c.byte) == NULL || S9xGameGenieToRaw(code.c_str(), c.address, c.byte) == NULL) { c.saved = save_current_value; if (c.saved) { c.saved_byte = S9xGetByteFree(c.address); } cheatVector.push_back(c); } else { uint32 address; uint8 bytes[3]; uint8 num_bytes; if (S9xGoldFingerToRaw(code.c_str(), address, num_bytes, bytes) == NULL) { for (int i = 0; i < num_bytes; i++) { c.address = address + i; c.byte = bytes[i]; c.saved = save_current_value; if (c.saved) { c.saved_byte = S9xGetByteFree(c.address); } cheatVector.push_back(c); } } else return false; // invalid format } } cheat.c.clear(); copy(cheatVector.begin(), cheatVector.end(), std::back_inserter(cheat.c)); return true; }
// Determine if the given ObsID is valid, for the given system bool isValidRinexObsID(const std::string& strID, const char sys) { if(strID.length() != 3) return false; char ot(strID[0]); char cb(strID[1]); char tc(strID[2]); std::string codes(ObsID::validRinexTrackingCodes[sys][cb]); if(codes.find(std::string(1,tc)) == std::string::npos) return false; if(sys == 'G' && ot == 'C' && tc == 'N') // the one exception return false; return true; }
TInt CFbsFont::DoReleaseGlyphOutline(TReleaseGlyphOutlineParam* aParam) const { TInt ret = KErrGeneral; TPckgBuf<TFBSGlyphOutlineParam> params; TInt count = aParam->iCount; params().iCount = count; params().iHinted = aParam->iHinted; params().iHandle = iHandle; TPtr8 codes((unsigned char *)aParam->iCodes, count * sizeof(TUint), count * sizeof(TUint)); ret = iFbs->SendCommand(EFbsMessReleaseGlyphOutline, TIpcArgs(¶ms, &codes)); return ret; }
// --------------------------------------------------------------------------- // CSmileyModel::SupportedCodesL // --------------------------------------------------------------------------- // HBufC* CSmileyModel::SupportedCodesL() { HBufC* codes( NULL ); if ( iImageInfoArray.Count() > 0 ) { codes = HBufC::NewL( iImageInfoArray.Count() ); TPtr ptr( codes->Des() ); for ( TInt i = 0; i < iImageInfoArray.Count(); i++ ) { if ( ptr.Locate( iImageInfoArray[i].iCode ) == KErrNotFound ) { ptr.Append( iImageInfoArray[i].iCode ); } } } return codes; }
void ImportableTableSync::ObjectBySource<T>::add( typename T::ObjectType& object ){ std::vector<std::string> codes(object.getCodesBySource(_source)); BOOST_FOREACH(const std::string& code, codes) { typename Map::iterator it(_map.find(code)); if(it != _map.end()) { it->second.insert(&object); } else { Set s; s.insert(&object); _map.insert(std::make_pair(code,s)); } }
vector<int> grayCode(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> codes(1); if (n == 0) return codes; codes.push_back(1); int base = 1; for (int i=1; i<n; i++) { base *= 2; int preSize = codes.size(); for (int j=preSize-1; j>=0; j--) { codes.push_back(codes[j]+base); } } return codes; }
TInt CFbsFont::DoGetGlyphOutline(TGetGlyphOutlineParam* aParam) const { TInt ret = KErrGeneral; TPckgBuf<TFBSGlyphOutlineParam> paramsBuf; TInt count = aParam->iCount; paramsBuf().iCount = aParam->iCount; paramsBuf().iHinted = aParam->iHinted; paramsBuf().iHandle = iHandle; TOffsetLen* offsetLen = (TOffsetLen *)User::Alloc(count * sizeof(TOffsetLen)); if (NULL == offsetLen) { return KErrNoMemory; } TPtr8 retBuf((TUint8 *)offsetLen, count * sizeof(TOffsetLen), count * sizeof(TOffsetLen)); TPtr8 codes((TUint8 *)(aParam->iCodes), count * sizeof(TUint), count * sizeof(TUint)); ret = iFbs->SendCommand( EFbsMessGetGlyphOutline, TIpcArgs(¶msBuf, &codes, &retBuf)); if (KErrNone == ret) { // server writes the offsets back to client, convert them // to local pointers. for (TInt i = 0; i < aParam->iCount; ++i) { aParam->iOutlines[i] = OffsetToPointer(offsetLen[i].iOffset, iFbs->HeapBase()); aParam->iLengths[i] = offsetLen[i].iLen; } } User::Free(offsetLen); return ret; }
TDF_API K K_DECL TDF_codeTable(K h, K market) { ::THANDLE tdf = NULL; std::string mkt; try { TDF::parseTdfHandle(h, tdf); mkt = q::q2String(market); } catch (std::string const& error) { return q::error2q(error); } unsigned int codeCount = 0; ::TDF_CODE* t = NULL; ::TDF_ERR const result = static_cast<::TDF_ERR>(::TDF_GetCodeTable(tdf, mkt.c_str(), &t, &codeCount)); TDF::Ptr<::TDF_CODE> codes(t); if (result != TDF_ERR_SUCCESS) { return q::error2q(TDF::getError(result)); } assert(codes); assert(codeCount >= 0); q::K_ptr data(ktn(0, 6)); kK(data.get())[0] = //Wind Code: AG1312.SHF Wind::accessor::SymbolAccessor<::TDF_CODE, char[32]>(&::TDF_CODE::szWindCode).extract(codes.get(), codeCount); kK(data.get())[1] = //market code: SHF Wind::accessor::SymbolAccessor<::TDF_CODE, char[ 8]>(&::TDF_CODE::szMarket).extract(codes.get(), codeCount); kK(data.get())[2] = //original code: ag1312 Wind::accessor::SymbolAccessor<::TDF_CODE, char[32]>(&::TDF_CODE::szCode).extract(codes.get(), codeCount); kK(data.get())[3] = Wind::accessor::SymbolAccessor<::TDF_CODE, char[32]>(&::TDF_CODE::szENName).extract(codes.get(), codeCount); kK(data.get())[4] = //Chinese name: »¦Òø1302 Wind::accessor::SymbolAccessor<::TDF_CODE, char[32], Wind::encoder::GB18030_UTF8>(&::TDF_CODE::szCNName).extract(codes.get(), codeCount); kK(data.get())[5] = Wind::accessor::IntAccessor<::TDF_CODE, G>(&::TDF_CODE::nType).extract(codes.get(), codeCount); return data.release(); }
int main (void) { double t0=omp_get_wtime(); // Open I/O for business! ifp = fopen(INPUT, "r"); // Open input file for reading ofp = fopen(OUTPUT, "w"); // Open output file for writing // Verify that I/O files are open if (ifp != 0) { printf("Input file is open\n"); } else { printf("***ERROR*** Unable to open the input file\n"); getchar(); return 0; } if (ofp != 0) { printf("Output file is open\n"); } else { printf("***ERROR*** Unable to open the output file\n"); getchar(); return 0; } // Read in number of elements, joints from input file fscanf(ifp, "%d,%d\n", &ne, &nj); fprintf(ofp, "Control Variables:\n\tNumber of Elements: %d\n", ne); fprintf(ofp, "\tNumber of Joints: %d\n\n", nj); /* Associate pointers with base address of arrays in function calls: parea = area; Note: in this context "&" can be omitted to obtain "&area[0]" Note: previous remark only works for 1D arrays: px=&x[0][0] */ // Define secondary variables which DO NOT depend upon neq double x[3][nj]; // Current joint coordinates int mcode[6][ne], jcode[3][nj], minc[2][ne];// Member incidence and constraint data double emod[ne]; // Element material properties double eleng[ne], deflen[ne], elong[ne]; // Element length, deformed length, and elongation double area[ne]; // Element cross-sectional properties double c1[ne], c2[ne], c3[ne]; // Direction cosines double qi, dqi; // Current and incremental load proportionality factor double qimax; // Maximum allowable load proportionality factor // Convergence parameters double tolfor, tolener; // Tolerances on force and energy double intener1; // Internal energy from first equilibrium iteration int inconv; // Flag for convergence test int itecnt, itemax; // Iteration counter and max number of iterations int errchk; // Error check variable on user defined functions int i; // Counter variable int csrflag=0; // Pass control to struc function errchk = struc(&jcode[0][0], &minc[0][0]); // Terminate program if errors encountered if (errchk == 1) { fprintf(ofp, "\n\nSolution failed\n"); printf("Solution failed, see output file\n"); // Close the I/O if (fclose(ifp) != 0) { printf("***ERROR*** Unable to close the input file\n"); } else { printf("Input file is closed\n"); } if (fclose(ofp) != 0) { printf("***ERROR*** Unable to close the output file\n"); } else { printf("Output file is closed\n"); } getchar(); return 0; } // Pass control to codes function codes (&mcode[0][0], &jcode[0][0], &minc[0][0]); printf("number of equations: %d\n", neq); // Define secondary variables which DO depend upon neq double q[neq]; // Reference load vector double qtot[neq]; // Total load vector, i.e. qi * q[neq] double d[neq], dd[neq]; // Total and incremental nodal displacement vectors double f[neq]; // Internal force vector double fp[neq]; // Internal force vector from previous load increment double fpi[neq]; // Internal force vector from previous iteration double r[neq]; // Residual force vector, i.e. qtot - f int maxa[neq + 1], kht[neq], lss; // Skyline storage parameters for stiffness matrix // Pass control to skylin function skylin (kht, maxa, &mcode[0][0], &lss); printf("size of stiffness matrix as a 1D element: %d\n",lss); // Define secondary variable which depends upon lss (the size of the stiffness marix as a 1D array) double *ss= (double *)malloc(lss*sizeof(double)); // Tangent stiffness matrix stored as an array // Pass control to prop function prop (&x[0][0], area, emod, eleng, c1, c2, c3, &minc[0][0]); // Pass control to load function errchk = load (q, &jcode[0][0]); // Terminate program if errors encountered if (errchk == 1) { fprintf(ofp, "\n\nSolution failed\n"); printf("Solution failed, see output file\n"); // Close the I/O if (fclose(ifp) != 0) { printf("***ERROR*** Unable to close the input file\n"); } else { printf("Input file is closed\n"); } if (fclose(ofp) != 0) { printf("***ERROR*** Unable to close the output file\n"); } else { printf("Output file is closed\n"); } getchar(); return 0; } // Read in solver parameters from input file fscanf(ifp, "%lf,%lf,%lf\n", &qimax, &qi, &dqi); fscanf(ifp, "%d\n", &itemax); fscanf(ifp, "%lf,%lf\n", &tolfor, &tolener); // Print layout for output of results fprintf(ofp, "\nNonlinear Equilibrium Path:\n\tLambda\t"); for (i = 0; i <= neq - 1; ++i) { fprintf(ofp, "\tDOF %d\t", i + 1); } // Initialize generalized nodal displacement and internal force vectors for (i = 0; i <= neq - 1; ++i) { d[i] = 0; f[i] = 0; } // Initialize element length and elongation variables for (i = 0; i <= ne - 1; ++i) { deflen[i] = eleng[i]; elong[i] = 0; } /* Begin load incrementation; load will be incremented until load proportionality factor is equal to user specified maximum */ do { /* Compute the generalized joint total load vector, store generalized internal force vector from previous configuration and re-initialize */ for (i = 0; i <= neq - 1; ++i) { qtot[i] = q[i] * qi; fp[i] = f[i]; f[i] = 0; } // Pass control to forces function forces (f, area, emod, c1, c2, c3, elong, eleng, &mcode[0][0]); itecnt = 1; // Re-initialize iteration counter at the start of each increment /* Start of each equilibrium iteration within load increment; iterations will continue until convergence is reached or iteration count exceeds user specified maximum */ do { printf("iteration: %d\n", itecnt); //printf("iteration count: %d \n", itecnt); // Compute residual force vector for use in evaluating displacement increment for (i = 0; i <= neq - 1; ++i) { r[i] = qtot[i] - f[i]; } // Pass control to stiff function stiff (ss, area, emod, eleng, c1, c2, c3, elong, maxa, &mcode[0][0], &lss); if (csrflag==1){ write_array_double("asky", lss, ss); write_array_int("maxa", neq+1, maxa); write_array_double("r", neq, r); } // Solve the system for incremental displacements if (lss == 1) { // Carry out computation of incremental displacement directly for lss = 1 dd[0] = r[0] / ss[0]; } else { // Pass control to solve function errchk = solve (ss, r, dd, maxa); if (csrflag==1){ write_array_double("dd", neq, dd); } ++csrflag; // Terminate program if errors encountered if (errchk == 1) { fprintf(ofp, "\n\nSolution failed\n"); printf("Solution failed, see output file\n"); // Close the I/O if (fclose(ifp) != 0) { printf("***ERROR*** Unable to close the input file\n"); } else { printf("Input file is closed\n"); } if (fclose(ofp) != 0) { printf("***ERROR*** Unable to close the output file\n"); } else { printf("Output file is closed\n"); } getchar(); return 0; } } /* Update generalized nodal displacement vector, store generalized internal force vector from previous iteration, and re-initialize generalized internal force vector */ for (i = 0; i <= neq - 1; ++i) { d[i] += dd[i]; fpi[i] = f[i]; f[i] = 0; } // Pass control to forces function updatc (&x[0][0], dd, c1, c2, c3, elong, eleng, deflen, &minc[0][0], &jcode[0][0]); // Pass control to forces function forces (f, area, emod, c1, c2, c3, elong, eleng, &mcode[0][0]); if (itecnt == 1) { // Compute internal energy from first iteration intener1 = 0; for (i = 0; i <= neq - 1; ++i) { intener1 += dd[i] * (qtot[i] - fp[i]); } } // Pass control to test function test (f, fp, qtot, dd, fpi, &intener1, &inconv, &neq, &tolfor, &tolener); itecnt ++; // Advance solution counter } while (inconv != 0 && itecnt <= itemax); // Store generalized internal force vector from current configuration for (i = 0; i <= neq - 1; ++i) { fp[i] = f[i]; } if (inconv != 0) { fprintf(ofp, "\n\n***ERROR*** Convergence not reached within specified"); fprintf(ofp, " number of iterations (INCONV = %d)", inconv); fprintf(ofp, "\n\nSolution failed\n"); printf("Solution failed, see output file\n"); // Close the I/O if (fclose(ifp) != 0) { printf("***ERROR*** Unable to close the input file\n"); } else { printf("Input file is closed\n"); } if (fclose(ofp) != 0) { printf("***ERROR*** Unable to close the output file\n"); } else { printf("Output file is closed\n"); } getchar(); return 0; } // Output model response fprintf(ofp, "\n\t%lf", qi); for (i = 0; i <= neq - 1; ++i) { fprintf(ofp, "\t%lf", d[i]); } qi += dqi; // Increment load proportionality factor } while (qi <= qimax); if (qi >= qimax && inconv == 0) { fprintf(ofp, "\n\nSolution successful\n"); printf("Solution successful\n"); } // Close the I/O if (fclose(ifp) != 0) { printf("***ERROR*** Unable to close the input file\n"); } else { printf("Input file is closed\n"); } if (fclose(ofp) != 0) { printf("***ERROR*** Unable to close the output file\n"); } else { printf("Output file is closed\n"); } getchar(); double t1 = omp_get_wtime(); printf("Total time spent (IO+computation): %g\n",t1-t0); return 0; }
void execute(Xbyak::CodeGenerator &gen) { void (*codes)() = (void (*)()) gen.getCode(); codes(); }
/** * Find a list of candidate marker from a given scene * * @param current frame, in grayscale 8UC1 format * @return a list of marker candidates **/ vector<Marker> MarkerDetector::findMarkerCandidates( Mat& frame ) { vector<Marker> candidates; /* Do some thresholding, in fact you should tune the parameters here a bit */ Mat thresholded; threshold( frame, thresholded, 50.0, 255.0, CV_THRESH_BINARY ); /* Find contours */ vector<vector<Point>> contours; findContours( thresholded.clone(), contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE ); for( vector<Point> contour: contours ) { /* Approximate polygons out of these contours */ vector<Point> approxed; approxPolyDP( contour, approxed, contour.size() * 0.05, true ); /* Make sure it passes our first candidate check */ if( !checkPoints( approxed ) ) continue; /* Do some perspective transformation on the candidate marker to a predetermined square */ Marker marker; marker.matrix = Mat( markerHeight, markerWidth, CV_8UC1 ); std::copy( approxed.begin(), approxed.end(), back_inserter( marker.poly ) ); /* Apply sub pixel search */ cornerSubPix( thresholded, marker.poly, Size(5, 5), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 40, 0.001) ); /* Projection target */ const static vector<Point2f> target_corners = { Point2f( -0.5f, -0.5f ), Point2f( +5.5f, -0.5f ), Point2f( +5.5f, +5.5f ), Point2f( -0.5f, +5.5f ), }; /* Apply perspective transformation, to project our 3D marker to a predefined 2D coords */ Mat projection = getPerspectiveTransform( marker.poly, target_corners ); warpPerspective( thresholded, marker.matrix, projection, marker.matrix.size() ); /* Ignore those region that's fully black, or not surrounded by black bars */ if( sum(marker.matrix) == Scalar(0) || countNonZero( marker.matrix.row(0)) != 0 || countNonZero( marker.matrix.row(markerHeight - 1)) != 0 || countNonZero( marker.matrix.col(0)) != 0 || countNonZero( marker.matrix.col(markerWidth - 1)) != 0 ) { continue; } /* Find the rotation that has the smallest hex value */ pair<unsigned int, unsigned int> minimum = { numeric_limits<unsigned int>::max(), 0 }; vector<unsigned int> codes(markerHeight); unsigned int power = 1 << (markerWidth - 3); /* Rotate the marker 4 times, store the hex code upon each rotation */ for( int rotation = 0; rotation < 4; rotation++ ) { stringstream ss; codes[rotation] = 0; for( int i = 1; i < markerHeight - 1; i++ ) { unsigned int code = 0; for ( int j = 1; j < markerWidth - 1; j++ ){ int value = static_cast<int>(marker.matrix.at<uchar>(i, j)); if( value == 0 ) code = code + ( power >> j ); } ss << hex << code; } ss >> codes[rotation]; if( minimum.first > codes[rotation] ) { minimum.first = codes[rotation]; minimum.second = rotation; } flip( marker.matrix, marker.matrix, 1 ); marker.matrix = marker.matrix.t(); } rotate( marker.poly.begin(), marker.poly.begin() + ((minimum.second + 2) % 4), marker.poly.end() ); for( int i = 0; i < minimum.second; i++ ) { flip( marker.matrix, marker.matrix, 1 ); marker.matrix = marker.matrix.t(); } marker.code = minimum.first; candidates.push_back( marker ); } return candidates; }
void DynamicResult::prepareCalculations(oRunner &runner) const { prepareCommon(runner); pCard pc = runner.getCard(); if (pc) { vector<pPunch> punches; pc->getPunches(punches); int np = 0; for (size_t k = 0; k < punches.size(); k++) { if (punches[k]->getTypeCode() >= 30) np++; } vector<int> times(np); vector<int> codes(np); vector<int> controls(np); int ip = 0; for (size_t k = 0; k < punches.size(); k++) { if (punches[k]->getTypeCode() >= 30) { times[ip] = punches[k]->getAdjustedTime(); codes[ip] = punches[k]->getTypeCode(); controls[ip] = punches[k]->isUsedInCourse() ? punches[k]->getControlId() : -1; ip++; } } parser.addSymbol("CardPunches", codes); parser.addSymbol("CardTimes", times); parser.addSymbol("CardControls", controls); pTeam t = runner.getTeam(); if (t) { int leg = runner.getLegNumber(); t->setResultCache(oTeam::RCCCardTimes, leg, times); t->setResultCache(oTeam::RCCCardPunches, leg, codes); t->setResultCache(oTeam::RCCCardControls, leg, controls); } } else { vector<int> e; parser.addSymbol("CardPunches", e); parser.addSymbol("CardTimes", e); parser.addSymbol("CardControls", e); } pCourse crs = runner.getCourse(true); const vector<SplitData> &sp = runner.getSplitTimes(false); if (crs) { vector<int> eCrs; vector<int> eSplitTime; vector<int> eAccTime; eCrs.reserve(crs->getNumControls()); eSplitTime.reserve(crs->getNumControls()); eAccTime.reserve(crs->getNumControls()); int start = runner.getStartTime(); int st = runner.getStartTime(); for (int k = 0; k < crs->getNumControls(); k++) { pControl ctrl = crs->getControl(k); if (ctrl->isSingleStatusOK()) { eCrs.push_back(ctrl->getFirstNumber()); if (size_t(k) < sp.size()) { if (sp[k].status == SplitData::OK) { eAccTime.push_back(sp[k].time-start); eSplitTime.push_back(sp[k].time-st); st = sp[k].time; } else if (sp[k].status == SplitData::NoTime) { eAccTime.push_back(st-start); eSplitTime.push_back(0); } else if (sp[k].status == SplitData::Missing) { eAccTime.push_back(0); eSplitTime.push_back(-1); } } } } if (runner.getFinishTime() > 0) { eAccTime.push_back(runner.getFinishTime()-start); eSplitTime.push_back(runner.getFinishTime()-st); } else if (!eAccTime.empty()) { eAccTime.push_back(0); eSplitTime.push_back(-1); } parser.addSymbol("CourseLength", crs->getLength()); parser.addSymbol("Course", eCrs); parser.addSymbol("SplitTimes", eSplitTime); parser.addSymbol("SplitTimesAccumulated", eAccTime); pTeam t = runner.getTeam(); if (t) { int leg = runner.getLegNumber(); t->setResultCache(oTeam::RCCCourse, leg, eCrs); t->setResultCache(oTeam::RCCSplitTime, leg, eSplitTime); } } else { vector<int> e; parser.addSymbol("CourseLength", -1); parser.addSymbol("Course", e); parser.addSymbol("SplitTimes", e); parser.addSymbol("SplitTimesAccumulated", e); } pClass cls = runner.getClassRef(); if (cls) { int nl = runner.getLegNumber(); parser.addSymbol("ShortestClassTime", cls->getBestLegTime(nl)); } vector<int> delta; vector<int> place; vector<int> after; runner.getSplitAnalysis(delta); runner.getLegTimeAfter(after); runner.getLegPlaces(place); parser.addSymbol("LegTimeDeviation", delta); parser.addSymbol("LegTimeAfter", after); parser.addSymbol("LegPlace", place); parser.addSymbol("Leg", runner.getLegNumber()); }
/// Read the string values. This function processes the data produced by /// version 0x01000000 of the write function. On successful completion, it /// returns 0. int ibis::dictionary::readKeys2(const char *evt, FILE *fptr) { uint32_t nkeys; int ierr = fread(&nkeys, 4, 1, fptr); if (ierr != 1) { LOGGER(ibis::gVerbose > 1) << "Warning -- " << evt << " failed to read the number of keys, fread returned " << ierr; return -6; } clear(); array_t<uint32_t> codes(nkeys); array_t<uint64_t> offsets(nkeys+1); ierr = fread(offsets.begin(), 8, nkeys+1, fptr); if (ierr != (int)(1+nkeys)) { LOGGER(ibis::gVerbose > 1) << "Warning -- " << evt << " failed to read the string positions, " "expected fread to return " << nkeys+1 << ", but got " << ierr; return -7; } ierr = fread(codes.begin(), 4, nkeys, fptr); if (ierr != (int)(nkeys)) { LOGGER(ibis::gVerbose > 1) << "Warning -- " << evt << " failed to read the string keys, " "expected fread to return " << nkeys << ", but got " << ierr; return -8; } uint32_t maxcode = 0; for (size_t j = 0; j < nkeys; ++ j) { if (maxcode < codes[j]) maxcode = codes[j]; } buffer_.resize(1); buffer_[0] = new char[offsets.back()-offsets.front()]; ierr = fread(buffer_[0], 1, offsets.back()-offsets.front(), fptr); if (ierr != (int)(offsets.back()-offsets.front())) { LOGGER(ibis::gVerbose > 1) << "Warning -- " << evt << " failed to read the strings, " "expected fread to return " << (offsets.back()-offsets.front()) << ", but got " << ierr; return -9; } raw_.resize(maxcode+1); for (size_t j = 0; j <= maxcode; ++ j) raw_[j] = 0; #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 7) key_.reserve(nkeys+nkeys); // older version does not have reserve #endif for (unsigned j = 0; j < nkeys; ++ j) { const char* tmp = buffer_[0] + (offsets[j] - offsets[0]); raw_[codes[j]] = tmp; key_[tmp] = codes[j]; #if DEBUG+0 > 2 || _DEBUG+0 > 2 LOGGER(ibis::gVerbose > 0) << "DEBUG -- " << evt << " raw_[" << codes[j] << "] = \"" << tmp << '"'; #endif } #if DEBUG+0 > 2 || _DEBUG+0 > 2 ibis::util::logger lg; lg() << "DEBUG -- " << evt << " got the following keys\n\t"; for (MYMAP::const_iterator it = key_.begin(); it != key_.end(); ++ it) lg() << "\n\t" << it->second << ": " << it->first; #endif return 0; } // ibis::dictionary::readKeys2
/// Read the string values. This function processes the data produced by /// version 0x00000000 of the write function. On successful completion, it /// returns 0. /// /// Note that this function assume the 20-byte header has been read /// already. int ibis::dictionary::readKeys0(const char *evt, FILE *fptr) { uint32_t nkeys; int ierr = fread(&nkeys, 4, 1, fptr); if (ierr != 1) { LOGGER(ibis::gVerbose > 1) << "Warning -- " << evt << " failed to read the number of keys, fread returned " << ierr; return -6; } clear(); array_t<uint32_t> codes(nkeys); ierr = fread(codes.begin(), 4, nkeys, fptr); if (ierr != (long)nkeys) { LOGGER(ibis::gVerbose > 1) << "Warning -- " << evt << " failed to read " << nkeys << ", fread returned " << ierr; return -7; } array_t<uint32_t> offsets(nkeys+1); ierr = fread(offsets.begin(), 4, nkeys+1, fptr); if (ierr != (int)(1+nkeys)) { LOGGER(ibis::gVerbose > 1) << "Warning -- " << evt << " failed to read the string positions, " "expected fread to return " << nkeys+1 << ", but got " << ierr; return -8; } buffer_.resize(1); buffer_[0] = new char[offsets.back()-offsets.front()]; ierr = fread(buffer_[0], 1, offsets.back()-offsets.front(), fptr); if (ierr != (int)(offsets.back()-offsets.front())) { LOGGER(ibis::gVerbose > 1) << "Warning -- " << evt << " failed to read the strings, " "expected fread to return " << (offsets.back()-offsets.front()) << ", but got " << ierr; return -9; } raw_.resize(nkeys+1); raw_[0] = 0; // some implementation of unordered_map does have function reserve // key_.reserve(nkeys+nkeys); for (unsigned j = 0; j < nkeys; ++ j) { const uint32_t ik = codes[j]; if (ik > 0 && ik <= nkeys) { raw_[ik] = buffer_[0] + (offsets[j] - offsets[0]); key_[raw_[ik]] = ik; } else { LOGGER(ibis::gVerbose > 1) << "Warning -- " << evt << " encounter code " << ik << " which is out of the expected range [0, " << nkeys << ']'; } #if DEBUG+0 > 2 || _DEBUG+0 > 2 LOGGER(ibis::gVerbose > 0) << "DEBUG -- " << evt << " raw_[" << ik << "] = \"" << raw_[ik] << '"'; #endif } #if DEBUG+0 > 2 || _DEBUG+0 > 2 ibis::util::logger lg; lg() << "DEBUG -- " << evt << " got the following keys\n\t"; for (MYMAP::const_iterator it = key_.begin(); it != key_.end(); ++ it) lg() << "\n\t" << it->second << ": " << it->first; #endif return 0; } // ibis::dictionary::readKeys0