bool ScriptDebuggerPrivate::executeCommand(const QString &command, const QStringList &args) { if (command == QLatin1String("c") || command == QLatin1String("continue")) { setMode(Run); return true; } else if (command == QLatin1String("s") || command == QLatin1String("step")) { setMode(StepInto); return true; } else if (command == QLatin1String("n") || command == QLatin1String("next")) { setMode(StepOver); m_stepDepth = 0; return true; } else if (command == QLatin1String("f") || command == QLatin1String("frame")) { bool ok = false; int index = args.value(0).toInt(&ok); if (ok) { if (index < 0 || index >= frameCount()) { errorMessage("No such frame."); } else { setCurrentFrameIndex(index); QScriptContext *ctx = currentFrameContext(); message(QString::fromLatin1("#%0 %1").arg(index).arg(ctx->toString())); } } } else if (command == QLatin1String("bt") || command == QLatin1String("backtrace")) { QScriptContext *ctx = engine()->currentContext(); int index = -1; while (ctx) { ++index; QString line = ctx->toString(); message(QString::fromLatin1("#%0 %1").arg(index).arg(line)); ctx = ctx->parentContext(); } } else if (command == QLatin1String("up")) { int index = currentFrameIndex() + 1; if (index == frameCount()) { errorMessage(QString::fromLatin1("Initial frame selected; you cannot go up.")); } else { setCurrentFrameIndex(index); QScriptContext *ctx = currentFrameContext(); message(QString::fromLatin1("#%0 %1").arg(index).arg(ctx->toString())); } } else if (command == QLatin1String("down")) { int index = currentFrameIndex() - 1; if (index < 0) { errorMessage(QString::fromLatin1("Bottom (innermost) frame selected; you cannot go down.")); } else { setCurrentFrameIndex(index); QScriptContext *ctx = currentFrameContext(); message(QString::fromLatin1("#%0 %1").arg(index).arg(ctx->toString())); } } else if (command == QLatin1String("b") || command == QLatin1String("break")) { QString str = args.value(0); int colonIndex = str.indexOf(QLatin1Char(':')); if (colonIndex != -1) { // filename:line form QString fileName = str.left(colonIndex); int lineNumber = str.mid(colonIndex+1).toInt(); int id = m_bpManager->setBreakpoint(fileName, lineNumber); message(QString::fromLatin1("Breakpoint %0 at %1, line %2.").arg(id+1).arg(fileName).arg(lineNumber)); } else { // function QScriptValue fun = engine()->globalObject().property(str); if (fun.isFunction()) { int id = m_bpManager->setBreakpoint(fun); message(QString::fromLatin1("Breakpoint %0 at %1().").arg(id+1).arg(str)); } } } else if (command == QLatin1String("d") || command == QLatin1String("delete")) { int id = args.value(0).toInt() - 1; m_bpManager->removeBreakpoint(id); } else if (command == QLatin1String("disable")) { int id = args.value(0).toInt() - 1; m_bpManager->setBreakpointEnabled(id, false); } else if (command == QLatin1String("enable")) { int id = args.value(0).toInt() - 1; m_bpManager->setBreakpointEnabled(id, true); } else if (command == QLatin1String("list")) { QScriptContext *ctx = currentFrameContext(); ScriptInfo *progInfo = scriptInfo(ctx); if (!progInfo) { errorMessage("No source text available for this frame."); } else { QScriptContextInfo ctxInfo(ctx); bool ok; int line = args.value(0).toInt(&ok); if (ok) { line = qMax(1, line - 5); } else { line = listLineNumber(); if (line == -1) line = qMax(progInfo->lineNumber(), ctxInfo.lineNumber() - 5); } for (int i = line; i < line + 10; ++i) { message(QString::fromLatin1("%0\t%1").arg(i).arg(progInfo->lineText(i))); } setListLineNumber(line + 10); } } else if (command == QLatin1String("info")) { if (args.size() < 1) { } else { QString what = args.value(0); if (what == QLatin1String("locals")) { QScriptValueIterator it(currentFrameContext()->activationObject()); while (it.hasNext()) { it.next(); QString line; line.append(it.name()); line.append(QLatin1String(" = ")); line.append(safeValueToString(it.value())); message(line); } } } } else if (command == QLatin1String("help")) { message("continue - continue execution\n" "step - step into statement\n" "next - step over statement\n" "list - show where you are\n" "\n" "break - set breakpoint\n" "delete - remove breakpoint\n" "disable - disable breakpoint\n" "enable - enable breakpoint\n" "\n" "backtrace - show backtrace\n" "up - one frame up\n" "down - one frame down\n" "frame - set frame\n" "\n" "info locals - show local variables"); } else { errorMessage(QString::fromLatin1("Undefined command \"%0\". Try \"help\".") .arg(command)); } return false; }
int main(int argc,char *argv[]) { int opt; PsimagLite::String file(""); SizeType total=0; RealType offset = 0; SizeType site3 = 0; RealType step = 0; while ((opt = getopt(argc, argv, "f:p:t:o:i:")) != -1) { switch (opt) { case 'f': file=optarg; break; case 'p': site3 = atoi(optarg); break; case 't': total = atoi(optarg); break; case 'i': step = atof(optarg); break; case 'o': offset = atof(optarg); break; default: /* '?' */ throw std::runtime_error("Wrong usage\n"); } } if (file=="") throw std::runtime_error("Wrong usage\n"); FreeFermions::InputCheck inputCheck; InputNgType::Writeable ioWriteable(file,inputCheck); InputNgType::Readable io(ioWriteable); GeometryParamsType geometryParams(io); SizeType electronsUp = GeometryParamsType::readElectrons(io,geometryParams.sites); PsimagLite::Vector<SizeType>::Type sites; GeometryParamsType::readVector(sites,file,"TSPSites"); sites.resize(3); sites[2] = site3; SizeType nthreads = 1; try { GeometryParamsType::readLabel(nthreads,file,"Threads="); } catch (std::exception& e) {} assert(nthreads>0); typedef PsimagLite::Concurrency ConcurrencyType; ConcurrencyType concurrency(&argc,&argv,nthreads); SizeType dof = 2; // spin up and down GeometryLibraryType geometry(geometryParams); std::cerr<<geometry; EngineType engine(geometry.matrix(),dof,false); PsimagLite::Vector<SizeType>::Type ne(dof,electronsUp); // 8 up and 8 down bool debug = false; bool verbose = false; RealType sum = 0; for (SizeType i=0;i<electronsUp;i++) sum += engine.eigenvalue(i); std::cerr<<"Energy="<<dof*sum<<"\n"; SizeType sigma3 = 0; std::cout<<"#sites= "; for (SizeType i=0;i<sites.size();i++) std::cout<<sites[i]<<" "; std::cout<<"\n"; typedef FreeFermions::ParallelHolonDoublon<RealType,FieldType,EngineType> ParallelHolonDoublonType; typedef PsimagLite::Parallelizer<ParallelHolonDoublonType> ParallelizerType; ParallelizerType threadedHolonDoublon(PsimagLite::Concurrency::npthreads, PsimagLite::MPI::COMM_WORLD); ParallelHolonDoublonType::HolonDoublonParamsType params(ne, sites, sigma3, offset, step, debug, verbose); ParallelHolonDoublonType helperHolonDoublon(engine,params); FieldType superdensity = helperHolonDoublon.calcSuperDensity(sites[0],sites[1]); std::cout<<"#superdensity="<<superdensity<<"\n"; threadedHolonDoublon.loopCreate(total,helperHolonDoublon); }
QScriptValue Mouse::position() const { return Point::constructor(mMouseDevice.cursorPosition(), engine()); }
bool Rect::intersects() const { return mRect.intersects(parameter(context(), engine())); }
QScriptValue Rect::size() const { return Size::constructor(mRect.size(), engine()); }
QScriptValue Rect::clone() const { return constructor(mRect, engine()); }
QScriptValue Rect::translate() { mRect.translate(Point::parameter(context(), engine())); return thisObject(); }
uint64_t IERandom::Int() { return engine(); }
double IERandom::Double01() { return (static_cast<double>(engine()) / std::mt19937_64::max()); }
uint64_t IERandom::IntMV(uint64_t mean, uint64_t variance) { assert(mean + variance <= std::mt19937_64::max()); assert(mean - variance >= std::mt19937_64::min()); return static_cast<uint64_t>(((static_cast<double>(engine()) / std::mt19937_64::max()) * 2 * variance)) + mean - variance; }
uint64_t IERandom::Int(uint64_t max) { assert(max <= std::mt19937_64::max()); return static_cast<uint64_t>(((static_cast<double>(engine()) / std::mt19937_64::max()) * max)); }
void americanSwaption( boost::shared_ptr<LiborForwardModel> & lfm, boost::shared_ptr<IborIndex> & libor, utilities::csvBuilder & file) { Date pricingDate = // pricing date Settings::instance().evaluationDate(); Date optionStart = libor->fixingCalendar().advance( // start in 2 days pricingDate, Period(2, Days)); Date optionEnd(16, July, 2016); Date fwdMaturity(16, July, 2021); //Date optionEnd = libor->fixingCalendar().advance( // start in 2 days // optionStart, // Period(6, Months)); //Date fwdMaturity = optionStart + Period(3, Years); // underlying 3 years Schedule schedule( optionStart, fwdMaturity, libor->tenor(), libor->fixingCalendar(), ModifiedFollowing, ModifiedFollowing, DateGeneration::Backward, false); Rate swapRate = 0.0404; // dummy swap rate boost::shared_ptr<VanillaSwap> forwardSwap( new VanillaSwap(VanillaSwap::Receiver, 100.0, schedule, swapRate, ActualActual(), schedule, libor, 0.0, libor->dayCounter())); forwardSwap->setPricingEngine(boost::shared_ptr<PricingEngine>( new DiscountingSwapEngine(libor->forwardingTermStructure()))); swapRate = forwardSwap->fairRate(); // obtain the fair rate forwardSwap = boost::shared_ptr<VanillaSwap>( // rebuild the "right" swap new VanillaSwap(VanillaSwap::Receiver, 100.0, schedule, swapRate, ActualActual(), schedule, libor, 0.0, libor->dayCounter())); forwardSwap->setPricingEngine(boost::shared_ptr<PricingEngine>( new DiscountingSwapEngine(libor->forwardingTermStructure()))); boost::shared_ptr<PricingEngine> engine( new LfmSwaptionEngine(lfm, libor->forwardingTermStructure())); boost::shared_ptr<Exercise> exercise( new AmericanExercise(optionEnd)); boost::shared_ptr<Swaption> americanSwaption( // create the swaption new Swaption(forwardSwap, exercise)); americanSwaption->setPricingEngine(engine); Real npv = americanSwaption->NPV(); std::cout << "American swaption npv: " // information << npv << std::endl; }
QScriptValue post_data_list_class::newInstance(const http_data_list &pdl) { QScriptValue data = engine()->newVariant(QVariant::fromValue(pdl)); return engine()->newObject(this, data); }
void ScriptDebuggerPrivate::positionChange(qint64 scriptId, int lineNumber, int /*columnNumber*/) { ScriptInfo *info = 0; bool enterInteractiveMode = false; if (m_bpManager->hasBreakpoints()) { // check if we hit a breakpoint info = m_scripts.value(scriptId); QScriptContext *ctx = engine()->currentContext(); QScriptContextInfo ctxInfo(ctx); QScriptValue callee = ctx->callee(); // try fileName:lineNumber int bpid = m_bpManager->findBreakpoint(info->fileName(), lineNumber); if ((bpid != -1) && m_bpManager->isBreakpointEnabled(bpid)) { message(QString::fromLatin1("Breakpoint %0 at %1:%2") .arg(bpid + 1).arg(info->fileName()).arg(lineNumber)); if (m_bpManager->isBreakpointSingleShot(bpid)) m_bpManager->removeBreakpoint(bpid); } if (bpid == -1) { // try function bpid = m_bpManager->findBreakpoint(callee); if ((bpid != -1) && m_bpManager->isBreakpointEnabled(bpid)) { message(QString::fromLatin1("Breakpoint %0, %1()") .arg(bpid + 1).arg(ctxInfo.functionName())); if (m_bpManager->isBreakpointSingleShot(bpid)) m_bpManager->removeBreakpoint(bpid); } } if ((bpid == -1) && !ctxInfo.functionName().isEmpty()) { // try functionName:fileName bpid = m_bpManager->findBreakpoint(ctxInfo.functionName(), ctxInfo.fileName()); if ((bpid != -1) && m_bpManager->isBreakpointEnabled(bpid)) { message(QString::fromLatin1("Breakpoint %0, %1():%2").arg(bpid + 1) .arg(ctxInfo.functionName()).arg(ctxInfo.fileName())); if (m_bpManager->isBreakpointSingleShot(bpid)) m_bpManager->removeBreakpoint(bpid); } } enterInteractiveMode = (bpid != -1); } switch (mode()) { case Run: break; case StepInto: enterInteractiveMode = true; break; case StepOver: enterInteractiveMode = enterInteractiveMode || (m_stepDepth <= 0); break; } if (enterInteractiveMode) { if (!info) info = m_scripts.value(scriptId); Q_ASSERT(info); message(QString::fromLatin1("%0\t%1").arg(lineNumber).arg(info->lineText(lineNumber))); interactive(); } }
void componentDisconnected() { CPPUNIT_ASSERT(engine()); engine()->stop(0); }
double IERandom::Double(double mean, double variance) { assert(variance >= 0); return ((static_cast<double>(engine()) / std::mt19937_64::max()) * 2 * variance) + mean - variance; }
void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const { ATRACE_CALL(); if (CC_UNLIKELY(mActiveBuffer == 0)) { // the texture has not been created yet, this Layer has // in fact never been drawn into. This happens frequently with // SurfaceView because the WindowManager can't know when the client // has drawn the first time. // If there is nothing under us, we paint the screen in black, otherwise // we just skip this update. // figure out if there is something below us Region under; const SurfaceFlinger::LayerVector& drawingLayers( mFlinger->mDrawingState.layersSortedByZ); const size_t count = drawingLayers.size(); for (size_t i=0 ; i<count ; ++i) { const sp<Layer>& layer(drawingLayers[i]); if (layer.get() == static_cast<Layer const*>(this)) break; under.orSelf( hw->getTransform().transform(layer->visibleRegion) ); } // if not everything below us is covered, we plug the holes! Region holes(clip.subtract(under)); if (!holes.isEmpty()) { clearWithOpenGL(hw, holes, 0, 0, 0, 1); } return; } // Bind the current buffer to the GL texture, and wait for it to be // ready for us to draw into. status_t err = mSurfaceFlingerConsumer->bindTextureImage(); if (err != NO_ERROR) { ALOGW("onDraw: bindTextureImage failed (err=%d)", err); // Go ahead and draw the buffer anyway; no matter what we do the screen // is probably going to have something visibly wrong. } bool canAllowGPU = false; #ifdef QCOM_BSP if(isProtected()) { char property[PROPERTY_VALUE_MAX]; if ((property_get("persist.gralloc.cp.level3", property, NULL) > 0) && (atoi(property) == 1)) { canAllowGPU = true; } } #endif bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure()); RenderEngine& engine(mFlinger->getRenderEngine()); if (!blackOutLayer || (canAllowGPU)) { // TODO: we could be more subtle with isFixedSize() const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize(); // Query the texture matrix given our current filtering mode. float textureMatrix[16]; mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering); mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix); if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) { /* * the code below applies the display's inverse transform to the texture transform */ // create a 4x4 transform matrix from the display transform flags const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1); const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1); const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1); mat4 tr; uint32_t transform = hw->getOrientationTransform(); if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) tr = tr * rot90; if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) tr = tr * flipH; if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) tr = tr * flipV; // calculate the inverse tr = inverse(tr); // and finally apply it to the original texture matrix const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr); memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix)); } // Set things up for texturing. mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight()); mTexture.setFiltering(useFiltering); mTexture.setMatrix(textureMatrix); engine.setupLayerTexturing(mTexture); } else { engine.setupLayerBlackedOut(); } drawWithOpenGL(hw, clip); engine.disableTexturing(); }
TEST( RocksEngineTest, DropDirect1 ) { std::string path = "/tmp/mongo-rocks-engine-test"; boost::filesystem::remove_all( path ); RocksEngine engine( path ); { MyOperationContext opCtx( &engine ); Status status = engine.createCollection( &opCtx, "test.foo", CollectionOptions() ); ASSERT_OK( status ); } { MyOperationContext opCtx( &engine ); Status status = engine.createCollection( &opCtx, "test.bar", CollectionOptions() ); ASSERT_OK( status ); } { MyOperationContext opCtx( &engine ); Status status = engine.createCollection( &opCtx, "silly.bar", CollectionOptions() ); ASSERT_OK( status ); } { std::list<std::string> names; engine.getCollectionNamespaces( "test", &names ); ASSERT_EQUALS( 2U, names.size() ); } { std::list<std::string> names; engine.getCollectionNamespaces( "silly", &names ); ASSERT_EQUALS( 1U, names.size() ); } { MyOperationContext opCtx( &engine ); Status status = engine.dropCollection( &opCtx, "test.foo" ); ASSERT_OK( status ); } { std::list<std::string> names; engine.getCollectionNamespaces( "test", &names ); ASSERT_EQUALS( 1U, names.size() ); ASSERT_EQUALS( names.front(), "test.bar" ); } { MyOperationContext opCtx( &engine ); Status status = engine.dropCollection( &opCtx, "test.foo" ); ASSERT_NOT_OK( status ); } }
QScriptValue Rect::setSize() { mRect.setSize(Size::parameter(context(), engine())); return thisObject(); }
QScriptValue ArrayBufferClass::newInstance(const QByteArray& ba) { QScriptValue data = engine()->newVariant(QVariant::fromValue(ba)); return engine()->newObject(this, data); }
QScriptValue Rect::intersected() const { return constructor(mRect.intersected(parameter(context(), engine())), engine()); }
int main(int argc, char *argv[]) { register int i; int c; char *p; char path[MAXPATHLEN]; pmOptions opts = { .short_options = allflags, .flags = PM_OPTFLAG_BOUNDARIES, }; /* ** preserve command arguments to allow restart of other version */ argvp = argv; /* ** read defaults-files /etc/atoprc en $HOME/.atoprc (if any) */ readrc("/etc/atoprc", 1); if ( (p = getenv("HOME")) ) { snprintf(path, sizeof(path), "%s/.atoprc", p); path[sizeof(path)-1] = '\0'; readrc(path, 0); } /* ** check if we are supposed to behave as 'atopsar' ** i.e. system statistics only */ __pmSetProgname(argv[0]); if (strcmp(pmProgname, "pcp-atopsar") == 0) return atopsar(argc, argv); __pmStartOptions(&opts); if (opts.narchives > 0) rawreadflag++; /* ** interpret command-line arguments & flags */ if (argc > 1) { /* ** gather all flags for visualization-functions ** ** generic flags will be handled here; ** unrecognized flags are passed to the print-routines */ i = 0; while (i < MAXFL-1 && (c = pmgetopt_r(argc, argv, &opts)) != EOF) { switch (c) { case '?': /* usage wanted ? */ prusage(pmProgname); break; case 'V': /* version wanted ? */ printf("%s\n", getstrvers()); exit(0); case 'w': /* writing of raw data ? */ rawname = opts.optarg; rawwriteflag++; break; case 'r': /* reading of raw data ? */ rawarchive(&opts, opts.optarg); rawreadflag++; break; case 'S': /* midnight limit ? */ midnightflag++; break; case 'a': /* all processes per sample ? */ deviatonly = 0; break; case 'R': /* all processes per sample ? */ calcpss = 1; break; case 'b': /* begin time ? */ opts.start_optarg = abstime(opts.optarg); break; case 'e': /* end time ? */ opts.finish_optarg = abstime(opts.optarg); break; case 'P': /* parseable output? */ if ( !parsedef(opts.optarg) ) prusage(pmProgname); vis.show_samp = parseout; break; case 'L': /* line length */ if ( !numeric(opts.optarg) ) prusage(pmProgname); linelen = atoi(opts.optarg); break; default: /* gather other flags */ flaglist[i++] = c; } } /* ** get optional interval-value and optional number of samples */ if (opts.optind < argc && opts.optind < MAXFL) { char *endnum, *arg; arg = argv[opts.optind++]; if (pmParseInterval(arg, &opts.interval, &endnum) < 0) { pmprintf( "%s: %s option not in pmParseInterval(3) format:\n%s\n", pmProgname, arg, endnum); free(endnum); opts.errors++; } else interval = opts.interval; if (opts.optind < argc) { arg = argv[opts.optind]; if (!numeric(arg)) prusage(pmProgname); if ((opts.samples = atoi(arg)) < 1) prusage(pmProgname); nsamples = opts.samples; } } } __pmEndOptions(&opts); if (opts.errors) prusage(pmProgname); /* ** find local host details (no privileged access required) */ setup_globals(&opts); /* ** check if we are in data recording mode */ if (rawwriteflag) { rawwrite(&opts, rawname, &interval, nsamples, midnightflag); cleanstop(0); } /* ** catch signals for proper close-down */ signal(SIGHUP, cleanstop); signal(SIGTERM, cleanstop); /* ** switch-on the process-accounting mechanism to register the ** (remaining) resource-usage by processes which have finished */ acctreason = acctswon(); /* ** determine properties (like speed) of all interfaces */ initifprop(); /* ** open socket to the IP layer to issue getsockopt() calls later on */ netatop_ipopen(); /* ** start the engine now ..... */ engine(); cleanstop(0); return 0; /* never reached */ }
QScriptValue Rect::center() const { return Point::constructor(mRect.center(), engine()); }
int main(int argc,char* argv[]) { int opt; PsimagLite::String file(""); while ((opt = getopt(argc, argv, "f:")) != -1) { switch (opt) { case 'f': file=optarg; break; default: /* '?' */ err("Wrong usage\n"); } } if (file == "") err("Wrong usage\n"); FreeFermions::InputCheck inputCheck; InputNgType::Writeable ioWriteable(file,inputCheck); InputNgType::Readable io(ioWriteable); GeometryParamsType geometryParams(io); SizeType electronsUp = GeometryParamsType::readElectrons(io, geometryParams.sites); SizeType dof = 2; // spin GeometryLibraryType geometry(geometryParams); std::cerr<<geometry; SizeType npthreads = 1; ConcurrencyType concurrency(&argc,&argv,npthreads); EngineType engine(geometry.matrix(), geometryParams.outputFile, dof, EngineType::VERBOSE_YES); PsimagLite::Vector<SizeType>::Type ne(dof,electronsUp); HilbertStateType gs(engine,ne); RealType sum = 0; for (SizeType i=0;i<ne[0];i++) sum += engine.eigenvalue(i); std::cerr<<"Energy="<<dof*sum<<"\n"; SizeType n = geometryParams.sites; SizeType norb = (geometryParams.type == GeometryLibraryType::FEAS || geometryParams.type == GeometryLibraryType::FEAS1D) ? geometryParams.orbitals : 1; for (SizeType orbital1=0; orbital1<norb; orbital1++) { for (SizeType orbital2=0; orbital2<norb; orbital2++) { for (SizeType site = 0; site<n ; site++) { OpNormalFactoryType opNormalFactory(engine); OperatorType& myOp1 = opNormalFactory(OperatorType::DESTRUCTION, site+orbital1*n, SPIN_DOWN); OperatorType& myOp2 = opNormalFactory(OperatorType::CREATION, site+orbital1*n, SPIN_UP); OperatorType& myOp3 = opNormalFactory(OperatorType::DESTRUCTION, site+orbital1*n, SPIN_UP); OperatorType& myOp4 = opNormalFactory(OperatorType::CREATION, site+orbital1*n, SPIN_DOWN); HilbertStateType phi1 = gs; myOp1.applyTo(phi1); myOp2.applyTo(phi1); HilbertStateType phi2 = gs; myOp3.applyTo(phi2); myOp4.applyTo(phi2); for (SizeType site2=0; site2<n; site2++) { OperatorType& myOp5 = opNormalFactory(OperatorType::DESTRUCTION, site2+orbital2*n, SPIN_DOWN); OperatorType& myOp6 = opNormalFactory(OperatorType::CREATION, site2+orbital2*n, SPIN_UP); OperatorType& myOp7 = opNormalFactory(OperatorType::DESTRUCTION, site2+orbital2*n, SPIN_UP); OperatorType& myOp8 = opNormalFactory(OperatorType::CREATION, site2+orbital2*n, SPIN_DOWN); HilbertStateType phi3 = gs; myOp5.applyTo(phi3); myOp6.applyTo(phi3); HilbertStateType phi4 = gs; myOp7.applyTo(phi4); myOp8.applyTo(phi4); RealType x13 = scalarProduct(phi3,phi1); RealType x24 = scalarProduct(phi4,phi2); std::cout<<(x13+x24)<<" "; //cicj(site,site2) += scalarProduct(gs,phi); } std::cout<<"\n"; } std::cout<<"-------------------------------------------\n"; } } }
int main(int argc, char* argv[]){ double *mesh; hydro_prob Hp; hydro_args Ha; int i,j; int init=0; int pSMul=1; int iDiv=0, jDiv=0; //select from hardcoded inits if(argc<2){ printf("No init supplied\n"); } else { if(!strcmp(argv[1],"sod")) init=1; else if(!strcmp(argv[1],"crn")) init=2; else if(!strcmp(argv[1],"wsc")) init=3; else if(!strcmp(argv[1],"scs")) init=4; else printf("Unknown init\n"); } //Get size multiplier if(init>2&&(argc<3||sscanf(argv[2],"%d",&pSMul)!=1)){ printf("No problem size multiplier supplied\n"); return 1; } if(pSMul<=0){ return 1; } Ha.sigma=0.9; Ha.nprtLine=100; printf("INIT:%s\n",argv[1]); switch(init){ case 1: Hp.nx=100; Hp.ny=1000; Hp.dx=0.25/Hp.nx; Hp.dy=1.0/Hp.ny; iDiv=100; jDiv=500; sprintf(Ha.outPre,"outDir/sod"); Ha.tend=-1.0; Ha.dtoutput=-0.01; Ha.nstepmax=1000; Ha.noutput=-1; break; case 2: Hp.nx=1000; Hp.ny=1000; Hp.dx=1.0/Hp.nx; Hp.dy=1.0/Hp.ny; iDiv=500; jDiv=500; sprintf(Ha.outPre,"outDir/crn"); Ha.tend=-1.0; Ha.dtoutput=-0.01; Ha.nstepmax=1000; Ha.noutput=-1; break; case 3: Hp.nx=100; Hp.ny=1000*pSMul; Hp.dx=0.25/Hp.nx; Hp.dy=1.0/Hp.ny; iDiv=100; jDiv=0.5*Hp.ny; sprintf(Ha.outPre,"outDir/wsc"); Ha.tend=-1.0; Ha.dtoutput=-0.01; Ha.nstepmax=1000; Ha.noutput=-1; break; case 4: Hp.nx=10*pSMul; Hp.ny=10*pSMul; Hp.dx=1.0/Hp.nx; Hp.dy=1.0/Hp.ny; iDiv=4; jDiv=500; sprintf(Ha.outPre,"outDir/scs"); Ha.tend=-1.0; Ha.dtoutput=-0.01; Ha.nstepmax=1000; Ha.noutput=-1; break; default: Hp.nx=100; Hp.ny=100; Hp.dx=0.1; Hp.dy=0.1; iDiv=0; jDiv=0; sprintf(Ha.outPre,"outDir/out"); Ha.tend=-1.0; Ha.dtoutput=-0.01; Ha.nstepmax=100; Ha.noutput=-1; break; } Hp.t=0.0; Hp.nvar=4; mesh=(double*)malloc(Hp.nvar*Hp.nx*Hp.ny*sizeof(double)); Hp.gamma=1.4; Hp.bndL=BND_REFL; Hp.bndR=BND_REFL; Hp.bndU=BND_REFL; Hp.bndD=BND_REFL; Ha.smallr=1e-10; Ha.smallc=1e-10; Ha.niter_riemann=10; for(j=0;j<Hp.ny;j++){ for(i=0;i<Hp.nx;i++){ mesh[i+Hp.nx*(j+Hp.ny*VARRHO)]=0.125; mesh[i+Hp.nx*(j+Hp.ny*VARVX )]=0.0; mesh[i+Hp.nx*(j+Hp.ny*VARVY )]=0.0; mesh[i+Hp.nx*(j+Hp.ny*VARPR )]=0.25; } } for(j=0;j<jDiv;j++){ for(i=0;i<iDiv;i++){ mesh[i+Hp.nx*(j+Hp.ny*VARRHO)]=1.0; mesh[i+Hp.nx*(j+Hp.ny*VARVX )]=0.0; mesh[i+Hp.nx*(j+Hp.ny*VARVY )]=0.0; mesh[i+Hp.nx*(j+Hp.ny*VARPR )]=2.5; } } engine(mesh,&Hp,&Ha); free(mesh); }
int main(int argc, const char ** argv) { print_copyright(); /* GraphChi initialization will read the command line arguments and the configuration file. */ graphchi_init(argc, argv); /* Metrics object for keeping track of performance counters and other information. Currently required. */ metrics m("item-cf"); /* Basic arguments for application */ min_allowed_intersection = get_option_int("min_allowed_intersection", min_allowed_intersection); distance_metric = get_option_int("distance", JACCARD); asym_cosine_alpha = get_option_float("asym_cosine_alpha", 0.5); if (distance_metric != JACCARD && distance_metric != AA && distance_metric != RA && distance_metric != ASYM_COSINE) logstream(LOG_FATAL)<<"Wrong distance metric. --distance_metric=XX, where XX should be either 0) JACCARD, 1) AA, 2) RA, 3) ASYM_COSINE" << std::endl; parse_command_line_args(); mytimer.start(); int nshards = convert_matrixmarket<EdgeDataType>(training/*, orderByDegreePreprocessor*/); if (nshards != 1) logstream(LOG_FATAL)<<"This application currently supports only 1 shard" << std::endl; K = get_option_int("K", K); if (K <= 0) logstream(LOG_FATAL)<<"Please specify the number of ratings to generate for each user using the --K command" << std::endl; assert(M > 0 && N > 0); //initialize data structure which saves a subset of the items (pivots) in memory adjcontainer = new adjlist_container(); //array for marking which items are conected to the pivot items via users. relevant_items = new bool[N]; //store node degrees in an array to be used for AA distance metric if (distance_metric == AA || distance_metric == RA) latent_factors_inmem.resize(M); /* Run */ ItemDistanceProgram program; graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, true, m); set_engine_flags(engine); engine.set_maxwindow(M+N+1); //open output files as the number of operating threads out_files.resize(number_of_omp_threads()); for (uint i=0; i< out_files.size(); i++){ char buf[256]; sprintf(buf, "%s.out%d", training.c_str(), i); out_files[i] = open_file(buf, "w"); } //run the program engine.run(program, niters); /* Report execution metrics */ if (!quiet) metrics_report(m); std::cout<<"Total item pairs compared: " << item_pairs_compared << " total written to file: " << sum(written_pairs) << " pairs with zero distance: " << zero_dist << std::endl; if (not_enough) logstream(LOG_WARNING)<<"Items that did not have enough similar items: " << not_enough << std::endl; for (uint i=0; i< out_files.size(); i++){ fflush(out_files[i]); fclose(out_files[i]); } std::cout<<"Created " << number_of_omp_threads() << " output files with the format: " << training << ".outXX, where XX is the output thread number" << std::endl; delete[] relevant_items; return 0; }
int main(int argc, const char ** argv) { print_copyright(); //* GraphChi initialization will read the command line arguments and the configuration file. */ graphchi_init(argc, argv); /* Metrics object for keeping track of performance counters and other information. Currently required. */ metrics m("svdpp-inmemory-factors"); svdpp.step_dec = get_option_float("svdpp_step_dec", 0.9); svdpp.itmBiasStep = get_option_float("svdpp_item_bias_step", 1e-3); svdpp.itmBiasReg = get_option_float("svdpp_item_bias_reg", 1e-3); svdpp.usrBiasStep = get_option_float("svdpp_user_bias_step", 1e-3); svdpp.usrBiasReg = get_option_float("svdpp_user_bias_reg", 1e-3); svdpp.usrFctrStep = get_option_float("svdpp_user_factor_step", 1e-3); svdpp.usrFctrReg = get_option_float("svdpp_user_factor_reg", 1e-3); svdpp.itmFctrReg = get_option_float("svdpp_item_factor_reg", 1e-3); svdpp.itmFctrStep = get_option_float("svdpp_item_factor_step", 1e-3); svdpp.itmFctr2Reg = get_option_float("svdpp_item_factor2_reg", 1e-3); svdpp.itmFctr2Step = get_option_float("svdpp_item_factor2_step", 1e-3); parse_command_line_args(); parse_implicit_command_line(); /* Preprocess data if needed, or discover preprocess files */ int nshards = convert_matrixmarket<EdgeDataType>(training, 0, 0, 3, TRAINING, false); if (validation != "") { int vshards = convert_matrixmarket<EdgeDataType>(validation, 0, 0, 3, VALIDATION, false); init_validation_rmse_engine<VertexDataType, EdgeDataType>(pvalidation_engine, vshards, &svdpp_predict); } svdpp_init(); if (load_factors_from_file) { load_matrix_market_matrix(training + "_U.mm", 0, 2*D); load_matrix_market_matrix(training + "_V.mm", M, D); load_matrix_market_vector(training + "_U_bias.mm", BIAS_POS, false, true, 0); load_matrix_market_vector(training + "_V_bias.mm", BIAS_POS, false, true, M); vec gm = load_matrix_market_vector(training + "_global_mean.mm", false, true); globalMean = gm[0]; } /* Run */ SVDPPVerticesInMemProgram program; graphchi_engine<VertexDataType, EdgeDataType> engine(training, nshards, false, m); set_engine_flags(engine); pengine = &engine; engine.run(program, niters); /* Output latent factor matrices in matrix-market format */ output_svdpp_result(training); test_predictions(&svdpp_predict); /* Report execution metrics */ if (!quiet) metrics_report(m); return 0; }
int main(int argc, char** argv) { // Initialize control plain using mpi graphlab::mpi_tools::init(argc, argv); graphlab::distributed_control dc; global_logger().set_log_level(LOG_INFO); // Parse command line options ----------------------------------------------- graphlab::command_line_options clopts("Single Source Shortest Path Algorithm."); std::string graph_dir; std::string format = "adj"; std::string exec_type = "synchronous"; size_t powerlaw = 0; std::vector<graphlab::vertex_id_type> sources; bool max_degree_source = false; clopts.attach_option("graph", graph_dir, "The graph file. If none is provided " "then a toy graph will be created"); clopts.add_positional("graph"); clopts.attach_option("format", format, "graph format"); clopts.attach_option("source", sources, "The source vertices"); clopts.attach_option("max_degree_source", max_degree_source, "Add the vertex with maximum degree as a source"); clopts.add_positional("source"); clopts.attach_option("directed", DIRECTED_SSSP, "Treat edges as directed."); clopts.attach_option("engine", exec_type, "The engine type synchronous or asynchronous"); clopts.attach_option("powerlaw", powerlaw, "Generate a synthetic powerlaw out-degree graph. "); std::string saveprefix; clopts.attach_option("saveprefix", saveprefix, "If set, will save the resultant pagerank to a " "sequence of files with prefix saveprefix"); if(!clopts.parse(argc, argv)) { dc.cout() << "Error in parsing command line arguments." << std::endl; return EXIT_FAILURE; } // Build the graph ---------------------------------------------------------- graph_type graph(dc, clopts); if(powerlaw > 0) { // make a synthetic graph dc.cout() << "Loading synthetic Powerlaw graph." << std::endl; graph.load_synthetic_powerlaw(powerlaw, false, 2, 100000000); } else if (graph_dir.length() > 0) { // Load the graph from a file dc.cout() << "Loading graph in format: "<< format << std::endl; graph.load_format(graph_dir, format); } else { dc.cout() << "graph or powerlaw option must be specified" << std::endl; clopts.print_description(); return EXIT_FAILURE; } // must call finalize before querying the graph graph.finalize(); dc.cout() << "#vertices: " << graph.num_vertices() << std::endl << "#edges: " << graph.num_edges() << std::endl; if(sources.empty()) { if (max_degree_source == false) { dc.cout() << "No source vertex provided. Adding vertex 0 as source" << std::endl; sources.push_back(0); } } if (max_degree_source) { max_deg_vertex_reducer v = graph.map_reduce_vertices<max_deg_vertex_reducer>(find_max_deg_vertex); dc.cout() << "No source vertex provided. Using highest degree vertex " << v.vid << " as source." << std::endl; sources.push_back(v.vid); } // Running The Engine ------------------------------------------------------- graphlab::omni_engine<sssp> engine(dc, graph, exec_type, clopts); // Signal all the vertices in the source set for(size_t i = 0; i < sources.size(); ++i) { engine.signal(sources[i], min_distance_type(0)); } engine.start(); const float runtime = engine.elapsed_seconds(); dc.cout() << "Finished Running engine in " << runtime << " seconds." << std::endl; // Save the final graph ----------------------------------------------------- if (saveprefix != "") { graph.save(saveprefix, shortest_path_writer(), false, // do not gzip true, // save vertices false); // do not save edges } // Tear-down communication layer and quit ----------------------------------- graphlab::mpi_tools::finalize(); return EXIT_SUCCESS; } // End of main
QScriptValue Mouse::move() const { mMouseDevice.setCursorPosition(Point::parameter(context(), engine())); return thisObject(); }
bool PCMPlayer::Start(PCMSynthesiser &_synthesiser, unsigned _sample_rate) { #ifdef ANDROID /* why, oh why is OpenSL/ES so complicated? */ SLObjectItf _object; SLresult result = SLES::CreateEngine(&_object, 0, nullptr, 0, nullptr, nullptr); if (result != SL_RESULT_SUCCESS) { LogFormat("PCMPlayer: slCreateEngine() result=%#x", (int)result); return false; } engine_object = SLES::Object(_object); result = engine_object.Realize(false); if (result != SL_RESULT_SUCCESS) { LogFormat("PCMPlayer: Engine.Realize() result=%#x", (int)result); engine_object.Destroy(); return false; } SLEngineItf _engine; result = engine_object.GetInterface(*SLES::IID_ENGINE, &_engine); if (result != SL_RESULT_SUCCESS) { LogFormat("PCMPlayer: Engine.GetInterface(IID_ENGINE) result=%#x", (int)result); engine_object.Destroy(); return false; } SLES::Engine engine(_engine); result = engine.CreateOutputMix(&_object, 0, nullptr, nullptr); if (result != SL_RESULT_SUCCESS) { LogFormat("PCMPlayer: CreateOutputMix() result=%#x", (int)result); engine_object.Destroy(); return false; } mix_object = SLES::Object(_object); result = mix_object.Realize(false); if (result != SL_RESULT_SUCCESS) { LogFormat("PCMPlayer: Mix.Realize() result=%#x", (int)result); mix_object.Destroy(); engine_object.Destroy(); return false; } SLDataLocator_AndroidSimpleBufferQueue loc_bufq = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, ARRAY_SIZE(buffers) - 1, }; SLDataFormat_PCM format_pcm; format_pcm.formatType = SL_DATAFORMAT_PCM; format_pcm.numChannels = 1; /* from the Android NDK docs: "Note that the field samplesPerSec is actually in units of milliHz, despite the misleading name." */ format_pcm.samplesPerSec = _sample_rate * 1000; format_pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16; format_pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16; format_pcm.channelMask = SL_SPEAKER_FRONT_CENTER; format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; // XXX SLDataSource audioSrc = { &loc_bufq, &format_pcm }; SLDataLocator_OutputMix loc_outmix = { SL_DATALOCATOR_OUTPUTMIX, mix_object, }; SLDataSink audioSnk = { &loc_outmix, nullptr, }; const SLInterfaceID ids2[] = { *SLES::IID_PLAY, *SLES::IID_ANDROIDSIMPLEBUFFERQUEUE, }; static constexpr SLboolean req2[] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, }; result = engine.CreateAudioPlayer(&_object, &audioSrc, &audioSnk, ARRAY_SIZE(ids2), ids2, req2); if (result != SL_RESULT_SUCCESS) { LogFormat("PCMPlayer: CreateAudioPlayer() result=%#x", (int)result); mix_object.Destroy(); engine_object.Destroy(); return false; } play_object = SLES::Object(_object); result = play_object.Realize(false); if (result != SL_RESULT_SUCCESS) { LogFormat("PCMPlayer: Play.Realize() result=%#x", (int)result); play_object.Destroy(); mix_object.Destroy(); engine_object.Destroy(); return false; } SLPlayItf _play; result = play_object.GetInterface(*SLES::IID_PLAY, &_play); if (result != SL_RESULT_SUCCESS) { LogFormat("PCMPlayer: Play.GetInterface(IID_PLAY) result=%#x", (int)result); play_object.Destroy(); mix_object.Destroy(); engine_object.Destroy(); return false; } play = SLES::Play(_play); SLAndroidSimpleBufferQueueItf _queue; result = play_object.GetInterface(*SLES::IID_ANDROIDSIMPLEBUFFERQUEUE, &_queue); if (result != SL_RESULT_SUCCESS) { LogFormat("PCMPlayer: Play.GetInterface(IID_ANDROIDSIMPLEBUFFERQUEUE) result=%#x", (int)result); play_object.Destroy(); mix_object.Destroy(); engine_object.Destroy(); return false; } queue = SLES::AndroidSimpleBufferQueue(_queue); result = queue.RegisterCallback(PlayedCallback, (void *)this); if (result != SL_RESULT_SUCCESS) { LogFormat("PCMPlayer: Play.RegisterCallback() result=%#x", (int)result); play_object.Destroy(); mix_object.Destroy(); engine_object.Destroy(); return false; } synthesiser = &_synthesiser; result = play.SetPlayState(SL_PLAYSTATE_PLAYING); if (result != SL_RESULT_SUCCESS) { LogFormat("PCMPlayer: Play.SetPlayState(PLAYING) result=%#x", (int)result); play_object.Destroy(); mix_object.Destroy(); engine_object.Destroy(); synthesiser = nullptr; return false; } next = 0; filled = false; for (unsigned i = 0; i < ARRAY_SIZE(buffers) - 1; ++i) Enqueue(); return true; #elif defined(WIN32) #else if (synthesiser != nullptr) { if (_sample_rate == sample_rate) { /* already open, just change the synthesiser */ SDL_LockAudio(); synthesiser = &_synthesiser; SDL_UnlockAudio(); return true; } Stop(); } sample_rate = _sample_rate; SDL_AudioSpec spec; spec.freq = sample_rate; spec.format = AUDIO_S16SYS; spec.channels = 2; spec.samples = 4096; spec.callback = ::Synthesise; spec.userdata = this; if (SDL_OpenAudio(&spec, nullptr) < 0) return false; synthesiser = &_synthesiser; SDL_PauseAudio(0); return true; #endif }