<commit_before>/* author: @gwzz
 *
 */
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
#include <iterator>
#include "graph.h"
#include "support.h"
#include "sctfile.h"

using namespace std;

// Pre-define hierarchy array
// CUI: array of top nodes concept id of each hierarchy
// ConName: array of the name of each hierarchy
const long long CUI[19] = {123037004, 404684003, 308916002, 272379006, 363787002, 410607006, 373873005, 78621006, 260787004, 71388002, 362981000, 419891008, 243796009, 900000000000441003, 48176007, 370115009, 123038009, 254291000, 105590001};
const string ConName[19] = {"Body_structure", "Clinical_finding", "Environment_or_geographical_location", "Event", "Observable_entity", "Organism", "Pharmaceutical_biologic_product", "Physical_force", "Physical_object", "Procedure", "Qualifier_value", "Record_artifact", "Situation_with_explicit_context", "SNOMED_CT_Model_Component", "Social_context", "Special_Concept", "Specimen", "Staging_and_scales", "Substance"};

int main(int argc, char* argv[])
{
  if (argc < 2)
  {
    std::cerr << "Usage: " << argv[0] << " SNOMED_CT_FILE_PATH" << std::endl;
    return 1;
  }
  // string out_put_folder = "/Users/zhuwei/Desktop/sct_nodes_within_hierarchy/";
  string out_put_folder = "/Users/zhuwei/Desktop/tc/";
  SctFile sf(argv[1]);
  long long top_node;
  std::map<long long, int> node_map;
  std::map<int, long long> reversed_node_map;
  std::vector<long long> output_vector;
  std::string sline;
  std::vector<std::string> relation = sf.relations();
  std::vector<std::string> nodes = sf.nodes();

    // Read in node file
    // (concept, index)
    // (index, concept) reversed
  for (int i = 0; i < nodes.size(); ++i){
    node_map[std::stoll(nodes[i])] = i;
  }
  for (map<long long, int>::iterator i = node_map.begin(); i != node_map.end(); ++i)
    reversed_node_map[i->second] = i->first;

  int nodeSize = node_map.size();
  // initialize graph g
  int rnodeSize = reversed_node_map.size();
  std::cout << nodeSize << " " << rnodeSize << endl;
  Graph g(nodeSize);
  std::vector<long long> is_a_relationship;
  for (auto i : relation){
    is_a_relationship.clear();
    is_a_relationship = Split(i, ',');
    // g.addEdge(node_map[is_a_relationship[1]],node_map[is_a_relationship[0]]);
    g.addEdge(node_map[is_a_relationship[0]],node_map[is_a_relationship[1]]);
  }

  // string out_put_file;
  // for (int i = 0; i < 19; ++i){
  //   output_vector.clear();
  //   out_put_file.clear();
  //   out_put_file = out_put_folder + ConName[i];
  //   top_node = CUI[i];
  //   output_vector = g.DFS(node_map[top_node]);
  //   fstream fout;
  //   fout.open(out_put_file,ios::app);
  //   for (auto o : output_vector){
  //       fout << reversed_node_map[o] << endl;
  //   }
  //   fout.close();
  // }
  fstream fout;
  string out_put_file = out_put_folder + "test";
  fout.open(out_put_file,ios::app);
  int tc_index = 0;
  for(std::map<long long, int>::iterator it = node_map.begin(); it != node_map.end(); ++it) {
    std::cout << it->first << endl;
    output_vector = g.DFS(it->second);
    fout << reversed_node_map[it->first] << '|';
    for (auto o : output_vector){
      fout << reversed_node_map[o] << ',';
    }
    fout << std::endl;
    std::cout << tc_index++ << endl;
  }
  fout.close();

  return 0;
}<commit_msg>tc test<commit_after>/* author: @gwzz
 *
 */
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
#include <iterator>
#include "graph.h"
#include "support.h"
#include "sctfile.h"

using namespace std;

// Pre-define hierarchy array
// CUI: array of top nodes concept id of each hierarchy
// ConName: array of the name of each hierarchy
const long long CUI[19] = {123037004, 404684003, 308916002, 272379006, 363787002, 410607006, 373873005, 78621006, 260787004, 71388002, 362981000, 419891008, 243796009, 900000000000441003, 48176007, 370115009, 123038009, 254291000, 105590001};
const string ConName[19] = {"Body_structure", "Clinical_finding", "Environment_or_geographical_location", "Event", "Observable_entity", "Organism", "Pharmaceutical_biologic_product", "Physical_force", "Physical_object", "Procedure", "Qualifier_value", "Record_artifact", "Situation_with_explicit_context", "SNOMED_CT_Model_Component", "Social_context", "Special_Concept", "Specimen", "Staging_and_scales", "Substance"};

int main(int argc, char* argv[])
{
  if (argc < 2)
  {
    std::cerr << "Usage: " << argv[0] << " SNOMED_CT_FILE_PATH" << std::endl;
    return 1;
  }
  // string out_put_folder = "/Users/zhuwei/Desktop/sct_nodes_within_hierarchy/";
  string out_put_folder = "/Users/zhuwei/Desktop/tc/";
  SctFile sf(argv[1]);
  long long top_node;
  std::map<long long, int> node_map;
  std::map<int, long long> reversed_node_map;
  std::vector<long long> output_vector;
  std::string sline;
  std::vector<std::string> relation = sf.relations();
  std::vector<std::string> nodes = sf.nodes();

    // Read in node file
    // (concept, index)
    // (index, concept) reversed
  for (int i = 0; i < nodes.size(); ++i){
    node_map[std::stoll(nodes[i])] = i;
  }
  for (map<long long, int>::iterator i = node_map.begin(); i != node_map.end(); ++i)
    reversed_node_map[i->second] = i->first;

  int nodeSize = node_map.size();
  // initialize graph g
  int rnodeSize = reversed_node_map.size();
  std::cout << nodeSize << " " << rnodeSize << endl;
  Graph g(nodeSize);
  std::vector<long long> is_a_relationship;
  for (auto i : relation){
    is_a_relationship.clear();
    is_a_relationship = Split(i, ',');
    // g.addEdge(node_map[is_a_relationship[1]],node_map[is_a_relationship[0]]);
    g.addEdge(node_map[is_a_relationship[0]],node_map[is_a_relationship[1]]);
  }

  // string out_put_file;
  // for (int i = 0; i < 19; ++i){
  //   output_vector.clear();
  //   out_put_file.clear();
  //   out_put_file = out_put_folder + ConName[i];
  //   top_node = CUI[i];
  //   output_vector = g.DFS(node_map[top_node]);
  //   fstream fout;
  //   fout.open(out_put_file,ios::app);
  //   for (auto o : output_vector){
  //       fout << reversed_node_map[o] << endl;
  //   }
  //   fout.close();
  // }
  fstream fout;
  string out_put_file = out_put_folder + "test";
  fout.open(out_put_file,ios::app);
  int tc_index = 0;
  // debug begin
    // output_vector = g.DFS(node_map[300591002]);
    // for (auto o : output_vector){
    //   cout << reversed_node_map[o] << ',';
    // }
  // debug end
  std::map<long long, int>::iterator it = node_map.begin();
  // std::advance( it, 149999 );
  for(it; it != node_map.end(); ++it) {
    std::cout << it->first << endl;
    output_vector = g.DFS(it->second);
    fout << it->first << '|';
    for (auto o : output_vector){
      fout << reversed_node_map[o] << ',';
    }
    fout << std::endl;
    std::cout << tc_index++ << endl;
  }
  fout.close();

  return 0;
}<|endoftext|>


<commit_before>#include <memory>
#include <iostream>
#include <fstream>

#include <deal.II/base/parameter_handler.h>
#include <deal.II/base/mpi.h>

#include "framework/builder/cfem_framework_builder.h"
#include "problem/parameters_dealii_handler.h"

int main(int argc, char* argv[]) {
  try {
    if (argc != 2) {
      std::cerr
          << "Call the program as mpirun -np num_proc bart input_file_name"
          << std::endl;
      return 1;
    }

    std::cout << "BAY AREA RADIATION TRANSPORT\n"
              << "Developed at the University of California, Berkeley"
              << std::endl;

    bart::problem::ParametersDealiiHandler prm;
    dealii::ParameterHandler d2_prm;
    const std::string filename{argv[1]};

    prm.SetUp(d2_prm);
    d2_prm.parse_input(filename, "");
    prm.Parse(d2_prm);

    dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);

    double k_eff_final;

    std::ofstream output_stream((prm.OutputFilenameBase() + ".vtu").c_str());

    switch(prm.SpatialDimension()) {
      case 1: {
        bart::framework::builder::CFEM_FrameworkBuilder<1> builder;
        auto framework_ptr = builder.BuildFramework(prm, d2_prm);
        framework_ptr->SolveSystem();
        framework_ptr->OutputResults(output_stream);
        k_eff_final = framework_ptr->system()->k_effective.value_or(0);
        break;
      }
      case 2: {
        bart::framework::builder::CFEM_FrameworkBuilder<2> builder;
        auto framework_ptr = builder.BuildFramework(prm, d2_prm);
        framework_ptr->SolveSystem();
        framework_ptr->OutputResults(output_stream);
        k_eff_final = framework_ptr->system()->k_effective.value_or(0);
        break;
      }
      case 3: {
        bart::framework::builder::CFEM_FrameworkBuilder<3> builder;
        auto framework_ptr = builder.BuildFramework(prm, d2_prm);
        framework_ptr->SolveSystem();
        framework_ptr->OutputResults(output_stream);
        k_eff_final = framework_ptr->system()->k_effective.value_or(0);
        break;
      }
    }

    std::cout << "Final k_effective: " << k_eff_final << std::endl;

  } catch (std::exception &exc) {
    std::cerr << std::endl << std::endl
              << "----------------------------------------------------"
              << std::endl;
    std::cerr << "Exception on processing: " << std::endl
              << exc.what() << std::endl
              << "Aborting!" << std::endl
              << "----------------------------------------------------"
              << std::endl;
    return 1;
  } catch (...) {
    std::cerr << std::endl << std::endl
              << "----------------------------------------------------"
              << std::endl;
    std::cerr << "Unknown exception!" << std::endl
              << "Aborting!" << std::endl
              << "----------------------------------------------------"
              << std::endl;
    return 1;
  }
  return 0;
}
<commit_msg>added mpi filename extension using process number<commit_after>#include <memory>
#include <iostream>
#include <fstream>

#include <deal.II/base/parameter_handler.h>
#include <deal.II/base/mpi.h>

#include "framework/builder/cfem_framework_builder.h"
#include "problem/parameters_dealii_handler.h"

