Exemple #1
0
void Parser::addFileToList ( const std::string &addfile, ProgramOptions &options, Map &fileList ) {
    fs::path pathToFile = fs::system_complete ( addfile );
    std::string filename = pathToFile.filename().string();
    uintmax_t fileSize = fs::file_size ( pathToFile );
    std::string filePath = pathToFile.string();
    File *file = new File ( fs::file_size ( pathToFile ), filePath, filename );

    if ( fileList.count ( filename ) ) {	//check if filename is a valid key
        innerMap &filemap = fileList[ filename ];
        if ( filemap.count ( fileSize ) ) {	//check if file_size is a valid key
            filemap[ fileSize ].push_back ( file );
        } else {	//create new vector for the Files and insert it with the file_size as the key
            boost::ptr_vector<File> *newFileList = new boost::ptr_vector<File>;
            newFileList->push_back ( file );
            filemap.insert ( innerMap::value_type ( fileSize, *newFileList ) );
        }
    } else {
        boost::ptr_vector<File> *newFileList = new boost::ptr_vector<File>;
        newFileList->push_back ( file );
        innerMap *newInnerMap = new innerMap;
        newInnerMap->insert ( innerMap::value_type ( fileSize, *newFileList ) );
        fileList.insert ( Map::value_type ( filename, *newInnerMap ) );
    }

    if ( options.getVerbose() || options.getPrintToConsoleOnly() )
        std::cout << "Added file " << filename << " (Size: " << fileSize /1024/1024 << "mb) from Directory: " << filePath << std::endl;
}
Exemple #2
0
void CaledoniaDriver(ProgramOptions& options, int& argc, char* argv[])
{
   //  Get basic MPI information
   MPI_Struct world;
   world = MPI_Struct::world();
#  ifdef USE_MPI
   MPI_Comm_rank(world.comm,&world.iproc);
   MPI_Comm_size(world.comm,&world.nproc);
#  endif
 
   bool verbose = options.get_value<bool>("verbose") && (world.iproc==0);
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Construction objects" << std::endl;

   // Construct a hamiltonian object 
   HAMILTON hamilton;
   hamilton.add_options(options);

   // Construct the sampling object
   SIMULATION simulation;
   simulation.add_options(options);

   typedef WALKER<typename HAMILTON::Config,typename HAMILTON::Observables> Walker;
   std::vector<Walker> walkerpool(1);

   // The measurement object
   // EMX_Measure measure_obj;
   MEASURE measure_obj;

   // Get parameters
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Parsing parameters" << std::endl;
   options.parse_command_line(argc,argv);
   if( options.get_value<bool>("help") ) return;

   // seed the random number geneator
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Creating random number generator" << std::endl;
   simulation.urng.seed( ParallelSeed(SeedFromClock()) );
   bool rng_output = false;
   bool rng_failed = RNGTestMoments(simulation.urng,rng_output,std::cout);
   if( false && rng_failed )
      std::cout << __FILE__ << ":" << __LINE__ << "Problem detected with random number generator (returns 1?)" << std::endl;

   // Initialize objects based on ProgramOptions
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Call Init routines" << std::endl;
   hamilton.init(verbose);
   hamilton.initial(walkerpool[0].sigma);
   simulation.init(hamilton,walkerpool,verbose);
   measure_obj.init(simulation);

   // Construct a representation of the model
   // This includes the "microscopic" configuration sigma_i
   // and the macroscopic quantities like magnetization and energy
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Beginning simulation" << std::endl;
   simulation.DoCalculate(hamilton,walkerpool,measure_obj);

   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Saving options" << std::endl;
   options.write();
}
bool CLProgram::create(const std::string& path, const ProgramOptions& compilerOptions, const std::vector<CLDevice>& devices /*= std::vector<CLDevice>()*/)
{
	std::ifstream file(path);
	if(file.fail())
	{
		std::cout << "Could not open file " << path << std::endl;
		return false;
	}
	std::vector<std::string> lines;
	while(!file.fail())
	{
		std::string line;
		std::getline(file, line);
		lines.push_back(line + "\n");
	}
	std::vector<const char*> linesChar;
	for(size_t idx = 0; idx < lines.size(); ++idx)
	{
		linesChar.push_back(lines[idx].c_str());
	}
	
	_program = ::clCreateProgramWithSource(OpenCL::get_context(), linesChar.size(), &linesChar[0], NULL, &_lastError);
	if(_lastError != CL_SUCCESS)
	{
		std::cout << "::clCreateProgramWithSource error." << std::endl;
	}
	if(_program == NULL)
		return false;

	_context = OpenCL::get_context();

	std::vector<cl_device_id> deviceIDs;
	std::for_each(devices.begin(), devices.end(), [&deviceIDs](const CLDevice& device) {
		deviceIDs.push_back(device.device);
	});

	if(deviceIDs.empty())
		_lastError = ::clBuildProgram(_program, 0, NULL, compilerOptions.c_str(), NULL, NULL);
	else
		_lastError = ::clBuildProgram(_program, deviceIDs.size(), &deviceIDs[0], compilerOptions.c_str(), NULL, NULL);

	if(_lastError != CL_SUCCESS)
	{
		std::cout << "::clBuildProgram error." << std::endl;
	}

	return _lastError == CL_SUCCESS;
}
Exemple #4
0
PopulationParams::PopulationParams(nat id, nat numberOfGenerations, popSize_t initSize, const ProgramOptions &progOpt)
    : initSize(initSize)
    , correction(1)
      // , correction(progOpt.get<nat>("ploidy") - 1 )
    , isNeutral(false)
{
    vector<string> stringEvents;
    if(progOpt.hasOption("popEvent"))
        stringEvents = progOpt.get<vector<string> >("popEvent");

    // parse rates
    recombinationRate = parseRate(progOpt.get<vector<string> >("recRate"),id);
    // geneConversionRate = parseRate(progOpt.get<vector<string> >("mutRate"), id);
    mutationRate = parseRate(progOpt.get<vector<string> >("mutRate"), id);

    if(NOT stringEvents.empty())
    {
        parseEvents(stringEvents,id);
        nat lastPopSize = initSize;

        // for(auto event : events)
        for(auto eventI = events.begin(); eventI  !=  events.end(); ++eventI)
        {
            (*eventI)->init(lastPopSize);

            if(eventI+1 != events.end())
            {
                nat whenIsNext = (*(eventI+1))->getWhen();
                lastPopSize = (*eventI)->getByTime(whenIsNext-1);
            }
        }
    }
}
Exemple #5
0
Simulation::Simulation(InfoFile &info, ProgramOptions &theProgOpt, ThreadPool &_tp)
  : progOpt(theProgOpt) 
  , numGen(progOpt.getNumberOfGenerations())
  , tp(_tp)
{

  // create chromosomes 
  Randomness &rng = tp[0].getRNG();
  vector<seqLen_t> lengths = progOpt.get<vector<seqLen_t> >("length");  
  nat idC = 0; 

  nat numPop = 1; 		// TODO pops 
  
  for(auto& length : lengths)
    {
      FitnessFunction fFun(progOpt.get<vector<string>>("selCoef"));
      Chromosome* chromo = new Chromosome(length, theProgOpt.hasOption("neutral"), fFun, idC++, numPop);
      chromo->init(rng);
      chromosomes.push_back(chromo); 
    }

  // create parameters of populations 
  vector<nat> popSizes = progOpt.get<vector<nat> >("popSize"); 
  assert(popSizes.size() == 1 );
  popParams.push_back( PopulationParams(0, numGen, popSizes[0], progOpt));  

  fractionalSimulation = new FractionalSimulation(tp,info,  progOpt, numGen, chromosomes, popParams); 
}
Exemple #6
0
Graph::Graph(nat initSize, const ProgramOptions &progOpt)
    : mutNodes(1000)
    , recNodes(1000)
    , nodMan(1000,
             progOpt.hasOption("refForCoal") ?
             progOpt.get<nat>("refForCoal") - 1
             : 0 ,
             NOT progOpt.hasOption("refForCoal"))
    , buffer(100)
