void FileLayer::prepareFileWrite(string fileName, bool append)
	{
		// make sure any old files were closed
		m_openFile.close();
		
		if (append) { m_openFile = ofstream(fileName, ios::out | ios::app); }
		else { m_openFile = ofstream(fileName, ios::out); }
	}
Beispiel #2
0
void Config::loadConfig()
{
	try {
		std::ifstream ifstream("Config.spider");
		std::string json;

		ifstream >> json;
		if (json.empty() == true)
			return;
		_pt.clear();
		std::istringstream is(json);
		boost::property_tree::read_json(is, _pt);

		_id = _pt.get<int>("id");
		_token = _pt.get<int>("token");
		_ip = _pt.get<std::string>("ip");
	}
	catch (std::exception &e)
	{
		std::cout << "Exception boost json : " << e.what() << std::endl;
		std::ofstream ofstream("Config.spider");
		ofstream.flush();
		ofstream.close();
	}
}
DialogReaderWriter::DialogReaderWriter(string aFileName, bool isSave)
{
	if(isSave)
		m_toTxt = ofstream (aFileName);
	else
		m_Input = ifstream(aFileName);
}
Beispiel #4
0
void Assembler::writeAlignedRawProgramToDisk(string fileName){
	ofstream file = ofstream(fileName);
	if(!file.is_open()){
		return;
	}
	for(int i=0; i<alignedProgram.size(); i++){
		ProgramAtom atom = alignedProgram[i];
		DIRECTIVE type = atom.type;
		bool tokenIsSegmentName = type <= DIRECTIVE_KTEXT;
		bool tokenIsLabel = type == DIRECTIVE_LABEL;
		bool tokenIsInstruction = type == DIRECTIVE_INSTRUCTION;
		bool tokenIsStringLiteral = type == DIRECTIVE_ASCII || DIRECTIVE_ASCII; 
		if(tokenIsLabel){
			file << atom.token << ':';
			file << '\n';
			continue;
		}else if(tokenIsSegmentName){
			file << '\n';
			file << parser.getDirectiveName(type);
			file << '\n';
			file << '\n';
			continue;
		}else{
			file << parser.literals.getHexLiteralString(atom.addr);
			file << ':';
			file << '\t';
			if(!tokenIsInstruction){file << parser.getDirectiveName(type) << '\t';}
			string val = tokenIsStringLiteral? parser.literals.getStringLiteralString(atom.token) : atom.token;
			file << val;
			file << '\n';
		}
	}

	file.close();
}
Beispiel #5
0
PWIZ_API_DECL void Reader_FASTA::read(const std::string& uri, shared_ptr<istream> uriStreamPtr, ProteomeData& result) const
{
    result.id = uri;

    Serializer_FASTA::Config config;
    if (config_.indexed) // override default MemoryIndex with a BinaryIndexStream
    {
        {ofstream((uri + ".index").c_str(), ios::app);} // make sure the file exists
        shared_ptr<iostream> isPtr(new fstream((uri + ".index").c_str(), ios::in | ios::out | ios::binary));

        // indexes smaller than 200mb are loaded entirely into memory
        boost::uintmax_t indexSize = bfs::file_size(uri + ".index");
        if (indexSize > 0 && indexSize < 200000000)
        {
            stringstream* indexFileStream = new stringstream();
            bio::copy(*isPtr, *indexFileStream);
            isPtr.reset(indexFileStream);
        }

        if (!*isPtr) // stream is unavailable or read only
        {
            isPtr.reset(new fstream((uri + ".index").c_str(), ios::in | ios::binary));
            bool canOpenReadOnly = !!*isPtr;
            if (canOpenReadOnly)
            {
                // check that the index is up to date;
                // if it isn't, a read only index is worthless
                config.indexPtr.reset(new data::BinaryIndexStream(isPtr));
                Serializer_FASTA serializer(config);
                serializer.read(uriStreamPtr, result);
                if (result.proteinListPtr->size() > 0)
                    try
                    {
                        result.proteinListPtr->protein(0);
                        return;
                    }
                    catch (exception&)
                    {
                        // TODO: log warning about stale read only index
                        canOpenReadOnly = false;
                    }
            }

            // TODO: try opening an index in other locations, e.g.:
            // * current working directory (may be read only)
            // * executing directory (may be read only)
            // * temp directory (pretty much guaranteed to be writable)
            if (!canOpenReadOnly)
            {
                // fall back to in-memory index
                config.indexPtr.reset(new data::MemoryIndex);
            }
        }
        else // stream is ready and writable
            config.indexPtr.reset(new data::BinaryIndexStream(isPtr));
    }

    Serializer_FASTA serializer(config);
    serializer.read(uriStreamPtr, result);
}
Beispiel #6
0
int main (int argc, char *argv[]) {
    try
    {
        if (argc != 2)
        {
            cout << "Usage: init root" << endl;
            return -2;
        }
        else
        {
            Meta_FS fs(argv[1]);
            Config config = fs.get_config();
            for (int i = 0; i < config.blocks_num; ++i)
            {
                const string block_name = fs.get_block_path(i);
                ofstream(block_name, ios::trunc).close();
                if (truncate(block_name.c_str(), config.block_size))
                {
                    throw FSException("Can't create blocks");
                }
            }
        }
        return 0;
    }
    catch (const FSException exc)
    {
        cerr << exc.what() << endl;
        return -1;
    }
}
Beispiel #7
0
string Osu_Info::getAPIKey()
{
	string API_KEY;
	bool APIFound = false;

	/// \TODO: Add option to enter new API key
	while (!APIFound)
	{
		ifstream APIkey_in("API.key");
		if (!APIkey_in.good())
		{
			APIkey_in.close();
			#ifdef _DEBUG
				cout << "API key not found! Applying new key..."<<endl;
			#endif
			API_KEY = Osu_Info::key;

			ofstream APIKey_out = ofstream("API.key");
			APIKey_out << API_KEY;
			APIKey_out.close();
		}
		else
		{
			APIkey_in >> API_KEY;
			APIFound = true;
		}
	}

	return API_KEY;
}
Beispiel #8
0
int main()
{
	Cmix_file::enable_ft_support();
	xcc_dirs::load_from_registry();
	string dir = xcc_dirs::get_dir(game_dune2);

	Cxd2_files files;
	if (files.load(dir))
		return 1;
	file_put(xcc_dirs::get_data_dir() + "xd2 files.xif", files.save().vdata());
	shared_data exe = file_get(dir + "dune2.exe");
	if (!exe.size())
		return 1;
	const char* e = reinterpret_cast<const char*>(exe.data());
	auto bt = reinterpret_cast<const t_building_type*>(&exe[194010]);
	for (auto& i : boost::make_iterator_range(bt, bt + 19))
	{
		ofstream("../xd2 be/dune/objects/" + to_lower_copy(string(e + 229504 + i.name)) + ".ini")
			<< "cameo = " << i.cameo_shp_index << endl
			<< "class = structure" << endl
			<< "cost = " << i.cost << endl
			<< "cx = " << (i.size == 0 || i.size == 2 ? 1 : i.size == 1 || i.size == 3 || i.size == 4 ? 2 : 3) << endl
			<< "cy = " << (i.size == 0 || i.size == 1 ? 1 : i.size == 2 || i.size == 3 || i.size == 5 ? 2 : 3) << endl
			<< "icon = " << i.icon_index << endl
			<< "power = " << i.power_in << endl
			<< "sight = " << i.sight << endl
			<< "strength = " << i.strength << endl
			<< "techlevel = " << i.techlevel << endl
			<< "wsa = " << e + 229504 + i.wsa << endl
			;
	}
	auto ut = reinterpret_cast<const t_unit_type*>(&exe[195840]);
	for (auto& i : boost::make_iterator_range(ut, ut + 27))
	{
		ofstream("../xd2 be/dune/objects/" + to_lower_copy(string(e + 229504 + i.name)) + ".ini")
			<< "body = " << i.body_shp_index << endl
			<< "cameo = " << i.cameo_shp_index << endl
			<< "cost = " << i.cost << endl
			<< "sight = " << i.sight << endl
			<< "speed = " << i.speed << endl
			<< "strength = " << i.strength << endl
			<< "turret = " << i.turret_shp_index << endl
			<< "wsa = " << e + 229504 + i.wsa << endl
			;
	}
	return 0;
}
Beispiel #9
0
void World::printHeightMapToFile(string file) {
	ofstream outputfile = ofstream(file);
	for (int x = 0; x < UNIT_SIZE * MAP_X_LENGTH; ++x) {
		for (int z = 0; z < UNIT_SIZE * MAP_Z_LENGTH; ++z) {
			outputfile << "[" << x << "] [" << z << "]:" << m_heightMap[x][z] << endl;
		}
	}
}
Beispiel #10
0
void Config::saveConfig()
{
	std::ofstream ofstream("Config.spider");
	ofstream.flush();
	std::ostringstream buf;
	boost::property_tree::write_json(buf, _pt, false);
	std::string json = buf.str();
	ofstream << json;
	ofstream.close();
}
void SemanticAnalyzer::open_file(string program_name) {
	size_t npos = 0;
	#if __APPLE__
		npos = this->filedir.find_last_of('/');
	#elif _WIN32
		npos = this->filedir.find_last_of('\\');
	#endif
	string directory = filedir.substr(0, npos + 1);
	string new_path = directory + program_name + ".asm";
	this->file_writer = ofstream(new_path);
}
Beispiel #12
0
HRESULT VideoEncoder::Initialize()
{
	HRESULT hr = S_OK;

	this->m_logFileStream = ofstream(this->m_logFile);

	if (this->m_inputFile == L"")
	{
		this->m_logFileStream << "输入短影配置文件无效." << endl;
		return ERROR_FILE_INVALID;
	}

	// 初始化 COM.
	hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
	
	// COM 未被调用代码初始化. 因此我们初始化它.
	if (SUCCEEDED(hr))
	{
		this->m_logFileStream << "COM初始化成功." << endl;
		this->m_COMInitializedInDll = true;
	}

	// COM被调用代码初始化.
	else if (hr == RPC_E_CHANGED_MODE || hr == S_FALSE)
	{
		this->m_COMInitializedInDll = false;
	}

	// COM初始化失败.
	else
	{
		return hr;
	}

	// 创建WIC 工厂
	CheckHR(CoCreateInstance(
		CLSID_WICImagingFactory,
		nullptr,
		CLSCTX_INPROC_SERVER,
		IID_PPV_ARGS(&this->m_pIWICFactory)
		));

	// 启动Media Foundation.
	CheckHR(MFStartup(MF_VERSION));
		
cleanup:
	if (!SUCCEEDED(hr))
	{
		DWORD error = GetLastError();
		this->m_logFileStream << "意外错误: " << error << endl;
	}
	return hr;
}
Beispiel #13
0
	inline void testSimpleInnerFastInfoset_10()
	{

		std::ifstream ifstream("simpleInner_10.xml", std::ios::in | std::ios::binary);
		std::ofstream ofstream("sample.fis", std::ios::out | std::ios::binary);
		std::ifstream ifstream2("sample.fis", std::ios::in | std::ios::binary);
		std::ofstream ofstream2("sampleFinal.xml", std::ios::out | std::ios::binary);
		std::stringbuf xml1;
		std::stringbuf fis;
		std::stringbuf xml2;
			
		std::ostream ostxml1(&xml1);
		std::ostream ofis(&fis);
		std::istream ifis(&fis);
		std::ostream oxml2(&xml2);

		ostxml1 << ifstream.rdbuf();

		std::istream ixml1(&xml1);
		
		boost::timer::auto_cpu_timer t2;
		
		for(int i=0; i< NUMBER_OF_LOOPS; ++i){
			xml1.pubseekpos(0);
			ixml1.rdbuf(&xml1);
			fis.pubseekpos(0);
			ofis.rdbuf(&fis);
			ifis.rdbuf(&fis);
			xml2.pubseekpos(0);
			oxml2.rdbuf(&xml2);

			try
			{
				Poco::FastInfoset::Converter::convertToFIS(ixml1, ofis);

				//std::cout << "Str: " << fis.in_avail() << std::endl;
				//std::cout << "Data: \n" << fis.str() << std::endl;
				std::cout << "Strlen: " << fis.str().size() << std::endl;
				break; 

				Poco::FastInfoset::Converter::convertToXML(ifis, oxml2);

			}
			catch(Poco::Exception &ex)
			{
				std::cout << ex.what() << std::endl;
				int i = 0;
			}
		}
	}