int main(int argc, char* argv[]) {
  try {
    if (argc != 2) {
      std::cerr
          << "Call the program as mpirun -np num_proc bart input_file_name"
          << std::endl;
      return 1;
    }

    std::cout << "BAY AREA RADIATION TRANSPORT\n"
              << "Developed at the University of California, Berkeley"
              << std::endl;

    bart::problem::ParametersDealiiHandler prm;
    dealii::ParameterHandler d2_prm;
    const std::string filename{argv[1]};

    prm.SetUp(d2_prm);
    d2_prm.parse_input(filename, "");
    prm.Parse(d2_prm);

    dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);

    double k_eff_final;

    const int n_processes = dealii::Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);
    const int process_id = dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);

    std::ofstream output_stream;
    const std::string output_filename_base{prm.OutputFilenameBase()};
    if (n_processes > 1) {
      const std::string full_filename = output_filename_base + dealii::Utilities::int_to_string(process_id, 4);
      output_stream.open((full_filename + ".vtu").c_str());
    } else {
      output_stream.open((output_filename_base + ".vtu").c_str());
    }

    switch(prm.SpatialDimension()) {
      case 1: {
        bart::framework::builder::CFEM_FrameworkBuilder<1> builder;
        auto framework_ptr = builder.BuildFramework(prm, d2_prm);
        framework_ptr->SolveSystem();
        framework_ptr->OutputResults(output_stream);
        k_eff_final = framework_ptr->system()->k_effective.value_or(0);
        break;
      }
      case 2: {
        bart::framework::builder::CFEM_FrameworkBuilder<2> builder;
        auto framework_ptr = builder.BuildFramework(prm, d2_prm);
        framework_ptr->SolveSystem();
        framework_ptr->OutputResults(output_stream);
        k_eff_final = framework_ptr->system()->k_effective.value_or(0);
        break;
      }
      case 3: {
        bart::framework::builder::CFEM_FrameworkBuilder<3> builder;
        auto framework_ptr = builder.BuildFramework(prm, d2_prm);
        framework_ptr->SolveSystem();
        framework_ptr->OutputResults(output_stream);
        k_eff_final = framework_ptr->system()->k_effective.value_or(0);
        break;
      }
    }

    std::cout << "Final k_effective: " << k_eff_final << std::endl;

  } catch (std::exception &exc) {
    std::cerr << std::endl << std::endl
              << "----------------------------------------------------"
              << std::endl;
    std::cerr << "Exception on processing: " << std::endl
              << exc.what() << std::endl
              << "Aborting!" << std::endl
              << "----------------------------------------------------"
              << std::endl;
    return 1;
  } catch (...) {
    std::cerr << std::endl << std::endl
              << "----------------------------------------------------"
              << std::endl;
    std::cerr << "Unknown exception!" << std::endl
              << "Aborting!" << std::endl
              << "----------------------------------------------------"
              << std::endl;
    return 1;
  }
  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include "NTClient.h"
using namespace std;

void initBot() {
	NTClient nclient = NTClient(220, 0.98);
	nclient.login("utpp_bot2", "123asd123"); // Throw-away account
	nclient.connect();
}
int main(int argc, char** argv) {
	srand(static_cast<unsigned int>(time(0)));
	initBot();
	return 0;
}<commit_msg>Lower base accuracy<commit_after>#include <iostream>
#include <cstdlib>
#include "NTClient.h"
using namespace std;

void initBot() {
	NTClient nclient = NTClient(220, 0.92);
	nclient.login("utpp_bot2", "123asd123"); // Throw-away account
	nclient.connect();
}
int main(int argc, char** argv) {
	srand(static_cast<unsigned int>(time(0)));
	initBot();
	return 0;
}<|endoftext|>


<commit_before>#include <iostream>
using namespace std;

extern "C" {
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <curl/curl.h>
#include <errno.h>
#include <sqlite3.h>
#include <getopt.h>
#include <libxml/xmlmemory.h>
#include "help.h"
#include "logger.h"
}

#include "localFileList.h"
#include "fileListStorage.h"
#include "amazonCredentials.h"
#include "remoteListOfFiles.h"
#include "upload.h"
#include "filePattern.h"

static char *accessKeyId=NULL, *secretAccessKey=NULL, *bucket=NULL, *endPoint = (char *) "s3.amazonaws.com",
	*source=NULL, *databasePath=NULL, *databaseFilename= (char *)".files.sqlite3";
static int performRebuild=0, performUpload=0, makeAllPublic=0, useRrs=0, showProgress=0, skipSsl=0, dryRun=0;

FilePattern *excludeFilePattern;

FILE *logStream;
int logLevel = LOG_ERR;

int rebuildDatabase(RemoteListOfFiles *remoteListOfFiles, AmazonCredentials *amazonCredentials, FileListStorage *fileListStorage) {
	int res = remoteListOfFiles->downloadList();
	if (res==LIST_FAILED) {
		return LIST_FAILED;
	}

  LOG(LOG_INFO, "[MetaUpdate] Got %d files, updating meta information", remoteListOfFiles->count);

	res = remoteListOfFiles->resolveMtimes();
	if (res==LIST_FAILED) {
		return LIST_FAILED;
	}

	if (fileListStorage->storeRemoteListOfFiles(remoteListOfFiles) == STORAGE_FAILED) {
    LOG(LOG_FATAL, "[MetaUpdate] Failed to store list of files");
		return LIST_FAILED;
	} else {
		return LIST_SUCCESS;
	}
}

static char *endPoints[] = {
	(char *) "s3.amazonaws.com",
	(char *) "s3-us-west-2.amazonaws.com",
	(char *) "s3-us-west-1.amazonaws.com",
	(char *) "s3-eu-west-1.amazonaws.com",
	(char *) "s3-ap-southeast-1.amazonaws.com",
	(char *) "s3-ap-northeast-1.amazonaws.com",
	(char *) "s3-sa-east-1.amazonaws.com",

#ifdef TEST
	(char *) "test.dev",
#endif

	NULL
};

int validateEndpoint(char *endPoint) {
	int i=0;
	while (char *e=endPoints[i++]) {
		if (e && strcmp(e, endPoint)==0) {
			return 1;
		}
	}

 	printf("--endPoint %s not valid, use one of:\n", endPoint);

 	i=0;
	while (char *e=endPoints[i++]) {
		printf("\t%s\n", e);
	}

	return 0;
}

char *buildDatabaseFilePath(char *databaseFilename, char *databasePath) {
	uint64_t len = strlen(databasePath)+strlen(databaseFilename)+1;
	char *databaseFilePath = (char *) malloc(len);
	bzero(databaseFilePath, len);
	strcat(databaseFilePath, databasePath);
	strcat(databaseFilePath, "/");
	strcat(databaseFilePath, databaseFilename);
	return databaseFilePath;
}

void showVersion() {
	printf("clarc version " VERSION " (c) 2012 Egor Egorov <me@egorfine.com>\nMIT License  |  http://egorfine.com/clarc/\n");
}

int parseCommandline(int argc, char *argv[]) {
	if (argc==1) {
		showVersion();
		printf("Perhaps, ask --help?\n");
		exit(0);
	}

  static struct option longOpts[] = {
    { "accessKeyId",       required_argument,  NULL,  0 },
    { "secretAccessKey",   required_argument,  NULL,  0 },
    { "bucket",            required_argument,  NULL,  0 },
    { "endPoint",          required_argument,  NULL,  0 },
    { "public",            no_argument,        NULL,  0 },
    { "rrs",               no_argument,        NULL,  0 },
    { "rss",               no_argument,        NULL,  0 }, // common typo
    { "skipSsl",           no_argument,        NULL,  0 },

    { "source",            required_argument,  NULL,  0 },
    { "ddbPath",           required_argument,  NULL,  0 },
    { "dbFilename",        required_argument,  NULL,  0 },

    { "exclude",           required_argument,  NULL,  0 },
    { "excludeFromFile",   required_argument,  NULL,  0 },

    { "progress",          no_argument,        NULL,  0 },
    { "logLevel",          required_argument,  NULL,  0 },

    { "dryRun",            no_argument,        NULL,  0 },

    { "rebuild",           no_argument,        NULL,  0 },
    { "upload",            no_argument,        NULL,  0 },

    { "version",           no_argument,        NULL,  'V' },
    { "help",              no_argument,        NULL,  'h' },

    { NULL,                0,                  NULL,  0 }
  };

	int ch, longIndex;
  while ((ch = getopt_long(argc, argv, "Vh", longOpts, &longIndex)) != -1) {
  	if (ch=='V') {
  		showVersion();
  		exit(0);
  	} else if (ch=='h') {
  		showHelp();
  		exit(0);
  	}

  	if (ch!=0) {
  		continue;
  	}

  	const char *longName = longOpts[longIndex].name;

  	if (strcmp(longName, "accessKeyId")==0) {
  		accessKeyId = strdup(optarg);

  	} else if (strcmp(longName, "secretAccessKey")==0) {
  		secretAccessKey = strdup(optarg);

  	} else if (strcmp(longName, "bucket")==0) {
  		bucket = strdup(optarg);

  	} else if (strcmp(longName, "endPoint")==0) {
  		endPoint = strdup(optarg);

  	} else if (strcmp(longName, "public")==0) {
  		makeAllPublic = 1;

    } else if (strcmp(longName, "skipSsl")==0) {
      skipSsl = 1;

  	} else if (strcmp(longName, "rrs")==0) {
  		useRrs = 1;

  	} else if (strcmp(longName, "rss")==0) {
  		printf("Warning: you spelled --rss; you meant -rrs which stands for Reduced Redundancy Storage.\n");
  		useRrs = 1;

    } else if (strcmp(longName, "dryRun")==0) {
      dryRun = 1;

    } else if (strcmp(longName, "progress")==0) {
      showProgress = 1;

    } else if (strcmp(longName, "logLevel")==0) {
      logLevel = atoi(optarg);
      if (logLevel <= 0 || logLevel > 5) {
        printf("--logLevel must be 1..5\n");
        exit(1);
      }

  	} else if (strcmp(longName, "source")==0) {
  		source = strdup(optarg);

  	} else if (strcmp(longName, "dbPath")==0) {
  		databasePath = strdup(optarg);

  	} else if (strcmp(longName, "dbFilename")==0) {
  		databaseFilename = strdup(optarg);

  	} else if (strcmp(longName, "rebuild")==0) {
  		performRebuild=1;

  	} else if (strcmp(longName, "upload")==0) {
  		performUpload=1;

  	} else if (strcmp(longName, "exclude")==0) {
  		if (!excludeFilePattern->add(optarg)) {
  			printf("Pattern `%s' is not valid.\n", optarg);
  			exit(1);
  		}
  	} else if (strcmp(longName, "excludeFromFile")==0) {
  		if (!excludeFilePattern->readFile(optarg)) {
  			printf("Cannot read or parse patterns in %s\n", optarg);
  			exit(1);
  		}
  	}
  }

  int failed = 0;

  if (!source) {
  	printf("Specify --source.\n");
  	failed = 1;
  }

  if (source && source[0]!='/') {
  	printf("--source must be absolute path.\n");
		failed=1;
  }

  if (!accessKeyId) {
  	printf("Specify --accessKeyId.\n");
  	failed = 1;
  }

  if (!secretAccessKey) {
  	printf("Specify --secretAccessKey.\n");
  	failed = 1;
  }

  if (!bucket) {
  	printf("Specify --bucket.\n");
  	failed = 1;
  }

  if (!validateEndpoint(endPoint)) {
  	failed = 1;
  }

  if (!performRebuild && !performUpload) {
  	printf("What shall I do? Say --rebuild and/or --upload!\n");
  	failed = 1;
  }

  if (failed) {
  	return 0;
  }

  while (source[strlen(source)-1]=='/') {
  	source[strlen(source)-1]=0;
  }

  if (!databasePath) {
  	databasePath = source;
  } else {
	  while (databasePath[strlen(databasePath)-1]=='/') {
	  	databasePath[strlen(databasePath)-1]=0;
	  }
	}

	return 1;
}

int verifySource(char *source) {
	struct stat fileInfo;
	if (lstat(source, &fileInfo)<0) {
		printf("%s doesn't exists.\n", source);
		return 0;
	}

	if (!(fileInfo.st_mode & S_IFDIR)) {
		printf("%s isn't a directory.\n", source);
		return 0;
	}

	return 1;
}

