TEST( io, local_stream ) { #ifndef WIN32 { boost::filesystem::remove( "./test.localsocket" ); boost::asio::local::stream_protocol::endpoint endpoint( "test.localsocket" ); EXPECT_TRUE( !boost::asio::local::stream_protocol::iostream( endpoint ) ); boost::asio::io_service service; boost::asio::local::stream_protocol::acceptor acceptor( service, endpoint ); EXPECT_TRUE( boost::asio::local::stream_protocol::iostream( endpoint ) ); comma::io::istream istream( "./test.localsocket" ); comma::io::ostream ostream( "./test.localsocket" ); istream.close(); ostream.close(); acceptor.close(); EXPECT_TRUE( !boost::asio::local::stream_protocol::iostream( endpoint ) ); EXPECT_TRUE( !boost::filesystem::is_regular_file( "./test.localsocket" ) ); boost::filesystem::remove( "./test.localsocket" ); } { boost::filesystem::remove( "./test.file" ); comma::io::ostream ostream( "./test.file" ); ostream.close(); boost::asio::io_service service; boost::asio::local::stream_protocol::endpoint endpoint( "test.file" ); try { boost::asio::local::stream_protocol::acceptor acceptor( service, endpoint ); EXPECT_TRUE( false ); } catch( ... ) {} boost::filesystem::remove( "./test.file" ); } #endif }
TEST( io, file_stream ) { { boost::filesystem::remove( "./test.pipe" ); boost::filesystem::remove( "./test.file" ); comma::io::ostream ostream( "./test.file" ); comma::io::istream istream( "./test.file" ); std::string line; *ostream << "hello, world" << std::endl; ostream->flush(); std::getline( *istream(), line ); EXPECT_EQ( line, "hello, world" ); ostream.close(); istream.close(); boost::filesystem::remove( "./test.file" ); } // todo: more testing? system( "mkfifo test.pipe" ); EXPECT_TRUE( boost::filesystem::exists( "./test.pipe" ) ); EXPECT_TRUE( !boost::filesystem::is_regular_file( "./test.pipe" ) ); EXPECT_TRUE( ::open( "./test.pipe", O_RDONLY | O_NONBLOCK ) > 0 ); comma::io::ostream os( "./test.pipe" ); EXPECT_TRUE( os() != NULL ); EXPECT_TRUE( os->good() ); system( "rm ./test.pipe" ); }
void KGameProcessIO::sendAllMessages(QDataStream &stream,int msgid, quint32 receiver, quint32 sender, bool usermsg) { qCDebug(GAMES_PRIVATE_KGAME) << "==============> KGameProcessIO::sendMessage (usermsg="<<usermsg<<")"; // if (!player()) return ; //if (!player()->isActive()) return ; if (usermsg) { msgid+=KGameMessage::IdUser; } qCDebug(GAMES_PRIVATE_KGAME) << "=============* ProcessIO (" << msgid << "," << receiver << "," << sender << ") ==========="; QByteArray buffer; QDataStream ostream(&buffer,QIODevice::WriteOnly); QBuffer *device=(QBuffer *)stream.device(); QByteArray data=device->buffer();; KGameMessage::createHeader(ostream,sender,receiver,msgid); // ostream.writeRawBytes(data.data()+device->at(),data.size()-device->at()); ostream.writeRawData(data.data(),data.size()); qCDebug(GAMES_PRIVATE_KGAME) << " Adding user data from pos="<< device->pos() <<" amount=" << data.size() << "byte"; //if (d->mMessageClient) d->mMessageClient->sendBroadcast(buffer); if (d->mProcessIO) { d->mProcessIO->send(buffer); } }
void output_to_files(const std::vector<map_t>& permutations, const comma::command_line_options& options ) { std::size_t count = 0; std::size_t total_count = 1; for ( std::size_t p = 0; p < permutations.size(); ++p ) { total_count = total_count * permutations[p].values.size(); } std::string prefix = options.value<std::string>("--prefix", ""); std::string dot = prefix.empty() ? "" : "."; // vector containing the current position in each input std::vector <std::size_t> index(permutations.size()); while (count < total_count) { std::string filename = prefix + dot + boost::lexical_cast<std::string>(count) + ".path-value"; std::ofstream ostream(filename.c_str()); for (std::size_t p = 0; p < permutations.size(); ++p) { ostream << permutations[p].path << "=" << permutations[p].values[index[p]] << std::endl; } ostream.close(); update_index(permutations, index); count++; } }
void SolveVCs::checkInWhy3(){ int counter = 0; for(ExprPtr e : exprs -> getExprs()){ std :: cout << "\nWhy3 VC " << counter << "\n"; //ExprPtr notE = Expression::mkNot(e); std::string errorMessage = ""; std::string fileName = "./vcs/vc" + std::to_string(counter) + ".why"; raw_fd_ostream ostream(fileName.c_str(), errorMessage); if(!errorMessage.empty()){ errs() << "Error opening file to write VCs" << "\n"; exit(1); } Why3Gen w3gen; w3gen.init(); w3gen.addToTheory(std::to_string(counter),e); w3gen.prettyprintTheory(ostream); counter++; } }
bool TransferProjectFile(wxString source, wxString target) { wxFileInputStream f_source(source); if (!f_source.Ok()) { wxLogMessage(wxT("Failed to read from %s"), source.c_str()); return false; } wxFileOutputStream f_target(target); if (!f_target.Ok()) { wxLogMessage(wxT("Failed to write to %s"), target.c_str()); return false; } wxTextInputStream istream(f_source); wxTextOutputStream ostream(f_target); for(;;) { wxString line = istream.ReadLine(); if (f_source.Eof() && line.IsEmpty()) { break; } ostream.WriteString(line + wxT("\n")); } return true; }
bool TransferSourcesFile(wxString source, wxString target) { wxFileInputStream f_source(source); if (!f_source.Ok()) { wxLogMessage(wxT("Failed to read from %s"), source.c_str()); return false; } wxFileOutputStream f_target(target); if (!f_target.Ok()) { wxLogMessage(wxT("Failed to write to %s"), target.c_str()); return false; } wxTextInputStream istream(f_source); wxTextOutputStream ostream(f_target); for(;;) { wxString line = istream.ReadLine(); wxString rest; if (f_source.Eof() && line.IsEmpty()) { break; } if (line.StartsWith(wxT("..\\..\\app\\"), &rest)) { line = rest.AfterFirst('\\'); } ostream.WriteString(line + wxT("\n")); } return true; }
/*! * \reimp */ QString UIParser::parseDisplayFile(QString filename, QMap<QString, QString> macros, bool partial) { QFile file(filename); if (!file.open(QIODevice::ReadOnly)) return ""; QXmlStreamReader reader(&file); UI displayInfo; displayInfo.parse(reader); QString qml; QTextStream ostream(&qml); if (partial) displayInfo.toPartialQML(ostream); else displayInfo.toQML(ostream); for(auto it=macros.begin(); it != macros.end(); it++) { qml.replace("$("+it.key()+")", it.value()); } return qml; }
void util::writeFile(const std::string& file, const std::string& data) { std::ofstream ostream(file, std::ios::out); ostream << data; ostream.close(); }
const std::string TypeUtil::getFormattedDescription(std::string &description) { std::string string; raw_string_ostream ostream(string); printFormattedTypeString(ostream, description, 0, description.size()); ostream.flush(); return string; }
void SolveVCs::generateSMTLib2(){ int counter = 0; SMTLib2Gen smt; smt.init(); for(ExprPtr e : exprs -> getExprs()){ std :: cout << "\nSMTLib VC " << counter; ExprPtr notE = Expression::mkNot(e); smt.encode(notE); counter++; } std::string errorMessage = ""; std::string fileName = "./vcs/vc" + std::to_string(counter) + ".smt2"; raw_fd_ostream ostream(fileName.c_str(), errorMessage); if(!errorMessage.empty()){ errs() << "Error opening file to write VCs" << "\n"; exit(1); } smt.prettyprint(ostream); }
void testXdr() { ontologydto::TypeDTO* typeDTO = new ontologydto::TypeDTO(*_typeElement); ontology::Type type(*typeDTO); ontologydto::TypeDTO* otherTypeDTO = new ontologydto::TypeDTO(*_typeElement); ontology::Type otherType(*otherTypeDTO); Instance instance(type); std::string name("Instance name."); std::string otherName("other Instance name."); instance.setName(name); iostream::XdrOutputStream ostream("testfile"); instance.encode(ostream); ostream.close(); std::map <int, void*> addressMappings; addressMappings[(int) &type] = static_cast <void*> (&type); addressMappings[(int) &otherType] = static_cast <void*> (&otherType); iostream::XdrInputStream istream("testfile"); Instance decodedInst(istream, addressMappings); istream.close(); remove("testfile"); assertTrue(decodedInst.getName() == name); assertFalse(decodedInst.getName() == otherName); assertTrue(&(decodedInst.getType()) == &type); assertFalse(&(decodedInst.getType()) == &otherType); }
bool Util::copyFile(QFile *source, QFile *target) { QStringList lines; if (source->open(IO_ReadOnly) && target->open(IO_WriteOnly)) { QTextStream istream(source); QString line; while (!istream.eof()) { line = istream.readLine(); lines += line; } source->close(); QTextStream ostream(target); for (QStringList::Iterator it = lines.begin(); it != lines.end(); ++it) { ostream << *it << "\n"; } target->close(); return true; } return false; }
/*virtual*/ U32 get_body(LLChannelDescriptors const& channels, buffer_ptr_t& buffer) { llifstream fstream(mFilename, std::ios::binary); if (!fstream.is_open()) throw AICurlNoBody(llformat("Failed to open \"%s\".", mFilename.c_str())); LLBufferStream ostream(channels, buffer.get()); char tmpbuf[4096]; #ifdef SHOW_ASSERT size_t total_len = 0; fstream.seekg(0, std::ios::end); size_t file_size = fstream.tellg(); fstream.seekg(0, std::ios::beg); #endif while (fstream) { fstream.read(tmpbuf, sizeof(tmpbuf)); std::streamsize len = fstream.gcount(); if (len > 0) { ostream.write(tmpbuf, len); #ifdef SHOW_ASSERT total_len += len; #endif } } if (fstream.bad()) throw AICurlNoBody(llformat("An error occured while reading \"%s\".", mFilename.c_str())); fstream.close(); ostream << std::flush; llassert(total_len == file_size && total_len == ostream.count_out()); return ostream.count_out(); }
void modCalcEquinox::processLines( QTextStream &istream ) { QFile fOut( OutputFileBatch->url().toLocalFile() ); fOut.open(QIODevice::WriteOnly); QTextStream ostream(&fOut); int originalYear = Year->value(); //Write header to output file ostream << i18n("# Timing of Equinoxes and Solstices\n") << i18n("# computed by KStars\n#\n") << i18n("# Vernal Equinox\t\tSummer Solstice\t\t\tAutumnal Equinox\t\tWinter Solstice\n#\n"); while ( ! istream.atEnd() ) { QString line = istream.readLine(); bool ok = false; int year = line.toInt( &ok ); //for now I will simply change the value of the Year widget to trigger //computation of the Equinoxes and Solstices. if ( ok ) { //triggers slotCompute(), which sets values of dSpring et al.: Year->setValue( year ); //Write to output file ostream << KGlobal::locale()->formatDate( dSpring.date(), KLocale::LongDate ) << "\t" << KGlobal::locale()->formatDate( dSummer.date(), KLocale::LongDate ) << "\t" << KGlobal::locale()->formatDate( dAutumn.date(), KLocale::LongDate ) << "\t" << KGlobal::locale()->formatDate( dWinter.date(), KLocale::LongDate ) << endl; } } if ( Year->value() != originalYear ) Year->setValue( originalYear ); }
int traits::run( const comma::command_line_options& options ) { comma::csv::options csv( options ); csv.full_xpath = true; bool discard_collinear = options.exists( "--discard-collinear" ); line_t first_default = comma::csv::ascii< line_t >().get( options.value< std::string >( "--first", "0,0,0,0,0,0" ) ); line_t second_default = comma::csv::ascii< line_t >().get( options.value< std::string >( "--second", "0,0,0,0,0,0" ) ); comma::csv::input_stream< lines_t > istream( std::cin, csv, std::make_pair( first_default, second_default ) ); comma::csv::output_stream < output_t > ostream( std::cout, csv.binary(), false, csv.flush ); comma::csv::tied< lines_t, output_t > tied( istream, ostream ); while( istream.ready() || ( std::cin.good() && !std::cin.eof() ) ) { const lines_t* r = istream.read(); if( !r ) { break; } const Eigen::Vector3d& f = ( r->first.second - r->first.first ).normalized(); const Eigen::Vector3d& s = ( r->second.second - r->second.first ).normalized(); if( comma::math::equal( f.dot( s ), f.norm() * s.norm() ) ) { if( discard_collinear ) { continue; } std::cerr << "points-calc: lines-nearest: got collinear lines (" << r->first.first.transpose() << " , " << r->first.second.transpose() << ") and (" << r->second.first.transpose() << " , " << r->second.second.transpose() << "), please use --discard collinear to discard" << std::endl; return 1; } const Eigen::Vector3d& m = s.cross( f ).normalized(); const Eigen::Vector3d& n = s.cross( m ).normalized(); const Eigen::Vector3d& d = r->second.first - r->first.first; const Eigen::Vector3d& a = r->first.first + f * n.dot( d ) / n.dot( f ); const Eigen::Vector3d& b = a + m * m.dot( d ); tied.append( output_t( a, b ) ); } return 0; }
/*virtual*/ U32 get_body(LLChannelDescriptors const& channels, buffer_ptr_t& buffer) { LLBufferStream ostream(channels, buffer.get()); ostream.write(mData, mSize); ostream << std::flush; // Always flush a LLBufferStream when done writing to it. return mSize; }
void modCalcDayLength::processLines( QTextStream &istream ) { QFile fOut( OutputFileBatch->url().toLocalFile() ); fOut.open(QIODevice::WriteOnly); QTextStream ostream(&fOut); //Write header ostream << "# " << i18nc("%1 is a location on earth", "Almanac for %1", geoBatch->fullName()) << QString(" [%1, %2]").arg(geoBatch->lng()->toDMSString()).arg(geoBatch->lat()->toDMSString()) << endl << "# " << i18n("computed by KStars") << endl << "#" << endl << "# Date SRise STran SSet SRiseAz STranAlt SSetAz DayLen MRise MTran MSet MRiseAz MTranAlt MSetAz LunarPhase" << endl << "#" << endl; QString line; QDate d; while ( ! istream.atEnd() ) { line = istream.readLine(); line = line.trimmed(); //Parse the line as a date, then compute Almanac values d = QDate::fromString( line ); if ( d.isValid() ) { updateAlmanac( d, geoBatch ); ostream << d.toString( Qt::ISODate ) << " " << srTimeString << " " << stTimeString << " " << ssTimeString << " " << srAzString << " " << stAltString << " " << ssAzString << " " << daylengthString << " " << mrTimeString << " " << mtTimeString << " " << msTimeString << " " << mrAzString << " " << mtAltString << " " << msAzString << " " << lunarphaseString << endl; } } }
int main( int ac, char** av ) { try { comma::command_line_options options( ac, av ); if( options.exists( "--help" ) || options.exists( "-h" ) || ac == 1 ) { usage(); } double d = boost::lexical_cast< double >( options.unnamed( "", "--binary,-b,--delimiter,-d,--fields,-f" )[0] ); int sign = d < 0 ? -1 : 1; int minutes = int( std::floor( std::abs( d )/60 ) ); int seconds = int( std::floor( std::abs( d ) - double(minutes) * 60 ) ); int microseconds = int( ( std::abs( d ) - ( double(minutes) * 60 + seconds ) ) * 1000000 ); minutes *= sign; seconds *= sign; microseconds *= sign; boost::posix_time::time_duration delay = boost::posix_time::minutes( minutes ) + boost::posix_time::seconds( seconds ) + boost::posix_time::microseconds( microseconds ); comma::csv::options csv( options ); comma::csv::input_stream< Point > istream( std::cin, csv ); comma::csv::output_stream< Point > ostream( std::cout, csv ); comma::signal_flag is_shutdown; while( !is_shutdown && std::cin.good() && !std::cin.eof() ) { const Point* p = istream.read(); if( !p ) { break; } Point q = *p; q.timestamp = p->timestamp + delay; if( csv.binary() ) { ostream.write( q, istream.binary().last() ); } else { ostream.write( q, istream.ascii().last() ); } } if( is_shutdown ) { std::cerr << "csv-time-delay: interrupted by signal" << std::endl; } return 0; } catch( std::exception& ex ) { std::cerr << "csv-time-delay: " << ex.what() << std::endl; } catch( ... ) { std::cerr << "csv-time-delay: unknown exception" << std::endl; } usage(); }
bool saveToFile(const ROSMessage& msg, const std::string& filename, bool asBinary) { std::ios_base::openmode mode; if (asBinary) mode = std::ios::out | std::ios::binary; else mode = std::ios::out; std::ofstream ofs(filename.c_str(), mode); if (!ofs.is_open()) { ROS_ERROR("File %s cannot be opened.", filename.c_str()); return false; } if (asBinary) { uint32_t serial_size = ros::serialization::serializationLength(msg); boost::shared_array<uint8_t> obuffer(new uint8_t[serial_size]); ros::serialization::OStream ostream(obuffer.get(), serial_size); ros::serialization::serialize(ostream, msg); ofs.write((char*) obuffer.get(), serial_size); } else { ofs<<msg; } ofs.close(); return true; }
void Configuration::error(std::string const& err, Location const* loc) const { std::ostream& out = ostream(Verb::ERROR); out << "ERROR: "; if (loc) out << *loc << ": "; out << err << std::endl; }
/*virtual*/ U32 get_body(LLChannelDescriptors const& channels, buffer_ptr_t& buffer) { LLBufferStream ostream(channels, buffer.get()); LLSDSerialize::toXML(mSD, ostream); // Need to flush the LLBufferStream or count_out() returns more than the written data. ostream << std::flush; return ostream.count_out(); }
TEST( io, std_stream ) { comma::io::istream istream( "-" ); comma::io::ostream ostream( "-" ); istream.close(); ostream.close(); // todo: more testing }
int main( int ac, char** av ) { try { comma::command_line_options options( ac, av, usage ); if( options.exists( "--list-ids" ) ) { std::cout << output::status::id() << "," << output::info::id() << "," << output::charge::id() << "," << output::trace::id() << std::endl; return 0; } options.assert_mutually_exclusive( "--id,--type" ); std::string output_id; std::string type = options.value< std::string >( "--type", "" ); if( !type.empty() ) { if( type == "status" ) { output_id = output::status::id(); } else if( type == "info" ) { output_id = output::info::id(); } else if( type == "charge" ) { output_id = output::charge::id(); } else if( type == "trace" ) { output_id = output::trace::id(); } else { std::cerr << "braille-to-csv: expected type, got: \"" << type << "\"" << std::endl; return 1; } } output_id = options.value< std::string >( "--id", output_id ); if( !output_id.empty() ) { if( output_id == output::status::id() ) { process< output::status, braille::packets::status >( options, output_id ); } else if ( output_id == output::info::id() ) { process< output::info, braille::packets::info >( options, output_id ); } else if ( output_id == output::charge::id() ) { process< output::charge, braille::packets::charge >( options, output_id ); } else if ( output_id == output::trace::id() ) { process< output::trace, braille::packets::trace >( options, output_id ); } else { std::cerr << "braille-to-csv: unexpected id: \"" << output_id << "\"" << std::endl; return 1; } } else { typedef snark::timestamped< accumulated_output > output_t; if( options.exists( "--list-fields,--output-fields" ) ) { std::cout << comma::join( comma::csv::names< output_t >( false ), ',' ) << std::endl; return 0; } comma::csv::options csv; csv.fields = options.value< std::string >( "--fields", "" ); csv.full_xpath = false; if( options.exists( "--format" ) ) { std::cout << comma::csv::format::value< output_t >( csv.fields, false ) << std::endl; return 0; } if( options.exists( "--binary,-b" ) ) { csv.format( comma::csv::format::value< output_t >( csv.fields, false ) ); } comma::csv::ascii_input_stream< input_t > istream( std::cin, comma::csv::options() ); comma::csv::output_stream< output_t > ostream( std::cout, csv ); output_t output; while( !is_shutdown && std::cin.good() && !std::cin.eof() ) { const input_t* input = istream.read(); if( !input ) { break; } std::string input_id = reinterpret_cast< const braille::header* >( &input->data[0] )->id(); output.t = input->t; if( input_id == output::status::id() ) { output.data.status = *reinterpret_cast< const braille::packet< braille::packets::status::size >* >( &input->data[0] ); } else if( input_id == output::info::id() ) { output.data.info = *reinterpret_cast< const braille::packet< braille::packets::info::size >* >( &input->data[0] ); } else if( input_id == output::charge::id() ) { output.data.charge = *reinterpret_cast< const braille::packet< braille::packets::charge::size >* >( &input->data[0] ); } else if( input_id == output::trace::id() ) { output.data.trace = *reinterpret_cast< const braille::packet< braille::packets::trace::size >* >( &input->data[0] ); } else { std::cerr << "braille-to-csv: expected id, got: \"" << input_id << "\"" << std::endl; return 1; } ostream.write( output ); } } return 0; } catch( std::exception& ex ) { std::cerr << "braille-to-csv: " << ex.what() << std::endl; } catch( ... ) { std::cerr << "braille-to-csv: unknown exception" << std::endl; } return 1; }
data_chunk alert_payload::to_data() const { data_chunk data; boost::iostreams::stream<byte_sink<data_chunk>> ostream(data); to_data(ostream); ostream.flush(); BITCOIN_ASSERT(data.size() == serialized_size()); return data; }
EStatus process_impl(const LLChannelDescriptors &channels, buffer_ptr_t &buffer, bool &eos, LLSD &context, LLPumpIO *pump) { LLBufferStream ostream(channels, buffer.get()); ostream.write(mData.data(), mData.size()); eos = true; return STATUS_DONE; }
data_chunk nonce_::to_data() const { data_chunk data; data_sink ostream(data); to_data(ostream); ostream.flush(); BITCOIN_ASSERT(data.size() == serialized_size()); return data; }
int tool_main(int argc, char** argv) { SkCommandLineFlags::Parse(argc, argv); for (int i = 0; i < FLAGS_skps.count(); i++) { if (SkCommandLineFlags::ShouldSkip(FLAGS_match, FLAGS_skps[i])) { continue; } SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(FLAGS_skps[i])); if (!stream) { SkDebugf("Could not read %s.\n", FLAGS_skps[i]); return 1; } sk_sp<SkPicture> src(SkPicture::MakeFromStream(stream)); if (!src) { SkDebugf("Could not read %s as an SkPicture.\n", FLAGS_skps[i]); return 1; } if (FLAGS_defer) { SkPictureRecorder recorder; SkDeferredCanvas deferred(recorder.beginRecording(src->cullRect())); src->playback(&deferred); src = recorder.finishRecordingAsPicture(); } const int w = SkScalarCeilToInt(src->cullRect().width()); const int h = SkScalarCeilToInt(src->cullRect().height()); SkRecord record; SkRecorder canvas(&record, w, h); src->playback(&canvas); if (FLAGS_optimize) { SkRecordOptimize(&record); } if (FLAGS_optimize2) { SkRecordOptimize2(&record); } dump(FLAGS_skps[i], w, h, record); if (FLAGS_write.count() > 0) { SkPictureRecorder r; SkRecordDraw(record, r.beginRecording(SkRect::MakeIWH(w, h)), nullptr, nullptr, 0, nullptr, nullptr); sk_sp<SkPicture> dst(r.finishRecordingAsPicture()); SkFILEWStream ostream(FLAGS_write[0]); dst->serialize(&ostream); } } return 0; }
/*virtual*/ U32 get_body(LLChannelDescriptors const& channels, buffer_ptr_t& buffer) { std::string data; mTree->write(data); LLBufferStream ostream(channels, buffer.get()); ostream.write(data.data(), data.size()); ostream << std::flush; // Always flush a LLBufferStream when done writing to it. return data.size(); }
data_chunk block::to_data(bool with_transaction_count) const { data_chunk data; data_sink ostream(data); to_data(ostream, with_transaction_count); ostream.flush(); BITCOIN_ASSERT(data.size() == serialized_size(with_transaction_count)); return data; }