void CCxxExpr::EmitBinExpr(Token token, const CCxxExpr &exprRight) { std::string operation; switch (token) { case Token::OperatorAdd: operation = "+"; break; case Token::OperatorAnd: operation = "&&"; break; case Token::OperatorLess: operation = "<"; break; case Token::OperatorMul: operation = "*"; break; case Token::OperatorSub: operation = "-"; break; default: // TODO: throw exception. break; } boost::format formatter("(%1% %2% %3%)"); formatter % m_code % operation % exprRight.m_code; m_code = boost::str(formatter); }
void EntityEditor::submitChanges() { if (mRootAdapter->hasChanges()) { Atlas::Message::Element rootElement = mRootAdapter->getSelectedChangedElements(); if (rootElement.isMap()) { std::map<std::string, ::Atlas::Message::Element> attributes(rootElement.asMap()); if (attributes.size()) { std::stringstream ss; Atlas::Message::QueuedDecoder decoder; Atlas::Codecs::XML codec(ss, decoder); Atlas::Formatter formatter(ss, codec); Atlas::Message::Encoder encoder(formatter); formatter.streamBegin(); encoder.streamMessageElement(attributes); formatter.streamEnd(); S_LOG_VERBOSE("Sending attribute update to server:\n" << ss.str()); EmberServices::getSingleton().getServerService().setAttributes(mEntity, attributes); } } } }
const variant& variant::operator[](const variant& v) const { if(type_ == TYPE_CALLABLE) { assert(v.as_int() == 0); return *this; } if(type_ == TYPE_MAP) { assert(map_); std::map<variant,variant>::const_iterator i = map_->elements.find(v); if (i == map_->elements.end()) { static variant null_variant; return null_variant; } return i->second; } else if(type_ == TYPE_LIST) { return operator[](v.as_int()); } else { throw type_error((formatter() << "type error: " << " expected a list or a map but found " << variant_type_to_string(type_) << " (" << to_debug_string() << ")").str()); } }
void StackTraceStringHandler::operator()(const char8_t *name, int32_t line) { if (ignoreLibs_ && ( strlen(name) == 0 || strstr(name, "util::StackTraceUtils::getStackTrace(") == name || strstr(name, "std::") == name || strstr(name, "operator ") == name)) { return; } if (maxDepth_ > 0 && lastDepth_ >= maxDepth_) { return; } lastDepth_++; str_.tryAppend("["); str_.tryAppend(name); if (line >= 0) { str_.tryAppend(":"); detail::RawNumberFormatter formatter; str_.tryAppend(formatter(line)); } str_.tryAppend("]"); }
String imageTitle(const String& filename, const IntSize& size) { #if USE(CF) #if !defined(BUILDING_ON_LEOPARD) RetainPtr<CFStringRef> filenameCFString(AdoptCF, filename.createCFString()); RetainPtr<CFLocaleRef> locale(AdoptCF, CFLocaleCopyCurrent()); RetainPtr<CFNumberFormatterRef> formatter(AdoptCF, CFNumberFormatterCreate(0, locale.get(), kCFNumberFormatterDecimalStyle)); int widthInt = size.width(); RetainPtr<CFNumberRef> width(AdoptCF, CFNumberCreate(0, kCFNumberIntType, &widthInt)); RetainPtr<CFStringRef> widthString(AdoptCF, CFNumberFormatterCreateStringWithNumber(0, formatter.get(), width.get())); int heightInt = size.height(); RetainPtr<CFNumberRef> height(AdoptCF, CFNumberCreate(0, kCFNumberIntType, &heightInt)); RetainPtr<CFStringRef> heightString(AdoptCF, CFNumberFormatterCreateStringWithNumber(0, formatter.get(), height.get())); return formatLocalizedString(WEB_UI_STRING("%@ %@×%@ pixels", "window title for a standalone image (uses multiplication symbol, not x)"), filenameCFString.get(), widthString.get(), heightString.get()); #else RetainPtr<CFStringRef> filenameCFString(AdoptCF, filename.createCFString()); return formatLocalizedString(WEB_UI_STRING("%@ %d×%d pixels", "window title for a standalone image (uses multiplication symbol, not x)"), filenameCFString.get(), size.width(), size.height()); #endif #else return formatLocalizedString(WEB_UI_STRING("<filename> %d×%d pixels", "window title for a standalone image (uses multiplication symbol, not x)"), size.width(), size.height()).replace("<filename>", filename); #endif }
void actionQueryTime(const std::string &kindName, const std::string &filename) { const unsigned polarizationCount = MeasurementSet::GetPolarizationCount(filename); const QualityTablesFormatter::StatisticKind kind = QualityTablesFormatter::NameToKind(kindName); QualityTablesFormatter formatter(filename); StatisticsCollection collection(polarizationCount); collection.Load(formatter); const std::map<double, DefaultStatistics> &timeStats = collection.TimeStatistics(); StatisticsDerivator derivator(collection); std::cout << "TIME"; for(unsigned p=0;p<polarizationCount;++p) std::cout << '\t' << kindName << "_POL" << p << "_R\t" << kindName << "_POL" << p << "_I" ; std::cout << '\n'; for(std::map<double, DefaultStatistics>::const_iterator i=timeStats.begin();i!=timeStats.end();++i) { const double time = i->first; std::cout << time; for(unsigned p=0;p<polarizationCount;++p) { const std::complex<long double> val = derivator.GetComplexStatistic(kind, i->second, p); std::cout << '\t' << val.real() << '\t' << val.imag(); } std::cout << '\n'; } }
// // Useful references: // - http://pocoproject.org/docs/Poco.Logger.html // - http://pocoproject.org/docs/Poco.FileChannel.html // //------------------------------------------------------------------------------------ // inspired by the Poco LogRotation sample ofLogger::ofLogger(){ bConsole = true; bFile = false; bHeader = false; bDate = true; bTime = true; bFrameNum = false; bMillis = false; splitterChannel = new Poco::SplitterChannel(); consoleChannel = new Poco::ConsoleChannel(); fileChannel = new Poco::FileChannel(ofToDataPath("openframeworks.log")); // console open, file not opened (added) by default splitterChannel->addChannel(consoleChannel); Poco::AutoPtr<Poco::Formatter> formatter(new Poco::PatternFormatter("%t")); formattingChannel = new Poco::FormattingChannel(formatter, splitterChannel); // the root logger has an empty name logger = &Poco::Logger::create("", formattingChannel, (int) OF_DEFAULT_LOG_LEVEL); // setup file logger fileChannel->setProperty("times", "local"); // use local system time fileChannel->setProperty("archive", "number"); // use number suffixs fileChannel->setProperty("compress", "false"); // don't compress fileChannel->setProperty("purgeCount", "10"); // max number of log files // add default of topic addTopic("of"); }
void actionQueryGlobalStat(const std::string &kindName, const std::string &filename) { MeasurementSet *ms = new MeasurementSet(filename); const unsigned polarizationCount = ms->GetPolarizationCount(); const BandInfo band = ms->GetBandInfo(0); delete ms; const QualityTablesFormatter::StatisticKind kind = QualityTablesFormatter::NameToKind(kindName); QualityTablesFormatter formatter(filename); StatisticsCollection collection(polarizationCount); collection.Load(formatter); DefaultStatistics statistics(polarizationCount); collection.GetGlobalCrossBaselineStatistics(statistics); StatisticsDerivator derivator(collection); double start = band.channels.begin()->frequencyHz; double end = band.channels.rbegin()->frequencyHz; std::cout << round(start/10000.0)/100.0 << '\t' << round(end/10000.0)/100.0; for(unsigned p=0;p<polarizationCount;++p) { long double val = derivator.GetStatisticAmplitude(kind, statistics, p); std::cout << '\t' << val; } std::cout << '\n'; }
void actionQueryBaselines(const std::string &kindName, const std::string &filename) { MeasurementSet *ms = new MeasurementSet(filename); const unsigned polarizationCount = ms->GetPolarizationCount(); delete ms; const QualityTablesFormatter::StatisticKind kind = QualityTablesFormatter::NameToKind(kindName); QualityTablesFormatter formatter(filename); StatisticsCollection collection(polarizationCount); collection.Load(formatter); const std::vector<std::pair<unsigned, unsigned> > &baselines = collection.BaselineStatistics().BaselineList(); StatisticsDerivator derivator(collection); std::cout << "ANTENNA1\tANTENNA2"; for(unsigned p=0;p<polarizationCount;++p) std::cout << '\t' << kindName << "_POL" << p << "_R\t" << kindName << "_POL" << p << "_I" ; std::cout << '\n'; for(std::vector<std::pair<unsigned, unsigned> >::const_iterator i=baselines.begin();i!=baselines.end();++i) { const unsigned antenna1 = i->first, antenna2 = i->second; std::cout << antenna1 << '\t' << antenna2; for(unsigned p=0;p<polarizationCount;++p) { const std::complex<long double> val = derivator.GetComplexBaselineStatistic(kind, antenna1, antenna2, p); std::cout << '\t' << val.real() << '\t' << val.imag(); } std::cout << '\n'; } }
void XMLParser::WriteToFile(char** fileHeader) { char theBuffer[8192]; ResizeableStringFormatter formatter(theBuffer, 8192); // // Write the file header for (UInt32 a = 0; fileHeader[a] != NULL; a++) { formatter.Put(fileHeader[a]); formatter.Put(kEOLString); } if (fRootTag) fRootTag->FormatData(&formatter, 0); // // New libC code. This seems to work better on Win32 formatter.PutTerminator(); FILE* theFile = ::fopen(fFilePath, "w"); if (theFile == NULL) return; qtss_fprintf(theFile, "%s", formatter.GetBufPtr()); ::fclose(theFile); #if __MacOSX__ (void) ::chown(fFilePath,76,80);//owner qtss, group admin #endif #ifndef __Win32__ ::chmod(fFilePath, S_IRUSR | S_IWUSR | S_IRGRP ); #endif }
//------------------------------------------------------------ //! Read a symbol's value as a string. Value will be formatted according to designated format. VIREO_EXPORT EggShellResult EggShell_ReadValueString(TypeManagerRef tm, const TypeRef typeRef, void* pData, const char* format, UInt8** valueString) { TypeManagerScope scope(tm); if (typeRef == nullptr || !typeRef->IsValid()) return kEggShellResult_InvalidTypeRef; static StringRef returnBuffer = nullptr; if (returnBuffer == nullptr) { // Allocate a string the first time it is used. // After that it will be resized as needed. STACK_VAR(String, tempReturn); returnBuffer = tempReturn.DetachValue(); } else { returnBuffer->Resize1D(0); } if (returnBuffer) { SubString formatss(format); TDViaFormatter formatter(returnBuffer, true, 0, &formatss, kJSONEncodingEggShell); formatter.FormatData(typeRef, pData); // Add an explicit null terminator so it looks like a C string. returnBuffer->Append((Utf8Char)'\0'); *valueString = returnBuffer->Begin(); return kEggShellResult_Success; } return kEggShellResult_UnableToCreateReturnBuffer; }
/** * Function save_library * writes the library out to disk. Returns true on success. * * @param aFileName - Filename to receive the library * @param aLibrary - Library to write * @param aEditFrame - the calling SCH_EDIT_FRAME */ static bool save_library( const wxString& aFileName, PART_LIB* aLibrary, SCH_EDIT_FRAME* aEditFrame ) { try { FILE_OUTPUTFORMATTER formatter( aFileName ); if( !aLibrary->Save( formatter ) ) { wxString msg = wxString::Format( _( "An error occurred attempting to save component library '%s'." ), GetChars( aFileName ) ); DisplayError( aEditFrame, msg ); return false; } } catch( ... /* IO_ERROR ioe */ ) { wxString msg = wxString::Format( _( "Failed to create component library file '%s'" ), GetChars( aFileName ) ); DisplayError( aEditFrame, msg ); return false; } return true; }
void HelpWriterContext::writeOptionItem(const std::string &name, const std::string &value, const std::string &defaultValue, const std::string &info, const std::string &description) const { TextWriter &file = outputFile(); switch (outputFormat()) { case eHelpOutputFormat_Console: { TextTableFormatter &formatter(impl_->state_->consoleOptionsFormatter()); formatter.clear(); formatter.addColumnLine(0, name); formatter.addColumnLine(1, value); if (!defaultValue.empty()) { formatter.addColumnLine(2, "(" + defaultValue + ")"); } if (!info.empty()) { formatter.addColumnLine(3, "(" + info + ")"); } TextLineWrapperSettings settings; settings.setIndent(11); settings.setLineLength(78); std::string formattedDescription = substituteMarkupAndWrapToString(settings, description); file.writeLine(formatter.formatRow()); file.writeLine(formattedDescription); break; } case eHelpOutputFormat_Rst: { std::string args(value); if (!defaultValue.empty()) { args.append(" ("); args.append(defaultValue); args.append(")"); } if (!info.empty()) { args.append(" ("); args.append(info); args.append(")"); } file.writeLine(formatString("``%s`` %s", name.c_str(), args.c_str())); TextLineWrapperSettings settings; settings.setIndent(4); file.writeLine(substituteMarkupAndWrapToString(settings, description)); break; } default: GMX_THROW(NotImplementedError( "This output format is not implemented")); } }
variant variant::operator/(const variant& v) const { if(type_ == TYPE_DECIMAL || v.type_ == TYPE_DECIMAL) { if(v.as_decimal().value() == 0) { throw type_error((formatter() << "divide by zero error").str()); } return variant(as_decimal() / v.as_decimal()); } const int numerator = as_int(); const int denominator = v.as_int(); if(denominator == 0) { throw type_error(formatter() << "divide by zero error"); } return variant(numerator/denominator); }
virtual std::ostream& dump(std::ostream& o) const { o << get_action_name() << ": "; ceph::JSONFormatter formatter(false); formatter.open_object_section(""); m_action.dump(&formatter); formatter.close_section(); formatter.flush(o); return o; }
void tchatbox::add_chat_message(const time_t& /*time*/, const std::string& speaker, int /*side*/, const std::string& message, events::chat_handler::MESSAGE_TYPE /*type*/) { const std::string text = formatter() << "<b>" << speaker << ":</b> " << font::escape_text(message); append_to_chatbox(text); }
void report(const char* file, int line) { char buf[128]; accumulative_heap_tracing_formatter_t formatter(&(m_tracer.tracer()), buf, 128, root()); while (!formatter.atend()) { UF_TRACE_X(file, line, (buf)); formatter.increment(); } }
void variant::must_be(variant::TYPE t) const { if(type_ != t) { throw type_error((formatter() << "type error: " << " expected " << variant_type_to_string(t) << " but found " << variant_type_to_string(type_) << " (" << to_debug_string() << ")").str()); } }
static void setupLogging(const std::string & log_level) { Poco::AutoPtr<Poco::ConsoleChannel> channel(new Poco::ConsoleChannel); Poco::AutoPtr<Poco::PatternFormatter> formatter(new Poco::PatternFormatter); formatter->setProperty("pattern", "%L%Y-%m-%d %H:%M:%S.%i <%p> %s: %t"); Poco::AutoPtr<Poco::FormattingChannel> formatting_channel(new Poco::FormattingChannel(formatter, channel)); Poco::Logger::root().setChannel(formatting_channel); Poco::Logger::root().setLevel(log_level); }
inline std::string formatMessage (const std::string& message, Runtime& runtime) { RuntimeMessageFormatter formatter(runtime); formatter.process(message); std::string formattedMessage = formatter.getFormattedMessage(); formattedMessage = fixDefinesMsgBox(formattedMessage, runtime.getContext()); return formattedMessage; }
void mp_staging::update_leader_display(ng::side_engine_ptr side, grid& row_grid) { const std::string current_faction = (*side->flg().choosable_factions()[side->flg().current_faction_index()])["name"]; // BIG FAT TODO: get rid of this shitty "null" string value in the FLG manager std::string current_leader = side->flg().current_leader() != "null" ? side->flg().current_leader() : font::unicode_em_dash; const std::string current_gender = side->flg().current_gender() != "null" ? side->flg().current_gender() : font::unicode_em_dash; // Sprite std::string new_image; if(side->flg().is_random_faction() || current_leader == "random") { new_image = ng::random_enemy_picture; } if(const unit_type* ut = unit_types.find(current_leader)) { const unit_type& type = ut->get_gender_unit_type(current_gender); new_image = formatter() << type.image() << "~RC(magenta>" << side->color_id() << ")"; // We don't need the unit type id anymore, and can now replace this variable with the type name current_leader = type.type_name(); } find_widget<image>(&row_grid, "leader_image", false).set_label(new_image); // Faction and leader if(!side->cfg()["name"].empty()) { current_leader = formatter() << side->cfg()["name"] << " (<i>" << current_leader << "</i>)"; } find_widget<label>(&row_grid, "leader_type", false).set_label(current_leader); find_widget<label>(&row_grid, "leader_faction", false).set_label("<span color='#a69275'>" + current_faction + "</span>"); // Gender if(current_gender != font::unicode_em_dash) { const std::string gender_icon = formatter() << "icons/icon-" << current_gender << ".png"; image& icon = find_widget<image>(&row_grid, "leader_gender", false); icon.set_label(gender_icon); icon.set_tooltip(current_gender); } }
void tcircle::draw(surface& canvas , const game_logic::map_formula_callable& variables) { /** * @todo formulas are now recalculated every draw cycle which is a bit * silly unless there has been a resize. So to optimize we should use an * extra flag or do the calculation in a separate routine. */ const unsigned x = x_(variables); const unsigned y = y_(variables); const unsigned radius = radius_(variables); DBG_GUI_D << "Circle: drawn at " << x << ',' << y << " radius " << radius << " canvas size " << canvas->w << ',' << canvas->h << ".\n"; VALIDATE_WITH_DEV_MESSAGE( static_cast<int>(x - radius) >= 0 , _("Circle doesn't fit on canvas.") , (formatter() << "x = " << x << ", radius = " << radius).str()); VALIDATE_WITH_DEV_MESSAGE( static_cast<int>(y - radius) >= 0 , _("Circle doesn't fit on canvas.") , (formatter() << "y = " << y << ", radius = " << radius).str()); VALIDATE_WITH_DEV_MESSAGE( static_cast<int>(x + radius) < canvas->w , _("Circle doesn't fit on canvas.") , (formatter() << "x = " << x << ", radius = " << radius << "', canvas width = " << canvas->w << ".").str()); VALIDATE_WITH_DEV_MESSAGE( static_cast<int>(y + radius) < canvas->h , _("Circle doesn't fit on canvas.") , (formatter() << "y = " << y << ", radius = " << radius << "', canvas height = " << canvas->h << ".").str()); // lock the surface surface_lock locker(canvas); draw_circle(canvas, color_, x, y, radius); }
int cs_vsnprintf (char *buf, size_t len, const char *format, va_list ap) { csFmtDefaultWriter<utf8_char> writer ((utf8_char*)buf, len); csFmtDefaultReader<utf8_char> reader ((utf8_char*)format, strlen (format)); csPrintfFormatter<csFmtDefaultWriter<utf8_char>, csFmtDefaultReader<utf8_char> > formatter (&reader, ap); formatter.Format (writer); return (int)(writer.GetTotal() - 1); }
void basic_fmt::realize() { fmt_command cmd; std::ostream formatter(this->buf_); ostream_string_output output(formatter); if( process_fmt(this->fmt_, this->pos_, cmd, output) != (size_t)-1 ) throw format_exception("basic_fmt: not all arguments realized"); this->pos_ = fmt_.size(); }
variant variant::operator%(const variant& v) const { const int numerator = as_int(); const int denominator = v.as_int(); if(denominator == 0) { throw type_error((formatter() << "divide by zero error").str()); } return variant(numerator%denominator); }
void operator()(const array_t& arr) const { tab(indent); std::cout << '['; for (const auto& entry : arr.entries) { boost::apply_visitor(formatter(indent + 2), entry); std::cout << ','; } tab(indent); std::cout << ']'; }
void operator()(const object_t& obj) const { tab(indent); std::cout << '{'; for (const auto& pair : obj.pairs) { formatter(indent + 2)(pair); std::cout << ','; } tab(indent); std::cout << '}'; }
/// Replaces the first formatting placeholder with a value. /// /// \param arg The replacement string. /// /// \return A new formatter in which the first formatting placeholder has been /// replaced by arg and is ready to replace the next item. /// /// \throw utils::format::extra_args_error If there are no more formatting /// placeholders in the input string, or if the placeholder is invalid. format::formatter format::formatter::replace(const std::string& arg) const { if (_placeholder_pos == _expansion.length()) throw format::extra_args_error(_format, arg); const std::string expansion = _expansion.substr(0, _placeholder_pos) + arg + _expansion.substr(_placeholder_pos + _placeholder.length()); return formatter(_format, expansion, _placeholder_pos + arg.length()); }
void StackTraceUtils::Impl::getSymbolName( StackTraceHandler &handler, void *address) { #ifdef _WIN64 typedef DWORD64 DWORDX; #else typedef DWORD DWORDX; #endif HANDLE process = ::GetCurrentProcess(); if (!process) { handler("", -1); return; } IMAGEHLP_MODULE imageModule = { sizeof(IMAGEHLP_MODULE) }; IMAGEHLP_LINE line ={ sizeof(IMAGEHLP_LINE) }; DWORDX dispSym = 0; DWORD dispLine = 0; char symbolBuffer[sizeof(IMAGEHLP_SYMBOL) + MAX_PATH] = {0}; IMAGEHLP_SYMBOL * imageSymbol = (IMAGEHLP_SYMBOL*) symbolBuffer; imageSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL); imageSymbol->MaxNameLength = MAX_PATH; const DWORDX intAddress = static_cast<DWORDX>(reinterpret_cast<uintptr_t>(address)); if(!SymGetModuleInfo(process, intAddress, &imageModule)) { util::detail::RawNumberFormatter formatter; handler(formatter(static_cast<uint64_t>(intAddress)), -1); } else if(!SymGetSymFromAddr(process, intAddress, &dispSym, imageSymbol)) { util::detail::RawNumberFormatter formatter; handler(formatter(static_cast<uint64_t>(intAddress)), -1); } else if(!SymGetLineFromAddr(process, intAddress, &dispLine, &line)) { handler(imageSymbol->Name, -1); } else { handler(imageSymbol->Name, line.LineNumber); } }
void tchatbox::add_whisper_window_whisper(const std::string& sender, const std::string& message) { tlobby_chat_window* t = whisper_window_open(sender, false); if(!t) { ERR_LB << "Whisper window not open in add_whisper_window_whisper for " << sender << "\n"; return; } const std::string text = formatter() << "<b>" << sender << ":</b> " << font::escape_text(message); append_to_chatbox(text, t - &open_windows_[0], false); }