int main(int argc, char *argv[]) {
	int res;
  curl_global_init(CURL_GLOBAL_ALL);
  xmlInitParser();

  logStream = stdout;
  logLevel = LOG_DBG;

	excludeFilePattern = new FilePattern();

  if (!parseCommandline(argc, argv)) {
  	exit(1);
  }

  if (!verifySource(source)) {
  	exit(1);
  }

  AmazonCredentials *amazonCredentials = new AmazonCredentials(
  	accessKeyId,
  	secretAccessKey,
  	bucket, endPoint
  );

	RemoteListOfFiles *remoteListOfFiles = new RemoteListOfFiles(amazonCredentials);
  remoteListOfFiles->showProgress = showProgress;
  if (skipSsl) {
    remoteListOfFiles->useSsl=0;
  }

	res = remoteListOfFiles->checkAuth();
	if (res == AUTH_FAILED_BUCKET_DOESNT_EXISTS) {
    LOG(LOG_FATAL, "[Auth] Failed: bucket doesn't exists, exit");
		exit(1);
	} else if (res == AUTH_FAILED) {
		LOG(LOG_FATAL, "[Auth] FAIL, exit");
		exit(1);
	}
  LOG(LOG_INFO, "[Auth] Success");

	char *databaseFilePath = buildDatabaseFilePath(databaseFilename, databasePath);
	LOG(LOG_DBG, "[Storage] Database path = %s", databaseFilePath);

	char errorResult[1024*100];
	FileListStorage *fileListStorage = new FileListStorage(databaseFilePath, errorResult);
	if (strlen(errorResult)>0) {
		LOG(LOG_FATAL, "[Storage] FAIL: %s, exit", errorResult);
		exit(1);
	}

	if (performRebuild) {
		if (rebuildDatabase(remoteListOfFiles, amazonCredentials, fileListStorage)==LIST_FAILED) {
			exit(1);
		}
	}

	if (performUpload) {
		if (excludeFilePattern->count==0) {
			delete excludeFilePattern;
			excludeFilePattern=NULL;
		}

		Uploader *uploader = new Uploader(amazonCredentials, excludeFilePattern);
		uploader->useRrs = useRrs;
		uploader->makeAllPublic = makeAllPublic;
    uploader->showProgress = showProgress;
    if (skipSsl) {
      uploader->useSsl=0;
    }
    uploader->dryRun = dryRun;

		res = uploader->uploadFiles(fileListStorage, source);

		if (res==UPLOAD_FAILED) {
			exit(1);
		}

		res = uploader->uploadDatabase(databaseFilePath, databaseFilename);
		if (res==UPLOAD_FAILED) {
			exit(1);
		}

		delete uploader;
	}

	free(databaseFilePath);
	delete fileListStorage;
	delete amazonCredentials;

	exit(0);
}
<commit_msg>dryRun<commit_after>#include <iostream>
using namespace std;

extern "C" {
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <curl/curl.h>
#include <errno.h>
#include <sqlite3.h>
#include <getopt.h>
#include <libxml/xmlmemory.h>
#include "help.h"
#include "logger.h"
}

#include "localFileList.h"
#include "fileListStorage.h"
#include "amazonCredentials.h"
#include "remoteListOfFiles.h"
#include "upload.h"
#include "filePattern.h"

static char *accessKeyId=NULL, *secretAccessKey=NULL, *bucket=NULL, *endPoint = (char *) "s3.amazonaws.com",
	*source=NULL, *databasePath=NULL, *databaseFilename= (char *)".files.sqlite3";
static int performRebuild=0, performUpload=0, makeAllPublic=0, useRrs=0, showProgress=0, skipSsl=0, dryRun=0;

FilePattern *excludeFilePattern;

FILE *logStream;
int logLevel = LOG_ERR;

int rebuildDatabase(RemoteListOfFiles *remoteListOfFiles, AmazonCredentials *amazonCredentials, FileListStorage *fileListStorage) {
	int res = remoteListOfFiles->downloadList();
	if (res==LIST_FAILED) {
		return LIST_FAILED;
	}

  LOG(LOG_INFO, "[MetaUpdate] Got %d files, updating meta information", remoteListOfFiles->count);

	res = remoteListOfFiles->resolveMtimes();
	if (res==LIST_FAILED) {
		return LIST_FAILED;
	}

  if (dryRun) {
    LOG(LOG_INFO, "[MetaUpdate] [dry] Skipped storing list of files");
    return LIST_SUCCESS;
  }

	if (fileListStorage->storeRemoteListOfFiles(remoteListOfFiles) == STORAGE_FAILED) {
    LOG(LOG_FATAL, "[MetaUpdate] Failed to store list of files");
		return LIST_FAILED;
	} else {
		return LIST_SUCCESS;
	}
}

static char *endPoints[] = {
	(char *) "s3.amazonaws.com",
	(char *) "s3-us-west-2.amazonaws.com",
	(char *) "s3-us-west-1.amazonaws.com",
	(char *) "s3-eu-west-1.amazonaws.com",
	(char *) "s3-ap-southeast-1.amazonaws.com",
	(char *) "s3-ap-northeast-1.amazonaws.com",
	(char *) "s3-sa-east-1.amazonaws.com",

#ifdef TEST
	(char *) "test.dev",
#endif

	NULL
};

int validateEndpoint(char *endPoint) {
	int i=0;
	while (char *e=endPoints[i++]) {
		if (e && strcmp(e, endPoint)==0) {
			return 1;
		}
	}

 	printf("--endPoint %s not valid, use one of:\n", endPoint);

 	i=0;
	while (char *e=endPoints[i++]) {
		printf("\t%s\n", e);
	}

	return 0;
}

char *buildDatabaseFilePath(char *databaseFilename, char *databasePath) {
	uint64_t len = strlen(databasePath)+strlen(databaseFilename)+1;
	char *databaseFilePath = (char *) malloc(len);
	bzero(databaseFilePath, len);
	strcat(databaseFilePath, databasePath);
	strcat(databaseFilePath, "/");
	strcat(databaseFilePath, databaseFilename);
	return databaseFilePath;
}

void showVersion() {
	printf("clarc version " VERSION " (c) 2012 Egor Egorov <me@egorfine.com>\nMIT License  |  http://egorfine.com/clarc/\n");
}

int parseCommandline(int argc, char *argv[]) {
	if (argc==1) {
		showVersion();
		printf("Perhaps, ask --help?\n");
		exit(0);
	}

  static struct option longOpts[] = {
    { "accessKeyId",       required_argument,  NULL,  0 },
    { "secretAccessKey",   required_argument,  NULL,  0 },
    { "bucket",            required_argument,  NULL,  0 },
    { "endPoint",          required_argument,  NULL,  0 },
    { "public",            no_argument,        NULL,  0 },
    { "rrs",               no_argument,        NULL,  0 },
    { "rss",               no_argument,        NULL,  0 }, // common typo
    { "skipSsl",           no_argument,        NULL,  0 },

    { "source",            required_argument,  NULL,  0 },
    { "ddbPath",           required_argument,  NULL,  0 },
    { "dbFilename",        required_argument,  NULL,  0 },

    { "exclude",           required_argument,  NULL,  0 },
    { "excludeFromFile",   required_argument,  NULL,  0 },

    { "progress",          no_argument,        NULL,  0 },
    { "logLevel",          required_argument,  NULL,  0 },

    { "dryRun",            no_argument,        NULL,  0 },

    { "rebuild",           no_argument,        NULL,  0 },
    { "upload",            no_argument,        NULL,  0 },

    { "version",           no_argument,        NULL,  'V' },
    { "help",              no_argument,        NULL,  'h' },

    { NULL,                0,                  NULL,  0 }
  };

	int ch, longIndex;
  while ((ch = getopt_long(argc, argv, "Vh", longOpts, &longIndex)) != -1) {
  	if (ch=='V') {
  		showVersion();
  		exit(0);
  	} else if (ch=='h') {
  		showHelp();
  		exit(0);
  	}

  	if (ch!=0) {
  		continue;
  	}

  	const char *longName = longOpts[longIndex].name;

  	if (strcmp(longName, "accessKeyId")==0) {
  		accessKeyId = strdup(optarg);

  	} else if (strcmp(longName, "secretAccessKey")==0) {
  		secretAccessKey = strdup(optarg);

  	} else if (strcmp(longName, "bucket")==0) {
  		bucket = strdup(optarg);

  	} else if (strcmp(longName, "endPoint")==0) {
  		endPoint = strdup(optarg);

  	} else if (strcmp(longName, "public")==0) {
  		makeAllPublic = 1;

    } else if (strcmp(longName, "skipSsl")==0) {
      skipSsl = 1;

  	} else if (strcmp(longName, "rrs")==0) {
  		useRrs = 1;

  	} else if (strcmp(longName, "rss")==0) {
  		printf("Warning: you spelled --rss; you meant -rrs which stands for Reduced Redundancy Storage.\n");
  		useRrs = 1;

    } else if (strcmp(longName, "dryRun")==0) {
      dryRun = 1;

    } else if (strcmp(longName, "progress")==0) {
      showProgress = 1;

    } else if (strcmp(longName, "logLevel")==0) {
      logLevel = atoi(optarg);
      if (logLevel <= 0 || logLevel > 5) {
        printf("--logLevel must be 1..5\n");
        exit(1);
      }

  	} else if (strcmp(longName, "source")==0) {
  		source = strdup(optarg);

  	} else if (strcmp(longName, "dbPath")==0) {
  		databasePath = strdup(optarg);

  	} else if (strcmp(longName, "dbFilename")==0) {
  		databaseFilename = strdup(optarg);

  	} else if (strcmp(longName, "rebuild")==0) {
  		performRebuild=1;

  	} else if (strcmp(longName, "upload")==0) {
  		performUpload=1;

  	} else if (strcmp(longName, "exclude")==0) {
  		if (!excludeFilePattern->add(optarg)) {
  			printf("Pattern `%s' is not valid.\n", optarg);
  			exit(1);
  		}
  	} else if (strcmp(longName, "excludeFromFile")==0) {
  		if (!excludeFilePattern->readFile(optarg)) {
  			printf("Cannot read or parse patterns in %s\n", optarg);
  			exit(1);
  		}
  	}
  }

  int failed = 0;

  if (!source) {
  	printf("Specify --source.\n");
  	failed = 1;
  }

  if (source && source[0]!='/') {
  	printf("--source must be absolute path.\n");
		failed=1;
  }

  if (!accessKeyId) {
  	printf("Specify --accessKeyId.\n");
  	failed = 1;
  }

  if (!secretAccessKey) {
  	printf("Specify --secretAccessKey.\n");
  	failed = 1;
  }

  if (!bucket) {
  	printf("Specify --bucket.\n");
  	failed = 1;
  }

  if (!validateEndpoint(endPoint)) {
  	failed = 1;
  }

  if (!performRebuild && !performUpload) {
  	printf("What shall I do? Say --rebuild and/or --upload!\n");
  	failed = 1;
  }

  if (failed) {
  	return 0;
  }

  while (source[strlen(source)-1]=='/') {
  	source[strlen(source)-1]=0;
  }

  if (!databasePath) {
  	databasePath = source;
  } else {
	  while (databasePath[strlen(databasePath)-1]=='/') {
	  	databasePath[strlen(databasePath)-1]=0;
	  }
	}

	return 1;
}

int verifySource(char *source) {
	struct stat fileInfo;
	if (lstat(source, &fileInfo)<0) {
		printf("%s doesn't exists.\n", source);
		return 0;
	}

	if (!(fileInfo.st_mode & S_IFDIR)) {
		printf("%s isn't a directory.\n", source);
		return 0;
	}

	return 1;
}

