TEST(BitsSnoob, Basics) { EXPECT_EQ(2, snoob(1u, 10u)); EXPECT_EQ(2, snoob(1u, 30u)); EXPECT_EQ(0xau, snoob(0x9u, 10u)); // TODO: Test 1 argument snoob }
void produce_simple_values() { using TestFactory = factory::MultiFact<string, theID>; TestFactory theFact; // the first "production line" is wired to a free function theFact.defineProduction (ONE, buildOne); // second "production line" uses a explicit partial closure theFact.defineProduction (TWO, bind (buildSome<theID>, TWO)); // for the third "production line" we set up a function object auto memberFunction = bind (&MultiFact_test::callMe, this, "lalü"); theFact.defineProduction (THR, memberFunction); // and the fourth "production line" uses a lambda, closed with a local reference string backdoor("backdoor"); theFact.defineProduction (FOU, [&] { return backdoor; }); CHECK (!isnil (theFact)); CHECK (theFact(ONE) == "1"); CHECK (theFact(TWO) == "2"); CHECK (theFact(THR) == "lalü"); CHECK (invocations_ == 1); CHECK (theFact(FOU) == "backdoor"); backdoor = "I am " + backdoor.substr(0,4); CHECK (theFact(FOU) == "I am back"); TestFactory anotherFact; CHECK (isnil (anotherFact)); VERIFY_ERROR (INVALID, anotherFact(ONE) ); anotherFact.defineProduction (ONE, memberFunction); CHECK (anotherFact(ONE) == "lalü"); CHECK (invocations_ == 2); CHECK (theFact(THR) == "lalü"); CHECK (invocations_ == 3); CHECK ( theFact.contains (FOU)); CHECK (!anotherFact.contains (FOU)); anotherFact = theFact; CHECK (anotherFact.contains (FOU)); CHECK (!isSameObject(theFact, anotherFact)); CHECK (anotherFact(ONE) == "1"); CHECK (anotherFact(TWO) == "2"); CHECK (anotherFact(THR) == "lalü"); CHECK (anotherFact(FOU) == "I am back"); CHECK (invocations_ == 4); }
void print_accepted(const util::NodeRange& nodes, std::function<bool(Node, Node)> is_strong, std::function<bool(Node)> is_root) { using util::fmt; using std::endl; using std::cout; auto count_parents = [&](const auto N) { using boost::count_if; using common::pars; auto has_n_parents = [&](auto node) { auto is_accepted = [&](auto par) { return is_strong(par, node); }; return !is_root(node) && count_if(pars(node), is_accepted) == N; }; return count_if(nodes, has_n_parents); }; auto W = static_cast<floating_t>(nodes.size()) / 100.; cout << "0 parents accepted: " << fmt(count_parents(0) / W) << "%" << endl; cout << "1 parents accepted: " << fmt(count_parents(1) / W) << "%" << endl; cout << "2 parents accepted: " << fmt(count_parents(2) / W) << "%" << endl; cout << "3 parents accepted: " << fmt(count_parents(3) / W) << "%" << endl; cout << "4 parents accepted: " << fmt(count_parents(4) / W) << "%" << endl; }
/** @test verify an extension built on top of the ItemWrapper: * a function which remembers the last result. Here we use * a test function, which picks a member of an vector and * returns a \em reference to it. Thus the cached "result" * can be used to access and change the values within the * original vector. In a real world usage scenario, such a * function could be an (expensive) data structure access. */ void verifyFunctionRefResult() { vector<int> testVec; for (uint i=0; i<10; ++i) testVec.push_back(i); FunctionResult<int&(size_t)> funRes (pickElement_ofVector(testVec)); // function was never invoked, thus the remembered result is NIL CHECK (!funRes); VERIFY_ERROR (BOTTOM_VALUE, *funRes ); int& r5 = funRes (5); CHECK (funRes); // indicates existence of cached result CHECK (5 == r5); CHECK (isSameObject (r5, testVec[5])); int& r5x = *funRes; CHECK (isSameObject (r5, r5x)); CHECK ( isSameObject (r5, *funRes)); int& r7 = funRes (7); CHECK (!isSameObject (r5, *funRes)); CHECK ( isSameObject (r7, *funRes)); -- r5x; ++ *funRes; CHECK (5-1 == testVec[5]); CHECK (7+1 == testVec[7]); CHECK (7+1 == r7); }
void initStreams() { string parametersPassiveFileName("../OpenGL/parametersPassiveCdef.txt"); inputParameters.open(parametersPassiveFileName); if ( !inputParameters.good() ) { cerr << "File " << parametersPassiveFileName << " doesn't exist, enter a valid path" << endl; cin.ignore(1E6,'\n'); exit(0); } parameters.loadParameterFile(inputParameters); #ifdef _WIN32 // WARNING: // Base directory and subject name, if are not // present in the parameters file, the program will stop suddenly!!! // Base directory where the files will be stored string baseDir = parameters.find("BaseDir"); if ( !exists(baseDir) ) create_directory(baseDir); // Subject name string subjectName = parameters.find("SubjectName"); // Principal streams file string transformationFileName("transformationFile_"); string trialFileName("trialFile_"); string anglesFileName("anglesFile_"); string responseFileName("responseFile_"); // Add the subject name to file extension transformationFileName +=string(subjectName)+".txt"; trialFileName +=string(subjectName)+".txt"; anglesFileName +=string(subjectName)+".txt"; responseFileName +=string(subjectName)+".txt"; // Check for output file existence /** Transformation file **/ if ( !fileExists((baseDir+transformationFileName)) ) transformationFile.open((baseDir+transformationFileName).c_str() ); /** Trial file **/ if ( !fileExists((baseDir+trialFileName)) ) trialFile.open((baseDir+trialFileName).c_str()); /** Angles file **/ if ( !fileExists((baseDir+anglesFileName)) ) anglesFile.open((baseDir+anglesFileName).c_str()); /** Response file **/ if ( !fileExists((baseDir+responseFileName)) ) responseFile.open((baseDir+responseFileName).c_str()); #endif cerr << "streams end" << endl; }
TEST(Peak, SortMagnitudeDescendingPositionDescending) { Real positions [] = {1, 0, 1, 4, 5}; Real magnitudes[] = {2, 2, 3, 1, 6}; vector<util::Peak> peaks = realsToPeaks(arrayToVector<Real>(positions), arrayToVector<Real>(magnitudes)); sort(peaks.begin(), peaks.end(), ComparePeakMagnitude<std::greater<Real>, std::greater<Real> >()); Real expectedPos[] = {5,1,1,0,4}; Real expectedMag[] = {6,3,2,2,1}; vector<util::Peak> expectedPeaks= realsToPeaks(arrayToVector<Real>(expectedPos), arrayToVector<Real>(expectedMag)); EXPECT_VEC_EQ(peaks, expectedPeaks); }
TEST(Peak, SortPositionAscendingMagnitudeAscending) { Real positions [] = {1, 0, 1, 4, 5}; Real magnitudes[] = {2, 2, 3, 1, 6}; vector<util::Peak> peaks = realsToPeaks(arrayToVector<Real>(positions), arrayToVector<Real>(magnitudes)); sort(peaks.begin(), peaks.end(), ComparePeakPosition<std::less<Real>, std::less<Real> >()); Real expectedPos[] = {0,1,1,4,5}; Real expectedMag[] = {2,2,3,1,6}; vector<util::Peak> expectedPeaks= realsToPeaks(arrayToVector<Real>(expectedPos), arrayToVector<Real>(expectedMag)); EXPECT_VEC_EQ(peaks, expectedPeaks); }
void __expect_in_target (E const& elm, Literal oper) { if (end_of_target()) throw error::State(_Fmt("Unable to %s element %s from target as demanded; " "no (further) elements in target sequence") % oper % elm , LUMIERA_ERROR_DIFF_CONFLICT); if (*pos_ != elm) throw error::State(_Fmt("Unable to %s element %s from target as demanded; " "found element %s on current target position instead") % oper % elm % *pos_ , LUMIERA_ERROR_DIFF_CONFLICT); }
/** @test proper handling of move and rvalue references */ void verifySaneMoveHandling() { using Data = shared_ptr<int>; using Wrap = ItemWrapper<Data>; Data data{new int(12345)}; CHECK (1 == data.use_count()); Wrap wrap{data}; CHECK (2 == data.use_count()); CHECK (12345 == **wrap); CHECK (isSameObject (*data, **wrap)); CHECK (!isSameObject (data, *wrap)); Wrap wcopy{wrap}; CHECK (3 == data.use_count()); Wrap wmove{move (wcopy)}; CHECK (3 == data.use_count()); CHECK (not wcopy); CHECK (wmove); wcopy = move(wmove); CHECK (3 == data.use_count()); CHECK (not wmove); CHECK (wcopy); Wrap wmove2{move (data)}; CHECK (0 == data.use_count()); CHECK (3 == wmove2->use_count()); CHECK (not data); CHECK (wmove2); CHECK (wrap); wmove2 = move (wcopy); CHECK (2 == wmove2->use_count()); CHECK (not wcopy); CHECK (wmove2); CHECK (wrap); wmove2 = move (wrap); CHECK (1 == wmove2->use_count()); CHECK (not wrap); CHECK (wmove2); wmove2 = move (wmove); CHECK (not wcopy); CHECK (not wmove); CHECK (not wmove2); }
virtual void run (Arg) { // Prepare an (test)Index (dummy "session") PPIdx testSession (build_testScopes()); ElementQuery queryAPI; MORef<DummyMO> dummy1 = queryAPI.pick (elementID_contains("MO2")); CHECK (dummy1); CHECK (dummy1->isValid()); INFO (test, "Location in Tree: %s", cStr(ScopePath(dummy1.getPlacement()))); string elementID = dummy1->operator string(); CHECK (contains (elementID, "MO2")); string specificID = elementID.substr(10); // should contain the random int-ID MORef<DummyMO> dummy2; CHECK (!dummy2); dummy2 = queryAPI.pick (elementID_contains(specificID)); CHECK (dummy2); // found the same object again CHECK (dummy2->isValid()); CHECK (dummy2 == dummy1); // put aside a new handle holding onto the MObject PDum newPlacement(dummy1.getPlacement()); CHECK (testSession->contains(dummy1)); CHECK (!testSession->contains(newPlacement)); // and now remove the placement and all contained elements testSession->clear (dummy1); CHECK (!testSession->contains(dummy1)); MORef<DummyMO> findAgain = queryAPI.pick (elementID_contains(specificID)); CHECK (!findAgain); // empty result because searched element was removed from session... MORef<DummyMO> otherElm = queryAPI.pick (elementID_contains("MO21")); CHECK (otherElm); // now pick just some other arbitrary element testSession->insert(newPlacement, otherElm); dummy2 = queryAPI.pick (elementID_contains(specificID)); CHECK (dummy2); CHECK (dummy2 != dummy1); CHECK (dummy2 != newPlacement); CHECK (isSharedPointee(newPlacement, dummy2.getPlacement())); CHECK (Scope::containing (dummy2.getRef()) == Scope (otherElm)); INFO (test, "New treelocation: %s", cStr(ScopePath(dummy2.getPlacement()))); }
virtual void run (Arg) { IterQueue<int> queue; CHECK (isnil (queue)); VERIFY_ERROR (ITER_EXHAUST, *queue ); VERIFY_ERROR (ITER_EXHAUST, ++queue ); queue.feed (1); queue.feed (3); queue.feed (5); CHECK (!isnil (queue)); CHECK (1 == *queue); ++queue; CHECK (3 == *queue); CHECK (3 == queue.pop()); CHECK (5 == *queue); ++queue; CHECK (isnil (queue)); VERIFY_ERROR (ITER_EXHAUST, *queue ); VERIFY_ERROR (ITER_EXHAUST, ++queue ); VERIFY_ERROR (ITER_EXHAUST, queue.pop() ); // use the generic builder API to feed // the contents of another iterator into the queue queue = build(queue).usingSequence (elements (23,45)); int i = queue.pop(); CHECK (i == 23); CHECK (45 == *queue); // feeding new elements and pulling / iteration can be mixed queue.feed(67); CHECK (45 == *queue); ++queue; CHECK (67 == *queue); ++queue; CHECK (isnil (queue)); queue.feed(89); CHECK (89 == *queue); queue.pop(); VERIFY_ERROR (ITER_EXHAUST, *queue ); }
/** @test OpaqueHolder with additional storage for subclass. * When a subclass requires more storage than the base class or * Interface, we need to create a custom OpaqueHolder, specifying the * actually necessary storage. Such a custom OpaqueHolder behaves exactly * like the standard variant, but there is protection against accidentally * using a standard variant to hold an instance of the larger subclass. * * @test Moreover, if the concrete class has a custom operator bool(), it * will be invoked automatically from OpaqueHolder's operator bool() * */ void checkSpecialSubclass () { typedef OpaqueHolder<Base, sizeof(Special)> SpecialOpaque; cout << showSizeof<Base>() << endl; cout << showSizeof<Special>() << endl; cout << showSizeof<Opaque>() << endl; cout << showSizeof<SpecialOpaque>() << endl; CHECK (sizeof(Special) > sizeof(Base)); CHECK (sizeof(SpecialOpaque) > sizeof(Opaque)); CHECK (sizeof(SpecialOpaque) <= sizeof(Special) + sizeof(void*) + _ALIGN_); Special s1 (6); Special s2 (3); CHECK (!s1); // even value CHECK (s2); // odd value CHECK (7 == s1.getIt()); // indeed subclass of DD<7> CHECK (7 == s2.getIt()); SpecialOpaque ospe0; SpecialOpaque ospe1 (s1); SpecialOpaque ospe2 (s2); CHECK (!ospe0); // note: bool test (isValid) CHECK (!ospe1); // also forwarded to contained object (myVal_==6 is even) CHECK ( ospe2); CHECK ( isnil(ospe0)); // while isnil just checks the empty state CHECK (!isnil(ospe1)); CHECK (!isnil(ospe2)); CHECK (7 == ospe1->getIt()); CHECK (6 == ospe1.get<Special>().myVal_); CHECK (3 == ospe2.get<Special>().myVal_); ospe1 = DD<5>(); // but can be reassigned like any normal Opaque CHECK (ospe1); CHECK (5 == ospe1->getIt()); VERIFY_ERROR (WRONG_TYPE, ospe1.get<Special>() ); Opaque normal = DD<5>(); CHECK (normal); CHECK (5 == normal->getIt()); #if false ////////////////////////////////////////////////////////TODO: restore throwing ASSERT // Assertion protects against SEGV VERIFY_ERROR (ASSERTION, normal = s1 ); #endif//////////////////////////////////////////////////////////// }
inline bool protocolled (TY val2check) { return contains ( command2::check_.str() , lexical_cast<string> (val2check) ); }
/** Returns the tooltip for this item. */ const QString CSearchAnalysisItem::getToolTip() { typedef CSwordModuleSearch::Results::const_iterator RCI; using util::htmlEscape; QString toolTipString("<center><b>"); toolTipString.append(htmlEscape(m_bookName)).append("</b></center><hr/>") .append("<table cellspacing=\"0\" cellpadding=\"3\" width=\"10" "0%\" height=\"100%\" align=\"center\">"); /// \todo Fix that loop int i = 0; for (RCI it = m_results.begin(); it != m_results.end(); ++it) { const CSwordModuleInfo * const info = it.key(); const int count = it.value().getCount(); const double percent = (info && count) ? ((static_cast<double>(m_resultCountArray.at(i)) * static_cast<double>(100.0)) / static_cast<double>(count)) : 0.0; toolTipString.append("<tr bgcolor=\"white\"><td><b><font color=\"") .append(CSearchAnalysisScene::getColor(i).name()).append("\">") .append(info ? info->name() : QString::null) .append("</font></b></td><td>") .append(m_resultCountArray.at(i)) .append(" (") .append(QString::number(percent, 'g', 2)) .append("%)</td></tr>"); ++i; } return toolTipString.append("</table>"); }
Preprocessor::Preprocessor(String aFileName, int aMaxErrorNum) { curFileName = aFileName; curFile = new ifstream(curFileName.getCString(), ios::in); lineNumber = colNumber = 1; errorNum = warningNum = 0; maxErrorNum = aMaxErrorNum; backtracked = 0; if (!curFile->is_open()) { throw String("Error: couldn't open file."); delete curFile; curFile = NULL; return; } unsigned char i; for (i=0; i<255; i++) { firstIdentifierChars[i] = isLetterChar(i) || i=='_'; nextIdentifierChars[i] = isLetterChar(i) || isNumberChar(i) || i=='_'; firstNumberChars[i] = isNumberChar(i) || i=='.'; nextNumberChars[i] = isLetterChar(i) || isNumberChar(i) || i=='_' || i=='.'; specialChars[i] = false; } }
void verifyCreation_and_Copy() { typedef PV Holder; typedef IMP ImpType; typedef typename PV::Interface Api; long prevSum = _checkSum; uint prevCnt = _created; Holder val = Holder::template build<ImpType>(); CHECK (prevSum+111 == _checkSum); // We got one primary ctor call CHECK (prevCnt+1 <= _created); // Note: usually, the compiler optimises CHECK (prevCnt+2 >= _created); // and skips the spurious copy-operation CHECK (sizeof(Holder) >= sizeof(ImpType)); Api& embedded = val; CHECK (isSameObject(embedded,val)); CHECK (INSTANCEOF(ImpType, &embedded)); prevCnt = _created; Holder val2(val); // invoke copy ctor without knowing the implementation type embedded.apiFunc(); CHECK (val != val2); // invoking the API function had an sideeffect on the state val = val2; // assignment of copy back to the original... CHECK (val == val2); // cancels the side effect CHECK (prevCnt+1 == _created); // one new embedded instance was created by copy ctor }
void TreeDiffMutatorBinding::__failMismatch (Literal oper, GenNode const& spec) { throw error::State(_Fmt("Unable to %s element %s. Current shape of target " "data does not match expectations") % oper % spec , LUMIERA_ERROR_DIFF_CONFLICT); }
void TreeDiffMutatorBinding::__fail_not_found (GenNode const& elm) { throw error::State(_Fmt("Premature end of sequence; unable to locate " "element %s in the remainder of the target.") % elm , LUMIERA_ERROR_DIFF_CONFLICT); }
void Texture::draw() { bind(); quad.draw(); unbind(); checkGLError("Texture::draw quad draw"); }
void SAMReader::reinit(_int64 startingOffset, _int64 amountOfFileToProcess) { _ASSERT(-1 != headerSize && startingOffset >= headerSize); // Must call init() before reinit() // // There's no way to tell if we start at the very beginning of a read, we need to see the previous newline. // So, read one byte before our assigned read in case that was the terminating newline of the previous read. // if (startingOffset > headerSize) { startingOffset--; amountOfFileToProcess++; } data->reinit(startingOffset, amountOfFileToProcess); char* buffer; _int64 validBytes; if (!data->getData(&buffer, &validBytes)) { return; } if (startingOffset != headerSize) { char *firstNewline = strnchr(buffer,'\n',validBytes); if (NULL == firstNewline) { return; } data->advance((unsigned)(firstNewline - buffer + 1)); // +1 skips over the newline. } }
String Preprocessor::peek (unsigned int position) { while (tokens.size() <= position) { if (!getToken()) return String(); } return tokens [position].token; }
void TreeDiffMutatorBinding::__expect_further_elements (GenNode const& elm) { if (not treeMutator_->hasSrc()) throw error::State(_Fmt("Premature end of target sequence, still expecting element %s; " "unable to apply diff further.") % elm , LUMIERA_ERROR_DIFF_CONFLICT); }
void __expect_further_elements (E const& elm) { if (end_of_target()) throw error::State(_Fmt("Premature end of target sequence, still expecting element %s; " "unable to apply diff further.") % elm , LUMIERA_ERROR_DIFF_CONFLICT); }
void TreeDiffMutatorBinding::__expect_valid_parent_scope (GenNode::ID const& idi) { if (0 == scopeManger_->depth()) throw error::Fatal(_Fmt("Diff application floundered after leaving scope %s; " "unbalanced nested scopes, diff attempts to pop root.") % idi.getSym() , LUMIERA_ERROR_DIFF_CONFLICT); }
void __expect_found (E const& elm, Iter const& targetPos) { if (targetPos == orig_.end()) throw error::State(_Fmt("Premature end of sequence; unable to locate " "element %s in the remainder of the target.") % elm , LUMIERA_ERROR_DIFF_CONFLICT); }
/** @test verify the allocation/de-allocation handling as * embedded into the CommandRegistry operation. * Simulates on low level what normally happens * during command lifecycle. */ void checkAllocation (CommandRegistry& registry) { // simulate what normally happens within a CommandDef typedef void Sig_oper(int); typedef long Sig_capt(int); typedef void Sig_undo(int,long); function<Sig_oper> o_Fun (command1::operate); function<Sig_capt> c_Fun (command1::capture); function<Sig_undo> u_Fun (command1::undoIt); CHECK (o_Fun && c_Fun && u_Fun); CHECK (cnt_inst == registry.instance_count()); // when the CommandDef is complete, it issues the // allocation call to the registry behind the scenes.... typedef shared_ptr<CommandImpl> PImpl; PImpl pImpl = registry.newCommandImpl(o_Fun,c_Fun,u_Fun); CHECK (1+cnt_inst == registry.instance_count()); CHECK (pImpl); CHECK (pImpl->isValid()); CHECK (!pImpl->canExec()); CHECK (1 == pImpl.use_count()); // no magic involved, we hold the only instance PImpl clone = registry.createCloneImpl(*pImpl); CHECK (clone->isValid()); CHECK (!clone->canExec()); CHECK (1 == clone.use_count()); CHECK (1 == pImpl.use_count()); CHECK (2+cnt_inst == registry.instance_count()); CHECK (!isSameObject (*pImpl, *clone)); CHECK (*pImpl == *clone); CHECK (!pImpl->canExec()); typedef Types<int> ArgType; TypedArguments<Tuple<ArgType>> arg{Tuple<ArgType>(98765)}; pImpl->setArguments(arg); CHECK (pImpl->canExec()); CHECK (!clone->canExec()); // this proves the clone has indeed a separate identity CHECK (*pImpl != *clone); // discard the first clone and overwrite with a new one clone = registry.createCloneImpl(*pImpl); CHECK (2+cnt_inst == registry.instance_count()); CHECK (*pImpl == *clone); CHECK (clone->canExec()); clone.reset(); pImpl.reset(); // corresponding allocation slots cleared automatically CHECK (cnt_inst == registry.instance_count()); }
void TreeDiffMutatorBinding::__expect_end_of_scope (GenNode::ID const& idi) { if (not treeMutator_->completeScope()) throw error::State(_Fmt("Diff application floundered in nested scope %s; " "unexpected extra elements found when diff " "should have settled everything.") % idi.getSym() , LUMIERA_ERROR_DIFF_CONFLICT); }
unsigned char *Texture::mapData() { if(!texture) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboTexture); texture = (unsigned char*)(glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_WRITE)); } checkGLError("Texture::mapData"); return texture; }
TEST(Peak, RealsToPeaks) { Real positionsArray [] = {1, 0, 1, 4, 5}; Real magnitudesArray [] = {2, 2, 3, 1, 6}; util::Peak peaksArray [] = {util::Peak(1,2),util::Peak(0,2),util::Peak(1,3),util::Peak(4,1),util::Peak(5,6)}; vector<Real> positions = arrayToVector<Real>(positionsArray); vector<Real> magnitudes = arrayToVector<Real>(magnitudesArray); vector<util::Peak> peaks = realsToPeaks(positions, magnitudes); EXPECT_VEC_EQ(peaks, arrayToVector<util::Peak>(peaksArray)); }
/** finish and leave child object scope, return to parent */ void TreeDiffMutatorBinding::emu (GenNode const& n) { TRACE (diff, "tree-diff: LEAVE scope %s", cStr(n.idi)); __expect_end_of_scope (n.idi); treeMutator_ = &scopeManger_->closeScope(); __expect_valid_parent_scope (n.idi); }