Beispiel #14
0
void SPHSystem::init() {
    curframe = 0;

    if( params.writeLog ) {
        logstream = ofstream(params.logfile, ios::binary);
        // write initial state
        writeHeader();
        writeFrame(&pressure[0]);
    }
    
    // step once
    computeAcceleration();
    leapFrogStart();
    checkState();
}
Beispiel #15
0
inline void testSesar()
{
	boost::timer::auto_cpu_timer t1;

		std::ifstream ifstream("TrajectoryClusterPayload.xml", std::ios::in | std::ios::binary);
		std::ofstream ofstream("TrajectoryClusterPayload.fis", std::ios::out | std::ios::binary);
		std::ifstream ifstream2("TrajectoryClusterPayload.fis", std::ios::in | std::ios::binary);
		std::ofstream ofstream2("TrajectoryClusterPayloadFinal.xml", std::ios::out | std::ios::binary);
		std::stringbuf xml1;
		std::stringbuf fis;
		std::stringbuf xml2;
			
		std::ostream ostxml1(&xml1);
		std::ostream ofis(&fis);
		std::istream ifis(&fis);
		std::ostream oxml2(&xml2);

		ostxml1 << ifstream.rdbuf();

		std::istream ixml1(&xml1);
		
		boost::timer::auto_cpu_timer t2;
		
		for(int i=0; i< 1000; ++i){
			xml1.pubseekpos(0);
			ixml1.rdbuf(&xml1);
			fis.pubseekpos(0);
			ofis.rdbuf(&fis);
			ifis.rdbuf(&fis);
			xml2.pubseekpos(0);
			oxml2.rdbuf(&xml2);

			try
			{
				Poco::FastInfoset::Converter::convertToFIS(ixml1, ofis);

				//std::cout << "Str: " << fis.str().size() << std::endl;
				//break; 

				Poco::FastInfoset::Converter::convertToXML(ifis, oxml2);

			}
			catch(Poco::Exception &ex)
			{
				std::cout << ex.what() << std::endl;
			}
		}
}
Beispiel #16
0
inline void testMIPPositions()
{
	std::ifstream ifstream("xml_input_positions.xml", std::ios::in | std::ios::binary);
	std::ofstream ofstream("xml_input_positions.fis", std::ios::out | std::ios::binary);
	std::ifstream ifstream2("xml_input_positions.fis", std::ios::in | std::ios::binary);
	std::ofstream ofstream2("xml_input_positionsFinal.xml", std::ios::out | std::ios::binary);
	std::stringbuf xml1;
	std::stringbuf fis;
	std::stringbuf xml2;
			
	std::ostream ostxml1(&xml1);
	std::ostream ofis(&fis);
	std::istream ifis(&fis);
	std::ostream oxml2(&xml2);

	ostxml1 << ifstream.rdbuf();

	std::istream ixml1(&xml1);

	//boost

	for(int i=0; i< 1000; ++i){
		xml1.pubseekpos(0);
		ixml1.rdbuf(&xml1);
		fis.pubseekpos(0);
		ofis.rdbuf(&fis);
		ifis.rdbuf(&fis);
		xml2.pubseekpos(0);
		oxml2.rdbuf(&xml2);

		try
		{
			Poco::FastInfoset::Converter::convertToFIS(ixml1, ofis);

				
			Poco::FastInfoset::Converter::convertToXML(ifis, oxml2);

		}
		catch(Poco::Exception &ex)
		{
			std::cout << ex.what() << ": " << ex.message() << std::endl;
			break;
		}
	}
	std::cout << "FAST INFOSET\nMIP Data Set (with Positions)\nSerialized size: " << fis.str().size() << std::endl;
}
Beispiel #17
0
/*!
 * \brief Executes the application to be tested with the specified \a args and stores the standard output and
 *        errors in \a stdout and \a stderr.
 * \throws Throws std::runtime_error when the application can not be executed.
 * \remarks
 *  - The specified \a args must be 0 terminated. The first argument is the application name.
 *  - Currently only supported under UNIX.
 *  - \a stdout and \a stderr are cleared before.
 */