int main(int argc, char *argv[]) {
	int res;
  curl_global_init(CURL_GLOBAL_ALL);
  xmlInitParser();

  logStream = stdout;
  logLevel = LOG_DBG;

	excludeFilePattern = new FilePattern();

  if (!parseCommandline(argc, argv)) {
  	exit(1);
  }

  if (!verifySource(source)) {
  	exit(1);
  }

  AmazonCredentials *amazonCredentials = new AmazonCredentials(
  	accessKeyId,
  	secretAccessKey,
  	bucket, endPoint
  );

	RemoteListOfFiles *remoteListOfFiles = new RemoteListOfFiles(amazonCredentials);
  remoteListOfFiles->showProgress = showProgress;
  if (skipSsl) {
    remoteListOfFiles->useSsl=0;
  }

	res = remoteListOfFiles->checkAuth();
	if (res == AUTH_FAILED_BUCKET_DOESNT_EXISTS) {
    LOG(LOG_FATAL, "[Auth] Failed: bucket doesn't exists, exit");
		exit(1);
	} else if (res == AUTH_FAILED) {
		LOG(LOG_FATAL, "[Auth] FAIL, exit");
		exit(1);
	}
  LOG(LOG_INFO, "[Auth] Success");

	char *databaseFilePath = buildDatabaseFilePath(databaseFilename, databasePath);
	LOG(LOG_DBG, "[Storage] Database path = %s", databaseFilePath);

	char errorResult[1024*100];
	FileListStorage *fileListStorage = new FileListStorage(databaseFilePath, errorResult);
	if (strlen(errorResult)>0) {
		LOG(LOG_FATAL, "[Storage] FAIL: %s, exit", errorResult);
		exit(1);
	}

	if (performRebuild) {
		if (rebuildDatabase(remoteListOfFiles, amazonCredentials, fileListStorage)==LIST_FAILED) {
			exit(1);
		}
	}

	if (performUpload) {
		if (excludeFilePattern->count==0) {
			delete excludeFilePattern;
			excludeFilePattern=NULL;
		}

		Uploader *uploader = new Uploader(amazonCredentials, excludeFilePattern);
		uploader->useRrs = useRrs;
		uploader->makeAllPublic = makeAllPublic;
    uploader->showProgress = showProgress;
    if (skipSsl) {
      uploader->useSsl=0;
    }
    uploader->dryRun = dryRun;

		res = uploader->uploadFiles(fileListStorage, source);

		if (res==UPLOAD_FAILED) {
			exit(1);
		}

		res = uploader->uploadDatabase(databaseFilePath, databaseFilename);
		if (res==UPLOAD_FAILED) {
			exit(1);
		}

		delete uploader;
	}

	free(databaseFilePath);
	delete fileListStorage;
	delete amazonCredentials;

	exit(0);
}
<|endoftext|>


<commit_before>#include <ncurses.h>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include "key_listeners.hh"
#include "file_contents.hh"
#include "configuration.hh"

int main(int argc, char**argv) {
    argc--;argv++;

    initscr();
    noecho();
    raw();

    if(use_colors()) {
        start_color();
    }

    init_conf();

    std::vector<std::string> lines = std::vector<std::string>();
    if(argc) {
        std::string line;
        std::ifstream myfile(argv[0]);
        if(!myfile.good())
            lines.push_back("[Invalid file]");
        else while(std::getline(myfile,line))
                 lines.push_back(line);
    } else {
        lines.push_back("");
    }

    init(lines);
    loop();

    endwin();
    return 0;
}
<commit_msg>Don't insert ``invalid file`` when new file.<commit_after>#include <ncurses.h>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include "key_listeners.hh"
#include "file_contents.hh"
#include "configuration.hh"

int main(int argc, char**argv) {
    argc--;argv++;

    initscr();
    noecho();
    raw();

    if(use_colors()) {
        start_color();
    }

    init_conf();

    std::vector<std::string> lines = std::vector<std::string>();
    if(argc) {
        std::string line;
        std::ifstream myfile(argv[0]);
        if(!myfile.good())
            lines.push_back("");
        else while(std::getline(myfile,line))
                 lines.push_back(line);
    } else {
        lines.push_back("");
    }

    init(lines);
    loop();

    endwin();
    return 0;
}
<|endoftext|>


<commit_before>#include "kernel.h"
#include "raster.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "pixeliterator.h"
#include "assignment.h"

using namespace Ilwis;
using namespace BaseOperations;

Assignment::Assignment()
{
}

Assignment::Assignment(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{
}

bool Assignment::execute(ExecutionContext *ctx, SymbolTable& symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;

    std::function<bool(const Box3D<qint32>)> Assign = [&](const Box3D<qint32> box ) -> bool {
        PixelIterator iterIn(_inputGC, box);
        PixelIterator iterOut(_outputGC, box);

        double v_in = 0;
        for_each(iterOut, iterOut.end(), [&](double& v){
            v_in = *iterIn;
            if ( v_in != rUNDEF) {
                v = v_in;
            }
            ++iterIn;
            ++iterOut;
        });
        return true;
    };

    bool res = OperationHelper::execute(Assign, _outputGC);

    if ( res && ctx != 0) {
        QVariant value;
        value.setValue<IGridCoverage>(_outputGC);
        ctx->_results.push_back(_outputGC->name());
        symTable.addSymbol(_outputGC->name(),0, itGRIDCOVERAGE,value);
    }
    return res;
}

Ilwis::OperationImplementation *Assignment::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new Assignment(metaid, expr);
}

Ilwis::OperationImplementation::State Assignment::prepare(ExecutionContext *, const SymbolTable &)
{
    if ( _expression.parameterCount() != 1) {
        ERROR3(ERR_ILLEGAL_NUM_PARM3,"rasvalue","1",QString::number(_expression.parameterCount()));
        return sPREPAREFAILED;
    }

    QString gc = _expression.parm(0).value();
    if (!_inputGC.prepare(gc)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,gc,"");
        return sPREPAREFAILED;
    }
    OperationHelper helper;
    helper.initialize(_inputGC, _outputGC, _expression.parm(0),
                                itGRIDSIZE | itENVELOPE | itCOORDSYSTEM | itGEOREF | itDOMAIN | itTABLE);
    return sPREPARED;
}

quint64 Assignment::createMetadata()
{
    QString url = QString("ilwis://operations/assignment");
    Resource res(QUrl(url), itOPERATIONMETADATA);
    res.addProperty("namespace","ilwis");
    res.addProperty("longname","assignment");
    res.addProperty("syntax","assignment(gridcoverage)");
    res.addProperty("inparameters","1");
    res.addProperty("pin_1_type", itGRIDCOVERAGE);
    res.addProperty("pin_1_name", TR("input gridcoverage"));
    res.addProperty("pin_1_desc",TR("input gridcoverage with any domain"));
    res.addProperty("pout_1_type", itGRIDCOVERAGE);
    res.addProperty("pout_1_name", TR("copied object"));
    res.addProperty("pout_1_desc",TR(""));
    res.prepare();
    url += "=" + QString::number(res.id());
    res.setUrl(url);

    mastercatalog()->addItems({res});
    return res.id();

}
<commit_msg>using alternate initialize function<commit_after>#include "kernel.h"
#include "raster.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "pixeliterator.h"
#include "mastercatalog.h"
#include "assignment.h"

using namespace Ilwis;
using namespace BaseOperations;

Assignment::Assignment()
{
}

Assignment::Assignment(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{
}

bool Assignment::execute(ExecutionContext *ctx, SymbolTable& symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;

    std::function<bool(const Box3D<qint32>)> Assign = [&](const Box3D<qint32> box ) -> bool {
        PixelIterator iterIn(_inputGC, box);
        PixelIterator iterOut(_outputGC, box);

        double v_in = 0;
        for_each(iterOut, iterOut.end(), [&](double& v){
            v_in = *iterIn;
            if ( v_in != rUNDEF) {
                v = v_in;
            }
            ++iterIn;
            ++iterOut;
        });
        return true;
    };

    bool res = OperationHelper::execute(Assign, _outputGC);

    if ( res && ctx != 0) {
        QVariant value;
        value.setValue<IGridCoverage>(_outputGC);
        ctx->_results.push_back(_outputGC->name());
        symTable.addSymbol(_outputGC->name(),0, itGRIDCOVERAGE,value);
    }
    return res;
}

Ilwis::OperationImplementation *Assignment::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new Assignment(metaid, expr);
}

Ilwis::OperationImplementation::State Assignment::prepare(ExecutionContext *, const SymbolTable &)
{
    if ( _expression.parameterCount() != 1) {
        ERROR3(ERR_ILLEGAL_NUM_PARM3,"rasvalue","1",QString::number(_expression.parameterCount()));
        return sPREPAREFAILED;
    }

    QString coverage = _expression.parm(0).value();
    Resource res = mastercatalog()->name2Resource(coverage);
    if ( !res.isValid()) {
        ERROR1(ERR_COULD_NOT_OPEN_READING_1,coverage);
        return sPREPAREFAILED;
    }
//    if ( res.ilwisType() == itGRIDCOVERAGE) {
//        if (!_inputGC.prepare(coverage)) {
//            ERROR2(ERR_COULD_NOT_LOAD_2,coverage,"");
//            return sPREPAREFAILED;
//        }
//    } else if ( res.ilwisType() == itPOLYGONCOVERAGE) {
//        IIlwisObject ob;
//        ob.prepare(coverage, res.ilwisType());
//    }
    IIlwisObject objIn;
    objIn.prepare(coverage, res.ilwisType());
    OperationHelper helper;
    helper.initialize(objIn, res.ilwisType(), _expression.parm(0),
                                itGRIDSIZE | itENVELOPE | itCOORDSYSTEM | itGEOREF | itDOMAIN | itTABLE);
    return sPREPARED;
}

quint64 Assignment::createMetadata()
{
    QString url = QString("ilwis://operations/assignment");
    Resource res(QUrl(url), itOPERATIONMETADATA);
    res.addProperty("namespace","ilwis");
    res.addProperty("longname","assignment");
    res.addProperty("syntax","assignment(gridcoverage)");
    res.addProperty("inparameters","1");
    res.addProperty("pin_1_type", itGRIDCOVERAGE);
    res.addProperty("pin_1_name", TR("input gridcoverage"));
    res.addProperty("pin_1_desc",TR("input gridcoverage with any domain"));
    res.addProperty("pout_1_type", itGRIDCOVERAGE);
    res.addProperty("pout_1_name", TR("copied object"));
    res.addProperty("pout_1_desc",TR(""));
    res.prepare();
    url += "=" + QString::number(res.id());
    res.setUrl(url);

    mastercatalog()->addItems({res});
    return res.id();

}
<|endoftext|>


<commit_before>
/*
  Copyright(c) 2015 - 2018 Denis Blank <denis.blank at outlook dot com>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files(the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions :

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
**/

#ifdef CONTINUABLE_HAS_EXPERIMENTAL_COROUTINE

#ifndef CONTINUABLE_WITH_NO_EXCEPTIONS
#include <exception>
#endif // CONTINUABLE_WITH_NO_EXCEPTIONS

#include <tuple>

#include <test-continuable.hpp>

namespace std {
namespace experimental {
template <class... T>
struct coroutine_traits<void, T...> {
  struct promise_type {
    void get_return_object() {
    }

    void set_exception(exception_ptr const&) noexcept {
    }

    // FIXME This throws errors in MSVC but is required in clang
#ifndef _MSC_VER
    void unhandled_exception() {
      GTEST_FATAL_FAILURE_("Unhandled async exception!");
    }
#endif // _MSC_VER

    suspend_never initial_suspend() noexcept {
      return {};
    }

    suspend_never final_suspend() noexcept {
      return {};
    }

    void return_void() noexcept {
    }
  };
};
} // namespace experimental
} // namespace std

/// Resolves the given promise asynchonously
template <typename S, typename T>
void resolve_async(S&& supplier, T&& promise) {
  // 0 args
  co_await supplier();

  // 1 args
  int a1 = co_await supplier(1);
  EXPECT_EQ(a1, 1);

  // 2-n args
  std::tuple<int, int> a2 = co_await supplier(1, 2);
  EXPECT_EQ(a2, std::make_tuple(1, 2));

  promise.set_value();
  co_return;
}