#ifndef NDEBUG
    , survivorsContainStartingNode(true)
#endif
{
    previousState.resize(initSize);
    fill(previousState.begin(), previousState.end(), nullptr);
}
Exemple #7
0
bool parseOptions(int ac, char** av, ProgramOptions& options) {
    po::positional_options_description positional_options;
    po::options_description desc;

    positional_options.add("compress", 1);

    desc.add_options()
            ("help,h", "this help message")
            ("output,o", po::value<std::string>(),
                    "for compression: output file (default is 'output.arch'), for extraction: output directory (current directory by default).")
            ("extract,x", po::value<std::string>(), "extract archive")
            ("compress", po::value<std::string>(), "compress file or folder");

    std::stringstream ss;
    ss << desc;
    options.setHelpString(ss.str());

    po::variables_map vm;

    try {
        po::store(
                po::command_line_parser(ac, av).options(desc).positional(
                        positional_options).run(), vm);
        po::notify(vm);

        return setOptions(vm, options);
    } catch (std::exception & ex) {
        std::cerr << ex.what() << std::endl;
        return false;
    }

}
TEST(ProgramOptions, Reset)
{
  ProgramOptions po;
  ProgramOptions::Option& help = po.add("help");
  ProgramOptions::Option& file = po.add("file").requiresValue("FILE");
  EXPECT_FALSE(help.enabled());
  EXPECT_FALSE(file.enabled());
  EXPECT_EQ("", file.value());

  const char* argv[] = { "program.exe", "--help", "--file=readme.txt" };
  po.parse(3, argv);
  EXPECT_TRUE(help.enabled());
  EXPECT_TRUE(file.enabled());
  EXPECT_EQ("readme.txt", file.value());

  po.reset();
  EXPECT_FALSE(help.enabled());
  EXPECT_FALSE(file.enabled());
  EXPECT_EQ("", file.value());
}
TEST(ProgramOptions, OptionMembers)
{
  ProgramOptions po;
  ProgramOptions::Option& help =
    po.add("help").mnemonic('h').description("Show the help");
  ProgramOptions::Option& output =
    po.add("output").mnemonic('O').requiresValue("OUTPUT");

  EXPECT_EQ("help", help.name());
  EXPECT_EQ("Show the help", help.description());
  EXPECT_EQ('h', help.mnemonic());
  EXPECT_FALSE(help.enabled());
  EXPECT_FALSE(help.doesRequireValue());

  EXPECT_EQ("output", output.name());
  EXPECT_EQ("", output.description());
  EXPECT_EQ('O', output.mnemonic());
  EXPECT_FALSE(output.enabled());
  EXPECT_TRUE(output.doesRequireValue());
}
bool ApplicationHttpServer::parsePhase2 (ProgramOptions& options) {
  if (options.has("server.require-keep-alive")) {
    _requireKeepAlive= true;
  }

  for (vector<string>::const_iterator i = _httpPorts.begin();  i != _httpPorts.end();  ++i) {
    addPort(*i);
  }

  return true;
}
Exemple #11
0
AppOptions::AppOptions(LPCTSTR pszCommandLine)
:m_enStartMode(smInteractive),
 m_dwAttachProcessId(0)
{
   ProgramOptions opt;

   ProgramOptions::T_fnOptionHandlerNoArg fnOnParamInteractive =
      std::bind(&AppOptions::OnParamInteractive, this);
   opt.RegisterOption(_T("i"), _T("interactive"), _T("Interactive mode (default)"), fnOnParamInteractive);

   ProgramOptions::T_fnOptionHandlerSingleArg fnOnParamAttach =
      std::bind(&AppOptions::OnParamAttach, this, std::placeholders::_1);

   opt.RegisterOption(_T("a"), _T("attach"),
      _T("Attach to process with pid given in next parameter (pid may be decimal or hex, when prefixed with 0x)"),
      fnOnParamAttach);

   ProgramOptions::T_fnOptionHandlerSingleArg fnOnParamStart =
      std::bind(&AppOptions::OnParamStart, this, std::placeholders::_1);
   opt.RegisterOption(_T("s"), _T("start"),
      _T("Start application given in next parameter"),
      fnOnParamStart);

   ProgramOptions::T_fnOptionHandlerSingleArg fnOnParamCommandLine =
      std::bind(&AppOptions::OnParamCommandLine, this, std::placeholders::_1);
   opt.RegisterOption(_T("c"), _T("command"),
      _T("Uses command line parameters given in next parameter, when /s is used"),
      fnOnParamCommandLine);

   if (_tcslen(pszCommandLine) > 0)
      opt.Parse(pszCommandLine);
}
Exemple #12
0
void Parser::parseFile ( ProgramOptions &options, boost::ptr_vector<File> &fileList ) {
    std::string output = options.getFileName();
    std::ifstream stream ( output, std::ios::in );

    std::string line, path, name;
    std::uintmax_t file_size;
    if ( stream.is_open() ) {
        while ( stream.good() ) {
            std::getline ( stream, line );
            std::stringstream lineStream ( line );
            lineStream >> file_size >> path >> name;
            File *newFile = new File ( file_size, path, name );
            fileList.push_back ( newFile );
        }
    } else
Exemple #13
0
/// \retval false App should not be started
/// \retval true App can be started
bool App::ParseCommandLine()
{
   ProgramOptions options;

   options.RegisterOutputHandler(&ProgramOptions::OutputConsole);
   options.RegisterHelpOption();

   bool bStartApp = true;

   options.RegisterOption(_T("r"), _T("register-wia"), _T("registers WIA handler for RemotePhotoTool"),
      0, [&](const std::vector<CString>&)
   {
      RegisterWIAHandler(true); bStartApp = false; return true;
   });

   options.RegisterOption(_T("u"), _T("unregister-wia"), _T("unregisters WIA handler for RemotePhotoTool"),
      0, [&](const std::vector<CString>&)
   {
      RegisterWIAHandler(false); bStartApp = false; return true;
   });

   options.RegisterOption(_T("o"), _T("open-wia"), _T("opens camera using WIA handler; <arg1>: Port, <arg2>: Guid"),
      2, [&](const std::vector<CString>& vecArgs)
   {
      vecArgs;
      ATLASSERT(vecArgs.size() == 2);
      // just let the app start here
      return true;
   });

   options.Parse(GetCommandLine());

   if (!bStartApp || options.IsSelectedHelpOption())
      return false;

   return true;
}
Exemple #14
0
bool Parser::parseRecursive ( const std::string directory, ProgramOptions &options, Map &fileList ) {

    fs::path path ( fs::initial_path() );
    path = fs::system_complete ( fs::path ( directory ) ); //returns reference to the file

    if ( !fs::exists ( path ) ) {
        std::cerr << "Could not find: " << path << std::endl;
        return false;
    }

    for ( fs::recursive_directory_iterator end, dir ( options.getStartDirectory() ); dir != end; ++dir ) {
        try {
            if ( fs::is_regular_file ( dir->path().string() ) )
                addFileToList ( dir->path().string(), options, fileList );
            else
                continue;
        } catch ( std::exception const& ex ) {
            std::cerr << dir->path() << " " << ex.what() << std::endl;
        }
    }
    return true;
}
bool ApplicationHttpsServer::parsePhase2 (ProgramOptions& options) {

  // check keep alive
  if (options.has("server.secure-require-keep-alive")) {
    _requireKeepAlive= true;
  }


  // add ports
  for (vector<string>::const_iterator i = _httpsPorts.begin();  i != _httpsPorts.end();  ++i) {
    addPort(*i);
  }


  // create the ssl context (if possible)
  bool ok = createSslContext();

  if (! ok) {
    return false;
  }

  // and return
  return true;
}
Exemple #16
0
/// \retval false App should not be started
/// \retval true App can be started
bool App::ParseCommandLine()
{
   ProgramOptions options;

   options.RegisterOutputHandler(&ProgramOptions::OutputConsole);
   options.RegisterHelpOption();

   options.RegisterParameterHandler([&](const CString& cszFilename)-> bool
   {
      // only take first filename
      if (m_cszFilename.IsEmpty())
         m_cszFilename = cszFilename;
      return true;
   });

   options.Parse(GetCommandLine());

   return !options.IsSelectedHelpOption();
}
Exemple #17
0
static void ParseProgramOptions (int argc, char* argv[]) {
  string level = "info";

  ProgramOptionsDescription description("STANDARD options");

  ProgramOptionsDescription hidden("HIDDEN options");

  hidden
    ("colors", "activate color support")
    ("no-pretty-print", "disable pretty printting")          
    ("auto-complete", "enable auto completion, use no-auto-complete to disable")
  ;

  description
    ("help,h", "help message")
    ("quite,s", "no banner")
    ("log.level,l", &level,  "log level")
    ("server", &ServerAddressPort, "server address and port")
    ("startup.directory", &StartupPath, "startup paths containing the Ruby files; multiple directories can be separated by cola")
    ("startup.modules-path", &StartupModules, "one or more directories separated by cola")
    ("pager", &OutputPager, "output pager")
    ("use-pager", "use pager")
    ("pretty-print", "pretty print values")          
    ("no-colors", "deactivate color support")
    ("no-auto-complete", "disable auto completion")
    // ("unit-tests", &UnitTests, "do not start as shell, run unit tests instead")
    (hidden, true)
  ;

  ProgramOptions options;

  if (! options.parse(description, argc, argv)) {
    cerr << options.lastError() << "\n";
    exit(EXIT_FAILURE);
  }

  // check for help
  set<string> help = options.needHelp("help");

  if (! help.empty()) {
    cout << description.usage(help) << endl;
    exit(EXIT_SUCCESS);
  }

  // set the logging
  TRI_SetLogLevelLogging(level.c_str());
  TRI_CreateLogAppenderFile("-");

  // set colors
  if (options.has("colors")) {
    NoColors = false;
  }

  if (options.has("no-colors")) {
    NoColors = true;
  }

  if (options.has("auto-complete")) {
    NoAutoComplete = false;
  }

  if (options.has("no-auto-complete")) {
    NoAutoComplete = true;
  }

  if (options.has("pretty-print")) {
    PrettyPrint = true;
  }

  if (options.has("no-pretty-print")) {
    PrettyPrint = false;
  }

  if (options.has("use-pager")) {
    UsePager = true;
  }

  if (options.has("quite")) {
    Quite = true;
  }
}
TEST(ProgramOptions, ParseErrors)
{
  ProgramOptions po;
  ProgramOptions::Option& help = po.add("help").mnemonic('?');
  ProgramOptions::Option& input = po.add("input").mnemonic('i').requiresValue("INPUT");
  ProgramOptions::Option& output = po.add("output").mnemonic('o').requiresValue("OUTPUT");

  const char* argv1[] = { "program.exe", "--input" };
  EXPECT_THROW(po.parse(2, argv1), ProgramOptionNeedsValue);

  const char* argv2[] = { "program.exe", "-i" };
  EXPECT_THROW(po.parse(2, argv2), ProgramOptionNeedsValue);

  const char* argv3[] = { "program.exe", "--test" };
  EXPECT_THROW(po.parse(2, argv3), InvalidProgramOption);

  const char* argv4[] = { "program.exe", "-?a" };
  po.reset();
  EXPECT_FALSE(help.enabled());
  EXPECT_THROW(po.parse(2, argv4), InvalidProgramOption);
  EXPECT_TRUE(help.enabled());  // -? is parsed anyway, -a is the invalid option

  const char* argv5[] = { "program.exe", "-io", "input-and-output.txt" };
  po.reset();
  EXPECT_THROW(po.parse(2, argv5), ProgramOptionNeedsValue);
  po.reset();
  EXPECT_THROW(po.parse(3, argv5), InvalidProgramOptionsCombination);
  EXPECT_TRUE(input.enabled());
  EXPECT_TRUE(output.enabled());
  EXPECT_EQ("input-and-output.txt", input.value());
  EXPECT_EQ("", output.value());
}
Exemple #19
0
void ArangoClient::parse (ProgramOptions& options,
                          ProgramOptionsDescription& description,
                          int argc,
                          char* argv[],
                          string const& initFilename) {
  if (! options.parse(description, argc, argv)) {
    LOGGER_FATAL_AND_EXIT(options.lastError());
  }

  // check for help
  set<string> help = options.needHelp("help");

  if (! help.empty()) {
    cout << description.usage(help) << endl;
    TRI_EXIT_FUNCTION(EXIT_SUCCESS, NULL);
  }

  // setup the logging
  TRI_SetLogLevelLogging(_logLevel.c_str());
  TRI_CreateLogAppenderFile("-", 0, TRI_LOG_SEVERITY_UNKNOWN, false);
  TRI_SetLineNumberLogging(false);
  TRI_SetThreadIdentifierLogging(false);

  // parse config file
  string configFile = "";

  if (! _configFile.empty()) {
    if (StringUtils::tolower(_configFile) == string("none")) {
      LOGGER_DEBUG("using no init file at all");
    }
    else {
      configFile = _configFile;
    }
  }


#ifdef _SYSCONFDIR_
  else {
    // use packaged config file from etc/relative
    string sysDir = string(_SYSCONFDIR_);
    string systemConfigFile = initFilename;

    if (! sysDir.empty()) {
      if (sysDir[sysDir.size() - 1] != TRI_DIR_SEPARATOR_CHAR) {
        sysDir += TRI_DIR_SEPARATOR_CHAR + systemConfigFile;
      }
      else {
        sysDir += systemConfigFile;
      }

      if (FileUtils::exists(sysDir)) {
        configFile = sysDir;
      }
      else {
        LOGGER_DEBUG("no system init file '" << sysDir << "'");
      }
    }
  }
#endif

  if (! configFile.empty()) {
    LOGGER_DEBUG("using init file '" << configFile << "'");

    if (! options.parse(description, configFile)) {
      LOGGER_FATAL_AND_EXIT("cannot parse config file '" << configFile << "': " << options.lastError());
    }
  }

  // set temp path
  if (options.has("temp-path")) {
    TRI_SetUserTempPath((char*) _tempPath.c_str());
  }

  // check if have a password
  _hasPassword = options.has("server.password") 
              || _disableAuthentication
              || options.has("jslint") 
              || options.has("javascript.unit-tests");

  // set colors
  if (options.has("colors")) {
    _noColors = false;
  }

  if (options.has("no-colors")) {
    _noColors = true;
  }

  // set auto-completion
  if (options.has("auto-complete")) {
    _noAutoComplete = false;
  }

  if (options.has("no-auto-complete")) {
    _noAutoComplete = true;
  }

  // set pretty print
  if (options.has("pretty-print")) {
    _prettyPrint = true;
  }

  if (options.has("no-pretty-print")) {
    _prettyPrint = false;
  }

  // set pager
  if (options.has("use-pager")) {
    _usePager = true;
  }

  // set quiet
  if (options.has("quiet")) {
    _quiet = true;
  }

  // .............................................................................
  // server options
  // .............................................................................

  if (_serverOptions) {

    // check connection args
    if (_connectTimeout <= 0) {
      LOGGER_FATAL_AND_EXIT("invalid value for --server.connect-timeout, must be positive");
    }

    if (_requestTimeout <= 0) {
      LOGGER_FATAL_AND_EXIT("invalid value for --server.request-timeout, must be positive");
    }

    // must specify a user name
    if (_username.size() == 0) {
      LOGGER_FATAL_AND_EXIT("no value specified for --server.username");
    }

    // no password given on command-line
    if (! _hasPassword) {
      usleep(10 * 1000);
      printContinuous("Please specify a password: "******"");
    }
  }
}
TEST(ProgramOptions, Parse)
{
  ProgramOptions po;
  ProgramOptions::Option& help = po.add("help").mnemonic('?');
  ProgramOptions::Option& input = po.add("input").mnemonic('i').requiresValue("INPUT");
  ProgramOptions::Option& output = po.add("output").mnemonic('o').requiresValue("OUTPUT");

  const char* argv1[] = { "program.exe", "-?" };
  po.parse(2, argv1);
  EXPECT_TRUE(help.enabled());

  const char* argv2[] = { "program.exe", "--help" };
  po.reset();
  po.parse(2, argv2);
  EXPECT_TRUE(help.enabled());

  const char* argv3[] = { "program.exe", "--input", "hello.cpp", "--output", "hello.exe" };
  po.reset();
  po.parse(5, argv3);
  EXPECT_FALSE(help.enabled());
  EXPECT_TRUE(input.enabled());
  EXPECT_TRUE(output.enabled());
  EXPECT_EQ("hello.cpp", input.value());
  EXPECT_EQ("hello.exe", output.value());

  const char* argv4[] = { "program.exe", "--input=hi.c", "--output=out.exe" };
  po.reset();
  po.parse(3, argv4);
  EXPECT_FALSE(help.enabled());
  EXPECT_TRUE(input.enabled());
  EXPECT_TRUE(output.enabled());
  EXPECT_EQ("hi.c", input.value());
  EXPECT_EQ("out.exe", output.value());

  const char* argv5[] = { "program.exe", "-?i", "input.md", "-o", "output.html", "extra-file.txt" };
  po.reset();
  po.parse(6, argv5);
  EXPECT_TRUE(help.enabled());
  EXPECT_TRUE(input.enabled());
  EXPECT_TRUE(output.enabled());
  EXPECT_EQ("input.md", input.value());
  EXPECT_EQ("output.html", output.value());
  ASSERT_EQ(1, po.values().size());
  EXPECT_EQ("extra-file.txt", po.values()[0]);

  const char* argv6[] = { "program.exe", "value1", "value2", "-o", "output", "value3", "--input=input", "value4" };
  po.reset();
  po.parse(8, argv6);
  ASSERT_EQ(4, po.values().size());
  EXPECT_EQ("value1", po.values()[0]);
  EXPECT_EQ("value2", po.values()[1]);
  EXPECT_EQ("value3", po.values()[2]);
  EXPECT_EQ("value4", po.values()[3]);
}
	//--------------------------------------------------------------------------
	GBuffer::GBuffer(				unsigned int _width, 
									unsigned int _height)
	{
		// Initialize G-Buffer textures
		positionTex.Allocate(GL_RGBA32F,_width,_height);
		normalTex.Allocate(GL_RGBA16F,_width,_height);
		diffuseTex.Allocate(GL_RGBA16F,_width,_height);
		depthTex.Allocate(GL_DEPTH32F_STENCIL8,_width,_height);
		positionTex.SetWrapping(GL_CLAMP_TO_EDGE,GL_CLAMP_TO_EDGE);
		normalTex.SetWrapping(GL_CLAMP_TO_EDGE,GL_CLAMP_TO_EDGE);
		diffuseTex.SetWrapping(GL_CLAMP_TO_EDGE,GL_CLAMP_TO_EDGE);
		depthTex.SetWrapping(GL_CLAMP_TO_EDGE,GL_CLAMP_TO_EDGE);

		// Initialize framebuffer
		int outPosition			= 0;
		int outDiffuseSpecular	= 1;
		int outNormalRoughness	= 2;
		glGenFramebuffers(1, &framebuffer);
		glBindFramebuffer(GL_FRAMEBUFFER,framebuffer);

		// Attach output textures
		glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0 + outPosition, positionTex.target, positionTex.id, 0);
		glf::CheckFramebuffer(framebuffer);

		glBindTexture(diffuseTex.target,diffuseTex.id);
		glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0 + outDiffuseSpecular, diffuseTex.target, diffuseTex.id, 0);
		glf::CheckFramebuffer(framebuffer);
		
		glBindTexture(normalTex.target,normalTex.id);
		glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0 + outNormalRoughness, normalTex.target, normalTex.id, 0);
		glf::CheckFramebuffer(framebuffer);

		glBindTexture(depthTex.target,depthTex.id);
		glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_STENCIL_ATTACHMENT, depthTex.target, depthTex.id, 0);
		glf::CheckFramebuffer(framebuffer);

		GLenum drawBuffers[3] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
		glDrawBuffers(3,drawBuffers);
		assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);


		// Program regular mesh
		ProgramOptions regularOptions = ProgramOptions::CreateVSOptions();
		regularOptions.AddDefine<int>("GBUFFER",				1);
		regularOptions.AddDefine<int>("OUT_POSITION",			outPosition);
		regularOptions.AddDefine<int>("OUT_DIFFUSE_SPECULAR",	outDiffuseSpecular);
		regularOptions.AddDefine<int>("OUT_NORMAL_ROUGHNESS",	outNormalRoughness);
		regularRenderer.program.Compile(regularOptions.Append(LoadFile(directory::ShaderDirectory + "meshregular.vs")),
										regularOptions.Append(LoadFile(directory::ShaderDirectory + "meshregular.fs")));

		regularRenderer.transformVar	= regularRenderer.program["Transform"].location;
		regularRenderer.modelVar		= regularRenderer.program["Model"].location;
		regularRenderer.diffuseTexUnit	= regularRenderer.program["DiffuseTex"].unit;
		regularRenderer.normalTexUnit	= regularRenderer.program["NormalTex"].unit;
		regularRenderer.roughnessVar	= regularRenderer.program["Roughness"].location;
		regularRenderer.specularityVar	= regularRenderer.program["Specularity"].location;

		glProgramUniform1i(regularRenderer.program.id, regularRenderer.program["DiffuseTex"].location, regularRenderer.diffuseTexUnit);
		glProgramUniform1i(regularRenderer.program.id, regularRenderer.program["NormalTex"].location,  regularRenderer.normalTexUnit);


		// Program terrain mesh
		ProgramOptions terrainOptions = ProgramOptions::CreateVSOptions();
		terrainOptions.AddDefine<int>("GBUFFER",				1);
		terrainOptions.AddDefine<int>("OUT_POSITION",			outPosition);
		terrainOptions.AddDefine<int>("OUT_DIFFUSE_SPECULAR",	outDiffuseSpecular);
		terrainOptions.AddDefine<int>("OUT_NORMAL_ROUGHNESS",	outNormalRoughness);
		terrainRenderer.program.Compile(terrainOptions.Append(LoadFile(directory::ShaderDirectory + "meshterrain.vs")),
										terrainOptions.Append(LoadFile(directory::ShaderDirectory + "meshterrain.cs")),
										terrainOptions.Append(LoadFile(directory::ShaderDirectory + "meshterrain.es")),
										terrainOptions.Append(LoadFile(directory::ShaderDirectory + "meshterrain.fs")));

		terrainRenderer.transformVar	= terrainRenderer.program["Transform"].location;
		terrainRenderer.diffuseTexUnit	= terrainRenderer.program["DiffuseTex"].unit;
		terrainRenderer.normalTexUnit	= terrainRenderer.program["NormalTex"].unit;
		terrainRenderer.heightTexUnit	= terrainRenderer.program["HeightTex"].unit;
		terrainRenderer.roughnessVar	= terrainRenderer.program["Roughness"].location;
		terrainRenderer.specularityVar	= terrainRenderer.program["Specularity"].location;

		terrainRenderer.tileSizeVar		= terrainRenderer.program["TileSize"].location;
		terrainRenderer.tileCountVar	= terrainRenderer.program["TileCount"].location;
		terrainRenderer.tileOffsetVar	= terrainRenderer.program["TileOffset"].location;
		terrainRenderer.projFactorVar	= terrainRenderer.program["ProjFactor"].location;
		terrainRenderer.tessFactorVar	= terrainRenderer.program["TessFactor"].location;
		terrainRenderer.heightFactorVar	= terrainRenderer.program["HeightFactor"].location;
		terrainRenderer.tileFactorVar	= terrainRenderer.program["TileFactor"].location;

		glProgramUniform1i(terrainRenderer.program.id, terrainRenderer.program["DiffuseTex"].location, terrainRenderer.diffuseTexUnit);
		glProgramUniform1i(terrainRenderer.program.id, terrainRenderer.program["NormalTex"].location,  terrainRenderer.normalTexUnit);
		glProgramUniform1i(terrainRenderer.program.id, terrainRenderer.program["HeightTex"].location,  terrainRenderer.heightTexUnit);

		glf::CheckError("GBuffer::GBuffer");
	}