int TestApplication::execApp(const char *const *args, string &output, string &errors, bool suppressLogging, int timeout) const
{
    // increase counter used for giving profiling files unique names
    static unsigned int invocationCount = 0;
    ++invocationCount;

    // determine the path of the application to be tested
    const char *appPath = m_applicationPathArg.firstValue();
    string fallbackAppPath;
    if (!appPath || !*appPath) {
        // try to find the path by removing "_tests"-suffix from own executable path
        // (the own executable path is the path of the test application and its name is usually the name of the application
        //  to be tested with "_tests"-suffix)
        const char *const testAppPath = m_parser.executable();
        const size_t testAppPathLength = strlen(testAppPath);
        if (testAppPathLength > 6 && !strcmp(testAppPath + testAppPathLength - 6, "_tests")) {
            fallbackAppPath.assign(testAppPath, testAppPathLength - 6);
            appPath = fallbackAppPath.data();
            // TODO: it would not hurt to verify whether "fallbackAppPath" actually exists and is executalbe
        } else {
            throw runtime_error("Unable to execute application to be tested: no application path specified");
        }
    }

    // determine new path for profiling output (to not override profiling output of parent and previous invocations)
    string newProfilingPath;
    if (const char *llvmProfileFile = getenv("LLVM_PROFILE_FILE")) {
        // replace eg. "/some/path/tageditor_tests.profraw" with "/some/path/tageditor0.profraw"
        if (const char *llvmProfileFileEnd = strstr(llvmProfileFile, ".profraw")) {
            const string llvmProfileFileWithoutExtension(llvmProfileFile, llvmProfileFileEnd);
            // extract application name from path
            const char *appName = strrchr(appPath, '/');
            appName = appName ? appName + 1 : appPath;
            // concat new path
            newProfilingPath = argsToString(llvmProfileFileWithoutExtension, '_', appName, invocationCount, ".profraw");
            // append path to profiling list file
            if (const char *profrawListFile = getenv("LLVM_PROFILE_LIST_FILE")) {
                ofstream(profrawListFile, ios_base::app) << newProfilingPath << endl;
            }
        }
    }

    return execAppInternal(appPath, args, output, errors, suppressLogging, timeout, newProfilingPath);
}
int main() {
	vector<Node> nodes = { Node(-1, 0), Node(0, 0), Node(0, 1), Node(1, 0), Node(-.5, -.5) };
	vector<Curve> curves = { parabolaCurve, semiCircleCurve };
	vector<CurvilinearEdge> edges = { 
		CurvilinearEdge(.5, 1., 0), 
		CurvilinearEdge(0., .5, 1),
		CurvilinearEdge(.5, 1., 1),
		CurvilinearEdge(0., .5, 0) 
	};
	vector<Triangle> triangles = {
		Triangle(0, 1, 2, 1, -2, 2),
		Triangle(1, 3, 2, -5, 0, -1),
		Triangle(0, 4, 1, -4, 0, -3)
	};
	Triangulation K(nodes, triangles, curves, edges);
	Triangulation M(K);
	vector<double> q;
	double mean, minElement;
	ofstream quality("Mathematica/quality.dat");
	// (1) “good” mesh example
	Indicies L = { 0, 1 }; // smart hack — we will not get “bad” triangles now
	K.refine(L);
	K.save(ofstream("Mathematica/nGoodIni.dat"), ofstream("Mathematica/tGoodIni.dat"));
	K.refine(3); // refine 3 times
	K.save(ofstream("Mathematica/nGood.dat"), ofstream("Mathematica/tGood.dat"));
	// quality measures
	q = K.qualityMeasure();
	minElement = *min_element(q.begin(), q.end());
	mean = accumulate(q.begin(), q.end(), 0.) / q.size();
	quality << minElement << '\n' << mean << '\n';
	// (2) “bad” example
	M.refine();
	M.save(ofstream("Mathematica/nBadIni.dat"), ofstream("Mathematica/tBadIni.dat"));
	M.refine(3); 
	M.save(ofstream("Mathematica/nBad.dat"), ofstream("Mathematica/tBad.dat"));
	q = M.qualityMeasure();
	minElement = *min_element(q.begin(), q.end());
	mean = accumulate(q.begin(), q.end(), 0.) / q.size();
	quality << minElement << '\n' << mean;
	return 0;
}
Beispiel #19
0
int CXCCWOLIRCServerClientDlg::update_hosts(const string& ipa)
{
	int attributes = GetFileAttributes(m_hosts);
	if (attributes != -1 && attributes & FILE_ATTRIBUTE_READONLY)
		SetFileAttributes(m_hosts, attributes & ~FILE_ATTRIBUTE_READONLY);
	string b;
	ifstream f(m_hosts);
	string s;
	while (getline(f, s))
	{
		Cmulti_line l = Cmulti_line(s).get_next_line('#');
		l.get_next_line(' ');
		string a = l.get_next_line(' ');
		if (a != "irc.westwood.com"
			&& a != "servserv.westwood.com")
			b += s + '\n';
	}
	if (f.bad())
		return 1;
	if (!ipa.empty())
		b += ipa + " irc.westwood.com\n"
			+ ipa + " servserv.westwood.com\n";
	return !(ofstream(m_hosts) << b);
}
#include "stdafx.h"
#include "ChineseWordStatistic.h"
#include "common.h"
#include "COriFileOperate.h"