TYPED_TEST(single_dimension_tests, are_awaitable) {
  auto const& supply = [&](auto&&... args) {
    // Supplies the current tested continuable
    return this->supply(std::forward<decltype(args)>(args)...);
  };

  EXPECT_ASYNC_RESULT(
      this->supply().then(cti::make_continuable<void>([&](auto&& promise) {
        // Resolve the cotinuable through a coroutine
        resolve_async(supply, std::forward<decltype(promise)>(promise));
      })));
}

#ifndef CONTINUABLE_WITH_NO_EXCEPTIONS

struct await_exception : std::exception {
  char const* what() const noexcept override {
    return "await_exception";
  }

  bool operator==(await_exception const&) const noexcept {
    return true;
  }
};

/// Resolves the given promise asynchonously through an exception
template <typename S, typename T>
void resolve_async_exceptional(S&& supplier, T&& promise) {
  // 0 args
  co_await supplier();

  // 1 args
  int a1 = co_await supplier(1);
  EXPECT_EQ(a1, 1);

  // 2-n args
  std::tuple<int, int> a2 = co_await supplier(1, 2);
  EXPECT_EQ(a2, std::make_tuple(1, 2));

  // GTest ASSERT_THROW isn't co_await friendly yet:
  // clang: 'return statement not allowed in coroutine; did you mean
  //        'co_return'?'
  EXPECT_THROW(co_await supplier().then([] { throw await_exception{}; }),
               await_exception);

  promise.set_value();
  co_return;
}

TYPED_TEST(single_dimension_tests, are_awaitable_with_exceptions) {
  auto const& supply = [&](auto&&... args) {
    // Supplies the current tested continuable
    return this->supply(std::forward<decltype(args)>(args)...);
  };

  ASSERT_ASYNC_COMPLETION(
      this->supply().then(cti::make_continuable<void>([&](auto&& promise) {
        // Resolve the cotinuable through a coroutine
        resolve_async_exceptional(supply,
                                  std::forward<decltype(promise)>(promise));
      })));
}

// TODO Implement this later
//
//  static cti::continuable<int> async_await() {
//   co_await cti::make_continuable<void>([](auto&& promise) {
//     // ...
//     promise.set_value();
//   });
//
//   co_return 1;
// }

#endif // CONTINUABLE_WITH_NO_EXCEPTIONS

#endif // CONTINUABLE_HAS_EXPERIMENTAL_COROUTINE
<commit_msg>Address a MSVC compiler bug which prevents collapsing references in coroutines * Closes #2<commit_after>
/*
  Copyright(c) 2015 - 2018 Denis Blank <denis.blank at outlook dot com>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files(the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions :

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
**/

#ifdef CONTINUABLE_HAS_EXPERIMENTAL_COROUTINE

#ifndef CONTINUABLE_WITH_NO_EXCEPTIONS
#include <exception>
#endif // CONTINUABLE_WITH_NO_EXCEPTIONS

#include <tuple>

#include <test-continuable.hpp>

namespace std {
namespace experimental {
template <class... T>
struct coroutine_traits<void, T...> {
  struct promise_type {
    void get_return_object() {
    }

    void set_exception(exception_ptr const&) noexcept {
    }

    // FIXME This throws errors in MSVC but is required in clang
#ifndef _MSC_VER
    void unhandled_exception() {
      GTEST_FATAL_FAILURE_("Unhandled async exception!");
    }
#endif // _MSC_VER

    suspend_never initial_suspend() noexcept {
      return {};
    }

    suspend_never final_suspend() noexcept {
      return {};
    }

    void return_void() noexcept {
    }
  };
};
} // namespace experimental
} // namespace std

/// Resolves the given promise asynchonously
template <typename S, typename T>
void resolve_async(S&& supplier, T promise) {
  // 0 args
  co_await supplier();

  // 1 args
  int a1 = co_await supplier(1);
  EXPECT_EQ(a1, 1);

  // 2-n args
  std::tuple<int, int> a2 = co_await supplier(1, 2);
  EXPECT_EQ(a2, std::make_tuple(1, 2));

  promise.set_value();
  co_return;
}

TYPED_TEST(single_dimension_tests, are_awaitable) {
  auto const& supply = [&](auto&&... args) {
    // Supplies the current tested continuable
    return this->supply(std::forward<decltype(args)>(args)...);
  };

  EXPECT_ASYNC_RESULT(
      this->supply().then(cti::make_continuable<void>([&](auto promise) {
        // Resolve the cotinuable through a coroutine
        resolve_async(supply, std::move(promise));
      })));
}

#ifndef CONTINUABLE_WITH_NO_EXCEPTIONS

struct await_exception : std::exception {
  char const* what() const noexcept override {
    return "await_exception";
  }

  bool operator==(await_exception const&) const noexcept {
    return true;
  }
};

/// Resolves the given promise asynchonously through an exception
template <typename S, typename T>
void resolve_async_exceptional(S&& supplier, T promise) {
  // 0 args
  co_await supplier();

  // 1 args
  int a1 = co_await supplier(1);
  EXPECT_EQ(a1, 1);

  // 2-n args
  std::tuple<int, int> a2 = co_await supplier(1, 2);
  EXPECT_EQ(a2, std::make_tuple(1, 2));

  // GTest ASSERT_THROW isn't co_await friendly yet:
  // clang: 'return statement not allowed in coroutine; did you mean
  //        'co_return'?'
  EXPECT_THROW(co_await supplier().then([] { throw await_exception{}; }),
               await_exception);

  promise.set_value();
  co_return;
}

TYPED_TEST(single_dimension_tests, are_awaitable_with_exceptions) {
  auto const& supply = [&](auto&&... args) {
    // Supplies the current tested continuable
    return this->supply(std::forward<decltype(args)>(args)...);
  };

  ASSERT_ASYNC_COMPLETION(
      this->supply().then(cti::make_continuable<void>([&](auto promise) {
        // Resolve the cotinuable through a coroutine
        resolve_async_exceptional(supply, std::move(promise));
      })));
}

// TODO Implement this later
//
//  static cti::continuable<int> async_await() {
//   co_await cti::make_continuable<void>([](auto&& promise) {
//     // ...
//     promise.set_value();
//   });
//
//   co_return 1;
// }

#endif // CONTINUABLE_WITH_NO_EXCEPTIONS

#endif // CONTINUABLE_HAS_EXPERIMENTAL_COROUTINE
<|endoftext|>


<commit_before>#include "SDL.hh"
#include "Logger.hh"
using namespace RAGE;
using namespace RAGE::SDL;

Logger Log("Test Events");

class Console
{

	friend class MyEngine;

	//if member embedded (object not reference), error when destructing Font...
	//to debug -> copy / deletion problem
	const Font _font;

	Color _bgColor;

	RGBSurface * surf;

	std::string text;

public :
	Console(const Font & fnt = Font(),Color c = Color(0,0,0)) :_font(fnt),_bgColor(c),surf(NULL),text(">")
	{
		//init();
		//draw();
	}

	bool init(int width, int height)
	{
		surf = new RGBSurface(_bgColor,width,height,8); //8 as magic number for minimum bpp.
		if (surf == NULL) return false;
		surf->optimise(); // Doesnt matter anyway we match the display one here.
		return true;
	}

	//WARNING : BUG here if trying to set to fullscreen using F6, then error, then trying to resize -> crash
	bool resize(int width, int height,bool keepcontent = true)
	{
		bool res = surf->resize(width,height,false);
		draw();
		return res;
	}

	void print(const std::string & newtext)
	{
		text += newtext;
		draw();
	}

	void add(char newchar)
	{
		if (newchar != '\0')
			text += newchar;
		draw();
	}

	void draw()
	{
		std::auto_ptr<RGBSurface> textsurf = _font.render(text,Color(255,255,255),Font::Solid);
		assert(textsurf.get());
		surf->fill(_bgColor);
		surf->blit(*textsurf);
	}

	~Console()
	{
		if (surf != NULL)
			delete surf,surf = NULL;
	}

};

//Defining general EventHandler
class MyGeneralHandler : public GeneralHandler
{
	friend class EventManager;
        bool _quitRequested;

        public:

            GeneralHandler() : _quitRequested(false)
            {}
            virtual ~GeneralHandler()
            {}

            //Callbacks on Window / Display events
            virtual bool handleActiveEvent(bool gain, bool active, bool inputfocus, bool mousefocus)
		{
			return false;
		}

            virtual bool handleResizeEvent(int w, int h)
		{
			App::getInstance().getWindow().resizeDisplay(w,h);
        		return true;
		}
            virtual bool handleExposeEvent()
		{
			 return false;
		}
            //callback on platform-dependent windows manager event
            virtual bool handleSysWMEvent(void)
    {
        return false;
    }

            //Callback on other Events
	    virtual bool handleUserEvent(Event::Type type, int code, void* data1, void* data2)
    {
        return false;
    }

            //Callback on Quit Event
            virtual bool handleQuitEvent(void)
		{
        		_quitRequested=true;
        		return true;
		}
            //Catch-all callback
            virtual bool handleEvent(Event &event)
		{
#if (DEBUG ==2)
        //Getting the details of the Event
        Log << nl << "Last chance handler : " << cevent.getType() << std::endl;
        return true;
#else

        return false;
#endif
		}

};

//Defining UserInput
class MyUserInput : public TextInput
{
public:

	Console *cons;

	MyUserInput() : TextInput(), cons(NULL) {}

	void setConsole (Console * newcons)
	{
		cons = newcons;
	}

    virtual bool handleKeyEvent (const Sym &s, bool pressed)
    {
        bool res = false;
            switch( s.getKey() )
            {
                case KEscape:
                if (pressed==false)
                {
#ifdef DEBUG
                    Log << nl << "Quit requested !" << std::endl;
#endif

                    _quitRequested=true;
                    res=true;
                }
                break;
                case KF5:
                if (pressed==true)
                    App::getInstance().getWindow().iconify();
                res = true;
                break;
				case KF6:
                if (pressed==true)
                    App::getInstance().getWindow().setFullscreen(!App::getInstance().getWindow().isFullscreen());
                res = true;
                break;
				default: if (pressed == true) cons->add(s.getChar());
                res = true;
            }
        return res;
    }
};

class MyEngine : public DefaultEngine
{

public:

	Point consolePos;
	Console * console;
	std::auto_ptr<RGBSurface> HelpMsg;

	MyEngine() : consolePos(0,0), console (NULL), HelpMsg(0)
	{}

	void setConsole( Console * cons ) { console = cons;}

    virtual ~MyEngine()
	{
	}

	bool init(int width, int height)
	{
		DefaultEngine::init(width,height);
		console->init(width,height - 2 * DefaultEngine::_logo.getHeight());
		consolePos.sety(DefaultEngine::_logo.getHeight());
		HelpMsg = console->_font.render("Plz Use Keyboard To Write Text Down", Color(0xFF, 0xFF, 0xFF), Font::Shaded, Color(0, 0, 0));
		return true;
	}

	bool resize(int width, int height)
	{
		DefaultEngine::resize(width,height);
		console->resize(width,height - 2 * DefaultEngine::_logo.getHeight());
		consolePos.sety(DefaultEngine::_logo.getHeight());
		return true;
	}

	void prerender()
	{
		//nothing for now
	}

	void render(VideoSurface & screen) const
    {
		DefaultEngine::render(screen);

		if (HelpMsg.get())
			screen.blit( *HelpMsg, Point::Point(5, 5) );

		if (console !=NULL)
			screen.blit(*(console->surf),consolePos);
    }

	void postrender()
	{
		//nothing for now
	}
};