Exemple #22
0
int main(int argc, const char* argv[])
{
    ProgramOptions  opts;
    if( opts.parse(argc, argv) ) {
        return 1;
    }

    {
        Debug_DisablePhase("Load Repository");
        Debug_DisablePhase("Load Root");
        Debug_DisablePhase("Load Dependencies");
        Debug_DisablePhase("Enumerate Build");
        Debug_DisablePhase("Run Build");

        if( const char* e = getenv("MINICARGO_DEBUG") )
        {
            while( *e )
            {
                const char* colon = ::std::strchr(e, ':');
                size_t len = colon ? colon - e : ::std::strlen(e);

                Debug_EnablePhase(::std::string(e, len).c_str());

                if( colon )
                    e = colon + 1;
                else
                    e = e + len;
            }
        }
    }

    try
    {
        Debug_SetPhase("Load Repository");
        // Load package database
        Repository repo;
        // TODO: load repository from a local cache
        if( opts.vendor_dir )
        {
            repo.load_vendored(opts.vendor_dir);
        }

        auto bs_override_dir = opts.override_directory ? ::helpers::path(opts.override_directory) : ::helpers::path();

        // 1. Load the Cargo.toml file from the passed directory
        Debug_SetPhase("Load Root");
        auto dir = ::helpers::path(opts.directory ? opts.directory : ".");
        auto m = PackageManifest::load_from_toml( dir / "Cargo.toml" );

        // 2. Load all dependencies
        Debug_SetPhase("Load Dependencies");
        m.load_dependencies(repo, !bs_override_dir.is_valid());

        // 3. Build dependency tree and build program.
        BuildOptions    build_opts;
        build_opts.build_script_overrides = ::std::move(bs_override_dir);
        build_opts.output_dir = opts.output_directory ? ::helpers::path(opts.output_directory) : ::helpers::path("output");
        build_opts.lib_search_dirs.reserve(opts.lib_search_dirs.size());
        build_opts.emit_mmir = opts.emit_mmir;
        build_opts.target_name = opts.target;
        for(const auto* d : opts.lib_search_dirs)
            build_opts.lib_search_dirs.push_back( ::helpers::path(d) );
        Debug_SetPhase("Enumerate Build");
        auto build_list = BuildList(m, build_opts);
        Debug_SetPhase("Run Build");
        if( !build_list.build(::std::move(build_opts), opts.build_jobs) )
        {
            ::std::cerr << "BUILD FAILED" << ::std::endl;
            if(opts.pause_before_quit) {
                ::std::cout << "Press enter to exit..." << ::std::endl;
                ::std::cin.get();
            }
            return 1;
        }
    }
    catch(const ::std::exception& e)
    {
        ::std::cerr << "EXCEPTION: " << e.what() << ::std::endl;
        if(opts.pause_before_quit) {
            ::std::cout << "Press enter to exit..." << ::std::endl;
            ::std::cin.get();
        }
        return 1;
    }

    if(opts.pause_before_quit) {
        ::std::cout << "Press enter to exit..." << ::std::endl;
        ::std::cin.get();
    }
    return 0;
}
void ArangoClient::parse (ProgramOptions& options,
                          ProgramOptionsDescription& description, 
                          int argc,
                          char* argv[],
                          string const& initFilename) {
  if (! options.parse(description, argc, argv)) {
    cerr << options.lastError() << "\n";
    exit(EXIT_FAILURE);
  }

  // check for help
  set<string> help = options.needHelp("help");

  if (! help.empty()) {
    cout << description.usage(help) << endl;
    exit(EXIT_SUCCESS);
  }

  // setup the logging
  TRI_SetLogLevelLogging(_logLevel.c_str());
  TRI_CreateLogAppenderFile("-");
  TRI_SetLineNumberLogging(false);
  TRI_SetThreadIdentifierLogging(false);

  // parse config file
  string configFile = "";

  if (! _configFile.empty()) {
    if (StringUtils::tolower(_configFile) == string("none")) {
      LOGGER_INFO << "using no init file at all";
    }
    else {
      configFile = _configFile;
    }
  }

#ifdef _SYSCONFDIR_

  else {
    string sysDir = string(_SYSCONFDIR_);
    string systemConfigFile = initFilename;

    if (! sysDir.empty()) {
      if (sysDir[sysDir.size() - 1] != '/') {
        sysDir += "/" + systemConfigFile;
      }
      else {
        sysDir += systemConfigFile;
      }

      if (FileUtils::exists(sysDir)) {
        configFile = sysDir;
      }
      else {
        LOGGER_DEBUG << "no system init file '" << sysDir << "'";
      }
    }
  }
  
#endif

  if (! configFile.empty()) {
    LOGGER_DEBUG << "using init file '" << configFile << "'";

    if (! options.parse(description, configFile)) {
      cout << "cannot parse config file '" << configFile << "': " << options.lastError() << endl;
      exit(EXIT_FAILURE);
    }
  }

  // check if have a password
  _hasPassword = options.has("server.password") || options.has("server.disable-authentication");

  // set colors
  if (options.has("colors")) {
    _noColors = false;
  }

  if (options.has("no-colors")) {
    _noColors = true;
  }

  // set auto-completion
  if (options.has("auto-complete")) {
    _noAutoComplete = false;
  }

  if (options.has("no-auto-complete")) {
    _noAutoComplete = true;
  }

  // set pretty print
  if (options.has("pretty-print")) {
    _prettyPrint = true;
  }

  if (options.has("no-pretty-print")) {
    _prettyPrint = false;
  }

  // set pager
  if (options.has("use-pager")) {
    _usePager = true;
  }

  // set quiet
  if (options.has("quiet")) {
    _quiet = true;
  }

  // .............................................................................
  // server options
  // .............................................................................

  if (_serverOptions) {

    // check connection args
    if (_connectTimeout <= 0) {
      cerr << "invalid value for --server.connect-timeout, must be positive" << endl;
      exit(EXIT_FAILURE);
    }

    if (_requestTimeout <= 0) {
      cerr << "invalid value for --server.request-timeout, must be positive" << endl;
      exit(EXIT_FAILURE);
    }
  
    // must specify a user name
    if (_username.size() == 0) {
      cerr << "no value specified for --server.username" << endl;
      exit(EXIT_FAILURE);
    }

    // no password given on command-line
    if (! _hasPassword) {
      cout << "Please specify a password: " << flush;

      // now prompt for it
#ifdef TRI_HAVE_TERMIOS_H
      TRI_SetStdinVisibility(false);
      getline(cin, _password);

      TRI_SetStdinVisibility(true);
#else
      getline(cin, _password);
#endif
    }
  }
}
Exemple #24
0
void ArangoClient::parse (ProgramOptions& options,
                          ProgramOptionsDescription& description,
                          string const& example,
                          int argc,
                          char* argv[],
                          string const& initFilename) {
  // if options are invalid, exit directly
  if (! options.parse(description, argc, argv)) {
    LOG_FATAL_AND_EXIT("%s", options.lastError().c_str());
  }

  // setup the logging
  TRI_SetLogLevelLogging(_logLevel.c_str());
  TRI_CreateLogAppenderFile("-", 0, TRI_LOG_SEVERITY_UNKNOWN, false);
  TRI_SetLineNumberLogging(false);
  TRI_SetThreadIdentifierLogging(false);

  // parse config file
  string configFile = "";
  bool allowLocal = false;

  if (! _configFile.empty()) {
    if (StringUtils::tolower(_configFile) == string("none")) {
      LOG_DEBUG("using no init file at all");
    }
    else {
      configFile = _configFile;
    }
  }

  else {
    char* d = TRI_LocateConfigDirectory();

    if (d != 0) {
      string sysDir = string(d) + initFilename;
      TRI_FreeString(TRI_CORE_MEM_ZONE, d);

      if (FileUtils::exists(sysDir)) {
        configFile = sysDir;
        allowLocal = true;
      }
      else {
        LOG_DEBUG("no system init file '%s'", sysDir.c_str());
      }
    }
  }

  if (! configFile.empty()) {
    if (allowLocal) {
      string localConfigFile = configFile + ".local";

      if (FileUtils::exists(localConfigFile)) {
        LOG_DEBUG("using init override file '%s'", localConfigFile.c_str());

        if (! options.parse(description, localConfigFile)) {
          LOG_FATAL_AND_EXIT("cannot parse config file '%s': %s", localConfigFile.c_str(), options.lastError().c_str());
        }
      }
    }

    LOG_DEBUG("using init file '%s'", configFile.c_str());

    if (! options.parse(description, configFile)) {
      LOG_FATAL_AND_EXIT("cannot parse config file '%s': %s", configFile.c_str(), options.lastError().c_str());
    }
  }

  // configuration is parsed and valid if we got to this point
  
  // check for --help
  set<string> help = options.needHelp("help");

  if (! help.empty()) {
    if (! example.empty()) {
      cout << "USAGE: " << argv[0] << " " << example << endl << endl;
    }
    cout << description.usage(help) << endl;

    // --help always returns success
    TRI_EXIT_FUNCTION(EXIT_SUCCESS, NULL);
  }


  // set temp path
  if (options.has("temp-path")) {
    TRI_SetUserTempPath((char*) _tempPath.c_str());
  }

  if (options.has("server.username")) {
    // if a username is specified explicitly, assume authentication is desired
    _disableAuthentication = false;
  }

  // check if have a password
  _hasPassword = options.has("server.password") 
              || _disableAuthentication
              || options.has("jslint") 
              || options.has("javascript.unit-tests");

  // set colors
  if (options.has("colors")) {
    _noColors = false;
  }

  if (options.has("no-colors")) {
    _noColors = true;
  }

  // set auto-completion
  if (options.has("auto-complete")) {
    _noAutoComplete = false;
  }

  if (options.has("no-auto-complete")) {
    _noAutoComplete = true;
  }

  // set pretty print
  if (options.has("pretty-print")) {
    _prettyPrint = true;
  }

  if (options.has("no-pretty-print")) {
    _prettyPrint = false;
  }

  // set pager
  if (options.has("use-pager")) {
    _usePager = true;
  }

  // set quiet
  if (options.has("quiet")) {
    _quiet = true;
  }

  // .............................................................................
  // server options
  // .............................................................................

  if (_serverOptions) {

    // check connection args
    if (_connectTimeout <= 0) {
      LOG_FATAL_AND_EXIT("invalid value for --server.connect-timeout, must be positive");
    }

    if (_requestTimeout <= 0) {
      LOG_FATAL_AND_EXIT("invalid value for --server.request-timeout, must be positive");
    }

    // must specify a user name
    if (_username.size() == 0) {
      LOG_FATAL_AND_EXIT("no value specified for --server.username");
    }

    // no password given on command-line
    if (! _hasPassword) {
      usleep(10 * 1000);
      printContinuous("Please specify a password: "******"");
    }
  }
}