int32 CChineseWordStatistic::s_nCount = 0;
ofstream CChineseWordStatistic::s_ofsWordCount1 = ofstream("F:/WordCount1/TotalWord1.txt");
ofstream CChineseWordStatistic::s_ofsWordCount2 = ofstream("F:/WordCount1/TotalWord2.txt");
ofstream CChineseWordStatistic::s_ofsWordCount3 = ofstream("F:/WordCount1/TotalWord3.txt");
hash_set<string> CChineseWordStatistic::s_hsetWordCount2 = hash_set<string>();
hash_set<string> CChineseWordStatistic::s_hsetWordCount3 = hash_set<string>();
map<string, hash_set<string> > CChineseWordStatistic::s_mapWordCount2 = map<string, hash_set<string> >();
map<string, hash_set<string> > CChineseWordStatistic::s_mapWordCount3 = map<string, hash_set<string> >();
hash_map<string, ofstream*> CChineseWordStatistic::s_hmapOfstream1 = hash_map<string, ofstream*>();
hash_map<string, ofstream*> CChineseWordStatistic::s_hmapOfstream2 = hash_map<string, ofstream*>();
hash_map<string, ofstream*> CChineseWordStatistic::s_hmapOfstream3 = hash_map<string, ofstream*>();

CChineseWordStatistic::CChineseWordStatistic()
{
	m_pSplitInfo = CSplitInfo::GetInst();
	m_wordNumWithSign = 0;
	m_wordNumWithoutSign = 0;
}

CChineseWordStatistic::~CChineseWordStatistic()
{

}