//Main Program
int main(int argc, char** argv)
{

    Logger testlog("Test Log");

    //Setup example

    testlog << nl << " Enabling SDL Video... " << std::endl;
	App::getInstance().setName ("RAGE::SDL test - Font");
    App::getInstance().initVideo(false,false,false,false);
	App::getInstance().initText();

    testlog << nl << " Creating the User Interface... " << std::endl;

    App::getInstance().getWindow().setBGColor(Color (64,0,0));

    Font font;

    if (argc > 1)
    {
	//specific font
	font.setTTF(argv[1],24);
    }

	Console cons(font);
	MyEngine engine;
	engine.setConsole(&cons);

   //UI Creation
    MyUserInput ui;
	ui.setConsole(&cons);
    MyGeneralHandler gh;
    App::getInstance().getWindow().getEventManager().setKeyboard(&ui);
   App::getInstance().getWindow().getEventManager().setGeneralHandler(&gh);

	//without this line the default engine is used
    App::getInstance().getWindow().setEngine(&engine);

    if (! (App::getInstance().getWindow().resetDisplay()))
    {
        testlog << nl << "Display Creation FAILED !"<< std::endl;
        exit(0);
    }
    else
    {
        App::getInstance().getWindow().mainLoop();
    }

    return 0;
}

<commit_msg>fix to build...<commit_after>#include "SDL.hh"
#include "Logger.hh"
using namespace RAGE;
using namespace RAGE::SDL;

Logger Log("Test Events");

class Console
{

	friend class MyEngine;

	//if member embedded (object not reference), error when destructing Font...
	//to debug -> copy / deletion problem
	const Font _font;

	Color _bgColor;

	RGBSurface * surf;

	std::string text;

public :
	Console(const Font & fnt = Font(),Color c = Color(0,0,0)) :_font(fnt),_bgColor(c),surf(NULL),text(">")
	{
		//init();
		//draw();
	}

	bool init(int width, int height)
	{
		surf = new RGBSurface(_bgColor,width,height,8); //8 as magic number for minimum bpp.
		if (surf == NULL) return false;
		surf->optimise(); // Doesnt matter anyway we match the display one here.
		return true;
	}

	//WARNING : BUG here if trying to set to fullscreen using F6, then error, then trying to resize -> crash
	bool resize(int width, int height,bool keepcontent = true)
	{
		bool res = surf->resize(width,height,false);
		draw();
		return res;
	}

	void print(const std::string & newtext)
	{
		text += newtext;
		draw();
	}

	void add(char newchar)
	{
		if (newchar != '\0')
			text += newchar;
		draw();
	}

	void draw()
	{
		std::auto_ptr<RGBSurface> textsurf = _font.render(text,Color(255,255,255),Font::Solid);
		assert(textsurf.get());
		surf->fill(_bgColor);
		surf->blit(*textsurf);
	}

	~Console()
	{
		if (surf != NULL)
			delete surf,surf = NULL;
	}

};

//Defining general EventHandler
class MyGeneralHandler : public GeneralHandler
{
	friend class EventManager;
        bool _quitRequested;

        public:

			//Callbacks on Window / Display events
            virtual bool handleActiveEvent(bool gain, bool active, bool inputfocus, bool mousefocus)
		{
			return false;
		}

            virtual bool handleResizeEvent(int w, int h)
		{
			App::getInstance().getWindow().resizeDisplay(w,h);
        		return true;
		}
            virtual bool handleExposeEvent()
		{
			 return false;
		}
            //callback on platform-dependent windows manager event
            virtual bool handleSysWMEvent(void)
    {
        return false;
    }

            //Callback on other Events
	    virtual bool handleUserEvent(Event::Type type, int code, void* data1, void* data2)
    {
        return false;
    }

            //Callback on Quit Event
            virtual bool handleQuitEvent(void)
		{
        		_quitRequested=true;
        		return true;
		}
            //Catch-all callback
            virtual bool handleEvent(Event &event)
		{
#if (DEBUG ==2)
        //Getting the details of the Event
        Log << nl << "Last chance handler : " << cevent.getType() << std::endl;
        return true;
#else

        return false;
#endif
		}

};

//Defining UserInput
class MyUserInput : public TextInput
{
public:

	Console *cons;

	MyUserInput() : TextInput(), cons(NULL) {}

	void setConsole (Console * newcons)
	{
		cons = newcons;
	}

    virtual bool handleKeyEvent (const Sym &s, bool pressed)
    {
        bool res = false;
            switch( s.getKey() )
            {
                case KEscape:
                if (pressed==false)
                {
#ifdef DEBUG
                    Log << nl << "Quit requested !" << std::endl;
#endif

                    _quitRequested=true;
                    res=true;
                }
                break;
                case KF5:
                if (pressed==true)
                    App::getInstance().getWindow().iconify();
                res = true;
                break;
				case KF6:
                if (pressed==true)
                    App::getInstance().getWindow().setFullscreen(!App::getInstance().getWindow().isFullscreen());
                res = true;
                break;
				default: if (pressed == true) cons->add(s.getChar());
                res = true;
            }
        return res;
    }
};

class MyEngine : public DefaultEngine
{

public:

	Point consolePos;
	Console * console;
	std::auto_ptr<RGBSurface> HelpMsg;

	MyEngine() : consolePos(0,0), console (NULL), HelpMsg(0)
	{}

	void setConsole( Console * cons ) { console = cons;}

    virtual ~MyEngine()
	{
	}

	bool init(int width, int height)
	{
		DefaultEngine::init(width,height);
		console->init(width,height - 2 * DefaultEngine::_logo.getHeight());
		consolePos.sety(DefaultEngine::_logo.getHeight());
		HelpMsg = console->_font.render("Plz Use Keyboard To Write Text Down", Color(0xFF, 0xFF, 0xFF), Font::Shaded, Color(0, 0, 0));
		return true;
	}

	bool resize(int width, int height)
	{
		DefaultEngine::resize(width,height);
		console->resize(width,height - 2 * DefaultEngine::_logo.getHeight());
		consolePos.sety(DefaultEngine::_logo.getHeight());
		return true;
	}

	void prerender()
	{
		//nothing for now
	}

	void render(VideoSurface & screen) const
    {
		DefaultEngine::render(screen);

		if (HelpMsg.get())
			screen.blit( *HelpMsg, Point::Point(5, 5) );

		if (console !=NULL)
			screen.blit(*(console->surf),consolePos);
    }

	void postrender()
	{
		//nothing for now
	}
};

//Main Program
int main(int argc, char** argv)
{

    Logger testlog("Test Log");

    //Setup example

    testlog << nl << " Enabling SDL Video... " << std::endl;
	App::getInstance().setName ("RAGE::SDL test - Font");
    App::getInstance().initVideo(false,false,false,false);
	App::getInstance().initText();

    testlog << nl << " Creating the User Interface... " << std::endl;

    App::getInstance().getWindow().setBGColor(Color (64,0,0));

    Font font;

    if (argc > 1)
    {
	//specific font
	font.setTTF(argv[1],24);
    }

	Console cons(font);
	MyEngine engine;
	engine.setConsole(&cons);

   //UI Creation
    MyUserInput ui;
	ui.setConsole(&cons);
    MyGeneralHandler gh;
    App::getInstance().getWindow().getEventManager().setKeyboard(&ui);
   App::getInstance().getWindow().getEventManager().setGeneralHandler(&gh);

	//without this line the default engine is used
    App::getInstance().getWindow().setEngine(&engine);

    if (! (App::getInstance().getWindow().resetDisplay()))
    {
        testlog << nl << "Display Creation FAILED !"<< std::endl;
        exit(0);
    }
    else
    {
        App::getInstance().getWindow().mainLoop();
    }

    return 0;
}

<|endoftext|>


<commit_before>
// Copyright (c) 2012, 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/image/image.hpp"
#include "openMVG/features/features.hpp"

/// Generic Image Collection image matching
#include "software/SfM/ImageCollectionMatcher_AllInMemory.hpp"
#include "software/SfM/ImageCollectionGeometricFilter.hpp"
#include "software/SfM/ImageCollection_F_ACRobust.hpp"
#include "software/SfM/pairwiseAdjacencyDisplay.hpp"
#include "software/SfM/SfMIOHelper.hpp"
#include "openMVG/matching/matcher_brute_force.hpp"
#include "openMVG/matching/matcher_kdtree_flann.hpp"
#include "openMVG/matching/indMatch_utils.hpp"

/// Generic Image Collection image matching
#include "software/SfM/ImageCollectionMatcher_AllInMemory.hpp"
#include "software/SfM/ImageCollectionGeometricFilter.hpp"
#include "software/SfM/ImageCollection_F_ACRobust.hpp"
#include "software/SfM/pairwiseAdjacencyDisplay.hpp"

/// Feature detector and descriptor interface
#include "patented/sift/SIFT.hpp"

#include "third_party/cmdLine/cmdLine.h"

#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/progress/progress.hpp"

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>

using namespace openMVG;
using namespace openMVG::matching;
using namespace openMVG::robust;
using namespace std;

