// ###################################################################### std::string ResizeSpec::toString() const { switch (itsMethod) { case NOOP: return "noop"; break; case FIXED: return convertToString(itsNewDims); break; case SCALE_UP: if (itsFactorW == itsFactorH) return sformat("*%g", itsFactorW); else return sformat("*%gx%g", itsFactorW, itsFactorH); break; case SCALE_DOWN: if (itsFactorW == itsFactorH) return sformat("/%g", itsFactorW); else return sformat("/%gx%g", itsFactorW, itsFactorH); break; } ASSERT(0); /* can't happen */ return std::string(); }
/** * This is called on every frame. * * @param wparam Not used. Here to match a function definition. * @param lparam Not used. Here to match a function definition. * @return 0. Not used. Here to match a function definition. */ /*afx_msg*/ LRESULT PageChunkWatcher::OnUpdateControls ( WPARAM /*wparam*/, LPARAM /*lparam*/ ) { if (chunkWatchCtrl_.GetSafeHwnd() != NULL) chunkWatchCtrl_.OnUpdateControl(); ChunkWatcher const &cw = WorldManager::instance().chunkWatcher(); if (numUnloaded_ != cw.numberUnloadedChunks()) { numUnloaded_ = cw.numberUnloadedChunks(); controls::setWindowText(*this, IDC_UNLOADED_NUM, sformat("{0}", numUnloaded_)); } if (numLoaded_ != cw.numberLoadedChunks()) { numLoaded_ = cw.numberLoadedChunks(); controls::setWindowText(*this, IDC_LOADED_NUM, sformat("{0}", numLoaded_)); } if (numDirty_ != cw.numberDirtyChunks()) { numDirty_ = cw.numberDirtyChunks(); controls::setWindowText(*this, IDC_NEEDSSHADOW_NUM, sformat("{0}", numDirty_)); } if (numCalced_ != cw.numberCalcedChunks()) { numCalced_ = cw.numberCalcedChunks(); controls::setWindowText(*this, IDC_DONESHADOW_NUM, sformat("{0}", numCalced_)); } return 0; }
// ###################################################################### std::string SimTime::toString(bool with_suffix) const { if (with_suffix) return sformat("%g", this->secs()); else return sformat("%gs", this->secs()); }
// ###################################################################### IntegerDirectionChannel:: IntegerDirectionChannel(OptionManager& mgr, const uint dirIndex, const double direction, const int dxnumer, const int dynumer, const uint denombits, nub::ref<IntegerMathEngine> eng) : IntegerSimpleChannel(mgr, "", "", MOTION, rutz::make_shared (new IntgReichardtPyrBuilder (dxnumer, dynumer, denombits, eng->getImath())), eng), itsIndex("IntegerDirectionChannelIndex", this, dirIndex), itsDirection("IntegerDirectionChannelDirection", this, direction), itsThresh(&OPT_DirectionChannelLowThresh, this) { GVX_TRACE(__PRETTY_FUNCTION__); itsTakeAbs.setVal(true); itsNormalizeOutput.setVal(true); itsScaleNoiseToMax.setVal(true); // kill small values in pyramid: const float fthresh = itsThresh.getVal(); itsLowThresh.setVal(intgScaleFromFloat(&fthresh, this->getImath()->nbits)); // kill negative values in pyramid: itsRectifyPyramid.setVal(true); setDescriptiveName(sformat("Integer Direction(%d)", int(direction))); setTagName(sformat("int-dir_%d", dirIndex)); }
void Logger::saveSingleEventFrame(MbariImage< PixRGB<byte> >& img, int frameNum, MbariVisualEvent::VisualEvent *event) { ASSERT(event->frameInRange(frameNum)); // create the file stem string evnum; if (itsSaveEventFeatures.getVal().length() > 0) evnum = sformat("%s_evt%04d_", itsSaveEventFeatures.getVal().c_str(), event->getEventNum() ); else evnum = sformat("evt%04d_", event->getEventNum()); Dims maxDims = event->getMaxObjectDims(); Dims d((float)maxDims.w()*itsScaleW, (float)maxDims.h()*itsScaleH); // compute the correct bounding box and cut it out Rectangle bbox1 = event->getToken(frameNum).bitObject.getBoundingBox(); Rectangle bbox = Rectangle::tlbrI(bbox1.top()*itsScaleH, bbox1.left()*itsScaleW, bbox1.bottomI()*itsScaleH, bbox1.rightI()*itsScaleW); //Point2D cen = event.getToken(frameNum).bitObject.getCentroid(); // first the horizontal direction int wpad = (d.w() - bbox.width()) / 2; int ll = bbox.left() - wpad; //int ll = cen.i - d.w() / 2; int rr = ll + d.w(); if (ll < 0) { rr -= ll; ll = 0; } if (rr >= img.getWidth()) { rr = img.getWidth() - 1; ll = rr - d.w(); } // now the same thing with the vertical direction int hpad = (d.h() - bbox.height()) / 2; int tt = bbox.top() - hpad; //int tt = cen.j - d.h() / 2; int bb = tt + d.h(); if (tt < 0) { bb -= tt; tt = 0; } if (bb >= img.getHeight()) { bb = img.getHeight() - 1; tt = bb - d.h(); } Rectangle bboxFinal = Rectangle::tlbrI(tt, ll, bb, rr); bboxFinal = bboxFinal.getOverlap(Rectangle(Point2D<int>(0, 0), img.getDims() - 1)); // scale if needed and cut out the rectangle and save it Image< PixRGB<byte> > cut = crop(img, bboxFinal); itsOfs->writeFrame(GenericFrame(cut), evnum, FrameInfo(evnum, SRC_POS)); }
// ###################################################################### // ColorBandChannel member definitions: // ###################################################################### ColorBandChannel::ColorBandChannel(OptionManager& mgr, const uint bandidx) : SingleChannel(mgr, "", "", COLBAND, rutz::make_shared(new GaussianPyrBuilder<float>(5))), itsBandIndex("ColorBandChannelIndex", this, bandidx) { itsTakeAbs.setVal(true); itsNormalizeOutput.setVal(true); setDescriptiveName(sformat("ColorBand(%d)", bandidx)); setTagName(sformat("cband_%d", bandidx)); }
Time::operator CString() const { #if defined(__BORLANDC__) && !defined(__WIN32__) // TODO: get country info under DJGPP & Win32 COUNTRY countryInfo; country(0, &countryInfo); #endif #if defined(__BORLANDC__) && !defined(__WIN32__) // TODO: get country info under DJGPP & Win32 switch (countryInfo.co_time) #else switch (0) #endif { case 1: { MTrace(("Time=%s", (const char*)sformat("%02i%s%02i", hours(), ":", minutes()))); return sformat("%02i%s%02i", hours(), ":", minutes()); } case 0: { if (hours() == 0) { MTrace(("Time=%s", (const char*)sformat("12%s%02iam", ":", minutes()))); return sformat("12%s%02iam", ":", minutes()); } if (hours() == 12) { MTrace(("Time=%s", (const char*)sformat("12%s%02ipm", ":", minutes()))); return sformat("12%s%02ipm", ":", minutes()); } if (hours() > 12) { MTrace(("Time=%s", (const char*)sformat("%02i%s%02ipm", hours()-12, ":", minutes()))); return sformat("%02i%s%02ipm", hours()-12, ":", minutes()); } if (hours() < 12) { MTrace(("Time=%s", (const char*)sformat("%02i%s%02iam", hours(), ":", minutes()))); return sformat("%02i%s%02iam", hours(), ":", minutes()); } } } return CString(); }
// ###################################################################### void MultiSpectralResidualChannel::buildSubChans() { this->removeAllSubChans(); rutz::shared_ptr<SpectralResidualChannel::Downsizer> dx0; for (size_t i = 0; i < itsResizeSpecs.size(); ++i) { nub::ref<SpectralResidualChannel> chan (new SpectralResidualChannel (this->getManager(), sformat("Spectral Residual (%s)", itsResizeSpecs[i].toString().c_str()), sformat("srs_%" ZU , i))); // make all the channels share the same downsizer if (i == 0) { dx0 = chan->getDownsizer(); ASSERT(dx0.get() != 0); } else chan->setDownsizer(dx0); this->addSubChan(chan); chan->exportOptions(MC_RECURSE); chan->setResizeSpec(itsResizeSpecs[i]); // we need all the subchannels to have the same output-resize // spec; this can happen two ways: (1) the user gives // --srs-output-resize and --srs-output-resize-spec=<foo> on the // command-line, in which case we're all set; or (2) if the user // specifies nothing then we force all the subchannels to have // an output-resize spec equivalent to chan[0]'s INPUT-resize // spec if (!itsDoOutputResize.getVal()) chan->setOutputResizeSpec(true, itsResizeSpecs[0]); LINFO("created %s with input resize %s, output blur %f, " "output resize %s", chan->descriptiveName().c_str(), chan->getResizeSpec().toString().c_str(), chan->getOutputBlur(), convertToString(chan->getOutputResizeSpec()).c_str()); } }
// ###################################################################### void EyeTrackerEyeLink::startTracking() { #ifndef HAVE_EYELINK LFATAL("Proprietary EyeLink developer API not installed"); #else // Show message at bottom of tracker display: eyecmd_printf(const_cast<char*>("record_status_message 'Recording [%d]...' "), getSession()); // set FIXUPDATE event property eyecmd_printf(const_cast<char*>("fixation_update_interval = 50")); eyecmd_printf(const_cast<char*>("fixation_update_accumulate = 50")); // Always send a TRIALID message before starting to record. It // should contain trial condition data required for analysis: eyemsg_printf(const_cast<char*>("TRIALID EYETRACK")); // TRIAL_VAR_DATA message is recorded for EyeLink Data Viewer // analysis It specifies the list of trial variables value for the // trial This must be specified within the scope of an individual // trial (i.e., after "TRIALID" and before "TRIAL_RESULT"): eyemsg_printf(const_cast<char*>("!V TRIAL_VAR_DATA EYETRACKING")); // Log eye tracker time at onset of clip: if (itsEventLog.isValid()) itsEventLog->pushEvent(sformat("Eye Tracker Time = %d", int(current_msec()))); // Actually start the recording: if (start_recording(1, 1, 1, 1)) LFATAL("Error trying to start recording"); #endif }
// ###################################################################### void SuperPixelRoadSegmenter::debugWin(Image<PixRGB<byte> >disp, std::string title) { //rutz::shared_ptr<XWinManaged> itsWin; //limit max window to 10 if(itsDebugWinCounter < 10) itsDebugWinCounter ++; std::string t = std::string(sformat("%s %d",title.c_str(),itsDebugWinCounter)); rutz::shared_ptr<XWinManaged> win; //if we don't have enough initialized window if(itsWinVec.size() < itsDebugWinCounter) { win.reset(new XWinManaged(disp.getDims(), 0, 0, t.c_str())); itsWinVec.push_back(win); } else { win.reset(new XWinManaged(disp.getDims(), 0, 0, t.c_str())); win = itsWinVec[itsDebugWinCounter-1]; } win->drawImage(disp,0,0); // for(uint ti = 0; ti < rTemplate.size(); ti++) // disp2.setVal(rTemplate[ti], 1.0F); // Raster::waitForKey(); }
/** * This function gets information text about a point at pos. * * @param pos The position (in client coordinates) to get information * about. * @param chunkText This is set to information about the chunk at this * position. * @param posText This is set to information about the given position. * @returns True if information could be obtained. */ bool ChunkWatchControl::getInfoText ( CPoint const &pos, std::string &chunkText, std::string &posText ) const { float wx, wz; if (screenToWorld(pos, &wx, &wz)) { Vector3 pos3(wx, 0.0f, wz); posText = sformat("({0}, {1})", wx, wz); Chunk *chunk = ChunkManager::instance().cameraSpace()->findChunkFromPoint(pos3); if (chunk != NULL) chunkText = chunk->identifier(); else chunkText = L("WORLDEDITOR/GUI/CONTROLS/CHUNK_WATCH_CONTROL/NOT_LOADED_STRING"); return true; } else { return false; } }
CString Time::longCString() const { #if defined(__BORLANDC__) && !defined(__WIN32__) // TODO: get country info under DJGPP & Win32 COUNTRY countryInfo; country(0, &countryInfo); #endif #if defined(__BORLANDC__) && !defined(__WIN32__) // TODO: get country info under DJGPP & Win32 switch (countryInfo.co_time) #else switch (0) #endif { case 1: return sformat("%02i%s%02i%s%02i", hours(), ":", minutes(), ":", seconds()); case 0: { if (hours() == 0) { return sformat("12%s%02i%s%02iam", ":", minutes(), ":", seconds()); } if (hours() == 12) { return sformat("12%s%02i%s%02ipm", ":", minutes(), ":", seconds()); } if (hours() > 12) { return sformat("%02i%s%02i%s%02ipm", hours()-12, ":", minutes(), ":", seconds()); } if (hours() < 12) { return sformat("%02i%s%02i%s%02iam", hours(), ":", minutes(), ":", seconds()); } } } return CString(); }
// ###################################################################### void NeoBrain::saveSpeechFile(const TokenMap& tokenMap, const std::string& fname) { rutz::shared_ptr<ParamMap> pmap(new ParamMap); int numTokenTypes = 0; for (TokenMap::const_iterator itr = tokenMap.begin(), stop = tokenMap.end(); itr != stop; ++itr) { rutz::shared_ptr<ParamMap> submap(new ParamMap); submap->putStringParam("NAME", (*itr).first); int numTokens = 0; for (size_t j = 0; j < (*itr).second.tokens.size(); ++j) { rutz::shared_ptr<ParamMap> subsubmap(new ParamMap); subsubmap->putIntParam("LOW", (*itr).second.tokens[j].low); subsubmap->putIntParam("HIGH", (*itr).second.tokens[j].high); int numTextItems = 0; for (size_t i = 0; i < (*itr).second.tokens[j].textList.size(); ++i) { subsubmap->putStringParam(sformat("TEXT_ITEM_%d", numTextItems), (*itr).second.tokens[j].textList[i]); ++numTextItems; } subsubmap->putIntParam("NUM_TEXT_ITEMS", numTextItems); submap->putSubpmap(sformat("TOKEN_%d", numTokens), subsubmap); ++numTokens; } submap->putIntParam("NUM_TOKENS", numTokens); pmap->putSubpmap(sformat("TOKEN_TYPE_%d", numTokenTypes), submap); ++numTokenTypes; } pmap->putIntParam("NUM_TOKEN_TYPES", numTokenTypes); pmap->format(fname); }
const char * srepresent(const char * string) { char * result; result = ""; for (size_t i = 0; i < strlen(string); i++) { sconcat(result, sformat("%d|", (int)string[i])); } return result; }
int command_load(int operand) { trace; int value = 0; log_debug(sformat("current_instruction %d", operand)); sc_memoryGet(operand, &value); sc_accumSet(value); return 0; }
TypeError::TypeError( const std::string& expected, dynamic::Type actual1, dynamic::Type actual2) : std::runtime_error(sformat( "TypeError: expected dynamic types `{}, but had types `{}' and `{}'", expected, dynamic::typeName(actual1), dynamic::typeName(actual2))) {}
int main(const int argc, const char** argv) { if (argc != 2) LFATAL("USAGE: %s <image.pgm>", argv[0]); // let's start by trying out a single model: it starts with our // initial conditions and we give it a steady input of 255: SurpriseModelSP m(UPDFAC, INIVAL, VARIANCE); // the model SurpriseModelSP s(UPDFAC, 255.0f, VARIANCE); // the sample for (int i = 0; i < NITER; i ++) LINFO("iter = %d, mean = %f, stdev = %f, surprise = %f", i, m.getMean(), sqrt(m.getVar()), m.surprise(s)); // get the input feature map: Image<byte> input = Raster::ReadGray(argv[1]); // convert to double: Image<double> in(input); // create sample variances: Image<double> invar(input.getDims(), NO_INIT); invar.clear(VARIANCE); // create SurpriseImage from our samples and their variances: SurpriseImage<SurpriseModelSP> sample(UPDFAC, in, invar); // create an ImageCache to accumulate our results: ImageCacheMinMax<float> cache; // create a surprise map: SurpriseMap<SurpriseModelSP> smap; smap.init(QLEN, UPDFAC, NUPDFAC, INIVAL, VARIANCE, NEIGHSIGMA, LOCSIGMA); // let's do it! for (int i = 0; i < NITER; i ++) { // get the surprise: Image<float> surp = smap.surprise(sample); float mi, ma; getMinMax(surp, mi, ma); LINFO("Done %d/%d: [%f .. %f]", i+1, NITER, mi, ma); // cache it: cache.push_back(surp); } // ok, let's save the results. First find the global max: Image<float> imax = cache.getMax(); float mi, ma; getMinMax(imax, mi, ma); LINFO("Global max is %f", ma); for (int i = 0; i < NITER; i ++) { Image<byte> sav(cache.pop_front() * 255.0f / ma); Raster::WriteGray(sav, sformat("SURP%03d%s", i, argv[1])); } return 0; }
/* static */ std::string AsyncSocketException::getMessage( AsyncSocketExceptionType type, const std::string& message, int errnoCopy) { if (errnoCopy != 0) { return sformat( "AsyncSocketException: {}, type = {}, errno = {} ({})", message, getExceptionTypeString(type), errnoCopy, errnoStr(errnoCopy)); } else { return sformat( "AsyncSocketException: {}, type = {}", message, getExceptionTypeString(type)); } }
// ###################################################################### bool BeoWebServer::initLogFile() { // get the time of day time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); char buffer [80]; strftime (buffer,80, "%Y_%m_%d__%H_%M_%S",timeinfo); std::string startTime(buffer); itsLogFolderName = std::string(sformat("%s%s", LOG_FOLDER, startTime.c_str())); LINFO("logFoldername: %s", itsLogFolderName.c_str()); // create a log directory if (mkdir(itsLogFolderName.c_str(), 0777) == -1) { LFATAL("Cannot create log folder: %s", itsLogFolderName.c_str()); return(EXIT_FAILURE); } std::string logFilename (sformat("%s/Log_%s.txt", itsLogFolderName.c_str(), startTime.c_str())); LINFO("logFilename: %s", logFilename.c_str()); std::string cTime = std::string("Time of day: ") + startTime; LINFO("%s", cTime.c_str()); cTime += std::string("\n"); // save in a file by appending to the file itsLogFilename = logFilename; FILE *rFile = fopen(itsLogFilename.c_str(), "at"); if (rFile != NULL) { LDEBUG("saving result to %s", logFilename.c_str()); fputs(cTime.c_str(), rFile); fclose (rFile); } else LFATAL("can't create file: %s", itsLogFilename.c_str()); return true; }
Error DotNetSolution::save() { bool dir_exists = DirAccess::exists(path); ERR_EXPLAIN("The directory does not exist."); ERR_FAIL_COND_V(!dir_exists, ERR_FILE_NOT_FOUND); String projs_decl; String sln_platform_cfg; String proj_platform_cfg; for (Map<String, ProjectInfo>::Element *E = projects.front(); E; E = E->next()) { const String &name = E->key(); const ProjectInfo &proj_info = E->value(); bool is_front = E == projects.front(); if (!is_front) projs_decl += "\n"; projs_decl += sformat(PROJECT_DECLARATION, name, proj_info.relpath.replace("/", "\\"), proj_info.guid); for (int i = 0; i < proj_info.configs.size(); i++) { const String &config = proj_info.configs[i]; if (i != 0 || !is_front) { sln_platform_cfg += "\n"; proj_platform_cfg += "\n"; } sln_platform_cfg += sformat(SOLUTION_PLATFORMS_CONFIG, config); proj_platform_cfg += sformat(PROJECT_PLATFORMS_CONFIG, proj_info.guid, config); } } String content = sformat(SOLUTION_TEMPLATE, projs_decl, sln_platform_cfg, proj_platform_cfg); FileAccess *file = FileAccess::open(path_join(path, name + ".sln"), FileAccess::WRITE); ERR_FAIL_NULL_V(file, ERR_FILE_CANT_WRITE); file->store_string(content); file->close(); memdelete(file); return OK; }
int printk(char* fmt, ...) { va_list ap; int i; va_start(ap, fmt); i = sformat(printk_buf, fmt, ap); tty_write(1,printk_buf, 0,i); return i; }
// ###################################################################### std::string IntegerSimpleChannel::getSubmapNameShort(const uint idx) const { GVX_TRACE(__PRETTY_FUNCTION__); ASSERT( itsLevelSpec.getVal().indexOK(idx) ); uint clev = 0, slev = 0; itsLevelSpec.getVal().indexToCS(idx, clev, slev); return sformat("%s(%d,%d)", tagName().c_str(), clev, slev); }
// ###################################################################### std::string IntegerSimpleChannel::getSubmapName(const uint idx) const { GVX_TRACE(__PRETTY_FUNCTION__); ASSERT( itsLevelSpec.getVal().indexOK(idx) ); uint clev = 0, slev = 0; itsLevelSpec.getVal().indexToCS(idx, clev, slev); return sformat("%s lev: %d delta: %d", descriptiveName().c_str(), clev, slev-clev); }
int sprintf( char* dst, const char *fmt, ... ) { va_list va; int size; va_start(va,fmt); size = sformat( dst, fmt, va ); va_end(va); return size; }
// public static IPAddress IPAddress::fromBinary(ByteRange bytes) { if (bytes.size() == 4) { return IPAddress(IPAddressV4::fromBinary(bytes)); } else if (bytes.size() == 16) { return IPAddress(IPAddressV6::fromBinary(bytes)); } else { string hexval = detail::Bytes::toHex(bytes.data(), bytes.size()); throw IPAddressFormatException( sformat("Invalid address with hex value '{}'", hexval)); } }
int command_sub(int operand) { trace; int a = 0; sc_memoryGet(operand, &a); int b = 0; sc_accumGet(&b); log_info(sformat("%d - %d = %d", b, a, b-a)); b -= a; sc_accumSet(b); return 0; }
// ###################################################################### std::string XWinManaged::describeKeyEvent(const XKeyEvent* ev) const { char buf[30]; KeySym keysym; XKeyEvent evcopy = *ev; // XLookupString() wants a non-const pointer const int len = XLookupString(&evcopy, &buf[0], sizeof(buf), &keysym, 0); const char* symname = XKeysymToString(keysym); if (symname == 0) symname = "VoidSymbol"; if (len > 1) return sformat("KeyPress code=%d sym=XK_%s (\"%s\")", ev->keycode, symname, &buf[0]); // else ... return sformat("KeyPress code=%d sym=XK_%s", ev->keycode, symname); }
void panic(char* fmt, ...) { va_list ap; int i; printk("\n\nKernel Panic: "); va_start(ap, fmt); i = sformat(printk_buf, fmt, ap); tty_write(1,printk_buf, 0,i); irq_disable(); __asm__("hlt"); }
dynamic const& dynamic::at(StringPiece idx) const& { auto* pobject = get_nothrow<ObjectImpl>(); if (!pobject) { throw_exception<TypeError>("object", type()); } auto it = pobject->find(idx); if (it == pobject->end()) { throw_exception<std::out_of_range>( sformat("couldn't find key {} in dynamic object", idx)); } return it->second; }
void CU() { trace; int tick_ignore; int current_instruction; int memory_contents; sc_instGet(¤t_instruction); log_debug(sformat("current_instruction %d", current_instruction)); sc_memoryGet(current_instruction, &memory_contents); int command; int operand; if (sc_commandDecode(memory_contents, &command, &operand)) { sc_regSet(FLAG_WRONG_COMMAND, 1); sc_regSet(FLAG_TICK_IGNORE, 1); trace; return; } ALU(command, operand); int had_overflow; sc_regGet(FLAG_OVERFLOW, &had_overflow); if (had_overflow) { trace; sc_regSet(FLAG_TICK_IGNORE, 1); return; } sc_regGet(FLAG_TICK_IGNORE, &tick_ignore); if (tick_ignore) { trace; return; } int new_instruction; sc_instGet(&new_instruction); if (new_instruction != current_instruction) { trace; return; } current_instruction++; if (current_instruction < 0 || current_instruction > 99) { trace; sc_regSet(FLAG_TICK_IGNORE, 1); return; } sc_instSet(current_instruction); }