FTW_RESULT CChineseWordStatistic::ChineseWordStatistic( const wchar_t* szFileName, const struct _stat *, FTW_FLAG eFlag, void* )
{
Beispiel #21
0
int
CIAO::DDS4CCM::Logger_Service::init (int argc, ACE_TCHAR * argv[])
{
  this->init ();
  this->parse_args (argc, argv);

  if (this->filename_.length () > 0)
    {
#if defined (ACE_LACKS_IOSTREAM_TOTALLY)

      FILE* output_stream = ACE_OS::fopen (this->filename_.c_str (), ACE_TEXT ("a"));

      ACE_LOG_MSG->msg_ostream (output_stream, 1);
#else /* ! ACE_LACKS_IOSTREAM_TOTALLY */
      ofstream* output_stream = 0;

      ACE_NEW_THROW_EX (output_stream,
                        ofstream (),
                        CORBA::NO_MEMORY (
                          CORBA::SystemException::_tao_minor_code (
                            0,
                            ENOMEM),
                          CORBA::COMPLETED_NO));

      output_stream->open (ACE_TEXT_ALWAYS_CHAR (this->filename_.c_str ()),
                           ios::out | ios::app);

      if (!output_stream->bad ())
        {
          ACE_LOG_MSG->msg_ostream (output_stream, 1);
        }
#endif /* ACE_LACKS_IOSTREAM_TOTALLY */

      ACE_LOG_MSG->clr_flags (ACE_Log_Msg::STDERR | ACE_Log_Msg::LOGGER);
      ACE_LOG_MSG->set_flags (ACE_Log_Msg::OSTREAM);
    }

  if (this->backend_.length () > 0)
    {

      ACE_Log_Msg_Backend* logger_be =
        ACE_Dynamic_Service<ACE_Log_Msg_Backend>::instance(this->backend_.c_str ());

      //        backend->open ("");

      if (logger_be == 0)
        {
          DDS4CCM_ERROR (DDS4CCM_LOG_LEVEL_ERROR,
                         (LM_EMERGENCY, DDS4CCM_INFO
                          "Logger_Service::init - "
                          "Unable to load backend %s\n",
                          this->backend_.c_str ()));
          return -1;
        }

      ACE_Log_Msg::msg_backend (logger_be);

      ACE_LOG_MSG->clr_flags (ACE_Log_Msg::STDERR | ACE_Log_Msg::LOGGER);
      ACE_LOG_MSG->set_flags (ACE_Log_Msg::CUSTOM);
    }

  return 0;
}
Log4cppLoggerFactory::PImpl::PImpl()
    :	appender(new log4cpp::OstreamAppender("console", &std::cout)),
      rootCategory(log4cpp::Category::getInstance("GameKeeper"))
{
    // add default appender
    log4cpp::PatternLayout * layout = new log4cpp::PatternLayout();
    layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S} [%c] %p: %m%n");
    this->appender->setLayout(layout);

    // start with DEBUG level until the file is loaded, so that we get all errors
    this->rootCategory.setPriority(log4cpp::Priority::DEBUG);
    this->rootCategory.addAppender(this->appender);

    this->rootLogger = std::make_unique<Log4cppLogger>(this->rootCategory);

    // read configuration file if exists
    bfs::path cFile = UserPaths::get().getConfigFile("log.conf");
    if(!bfs::exists(cFile))
    {
        return;
    }

    Logger& logger = this->getComponentLogger("logger");
    logger << LogLevel::Debug << "parse config file at: " << cFile.string() << endl;

    bfs::ifstream ifstream(cFile);
    bfs::path cFileGen = UserPaths::get().getConfigFile("log.conf.gen");
    bfs::remove(cFileGen);
    bfs::ofstream ofstream(cFileGen);
    std::string line;
    std::string parsedLine;

    while(!ifstream.eof())
    {
        std::getline(ifstream, line);
        // ignore empty lines
        if(line.empty())
        {
            continue;
        }

        parsedLine = parseLine(line);
        logger << LogLevel::Debug << "parsed line \"" << line << "\" to: \"" << parsedLine << "\"" << endl;
        ofstream << parsedLine << std::endl;
    }

    // ignore the file if nothing was parsed
    if(ofstream.tellp() <= 0)
    {
        return;
    }

    logger << LogLevel::Info << "moving to new configuration" << endl;

    log4cpp::PropertyConfigurator pci;
    pci.configure(cFileGen.string());
    bfs::remove(cFileGen);

    // we have another logger noew
    this->rootCategory.removeAppender(this->appender);
    this->appender = nullptr;
    this->rootLogger = std::make_unique<Log4cppLogger>(this->rootCategory);
}
Beispiel #23
0
// ----------------------------------------------------------------------------
int main( int nombreDArguments, char *arguments[ ] )
// ----------------------------------------------------------------------------
{
	char *nomDuFichierDeCorrection = "correction.txt";
	if ( nombreDArguments == 2 ) {
		nomDuFichierDeCorrection = arguments[ 1 ];
	}
	ofstream correction = ofstream( nomDuFichierDeCorrection, ios::out );
	if ( correction == 0 ) {
		cerr << "Echec de l'ouverture de \"" << nomDuFichierDeCorrection
			<< "\"" << endl;
		return 1;
	}

	char message[ 1024 ];
	double valeur;
	bool continuer = true;
	double noteMax = 0.0;
	double note = 0.0;
	unsigned int numeroDeTest = 0;

 	EntierBorne unite;


	/*
	* test des limites d'un EntierBorne implicite.
	*/
	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		if ( unite.fournirMinimum( ) != 0 ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fournirMinimum( ) d'un EntierBorne implicite devrait\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"etre 0.\n" );
			rapporter( correction, message );
		}
	}
	
	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		if ( unite.fournirMaximum( ) != 1 ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fournirMaximum( ) d'un EntierBorne implicite devrait\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"etre 1.\n" );
			rapporter( correction, message );
		}
	}

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		if ( unite.fournirValeur( ) != 0 ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fournirMaximum( ) d'un EntierBorne implicite devrait\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"etre 1.\n" );
			rapporter( correction, message );
		}
	}

	int minimum = 0;
	int maximum = 10;
 	EntierBorne indice( minimum, maximum );

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		if ( indice.fournirMinimum( ) != minimum ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fournirMinimum( ) d'un EntierBorne implicite devrait\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"etre 0.\n" );
			rapporter( correction, message );
		}
	}
	
	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		if ( indice.fournirMaximum( ) != maximum ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fournirMaximum( ) d'un EntierBorne implicite devrait\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"etre 1.\n" );
			rapporter( correction, message );
		}
	}
	
	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		if ( indice.fournirValeur( ) != minimum ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fournirMaximum( ) d'un EntierBorne implicite devrait\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"etre 1.\n" );
			rapporter( correction, message );
		}
	}

	indice.fixerAuMaximum( );
	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		if ( indice.fournirValeur( ) != maximum ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fournirMaximum( ) d'un EntierBorne implicite devrait\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"etre 1.\n" );
			rapporter( correction, message );
		}
	}

	indice.fixerAuMinimum( );
	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		if ( indice.fournirValeur( ) != minimum ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fournirMaximum( ) d'un EntierBorne implicite devrait\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"etre 1.\n" );
			rapporter( correction, message );
		}
	}

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		bool exceptionCapturee = false;
		try {
			indice.modifierValeur( maximum + 1 );
		}
		catch( EntierBorne::HorsBornes ) {
			exceptionCapturee = true;
		}
		if ( !exceptionCapturee ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) exception HorsBornes non declenchee dans\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"modifierValeur().\n" );
			rapporter( correction, message );
		}
	}

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		bool exceptionCapturee = false;
		try {
			indice.modifierValeur( minimum - 1 );
		}
		catch( EntierBorne::HorsBornes ) {
			exceptionCapturee = true;
		}
		if ( !exceptionCapturee ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) exception HorsBornes non declenchee dans\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"modifierValeur().\n" );
			rapporter( correction, message );
		}
	}

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		bool exceptionCapturee = false;
		try {
			indice.modifierValeur( maximum );
		}
		catch( EntierBorne::HorsBornes ) {
			exceptionCapturee = true;
		}
		if ( exceptionCapturee ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) exception HorsBornes declenchee pour valeur = maximum dans\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"modifierValeur().\n" );
			rapporter( correction, message );
		}
	}

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		bool exceptionCapturee = false;
		try {
			indice.modifierValeur( minimum );
		}
		catch( EntierBorne::HorsBornes ) {
			exceptionCapturee = true;
		}
		if ( exceptionCapturee ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) exception HorsBornes declenchee pour valeur = minimum dans\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"modifierValeur().\n" );
			rapporter( correction, message );
		}
	}

	IntervalleEntier intervalle( minimum, maximum );
 	EntierBorne repere( intervalle );

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		if ( repere.fournirMinimum( ) != minimum ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fournirMinimum( ) d'un EntierBorne construit sur un\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"IntervalleEntier [0..10] devrait renvoyer 0.\n" );
			rapporter( correction, message );
		}
	}

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		if ( repere.fournirMaximum( ) != maximum ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fournirMinimum( ) d'un EntierBorne construit sur un\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"IntervalleEntier [0..10] devrait renvoyer 10.\n" );
			rapporter( correction, message );
		}
	}

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		bool exceptionCapturee = false;
		try {
			repere.modifierValeur(( maximum + minimum )/2 );
		}
		catch( EntierBorne::HorsBornes ) {
			exceptionCapturee = true;
		}
		if ( exceptionCapturee ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fixer un EntierBorne au milieur de son IntervalleEntier\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"ne devrait pas declencher d'exception.\n" );
			rapporter( correction, message );
		}
	}

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		bool exceptionCapturee = false;
		try {
			repere.modifierValeur( maximum + 1 );
		}
		catch( EntierBorne::HorsBornes ) {
			exceptionCapturee = true;
		}
		if ( !exceptionCapturee ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fixer un EntierBorne au dessus de son maximum\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"devrait declencher l'exception HorsBornes.\n" );
			rapporter( correction, message );
		}
	}

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		bool exceptionCapturee = false;
		try {
			repere.modifierValeur( minimum - 1 );
		}
		catch( EntierBorne::HorsBornes ) {
			exceptionCapturee = true;
		}
		if ( !exceptionCapturee ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fixer un EntierBorne au dessous de son minimum\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"devrait declencher l'exception HorsBornes.\n" );
			rapporter( correction, message );
		}
	}

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		bool exceptionCapturee = false;
		try {
			repere.modifierValeur( minimum );
		}
		catch( EntierBorne::HorsBornes ) {
			exceptionCapturee = true;
		}
		if ( exceptionCapturee ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fixer un EntierBorne a son minimum ne devrait pas\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"declencher d'exception.\n" );
			rapporter( correction, message );
		}
	}

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		bool exceptionCapturee = false;
		try {
			repere.modifierValeur( maximum );
		}
		catch( EntierBorne::HorsBornes ) {
			exceptionCapturee = true;
		}
		if ( exceptionCapturee ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) fixer un EntierBorne a son maximum ne devrait pas\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"declencher d'exception.\n" );
			rapporter( correction, message );
		}
	}

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		bool exceptionCapturee = false;
		try {
			repere++;
		}
		catch( EntierBorne::HorsBornes ) {
			exceptionCapturee = true;
		}
		if ( !exceptionCapturee ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) decrementer un EntierBorne en dessous de son minimum devrait\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"declencher l'exception HorsBornes.\n" );
			rapporter( correction, message );
		}
	}

	int notes[ 10 ];
	EntierBorne index( 0, 10 );
	notes[ 3 ] = 3;

	numeroDeTest++;
	valeur = 10.0;
	noteMax += valeur;
	note -= valeur;
	if ( continuer ) {
		note += valeur;
		if ( notes[ 3 ] != 3 ) {
			note -= valeur;
			continuer = false;
			char *pt = message;
			sprintf( pt,
				"(%u) Un EntierBorne utiliser en indice de tableau devrait\n",
				numeroDeTest );
			sprintf( pt += strlen( pt ),
				"acceder a la cellule correspondant a sa valeur.\n" );
			rapporter( correction, message );
		}
	}

	/* ----------------------------- service --------------------------------- */
	note += noteMax;
	note = note/noteMax;
	sprintf( message, "note obtenue: %6.2lf.\n", note );
	rapporter( correction, message );
	return 0;
}
Beispiel #24
0
void DataFile::SaveData(string filename, char* &dataStruct, unsigned int dataSize){
	DataFile::fileWriter = ofstream(filename.c_str(), ofstream::binary);
	DataFile::fileWriter.write(dataStruct, dataSize);
	DataFile::fileWriter.close();
}
int
CIAO::Logger_Service::init (int argc, ACE_TCHAR * argv[])
{
    // Get prospective values from the environment first, those given on
    // command line can override
    ACE_Env_Value<int> log (ACE_TEXT("CIAO_LOG_LEVEL"), CIAO_debug_level);
    CIAO_debug_level = log;

    ACE_Env_Value<int> trace (ACE_TEXT("CIAO_TRACE_ENABLE"), 0);
    this->trace_ = (trace != 0);

    ACE_Env_Value<const ACE_TCHAR *> filename (ACE_TEXT("CIAO_LOG_FILE"), this->filename_.c_str ());
    this->filename_ = filename;

    ACE_Env_Value<const ACE_TCHAR *> backend (ACE_TEXT("CIAO_LOG_BACKEND"), this->backend_.c_str ());
    this->backend_ = backend;

    this->parse_args (argc, argv);

    if (this->trace_)
    {
        CIAO_ENABLE_TRACE ();
    }
    else
    {
        CIAO_DISABLE_TRACE ();
    }

    if (this->filename_.length () > 0)
    {
#if defined (ACE_LACKS_IOSTREAM_TOTALLY)

        FILE* output_stream = ACE_OS::fopen (this->filename_.c_str (), ACE_TEXT ("a"));

        ACE_LOG_MSG->msg_ostream (output_stream, 1);
#else /* ! ACE_LACKS_IOSTREAM_TOTALLY */
        ofstream* output_stream = 0;

        ACE_NEW_THROW_EX (output_stream,
                          ofstream (),
                          CORBA::NO_MEMORY (
                              CORBA::SystemException::_tao_minor_code (
                                  0,
                                  ENOMEM),
                              CORBA::COMPLETED_NO));

        output_stream->open (ACE_TEXT_ALWAYS_CHAR (this->filename_.c_str ()),
                             ios::out | ios::app);

        if (!output_stream->bad ())
        {
            ACE_LOG_MSG->msg_ostream (output_stream, 1);
        }
#endif /* ACE_LACKS_IOSTREAM_TOTALLY */

        ACE_LOG_MSG->clr_flags (ACE_Log_Msg::STDERR | ACE_Log_Msg::LOGGER);
        ACE_LOG_MSG->set_flags (ACE_Log_Msg::OSTREAM);
    }

    if (this->backend_.length () > 0)
    {

        ACE_Log_Msg_Backend* logger_be =
            ACE_Dynamic_Service<ACE_Log_Msg_Backend>::instance(this->backend_.c_str ());

        //        backend->open ("");

        if (logger_be == 0)
        {
            CIAO_ERROR (1,
                        (LM_EMERGENCY, CLINFO
                         "Logger_Service::init - "
                         "Unable to load backend %s\n",
                         this->backend_.c_str ()));
            return -1;
        }

        ACE_Log_Msg::msg_backend (logger_be);

        ACE_LOG_MSG->clr_flags (ACE_Log_Msg::STDERR | ACE_Log_Msg::LOGGER);
        ACE_LOG_MSG->set_flags (ACE_Log_Msg::CUSTOM);
    }

    return 0;
}
Beispiel #26
0
void writetofile(bool obj)
{
    streambuf* coutBuf = cout.rdbuf();
    
    for(int i = 0; i < MeshpolyhedraData.size(); i++)
    {
        ofstream of;
        if(obj) 
            of = ofstream("test-k-" + to_string(k) + "-" + to_string(i) + ".obj");
        else
            of = ofstream("test-k-" + to_string(k) + "-" + to_string(i) + ".tri");//for swift
        
        streambuf* fileBuf = of.rdbuf();
        cout.rdbuf(fileBuf);
        vector<CP_Vector3D> &points = MeshpolyhedraData[i];
        if(!obj)
        {
            cout << "TRI" << endl;
            cout << points.size() << endl;
            cout << MeshPolyhedronIndex.size() / 3 << endl;
        }

        for(int i = 0; i < points.size(); i++)
        {
            if(obj)
                cout << "v ";
             cout<< points[i].x << " " <<  points[i].y << " " <<  points[i].z << endl;
        }
        cout << endl;

        for(int i = 0; i < MeshPolyhedronIndex.size()/3; i++)
        {
            if(obj)
                cout << "f " << MeshPolyhedronIndex[i*3+0] + 1 << " " << MeshPolyhedronIndex[i*3+1] + 1<< " " << MeshPolyhedronIndex[i*3+2] + 1<< endl;
            else
                cout << MeshPolyhedronIndex[i*3+0] << " " << MeshPolyhedronIndex[i*3+1] << " " << MeshPolyhedronIndex[i*3+2] << endl;
        }
        of.flush();
        of.close();
    }

    bool writeoriginmodels = false;
    if(writeoriginmodels)
    {
        for(int i = 0; i< MeshPointsData.size();i++)
        {
            ofstream of("test-k-model-" + to_string(i) + ".obj");
            streambuf* fileBuf = of.rdbuf();
            cout.rdbuf(fileBuf);
            vector<CP_Vector3D> &points = MeshPointsData[i];
            for(int i = 0; i < points.size(); i++)
            {
                cout << "v ";
                cout<< points[i].x << " " <<  points[i].y << " " <<  points[i].z << endl;
            }
            cout << endl;
            for(int i = 0; i < trianges_index.size()/3; i++)
                cout << "f " << trianges_index[i*3+0] + 1 << " " << trianges_index[i*3+1] + 1<< " " << trianges_index[i*3+2] + 1<< endl;
            of.flush();
            of.close();
        }
    }
    cout.rdbuf(coutBuf);
}
int
ACE_TMAIN (int argc, ACE_TCHAR **)
{
  if (argc > 1)
    {
      // Send output to file.
#if !defined (ACE_LACKS_IOSTREAM_TOTALLY)
      ACE_NEW_RETURN (out_stream,
                      ofstream ("test_task_three.out",
                                ios::trunc|ios::out),
                      -1);
#else
      if ((out_stream = ACE_OS::fopen ("test_task_three.out", "w")) == 0)
        return -1;
#endif
      ACE_LOG_MSG->set_flags (ACE_Log_Msg::OSTREAM);
      ACE_LOG_MSG->msg_ostream (out_stream);
    }

  // Register a signal handler.
  ACE_Sig_Action sa ((ACE_SignalHandler) handler, SIGINT);
  ACE_UNUSED_ARG (sa);

  ACE_Reactor *reactor1 = ACE_Reactor::instance ();
  ACE_Reactor *reactor2 = new ACE_Reactor ();

  Test_Task t1[TASK_COUNT];
  Test_Task t2[TASK_COUNT];

  ACE_Thread::spawn (ACE_THR_FUNC (dispatch),
                     reactor2);

  reactor1->owner (ACE_OS::thr_self ());

  for (size_t index = 0; index < TASK_COUNT; index++)
    {
      t1[index].open (reactor1);
      t2[index].open (reactor2);
    }

  ACE_OS::sleep (3);

  while (done == 0)
    {
      ACE_Time_Value timeout (2);

      if (reactor1->handle_events (timeout) <= 0)
        {
          if (errno == ETIME)
            {
              ACE_DEBUG ((LM_DEBUG,
                          ACE_TEXT ("no activity within 2 seconds, shutting down\n")));
              break;
            }
          else
            ACE_ERROR ((LM_ERROR,
                        ACE_TEXT ("%p error handling events\n"),
                        ACE_TEXT ("main")));
        }
    }

  if (argc > 1)
    {
#if !defined (ACE_LACKS_IOSTREAM_TOTALLY)
      *out_stream << flush;
      delete out_stream;
#else
      ACE_OS::fflush(out_stream);
      ACE_OS::fclose(out_stream);
#endif
      ACE_LOG_MSG->clr_flags (ACE_Log_Msg::OSTREAM);
      ACE_LOG_MSG->msg_ostream (0);
    }

  // Bail out here so that we don't call the destructors for the tasks..
  ACE_OS::exit (0);
  /* NOTREACHED */

  return 0;
}
int main(int argc, char *argv[]){
	std::vector<std::string> params;
	std::map<std::string, std::vector<std::string>> options;
	std::set<std::string> flags;
	std::set<std::string> option_set = {
		"-i", "--input",
		"-o", "--output"
	};
	std::set<std::string> flag_set = {
		"-h", "--help",
		"--nocolor"
	};

	pinput::parse(argc, argv, params, options, flags, option_set, flag_set);


	const bool nocolor = flags.count("--nocolor");

	const char* ecolor = (nocolor)? "" : ansi::red;
	const char* rcolor = (nocolor)? "" : ansi::reset;

	const bool show_help = flags.count("-h") || flags.count("--help");
	if(show_help){
		help();
		return 0;
	}

	try{

		bool open_in = false;
		std::string file_name_in;
		std::vector<std::string> file_name_out;

		fill_parameters(options, file_name_in, open_in, file_name_out);
		
		std::vector<double> vector_u;
		std::vector<uint> vector_d;
		std::vector<uint> vector_n;

		size_t u_width;
		size_t d_width;
		size_t n_width;
		size_t k;

		os::benchmark_t benchmark;

		// INPUT
		std::streambuf* buffer_in;
		std::ifstream ifstream;
		if(open_in){
			ifstream.open(file_name_in);
			buffer_in = ifstream.rdbuf();
		}
		else buffer_in = std::cin.rdbuf();
		std::istream istream(buffer_in);

		os::load_benchmark(istream, benchmark, vector_u, vector_d, vector_n, u_width, d_width, n_width, k);
		if(open_in) ifstream.close();

		if(n_width > file_name_out.size()) throw lib::exception("too few output files");

		std::vector<os::benchmark_t> new_benchmark(n_width);

		for(auto& x : benchmark){
			new_benchmark[x.n].push_back(x);
		}

		for(size_t i = 0; i < n_width; ++i){
			std::ofstream ofstream(file_name_out[i]);
			os::store_benchmark(ofstream, new_benchmark[i], vector_u, vector_d, std::vector<uint>(1,vector_n[i]), u_width, d_width, 1, k);
			ofstream.close();
		}

	}
	catch(const std::exception& e){
		std::cout << ecolor << "error -> " << e.what() << rcolor << std::endl;
		return 1;
	}

	return 0;
}
Beispiel #29
0
int
ACE_Logging_Strategy::init (int argc, ACE_TCHAR *argv[])
{
  ACE_TRACE ("ACE_Logging_Strategy::init");

  // Store current priority masks for changes in <parse_args>.

  this->process_priority_mask_ =
    this->log_msg_->priority_mask (ACE_Log_Msg::PROCESS);

  this->thread_priority_mask_ =
    this->log_msg_->priority_mask (ACE_Log_Msg::THREAD);

  // Use the options hook to parse the command line arguments.
  this->parse_args (argc, argv);

  // Setup priorities (to original if not specified on command line)

  this->log_msg_->priority_mask (thread_priority_mask_,
                                 ACE_Log_Msg::THREAD);

  this->log_msg_->priority_mask (process_priority_mask_,
                                 ACE_Log_Msg::PROCESS);

  // Check if any flags were specified. If none were specified, let
  // the default behavior take effect.
  if (this->flags_ != 0)
    {
      // Clear all flags
      this->log_msg_->clr_flags (ACE_Log_Msg::STDERR
                                 | ACE_Log_Msg::LOGGER
                                 | ACE_Log_Msg::OSTREAM
                                 | ACE_Log_Msg::VERBOSE
                                 | ACE_Log_Msg::VERBOSE_LITE
                                 | ACE_Log_Msg::SILENT
                                 | ACE_Log_Msg::SYSLOG);
      // Check if OSTREAM bit is set
      if (ACE_BIT_ENABLED (this->flags_,
                           ACE_Log_Msg::OSTREAM))
        {
          int delete_ostream = 0;
#if defined (ACE_LACKS_IOSTREAM_TOTALLY)
          FILE *output_file = this->log_msg_->msg_ostream ();
          if (wipeout_logfile_)
            {
              // close and re-open a stream if such exits
              if (output_file &&
                  ACE_OS::fclose (output_file) == -1)
                return -1;
              output_file = ACE_OS::fopen (this->filename_, ACE_TEXT ("wt"));
            }
          // open a stream only if such doesn't exists
          else if (output_file == 0)
            output_file = ACE_OS::fopen (this->filename_,
                                         ACE_TEXT ("at"));

          if (output_file == 0)
            return -1;
#else
          ostream *output_file = this->log_msg_->msg_ostream ();
          // Create a new ofstream to direct output to the file.
          if (wipeout_logfile_)
            {
              ACE_NEW_RETURN
                (output_file,
                 ofstream (ACE_TEXT_ALWAYS_CHAR (this->filename_)),
                 -1);
              delete_ostream = 1;
            }
          else if (output_file == 0)
            {
              ACE_NEW_RETURN
                (output_file,
                 ofstream (ACE_TEXT_ALWAYS_CHAR (this->filename_),
                           ios::app | ios::out),
                 -1);
              delete_ostream = 1;
            }

          if (output_file->rdstate () != ios::goodbit)
            {
              if (delete_ostream)
                delete output_file;
              return -1;
            }
#endif /* ACE_LACKS_IOSTREAM_TOTALLY */
          // Set the <output_file> that'll be used by the rest of the
          // code.
          this->log_msg_->msg_ostream (output_file, delete_ostream);

          // Setup a timeout handler to perform the maximum file size
          // check (if required).
          if (this->interval_ > 0 && this->max_size_ > 0)
            {
              if (this->reactor () == 0)
                // Use singleton.
                this->reactor (ACE_Reactor::instance ());
            }
        }
      // Now set the flags for Log_Msg
      this->log_msg_->set_flags (this->flags_);
    }

  return this->log_msg_->open (this->program_name_,
                               this->log_msg_->flags (),
                               this->logger_key_);
}
Beispiel #30
0
/*!
 * \brief Constructs a TestApplication instance.
 * \throws Throws std::runtime_error if an instance has already been created.
 */