int main(int argc, char **argv)
{
  CmdLine cmd;

  std::string sImaDirectory;
  std::string sOutDir = "";
  float fDistRatio = .6f;
  bool bOctMinus1 = false;
  size_t coefZoom = 1;
  float dPeakThreshold = 0.04f;

  cmd.add( make_option('i', sImaDirectory, "imadir") );
  cmd.add( make_option('o', sOutDir, "outdir") );
  cmd.add( make_option('r', fDistRatio, "distratio") );
  cmd.add( make_option('s', bOctMinus1, "octminus1") );
  cmd.add( make_option('p', dPeakThreshold, "peakThreshold") );

  try {
      if (argc == 1) throw std::string("Invalid command line parameter.");
      cmd.process(argc, argv);
  } catch(const std::string& s) {
      std::cerr << "Usage: " << argv[0] << ' '
      << "[-i|--imadir path] "
      << "[-o|--outdir path] "
      << "[-r|--distratio 0.6] "
      << "[-s|--octminus1 0 or 1] "
      << "[-p|--peakThreshold 0.04 -> 0.01] "
      << std::endl;

      std::cerr << s << std::endl;
      return EXIT_FAILURE;
  }

  std::cout << " You called : " <<std::endl
            << argv[0] << std::endl
            << "--imadir " << sImaDirectory << std::endl
            << "--outdir " << sOutDir << std::endl
            << "--distratio " << fDistRatio << std::endl
            << "--octminus1 " << bOctMinus1 << std::endl
            << "--peakThreshold " << dPeakThreshold << std::endl;

  if (sOutDir.empty())  {
    std::cerr << "\nIt is an invalid output directory" << std::endl;
    return EXIT_FAILURE;
  }

  // -----------------------------
  // a. List images
  // b. Compute features and descriptor
  // c. Compute putatives descriptor matches
  // d. Geometric filtering of putatives matches
  // e. Export some statistics
  // -----------------------------

  // Create output dir
  if (!stlplus::folder_exists(sOutDir))
    stlplus::folder_create( sOutDir );

  //---------------------------------------
  // a. List images
  //---------------------------------------
  std::string sListsFile = stlplus::create_filespec( sOutDir,
                                                     "lists.txt" ).c_str();
  if (!stlplus::is_file(sListsFile) )
  {
    std::cerr << std::endl
      << "The input matching/lists.txt is missing" << std::endl;
    return false;
  }

  std::vector<openMVG::SfMIO::CameraInfo> vec_camImageName;
  std::vector<openMVG::SfMIO::IntrinsicCameraInfo> vec_focalGroup;
  if (!openMVG::SfMIO::loadImageList( vec_camImageName,
                                      vec_focalGroup,
                                      sListsFile) )
  {
    std::cerr << "\nEmpty image list." << std::endl;
    return false;
  }

  std::vector<std::string> vec_fileNames;
  std::vector<std::pair<size_t, size_t> > vec_imagesSize;
  for ( std::vector<openMVG::SfMIO::CameraInfo>::const_iterator iter_camInfo = vec_camImageName.begin();
     iter_camInfo != vec_camImageName.end();
     iter_camInfo++ )
  {
    vec_imagesSize.push_back( std::make_pair( vec_focalGroup[iter_camInfo->m_intrinsicId].m_w,
                                              vec_focalGroup[iter_camInfo->m_intrinsicId].m_h ) );
    vec_fileNames.push_back( stlplus::create_filespec( sImaDirectory, iter_camInfo->m_sImageName) );
  }

  //---------------------------------------
  // b. Compute features and descriptor
  //    - extract sift features and descriptor
  //    - if keypoints already computed, re-load them
  //    - else save features and descriptors on disk
  //---------------------------------------

  typedef Descriptor<float, 128> DescriptorT;
  typedef SIOPointFeature FeatureT;
  typedef std::vector<FeatureT> FeatsT;
  typedef vector<DescriptorT > DescsT;
  typedef KeypointSet<FeatsT, DescsT > KeypointSetT;

  {
    std::cout << "\n\nEXTRACT FEATURES" << std::endl;
    vec_imagesSize.resize(vec_fileNames.size());

    Image<RGBColor> imageRGB;
    Image<unsigned char> imageGray;

    C_Progress_display my_progress_bar( vec_fileNames.size() );
    for(size_t i=0; i < vec_fileNames.size(); ++i)  {
      KeypointSetT kpSet;

      std::string sFeat = stlplus::create_filespec(sOutDir,
        stlplus::basename_part(vec_fileNames[i]), "feat");
      std::string sDesc = stlplus::create_filespec(sOutDir,
        stlplus::basename_part(vec_fileNames[i]), "desc");

      //Test if descriptor and feature was already computed
      if (stlplus::file_exists(sFeat) && stlplus::file_exists(sDesc)) {

        if (ReadImage(vec_fileNames[i].c_str(), &imageRGB)) {
          vec_imagesSize[i] = make_pair(imageRGB.Width(), imageRGB.Height());
        }
        else {
          ReadImage(vec_fileNames[i].c_str(), &imageGray);
          vec_imagesSize[i] = make_pair(imageGray.Width(), imageGray.Height());
        }
      }
      else  { //Not already computed, so compute and save

        if (ReadImage(vec_fileNames[i].c_str(), &imageRGB)) {
          Rgb2Gray(imageRGB, &imageGray);
        }
        else{
          ReadImage(vec_fileNames[i].c_str(), &imageGray);
        }

        // Compute features and descriptors and export them to file
        SIFTDetector(imageGray,
          kpSet.features(), kpSet.descriptors(),
          bOctMinus1, true, dPeakThreshold);

        kpSet.saveToBinFile(sFeat, sDesc);
        vec_imagesSize[i] = make_pair(imageGray.Width(), imageRGB.Height());
      }
      ++my_progress_bar;
    }
  }

  //---------------------------------------
  // c. Compute putatives descriptor matches
  //    - L2 descriptor matching
  //    - Keep correspondences only if NearestNeighbor ratio is ok
  //---------------------------------------
  IndexedMatchPerPair map_PutativesMatches;
  // Define the matcher and the used metric (Squared L2)
  // ANN matcher could be defined as follow:
  typedef flann::L2<DescriptorT::bin_type> MetricT;
  typedef ArrayMatcher_Kdtree_Flann<DescriptorT::bin_type, MetricT> MatcherT;
  // Brute force matcher is defined as following:
  //typedef L2_Vectorized<DescriptorT::bin_type> MetricT;
  //typedef ArrayMatcherBruteForce<DescriptorT::bin_type, MetricT> MatcherT;

  // If the matches already exists, reload them
  if (stlplus::file_exists(sOutDir + "/matches.putative.txt"))
  {
    PairedIndMatchImport(sOutDir + "/matches.putative.txt", map_PutativesMatches);
    std::cout << std::endl << "PUTATIVE MATCHES -- PREVIOUS RESULTS LOADED" << std::endl;
  }
  else // Compute the putatives matches
  {
    ImageCollectionMatcher_AllInMemory<KeypointSetT, MatcherT> collectionMatcher(fDistRatio);
    if (collectionMatcher.loadData(vec_fileNames, sOutDir))
    {
      std::cout  << std::endl << "PUTATIVE MATCHES" << std::endl;
      collectionMatcher.Match(vec_fileNames, map_PutativesMatches);
      //---------------------------------------
      //-- Export putative matches
      //---------------------------------------
      std::ofstream file (std::string(sOutDir + "/matches.putative.txt").c_str());
      if (file.is_open())
        PairedIndMatchToStream(map_PutativesMatches, file);
      file.close();
    }
  }
  //-- export putative matches Adjacency matrix
  PairWiseMatchingToAdjacencyMatrixSVG(vec_fileNames.size(),
    map_PutativesMatches,
    stlplus::create_filespec(sOutDir, "PutativeAdjacencyMatrix", "svg"));

  //---------------------------------------
  // d. Geometric filtering of putatives matches
  //    - AContrario Estimation of the Fundamental matrix
  //    - Use a upper bound for the plausible F matrix
  //      acontrario estimated threshold
  //---------------------------------------
  IndexedMatchPerPair map_GeometricMatches_F;

  GeometricFilter_FMatrix_AC geomFilter_F_AC(4.0);
  ImageCollectionGeometricFilter<FeatureT, GeometricFilter_FMatrix_AC> collectionGeomFilter;
  if (collectionGeomFilter.loadData(vec_fileNames, sOutDir))
  {
    std::cout << std::endl << " - GEOMETRIC FILTERING - " << std::endl;
    collectionGeomFilter.Filter(
      geomFilter_F_AC,
      map_PutativesMatches,
      map_GeometricMatches_F,
      vec_imagesSize);

    //---------------------------------------
    //-- Export geometric filtered matches
    //---------------------------------------
    std::ofstream file (string(sOutDir + "/matches.f.txt").c_str());
    if (file.is_open())
      PairedIndMatchToStream(map_GeometricMatches_F, file);
    file.close();

    //-- export Adjacency matrix
    std::cout << "\n Export Adjacency Matrix of the pairwise's Epipolar matches"
      << std::endl;
    PairWiseMatchingToAdjacencyMatrixSVG(vec_fileNames.size(),
      map_GeometricMatches_F,
      stlplus::create_filespec(sOutDir, "EpipolarAdjacencyMatrix", "svg"));
  }
  return EXIT_SUCCESS;
}

<commit_msg>Fix hardcoded path in error message<commit_after>
// Copyright (c) 2012, 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/image/image.hpp"
#include "openMVG/features/features.hpp"

/// Generic Image Collection image matching
#include "software/SfM/ImageCollectionMatcher_AllInMemory.hpp"
#include "software/SfM/ImageCollectionGeometricFilter.hpp"
#include "software/SfM/ImageCollection_F_ACRobust.hpp"
#include "software/SfM/pairwiseAdjacencyDisplay.hpp"
#include "software/SfM/SfMIOHelper.hpp"
#include "openMVG/matching/matcher_brute_force.hpp"
#include "openMVG/matching/matcher_kdtree_flann.hpp"
#include "openMVG/matching/indMatch_utils.hpp"

/// Generic Image Collection image matching
#include "software/SfM/ImageCollectionMatcher_AllInMemory.hpp"
#include "software/SfM/ImageCollectionGeometricFilter.hpp"
#include "software/SfM/ImageCollection_F_ACRobust.hpp"
#include "software/SfM/pairwiseAdjacencyDisplay.hpp"

/// Feature detector and descriptor interface
#include "patented/sift/SIFT.hpp"

#include "third_party/cmdLine/cmdLine.h"

#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/progress/progress.hpp"

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>

using namespace openMVG;
using namespace openMVG::matching;
using namespace openMVG::robust;
using namespace std;

int main(int argc, char **argv)
{
  CmdLine cmd;

  std::string sImaDirectory;
  std::string sOutDir = "";
  float fDistRatio = .6f;
  bool bOctMinus1 = false;
  size_t coefZoom = 1;
  float dPeakThreshold = 0.04f;

  cmd.add( make_option('i', sImaDirectory, "imadir") );
  cmd.add( make_option('o', sOutDir, "outdir") );
  cmd.add( make_option('r', fDistRatio, "distratio") );
  cmd.add( make_option('s', bOctMinus1, "octminus1") );
  cmd.add( make_option('p', dPeakThreshold, "peakThreshold") );

  try {
      if (argc == 1) throw std::string("Invalid command line parameter.");
      cmd.process(argc, argv);
  } catch(const std::string& s) {
      std::cerr << "Usage: " << argv[0] << ' '
      << "[-i|--imadir path] "
      << "[-o|--outdir path] "
      << "[-r|--distratio 0.6] "
      << "[-s|--octminus1 0 or 1] "
      << "[-p|--peakThreshold 0.04 -> 0.01] "
      << std::endl;

      std::cerr << s << std::endl;
      return EXIT_FAILURE;
  }

  std::cout << " You called : " <<std::endl
            << argv[0] << std::endl
            << "--imadir " << sImaDirectory << std::endl
            << "--outdir " << sOutDir << std::endl
            << "--distratio " << fDistRatio << std::endl
            << "--octminus1 " << bOctMinus1 << std::endl
            << "--peakThreshold " << dPeakThreshold << std::endl;

  if (sOutDir.empty())  {
    std::cerr << "\nIt is an invalid output directory" << std::endl;
    return EXIT_FAILURE;
  }

  // -----------------------------
  // a. List images
  // b. Compute features and descriptor
  // c. Compute putatives descriptor matches
  // d. Geometric filtering of putatives matches
  // e. Export some statistics
  // -----------------------------

  // Create output dir
  if (!stlplus::folder_exists(sOutDir))
    stlplus::folder_create( sOutDir );

  //---------------------------------------
  // a. List images
  //---------------------------------------
  std::string sListsFile = stlplus::create_filespec( sOutDir,
                                                     "lists.txt" ).c_str();
  if (!stlplus::is_file(sListsFile) )
  {
    std::cerr << std::endl
      << "The input file \""<< sListsFile << "\" is missing" << std::endl;
    return false;
  }

  std::vector<openMVG::SfMIO::CameraInfo> vec_camImageName;
  std::vector<openMVG::SfMIO::IntrinsicCameraInfo> vec_focalGroup;
  if (!openMVG::SfMIO::loadImageList( vec_camImageName,
                                      vec_focalGroup,
                                      sListsFile) )
  {
    std::cerr << "\nEmpty image list." << std::endl;
    return false;
  }

  std::vector<std::string> vec_fileNames;
  std::vector<std::pair<size_t, size_t> > vec_imagesSize;
  for ( std::vector<openMVG::SfMIO::CameraInfo>::const_iterator iter_camInfo = vec_camImageName.begin();
     iter_camInfo != vec_camImageName.end();
     iter_camInfo++ )
  {
    vec_imagesSize.push_back( std::make_pair( vec_focalGroup[iter_camInfo->m_intrinsicId].m_w,
                                              vec_focalGroup[iter_camInfo->m_intrinsicId].m_h ) );
    vec_fileNames.push_back( stlplus::create_filespec( sImaDirectory, iter_camInfo->m_sImageName) );
  }

  //---------------------------------------
  // b. Compute features and descriptor
  //    - extract sift features and descriptor
  //    - if keypoints already computed, re-load them
  //    - else save features and descriptors on disk
  //---------------------------------------

  typedef Descriptor<float, 128> DescriptorT;
  typedef SIOPointFeature FeatureT;
  typedef std::vector<FeatureT> FeatsT;
  typedef vector<DescriptorT > DescsT;
  typedef KeypointSet<FeatsT, DescsT > KeypointSetT;

  {
    std::cout << "\n\nEXTRACT FEATURES" << std::endl;
    vec_imagesSize.resize(vec_fileNames.size());

    Image<RGBColor> imageRGB;
    Image<unsigned char> imageGray;

    C_Progress_display my_progress_bar( vec_fileNames.size() );
    for(size_t i=0; i < vec_fileNames.size(); ++i)  {
      KeypointSetT kpSet;

      std::string sFeat = stlplus::create_filespec(sOutDir,
        stlplus::basename_part(vec_fileNames[i]), "feat");
      std::string sDesc = stlplus::create_filespec(sOutDir,
        stlplus::basename_part(vec_fileNames[i]), "desc");

      //Test if descriptor and feature was already computed
      if (stlplus::file_exists(sFeat) && stlplus::file_exists(sDesc)) {

        if (ReadImage(vec_fileNames[i].c_str(), &imageRGB)) {
          vec_imagesSize[i] = make_pair(imageRGB.Width(), imageRGB.Height());
        }
        else {
          ReadImage(vec_fileNames[i].c_str(), &imageGray);
          vec_imagesSize[i] = make_pair(imageGray.Width(), imageGray.Height());
        }
      }
      else  { //Not already computed, so compute and save

        if (ReadImage(vec_fileNames[i].c_str(), &imageRGB)) {
          Rgb2Gray(imageRGB, &imageGray);
        }
        else{
          ReadImage(vec_fileNames[i].c_str(), &imageGray);
        }

        // Compute features and descriptors and export them to file
        SIFTDetector(imageGray,
          kpSet.features(), kpSet.descriptors(),
          bOctMinus1, true, dPeakThreshold);

        kpSet.saveToBinFile(sFeat, sDesc);
        vec_imagesSize[i] = make_pair(imageGray.Width(), imageRGB.Height());
      }
      ++my_progress_bar;
    }
  }

  //---------------------------------------
  // c. Compute putatives descriptor matches
  //    - L2 descriptor matching
  //    - Keep correspondences only if NearestNeighbor ratio is ok
  //---------------------------------------
  IndexedMatchPerPair map_PutativesMatches;
  // Define the matcher and the used metric (Squared L2)
  // ANN matcher could be defined as follow:
  typedef flann::L2<DescriptorT::bin_type> MetricT;
  typedef ArrayMatcher_Kdtree_Flann<DescriptorT::bin_type, MetricT> MatcherT;
  // Brute force matcher is defined as following:
  //typedef L2_Vectorized<DescriptorT::bin_type> MetricT;
  //typedef ArrayMatcherBruteForce<DescriptorT::bin_type, MetricT> MatcherT;

  // If the matches already exists, reload them
  if (stlplus::file_exists(sOutDir + "/matches.putative.txt"))
  {
    PairedIndMatchImport(sOutDir + "/matches.putative.txt", map_PutativesMatches);
    std::cout << std::endl << "PUTATIVE MATCHES -- PREVIOUS RESULTS LOADED" << std::endl;
  }
  else // Compute the putatives matches
  {
    ImageCollectionMatcher_AllInMemory<KeypointSetT, MatcherT> collectionMatcher(fDistRatio);
    if (collectionMatcher.loadData(vec_fileNames, sOutDir))
    {
      std::cout  << std::endl << "PUTATIVE MATCHES" << std::endl;
      collectionMatcher.Match(vec_fileNames, map_PutativesMatches);
      //---------------------------------------
      //-- Export putative matches
      //---------------------------------------
      std::ofstream file (std::string(sOutDir + "/matches.putative.txt").c_str());
      if (file.is_open())
        PairedIndMatchToStream(map_PutativesMatches, file);
      file.close();
    }
  }
  //-- export putative matches Adjacency matrix
  PairWiseMatchingToAdjacencyMatrixSVG(vec_fileNames.size(),
    map_PutativesMatches,
    stlplus::create_filespec(sOutDir, "PutativeAdjacencyMatrix", "svg"));

  //---------------------------------------
  // d. Geometric filtering of putatives matches
  //    - AContrario Estimation of the Fundamental matrix
  //    - Use a upper bound for the plausible F matrix
  //      acontrario estimated threshold
  //---------------------------------------
  IndexedMatchPerPair map_GeometricMatches_F;

  GeometricFilter_FMatrix_AC geomFilter_F_AC(4.0);
  ImageCollectionGeometricFilter<FeatureT, GeometricFilter_FMatrix_AC> collectionGeomFilter;
  if (collectionGeomFilter.loadData(vec_fileNames, sOutDir))
  {
    std::cout << std::endl << " - GEOMETRIC FILTERING - " << std::endl;
    collectionGeomFilter.Filter(
      geomFilter_F_AC,
      map_PutativesMatches,
      map_GeometricMatches_F,
      vec_imagesSize);

    //---------------------------------------
    //-- Export geometric filtered matches
    //---------------------------------------
    std::ofstream file (string(sOutDir + "/matches.f.txt").c_str());
    if (file.is_open())
      PairedIndMatchToStream(map_GeometricMatches_F, file);
    file.close();

    //-- export Adjacency matrix
    std::cout << "\n Export Adjacency Matrix of the pairwise's Epipolar matches"
      << std::endl;
    PairWiseMatchingToAdjacencyMatrixSVG(vec_fileNames.size(),
      map_GeometricMatches_F,
      stlplus::create_filespec(sOutDir, "EpipolarAdjacencyMatrix", "svg"));
  }
  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/**
 This class calculates the space charge kicks for bunch using 2.5D approach in transverse direction
 and Rick Baartman's approach (RB) to the longitudinal kicks. There is a hope that will be simular to
 the true 3D discription of space charge.
*/

#ifndef SC_SPACECHARGE_CALC_2P5D_RB_H
#define SC_SPACECHARGE_CALC_2P5D_RB_H

//MPI Function Wrappers
#include "orbit_mpi.hh"
#include "wrap_mpi_comm.hh"

#include <cstdlib>
#include <cmath>

//ORBIT bunch
#include "Bunch.hh"

//pyORBIT utils
#include "CppPyWrapper.hh"
#include "BunchExtremaCalculator.hh"

#include "Grid1D.hh"
#include "Grid2D.hh"
#include "PoissonSolverFFT2D.hh"

using namespace std;

class SpaceChargeCalc2p5Drb: public OrbitUtils::CppPyWrapper
{
public:

	/** Constructor with the "x to y ratio" parameter. */
	SpaceChargeCalc2p5Drb(int xSize, int ySize, int zSize, double xy_ratio_in);

	/** Constructor with "ratio" parameter equals 1. */
	SpaceChargeCalc2p5Drb(int xSize, int ySize, int zSize);

	/** Destructor */
	virtual ~SpaceChargeCalc2p5Drb();

	/** Calculates space charge and applies the transverse and
	    longitudinal SC kicks to the macro-particles in the bunch. */
	void trackBunch(Bunch* bunch, double length, double pipe_radius);

	/** Returns the 2D rho grid with a transverse density distribution. **/
	Grid2D* getRhoGrid();

	/** Returns the 2D phi grid with a transverse potential. **/
	Grid2D* getPhiGrid();

	/** Returns the 1D grid with a longitudinal density. **/
	Grid1D* getLongGrid();

	/** Returns the 1D grid with a derivative of the longitudinal density. **/
	Grid1D* getLongDerivativeGrid();

	/** Sets the number of smoothing points to calculate the derivative of the longitudinal density. */
	void setLongAveragingPointsN(int n_points);

	/** Returns the number of smoothing points to calculate the derivative of the longitudinal density. */
	int getLongAveragingPointsN();

private:

	/** Analyses the bunch and does bining. */
 double bunchAnalysis(Bunch* bunch, double& totalMacrosize, double& x_c, double& y_c, double& a_bunch);

 /** Calculates the derivative of the longitudinal density by using Quadratic Curve Fitting */
 void calculateLongDerivative();

protected:
	PoissonSolverFFT2D* poissonSolver;
	Grid2D* rhoGrid;
	Grid2D* phiGrid;
	Grid1D* zGrid;
	Grid1D* zDerivGrid;
	OrbitUtils::BunchExtremaCalculator* bunchExtremaCalc;

	double xy_ratio;
	int n_long_avg;

	//auxiliary 5x2 array for Quadratic Curve Fitting
	double** S_arr;
};
//end of SC_SPACECHARGE_CALC_2P5D_RB_H
#endif
<commit_msg>The comment about "hope" removed. There is no hope that this algorithm will work for linac bunches<commit_after>/**
 This class calculates the space charge kicks for bunch using 2.5D approach in transverse direction
 and Rick Baartman's approach (RB) to the longitudinal kicks. It is not sutable for short bunches, but can be used in
 rings.
*/

#ifndef SC_SPACECHARGE_CALC_2P5D_RB_H
#define SC_SPACECHARGE_CALC_2P5D_RB_H

//MPI Function Wrappers
#include "orbit_mpi.hh"
#include "wrap_mpi_comm.hh"

#include <cstdlib>
#include <cmath>

//ORBIT bunch
#include "Bunch.hh"

//pyORBIT utils
#include "CppPyWrapper.hh"
#include "BunchExtremaCalculator.hh"

#include "Grid1D.hh"
#include "Grid2D.hh"
#include "PoissonSolverFFT2D.hh"

using namespace std;

class SpaceChargeCalc2p5Drb: public OrbitUtils::CppPyWrapper
{
public:

	/** Constructor with the "x to y ratio" parameter. */
	SpaceChargeCalc2p5Drb(int xSize, int ySize, int zSize, double xy_ratio_in);

	/** Constructor with "ratio" parameter equals 1. */
	SpaceChargeCalc2p5Drb(int xSize, int ySize, int zSize);

	/** Destructor */
	virtual ~SpaceChargeCalc2p5Drb();

	/** Calculates space charge and applies the transverse and
	    longitudinal SC kicks to the macro-particles in the bunch. */
	void trackBunch(Bunch* bunch, double length, double pipe_radius);

	/** Returns the 2D rho grid with a transverse density distribution. **/
	Grid2D* getRhoGrid();

	/** Returns the 2D phi grid with a transverse potential. **/
	Grid2D* getPhiGrid();

	/** Returns the 1D grid with a longitudinal density. **/
	Grid1D* getLongGrid();

	/** Returns the 1D grid with a derivative of the longitudinal density. **/
	Grid1D* getLongDerivativeGrid();

	/** Sets the number of smoothing points to calculate the derivative of the longitudinal density. */
	void setLongAveragingPointsN(int n_points);

	/** Returns the number of smoothing points to calculate the derivative of the longitudinal density. */
	int getLongAveragingPointsN();

private:

	/** Analyses the bunch and does bining. */
 double bunchAnalysis(Bunch* bunch, double& totalMacrosize, double& x_c, double& y_c, double& a_bunch);

 /** Calculates the derivative of the longitudinal density by using Quadratic Curve Fitting */
 void calculateLongDerivative();

protected:
	PoissonSolverFFT2D* poissonSolver;
	Grid2D* rhoGrid;
	Grid2D* phiGrid;
	Grid1D* zGrid;
	Grid1D* zDerivGrid;
	OrbitUtils::BunchExtremaCalculator* bunchExtremaCalc;

	double xy_ratio;
	int n_long_avg;

	//auxiliary 5x2 array for Quadratic Curve Fitting
	double** S_arr;
};
//end of SC_SPACECHARGE_CALC_2P5D_RB_H
#endif
<|endoftext|>