TestApplication::TestApplication(int argc, char **argv)
    : m_helpArg(m_parser)
    , m_testFilesPathArg("test-files-path", 'p', "specifies the path of the directory with test files")
    , m_applicationPathArg("app-path", 'a', "specifies the path of the application to be tested")
    , m_workingDirArg("working-dir", 'w', "specifies the directory to store working copies of test files")
    , m_unitsArg("units", 'u', "specifies the units to test; omit to test all units")
{
    // check whether there is already an instance
    if (m_instance) {
        throw runtime_error("only one TestApplication instance allowed at a time");
    }
    m_instance = this;

    // determine fallback path for testfiles which is used when --test-files-path/-p not present
    // -> read TEST_FILE_PATH environment variable
    m_fallbackTestFilesPath = readTestfilePathFromEnv();
    // -> find source directory if TEST_FILE_PATH not present
    bool fallbackIsSourceDir = m_fallbackTestFilesPath.empty();
    if (fallbackIsSourceDir) {
        m_fallbackTestFilesPath = readTestfilePathFromSrcRef();
    }

    // handle specified arguments (if present)
    if (argc && argv) {
        // setup argument parser
        for (Argument *arg : initializer_list<Argument *>{ &m_testFilesPathArg, &m_applicationPathArg, &m_workingDirArg }) {
            arg->setRequiredValueCount(1);
            arg->setValueNames({ "path" });
            arg->setCombinable(true);
        }
        m_unitsArg.setRequiredValueCount(Argument::varValueCount);
        m_unitsArg.setValueNames({ "unit1", "unit2", "unit3" });
        m_unitsArg.setCombinable(true);
        m_parser.setMainArguments({ &m_testFilesPathArg, &m_applicationPathArg, &m_workingDirArg, &m_unitsArg, &m_helpArg });

        // parse arguments
        try {
            m_parser.parseArgs(argc, argv);
        } catch (const Failure &failure) {
            cerr << failure;
            m_valid = false;
            return;
        }

        // print help
        if (m_helpArg.isPresent()) {
            exit(0);
        }
    }

    // handle path for testfiles and working-copy
    cerr << "Directories used to search for testfiles:" << endl;
    if (m_testFilesPathArg.isPresent()) {
        if (*m_testFilesPathArg.values().front()) {
            cerr << ((m_testFilesPath = m_testFilesPathArg.values().front()) += '/') << endl;
        } else {
            cerr << (m_testFilesPath = "./") << endl;
        }
    } else {
        // use fallback path if --test-files-path/-p not present
        m_testFilesPath.swap(m_fallbackTestFilesPath);
        cerr << m_testFilesPath << endl;
    }
    // if it wasn't already the case, use the source directory as fallback dir
    if (m_fallbackTestFilesPath.empty() && !fallbackIsSourceDir) {
        m_fallbackTestFilesPath = readTestfilePathFromSrcRef();
        fallbackIsSourceDir = true;
    }
    if (!m_fallbackTestFilesPath.empty() && m_testFilesPath != m_fallbackTestFilesPath) {
        cerr << m_fallbackTestFilesPath << endl;
    }
    cerr << "./testfiles/" << endl << endl;
    cerr << "Directory used to store working copies:" << endl;
    if (m_workingDirArg.isPresent()) {
        if (*m_workingDirArg.values().front()) {
            (m_workingDir = m_workingDirArg.values().front()) += '/';
        } else {
            m_workingDir = "./";
        }
    } else if (const char *workingDirEnv = getenv("WORKING_DIR")) {
        if (*workingDirEnv) {
            m_workingDir = argsToString(workingDirEnv, '/');
        }
    } else {
        if (m_testFilesPathArg.isPresent()) {
            m_workingDir = m_testFilesPath + "workingdir/";
        } else if (!m_fallbackTestFilesPath.empty() && !fallbackIsSourceDir) {
            m_workingDir = m_fallbackTestFilesPath + "workingdir/";
        } else {
            m_workingDir = "./testfiles/workingdir/";
        }
    }
    cerr << m_workingDir << endl << endl;

    // clear list of all additional profiling files created when forking the test application
    if (const char *profrawListFile = getenv("LLVM_PROFILE_LIST_FILE")) {
        ofstream(profrawListFile, ios_base::trunc);
    }

    m_valid = true;
    cerr << TextAttribute::Bold << "Executing test cases ..." << Phrases::EndFlush;
}